Skip to content

fix(workspaces): recover a real terminal when activation throws for a planless agent create - #20190

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/fix-preseed-recovery-surface
Sep 14, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/fix-preseed-recovery-surface

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 0
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2

Minimal extraction of one fix from #20181, so it can land on its own. 1 source line removed (4 with the forced reformat), 1 test file. #20181 keeps the architecture and lands separately.

Landing: post-cut, deliberately. The branch this closes has no identified trigger (see Reachability). Putting a change to brand-new code into a release cut for a theoretical branch would invert the no-regressions priority the cut is being held to.

This is not a regression fix. The branch is #20175's own new recovery code, so v1.4.200 had no equivalent — and for the same hypothetical throw its outcome was strictly worse (the stranded creation surface that #20175 fixed). This is a residual improvement on new code.

The branch, and what it does

#20175's activation-failure recovery re-seeds the workspace surface, but passes callerProvidesSurface: true whenever an agent is selected (worktree-creation-flow-execute.ts:212 on main). Activation is the caller that would have provided that surface — and it just threw.

With the flag set and no startup plan, ensureWorktreeHasInitialTerminal takes its zero-tab pre-seed branch (worktree-initial-terminal-seeding.ts:141-160): callerProvidesSurface === true && renderableTabCount === 0 && !sequencedStartup && !issueCommand && !setupNeedsHostTerminal && !defaultTabs?.tabs.length && createNewTerminalForStartup !== true → it queues setup/issue commands and return null instead of creating a terminal.

So the recovery seeds nothing and the workspace ends up with zero tabs. It is silent: returning null is not a throw, so the inner catch never fires; the outer catch has already logged 'worktree create: activate-and-reveal failed' and the flow proceeds to completeWorktreeCreation. No toast, no error state — a created workspace that simply has no tabs, with nothing left to recover on reopen.

Reachability — why this is correct-but-theoretical

Two independent conditions must hold. The shape is reachable; the throw is not explained.

The shape (agent !== null with startupPlan == null, terminal route) is genuinely reachable, but only through malformed user-persisted settings, not ordinary use:

  • buildAgentStartupPlan returns null from !baseCommand.ok (shared/tui-agent-startup.ts:70-72). resolveAgentLaunchCommand reports not-ok for exactly four causes, all from persisted Settings strings: a failing args suffix plan, an unbalanced quote in agentDefaultArgs, a malformed agentCmdOverrides entry, and a command override conflicting with requested model/effort options (shared/tui-agent-launch-command.ts:41-77).
  • Its other null return, the empty prompt, does not apply: quick create passes allowEmptyPromptLaunch: true (quick-startup-plan.ts:94). An agent create with an empty prompt yields a real plan, so the natural first guess for this path is wrong.
  • The Settings editor commits the raw trimmed draft with no tokenization (AgentLaunchDefaultsEditor.tsx:82), and quick submit dispatches the request without gating on the resulting null plan, so a bad value reaches creation silently. Both are filed separately; neither is fixed here.

The throw is the unexplained half. The recovery is gated shouldActivateOnCompletion && !structuredLaunch, and it only matters if activateAndRevealWorktree throws before the activation gate arms at worktree-activation.ts:250 — a throw after that point is recovered independently by the gate's empty outcome reseed. Enumerating every statement in that pre-gate segment (setActiveRepo :202, setActiveView :207, setActiveWorktree :212, the runtime-env lookup :214-215, activateWebRuntimeSessionWorktree :217 — async, so it rejects rather than throwing synchronously — the visit stamps :225/:230, and reconcileWorktreeTabModel in the gate-arming computation at :242, a pure projection plus a set patch) turns up no plausible thrower. Every thrower #20175 was built against sits after gate registration.

So this PR is deliberately narrow: the reachable instance of the same null-plan-with-agent shape is a no-throw path already handled elsewhere, and the instance this fixes additionally needs a throw nobody has identified.

The fix

Drop the flag from the recovery call. The create-time call keeps it (now the only code occurrence, at :255) — there the agent pane really is the surface the caller provides.

The enclosing object literal collapses to a ternary because oxlint's unicorn/no-useless-spread rejects a lone conditional spread; verified by linting the pure deletion, which errors at :212. That is the only reason the source diff is 4 lines rather than 1.

Validation

New self-contained worktree-creation-activation-recovery-surface.test.ts, 2 tests. The seeding mock mirrors the real zero-tab branch — it returns null when handed callerProvidesSurface, a tab otherwise — so the first test asserts the user-visible consequence (a tab reaches completion) rather than an argument shape; the second pins the argument to document the mechanism.

Scope of the test, stated plainly: it sets startupPlan: null on the request and makes activateAndRevealWorktree throw. It constructs that state directly rather than driving the composer, so it proves the branch's behaviour, not its reachability. Reachability of the shape is established by the trace above; the throw is not.

Ablation, re-measured at the final commit (c569014f2d), reverting only the source file to origin/main and leaving the test as shipped here:

Arm State Result
A worktree-creation-flow-execute.ts at origin/main 2 failed
B final head 2 passed
  • Creation-flow sweep: 27 test files, 1446 passed / 1 skipped — including fix(workspaces): complete a worktree create when a post-create step throws #20175's own worktree-creation-flow-stranded-surface.test.ts, unchanged and still green.
  • oxlint clean on both files; oxfmt reports no drift; tsc --noEmit -p config/tsconfig.tc.web.json clean.
  • pnpm run check:code-quality:changed: 0 new findings across 2 changed files.
  • pnpm-lock.yaml verified unmodified at commit time.

… planless agent create

#20175's activation-failure recovery re-seeds the workspace surface, but passed
callerProvidesSurface: true whenever an agent was selected. Activation is the
caller that would have provided that surface, and it just threw. With the flag
set and no startup plan, worktree-initial-terminal-seeding takes its zero-tab
pre-seed branch: it queues setup/issue commands and returns null instead of
creating a terminal. The recovery then recovers nothing and the freshly created
workspace opens with no tabs.

Dropping the flag from the recovery call is the whole fix. The create-time call
keeps it: there, the agent pane really is the surface the caller provides.

The enclosing object literal becomes a ternary because oxlint's
unicorn/no-useless-spread rejects a lone conditional spread.
@coderabbitai

coderabbitai Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The activation-failure recovery path now passes undefined when no backend startup terminal was spawned. The activating-branch regression test uses a planless Claude agent request and expects undefined.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 6361d

The activation-failure recovery behavior is implemented, but its regression test can miss loss of the recovered tab during completion. Add the completion assertion before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides detailed context, rationale, implementation scope, reachability analysis, and validation results. However, it does not follow the required template structure and omits the req… Rewrite the description using the repository template. Include ELI5, What Changed, Why, a Fixes #<issue> entry, Visual Proof with N/A and a reason if applicable, Testing with the required checkboxes and platforms, AI Disclosure if appli…
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main fix: recovering a real terminal when activation fails during planless agent creation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description provides detailed context, rationale, implementation scope, reachability analysis, and validation results. However, it does not follow the required template structure and omits the required Linked Issue entry, explicit Visual Proof response such as N/A, checklist items, and several required sections.

Resolution

Rewrite the description using the repository template. Include ELI5, What Changed, Why, a Fixes #&lt;issue&gt; entry, Visual Proof with N/A and a reason if applicable, Testing with the required checkboxes and platforms, AI Disclosure if applicable, Review, Agent skill upstream boundary, Notes, and Checklist sections.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot 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.

✅ No new issues found.

Reviewed changes

First review at c569014. This is a tight, well-scoped extraction of one fix from #20181.

  • Recovery seed drops callerProvidesSurface — the activation-failure recovery call in worktree-creation-flow-execute.ts no longer tells ensureWorktreeHasInitialTerminal that the caller provides a surface. Since activation is that caller and it just threw, an agent create with no startup plan no longer falls into the zero-tab pre-seed branch that returns null — the workspace gets a real terminal. The create-time call keeps the flag, correctly.
  • New regression test — worktree-creation-activation-recovery-surface.test.ts pins the user-visible outcome (a recovered tab reaches seedAgentTabStateAfterWorktreeCreate through the real completeWorktreeCreation) as well as the argument shape. Its seeding mock mirrors the real zero-tab branch rather than asserting a shape in isolation.

I re-ran the ablation locally: reverting only worktree-creation-flow-execute.ts to origin/main and leaving the test as shipped makes both tests fail, so the test genuinely covers the regression. structuredLaunch skips this branch and the zero-tab path requires !sequencedStartup, so no structured-surface or startup-plan behavior is affected.

Pullfrog  | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: c0c170fb-5668-47ea-b18c-a0e013b43a1e

📥 Commits

Reviewing files that changed from the base of the PR and between c569014 and ef35c9c.

📒 Files selected for processing (2)
  • src/renderer/src/lib/worktree-creation-flow-execute.ts
  • src/renderer/src/lib/worktree-creation-flow-stranded-surface.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

{}
undefined
)
expect(ensureWorktreeHasInitialTerminal).toHaveReturnedWith('recovered-tab')

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- candidate test files ---'
fd -t f 'worktree-creation-flow-stranded-surface\.test\.ts$' .
printf '%s\n' '--- test section ---'
test_file="$(fd -t f 'worktree-creation-flow-stranded-surface\.test\.ts$' . | head -n 1)"
sed -n '150,225p' "$test_file"
printf '%s\n' '--- related symbols ---'
rg -n -S 'executeWorktreeCreation|ensureWorktreeHasInitialTerminal|primaryTabId|completion' src/renderer/src/lib "$test_file" -g '*.ts' -g '*.tsx' | head -n 160
printf '%s\n' '--- implementation candidates ---'
rg -l -S 'function executeWorktreeCreation|const executeWorktreeCreation|executeWorktreeCreation\s*=' src/renderer/src -g '*.ts' -g '*.tsx'

Repository: stablyai/orca

Length of output: 23842


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 28632


🏁 Script executed:

#!/bin/bash
set -e
test_file="$(fd -t f 'worktree-creation-flow-stranded-surface\.test\.ts$' . | head -n 1)"
printf '%s\n' '--- test section ---'
sed -n '150,225p' "$test_file"
printf '%s\n' '--- related symbols ---'
rg -n -S 'executeWorktreeCreation|ensureWorktreeHasInitialTerminal|primaryTabId|completion' src/renderer/src/lib "$test_file" -g '*.ts' -g '*.tsx' | head -n 200
printf '%s\n' '--- implementation candidates ---'
rg -l -S 'function executeWorktreeCreation|const executeWorktreeCreation|executeWorktreeCreation\s*=' src/renderer/src -g '*.ts' -g '*.tsx'

Repository: stablyai/orca

Length of output: 28642


🏁 Script executed:

pwd; fd -t f 'worktree-creation-flow-stranded-surface\.test\.ts$' .; rg -n -S 'executeWorktreeCreation|ensureWorktreeHasInitialTerminal|primaryTabId' src/renderer/src -g '*.ts' -g '*.tsx' | head -n 200

Repository: stablyai/orca

Length of output: 25244


🏁 Script executed:

set -e
f=$(fd -t f 'worktree-creation-flow-stranded-surface\.test\.ts$' . | head -n1)
sed -n '170,215p' "$f"
rg -n -S 'ensureWorktreeHasInitialTerminal|primaryTabId|executeWorktreeCreation' src/renderer/src -g '*.ts' -g '*.tsx' | head -n 160

Repository: stablyai/orca

Length of output: 21392


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- execute implementation ---'
sed -n '160,330p' src/renderer/src/lib/worktree-creation-flow-execute.ts
printf '%s\n' '--- completion mock and nearby assertions ---'
sed -n '1,135p' src/renderer/src/lib/worktree-creation-flow-stranded-surface.test.ts
sed -n '235,280p' src/renderer/src/lib/worktree-creation-flow-stranded-surface.test.ts

Repository: stablyai/orca

Length of output: 13276


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- completion binding ---'
sed -n '1,45p' src/renderer/src/lib/worktree-creation-flow-execute.ts
rg -n -S 'function completeWorktreeCreation|const completeWorktreeCreation|export .*completeWorktreeCreation|completeWorktreeCreation\s*\(' src/renderer/src/lib -g '*.ts' | head -n 80
printf '%s\n' '--- completion implementation candidates ---'
rg -l -S 'function completeWorktreeCreation|const completeWorktreeCreation|export .*completeWorktreeCreation' src/renderer/src/lib -g '*.ts' | head -n 20

Repository: stablyai/orca

Length of output: 2788


Assert the recovered tab at the completion boundary.

ensureWorktreeHasInitialTerminal is mocked to return 'recovered-tab', so toHaveReturnedWith('recovered-tab') checks only the mock result. executeWorktreeCreation passes the value as primaryTabId to the imported completeWorktreeCreation. Assert that completion input or its persisted result instead.

@coderabbitai coderabbitai Bot 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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)
src/renderer/src/lib/worktree-creation-flow-stranded-surface.test.ts (1)

202-202: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the recovered tab ID at completion.

When activation throws, executeWorktreeCreation assigns the recovery result to primaryTabId and passes it to completeWorktreeCreation. This test only checks cleanup, so a regression that drops the value before seedAgentTabStateAfterWorktreeCreate would still pass. Assert that the completion consumer receives primaryTabId: 'recovered-tab'.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 3344c1c1-70b0-4bdb-92e2-f023d103ab2c

📥 Commits

Reviewing files that changed from the base of the PR and between ef35c9c and 6361d9d.

📒 Files selected for processing (1)
  • src/renderer/src/lib/worktree-creation-flow-stranded-surface.test.ts
💤 Files with no reviewable changes (1)
  • src/renderer/src/lib/worktree-creation-flow-stranded-surface.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron UI validation

Validated the hidden rendered app at PR head c569014f2d5fdb81ac7495b88044cc4946750a21 using Playwright over CDP. Every image below is an uncropped 1728×994 full app-window capture with surrounding product context; before each capture I rechecked window.api.app.getIdentity() against this worktree (and against a separate detached origin/main worktree for the comparison arm).

1. Normal Codex workspace create

A local git workspace was created with Codex and the real prompt Reply with exactly: PR 20190 normal create QA. The visible result was a single Codex surface showing the exact response, with no stray shell tab. Backing state: reconcileWorktreeTabModel(...).renderableTabCount === 1; the sole terminal was stamped launchAgent: "codex".

The hidden renderer would not keep focus in the prompt field—the modal routed typing back to the workspace-name field—so this interaction was not submitted through the full modal. I used the production runBackgroundWorktreeCreation launch/store boundary without changing source.

Normal Codex create: one agent surface, no stray shell

2. Blank Terminal (agent === null)

Driven through the real New Workspace modal, declining setup hooks. The visible result was exactly one shell tab. Backing state: renderableTabCount === 1; the sole terminal had launchAgent: null.

Blank Terminal create: exactly one shell tab

3. Folder workspace with Codex

Registered a plain directory with project setup-existing-folder --kind folder, then created the workspace through the real folder Create Workspace modal. The visible result was one Codex surface and no stray shell. Backing state: renderableTabCount === 1; the sole terminal had launchAgent: "codex".

Folder workspace create: one Codex surface, no stray shell

4. Reachable null-plan half, and the remaining gap

Through Settings → Agents → Codex → Arguments, I saved the malformed value --flag "unclosed. The production quick-startup planner then returned startupPlan: null and no backend startup payload for an agent-selected request. Because of the same hidden-renderer composer limitation above, creation was dispatched at the production runBackgroundWorktreeCreation boundary.

On the PR branch, an exact repeat completed visibly with one blank shell; backing state was renderableTabCount === 1, sole terminal launchAgent: null. A separately launched, separately profiled origin/main instance at fa3d29fa11 produced the same result on the matched repeat: one blank shell, renderableTabCount === 1, launchAgent: null. Instrumented repeats on both arms captured no activation error.

The initial cold-profile origin/main attempt transiently completed with renderableTabCount === 0; repeating in that same instance produced the one-shell result above, while both PR-branch attempts produced one shell. Since no activation failure was logged or captured, that cold-start difference is not evidence that the PR's recovery catch ran.

PR branch:

PR branch null-plan state: one blank shell

origin/main matched repeat:

origin/main null-plan state: one blank shell

Unverified

I could not honestly produce the activation throw required to enter the changed recovery call. I did not patch source, inject a throw, or otherwise manufacture that condition. Therefore the changed catch path itself remains unexercised on screen; the evidence above covers the surrounding create behaviors and the independently reachable null-startup-plan state.

@pullfrog pullfrog Bot 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.

✅ No new issues found.

Reviewed changes

Re-reviewed the two commits since the previous pullfrog review at c569014 (ef35c9c, 6361d9d). Both are test-only consolidation layered on the unchanged fix.

  • Consolidated recovery-surface coverage into the existing stranded-surface test — the standalone worktree-creation-activation-recovery-surface.test.ts is deleted and its planless-agent case is folded into worktree-creation-flow-stranded-surface.test.ts, which now drives makeRequest({ agent: 'claude' }) and asserts the recovery seed's options argument.
  • Trimmed the recovery options fallback — the source now passes undefined instead of {} when backendSpawned is false, and shortens the explanatory comment; no behavior change, since {} and undefined are equivalent for the optional opts.
  • Dropped a tautological assertion — toHaveReturnedWith('recovered-tab') only re-checked the mock's own mockReturnValue, so removing it is correct.

I re-ran the ablation at the current head (6361d9d): reverting only worktree-creation-flow-execute.ts to origin/main makes the planless-agent test fail on a spurious callerProvidesSurface: true, so the consolidated test still genuinely covers the regression. The focused test file is 8/8 green and the changed-code quality gate reports 0 new findings across the 2 files.

ℹ️ PR description describes the deleted standalone test

The PR body says the fix adds a "self-contained worktree-creation-activation-recovery-surface.test.ts, 2 tests" and reports the ablation "at the final commit (c569014f2d)". Neither matches the current head: that file is deleted, the coverage now lives in worktree-creation-flow-stranded-surface.test.ts, and the final commit is 6361d9d.

Technical details
# Refresh the PR description to match the shipped test layout

## Affected sites
- PR body "## Validation" section — references `worktree-creation-activation-recovery-surface.test.ts` and its 2 tests.
- PR body "Ablation, re-measured at the final commit (`c569014f2d`)" — the head has advanced to `6361d9d`.

## Required outcome
- The description should name `worktree-creation-flow-stranded-surface.test.ts` as the file carrying the planless-agent recovery coverage, and report ablation against the current head.

## Suggested approach (optional)
- Re-run the two-arm ablation at `6361d9d` and update the table; the current table was measured against `c569014`, before the standalone test was folded in.

Pullfrog  | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025
brennanb2025 merged commit 06c83e2 into main Sep 14, 2026
27 checks passed
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.

1 participant