Restore hosted background tasks and preserve live hosts on reconnect failure

This commit is contained in:
2026-11-07 16:22:38 +00:00
parent 5061cd5da4
commit 4ead2abdbf
4 changed files with 345 additions and 30 deletions
+71 -30
View File
@@ -97,6 +97,8 @@ func hostBinaryPath() string {
type hostLink struct {
dir string
record claudehost.Record
// Immutable capability of this attachment; old hosts cannot protect idle background tasks.
tasksKnown bool
mu sync.Mutex
conn *claudehost.Conn
@@ -134,11 +136,17 @@ type replayPlan struct {
pending map[string]bool
busyAtAcked bool
restore bool
tasks *[]claudehost.Task
}
// startHosted starts a host for args and attaches to it.
func (s *session) startHosted(ctx context.Context, args []string, mode string, env []string) (*process, error) {
c := s.chat
for _, record := range claudehost.Records(c.hostDir) {
if record.SessionID == s.id && hostReferenceLive(record) {
return nil, errors.New("the existing Claude Code host is temporarily unavailable; its work was left running, retry to reconnect")
}
}
hostConfig.Lock()
binary, hostArgs := hostConfig.binary, append([]string(nil), hostConfig.args...)
hostConfig.Unlock()
@@ -154,10 +162,10 @@ func (s *session) startHosted(ctx context.Context, args []string, mode string, e
paths := claudehost.PathsFor(c.hostDir, s.id)
conn, status, err := claudehost.Attach(paths.Socket, 0, hostAttachTimeout)
if err != nil {
claudehost.KillStale(c.hostDir, claudehost.Record{SessionID: s.id, HostPID: cmd.Process.Pid})
return nil, fmt.Errorf("attach to the Claude Code host: %w", err)
log.Printf("claude chat %s: newly started host unavailable; leaving it intact for reconnect", s.id)
return nil, fmt.Errorf("attach to the Claude Code host (left running for reconnect): %w", err)
}
link := &hostLink{dir: c.hostDir, conn: conn, record: claudehost.Record{
link := &hostLink{dir: c.hostDir, conn: conn, tasksKnown: status.Tasks != nil, record: claudehost.Record{
SessionID: s.id, HostPID: status.HostPID, ClaudePID: status.ClaudePID, Socket: paths.Socket,
}}
p := newProcess(s, mode)
@@ -168,15 +176,14 @@ func (s *session) startHosted(ctx context.Context, args []string, mode string, e
}
// connectHost attaches to a host found in the registry and prepares a
// process for s without registering it. A host that is unreachable, belongs
// to another session or never finished initializing is stopped and its files
// removed; nil is returned and the next prompt starts a fresh CLI with
// --resume.
// process for s without registering it. A live but temporarily unreachable host
// is never killed to repair the control connection. Its registration blocks a
// duplicate CLI until reconnect succeeds. Only dead references are removed.
func (c *Chat) connectHost(record claudehost.Record) (*process, *claudehost.Conn, replayPlan) {
conn, status, err := claudehost.Attach(record.Socket, 0, hostAttachTimeout)
if err != nil {
log.Printf("claude chat %s: host unreachable (%v); the next prompt resumes the session", record.SessionID, err)
claudehost.KillStale(c.hostDir, record)
log.Printf("claude chat %s: host unreachable (%v); retaining any live work for reconnect", record.SessionID, err)
c.removeDeadHostReference(record)
return nil, nil, replayPlan{}
}
var models []protocol.ChatModel
@@ -188,7 +195,7 @@ func (c *Chat) connectHost(record claudehost.Record) (*process, *claudehost.Conn
}
if status.SessionID != record.SessionID || err != nil {
_ = conn.Close()
claudehost.KillStale(c.hostDir, record)
c.removeDeadHostReference(record)
return nil, nil, replayPlan{}
}
directory := status.Directory
@@ -197,12 +204,12 @@ func (c *Chat) connectHost(record claudehost.Record) (*process, *claudehost.Conn
}
s := c.sessionFor(record.SessionID, directory)
p := newProcess(s, status.Mode)
p.link = &hostLink{dir: c.hostDir, conn: conn, committed: status.Acked, record: claudehost.Record{
p.link = &hostLink{dir: c.hostDir, conn: conn, committed: status.Acked, tasksKnown: status.Tasks != nil, record: claudehost.Record{
SessionID: record.SessionID, HostPID: status.HostPID, ClaudePID: status.ClaudePID, Socket: record.Socket,
}}
p.stderr.WriteString(status.Stderr)
p.models, p.account, p.appliedModel = models, account, status.Model
plan := replayPlan{base: status.Base, silentUntil: status.Acked, catchUpEnd: status.End, pending: map[string]bool{}, busyAtAcked: status.BusyAtAcked, restore: true}
plan := replayPlan{base: status.Base, silentUntil: status.Acked, catchUpEnd: status.End, pending: map[string]bool{}, busyAtAcked: status.BusyAtAcked, restore: true, tasks: status.Tasks}
for _, pending := range status.Pending {
plan.pending[pending.ID] = true
}
@@ -299,6 +306,14 @@ func (s *session) existingHost() *process {
func (p *process) readHost(conn *claudehost.Conn, plan replayPlan) {
s := p.session
live := false
tasksReconciled := false
catchUpReady := func() {
if !tasksReconciled {
s.reconcileHostTasks(plan.tasks)
tasksReconciled = true
}
p.markReady()
}
goLive := func() {
if live {
return
@@ -336,7 +351,7 @@ func (p *process) readHost(conn *claudehost.Conn, plan replayPlan) {
goLive()
}
if plan.catchUpEnd <= plan.base {
p.markReady()
catchUpReady()
}
sinceAck := 0
for {
@@ -344,9 +359,16 @@ func (p *process) readHost(conn *claudehost.Conn, plan replayPlan) {
if err != nil {
goLive()
p.markReady()
if next := p.hostLost(conn, err); next != nil {
if next, status := p.hostLost(conn, err); next != nil {
conn = next
plan = replayPlan{}
plan = replayPlan{catchUpEnd: status.End, tasks: status.Tasks}
tasksReconciled = false
p.link.mu.Lock()
committed := p.link.committed
p.link.mu.Unlock()
if committed >= status.End {
catchUpReady()
}
continue
}
return
@@ -371,7 +393,7 @@ func (p *process) readHost(conn *claudehost.Conn, plan replayPlan) {
goLive()
}
if frame.End >= plan.catchUpEnd {
p.markReady()
catchUpReady()
}
case claudehost.OpExit:
goLive()
@@ -416,19 +438,18 @@ func (p *process) markReady() {
// hostLost handles an ended host connection. A deliberate detach or close just
// ends the reader; an unexpected loss is retried once (the host may only have
// dropped the connection), and otherwise the host is treated as crashed: what
// it left is stopped and the turn is settled with a notice, and the next prompt
// resumes the session with --resume as after any release.
func (p *process) hostLost(conn *claudehost.Conn, cause error) *claudehost.Conn {
// dropped the connection). A live host/CLI is preserved when retries fail;
// only a confirmed dead reference is removed before allowing a resumed CLI.
func (p *process) hostLost(conn *claudehost.Conn, cause error) (*claudehost.Conn, *claudehost.Status) {
link := p.link
_ = conn.Close()
if link.detached.Load() {
p.finishDetached()
return nil
return nil, nil
}
if link.closing.Load() {
p.finish(nil)
return nil
return nil, nil
}
link.mu.Lock()
committed := link.committed
@@ -438,34 +459,54 @@ func (p *process) hostLost(conn *claudehost.Conn, cause error) *claudehost.Conn
if link.detached.Load() || link.closing.Load() {
break
}
next, _, err := claudehost.Attach(link.record.Socket, committed, hostAttachTimeout)
next, status, err := claudehost.Attach(link.record.Socket, committed, hostAttachTimeout)
if err == nil {
link.mu.Lock()
link.conn = next
link.mu.Unlock()
return next
return next, status
}
}
if link.detached.Load() {
p.finishDetached()
return nil
return nil, nil
}
if link.closing.Load() {
p.finish(nil)
return nil
return nil, nil
}
log.Printf("claude chat %s: host connection lost (%v); falling back to --resume", p.session.id, cause)
claudehost.KillStale(link.dir, link.record)
if hostReferenceLive(link.record) {
message := "Claude Code control connection is temporarily unavailable; work was left running, retry to reconnect"
log.Printf("claude chat %s: host connection lost (%v); retaining live host and CLI", p.session.id, cause)
s := p.session
s.mu.Lock()
if s.proc == p {
s.proc = nil
s.lastErr = message
}
s.mu.Unlock()
p.finishDetachedReason(message)
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventTool,
Part: &protocol.ChatPart{Type: protocol.ChatPartTool, ID: "claude-host-unavailable", Name: "Claude Code",
State: &protocol.ChatToolState{Status: protocol.ChatToolError, Error: &protocol.ChatError{Type: "connection", Message: message}}}})
return nil, nil
}
log.Printf("claude chat %s: host and CLI stopped (%v); the next prompt resumes", p.session.id, cause)
claudehost.Remove(link.dir, link.record.SessionID)
p.mu.Lock()
p.stderr.Reset()
p.mu.Unlock()
p.finish(errors.New("the Claude Code host stopped unexpectedly; the next prompt resumes this session with --resume"))
return nil
return nil, nil
}
// finishDetached ends a process this server let go of on shutdown. The CLI
// keeps running in its host; nothing is reported to watchers.
func (p *process) finishDetached() {
p.finishDetachedReason("the server is shutting down")
}
func (p *process) finishDetachedReason(reason string) {
p.mu.Lock()
if p.exited {
p.mu.Unlock()
@@ -478,7 +519,7 @@ func (p *process) finishDetached() {
p.mu.Unlock()
for _, ch := range pending {
select {
case ch <- controlReply{err: "the server is shutting down"}:
case ch <- controlReply{err: reason}:
default:
}
}