From 19b0529ce7d8cf8490be3bed3a4bb9845991ed42 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Fri, 13 Nov 2026 19:35:31 -0400 Subject: [PATCH 1/2] fix(server): detach the attached runtime when a --listen TUI tab closes Sessions spawned from TUI tabs under --listen are attached to the serving SessionManager, but nothing released them when the tab was closed, so the runtime, session, event log and follow-up injector stayed retained and the session kept showing up as active until the process exited. Add SessionManager.DetachRuntime (the inverse of AttachRuntime, keeping the persisted session) and call it from the spawner's cleanup. Signed-off-by: Alex Castillo --- cmd/root/run.go | 6 ++++++ pkg/server/server_attached_test.go | 27 +++++++++++++++++++++++++++ pkg/server/session_manager.go | 25 +++++++++++++++++++++++++ 3 files changed, 58 insertions(+) diff --git a/cmd/root/run.go b/cmd/root/run.go index 79d1e9365f..9c980cf587 100644 --- a/cmd/root/run.go +++ b/cmd/root/run.go @@ -1397,6 +1397,12 @@ func (f *runExecFlags) createSessionSpawner(agentSource config.Source, sessStore // Create cleanup function cleanup := func() { + // Under --listen the session was attached to the serving manager + // (see recallCoordinatorOpt); release it when the tab goes away so + // the runtime, event log and injector are not retained. + if f.listenSM != nil { + f.listenSM.DetachRuntime(newSess.ID) + } stopToolSets(spawnCtx, t) } diff --git a/pkg/server/server_attached_test.go b/pkg/server/server_attached_test.go index 4b091af88d..3591262408 100644 --- a/pkg/server/server_attached_test.go +++ b/pkg/server/server_attached_test.go @@ -735,3 +735,30 @@ func TestAttachedServer_StatusWaitTimesOut(t *testing.T) { defer resp.Body.Close() assert.Equal(t, http.StatusServiceUnavailable, resp.StatusCode) } + +func TestSessionManager_DetachRuntimeReleasesAttachedSession(t *testing.T) { + t.Parallel() + + ctx := t.Context() + store := session.NewInMemorySessionStore() + sess := session.New() + require.NoError(t, store.AddSession(ctx, sess)) + + sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{}) + sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess) + sm.RegisterFollowUpInjector(sess.ID, func(context.Context, string) {}) + require.Len(t, sm.GetActiveSessions(), 1) + + sm.DetachRuntime(sess.ID) + + assert.Empty(t, sm.GetActiveSessions()) + _, injected := sm.followUpInjectors.Load(sess.ID) + assert.False(t, injected, "follow-up injector must be released") + + // The persisted session survives the detach. + _, err := store.GetSession(ctx, sess.ID) + require.NoError(t, err) + + // Detaching an unknown or already detached session is a no-op. + sm.DetachRuntime(sess.ID) +} diff --git a/pkg/server/session_manager.go b/pkg/server/session_manager.go index c737081d2a..feb18bea03 100644 --- a/pkg/server/session_manager.go +++ b/pkg/server/session_manager.go @@ -462,6 +462,31 @@ func (sm *SessionManager) AttachRuntime(ctx context.Context, sessionID string, r return &rs.streaming } +// DetachRuntime is the inverse of [SessionManager.AttachRuntime]: it releases +// the manager's in-memory state for an attached session (runtime registration, +// cancellation signal, event log, follow-up injector) without touching the +// persisted session. An embedder calls it when it stops owning the session, +// e.g. when a TUI tab is closed under --listen; otherwise the runtime and its +// session would stay reachable (and listed as active) until the process exits. +// Unlike [SessionManager.DeleteSession], the stored session is kept so it can +// still be resumed later. It is a no-op for unknown sessions. +func (sm *SessionManager) DetachRuntime(sessionID string) { + sm.mux.Lock() + defer sm.mux.Unlock() + rs, ok := sm.runtimeSessions.Load(sessionID) + if !ok { + return + } + if rs.cancel != nil { + rs.cancel() + } + sm.runtimeSessions.Delete(sessionID) + sm.dropEventLog(sessionID) + sm.followUpInjectors.Delete(sessionID) + sm.followUpKeys.Delete(sessionID) + sm.pendingSafetyDefaults.Delete(sessionID) +} + // GetSession retrieves a session by ID. func (sm *SessionManager) GetSession(ctx context.Context, id string) (*session.Session, error) { if rs, ok := sm.runtimeSessions.Load(id); ok && rs.session != nil { From b59a3300888bd43a6ad59decdc31b6053f7cd62e Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Sat, 21 Nov 2026 05:24:10 -0400 Subject: [PATCH 2/2] fix(server): cover the full tab lifecycle on detach Clear the recall handler AttachRuntime installed, tear down the event log without tombstoning the session ID so it can be reattached, and detach the initial --listen tab when it is closed, not only spawned tabs. Signed-off-by: Alex Castillo --- cmd/root/run.go | 9 ++++-- cmd/root/run_listen.go | 12 +++++++ cmd/root/run_listen_test.go | 32 +++++++++++++++++++ pkg/server/server_attached_test.go | 50 ++++++++++++++++++++++++++++++ pkg/server/session_manager.go | 25 +++++++++++++-- 5 files changed, 122 insertions(+), 6 deletions(-) diff --git a/cmd/root/run.go b/cmd/root/run.go index 9c980cf587..9ac5f8c2b6 100644 --- a/cmd/root/run.go +++ b/cmd/root/run.go @@ -577,6 +577,9 @@ func (f *runExecFlags) runOrExec(ctx context.Context, out *cli.Printer, args []s if err != nil { return err } + // Under --listen the initial tab is attached to the serving manager too; + // detach it when the tab is closed, like tabs made by createSessionSpawner. + tuiCleanup := detachOnCleanup(f.listenSM, sess.ID, cleanup) applyTheme(f.theme) opts, err := f.buildAppOpts(args) @@ -602,7 +605,7 @@ func (f *runExecFlags) runOrExec(ctx context.Context, out *cli.Printer, args []s } runErr := func() error { if f.lean { - return f.runLeanTUI(ctx, rt, sess, cleanup, args, opts...) + return f.runLeanTUI(ctx, rt, sess, tuiCleanup, args, opts...) } if cassettePath != "" { // Record keystrokes and clicks alongside the model traffic so a @@ -611,9 +614,9 @@ func (f *runExecFlags) runOrExec(ctx context.Context, out *cli.Printer, args []s rec = recorder.New(m) return rec } - return runTUIWrapped(ctx, rt, sess, b.Spawner(rt), cleanup, tuiOptions, wrap, opts...) + return runTUIWrapped(ctx, rt, sess, b.Spawner(rt), tuiCleanup, tuiOptions, wrap, opts...) } - return runTUI(ctx, rt, sess, b.Spawner(rt), cleanup, tuiOptions, opts...) + return runTUI(ctx, rt, sess, b.Spawner(rt), tuiCleanup, tuiOptions, opts...) }() if rec != nil && rec.HasInput() { writeGeneratedTUITest(ctx, out, rec, cassettePath, agentFileName) diff --git a/cmd/root/run_listen.go b/cmd/root/run_listen.go index f9e5664ab6..0aec360ee4 100644 --- a/cmd/root/run_listen.go +++ b/cmd/root/run_listen.go @@ -119,3 +119,15 @@ func (f *runExecFlags) startSessionCoordinator(ctx context.Context, out *cli.Pri sm.RegisterFollowUpInjector(sess.ID, a.InjectUserMessage) }, nil } + +// detachOnCleanup wraps cleanup so the session is also detached from the +// --listen session manager sm (nil when not listening) before it runs. +func detachOnCleanup(sm *server.SessionManager, sessionID string, cleanup func()) func() { + if sm == nil { + return cleanup + } + return func() { + sm.DetachRuntime(sessionID) + cleanup() + } +} diff --git a/cmd/root/run_listen_test.go b/cmd/root/run_listen_test.go index ed567235b0..4e88cd5d60 100644 --- a/cmd/root/run_listen_test.go +++ b/cmd/root/run_listen_test.go @@ -13,6 +13,7 @@ import ( "github.com/docker/docker-agent/pkg/app" "github.com/docker/docker-agent/pkg/config" "github.com/docker/docker-agent/pkg/runtime" + "github.com/docker/docker-agent/pkg/server" "github.com/docker/docker-agent/pkg/session" msgtypes "github.com/docker/docker-agent/pkg/tui/messages" ) @@ -83,3 +84,34 @@ func TestStartSessionCoordinatorRejectsNonLocalListener(t *testing.T) { require.ErrorContains(t, err, "require --auth-token") assert.Nil(t, opt) } + +func TestDetachOnCleanupReleasesListenSession(t *testing.T) { + t.Parallel() + + ctx := t.Context() + store := session.NewInMemorySessionStore() + sess := session.New() + require.NoError(t, store.AddSession(ctx, sess)) + rt := &recallRuntime{store: store} + + sm := server.NewSessionManager(ctx, nil, store, 0, &config.RuntimeConfig{}) + flags := &runExecFlags{listenSM: sm} + _ = flags.recallCoordinatorOpt(ctx, rt, sess) + require.Len(t, sm.GetActiveSessions(), 1) + require.NotNil(t, rt.recallHandler) + + cleaned := false + detachOnCleanup(sm, sess.ID, func() { cleaned = true })() + + assert.True(t, cleaned, "wrapped cleanup must still run") + assert.Empty(t, sm.GetActiveSessions(), "closed initial tab must leave the active session list") + assert.Nil(t, rt.recallHandler, "recall handler must be cleared") +} + +func TestDetachOnCleanupWithoutListenKeepsCleanup(t *testing.T) { + t.Parallel() + + cleaned := false + detachOnCleanup(nil, "id", func() { cleaned = true })() + assert.True(t, cleaned) +} diff --git a/pkg/server/server_attached_test.go b/pkg/server/server_attached_test.go index 6d8055ed84..14560ae383 100644 --- a/pkg/server/server_attached_test.go +++ b/pkg/server/server_attached_test.go @@ -788,3 +788,53 @@ func TestSessionManager_DetachRuntimeReleasesAttachedSession(t *testing.T) { // Detaching an unknown or already detached session is a no-op. sm.DetachRuntime(sess.ID) } + +// recallFakeRuntime records the handler set through SetRecallHandler. +type recallFakeRuntime struct { + fakeRuntime + + handler runtime.RecallHandler +} + +func (r *recallFakeRuntime) SetRecallHandler(h runtime.RecallHandler) { r.handler = h } + +func TestSessionManager_DetachRuntimeClearsRecallHandler(t *testing.T) { + t.Parallel() + + ctx := t.Context() + store := session.NewInMemorySessionStore() + sess := session.New() + require.NoError(t, store.AddSession(ctx, sess)) + + rt := &recallFakeRuntime{} + sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{}) + sm.AttachRuntime(ctx, sess.ID, rt, sess) + require.NotNil(t, rt.handler) + + sm.DetachRuntime(sess.ID) + + assert.Nil(t, rt.handler, "recall handler installed by AttachRuntime must be cleared") +} + +func TestSessionManager_DetachRuntimeAllowsReattach(t *testing.T) { + t.Parallel() + + ctx := t.Context() + store := session.NewInMemorySessionStore() + sess := session.New() + require.NoError(t, store.AddSession(ctx, sess)) + + sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{}) + src := func(ctx context.Context, send func(any)) { <-ctx.Done() } + + sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess) + sm.RegisterEventSource(sess.ID, src) + require.True(t, sm.HasEventSource(sess.ID)) + + sm.DetachRuntime(sess.ID) + assert.False(t, sm.HasEventSource(sess.ID), "detach must tear down the event log") + + sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess) + sm.RegisterEventSource(sess.ID, src) + assert.True(t, sm.HasEventSource(sess.ID), "same ID must be able to register a new event source after reattach") +} diff --git a/pkg/server/session_manager.go b/pkg/server/session_manager.go index b313a0affb..89bb20dc99 100644 --- a/pkg/server/session_manager.go +++ b/pkg/server/session_manager.go @@ -341,6 +341,19 @@ func (sm *SessionManager) dropEventLog(sessionID string) { } } +// releaseEventLog tears down sessionID's event log, if any, without +// tombstoning the ID: unlike dropEventLog it is for a session that merely +// stops being attached (see DetachRuntime), so the same ID can be attached +// again and register a fresh event source. +func (sm *SessionManager) releaseEventLog(sessionID string) { + sm.eventLogsMu.Lock() + defer sm.eventLogsMu.Unlock() + if pe, ok := sm.eventLogs.Load(sessionID); ok { + pe.cancel() + sm.eventLogs.Delete(sessionID) + } +} + // appendSessionEvent appends event to sessionID's event log, creating the // log on demand (see ensureEventLog) if this is the first out-of-band event // the session has ever produced. Events for a deleted session are dropped. @@ -468,8 +481,8 @@ func (sm *SessionManager) AttachRuntime(ctx context.Context, sessionID string, r // persisted session. An embedder calls it when it stops owning the session, // e.g. when a TUI tab is closed under --listen; otherwise the runtime and its // session would stay reachable (and listed as active) until the process exits. -// Unlike [SessionManager.DeleteSession], the stored session is kept so it can -// still be resumed later. It is a no-op for unknown sessions. +// Unlike [SessionManager.DeleteSession], the stored session is kept and the +// session ID is not tombstoned, so it can be attached again (e.g. a reopened tab). It is a no-op for unknown sessions. func (sm *SessionManager) DetachRuntime(sessionID string) { sm.mux.Lock() defer sm.mux.Unlock() @@ -481,7 +494,13 @@ func (sm *SessionManager) DetachRuntime(sessionID string) { rs.cancel() } sm.runtimeSessions.Delete(sessionID) - sm.dropEventLog(sessionID) + // Undo the recall handler installed by AttachRuntime so a runtime kept by + // the embedder falls back to its own steer queue instead of routing idle + // recalls to a session this manager no longer owns. + if setter, ok := rs.runtime.(recallHandlerSetter); ok { + setter.SetRecallHandler(nil) + } + sm.releaseEventLog(sessionID) sm.followUpInjectors.Delete(sessionID) sm.followUpKeys.Delete(sessionID) sm.pendingSafetyDefaults.Delete(sessionID)