Repository navigation
fix(server): detach a closed TUI tab's runtime - #4931
Conversation
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 <novelnexusai@outlook.com>
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.
| 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) |
There was a problem hiding this comment.
[blocking] High confidence: include the initial tab in the detach lifecycle. It goes through startSessionCoordinator rather than createSessionSpawner, but this branch discards the detach callback, and the --listen branch never returns one. With --listen, open another tab and close the initial tab: its cleanup only stops toolsets and calls rt.Close() (cmd/root/backend.go:126-134), while LocalRuntime.Close does not unregister it from the manager (pkg/runtime/runtime.go:1300-1303). Consequently f.listenSM retains the initial runtime/session, its injector bound to the closed App, and its event-log entry; the closed tab also remains in GET /api/sessions. This leaves #4909's closed-tab cleanup requirement unmet. Propagate the detach callback into the initial tab's cleanup, including the --listen path, and add lifecycle regression coverage for closing initial and spawned tabs.
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 (docker#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.
|
Thanks — fixed in 30e933f.
Tests:
|
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 (docker#4909). Keep the closure, which reads cleanup when it runs, and annotate the false positive; no behavior change. Signed-off-by: PerryLink <novelnexusai@outlook.com>
|
CI update: the lint job was red on a single gocritic finding ( I kept the closure. Checked locally with golangci-lint v2.14.0 (the CI version): 0 issues; project |
aheritier
left a comment
There was a problem hiding this comment.
Reviewed all five changed files and both commits since b704b1d against #4909. The ordinary close path now releases the attachment without deleting the stored session, but detach must preserve the busy guard until the old stream stops and must not tear down a replacement attachment.
Prior threads: #4611195948 is addressed in code, although GitHub still shows the thread as unresolved and outdated. 30e933f threads detach through both coordinator branches and passes the wrapped cleanup to the initial tab; spawned tabs use the same wrapper. The follow-up commit correctly keeps the deferred closure so it calls the wrapped cleanup. The new tests cover the coordinator callback and cleanup order separately, but neither closes actual initial and spawned tabs and checks the serving manager afterward. Add that lifecycle regression coverage.
Overlap with #4930: Both open PRs deliver #4909, including initial-tab detach, recall-handler cleanup, and sequential same-ID event-log reattachment. This PR also detaches the private non-listen recall coordinator. The same-ID tests establish that a new source can be registered, not that a replacement survives overlapping cleanup or that an existing cursor can resume correctly. Land one fix for #4909, not both.
|
👋 We’ve requested changes on this PR. Once you’ve addressed the feedback, please mark it ready for review. |
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 docker#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 <novelnexusai@outlook.com>
|
Thanks — reworked in [blocking] Preserve the #3590 busy guard until the old stream stops The ID-only [blocking] Bind cleanup to the attachment that owns it The handle is the attachment identity. [blocking] Lifecycle regression coverage for real initial and spawned tabs
[should-fix] SSE cursors on same-ID reattach A log recreated for a reattached session continues the previous log's sequence [should-fix] Do not advertise the closed initial tab as a live target
[should-fix] Isolate the listener test from the real run registry
Validation, matching the CI tools: On the overlap with #4930: understood — one fix for #4909, not both. This |
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.
aheritier
left a comment
There was a problem hiding this comment.
The new lifecycle test covers closing both the initial and spawned tabs without deleting their stored sessions. The attachment handle also keeps stale cleanup from deleting a replacement in the tested interleaving. Please keep that coverage and address the remaining teardown and attach-discovery paths.
Prior threads: #4611195948 (initial tab), #4654231413 (stale cleanup), #4654231420 (SSE cursor), and #4654231431 (run registry isolation) are addressed by the changes and tests. #4654231410 is addressed for a draining stream in isolation, but concurrent snapshot reads can still prevent cleanup. #4654231427 is addressed when one other tab survives; explicit selection still needs to work when several survive. This overlaps #4930; land one fix for #4909.
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 <session-id>` 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 docker#4909 Signed-off-by: PerryLink <novelnexusai@outlook.com>
|
Thanks for the second-round review. Both blocking items are addressed in the new head (on top of [blocking] A failed You are right: I audited every holder of that guard rather than only the snapshot. New test [blocking] Correct: The CLI lookup is now Tests are at the CLI lookup layer ( Preserved coverage and validation All previous coverage passes: closing real initial and spawned tabs through On the overlap with #4930: understood. This revision does not ask for two landings; happy to follow your call and close this one if you prefer #4930. — PerryLink |
aheritier
left a comment
There was a problem hiding this comment.
Closing either the initial tab or a spawned tab now detaches it without deleting the stored session, and the new snapshot-overlap test covers the teardown case from the last review. The remaining blockers are in explicit MCP tab selection. This still overlaps #4930; only one fix for #4909 should land.
Prior threads: #4611195948 (initial-tab cleanup), #4654231410 (busy guard while the stream drains), #4654231413 (stale cleanup), #4654231420 (SSE cursor), #4654231431 (registry isolation), and #4680438994 (snapshot overlap) are addressed. #4654231427 is addressed for run-level discovery; #4680439009 is addressed in the resolver, but not yet in the command users are told to run.
|
Please mark this PR ready for review once you’ve addressed the feedback. |
serve mcp --attach advertises a session id, but pflag gives --attach a
NoOptDefVal ("latest"), so `--attach <session-id>` parses as
`--attach=latest` plus a positional argument that attach mode ignored: the
command shown in errors and docs could repeat the ambiguity error or attach
to the wrong run.
Advertise and document the `--attach=<session-id>` spelling in the ambiguity
error, docs and help, and honour the space-separated spelling by using the
single positional argument as the target. The bare --attach still selects the
most recent run.
Resolve an explicitly named session id from the live view instead of the run
record: a live exact match wins over any partial match, so a recorded initial
id that contains a spawned tab's full id cannot shadow it. A partial id
selects a live tab only when it matches one live session; several matches are
reported as ambiguous instead of silently binding the recorded initial tab.
An exactly named closed tab keeps its clear "tab was closed" error, and
pid/address/latest discovery is unchanged.
Cover both advertised spellings by executing the real command, and cover the
live exact-match and ambiguous-partial ordering with the initial and spawned
tabs both live. The existing detach, SSE and registry coverage is unchanged.
Refs docker#4909
Signed-off-by: PerryLink <novelnexusai@outlook.com>
aheritier
left a comment
There was a problem hiding this comment.
The initial and spawned tab cleanup now detaches the runtime without deleting the stored session. Please address the attach startup regression below, then mark the PR ready for review.
Prior threads: #4611195948, #4654231410, #4654231413, #4654231420, #4654231427, #4654231431, and #4680438994 are addressed. The advertised syntax and exact-match ordering now address #4680439009, #4696748727, and #4696748744; the CLI tests still need to distinguish the named tab from the default.
I found no CI-abuse concern in the reviewed changes. The diff does not modify workflows, build or test scripts, or dependency manifests.
Ctrl+Z suspends the TUI process that serves a --listen run's control plane, but the process still passes the registry's signal-zero check, so the run stays registered and its listener accepts connections without ever answering HTTP. The explicit-session lookup probed every discovered run serially, so an unrelated suspended TUI made `serve mcp --attach=<healthy-tab>` wait for the 30s request timeout on it before the healthy run was even queried; the attach proxy could not start until then. Probe all discovered runs concurrently under one short overall deadline, so a stalled endpoint only consumes that small budget and an exact match on a healthy run is selected promptly. Keep the recorded-initial-tab lookup bounded by the same deadline, and keep the exact/ambiguous/partial resolution order, the unreachable-run reporting, and pid/address/latest discovery unchanged. Cover it with a two-run regression: the suspended run is discovered first and the healthy run serves the requested session exactly; the test asserts the healthy tab is selected without waiting for the request timeout. Also strengthen the advertised-command tests: the fixture now has the live recorded initial tab next to the named spawned tab, so a command that ignores the supplied id and resolves the most recent run selects the initial tab and fails. Both explicit spellings must select the spawned tab and bare --attach must select the initial tab. Refs docker#4909 Signed-off-by: PerryLink <novelnexusai@outlook.com>
aheritier
left a comment
There was a problem hiding this comment.
Closing either the initial tab or a spawned tab now releases its attachment without deleting the saved session. The remaining blocker is that the new discovery deadline can send a partial-ID attach to the wrong tab.
Prior threads: #4712048164 is addressed for a healthy exact match, and the two-tab fixture addresses #4712048172. The earlier findings are addressed: #4611195948, #4654231410, #4654231413, #4654231420, #4654231427, #4654231431, #4680438994, #4680439009, #4696748727, and #4696748744.
The bounded --attach discovery probes every registered run concurrently under one short overall deadline, so an unrelated suspended TUI cannot delay a healthy exact match. A probe that hits the deadline leaves its run's live tabs out of the discovery view, though: a partial session ID that matches a single tab on the runs that answered can also occur on a tab of the run that did not answer, so starting the stdio proxy on it can send later MCP calls to the wrong tab. The previous code treated such a match as unique and attached. Treat a failed probe as an incomplete live view: a partial ID now selects a live tab only when every discovered run answered. If any probe failed, the lookup asks for the full session ID (--attach=<session-id>) or a retry instead of starting the proxy. A live exact match still wins regardless of unanswered runs, and the ambiguous-partial and recorded-closed-tab errors, the bounded lookup and the healthy exact-match behavior are unchanged. Add a two-run regression (one stalled endpoint, one healthy endpoint serving a tab whose ID contains the requested substring) at both the resolver and the advertised-command level: both assert the lookup fails with the full-ID/retry guidance and that the stdio proxy is not started. A stalled unrelated run still permits a healthy exact match. Refs docker#4909 Signed-off-by: PerryLink <novelnexusai@outlook.com>
aheritier
left a comment
There was a problem hiding this comment.
Looks good, no issues. Thanks for addressing the attach feedback.
In
--listenmode every TUI tab attaches its runtime to the serving session manager (AttachRuntime), but closing a tab only cancels the supervisor's session context: the session manager drops entries only on session deletion (DeleteSession→finishSessionDeletion), so per closed tab the runtime, the session, the attach context (context.WithCancel(context.WithoutCancel(ctx))), the follow-up injector closure and the recall handler all stay reachable for the process lifetime (#4909).Fix
SessionManager.DetachRuntime(sessionID), symmetric withAttachRuntime: removes the runtime entry, cancels the attach context, clears the runtime's recall handler and drops the follow-up injector, key cache and the session's event log. The persisted session is untouched, and — unlikeDeleteSession— the event log is not marked permanently deleted, so the session can be attached again (a reopened tab).Supervisor.CloseSessionalready runs off the lock, now calls it, so closing a tab releases its runtime.recallCoordinatorOptreturns the detach function alongside the app option.Tests
pkg/server/session_detach_test.go:TestDetachRuntime_CleansUpAttachedState— after attach + injector + event source: the runtime entry is gone, the attach context is cancelled, the recall handler is cleared, the injector and event log are dropped; the stored session survives, and re-attaching works (the event log is not blacklisted the way deletion blacklists it).TestDetachRuntime_UnknownSessionIsNoop.go test ./pkg/server/ ./pkg/tui/service/supervisor/ ./cmd/root/passes, andgo vet ./pkg/server/ ./cmd/root/is clean.Closes #4909