Skip to content

refactor(terminal): one PTY attribution for teardown, close and identity; delete the deprecated owner resolver - #30626

Merged
nwparker merged 5 commits into
mainfrom
nwparker/r3-f8-pty-attribution
Oct 19, 2026
Merged

nwparker merged 5 commits into
mainfrom
nwparker/r3-f8-pty-attribution

Conversation

@nwparker

@nwparker nwparker commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When you close, hibernate or shut down a terminal, Orca has to work out which machine that terminal's process runs on. Until now it asked one resolver when it started the terminal and a different, older resolver when it stopped it. Usually the two agreed, but in a few edge cases they didn't. This PR makes stopping ask the same question starting does, and then deletes the older resolver.

What Changed

Before, for the user:

  • A project published by two hosts with an unstamped row (a "twin"), or a project whose SSH target two servers both claim, could have a terminal stopped on the wrong machine. It could also be left running while Orca believed it was closed.
  • A legacy remote: terminal id with no server named could be closed on this app instead of where it was started.

After:

  • Stop, hibernate and close land where spawn put the process. If Orca can't tell which host that was, the remote id is skipped and logged. It is never closed locally.

Mechanism:

  • resolveTerminalPtyOwner plus isUnattributedTwinWorktree (in lib/terminal-worktree-route.ts) sit on top of resolveTerminalHostOwnership, which spawn already uses. Shutdown, pane and agent hibernation, individual close, and PTY identity all read them.
  • Contested ssh: targets, handled in resolveStrictWorktreeOperationRouteResultForHost:
    • two servers both claim the target → ambiguous;
    • a direct repo row backs the listing → it is dialled directly, even when servers proxy the same target id;
    • any other contradiction → ambiguous.
  • Spawn's git branch takes this strict route whenever a host is named, so resolveOwner and the terminal route answer alike.
  • Deleted:
    • getRuntimeEnvironmentIdForWorktree / resolveRuntimeOwnerForWorktree. The legacy branch survives only as the private fallback inside resolveOwnerWithLegacyFallback.
    • the alias golden test. Its answers are kept as a fixture, so both acceptance tests list every deliberate difference.
    • the deprecated-importer ratchet script, its baseline, its pr.yml step and the package.json script.
  • hasHostEvidence now reads the owner indexes instead of scanning.

Deliberate differences from the deleted resolver's teardown answers. Exactly these, as listed in terminal-pty-owner-acceptance.test.ts:

  • C, stale server stamp (3 rows): follows spawn to the server;
  • D77, folder twins (6 rows): ambiguous;
  • B, rival servers (2 rows): ambiguous.

Every one moves an answer toward the server or to "refuse", never toward local.

Why

  • Spawn and teardown disagreeing is exactly the asymmetry behind fix(runtime): route HUB-owned SSH worktrees through owning runtime #9994 and STA-2639. Sharing the spawn resolver itself makes disagreement structurally impossible. An adapter that merely "matches" spawn could drift again.
  • Deleting the deprecated pair ends the parallel-resolver family that round 3 has been folding away (57 importers → 0).
  • Net diff is negative: the deleted pair, golden test, ratchet and baseline outweigh the new attribution.

Alternatives considered:

  • Keeping the old resolver for teardown only. That leaves the asymmetry in place.
  • A new teardown-only adapter. That would be a second source of truth.

Linked Issue

Round 3 of the SSH/remote hardening (design round3-design.md §7, S6(a)/F8). No single issue.

Visual Proof

N/A. There's no UI change; this is ownership routing for terminal teardown.

Testing

  • terminal-pty-owner-acceptance.test.ts:

    • the whole owner matrix against the deleted resolver's answers, with only the deliberate differences;
    • the contested-target rule: direct plus proxy, two proxies, and direct plus two proxies.
  • terminal-tab-close-providers.test.ts: an ambiguous owner skips and logs an unscoped remote: id instead of closing it on this app. This fails before the fix.

  • terminal-pane-retirement-ownership.test.ts, worktree-runtime-owner.test.ts, paired-web-client-host.test.ts, store/terminals/.

  • Local units: src/renderer/src/lib, src/renderer/src/store, components/terminal-pane, components/terminal-workspace, config/scripts, single worker. 2,074 files passed. The 3 failing config/scripts build-harness files (process-host-dev-rebuild, main-entry-facade, macos-terminal-host-bundle) fail identically on origin/main on this machine.

  • Full pr.yml static job run locally: 0 failures.

  • ssh-orcad Docker lane: dispatched on the head (all tests/e2e/ssh-orcad-*.spec.ts).

  • Live verification: none beyond the Docker lane. This changes which host a teardown targets in twin and contested states, which the unit matrix enumerates exhaustively.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Claude (Opus) implemented this. Codex (gpt-6.1-sol, high) and a separate Opus pass reviewed it.

Review

  • Codex (3 rounds):
    • rounds 1 and 3 clean;
    • round 2 found a P1, a test-only type error in the new close-provider fixture. Fixed.
  • Opus: no P1 and no P2. Its P3s:
    • Fixed: close-path test added; the three-row contested case pinned (direct wins); a comment corrected.
    • Dismissed:
      • An unparseable named host reads local on teardown. It is typed ExecutionHostId, and resolveOwner uses the same rule, so they stay in parity.
      • Extra hub-owner scans on the identity path. These run only for unscoped remote: ids, and no indexed lookup became a scan.

ref-oss check (after 3+ review rounds; VS Code terminalProcessManager.ts/remotePty.ts, Zed project/src/terminals.rs):

  • Both store the owner on the terminal at spawn, and kill/close go through that handle. Neither resolves the owner again at teardown.
  • Orca already does this for its primary path: scoped remote:<env> PTY ids carry their server, and close and identity use it directly.
  • This PR's "same resolver, refuse when ambiguous" applies only to legacy unscoped ids that stored no owner. That is the migration fallback ref-oss recommends, and VS Code likewise throws instead of defaulting to local.
  • The approach is unchanged. Persisting an owner field for the last unscoped records would be a separate wire change (optional field), not needed here.

Focus-read ratchet: 1085 → 1081. The ratchet's discovery skips functions that return their value inside an object literal, so it does not count resolveTerminalPtyOwner. That function reads the focused runtime only for setup terminals, as before. Seeding it would newly count about 10 teardown files that the deleted resolver also never registered in. So I left the discovery unchanged rather than inflate the baseline.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • SSH: a remote PTY is never closed or killed on local because of an ambiguous owner. Loss of contact is not treated as process exit.
  • Folder workspaces: folder twins refuse instead of guessing. Raw ids on folders still tear down locally, as before.
  • Wire: none, renderer only. Cross-platform: no platform-specific code.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…ity; delete the deprecated resolver pair

- strict ssh: route: a proven direct listing beats a same-id server proxy; other contradictions refuse
- terminal spawn's git branch takes the strict route when a host is named (rivals refuse)
- resolveTerminalPtyOwner + isUnattributedTwinWorktree replace resolveRuntimeOwnerForWorktree in
  shutdown, pane and agent hibernation, and PTY identity; close logs unroutable runtime ids
- delete getRuntimeEnvironmentIdForWorktree/resolveRuntimeOwnerForWorktree (legacy branch moved
  into the adapter), the alias golden test, the importer ratchet, its baseline and pr.yml step
- hasHostEvidence reads the owner indexes instead of scanning repos and groups
…ed remote ids (Opus P2)

- an unattributed twin's unscoped remote: id is skipped and logged on close, never closed locally
- setup terminals: identity and close follow spawn's runtime; raw-id teardown stays local
- drop the last stale getRuntimeEnvironmentIdForWorktree mock (tests/e2e unit suite)
@coderabbitai

coderabbitai Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

The change adds terminal PTY ownership classification and updates worktree routing to use strict host-specific resolution when a named host is available. Terminal hibernation, shutdown, and retirement paths now use the PTY owner resolver. Runtime environment lookup callers and tests use the legacy-fallback helper. The change also removes the deprecated runtime-owner importer ratchet from the workflow, lint command, and related configuration.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to a0d7d

The change routes terminal teardown through the shared host-attribution resolver and skips closes whose owner is ambiguous. No merge-blocking issue was identified; the test mock could be tightened.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 42.31% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 19 files. (2 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly identifies the main changes: consolidating PTY attribution for teardown, close, and identity, and deleting the deprecated resolver.
Description check Passed The description is detailed and covers the required change, rationale, testing, risks, review notes, and checklist. The Linked Issue section does not contain an actual issue link, and the standard com…
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.
Full details: Description check

Explanation

The description is detailed and covers the required change, rationale, testing, risks, review notes, and checklist. The Linked Issue section does not contain an actual issue link, and the standard command checklist remains unchecked, but the description is otherwise complete.

Full details: Docstring Coverage

Explanation

Docstring coverage is 42.31% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 19 files. (2 skipped: 2 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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: 1
src/renderer/src/store/terminals/terminal-tab-close-providers.test.ts: 1

11-14: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make the "where spawn started it" test depend on the mocked owner.

The resolveTerminalWorktreeRoute mock always returns env-a. The test also sets mocks.ptyOwner.current to env-a. Because of this, the first test passes for any non-ambiguous owner value. The test does not prove that the close destination follows the owner that spawn resolved. Derive the route mock from mocks.ptyOwner.current, or set a different environment ID for the route mock. Then the assertion checks a real dependency.

Based on learnings: "check that the test actually exercises that resolution path (e.g., via a fake provider/fixture returning values that differ from defaults)".

♻️ Proposed change
 vi.mock('@/lib/terminal-worktree-route', () => ({
   resolveTerminalPtyOwner: () => mocks.ptyOwner.current,
-  resolveTerminalWorktreeRoute: () => ({ runtimeEnvironmentId: 'env-a' })
+  resolveTerminalWorktreeRoute: () => ({
+    runtimeEnvironmentId:
+      mocks.ptyOwner.current.kind === 'runtime' ? mocks.ptyOwner.current.environmentId : null
+  })
 }))
   it('closes it where spawn started it', () => {
-    mocks.ptyOwner.current = { kind: 'runtime', environmentId: 'env-a' }
+    mocks.ptyOwner.current = { kind: 'runtime', environmentId: 'env-spawn' }
     retire()
     expect(mocks.callRuntimeRpc).toHaveBeenCalledWith(
-      { kind: 'environment', environmentId: 'env-a' },
+      { kind: 'environment', environmentId: 'env-spawn' },

Also applies to: 48-56

Source: Learnings


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 510fbc27-1dac-4a09-ab6f-194a65c1955c
📥 Commits

Reviewing files that changed from the base of the PR and between 5f2bb93 and a0d7df9.

📒 Files selected for processing: 28
  • .github/workflows/pr.yml
  • config/deprecated-runtime-owner-importers-baseline.txt
  • config/focus-setting-read-baseline.txt
  • config/scripts/check-deprecated-runtime-owner-ratchet.mjs
  • config/scripts/check-deprecated-runtime-owner-ratchet.test.mjs
  • config/scripts/pr-preflight-gates.test.mjs
  • package.json
  • src/renderer/src/components/terminal-workspace-model.ts
  • src/renderer/src/lib/agent-hibernation-coordinator.ts
  • src/renderer/src/lib/agent-hibernation-runtime-owner.ts
  • src/renderer/src/lib/legacy-runtime-owner-answers.test-fixture.ts
  • src/renderer/src/lib/paired-web-client-host.test.ts
  • src/renderer/src/lib/resolve-owner-acceptance.test.ts
  • src/renderer/src/lib/runtime-owner-alias-golden.test.ts
  • src/renderer/src/lib/terminal-pty-owner-acceptance.test.ts
  • src/renderer/src/lib/terminal-worktree-route.ts
  • src/renderer/src/lib/worktree-operation-route.ts
  • src/renderer/src/lib/worktree-reactivation-preserved-pane-replacement.test.ts
  • src/renderer/src/lib/worktree-runtime-owner.test.ts
  • src/renderer/src/lib/worktree-runtime-owner.ts
  • src/renderer/src/store/slices/terminal-pane-retirement-ownership.test.ts
  • src/renderer/src/store/slices/terminal-tab-retirement.ts
  • src/renderer/src/store/terminals/terminal-pane-hibernation.ts
  • src/renderer/src/store/terminals/terminal-shutdown.ts
  • src/renderer/src/store/terminals/terminal-tab-close-providers.test.ts
  • src/renderer/src/store/terminals/terminal-tab-close-providers.ts
  • src/renderer/src/store/terminals/terminal-teardown-owner.ts
  • tests/e2e/codex-child-approval-activity-row.unit.test.ts
💤 Files with no reviewable changes: 7
  • .github/workflows/pr.yml
  • config/deprecated-runtime-owner-importers-baseline.txt
  • src/renderer/src/lib/runtime-owner-alias-golden.test.ts
  • config/scripts/check-deprecated-runtime-owner-ratchet.test.mjs
  • config/scripts/pr-preflight-gates.test.mjs
  • config/scripts/check-deprecated-runtime-owner-ratchet.mjs
  • tests/e2e/codex-child-approval-activity-row.unit.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@nwparker
nwparker merged commit 7ce58ec into main Oct 19, 2026
64 checks passed
DimitriBrick added a commit to ggrafhalfbrick/orca that referenced this pull request Oct 19, 2026
The upstream/main merge of 2026-10-19 deleted getRuntimeEnvironmentIdForWorktree
(stablyai#30626) and changed Store.updateRepo to take the repo as its host target. The
Perforce workspace target still imported the deleted function, so the renderer
failed to load and the window stayed black; the copy commands no longer type
checked.

- perforce-workspace-target reads runtimeEnvironmentIdWithLegacyFallbackUnlessTwin,
  the read-only replacement that keeps the old legacy fallback and twin-as-null answer
- detectProject passes the repo to updateRepo; its executionHostId names the host

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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