Skip to content

fix(server): detach a closed TUI tab's runtime - #4931

Open
PerryLink wants to merge 7 commits into
docker:mainfrom
PerryLink:fix/detach-closed-tui-tab-runtime
Open

PerryLink wants to merge 7 commits into
docker:mainfrom
PerryLink:fix/detach-closed-tui-tab-runtime

Conversation

@PerryLink

Copy link
Copy Markdown
Contributor

In --listen mode 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 with AttachRuntime: 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 — unlike DeleteSession — the event log is not marked permanently deleted, so the session can be attached again (a reopened tab).
  • The TUI spawner's cleanup, which Supervisor.CloseSession already runs off the lock, now calls it, so closing a tab releases its runtime. recallCoordinatorOpt returns 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, and go vet ./pkg/server/ ./cmd/root/ is clean.

Closes #4909

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>
@PerryLink
PerryLink requested a review from a team as a code owner November 14, 2026 01:54
@aheritier aheritier added area/runtime Runtime engine, agent loop execution, tool dispatch, loop detection kind/fix PR fixes a bug (maps to fix:). Use on PRs only. labels Nov 14, 2026
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.

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the attach/detach lifecycle against #4909. See inline comment.

Comment thread cmd/root/run_listen.go Outdated
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.
@PerryLink

Copy link
Copy Markdown
Contributor Author

Thanks — fixed in 30e933f.

startSessionCoordinator now returns the detach callback for both branches: the non-listen branch returns the one from recallCoordinatorOpt, and the --listen branch returns func() { sm.DetachRuntime(sess.ID) }. In run.go the initial tab's cleanup is wrapped with detachOnClose(cleanup, detachCoordinator) before it is handed to the TUI, and the deferred call now goes through a closure so it runs the wrapped cleanup too. The spawner's tabs use the same detachOnClose wrapper, so closing either kind of tab detaches before the toolsets stop and the runtime closes; the wrapper is sync.Once, so double cleanup is a no-op and detach runs before the base cleanup.

Tests:

  • TestStartSessionCoordinatorListenReturnsDetach starts the listen coordinator on a loopback listener, checks the session is in GetActiveSessions(), calls the returned detach callback and asserts the session is gone (WaitSessionAttached is false);
  • TestDetachOnCloseRunsDetachOnceBeforeCleanup pins the once/order semantics used for both the initial and the spawned tab.

go test ./cmd/root/ ./pkg/server/ passes (the existing detach tests in pkg/server/session_detach_test.go included).

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>
@PerryLink

Copy link
Copy Markdown
Contributor Author

CI update: the lint job was red on a single gocritic finding (deferUnlambda
at cmd/root/run.go:565, suggesting defer cleanup()).

I kept the closure. defer cleanup() evaluates the func value when the defer is
registered, which is before startSessionCoordinator returns the detach
callback and cleanup is wrapped with detachOnClose — the wrapper, and so the
detach, would never run for the initial tab. The line now carries a
//nolint:gocritic with that reason.

Checked locally with golangci-lint v2.14.0 (the CI version): 0 issues; project
cops, go mod tidy --diff, go build ./..., go vet ./... and
go test ./cmd/root/... ./pkg/server/... pass. No behavior change.

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pkg/server/session_manager.go Resolved
Comment thread pkg/server/session_manager.go Resolved
Comment thread pkg/server/session_manager.go Resolved
Comment thread cmd/root/run_listen.go Resolved
Comment thread cmd/root/run_listen_test.go Resolved
@aheritier
aheritier marked this pull request as draft November 22, 2026 00:14
@aheritier

Copy link
Copy Markdown
Collaborator

👋 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>
@PerryLink
PerryLink marked this pull request as ready for review November 22, 2026 02:31
@PerryLink

Copy link
Copy Markdown
Contributor Author

Thanks — reworked in fc1e6af (applies on top of e9383eb).

[blocking] Preserve the #3590 busy guard until the old stream stops

The ID-only DetachRuntime is gone. AttachRuntime now returns a
*RuntimeAttachment handle; its Detach marks the attachment closing, cancels
the attach lifetime and unregisters the per-attachment state, but keeps the
runtimeSessions entry registered so AddMessage/UpdateMessage still see the
stream's guard. The entry is dropped only when the stream releases the guard
(the handle's Unlock, or the managed-run/recall teardown path, call
finishDetach). While closing, the attachment also rejects new work
(RunSession, steer, follow-up, resume and recall return
ErrSessionNotRunning). New test
TestDetachRuntime_KeepsBusyGuardUntilStreamStops holds the old stream open
across close and asserts message edits keep returning ErrSessionBusy until it
exits, then succeed.

[blocking] Bind cleanup to the attachment that owns it

The handle is the attachment identity. Detach no-ops unless that attachment
is still the one registered for the session ID, and registration/teardown is
serialised under sm.mux, so a stale cleanup cannot remove a replacement or
drop its injector, key cache or event log, and it also cannot clear a recall
handler newly installed on a reused runtime. New tests:
TestDetachRuntime_StaleCleanupLeavesReplacementUsable (same runtime instance
reused) and TestDetachRuntime_PendingTeardownDoesNotTearDownReplacement (the
old detach is pending while a replacement attaches, then the old stream ends).

[blocking] Lifecycle regression coverage for real initial and spawned tabs

TestInitialAndSpawnedTabCloseDetachFromListenManager starts the real
startSessionCoordinator (listen), wires the initial tab exactly as
runOrExec does, creates a spawned tab with the real createSessionSpawner,
and closes both through supervisor.CloseSession. After each close it checks
the serving manager: only the closed tab leaves GetActiveSessions, the other
stays attached, and the persisted session survives the initial tab's close;
closing the last tab leaves the manager empty.

[should-fix] SSE cursors on same-ID reattach

A log recreated for a reattached session continues the previous log's sequence
number (remembered per session ID), so a subscriber that reconnects with its
old Last-Event-ID replays the replacement's events instead of filtering them
out. A cursor above everything the current log has produced is still reported
as a gap reset, including when the new log's backlog is empty. New tests:
TestEventLog_ContinuityAcrossReattach,
TestEventLog_CursorAboveLastSeqSignalsReset,
TestDetachRuntime_ReattachContinuesSSECursor.

[should-fix] Do not advertise the closed initial tab as a live target

serve mcp --attach now resolves the run's discovery record against
GET /api/sessions?active=true before starting the proxy
(mcp.ResolveAttachSession): the recorded session is used while it is still
attached; an explicitly selected session that is no longer attached fails with
a clear error listing the live sessions and is never silently redirected; a
fresh run-level discovery resolves the only live session, or fails with the
candidates when ambiguous. Tests in pkg/mcp/attach_test.go.

[should-fix] Isolate the listener test from the real run registry

runExecFlags has a runRegistry test seam (discoveryRegistry());
TestStartSessionCoordinatorListenUsesIsolatedRegistry injects a temporary
registry, asserts the discovery record lands there, and that cancelling the run
context removes it. The lifecycle tests use the same seam, so no test
advertises a fake live run in the user's registry.

Validation, matching the CI tools: go build ./..., go vet,
go test ./pkg/server/ ./cmd/root/ ./pkg/mcp/ ./pkg/runtime/remote/ (plus
pkg/app and the supervisor package), go test -race on the server detach and
event-log tests, go mod tidy --diff, project cops (go run ./lint .:
2906 files, no offenses) and golangci-lint v2.14.0 (0 issues) all pass locally.

On the overlap with #4930: understood — one fix for #4909, not both. This
revision does not ask for two landings; happy to follow your call on which PR
to keep and to close this one if you prefer #4930.

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
aheritier self-requested a review November 24, 2026 11:47

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pkg/server/session_manager.go Resolved
Comment thread pkg/mcp/attach.go Resolved
@aheritier
aheritier marked this pull request as draft November 24, 2026 13:10
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>
@PerryLink
PerryLink marked this pull request as ready for review November 24, 2026 14:37
@PerryLink

Copy link
Copy Markdown
Contributor Author

Thanks for the second-round review. Both blocking items are addressed in the new head (on top of e10d4880), and all the existing lifecycle/identity/SSE/registry coverage is kept.

[blocking] A failed TryLock does not mean a stream will finish the detach (pkg/server/session_manager.go:566)

You are right: GetSessionSnapshot takes the same guard on an idle attachment and released it with a plain Unlock, so an idle tab close that overlaps a snapshot was never retried and could stay in GET /api/sessions?active=true forever.

I audited every holder of that guard rather than only the snapshot. GetActiveSessions, GetSessionStatus, the FollowUpSession probe and the AddMessage/UpdateMessage busy checks had the same plain-release pattern. They now release through unlockStream, which unlocks and then calls finishDetach, so a detach that lands during any non-stream probe is finished by that probe release. AddMessage/UpdateMessage needed a small restructure to drop sm.mux before releasing the guard, because finishDetach takes sm.mux. The invariant is documented on finishDetach: every holder of the guard releases through RuntimeAttachment.Unlock or unlockStream.

New test TestDetachRuntime_IdleSnapshotOverlapFinishesTeardown parks an idle snapshot on modelSwitch after it has taken the streaming guard, detaches while it is parked, asserts the closing attachment is still registered (there is no stream to release the guard), then releases the snapshot and asserts both runtimeSessions and GET /api/sessions?active=true are empty. I confirmed the test fails with the old plain Unlock and passes with the fix.

[blocking] serve mcp --attach <session-id> cannot select a spawned tab (pkg/mcp/attach.go:147)

Correct: runAttach called runregistry.Find first, and a discovery record only carries the initial session ID, so a spawned tab ID failed before ResolveAttachSession ran.

The CLI lookup is now resolveAttachTarget (cmd/root/mcp.go). pid/address/latest still discover a run through the registry and resolve the live session inside it, exactly as before. An explicit session ID is first resolved against the run the record names (so the clear tab-was-closed error is preserved), and then, if the record cannot serve it, against the attached sessions of every live discovered run: exact match first, then a unique prefix. serve mcp --attach <spawned-tab-id> therefore selects exactly one live tab, including when several tabs survive. An explicitly selected closed session still fails clearly and is never silently redirected, and naming the recorded initial session exactly never prefix-matches a different live tab (that rule has its own test). The live-session probe is exposed as mcp.LiveAttachSessions and reused by the resolver.

Tests are at the CLI lookup layer (cmd/root/mcp_test.go), not only the HTTP resolver: spawned tab by exact ID, spawned tab by unique prefix, a tab on the second of two runs, explicit closed tab error, no-prefix-redirect for an exactly named closed session, unknown session, and pid/latest run discovery with a live tab plus the ambiguous discovery error. The existing pkg/mcp resolver tests still pass. I also updated the --attach help text and docs/features/cli/index.md to say that a spawned tab session id is selectable.

Preserved coverage and validation

All previous coverage passes: closing real initial and spawned tabs through supervisor.CloseSession, stale cleanup vs. a replacement attachment, pending teardown, the #3590 busy guard while a stream drains, SSE cursor continuity/gap, the HTTP attach resolver, and the isolated run-registry listener tests. Validation matches CI: go build ./..., go vet ./..., gofmt/golangci-lint fmt clean, targeted go test (pkg/server, cmd/root, pkg/mcp, pkg/runtime/remote, the supervisor package and pkg/app), go test -race on the detach/event-log tests, golangci-lint v2.14.0 (0 issues), project cops (go run ./lint .: 2906 files, no offenses) and go mod tidy --diff all pass. Full go test ./... is otherwise green; the only failures are in untouched packages and environmental: pkg/runtime TestDoCompactAfterHookFires needs jq (not installed on this machine), and one pkg/tools/mcp/oauthflow OAuth test was flaky in the full run and passes on rerun.

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/runtime Runtime engine, agent loop execution, tool dispatch, loop detection kind/fix PR fixes a bug (maps to fix:). Use on PRs only.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Closing a TUI tab leaks its runtime, session and context in --listen mode

2 participants