Skip to content

fix(git): route git operations for folder-workspace selectors - #10819

Draft
nwparker wants to merge 17 commits into
mainfrom
nwparker/fix-6357-folder-workspace-git-routing
Draft

nwparker wants to merge 17 commits into
mainfrom
nwparker/fix-6357-folder-workspace-git-routing

Conversation

@nwparker

@nwparker nwparker commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Part of #6357

Draft. Backend routing is done and CI is green. The open question is scope — see Where this is and isn't visible.

What this fixes, in one sentence

Orca's git backend didn't know how to answer "which repo do you mean?" when a workspace is a folder containing several git repos instead of a single checkout — so every git operation on one threw selector_not_found. This teaches it.

The setup

Orca has two kinds of workspace:

  • a git worktree — a checkout Orca made. Exactly one repo. Everything assumed this.
  • a folder workspace — any directory you point Orca at. It may contain several independent repos, or none.

#6357's reporter has the second kind: a container fint/ that is not a git repo, holding fint_api, fint-admin, fint-portal, fint-sales. They opened the container so one agent could work across frontend + backend in a single session.

Given that, the router looked up a worktree for the container, found nothing, and errored — instead of asking which repo inside the folder the operation meant.

BEFORE: git.status  folder:<id>  →  throws selector_not_found
        git.commit  folder:<id>  →  throws selector_not_found
        git.diff    folder:<id>  →  throws selector_not_found

How it decides

Two addressing schemes, chosen by whether the operation carries a file path:

Operations How it routes
Path-bearing diff, stage, unstage, discard Route to the child repo that owns that path — deepest match wins, so a nested repo beats its ancestor. A bulk batch is grouped by owning repo, one git invocation per repo.
Path-less commit, abortMerge, abortRebase, commit-message generation Nothing to route on, so select exactly one child repo, and fail before mutating on 0, >1, or any child that can't be inspected.

status merges every child repo into one list with workspace-relative paths (fint_api/src/app.ts), leaving head/branch/upstream unset because no single repo owns them.

Why it refuses instead of fanning out

This is the design's real content, and the first version of this PR got it wrong (it committed every child repo with a staged index).

Git has no cross-repo transaction. If repo 1 commits and repo 2 fails, there is no rollback — repo 1's commit is a published fact. And neither return shape can describe that honestly: git.commit returns {success, error?}. Reporting success: false implies nothing happened, when something did. Reporting success: true hides a real failure.

So it declines rather than half-committing:

Staged changes span multiple repositories (fint_api, fint-portal).
Commit one repository at a time.

The user keeps their index and picks. An uninspectable child fails the whole operation closed, because that child may be the one holding the staged work.

Where this is and isn't visible

Worth being explicit, because it's the difference between "fixes the reported bug" and "fixes part of it."

✅ Reachable today — but narrowly. The CLI passes selectors through verbatim (normalizeWorktreeSelector, src/cli/selectors.ts:27-32) into git.status (src/cli/handlers/file.ts:187), which dispatches to the exact method this PR patches (rpc/methods/git.ts:109-110 → runtime.getRuntimeGitStatus). So orca file open-changed --worktree folder:<id> goes from selector_not_found to a working merged status.

Scoping that honestly: it's one command. There are no git-namespaced CLI commands at all, and orca file open / file diff route through files.* → resolveRuntimeFileTarget, which already handled folder workspaces on main (orca-runtime.ts:7390-7396) and is untouched here. The user must also pass --worktree folder:<id> explicitly — current/active resolve from worktree.list, which emits <repoId>::<path> ids, not folder: keys. The id is obtainable (orca worktree ps --json emits it; terminals in a folder workspace export ORCA_WORKSPACE_ID=folder:<id>) but it isn't documented for this use: the skill guide lists folder:<folderId> as valid for worktree create --parent-worktree only (skill-guides/orca-cli.md:126).

The larger consumer is the git.* RPC surface generally — the relay exposes all of it (src/relay/git-handler.ts:203-216), and mobile drives it directly.

❌ Not reachable — desktop GUI. The Source Control tab is gitOnly: true (right-sidebar/index.tsx:124) and folder workspaces set isFolder (:85), so right-sidebar-activity-visibility.ts:14-16 filters the tab out entirely, and useGitStatusPolling.ts:81 never fetches the merged status. That gate is on main too, so it isn't a regression — but it does mean this PR alone does not make the GUI's empty changes list populate. Lifting that gate is a separate product change (sizing): a folder workspace has no single branch or upstream, so the panel needs a genuinely different shape.

⚠️ Partly reachable — mobile. Mobile has no folder gate, so git.status/git.diff start working. But branchCompare, upstreamStatus, fetch/pull/push, and history are still unrouted and throw into a retry loop — filed as #11153.

So: which part of #6357 does this close?

#6357 reports two distinct bugs. This closes neither outright, and the linkage is Part of rather than Closes deliberately:

Verification

  • 69/69 across four folder-workspace test files; 3003 passed / 5 skipped / 0 failed across src/main/runtime/
  • CI green on the merge commit: 22 pass / 2 skip / 0 fail
  • tsc --noEmit, oxlint, oxfmt clean; max-lines ratchet passes

Integration tests drive real git repos on disk — real init/commit/merge producing real conflicts and real index.lock contention, not mocks. Mutation-tested: each mechanism disabled individually against the unchanged suite, 0 survivors, each killing a distinct test set.

Representative cases:

✓ K:  commit routes to the one child repo that has a staged index
✓ K2: staging across two repos is refused before either is committed
✓ K5: a child repo that cannot be inspected fails the commit instead of committing around it
✓ K6: a child repo with a corrupt index fails the commit instead of committing around it
✓ K7: a staged file sorting past the status entry cap is still seen as staged
✓ L:  abort targets only the child repo actually mid-merge
✓ L4: two child repos mid-merge is refused rather than aborting an arbitrary one
✓ M:  commit-message generation routes to the same child repo the commit would
✓ M4: cancelling one child repo leaves a sibling repo untouched
✓ refuses a nested repo root instead of routing it to the ancestor repo

Why selection uses a probe, not getStatus

getStatus is built for display and two of its affordances make it unusable for deciding which repo to commit: it catches a failed git read and resolves an empty result (a corrupt index looks identical to a clean repo), and it caps entries at 1000. With >1000 files sorting ahead of the staged one, the staged row falls outside the window — measured at line 1201 on a real repo — and the commit silently goes to a different child repo reporting {success: true}.

Selection instead asks git a yes/no question: git diff --cached --quiet. No entry cap, and a broken index exits 128 instead of looking clean. Verified on real repos:

clean                 → rc=0
staged                → rc=1
corrupt index         → rc=128  "fatal: .git/index: index file smaller than expected"
unborn HEAD + staged  → rc=1    (why not `diff --cached HEAD`, which errors here)

The abort path deliberately keeps getStatus as well, because its gitdir-marker check is the only reliable merge-vs-rebase discriminator — git rev-parse --verify REBASE_HEAD still returns rc=0 after a rebase completes and would report a phantom rebase forever. So abort runs both: the probe supplies fail-loud, getStatus supplies the discriminator.

Trade-offs

  • A commit spanning two repos is refused, not split. Deliberate, per the reasoning above. The message names both repos so the user knows what to do.
  • head/branch/upstream are unset on a merged status, and conflictOperation is unknown when two children conflict rather than reporting one child's state as the workspace's.
  • Bulk staging is not atomic across repos. Resolution is all-or-nothing (one unowned path rejects the batch before any git runs), but execution isn't — a repo failing midway leaves earlier repos staged. Called out in-code at the loop.

Files touched

New folder-workspace-child-repos.ts, folder-workspace-git-operation-routing.ts, folder-workspace-child-repo-probe.ts, plus their tests. Also substantially edits src/main/runtime/orca-runtime.ts (routing entry points, child-repo resolution, commit-message cancel lanes) and orca-runtime-git.ts — that's where most of the review surface is.

Cross-platform

Path handling routes through normalizeRuntimePathForComparison, which folds Windows case and both WSL UNC aliases (wsl.localhost, wsl$) to one canonical key. No / or \ assumptions; all joins go through node:path. SSH/remote hosts use the same RuntimeGitTarget resolution as single-repo worktrees, and the probe dispatches on target.connectionId exactly like every sibling operation — SSH via execNonInteractive, native/WSL via gitExecFileAsync with localGitOptionsForTarget. On the SSH branch a null exitCode, a timeout, or a spawn error all throw rather than defaulting to 0, since defaulting would read as "nothing staged" — the precise false negative this module exists to prevent.

Git baseline: git diff --cached --quiet is well under the 2.25 floor in AGENTS.md — --quiet implies --exit-code, whose rc=1-on-differences contract predates git 2.x. The repo already relies on the same idiom in commit-object-ref.ts and branch-rename.ts.

nwparker and others added 5 commits July 26, 2026 17:07
A folder workspace is a container directory that is not itself a git repo, with
the real repos nested inside it. Every git op addressed to the workspace selector
resolved against the container and failed with selector_not_found, so the Source
Control list came up empty and every diff errored.

Route path-addressed ops (diff, stage, unstage, discard) to whichever child repo
owns the requested path, rebasing the path onto that repo. Bulk ops group their
paths by owning repo so one request can span several repos, and reject the whole
batch if any path is unowned rather than partially applying.

Status has no path to route on, so it fans out across the child repos and merges
their entries under workspace-relative paths — the same addressing the other ops
then resolve. head/branch/upstream stay unset because no single child repo
describes the workspace; every renderer consumer already treats them as optional.

Fixes #6357
git.commit and the merge/rebase aborts carry no path, so the child-repo routing
the rest of this PR uses had nothing to resolve against and they still failed
with selector_not_found. That left the workspace Source Control able to list and
stage files but not commit them — an affordance made reachable without being
made to work.

Commit fans out to every child repo with a staged index, which is exactly the set
the merged status just showed the user as staged; repos with an empty index are
skipped rather than reporting 'nothing to commit'. A partial failure names the
repos that failed instead of collapsing to one blanket result.

Abort targets only the child repos actually in that conflict state, so a no-op
abort settles like it does for a single repo instead of erroring.

Co-authored-by: Orca <[email protected]>
…d-bearing

The two `..` tests both passed with the guard deleted: child repos are already
filtered to those inside the folder root, so any path a match could accept is
inside the folder anyway. Replace the tautological test with one that pins the
real behavior (a `..` path normalizing back inside still routes) and label the
guard as defense-in-depth against the candidate filter widening.

Co-authored-by: Orca <[email protected]>
…allowing them

A child repo whose status read fails silently vanished from the merged status
(indistinguishable from clean) and from the commit set (a "success" that
skipped staged files). A failed abort left a repo conflicted with no trail.
Each now warns with the repo path. Also gives the test fixture a unique temp
dir so concurrent runs stop rm -rf'ing each other mid-test.

Co-authored-by: Orca <[email protected]>
The same directory can be registered twice (imported directly and picked up by
a folder scan). Both copies fanned out, so the merged status listed every file
twice and a commit ran against the repo twice. Also records the bulk-path
grouping's real failure semantics: resolution is all-or-nothing, execution is
not.

Co-authored-by: Orca <[email protected]>
@nwparker

Copy link
Copy Markdown
Contributor Author

Round-1 findings closed — 4 commits since the last review

Commit Closes
c857b294aa MAJOR — commit/abort now fan out across child repos (tests K–L2)
928ab30919 MINOR 2 — dead escape guard + its tautological tests
13874b60ee MINOR 3, 5 — silent fan-out catches; fixture path race
7a8a1ff386 MINOR 4, 6 — atomicity comment; duplicate repo registrations

On MINOR 2 — the reviewer was right, and the first fix attempt was wrong

Deleting the guard left 31/31 green, confirming the finding. My replacement test also passed with the guard deleted, so I probed instead of shipping it:

resolved = /work/fint/fint_api/src/app.ts
insideRoot(/work/sibling-ws) = null
isPathInsideOrEqual(/work/fint/fint_api) = true
listChildRepos considers /work/fint/fint_api under root /work/sibling-ws? false

listFolderWorkspaceChildRepos already bounds candidates to repos under the folder root. Since every child repo ⊆ folder path, any path inside a child repo is necessarily inside the folder — the guard can never reject something a match would have accepted. The misleading test is deleted; the guard stays labeled defense-in-depth.

Regression evidence is now a measured comparison, not an assertion

Same suite run at HEAD and at parent c67aadbc18 in a separate baseline worktree:

Passed Failed files
Baseline c67aadbc18 15345 1 — packaged-cli-assets.test.ts
This branch 15378 1 — packaged-cli-assets.test.ts (same)

+33 tests, zero new failures.

Note for reviewers using this worktree

A // MUTATION: partial failure reported as success line appeared in my live working copy of folder-workspace-child-repos.ts mid-session — a mutation probe run against the shared branch worktree rather than a scratch copy. Caught and reverted before commit (git diff verified clean), and it never reached any pushed commit. Flagging so nobody mistakes a stray probe for intended code.

Still draft — not for merge.

…po instead of fanning out

Git has no cross-repo transaction. Fanning `git.commit` out across every staged
child repo could commit repos 1..k and fail on k+1, and neither {success,error}
nor {ok:true} can describe that half-done state. Three false-success paths came
out of it:

- an unresolvable or unreadable child was dropped to null and never reached the
  summarizer, so another repo committed and the RPC returned success while the
  user's staged files were never attempted
- a failed abort was logged and the method still returned {ok:true}, so the user
  saw success on a still-conflicted repo
- merged status reported the first conflicted child's operation, offering one
  abort button that silently meant whichever repo came first

Commit and abort now select exactly one child — by staged index and by live
conflict state respectively — and fail before mutating anything on 0, >1, or
any repo that could not be inspected. generateRuntimeCommitMessage routes the
same way; it previously threw selector_not_found for every folder workspace.

Also fixes deepest-first child ordering: it sorted on raw path length, so
\\wsl$\Ubuntu\work\repo\nested (30 chars) lost to its own ancestor
\\wsl.localhost\Ubuntu\work\repo (32) and the nested repo's files routed to
the ancestor. Sort on the normalized path instead.

Co-authored-by: Orca <[email protected]>
@nwparker

nwparker commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor Author

What the user sees

The two outcomes of the select-one policy. Rendered from the strings the code actually produces — not a live app capture, and I'd rather label that than imply I drove the real UI. Both strings are copied verbatim from folder-workspace-git-operation-routing.ts and asserted in tests K/K2.

 ONE REPO STAGED → COMMITS IT            TWO REPOS STAGED → REFUSES BEFORE MUTATING
 ● fint_api/     2 staged                ● fint_api/       2 staged
 ○ fint-portal/  clean                   ● fint-portal/    1 staged
 [ Commit ]                              [ Commit ]
 ┌──────────────────────────────┐        ┌────────────────────────────────────────┐
 │ ✓ Committed to fint_api      │        │ Staged changes span multiple           │
 └──────────────────────────────┘        │ repositories (fint-api-repo,           │
                                         │ fint-portal-repo).                     │
                                         │ Commit one repository at a time.       │
                                         └────────────────────────────────────────┘

Before this PR, both cases threw selector_not_found.

The right-hand case is the deliberate trade-off, not a limitation I overlooked: git has no cross-repo transaction, so a fan-out that commits repo 1 and then fails on repo 2 leaves a published commit that neither {success:false} nor {success:true} describes truthfully. Refusing keeps the user's index intact and lets them choose.

@nwparker

nwparker commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Fix proof — measured before/after, same suite run twice

BEFORE = the three impl files reverted to origin/main. AFTER = fix applied (7bd1f59edd). Real on-disk git fixture: real init/commit/merge producing real conflicts, real index.lock contention. No mocks.

Before (main) After (fix)
Behavioral rows 16 failed / 5 passed 0 failed / 21 passed
Full suite — 0 failed / 52 passed

16 tests flipped red → green. Every other behavioral row passed both times — the fix added routing without disturbing existing behavior.

Test Before After
A: file explorer resolves for a folder workspace (merged #6569 path) ✅ PASS ✅ PASS
B: git status lists changes from every child repo, workspace-relative ❌ selector_not_found ✅ PASS
C: git diff for the SAME folder-workspace selector resolves the owning child repo ❌ selector_not_found ✅ PASS
C2: a workspace-relative path escaping the folder does not resolve to another repo ❌ Assertionexpected 'selector_not_found' to contain 'invalid_relative_pa ✅ PASS
D: the folder REPO placeholder selector still reports an empty, non-repo status ✅ PASS ✅ PASS
F: the RPC surface the renderer actually calls succeeds end to end ❌ Assertionexpected { id: 'r1', ok: false, …(2) } to match object { ok: ✅ PASS
H: every file status lists can then be staged, unstaged and discarded ❌ selector_not_found ✅ PASS
I: a bulk request spanning two child repos stages every path in both ❌ selector_not_found ✅ PASS
J: a bulk request naming a path no child repo owns fails instead of partially applying ❌ selector_not_found ✅ PASS
K: commit routes to the one child repo that has a staged index ❌ selector_not_found ✅ PASS
K2: staging across two repos is refused before either is committed ❌ selector_not_found ✅ PASS
K5: a child repo that cannot be inspected fails the commit instead of committing around it ❌ selector_not_found ✅ PASS
K3: committing with nothing staged anywhere reports it instead of silently succeeding ❌ promise rejected "selector_not_found" instead of resolving ✅ PASS
K4: an empty message is rejected for a folder workspace too ✅ PASS ✅ PASS
L: abort targets only the child repo actually mid-merge ❌ promise rejected "selector_not_found" instead of resolving ✅ PASS
L2: aborting when no child repo is mid-operation says so instead of reporting ok ❌ expected [Function] to throw error including 'No repository in this wo ✅ PASS
L3: a failed abort propagates rather than reporting ok on a still-conflicted repo ✅ PASS ✅ PASS
L4: two child repos mid-merge is refused rather than aborting an arbitrary one ❌ expected [Function] to throw error including 'More than one repository ✅ PASS
M: commit-message generation routes to the same child repo the commit would ❌ selector_not_found ✅ PASS
M2: generation reports no staged changes rather than a resolution error ❌ selector_not_found ✅ PASS
E: the real child git worktree resolves fine when its repo is registered ✅ PASS ✅ PASS

31 rows are deliberately excluded from that table and from the flip count: they fail on main with is not a function or exercise folder-workspace-git-operation-routing.ts, a module that doesn't exist on main. Neither has a meaningful "before", and counting them as flips would inflate the number — the honest figure is 16, not 47.

Fixture: container fint/ (not a git repo) holding child repos fint_api/ and fint-portal/, each with a modified and an untracked file, plus a real linked worktree on feature/refund.

Supersedes the before/after table in an earlier comment, which was measured against the since-scrapped fan-out design.

nwparker and others added 2 commits July 26, 2026 21:12
… index probe

`getStatus` is built for display, and two of its display affordances make it
wrong as a selection predicate: it catches a failed git read and resolves an
empty result, and it caps entries at 1000. Under it, "no staged entry" means
*not staged*, *unreadable*, or *truncated* — indistinguishable. Selection that
cannot tell those apart commits a different child repo and reports success.

Replace it for selection with `git diff --cached --quiet`: no entry cap, and a
broken index exits 128 rather than looking clean. The abort path keeps reading
`conflictOperation` from `getStatus` (its gitdir markers are the only reliable
merge-vs-rebase discriminator — REBASE_HEAD survives a *completed* rebase) but
now asserts the index is readable first, so an unreadable repo fails closed
instead of handing the abort to a different one.

Also route commit-message cancellation: generation re-enters by the child's own
selector, so its cancel lane is keyed to that child's path. The folder selector
resolved to no worktree and threw `selector_not_found`, and every caller is
fire-and-forget — Cancel silently did nothing.
@nwparker

Copy link
Copy Markdown
Contributor Author

Round 4 resolved — all three MAJORs fixed in b9b9984

Round 3 fixed what selection does. Round 4 found that how it decided was unsound. I confirmed all three at source level before fixing rather than taking the report on faith.

# Finding Confirmed at Fix Test
1 fail-closed never fired on a real status failure status.ts:270-296 — catches a failed git read and resolves an empty result select on git diff --cached --quiet (rc 128 on a broken index) K6
2 the 1000-entry cap could hide the staged file status.ts:370 exposes didHitLimit; selection ignored it same probe — no entry cap K7
3 Cancel was silently dead orca-runtime.ts:7168 bound straight through; folder selector → selector_not_found, callers fire-and-forget route to every child lane the selector could have started M3

Measured, not assumed

Exit-code contract on real repos:

clean                 rc=0
staged                rc=1
corrupt index         rc=128  "fatal: .git/index: index file smaller than expected"
unborn HEAD + staged  rc=1     (why not `diff --cached HEAD`, which errors here)

For #2, the cap only bites when >1000 entries sort ahead of the staged one. Built that fixture and measured it: the staged row lands at line 1201, outside the 1000-row window. See the image in the PR body.

Two things I got wrong and corrected

REBASE_HEAD is not a usable conflict probe. I intended to replace detectConflictOperation wholesale. Testing it against a real rebase-conflict fixture showed git rev-parse --verify REBASE_HEAD still returns rc=0 after the rebase completes — it would report a phantom rebase forever. So the abort path keeps getStatus for the merge-vs-rebase discriminator and adds the probe only for fail-loud (L5). Narrower change than planned, and correct.

My first K7 was a bad test. It staged all 1200 files, so a staged row still landed inside the cap — it passed under mutation, proving nothing. Rebuilt against measured git ordering, it now fails under mutation with success: false, which is the bug's actual signature: truncation makes the staged repo invisible, leaving zero candidates. The test also asserts its own premise (expect(rowIndex).toBeGreaterThan(1000)) so it can't silently stop exercising the cap.

Verification

  • 2706 passed / 5 skipped / 0 failed across src/main/runtime/ (157 files); 56/56 in the three folder-workspace files
  • 3 mutations, 0 survivors — each kills exactly one test and nothing else, so no test is redundant
  • tsc -p config/tsconfig.node.json clean, oxlint clean
  • Git 2.25 baseline: --quiet implies --exit-code, whose rc=1-on-differences contract predates git 2.x; the repo already uses the same idiom in commit-object-ref.ts and branch-rename.ts
  • Cross-platform: the probe dispatches on target.connectionId like every sibling op — SSH via execNonInteractive, native/WSL via gitExecFileAsync with localGitOptionsForTarget. On SSH a null exitCode, timeout, or spawn error all throw rather than defaulting to 0, since defaulting would read as "nothing staged" — the exact false negative this module exists to prevent.

Still draft, not for merge.

…running in

Cancel fanned out to every child repo in the workspace. Cancellation is keyed
by cwd alone, with no notion of who asked, so a concurrent draft the user
started from a sibling repo's own view was killed too — and the renderer keeps
generation per-worktree precisely so navigating away does not cancel it, which
makes that concurrent draft reachable rather than theoretical.

Record the child selector each folder-workspace generation actually routed to
and cancel only those. A stale Cancel with nothing in flight now signals no
child at all, instead of acting as a kill switch for whatever runs there next.
@nwparker

Copy link
Copy Markdown
Contributor Author

Round-5 MAJOR — confirmed and fixed in f5a11b3

The collateral-cancellation finding is correct, and it was a regression this PR introduced. Verified at source before fixing rather than taking it on faith:

link in the chain evidence
the broadcast really does fan out orca-runtime.ts mapped every listFolderWorkspaceChildRepos result to cancelRuntimeGenerateCommitMessage(id:…)
cancellation cannot tell callers apart commit-message-text-generation.ts:515-535 — cancelTokensByLane keyed by localLaneKey('commit-message', cwd) only; the SSH side keys by (path, 'commit-message')
a concurrent sibling draft is reachable, not theoretical SourceControl.tsx:1075 keeps generation state per-worktree with the comment "so navigating worktrees mid-generation never cancels the in-flight request" — that is precisely the state that survives navigating to the folder workspace

So the doc comment's premise — "both cancel paths are cwd-keyed best-effort no-ops when nothing is in flight" — was only true when nothing else was in flight. It is exactly wrong in the case that matters.

Fix: record the child selector each folder-workspace generation actually routes to (folderWorkspaceCommitMessageLanes, keyed by normalized folder path, cleared in a finally), and cancel only those lanes. This also answers the original reason the broadcast existed — staging can move between generate and cancel, so re-selecting at cancel time can name the wrong repo. Remembering the lane sidesteps re-selection entirely.

Tests — you correctly noted M3 only spied routing and so could not see collateral cancellation. All three now hold a real in-flight generation open:

  • M3 (rewritten) — cancel routes to exactly the lane generation started under
  • M4 (new) — cancelling one child leaves a sibling untouched; each child carries a unique marker file so a routed selector can be named by repo
  • M5 (new) — a stale Cancel with nothing in flight signals no child, so it can't act as a kill switch for whatever runs there next

Mutation-tested: restoring the pre-fix broadcast verbatim fails M3, M4 and M5 and nothing else (24 of 27 still pass).

Verification: 27/27 in the routing suite, 2708 passed / 5 skipped across all of src/main/runtime/, tsc -p config/tsconfig.node.json clean, oxlint clean.

Cross-platform: the lane key goes through normalizeRuntimePathForComparison, the same normalization the child-repo matcher already uses for WSL/UNC path spellings — no new platform assumption.

@nwparker

Copy link
Copy Markdown
Contributor Author

Response — MAJOR confirmed and fixed in f5a11b3

This review landed against the commit before the fix. The finding was correct, it was a regression this PR introduced in the round-4 cancel change, and it's fixed at HEAD.

Verified all three links at source before touching code rather than taking the report on faith:

  1. the broadcast really did fan out to every child;
  2. cancellation is keyed by cwd alone (commit-message-text-generation.ts:515-535, and ssh-git-provider.ts remotely) — no request/origin identity, exactly as reported;
  3. a concurrent sibling draft is genuinely reachable — SourceControl.tsx:1075 keeps generation per-worktree specifically "so navigating worktrees mid-generation never cancels the in-flight request".

The old doc comment's premise ("cwd-keyed best-effort no-ops when nothing is in flight") was false in precisely the case that mattered.

Fix — took the recommended approach: record the child lane each generation actually routes to, cancel only that, clear in a finally. That also retires the reason the broadcast existed — staging can move between generate and cancel, so re-selecting at cancel time can name the wrong repo. Recording the lane sidesteps re-selection entirely.

On "M3 only spies routing and does not detect this collateral cancellation" — accurate, and the reason it couldn't have caught this. M3 was rewritten and M4/M5 added; all three now hold a real in-flight generation open:

  • M3 — cancel routes to the lane generation actually started
  • M4 — sibling repo untouched (unique marker files per child, so a routed selector can be named by repo)
  • M5 — stale cancel with nothing in flight signals no child at all

Mutation-tested: restoring the pre-fix broadcast verbatim fails M3/M4/M5 and nothing else (24/27 still pass). Suite 27/27 green at HEAD, tsc + oxlint clean.

Screenshot evidence of the before/after is committed in be7913c7 and embedded in the PR body — same probe both runs, differing only in routing: PROBE_CANCEL_COUNT 2 (sibling killed) → 1.

On the secondary point about swallowed per-child failures: agreed it's secondary. Kept the swallow with a console.warn so one unreachable repo can't strand the others, given the renderer treats cancel as fire-and-forget.

…pace id and refcount

Round-6 review found two ways the cancel-lane bookkeeping added in f5a11b3 could
still reach the wrong draft.

Keyed by container path, two folder workspaces that share a POSIX path on
different SSH hosts collapse to one entry, so one host's Cancel resolves the
other host's recorded child selector. FolderWorkspace already carries an `id`,
which is host-unique, so key on that instead.

Stored as a Set, two concurrent generations into the same child are one entry.
The first to settle deletes it in its `finally` and the second draft is left
with no lane at all — Cancel becomes a silent no-op. Refcount instead.

M6 pins the multiplicity case, M7 pins the host-isolation case; each dies only
under its own mutation.
@nwparker

Copy link
Copy Markdown
Contributor Author

Round 6 — all three findings verified at source

Two are this PR's regressions and are now fixed in 4a453dc. One is real but pre-exists on origin/main; I'm reporting it rather than folding it in.


✅ Finding 2 — path keying conflates two SSH hosts — ACCEPTED, fixed

Correct. The lane map was keyed by container path, and two folder workspaces can share a POSIX path on different hosts (/home/dev/work on awin and on openssh). They'd collapse to one entry, and one host's Cancel would resolve the other host's recorded child selector and kill its draft.

FolderWorkspace already carries an id (src/shared/types.ts:320-342) that is host-unique, so keying on that gives host isolation for free — no new plumbing.

-  folderPath: folderWorkspace.folderPath,
+  folderWorkspaceId: folderWorkspace.id,

Pinned by M7, which asserts the key list directly rather than probing a normalizer:

expect([...lanes.keys()]).toEqual([FOLDER_WS_ID])
expect([...lanes.keys()].some((key) => key.includes(CONTAINER))).toBe(false)

✅ Finding 3 — Set loses multiplicity — ACCEPTED, fixed

Also correct, and worse than the review framed it. Two clients generating into the same child (two windows on one workspace) produce one Set entry. Whichever settles first runs its finally and deletes it — so the still-running draft has no lane at all, and Cancel becomes a silent no-op. That's the exact failure this PR set out to remove, reintroduced one layer up.

Now a refcount:

lanes.set(childSelector, (lanes.get(childSelector) ?? 0) + 1)
try { ... } finally {
  const remaining = (lanes.get(childSelector) ?? 1) - 1
  if (remaining > 0) { lanes.set(childSelector, remaining) } else { lanes.delete(childSelector) }
  if (lanes.size === 0) { this.folderWorkspaceCommitMessageLanes.delete(key) }
}

⚠️ Finding 1 — cancel exposed before the cwd lane exists — REAL, but pre-existing; not this PR

The mechanism is right. cancelTokensByLane.set(laneKey, cancelToken) runs only after the process spawns (commit-message-text-generation.ts:639), while generateRuntimeCommitMessage first awaits target resolution, settings, the staged-context read and env prep. A Cancel landing in that window finds no token and no-ops.

But this PR never touched that file, and the window is not folder-workspace-specific — the single-repo path has it too:

$ git diff origin/main..HEAD --stat -- src/main/text-generation/commit-message-text-generation.ts
(empty)

$ git show origin/main:src/main/text-generation/commit-message-text-generation.ts | sed -n '639p'
    cancelTokensByLane.set(laneKey, cancelToken)

Same line, same position, on main. Closing it means making the token installable before spawn (or queueing a pending-cancel flag consumed at spawn) across both paths — a change to shared generation lifecycle, not to folder-workspace routing. Scope-creeping it into this PR would mean shipping an untested lifecycle change under a routing PR's review. Proposing it be tracked as its own issue. Say the word if you'd rather it land here and I'll open it as a stacked PR.


Proof the new tests aren't passing for the wrong reason

Mutation-tested — each mutation kills exactly its own test and nothing else:

Mutation Result
Restore Set semantics (lanes.set(sel, 1) + unconditional delete) × M6 — 1 failed, 28 passed
Restore path keying (folderWorkspace.folderPath) × M7 — expected [ Array(1) ] to deeply equal [ 'fw-1' ] — 1 failed, 28 passed

M6 was also rewritten after it proved flaky on first authoring. The original awaited a named handle (await first) after releasing releases[0], but both generations resolve their target concurrently, so which one reaches the spy first isn't ordered — the release didn't reliably belong to the awaited promise. It now waits on releases reaching length 2 and awaits Promise.race, which pins "one has fully released its lane" without assuming an order. 3/3 clean runs in isolation.

Verification

  • folder-workspace-git-routing.test.ts — 29/29
  • Full src/main/runtime/ — 156 files, 2710 passed | 5 skipped
  • tsc --noEmit -p config/tsconfig.node.json — clean
  • oxlint + oxfmt — clean

Cross-platform: no path-literal or separator logic added; the change actually removes a path-comparison dependency in favour of an opaque id, which is what makes the two-SSH-host case safe.

Perf: one Map lookup and one integer increment per generation, on a map bounded by open folder workspaces. Entries are deleted when the last lane drains, so no growth across sessions.

Still draft — not for merge.

@nwparker

Copy link
Copy Markdown
Contributor Author

Filed finding 1 as #10855 — it reproduces on the single-repo path too, so it's tracked independently of this PR.

@nwparker

Copy link
Copy Markdown
Contributor Author

Round 7 — production logic clean; accepted the test-fidelity finding

Round 7 found nothing wrong in 4a453dc's production code. It traced the refcount by hand across concurrent-same-child, two-children-one-workspace and sequential-drain interleavings, and confirmed the increment-before-try gap can't leak (a template-literal build and two Map ops — nothing there can throw or preempt). Perf and cross-platform came back clean from a separate audit too. Both findings were on the test side, and the first one is a fair hit.


✅ MINOR — M7 asserted an implementation detail, not isolation — ACCEPTED, rewritten in c0d718c

Correct, and it's the weakness I already suspected when writing it. The old M7 asserted:

expect([...lanes.keys()]).toEqual([FOLDER_WS_ID])

That holds any time the id is used as the key. It says nothing about whether one workspace's Cancel can reach another's draft — and the fixture only ever had one FolderWorkspace, so there was nothing to be isolated from. It would have passed even if resolveFolderWorkspaceLaunchScope mis-resolved which record a same-path Cancel belongs to.

M7 now registers a second FolderWorkspace record sharing the container path, holds a real generation open under the first, and drives Cancel through the second:

const run = await withInFlightGeneration(runtime, selector)
await runtime.cancelRuntimeGenerateCommitMessage(`id:${folderWorkspaceKey(OTHER_WS_ID)}`)
expect(run.cancelSelectors()).toEqual([])          // other workspace signals no child
await runtime.cancelRuntimeGenerateCommitMessage(selector)
expect(run.cancelSelectors()).toEqual(run.generateSelectors())  // owner can still cancel its own

The mutation result is the real tell. Under path keying it now fails with:

AssertionError: expected [ Array(1) ] to deeply equal []

The other workspace's Cancel actually reached and signalled the first workspace's child — that's the bug reproducing, not a key-spelling mismatch.

One deviation from the suggested fix, stated explicitly: the review suggested giving the second workspace a non-null connectionId to model "another SSH host" literally. That isn't reachable in this fixture — inferFolderWorkspacePathConnection returns {kind: 'ambiguous'} when a connectionId is set over local child repos (folder-workspace-path-status.ts:79-85), and resolveFolderWorkspaceConnectionId throws folder_workspace_connection_ambiguous before any routing happens (orca-runtime.ts:24103-24105). Two records sharing one folderPath is the same collision without dragging in provider machinery. Happy to add a provider-level test separately if you want the SSH path itself covered.

✅ NIT — M6 didn't confirm the refcount drains — ACCEPTED

await Promise.all(both)
// Both settled: the refcount must reach zero rather than stranding a lane at 1.
expect((runtime['folderWorkspaceCommitMessageLanes'] as Map<string, unknown>).size).toBe(0)

Verification

  • folder-workspace-git-routing.test.ts — 29/29
  • Full src/main/runtime/ — 156 files, 2710 passed | 5 skipped
  • Mutations re-run against the rewritten tests: path keying kills M7 only, Set semantics kills M6 only — 1 failed / 28 passed in each case
  • tsc --noEmit, oxlint, oxfmt — clean
  • git diff on orca-runtime.ts vs 4a453dc is empty — this round touched tests only, so the reviewed production logic is byte-identical to what was verified

Perf / cross-platform (separate audit)

No regression, cross-platform safe. Bookkeeping is 4 O(1) map ops per generation; cancel stays O(children-with-in-flight-lanes). Every increment has a matching finally decrement on both resolve and throw, and entries are reclaimed at zero, so nothing grows across sessions. It's reached only from explicit user actions (generate button, create-PR intent, Cancel click) — nothing on keystroke, render or file-watch paths.

Worth noting it's strictly lighter than the parent commit: that version called the regex-based normalizeRuntimePathForComparison on both the generate and cancel paths; this one does a direct id lookup. That also removes the Windows case-folding and WSL UNC-aliasing sensitivity the old key inherited from the normalizer — so the id key is both faster and more portable, not a trade.

Still draft — not for merge.

@nwparker

Copy link
Copy Markdown
Contributor Author

Follow-up: verified M7 is not vacuous.

The obvious way the rewritten M7 could pass for the wrong reason is if Cancel through workspace B never reached the folder-workspace path at all — bailing out early would make expect(run.cancelSelectors()).toEqual([]) trivially true. I probed it rather than reasoning about it: swapping workspace B's selector for a non-folder one (id:not-a-folder-workspace-at-all) gives

PROBE bail-out cancelSelectors = ["id:not-a-folder-workspace-at-all"]
× M7 — 1 failed

A bail-out does not produce []. It falls through the ?? at orca-runtime.ts:7178 to gitCommands.cancelRuntimeGenerateCommitMessage(selector), so the spy records a call and the assertion fails. [] is reachable only when workspace B genuinely resolves as a folder workspace, reaches the lane lookup at :24400, and misses — which is the property under test.

Probe removed; file restored to the committed state (git diff empty), 29/29 green.

…'s spelling

Round 7 was right that M7 asserted an implementation detail. It checked the
lane map's key was the workspace id rather than a path, which holds any time
the id is used as the key and says nothing about whether one workspace's
Cancel can reach another's draft — there was only ever one workspace in the
fixture to be isolated from.

Now a second FolderWorkspace record shares the container path, and Cancel is
driven through *it* while the first has a real generation in flight. Under
path keying the mutation fails with `expected [Array(1)] to deeply equal []` —
the other workspace's Cancel actually signalled the first one's child, which
is the bug, rather than a key spelling mismatch.

Two records sharing one folderPath is the cheapest fixture for that collision.
A literal two-SSH-host version is reachable — project-group scoping keeps each
host's repos out of the other's candidate set, so neither resolves ambiguous —
but it would also need a registered IFilesystemProvider and faked remote git
execution before staged-file detection ran, which buys no extra coverage of
the lane keying this test is about.

M6 also now asserts the refcount drains to zero once both generations settle.
@nwparker
nwparker force-pushed the nwparker/fix-6357-folder-workspace-git-routing branch from c0d718c to a0aceba Compare July 27, 2026 05:48
@nwparker

Copy link
Copy Markdown
Contributor Author

Round 8 — CLEAN on code; one NIT accepted against my commit message

Round 8 found no defect in the code. It independently reproduced both properties rather than taking my word for them, which is what I wanted from this round:

  • M7 is not vacuous. It traced id:folder:fw-2 all the way through parseWorkspaceKey → store lookup → getFolderWorkspacePathStatus and confirmed scope resolution genuinely succeeds for workspace B (resolves {kind:'local'}, real stat() on the on-disk container passes, no selector_not_found), then misses at the lane lookup. It also re-ran the path-keying mutation itself and got + "id:fint-api-repo::…/fint/fint_api" — naming the exact child selector workspace B wrongly signalled. Same conclusion as my probe, reached independently.
  • M6's drain assertion is not racy — each finally completes before its outer promise settles, with no further await.
  • The fixture is a real product state: createFolderWorkspace never checks whether another record already points at that folderPath, so two same-path records are constructible.

✅ NIT — my "not reachable" claim was an overclaim — ACCEPTED, commit message amended

The reviewer is right and I was wrong. I claimed a literal two-SSH-host fixture was unreachable because inferFolderWorkspacePathConnection returns ambiguous. That holds only for my fixture, where no repo carries a projectGroupId — so getFolderScopeCandidateRepos falls through to unfiltered pathRepos, the local repos set hasLocalRepo, and the connectionId branch trips.

With project-group scoping it does not. pathRepos explicitly excludes repos already in the group subtree (folder-workspace-path-status.ts:41-45), so two same-path workspaces in different groups never see each other's repos and both resolve cleanly. I verified that in the source rather than just accepting the correction.

The practical conclusion stands — a working two-host M7 would additionally need a registered IFilesystemProvider and faked remote git execution before staged-file detection ran, and none of that exercises the lane keying under test — but the stated reason was wrong, so the commit message now says "reachable, but buys no extra coverage" instead of "not reachable."

Amended as a0aceba. Message-only: git diff c0d718c..a0aceba is empty, so the reviewed tree is unchanged and 29/29 still green.

Loop status

8 rounds. r3: 3 MAJORs → redesign · r4: 3 MAJORs · r5: 1 MAJOR (self-inflicted) · r6: 2 MAJORs (self-inflicted) + 1 declined as pre-existing (#10855) · r7: code CLEAN, 1 MINOR on test fidelity · r8: code CLEAN, 1 NIT on a commit message. The severity curve has flattened out — findings went from correctness bugs, to a test that proved less than it claimed, to prose in a commit message.

Still draft — not for merge.

@nwparker

Copy link
Copy Markdown
Contributor Author

One linkage change before this merges: Closes #6357 → Part of #6357

Line 1 of the description is Closes #6357, which would auto-close that issue on merge. It shouldn't, because #6357 reports two distinct bugs and this PR fixes one of them.

  • Bug 2 (folder-workspace session, git changes list empty, files fail to open) — this is what the PR fixes. Reproduced locally with no networking: six git RPCs (getRuntimeGitStatus, getRuntimeGitDiff, commitRuntimeGit, abortRuntimeGitMerge, abortRuntimeGitRebase, getRuntimeGitHistory) all throw selector_not_found against a folder-workspace selector.
  • Bug 1 (primary repo view, git changes do list — 24 files — but every diff fails) — not fixed here, and it's the headline symptom with the screenshot.

Bug 1 can't be a selector-routing failure, because that breaks status and diff together. The two calls resolve ownership from different inputs:

path ownership input
git status getSettingsForWorktreeRuntimeOwner(store, worktreeId) — the workspace owner (file-explorer-runtime-owner.ts:5-12)
file diff settingsForRuntimeOwner(activeSettings, file.runtimeEnvironmentId) — the per-tab stamp (useEditorPanelContentState.ts:243)

When the per-tab stamp points at an environment that lacks the worktree, status stays green off the workspace owner while every diff throws — exactly Bug 1. That's the #10859 ownership-translation mechanism, tracked separately (detail).

So: retitle the linkage to Part of #6357 and this is fine to ship on its own merits. Nothing else about the PR changes — it's a real, independently-reproducible fix, and #10859 doesn't affect it.

Two smaller notes while here:

  • The description says the change is scoped to folder-workspace-*.ts and orca-runtime-git.ts; it also substantially edits src/main/runtime/orca-runtime.ts. Worth correcting so reviewers look in the right place.
  • The diff carries two evidence/*.png binaries — probably want those out before merge.

The two-resolver split is read from source at the cited lines. Flagging the linkage rather than changing it, since it's your PR.

@nwparker

Copy link
Copy Markdown
Contributor Author

Independent round-9 review — verified at source, findings below

I re-verified this branch from scratch in a clean worktree rather than trusting the rounds 1–8 write-ups. The parts that were checked are solid; what nobody checked across 8 rounds is whether the routed code is reachable. It mostly isn't.

What independently checks out

Claim Verified how Result
Bug is real resolveRuntimeGitTarget at merge base c67aadbc18 has no folder branch; current origin/main still has no folder-workspace-* module ✅ real, still unfixed on main
60/60 tests ran the three files ✅ 60 passed
No regressions full src/main/runtime/ ✅ 2710 passed / 5 skipped / 0 failed
Mutation testing applied 3 mutations myself on a throwaway copy ✅ 0 survivors — fail-open→7 kills, raw-length sort→2, getStatus predicate→K6+K7
Merges onto current main git merge-tree at 165 commits behind ✅ 0 conflicts; I materialized the merged tree: 60/60 and 2990 runtime tests pass post-merge
tsc / oxlint / max-lines ratchet run ✅ clean

The test suite is genuinely stronger than typical — real on-disk git, mkdtempSync fixtures, K7 asserting its own premise. Mutation testing reproduced exactly as documented. That part of the PR I'd defend.


MAJOR 1 — On desktop, none of this is reachable. The Source Control tab is hard-gated off for folder workspaces.

This is the finding that decides the PR, and it's the one 8 rounds of review never asked.

  • right-sidebar/index.tsx:124 — the source-control activity item is gitOnly: true
  • right-sidebar/index.tsx:85 — isFolder = isFolderWorkspace || …, true for any folder: selector
  • right-sidebar-activity-visibility.ts:14-16 — gitOnly && isFolder → filtered out of the activity bar

So on desktop the Source Control panel never mounts for a folder workspace, and getRuntimeGitStatus / commit / abort are never called with a folder selector. I confirmed this gate is identical on current origin/main, so merging changes nothing a desktop user can see.

Issue #6357 Bug 2 says "the git changes list shows up empty." That's this gate — a renderer-side omission — not selector_not_found in the runtime. The PR fixes a real main-process defect, but not the one the reporter is looking at. Worth confirming against the reporter's actual build before investing further.

MAJOR 2 — A registered nested child repo is double-reported, and discarding the parent's row deletes it

Reproduced on real git, not reasoned about:

$ git status --porcelain=v2 -uall     # in parent A, with registered repo at A/B
? B/

Merged status therefore contains both A/B/ (untracked dir, from A) and A/B/<files> (from B) — contradictory rows for one tree. mergeFolderWorkspaceGitStatus dedupes by repo, never by resulting workspace path.

Routing makes it destructive. For path A/B, folder-workspace-child-repos.ts:74-76 tries B first (deepest), gets rebasedRelativePath === '', and continues to the ancestor A. Discard then runs in A:

$ git clean -ffdx -- ':(literal)B'
Removing B/
$ ls B/work.txt
ls: B/work.txt: No such file or directory     # nested repo gone, .git and uncommitted work included

A '' rebase means "this path is a child repo root" — that should return null, not fall through to the ancestor. This is data loss, and it's the one place the PR's own fail-closed philosophy is inverted.

MAJOR 3 — Mobile is reachable, and half the surface still throws

mobile/src/source-control/use-mobile-git-requests.ts:26 passes worktree: \id:${worktreeId}`with **no folder gate** (unlike desktop), and folder workspaces do surface there. Routed:git.status, git.diff. Not routed, still selector_not_found: git.branchCompare(auto-fires on every status success),git.upstreamStatus/fetch/pull/push(Sync button),git.history`.

Worse, use-mobile-source-control-loaders.ts:224-226 treats selector_not_found as transient and retries it — so the user gets a retry loop then a bare error string, with the branch card silently blank (branch is undefined per the merge design).

MAJOR 4 — Zero SSH coverage on a fail-closed mechanism

Every fixture uses connectionId: null. The PR adds SSH branches in folder-workspace-child-repo-probe.ts:55-77 and 4+ sites in orca-runtime-git.ts, none exercised. The specific uncovered line is the exitCode === null guard (probe:74) whose entire stated purpose is preventing a signal-killed probe reading as "nothing staged" — the exact false negative this module exists for. AGENTS.md mandates SSH consideration; a stub provider covers this without a real host.

MINOR 5 — Status silently drops a child repo; commit hard-fails on identical state

orca-runtime.ts:24216-24219 returns null for a child with no resolved worktree without even the console.warn the adjacent getStatus-failure path emits at :24225. computeResolvedWorktrees has a 5s timeout falling back to {worktrees: []}, so one cold/slow SSH repo vanishes from status indistinguishably from clean — then commit reports "Could not inspect every repository". The asymmetry is the bug; status should warn at minimum.

MINOR 6 — resolveRuntimeGitTargetPathGroups is O(paths × repos log repos) with regex per comparison

orca-runtime.ts:7246 calls matchFolderWorkspaceChildRepo per path, which re-filters and re-sorts every repo inside listFolderWorkspaceChildRepos — each comparison running normalizeRuntimePathForComparison (3-4 regexes). At 50 child repos × 2000 paths that's ~0.6s of synchronous main-process CPU before any git runs. One-line fix: hoist the child-repo list out of the loop.

Bulk discard's non-atomic loop (orca-runtime-git.ts:999-1020) also means repo A's files are irreversibly deleted before repo B throws — strictly worse than the partial-commit case this design explicitly rejects.

MINOR 7 — git init -b needs Git 2.28, above the declared 2.25 baseline

folder-workspace-git-routing.test.ts:42. Every other real-git test uses plain init --quiet (repo-detection.test.ts:58). Won't fail CI, breaks local runs on a baseline binary.

NIT 8 — evidence/ has no precedent

Absent from origin/main, never merged in history; .gitignore:107 ignores /pr-evidence/, suggesting the intended convention is an ignored dir. 260K of PNGs permanent in history.


Recommendation: don't merge as-is — but don't close either

The engineering is real and the fix is correct for what it covers. But MAJOR 2 is data loss and should be fixed regardless of anything else — return null for a '' rebase instead of falling through to the ancestor.

The bigger question is MAJOR 1. As it stands this PR routes a code path that desktop can't reach and mobile can only half-use. Three ways forward:

  1. Fix MAJOR 2 + 4, land as infrastructure, and file the desktop gate (MAJOR 1) and mobile gaps (MAJOR 3) as the follow-ups that actually close [Bug] Worktree in a monorepo, can not see files and git changes #6357 Bug 2. Defensible — the routing has to exist before the gate can be lifted.
  2. Expand to include the gate flip, making it a user-visible fix. Larger, but it's the thing the reporter asked for.
  3. Close if folder-workspace Source Control isn't a product direction — in which case the right fix for [Bug] Worktree in a monorepo, can not see files and git changes #6357 is a clear "not supported here" state instead of selector_not_found.

I'd take (1), with MAJOR 2 fixed first. Happy to do that work — say which.

Verified in a clean worktree at a0aceba: mutation testing re-run independently, nested-repo deletion reproduced on real git, merge-with-main materialized and tested. Prior rounds' fixes all hold up; these are gaps in what was asked, not errors in what was answered.

…g it to the ancestor

An ancestor repo reports a registered nested repo as a single untracked directory
row (`? vendor/sdk/`), so that path is reachable from the merged folder-workspace
status. Matching tried the nested repo first, got an empty rebase, and fell through
to the ancestor — where discard runs `git clean -ffdx -- ':(literal)vendor/sdk'` and
deletes the nested repo wholesale, .git and uncommitted work included.

An empty rebase means the path *is* a child repo root, which addresses no file in
any repo. Refuse it rather than treating it as an ordinary path in the parent.

Also here:
- cover the probe's SSH branch, which had no tests at all. The `exitCode === null`
  guard exists precisely so a signal-killed probe cannot read as "nothing staged";
  defaulting it to 0 now fails a test instead of silently committing another repo.
- warn when status skips an unresolvable child. It dropped out of the merged list
  looking exactly like a clean repo, with no trace, while commit fails closed on
  that same state.
- hoist the child-repo list out of the per-path loop in bulk routing; it re-filtered
  and re-sorted with a regex normalize per comparison on every path.
- `git init -b` needs git 2.28, above the 2.25 baseline in AGENTS.md.

Co-authored-by: Orca <[email protected]>
@nwparker

Copy link
Copy Markdown
Contributor Author

Fixed the data-loss bug and three smaller findings — 4870b75

Landed the items that don't depend on the scoping question. MAJOR 1 (desktop gate) and MAJOR 3 (mobile) are untouched — those are the scope call, below.

MAJOR 2 — nested repo deletion — fixed

matchFolderWorkspaceChildRepo now returns null when the rebase is empty, instead of falling through to the ancestor:

-    if (rebasedRelativePath === null || rebasedRelativePath === '') {
+    if (rebasedRelativePath === null) {
       continue
     }
+    if (rebasedRelativePath === '') {
+      return null
+    }

An empty rebase means the path is a child repo root — it addresses no file in any repo, so routing it to the parent was always wrong.

Regression test added, and I confirmed it isn't vacuous: reverting to the old two-condition continue fails it with the ancestor match reproducing. Note the pre-existing returns null for the repo root itself test passed either way, because its fixture has no ancestor to fall through to; the new one registers both.

MAJOR 4 — SSH coverage — fixed

New folder-workspace-child-repo-probe.test.ts, 8 tests with a stubbed provider (no host needed): rc 0/1/128, exitCode === null, timedOut, spawnError, missing provider, and that the probe runs in the child repo's cwd rather than the container.

Mutation-tested the guard that matters — replacing it with result.exitCode ?? 0 fails exactly throws on a signal-killed probe rather than reading it as "nothing staged" and nothing else. That's the false negative the module exists to prevent, now actually pinned.

MINOR 5 / 6 / 7 — fixed

  • Status now console.warns when it skips an unresolvable child, matching the warn the adjacent getStatus-failure path already emits. Kept best-effort (one cold repo shouldn't blank the workspace) — the asymmetry with commit's fail-closed is intentional, just no longer silent.
  • Hoisted listFolderWorkspaceChildRepos out of the per-path loop in resolveRuntimeGitTargetPathGroups via an optional pre-computed arg.
  • git init -b → git init + symbolic-ref HEAD, since -b needs 2.28 and AGENTS.md declares 2.25.

Verification

  • 69/69 across the four folder-workspace files (was 60; +8 SSH, +1 regression)
  • 2719 passed / 5 skipped / 0 failed across src/main/runtime/ (was 2710)
  • tsc -p config/tsconfig.node.json, oxlint, oxfmt clean
  • Both new mechanisms mutation-tested, each killing exactly its own test

I also re-verified the branch merges onto current main (165 commits behind): git merge-tree gives 0 conflicts, and I materialized the merged tree and ran it — 60/60 and 2990 runtime tests passed there before these commits.


Still open: what is this PR for?

MAJOR 1 stands and it's the deciding question. The Source Control tab is gitOnly: true (right-sidebar/index.tsx:124) and folder workspaces set isFolder (:85), so right-sidebar-activity-visibility.ts:14-16 filters it out — same on current main. No desktop user can reach any of this code.

The routing is now correct and safe, which makes it sound infrastructure. But it doesn't fix what #6357's reporter sees until the gate is lifted, and lifting the gate is a real product decision — a folder workspace has no single HEAD, branch, or upstream, so the panel would need to render a genuinely different shape.

My read: keep this as the infrastructure step, and file the gate flip + the mobile branchCompare/push/pull/history gaps as the follow-ups that actually close Bug 2. But that's your call — it's equally defensible to hold the PR until it's user-visible. Leaving it draft until you decide.

The code-quality gate on main flags import(no-duplicates); the new import
duplicated a shared/types block already present in the file.

Co-authored-by: Orca <[email protected]>
@nwparker

Copy link
Copy Markdown
Contributor Author

Sizing the desktop gate lift — the decision this PR is actually blocked on

Since MAJOR 1 is the deciding question, I traced what it would take to lift the gate rather than leave it as "someone should look at this."

Lifting the activity-bar gate alone gets you a broken panel

right-sidebar-activity-visibility.ts:14-16 is not the only gate — it's just the first one:

  • SourceControl.tsx:5419 — if (!activeWorktree || !activeRepo || !worktreePath) returns "Select a workspace". folderWorkspaceToWorktree stamps repoId: 'folder-workspace:<groupId>' (folder-workspace-worktree.ts:8), which is never inserted into state.repos, so useRepoById returns null and the panel bails immediately.
  • useGitStatusPolling.ts:62,81-82 — activeRepoSupportsGit is false for the same null repo, gating canFetchActiveWorktreeGitStatus. The merged status this PR builds is never fetched by the poller. That's the sharpest statement of the problem.
  • SourceControl.tsx:1193 — isFolder = activeRepo ? isFolderRepo(activeRepo) : false evaluates false with a null repo, so the ~20 downstream isFolder guards stop suppressing anything. Those guards are shaped for a folder repo, not a folder workspace.
  • SourceControl.tsx:873-887 — activeRepoSettings collapses to null, so every RPC loses owner-host routing. That breaks SSH/WSL folder workspaces specifically.

There's no synthetic-Repo precedent to copy. The existing pattern is a synthetic worktree (worktrees.ts:683-712); repos.ts:1302 uses the folder-workspace: string only as a cache key.

Two unrouted RPCs auto-fire on panel open

Not just on user action:

RPC Fires Where
getRuntimeGitUpstreamStatus on open SourceControl.tsx:4991-5008
getRuntimeGitBranchCompare once base ref resolves SourceControl.tsx:4845
getRuntimeGitConflictOperation 3s poll stale-conflict-operation-poll.ts:84
history / submodules / branch diff user-triggered —

Both auto-firing ones land in selector_not_found.

What would render

Given the merge deliberately omits head/branch/upstreamStatus: branch pill blank (worktree-git-identity-display.ts:32-34 returns null for empty branch+head), push/pull/sync render in a wrong state and throw if clicked, Create PR becomes eligible with a synthetic repo and then fails (SourceControl.tsx:1524-1527), branch compare stays blank (fails safe).

Sizing

Not contained. Gate flip + null guards yields a panel that renders a blank branch pill, throws on open, and shows buttons that can't work. The architectural call is: is a folder workspace a repo, or a new multi-repo mode?

  • Synthetic repo — ~6-10 files. Cheaper, but lies to ~200 activeRepo.* reads in an 8200-line component, and branch/upstream/PR stay semantically wrong.
  • Real multi-repo mode — 15-25 files, per-child-repo sections with their own branch/upstream rows, and each unrouted RPC needs a fan-out contract. The {success, error?} shape itself needs revisiting — this PR's own comment (folder-workspace-git-operation-routing.ts:6-9) already notes it can't describe partial multi-repo failure.

My read: the merged-status shape chosen here (workspace-relative paths, no HEAD/branch/upstream) implicitly commits to a stage/commit-only panel. That's a coherent and genuinely smaller third option — flip the gate, add the synthetic repo, and hide the branch/upstream/PR/history/compare block entirely rather than null-guarding it. Roughly 8-12 files. It needs you to accept that folder-workspace Source Control is a changes list, not the full panel.

That's a product decision, so I've stopped here rather than picking one.

One pre-existing bug found while tracing

stale-conflict-operation-poll.ts:84 uses getRightSidebarWorktreeRuntimeSettings, not activeRepoSettings — so it is not gated by activeRepoSupportsGit and likely already fires getRuntimeGitConflictOperation for folder workspaces today, throwing selector_not_found every 3s into the bare catch {} at :92. Independent of this PR (this PR would incidentally fix it, since getRuntimeGitConflictOperation is unrouted but the poll is swallowed either way). Flagging rather than filing, since it's silent.

Traced statically. I did not runtime-confirm that getRuntimeGitUpstreamStatus throws rather than soft-erroring for a folder selector — worth a quick check before finalizing sizing.

nwparker and others added 2 commits July 28, 2026 02:18
…der-workspace-git-routing

# Conflicts:
#	src/main/runtime/orca-runtime.ts
@nwparker

Copy link
Copy Markdown
Contributor Author

Rebased onto current main — was CONFLICTING, now MERGEABLE (bbde718)

Main moved while this sat at 165 commits behind and the branch went to CONFLICTING. One conflict, in orca-runtime.ts, and it was benign: both sides added imports to the same shared/types block. Resolved as the union — GitStatusResult from this branch alongside main's new GitHub/GitLab types.

Also fixed the static analysis failure from 4870b75: the gate that caught it (audit:code-quality:native, import(no-duplicates)) doesn't exist on this branch's base — it landed on main in the 165 commits. My import type { GitStatusResult } duplicated a shared/types block already in the file; folded into the existing one (67c67b1). The merge then made that resolution moot but consistent.

Post-merge verification

Check Result
src/main/runtime/ full suite 3003 passed / 5 skipped / 0 failed (187 files)
Four folder-workspace files 69/69
tsc --noEmit -p config/tsconfig.node.json 0 errors
Conflict markers none; all 7 folder-workspace method references intact

Worth noting the earlier "merges cleanly" claim in my review was accurate when measured — main moved between then and now. That's the hazard of a branch this far behind, and it'll recur if this sits much longer.

CI is running on the merge commit now.

@nwparker

Copy link
Copy Markdown
Contributor Author

CI green on the merge commit — bbde718

22 passed / 2 skipped / 0 failed, and the PR is back to MERGEABLE.

That covers everything actionable I found except the two scope questions, which are yours:

Finding State
MAJOR 2 — nested repo deletion (data loss) fixed 4870b75
MAJOR 4 — no SSH coverage fixed — 8 tests, mutation-verified
MINOR 5/6/7 — silent status drop, O(N·R) match, git init -b fixed
static analysis failure fixed 67c67b1
CONFLICTING after main moved fixed bbde718
MAJOR 1 — desktop gate open — product decision (sizing)
MAJOR 3 — mobile unrouted RPCs open — needs an issue

On the evidence/ NIT — declining my own suggestion

I started to remove the two PNGs and reverted. The PR body embeds them via raw.githubusercontent.com/.../nwparker/fix-6357-folder-workspace-git-routing/evidence/..., so deleting them from the branch breaks the body's images. If you want them out of the diff, they need re-hosting first (drag into a comment, swap the body URLs, then delete). Not worth doing unless you care — flagging so it isn't silently dropped.

What I'd do next

Land it as main-process infrastructure. It's correct, safe, tested, and merges clean — but it is not yet a user-visible fix for #6357, and I've amended the PR body to say that rather than leave the old framing standing. The gate flip is the follow-up that actually closes Bug 2.

If you'd rather this PR be the user-visible fix, say so and I'll take the stage/commit-only panel option (~8-12 files): flip the gate, mint the synthetic repo, hide the branch/upstream/PR/history block instead of null-guarding it.

Still draft — I haven't marked it ready, since which of those two it is changes what "ready" means.

@nwparker

Copy link
Copy Markdown
Contributor Author

Filed MAJOR 3 as #11153 — mobile retries selector_not_found for the folder-workspace git RPCs #10819 doesn't route (branchCompare, upstreamStatus, fetch/pull/push, history). Tracked separately since it's independent of the desktop-gate decision, and mobile is currently the only surface where any of this code is reachable.

That leaves MAJOR 1 (desktop gate) as the sole open item on this PR, and it's the scope call rather than a defect.

@nwparker

Copy link
Copy Markdown
Contributor Author

Rewrote the description — and corrected my own "unreachable" claim

The description now leads with what the PR does, when it helps, and which part of #6357 it closes, instead of opening with a review-round changelog.

One substantive correction to my round-9 review. I said this code was unreachable and implied that meant unreachable everywhere. That was too strong — I'd only checked the desktop GUI. Tracing the CLI shows it is reachable today:

orca file open-changed --worktree folder:<id>
  → src/cli/selectors.ts:27-32   normalizeWorktreeSelector passes 'folder:<id>' through verbatim
  → src/cli/handlers/file.ts:187 client.call('git.status', { worktree })
  → rpc/methods/git.ts:109-110   runtime.getRuntimeGitStatus(params.worktree)   ← patched here

No gate anywhere on that path. The relay exposes the same git.* surface (src/relay/git-handler.ts:203-216), and agents drive Orca through that CLI — which is exactly the "one agent working across frontend + backend" workflow #6357 opens with.

So the accurate framing is per-surface, not a flat yes/no:

Surface Before After
CLI / agents selector_not_found works
Mobile selector_not_found status/diff work; #11153 still open
Desktop GUI tab hidden tab still hidden — needs the gate flip

That makes this a real user-facing fix for the CLI/agent path, and backend groundwork for the GUI. Still Part of #6357 rather than Closes, since the GUI half of Bug 2 and all of Bug 1 (#10859) remain.

Sorry for the earlier overstatement — the desktop finding was right, but I generalized it past what I'd actually checked.

@nwparker

Copy link
Copy Markdown
Contributor Author

Tightening the CLI claim — two details I had wrong

An independent trace of the CLI surface confirmed the routing chain but corrected two things in my previous comment. Both narrow the claim; the direction holds.

1. orca file open / file diff were never broken. I implied the whole orca file family failed for folder workspaces. It didn't — those hit files.open/files.openDiff, which route through resolveRuntimeFileTarget, and that already handled folder workspaces on main:

$ git show origin/main:src/main/runtime/orca-runtime.ts | sed -n '7390,7396p'
    const folderScope = await this.resolveFolderWorkspaceLaunchScope(worktreeSelector)
    if (folderScope?.folderWorkspace) { ... }

Untouched by this PR. The genuinely-fixed CLI command is orca file open-changed — one command, the only CLI callsite that reaches git.status. There are no git-namespaced CLI commands at all.

2. Agents aren't currently steered here. I said "agents drive Orca through that CLI" as if this path were an established agent workflow. The skill guide documents folder:<folderId> for worktree create --parent-worktree only (skill-guides/orca-cli.md:126) and omits it from the general selector list. The id is obtainable — orca worktree ps --json emits it, and folder-workspace terminals export ORCA_WORKSPACE_ID=folder:<id> — so it's reachable, but by an agent that already knows to try it.

What stands: the routing chain is real (selectors.ts:27-32 → file.ts:187 → rpc/methods/git.ts:109 → the patched getRuntimeGitStatus), with no gate on it, and folder:<id> throws selector_not_found on main today. So this is not GUI-dead-code. But the accurate size is one CLI command plus the git.* RPC surface the relay and mobile consume — not "the CLI and agent workflow" broadly.

Description updated to say exactly that.

…der-workspace-git-routing

# Conflicts:
#	src/main/runtime/orca-runtime-git.ts
@nwparker

Copy link
Copy Markdown
Contributor Author

Merged main again (4bdbeb8) — one semantic conflict worth noting

main moved again and this went back to CONFLICTING. This time it wasn't a trivial import collision:

orca-runtime-git.ts — getRuntimeGitStatus. main added sharedLinkPaths inline (#10451: git can't ignore a shared symlink under a directory-only rule, so status is told which untracked entries are Orca's own artifacts). This PR had extracted that same method body into getRuntimeGitStatusForTarget so folder workspaces could fan out across child repos without re-resolving each one.

Taking either side alone would have been wrong:

Resolved by folding main's logic into the shared helper, so it applies to the single-repo path and to every folder-workspace child repo:

const sharedLinkPaths = target.repo ? getWorktreeSharedLinkPaths(target.repo) : []
const sharedOptions = sharedLinkPaths.length > 0 ? { sharedLinkPaths } : {}

Child repos carry a real Repo (resolveChildRepoGitTarget sets it), so they now get #10451's behavior too — which is the correct outcome, not just a compiling one.

Post-merge: src/main/runtime/ 3008 passed / 5 skipped / 0 failed (189 files, up from 3003 — main's new tests included), tsc --noEmit clean, no conflict markers.

Worth flagging as a pattern: this is the second re-merge in a day, and this one had actual semantic overlap. The longer it sits behind main, the more orca-runtime-git.ts and orca-runtime.ts will collide — both are high-traffic files.

This branch has not been deployed

No deployments
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