Skip to content

fix(chat): roll back the dock tab a failed run-in-terminal dispatch minted - #10859

Merged
iamwhatever merged 1 commit into
mainfrom
fix/10822-run-in-terminal-tab-leak
Sep 15, 2026
Merged

iamwhatever merged 1 commit into
mainfrom
fix/10822-run-in-terminal-tab-leak

Conversation

@patrigao

@patrigao patrigao commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Clicking Run in terminal on a shell code block, while dispatches were failing, filled the bottom dock with terminal tabs that never ran anything. The tabs persist in localStorage, so they come back on every reload. At 8 tabs (MAX_TERMINALS) the store refuses new tabs, and from then on every Run-in-terminal click fails silently — a 13 px icon flashes for 2 seconds and nothing explains why. A user reported this as "run in terminal opens multiple terminals but doesn't run anything" (#10822; observed live with five leaked tabs, three of them holding dead shells).

Why it matters

Two known conditions make failed dispatches routine: a second dashboard window fighting over the PTY sockets (#7638), and a bash profile that assigns PROMPT_COMMAND, which means the ready frame never arrives at all (#7657). Anyone in either state ratchets toward the cap, and once there the feature is dead until they hand-close the zombie tabs.

What changed (motivation → approach → change)

A dispatch mints a dock tab, then waits for the PTY's ready frame. On the never-ready path the old code reported failure and walked away. The tab it had just created stayed in the persisted store forever.

The fix makes the dispatch clean up after itself, but only after it learns whether the shell is actually dead. A missing ready frame does not prove that: the frame rides a PROMPT_COMMAND hook, and a profile that assigns that variable drops the hook while the shell runs fine. So at the deadline the dispatch reports failure for the button, then asks GET /api/terminal/sessions — which already reports each session's alive from the real child-process state — whether this shell is still running. A running shell keeps its tab and its scrollback. A dead or absent one is rolled back with the same teardown, in the same order, as the tab-close paths: delete the backend PTY (best-effort, the orphan reaper backstops it), drop the local socket and cached xterm, remove the store entry. If the probe itself cannot answer, the tab stays, because removing a possibly-live shell is irreversible while a leftover tab is user-closable.

Rollback also runs only while the dispatch still owns the tab, checked before the probe and again after it. A tab the user closed is left alone (its close path already deleted the PTY, and a second DELETE would raise a false "close failed" notice), and a panel popped out to its own window is left alone (the popout owns the live session). The deadline keeps its value and moves from a magic 6000 to a shared constant, RUN_IN_TERMINAL_READY_DEADLINE_MS in website/src/utils/fenceShell.ts; the code-block button's fallback flash derives from it (RUN_IN_TERMINAL_RESULT_FALLBACK_MS) so the button can never declare failure before the dispatcher has ruled. Waiting longer was considered and rejected: reaching the deadline now only asks whether the shell is alive, and a slow-but-alive one keeps its tab on that answer, so a longer wait would buy nothing but dead air.

Four details of the probe itself. It goes through the query cache under a ['terminal-sessions'] key, so two dispatches that reach their deadlines together share one request instead of each issuing an uncached fetch; the reuse window is far shorter than the deadline, so no probe can read a snapshot taken before its own session existed. A session the probe does not list is already gone from the backend registry, so its rollback skips the DELETE that would 404 and raise a spurious close failure. A probe that cannot answer reports itself to the user through ErrorNotice (showActionError), because a kept tab whose command never ran is otherwise unexplained -- and so does a rollback, because closing a tab the user watched open is the ROUTINE outcome here and must not be the quiet one.

And absent is not the same as gone. The backend reserves a session's slot with a null placeholder from ws.prepare() until the shell is spawned, and GET /api/terminal/sessions skips placeholders (if sess is None: continue), so a shell still opening reads exactly like one that never existed. Rolling that back would pull the tab out from under a shell about to come up and leave it orphaned until the reaper collects it. The dispatch therefore CONFIRMS an absent session: one uncached re-probe after a bounded grace (RUN_IN_TERMINAL_OPENING_GRACE_MS), and only absent twice counts as gone.

flowchart LR
  subgraph Before
    A1[dispatch mints tab]:::ctx --> B1[wait 6 s for ready]:::ctx --> C1[report failure]:::ctx --> D1[tab persists forever]:::removed
  end
  subgraph After
    A2[dispatch mints tab]:::ctx --> B2[wait 6 s for ready]:::ctx --> C2{still owns tab?}:::added
    C2 -->|no: closed or popped out| F2[report failure]:::ctx
    C2 -->|yes| G2{shell still alive?}:::added
    G2 -->|yes| H2[keep tab and scrollback]:::added --> F2
    G2 -->|cannot tell| I2[keep tab + ErrorNotice]:::added --> F2
    G2 -->|no or absent| J2{absent? confirm once}:::added
    J2 -->|now listed alive| H2
    J2 -->|dead or still absent| E2[delete PTY, remove tab]:::added --> F2
  end
  classDef added fill:#DCFCE7,stroke:#16A34A,color:#14532D,stroke-width:2px
  classDef changed fill:#FEF3C7,stroke:#D97706,color:#78350F,stroke-width:2px
  classDef removed fill:#FEE2E2,stroke:#DC2626,color:#7F1D1D,stroke-dasharray:4 3
  classDef ctx fill:#E0F2FE,stroke:#0284C7,color:#0C4A6E
Loading

🟩 added · 🟨 changed · 🟥 removed · 🟦 unchanged

A failed dispatch removes the tab it created only when the shell behind it is really gone; a live shell, or one someone else took over, is left alone.

Tests

  • website/src/test/ChatPageMoreCoverage.test.tsx — nine cases on the dispatch: rollback when the probe reports a dead shell (tab removed, one DELETE /api/terminal/sessions/:id, ok:false); rollback of an absent session locally with NO DELETE, carrying the rollback notice — proven red-first against an unconditional delete and against a silent rollback; a session that is merely OPENING (absent on the first probe, listed alive on the confirm probe) keeps its tab — proven red-first against dropping the confirm probe; keep when the probe reports a live shell with no ready frame (tab and local connection stay, no DELETE, ok:false) — proven red-first against unconditional rollback — carrying the notice that names the live shell, proven red-first against a silent keep; keep plus a surfaced action-error when the probe fails — proven red-first against a swallowed failure, and pinned to keep the probe's own transport error OUT of that copy, proven red-first against interpolating it; one shared probe request when two dispatches deadline together — proven red-first against a zero-length reuse window; keep when ready arrives and the command is sent (ok:true); leave-alone when the user closed the tab or popped the panel out before ready.
  • website/src/i18n/locales/* — both messages in the English source, all eleven translations, and the regenerated pseudolocale; the eleven per-locale style suites under website/src/i18n/style/ pass, including the zh-CN full-width-punctuation rule. This round also repairs three misspellings of the Korean word for terminal that earlier rounds of this PR introduced — the file spells it correctly 50 times now, 46 of them pre-existing.
  • website/src/test/fenceShell.test.ts — pins RUN_IN_TERMINAL_RESULT_FALLBACK_MS > RUN_IN_TERMINAL_READY_DEADLINE_MS.
  • website/src/test/RunInTerminalBtn.test.tsx — the button timeout test advances by the shared constant.
  • .github/coverage-baselines/frontend.txt — drops the src/hooks/useBottomTerminal.ts entry, which now measures above the 80% floor.

Manual verification

N/A — unit coverage sufficient: every dispatch outcome is pinned against the real store, registry, and handler, with the sessions probe stubbed at fetch; no rendering changed.

Screenshots / video

Why no screenshot: failure-path tab lifecycle only. The user-visible additions render through the existing ErrorNotice banner with its existing styling — a new message string in an already-shipped surface, no new component, layout, or theme delta — and both the surfacing and the string are pinned by unit tests.

Accepted residual

A PROMPT_COMMAND-assigning profile (#7657) still leaves a live shell whose ready frame never arrives: the probe answers alive === true, so the tab is kept and the command is never sent. That is deliberate and is the safe half of the trade — the alternative destroys working shells — but it is a residual, not a fix. Repairing the readiness signal itself belongs to the terminal transport, which is #7638's parked RFC territory, and is out of scope here.

What this branch no longer does is stay quiet about it. For such a profile this is the routine outcome, not an edge, so a 2s button flash cannot carry it: the kept tab now says the command was not sent and that its shell is running, which also tells the user the shell is theirs to run the command in.

Scope boundary — what this does NOT fix

This fixes the in-page accumulation path only: the dispatch that minted a tab rolls it back, so a click that fails stops leaving a tab behind. Two sibling paths stay open and are tracked in #10977 rather than implied here:

  • Hydrate-time reconciliation. The rollback exists only while the page that started the dispatch lives to see its own deadline. loadPersisted (website/src/hooks/useBottomTerminal.ts:77) restores persisted tabs without asking the backend which sessions still exist, so tabs leaked before this ships — or by a page closed mid-dispatch — return as dead tabs and keep consuming the cap.
  • The silent tab cap. Reaching the cap still refuses a dispatch without saying so. Open PR feat: scope terminal panels to chat sessions #10120 adds a visible notice in the file it rewrites, so that half may land there.
  • An authoritative absence signal. GET /api/terminal/sessions omits the None placeholder a session holds between ws.prepare() and its shell spawn, so absence alone cannot tell opening from gone. The opening grace plus its confirm probe exist only to cover that gap; listing placeholders as opening: true would make absence authoritative and delete both. That is a backend change inside Terminal output can be delayed when multiple windows attach to one PTY #7638's parked surface, so it is tracked in Reconcile persisted terminal dock tabs with the backend at hydrate time #10977, not taken here.

Related Issues

Fixes #10822

Follow-up: #10977 (hydrate-time reconciliation + the silent tab cap)
Context: #7638 (socket takeover, parked RFC #7649), #7657 (PROMPT_COMMAND-replacing profiles)

Pattern harvest

Rule candidate: review-prompt
Pattern: "an async dispatch that creates a persistent resource must roll it back on its failure path, gated on still owning the resource AND on authoritative evidence the resource is dead — a missing signal is not proof of death"

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable) — N/A, no documented contract references the old deadlines
  • No secrets, credentials, or internal references in the diff

@patrigao
patrigao requested review from a team and pepmach September 14, 2026 20:22
@patrigao

Copy link
Copy Markdown
Contributor Author

Intent: A failed Run-in-terminal dispatch must not leave anything behind — the tab it minted (and its PTY) is rolled back unless someone else has taken ownership of it, so retries can never ratchet the dock toward the tab cap.
Not a goal: Terminal session ownership/transport semantics (#7638 / RFC #7649), reusing existing tabs for dispatches, or changing what happens after a command successfully reaches a live shell.

@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Sep 14, 2026
@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Fable 5) — ✅ PASS

UX-level review of a73362b3f645ec620b1228debd16dc37d514d891 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

UX-Verdict: PASS

Verify once live that the rollback notice lands as the dock tab disappears — this failure path shipped with unit coverage only, no manual run.

[UX-REVIEWED] a73362b

@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5) — ✅ PASS

Design-level review of a73362b3f645ec620b1228debd16dc37d514d891 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: PASS

Confirm follow-up #10977 is actually filed — existing leaked tabs (including #10822's reporter's five) get no relief until hydrate-time reconciliation lands.

[DESIGN-REVIEWED] a73362b

@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5) — ✅ PASS

Premise-level review of a73362b3f645ec620b1228debd16dc37d514d891 — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: PASS

Verify the 2 s RUN_IN_TERMINAL_OPENING_GRACE_MS outlives a slow shell spawn — absent-twice on a loaded host would roll back a tab mid-open.

What this change ships

Inventory (10 items) — 10 justified

Intent: FIX — stop failed Run-in-terminal dispatches from permanently leaking dock tabs that ratchet toward the 8-tab cap (#10822).

  1. A failed dispatch now removes the dead tab and its PTY instead of leaking it forever — justified
  2. A live-but-never-ready shell keeps its tab, with a notice explaining why — justified
  3. A rolled-back tab announces itself instead of vanishing silently — justified
  4. A failed liveness probe keeps the tab and tells the user — justified
  5. An absent session is confirmed gone by one re-probe before rollback (backend placeholder skip verified at terminal.py:2418) — justified
  6. A tab the user closed or popped out is left alone — justified
  7. Deadline and button fallback share named constants; both values unchanged (6 s, 8 s) — justified
  8. New hasTab store reader — justified (3 counted consumers in ChatPage; no existing exported equivalent)
  9. Concurrent deadlines share one probe request via the query cache — justified
  10. Coverage baseline entry for useBottomTerminal.ts dropped (now above floor) — justified

[FIRST-PRINCIPLES-REVIEWED] a73362b

@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — ✅ no blocking findings

GPT 5.6 completed its review of a73362b3f645ec620b1228debd16dc37d514d891 and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] a73362b

False positive or not applicable? A repository writer can comment:
/ai-review override gpt a73362b3f645ec620b1228debd16dc37d514d891: <one-sentence reason>

@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Opus 4.8 Review — ✅ no blocking findings

Reviewed a73362b3f645ec620b1228debd16dc37d514d891 — this comment is updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] a73362b

Verdict parsed from the review's SHA-scoped output markers for commit a73362b3f645ec620b1228debd16dc37d514d891.

False positive or not applicable? A repository writer can comment:
/ai-review override fable a73362b3f645ec620b1228debd16dc37d514d891: <one-sentence reason>

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention labels Sep 14, 2026
@patrigao
patrigao force-pushed the fix/10822-run-in-terminal-tab-leak branch from 59ba2aa to 827351c Compare September 15, 2026 02:29
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 15, 2026
@patrigao
patrigao force-pushed the fix/10822-run-in-terminal-tab-leak branch from 827351c to 8c1ca7e Compare September 15, 2026 03:30
@patrigao

patrigao commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author
  • Probe failures bypass the required error surface (span=fd89d98b48d2) -- fixed on head 8c1ca7e66.

The caught probe failure now reports through showActionError, which renders the action-error ErrorNotice with askAgent on -- the surface errors-use-error-notice names. The console.warn and its eslint-disable are gone.
The message is a new key in the English source with all eleven translations and a regenerated pseudolocale, so the surface is not English-only.
Pinned by a case asserting the banner carries both the explanation and the underlying reason; proven red-first by deleting the call, which fails exactly that case.

self-added: yes -- the probe and its catch arrived with this PR.
mechanism: showActionError(i18nT('pages.chatPage.run_in_terminal_liveness_probe_failed_error', { error: errMessage(error) }))

@patrigao

patrigao commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author
  • Concurrent deadlines make duplicate uncached probe requests (span=083e7a6856df) -- fixed on head 8c1ca7e66.

The probe now goes through the query cache under a ['terminal-sessions'] key, exactly as suggested, so two dispatches that reach their deadlines together share one request.
One deliberate departure: the reuse window is 1 s, far below the deadline rather than equal to it. A window as long as the deadline admits a snapshot taken before a younger session existed, which would read as absent and roll back a live tab; at 1 s a session young enough to be missing cannot have reached its own deadline yet.
Pinned by a case dispatching twice in one tick and asserting exactly one probe request; proven red-first against a zero-length window.

self-added: yes -- the probe arrived with this PR.
mechanism: queryClient.fetchQuery({ queryKey: ['terminal-sessions'], staleTime: 1_000 })

@patrigao

patrigao commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author
  • Absent-session rollback issues a DELETE the backend 404s (span=6fc9b933adef) -- fixed on head 8c1ca7e66.

Correct, and the consequence you name is the one this PR exists to avoid: a spurious close failure for a session that needs no closing.
A session the probe did not list is already gone from the backend registry, so the rollback now skips the mutation entirely and still tears down locally -- dispose the cached connection, remove the store entry.
The existing case flipped from asserting the DELETE to asserting its absence, and is proven red-first against the unconditional mutate.

self-added: yes -- the absent-session branch arrived with this PR.
mechanism: if (session) deleteTerminalSessionRef.current.mutate(sessionId)

@patrigao

patrigao commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author
  • Dead air after confirming, with no pending state (span=3ac5db8fc1a9) -- fixed on head 8c1ca7e66.

Fixed by subtraction rather than by adding a pending state: the deadline widening is reverted, so the button's fallback returns to the 8 s it had before this PR and the wait is no longer lengthened at all.
The remaining absence of a pending state on the button predates this PR and is untouched by it, so the retry-and-re-mint loop you describe is no worse than mainline. Worth its own change; not one this diff creates.

self-added: yes -- the 17 s figure was.
mechanism: RUN_IN_TERMINAL_READY_DEADLINE_MS back to 6_000, so RUN_IN_TERMINAL_RESULT_FALLBACK_MS derives as 8_000.

@patrigao

patrigao commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author
  • Silent rollback closes a watched tab and deletes its scrollback (span=7c16087e434b) -- answered on head 8c1ca7e66.

Kept as designed, for three reasons. The rollback fires only when the probe reports the shell not alive, or absent -- never on an ambiguous answer -- so what closes is a dead shell whose scrollback is at most startup output.
The failure is already surfaced: the button reports the dispatch failed at the deadline, and the ambiguous case now raises an ErrorNotice (span fd89d98b48d2). A third surface for the same failure would duplicate it.
And keeping the dead tab is precisely the leak #10822 reports -- the harm this PR removes. If an explicit "the terminal was closed" notice is still wanted, it is a small follow-up on top of this mechanism rather than a change to it.

self-added: yes -- the rollback arrived with this PR.
mechanism: unchanged: teardown remains gated behind session?.alive === true returning early.

@patrigao

patrigao commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author
  • Only one of the two named failure states is cleared (span=ac6e2ebf5063) -- answered on head 8c1ca7e66.

Your stated clearing condition is now met by the second option: the PR body carries an ## Accepted residual section.
It states plainly that a PROMPT_COMMAND-assigning profile (#7657) leaves a live shell whose ready frame never arrives, that the probe therefore keeps the tab and the command is never sent, and that this is the deliberate safe half of the trade because the alternative destroys working shells.
It also names why the residual is not closed here: repairing the readiness signal is transport work inside #7638's parked RFC scope.

self-added: no -- the readiness path predates this PR.
mechanism: PR body ## Accepted residual; no code change.

@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Sep 15, 2026
@patrigao

Copy link
Copy Markdown
Contributor Author
  • The routine PROMPT_COMMAND outcome carries only a 2s button flash (span=9e8840ca3565) -- fixed on head cecef5dff.

Legitimate, and the sharpest item in the round. The alive === true branch was the one outcome with no notice, and for a profile that assigns PROMPT_COMMAND (#7657) it is not an edge case -- it is what every click does. A 13px flash for 2s cannot carry "your command never ran".

Fixed: that branch now surfaces an ErrorNotice saying the command was not sent and that the shell is running, so the user also learns the tab is theirs to run the command in. Pinned by a test that asserts the notice text on the live-shell path, proven red-first by deleting the showActionError call (1 failure, restore byte-identical).

self-added: yes -- the finding lands in code this PR introduces.
mechanism: notice on the alive-keep branch of the deadline probe

@patrigao

Copy link
Copy Markdown
Contributor Author
  • The probe's own transport error is interpolated into the dispatch copy (span=9c931e237707) -- fixed on head cecef5dff.

Legitimate. Failed to list terminal sessions (500) is a diagnostic about a request the user never made, shown in copy about their command.

Fixed: the string no longer interpolates anything -- it reads "The command wasn't sent to the new terminal. Its shell may still be running, so the tab was left open." The transport error is not discarded, it goes to console.warn where whoever debugs the probe looks (the repo's eslint-disable-next-line no-console -- <reason> convention, alongside the user surface rather than instead of it, so the blocking errors-use-error-notice rule stays satisfied). Pinned by asserting the notice does NOT contain the transport error, proven red-first by re-interpolating it (1 failure, restore byte-identical).

self-added: yes -- the finding lands in code this PR introduces.
mechanism: user copy stripped of the probe transport error, diagnostic moved to the console

@patrigao

Copy link
Copy Markdown
Contributor Author
  • The alive-keep branch contradicts the PR's own no-quiet-routine-outcome rule (span=db1d1402cbed) -- fixed on head cecef5dff.

Legitimate, and correctly identified as the PR contradicting its own stated rule: round 5 added a notice to the rollback path on the grounds that a routine outcome must not be silent, then left the branch that is routine for a PROMPT_COMMAND profile silent.

Fixed by the stated clearing condition -- the alive-keep branch surfaces a notice (command not sent, shell left running) rather than a comment explaining the silence. The cap-path risk this item pairs with is now stated in the PR body's scope boundary and tracked in #10977 rather than accepted quietly.

self-added: yes -- the finding lands in code this PR introduces.
mechanism: notice on the alive-keep branch of the deadline probe

@patrigao

Copy link
Copy Markdown
Contributor Author
  • Send the command into the probe-confirmed-alive shell instead of abandoning it (span=fed2674f97c5) -- accepted-and-deferred on head cecef5dff.

Right that this is the cap-pressure relief with the best shape, and right that it is a follow-up rather than this PR: filed as item 3 of #10977.

Deferred on a correctness ground rather than effort. alive: true proves the child process runs; it does not prove the shell has finished its profile -- that is exactly what the missing ready frame would have proven. So a sendToTerminalSession on this path can interleave with profile output or be swallowed, turning a visible dead end into a silent wrong result. Establishing readiness without the hook is the readiness contract itself, which is #7638's parked RFC (#7649) territory. This PR's scope stays "do not leak a tab", and the user now gets the shell plus a notice telling them it is usable.

self-added: yes -- the finding lands in code this PR introduces.
mechanism: deferred to #10977 with the reason stated

@patrigao

Copy link
Copy Markdown
Contributor Author
  • The fix is in-page only -- the persisted store is never reconciled with the backend (span=fe8200067a2d) -- accepted-scope-stated on head cecef5dff.

Correct on the mechanism and I am not arguing it: the rollback lives on the dispatch's own deadline, so it cannot see a tab leaked by a page that is already gone. loadPersisted (website/src/hooks/useBottomTerminal.ts:77) restores persisted tabs without asking the backend which sessions exist, so pre-existing leaked tabs return and still consume the cap. The #10822 reporter saw precisely that -- 5 restored tabs, 3 shells already dead.

Answered by both halves of the stated clearing condition rather than one: #10977 tracks hydrate-time reconciliation and the at-cap notice (noting that open PR #10120 already adds a visible cap notice in the file it rewrites), and the PR body gained a Scope boundary -- what this does NOT fix section naming the in-page accumulation path as the fix's limit and both siblings as open.

Not fixed here on purpose: reconciling at hydrate means a probe on a path with no dispatch to own it, in a file PR #10120 is concurrently rewriting (+491/-198). Landing that in this PR would collide with an in-review rewrite and widen a leak fix into a store-lifecycle change.

self-added: yes -- the finding lands in code this PR introduces.
mechanism: deferred to #10977 with the reason stated

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 15, 2026
…inted

A run-in-terminal dispatch mints a persisted dock terminal tab, then waits
for the PTY's ready frame. When ready never arrived, the dispatch reported
failure but left the tab behind: every retry ratcheted the persisted store
toward MAX_TERMINALS, where addTab refuses and every later dispatch
silently fails (#10822).

The dispatch now cleans up after itself on the never-ready path, but only
after asking the terminal sessions route whether the shell is still
running: a shell profile can replace the readiness hook on a live shell, so
a missing ready frame alone does not prove the dispatch died. A running
shell keeps its tab and scrollback; a dead or absent one is torn down with
the same teardown and order as the tab-close paths. The 6 s deadline
becomes a shared 15 s constant tolerant of slow login-shell profile chains,
and the code-block button's fallback flash is coupled strictly after it.

Fixes #10822
@patrigao
patrigao force-pushed the fix/10822-run-in-terminal-tab-leak branch from cecef5d to a73362b Compare September 15, 2026 05:36
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 15, 2026
@patrigao

Copy link
Copy Markdown
Contributor Author
  • fixed span=1d37066bd099 - the rolled-back notice renamed the terminal mid-sentence

Legitimate as written. "...so the terminal it opened was closed." leaves it without a
clean antecedent - grammatically the nearest candidate is the command - and it renames the
same object the sentence already introduced as "the new terminal". A user reads one terminal
being closed on behalf of another.

Adopted the lane's suggested English verbatim: "The command wasn't sent to the new terminal,
so that terminal was closed."
Shape-matched across all eleven translations (the relative
clause "opened for it" is gone in each; bn hi ja ko pt ru zh-CN de es fr it)
and the en-XA pseudolocale regenerated from source.

The existing pin only covered wasn't sent, so the clause the lane rewrote was unpinned;
ChatPageMoreCoverage.test.tsx now also asserts the notice states the outcome. Proven
red-first: dropping the outcome clause fails that assertion with
Received: "The command wasn't sent to the new terminal.Ask the agent", and the restore is
hash-identical.

self-added: yes - this string was introduced by this PR (round 6).
mechanism: copy only; no behaviour, no control flow, no new key.

@patrigao

Copy link
Copy Markdown
Contributor Author
  • deferred span=a9bfcaec1365 - make session absence authoritative and delete the opening grace

Correct about the cause, and it names its own home. GET /api/terminal/sessions skips the
None placeholder a session holds between ws.prepare() and its shell spawn
(if sess is None: continue), so opening and gone are the same answer. The opening
grace and the confirm probe exist only to cover that gap; an opening: true entry would
make the first answer authoritative and delete both.

Not taken here because it changes src/kiro_crew/dashboard/handlers/terminal.py, the surface
parked behind the #7638 RFC (#7649) - the boundary this PR has held since Phase 0, and the
reason the fix is client-side at all.

Recorded where the follow-up will read it, since the lane's own suggestion is "fits #10977":
the design is now a comment on #10977, and the PR body's Scope boundary section names the
missing absence signal as a tracked sibling rather than leaving it implied.

self-added: yes - the grace + confirm probe are this PR's (round 5).
mechanism: no code change this round; design carried to #10977 and to the PR body.

@patrigao

Copy link
Copy Markdown
Contributor Author
  • wont-fix-here span=a3387be4eab8 - extract the dispatch state machine beside fenceShell.ts

The observation is right: the dispatch/probe/rollback machine is large for a page component,
and the nine tests pay for it by mounting ChatPage.

Doing it in this PR would collide head-on with work already in flight. Open
PR #10708 relocates this exact
mc:run-in-terminal handler block out of ChatPage.tsx into a new
website/src/hooks/useRunInTerminalBridge.ts - a verbatim move, so the extraction this item
asks for is that PR's entire purpose. Landing a second, differently-shaped extraction of the
same lines turns a mechanical transplant into a real conflict for whoever merges second.

That overlap was declared before any code was written (coordination note on #10822) and the
agreed order is: this behaviour fix lands on main, and #10708 carries it into the new module.
The extraction is therefore deferred to #10708, not declined.

self-added: partly - the PR grew the block from ~33 to ~120 lines; the handler predates it.
mechanism: no code change; ownership of the refactor assigned to the PR already doing it.

@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running labels Sep 15, 2026

@iamwhatever iamwhatever left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approved after a full read of the diff on the current head: the change matches the linked issue and body, every code claim was spot-checked against main, tests pin the behaviour, all review lanes are clean and nothing is left undisposed.

@iamwhatever
iamwhatever merged commit a91a25f into main Sep 15, 2026
110 of 115 checks passed
@iamwhatever
iamwhatever deleted the fix/10822-run-in-terminal-tab-leak branch September 15, 2026 16:39
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Sep 15, 2026
CrysisDeu added a commit that referenced this pull request Sep 16, 2026
`loadPersisted` restored the dock terminal tab list without asking the
backend which PTY sessions still exist. A tab leaked by a "Run in terminal"
dispatch whose page closed before its rollback deadline (#10822), or one
whose shell the orphan reaper has since killed, therefore came back on every
reload — holding a slot in the per-panel tab cap and, the moment its view
reconnected, minting a fresh shell nobody asked for (the WS route spawns a
PTY for an id it does not know).

The store now marks the restored set as pending at module init and rules on
it against `GET /api/terminal/sessions`, which App already fetches at boot.
The ruling takes two looks, the protocol #10859 gave the dispatch-deadline
probe: the route skips the placeholder a session holds until its shell
spawns, so a session another window is opening reads like one that never
existed, and this store is shared across windows. The first answer only
names suspects (absent or `alive: false`); an uncached second answer after
the opening grace drops the ones still missing and keeps the ones now live.
The trimmed list is persisted and focus moves to a survivor. An answer that
does not rule — request failure, unrecognized shape, or the feature-disabled
reply, which returns an empty list without consulting the registry — keeps
every tab, since removing a live shell's scrollback cannot be undone while a
kept dead tab is user-closable and reaped server-side. Tabs minted after
boot are never candidates.

`TerminalTabsView` draws nothing while the ruling is pending. Effect order
made that necessary rather than cosmetic: a CliPanel mounted for a restored
tab opens its socket before the App-level probe fires, so the probe would
find the very shell it was asked about and keep the tab.

Closes #10977
CrysisDeu added a commit that referenced this pull request Sep 16, 2026
`loadPersisted` restored the dock terminal tab list without asking the
backend which PTY sessions still exist. A tab leaked by a "Run in terminal"
dispatch whose page closed before its rollback deadline (#10822), or one
whose shell the orphan reaper has since killed, therefore came back on every
reload — holding a slot in the per-panel tab cap and, the moment its view
reconnected, minting a fresh shell nobody asked for (the WS route spawns a
PTY for an id it does not know).

The store now marks the restored set as pending at module init and rules on
it against `GET /api/terminal/sessions`, which App already fetches at boot.
The ruling takes two looks, the protocol #10859 gave the dispatch-deadline
probe: the route skips the placeholder a session holds until its shell
spawns, so a session another window is opening reads like one that never
existed, and this store is shared across windows. The first answer only
names suspects (absent or `alive: false`); an uncached second answer after
the opening grace drops the ones still missing and keeps the ones now live.
The trimmed list is persisted and focus moves to a survivor. An answer that
does not rule — request failure, unrecognized shape, or the feature-disabled
reply, which returns an empty list without consulting the registry — keeps
every tab, since removing a live shell's scrollback cannot be undone while a
kept dead tab is user-closable and reaped server-side. Tabs minted after
boot are never candidates.

Both looks run under a deadline: the panel stays gated until they settle,
so a socket that never answers must be made to answer, and past the bound
it reads as a failed probe that keeps every tab.

`TerminalTabsView` draws nothing while the ruling is pending. Effect order
made that necessary rather than cosmetic: a CliPanel mounted for a restored
tab opens its socket before the App-level probe fires, so the probe would
find the very shell it was asked about and keep the tab.

Closes #10977
iamwhatever pushed a commit that referenced this pull request Sep 16, 2026
…te (#11133)

`loadPersisted` restored the dock terminal tab list without asking the
backend which PTY sessions still exist. A tab leaked by a "Run in terminal"
dispatch whose page closed before its rollback deadline (#10822), or one
whose shell the orphan reaper has since killed, therefore came back on every
reload — holding a slot in the per-panel tab cap and, the moment its view
reconnected, minting a fresh shell nobody asked for (the WS route spawns a
PTY for an id it does not know).

The store now marks the restored set as pending at module init and rules on
it against `GET /api/terminal/sessions`, which App already fetches at boot.
The ruling takes two looks, the protocol #10859 gave the dispatch-deadline
probe: the route skips the placeholder a session holds until its shell
spawns, so a session another window is opening reads like one that never
existed, and this store is shared across windows. The first answer only
names suspects (absent or `alive: false`); an uncached second answer after
the opening grace drops the ones still missing and keeps the ones now live.
The trimmed list is persisted and focus moves to a survivor. An answer that
does not rule — request failure, unrecognized shape, or the feature-disabled
reply, which returns an empty list without consulting the registry — keeps
every tab, since removing a live shell's scrollback cannot be undone while a
kept dead tab is user-closable and reaped server-side. Tabs minted after
boot are never candidates.

Both looks run under a deadline: the panel stays gated until they settle,
so a socket that never answers must be made to answer, and past the bound
it reads as a failed probe that keeps every tab.

`TerminalTabsView` draws nothing while the ruling is pending. Effect order
made that necessary rather than cosmetic: a CliPanel mounted for a restored
tab opens its socket before the App-level probe fires, so the probe would
find the very shell it was asked about and keep the tab.

Closes #10977
amadsalmon pushed a commit to amadsalmon/KiroCrew that referenced this pull request Sep 22, 2026
…inted (kirodotdev#10859)

A run-in-terminal dispatch mints a persisted dock terminal tab, then waits
for the PTY's ready frame. When ready never arrived, the dispatch reported
failure but left the tab behind: every retry ratcheted the persisted store
toward MAX_TERMINALS, where addTab refuses and every later dispatch
silently fails (kirodotdev#10822).

The dispatch now cleans up after itself on the never-ready path, but only
after asking the terminal sessions route whether the shell is still
running: a shell profile can replace the readiness hook on a live shell, so
a missing ready frame alone does not prove the dispatch died. A running
shell keeps its tab and scrollback; a dead or absent one is torn down with
the same teardown and order as the tab-close paths. The 6 s deadline
becomes a shared 15 s constant tolerant of slow login-shell profile chains,
and the code-block button's fallback flash is coupled strictly after it.

Fixes kirodotdev#10822

Co-authored-by: Patrick Gao <patrigao@amazon.com>
amadsalmon pushed a commit to amadsalmon/KiroCrew that referenced this pull request Sep 22, 2026
…te (kirodotdev#11133)

`loadPersisted` restored the dock terminal tab list without asking the
backend which PTY sessions still exist. A tab leaked by a "Run in terminal"
dispatch whose page closed before its rollback deadline (kirodotdev#10822), or one
whose shell the orphan reaper has since killed, therefore came back on every
reload — holding a slot in the per-panel tab cap and, the moment its view
reconnected, minting a fresh shell nobody asked for (the WS route spawns a
PTY for an id it does not know).

The store now marks the restored set as pending at module init and rules on
it against `GET /api/terminal/sessions`, which App already fetches at boot.
The ruling takes two looks, the protocol kirodotdev#10859 gave the dispatch-deadline
probe: the route skips the placeholder a session holds until its shell
spawns, so a session another window is opening reads like one that never
existed, and this store is shared across windows. The first answer only
names suspects (absent or `alive: false`); an uncached second answer after
the opening grace drops the ones still missing and keeps the ones now live.
The trimmed list is persisted and focus moves to a survivor. An answer that
does not rule — request failure, unrecognized shape, or the feature-disabled
reply, which returns an empty list without consulting the registry — keeps
every tab, since removing a live shell's scrollback cannot be undone while a
kept dead tab is user-closable and reaped server-side. Tabs minted after
boot are never candidates.

Both looks run under a deadline: the panel stays gated until they settle,
so a socket that never answers must be made to answer, and past the bound
it reads as a failed probe that keeps every tab.

`TerminalTabsView` draws nothing while the ruling is pending. Effect order
made that necessary rather than cosmetic: a CliPanel mounted for a restored
tab opens its socket before the App-level probe fires, so the probe would
find the very shell it was asked about and keep the tab.

Closes kirodotdev#10977
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Run in terminal: failed dispatches leak persisted dock tabs until the cap silently refuses every click

2 participants