Skip to content

refactor(terminal): report breaches of the two layout invariants; add an unrun load repair - #25673

Merged
Jinwoo-H merged 10 commits into
mainfrom
terminal-topology-b1-3-owner-invariants
Oct 7, 2026
Merged

Jinwoo-H merged 10 commits into
mainfrom
terminal-topology-b1-3-owner-invariants

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​430 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​430
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​136 $\color{#cf222e}{\Huge{\mathbf{−}}}$​5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​131

ELI5

Two rules should always hold for terminal layout: one terminal is shown by one pane, and one pane lives in one tab. When they break, users see the same terminal in two panes or tabs and one of them freezes (Linear STA-9417, STA-9259). This PR adds a check for both rules. For now it only records what it finds in a trace. Nothing changes for users.

What Changed

  • terminal-owner-invariants.ts: findTerminalBindingConflict reports whether a new terminal binding would put one terminal in two panes, or one pane in two tabs, across the local and SSH sessions (a remote Orca server's sessions are skipped: only its own sync writes them). It counts one terminal as one PTY incarnation; a relay PTY id like pty-1 without both incarnations does not count, because relay ids repeat after a relay restart. A pane held by another tab on a different host is reported separately (leaf_in_other_tab_on_other_host), since the SSH reattach writes SSH panes into the local session and that may be one moved pane.
  • The binding write (persistPtyBinding) runs that check after its fast path (so a no-op rebind skips the scan) and records any breach as binding.owner_conflict on the existing persistence.pty-binding trace span. The binding is written exactly as before, whether the check finds a breach, finds nothing, or throws (a throw is recorded as check_threw).
  • ptyBindingIsRefused takes the host sessions with their host ids, so the binding write builds that list once for both checks.

Before/after for users: none. Same bindings, same saved state, nothing new sent out of the app.

Why

Later in this refactor, the binding write will refuse these breaches and a startup repair will remove saved duplicates, in the same release that removes the code creating today's duplicates. Turning a refusal on earlier would make the existing startup sweep fail visibly. Landing the check report-only now gives a baseline of how often duplicates happen in real use before anything changes. The repair lands with the change that runs it, so this PR carries no code without a caller.

Linked Issue

Maintainer PR. Part of the terminal layout refactor (Linear STA-9417, STA-9259).

Visual Proof

N/A: no behavior change.

Testing

  • pnpm tc, oxlint, oxfmt and check:code-quality:changed pass; the terminal layout boundary test passes unchanged.

  • Inertness test (terminal-owner-report-only.test.ts): seeds a profile with a saved duplicate, a folder workspace tab and an SSH session, then runs six bindings including both duplicate bugs, once with the check and once with it stubbed out. Every stored write and the final saved profile are byte-identical; the check reported exactly the three breaches; the seeded duplicate loads unchanged. A second run makes the check throw and shows the same result. Turning the check into a refusal, or removing the throw guard, fails the test.

  • Unit tests for both rules, the repeating relay id case and the other-host case; persistence/terminal-topology and persistence/loading-store: 369/369.

  • I manually tested these changes locally

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

Not manually tested in the app: no behavior or UI change.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

No change to saved state, wire protocols, SSH, mobile or platform behavior. The check adds one scan of the session's bindings to non-fast-path binding writes.

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)

… an unrun load repair

The binding write now checks, after the fast lane, that a terminal is bound to at most one
leaf and a leaf id is in at most one tab, and records a breach on the persistence.pty-binding
span as binding.owner_conflict. It never refuses or changes the write (D16). The load repair
for saved duplicates is added and unit-tested but not called on load; the B2 core turns on
refusal and repair together.
@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e05e0e54-4fe6-4a11-9cbc-a9c4a833c818
📥 Commits

Reviewing files that changed from the base of the PR and between 1d684c2 and b4209cc.

📒 Files selected for processing (1)
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts

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


📝 Walkthrough

Walkthrough

The changes add terminal-owner utilities that collect owners from local and SSH partitions, compare terminal identities, and detect binding conflicts. PTY binding persistence runs the check after fast-lane handling and records conflict reasons or check_threw without preventing writes. The span records the result, and partition refusal checks now use host-session partitions. Tests cover owner matching and verify that reporting does not change binding results, writes, or saved state. The subscription method also infers its return type from backgroundTasks.subscribe.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to b4209

The added check is diagnostic and does not change PTY binding writes. No concrete user-facing regression or merge-blocking risk is established; the PR appears ready for normal validation.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 75993

The change reports duplicate terminal ownership without changing which bindings are saved. No new attack path was established, but incomplete security coverage prevents a minimal-risk assessment.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The added diagnostic operation reaches saved local and SSH layouts in the current profile. Its inspected implementation reads ownership metadata and returns a classification; it does not execute terminal commands, acquire credentials, or write remote runtime state.

Trust Boundaries and Controls

  • observed — Existing source-binding and incarnation checks, closed-tab checks across all supplied partitions, retired-surface checks, and mayCreate restrictions still gate the write. The ownership detector's local/SSH filtering does not narrow the separate closed-tab refusal scan.

Resilience and Maintainability Implications

  • observed — A detector exception is reduced to check_threw before the existing write path continues. Consequently, this diagnostic is not a fail-closed security control, and duplicate-owner acceptance predates the added reporting rather than representing a newly weakened fence.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The title accurately describes the report-only invariant check, but it also says the PR adds a load repair. The PR objectives state that no repair is implemented or run. Remove the claim about adding a load repair. Use a title that describes the report-only terminal layout invariant check.
Docstring Coverage ⚠️ Warning Docstring coverage is 51.85% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The description covers the required sections, explains the change and its purpose, identifies the maintainer exception for the linked issue, marks visual proof as not applicable, and reports testing. …
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e631b9c0-7715-4e55-971f-ba18b98d93c7
📥 Commits

Reviewing files that changed from the base of the PR and between 17ecee6 and 6a46390.

📒 Files selected for processing (7)
  • src/main/persistence/loading-store/pty-binding-persistence.ts
  • src/main/persistence/loading-store/pty-binding-span.ts
  • src/main/persistence/terminal-topology/terminal-owner-invariants.test.ts
  • src/main/persistence/terminal-topology/terminal-owner-invariants.ts
  • src/main/persistence/terminal-topology/terminal-owner-load-repair.test.ts
  • src/main/persistence/terminal-topology/terminal-owner-load-repair.ts
  • src/main/persistence/terminal-topology/terminal-owner-report-only.test.ts

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

Comment on lines +79 to +113
/** A split, or a recorded focus, means the user worked in the tab. */
function hasUserHistory(session: WorkspaceSessionState, owner: TerminalLeafOwner): boolean {
const layout = session.terminalLayoutsByTabId[owner.tab.id]
return (
layout?.root?.type === 'split' ||
Object.values(session.unifiedTabs ?? {}).some((tabs) =>
tabs.some(
(unified) =>
unified.contentType === 'terminal' &&
(unified.entityId === owner.tab.id || unified.id === owner.tab.id) &&
typeof unified.lastFocusedAt === 'number'
)
)
)
}

/** Relay ids like `pty-1` repeat across relay restarts, so without incarnations they prove nothing. */
function isLegacyRelayIdMatchedByIdAlone(owners: readonly TerminalLeafOwner[]): boolean {
const relayPtyId = parseAppSshPtyId(owners[0]?.ptyId ?? '')?.relayPtyId
return (
relayPtyId !== undefined &&
/^pty-\d+$/.test(relayPtyId) &&
owners.some((owner) => owner.incarnationId === undefined)
)
}

/** Bound leaves grouped by terminal; a group whose incarnations all differ is stale, not shared. */
function groupLeavesByTerminal(owners: readonly TerminalLeafOwner[]): TerminalLeafOwner[][] {
const bound = owners.filter((owner) => owner.ptyId)
return [...groupedBy(bound, (owner) => owner.ptyId).values()].filter(
(group) =>
group.some((owner, index) => group.slice(index + 1).some((o) => isSameTerminal(owner, o))) &&
!isLegacyRelayIdMatchedByIdAlone(group)
)
}

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '56,100p' src/main/persistence/terminal-topology/terminal-owner-invariants.ts
sed -n '75,215p' src/main/persistence/terminal-topology/terminal-owner-load-repair.ts

Repository: stablyai/orca

Length of output: 7265


🏁 Script executed:

printf '%s\n' '--- changed file diff ---'
git diff --unified=5 17ecee6337e65ec39efe8de598183f679f8437c4 6a4639023a5526140544e8817df7397fe5ef6a79 -- src/main/persistence/terminal-topology/terminal-owner-load-repair.ts

printf '%s\n' '--- relevant symbols and callers ---'
rg -n -F -- 'repairDuplicateTerminalOwners' src test tests 2>/dev/null || true
rg -n -F -- 'isSameTerminal' src/main/persistence/terminal-topology src/main/persistence 2>/dev/null || true
rg -n -F -- 'parseAppSshPtyId' src/main src/shared 2>/dev/null || true
rg -n -F -- 'collectTerminalLeafOwners' src/main/persistence/terminal-topology src/main/persistence 2>/dev/null || true

printf '%s\n' '--- terminal owner invariant declarations ---'
nl -ba src/main/persistence/terminal-topology/terminal-owner-invariants.ts | sed -n '1,180p'
printf '%s\n' '--- repair file complete relevant declarations ---'
nl -ba src/main/persistence/terminal-topology/terminal-owner-load-repair.ts | sed -n '1,250p'

Repository: stablyai/orca

Length of output: 33896


🏁 Script executed:

printf '%s\n' '--- repair tests ---'
nl -ba src/main/persistence/terminal-topology/terminal-owner-load-repair.test.ts | sed -n '1,360p'

printf '%s\n' '--- PTY ID contract ---'
nl -ba src/shared/ssh-pty-id.ts | sed -n '1,130p'
rg -n -F -- 'terminalPtyIncarnationsByPaneKey' src/main src/shared | head -80

printf '%s\n' '--- retirement helper ---'
rg -n -F -- 'function retireTerminalSurfaceFromPersistence' src/main
nl -ba src/main/runtime/mobile-session-terminal-persistence-retirement.ts | sed -n '1,260p'

printf '%s\n' '--- state/input construction around incarnation writes ---'
rg -n -F -- 'incarnationId' src/main/persistence src/main/runtime src/main/ipc src/shared | head -160

Repository: stablyai/orca

Length of output: 42267


🏁 Script executed:

printf '%s\n' '--- retirement helper exact bounds ---'
nl -ba src/main/runtime/mobile-session-terminal-persistence-retirement.ts | sed -n '35,125p'

printf '%s\n' '--- remaining repair tests ---'
nl -ba src/main/persistence/terminal-topology/terminal-owner-load-repair.test.ts | sed -n '320,460p'

printf '%s\n' '--- groupedBy contract ---'
nl -ba src/shared/grouped-by.ts | sed -n '1,100p'

Repository: stablyai/orca

Length of output: 7321


Do not let a missing incarnation bridge distinct terminals.

For a non-legacy PTY ID, owners with incarnations A, missing, and B pass the current pairwise grouping check. A/missing and missing/B match, although A and B are distinct terminals. repairPartition can then unbind or retire the B binding and its tab.

Skip a group when it has a missing incarnation and more than one distinct recorded incarnation. Retain the existing legacy relay-ID exclusion.

Suggested fix
-/** Relay ids like `pty-1` repeat across relay restarts, so without incarnations they prove nothing. */
-function isLegacyRelayIdMatchedByIdAlone(owners: readonly TerminalLeafOwner[]): boolean {
+/** Do not repair a group when an unrecorded incarnation bridges distinct terminals. */
+function shouldSkipTerminalGroup(owners: readonly TerminalLeafOwner[]): boolean {
   const relayPtyId = parseAppSshPtyId(owners[0]?.ptyId ?? '')?.relayPtyId
-  return (
-    relayPtyId !== undefined &&
-    /^pty-\d+$/.test(relayPtyId) &&
-    owners.some((owner) => owner.incarnationId === undefined)
-  )
+  const hasMissingIncarnation = owners.some((owner) => owner.incarnationId === undefined)
+  const recordedIncarnations = new Set(
+    owners
+      .map((owner) => owner.incarnationId)
+      .filter((id): id is string => id !== undefined)
+  )
+  return (
+    hasMissingIncarnation &&
+    ((relayPtyId !== undefined && /^pty-\d+$/.test(relayPtyId)) ||
+      recordedIncarnations.size > 1)
+  )
 }
@@
-      !isLegacyRelayIdMatchedByIdAlone(group)
+      !shouldSkipTerminalGroup(group)
   )
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/** A split, or a recorded focus, means the user worked in the tab. */
function hasUserHistory(session: WorkspaceSessionState, owner: TerminalLeafOwner): boolean {
const layout = session.terminalLayoutsByTabId[owner.tab.id]
return (
layout?.root?.type === 'split' ||
Object.values(session.unifiedTabs ?? {}).some((tabs) =>
tabs.some(
(unified) =>
unified.contentType === 'terminal' &&
(unified.entityId === owner.tab.id || unified.id === owner.tab.id) &&
typeof unified.lastFocusedAt === 'number'
)
)
)
}
/** Relay ids like `pty-1` repeat across relay restarts, so without incarnations they prove nothing. */
function isLegacyRelayIdMatchedByIdAlone(owners: readonly TerminalLeafOwner[]): boolean {
const relayPtyId = parseAppSshPtyId(owners[0]?.ptyId ?? '')?.relayPtyId
return (
relayPtyId !== undefined &&
/^pty-\d+$/.test(relayPtyId) &&
owners.some((owner) => owner.incarnationId === undefined)
)
}
/** Bound leaves grouped by terminal; a group whose incarnations all differ is stale, not shared. */
function groupLeavesByTerminal(owners: readonly TerminalLeafOwner[]): TerminalLeafOwner[][] {
const bound = owners.filter((owner) => owner.ptyId)
return [...groupedBy(bound, (owner) => owner.ptyId).values()].filter(
(group) =>
group.some((owner, index) => group.slice(index + 1).some((o) => isSameTerminal(owner, o))) &&
!isLegacyRelayIdMatchedByIdAlone(group)
)
}
/** A split, or a recorded focus, means the user worked in the tab. */
function hasUserHistory(session: WorkspaceSessionState, owner: TerminalLeafOwner): boolean {
const layout = session.terminalLayoutsByTabId[owner.tab.id]
return (
layout?.root?.type === 'split' ||
Object.values(session.unifiedTabs ?? {}).some((tabs) =>
tabs.some(
(unified) =>
unified.contentType === 'terminal' &&
(unified.entityId === owner.tab.id || unified.id === owner.tab.id) &&
typeof unified.lastFocusedAt === 'number'
)
)
)
}
/** Do not repair a group when an unrecorded incarnation bridges distinct terminals. */
function shouldSkipTerminalGroup(owners: readonly TerminalLeafOwner[]): boolean {
const relayPtyId = parseAppSshPtyId(owners[0]?.ptyId ?? '')?.relayPtyId
const hasMissingIncarnation = owners.some((owner) => owner.incarnationId === undefined)
const recordedIncarnations = new Set(
owners
.map((owner) => owner.incarnationId)
.filter((id): id is string => id !== undefined)
)
return (
hasMissingIncarnation &&
((relayPtyId !== undefined && /^pty-\d+$/.test(relayPtyId)) ||
recordedIncarnations.size > 1)
)
}
/** Bound leaves grouped by terminal; a group whose incarnations all differ is stale, not shared. */
function groupLeavesByTerminal(owners: readonly TerminalLeafOwner[]): TerminalLeafOwner[][] {
const bound = owners.filter((owner) => owner.ptyId)
return [...groupedBy(bound, (owner) => owner.ptyId).values()].filter(
(group) =>
group.some((owner, index) => group.slice(index + 1).some((o) => isSameTerminal(owner, o))) &&
!shouldSkipTerminalGroup(group)
)
}

…toast

Main (#25668) introduced a duplicate import that fails the focused code-quality lint.
…tion of same terminal

Defer the unrun load repair to the change that runs it. Repeating relay ids without both
incarnations are no longer one terminal, a leaf held on another host is reported apart, and the
refusal check takes host partitions directly.

@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 critical issues — two minor notes below.

Reviewed changes

Reviewed the delta since the prior reviewed version (c5288cd → 7599378), which narrows this PR to the report-only owner check.

  • Removed the unrun load repair (terminal-owner-load-repair.ts and its test), deferring it to the change that runs it.
  • Threaded the landing hostId into findTerminalBindingConflict and split a leaf held by another tab on another host into its own leaf_in_other_tab_on_other_host reason.
  • Reworked isSameTerminal so a repeating relay id (…@@pty-N) with either incarnation unrecorded is no longer treated as the same terminal.
  • ptyBindingIsRefused now takes the host partitions directly, and the binding write builds that list once for both checks.

The deletion resolves CodeRabbit's earlier finding about groupLeavesByTerminal (the pairwise isSameTerminal filter that a missing incarnation could bridge) — that code is gone. The unit and inertness tests are falsifiable: the relay-id test would pass under the old id-alone matching, and the report-only test asserts byte-identical writes/saved state with the check on, off, and throwing.

ℹ️ PR description still promises a load repair the branch no longer carries

The head commit removes the repair to defer it, but the title ("add an unrun load repair") and the ELI5, What Changed, Why, and Testing sections still describe it, so a reviewer is sent looking for a file that isn't there. Update the description to match the report-only scope.

Technical details
# Description out of sync with head

## Affected sites
- PR title — "add an unrun load repair"
- PR body — ELI5, "What Changed", "Why", and "Testing" all reference the load repair and `repairDuplicateTerminalOwners`, which no longer exist at `7599378`.

## Required outcome
- The description reflects that only the report-only check ships and the repair is deferred.

## Open questions for the human
- The body says the repair "lands with the change that runs it, so this PR carries no code without a caller." Now that it is removed here, does it return on this branch or land as its own PR?

ℹ️ Nitpicks

  • TerminalLeafOwner.order (terminal-owner-invariants.ts:53) is set but never read now that the load repair — its only consumer — is gone, and the "for deterministic tie-breaks" comment no longer matches a caller. Keep it only if the deferred repair re-adds the sort.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit 55c86ce into main Oct 7, 2026
77 of 85 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