Skip to content

refactor(workspaces): settle the worktree-create tail by outcome value instead of per-step catches - #20181

Closed
brennanb2025 wants to merge 4 commits into
mainfrom
brennanb2025/settle-worktree-create-tail
Closed

brennanb2025 wants to merge 4 commits into
mainfrom
brennanb2025/settle-worktree-create-tail

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #20175, which merged to main at 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.ts is untouched here — #20175's shared startWorktreeCreation caller .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's try/catch ends the moment createWorktree resolves, so a throw in the tail escaped past the only code that removes the pending entry. shouldShowWorktreeCreationSurface stayed 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/catch regions, 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 pushed worktree-creation-flow-execute.ts from 249 to 324 lines.

The shape

The semantic boundary is createWorktree resolving. 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.ts exposes runWorktreePostCreateSteps, returning

{ kind: 'complete', activation, primaryTabId, structuredLaunchAccepted }
| { kind: 'cancelled' }
| { kind: 'awaiting-visibility' }

under one try/catch that never throws. executeWorktreeCreation owns 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 tsc at the settlement block (verified by ablation), so a future outcome cannot silently settle nothing. Settlement uses a narrowing if-chain rather than a switch deliberately: a switch with a trailing break would let a new variant fall through and settle nothing, which is this bug class.

Deliberately not done

  • Not a bare 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) and awaiting-visibility (markStructuredWorktreeLaunchUnconfirmed deliberately keeps the entry with status: 'error' + structuredLaunchRecoveryWorktreeId, the panel retry's only handle on the unconfirmed session — worktree-creation-structured-recovery.ts:8-20).
  • shouldShowWorktreeCreationSurface is not made self-healing. The surface legitimately persists after the worktree row exists, for that same recovery affordance.
  • No attempt at the trigger. The throw fires after seeding, inside activateAndRevealWorktree's post-seed steps (worktree-activation.ts:277-320), plausibly a subscriber throwing during a set(). Out of scope; the breadcrumbs below are the field instrument for it.
  • Guard boundary stops at the activation step. The two other awaits after createWorktree resolves 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

  1. A planless agent create now recovers a real terminal. The merged fix passes callerProvidesSurface: true in 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.
  2. The breadcrumb names the failing step. Collapsing six per-step console.error strings into one catch would have lost step identity, which is the field instrument for the unidentified trigger. A stage on 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 activateAndRevealWorktree delivers the agent draft prompt to primaryTabId: null instead 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 single recoverRevealedWorkspaceSurface called 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:

Arm State Result
A worktree-creation-flow-execute.ts at origin/main, new module absent 2 failed / 14 passed
D full change 16 passed
E full change, but the catch discards progress instead of reporting it 4 failed / 12 passed

Arm 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 main before #20175 merged (base 6252f8149b, 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.

  • Broad sweep: 26 creation-related test files, 1452 passed / 1 skipped.
  • oxlint clean on all 4 changed files; no max-lines disable added; oxfmt reports no drift.
  • tsc --noEmit on tsconfig.tc.web.json and tsconfig.tc.cli.json: clean. tsconfig.node.json reports 29 errors in src/main/claude/, identical before and after and none naming a file here (pre-existing on main).

Folder workspaces: verified inapplicable, not skipped

executeWorktreeCreation only ever creates git worktrees, so this bug class has no folder-workspace twin. Chain:

  1. Both submit entry points dispatch on isProjectGroupTarget (runtime-target-selection.ts:42) and return early into submitFolderTarget before reaching the pending-creation flow — quick-submit-action.ts:70-73, full-submit-orchestration.ts:66-69.
  2. runBackgroundWorktreeCreation's only non-test caller is quick-creation-execution.ts:270. The 'folder' literal at :203 is only a planAgentSessionLaunch routing input, not a creation kind.
  3. The folder path awaits its create inside one try/catch/finally with setCreating(false) in the finally and never touches pendingWorktreeCreations (folder-submit-orchestration.ts:86-183) — there is no stranded-surface state for it to reach.
  4. The folder-vs-worktree activation dispatch lives in activateAndRevealWorkspace (worktree-activation.ts:331-344); this tail calls activateAndRevealWorktree, the git path.
  5. The only folder key in the worktree-create subtree is the parent pick (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.ts

Settlement now sits behind one more await, which starved that file's 2-microtask flushAsyncWorktreeCreation helper — 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-line max-lines cap.

Merge Sim added 2 commits September 11, 2026 18:14
… 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
@brennanb2025 brennanb2025 changed the title fix(workspaces): settle a worktree create by outcome so a post-create throw still shows the workspace refactor(workspaces): settle the worktree-create tail by outcome value instead of per-step catches Sep 12, 2026
@coderabbitai

coderabbitai Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: cbdcd838-474c-40c6-a11d-c182d692d862

📥 Commits

Reviewing files that changed from the base of the PR and between dd08199 and 15ec6ed.

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

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


📝 Walkthrough

Walkthrough

The change extracts post-create worktree handling into runWorktreePostCreateSteps. The pipeline reports completion, cancellation, or uncertain visibility. The creation flow settles each outcome explicitly. Activation failures trigger best-effort tab and terminal recovery. Tests cover post-create failures, structured-session outcomes, concurrent creations, pre-create errors, tab preservation, and asynchronous flushing.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 15ec6

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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… 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 u…
Docstring Coverage ⚠️ Warning Docstring coverage is 38.89% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 5 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 identifies the main change: refactoring worktree-creation tail settlement to use outcome values instead of per-step catches.
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 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.

  • 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

  • Outcome-based post-create settlement — new worktree-creation-post-create-steps.ts wraps activation, initial-terminal seeding, after-wake seeding, and the structured launch in one try/catch that returns complete / cancelled / awaiting-visibility and never throws; executeWorktreeCreation settles 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 / primaryTabId that 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-void call sites in worktree-creation-flow.ts now share startWorktreeCreation, whose .catch() stamps status: 'error', logs, and toasts only when the panel is not already showing the error; covers pre-createWorktree failures.
  • 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.ts swaps 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.

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

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

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.ts returns complete / cancelled / awaiting-visibility under one try/catch; executeWorktreeCreation now 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.ts grows to 14 tests; worktree-creation-flow.test.ts flush 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.

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

structuredLaunchAccepted: args.structuredLaunch
}
try {
return await settleCreatedWorkspace(args, progress)

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.

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.

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

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 PostCreateStage recorded before each tail step and passed to the single catch's console.error, so step identity survives collapsing the per-step catches into one.
  • Planless-agent recovery fixed — recoverRevealedWorkspaceSurface no longer passes callerProvidesSurface, 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.ts grows 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.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Fixed on main by #20175; this follow-up refactor is no longer needed.

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