Repository navigation
refactor(terminal): report breaches of the two layout invariants; add an unrun load repair - #25673
Conversation
… 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.
…ck throws; plain-language comments
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configuration
📒 Files selected for processing (1)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughThe 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 Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to 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 ReviewSecurity architecture risk: 🔵 Low · up to 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 Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
e631b9c0-7715-4e55-971f-ba18b98d93c7
📒 Files selected for processing (7)
src/main/persistence/loading-store/pty-binding-persistence.tssrc/main/persistence/loading-store/pty-binding-span.tssrc/main/persistence/terminal-topology/terminal-owner-invariants.test.tssrc/main/persistence/terminal-topology/terminal-owner-invariants.tssrc/main/persistence/terminal-topology/terminal-owner-load-repair.test.tssrc/main/persistence/terminal-topology/terminal-owner-load-repair.tssrc/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.
| /** 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) | ||
| ) | ||
| } |
There was a problem hiding this comment.
🗄️ 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.tsRepository: 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 -160Repository: 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.
| /** 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.
There was a problem hiding this comment.
ℹ️ 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.tsand its test), deferring it to the change that runs it. - Threaded the landing
hostIdintofindTerminalBindingConflictand split a leaf held by another tab on another host into its ownleaf_in_other_tab_on_other_hostreason. - Reworked
isSameTerminalso a repeating relay id (…@@pty-N) with either incarnation unrecorded is no longer treated as the same terminal. ptyBindingIsRefusednow 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.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
(cherry picked from commit 1a5f687)

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:findTerminalBindingConflictreports 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 likepty-1without 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.persistPtyBinding) runs that check after its fast path (so a no-op rebind skips the scan) and records any breach asbinding.owner_conflicton the existingpersistence.pty-bindingtrace span. The binding is written exactly as before, whether the check finds a breach, finds nothing, or throws (a throw is recorded ascheck_threw).ptyBindingIsRefusedtakes 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 andcheck:code-quality:changedpass; 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-topologyandpersistence/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
docs/reference/agent-skill-sharing-upstream-boundary.mdand 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
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)