Skip to content

Keep showing your workspaces when a project is too slow to answer instead of reporting zero - #12222

Merged
nwparker merged 7 commits into
mainfrom
nwparker/bugbash-11869
Aug 4, 2026
Merged

nwparker merged 7 commits into
mainfrom
nwparker/bugbash-11869

Conversation

@nwparker

@nwparker nwparker commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

worktree.ps is the only catalog source for Orca Mobile, and it could silently publish an empty workspace list for a host that was full of workspaces.

In computeResolvedWorktrees (src/main/runtime/orca-runtime.ts:27688) every per-repo git scan was wrapped in withTimeout(..., RESOLVED_WORKTREE_REPO_TIMEOUT_MS, { ok: false, worktrees: [] }). The timeout fallback was zero rows — which threw away the degraded-but-useful fallback the very same code path builds on a fast failure: listRepoWorktreesForResolutionUncached (src/main/runtime/orca-runtime.ts:27856, :27861) returns { ok: false, worktrees: this.listStoredWorktreesForResolution(repo) }, commented "keep persisted rows … instead of zero rows". A scan that was merely slow (WAN/Tailscale SSH round trips, a loaded remote box, a wedged local git, Promise.all fan-out across many repos) was therefore strictly worse than a scan that failed outright. The resulting { worktrees: [], totalCount: 0 } is byte-indistinguishable from "this host genuinely has no workspaces", so mobile rendered "0 worktrees" while the notification deep-link path — which never reads the catalog — kept working.

The timeout branch now restores persisted rows, the same degraded row shape (head: '', branch: '') already shipping today for disconnected SSH repos.

A rejected scan is left exactly as it was, and the code now actually enforces that. withTimeout (src/main/runtime/orca-runtime.ts:33701) resolves its fallback on rejection as well as on timeout (promise.then(v => resolve(v), () => resolve(fallback))), so a bare null fallback would not be a timeout-only sentinel — a rejection would reach it too. The scan promise therefore gets an explicit .catch(() => ({ ok: false, worktrees: [] })) before it is handed to withTimeout, so null can only mean "timed out". That matters because resolveWorktreeSelector (src/main/runtime/orca-runtime.ts:27057) has an intentional store-only id fallback gated on repo?.connectionId, and orca-runtime.test.ts:36228 pins that a rejected local scan must still produce selector_not_found. Two dedicated tests pin the rejection contract directly (catalog shape and selector_not_found). The ?? also keeps the store read lazy — it never runs on the healthy path.

listStoredSshWorktreesForResolution is renamed to listStoredWorktreesForResolution (src/main/runtime/orca-runtime.ts:27865) because the new call site is repo-kind-agnostic. Its body reads only store.getAllWorktreeMeta(), store.getRepos(), splitWorktreeId, getRepoExecutionHostId and areWorktreePathsEqual — no git binary, no connection, no path-separator assumption. This is also why the reporter's headless orca serve case is covered: a remote server holds its repos with no connectionId, so its scans take the local branch, and a hung local scan now yields persisted rows too.

Because the helper is no longer SSH-only, it also had to grow the execution-host ownership gate its siblings in src/main/ipc/worktrees.ts already apply (:736, :827-828, :1119-1123). One repo id can be registered on more than one execution host — that invariant is spelled out at src/main/persistence.ts:4611 and src/main/ipc/repos.ts:2056 — so without the gate a stalled host republished the other host's persisted rows under its own id. The healthy host's real row lost: the catalog kept the blank head/branch of the degraded copy. listStoredWorktreesForResolution (:27879) now uses the same predicate as hasConflictingStoredWorktreeOwner (src/main/ipc/worktrees.ts:1119) — meta.hostId ? meta.hostId !== expectedHostId : repoOwnerCount > 1 — so a stamped row belongs only to its own host, and an unstamped row is claimable only when the repo id has a single owner. The single-host case the fix exists for (the reporter's directly-paired orca serve, one owner, stamped or unstamped) is unaffected, and there is a test pinning that.

One deliberate behavior change falls out of that gate: a persisted worktree meta stamped hostId: 'local' under a repo that was later converted to SSH is now skipped by the degraded fallback (the old SSH-only helper had no gate and would have restored it), which matches the gate the shipped desktop path listDisconnectedSshWorktrees (src/main/ipc/worktrees.ts:826-828) already applies to those same rows.

Everything destructive stays gated on scan.ok: pruneLineageForMissingRepoWorktrees (:27698) still does not run on a degraded result, and worktreeScanCache (:27826) still only caches ok results returned from listRepoWorktreesForResolution, which this fallback never enters. What counts as a successful scan is deliberately unchanged, so no repo becomes uncacheable and no extra git worktree list is spawned.

Scope: this fixes part of #11869, not all of it

Issue #11869 reports two things. This PR addresses one of them.

Fixed here: a repo scan that stalls past the 5s per-repo budget no longer publishes a healthy-looking empty catalog. That is the failure mode that makes a fully populated host render as "0 worktrees" on mobile while the notification deep link still opens the workspace, and it is the mode most likely to hit a Tailscale/WAN-attached runtime.

Not fixed here:

  • Desktop Runtime Environments are still not merged into the mobile host list. Mobile paired to the Mac still sees only the Mac's own repos. That is a product-shape question (item 1 in the reporter's "Ask") and needs its own change.
  • A remote scan that fails fast can still publish zero rows as authoritative. src/relay/git-handler.ts:1430 ends git.listWorktrees with .catch(() => []), so a missing git binary, an unmounted repo path or a permission error on the remote host arrives as an empty array over a successful RPC. listRepoWorktreesForResolutionUncached then yields { ok: true, worktrees: [] }, which prunes lineage and shows an empty repo. That is a pre-existing bug on the relay side, it is not touched by this diff, and it should be fixed where the error is swallowed rather than by inferring failure from row counts in the runtime (see below).

Because of the above, this PR does not close #11869. It relates to it.

Relates to #11869

Rejected approach: treating a zero-row local scan as a failed scan

An earlier revision of this branch inferred failure from row count — git worktree list always reports the main worktree, so zero rows implies git never answered. It was reverted, because worktreeScanCache.set is gated on result.ok (:27822, set at :27826): a permanently zero-row repo (registered path on an unmounted volume, project folder deleted in Finder, an agent-scratch repo root under .claude/worktrees/… that was cleaned up — all of which listWorktrees turns into [] at src/main/git/worktree.ts:770-775) would never be cached again. Instead of one scan per 30s (or per 5min for agent-scratch roots, a TTL added specifically to cut a measured ~128 git execs/min), it would re-spawn git worktree list on every resolved-snapshot recompute — ~1/s under a foregrounded phone, forever, since that state never self-heals. It also silently converted two pre-existing contract tests. A test now pins the caching invariant so this cannot be reintroduced by accident.

ELI5

Orca asks each of your projects "which workspaces do you have?" and waits up to five seconds for an answer. If a project was just being slow — a laptop on a distant network, a busy remote machine — Orca used to give up and report that the project had no workspaces at all, with no warning that anything had gone wrong. On your phone, a host packed with work looked completely empty, even though tapping a notification still opened the right workspace.

Now, when a project is too slow to answer, Orca shows the workspaces it already remembers from last time instead of showing nothing. The branch name next to them may be blank until the real answer arrives, but the workspaces are there and you can tap them.

Nothing changes when a project answers quickly, and nothing changes when a project answers with a genuine error — an error is still treated as a real answer.

Fix proof

Regression suite src/main/runtime/worktree-ps-degraded-repo-scan.test.ts, run against the unchanged source — 4 of the 15 cases fail (the stall cases that motivated the PR; the rejection-contract, caching and ownership cases are checked separately below):

 FAIL  src/main/runtime/worktree-ps-degraded-repo-scan.test.ts > worktree.ps on a degraded repo scan > keeps persisted worktrees when a remote scan stalls past the per-repo budget
AssertionError: expected [] to include 'repo-remote::/home/user/projects/app-…'

 FAIL  src/main/runtime/worktree-ps-degraded-repo-scan.test.ts > worktree.ps on a degraded repo scan > keeps persisted worktrees when a local scan stalls past the per-repo budget
AssertionError: expected [] to include 'repo-remote::/home/user/projects/app-…'

 FAIL  src/main/runtime/worktree-ps-degraded-repo-scan.test.ts > worktree.ps on a degraded repo scan > restores persisted rows stamped for this host when its only owner stalls
AssertionError: expected [] to include 'repo-remote::/home/user/projects/app-…'

 FAIL  src/main/runtime/worktree-ps-degraded-repo-scan.test.ts > worktree.ps on a degraded repo scan > lists restored worktrees while a scan is stalled and still hides agent scratch
AssertionError: expected [] to include 'repo-remote::/home/user/projects/app-…'

With the timeout fallback in place but the rejection not absorbed (no .catch), the two rejection cases fail:

 × treats a rejected scan as a real answer instead of restoring persisted worktrees
 × still reports selector_not_found for a local worktree when the scan rejects

With the reverted zero-row guard reinstated, the caching case fails:

 × caches a zero-row local scan instead of rescanning on every poll

With the timeout fallback in place but without the execution-host ownership gate, the two co-hosted-repo cases fail — the stalled host's blank row wins over the healthy host's real one:

 × does not overwrite another execution host's healthy rows when this host's scan stalls
   AssertionError: expected '' to be 'feature'
 × does not claim an unstamped persisted row when the repo id is registered on two hosts
   AssertionError: expected 'local' to be 'ssh:ssh-remote-1'

After the fix:

$ npx vitest run --config config/vitest.config.ts src/main/runtime/worktree-ps-degraded-repo-scan.test.ts

 Test Files  1 passed (1)
      Tests  15 passed (15)

The fifteen cases cover: remote stall restores rows; remote unreachable (fast failure) control; local stall restores rows (the reporter's headless orca serve shape); a stamped single-owner row still restores (the ownership gate must not cost the fix its primary case); a rejected scan does not restore rows; a rejected scan still yields selector_not_found; a zero-row local scan stays cached (no rescan storm); a permanent stall does not re-spawn git worktree list on later polls; a stalled host does not overwrite a co-hosted host's healthy rows; an unstamped row is not claimed when the repo id has two owners; a healthy scan still drops a removed worktree (the fallback never leaks onto the ok path); lineage pruning stays off during a stall; a degraded (non-ok) scan is not cached, so the next poll rescans instead of pinning the repo to persisted rows; getAllWorktreeMeta is not re-read on a healthy scan (laziness); and worktree.list shows the restored rows while still hiding agent-scratch paths.

No regressions

Full src/main/runtime/ suite (which includes the ~1,000-test orca-runtime.test.ts, all the worktree.ps / resolved-snapshot / lineage-pruning / scan-cache / visibility assertions, the worktree RPC method suites under src/main/runtime/rpc/methods/, and runtime-metadata-ownership-watch). The ownership-predicate suites this gate mirrors live outside that path (src/main/ipc/worktrees.*, src/shared/worktree-ownership.test.ts) and are not covered by this run — no file in either location is touched by this diff:

$ npx vitest run --config config/vitest.config.ts src/main/runtime/

 Test Files  219 passed | 1 skipped (220)
      Tests  3434 passed | 6 skipped (3440)

orca-runtime.test.ts on its own, including the two contract tests this change was specifically shaped around (does not prune lineage when a runtime local worktree scan fails, returns a non-authoritative detected list when a runtime local worktree scan fails) — both are unmodified by this PR:

$ npx vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/worktree-ps-degraded-repo-scan.test.ts

 Test Files  2 passed (2)
      Tests  1018 passed | 1 skipped (1019)

Trade-offs

This is not a zero-cost change. Three consequences, all confined to the stall window:

  1. Stale rows can linger. While a repo's scan is stalled, a workspace deleted outside Orca stays in the catalog until the scan recovers (bounded by the 1s resolved-snapshot TTL plus scan completion). This is the exact trade-off already shipped for disconnected SSH repos: a stale row you can act on beats an empty host you can't.
  2. Selector resolution widens for local repos during a stall. resolveWorktreeSelector can now match a restored row, and it feeds removeManagedWorktree (via resolveWorktreeRemovalTarget), sleepManagedWorktree, stopExactTerminalsForWorktree and createTerminal (via resolveTerminalWorkspaceLaunchScope). Those commands fail at the git/FS layer with a real error instead of selector_not_found. This is a deliberate accepted trade, not a non-event. The pre-existing connectionId-gated id fallback at :27057 is untouched, and a rejected scan (the shipped contract) is unaffected — now enforced by the explicit .catch and two tests.
  3. Restored rows are visibly degraded. They carry head: '' and branch: '' (WorktreeMeta persists no branch), so mobile shows the workspace name with a blank branch label and the PR badge falls back to meta.linkedPR. Strictly better than the workspace vanishing, and it is the shape already shipping for disconnected SSH.

Known limitation, deliberately not fixed here: during a permanent stall each worktree.ps poll still waits the full 5s, because withTimeout arms a fresh timer per call against a promise that never settles. worktreeScanInFlight already dedupes the underlying scan, so there is no scan storm — mobile gets a correct list but a 5s refresh. A stalled-repo short-circuit, and a wire-level degraded flag so the staleness is visible rather than silent, are follow-ups. Today the same situation is silently empty, which is worse.

Cross-platform

No platform-conditional code was added or touched, and no UI was touched.

  • macOS / Linux / Windows: identical behavior. listStoredWorktreesForResolution builds rows from splitWorktreeId (src/shared/worktree-id.ts:20) — a pure string split on the first ::, which never interprets the path and so carries no separator or case assumption of its own — and from areWorktreePathsEqual (src/main/ipc/worktree-path-comparison.ts:4), which is the piece that actually normalizes slash style and drive-letter casing for Windows and WSL hosts. The ownership gate compares ExecutionHostIds (local / ssh:<encodeURIComponent(id)> / runtime:<id>, src/shared/execution-host.ts), which are opaque identifiers rather than filesystem paths, so it carries no case or separator assumption either. No path.join, no separator literals, no metaKey, no accelerators, no new tokens or shadcn primitives.
  • SSH remote: this is the primary case. SSH/WSL/relay repos are the ones whose scans stall past 5s over Tailscale/WAN; the fix extends the already-intended "keep persisted rows while the provider reconnects" behavior to the timeout path it was being discarded on. A headless remote orca serve holds its repos with no connectionId, so its scans take the local branch — which is exactly why the fallback was generalized off the SSH-only name rather than gated behind repo.connectionId. Covered by a dedicated test. The relay's fast-failure .catch(() => []) is out of scope, as described above. Co-hosted repo ids (the same repo registered on local and an SSH host) are covered by the ownership gate and two dedicated tests.
  • Folder workspaces (non-git): unaffected, but for exactly one reason — the isFolderRepo(repo) early return (src/main/runtime/orca-runtime.ts:27666). computeResolvedWorktrees returns folder repos through that branch before reaching the timeout wrapper, so they never scan git and never hit the fallback. An earlier version of this body claimed folder-workspace instance meta keys (projectId::path::workspace:<uuid>) were additionally filtered out by parsed.repoId !== repo.id. That was wrong: splitWorktreeId (src/shared/worktree-id.ts:20) splits on the first ::, so projectId::/path::workspace:<uuid> yields repoId === projectId — it would match, not be filtered. The early return is the only thing keeping folder repos off this path, and it is sufficient.
  • Git compatibility: no git subcommand, option, or capability probe was added or changed, so there is nothing to gate through GitCapabilityCache and the Git 2.25 baseline is untouched. The fallback deliberately runs no git binary at all, so it is also correct on hosts where git is missing, wedged, or older than baseline.
  • Git providers: fully provider-agnostic. No GitHub- or GitLab-specific path is involved, and the change is upstream of the PR-cache lookup in getWorktreePs.
  • Verification platform: every suite and counterfactual quoted above was executed on macOS (darwin) only. The Windows/WSL and Linux reasoning in this section is by code inspection, not by execution; nothing here was run on a Windows or Linux host, and no manual end-to-end repro against a real stalled Tailscale runtime was performed — the stall is reproduced with fake timers and a never-settling promise.

Performance

Healthy path (the hot one — a 1s-TTL snapshot poll): one added .catch handler and one ?? per repo per refresh. No store read is added, because listStoredWorktreesForResolution only runs when the null timeout sentinel comes back. That laziness is pinned by a test asserting getAllWorktreeMeta is called exactly once on a healthy scan. Scan-cache eligibility is unchanged, so no repo starts rescanning more often than it did before.

Degraded path: one Object.entries(getAllWorktreeMeta()) pass plus one store.getRepos() filter per stalled repo per snapshot. Both read live in-memory structures, not I/O — and both are costs already incurred today for every unreachable SSH repo and by the equivalent gates in src/main/ipc/worktrees.ts.

No new git execs, no new IPC/RPC round trips, no new polling, no renderer changes, and no change to RESOLVED_WORKTREE_REPO_TIMEOUT_MS, WORKTREE_SCAN_CACHE_TTL_MS or RESOLVED_WORKTREE_CACHE_TTL_MS. The 5s per-repo cap is preserved exactly, so mobile startup is not slowed — one stalled repo still cannot block session loading for the others.

Security

No change. No IPC or RPC surface was added, removed, or reshaped — worktree.ps keeps its existing response type and its existing mobile allowlist entry. No command execution was added; the new code path deliberately executes nothing, which is the point of the fallback. No path is constructed, joined, or written — persisted worktree ids are parsed with the existing splitWorktreeId and compared with the existing areWorktreePathsEqual, and rows are filtered to parsed.repoId === repo.id and to this repo's execution host, so neither another repo nor another host's paths can surface under this repo's id. No auth, pairing, or credential surface is touched. The renamed method remains private.

AI Review Report

Reviewed by independent subagents in a loop until clean, across two hostile lenses — correctness/regressions and cross-platform + remote + performance.

  • Review loop count: 4 round(s)
  • Final verdict: CLEAN

Round 2 produced four major reports, which collapse to the three distinct issues below (the first was raised independently by both lenses). All three were real and all three are addressed:

  1. Zero-row local scan becomes permanently uncacheable → git re-spawn every ~1s (reported twice, by both lenses). Real. Fixed by reverting the zero-row guard entirely rather than special-casing the cache; the caching invariant is now pinned by a test, and a second test pins that a permanent stall does not re-spawn git worktree list on later polls (worktreeScanInFlight dedupes it).
  2. The body's withTimeout safety claim was false — null was not a timeout-only sentinel and no .catch existed. Real. Fixed in code (the rejection is now genuinely absorbed before withTimeout), the two contract tests in orca-runtime.test.ts are untouched by this PR, and the claim in this body was corrected to match the code.
  3. Local/remote asymmetry: the SSH branch still treats a relay [] as authoritative. The relay behaviour is real (src/relay/git-handler.ts:1430) but pre-existing, and the asymmetry only existed because of the reverted local guard. It is documented above as an explicit non-goal with a pointer to where it should be fixed, rather than papered over by row-count inference in the runtime.

Round 3 raised one further blocking finding, which was also real and is now fixed:

  1. The generalized fallback dropped the execution-host ownership gate. listStoredSshWorktreesForResolution only ever ran for SSH repos; generalizing it to every repo kind widened it across execution hosts without the gate that src/main/ipc/worktrees.ts applies at :736, :827-828 and :1119-1123. Since one repo id can be registered on several execution hosts (src/main/persistence.ts:4611, src/main/ipc/repos.ts:2056), a stalled host republished the other host's persisted rows under its own id and the blank head/branch of the degraded copy won over the healthy host's real row. Fixed by reusing the existing predicate rather than inventing a new one, and pinned by two tests that fail without it (expected '' to be 'feature') plus one that pins the single-owner case the fix exists for.

Round 4 found no blocking or major issues and recorded one non-blocking note, kept here rather than fixed:

  • The ownership gate silently changes one pre-existing behavior. A worktree meta stamped hostId: 'local' under a repo that was later converted to SSH used to be restored by listStoredSshWorktreesForResolution (which had no gate) and is now skipped by the degraded fallback. This is intentional — it aligns the fallback with the gate listDisconnectedSshWorktrees (src/main/ipc/worktrees.ts:826-828) already applies to the same rows on the shipped desktop path — but it is a real behavior change for that migration case, so it is disclosed in the Summary above rather than left implicit. No test pins it.

The scope claim was also corrected: this PR does not close #11869. Two body claims were also corrected against the diff after review: the folder-workspace splitWorktreeId rationale (see Cross-platform) and the list of selector-resolution consumers in Trade-off 2 (stopExactTerminalsForWorktree, not terminalExactStop).

Made with Orca 🐋

…o answer

`computeResolvedWorktrees` wrapped every per-repo git scan in a 5s
`withTimeout` whose fallback was zero rows. A repo whose scan stalled
(WAN/Tailscale SSH round trips, a loaded remote box, a wedged local git)
therefore published a healthy-looking empty catalog — strictly worse than
a scan that fails outright, which already falls back to persisted rows
"instead of zero rows". `worktree.ps` is the only catalog source for Orca
Mobile, so a fully populated host rendered as "0 worktrees" while
notification deep-links kept working.

The timeout fallback now restores persisted rows, the same degraded shape
already shipping for disconnected SSH repos. A *rejected* scan is left
untouched and still yields an authoritative empty list, so the
`connectionId`-gated selector contract for local repos is preserved: the
inner promise's rejection is neutralized first, and `null` is used as a
timeout-only sentinel that also keeps the store read off the healthy path.

`listStoredSshWorktreesForResolution` is renamed to
`listStoredWorktreesForResolution` because the new call site is
repo-kind-agnostic; its body reads only persisted metadata, so it runs no
git binary and works on any host.

Closes #11869

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

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@nwparker, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 7 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b6009429-d9e7-4eec-a076-6bd3928c90f4

📥 Commits

Reviewing files that changed from the base of the PR and between 7591ec2 and e898006.

📒 Files selected for processing (1)
  • src/main/runtime/worktree-ps-degraded-repo-scan.test.ts
📝 Walkthrough

Walkthrough

OrcaRuntimeService treats rejected repository scans as empty results. Timed-out, unreachable, or unavailable SSH scans restore persisted worktrees filtered by execution host. The persistence fallback helper and comments use generic naming. New Vitest coverage validates fallback behavior, selector errors, caching, retries, host ownership, lineage handling, metadata reads, and restored worktree listing.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary user-visible change: retaining workspaces when repository scans exceed the timeout.
Description check ✅ Passed The description covers the required sections and provides detailed scope, testing, cross-platform review, security, risks, and follow-up information.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ 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.

nwparker and others added 2 commits August 3, 2026 00:09
…ative catalog

The stall fallback only rescued repos whose scan hung. Local repos rarely
hang: `listWorktrees` swallows a missing git binary, an unmounted repo path
and git-compat failures into `[]`, so `listRepoWorktreesForResolutionUncached`
wrapped that as `{ ok: true, worktrees: [] }`. That is the exact #11869
symptom — `worktree.ps` publishes `{worktrees: [], totalCount: 0}` for a fully
populated host — and worse, `scan.ok` let `pruneLineageForMissingRepoWorktrees`
run with an empty live set, deleting every lineage row and re-minting parent
instance IDs over a transient environment fault.

A live repo always reports its main worktree, so zero local rows can only mean
git never answered. Degrade it to persisted rows like the unreachable-SSH
branch: no prune, no empty catalog, and no 30s cache entry (only `ok` scans are
cached).

A rejected scan now takes the same degraded path; the previous
"rejection stays authoritative-empty" split described a state the local
implementation cannot produce.

Tests that mocked `listWorktrees` to reject were exercising that impossible
state; they now use the real zero-row shape, and the prune guards get real
lineage rows so they discriminate.

Closes #11869
Revert the zero-row local-scan guard: it made a permanently broken repo
uncacheable, so every ~1s snapshot recompute re-spawned git worktree list.
Absorb the scan rejection before withTimeout so null really is a
timeout-only sentinel and a rejected scan keeps its shipped semantics.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
src/main/runtime/orca-runtime.ts (1)

27865-27891: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Update the stale SSH-specific comment on the generalized helper.

Line 27876 says: mirror worktrees:list's disconnected-SSH fallback. listStoredWorktreesForResolution is now called for two purposes: an SSH provider failure/missing provider (line 27856, 27861) and a local-or-remote scan timeout (line 27696 in computeResolvedWorktrees). The comment still describes only the SSH case, which can mislead a future reader into thinking this helper's scope is SSH-only.

📝 Proposed comment update
-      // Why: mirror worktrees:list's disconnected-SSH fallback — keep persisted rows while a scan is unreachable or stalled instead of zero rows.
+      // Why: keep persisted rows while a repo scan is unreachable (missing/broken SSH provider) or stalled past the resolution timeout, instead of publishing zero rows.

The provided line_range_change_details for this range states "the associated comment no longer describes the rows as SSH-specific," but the code still contains SSH-specific wording. Update the comment to match the generalized scope, or update the summary if the comment is intentionally left as-is.

#!/bin/bash
# Description: Check for any remaining SSH-specific naming/comments tied to the renamed helper.
set -euo pipefail

# Test: Search for the old function name and SSH-specific wording near the helper. Expect: no leftover references outside this comment.
rg -n 'listStoredSshWorktreesForResolution' --type=ts
rg -n 'disconnected-SSH fallback' --type=ts
src/main/runtime/worktree-ps-degraded-repo-scan.test.ts (2)

197-213: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a companion test for degraded (stalled) scans not updating the cache.

This test confirms a zero-row local scan result is cached (listWorktreesMock called once across two polls). The PR objective states degraded results must avoid scan-cache updates, so a stalled scan should be retried on the next poll instead of being cached. No test in this file verifies that behavior directly; the closest test (Line 228-245) only checks lineage pruning is skipped during a stall, not that a subsequent poll re-invokes listWorktreesMock.

Add a test that stalls the scan past the per-repo budget, advances timers further, calls getWorktreePs again, and asserts listWorktreesMock was called more than once.


215-226: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert removeWorkspaceLineage is also called for the pruned worktree.

This test verifies removeWorktreeLineage is called when a healthy scan drops WORKTREE_ID, but it does not verify removeWorkspaceLineage. The store fixture at Line 108 seeds a workspace lineage entry keyed by worktree:${WORKTREE_ID} for this same worktree. The persistence layer exposes a separate function for this cleanup: "removeWorkspaceLineage(childWorkspaceKey: WorkspaceKey): void { delete this.state.workspaceLineageByChildKey[childWorkspaceKey] this.scheduleSave() }". The sibling stalled-scan test (Line 228-245) explicitly checks removeWorkspaceLineage is NOT called during a stall, so the symmetric "healthy scans prune it" case should be verified here.

Pass a removeWorkspaceLineage mock into makeStore and assert it is called with the corresponding workspace key.

✅ Proposed test addition
   it('drops and prunes a worktree that a healthy scan no longer reports', async () => {
     const removeWorktreeLineage = vi.fn()
+    const removeWorkspaceLineage = vi.fn()
     listWorktreesMock.mockResolvedValue([
       { path: REPO_PATH, head: 'abc', branch: 'main', isBare: false, isMainWorktree: true }
     ])
-    const runtime = new OrcaRuntimeService(makeStore({ removeWorktreeLineage }) as never)
+    const runtime = new OrcaRuntimeService(
+      makeStore({ removeWorktreeLineage, removeWorkspaceLineage }) as never
+    )

     const result = await runtime.getWorktreePs(10_000)

     expect(result.worktrees.map((worktree) => worktree.worktreeId)).not.toContain(WORKTREE_ID)
     expect(removeWorktreeLineage).toHaveBeenCalledWith(WORKTREE_ID)
+    expect(removeWorkspaceLineage).toHaveBeenCalledWith(`worktree:${WORKTREE_ID}`)
   })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 40689ec3-9234-409f-9229-580adc31c466

📥 Commits

Reviewing files that changed from the base of the PR and between 8b311ae and f6de9f1.

📒 Files selected for processing (2)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/worktree-ps-degraded-repo-scan.test.ts

The timeout fallback generalized listStoredSshWorktreesForResolution to every
repo kind, but it never carried the execution-host ownership gate its siblings
in src/main/ipc/worktrees.ts apply. One repo id can be registered on several
execution hosts, so a stalled host republished the other host's persisted rows
under its own id and overwrote their real branch/head with blank ones.

Gate the persisted rows the same way hasConflictingStoredWorktreeOwner does:
a stamped row only belongs to its own host, and an unstamped row is only
claimable when the repo id has a single owner.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/main/runtime/worktree-ps-degraded-repo-scan.test.ts (2)

231-242: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the duplicated SSH worktree fixture.

Both tests build the same getSshGitProviderMock return value. The only intended difference between the two tests is host stamping in metaById. A shared fixture makes that difference explicit.

♻️ Proposed shared fixture
+function makeSshWorktreeScan() {
+  return {
+    listWorktrees: vi.fn(async () => [
+      { path: REPO_PATH, head: 'abc', branch: 'main', isBare: false, isMainWorktree: true },
+      { path: WORKTREE_PATH, head: 'def', branch: 'feature', isBare: false, isMainWorktree: false }
+    ])
+  }
+}

Then use it in both tests:

-      getSshGitProviderMock.mockReturnValue({
-        listWorktrees: vi.fn(async () => [
-          { path: REPO_PATH, head: 'abc', branch: 'main', isBare: false, isMainWorktree: true },
-          {
-            path: WORKTREE_PATH,
-            head: 'def',
-            branch: 'feature',
-            isBare: false,
-            isMainWorktree: false
-          }
-        ])
-      })
+      getSshGitProviderMock.mockReturnValue(makeSshWorktreeScan())

Also applies to: 272-283


324-326: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the restored row shape, not only its presence.

The PR states that restored rows use blank branch and head metadata. This test only checks that WORKTREE_ID is present. An assertion on the restored fields would pin that documented contract.

♻️ Proposed assertion
-      expect(result.worktrees.map((worktree) => worktree.worktreeId)).toContain(WORKTREE_ID)
+      const restored = result.worktrees.find((worktree) => worktree.worktreeId === WORKTREE_ID)
+      expect(restored).toBeDefined()
+      expect(restored?.hostId).toBe(LOCAL_EXECUTION_HOST_ID)
+      expect(restored?.branch).toBe('')

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 10a00e9b-c3c3-47c9-a8a4-3297462e81b5

📥 Commits

Reviewing files that changed from the base of the PR and between f6de9f1 and 0195d3e.

📒 Files selected for processing (2)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/worktree-ps-degraded-repo-scan.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/orca-runtime.ts

…ft open

Adds a case proving a completed-but-degraded scan is not cached (it rescans
on the next poll), asserts the restored row's degraded shape and the
workspace-lineage half of healthy pruning, and drops the duplicated SSH
scan fixture. Also generalizes the SSH-worded comment on the now
repo-kind-agnostic persisted-row fallback.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8698aee3-0677-453f-8896-8f6c92e24961

📥 Commits

Reviewing files that changed from the base of the PR and between 0195d3e and 28a01da.

📒 Files selected for processing (2)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/worktree-ps-degraded-repo-scan.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/orca-runtime.ts

@nwparker
nwparker merged commit 8f29f58 into main Aug 4, 2026
42 checks passed
@nwparker
nwparker deleted the nwparker/bugbash-11869 branch August 4, 2026 08:26
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tead of reporting zero (stablyai#12222)

A stalled per-repo git scan no longer publishes a healthy-looking empty catalog. Adds an execution-host ownership gate so a degraded host cannot republish another host's worktree rows under its own id.

Relates to stablyai#11869 — this fixes the stall-publishes-zero half. The issue stays open for the remainder.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant