Repository navigation
refactor(workspaces): settle the worktree-create tail by outcome value instead of per-step catches - #20181
refactor(workspaces): settle the worktree-create tail by outcome value instead of per-step catches#20181brennanb2025 wants to merge 4 commits into
Conversation
… throw still shows the workspace A freshly created workspace could open with no tabs: executeWorktreeCreation's try/catch ends when createWorktree resolves, so a throw in the tail (activation, terminal seeding, after-wake seed, structured launch) escaped past the only code that removes the pending entry. All three callers invoked it as a bare void, so the rejection was unobserved, shouldShowWorktreeCreationSurface stayed true, and the creation panel covered a workbench that was mounted and fine behind it. The semantic boundary is createWorktree resolving. Before it, a failure is a create failure: the three call sites now share startWorktreeCreation, whose .catch() stamps status 'error' and toasts. After it, the worktree exists on disk, so the tail reports a settlement value instead of relying on nothing throwing. runWorktreePostCreateSteps returns 'complete' | 'cancelled' | 'awaiting-visibility' under one guard and never throws; executeWorktreeCreation owns settlement, and the two non-completing outcomes keep behaving exactly as before.
…orktree-create-tail # Conflicts: # src/renderer/src/lib/worktree-creation-flow-execute.ts # src/renderer/src/lib/worktree-creation-flow-stranded-surface.test.ts
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review. 📝 WalkthroughWalkthroughThe change extracts post-create worktree handling into Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to The refactor preserves explicit settlement and recovery behavior with expanded regression coverage; no unresolved merge-blocking risk is identified. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives detailed context, rationale, implementation scope, and validation results. However, it omits multiple required template sections, including the required Linked Issue entry with a Fixes reference, Visual Proof or an explicit N/A explanation, the Testing checklist, AI Disclosure, Review, Agent skill upstream boundary, Notes, and the final Checklist. Resolution Add the missing template sections. Include a Linked Issue entry using the required Fixes # format, provide visual proof or write N/A with a reason, complete the Testing and repository checklists, address AI Disclosure, Review, Agent skill upstream boundary, and Notes, and retain the existing technical details under the corresponding ELI5, What Changed, and Why headings.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Outcome-based post-create settlement — new
worktree-creation-post-create-steps.tswraps activation, initial-terminal seeding, after-wake seeding, and the structured launch in onetry/catchthat returnscomplete/cancelled/awaiting-visibilityand never throws;executeWorktreeCreationsettles each outcome in one place, so a tail throw now completes and reveals the workspace instead of stranding the pending entry. - Progress-preserving catch — the guard reports
activation/primaryTabIdthat already landed rather than resetting them, so a later step throwing does not discard a tab an earlier step seeded. - Caller-side backstop — the three bare-
voidcall sites inworktree-creation-flow.tsnow sharestartWorktreeCreation, whose.catch()stampsstatus: 'error', logs, and toasts only when the panel is not already showing the error; covers pre-createWorktreefailures. - Tests — new
worktree-creation-flow-stranded-surface.test.ts(10 tests) pins the throw-guard, the two non-completing outcomes, the preserved-tab behavior, and the pre-create backstop;worktree-creation-flow.test.tsswaps the flush helper for a timer boundary so it drains the flow's growing await depth.
The two unguarded awaits between createWorktree resolving and the guard (attachEphemeralVmRuntimeToWorkspace, preflightAgentTrust) are contained at their own call sites, so the boundary is where the description says it is. Existing direct-executeWorktreeCreation tests (worktree-creation-structured-unknown-outcome, agent-seeding, chat-setup) still pass. Verified locally: focused tests 38 passed, oxlint clean on all 5 files, and the max-lines ratchet is green.
openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Important
One behavioral regression found: the single outer try/catch aborts later independent steps that main's per-step catches still ran, contradicting the PR's "no observable behavioural delta" claim. Details inline.
Reviewed changes
- Outcome-value settlement module — new
worktree-creation-post-create-steps.tsreturnscomplete/cancelled/awaiting-visibilityunder onetry/catch;executeWorktreeCreationnow settles each outcome itself and drops its four per-step catches. - Activation-failure recovery — #20175's recovery heuristic is preserved and consolidated into
recoverRevealedWorkspaceSurface(verified startup/agent tab → else seed if no tabs → after-wake), gated to the activating branch. - Tests —
worktree-creation-flow-stranded-surface.test.tsgrows to 14 tests;worktree-creation-flow.test.tsflush helper moves to a macrotask boundary.
The shape is clean and the settlement contract is well-documented, but the consolidation is not behavior-preserving. In openCreatedWorkspaceSurface every step now shares the single catch, and settleCreatedWorkspace awaits the structured launch after that call. So an early throw skips later steps instead of letting them run. I verified this with a temporary direct-unit test of runWorktreePostCreateSteps (since removed): with a structured request carrying result.setup and a throwing ensureWorktreeHasInitialTerminal, the outcome is {kind:'complete', structuredLaunchAccepted:true} and launchStructuredWorktreeSession is never called, so the agent never launches while completion skips its seeding fallback. A background seed throw likewise skips the after-wake seed. The 14 tests pass on main (arm A), so none of them pin the difference.
openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
| structuredLaunchAccepted: args.structuredLaunch | ||
| } | ||
| try { | ||
| return await settleCreatedWorkspace(args, progress) |
There was a problem hiding this comment.
One try/catch around the whole body changes control flow, not just error handling: a throw in an early step now aborts every later independent step, which main's four per-step catches allowed to run. Concretely, a structured-native-chat create carrying setup work that throws in ensureWorktreeHasInitialTerminal never reaches launchStructuredWorktreeSession (line 103) while structuredLaunchAccepted stays true, so completeWorktreeCreation also skips seedAgentTabStateAfterWorktreeCreate and focus — the workspace opens with no agent. No test injects a throw before a later step, and all 14 pass on main, so this delta is unpinned.
Technical details
# Single outer catch aborts later independent steps
## Affected sites
- `src/renderer/src/lib/worktree-creation-post-create-steps.ts:191-196` — the `runWorktreePostCreateSteps` catch returns `complete` immediately, skipping any step after the throw.
- `src/renderer/src/lib/worktree-creation-post-create-steps.ts:95,103` — `settleCreatedWorkspace` calls `openCreatedWorkspaceSurface` (uncaught) and only then awaits the structured launch, so an `openCreatedWorkspaceSurface` throw pre-empts the launch.
- `src/renderer/src/lib/worktree-creation-post-create-steps.ts:141-174` — `recoverRevealedWorkspaceSurface` mirrors the same pattern: seeding and after-wake share one `try`, so a seeding-recovery throw skips after-wake recovery (`main` had two try blocks).
## Evidence
Direct unit call to `runWorktreePostCreateSteps` (temp test, removed): request `{agent:'codex', agentLaunchRoute:'structured-native-chat'}`, `result.setup` present, `structuredLaunch:true`, `shouldActivateOnCompletion:true`, `ensureWorktreeHasInitialTerminal` throws. Outcome was `{kind:'complete', activation:false, primaryTabId:null, structuredLaunchAccepted:true}` and `launchStructuredWorktreeSession` was called 0 times. `main`'s per-step version catches the seeding error and still runs the structured launch.
## Required outcome
A throw in one best-effort tail step must not prevent the remaining best-effort steps from running, matching `main`. Settlement must still complete (the original #20175 fix).
## Suggested approach
Restore per-step containment inside `openCreatedWorkspaceSurface` (one `try/catch` per `activateAndRevealWorktree`, `ensureWorktreeHasInitialTerminal`, `ensureWebRuntimeWorktreeTerminalAfterWake`, each recording progress), and split `recoverRevealedWorkspaceSurface` back into separate try blocks for seeding and after-wake. Keep the outer catch purely as the last-resort settlement guarantee. Add tests for structured+seed-throw (assert `launchStructuredWorktreeSession` still called) and seed-throw+after-wake (assert after-wake still called); both fail against the current head.…ace for a planless agent create
…orktree-create-tail
There was a problem hiding this comment.
Important
The two new commits in this delta are clean and the recovery change is a real improvement, but they do not address the must-address containment regression flagged in the prior review — the single tail try/catch still aborts later independent steps after an early throw. That thread remains open. No new issues were found in this delta.
Reviewed changes
- Step-naming breadcrumb — added a
PostCreateStagerecorded before each tail step and passed to the single catch'sconsole.error, so step identity survives collapsing the per-step catches into one. - Planless-agent recovery fixed —
recoverRevealedWorkspaceSurfaceno longer passescallerProvidesSurface, so an agent create whose activation throws and that has no startup plan seeds a real terminal instead of hitting the zero-tab pre-seed branch. - Tests —
worktree-creation-flow-stranded-surface.test.tsgrows to 16 tests, adding the planless-agent recovery, the stage breadcrumb, the later-step-preserves-tab case, structured-launch rejection, and the two non-completing outcomes.
openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
|
Fixed on main by #20175; this follow-up refactor is no longer needed. |

Follow-up to #20175, which merged to
mainat 2026-09-12T01:07Z (70a588c8bf) while this was being built. It replaces that fix's enumerated per-step guards with outcome-value settlement, on top of what landed.worktree-creation-flow.tsis untouched here — #20175's sharedstartWorktreeCreationcaller.catch()backstop is the structurally correct half, it is shipping, and it is kept exactly as merged.What shipped, and why its shape is not the one we want
executeWorktreeCreation'stry/catchends the momentcreateWorktreeresolves, so a throw in the tail escaped past the only code that removes the pending entry.shouldShowWorktreeCreationSurfacestayed true and the creation panel covered a workbench that was mounted and correct behind it — a fresh workspace with no tabs, fixed by switching away and back.#20175 fixed it with four individual
try/catchregions, one per known throw site. That works for today's steps, but the guarantee is enumerated rather than structural: a step added to the tail later does not inherit it. It also pushedworktree-creation-flow-execute.tsfrom 249 to 324 lines.The shape
The semantic boundary is
createWorktreeresolving. Before it, a failure is a create failure — the shipped caller backstop owns that. After it, the worktree exists on disk and every failure must still complete and show the workspace, never error.So the tail settles on a returned value instead of on nothing throwing. New
worktree-creation-post-create-steps.tsexposesrunWorktreePostCreateSteps, returningunder one
try/catchthat never throws.executeWorktreeCreationowns settlement in one place and drops from 324 to 201 lines. A step added to the tail later inherits the guarantee.Adding an unhandled variant to the union fails
tscat the settlement block (verified by ablation), so a future outcome cannot silently settle nothing. Settlement uses a narrowingif-chain rather than aswitchdeliberately: aswitchwith a trailingbreakwould let a new variant fall through and settle nothing, which is this bug class.Deliberately not done
finally { completeWorktreeCreation() }. Both non-completing outcomes are load-bearing and now have tests:cancelled(the cancel path already removed the entry; completing would re-seed tabs and steal focus for a workspace being torn down) andawaiting-visibility(markStructuredWorktreeLaunchUnconfirmeddeliberately keeps the entry withstatus: 'error'+structuredLaunchRecoveryWorktreeId, the panel retry's only handle on the unconfirmed session —worktree-creation-structured-recovery.ts:8-20).shouldShowWorktreeCreationSurfaceis not made self-healing. The surface legitimately persists after the worktree row exists, for that same recovery affordance.activateAndRevealWorktree's post-seed steps (worktree-activation.ts:277-320), plausibly a subscriber throwing during aset(). Out of scope; the breadcrumbs below are the field instrument for it.createWorktreeresolves are contained at their own call sites (ephemeral-vm-worktree-creation.ts:169-181,agent-trust-preflight.ts:19-27). Widening to the cancellation check would change no behaviour today.Two behavioural improvements over the merged version
callerProvidesSurface: truein its activation catch, so an agent create with no startup plan hits the zero-tab pre-seed branch (worktree-initial-terminal-seeding.ts:141-160) and recovers nothing. Activation is what would have provided that surface, and it threw — so the consolidated recovery no longer claims otherwise.console.errorstrings into one catch would have lost step identity, which is the field instrument for the unidentified trigger. Astageon the progress record restores it as data:'worktree create: post-create step failed', 'seed-after-wake-terminal', worktreeId, error. It composes with future steps instead of needing a new literal per step.#20175's recovery heuristic is kept, consolidated
It was going to be deleted as redundant under this shape. It is not redundant — measured: without it, a throw in
activateAndRevealWorktreedelivers the agent draft prompt toprimaryTabId: nullinstead of the stamped agent tab, and a tabless workspace gets nothing seeded. Since #20175 shipped, deleting that is a regression. It is preserved as a singlerecoverRevealedWorkspaceSurfacecalled from the one catch instead of inlined per-step, gated to the activating branch (shouldActivateOnCompletion && !structuredLaunch, which reproduces #20175's scope exactly) and itself guarded so settlement never depends on recovery succeeding.The catch also reports progress that already landed rather than resetting to
activation: false, primaryTabId: null. Safe because both are only ever assigned from fully completed calls; arm E below shows it is a real behavioural difference.Validation
worktree-creation-flow-stranded-surface.test.ts: 16 tests, up from #20175's 8. All 8 of its tests are carried over — no shipped behavioural pin was dropped.Ablation at the final head:
worktree-creation-flow-execute.tsatorigin/main, new module absentArm A names the honest delta: the 2 failures are the two improvements above. The other 14 tests pass against
main— because #20175 already guards every throw site that exists today. The restructure's own discriminating property, that a future tail step inherits the guarantee, is not expressible as a test of today's code; recorded here rather than dressed up. Arm E shows what the progress-reporting catch is worth.For reference, against
mainbefore #20175 merged (base6252f8149b, the tests as they stood then): arm A 7 failed / 3 passed; execute-only reverted 5 failed; flow-only reverted 2 failed; full change 10 passed. That is what the two halves were each worth.oxlintclean on all 4 changed files; nomax-linesdisable added;oxfmtreports no drift.tsc --noEmitontsconfig.tc.web.jsonandtsconfig.tc.cli.json: clean.tsconfig.node.jsonreports 29 errors insrc/main/claude/, identical before and after and none naming a file here (pre-existing onmain).Folder workspaces: verified inapplicable, not skipped
executeWorktreeCreationonly ever creates git worktrees, so this bug class has no folder-workspace twin. Chain:isProjectGroupTarget(runtime-target-selection.ts:42) and return early intosubmitFolderTargetbefore reaching the pending-creation flow —quick-submit-action.ts:70-73,full-submit-orchestration.ts:66-69.runBackgroundWorktreeCreation's only non-test caller isquick-creation-execution.ts:270. The'folder'literal at:203is only aplanAgentSessionLaunchrouting input, not a creation kind.try/catch/finallywithsetCreating(false)in thefinallyand never touchespendingWorktreeCreations(folder-submit-orchestration.ts:86-183) — there is no stranded-surface state for it to reach.activateAndRevealWorkspace(worktree-activation.ts:331-344); this tail callsactivateAndRevealWorktree, the git path.worktree-create-parent-pick.ts:47) — an input, not the created id.A folder test through this flow would have exercised the git path and proved nothing, so none is included.
Test-only change in
worktree-creation-flow.test.tsSettlement now sits behind one more
await, which starved that file's 2-microtaskflushAsyncWorktreeCreationhelper — the exact fragility the file already documents on its issue-command test. The helper now awaits a timer boundary, draining whatever depth the flow grows to. It also removes a counted line, which matters: the file was sitting at exactly the 800-linemax-linescap.