fix(desktop): retry an agent launch whose terminal attach was cancelled

PA
3mo ago
+475-26

What & why

Creating a workspace with a prompt sometimes gives you the setup terminal and no agent, with no error anywhere. I hit it repeatedly on a loaded machine (16GB MBA, disk near full); my ~/.superset/daemon.log has 29 occurrences, the oldest from 2026-04-17, so this is long-standing rather than new.

Root cause. A launch attaches with joinPending: true, so when the pane's <Terminal> already has an attach in flight the launch rides on that request rather than owning one (the #2748 fix). The AbortController stays with the component, though. When the component unmounts or supersedes its own attach — routine while workspace init brings an agent pane up mid-render — the shared request is aborted and the passenger launch dies with it, even though the pane is alive and about to be re-attached. launchTerminalAdapter then catches and calls removePane, killing the pane.

Normally the launch wins the race (one microtask, vs React's scheduler committing on a macrotask) and owns the attach, which is why this is intermittent and load-sensitive. The host has no joinPending concept at all (terminal-host.ts:84 aborts any existing pending attach unconditionally); the join only exists in DaemonTerminalManager.

Why it was invisible. #5925 added if (isTerminalAttachCanceledMessage(...)) return; to WorkspaceInitEffects, which silenced the symptom instead of the race. No toast, no log, no retry — the workspace just quietly ends up without its agent.

The fix. Retry a cancelled attach instead of treating it as a verdict on the pane. The retry lives inside ensureTerminalAttached, which runs inside the adapter's try, so the pane is never destroyed in the first place. Only cancellations retry; TERMINAL_SESSION_KILLED (a genuinely gone pane) fails immediately.

Plus two things that stand on their own:

  • Stop swallowing the failure, and map both pane-gone sentinels to prose so neither leaks raw into a toast.
  • Thread a typed reason through killTerminalForPane. Every destructive path funnels through it and it recorded nothing, which is exactly why a pane dying 60ms after creation was indistinguishable in the logs from one the user closed on purpose.

Evidence

From my own machine, a failing vs. a succeeding creation:

FAIL  .079 pane created (setup)      SUCCESS  .474 pane created (setup)
      .114 Creating/attaching …079            .509 Creating/attaching …474
      .172 pane created (agent)                .576 pane created (agent)
      .198 Creating/attaching …172             .591 Creating/attaching …576
      .202 Session …172 killed                 .840 Session …576 created
      .217 Session …172 killed                 .847 Session …474 created
      .469 TERMINAL_ATTACH_CANCELED
      .470 Session …079 created

Terminal history confirms which pane is which: on the failing run the survivor ran the setup script and the killed pane has zero history — it never reached claude. Persisted tab state shows the same thing: the success case keeps {row, first: setup, second: agent}, the failure collapses back to the bare setup pane.

Two details that took a while to read correctly, and are worth knowing if you touch this code:

  • The host's CANCELED log line is emitted when its queued spawn unwinds, not when the abort fires — it sits behind spawnLimiter (MAX_CONCURRENT_SPAWNS = 3). That is why it appears several hundred ms late, next to the other pane's created line. Reading it as the moment of cancellation inverts the whole causality.
  • The two kills ~10ms apart are removePane followed by the unmount with paneDestroyed=true. That is also the signature of a normal pane close, which is what made this so hard to spot in logs.

How I tested it

bun test in apps/desktop: 3653 pass / 2 fail / 1 error, against a 3645 / 2 / 1 baseline measured on a clean tree at HEAD (I reverted the whole diff, ran the suite, and restored). That is +8 tests, +8 passing, failures unchanged. The two failures are pre-existing and unrelated — getProcessEnvWithShellPath in git.test.ts (fails identically on clean HEAD) and a @dnd-kit/React module-interop error in useSidebarDnd.test.ts that only appears in full-suite runs and passes in isolation.

tsc --noEmit clean, biome check clean across 3702 files, i18n enforcement 82 pass, sherif 0 errors.

New tests:

  • launch-command.test.ts — retries a cancel, gives up after the budget, does not retry a killed pane or unrelated failures, keeps joinPending on every attempt.
  • daemon-manager.test.ts — pins the join-then-cancel semantics the retry exists for (the #2748 tests only covered two racing attaches, never the owner cancelling afterwards), the unmount case where the retry owns the request, and the supersede case where it joins the replacement instead.

Confidence — please read before merging

What I'm confident about, because it's proven in tests or in the logs above:

  • The passenger race is real and previously untested. The owner's cancel does kill a joined launch.
  • The recovery works: after the cancel there's no tombstone and no pending entry, so the retry attaches cleanly.
  • The silent swallow is real, and a raw TERMINAL_SESSION_KILLED would otherwise have leaked into a toast (caught in review of this branch).
  • No regressions, measured against a clean-tree baseline rather than assumed.

What is not verified, and why I'd like a second opinion:

  • I have not watched a real workspace creation fail and then succeed on the retry. The mechanism and the recovery are proven in tests; the end-to-end gate is not closed. I could not attach CDP to a packaged build to catch a live repro.
  • I never identified which caller ultimately destroys the pane in every case. The evidence points at launchTerminalAdapter's catch as the consequence of the cancel, but updateTabLayout (store.ts:519) also kills panes purely from a layout diff and I could not rule it out from logs alone. That is what the kill-reason instrumentation is for: if a report ever comes back with update-tab-layout or remove-tab, this diagnosis is wrong and the fix is treating a symptom.
  • The retry budget survives a burst of supersedes but is not unbounded, so a pane that thrashes its attach more than 3 times still fails — loudly now, rather than silently.

Follow-ups I deliberately left out to keep this reviewable:

  • The deeper fix is giving a joined attach its own lifetime in DaemonTerminalManager (refcount, so the owner's cancel doesn't tear down joiners). The retry gets the same outcome with far less blast radius.
  • pendingTerminalSetups (stores/workspace-init.ts) is non-persisted zustand, and the recovery path at WorkspaceInitEffects.tsx:406-448 rebuilds from getSetupCommands, which carries no agent. Restart mid-init and the agent is lost with no way back.
  • settledByIdempotency (agent-session-orchestrator.ts:17) is a module-level Map that is never cleared, so a failed launch with an idempotency key can never be retried for the session's lifetime. Latent — this path sets no key.

Related: #6774 is the CLI/cross-host analogue of the same "agent launch fails, error swallowed" shape.

Checklist

  • PR title follows conventional commits (type(scope): subject)
  • bun run lint and bun run typecheck pass (CI fails on lint warnings too)
  • "Allow edits from maintainers" is checked on fork PRs

https://claude.ai/code/session_014FCFavVKRFSXBfuV7de6gp


Summary by cubic

Retries an agent launch when its terminal attach is cancelled, so workspace creation no longer silently ends up with the setup terminal and no agent. The launch now retries a cancelled attach instead of treating it as a verdict on the pane, and surfaces real failures instead of swallowing them.

  • A cancelled attach is retried up to 3 times; a killed session fails immediately.
  • Pane-gone errors now map to a user-facing message instead of leaking raw protocol strings.
  • killTerminalForPane now records why a pane was killed, so mid-launch pane deaths are distinguishable from user closes.

Summary by CodeRabbit

  • Bug Fixes

    • Terminal launches now automatically retry when an attach request is canceled, up to three attempts.
    • Canceled terminal sessions are handled without replacing active pending requests.
    • Terminal sessions that close before starting now display a clear error notification instead of being silently ignored.
    • Other terminal failures continue to surface immediately without unnecessary retries.
  • Diagnostics

    • Added optional terminal lifecycle debug logging to help trace terminal cleanup and closure events.