From 01040a7b128c4bee22195d024dd3af1d3c22a848 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 21 Nov 2026 18:10:41 +0000 Subject: [PATCH] Stop the replaced session on /new for every harness /new already released the old native session through the chat-close release path, but two gaps let the replaced session stay alive, and the client told the operator it could still be resumed in a terminal: - Claude Code: ReleaseSession only closed a host this server was attached to. A host registered for the session but not attached (a failed reattach, or one left by an earlier server) kept running. It is now asked to close over its socket and killed as a fallback. - Codex: ReleaseSession only interrupted an active turn. It now also sends thread/unsubscribe so the App Server unloads the thread; a later prompt reloads it through the existing "thread not found" resume path. - The /new notice now says the previous session was stopped. Co-Authored-By: Claude Opus 5.5 --- .../features/chat/domain/chat_commands.dart | 5 +- .../chat/domain/chat_commands_test.dart | 11 ++++ docs/chat-backends.md | 14 +++-- internal/claude/claude.go | 4 +- internal/claude/hosted.go | 55 +++++++++++++++++- internal/claude/hosted_test.go | 33 +++++++++++ internal/codex/chat.go | 20 +++++-- internal/codex/detach_test.go | 56 +++++++++++++++++++ 8 files changed, 183 insertions(+), 15 deletions(-) diff --git a/app/lib/features/chat/domain/chat_commands.dart b/app/lib/features/chat/domain/chat_commands.dart index c4fafe3f..b274c8af 100644 --- a/app/lib/features/chat/domain/chat_commands.dart +++ b/app/lib/features/chat/domain/chat_commands.dart @@ -160,10 +160,11 @@ const String chatRenameUsageReport = 'Usage: /rename — renames this session.'; /// The line the fresh conversation opens on after `/new`: the chat is the -/// same, the agent's context is empty. +/// same, the agent's context is empty, and the server has already stopped the +/// replaced session's agent and background work before it answered. const String chatNewSessionNotice = 'New session started. The agent no longer sees the earlier conversation; ' - 'the previous session can still be resumed in a terminal.'; + 'the previous session was stopped.'; /// The line a conversation opens on when another device started its new /// session. diff --git a/app/test/features/chat/domain/chat_commands_test.dart b/app/test/features/chat/domain/chat_commands_test.dart index e1d11d30..464a5590 100644 --- a/app/test/features/chat/domain/chat_commands_test.dart +++ b/app/test/features/chat/domain/chat_commands_test.dart @@ -94,4 +94,15 @@ void main() { '“/close” is not available yet, so nothing was sent to the agent.', ); }); + + test('the /new notice says the replaced session was stopped', () { + // The server releases the old harness session before it answers, so the + // notice must not suggest it is still running or resumable. + expect( + chatNewSessionNotice, + 'New session started. The agent no longer sees the earlier ' + 'conversation; the previous session was stopped.', + ); + expect(chatNewSessionNotice, isNot(contains('resume'))); + }); } diff --git a/docs/chat-backends.md b/docs/chat-backends.md index e595e19c..7134fc7f 100644 --- a/docs/chat-backends.md +++ b/docs/chat-backends.md @@ -231,11 +231,15 @@ and with the same title. OpenCode makes a new `ses_` session, Codex a new thread and Claude Code a new session UUID. The server then re-keys the `operator_sessions` row in one transaction. The new row keeps the title, directory, tag, backend, colour, star, creation time, model override and mode. -The old row is not deleted: it records `replaced_by`, is no longer listed, and -its native session can still be resumed in a terminal. Before the row is moved, -the server releases the old native runtime; this stops active/background work -without deleting the native transcript. If release fails, `/new` reports an -error and leaves the registry row on the old session. +The old row is not deleted: it records `replaced_by` and is no longer listed. +Before the row is moved, the server releases the old native runtime, the same +release chat close uses, so `/new` never leaves the replaced session running: +Claude Code's host and CLI exit (including a registered host this server is not +attached to), a Codex thread's turn is interrupted and the thread is +unsubscribed so the App Server unloads it, and OpenCode's turn and running +shells are stopped (the shared OpenCode service itself has no per-session +process). The native transcript is kept on disk. If release fails, `/new` +reports an error and leaves the registry row on the old session. The row is re-keyed rather than mapped from a stable id because every other layer is keyed by the native id: rooms, queues, transcripts, shells, exports and diff --git a/internal/claude/claude.go b/internal/claude/claude.go index ff58d953..57a3e8a9 100644 --- a/internal/claude/claude.go +++ b/internal/claude/claude.go @@ -510,7 +510,8 @@ func (s *session) releaseIdleProcess() { } } -func (s *session) closeProcess() { +// closeProcess stops the session's CLI and reports whether one was attached. +func (s *session) closeProcess() bool { s.mu.Lock() p := s.proc s.proc = nil @@ -518,6 +519,7 @@ func (s *session) closeProcess() { if p != nil { p.close() } + return p != nil } // findTranscriptFile locates the CLI's session file. Project directories are diff --git a/internal/claude/hosted.go b/internal/claude/hosted.go index bf284c13..f67eb1b3 100644 --- a/internal/claude/hosted.go +++ b/internal/claude/hosted.go @@ -647,14 +647,63 @@ func (c *Chat) Detach() { } // ReleaseSession stops a session's CLI (and its host) for an explicit operator -// close. The transcript stays; a later prompt resumes it. +// close or /new. The transcript stays; a later prompt resumes it. A host still +// registered for the session that this server holds no connection to (a +// reattach that failed, or one left by an earlier server) is stopped too, so a +// release never leaves a Claude Code process running behind the chat. func (c *Chat) ReleaseSession(_ context.Context, id string) error { - if s := c.session(id); s != nil { - s.closeProcess() + if s := c.session(id); s != nil && s.closeProcess() { + return nil } + c.stopUnattachedHost(id) return nil } +// stopUnattachedHost asks the host registered for id to stop its CLI and exit, +// then kills whatever is left of it (KillStale only signals processes whose +// command line names this session) and removes its files. +func (c *Chat) stopUnattachedHost(id string) { + if c.hostDir == "" || id == "" { + return + } + data, err := os.ReadFile(claudehost.PathsFor(c.hostDir, id).Record) + if err != nil { + return + } + var record claudehost.Record + if json.Unmarshal(data, &record) != nil || record.SessionID != id { + claudehost.Remove(c.hostDir, id) + return + } + if conn, err := claudehost.Dial(record.Socket, time.Second); err == nil { + closed := make(chan struct{}) + go func() { + defer close(closed) + if conn.Send(claudehost.Frame{Op: claudehost.OpClose}) != nil { + return + } + for { + frame, err := conn.Recv() + if err != nil || frame.Op == claudehost.OpClosed { + return + } + } + }() + select { + case <-closed: + case <-time.After(8 * time.Second): + } + _ = conn.Close() + // The host exits right after OpClosed; give it a moment before the + // fallback signals below. + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) && claudehost.ProcessMatches(record.HostPID, record.SessionID) { + time.Sleep(50 * time.Millisecond) + } + } + claudehost.KillStale(c.hostDir, record) +} + // ProbeTurn reports whether a turn is in flight, after a reattached host's // replay has rebuilt the session, so a turn that survived a restart is // observed and notifies. diff --git a/internal/claude/hosted_test.go b/internal/claude/hosted_test.go index a861e6cb..ce86188b 100644 --- a/internal/claude/hosted_test.go +++ b/internal/claude/hosted_test.go @@ -353,6 +353,39 @@ func TestReleasingAHostedChatStopsItsHost(t *testing.T) { } } +// /new and close release a session even when this server never attached to +// its host (a failed reattach, or a host left by an earlier server): the +// registered host is stopped rather than left running until it idles out. +func TestReleasingAnUnattachedHostedChatStopsItsHost(t *testing.T) { + fixture := hostedSetup(t) + first := hostedChat(t) + session := newCreatedChat(t, first) + frames := subscribe(t, first, session.ID) + if err := first.Prompt(context.Background(), session.ID, "hello"); err != nil { + t.Fatal(err) + } + waitStepEnded(t, frames) + record := onlyRecord(t, fixture) + first.Detach() + if !alive(record.HostPID) { + t.Fatal("a detached host must keep running") + } + // A server without the reattach pass holds no connection to the host. + second := newChat(context.Background()) + t.Cleanup(second.Close) + if second.session(session.ID) != nil { + t.Fatal("the second server must not be attached to the host") + } + if err := second.ReleaseSession(context.Background(), session.ID); err != nil { + t.Fatal(err) + } + eventually(t, "the unattached host to exit", func() bool { return !alive(record.HostPID) || isZombie(record.HostPID) }) + eventually(t, "the CLI to exit", func() bool { return !alive(record.ClaudePID) || isZombie(record.ClaudePID) }) + if records := claudehost.Records(fixture.hostDir); len(records) != 0 { + t.Fatalf("a released host must remove its registry record: %+v", records) + } +} + func TestHostStatusReportsRegistryAndPrivateSocket(t *testing.T) { fixture := hostedSetup(t) chat := hostedChat(t) diff --git a/internal/codex/chat.go b/internal/codex/chat.go index 9e3cf060..3785b3c9 100644 --- a/internal/codex/chat.go +++ b/internal/codex/chat.go @@ -554,16 +554,28 @@ func (c *Chat) StopTasks(context.Context, string) (int, error) { return 0, errors.New("Codex does not expose a separate background-task stop operation") } -// ReleaseSession stops an active Codex turn while preserving the thread and -// its transcript. Codex has no separate per-thread process to reap. +// ReleaseSession stops a Codex thread for an explicit close or /new: it +// interrupts an active turn, then unsubscribes this connection so the App +// Server unloads the thread (and its live runtime) once no other client holds +// it. The persisted thread and transcript stay; a later prompt reloads it +// through the "thread not found" resume path in PromptWithMessageIDModel. func (c *Chat) ReleaseSession(ctx context.Context, id string) error { c.mu.Lock() turn := c.turns[id] c.mu.Unlock() - if turn == "" { + if turn != "" { + if err := c.Interrupt(ctx, id); err != nil { + return err + } + } + _, err := c.call(ctx, "thread/unsubscribe", map[string]any{"threadId": id}) + var refused *rpcCallError + if errors.As(err, &refused) && refused.Code == -32601 { + // An App Server without thread/unsubscribe keeps the thread loaded; + // the interrupt above already stopped its work. return nil } - return c.Interrupt(ctx, id) + return err } // Create starts one Codex thread in directory. diff --git a/internal/codex/detach_test.go b/internal/codex/detach_test.go index 74b5b9c8..920215aa 100644 --- a/internal/codex/detach_test.go +++ b/internal/codex/detach_test.go @@ -46,3 +46,59 @@ func TestDetachLeavesTurnRunningForNextConnection(t *testing.T) { } } } + +// Releasing a thread (chat close or /new) interrupts its turn and then +// unsubscribes, so the App Server unloads the replaced thread instead of +// keeping it loaded indefinitely. +func TestReleaseSessionInterruptsAndUnloadsThread(t *testing.T) { + var mu sync.Mutex + var methods []string + var unsubscribed string + appServer := func(method string, params json.RawMessage) any { + mu.Lock() + defer mu.Unlock() + methods = append(methods, method) + if method == "thread/unsubscribe" { + var body struct { + ThreadID string `json:"threadId"` + } + _ = json.Unmarshal(params, &body) + unsubscribed = body.ThreadID + return json.RawMessage(`{"status":"unsubscribed"}`) + } + return json.RawMessage(`{}`) + } + c := modelTestChat(t, appServer) + c.mu.Lock() + c.turns[fixtureThread] = "turn" + c.mu.Unlock() + if err := c.ReleaseSession(context.Background(), fixtureThread); err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if len(methods) != 2 || methods[0] != "turn/interrupt" || methods[1] != "thread/unsubscribe" || unsubscribed != fixtureThread { + t.Fatalf("release must interrupt then unsubscribe the thread: %v (%q)", methods, unsubscribed) + } +} + +// An idle thread is still unloaded, and an App Server that predates +// thread/unsubscribe does not make the release fail. +func TestReleaseSessionUnloadsIdleThreadAndToleratesOldServers(t *testing.T) { + var mu sync.Mutex + var methods []string + c := modelTestChat(t, func(method string, _ json.RawMessage) any { + mu.Lock() + defer mu.Unlock() + methods = append(methods, method) + return &rpcError{Code: -32601, Message: "method not found"} + }) + if err := c.ReleaseSession(context.Background(), fixtureThread); err != nil { + t.Fatalf("an unsupported unsubscribe must not fail the release: %v", err) + } + mu.Lock() + defer mu.Unlock() + if len(methods) != 1 || methods[0] != "thread/unsubscribe" { + t.Fatalf("an idle release must only unsubscribe: %v", methods) + } +}