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 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
+16
-4
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user