Skip to content

fix(runtime): stop a first status publication retiring in-flight worktree scans - #19357

Merged
nwparker merged 1 commit into
mainfrom
nwparker/runtime-first-status-not-a-reconnect
Sep 8, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/runtime-first-status-not-a-reconnect

Conversation

@nwparker

@nwparker nwparker commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

You connect your Mac to a remote Orca machine. The sidebar shows a few of that machine's worktrees — but not all of them. Nothing you click brings the rest back. Then you create a new worktree over there, and suddenly the missing handful appears.

Here's what was happening. When the app asks a remote host "what worktrees do you have?", it asks about every repo at once, in parallel. While those questions are still out, the app separately gets its first "yes, I'm here" heartbeat from that host. The app treated that first heartbeat as "the connection changed" — and its rule for a changed connection is "throw away any answer that came back over the old one."

But nothing had changed. It was the same connection the questions were sent on. So every repo that hadn't answered yet got its perfectly good answer thrown in the bin, silently, with no retry. Whichever repos happened to answer first survived. That's your partial list. It stayed partial because nothing ever asks again — until creating a worktree triggers a fresh sweep, which is why that fixed it.

Two things were wrong, and both are fixed:

  1. A first hello is not a reconnect. There was no earlier connection for it to differ from.
  2. A discarded answer should be re-asked, not dropped. Even with a correct rule, a real reconnect mid-flight still silently deleted finished work.

Root cause

src/renderer/src/store/slices/runtime-status.ts — connectionChanged was:

status.status !== null &&
(previous?.status == null || previous.status.runtimeId !== status.status.runtimeId)

previous?.status == null conflates two different states:

  • previous === undefined — no entry yet. Cold start. Not a connection change.
  • previous.status === null — we recorded the host unreachable, and it now answers. A genuine reconnect.

Only the second should advance the connection generation. Measured on the real store action: a cold-start publish moved the generation 0 -> 1.

That generation is a fence. src/renderer/src/store/slices/worktrees/listing/detected-worktree-refresh.ts re-checks it after a worktree.detectedList has already resolved successfully and throws runtime_environment_generation_changed. fetch-all-worktrees.ts:77 (and :140) catches that, console.errors, and moves on — the repo's rows never merge.

fetchAllWorktrees scans all of a host's repos concurrently via mapReposForWorktreeRefresh, so one bump discards every repo still outstanding at that instant. Whole repos at a time, arbitrary which — hence "a few, but not all" rather than a clean split. See Confirmed prediction: the reporter independently confirmed that granularity.

Nothing re-reads afterwards: src/renderer/src/components/sidebar/index.tsx:118-125 only re-runs fetchAllWorktrees() when repoCount changes. The recovery the user saw comes from reposChanged, which triggers refreshRuntimeProjectWorktreesAndLineage over all of that environment's repos (runtime-client-ipc-bridge.ts:61-80).

The fix

1. A first publication is not a connection change (runtime-status.ts). Split the predicate in two:

const runtimeSessionStarted = status.status !== null &&
  (previous?.status == null || previous.status.runtimeId !== status.status.runtimeId)
const connectionChanged = runtimeSessionStarted && previous !== undefined

The provider-session bump deliberately keeps the broader predicate — integration-readiness caches key off the runtime session, for which a first publication is a real transition. That distinction is pinned by a mutation test (below).

2. A stale-generation scan is re-read, not dropped (detected-worktree-refresh.ts). The environment branch is extracted to listDetectedWorktreesForRuntimeRepoOnce and retried once against the new generation. The coalescing key embeds both generations and is recomputed per attempt, so a retry cannot join the superseded connection's in-flight scan. Bounded at exactly one retry: a second stale answer means the connection is still churning, and retrying into that would stall the caller instead of failing visibly.

I fixed both halves deliberately. Fixing only the predicate would leave a genuine mid-flight reconnect still silently deleting completed scans.

Reproduction

src/renderer/src/store/slices/worktrees-runtime-connection-generation-fence.test.ts drives the real slice: 5 repos on one runtime host, one answers immediately, the generation moves while the other four are in flight.

Before (the fence discards them):

Failed to fetch worktrees for repo repo2: Error: runtime_environment_generation_changed
Failed to fetch worktrees for repo repo3: Error: runtime_environment_generation_changed
Failed to fetch worktrees for repo repo4: Error: runtime_environment_generation_changed
Failed to fetch worktrees for repo repo5: Error: runtime_environment_generation_changed
PUBLISHED: [ 'repo1' ]

After: all five publish, each with its row. The control case (nothing perturbs the connection) publishes all five before and after, so the test is not merely asserting "the happy path works".

Cold-start generation, measured through setRuntimeEnvironmentStatus: 0 -> 1 before, 0 -> 0 after.

Mutation testing

Each assertion was checked against the specific defect it claims to catch — mutated one at a time, never a wholesale revert:

Mutation Test that failed
connectionChanged = runtimeSessionStarted (restore the first-publish bump) does not advance the connection generation when no entry existed + 4 generation assertions in runtime-status.test.ts
Retry disabled (attempt >= 0) re-reads instead of dropping the repos still in flight — reproduced [ 'repo1' ] exactly
Retry bound loosened to 2 gives up after one re-read so a churning connection cannot stall the caller (expected 3 to be 2)
Provider bump narrowed to connectionChanged existing invalidates provider state only when the active runtime session changes

Four assertions in runtime-status.test.ts were updated rather than added to: they encoded the old first-publish off-by-one. Each still asserts its real invariant — that recovery advances, that stable re-polls don't, that a runtime-id change does, and that stored and canonical generations stay aligned after a re-pair. Only the numbers moved.

Confirmed prediction

This mechanism makes a specific, falsifiable prediction about what the user should have seen. Because the scans run concurrently per repo and the fence discards a whole repo's result at a time, the missing worktrees must be absent in whole-repo groups — never scattered within a repo. Nothing else about the report constrains that: a partial list is equally consistent with rows going missing individually.

The reporter was asked which pattern they saw, without being told which answer the theory needed. Whole repos at a time.

A scattered-within-repo pattern would have falsified this fix and sent the investigation back to the visibility filter or the merge path. The answer could have gone either way, and it went the way the mechanism required. That is a successful prediction rather than a post-hoc fit, and it is stronger evidence than any amount of further code reading — it closes the one link between the mechanism and the user's actual session that code alone could not establish.

Two traps for the next person

The CLI is not the sidebar's reader. orca worktree list --json reports every runtime host in omittedHostIds, including the one you're investigating. It cannot reproduce this, and reaching for it first leads straight to "not reproducible".

externalWorktreeVisibility: 'hide' is a red herring here, ruled out with numbers. On the host I measured, one repo returns 59 detected / 19 visible — 11 external + 29 agent-scratch rows suppressed by that repo's configured visibility. That is stable across both worktree.detectedList and worktree.list, and unchanged by creating a worktree, so it is not the disappearance being reported. Hidden rows and missing rows look identical in the output; this trap has nearly produced a false finding twice.

Verification

  • pnpm tc — clean
  • oxlint — 0 errors (the new test lives in its own file rather than pushing runtime-status.test.ts past max-lines; no disable added)
  • pnpm run check:code-quality:changed — 0 new findings across 5 changed files
  • pnpm format
  • pnpm vitest run src/renderer/src/store src/renderer/src/hooks — 504 files, 4243 tests, all passing

Limitation, stated plainly

I reproduced the mechanism on real slice code, not the user's session end-to-end. The packaged app does not expose the renderer store (__store is build-gated on VITE_EXPOSE_STORE; no match in app.asar), the running instance has no CDP port, and renderer console.error is not forwarded to any log file — so the user's actual session left no readable trace. Restarting the app or pairing a second device to the shared host would have disturbed teammates actively using it, so I did neither.

The whole-repo granularity signature is confirmed by the reporter (above) — that gap is closed. What remains inferred, not measured is narrower: whether the status publish overlapped fetchAllWorktrees specifically in their session. The publisher is probeRuntimeStatus, fired when the runtime client-events subscription becomes ready (runtime-client-ipc-bridge.ts:274,292), concurrent with and independent of the deferred startup chain at use-app-startup-hydration.ts:312-324.

The experiment that would settle it: instrument a client at both sites and confirm the bump lands between the first and last detectedList of the startup batch. If the status publish reliably precedes fetchAllWorktrees, the race is unreachable at startup and the trigger is a genuine mid-session reconnect instead — narrower, and the same fix applies either way.

Separately, a hypothesis worth recording as refuted: this is not partition precedence. repoWithFetchedOwner (src/renderer/src/store/repos/owner-routing.ts) unconditionally stamps every repo fetched from a runtime target with executionHostId: runtime:<envId>, so remote rows arriving as executionHostId: 'local' or with none at all cannot collide with the client's local partition.

…tree scans

A paired runtime host's first status publication counted as a connection
change, advancing the connection generation. Worktree scans already in
flight against that same connection were then discarded, so the sidebar
showed a strict subset of the host's worktrees until an unrelated refresh.

Two independent defects, both fixed:

- `connectionChanged` conflated "no entry yet" with "recorded unreachable".
  Only the latter is a reconnect. The provider-session bump keeps the
  broader predicate, since a first publication is a real session start for
  integration-readiness caches.
- A stale-generation result was thrown away with no retry, so even a
  genuine mid-flight reconnect silently dropped completed work. The scan is
  now re-read once against the new generation.
@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 0c483601-1ba9-4fdf-83ff-f84d548e87b6

📥 Commits

Reviewing files that changed from the base of the PR and between d0506bf and fc6e897.

📒 Files selected for processing (5)
  • src/renderer/src/store/slices/runtime-status-first-publication.test.ts
  • src/renderer/src/store/slices/runtime-status.test.ts
  • src/renderer/src/store/slices/runtime-status.ts
  • src/renderer/src/store/slices/worktrees-runtime-connection-generation-fence.test.ts
  • src/renderer/src/store/slices/worktrees/listing/detected-worktree-refresh.ts

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


📝 Walkthrough

Walkthrough

Runtime status handling now separates provider session starts from connection-generation changes. First reachable publications start sessions without advancing the connection generation, while reconnects and runtime changes still advance it. Environment worktree refreshes now detect stale generations, clean up in-flight scans, and retry once. New tests cover initial status publication, recovery, stable scans, mid-scan generation changes, and continuously changing connections.

Merge Risk: ⚪ Minimal · up to fc6e8

Runtime worktree scanning now retains valid results through an initial host status publication and safely retries scans interrupted by a reconnect, while bounded retries prevent indefinite refreshes during connection churn. No current merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 main fix: preventing a first runtime status publication from retiring in-flight worktree scans.
Description check ✅ Passed The description is detailed, focused, and covers the problem, root cause, implementation, tests, limitations, and verification. The linked issue field is blank, and the required visual-proof section l…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • First status publication is no longer a reconnect (runtime-status.ts) — splits the old connectionChanged predicate into runtimeSessionStarted and connectionChanged = runtimeSessionStarted && previous !== undefined, so a cold-start publication no longer advances the connection-generation fence that was retiring in-flight worktree scans.
  • Stale-generation scans are re-read, not dropped (detected-worktree-refresh.ts) — extracts listDetectedWorktreesForRuntimeRepoOnce and retries a runtime_environment_generation_changed failure once against the new generation, recomputing the coalescing key per attempt so a retry cannot join the superseded connection's in-flight scan.
  • Regression + mutation tests across three files — a slice-level fence test that drives 5 concurrent repos through a generation bump, a first-publication unit test, and updated generation-count assertions in runtime-status.test.ts.

The two halves are sound. I confirmed the previous === undefined heuristic is safe in production: every path that removes a status entry (setRuntimeEnvironments remove/re-pair, clearRuntimeEnvironmentStatus) also advances the canonical generation, and retainRuntimeEnvironmentStatuses (which deletes without bumping) has no production callers. The bumpProviderRuntimeSessionGeneration condition is semantically unchanged by the rename. The retry preserves teardown semantics (teardown runs only on a non-stale result, so no double-teardown), and all three callers of listDetectedWorktreesForRepoCoalesced benefit. The fence/retry tests are real guards — they fail pre-fix and with the retry disabled, verified locally (48 tests pass across the three files).

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

@nwparker
nwparker merged commit fc78a7d into main Sep 8, 2026
35 checks passed
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