From d5f2248e317bc0b9434cce083db157f6839894bf Mon Sep 17 00:00:00 2001 From: PerryLink Date: Sat, 14 Nov 2026 09:54:37 +0800 Subject: [PATCH 1/7] fix(server): detach a closed TUI tab's runtime Every TUI tab attaches its runtime and session to the session manager (AttachRuntime), but closing a tab only cancelled the supervisor context: the manager cleans up on session deletion, so in --listen mode each closed tab leaked its runtime, session, attach context, follow-up injector and recall handler for the process lifetime. Add SessionManager.DetachRuntime, symmetric with AttachRuntime: remove the entry, cancel the attach context, clear the recall handler and drop the injector and event log, leaving the persisted session alone and attachable again. The TUI spawner's cleanup, run by Supervisor.CloseSession, calls it. Signed-off-by: PerryLink --- cmd/root/run.go | 13 +++--- cmd/root/run_listen.go | 8 ++-- pkg/server/session_detach_test.go | 78 +++++++++++++++++++++++++++++++ pkg/server/session_manager.go | 37 +++++++++++++++ 4 files changed, 127 insertions(+), 9 deletions(-) create mode 100644 pkg/server/session_detach_test.go diff --git a/cmd/root/run.go b/cmd/root/run.go index 79d1e9365f..5a89a49233 100644 --- a/cmd/root/run.go +++ b/cmd/root/run.go @@ -1395,11 +1395,6 @@ func (f *runExecFlags) createSessionSpawner(agentSource config.Source, sessStore spawnReq.AgentName = agt.Name() newSess := session.New(f.buildSessionOpts(agt, t, spawnReq)...) - // Create cleanup function - cleanup := func() { - stopToolSets(spawnCtx, t) - } - // Create the app var appOpts []app.Opt if gen := localRt.TitleGenerator(spawnCtx); gen != nil { @@ -1408,11 +1403,17 @@ func (f *runExecFlags) createSessionSpawner(agentSource config.Source, sessStore if ctrl != nil { appOpts = append(appOpts, app.WithSnapshotController(ctrl)) } - coordinatorOpt := f.recallCoordinatorOpt(spawnCtx, localRt, newSess) + coordinatorOpt, detachRuntime := f.recallCoordinatorOpt(spawnCtx, localRt, newSess) if coordinatorOpt != nil { appOpts = append(appOpts, coordinatorOpt) } + // Create cleanup function + cleanup := func() { + detachRuntime() + stopToolSets(spawnCtx, t) + } + a := app.New(spawnCtx, localRt, newSess, appOpts...) return a, newSess, cleanup, nil diff --git a/cmd/root/run_listen.go b/cmd/root/run_listen.go index f9e5664ab6..69843b5839 100644 --- a/cmd/root/run_listen.go +++ b/cmd/root/run_listen.go @@ -34,20 +34,21 @@ import ( // become first-class control-plane sessions: clients can snapshot them, tail // their events and send follow-ups, exactly like the initial session. Without // this, a board watching the run sees a green card while a tab is mid-turn. -func (f *runExecFlags) recallCoordinatorOpt(ctx context.Context, rt runtime.Runtime, sess *session.Session) app.Opt { +func (f *runExecFlags) recallCoordinatorOpt(ctx context.Context, rt runtime.Runtime, sess *session.Session) (app.Opt, func()) { sm := f.listenSM exposed := sm != nil if !exposed { sm = server.NewSessionManager(ctx, nil, rt.SessionStore(), 0, &f.runConfig, server.WithSessionWorkingDirRoot(f.sessionWorkingDirRoot)) } guard := sm.AttachRuntime(ctx, sess.ID, rt, sess) + detach := func() { sm.DetachRuntime(sess.ID) } return func(a *app.App) { app.WithStreamGuard(guard)(a) if exposed { registerAppEventSource(sm, sess.ID, a) } sm.RegisterFollowUpInjector(sess.ID, a.InjectUserMessage) - } + }, detach } // registerAppEventSource exposes an App's runtime events on the control @@ -69,7 +70,8 @@ func registerAppEventSource(sm *server.SessionManager, sessionID string, a *app. // (see recallCoordinatorOpt for the stream-guard wiring shared by both paths). func (f *runExecFlags) startSessionCoordinator(ctx context.Context, out *cli.Printer, rt runtime.Runtime, sess *session.Session) (app.Opt, error) { if f.listenAddr == "" { - return f.recallCoordinatorOpt(ctx, rt, sess), nil + opt, _ := f.recallCoordinatorOpt(ctx, rt, sess) + return opt, nil } sm := server.NewSessionManager(ctx, nil, rt.SessionStore(), 0, &f.runConfig, server.WithSessionWorkingDirRoot(f.sessionWorkingDirRoot)) diff --git a/pkg/server/session_detach_test.go b/pkg/server/session_detach_test.go new file mode 100644 index 0000000000..d00ede5f48 --- /dev/null +++ b/pkg/server/session_detach_test.go @@ -0,0 +1,78 @@ +package server + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/docker/docker-agent/pkg/config" + "github.com/docker/docker-agent/pkg/runtime" + "github.com/docker/docker-agent/pkg/session" +) + +// recallRuntime records the recall handler installed by AttachRuntime, so a +// detach can assert the handler was unregistered. +type recallRuntime struct { + *fakeRuntime + handler runtime.RecallHandler +} + +func (r *recallRuntime) SetRecallHandler(handler runtime.RecallHandler) { r.handler = handler } + +func TestDetachRuntime_CleansUpAttachedState(t *testing.T) { + t.Parallel() + + ctx := t.Context() + store := session.NewInMemorySessionStore() + sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{}) + sess := session.New() + require.NoError(t, store.AddSession(ctx, sess)) + rt := &recallRuntime{fakeRuntime: &fakeRuntime{}} + + sm.AttachRuntime(ctx, sess.ID, rt, sess) + require.NotNil(t, rt.handler, "attach must install the recall handler") + sm.RegisterFollowUpInjector(sess.ID, func(context.Context, string) {}) + sm.RegisterEventSource(sess.ID, func(context.Context, func(any)) {}) + + attached, ok := sm.runtimeSessions.Load(sess.ID) + require.True(t, ok) + _, ok = sm.eventLogs.Load(sess.ID) + require.True(t, ok) + + sm.DetachRuntime(sess.ID) + + _, ok = sm.runtimeSessions.Load(sess.ID) + assert.False(t, ok, "detach must remove the attached runtime") + assert.Nil(t, rt.handler, "detach must unregister the recall handler") + _, ok = sm.followUpInjectors.Load(sess.ID) + assert.False(t, ok, "detach must drop the follow-up injector") + _, ok = sm.eventLogs.Load(sess.ID) + assert.False(t, ok, "detach must drop the event log") + select { + case <-attached.done: + default: + t.Fatal("detach must cancel the attach context") + } + + // The session itself survives the detach. + _, err := store.GetSession(ctx, sess.ID) + require.NoError(t, err, "detach must not delete the session") + + // Attaching again works: unlike session deletion, detach does not mark the + // event log permanently gone. + sm.AttachRuntime(ctx, sess.ID, rt, sess) + sm.RegisterEventSource(sess.ID, func(context.Context, func(any)) {}) + _, ok = sm.eventLogs.Load(sess.ID) + assert.True(t, ok, "a detached session must be attachable again") +} + +func TestDetachRuntime_UnknownSessionIsNoop(t *testing.T) { + t.Parallel() + + ctx := t.Context() + sm := NewSessionManager(ctx, config.Sources{}, session.NewInMemorySessionStore(), 0, &config.RuntimeConfig{}) + + assert.NotPanics(t, func() { sm.DetachRuntime("missing") }) +} diff --git a/pkg/server/session_manager.go b/pkg/server/session_manager.go index c737081d2a..abc675d6f4 100644 --- a/pkg/server/session_manager.go +++ b/pkg/server/session_manager.go @@ -462,6 +462,43 @@ func (sm *SessionManager) AttachRuntime(ctx context.Context, sessionID string, r return &rs.streaming } +// DetachRuntime removes the runtime attached for sessionID without deleting the +// session. It is symmetric with [SessionManager.AttachRuntime]: the attach context +// is cancelled and the follow-up injector, recall handler and event log are +// unregistered, while the persisted session and its history are left alone. The +// owner of a closed view (a TUI tab) calls it instead of DeleteSession, so the +// runtime, session and context do not accumulate for the process lifetime. +func (sm *SessionManager) DetachRuntime(sessionID string) { + sessionRuntime, ok := sm.runtimeSessions.Load(sessionID) + if !ok { + return + } + // Delete only our entry: a concurrent AttachRuntime may have replaced it. + if current, ok := sm.runtimeSessions.Load(sessionID); ok && current == sessionRuntime { + sm.runtimeSessions.Delete(sessionID) + } + if sessionRuntime.cancel != nil { + sessionRuntime.cancel() + } + if setter, ok := sessionRuntime.runtime.(recallHandlerSetter); ok { + setter.SetRecallHandler(nil) + } + sm.followUpInjectors.Delete(sessionID) + sm.followUpKeys.Delete(sessionID) + sm.detachEventLog(sessionID) +} + +// detachEventLog removes the session's event log without marking the session as +// deleted, so a later AttachRuntime can register a fresh one. +func (sm *SessionManager) detachEventLog(sessionID string) { + sm.eventLogsMu.Lock() + defer sm.eventLogsMu.Unlock() + if pe, ok := sm.eventLogs.Load(sessionID); ok { + pe.cancel() + sm.eventLogs.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 b704b1d9b5240b690cec9287a237910e4fd489de Mon Sep 17 00:00:00 2001 From: PerryLink Date: Sun, 15 Nov 2026 18:07:02 +0800 Subject: [PATCH 2/7] test(server): separate the embedded fake in the detach test golangci-lint's embeddedstructfieldcheck requires an empty line between an embedded field and regular fields; the detach test added in d5f2248 tripped it, so the lint job failed on that file. No behavior change. --- pkg/server/session_detach_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/pkg/server/session_detach_test.go b/pkg/server/session_detach_test.go index d00ede5f48..c82847b817 100644 --- a/pkg/server/session_detach_test.go +++ b/pkg/server/session_detach_test.go @@ -16,6 +16,7 @@ import ( // detach can assert the handler was unregistered. type recallRuntime struct { *fakeRuntime + handler runtime.RecallHandler } From 30e933f70e27c9b2be057fac8957559e70c6d0b5 Mon Sep 17 00:00:00 2001 From: PerryLink Date: Wed, 18 Nov 2026 19:31:35 +0800 Subject: [PATCH 3/7] fix(server): detach the initial tab when it closes startSessionCoordinator discarded the detach callback for both branches, and the --listen branch never returned one, so closing the initial tab only stopped its toolsets and closed the runtime. The manager kept the runtime, session, attach context, follow-up injector and event log, and the closed tab stayed in GET /api/sessions (#4909). Return the detach callback from both branches and wrap the initial tab's cleanup with detachOnClose, the same wrapper the spawner uses for spawned tabs. Cover the listen detach and the wrapper's once/detach-before-cleanup order in cmd/root tests. --- cmd/root/run.go | 18 ++++++++++----- cmd/root/run_listen.go | 27 +++++++++++++++++----- cmd/root/run_listen_test.go | 46 +++++++++++++++++++++++++++++++++++-- 3 files changed, 77 insertions(+), 14 deletions(-) diff --git a/cmd/root/run.go b/cmd/root/run.go index 5a89a49233..313e83c59d 100644 --- a/cmd/root/run.go +++ b/cmd/root/run.go @@ -560,7 +560,9 @@ func (f *runExecFlags) runOrExec(ctx context.Context, out *cli.Printer, args []s if err != nil { return err } - defer cleanup() + // The closure (not the func value) is deferred: startSessionCoordinator may + // wrap cleanup with the attach detach callback below. + defer func() { cleanup() }() if !useTUI { // Non-interactive (--exec) runs never clean up the worktree: there @@ -573,10 +575,17 @@ func (f *runExecFlags) runOrExec(ctx context.Context, out *cli.Printer, args []s // same busy guard RunSession/AddMessage/UpdateMessage use, so a // concurrent REST call is correctly rejected with 409 instead of racing // the TUI's live stream (#3590); see app.WithStreamGuard. - coordinatorOpt, err := f.startSessionCoordinator(ctx, out, rt, sess) + coordinatorOpt, detachCoordinator, err := f.startSessionCoordinator(ctx, out, rt, sess) if err != nil { return err } + // The initial tab attaches its runtime to the control plane (--listen) or to + // the recall manager like a spawned tab, so closing it must detach before its + // runtime is torn down: otherwise the manager keeps the runtime, session, + // attach context and event log for the process lifetime (#4909). + if detachCoordinator != nil { + cleanup = detachOnClose(cleanup, detachCoordinator) + } applyTheme(f.theme) opts, err := f.buildAppOpts(args) @@ -1409,10 +1418,7 @@ func (f *runExecFlags) createSessionSpawner(agentSource config.Source, sessStore } // Create cleanup function - cleanup := func() { - detachRuntime() - stopToolSets(spawnCtx, t) - } + cleanup := detachOnClose(func() { stopToolSets(spawnCtx, t) }, detachRuntime) a := app.New(spawnCtx, localRt, newSess, appOpts...) diff --git a/cmd/root/run_listen.go b/cmd/root/run_listen.go index 69843b5839..ab94c33bae 100644 --- a/cmd/root/run_listen.go +++ b/cmd/root/run_listen.go @@ -5,6 +5,7 @@ import ( "fmt" "log/slog" "os" + "sync" "time" tea "charm.land/bubbletea/v2" @@ -68,10 +69,10 @@ func registerAppEventSource(sm *server.SessionManager, sessionID string, a *app. // external processes can drive the running TUI (steer, followup, resume, ...). // It returns an app.Opt that registers the App as the attached session owner // (see recallCoordinatorOpt for the stream-guard wiring shared by both paths). -func (f *runExecFlags) startSessionCoordinator(ctx context.Context, out *cli.Printer, rt runtime.Runtime, sess *session.Session) (app.Opt, error) { +func (f *runExecFlags) startSessionCoordinator(ctx context.Context, out *cli.Printer, rt runtime.Runtime, sess *session.Session) (app.Opt, func(), error) { if f.listenAddr == "" { - opt, _ := f.recallCoordinatorOpt(ctx, rt, sess) - return opt, nil + opt, detach := f.recallCoordinatorOpt(ctx, rt, sess) + return opt, detach, nil } sm := server.NewSessionManager(ctx, nil, rt.SessionStore(), 0, &f.runConfig, server.WithSessionWorkingDirRoot(f.sessionWorkingDirRoot)) @@ -83,11 +84,11 @@ func (f *runExecFlags) startSessionCoordinator(ctx context.Context, out *cli.Pri ln, err := server.Listen(ctx, f.listenAddr) if err != nil { - return nil, fmt.Errorf("listen %s: %w", f.listenAddr, err) + return nil, nil, fmt.Errorf("listen %s: %w", f.listenAddr, err) } if err := httpsec.ValidateListenerAuth(ln.Addr(), ""); err != nil { _ = ln.Close() - return nil, err + return nil, nil, err } context.AfterFunc(ctx, func() { _ = ln.Close() }) @@ -119,5 +120,19 @@ func (f *runExecFlags) startSessionCoordinator(ctx context.Context, out *cli.Pri // Route control-plane follow-ups and idle recalls into the TUI App so // each starts a real turn and streams events to every subscriber. sm.RegisterFollowUpInjector(sess.ID, a.InjectUserMessage) - }, nil + }, func() { sm.DetachRuntime(sess.ID) }, nil +} + +// detachOnClose runs detach before cleanup, once, so a closed tab stops being +// an attached control-plane session before its runtime is torn down. Both the +// initial tab and the tabs the spawner creates use it (see run.go and +// createSessionSpawner). +func detachOnClose(cleanup, detach func()) func() { + var once sync.Once + return func() { + once.Do(func() { + detach() + cleanup() + }) + } } diff --git a/cmd/root/run_listen_test.go b/cmd/root/run_listen_test.go index ed567235b0..52c3b60551 100644 --- a/cmd/root/run_listen_test.go +++ b/cmd/root/run_listen_test.go @@ -2,6 +2,7 @@ package root import ( "context" + "io" "testing" "testing/synctest" "time" @@ -11,6 +12,7 @@ import ( "github.com/stretchr/testify/require" "github.com/docker/docker-agent/pkg/app" + "github.com/docker/docker-agent/pkg/cli" "github.com/docker/docker-agent/pkg/config" "github.com/docker/docker-agent/pkg/runtime" "github.com/docker/docker-agent/pkg/session" @@ -41,7 +43,7 @@ func TestStartSessionCoordinatorWithoutListenRoutesIdleRecallToApp(t *testing.T) rt := &recallRuntime{store: store} flags := &runExecFlags{runConfig: config.RuntimeConfig{}} - opt, err := flags.startSessionCoordinator(ctx, nil, rt, sess) + opt, _, err := flags.startSessionCoordinator(ctx, nil, rt, sess) require.NoError(t, err) require.NotNil(t, opt) require.NotNil(t, rt.recallHandler) @@ -79,7 +81,47 @@ func TestStartSessionCoordinatorRejectsNonLocalListener(t *testing.T) { require.NoError(t, store.AddSession(t.Context(), sess)) flags := &runExecFlags{listenAddr: "0.0.0.0:0"} - opt, err := flags.startSessionCoordinator(t.Context(), nil, &recallRuntime{store: store}, sess) + opt, detach, err := flags.startSessionCoordinator(t.Context(), nil, &recallRuntime{store: store}, sess) require.ErrorContains(t, err, "require --auth-token") assert.Nil(t, opt) + assert.Nil(t, detach) +} + +func TestStartSessionCoordinatorListenReturnsDetach(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + + store := session.NewInMemorySessionStore() + sess := session.New() + require.NoError(t, store.AddSession(ctx, sess)) + flags := &runExecFlags{listenAddr: "127.0.0.1:0"} + + opt, detach, err := flags.startSessionCoordinator(ctx, cli.NewPrinter(io.Discard), &recallRuntime{store: store}, sess) + require.NoError(t, err) + require.NotNil(t, opt) + require.NotNil(t, detach) + require.NotNil(t, flags.listenSM) + require.Len(t, flags.listenSM.GetActiveSessions(), 1) + + detach() + + require.Empty(t, flags.listenSM.GetActiveSessions()) + assert.False(t, flags.listenSM.WaitSessionAttached(ctx, sess.ID, 10*time.Millisecond)) +} + +func TestDetachOnCloseRunsDetachOnceBeforeCleanup(t *testing.T) { + t.Parallel() + + var order []string + cleanup := detachOnClose( + func() { order = append(order, "cleanup") }, + func() { order = append(order, "detach") }, + ) + + cleanup() + cleanup() + + assert.Equal(t, []string{"detach", "cleanup"}, order) } From e9383eb724bbd7e1d05ae9f3da70dc60677c330e Mon Sep 17 00:00:00 2001 From: PerryLink Date: Sat, 21 Nov 2026 12:00:47 +0800 Subject: [PATCH 4/7] fix(ci): silence gocritic deferUnlambda on the deferred cleanup closure golangci-lint's gocritic flags the deferred closure in runOrExec as deferUnlambda and suggests `defer cleanup()`. That rewrite is wrong here: deferring the func value captures cleanup when the defer is registered, so the detachOnClose wrapper installed after startSessionCoordinator returns would never run and a closed initial tab would keep its runtime attached (#4909). Keep the closure, which reads cleanup when it runs, and annotate the false positive; no behavior change. Signed-off-by: PerryLink --- cmd/root/run.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cmd/root/run.go b/cmd/root/run.go index 313e83c59d..de0511f682 100644 --- a/cmd/root/run.go +++ b/cmd/root/run.go @@ -561,8 +561,9 @@ func (f *runExecFlags) runOrExec(ctx context.Context, out *cli.Printer, args []s return err } // The closure (not the func value) is deferred: startSessionCoordinator may - // wrap cleanup with the attach detach callback below. - defer func() { cleanup() }() + // wrap cleanup with the attach detach callback below, so the deferred call + // must read cleanup when it runs. + defer func() { cleanup() }() //nolint:gocritic // deferUnlambda would capture cleanup before the detach wrapper is installed if !useTUI { // Non-interactive (--exec) runs never clean up the worktree: there From 654d6af3217fc0cf7788cf2e3826c888221ca856 Mon Sep 17 00:00:00 2001 From: PerryLink Date: Sun, 22 Nov 2026 10:30:48 +0800 Subject: [PATCH 5/7] fix(server): keep the detach guard and scope it to the attachment Closing a TUI tab runs the supervisor's cleanup off-lock, so detaching immediately removed the runtimeSessions entry that AddMessage and UpdateMessage probe to reject edits while the tab's stream is still running. Mark the attachment closing and drop the entry only once the stream releases its #3590 guard, so a REST edit cannot interleave with the stream it has to be rejected against. Bind the detach to the attachment it was created for instead of the session ID: AttachRuntime returns a *RuntimeAttachment handle whose Detach no-ops for a stale cleanup, and registration/teardown is serialised under sm.mux, so a same-ID replacement keeps its runtime registration, injector, key cache, event log and recall handler. A reused runtime also keeps the recall handler installed by the replacement. Continue the event-log sequence across a same-ID reattachment so a client reconnecting with its old Last-Event-ID does not silently filter out the replacement's events, and signal a gap when a cursor cannot belong to the current log. Resolve serve mcp --attach discovery against the run's active sessions so a closed initial tab is not advertised as a live target: an explicit session ID that is no longer attached fails clearly, while run-level discovery picks the only live session or lists the candidates. Cover the real lifecycle: closing an actual initial tab and an actual spawned tab through supervisor.CloseSession must detach both from the serving manager, and the listener test uses an injected temporary run registry. Signed-off-by: PerryLink --- cmd/root/mcp.go | 24 +++- cmd/root/mcp_test.go | 13 ++ cmd/root/run.go | 15 +++ cmd/root/run_listen.go | 15 +-- cmd/root/run_listen_test.go | 121 ++++++++++++++++- pkg/mcp/attach.go | 54 ++++++++ pkg/mcp/attach_test.go | 89 +++++++++++++ pkg/runtime/remote/client.go | 15 ++- pkg/server/eventlog.go | 59 +++++--- pkg/server/eventlog_test.go | 53 ++++++++ pkg/server/session_detach_test.go | 187 ++++++++++++++++++++++++-- pkg/server/session_manager.go | 215 ++++++++++++++++++++++-------- 12 files changed, 766 insertions(+), 94 deletions(-) diff --git a/cmd/root/mcp.go b/cmd/root/mcp.go index e5a831b556..5c0d2ebe6a 100644 --- a/cmd/root/mcp.go +++ b/cmd/root/mcp.go @@ -4,6 +4,8 @@ import ( "context" "errors" "fmt" + "strconv" + "strings" "github.com/spf13/cobra" @@ -122,5 +124,25 @@ func (f *mcpFlags) runAttach(ctx context.Context) error { if err != nil { return err } - return mcp.StartAttachStdio(ctx, rec.Addr, rec.SessionID) + // The discovery record keeps naming the session the run started with, but + // that tab can be closed while the run stays alive. Resolve a session that + // is actually attached before starting the proxy; an explicitly named + // closed session fails instead of being silently redirected. + sessionID, err := mcp.ResolveAttachSession(ctx, rec.Addr, rec.SessionID, attachTargetIsSessionID(target)) + if err != nil { + return err + } + return mcp.StartAttachStdio(ctx, rec.Addr, sessionID) +} + +// attachTargetIsSessionID reports whether a --attach value names a session ID +// explicitly rather than discovering the run by pid, address, or "latest". +func attachTargetIsSessionID(target string) bool { + if target == "" || target == "latest" { + return false + } + if _, err := strconv.Atoi(target); err == nil { + return false + } + return !strings.HasPrefix(target, "http://") && !strings.HasPrefix(target, "https://") } diff --git a/cmd/root/mcp_test.go b/cmd/root/mcp_test.go index 7199be5624..d96ec28b73 100644 --- a/cmd/root/mcp_test.go +++ b/cmd/root/mcp_test.go @@ -83,3 +83,16 @@ func TestMCPKeepAliveAcceptedForStdio(t *testing.T) { require.Error(t, err) assert.NotContains(t, err.Error(), "--mcp-keepalive") } + +func TestAttachTargetIsSessionID(t *testing.T) { + t.Parallel() + + // Explicit session IDs are the only attach targets that must not be + // silently redirected when the session's tab has closed. + for _, target := range []string{"abc123", "0f9a-session", "PerryLink/session"} { + assert.True(t, attachTargetIsSessionID(target), "target %q names a session", target) + } + for _, target := range []string{"", "latest", "4242", "http://127.0.0.1:8080", "https://example.test"} { + assert.False(t, attachTargetIsSessionID(target), "target %q discovers a run", target) + } +} diff --git a/cmd/root/run.go b/cmd/root/run.go index de0511f682..400556a9ad 100644 --- a/cmd/root/run.go +++ b/cmd/root/run.go @@ -31,6 +31,7 @@ import ( "github.com/docker/docker-agent/pkg/model/provider/dmr" "github.com/docker/docker-agent/pkg/permissions" "github.com/docker/docker-agent/pkg/profiling" + "github.com/docker/docker-agent/pkg/runregistry" "github.com/docker/docker-agent/pkg/runtime" "github.com/docker/docker-agent/pkg/sandbox" "github.com/docker/docker-agent/pkg/server" @@ -149,6 +150,20 @@ type runExecFlags struct { // clients can observe and drive every tab of the run — not just the // initial session. Nil when --listen is off. listenSM *server.SessionManager + + // runRegistry writes the --listen discovery record. Nil means the + // process-wide runregistry.Default(); tests inject a temp-dir registry so + // they never advertise a fake live run in (or leave a stale record in) the + // user's real registry. + runRegistry *runregistry.Registry +} + +// discoveryRegistry returns the registry used for --listen discovery records. +func (f *runExecFlags) discoveryRegistry() *runregistry.Registry { + if f.runRegistry != nil { + return f.runRegistry + } + return runregistry.Default() } func newRunCmd() *cobra.Command { diff --git a/cmd/root/run_listen.go b/cmd/root/run_listen.go index ab94c33bae..d788560121 100644 --- a/cmd/root/run_listen.go +++ b/cmd/root/run_listen.go @@ -41,15 +41,14 @@ func (f *runExecFlags) recallCoordinatorOpt(ctx context.Context, rt runtime.Runt if !exposed { sm = server.NewSessionManager(ctx, nil, rt.SessionStore(), 0, &f.runConfig, server.WithSessionWorkingDirRoot(f.sessionWorkingDirRoot)) } - guard := sm.AttachRuntime(ctx, sess.ID, rt, sess) - detach := func() { sm.DetachRuntime(sess.ID) } + attachment := sm.AttachRuntime(ctx, sess.ID, rt, sess) return func(a *app.App) { - app.WithStreamGuard(guard)(a) + app.WithStreamGuard(attachment)(a) if exposed { registerAppEventSource(sm, sess.ID, a) } sm.RegisterFollowUpInjector(sess.ID, a.InjectUserMessage) - }, detach + }, attachment.Detach } // registerAppEventSource exposes an App's runtime events on the control @@ -76,7 +75,7 @@ func (f *runExecFlags) startSessionCoordinator(ctx context.Context, out *cli.Pri } sm := server.NewSessionManager(ctx, nil, rt.SessionStore(), 0, &f.runConfig, server.WithSessionWorkingDirRoot(f.sessionWorkingDirRoot)) - guard := sm.AttachRuntime(ctx, sess.ID, rt, sess) + attachment := sm.AttachRuntime(ctx, sess.ID, rt, sess) // Publish the serving manager so sessions spawned later (TUI tabs) attach // to it too (see recallCoordinatorOpt). Set before the TUI starts, so no // spawn can race it. @@ -92,7 +91,7 @@ func (f *runExecFlags) startSessionCoordinator(ctx context.Context, out *cli.Pri } context.AfterFunc(ctx, func() { _ = ln.Close() }) - cleanup, err := runregistry.Default().Write(runregistry.Record{ + cleanup, err := f.discoveryRegistry().Write(runregistry.Record{ PID: os.Getpid(), Addr: "http://" + ln.Addr().String(), SessionID: sess.ID, @@ -115,12 +114,12 @@ func (f *runExecFlags) startSessionCoordinator(ctx context.Context, out *cli.Pri }() return func(a *app.App) { - app.WithStreamGuard(guard)(a) + app.WithStreamGuard(attachment)(a) registerAppEventSource(sm, sess.ID, a) // Route control-plane follow-ups and idle recalls into the TUI App so // each starts a real turn and streams events to every subscriber. sm.RegisterFollowUpInjector(sess.ID, a.InjectUserMessage) - }, func() { sm.DetachRuntime(sess.ID) }, nil + }, attachment.Detach, nil } // detachOnClose runs detach before cleanup, once, so a closed tab stops being diff --git a/cmd/root/run_listen_test.go b/cmd/root/run_listen_test.go index 52c3b60551..5f5e8438e6 100644 --- a/cmd/root/run_listen_test.go +++ b/cmd/root/run_listen_test.go @@ -3,6 +3,7 @@ package root import ( "context" "io" + "slices" "testing" "testing/synctest" "time" @@ -14,9 +15,13 @@ import ( "github.com/docker/docker-agent/pkg/app" "github.com/docker/docker-agent/pkg/cli" "github.com/docker/docker-agent/pkg/config" + "github.com/docker/docker-agent/pkg/environment" + "github.com/docker/docker-agent/pkg/runregistry" "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" + "github.com/docker/docker-agent/pkg/tui/service/supervisor" ) type recallRuntime struct { @@ -32,6 +37,37 @@ func (r *recallRuntime) SetRecallHandler(handler runtime.RecallHandler) { r.recallHandler = handler } +// The App started by the supervisor below asks the runtime for its startup info +// and registers event sinks; the embedded nil Runtime would panic, so the bare +// recall fixture stubs them out. +func (r *recallRuntime) EmitStartupInfo(context.Context, *session.Session, runtime.EventSink) {} + +func (r *recallRuntime) OnToolsChanged(func(runtime.Event)) {} + +func (r *recallRuntime) OnBackgroundEvent(func(runtime.Event)) {} + +func (r *recallRuntime) OnElicitationRequest(func(runtime.Event)) {} + +// testListenFlags builds the flags for a control-plane test with an isolated +// run registry: the listener writes a discovery record under the data dir, and +// tests must never advertise a fake live run (or leave a stale record) in the +// real one. +func testListenFlags(t *testing.T) (*runExecFlags, *runregistry.Registry) { + t.Helper() + registry := runregistry.New(t.TempDir()) + return &runExecFlags{ + listenAddr: "127.0.0.1:0", + runConfig: config.RuntimeConfig{EnvProviderOverride: environment.NewMapEnvProvider(map[string]string{"OPENAI_API_KEY": "test"})}, + runRegistry: registry, + }, registry +} + +const testSpawnAgentManifest = `agents: + root: + model: openai/gpt-5-mini + instruction: test agent +` + func TestStartSessionCoordinatorWithoutListenRoutesIdleRecallToApp(t *testing.T) { t.Parallel() @@ -87,7 +123,10 @@ func TestStartSessionCoordinatorRejectsNonLocalListener(t *testing.T) { assert.Nil(t, detach) } -func TestStartSessionCoordinatorListenReturnsDetach(t *testing.T) { +// TestStartSessionCoordinatorListenUsesIsolatedRegistry covers the listener +// lifecycle and the test-registry isolation: the record is written to the +// injected registry, and cancelling the run context removes it again. +func TestStartSessionCoordinatorListenUsesIsolatedRegistry(t *testing.T) { t.Parallel() ctx, cancel := context.WithCancel(t.Context()) @@ -96,7 +135,7 @@ func TestStartSessionCoordinatorListenReturnsDetach(t *testing.T) { store := session.NewInMemorySessionStore() sess := session.New() require.NoError(t, store.AddSession(ctx, sess)) - flags := &runExecFlags{listenAddr: "127.0.0.1:0"} + flags, registry := testListenFlags(t) opt, detach, err := flags.startSessionCoordinator(ctx, cli.NewPrinter(io.Discard), &recallRuntime{store: store}, sess) require.NoError(t, err) @@ -105,10 +144,20 @@ func TestStartSessionCoordinatorListenReturnsDetach(t *testing.T) { require.NotNil(t, flags.listenSM) require.Len(t, flags.listenSM.GetActiveSessions(), 1) - detach() + records, err := registry.List() + require.NoError(t, err) + require.Len(t, records, 1, "the listener must advertise the run in the injected registry") + assert.Equal(t, sess.ID, records[0].SessionID) + detach() require.Empty(t, flags.listenSM.GetActiveSessions()) assert.False(t, flags.listenSM.WaitSessionAttached(ctx, sess.ID, 10*time.Millisecond)) + + cancel() + require.Eventually(t, func() bool { + records, err := registry.List() + return err == nil && len(records) == 0 + }, 5*time.Second, 10*time.Millisecond, "cancelling the run must remove the discovery record") } func TestDetachOnCloseRunsDetachOnceBeforeCleanup(t *testing.T) { @@ -125,3 +174,69 @@ func TestDetachOnCloseRunsDetachOnceBeforeCleanup(t *testing.T) { assert.Equal(t, []string{"detach", "cleanup"}, order) } + +// activeSessionIDs snapshots the control plane's active session IDs. +func activeSessionIDs(sm *server.SessionManager) []string { + sessions := sm.GetActiveSessions() + ids := make([]string, 0, len(sessions)) + for _, sess := range sessions { + ids = append(ids, sess.ID) + } + return ids +} + +// TestInitialAndSpawnedTabCloseDetachFromListenManager is the lifecycle +// regression test for #4909: it closes a real initial tab and a real spawned tab +// through supervisor.CloseSession (the path the TUI uses) and checks the serving +// manager afterwards, instead of invoking the detach/cleanup callbacks directly. +func TestInitialAndSpawnedTabCloseDetachFromListenManager(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + + store := session.NewInMemorySessionStore() + sess := session.New() + require.NoError(t, store.AddSession(ctx, sess)) + rt := &recallRuntime{store: store} + flags, _ := testListenFlags(t) + flags.agentName = "root" + + coordinatorOpt, detachCoordinator, err := flags.startSessionCoordinator(ctx, cli.NewPrinter(io.Discard), rt, sess) + require.NoError(t, err) + require.NotNil(t, coordinatorOpt) + require.NotNil(t, detachCoordinator) + + // The spawner is the real one runOrExec hands to the TUI. + spawner := flags.createSessionSpawner(config.NewBytesSource("agent.yaml", []byte(testSpawnAgentManifest)), store) + sup := supervisor.New(spawner) + + // Initial tab: wired exactly as runOrExec wires it before handing the + // cleanup to the TUI. + initialCleanup := detachOnClose(func() {}, detachCoordinator) + initialApp := app.New(ctx, rt, sess, coordinatorOpt) + sup.AddSession(ctx, initialApp, sess, t.TempDir(), initialCleanup) + require.Equal(t, []string{sess.ID}, activeSessionIDs(flags.listenSM)) + + // Spawned tab: created by the real spawner and added by the supervisor. + spawnedID, err := sup.SpawnSession(ctx, t.TempDir()) + require.NoError(t, err) + require.NotEqual(t, sess.ID, spawnedID) + require.ElementsMatch(t, []string{sess.ID, spawnedID}, activeSessionIDs(flags.listenSM)) + + // Closing the initial tab while another tab is open must detach only it. + sup.CloseSession(sess.ID) + require.Eventually(t, func() bool { + return slices.Equal([]string{spawnedID}, activeSessionIDs(flags.listenSM)) + }, 5*time.Second, 10*time.Millisecond, "closing the initial tab must detach it and leave the spawned tab attached") + + // Tab close is not session delete: the initial session is still stored. + _, err = store.GetSession(ctx, sess.ID) + require.NoError(t, err, "closing the initial tab must not delete the session") + + // Closing the last tab releases the manager completely. + sup.CloseSession(spawnedID) + require.Eventually(t, func() bool { + return len(flags.listenSM.GetActiveSessions()) == 0 + }, 5*time.Second, 10*time.Millisecond, "closing the spawned tab must detach it") +} diff --git a/pkg/mcp/attach.go b/pkg/mcp/attach.go index a370df347c..e6c73440e5 100644 --- a/pkg/mcp/attach.go +++ b/pkg/mcp/attach.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "log/slog" + "strings" "github.com/modelcontextprotocol/go-sdk/mcp" @@ -101,6 +102,59 @@ func AttachServer(ctx context.Context, addr, sessionID string) (*mcp.Server, err return server, nil } +// ResolveAttachSession returns the session ID an attach client should drive for +// the run at addr. recorded is the session ID stored in the run's discovery +// record; explicit reports whether the caller named that session explicitly +// (rather than discovering the run by pid, address, or "latest"). +// +// A run's discovery record keeps naming the session it started with, but under +// --listen that initial tab can be closed while the run (and other tabs) stay +// alive. Attaching to the closed ID would make every send fail with "session +// not found or not running", so: +// +// - when the recorded session is still attached, it is used; +// - an explicitly named session that is no longer attached fails with a clear +// error listing the live sessions instead of being silently redirected to +// another one; +// - a fresh run-level discovery resolves the live session when there is +// exactly one, and otherwise fails clearly listing the candidates. +func ResolveAttachSession(ctx context.Context, addr, recorded string, explicit bool) (string, error) { + client, err := remote.NewClient(addr) + if err != nil { + return "", fmt.Errorf("client for %s: %w", addr, err) + } + active, err := client.GetActiveSessions(ctx) + if err != nil { + return "", fmt.Errorf("listing attached sessions of %s: %w", addr, err) + } + live := make([]string, 0, len(active)) + for _, sess := range active { + if sess.ID == recorded { + return recorded, nil + } + live = append(live, sess.ID) + } + + if explicit { + return "", fmt.Errorf("session %s is no longer attached to the run at %s (its tab was closed); live sessions: %s", recorded, addr, formatSessionIDs(live)) + } + switch len(live) { + case 0: + return "", fmt.Errorf("the run at %s has no attached session: its initial session %s was closed and no other tab is open", addr, recorded) + case 1: + return live[0], nil + default: + return "", fmt.Errorf("the run's initial session %s is no longer attached and the run has several live sessions; select one explicitly with --attach : %s", recorded, formatSessionIDs(live)) + } +} + +func formatSessionIDs(ids []string) string { + if len(ids) == 0 { + return "none" + } + return strings.Join(ids, ", ") +} + // StartAttachStdio runs the attach MCP server over stdio. func StartAttachStdio(ctx context.Context, addr, sessionID string) error { server, err := AttachServer(ctx, addr, sessionID) diff --git a/pkg/mcp/attach_test.go b/pkg/mcp/attach_test.go index e1e0512289..bb0239d55a 100644 --- a/pkg/mcp/attach_test.go +++ b/pkg/mcp/attach_test.go @@ -1,12 +1,101 @@ package mcp import ( + "encoding/json" + "net/http" + "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/docker/docker-agent/pkg/api" ) +// activeSessionsServer serves GET /api/sessions?active=true with the given +// session IDs, mimicking a --listen control plane. +func activeSessionsServer(t *testing.T, ids ...string) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/sessions" { + http.NotFound(w, r) + return + } + if r.URL.Query().Get("active") != "true" { + http.Error(w, "test server only serves active sessions", http.StatusBadRequest) + return + } + sessions := make([]api.SessionsResponse, 0, len(ids)) + for _, id := range ids { + sessions = append(sessions, api.SessionsResponse{ID: id}) + } + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(sessions); err != nil { + t.Errorf("encoding sessions: %v", err) + } + })) + t.Cleanup(srv.Close) + return srv +} + +func TestResolveAttachSession_UsesAttachedRecordedSession(t *testing.T) { + t.Parallel() + + srv := activeSessionsServer(t, "initial", "spawned") + + sessionID, err := ResolveAttachSession(t.Context(), srv.URL, "initial", true) + require.NoError(t, err) + assert.Equal(t, "initial", sessionID) + + sessionID, err = ResolveAttachSession(t.Context(), srv.URL, "spawned", false) + require.NoError(t, err) + assert.Equal(t, "spawned", sessionID) +} + +func TestResolveAttachSession_ExplicitClosedSessionFailsClearly(t *testing.T) { + t.Parallel() + + srv := activeSessionsServer(t, "spawned") + + _, err := ResolveAttachSession(t.Context(), srv.URL, "closed-initial", true) + require.Error(t, err) + assert.Contains(t, err.Error(), "closed-initial") + assert.Contains(t, err.Error(), "no longer attached") + assert.Contains(t, err.Error(), "spawned", "the error must list the live sessions") +} + +func TestResolveAttachSession_DiscoveryResolvesUnambiguousLiveSession(t *testing.T) { + t.Parallel() + + srv := activeSessionsServer(t, "spawned") + + sessionID, err := ResolveAttachSession(t.Context(), srv.URL, "closed-initial", false) + require.NoError(t, err) + assert.Equal(t, "spawned", sessionID, "run-level discovery must resolve the live tab instead of the closed initial session") +} + +func TestResolveAttachSession_DiscoveryFailsWhenAmbiguous(t *testing.T) { + t.Parallel() + + srv := activeSessionsServer(t, "tab-a", "tab-b") + + _, err := ResolveAttachSession(t.Context(), srv.URL, "closed-initial", false) + require.Error(t, err) + assert.Contains(t, err.Error(), "tab-a") + assert.Contains(t, err.Error(), "tab-b") + assert.Contains(t, err.Error(), "--attach ") +} + +func TestResolveAttachSession_DiscoveryFailsWhenRunHasNoTabs(t *testing.T) { + t.Parallel() + + srv := activeSessionsServer(t) + + _, err := ResolveAttachSession(t.Context(), srv.URL, "closed-initial", false) + require.Error(t, err) + assert.Contains(t, err.Error(), "no attached session") +} + func TestAttachServer_RequiresArgs(t *testing.T) { t.Parallel() ctx := t.Context() diff --git a/pkg/runtime/remote/client.go b/pkg/runtime/remote/client.go index 8b4240bff2..55c46c2735 100644 --- a/pkg/runtime/remote/client.go +++ b/pkg/runtime/remote/client.go @@ -110,7 +110,11 @@ func (c *Client) doRequestWithTimeout(ctx context.Context, method, endpoint stri } u := *c.baseURL - u.Path = path.Join(u.Path, endpoint) + // Keep an endpoint's query string out of the path: path.Join would escape + // the "?" into the path and drop the query. + endpointPath, endpointQuery, _ := strings.Cut(endpoint, "?") + u.Path = path.Join(u.Path, endpointPath) + u.RawQuery = endpointQuery // Apply per-request timeout based on category timeout := c.timeoutFor(timeoutCategory) @@ -250,6 +254,15 @@ func (c *Client) GetSessions(ctx context.Context) ([]api.SessionsResponse, error return sessions, err } +// GetActiveSessions retrieves only the sessions currently attached to the +// remote run (GET /api/sessions?active=true). Unlike GetSessions it never +// includes historical sessions loaded from the store. +func (c *Client) GetActiveSessions(ctx context.Context) ([]api.SessionsResponse, error) { + var sessions []api.SessionsResponse + err := c.doRequest(ctx, http.MethodGet, "/api/sessions?active=true", nil, &sessions) + return sessions, err +} + // GetSession retrieves a session by ID func (c *Client) GetSession(ctx context.Context, id string) (*api.SessionResponse, error) { var sess api.SessionResponse diff --git a/pkg/server/eventlog.go b/pkg/server/eventlog.go index 4714ed08c4..27232d8c7c 100644 --- a/pkg/server/eventlog.go +++ b/pkg/server/eventlog.go @@ -18,10 +18,12 @@ type seqEvent struct { } // gapEvent is sent to a subscriber whose requested resume point has already -// been evicted from the ring buffer. It is a per-connection control marker, -// not part of the session's sequenced stream, so it carries no sequence -// number. The client should re-snapshot (GET /snapshot) to resync, then -// continue tailing from the snapshot's sequence number. +// been evicted from the ring buffer, or whose cursor is above everything this +// log has produced (so it belongs to a different log for the same session ID). +// It is a per-connection control marker, not part of the session's sequenced +// stream, so it carries no sequence number. The client should re-snapshot +// (GET /snapshot) to resync, then continue tailing from the snapshot's sequence +// number. type gapEvent struct { Type string `json:"type"` // always "gap" } @@ -64,11 +66,21 @@ type eventListener struct { } func newEventLog(capacity int) *eventLog { + return newEventLogAt(capacity, 0) +} + +// newEventLogAt creates a log whose sequence numbers start at startSeq. A log +// recreated for a session that is being reattached (see +// SessionManager.RegisterEventSource) starts where the previous log for that +// session ID stopped, so a client resuming with its last event ID still has a +// valid cursor instead of silently filtering out the new log's events. +func newEventLogAt(capacity int, startSeq uint64) *eventLog { if capacity <= 0 { capacity = defaultEventLogCapacity } return &eventLog{ capacity: capacity, + seq: startSeq, listeners: make(map[*eventListener]struct{}), } } @@ -149,10 +161,13 @@ func (l *eventLog) lastSeq() uint64 { // delivered live: every event is seen exactly once, in order. func (l *eventLog) stream(ctx context.Context, since *uint64, send func(seq uint64, event any)) { l.mu.Lock() + // Snapshot the log's last sequence number together with the backlog: a + // cursor above it cannot have been produced by this log (see gapped). + lastSeq := l.seq if l.closed { backlog := l.backlogLocked(since) l.mu.Unlock() - l.replay(ctx, since, backlog, send) + l.replay(ctx, since, lastSeq, backlog, send) return } backlog := l.backlogLocked(since) @@ -166,7 +181,7 @@ func (l *eventLog) stream(ctx context.Context, since *uint64, send func(seq uint delete(l.listeners, ln) }() - if !l.replay(ctx, since, backlog, send) { + if !l.replay(ctx, since, lastSeq, backlog, send) { return } @@ -202,10 +217,11 @@ func (l *eventLog) backlogLocked(since *uint64) []seqEvent { return out } -// replay sends a gap marker (when the resume point was evicted) followed by -// the backlog. Returns false if ctx was cancelled mid-replay. -func (l *eventLog) replay(ctx context.Context, since *uint64, backlog []seqEvent, send func(seq uint64, event any)) bool { - if since != nil && l.gapped(*since, backlog) { +// replay sends a gap marker (when the resume point was evicted or belongs to a +// previous log) followed by the backlog. Returns false if ctx was cancelled +// mid-replay. +func (l *eventLog) replay(ctx context.Context, since *uint64, lastSeq uint64, backlog []seqEvent, send func(seq uint64, event any)) bool { + if since != nil && l.gapped(*since, lastSeq, backlog) { select { case <-ctx.Done(): return false @@ -224,11 +240,24 @@ func (l *eventLog) replay(ctx context.Context, since *uint64, backlog []seqEvent return true } -// gapped reports whether resuming at since lost events: the next expected -// sequence number (since+1) is older than the oldest event we can still -// replay. An empty backlog with a non-zero since is not a gap on its own -// (the client is simply already caught up). -func (l *eventLog) gapped(since uint64, backlog []seqEvent) bool { +// gapped reports whether resuming at since lost events. +// +// A since above lastSeq cannot come from this log: sequence numbers only grow +// within one log, so the cursor belongs to a different log for the same session +// ID. Every event of this log would be filtered out by that cursor, so signal a +// gap even when the backlog is still empty and tell the client to re-snapshot. +// The usual same-ID reattachment path preserves the numbering instead (see +// SessionManager.eventLogLastSeq); this is the defensive reset for a log whose +// continuity could not be preserved. +// +// Otherwise the resume point is a gap when the next expected sequence number +// (since+1) is older than the oldest event still replayable. An empty backlog +// with a non-zero since is not a gap in that case (the client is simply already +// caught up). +func (l *eventLog) gapped(since, lastSeq uint64, backlog []seqEvent) bool { + if since > lastSeq { + return true + } if len(backlog) == 0 { return false } diff --git a/pkg/server/eventlog_test.go b/pkg/server/eventlog_test.go index aa1c651dae..3068a5f637 100644 --- a/pkg/server/eventlog_test.go +++ b/pkg/server/eventlog_test.go @@ -163,6 +163,59 @@ func TestEventLog_NoGapWhenCaughtUp(t *testing.T) { }) } +// TestEventLog_ContinuityAcrossReattach pins the same-ID reattach behavior: a +// log recreated for a reattached session starts at the previous log's last +// sequence number, so a client reconnecting with its last event ID keeps a valid +// cursor and receives the replacement's events instead of filtering them out. +func TestEventLog_ContinuityAcrossReattach(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + oldLog := newEventLog(8) + oldLog.append("old-1") // 1 + oldLog.append("old-2") // 2 + resumeCursor := oldLog.lastSeq() + + newLog := newEventLogAt(8, resumeCursor) + stop, got := collect(t, newLog, &resumeCursor) + defer stop() + + newLog.append("startup") // 3 + synctest.Wait() + require.Len(t, got(), 1, "resuming across a reattach must not need a reset") + assert.Equal(t, uint64(3), got()[0].seq) + _, isGap := got()[0].event.(gapEvent) + assert.False(t, isGap) + }) +} + +// TestEventLog_CursorAboveLastSeqSignalsReset covers the defensive reset: a +// cursor above everything this log has ever produced cannot belong to it (e.g. +// a log recreated without continuity), so it must be signalled as a gap instead +// of filtering out every event. +func TestEventLog_CursorAboveLastSeqSignalsReset(t *testing.T) { + t.Parallel() + + synctest.Test(t, func(t *testing.T) { + log := newEventLog(8) + log.append("a") // 1 + since := uint64(2) + + stop, got := collect(t, log, &since) + defer stop() + + synctest.Wait() + require.Len(t, got(), 1) + _, isGap := got()[0].event.(gapEvent) + assert.True(t, isGap, "a cursor above the log's last sequence must signal a reset") + + log.append("b") // 2 + synctest.Wait() + require.Len(t, got(), 2) + assert.Equal(t, uint64(2), got()[1].seq) + }) +} + // TestEventLog_RegistrationIsGapless asserts the critical property: an event // appended concurrently with a new subscriber connecting is delivered exactly // once — either in the backlog or live, never dropped and never duplicated. diff --git a/pkg/server/session_detach_test.go b/pkg/server/session_detach_test.go index c82847b817..879aba39ff 100644 --- a/pkg/server/session_detach_test.go +++ b/pkg/server/session_detach_test.go @@ -3,6 +3,7 @@ package server import ( "context" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -22,27 +23,38 @@ type recallRuntime struct { func (r *recallRuntime) SetRecallHandler(handler runtime.RecallHandler) { r.handler = handler } -func TestDetachRuntime_CleansUpAttachedState(t *testing.T) { - t.Parallel() +func newDetachTestManager(t *testing.T) (*SessionManager, *session.Session) { + t.Helper() ctx := t.Context() store := session.NewInMemorySessionStore() - sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{}) sess := session.New() require.NoError(t, store.AddSession(ctx, sess)) + return NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{}), sess +} + +func blockUntilCancelled(ctx context.Context, send func(any)) { + <-ctx.Done() +} + +func TestAttachRuntime_DetachCleansUpAttachedState(t *testing.T) { + t.Parallel() + + ctx := t.Context() + sm, sess := newDetachTestManager(t) rt := &recallRuntime{fakeRuntime: &fakeRuntime{}} - sm.AttachRuntime(ctx, sess.ID, rt, sess) + attachment := sm.AttachRuntime(ctx, sess.ID, rt, sess) require.NotNil(t, rt.handler, "attach must install the recall handler") sm.RegisterFollowUpInjector(sess.ID, func(context.Context, string) {}) - sm.RegisterEventSource(sess.ID, func(context.Context, func(any)) {}) + sm.RegisterEventSource(sess.ID, blockUntilCancelled) attached, ok := sm.runtimeSessions.Load(sess.ID) require.True(t, ok) _, ok = sm.eventLogs.Load(sess.ID) require.True(t, ok) - sm.DetachRuntime(sess.ID) + attachment.Detach() _, ok = sm.runtimeSessions.Load(sess.ID) assert.False(t, ok, "detach must remove the attached runtime") @@ -58,22 +70,173 @@ func TestDetachRuntime_CleansUpAttachedState(t *testing.T) { } // The session itself survives the detach. - _, err := store.GetSession(ctx, sess.ID) + _, err := sm.sessionStore.GetSession(ctx, sess.ID) require.NoError(t, err, "detach must not delete the session") // Attaching again works: unlike session deletion, detach does not mark the // event log permanently gone. - sm.AttachRuntime(ctx, sess.ID, rt, sess) - sm.RegisterEventSource(sess.ID, func(context.Context, func(any)) {}) + replacement := sm.AttachRuntime(ctx, sess.ID, rt, sess) + sm.RegisterEventSource(sess.ID, blockUntilCancelled) _, ok = sm.eventLogs.Load(sess.ID) assert.True(t, ok, "a detached session must be attachable again") + replacement.Detach() + + // Detaching twice is a no-op. + assert.NotPanics(t, attachment.Detach) +} + +// TestDetachRuntime_KeepsBusyGuardUntilStreamStops is the regression test for +// the #3590 busy guard: closing a tab schedules cleanup without waiting for the +// tab's stream to drain, but AddMessage/UpdateMessage must keep rejecting edits +// until that stream has actually stopped. +func TestDetachRuntime_KeepsBusyGuardUntilStreamStops(t *testing.T) { + t.Parallel() + + ctx := t.Context() + sm, sess := newDetachTestManager(t) + rt := &recallRuntime{fakeRuntime: &fakeRuntime{}} + attachment := sm.AttachRuntime(ctx, sess.ID, rt, sess) + sm.RegisterFollowUpInjector(sess.ID, func(context.Context, string) {}) + sm.RegisterEventSource(sess.ID, blockUntilCancelled) + + // Hold the guard exactly like pkg/app's WithStreamGuard does around the + // TUI's direct RunStream call. An HTTP-started stream would hold the same + // lock while its request context keeps it alive, which is why closing the + // tab must not drop the guard on its own. + attachment.Lock() + attachment.Detach() + + // The per-attachment state is gone, but the old stream still owns the busy + // guard, so edits must keep failing. + assert.Nil(t, rt.handler) + assert.False(t, sm.HasEventSource(sess.ID)) + assert.Len(t, sm.GetActiveSessions(), 1, "the closing attachment stays registered while its stream drains") + require.ErrorIs(t, sm.AddMessage(ctx, sess.ID, session.UserMessage("edit mid-stream")), ErrSessionBusy) + require.ErrorIs(t, sm.UpdateMessage(ctx, sess.ID, "0", session.UserMessage("edit mid-stream")), ErrSessionBusy) + + // Releasing the guard ends the stream: the attachment is finally removed and + // the stored session can be edited again. + attachment.Unlock() + + assert.Empty(t, sm.GetActiveSessions(), "stream teardown must finish the detach") + require.NoError(t, sm.AddMessage(ctx, sess.ID, session.UserMessage("edit after close"))) +} + +// TestDetachRuntime_StaleCleanupLeavesReplacementUsable covers the cleanup that +// races a same-ID reattach: a detach for the old attachment must not remove the +// replacement or clear its injector, key cache, event log or recall handler. +func TestDetachRuntime_StaleCleanupLeavesReplacementUsable(t *testing.T) { + t.Parallel() + + ctx := t.Context() + sm, sess := newDetachTestManager(t) + oldRT := &recallRuntime{fakeRuntime: &fakeRuntime{}} + oldAttachment := sm.AttachRuntime(ctx, sess.ID, oldRT, sess) + + // The same session ID is attached again, replacing the first attachment. + // Reuse the same runtime instance on purpose: a stale detach used to clear + // whatever recall handler the runtime has installed, including the + // replacement's one. + newAttachment := sm.AttachRuntime(ctx, sess.ID, oldRT, sess) + sm.RegisterFollowUpInjector(sess.ID, func(context.Context, string) {}) + sm.RegisterEventSource(sess.ID, blockUntilCancelled) + require.NotNil(t, oldRT.handler) + + // Late cleanup for the replaced attachment. + oldAttachment.Detach() + + assert.NotNil(t, oldRT.handler, "stale cleanup must not clear the replacement's recall handler") + assert.True(t, sm.HasEventSource(sess.ID), "stale cleanup must not drop the replacement's event log") + _, ok := sm.followUpInjectors.Load(sess.ID) + assert.True(t, ok, "stale cleanup must not drop the replacement's follow-up injector") + require.Len(t, sm.GetActiveSessions(), 1) + + // The replacement is still usable and is the one that detach removes. + require.NoError(t, sm.AddMessage(ctx, sess.ID, session.UserMessage("still editable"))) + newAttachment.Detach() + assert.Empty(t, sm.GetActiveSessions()) } -func TestDetachRuntime_UnknownSessionIsNoop(t *testing.T) { +// TestDetachRuntime_PendingTeardownDoesNotTearDownReplacement covers the other +// interleaving: the old attachment detaches while its stream is still running, +// a replacement is attached for the same ID, and only then does the old stream +// stop. Finishing the old detach must leave the replacement untouched. +func TestDetachRuntime_PendingTeardownDoesNotTearDownReplacement(t *testing.T) { t.Parallel() ctx := t.Context() - sm := NewSessionManager(ctx, config.Sources{}, session.NewInMemorySessionStore(), 0, &config.RuntimeConfig{}) + sm, sess := newDetachTestManager(t) + oldRT := &recallRuntime{fakeRuntime: &fakeRuntime{}} + oldAttachment := sm.AttachRuntime(ctx, sess.ID, oldRT, sess) + + oldAttachment.Lock() // old stream is running + oldAttachment.Detach() // cleanup arrives while the stream drains + + // A reopened tab reattaches the same session ID before the old stream ends. + newRT := &recallRuntime{fakeRuntime: &fakeRuntime{}} + newAttachment := sm.AttachRuntime(ctx, sess.ID, newRT, sess) + sm.RegisterFollowUpInjector(sess.ID, func(context.Context, string) {}) + sm.RegisterEventSource(sess.ID, blockUntilCancelled) + require.NotNil(t, newRT.handler) + + oldAttachment.Unlock() // old stream ends, finishing the pending detach + + assert.NotNil(t, newRT.handler, "finishing a stale detach must not clear the replacement's recall handler") + assert.True(t, sm.HasEventSource(sess.ID)) + _, ok := sm.followUpInjectors.Load(sess.ID) + assert.True(t, ok) + require.Len(t, sm.GetActiveSessions(), 1) + require.NoError(t, sm.AddMessage(ctx, sess.ID, session.UserMessage("still editable"))) + + newAttachment.Detach() + assert.Empty(t, sm.GetActiveSessions()) +} + +// TestDetachRuntime_ReattachContinuesSSECursor is the should-fix regression for +// stale SSE cursors: a subscriber that disconnects before session_exited and +// reconnects after the same session ID was reattached must keep a valid cursor, +// so it sees the replacement's startup events instead of silently filtering +// them out (and must not need a reset because of the reattach). +func TestDetachRuntime_ReattachContinuesSSECursor(t *testing.T) { + t.Parallel() + + ctx := t.Context() + sm, sess := newDetachTestManager(t) + rt := &recallRuntime{fakeRuntime: &fakeRuntime{}} - assert.NotPanics(t, func() { sm.DetachRuntime("missing") }) + first := sm.AttachRuntime(ctx, sess.ID, rt, sess) + sm.RegisterEventSource(sess.ID, func(ctx context.Context, send func(any)) { + send("startup-1") + <-ctx.Done() + }) + + var cursor uint64 + require.Eventually(t, func() bool { + seq, ok := sm.LastEventSeq(sess.ID) + cursor = seq + return ok && seq > 0 + }, time.Second, 5*time.Millisecond) + + first.Detach() + require.False(t, sm.HasEventSource(sess.ID)) + + second := sm.AttachRuntime(ctx, sess.ID, rt, sess) + sm.RegisterEventSource(sess.ID, func(ctx context.Context, send func(any)) { + send("startup-2") + <-ctx.Done() + }) + require.Eventually(t, func() bool { + seq, ok := sm.LastEventSeq(sess.ID) + return ok && seq == cursor+1 + }, time.Second, 5*time.Millisecond, "a reattached session must continue the event sequence") + + // The cursor from the old log replays the replacement's event without a gap. + streamCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) + defer cancel() + var seqs []uint64 + require.True(t, sm.StreamEvents(streamCtx, sess.ID, &cursor, func(seq uint64, _ any) { + seqs = append(seqs, seq) + })) + require.Equal(t, []uint64{cursor + 1}, seqs) + second.Detach() } diff --git a/pkg/server/session_manager.go b/pkg/server/session_manager.go index abc675d6f4..c9692338b8 100644 --- a/pkg/server/session_manager.go +++ b/pkg/server/session_manager.go @@ -47,6 +47,7 @@ type activeRuntimes struct { streaming sync.Mutex // Held while a RunStream is in progress; serialises concurrent requests modelSwitch sync.Mutex // Serialises model changes with manager-owned session persistence deleting atomic.Bool // Set before deletion waits for an in-flight model transaction + closing atomic.Bool // Set when the owning view detached; the entry stays registered until the stream releases streaming (see RuntimeAttachment.Detach). } // SessionManager manages sessions for the HTTP API server and the --listen @@ -104,6 +105,14 @@ type SessionManager struct { // by eventLogsMu. deletedEventLogs map[string]struct{} + // eventLogLastSeq remembers the last sequence number each session's + // detached event log reached, so a same-ID reattachment continues the + // numbering instead of restarting at zero: a client reconnecting with its + // previous Last-Event-ID must keep a valid cursor and not silently filter + // out the replacement's startup events (#4909 review). Guarded by + // eventLogsMu; entries are dropped with the session (dropEventLog). + eventLogLastSeq map[string]uint64 + // sessionReady is closed once the first session is attached or created, // signalling that the server is ready to accept session-scoped requests. sessionReady chan struct{} @@ -180,6 +189,7 @@ func NewSessionManager(ctx context.Context, sources config.Sources, sessionStore deletedSessions: concurrent.NewMap[string, *activeRuntimes](), eventLogs: concurrent.NewMap[string, *pumpedEventLog](), deletedEventLogs: make(map[string]struct{}), + eventLogLastSeq: make(map[string]uint64), followUpInjectors: concurrent.NewMap[string, FollowUpInjector](), followUpKeys: concurrent.NewMap[string, *idempotencyCache](), pendingSafetyDefaults: concurrent.NewMap[string, struct{}](), @@ -260,10 +270,18 @@ func (sm *SessionManager) RegisterEventSource(sessionID string, src EventSource) return } var log *eventLog - if pe, ok := sm.eventLogs.Load(sessionID); ok && pe.lazy { - log = pe.log - } else { - log = newEventLog(defaultEventLogCapacity) + // Continue the sequence of the session's previous log, if it had one: a + // reattached session must not restart a reconnecting client's cursor. + startSeq := sm.eventLogLastSeq[sessionID] + if pe, ok := sm.eventLogs.Load(sessionID); ok { + if pe.lazy { + log = pe.log + } else if seq := pe.log.lastSeq(); seq > startSeq { + startSeq = seq + } + } + if log == nil { + log = newEventLogAt(defaultEventLogCapacity, startSeq) } pumpCtx, cancel := context.WithCancel(context.Background()) sm.eventLogs.Store(sessionID, &pumpedEventLog{log: log, cancel: cancel}) @@ -320,7 +338,7 @@ func (sm *SessionManager) ensureEventLog(sessionID string) *pumpedEventLog { if pe, ok := sm.eventLogs.Load(sessionID); ok { return pe } - log := newEventLog(defaultEventLogCapacity) + log := newEventLogAt(defaultEventLogCapacity, sm.eventLogLastSeq[sessionID]) pe := &pumpedEventLog{log: log, cancel: func() { log.close("session ended") }, lazy: true} sm.eventLogs.Store(sessionID, pe) return pe @@ -335,6 +353,7 @@ func (sm *SessionManager) dropEventLog(sessionID string) { sm.eventLogsMu.Lock() defer sm.eventLogsMu.Unlock() sm.deletedEventLogs[sessionID] = struct{}{} + delete(sm.eventLogLastSeq, sessionID) if pe, ok := sm.eventLogs.Load(sessionID); ok { pe.cancel() sm.eventLogs.Delete(sessionID) @@ -434,21 +453,24 @@ func (sm *SessionManager) StreamEvents(ctx context.Context, sessionID string, si // building one from agentFilename. This is what lets a single in-process // runtime be shared between the TUI and an HTTP control plane. // -// The internal cancellation signal is fired by [SessionManager.DeleteSession]; -// SSE streams and other lifetime-bound consumers use it (via -// [SessionManager.StreamEvents]) to terminate when the session is detached. +// The internal cancellation signal is fired by [SessionManager.DeleteSession] +// and by [RuntimeAttachment.Detach]; SSE streams and other lifetime-bound +// consumers use it (via [SessionManager.StreamEvents]) to terminate when the +// session is detached. // -// It returns the same lock RunSession and AddMessage/UpdateMessage already -// use (via TryLock) to detect and reject concurrent mutations while a stream -// is active. Callers that stream the attached runtime directly — bypassing -// RunSession entirely, e.g. the TUI's App.Run/Retry/RunWithMessage calling -// rt.RunStream itself — previously left that lock unheld for the whole -// attached/TUI stream, so a concurrent AddMessage/UpdateMessage or -// RunSession wrongly observed the session as idle instead of 409ing (#3590). -// The caller must hold this lock for the duration of every direct RunStream -// call (see the pkg/app WithStreamGuard option) so the busy check sees -// attached streams too. -func (sm *SessionManager) AttachRuntime(ctx context.Context, sessionID string, rt runtime.Runtime, sess *session.Session) sync.Locker { +// The returned [RuntimeAttachment] is the same lock RunSession and +// AddMessage/UpdateMessage already use (via TryLock) to detect and reject +// concurrent mutations while a stream is active. Callers that stream the +// attached runtime directly — bypassing RunSession entirely, e.g. the TUI's +// App.Run/Retry/RunWithMessage calling rt.RunStream itself — previously left +// that lock unheld for the whole attached/TUI stream, so a concurrent +// AddMessage/UpdateMessage or RunSession wrongly observed the session as idle +// instead of 409ing (#3590). The caller must hold this lock for the duration of +// every direct RunStream call (see the pkg/app WithStreamGuard option) so the +// busy check sees attached streams too. The same handle owns the detach path +// (see RuntimeAttachment.Detach), so a view closing must detach through the +// handle it attached rather than through the session ID. +func (sm *SessionManager) AttachRuntime(ctx context.Context, sessionID string, rt runtime.Runtime, sess *session.Session) *RuntimeAttachment { ctx, cancel := context.WithCancel(context.WithoutCancel(ctx)) rs := &activeRuntimes{ runtime: rt, @@ -456,44 +478,121 @@ func (sm *SessionManager) AttachRuntime(ctx context.Context, sessionID string, r cancel: cancel, session: sess, } + // Serialise the registration with Detach/finishDetach: a detach for a + // previous attachment must observe either the old entry or this one, never + // a half-swapped state where it clears the replacement's per-ID state. + sm.mux.Lock() sm.runtimeSessions.Store(sessionID, rs) + sm.mux.Unlock() sm.registerRecallHandler(sessionID, rt) sm.markReady() - return &rs.streaming + return &RuntimeAttachment{sm: sm, sessionID: sessionID, rs: rs} } -// DetachRuntime removes the runtime attached for sessionID without deleting the -// session. It is symmetric with [SessionManager.AttachRuntime]: the attach context -// is cancelled and the follow-up injector, recall handler and event log are -// unregistered, while the persisted session and its history are left alone. The -// owner of a closed view (a TUI tab) calls it instead of DeleteSession, so the -// runtime, session and context do not accumulate for the process lifetime. -func (sm *SessionManager) DetachRuntime(sessionID string) { - sessionRuntime, ok := sm.runtimeSessions.Load(sessionID) - if !ok { - return +// RuntimeAttachment is the handle returned by [SessionManager.AttachRuntime]. It +// is the [sync.Locker] callers hold for the duration of every direct RunStream +// call (#3590), and it identifies the attachment for +// [RuntimeAttachment.Detach], so a cleanup that races a same-ID replacement can +// only ever tear down the attachment it owns. +type RuntimeAttachment struct { + sm *SessionManager + sessionID string + rs *activeRuntimes +} + +// Lock implements [sync.Locker] on the attachment's stream guard. +func (a *RuntimeAttachment) Lock() { a.rs.streaming.Lock() } + +// Unlock releases the attachment's stream guard. When the attachment was +// detached while its stream was still running, this is where the manager can +// finally drop the registration: the #3590 busy guard is no longer needed once +// the stream has stopped. +func (a *RuntimeAttachment) Unlock() { + a.rs.streaming.Unlock() + a.sm.finishDetach(a.sessionID, a.rs) +} + +// Detach releases this attachment: the attach context is cancelled, the recall +// handler and the follow-up injector/key cache are unregistered, and the event +// log is torn down, while the persisted session and its history are left alone. +// It is idempotent. +// +// Detach is scoped to the attachment it is called on. A same-ID +// [SessionManager.AttachRuntime] replaces the registration, so a stale cleanup +// for the old attachment must not touch the replacement: Detach no-ops unless +// this attachment is still the one registered for the session ID. +// +// The runtimeSessions entry is not dropped until the attachment's stream has +// stopped. AddMessage and UpdateMessage take their #3590 busy decision from that +// entry, so deleting it while the old stream still holds the guard would let a +// REST edit interleave with the very stream it has to be rejected against (an +// HTTP-started stream is not stopped by canceling the attach context: RunSession +// uses the request context). Until teardown the entry is marked closing, which +// also makes the owning run reject new work (see runtimeActive). +func (a *RuntimeAttachment) Detach() { + sm := a.sm + sm.mux.Lock() + if current, ok := sm.runtimeSessions.Load(a.sessionID); !ok || current != a.rs { + sm.mux.Unlock() + return // stale cleanup: the ID now belongs to a replacement attachment. } - // Delete only our entry: a concurrent AttachRuntime may have replaced it. - if current, ok := sm.runtimeSessions.Load(sessionID); ok && current == sessionRuntime { - sm.runtimeSessions.Delete(sessionID) + if !a.rs.closing.CompareAndSwap(false, true) { + sm.mux.Unlock() + return // an earlier Detach is already waiting for the stream to stop. } - if sessionRuntime.cancel != nil { - sessionRuntime.cancel() + if a.rs.cancel != nil { + a.rs.cancel() } - if setter, ok := sessionRuntime.runtime.(recallHandlerSetter); ok { + if setter, ok := a.rs.runtime.(recallHandlerSetter); ok { setter.SetRecallHandler(nil) } - sm.followUpInjectors.Delete(sessionID) - sm.followUpKeys.Delete(sessionID) - sm.detachEventLog(sessionID) + sm.followUpInjectors.Delete(a.sessionID) + sm.followUpKeys.Delete(a.sessionID) + sm.detachEventLog(a.sessionID) + sm.mux.Unlock() + + // With no stream in progress the attachment is gone right away; otherwise the + // stream's Unlock finishes the detach once the guard is released. + sm.finishDetach(a.sessionID, a.rs) +} + +// finishDetach drops a closing attachment's runtimeSessions entry once no stream +// holds its guard anymore. The identity check keeps a late finish for a replaced +// attachment from deleting its replacement. +func (sm *SessionManager) finishDetach(sessionID string, rs *activeRuntimes) { + if !rs.closing.Load() { + return + } + if !rs.streaming.TryLock() { + return // a stream is still running; its release calls finishDetach again. + } + defer rs.streaming.Unlock() + sm.mux.Lock() + defer sm.mux.Unlock() + if current, ok := sm.runtimeSessions.Load(sessionID); ok && current == rs { + sm.runtimeSessions.Delete(sessionID) + } +} + +// unlockStream releases the attachment's stream guard and completes a pending +// detach once the stream has stopped. +func (rs *activeRuntimes) unlockStream(sm *SessionManager, sessionID string) { + rs.streaming.Unlock() + sm.finishDetach(sessionID, rs) } // detachEventLog removes the session's event log without marking the session as -// deleted, so a later AttachRuntime can register a fresh one. +// deleted, so a later AttachRuntime can register a fresh one. The log's last +// sequence number is remembered so a same-ID reattachment continues the +// numbering (see eventLogLastSeq). func (sm *SessionManager) detachEventLog(sessionID string) { sm.eventLogsMu.Lock() defer sm.eventLogsMu.Unlock() if pe, ok := sm.eventLogs.Load(sessionID); ok { + if sm.eventLogLastSeq == nil { + sm.eventLogLastSeq = make(map[string]uint64) + } + sm.eventLogLastSeq[sessionID] = pe.log.lastSeq() pe.cancel() sm.eventLogs.Delete(sessionID) } @@ -1110,6 +1209,14 @@ func (sm *SessionManager) RunSession(ctx context.Context, sessionID, agentFilena sm.registerRecallHandler(sessionID, rt) sm.markReady() } else { + if runtimeSession.closing.Load() { + // The owning view was closed and the entry is only kept until its + // stream stops (see RuntimeAttachment.Detach): do not start a new + // turn on a session that is being detached. + sm.mux.Unlock() + cancel() + return nil, ErrSessionNotRunning + } titleGen = runtimeSession.titleGen } @@ -1140,7 +1247,7 @@ func (sm *SessionManager) RunSession(ctx context.Context, sessionID, agentFilena defer runtimeSession.modelSwitch.Unlock() if !sm.runtimeActive(sessionID, runtimeSession) { - runtimeSession.streaming.Unlock() + runtimeSession.unlockStream(sm, sessionID) cancel() return nil, ErrSessionNotRunning } @@ -1155,7 +1262,7 @@ func (sm *SessionManager) RunSession(ctx context.Context, sessionID, agentFilena // runtime, persisted snapshot, live session, and rollback in one transaction. undoModelOverride, err := sm.applyRunModelOverride(ctx, runtimeSession, modelOverride) if err != nil { - runtimeSession.streaming.Unlock() + runtimeSession.unlockStream(sm, sessionID) cancel() return nil, err } @@ -1163,14 +1270,14 @@ func (sm *SessionManager) RunSession(ctx context.Context, sessionID, agentFilena if modelOverride != "" { if err := ctx.Err(); err != nil { undoModelOverride(context.WithoutCancel(ctx)) - runtimeSession.streaming.Unlock() + runtimeSession.unlockStream(sm, sessionID) cancel() return nil, err } } if err := sm.applyAgentSwitchCommands(ctx, runtimeSession.runtime, messages); err != nil { undoModelOverride(context.WithoutCancel(ctx)) - runtimeSession.streaming.Unlock() + runtimeSession.unlockStream(sm, sessionID) cancel() return nil, err } @@ -1187,7 +1294,7 @@ func (sm *SessionManager) RunSession(ctx context.Context, sessionID, agentFilena if err := sm.sessionStore.UpdateSession(ctx, sess); err != nil { undoModelOverride(context.WithoutCancel(ctx)) - runtimeSession.streaming.Unlock() + runtimeSession.unlockStream(sm, sessionID) cancel() return nil, err } @@ -1211,7 +1318,7 @@ func (sm *SessionManager) RunSession(ctx context.Context, sessionID, agentFilena // see ErrSessionBusy. defer close(streamChan) defer cancel() - defer runtimeSession.streaming.Unlock() + defer runtimeSession.unlockStream(sm, sessionID) var titleEvents <-chan runtime.Event if needsTitle { @@ -1282,7 +1389,7 @@ func sendStreamEvent(ctx context.Context, events chan<- runtime.Event, event run } func (sm *SessionManager) runtimeActive(sessionID string, rs *activeRuntimes) bool { - if rs.deleting.Load() { + if rs.deleting.Load() || rs.closing.Load() { return false } active, ok := sm.runtimeSessions.Load(sessionID) @@ -1346,7 +1453,7 @@ func (sm *SessionManager) ResumeSession(ctx context.Context, sessionID, confirma // is not actively running or if the steer buffer is full. func (sm *SessionManager) SteerSession(ctx context.Context, sessionID string, messages []api.Message) error { rt, exists := sm.runtimeSessions.Load(sessionID) - if !exists { + if !exists || rt.closing.Load() { return ErrSessionNotRunning } @@ -1384,7 +1491,7 @@ func (sm *SessionManager) SteerSession(ctx context.Context, sessionID string, me // stream; the returned boolean indicates whether a stream is active. func (sm *SessionManager) FollowUpSession(ctx context.Context, sessionID string, messages []api.Message, idempotencyKey string) (streaming, duplicate bool, err error) { rt, exists := sm.runtimeSessions.Load(sessionID) - if !exists { + if !exists || rt.closing.Load() { return false, false, ErrSessionNotRunning } @@ -1437,7 +1544,7 @@ func (sm *SessionManager) recallSession(ctx context.Context, sessionID string, m } rt, exists := sm.runtimeSessions.Load(sessionID) - if !exists { + if !exists || rt.closing.Load() { return ErrSessionNotRunning } rt.snapshotBoundary.Lock() @@ -1451,7 +1558,7 @@ func (sm *SessionManager) recallSession(ctx context.Context, sessionID string, m rt.modelSwitch.Lock() if !sm.runtimeActive(sessionID, rt) { rt.modelSwitch.Unlock() - rt.streaming.Unlock() + rt.unlockStream(sm, sessionID) runCancel() return ErrSessionNotRunning } @@ -1461,7 +1568,7 @@ func (sm *SessionManager) recallSession(ctx context.Context, sessionID string, m sess, err = sm.sessionStore.GetSession(ctx, sessionID) if err != nil { rt.modelSwitch.Unlock() - rt.streaming.Unlock() + rt.unlockStream(sm, sessionID) runCancel() return err } @@ -1469,7 +1576,7 @@ func (sm *SessionManager) recallSession(ctx context.Context, sessionID string, m sess.AddMessage(session.UserMessage(msg.Content, msg.MultiContent...)) if err := sm.sessionStore.UpdateSession(ctx, sess); err != nil { rt.modelSwitch.Unlock() - rt.streaming.Unlock() + rt.unlockStream(sm, sessionID) runCancel() return err } @@ -1484,7 +1591,7 @@ func (sm *SessionManager) recallSession(ctx context.Context, sessionID string, m sm.ensureEventLog(sessionID) _, skipMirroredElicitation := rt.runtime.(elicitationSinkMirror) go func() { - defer rt.streaming.Unlock() + defer rt.unlockStream(sm, sessionID) defer runCancel() // Merge before appending so replay sequence numbers name merged events. // The log must still get the events emitted while the run is torn From e10d48807f48aaff822233e7a2fb05eef233f2a1 Mon Sep 17 00:00:00 2001 From: PerryLink Date: Sun, 22 Nov 2026 17:15:33 +0800 Subject: [PATCH 6/7] test(server): widen the registry cleanup wait for slow CI filesystems The listener lifecycle test waited five seconds for the context-cancelled cleanup to remove the discovery record. That is enough on Linux but not on the Windows runner, where the asynchronous removal can land later under Defender/AV and a busy disk, and the test failed with "cancelling the run must remove the discovery record" after 5.05s while the cleanup itself is correct. Poll for up to thirty seconds instead; the assertion is unchanged and still fails if the record is never removed. --- cmd/root/run_listen_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/root/run_listen_test.go b/cmd/root/run_listen_test.go index 5f5e8438e6..e35a147918 100644 --- a/cmd/root/run_listen_test.go +++ b/cmd/root/run_listen_test.go @@ -157,7 +157,7 @@ func TestStartSessionCoordinatorListenUsesIsolatedRegistry(t *testing.T) { require.Eventually(t, func() bool { records, err := registry.List() return err == nil && len(records) == 0 - }, 5*time.Second, 10*time.Millisecond, "cancelling the run must remove the discovery record") + }, 30*time.Second, 25*time.Millisecond, "cancelling the run must remove the discovery record") } func TestDetachOnCloseRunsDetachOnceBeforeCleanup(t *testing.T) { From a77e4120b0629b30807e27b0691635630c0e1fa9 Mon Sep 17 00:00:00 2001 From: PerryLink Date: Tue, 24 Nov 2026 22:37:28 +0800 Subject: [PATCH 7/7] fix: finish idle-tab detach and select live attach tabs Closing a TUI tab detaches its runtime attachment, but the teardown could not finish when the streaming guard was held by a non-stream caller: GetSessionSnapshot takes the same guard for an idle snapshot and released it with a plain Unlock, so a detach that landed during the snapshot was never retried and the closed tab stayed in GET /api/sessions?active=true forever. Release the guard through unlockStream everywhere it is taken for a probe (the snapshot, the active-sessions/status probes, the follow-up probe and the AddMessage/UpdateMessage busy checks) so a pending detach is finished as soon as the last holder releases. Cover the idle detach overlapping a snapshot with a regression test. `serve mcp --attach ` could not select a tab spawned after startup: runAttach resolved the target with runregistry.Find first, and registry records only carry the run's initial session ID, so a spawned tab ID failed before the live-session resolver ran. Resolve explicit session IDs against the attached sessions of every live discovered run (exact match before a unique prefix), while keeping pid/address/latest discovery and the clear error for an explicitly selected closed tab. Add CLI lookup coverage, not only the HTTP resolver tests, and document that a spawned tab can be selected. Refs #4909 Signed-off-by: PerryLink --- cmd/root/mcp.go | 170 ++++++++++++++++++++++-- cmd/root/mcp_test.go | 210 ++++++++++++++++++++++++++++++ docs/features/cli/index.md | 2 +- pkg/mcp/attach.go | 38 ++++-- pkg/server/session_detach_test.go | 61 +++++++++ pkg/server/session_manager.go | 76 ++++++++--- 6 files changed, 512 insertions(+), 45 deletions(-) diff --git a/cmd/root/mcp.go b/cmd/root/mcp.go index 5c0d2ebe6a..65ed778e1e 100644 --- a/cmd/root/mcp.go +++ b/cmd/root/mcp.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "slices" "strconv" "strings" @@ -26,6 +27,11 @@ type mcpFlags struct { authToken string insecureNoAuth bool runConfig config.RuntimeConfig + + // runRegistry resolves --attach targets. Nil means the process-wide + // runregistry.Default(); tests inject an isolated registry so the CLI + // lookup never reads the user's real run registry. + runRegistry attachRuns } func newMCPCmd() *cobra.Command { @@ -47,7 +53,7 @@ func newMCPCmd() *cobra.Command { cmd.PersistentFlags().StringVarP(&flags.agentName, "agent", "a", "", "Name of the agent to run (all agents if not specified)") cmd.PersistentFlags().BoolVar(&flags.http, "http", false, "Use streaming HTTP transport instead of stdio") cmd.PersistentFlags().StringVarP(&flags.listenAddr, "listen", "l", "127.0.0.1:8081", "Address to listen on") - cmd.PersistentFlags().StringVar(&flags.attach, "attach", "", "Attach to a running TUI run by pid, address, or session id (or empty for the most recent)") + cmd.PersistentFlags().StringVar(&flags.attach, "attach", "", "Attach to a running TUI run by pid, address, or session id, including a tab spawned after the run started (or empty for the most recent)") cmd.PersistentFlags().Lookup("attach").NoOptDefVal = "latest" cmd.PersistentFlags().StringVar(&flags.safety, "safety", "", "Tool safety policy (strict, balanced, restricted, autonomous); only valid with --http") cmd.PersistentFlags().StringVar(&flags.authToken, "auth-token", "", "Bearer token required for HTTP MCP requests; only valid with --http") @@ -116,23 +122,165 @@ func (f *mcpFlags) runMCPCommand(cmd *cobra.Command, args []string) (commandErr } func (f *mcpFlags) runAttach(ctx context.Context) error { - target := f.attach + addr, sessionID, err := resolveAttachTarget(ctx, f.attachRuns(), f.attach) + if err != nil { + return err + } + return mcp.StartAttachStdio(ctx, addr, sessionID) +} + +// attachRuns is the subset of the run registry the --attach lookup needs. +// *runregistry.Registry is the production implementation; tests inject an +// in-memory fake so the CLI lookup never reads the user's real registry. +type attachRuns interface { + Find(target string) (runregistry.Record, error) + List() ([]runregistry.Record, error) +} + +var _ attachRuns = (*runregistry.Registry)(nil) + +// attachRuns returns the registry used to resolve --attach targets. +func (f *mcpFlags) attachRuns() attachRuns { + if f.runRegistry != nil { + return f.runRegistry + } + return runregistry.Default() +} + +// attachSession is a live tab resolved on a discovered run. +type attachSession struct { + addr string + sessionID string +} + +// resolveAttachTarget maps a --attach value to the control-plane address of the +// live run that serves it and the session ID the MCP proxy should drive. +// +// A pid, an http(s) address, or an empty/"latest" target discovers a run through +// the registry; the session is then resolved inside that run: its recorded +// initial session while that is still attached, the only live session when the +// initial tab was closed, or a clear error listing the candidates. +// +// A session ID selects that live session. A run's registry record only stores +// the session the run started with, so a TUI tab spawned after startup is not on +// any record. The lookup therefore probes every live run's attached sessions for +// the ID, which is what makes "serve mcp --attach " work. An +// explicitly selected session that is attached nowhere fails clearly instead of +// being silently redirected to another tab. +func resolveAttachTarget(ctx context.Context, runs attachRuns, target string) (addr, sessionID string, err error) { + target = strings.TrimSpace(target) if target == "latest" { target = "" } - rec, err := runregistry.Default().Find(target) + + if !attachTargetIsSessionID(target) { + rec, err := runs.Find(target) + if err != nil { + return "", "", err + } + sessionID, err := mcp.ResolveAttachSession(ctx, rec.Addr, rec.SessionID, false) + if err != nil { + return "", "", err + } + return rec.Addr, sessionID, nil + } + + // An explicit session ID is either the discovered run's recorded initial + // session (the original lookup path) or a tab spawned after startup, which + // no registry record knows about. Try the recorded run first so its "tab was + // closed" error is preserved when that is what the caller named, then fall + // back to scanning every live run for the tab. + var recordedErr error + if rec, findErr := runs.Find(target); findErr == nil { + sessionID, err := mcp.ResolveAttachSession(ctx, rec.Addr, rec.SessionID, true) + if err == nil { + return rec.Addr, sessionID, nil + } + recordedErr = err + if rec.SessionID == target { + // The caller named the run's initial session exactly and its tab is + // closed: fail instead of prefix-matching a different live tab, so an + // explicit closed selection is never silently redirected. + return "", "", err + } + } + + resolved, err := findLiveAttachSession(ctx, runs, target) if err != nil { - return err + if recordedErr != nil { + return "", "", recordedErr + } + return "", "", err } - // The discovery record keeps naming the session the run started with, but - // that tab can be closed while the run stays alive. Resolve a session that - // is actually attached before starting the proxy; an explicitly named - // closed session fails instead of being silently redirected. - sessionID, err := mcp.ResolveAttachSession(ctx, rec.Addr, rec.SessionID, attachTargetIsSessionID(target)) + return resolved.addr, resolved.sessionID, nil +} + +// findLiveAttachSession resolves an explicitly selected tab against the attached +// sessions of every discovered run. Exact IDs win over prefixes and the match +// must be unique, so a client is never silently attached to a different tab. +func findLiveAttachSession(ctx context.Context, runs attachRuns, target string) (attachSession, error) { + records, err := runs.List() if err != nil { - return err + return attachSession{}, fmt.Errorf("listing live runs: %w", err) + } + + var exact, prefix []attachSession + var live, unreachable []string + for _, rec := range records { + ids, err := mcp.LiveAttachSessions(ctx, rec.Addr) + if err != nil { + // One unreachable run must not hide a tab that lives on another; + // report it only when nothing matches anywhere. + unreachable = append(unreachable, fmt.Sprintf("%s: %v", rec.Addr, err)) + continue + } + live = append(live, ids...) + for _, id := range ids { + candidate := attachSession{addr: rec.Addr, sessionID: id} + switch { + case id == target: + exact = append(exact, candidate) + case strings.HasPrefix(id, target): + prefix = append(prefix, candidate) + } + } + } + + matches := exact + if len(matches) == 0 { + matches = prefix + } + switch len(matches) { + case 1: + return matches[0], nil + case 0: + slices.Sort(live) + msg := fmt.Sprintf("session %s is not attached to any live docker-agent run; live sessions: %s", target, formatLiveSessions(live)) + if len(unreachable) > 0 { + slices.Sort(unreachable) + msg += "; could not query runs: " + strings.Join(unreachable, ", ") + } + return attachSession{}, errors.New(msg) + default: + slices.SortFunc(matches, func(a, b attachSession) int { + if c := strings.Compare(a.sessionID, b.sessionID); c != 0 { + return c + } + return strings.Compare(a.addr, b.addr) + }) + options := make([]string, 0, len(matches)) + for _, m := range matches { + options = append(options, fmt.Sprintf("%s (run at %s)", m.sessionID, m.addr)) + } + return attachSession{}, fmt.Errorf("session %q is ambiguous: it matches %s", target, strings.Join(options, ", ")) + } +} + +func formatLiveSessions(ids []string) string { + if len(ids) == 0 { + return "none" } - return mcp.StartAttachStdio(ctx, rec.Addr, sessionID) + return strings.Join(ids, ", ") } // attachTargetIsSessionID reports whether a --attach value names a session ID diff --git a/cmd/root/mcp_test.go b/cmd/root/mcp_test.go index d96ec28b73..f064aab8b4 100644 --- a/cmd/root/mcp_test.go +++ b/cmd/root/mcp_test.go @@ -1,12 +1,22 @@ package root import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" "os" "path/filepath" + "strconv" + "strings" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/docker/docker-agent/pkg/api" + "github.com/docker/docker-agent/pkg/runregistry" ) func TestMCPHTTPSafetyAndAuthenticationFlagsRequireHTTP(t *testing.T) { @@ -96,3 +106,203 @@ func TestAttachTargetIsSessionID(t *testing.T) { assert.False(t, attachTargetIsSessionID(target), "target %q discovers a run", target) } } + +// fakeAttachRuns is an in-memory attachRuns for the CLI lookup tests: it never +// touches the user's real run registry and can advertise several runs at once. +type fakeAttachRuns struct { + records []runregistry.Record +} + +var _ attachRuns = (*fakeAttachRuns)(nil) + +func (f *fakeAttachRuns) List() ([]runregistry.Record, error) { return f.records, nil } + +// Find mimics *runregistry.Registry.Find for the target shapes the tests use. +func (f *fakeAttachRuns) Find(target string) (runregistry.Record, error) { + target = strings.TrimSpace(target) + if target == "" { + if len(f.records) == 0 { + return runregistry.Record{}, runregistry.ErrNoRun + } + latest := f.records[0] + for _, rec := range f.records[1:] { + if rec.StartedAt.After(latest.StartedAt) { + latest = rec + } + } + return latest, nil + } + if pid, err := strconv.Atoi(target); err == nil { + for _, rec := range f.records { + if rec.PID == pid { + return rec, nil + } + } + return runregistry.Record{}, fmt.Errorf("no live run with pid %d: %w", pid, runregistry.ErrNoRun) + } + if strings.HasPrefix(target, "http://") || strings.HasPrefix(target, "https://") { + want := strings.TrimRight(target, "/") + for _, rec := range f.records { + if strings.TrimRight(rec.Addr, "/") == want { + return rec, nil + } + } + return runregistry.Record{}, fmt.Errorf("no live run at %s: %w", target, runregistry.ErrNoRun) + } + for _, rec := range f.records { + if rec.SessionID == target { + return rec, nil + } + } + for _, rec := range f.records { + if strings.Contains(rec.SessionID, target) { + return rec, nil + } + } + return runregistry.Record{}, fmt.Errorf("no live run matches %q: %w", target, runregistry.ErrNoRun) +} + +// attachSessionsServer serves GET /api/sessions?active=true with the given +// session IDs, mimicking a --listen control plane with those tabs open. +func attachSessionsServer(t *testing.T, ids ...string) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/sessions" || r.URL.Query().Get("active") != "true" { + http.NotFound(w, r) + return + } + sessions := make([]api.SessionsResponse, 0, len(ids)) + for _, id := range ids { + sessions = append(sessions, api.SessionsResponse{ID: id}) + } + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(sessions); err != nil { + t.Errorf("encoding active sessions: %v", err) + } + })) + t.Cleanup(srv.Close) + return srv +} + +func attachTestRecord(addr, sessionID string) runregistry.Record { + return runregistry.Record{PID: 4242, Addr: addr, SessionID: sessionID, StartedAt: time.Now()} +} + +// TestResolveAttachTarget_SelectsSpawnedTabBySessionID is the regression test +// for selecting a TUI tab spawned after startup through serve mcp --attach: +// the run's discovery record only knows the initial session, so the CLI lookup +// must find the spawned tab among the run's live sessions instead of failing in +// the registry lookup first (#4909 review). +func TestResolveAttachTarget_SelectsSpawnedTabBySessionID(t *testing.T) { + t.Parallel() + + srv := attachSessionsServer(t, "spawned-a", "spawned-b") + runs := &fakeAttachRuns{records: []runregistry.Record{attachTestRecord(srv.URL, "initial-closed")}} + + addr, sessionID, err := resolveAttachTarget(t.Context(), runs, "spawned-b") + require.NoError(t, err, "a spawned tab must be selectable by its session ID") + assert.Equal(t, srv.URL, addr) + assert.Equal(t, "spawned-b", sessionID) +} + +func TestResolveAttachTarget_SelectsSpawnedTabByUniquePrefix(t *testing.T) { + t.Parallel() + + srv := attachSessionsServer(t, "tab-alpha", "tab-beta") + runs := &fakeAttachRuns{records: []runregistry.Record{attachTestRecord(srv.URL, "initial-closed")}} + + _, sessionID, err := resolveAttachTarget(t.Context(), runs, "tab-al") + require.NoError(t, err) + assert.Equal(t, "tab-alpha", sessionID) +} + +func TestResolveAttachTarget_ExplicitClosedTabFailsClearly(t *testing.T) { + t.Parallel() + + srv := attachSessionsServer(t, "spawned-a") + runs := &fakeAttachRuns{records: []runregistry.Record{attachTestRecord(srv.URL, "closed-initial")}} + + _, _, err := resolveAttachTarget(t.Context(), runs, "closed-initial") + require.Error(t, err) + assert.Contains(t, err.Error(), "closed-initial") + assert.Contains(t, err.Error(), "no longer attached") + assert.Contains(t, err.Error(), "spawned-a", "the error must list the live sessions") +} + +// TestResolveAttachTarget_ClosedRecordedSessionIsNeverPrefixRedirected pins the +// explicit-selection rule: naming the run's recorded initial session whose tab +// is closed fails, even when another live tab has that ID as a prefix. An +// explicitly selected closed session must never be silently swapped for a +// different tab. +func TestResolveAttachTarget_ClosedRecordedSessionIsNeverPrefixRedirected(t *testing.T) { + t.Parallel() + + srv := attachSessionsServer(t, "closed-initial-2") + runs := &fakeAttachRuns{records: []runregistry.Record{attachTestRecord(srv.URL, "closed-initial")}} + + _, _, err := resolveAttachTarget(t.Context(), runs, "closed-initial") + require.Error(t, err) + assert.Contains(t, err.Error(), "no longer attached") + assert.Contains(t, err.Error(), "closed-initial-2") +} + +func TestResolveAttachTarget_UnknownSessionFailsInsteadOfRedirecting(t *testing.T) { + t.Parallel() + + srv := attachSessionsServer(t, "spawned-a") + runs := &fakeAttachRuns{records: []runregistry.Record{attachTestRecord(srv.URL, "closed-initial")}} + + _, _, err := resolveAttachTarget(t.Context(), runs, "dead-tab") + require.Error(t, err) + assert.Contains(t, err.Error(), "dead-tab") + assert.Contains(t, err.Error(), "not attached to any live docker-agent run") + assert.Contains(t, err.Error(), "spawned-a") +} + +// TestResolveAttachTarget_SelectsTabOnSecondRun covers several --listen runs: +// a tab that registry records do not know about must be found on the run that +// actually serves it, not on whichever run the registry lookup returns first. +func TestResolveAttachTarget_SelectsTabOnSecondRun(t *testing.T) { + t.Parallel() + + first := attachSessionsServer(t, "tab-1") + second := attachSessionsServer(t, "tab-2") + runs := &fakeAttachRuns{records: []runregistry.Record{ + attachTestRecord(first.URL, "initial-1"), + attachTestRecord(second.URL, "initial-2"), + }} + + addr, sessionID, err := resolveAttachTarget(t.Context(), runs, "tab-2") + require.NoError(t, err) + assert.Equal(t, second.URL, addr) + assert.Equal(t, "tab-2", sessionID) +} + +func TestResolveAttachTarget_RunDiscoveryStillResolvesLiveTab(t *testing.T) { + t.Parallel() + + srv := attachSessionsServer(t, "spawned-a") + runs := &fakeAttachRuns{records: []runregistry.Record{attachTestRecord(srv.URL, "closed-initial")}} + + // Discovered by pid and by latest: both resolve the only live tab after + // the run's initial tab was closed. + for _, target := range []string{"4242", "", "latest"} { + addr, sessionID, err := resolveAttachTarget(t.Context(), runs, target) + require.NoError(t, err, "target %q", target) + assert.Equal(t, srv.URL, addr, "target %q", target) + assert.Equal(t, "spawned-a", sessionID, "target %q", target) + } +} + +func TestResolveAttachTarget_RunDiscoveryFailsWhenAmbiguous(t *testing.T) { + t.Parallel() + + srv := attachSessionsServer(t, "tab-a", "tab-b") + runs := &fakeAttachRuns{records: []runregistry.Record{attachTestRecord(srv.URL, "closed-initial")}} + + _, _, err := resolveAttachTarget(t.Context(), runs, "4242") + require.Error(t, err) + assert.Contains(t, err.Error(), "tab-a") + assert.Contains(t, err.Error(), "tab-b") + assert.Contains(t, err.Error(), "--attach ") +} diff --git a/docs/features/cli/index.md b/docs/features/cli/index.md index d31f6c3ee2..98cf508e50 100644 --- a/docs/features/cli/index.md +++ b/docs/features/cli/index.md @@ -364,7 +364,7 @@ $ docker agent serve mcp [flags] | `--insecure-no-auth` | `false` | Permit unauthenticated non-loopback HTTP MCP binding. | | `-l, --listen ` | `127.0.0.1:8081` | Address to listen on (only used with `--http`). | | `--mcp-keepalive ` | `0` (disabled) | Interval between MCP keep-alive pings (e.g. `30s`). Only when serving an agent over stdio — rejected with `--http` (the stateless HTTP transport, MCP `2026-07-28`, has no server-initiated ping) and with `--attach`. | -| `--attach [target]` | (none) | Attach to a running TUI run by pid, address, or session id; given without a value, selects the most recent run. | +| `--attach [target]` | (none) | Attach to a running TUI run by pid, address, or session id; a session id selects that tab, including a tab spawned after the run started. Given without a value, selects the most recent run. | All [runtime configuration flags](#runtime-configuration-flags) are also accepted. diff --git a/pkg/mcp/attach.go b/pkg/mcp/attach.go index e6c73440e5..a08f8d87b4 100644 --- a/pkg/mcp/attach.go +++ b/pkg/mcp/attach.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "log/slog" + "slices" "strings" "github.com/modelcontextprotocol/go-sdk/mcp" @@ -119,20 +120,12 @@ func AttachServer(ctx context.Context, addr, sessionID string) (*mcp.Server, err // - a fresh run-level discovery resolves the live session when there is // exactly one, and otherwise fails clearly listing the candidates. func ResolveAttachSession(ctx context.Context, addr, recorded string, explicit bool) (string, error) { - client, err := remote.NewClient(addr) + live, err := LiveAttachSessions(ctx, addr) if err != nil { - return "", fmt.Errorf("client for %s: %w", addr, err) + return "", err } - active, err := client.GetActiveSessions(ctx) - if err != nil { - return "", fmt.Errorf("listing attached sessions of %s: %w", addr, err) - } - live := make([]string, 0, len(active)) - for _, sess := range active { - if sess.ID == recorded { - return recorded, nil - } - live = append(live, sess.ID) + if slices.Contains(live, recorded) { + return recorded, nil } if explicit { @@ -148,6 +141,27 @@ func ResolveAttachSession(ctx context.Context, addr, recorded string, explicit b } } +// LiveAttachSessions returns the IDs of the sessions currently attached to the +// run serving at addr (GET /api/sessions?active=true). Unlike the run's +// discovery record, which keeps naming the session the run started with, this is +// the live view: under --listen every open TUI tab is listed, including tabs +// spawned after startup, so a caller can select one explicitly. +func LiveAttachSessions(ctx context.Context, addr string) ([]string, error) { + client, err := remote.NewClient(addr) + if err != nil { + return nil, fmt.Errorf("client for %s: %w", addr, err) + } + active, err := client.GetActiveSessions(ctx) + if err != nil { + return nil, fmt.Errorf("listing attached sessions of %s: %w", addr, err) + } + ids := make([]string, 0, len(active)) + for _, sess := range active { + ids = append(ids, sess.ID) + } + return ids, nil +} + func formatSessionIDs(ids []string) string { if len(ids) == 0 { return "none" diff --git a/pkg/server/session_detach_test.go b/pkg/server/session_detach_test.go index 879aba39ff..4c789ef5ad 100644 --- a/pkg/server/session_detach_test.go +++ b/pkg/server/session_detach_test.go @@ -2,6 +2,7 @@ package server import ( "context" + "sync" "testing" "time" @@ -122,6 +123,66 @@ func TestDetachRuntime_KeepsBusyGuardUntilStreamStops(t *testing.T) { require.NoError(t, sm.AddMessage(ctx, sess.ID, session.UserMessage("edit after close"))) } +// TestDetachRuntime_IdleSnapshotOverlapFinishesTeardown is the regression test +// for an idle tab close that overlaps a snapshot: GetSessionSnapshot takes the +// same streaming guard for a moment on an idle attachment and releases it with +// the guard's new owner-aware release. A plain Unlock there would lose the +// teardown: finishDetach's TryLock fails during the snapshot but no stream +// goroutine ever comes back to finish it, so the closed tab would stay in +// GET /api/sessions?active=true forever (#4909 review). +func TestDetachRuntime_IdleSnapshotOverlapFinishesTeardown(t *testing.T) { + t.Parallel() + + ctx := t.Context() + sm, sess := newDetachTestManager(t) + rt := &recallRuntime{fakeRuntime: &fakeRuntime{}} + attachment := sm.AttachRuntime(ctx, sess.ID, rt, sess) + sm.RegisterFollowUpInjector(sess.ID, func(context.Context, string) {}) + sm.RegisterEventSource(sess.ID, blockUntilCancelled) + + attached, ok := sm.runtimeSessions.Load(sess.ID) + require.True(t, ok) + + // Park the snapshot on its modelSwitch lock after it has taken the idle + // streaming guard, so the detach below deterministically overlaps it. + attached.modelSwitch.Lock() + var releaseOnce sync.Once + releaseSnapshot := func() { releaseOnce.Do(attached.modelSwitch.Unlock) } + t.Cleanup(releaseSnapshot) + + snapshotErr := make(chan error, 1) + go func() { + _, err := sm.GetSessionSnapshot(ctx, sess.ID) + snapshotErr <- err + }() + + // Wait until the snapshot owns the guard. A failed TryLock means someone + // holds it, and the parked snapshot is the only holder here. + require.Eventually(t, func() bool { + if attached.streaming.TryLock() { + attached.streaming.Unlock() + return false + } + return true + }, 10*time.Second, time.Millisecond, "the idle snapshot must take the streaming guard") + + // Closing the tab now cannot finish: the guard is held by the snapshot, not + // by a stream that would release it and retry the teardown. + attachment.Detach() + _, stillAttached := sm.runtimeSessions.Load(sess.ID) + require.True(t, stillAttached, "teardown must wait for the snapshot's guard") + require.Len(t, sm.GetActiveSessions(), 1, "the closing attachment stays registered while the snapshot holds its guard") + + // Releasing the snapshot guard completes the pending teardown. + releaseSnapshot() + require.NoError(t, <-snapshotErr) + require.Eventually(t, func() bool { + _, attached := sm.runtimeSessions.Load(sess.ID) + return !attached + }, 10*time.Second, time.Millisecond, "the snapshot's release must finish the pending detach") + assert.Empty(t, sm.GetActiveSessions(), "a closed idle tab must not stay in /api/sessions?active=true") +} + // TestDetachRuntime_StaleCleanupLeavesReplacementUsable covers the cleanup that // races a same-ID reattach: a detach for the old attachment must not remove the // replacement or clear its injector, key cache, event log or recall handler. diff --git a/pkg/server/session_manager.go b/pkg/server/session_manager.go index c9692338b8..2523d0707e 100644 --- a/pkg/server/session_manager.go +++ b/pkg/server/session_manager.go @@ -556,9 +556,21 @@ func (a *RuntimeAttachment) Detach() { sm.finishDetach(a.sessionID, a.rs) } -// finishDetach drops a closing attachment's runtimeSessions entry once no stream -// holds its guard anymore. The identity check keeps a late finish for a replaced -// attachment from deleting its replacement. +// finishDetach drops a closing attachment's runtimeSessions entry once its +// streaming guard is released. The identity check keeps a late finish for a +// replaced attachment from deleting its replacement. +// +// finishDetach only ever completes a teardown opportunistically and never +// blocks: it uses TryLock because the guard may be held by a live stream, and +// it is the guard's release that has to call back here. Every holder of +// rs.streaming therefore releases it through RuntimeAttachment.Unlock or +// unlockStream, which invoke finishDetach after Unlock; a plain streaming.Unlock +// would drop the guard without retrying and could leak a closed attachment in +// GET /api/sessions?active=true forever (#4909 review). This matters for +// non-stream holders too: an idle GetSessionSnapshot/GetActiveSessions/ +// GetSessionStatus probe or an AddMessage/UpdateMessage busy check acquires the +// same guard for a moment, so a detach that lands during one of those probes +// must be finished by the probe's release. func (sm *SessionManager) finishDetach(sessionID string, rs *activeRuntimes) { if !rs.closing.Load() { return @@ -640,13 +652,16 @@ func (sm *SessionManager) WaitSessionAttached(ctx context.Context, sessionID str // server. Unlike GetSessions, it never reads historical sessions from disk. func (sm *SessionManager) GetActiveSessions() []api.SessionsResponse { sessions := []api.SessionsResponse{} - sm.runtimeSessions.Range(func(_ string, rs *activeRuntimes) bool { + sm.runtimeSessions.Range(func(sessionID string, rs *activeRuntimes) bool { if rs.session == nil { return true } streaming := !rs.streaming.TryLock() if !streaming { - rs.streaming.Unlock() + // Release through unlockStream, not a plain Unlock: if the + // attachment was detached while this probe held the guard, the + // release is what finishes the teardown (see finishDetach). + rs.unlockStream(sm, sessionID) } title := rs.session.TitleSnapshot() inputTokens, outputTokens := rs.session.Usage() @@ -676,10 +691,12 @@ func (sm *SessionManager) GetSessionStatus(ctx context.Context, id string) (*api sess := rs.session // Probe streaming state: TryLock succeeds only when no RunStream is - // in progress. Immediately unlock so we don't interfere. + // in progress. Immediately unlock so we don't interfere, through + // unlockStream so a detach that landed while this probe held the guard + // is finished here (see finishDetach). streaming := !rs.streaming.TryLock() if !streaming { - rs.streaming.Unlock() + rs.unlockStream(sm, id) } title := sess.TitleSnapshot() @@ -712,7 +729,11 @@ func (sm *SessionManager) GetSessionSnapshot(ctx context.Context, id string) (*a defer rs.snapshotBoundary.Unlock() // Keep an idle turn stable until messages and cursor have been copied. if rs.streaming.TryLock() { - defer rs.streaming.Unlock() + // Release through unlockStream: this probe is not a stream (there + // is no later Unlock from a stream goroutine), so if the tab was + // detached while the snapshot held the guard, this release is the + // only chance to finish the teardown (#4909 review). + defer rs.unlockStream(sm, id) } else { streaming = true } @@ -1529,9 +1550,11 @@ func (sm *SessionManager) FollowUpSession(ctx context.Context, sessionID string, // Probe streaming state so the caller knows whether the follow-up // will be consumed by the current turn or sit idle until the next. + // unlockStream (not a plain Unlock) also completes a detach that landed + // while this probe held the guard (see finishDetach). streaming = !rt.streaming.TryLock() if !streaming { - rt.streaming.Unlock() + rt.unlockStream(sm, sessionID) } return streaming, false, nil @@ -2201,15 +2224,21 @@ func (sm *SessionManager) GetAgentToolCount(ctx context.Context, agentFilename, // store write completes would otherwise interleave with it (#3590). func (sm *SessionManager) AddMessage(ctx context.Context, sessionID string, msg *session.Message) error { sm.mux.Lock() - defer sm.mux.Unlock() rt, ok := sm.runtimeSessions.Load(sessionID) - if ok { - if !rt.streaming.TryLock() { - return ErrSessionBusy - } - defer rt.streaming.Unlock() + if ok && !rt.streaming.TryLock() { + sm.mux.Unlock() + return ErrSessionBusy } + // The guard must be released through unlockStream so a detach that landed + // while the busy check held it is finished (see finishDetach). Do it after + // sm.mux is dropped: finishDetach takes sm.mux. + defer func() { + sm.mux.Unlock() + if ok { + rt.unlockStream(sm, sessionID) + } + }() _, err := sm.sessionStore.AddMessage(ctx, sessionID, msg) if err != nil { @@ -2231,14 +2260,19 @@ func (sm *SessionManager) AddMessage(ctx context.Context, sessionID string, msg // the whole mutation instead of releasing it right after the check. func (sm *SessionManager) UpdateMessage(ctx context.Context, sessionID, msgID string, msg *session.Message) error { sm.mux.Lock() - defer sm.mux.Unlock() - if rt, ok := sm.runtimeSessions.Load(sessionID); ok { - if !rt.streaming.TryLock() { - return ErrSessionBusy - } - defer rt.streaming.Unlock() + rt, ok := sm.runtimeSessions.Load(sessionID) + if ok && !rt.streaming.TryLock() { + sm.mux.Unlock() + return ErrSessionBusy } + // See AddMessage: release the guard through unlockStream, after sm.mux. + defer func() { + sm.mux.Unlock() + if ok { + rt.unlockStream(sm, sessionID) + } + }() msgPos, err := strconv.ParseInt(msgID, 10, 64) if err != nil {