diff --git a/cmd/root/run.go b/cmd/root/run.go index 79d1e9365f..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) @@ -1397,6 +1400,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/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 6eef61d646..14560ae383 100644 --- a/pkg/server/server_attached_test.go +++ b/pkg/server/server_attached_test.go @@ -761,3 +761,80 @@ 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) +} + +// 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 a4b962d08b..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. @@ -462,6 +475,37 @@ 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 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() + rs, ok := sm.runtimeSessions.Load(sessionID) + if !ok { + return + } + if rs.cancel != nil { + rs.cancel() + } + sm.runtimeSessions.Delete(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) +} + // 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 {