Skip to content

fix(worktrees): stop a failed worktree scan from being recorded as an authoritative empty listing - #18456

Merged
nwparker merged 3 commits into
mainfrom
nwparker/crash-wsl-scan-failure-laundering
Sep 4, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/crash-wsl-scan-failure-laundering

Conversation

@nwparker

@nwparker nwparker commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​446 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​445
Prod 17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​287 $\color{#cf222e}{\Huge{\mathbf{−}}}$​35 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​252

What

On a Windows host whose WSL distro has gone away (renamed, unregistered, or wedged after a Windows/WSL update), every git worktree list Orca routes through wsl.exe fails with exit 4294967295 and an empty stderr. listWorktrees (pre-change src/main/git/worktree-listing.ts:81-82) caught any failure, logged a warning, and returned [].

That [] was indistinguishable from "this repo genuinely has no worktrees". The detected-worktree scan consumed it through listRepoWorktrees (pre-change src/main/ipc/worktrees/listing/detected-worktree-scan-cache.ts:114,147), detected-provider-listing.ts took the success path and returned authoritative: true, worktrees: [], and the two destructive side effects downstream of that — rememberLocalWorktreeRoots and pruneLineageForMissingRepoWorktrees — ran against an empty truth. The renderer's #1158 retention guard (src/renderer/src/store/slices/degraded-repo-worktree-validity.ts:52-77) only protects rows for repos that are not authoritative, so an authoritative empty listing walked straight past it and the persisted worktrees plus their attached agent tabs were dropped.

Root cause to file:line: src/main/git/worktree-listing.ts:81-82 (pre-change) laundering an arbitrary Git/host failure into [], consumed as authoritative at src/main/ipc/worktrees/listing/detected-worktree-scan-cache.ts:114,147 (pre-change).

Field impact: 1 field report with a user note (murlock1000, Windows, v1.4.195: "The agent tabs are not restoring after update"). The low report count understates it: this is permanent data loss, not a transient glitch. Once the prune runs, the worktree metadata and lineage are gone from the store; repairing the WSL distro afterwards does not bring the tabs back.

The fix, in two parts:

P0 — stop the laundering. src/main/git/worktree-listing.ts extracts the existing softening predicate as isTrueEmptyWorktreeListing(repoPath, err) — repo path ENOENT and really gone, or isNotGitRepositoryError — leaving the two lenient catches byte-equivalent, and adds listWorktreesStrictAllowingTrueEmpty, which is listWorktreesStrict plus exactly those two empties. src/main/git/worktree-scan-cache.ts adds listWorktreesSharedStrictAllowingTrueEmpty under a new scan kind 'strict-true-empty' (a strict joiner must not inherit []; a lenient joiner must not inherit a rejection). src/main/repo-worktrees.ts adds listRepoWorktreesForDetectedScan, which shares listRepoWorktrees' host routing (folder / runtime / SSH paths untouched) but uses the strict local lister. Both detected-scan call sites now use it. The failure propagates out of listDetectedGitWorktrees, so detected-provider-listing.ts:146-170 returns authoritative: false, worktrees: [], the two destructive side effects are never reached, and the #1158 guard keeps the worktrees and their tabs.

P1 — make the failure diagnosable. src/main/git/command-runner/git-process-env.ts sets WSL_UTF8: '1' on win32 (same reason as src/main/wsl/wsl-runner.ts:129, #9010) so wsl.exe stops emitting its own diagnostics as UTF-16LE. New src/main/git/command-runner/wsl-host-failure.ts (readWslHostFailureDiagnostic / annotateWslHostFailure) classifies exit 0xFFFFFFFF + empty stderr on a WSL-routed command as a host failure, strips UTF-16 NULs, and prefixes the error message with the Wsl/Service/WSL_E_* text while preserving code, stdout, stderr and the original message. Wired into git-exec-file.ts around both capture paths, so git.exec spans record it.

P2 — tell the user, and give them a way out. A retained-but-unscannable repo used to be indistinguishable from a healthy one in the sidebar. DetectedWorktreeListResult gains an optional unavailableReason?: string (src/shared/worktree/types.ts), set only on the failed-scan catch in detected-provider-listing.ts from describeWorktreeScanFailure (worktree-listing-diagnostics.ts: first two non-empty lines of the error, so the wsl.exe host failure (distro "…"): … Wsl/Service/WSL_E_* text P1 produces is what arrives). The repo header renders RepoScanUnavailableIndicator (src/renderer/src/components/sidebar/worktree-list/rows/) when a listing is non-authoritative and carries a reason: a destructive-tinted warning glyph whose tooltip states the reason and that existing worktrees are kept, and whose click re-runs fetchWorktrees for the repo's execution host. The two renderer equality checks (detected-worktree-host-merge.ts, worktree-catalog-visibility.ts) include the reason so a changed cause re-renders. A non-authoritative listing without a reason (disconnected SSH host, conflicting owner) renders nothing, as before.

No argv changed, so buildWslExecArgs / buildWslCapturedLoginShellCommand are untouched. Wire: unavailableReason is a new optional field on an existing response type (additive, safe per docs/reference/remote-wire-compatibility.md); authoritative already existed.

Fix evidence

P0 — RED with the production hunk reverted (detected scan put back on the lenient listRepoWorktrees; test file unchanged):

$ ./node_modules/.bin/vitest run src/main/ipc/worktrees/listing/detected-scan-failure-authority.test.ts --config config/vitest.config.ts

  code: 4294967295,
  stdout: 'Error code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND\r\n',
  stderr: ''
}

 ❯ src/main/ipc/worktrees/listing/detected-scan-failure-authority.test.ts (4 tests | 1 failed) 9ms
     × reports a failed scan as non-authoritative and prunes nothing 5ms

⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯

 FAIL  src/main/ipc/worktrees/listing/detected-scan-failure-authority.test.ts > detected worktree listing authority > reports a failed scan as non-authoritative and prunes nothing
AssertionError: expected true to be false // Object.is equality

- Expected
+ Received

- false
+ true

 ❯ src/main/ipc/worktrees/listing/detected-scan-failure-authority.test.ts:78:34
     76|     const result = await listDetected()
     77|
     78|     expect(result.authoritative).toBe(false)
       |                                  ^
     79|     expect(result.source).toBe('metadata-fallback')
     80|     expect(result.worktrees).toEqual([])

 Test Files  1 failed (1)
      Tests  1 failed | 3 passed (4)

P0 — GREEN with the hunk restored:

$ ./node_modules/.bin/vitest run src/main/ipc/worktrees/listing/detected-scan-failure-authority.test.ts --config config/vitest.config.ts

 Test Files  1 passed (1)
      Tests  4 passed (4)
   Duration  623ms

The four cases: WSL host failure → authoritative:false + no roots registered + no lineage prune; fatal: not a git repository → authoritative:true, worktrees:[] + side effects run; repo path ENOENT → authoritative:true, worktrees:[]; healthy scan → authoritative:true with the worktree listed. Only gitExecFileAsync is mocked, so the real worktree-listing → worktree-scan-cache → repo-worktrees → detected-worktree-scan-cache → detected-provider-listing chain executes.

P1 — RED with the annotation call and the WSL_UTF8 assignment reverted (the classifier module was left in place, so its 3 pure unit tests still pass; the 2 wiring tests fail):

$ ./node_modules/.bin/vitest run src/main/git/command-runner/wsl-host-failure.test.ts --config config/vitest.config.ts

+ Received:
undefined

 ❯ src/main/git/command-runner/wsl-host-failure.test.ts:112:56
    110|
    111|   it('sets WSL_UTF8 so wsl.exe explains itself in UTF-8', () => {
    112|     expect(nonInteractiveGitEnv({}, 'win32').WSL_UTF8).toBe('1')
       |                                                        ^
    113|     expect(nonInteractiveGitEnv({}, 'darwin').WSL_UTF8).toBeUndefined()
    114|   })

 FAIL  src/main/git/command-runner/wsl-host-failure.test.ts > WSL-routed git subprocess > reports a dead distro instead of an empty git error
AssertionError: expected 'Command failed: wsl.exe -d kali-linux…' to contain 'Wsl/Service/WSL_E_DISTRO_NOT_FOUND'

Expected: "Wsl/Service/WSL_E_DISTRO_NOT_FOUND"
Received: "Command failed: wsl.exe -d kali-linux --exec sh -lc ..."

 Test Files  1 failed (1)
      Tests  2 failed | 3 passed (5)

P1 — GREEN with the hunks restored:

$ ./node_modules/.bin/vitest run src/main/git/command-runner/wsl-host-failure.test.ts --config config/vitest.config.ts

 Test Files  1 passed (1)
      Tests  5 passed (5)
   Duration  257ms

Live reproduction on a real Windows host (awin, driven through orca terminal on --environment awin, Git Bash) against a live wsl.exe with a distro name that does not exist — this is the exact input shape the classifier keys on:

=== ORCA-PROBE-BEGIN ===
{
  "label": "no WSL_UTF8 (pre-fix env)",
  "exitCode": 4294967295,
  "stderrBytes": 0,
  "stdoutRaw": "\"T\\^@h\\^@e\\^@r\\^@e\\^@ \\^@i\\^@s\\^@ \\^@n\\^@o\\^@ …W\\^@S\\^@L\\^@_\\^@E\\^@_\\^@D\\^@I\\^@S\\^@T\\^@R\\^@O\\^@_\\^@N\\^@O\\^@T\\^@_\\^@F\\^@O\\^@U\\^@N\\^@D\\^@\\r\\^@\\n\\^@\"",
  "classifiedAs": "There is no distribution with the supplied name.\r\nError code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND"
}
{
  "label": "WSL_UTF8=1 (this PR)",
  "exitCode": 4294967295,
  "stderrBytes": 0,
  "stdoutRaw": "\"There is no distribution with the supplied name.\\r\\nError code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND\\r\\n\"",
  "classifiedAs": "There is no distribution with the supplied name.\r\nError code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND"
}
=== ORCA-PROBE-END ===

P2 — RED with the unavailableReason assignment in detected-provider-listing.ts and the equality hunk in worktree-catalog-visibility.ts reverted (indicator component left in place):

$ ./node_modules/.bin/vitest run --config config/vitest.config.ts \
    src/main/ipc/worktrees/listing/detected-scan-failure-authority.test.ts \
    src/renderer/src/store/slices/worktrees/listing/detected-worktree-unavailable-reason.test.ts
     × is part of listing equality 4ms
     × reports a failed scan as non-authoritative and prunes nothing 4ms
     × surfaces the annotated wsl.exe diagnostic as the unavailable reason 1ms
     × retains a WSL repo whose guest directory is gone, and says why 2ms
AssertionError: expected undefined to be 'wsl.exe host failure (distro "kali-li…' // Object.is equality
AssertionError: expected true to be false // Object.is equality
 Test Files  2 failed (2)
      Tests  4 failed | 4 passed (8)

P2 — GREEN with the hunks restored:

 Test Files  3 passed (3)
      Tests  11 passed (11)

(RepoScanUnavailableIndicator.test.tsx: renders nothing for authoritative or reason-less listings; renders the destructive marker for a failed scan and calls fetchWorktrees(repoId, { executionHostId }) on click.)

Live wsl.exe shapes on the real Windows host (awin, Git Bash via orca terminal, Node spawnSync with WSL_UTF8=1, argv identical to resolveCommand's non-login-shell form) — this is the measurement behind Trade-offs 1 and 2:

{"d":"no-such-distro","p":"/tmp","status":4294967295,"ms":29,"stdout":"There is no distribution with the supplied name.\r\nError code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND\r\n","stderr":""}
{"d":"Ubuntu-24.04","p":"/home/neil/does-not-exist-xyz","status":1,"ms":54,"stdout":"","stderr":"bash: line 1: cd: /home/neil/does-not-exist-xyz: No such file or directory\n"}
{"d":"Ubuntu-24.04","p":"/tmp","status":128,"ms":53,"stdout":"","stderr":"fatal: not a git repository (or any of the parent directories): .git\n"}

Row 2 is the deleted-guest-directory shape from Trade-off 1 (exit 1, bash: cd, no ENOENT), now pinned by the retains a WSL repo whose guest directory is gone case. Row 1 is the dead-distro shape and its cost: ~30 ms per spawn. Probe files were removed and the probe terminal closed.

Full verification, all run from the branch working tree:

$ node config/scripts/run-typecheck-projects-in-parallel.mjs
TC_EXIT=0

$ ./node_modules/.bin/vitest run --config config/vitest.config.ts \
    src/main/ipc/worktrees/listing src/main/ipc/worktrees-windows.test.ts src/main/repo-worktrees.test.ts \
    src/main/git/command-runner/wsl-host-failure.test.ts src/renderer/src/store/slices/worktrees/listing \
    src/renderer/src/components/sidebar/worktree-list/rows src/renderer/src/i18n/runtime-required-catalog.test.ts \
    src/renderer/src/i18n/locale-english-regression.test.ts src/renderer/src/store/slices/degraded-repo-worktree-validity.test.ts
 Test Files  15 passed (15)
      Tests  116 passed (116)

$ ./node_modules/.bin/vitest run --config config/vitest.config.ts \
    src/renderer/src/store/slices/worktrees src/renderer/src/components/sidebar
 Test Files  320 passed (320)
      Tests  2817 passed (2817)

$ node config/scripts/check-changed-code-quality.mjs
code quality: 0 new finding(s) across 22 changed file(s).
type-aware code quality: 0 new finding(s) across 22 changed file(s).
React Doctor: 0 new finding(s) across 22 changed file(s).
Changed-code quality gate passed since 4cc0b8de61a6.

$ ./node_modules/.bin/oxlint <changed files>
(no findings)

$ node config/scripts/verify-localization-catalog.mjs --fix   # adds the 3 new en.json leaves
$ node config/scripts/verify-localization-extraction.mjs       # clean

A broad sweep of src/main/ipc src/main/git src/main/runtime src/main/repo-worktrees.test.ts passed 12325 tests / 4 skipped, with one unrelated load flake (src/main/ipc/ephemeral-vm.test.ts, EPIPE writing to a child stdin) that passes in isolation.

What is NOT proven — stated explicitly:

  • The awin probe ran a JavaScript transliteration of wsl-host-failure.ts, not the shipped TypeScript. The Windows host has no build of this branch. What the probe proves is that exit 4294967295 + 0-byte stderr + diagnostic-on-stdout (UTF-16LE without WSL_UTF8, UTF-8 with it) is the genuine wsl.exe host-failure shape and that the classification logic extracts the WSL_E_ code from both encodings. The shipped TypeScript is covered by the unit tests plus the gitExecFileAsync wiring tests above, not by the probe.
  • The renderer half of the chain was not re-executed. degraded-repo-worktree-validity.ts:52-77 → workspace-terminal-row-plan.ts is unchanged by this PR; this fix only changes the authoritative flag that guard reads. That the flag reaches and satisfies the guard was verified by source reading, not by running the renderer. The P2 indicator is unit-tested (mount, click → fetchWorktrees) but was not screenshotted in the built app.
  • No end-to-end reproduction on a genuinely wedged distro with the built app. The scan-level behaviour is pinned by the integration test; the full user-visible "tabs survive the bad update" loop is not.

Host hygiene: the probe file C:\tmp\orca-wsl-probe.cjs was deleted (ls confirms it is gone) and the probe terminal tab was closed.

ELI5

Orca keeps a list of your working folders (worktrees) and pins your agent chat tabs to them. To refresh that list on Windows, it asks the Linux-inside-Windows environment (WSL) "what folders do you have?"

After a Windows update, that Linux environment can vanish or break. When it does, the question fails — and, importantly, it fails silently: the error message comes back completely blank. Orca's old code saw a failed question with no explanation and treated it as if Linux had cheerfully answered "I have zero folders."

Orca believed it. It deleted its record of every worktree for that repo, and the agent tabs attached to them disappeared. That is what the one user who reported this saw: "the agent tabs are not restoring after update." And because Orca had already erased the records, fixing WSL afterwards did not bring the tabs back — they were gone for good.

This change teaches Orca the difference between two answers that used to look identical: "I checked, and there really are zero folders" (safe to clean up) and "I couldn't check" (do nothing, keep everything). Only the first kind now allows anything to be deleted. The second kind is marked as an unreliable answer, and an existing safety net already knows to leave your data alone when the answer is unreliable.

The second half of the change makes the blank error stop being blank. Windows was writing the explanation in a text encoding Orca did not read, so it looked empty; Orca now asks for it in a readable encoding and attaches the real reason ("there is no distribution with that name") to the error. So next time this happens, the logs say why instead of showing an error with no text.

And the third part puts that reason where you can see it: the project's row in the sidebar gets a small warning mark. Hover it and it tells you what went wrong and that your worktrees are being kept; click it and Orca tries the check again.

Trade-offs

This section is a safety disclosure. Read it as one.

  1. A WSL repo whose directory was genuinely deleted will no longer prune. On a native host, a missing repo directory makes Git fail with ENOENT, which stays classified as a true empty and still prunes. Under WSL the spawn cwd is the Windows interop directory, so the guest reports bash: cd: …: No such file or directory with exit 1 (measured on awin, see evidence) — which matches neither true-empty branch — and is classified as a failure → authoritative:false → the repo's rows are retained. This is deliberate and now pinned by a test (retains a WSL repo whose guest directory is gone, and says why): the host side cannot verify a guest path's existence, and parsing a shell error message into "authoritatively gone" would re-open the laundering hole. What the user sees: the repo header shows the warning glyph with the bash: cd: … No such file or directory reason and a retry; the rows stay until the user removes the repo in Orca or the directory comes back. Affects: WSL users who delete a repo directory outside Orca.

  2. Failed detected scans are not negatively cached, so a wedged host re-spawns wsl.exe on every sequential detected-scan refresh. detected-worktree-scan-cache.ts:172-177 writes the 5s TTL entry only after await scan.promise resolves; a rejection only coalesces concurrent callers. Quantified: (a) a dead-distro wsl.exe spawn costs ~30 ms on awin (evidence above), and every scan is serialised through the Git admission tiers; (b) the worktrees:listDetected scan has no periodic driver — it runs at startup (session-referenced repos, then the deferred all-repo pass), on worktrees:changed / repo-count / settings-focus events, and on explicit user actions (add repo, Retry scan, visibility dialogs); (c) the RUNTIME_WORKTREE_RECOVERY_REFRESH_DELAYS_MS burst named in the earlier version of this note goes through session.tabs.list → the runtime's own worktreeScanCache, which already caches a failed local scan for 30 s (worktree-ps-degraded-repo-scan.test.ts: caches a failed local scan instead of respawning Git on every poll), so it costs 1 spawn per repo per 30 s, not 5. Net: a handful of ~30 ms spawns per user-visible event in the failure state, which is not noticeable even on a slow box. Deliberately left as-is rather than adding a failure TTL: the user-driven Retry (P2) is the retry path, and a TTL would make it lie for its duration.

  3. Reduced scan coalescing on the success path. The detected scan previously ran listWorktrees ('lenient'), whose runner calls the shared listWorktreeGraph ('graph'), so it shared one subprocess with every graph reader (registered-worktree-roots-cache.ts:57, hosted-review.ts:74/88, filesystem-source-control-ai-targets.ts:80) and with other lenient readers. The new 'strict-true-empty' kind shares with neither, because a lenient joiner must not inherit a rejection and a strict joiner must not inherit []. Cost while scans succeed: at most one extra git worktree list per repo per 5s TTL when a graph reader overlaps a detected scan, and zero when there is no overlap. Combined with item 2, that bound holds only while scans succeed.

  4. P1 diagnosability covers the execFile path only, not the streaming path. annotateWslHostFailure is imported solely by git-exec-file.ts. git-stream-stdout.ts's onClose still builds new Error(`git exited with ${code}: ${stderr}`) with an empty stderr, and never captures stdout (it tracks only stdoutBytes, streaming bytes to options.onStdout). That is verbatim the second field error shape from the investigation (Error: git exited with 4294967295: at ChildProcess.onClose), and it remains causeless after this PR.

  5. WSL_UTF8 misses the network-git branch. git-exec-file.ts:65-67 uses buildNetworkSshPolicyEnv when useConfiguredSshCommandForNetwork is set (runtime-remote-fetch-controller.ts:193), and that helper builds env via promptGuardGitEnv directly (git-ssh-policy-env.ts:127), never nonInteractiveGitEnv. WSL-routed fetch/push failures on Windows keep the pre-fix UTF-16 mojibake blindness.

  6. WSL_UTF8=1 is assigned unconditionally on win32, overwriting any caller- or user-supplied value (git-process-env.ts:66-70 uses next.WSL_UTF8 = '1', not ??=). Harmless today since nothing in-tree sets it, but it silently discards an explicit WSL_UTF8=0 from the user's environment.

  7. WSL_UTF8=1 is set for all Git on Windows, not just WSL-routed Git. The variable is only read by wsl.exe, so native git.exe is unaffected. The narrower alternative (threading the resolved command into the env builder) would have required restructuring git-exec-file's env/resolution ordering.

  8. annotateWslHostFailure mutates the caught Error's message (prefix) rather than wrapping it. Deliberate: code, stdout, stderr, error identity and every existing message-substring classifier (isNotGitRepositoryError, the direct-Git fallbacks) keep working. error.stack still shows the original head; the span head comes from message and does carry the diagnostic.

  9. The user-facing signal is a header glyph + tooltip, not a banner or notification. P2 surfaces the cause on the repo header of the retained rows with a click-to-retry; it does not toast, does not offer "reconfigure distro" inline (that lives in Project Settings → Windows runtime, one click away via the header menu), and is not shown for a non-authoritative listing that carries no reason (disconnected SSH host — the host section already says so; conflicting stored owner). The copy is the raw diagnostic (wsl.exe host failure (distro "…"): … Wsl/Service/WSL_E_DISTRO_NOT_FOUND), not a friendly rewrite, because the code is what the user searches for. For an SSH repo whose provider call throws while connected, the glyph will show the provider error until the next successful scan.

  10. Remote wire: unavailableReason is a new optional field on DetectedWorktreeListResult, so an old client ignores it and a new client against an old host simply renders no glyph (the field is absent, not false). An old client paired to a new host now sees authoritative:false where it previously saw true for a failed scan — which is exactly the retention behaviour the old client's Fix silent data loss when workspace session hydration fails #1158 guard already implements. The runtime's own listDetected (runtime-managed-worktree-queries.ts) does not set the reason yet, so a runtime-hosted Windows repo with a dead distro is retained but un-badged (follow-up 5).

  11. worktrees:list / worktrees:listAll still answer [] on a failed scan (they carry no authority flag on the wire). Unchanged by this PR — the retention decision is driven by the detected listing, not by these.

Adversarial review

1 round(s), converged clean = true.

Round 1 — no blocking findings. The reviewer independently reproduced every claimed command: GREEN for both new test files (9 tests), and the revert-the-production-hunk experiment went RED exactly as claimed for both P0 (expected true to be false, line 78) and P1 (WSL_UTF8 undefined + missing WSL_E_DISTRO_NOT_FOUND) — confirming the tests are not theatre. pnpm tc and oxlint clean; the failures in the full src/main sweep were load flakes that pass individually and are unrelated to the diff.

The reviewer also verified by source reading the mechanism the PR asserts but does not re-execute: authoritative:false genuinely reaches and satisfies the #1158 retention guard (degraded-repo-worktree-validity.ts:52-77 excludes the repo from both repoIdsWithLoadedWorktrees and repoIdsWithAuthoritativeDetectedWorktrees), fetched-worktree-merge.ts:190 keeps the visible rows, mergeDetectedWorktreesForHost propagates the false flag rather than inheriting the prior true, and every downstream purge site gates on authoritative. The isTrueEmptyWorktreeListing extraction is semantically byte-equivalent to the two lenient catches, the strict lister produces an identical row shape on success, SSH/folder/runtime routing is untouched, there is no new timer or unhandled-rejection path, and the runtime RPC twin (repo-worktree-resolution-scan.ts) was already strict so it needed no change. Verdict: not symptom-suppression — it removes a data-destroying misclassification whose chain the source investigation proved.

Seven non-blocking findings, all ACCEPTED AS DISCLOSED LIMITATIONS rather than fixed in this PR. Each is written up in full in Trade-offs above; nothing was rebutted. Residual risk per item:

  • WSL deleted-repo-dir never prunes again (Trade-off 1) — accepted and now pinned by a test built from the shape measured on the real host; the user sees why on the header. Residual: stale rows persist until removed in Orca.
  • Lost negative caching on failed scans (Trade-off 2) — accepted after measurement: ~30 ms per spawn, event-driven only, and the recovery burst already goes through a 30 s failure cache on the runtime side. Not worth a second cache.
  • Coalescing loss wider than first stated (Trade-off 3) — accepted and the bound restated honestly; the original "one extra spawn per repo per 5s" claim was corrected to note it holds only while scans succeed.
  • Streaming path still causeless (Trade-off 4) — accepted; the second field error shape is not covered. Filed as a follow-up.
  • buildNetworkSshPolicyEnv misses WSL_UTF8 (Trade-off 5) — accepted; WSL-routed fetch/push on Windows keeps the mojibake blindness. Filed as a follow-up.
  • Unconditional WSL_UTF8 assignment instead of ??= (Trade-off 6) — accepted as harmless today (nothing in-tree sets it) and left as a one-line follow-up rather than churning the diff.
  • No user-facing signal after the fix (Trade-off 9) — addressed in P2: header glyph carrying the reason, click to retry. Residual: glyph-only, no toast; runtime-hosted repos not yet badged.

Follow-ups

  1. Pin the WSL deleted-repo-directory classification with a test. Done in this PR (retention kept, test added from the measured shape). A guest-side existence probe that could safely promote it to a true empty remains a possible later refinement.
  2. Annotate WSL host failures on the streaming Git path. git-stream-stdout.ts's onClose builds git exited with ${code}: ${stderr} with an empty stderr and discards stdout (it counts stdoutBytes and forwards bytes to options.onStdout). Capture a bounded stdout tail on non-zero exit and run it through readWslHostFailureDiagnostic, so the Error: git exited with 4294967295 shape from the field bundle also carries a cause.
  3. Route buildNetworkSshPolicyEnv through nonInteractiveGitEnv (or add WSL_UTF8 to it). git-ssh-policy-env.ts:127 builds env from promptGuardGitEnv directly, so the useConfiguredSshCommandForNetwork branch at git-exec-file.ts:65-67 (used by runtime-remote-fetch-controller.ts:193) misses the UTF-8 fix for WSL-routed fetch/push on Windows.
  4. Cache failed detected scans negatively. Measured and deliberately not done (Trade-off 2).
  5. Extend the scan-failure signal to runtime-hosted repos. runtime-managed-worktree-queries.ts listDetected returns authoritative: scan.ok without a reason (its scanRepo collapses the error to { ok: false }), so a Windows repo served by a paired runtime is retained but shows no glyph. Thread the caught error through RuntimeWorktreeScanResult and set unavailableReason there too.
  6. Default rather than overwrite WSL_UTF8. One-liner: git-process-env.ts:69 should use next.WSL_UTF8 ??= '1' so an explicit user-set value is respected.
  7. Consider restoring cross-kind scan coalescing. The 'strict-true-empty' kind cannot share a subprocess with 'lenient' or 'graph' because the joiners disagree about how to treat a failure. A shared scan that returns a discriminated result (rows or the raw failure) and lets each joiner apply its own softening would recover the coalescing without re-introducing the laundering.

…itative empty listing

A `git worktree list` that could not run at all — a WSL distro that stopped
resolving, a hung mount, a git binary that errored — was softened to `[]` by the
lenient listing path, so the detected scan published it as
`authoritative: true, worktrees: []`. That disables the #1158 retention guard,
drops every persisted tab for the repo, and the pruned session is written back to
disk on the next launch. The loss is permanent, not a transient glitch.

Route the detected scan through a strict listing that still reports the two
genuinely empty states (repo path gone, not a Git repo) as `[]`. Everything else
rejects, so the existing catch answers `authoritative: false` and the destructive
halves (`rememberLocalWorktreeRoots`, `pruneLineageForMissingRepoWorktrees`)
never see a failed scan.

Also make the failure readable: wsl.exe reports its own launch failures as exit
0xFFFFFFFF with an EMPTY stderr and the `Wsl/Service/WSL_E_*` line on stdout as
UTF-16LE, which is why the field bundle carried a git error with no text. Set
WSL_UTF8 for WSL-routed git (matching the wsl runner, #9010) and attach that
stdout diagnostic to the error so `git.exec` spans name the cause.
@coderabbitai

coderabbitai Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: f0c4b833-bc6b-4790-a935-1775846c7710

📥 Commits

Reviewing files that changed from the base of the PR and between b6f453d and c008f39.

📒 Files selected for processing (23)
  • src/main/git/command-runner/git-exec-file.ts
  • src/main/git/command-runner/git-process-env.ts
  • src/main/git/command-runner/wsl-host-failure.test.ts
  • src/main/git/command-runner/wsl-host-failure.ts
  • src/main/git/worktree-listing.ts
  • src/main/git/worktree-scan-cache.ts
  • src/main/git/worktree.ts
  • src/main/ipc/worktrees-test-module-mocks.ts
  • src/main/ipc/worktrees-windows.test.ts
  • src/main/ipc/worktrees/listing/detected-provider-listing.ts
  • src/main/ipc/worktrees/listing/detected-scan-failure-authority.test.ts
  • src/main/ipc/worktrees/listing/detected-worktree-scan-cache.ts
  • src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts
  • src/main/ipc/worktrees/listing/worktree-listing-diagnostics.ts
  • src/main/repo-worktrees.ts
  • src/renderer/src/components/sidebar/worktree-list/rows/RepoScanUnavailableIndicator.test.tsx
  • src/renderer/src/components/sidebar/worktree-list/rows/RepoScanUnavailableIndicator.tsx
  • src/renderer/src/components/sidebar/worktree-list/rows/SectionHeader.tsx
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/store/slices/worktrees/listing/detected-worktree-host-merge.ts
  • src/renderer/src/store/slices/worktrees/listing/detected-worktree-unavailable-reason.test.ts
  • src/renderer/src/store/slices/worktrees/listing/worktree-catalog-visibility.ts
  • src/shared/worktree/types.ts

📝 Walkthrough

Walkthrough

The change adds WSL host-failure decoding and error annotation for failed Windows Git commands. Windows Git environments now request UTF-8 WSL output. Worktree scanning now distinguishes missing or non-repository paths from Git and WSL failures. Detected scans use the stricter behavior and report failed scans as non-authoritative. Tests cover diagnostics, encoding, scan caching, authority, authorization roots, lineage cleanup, and unavailable-reason state.

Merge Risk: ⚪ Minimal · up to 9584f

Failed Git or WSL worktree scans no longer authorize an empty result that could remove saved worktree metadata or tabs, while genuine missing and non-repository paths remain empty. No current merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.83% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 13 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description provides extensive technical context, rationale, trade-offs, and test evidence. However, it omits required template sections, leaves the mandatory linked issue as Fixes #, and does n… Add a valid linked issue number, add the missing required headings and content for Why, Visual Proof, Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist. For the sidebar indicator change, attach before/after…
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly identifies the primary change: failed worktree scans no longer become authoritative empty listings. It is concise and specific.
Full details: Description check

Explanation

The description provides extensive technical context, rationale, trade-offs, and test evidence. However, it omits required template sections, leaves the mandatory linked issue as Fixes #, and does not provide the required visual-proof declaration or attachments for the UI behavior change.

Resolution

Add a valid linked issue number, add the missing required headings and content for Why, Visual Proof, Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist. For the sidebar indicator change, attach before/after visual proof; if visual proof is not possible, explicitly explain why under Visual Proof.

  • Fix all pre-merge checks with AI
✨ Finishing Touches
📝 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

  • P0 de-laundering — listWorktreesStrictAllowingTrueEmpty (plus a new 'strict-true-empty' scan kind) rejects any Git/host failure except the two true empties, so a dead WSL distro can no longer be published as an authoritative empty listing.
  • Host-routing refactor — listRepoWorktreesForDetectedScan shares listRepoWorktrees' folder/SSH/runtime routing via listRoutedRepoWorktrees, changing only the local lister; both detected-scan call sites switch to it.
  • P1 diagnosability — WSL_UTF8=1 on win32 plus readWslHostFailureDiagnostic/annotateWslHostFailure classify exit 0xFFFFFFFF + empty stderr and prefix the git.exec span with the WSL_E_* text.
  • Tests — the authority integration test (detected-scan-failure-authority.test.ts) exercises the real capability-cache rethrow path with exact authoritative assertions, and the classifier/wiring tests are non-theatre (both go RED with the production hunk reverted).

I independently traced the rejection through CapabilityProbeCache.runWithFallback (rethrows non-unsupported errors), confirmed authoritative: false reaches the #1158 renderer guard, and verified the extraction is byte-equivalent to the two lenient catches. The disclosed trade-offs (WSL deleted-dir retention, lost negative caching, coalescing loss) are real but conservative, and the follow-up list covers them.

ℹ️ Adjacent to trade-off 4: the buffer and sync exec paths also miss WSL_UTF8

gitExecFileAsyncBuffer (git-exec-file.ts:228) and gitExecFileSync both build env via untranslatedGitOutputEnv, not nonInteractiveGitEnv, and neither runs through the capture() wrapper that applies annotateWslHostFailure. A dead distro on a git show blob read or a sync git command therefore still reaches telemetry as UTF-16 mojibake with no cause. Out of scope for the worktree-scan data-loss this PR fixes, and the same class as the already-disclosed streaming/network gaps, but worth folding into follow-up 2 so the diagnosability story is complete.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…ader with a retry

A failed scan now travels with its reason (optional unavailableReason on
DetectedWorktreeListResult), the repo header shows it with click-to-retry,
and the WSL deleted-guest-directory shape measured on a real Windows host is
pinned as retained-not-pruned.

@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

The second commit builds the P2 user-facing layer on top of the already-reviewed P0/P1 de-laundering fix, all scoped to surfacing a retained-but-unscannable repo's cause:

  • unavailableReason on the detected listing — DetectedWorktreeListResult gains an optional unavailableReason?: string (src/shared/worktree/types.ts), additive and wire-safe; detected-provider-listing.ts sets it from describeWorktreeScanFailure(err) on both the local-failure and provider-threw-while-connected SSH branches, while the disconnected-SSH and conflicting-owner paths correctly stay reason-less (no glyph).
  • describeWorktreeScanFailure — extracts the first two non-empty lines of the error message (the classifier's summary plus its WSL_E_* code, dropping the raw command that follows), capped at 240 chars with a no-diagnostic fallback.
  • RepoScanUnavailableIndicator — a destructive-tinted header glyph rendered only for !authoritative && unavailableReason, whose tooltip states the reason and that worktrees are kept, and whose click re-runs fetchWorktrees for the repo's execution host; wired into SectionHeader.tsx behind isRepoHeader.
  • Equality + i18n — unavailableReason folded into both mergeDetectedWorktreesForHost and areDetectedWorktreeResultsEqual so a changed cause re-renders, plus three auto.components.sidebar.RepoScanUnavailableIndicator leaves in en.json.

The two new test files (RepoScanUnavailableIndicator.test.tsx, detected-worktree-unavailable-reason.test.ts) plus the extended authority test are non-theatre — I ran all four new/changed files (16 tests) green locally, and the assertions pin exact reasons and authority flags rather than loose truthiness.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

# Conflicts:
#	src/main/ipc/worktrees/listing/detected-provider-listing.ts
@coderabbitai

coderabbitai Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@nwparker
nwparker merged commit d3501f7 into main Sep 4, 2026
3 of 4 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… authoritative empty listing (stablyai#18456)

* fix(worktrees): stop a failed worktree scan from pruning as an authoritative empty listing

A `git worktree list` that could not run at all — a WSL distro that stopped
resolving, a hung mount, a git binary that errored — was softened to `[]` by the
lenient listing path, so the detected scan published it as
`authoritative: true, worktrees: []`. That disables the stablyai#1158 retention guard,
drops every persisted tab for the repo, and the pruned session is written back to
disk on the next launch. The loss is permanent, not a transient glitch.

Route the detected scan through a strict listing that still reports the two
genuinely empty states (repo path gone, not a Git repo) as `[]`. Everything else
rejects, so the existing catch answers `authoritative: false` and the destructive
halves (`rememberLocalWorktreeRoots`, `pruneLineageForMissingRepoWorktrees`)
never see a failed scan.

Also make the failure readable: wsl.exe reports its own launch failures as exit
0xFFFFFFFF with an EMPTY stderr and the `Wsl/Service/WSL_E_*` line on stdout as
UTF-16LE, which is why the field bundle carried a git error with no text. Set
WSL_UTF8 for WSL-routed git (matching the wsl runner, stablyai#9010) and attach that
stdout diagnostic to the error so `git.exec` spans name the cause.

* fix(worktrees): surface a failed worktree scan's cause on the repo header with a retry

A failed scan now travels with its reason (optional unavailableReason on
DetectedWorktreeListResult), the repo header shows it with click-to-retry,
and the WSL deleted-guest-directory shape measured on a real Windows host is
pinned as retained-not-pruned.
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