Skip to content

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

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

PerryLink wants to merge 5 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.

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