Skip to content

fix(runtime): attribute unowned workspaces to the active runtime, not the client - #11512

Open
plotarmordev wants to merge 1 commit into
stablyai:mainfrom
plotarmordev:fix/unowned-workspace-resolves-to-active-runtime
Open

plotarmordev wants to merge 1 commit into
stablyai:mainfrom
plotarmordev:fix/unowned-workspace-resolves-to-active-runtime

Conversation

@plotarmordev

@plotarmordev plotarmordev commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A repo that lives on a remote orca serve machine carries no connectionId — it is local to that server, not to the connecting client. getResolvedExecutionHostIdForWorktree treats that absence as "local", so operations on the workspace are routed to the client's own daemon, which cannot see the path.

From the desktop client this surfaces as:

DaemonProtocolError: Working directory "/home/<user>/Documents/<repo>" does not exist.
It may have been deleted or is on an unmounted volume.

and the request never reaches the server. Same root cause as #9047, which reports it from the web client ("Couldn't determine which host owns this workspace" / "Local PTYs are unavailable in the web client") — that issue's own note says worktrees on the serve's local host "should resolve their operation owner to that runtime environment rather than {kind:'local'}".

Worth flagging for triage: #9047 is filed as web-client-only, but the desktop client is affected too, with a different error string.

Root cause — src/renderer/src/lib/resolved-worktree-execution-host.ts:

return repo.connectionId?.trim()
  ? toSshExecutionHostId(repo.connectionId)
  : LOCAL_EXECUTION_HOST_ID   // ← the client's machine, not the server's

The same unconditional fallback exists on the folder-workspace path.

Fix — resolve the fallback against settings.activeRuntimeEnvironmentId: when a runtime is connected, it owns anything not otherwise claimed. With no runtime active the result is unchanged, so purely local setups behave identically.

Two notes on why this shape: activeRuntimeEnvironmentId is already part of WorktreeRuntimeOwnerState, so there is no new plumbing; and there is precedent directly above, where the folder path already resolves to a runtime host via restoredRuntimeHostIdByWorkspaceSessionKey. Unowned repos simply never got the same treatment. Both fallback sites now share one helper.

Screenshots

No visual change — this corrects which host an operation is routed to. The UI is unchanged; the difference is that opening a workspace on a remote orca serve host succeeds instead of erroring.

Testing

  • pnpm lint — passes for the file in this PR. One pre-existing failure unrelated to it: src/main/daemon/daemon-pty-router.ts:381 max-lines (304 > 300), which reproduces identically on pristine origin/main.
  • pnpm typecheck — clean.
  • pnpm test — resolved-worktree-execution-host, worktree-runtime-owner, execution-host-registry: all pass.
  • pnpm build — could not complete in this environment, for a reason unrelated to the diff: [email protected] ships prebuilds only for darwin-arm64/x64 and win32-arm64/x64, so on aarch64 Linux it must compile from source, and these deps were installed with --ignore-scripts. The failure is the plain-node-entry-guard step loading daemon-entry.js (Failed to load native module: pty.node … prebuilds/linux-arm64), which this PR does not touch. pnpm build:web does complete cleanly, and pnpm run build:electron-vite gets as far as that guard with no errors attributable to these files.
  • Tests added. Two cases: an unowned repo with an active runtime resolves to runtime:env-1; an unowned repo with no active runtime still resolves to local. Reverting only the source change makes the first fail with expected 'local' to be 'runtime:env-1', so it is a genuine regression test rather than a restatement.

Verified on hardware. Two-node aarch64 Linux cluster running orca serve headless, opened from a macOS desktop client over Tailscale, Orca v1.4.161 both ends:

Client Bundle Opening a repo on the server's local host
macOS desktop app stock ❌ DaemonProtocolError: Working directory … does not exist
Browser web client patched, served by the same server ✅ opens

Same daemon, same path, same pairing — the only variable is this patch. Server-side logs show the failing case never reaches the daemon at all. Adding the server as an SSH host also works on stock, which further isolates the failure to the runtime-server ownership path rather than transport or permissions.

AI Review Report

Risks checked: whether the fallback change alters behaviour for purely local setups; whether activeRuntimeEnvironmentId is reliably populated where this resolver runs; whether the folder-workspace and repo paths needed to diverge; whether an explicitly-owned workspace could be captured by the new fallback.

Findings and outcomes:

  • Confirmed the helper only fires after every explicit ownership signal is exhausted — worktree.hostId, repo.executionHostId, repo.connectionId, group.executionHostId, and the restored runtime host. Explicitly-owned workspaces are untouched.
  • Confirmed LOCAL_EXECUTION_HOST_ID is still returned when no runtime is active, so single-machine behaviour is bit-identical. This is asserted by one of the two new tests.
  • Reviewed against getSettingsFocusedExecutionHostId and getExecutionHostIdForWorktree, which already consume activeRuntimeEnvironmentId the same way — the new helper is consistent with existing consumers rather than introducing a new pattern.
  • Greptile's review on this PR returned "safe to merge"; CodeRabbit generated no actionable comments.

Cross-platform: reviewed for macOS, Linux and Windows. The change is pure string/ID resolution in the renderer — no paths are constructed or compared, no shell invocation, no filesystem access, no platform-conditional logic, no Electron API use. It cannot behave differently across platforms. Verified end-to-end with a macOS client against a Linux server, which is the cross-platform case that matters here.

Security Audit

  • Input handling — activeRuntimeEnvironmentId is read from the app's own settings, trimmed, and used only to build a runtime:<id> host identifier. It is not interpolated into a path, command, or URL.
  • Command execution / path handling — none; this file resolves identifiers only.
  • Auth — no change to authentication or pairing. Operations are routed to a runtime the client is already connected and authenticated to; nothing new is trusted.
  • Privilege direction — worth stating explicitly: the change makes unowned workspaces resolve to the connected runtime rather than the local machine. That routes work away from the client's own daemon, so it narrows rather than widens what the local host is asked to execute. With no runtime connected, nothing changes.
  • Secrets / dependencies / IPC — none touched, none added.

Follow-up: none identified.

Notes

@coderabbitai

coderabbitai Bot commented Jul 30, 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: Pro Plus

Run ID: 1be362d7-8801-49c5-b499-42d5a55d6ad1

📥 Commits

Reviewing files that changed from the base of the PR and between 31e9f4a and baba278.

📒 Files selected for processing (2)
  • src/renderer/src/lib/resolved-worktree-execution-host.test.ts
  • src/renderer/src/lib/resolved-worktree-execution-host.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/lib/resolved-worktree-execution-host.test.ts
  • src/renderer/src/lib/resolved-worktree-execution-host.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

Unowned folders and worktrees now resolve to the active runtime environment’s execution host when one is configured. The resolution trims the runtime environment ID and falls back to the local execution host when none is available. New tests cover active-runtime resolution for repositories and folder workspaces, along with the local fallback.

Merge Risk: ⚪ Minimal · up to baba2

This localized change routes unowned workspaces to the active runtime while preserving local behavior when no runtime is connected; no actionable merge-blocking risk remains after normal checks and review.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: routing unowned workspaces to the active runtime instead of the client.
Description check ✅ Passed The description clearly covers the problem, fix, testing, visual impact, security, and limitations, but it omits some template headings and a formal Fixes # entry.
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.

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.

@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/renderer/src/lib/resolved-worktree-execution-host.ts (1)

21-27: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Keep the runtime-host rationale concise in both locations.

  • src/renderer/src/lib/resolved-worktree-execution-host.ts#L21-L27: replace the multi-line JSDoc with a one-line summary of active-runtime versus local fallback.
  • src/renderer/src/lib/resolved-worktree-execution-host.test.ts#L25-L27: reduce the duplicated test explanation to one line, retaining only the orca serve ownership distinction.

As per coding guidelines, “Comments must be concise, limited to non-obvious information, and preferably one line.”

Source: Coding guidelines

src/renderer/src/lib/resolved-worktree-execution-host.test.ts (1)

24-56: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover the unowned folder fallback too.

These cases exercise only repository ownership. Add active-runtime and no-runtime assertions for a folder:<id> with matching folder and project-group records, so the changed fallback at src/renderer/src/lib/resolved-worktree-execution-host.ts Line 65 is directly protected. PR objectives require both fallback paths to be covered.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3dbe8a37-574b-44fa-be7a-70c8406b1735

📥 Commits

Reviewing files that changed from the base of the PR and between 561e2d3 and e1834826872b52dfb7f9a33424d3b6efb1fc6711.

📒 Files selected for processing (2)
  • src/renderer/src/lib/resolved-worktree-execution-host.test.ts
  • src/renderer/src/lib/resolved-worktree-execution-host.ts

@greptile-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

Fixes workspace-to-host routing for repositories living on a remote orca serve machine. Such repos carry no connectionId (they are local to the server, not the client), so the old fallback incorrectly sent operations to the connecting client's own daemon — which cannot see those paths — producing DaemonProtocolError: Working directory … does not exist.

  • Introduces getUnownedWorkspaceHost(state): returns runtime:<activeRuntimeEnvironmentId> when a runtime is connected, otherwise LOCAL_EXECUTION_HOST_ID. This is applied at both the repo-path and folder-workspace fallback sites in getResolvedExecutionHostIdForWorktree / getResolvedFolderHost.
  • The helper mirrors the existing getSettingsFocusedExecutionHostId pattern and only fires after all explicit ownership signals (worktree.hostId, repo.executionHostId, repo.connectionId, group.executionHostId, restored runtime host) are exhausted.
  • Three new regression tests cover: unowned repo → runtime, unowned folder → runtime, and unowned workspace → local with no active runtime. The folder test also addresses the gap noted in the prior review.

Confidence Score: 5/5

Safe to merge. The change is narrowly scoped to the last-resort fallback in workspace-to-host resolution, all explicit ownership signals take priority, and behaviour is unchanged when no runtime is active.

The fix touches a single, well-isolated fallback path whose output is fully determined by state.settings?.activeRuntimeEnvironmentId. All earlier ownership checks remain ahead of it, so no explicitly-owned workspace is affected. The three new tests are genuine regression guards, and the folder-path coverage gap from the prior review thread is now closed.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/renderer/src/lib/resolved-worktree-execution-host.ts Introduces getUnownedWorkspaceHost helper that returns the active runtime host (or local) for workspaces with no explicit ownership signal; applied at both the repo and folder-workspace fallback sites. Logic is minimal, well-guarded, and consistent with existing patterns like getSettingsFocusedExecutionHostId.
src/renderer/src/lib/resolved-worktree-execution-host.test.ts Adds three new tests: unowned repo → active runtime, unowned folder → active runtime, and unowned workspace → local when no runtime is set. The folder-path coverage addresses the gap flagged in the prior review thread.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[getResolvedExecutionHostIdForWorktree] --> B{worktreeId present?}
    B -- No --> Z1[null]
    B -- Yes --> C{FLOATING_TERMINAL?}
    C -- Yes --> Z2[local]
    C -- No --> D{folder scope?}
    D -- Yes --> E[getResolvedFolderHost]
    D -- No --> F{worktree.hostId set?}
    F -- Yes --> Z3[worktreeHost.id]
    F -- No --> G{repo found?}
    G -- No --> Z4[null]
    G -- Yes --> H{repo.executionHostId set?}
    H -- Yes --> Z5[explicitRepoHost.id]
    H -- No --> I{repo.connectionId set?}
    I -- Yes --> Z6[ssh:connectionId]
    I -- No --> J[getUnownedWorkspaceHost]
    J --> K{activeRuntimeEnvironmentId?}
    K -- Yes --> Z7[runtime:envId]
    K -- No --> Z8[local]
Loading

Reviews (3): Last reviewed commit: "fix(runtime): attribute unowned workspac..." | Re-trigger Greptile

@plotarmordev

Copy link
Copy Markdown
Contributor Author

Rebased onto current main to clear the conflict. The conflicted line was the same fallback this PR targets: main introduced preferredHostId (active-workspace host preference) on it. Resolution keeps main's semantics — preferredHostId wins whenever it is known — and applies this PR's change only to the residual case (preferredHostId absent), which now resolves to getUnownedWorkspaceHost(state) instead of unconditional LOCAL_EXECUTION_HOST_ID. All 8 tests in resolved-worktree-execution-host.test.ts pass on the merged result.

@AmethystLiang
AmethystLiang requested review from AmethystLiang and removed request for OrcaWin August 1, 2026 22:53
@AmethystLiang

Copy link
Copy Markdown
Contributor

Fixing:

  • @coderabbitai: comment — [![Review Change Stack](https://storage.googleapis.com/coderabbit_publi…
  • @coderabbitai: review summary —
    Details

Will be in the next commit.

@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmethystLiang Acknowledged. I will review the updated commit when it is available.

You are interacting with an AI system.

A repo living on a remote `orca serve` machine carries no connectionId,
because it is local *to that server* rather than to the connecting client.
getResolvedExecutionHostIdForWorktree treated that absence as "local", so
operations on such a workspace were routed to the client's own daemon, which
cannot see the path. The desktop client surfaces this as:

  DaemonProtocolError: Working directory "<path>" does not exist.
  It may have been deleted or is on an unmounted volume.

and the request never reaches the server. Refs stablyai#9047, which reports the same
root cause from the web client ("Couldn't determine which host owns this
workspace" / "Local PTYs are unavailable").

Resolve the fallback against settings.activeRuntimeEnvironmentId instead: when
a runtime is connected it owns anything not otherwise claimed. With no runtime
active the result is unchanged, so purely local setups are unaffected.

activeRuntimeEnvironmentId is already part of WorktreeRuntimeOwnerState, and
the folder-workspace path above already resolves to a runtime host via
restoredRuntimeHostIdByWorkspaceSessionKey — unowned repos simply never got the
same treatment. Both fallback sites now share one helper.
@plotarmordev
plotarmordev force-pushed the fix/unowned-workspace-resolves-to-active-runtime branch from cdb10cc to baba278 Compare August 16, 2026 05:24
@coderabbitai

coderabbitai Bot commented Aug 16, 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.

@plotarmordev

Copy link
Copy Markdown
Contributor Author

@AmethystLiang gentle bump — the follow-up commit mentioned on Aug 3 never landed, and #9047 got a new repro on current main as of Aug 11 (PannenetsF's comment), which also traces a second affected code path in file-explorer-operation-owner.ts.

I've rebased onto latest main (now mergeable, all tests green).
Anything else needed to get this in?

@nwparker nwparker removed the P0 label Aug 19, 2026
svc-orca Bot pushed a commit to LesleyMurfin/orca that referenced this pull request Sep 7, 2026
… are saved (stablyai#16733)

resolveWorktreeOperationRouteResult establishes positive identity from the
worktree and repo catalogs, then discards it. With no runtime active the only
exit is the legacy-local gate, which requires an empty saved-runtime list, so one
saved runtime environment -- connected or not, related or not -- made it false
and the call returned { kind: 'missing' }. Every owner-routed operation on a
genuinely local git worktree then failed closed, and because
resolveTerminalWorktreeRoute is the sole gate in front of
terminal-request-ipc-bridge.ts, the user saw "Terminal creation is unavailable
because the worktree owner could not be resolved".

Folder workspaces hit the same gate and were carved out in stablyai#10251/stablyai#10269, whose
comment in this file states the principle and names this exact failure mode: a
found record is positive identity evidence, and the worktree legacy hydration
gates "would fail local folders closed whenever unrelated runtimes exist". Git
worktrees never got the equivalent. This adds it, in the same shape and the same
function.

The rule is not new. An unstamped repo row is read as locally owned by
getRepoExecutionHostId, by main's resolveRepoOwnershipEvidence, and by
Repo.executionHostId's own documentation; and the repo write path
(repoWithFetchedOwner) stamps runtime: and ssh: owners at fetch time, so an
unstamped row is a legacy row that predates owner projection -- local by
construction. The router now consults that evidence instead of contradicting it.
The sidebar already rendered these worktrees as Local; this removes the
disagreement rather than adding a heuristic.

Four properties this change holds to:

1. The branch sits after the active-runtime block, so an unambiguous active
   runtime still wins (routes runtime:<id>, not local) and an ambiguous or
   mid-hydration focus still returns missing. That ordering is structural, not
   incidental.
2. mayBeLegacyLocal is left byte-identical (verified: both 7-line hunks hash to
   f0ed1b4287c646cb). The new branch does take over the two states where a local
   repo row exists and no runtime is saved, but returns the identical local
   route, so no input changes its answer -- only which branch produced it.
3. The helper returns null on anything but unanimous local, so the branch can
   only ever convert missing into local. It never returns ambiguous: a
   contradiction between repo rows is already decided upstream by
   resolveExplicitWorktreeOperationRouteResult, and answering it here would be a
   second, divergent authority.
4. It reads neither runtimeEnvironmentCatalogHydrated nor
   removedRuntimeEnvironmentIds. That is sound rather than merely convenient,
   because it consults host evidence rather than runtime-environment inference: a
   runtime-owned repo row is stamped runtime:<id> at fetch time, so neither an
   unhydrated runtime catalog nor a removed environment can turn an unstamped row
   into a remote one.

Control only reaches this point after the explicit catalog resolver returned
missing, which means every worktree row and every repo row for this id is
unstamped -- any stamped row routes ssh: or runtime: earlier, and two disagreeing
rows return ambiguous earlier. There is no remote-owned state left here to leak.

Out of scope, deliberately: who wins when a runtime is focused (stablyai#11512), and
back-filling Worktree.hostId at creation time, which is a persistence migration
over worktreeMeta and does nothing for the users already carrying unstamped rows.

The 7 cases red in the two preceding commits now pass; the 52 that guard the
fail-closed contract are unchanged.

  Test Files  2 passed (2)
       Tests  59 passed (59)
nwparker pushed a commit that referenced this pull request Sep 15, 2026
#16841 still fails closed (#16829)

* test(worktrees): cover local worktree owner routing with saved runtimes (#16733)

A local git worktree whose rows carry no host stamp fails every owner-routed
operation closed as soon as any runtime environment is saved, however unrelated.
resolveWorktreeOperationRouteResult establishes positive identity from the
worktree/repo catalogs, then discards it: with no runtime active the only exit is
the legacy-local gate, which demands an empty saved-runtime list. One saved
environment makes that false and the call returns { kind: 'missing' }.

These tests state the contract before the fix, so the claim that the fix is
purely additive can be checked rather than asserted. Committed red on purpose.

Observed at 5631aa0 (vitest run, both files):

  Tests  7 failed | 52 passed (59)

The 7 failing are exactly the states that must become local, plus their two
consumers:

  - an unrelated runtime is saved (the reported bug)
  - several unrelated runtimes are saved
  - the repo is known before its worktree row is listed
  - the saved-runtime catalog has not hydrated
  - an unrelated runtime was removed
  - resolveTerminalWorktreeRoute on such a worktree (the gate in front of the
    "Terminal creation is unavailable" reply)
  - the folder/worktree parity state: identical store, folder local, worktree
    missing

The other 52 pass now and must keep passing: connection-owned and
runtime-stamped repos never route local, a stamped worktree row still outranks
its repo, contradictory repo rows stay ambiguous, an ambiguous or hydrating
runtime focus still fails closed, and a genuinely unknown id still fails closed.
That set is the additive-only guarantee.

* test(worktrees): re-aim two fail-closed cases at genuinely missing owners (#16733)

Two cases in src/renderer/src/lib/worktree-operation-route.test.ts assert the
behaviour #16733 reports as the bug, so they have to move:

  - :158 'fails a paired-client ownerless stale publication closed instead of
    routing it locally'
  - :171 'fails ownerless rows closed until the saved-runtime catalog is hydrated'

Both arrived with #9994 (41751dd, route HUB-owned SSH worktrees through their
owning runtime), whose stated goal was to fail closed for missing or stale
owners. That goal is right and is kept. The premise being rebutted is narrower:
neither fixture describes a missing or stale owner. Each carries a present repo
row that is merely unstamped -- repos: [{ id: 'repo-1' }] -- and three places in
this codebase already read exactly that row as locally owned:

  - shared/execution-host.ts getRepoExecutionHostId returns LOCAL_EXECUTION_HOST_ID
  - main/ipc/worktrees/listing/worktree-host-ownership.ts resolveRepoOwnershipEvidence
    falls back to LOCAL_EXECUTION_HOST_ID, and the listing and removal paths trust it
  - shared/repo-types.ts documents executionHostId as the field runtime-host repos
    need precisely because they otherwise look identical to local repos

attribute. It swept in the legacy-local case because at the time nothing in this
resolver consulted the repo index for an unstamped row.

So each case is re-aimed at the state it was actually defending, and neither is
deleted -- the fail-closed coverage is not reduced, it is pointed at a real
missing owner:

  - the first becomes 'fails a paired-client publication closed when no repo row
    can own it': same runtime state, repos: []. A worktree row alone is not host
    evidence, so this still returns missing, before and after the fix.
  - the second becomes 'fails ownerless rows closed mid-hydration while a saved
    runtime could own them': an active runtime with an ambiguous saved catalog
    during hydration. This returns missing from the active-runtime branch and is
    untouched by the fix. It is worded to stay distinct from the neighbouring
    case at :185, which already covers focus-is-not-ownership with an empty
    catalog, rather than duplicating it.

The states these two cases vacate are re-asserted with their corrected expected
result in the #16733 block added by the previous commit. Suite unchanged at
7 failed | 52 passed (59): the rewrites pass, the 7 reds are still the 7 states
the fix must convert.

* fix(worktrees): keep unstamped local worktrees routable when runtimes are saved (#16733)

resolveWorktreeOperationRouteResult establishes positive identity from the
worktree and repo catalogs, then discards it. With no runtime active the only
exit is the legacy-local gate, which requires an empty saved-runtime list, so one
saved runtime environment -- connected or not, related or not -- made it false
and the call returned { kind: 'missing' }. Every owner-routed operation on a
genuinely local git worktree then failed closed, and because
resolveTerminalWorktreeRoute is the sole gate in front of
terminal-request-ipc-bridge.ts, the user saw "Terminal creation is unavailable
because the worktree owner could not be resolved".

Folder workspaces hit the same gate and were carved out in #10251/#10269, whose
comment in this file states the principle and names this exact failure mode: a
found record is positive identity evidence, and the worktree legacy hydration
gates "would fail local folders closed whenever unrelated runtimes exist". Git
worktrees never got the equivalent. This adds it, in the same shape and the same
function.

The rule is not new. An unstamped repo row is read as locally owned by
getRepoExecutionHostId, by main's resolveRepoOwnershipEvidence, and by
Repo.executionHostId's own documentation; and the repo write path
(repoWithFetchedOwner) stamps runtime: and ssh: owners at fetch time, so an
unstamped row is a legacy row that predates owner projection -- local by
construction. The router now consults that evidence instead of contradicting it.
The sidebar already rendered these worktrees as Local; this removes the
disagreement rather than adding a heuristic.

Four properties this change holds to:

1. The branch sits after the active-runtime block, so an unambiguous active
   runtime still wins (routes runtime:<id>, not local) and an ambiguous or
   mid-hydration focus still returns missing. That ordering is structural, not
   incidental.
2. mayBeLegacyLocal is left byte-identical (verified: both 7-line hunks hash to
   f0ed1b4287c646cb). The new branch does take over the two states where a local
   repo row exists and no runtime is saved, but returns the identical local
   route, so no input changes its answer -- only which branch produced it.
3. The helper returns null on anything but unanimous local, so the branch can
   only ever convert missing into local. It never returns ambiguous: a
   contradiction between repo rows is already decided upstream by
   resolveExplicitWorktreeOperationRouteResult, and answering it here would be a
   second, divergent authority.
4. It reads neither runtimeEnvironmentCatalogHydrated nor
   removedRuntimeEnvironmentIds. That is sound rather than merely convenient,
   because it consults host evidence rather than runtime-environment inference: a
   runtime-owned repo row is stamped runtime:<id> at fetch time, so neither an
   unhydrated runtime catalog nor a removed environment can turn an unstamped row
   into a remote one.

Control only reaches this point after the explicit catalog resolver returned
missing, which means every worktree row and every repo row for this id is
unstamped -- any stamped row routes ssh: or runtime: earlier, and two disagreeing
rows return ambiguous earlier. There is no remote-owned state left here to leak.

Out of scope, deliberately: who wins when a runtime is focused (#11512), and
back-filling Worktree.hostId at creation time, which is a persistence migration
over worktreeMeta and does nothing for the users already carrying unstamped rows.

The 7 cases red in the two preceding commits now pass; the 52 that guard the
fail-closed contract are unchanged.

  Test Files  2 passed (2)
       Tests  59 passed (59)

* test(worktrees): defer repo-row-only routing to #16841's fail-closed rule (#16733)

Upstream #16841 (merged d347595) landed its own fix for #16733 and drew the
positive-identity line one notch tighter than this branch did: its
'does not treat a repo row alone as positive local identity' case asserts that a
worktree id no row has ever listed stays `missing`, even when the repo row for
its repoId is local.

This branch's 'routes a known local repo before its worktree row has been listed'
asserted the opposite result for that identical state, so the two cannot both
hold. Main's rule is the safer reading — a repo row is repo identity, not
worktree identity — so the reconciled code gates
resolveUnstampedLocalWorktreeRoute on hasKnownWorktree and this case is dropped
rather than re-pinned. Every state that actually reproduces #16733 keeps a
worktree row (listed or detected), so the reported bug and both extra
fail-closed edge cases this branch fixes are unaffected.

* refactor(worktrees): drop the unreachable disagreement loop in resolveUnstampedLocalWorktreeRoute

resolveWorktreeOperationRouteResult only calls resolveUnstampedLocalWorktreeRoute after
resolveExplicitWorktreeOperationRouteResult has already returned 'missing' for this repoId.
That function (worktree-operation-catalog-route.ts) indexes every repo row carrying a
non-empty executionHostId or connectionId and resolves/ambiguous-es on any of them, so by
construction every row resolveUnstampedLocalWorktreeRoute ever sees is unstamped -- and
getRepoExecutionHostId's own fallback (shared/execution-host.ts) always resolves an unstamped
row to local. The per-row disagreement check could never actually return null; it was dead
defensive code describing a state the caller's short-circuit already rules out. Reduced to
an existence check with identical behavior (verified: same 66/66 tests, same mutation-proof
property -- reverting only this file still fails exactly the same 6 tests it did before).
Also harmonized a same-function 'local' string literal to the LOCAL_EXECUTION_HOST_ID constant
already in use one branch above it, and dropped a dangling getWorktreeExecutionHostId doc
reference the shipped code never actually calls.

* docs(routing): document the undocumented worktree operation route helpers
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
stablyai#16841 still fails closed (stablyai#16829)

* test(worktrees): cover local worktree owner routing with saved runtimes (stablyai#16733)

A local git worktree whose rows carry no host stamp fails every owner-routed
operation closed as soon as any runtime environment is saved, however unrelated.
resolveWorktreeOperationRouteResult establishes positive identity from the
worktree/repo catalogs, then discards it: with no runtime active the only exit is
the legacy-local gate, which demands an empty saved-runtime list. One saved
environment makes that false and the call returns { kind: 'missing' }.

These tests state the contract before the fix, so the claim that the fix is
purely additive can be checked rather than asserted. Committed red on purpose.

Observed at 5631aa0 (vitest run, both files):

  Tests  7 failed | 52 passed (59)

The 7 failing are exactly the states that must become local, plus their two
consumers:

  - an unrelated runtime is saved (the reported bug)
  - several unrelated runtimes are saved
  - the repo is known before its worktree row is listed
  - the saved-runtime catalog has not hydrated
  - an unrelated runtime was removed
  - resolveTerminalWorktreeRoute on such a worktree (the gate in front of the
    "Terminal creation is unavailable" reply)
  - the folder/worktree parity state: identical store, folder local, worktree
    missing

The other 52 pass now and must keep passing: connection-owned and
runtime-stamped repos never route local, a stamped worktree row still outranks
its repo, contradictory repo rows stay ambiguous, an ambiguous or hydrating
runtime focus still fails closed, and a genuinely unknown id still fails closed.
That set is the additive-only guarantee.

* test(worktrees): re-aim two fail-closed cases at genuinely missing owners (stablyai#16733)

Two cases in src/renderer/src/lib/worktree-operation-route.test.ts assert the
behaviour stablyai#16733 reports as the bug, so they have to move:

  - :158 'fails a paired-client ownerless stale publication closed instead of
    routing it locally'
  - :171 'fails ownerless rows closed until the saved-runtime catalog is hydrated'

Both arrived with stablyai#9994 (41751dd, route HUB-owned SSH worktrees through their
owning runtime), whose stated goal was to fail closed for missing or stale
owners. That goal is right and is kept. The premise being rebutted is narrower:
neither fixture describes a missing or stale owner. Each carries a present repo
row that is merely unstamped -- repos: [{ id: 'repo-1' }] -- and three places in
this codebase already read exactly that row as locally owned:

  - shared/execution-host.ts getRepoExecutionHostId returns LOCAL_EXECUTION_HOST_ID
  - main/ipc/worktrees/listing/worktree-host-ownership.ts resolveRepoOwnershipEvidence
    falls back to LOCAL_EXECUTION_HOST_ID, and the listing and removal paths trust it
  - shared/repo-types.ts documents executionHostId as the field runtime-host repos
    need precisely because they otherwise look identical to local repos

attribute. It swept in the legacy-local case because at the time nothing in this
resolver consulted the repo index for an unstamped row.

So each case is re-aimed at the state it was actually defending, and neither is
deleted -- the fail-closed coverage is not reduced, it is pointed at a real
missing owner:

  - the first becomes 'fails a paired-client publication closed when no repo row
    can own it': same runtime state, repos: []. A worktree row alone is not host
    evidence, so this still returns missing, before and after the fix.
  - the second becomes 'fails ownerless rows closed mid-hydration while a saved
    runtime could own them': an active runtime with an ambiguous saved catalog
    during hydration. This returns missing from the active-runtime branch and is
    untouched by the fix. It is worded to stay distinct from the neighbouring
    case at :185, which already covers focus-is-not-ownership with an empty
    catalog, rather than duplicating it.

The states these two cases vacate are re-asserted with their corrected expected
result in the stablyai#16733 block added by the previous commit. Suite unchanged at
7 failed | 52 passed (59): the rewrites pass, the 7 reds are still the 7 states
the fix must convert.

* fix(worktrees): keep unstamped local worktrees routable when runtimes are saved (stablyai#16733)

resolveWorktreeOperationRouteResult establishes positive identity from the
worktree and repo catalogs, then discards it. With no runtime active the only
exit is the legacy-local gate, which requires an empty saved-runtime list, so one
saved runtime environment -- connected or not, related or not -- made it false
and the call returned { kind: 'missing' }. Every owner-routed operation on a
genuinely local git worktree then failed closed, and because
resolveTerminalWorktreeRoute is the sole gate in front of
terminal-request-ipc-bridge.ts, the user saw "Terminal creation is unavailable
because the worktree owner could not be resolved".

Folder workspaces hit the same gate and were carved out in stablyai#10251/stablyai#10269, whose
comment in this file states the principle and names this exact failure mode: a
found record is positive identity evidence, and the worktree legacy hydration
gates "would fail local folders closed whenever unrelated runtimes exist". Git
worktrees never got the equivalent. This adds it, in the same shape and the same
function.

The rule is not new. An unstamped repo row is read as locally owned by
getRepoExecutionHostId, by main's resolveRepoOwnershipEvidence, and by
Repo.executionHostId's own documentation; and the repo write path
(repoWithFetchedOwner) stamps runtime: and ssh: owners at fetch time, so an
unstamped row is a legacy row that predates owner projection -- local by
construction. The router now consults that evidence instead of contradicting it.
The sidebar already rendered these worktrees as Local; this removes the
disagreement rather than adding a heuristic.

Four properties this change holds to:

1. The branch sits after the active-runtime block, so an unambiguous active
   runtime still wins (routes runtime:<id>, not local) and an ambiguous or
   mid-hydration focus still returns missing. That ordering is structural, not
   incidental.
2. mayBeLegacyLocal is left byte-identical (verified: both 7-line hunks hash to
   f0ed1b4287c646cb). The new branch does take over the two states where a local
   repo row exists and no runtime is saved, but returns the identical local
   route, so no input changes its answer -- only which branch produced it.
3. The helper returns null on anything but unanimous local, so the branch can
   only ever convert missing into local. It never returns ambiguous: a
   contradiction between repo rows is already decided upstream by
   resolveExplicitWorktreeOperationRouteResult, and answering it here would be a
   second, divergent authority.
4. It reads neither runtimeEnvironmentCatalogHydrated nor
   removedRuntimeEnvironmentIds. That is sound rather than merely convenient,
   because it consults host evidence rather than runtime-environment inference: a
   runtime-owned repo row is stamped runtime:<id> at fetch time, so neither an
   unhydrated runtime catalog nor a removed environment can turn an unstamped row
   into a remote one.

Control only reaches this point after the explicit catalog resolver returned
missing, which means every worktree row and every repo row for this id is
unstamped -- any stamped row routes ssh: or runtime: earlier, and two disagreeing
rows return ambiguous earlier. There is no remote-owned state left here to leak.

Out of scope, deliberately: who wins when a runtime is focused (stablyai#11512), and
back-filling Worktree.hostId at creation time, which is a persistence migration
over worktreeMeta and does nothing for the users already carrying unstamped rows.

The 7 cases red in the two preceding commits now pass; the 52 that guard the
fail-closed contract are unchanged.

  Test Files  2 passed (2)
       Tests  59 passed (59)

* test(worktrees): defer repo-row-only routing to stablyai#16841's fail-closed rule (stablyai#16733)

Upstream stablyai#16841 (merged d347595) landed its own fix for stablyai#16733 and drew the
positive-identity line one notch tighter than this branch did: its
'does not treat a repo row alone as positive local identity' case asserts that a
worktree id no row has ever listed stays `missing`, even when the repo row for
its repoId is local.

This branch's 'routes a known local repo before its worktree row has been listed'
asserted the opposite result for that identical state, so the two cannot both
hold. Main's rule is the safer reading — a repo row is repo identity, not
worktree identity — so the reconciled code gates
resolveUnstampedLocalWorktreeRoute on hasKnownWorktree and this case is dropped
rather than re-pinned. Every state that actually reproduces stablyai#16733 keeps a
worktree row (listed or detected), so the reported bug and both extra
fail-closed edge cases this branch fixes are unaffected.

* refactor(worktrees): drop the unreachable disagreement loop in resolveUnstampedLocalWorktreeRoute

resolveWorktreeOperationRouteResult only calls resolveUnstampedLocalWorktreeRoute after
resolveExplicitWorktreeOperationRouteResult has already returned 'missing' for this repoId.
That function (worktree-operation-catalog-route.ts) indexes every repo row carrying a
non-empty executionHostId or connectionId and resolves/ambiguous-es on any of them, so by
construction every row resolveUnstampedLocalWorktreeRoute ever sees is unstamped -- and
getRepoExecutionHostId's own fallback (shared/execution-host.ts) always resolves an unstamped
row to local. The per-row disagreement check could never actually return null; it was dead
defensive code describing a state the caller's short-circuit already rules out. Reduced to
an existence check with identical behavior (verified: same 66/66 tests, same mutation-proof
property -- reverting only this file still fails exactly the same 6 tests it did before).
Also harmonized a same-function 'local' string literal to the LOCAL_EXECUTION_HOST_ID constant
already in use one branch above it, and dropped a dangling getWorktreeExecutionHostId doc
reference the shipped code never actually calls.

* docs(routing): document the undocumented worktree operation route helpers

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants