Merge: Claude Code chats survive server restarts via a detachable host

This commit is contained in:
2026-11-04 16:15:06 +00:00
21 changed files with 2400 additions and 40 deletions
+76 -22
View File
@@ -14,6 +14,7 @@ import (
"sync/atomic"
"time"
"git.a-wan.net/alan/pipelines/internal/claudehost"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -48,6 +49,23 @@ type process struct {
// mode is the permission mode this process runs in, guarded by the
// session's mu: set at spawn and after a confirmed set_permission_mode.
mode string
// link is set when a detachable host owns the CLI (hosted.go); cmd and
// stdin are then unused.
link *hostLink
// ready closes once a reattached process has replayed the output it
// missed; a process this server started is ready at once.
ready chan struct{}
readyOnce sync.Once
// models, account and appliedModel carry an attached host's
// initialize state until the session adopts it.
models []protocol.ChatModel
account accountIdentity
appliedModel string
}
func newProcess(s *session, mode string) *process {
return &process{session: s, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{}), ready: make(chan struct{}), mode: mode}
}
type controlReply struct {
@@ -97,6 +115,7 @@ func sessionDisplayName(title string) string {
// spawn starts the CLI in the session directory. A session whose transcript
// already exists resumes it; a new one pins the id we recorded at create time.
// With hosting configured the CLI runs in a detachable host (hosted.go).
func (s *session) spawn(ctx context.Context) (*process, error) {
if err := s.requireBinary(); err != nil {
return nil, err
@@ -107,34 +126,24 @@ func (s *session) spawn(ctx context.Context) (*process, error) {
if info, err := os.Stat(s.directory); err != nil || !info.IsDir() {
return nil, fmt.Errorf("Claude session directory is not available: %s", s.directory)
}
if p := s.existingHost(); p != nil {
return p, nil
}
args, mode := s.cliArgs(findTranscriptFile(s.id) != "")
cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...)
cmd.Dir = s.directory
env, notices := s.chat.processEnv(ctx, s.directory)
cmd.Env = env
s.mu.Lock()
s.envNotices = notices
s.mu.Unlock()
cmd.WaitDelay = 5 * time.Second
stdin, err := cmd.StdinPipe()
var p *process
var err error
if s.chat.hostDir != "" {
p, err = s.startHosted(ctx, args, mode, env)
} else {
p, err = s.startDirect(args, mode, env)
}
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start Claude Code: %w", err)
}
p := &process{session: s, cmd: cmd, stdin: stdin, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{}), mode: mode}
go p.readStderr(stderr)
go p.readStdout(stdout)
go p.wait()
// The CLI holds can_use_tool requests until the host has initialized. Do that
// before any user turn so an approval is never silently denied.
initCtx, cancel := context.WithTimeout(ctx, initializeTimeout)
@@ -152,11 +161,47 @@ func (s *session) spawn(ctx context.Context) (*process, error) {
return p, nil
}
// startDirect runs the CLI as this server's own child.
func (s *session) startDirect(args []string, mode string, env []string) (*process, error) {
cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...)
cmd.Dir = s.directory
cmd.Env = env
cmd.WaitDelay = 5 * time.Second
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start Claude Code: %w", err)
}
p := newProcess(s, mode)
p.cmd, p.stdin = cmd, stdin
p.markReady()
go p.readStderr(stderr)
go p.readStdout(stdout)
go p.wait()
return p, nil
}
func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, accountIdentity, error) {
raw, err := p.request(ctx, "initialize", map[string]any{"subtype": "initialize"})
if err != nil {
return nil, accountIdentity{}, fmt.Errorf("initialize Claude Code: %w%s", err, p.diagnostic())
}
return parseInitialize(raw)
}
// parseInitialize reads the CLI's initialize response: its model catalog and
// signed-in account.
func parseInitialize(raw json.RawMessage) ([]protocol.ChatModel, accountIdentity, error) {
var reply struct {
Models []struct {
Value string `json:"value"`
@@ -237,7 +282,6 @@ func (p *process) write(value any) error {
if err != nil {
return err
}
data = append(data, '\n')
p.writeMu.Lock()
defer p.writeMu.Unlock()
p.mu.Lock()
@@ -246,6 +290,10 @@ func (p *process) write(value any) error {
if exited {
return errProcessClosed
}
if p.link != nil {
return p.link.send(claudehost.Frame{Op: claudehost.OpIn, Data: data})
}
data = append(data, '\n')
if _, err := p.stdin.Write(data); err != nil {
return fmt.Errorf("write to Claude Code: %w", err)
}
@@ -314,7 +362,9 @@ func (p *process) finish(err error) {
default:
}
}
_ = p.stdin.Close()
if p.stdin != nil {
_ = p.stdin.Close()
}
p.session.processExit(p, err)
}
@@ -325,6 +375,10 @@ func (p *process) close() {
if exited {
return
}
if p.link != nil {
p.closeHosted()
return
}
_ = p.stdin.Close()
if p.cmd.Process != nil {
_ = p.cmd.Process.Signal(os.Interrupt)