Skip to content

fix(terminal): a park must not discard the only copy of a remote pane's scrollback - #21285

Merged
nwparker merged 12 commits into
mainfrom
fix/park-discards-only-scrollback-copy
Sep 19, 2026
Merged

nwparker merged 12 commits into
mainfrom
fix/park-discards-only-scrollback-copy

Conversation

@nwparker

@nwparker nwparker commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 18 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1197 $\color{#cf222e}{\Huge{\mathbf{−}}}$​23 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1174
Prod 41 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​473 $\color{#cf222e}{\Huge{\mathbf{−}}}$​70 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​403

main still reproduces this, and #20096 is not the fix

A user on a current hourly build lost the contents of every terminal in an SSH workspace while tabs and splits survived. This reproduces on 09622f0c289.

#20096 (851befa9290) does not fix it. That PR gates parking on host-contact revocation — a host that refused us. The host here is live and reachable; it simply has no retained buffer for that pty (its headless emulator is disposed on pty exit, provider reset, a daemon transient fact, or an execution-context change). Such a host still advertises the paired-parking capability, and its park is still licensed. Different slice of the same area.

Root cause — three links

1. The park discards the only copy. A remote-runtime pty's bytes never transit the client's main process, so the pane's xterm buffer is the only client-side copy. Only the retention-budget force-park serialized it — force-park-buffer-capture.ts was called from exactly one place, the force-park loop in use-terminal-parking-pass.ts. The ordinary hysteresis cold-park, both worktree-level and per-tab, unmounted the pane and captured nothing.

2. The licence to unmount is a build constant. isParkRestorableTerminalPty → pairedRuntimeParkingEnvironmentIds → TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY, advertised unconditionally at src/main/runtime/orca-runtime-get-status.ts:66 from the static list at src/shared/protocol-version.ts:329. It is never checked against whether the host retained this pty's buffer, and no client→host park/retain handshake exists at all. The client discards its only copy on a capability that answers a different question than the one being asked.

3. An unverifiable answer is read as empty. reattach-result-handler.ts:295:

prefetchedParkModelSnapshot = result.kind === 'snapshot' ? result.snapshot : null

retry-worthy collapses to null with no retry. It is produced both when the host answers unavailable: 'no-serializable-buffer' — whose own host-side comment at terminal-multiplex-slot-frames.ts:244 reads "no serializer answered, which is not proof the pane is empty" — and when the snapshot request times out (hidden-output-snapshot-serialize.ts:63: "the reject path is the request timeout — the frame went out and the host stayed silent"). Blank pane, live bytes only.

This is the docs/reference/ssh-execution-boundary.md inversion: unverifiable read as exited, here destroying user data.

The fix

Capture before every park, not only force-park, reusing the existing capture machinery. No behaviour change in the happy path — the host image only paints when non-empty, so the client copy is visible only when the host has nothing.

It also makes an existing false comment true: replayed-scrollback-store-release.ts:19 claims "remote/SSH worktrees re-serialize at the next park", which held only for force-park. Now it holds.

Scope: within-session is fixed and proven; the restart case is not closed here

The reported symptom — switch workspace away, come back, content gone — is fixed, and the e2e proves it in both directions. A full app restart is a separate question that this PR does not answer. The user hit their bug during an app update, so read that limitation literally rather than assuming it generalises.

Durability across a restart: confirmed lost, and filed as #21295

Settled empirically after a false start. The park capture reaches the renderer store and does not reach disk:

[parked-restart] {"tokenBeforePark":true,"storeAtPark":315,"onDiskAfterQuit":0,
                  "storeAfterRelaunch":0,"tokenAfterReveal":false}

onDiskAfterQuit: 0 means the client's own orca-data.json was found and read, and carries the tab's layout without its buffers — so the loss is in the write path, not in sync or reveal. Tracked as #21295, with repro/parked-scrollback-restart as a runnable measurement. Deliberately not fixed here: it is a different layer, and the repro is currently red.

An earlier reading of this appeared to show the same loss but was invalid — the paired client's dispose() removes the profile directory, so the "relaunch on the same profile" was a first run on an empty one. That reading was withdrawn, and the missing quit/relaunch primitive is filed separately as #21296.

Also settled: the host's copy carries the layout but no buffers ({"capturedLocally":199,"hostBufferLength":0}, read out of ~/.orca/sessions/*.json in the Docker SSH container), so the reconnect hazard is not a race against a stale host copy — the host never has one.

The reconnect-merge fix is defensive; the park capture is not

Worth separating, because a reviewer flagged that the original wording understated it. canReleaseReplayedScrollbackFromStore (replayed-scrollback-store-release.ts:19-21) already discarded the client's only copy for any remote/SSH worktree, on the stated ground that "remote/SSH worktrees re-serialize at the next park" — and that sentence was false for cold parks, so the release was firing against a premise nothing upheld. This PR makes it true. That is repairing a broken invariant in the existing model, not wrapping a symptom.

The reconnect-merge change below is the part that is merely defensive.

remote-layout-scrollback-retention.ts and its call site in mergeDirectSshRemoteWorkspaceSession close a genuine "the merge discards the only copy" hole, and it is mutation-proven at its own level: unwiring the call fails both merge tests while the helper's own tests still pass.

It is not proven to change any user-visible outcome, and should not be read as part of the fix this PR demonstrates. The two topologies are disjoint. The data loss lives in paired/remote-runtime ptys, whose client syncs through web-session-tabs-sync, while that merge is reached only via applyDirectSshRemoteWorkspaceSnapshot — direct SSH. And the direct-SSH path has a daemon-backed restore that repaints the scrollback regardless: I confirmed that by disabling the park capture entirely in the SSH lane and watching the token still come back. That is also why an earlier SSH restart spec was deleted rather than shipped — its headline assertion was satisfied by that restore, so it passed with the fix removed.

Why not bump tab.generation on capture

The natural-looking fix is to mark the tab locally newer so the merge preserves it. Don't: the pane key is `${tab.id}-${tab.generation ?? 0}` (TerminalLegacyTerminalPanes.tsx:86), so a bump remounts the pane and destroys the very xterm buffer the capture just serialized — the fix would eat its own input. It would also lift the recovery-storm ledger ceiling (terminal-tab-recovery-ledger.ts:74-80) and let a stale local ptyId win through preserveNewerLocalTerminalFields.

Why stripping the buffers from the remote projection was rejected

Both reasons, because this looks like an obvious cleanup and will be proposed again:

  1. buffersByLeafId has a real consumer. A host-sourced layout reaches restoreScrollbackBuffers on a second desktop, so stripping removes the only cold-restore source another machine has for a parked SSH tab. That is documented intent (workspace-session-terminal-buffers.ts:121-125), not an accident.
  2. Stripping scrollbackRefsByLeafId would destroy data. A ref is "v1-" + sha256(tabId + "\0" + leafId) naming a local .bin. Because the hash is deterministic, a receiving client's local refs survive a pull only because the uploader ships the identical string. Strip it and the receiver drops its own refs on merge, then GCs its own snapshot files.

Upload volume: a frequency change, not a new location

Terminal content already reaches ~/.orca/sessions/*.json on the SSH host on sleep, hibernate, force-park and shutdown. This change makes it happen on ordinary parks too, bounded at 512 KiB/tab by pruneLocalTerminalScrollbackBuffers, which does run on the export payload (remote-workspace-target-sync.ts:195 → workspace-session.ts:340). A frequency change within an existing design — not a new place the user's content lives.

Review finding: the mirrored-layout rebuild discarded the capture (fixed, f210dece83c)

Raised in review. On the paired/remote-runtime topology — the one this PR targets — chooseRemoteTerminalLayout rebuilt a mirrored tab's layout from the host's picture and never carried buffersByLeafId / scrollbackRefsByLeafId forward, though it already receives existingLayout. The host publishes no scrollback of its own, so any applied session-inventory frame dropped the only client-side copy.

The mechanism is self-defeating rather than merely incomplete: the capture is what makes the stored layout differ from the rebuilt one, terminalLayoutEqual compares both buffer records (terminal-layout-equality.ts:53), so the write is not bailed out and apply-terminal-records.ts:62-70 assigns wholesale. The capture's own presence triggered its deletion. With the carry-through the layouts compare equal again and the write bails.

Measured on the rig rather than argued statically — forced frame between park and reveal, triggered by a host tab open (one of the snapshotVersion + 1 bumps in orca-runtime-sync-window-graph.ts:230-258, so the frame is genuinely applied rather than outranked by tracking-decisions.ts:108-116):

before fix   park 336 bytes -> after frame 0 bytes -> tokenAfterReveal false   (spec red)
after fix    park 411 bytes -> after frame 411     -> tokenAfterReveal true    (spec green)

The spec now forces that frame inside the park→reveal window and asserts survivedInventoryFrame, so it covers the destroying event rather than sitting adjacent to it. Previously it passed either way, because no frame happened to land in its window.

An identical fix was written and reverted earlier on this branch as "no measurable effect." That measurement ran on a harness deleting the client profile between launches, so nothing downstream of persistence could register — it was never actually tested. Recorded here because the revert is in the branch history and should not be read as evidence against the fix.

Open, measured, and not addressed by this PR

Both are consequences of this change and are real. Neither is fixed here; ordering is deliberate — correctness first.

Upload inflation. Buffers ride in a whole-session replace-session, not a delta: workspace-session-patch.ts:69-71 sets the entire terminalLayoutsByTabId map, then a 150 ms debounce and persist. At the enforced cap, measured: 4 tabs x 1 pane ≈ 2.2 MiB; 8 x 2 ≈ 9.0 MiB; 20 x 2 ≈ 22.4 MiB (≈188 s on a 1 Mbit uplink). Before this PR an ordinary-parked remote tab carried no buffers, so this is new volume on the common path. The carry-through does not fix it.

A shape worth evaluating, not yet built: keep client-side retention on every park but leave the upload on the pre-existing cadence (force-park, hibernate, shutdown). scrollbackRefsByLeafId already exists for exactly this — a ref is a deterministic hash naming a client-local .bin, so it costs a few bytes on the wire while the local restore reads the file. That would preserve both the data-loss fix and the second-desktop restore without putting tens of MiB on a slow uplink on every workspace switch. Whether it is cleanly separable is unverified.

Main-thread stall. The capture is synchronous xterm serialization on the renderer main thread: 80–280 ms per full pane, converging with the code's own estimate at terminal-shutdown-layout-capture.ts:49-50. Per pass: 4 panes ≈ 323 ms, 20 panes ≈ 1.6 s at 5k scrollback. It runs in the useEffect body and the trigger is the ordinary 30 s hidden-worktree cold park — by which time the user is typically working in a different workspace in the same renderer, so the stall lands on a visible terminal's keystrokes. Before this PR only the rare force-park captured.

E2E

tests/e2e/paired-remote-terminal-parked-scrollback-survives.spec.ts — paired-desktop topology, real remote-runtime ptys.

[parked-scrollback] after-inventory-frame {"leafIds":["16f8a50d…"],"length":345,"layoutKnown":true}
[parked-scrollback] host-retains {"tokenBeforePark":true,"parked":true,"tokenAfterReveal":true}
  ✓  1 … host retains the buffer › a cold-parked remote terminal restores its scrollback on reveal (10.0s)
[parked-scrollback] after-inventory-frame {"leafIds":["78a8d4c5…"],"length":411,"layoutKnown":true}
[parked-scrollback] host-empty  {"tokenBeforePark":true,"parked":true,"tokenAfterReveal":true}
  ✓  2 … host retains nothing › a cold-parked remote terminal keeps its scrollback when the host cannot answer (39.8s)
  2 passed (1.0m)

What the spec asserts. A token is typed into the terminal and echoed back by the fixture, so it exists only in that pane's buffer. Between park and reveal the spec forces a host session-inventory frame — a host tab open, one of the snapshotVersion + 1 bumps in orca-runtime-sync-window-graph.ts:230-258, so the frame is genuinely applied rather than outranked by tracking-decisions.ts:108-116 — then asserts survivedInventoryFrame before checking the reveal.

Three oracles in this spec were wrong before they were right, all the same shape: the test sat adjacent to the bug rather than on it. Worth stating because the diff cannot show it.

  1. A marker baked into the terminal's argv. Survived mutation, because a respawned command reprints its own argv. The tell was byte-identical buffer lengths across mutated and unmutated runs (338 / 281 both times) — the assertion was not reading what it claimed to.
  2. A direct-SSH restart variant. Passed with the park capture disabled entirely, because that path has a daemon-backed restore that repaints the scrollback regardless. Deleted rather than shipped.
  3. No forced inventory frame. Passed whether or not the mirrored-layout rebuild carried the capture, because no frame happened to land in its window. That is the review finding above, and it is why the frame is now forced inside the window.

Each was caught the same way — by disabling the fix and checking the test noticed, and by instrumenting beside the assertion so a reading could contradict itself. A measurement that reports only the number under test cannot.

Mutation results. Disabling the tab-level capture: storedBufferLength: 0, regression case fails, control still passes. Removing the mirrored-layout carry-through: after-inventory-frame length: 0, red on survivedInventoryFrame.

The control is insensitive to the fix by construction — with the host retaining its buffer the reveal is served by the host restore and never consults the client copy. That is what stops the regression case being green for a harness reason: if the harness stopped parking, stopped revealing, or never echoed the token, the control fails too.

Verification

  • pnpm tc clean; oxlint clean.
  • Merge-commit gate passes: ORCA_CODE_QUALITY_BASE=origin/main node config/scripts/check-changed-code-quality.mjs → "Changed-code quality gate passed since 09622f0." It first flagged 3 new as casts, all removed rather than suppressed — one of them was hiding an unvalidated RPC payload, now checked by readCreatedTerminalTab.
  • ⚠️ That gate printed Changed-code quality gate failed with 3 finding(s) while exiting 0. Do not trust its exit code; read the output. Same class of trap as the e2e runner exiting 0 with failures.
  • Terminal-pane unit suite: 4369 passed, 1 failed. The one failure (terminal-pane-hook-order-parity, expected length 209 but got 211) reproduces identically on a clean origin/main worktree — pre-existing, not from this branch.

Known interaction with the stale-resume investigation

A sibling investigation is tracing a coding agent auto-resuming a session id the host does not have. Its root cause is sleepingAgentSessionsByPaneKey, classified 'sleepingAgentKeyed' in src/shared/workspace-session-host-field-ownership.ts:50 — a class that bypasses host contention entirely, so every partition's records merge at boot with no provenance retained.

This PR does not touch that field, and does not increase exposure to that bug. Different field, different ownership class, different mechanism.

What the two do share is the partition router at src/renderer/src/lib/workspace-session-host-persistence.ts:196-198, which returns LOCAL_EXECUTION_HOST_ID when the repo is unknown at write time. terminalLayoutsByTabId is 'tabKeyed' (:46) and rides it. The consequence lands on this change rather than on theirs: if the catalog is unhydrated at write time, the buffers captured here route to the local partition, and after a restart the SSH partition has none — the fallback silently isn't there. That is a durability ceiling on the fix, not a new failure mode. Within a session (the reported scenario: switch away, come back) it does not apply, because the reveal reads the in-memory store rather than a reloaded partition.

No ordering constraint: this is safe to land alone. It never makes anything worse than main; at worst a mis-routed write leaves it no better than main for a park that straddles a restart.

Not covered by this PR

  • The worktree-level ordinary park is not e2e-covered. With only two worktrees, the one you switch away from holds the last-active exemption (perf(terminal): tune cold-park keep-warm so common rotation never remounts #8262), so it never becomes a park candidate — the scenario I attempted sat at parked: false. It uses the same capture helper and is unit-covered, but the e2e assertion is per-tab only.
  • The split-orientation flip is a separate bug and is not fixed here. It lives in synthesizeDegenerateLayout (remote-terminal-layout-resolution.ts:68-76), not in the parking path.
  • One flake worth knowing. The pre-existing paired-remote-terminal-parked-reveal-interactivity spec failed once on this branch (hostReceivedInput: false) then passed 5/5; baseline is 4/4. Not conclusive, but the mechanism is specific: the client fallback paints at mount, before the transport attaches, so the pane looks ready slightly earlier than it is, and pre-connect keystrokes are dropped. The drop itself is pre-existing; this change makes the window easier to hit. Clean follow-up: paint the fallback only after the host restore comes back empty.

@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview 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: f2d3de46-777d-48b7-ace7-2a7aae88d949

📥 Commits

Reviewing files that changed from the base of the PR and between c0a03e1 and 1156da924307fab9318516cc6554310dcea51e2b.

📒 Files selected for processing (4)
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts
  • src/renderer/src/runtime/web-session-tabs-sync/state.ts
  • src/renderer/src/runtime/web-session-tabs-sync/terminal-surfaces.ts
  • src/shared/workspace-session-terminal-buffers.ts

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


📝 Walkthrough

Walkthrough

The change captures terminal buffers for ordinary and force parking. It stores ordinary-park scrollback in a local-only per-tab home and resolves it with shared scrollback during restoration. It preserves scrollback when remote layouts replace local layouts. It carries the new state through persistence, synchronization, hydration, transfer, pruning, and cleanup paths. It adds an E2E-only snapshot-unavailable flag and paired-terminal tests for ordinary and force parking.

Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to 1156d

Some terminal parking and restore paths can still lose or retain stale scrollback. These flows should be corrected before merging.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides extensive technical context, rationale, testing evidence, limitations, and linked issue references, but it does not follow the repository template. Required sections such as E… Restructure the description using all required template headings. Add the actual linked issue in the Fixes #... field, add Visual Proof or N/A with a reason, complete the Testing checkboxes and platform coverage, complete AI Disclosure …
Docstring Coverage ⚠️ Warning Docstring coverage is 22.39% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 67 functions across 58 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: preventing remote terminal scrollback loss during parking.
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 provides extensive technical context, rationale, testing evidence, limitations, and linked issue references, but it does not follow the repository template. Required sections such as ELI5, What Changed, Why, Linked Issue with a Fixes entry, Visual Proof or N/A, checklist items, AI Disclosure, Review, and Agent skill upstream boundary are missing or incomplete.

Resolution

Restructure the description using all required template headings. Add the actual linked issue in the Fixes #... field, add Visual Proof or N/A with a reason, complete the Testing checkboxes and platform coverage, complete AI Disclosure when applicable, state the Review and Agent skill boundary status, add Notes, and complete the Checklist. Retain the existing technical details under What Changed, Why, and Testing.

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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: e99237b2-b2ea-4a86-8d71-ecdd2108b5a4

📥 Commits

Reviewing files that changed from the base of the PR and between 9de6f2c and af6e728.

📒 Files selected for processing (12)
  • src/main/runtime/rpc/methods/terminal/terminal-snapshot-publication.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-buffer-capture.test.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-buffer-capture.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-tab-capture-episodes.test.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-tab-capture-episodes.ts
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts
  • src/renderer/src/components/use-terminal-parking-foundation.ts
  • src/renderer/src/components/use-terminal-parking-pass.ts
  • src/shared/workspace-session-terminal-buffers.ts
  • tests/e2e/helpers/paired-host-terminal.ts
  • tests/e2e/paired-remote-terminal-parked-scrollback-survives.spec.ts

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

nowMs
})
// Why before the commit: the panes are still mounted in this flush — the last moment the only client-side copy of a remote tab's scrollback can be serialized.
captureNewlyParkedTerminalTabs(worktreeId, parkedTabIds, parkedTabCaptureDoneRef.current)

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '120,360p' src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts
rg -n 'useTerminalParkVerdictPin|parkedTabCaptureDoneRef|setParkedTabIds|parkedTabIds' src/renderer/src/components/terminal-pane
sed -n '1,280p' src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts

Repository: stablyai/orca

Length of output: 32482


🏁 Script executed:

sed -n '340,430p' src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts
cat -n src/renderer/src/components/terminal-pane/parked-terminal-tab-capture-episodes.ts
cat -n src/renderer/src/components/terminal-pane/use-terminal-park-verdict-pin.ts
cat -n src/renderer/src/components/terminal-pane/terminal-cold-park-withheld-tabs.ts
rg -n "captureNewlyParkedTerminalTabs|parkedTabCaptureDoneRef|coldParkedTerminalTabIds|parkedTerminalTabIds" src/renderer/src/components/terminal-pane --glob '*.ts' --glob '*.tsx'

Repository: stablyai/orca

Length of output: 16223


🏁 Script executed:

cat -n src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx | sed -n '90,175p'
fd -i 'parked-terminal-buffer-capture' src
cat -n src/renderer/src/components/terminal-pane/parked-terminal-buffer-capture.ts
rg -n "restore.*buffer|scrollback|captureParkedTerminalBuffers|no-serializable-buffer" src/renderer/src/components/terminal-pane src/shared

Repository: stablyai/orca

Length of output: 50369


Capture only tabs that will unmount.

parkedTabIds is the pre-render result from withholdUnparkableTerminalTabs. Later mounted-pane gates and useTerminalParkVerdictPin can keep a listed tab mounted. The capture helper then marks the tab in parkedTabCaptureDoneRef; it clears that entry only when a later call omits the tab. Additional output can arrive before the tab finally unmounts, while later capture attempts skip the unchanged ledger entry and restore stale scrollback.

Align the capture ledger with the final rendered park verdict, or remove tabs withheld by later gates so their final park pass captures them again.

@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.

Important

The fix covers the automatic park paths but not the manual park path (Developer > Park terminal), which also unmounts a paired remote worktree's panes and still discards the only client-side copy. Because manual parking is driven from an event handler rather than the parking pass, the new worktree-level capture cannot see it even if its ids were added to the loop.

Reviewed changes

  • Pre-park capture for the automatic parks — captureParkedTerminalBuffers is now called from the ordinary worktree-level pass and a new per-tab episode helper, so a remote-runtime pane's xterm is serialized before its park unmounts it.
  • Per-tab park episode ledger — parked-terminal-tab-capture-episodes.ts captures newly parked tabs once per episode, prunes on reveal so the copy re-arms, and captures one tab per call so a mid-remount tab stays unmarked and retries.
  • E2E host-unavailable override and paired spec — ORCA_E2E_FORCE_REMOTE_TERMINAL_SNAPSHOT_UNAVAILABLE makes the host answer no-serializable-buffer, and a new paired-desktop spec asserts a token typed before the park survives the reveal.
  • Shared paired-host terminal helper — tests/e2e/helpers/paired-host-terminal.ts extracts the host-terminal/mirror plumbing and validates the create-terminal RPC shape instead of casting it.
  • Rename/comment cleanup — the force-park-* names and the stale replayed-scrollback-store-release.ts claim are updated to match.

ℹ️ The stored copy is released without per-leaf confirmation

terminal-pane-layout-restore.ts:35-51 deletes the whole buffersByLeafId map for a remote/SSH worktree right after restoreScrollbackBuffers runs, without checking that every stored leaf was actually painted. restoreScrollbackBuffers silently continues past a leaf whose pane is unmapped, missing, or disposed (layout-serialization.ts:157-171), and replayIntoTerminal can no-op on a certified-dead pipeline — so the client copy can be deleted while the xterm never received it. This is pre-existing, but this PR makes that copy the designed fallback for every park, so the missing confirmation is now load-bearing.

Technical details
# Releasing the stored scrollback has no per-leaf success check

## Affected sites
- `src/renderer/src/components/terminal-pane/terminal-pane-layout-restore.ts:35` — the release runs unconditionally for remote/SSH worktrees once `restoredBuffers` is non-empty.
- `src/renderer/src/components/terminal-pane/layout-serialization.ts:157` — `restoreScrollbackBuffers` `continue`s on unmapped/disposed leaves without signalling failure.
- `src/renderer/src/components/terminal-pane/replayed-scrollback-store-release.ts:19` — the release justification now depends on xterm actually holding the bytes at the next park.

## Required outcome
Only drop the store copy for leaves whose buffer was written into a live pane; keep the rest so a later reveal or park can still use them.

## Open questions for the human (optional)
Is this reachable enough to warrant a follow-up, or does the park-reveal path always map every stored leaf?

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

// serialized. The paired-parking capability that licenses the unmount says nothing about
// whether the host retained this pty's buffer, so the park must not leave the client with
// nothing to fall back on. Force-parks capture below with their eviction-exempt carve-out.
for (const worktreeId of pass.nextParkedTerminalWorktreeIds) {

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.

The new capture loop only walks pass.nextParkedTerminalWorktreeIds, so a manual park (Developer > Park terminal) is never captured. Manual parking unmounts the same paired remote panes via effectiveParkedTerminalWorktreeIds → shouldColdParkTerminalPanes, and because it is driven from an event handler rather than this effect, the panes are already unmounted by the time the pass runs — so adding the manual ids to this set would not be enough on its own.

Technical details
# Manual park is still an uncaptured park

## Affected sites
- `src/renderer/src/components/use-terminal-parking-pass.ts:91` — loop input is `pass.nextParkedTerminalWorktreeIds` (automatic only).
- `src/renderer/src/components/terminal-pane/use-manual-terminal-worktree-parking.ts:69` — manual park sets `manuallyParkedWorktreeIds` from a window event.
- `src/renderer/src/components/use-terminal-parking-foundation.ts:56` — manual + automatic are combined into `effectiveParkedTerminalWorktreeIds`.
- `src/renderer/src/components/TerminalSplitWorkspaceSurfaces.tsx:53` — that combined set drives `shouldColdParkTerminalPanes`, which unmounts the panes.

## Required outcome
A manual park of a paired remote worktree must leave a client-side copy, or the PR should explicitly scope manual parking out of the "every park" invariant.

## Suggested approach (optional)
Capture in `parkWorktree` before `setManuallyParkedWorktreeIds` (the last moment the panes are mounted), reusing `captureParkedTerminalBuffers`. A pass-effect capture cannot work here because the unmount commits before the effect runs.

## Open questions for the human (optional)
Is manual park intentionally out of scope? If so, the helper/PR comment "every park" is misleading.

}
// Why one tab per call: coverage is reported for the whole batch, and a tab mid-remount must
// stay unmarked so the next pass retries it instead of parking it uncaptured.
if (captureParkedTerminalBuffers({ worktreeId, tabIds: [tabId], repos })) {

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.

captureParkedTerminalBuffers reports success as captured === requested, but captureTerminalShutdownBuffersBestEffort counts any registered callback that does not throw — including one that stores nothing. The registered capture returns early when manager/container is absent or the manager has no panes, so a tab can be marked captured here with no buffer stored and never retried, which is the case this comment says must retry.

Technical details
# Coverage signal counts a no-op capture as success

## Affected sites
- `src/renderer/src/components/terminal-pane/parked-terminal-buffer-capture.ts:30` — `return captured === requested`.
- `src/renderer/src/components/terminal-pane/shutdown-buffer-captures.ts:36` — `captured += 1` after any non-throwing callback.
- `src/renderer/src/components/terminal-pane/use-terminal-pane-title-effects.ts:190` — the registered callback returns without `setTabLayout` when the manager/container is missing or `panes.length === 0`.
- `src/renderer/src/components/use-terminal-parking-pass.ts:98` — the worktree-level caller passes every tab, so `requested` includes already-unmounted tabs and the worktree can never be marked.

## Required outcome
"Captured" should mean a buffer was actually stored, or the worktree-level request should be scoped so an unmounted tab does not pin the episode ledger open forever.

## Suggested approach (optional)
Capture one tab per call (as this helper already does) in the worktree-level loop too, and have the capture callback report whether it stored anything rather than throw-or-not.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues found in the incremental changes — the retention helper and its merge integration are clean, and the tests are non-vacuous. Prior review threads remain open.

Reviewed changes — incremental delta since the prior review at 3c75418:

  • Reconnect-merge retention — new retainLocalScrollbackInRemoteLayout carries this client's captured buffersByLeafId / scrollbackRefsByLeafId into the host layout when a direct-SSH reconnect replaces a tab's layout, filtered to the host's leaves and preferring the local copy on a conflict.
  • Merge integration — mergeDirectSshRemoteWorkspaceSession maps the replaced remote layouts through the helper, so a just-parked tab whose generation did not bump keeps its client-only capture.
  • Tests — a new helper suite (7 cases) and a merge-level suite (2 cases) proving the park capture survives a same-generation reconnect; both fail without the change.
  • Docs — the unhydrated-catalog fallback comments now explain why the parking and worktree-runtime-owner.ts decisions point in opposite directions.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker

Copy link
Copy Markdown
Contributor Author

Correction for the follow-up: the upload path is not workspace-session-patch.ts

Recording this so it doesn't get lost, because acting on the wrong line would produce a fix that measures better and changes nothing.

The upload-inflation finding cited workspace-session-patch.ts:69-71 — the branch that sets the entire terminalLayoutsByTabId map whenever any of three fields changed. That is the local disk persist: buildWorkspaceSessionPatch feeds persist({ patch }) at session-write-subscriber.ts:168.

The network path is a different function: buildWorkspaceSessionPayload (workspace-session.ts:340) → exportRemoteWorkspaceSession (remote-workspace-session-projection.ts:58) → a wholesale replace-session patch.

Both carry the buffers, so the measured MiB figures are real — but they are evidence about the export. A change aimed at the patch builder would cut disk I/O and leave the uplink untouched.

Shape of the follow-up, and why it is a separate PR

Ordinary-park captures move to a top-level session field (parkedScrollbackByTabId), leaving inline buffersByLeafId on the pre-existing force-park / hibernate / shutdown cadence.

Top-level is load-bearing: exportRemoteWorkspaceSession is an explicit allowlist of named top-level fields, so a new one is omitted from the upload for free. A field inside TerminalLayoutSnapshot would ride along instead, because layout entries are copied whole (remote-workspace-session-projection.ts:152-156).

Two properties worth keeping when someone tidies this later:

  • Immunity by construction. The mirrored-tab apply rewrites only ptyIdsByTabId and terminalLayoutsByTabId (apply-terminal-records.ts), so scrollback in a top-level field cannot be wiped by a host inventory frame at all. Moving it back into the layout would reintroduce the wipe this PR fixes.
  • One accessor. The two fields encode shared with peers vs local-only — a real distinction, not a duplicate. Every read must resolve through a single accessor; restoreTerminalPaneLayout's direct read of initialLayoutRef.current.buffersByLeafId is the drift vector.

The trap: once ordinary parks stop writing buffersByLeafId, this PR's survivedInventoryFrame assertion passes trivially — there is nothing left in the layout to wipe. The mirrored-layout retention fix stays necessary for force-park/hibernate/shutdown captures on mirrored tabs, so that coverage must re-point to a force-park scenario (terminalRetentionLimit is already an e2e override). Without that, the follow-up silently converts a mutation-proven assertion into a survivor.

Foundation is on wip/park-scrollback-local-field (typecheck clean, nothing reads or writes the field yet). Five exhaustive satisfies Record<keyof WorkspaceSessionState, …> constraints reject the field until every registry has an entry, which is why it has no safe partial state and does not belong as a commit here.

One note carried over rather than acted on: the new field is classified 'tabKeyed', so it routes through the same partition fallback at workspace-session-host-persistence.ts:196-198 that returns local when the repo is unknown at write time. That does not affect the upload, but park scrollback can land in the wrong partition during catalog lag, exactly as the layouts it shadows can.

nwparker added a commit that referenced this pull request Sep 17, 2026
Second foundation slice: the capture callback can now split a capture, keeping structure
(root, ptyIds, titles) in the shared layout and putting the bytes in parkedScrollbackByTabId,
which the remote projection never enumerates.

No caller yet, and none is possible on main: the ordinary cold-park capture that this cadence
split exists to redirect is #21285, which has not landed. A shared capture clears the local
copy so the two homes cannot both hold a stale version of the same leaf.

Typecheck clean.
@nwparker

Copy link
Copy Markdown
Contributor Author

Handover: cadence-split follow-up, parked at wip/park-scrollback-local-field@4e08314a194

Resumable by anyone. Two commits, both typecheck-clean, both deliberately independent of this PR.

The dependency that blocks the rest

The cadence split cannot be built off main. main has no ordinary-park capture — force-park-buffer-capture.ts / captureForceParkedWorktreeBuffers is the only capture there, called solely from the retention force-park loop. The ordinary-park capture is this PR. So "ordinary parks go client-local, the rare cadence stays shared" has nothing to redirect until #21285 lands.

The remaining work is mechanical once both cadences are in one tree, and not before.

Done

133bdb37e41 — the persisted field. WorkspaceSessionState.parkedScrollbackByTabId (top-level, Record<tabId, Record<leafId, string>>), zod schema + salvagedOptional salvage entry, and entries in all five exhaustive registries: host-field ownership ('tabKeyed'), profile-transfer disposition, worktree ownership, schema field coverage, relevant-fields. Plus AppState, initial state, setTabParkedScrollback, and the persisted payload wiring.

Those five satisfies Record<keyof WorkspaceSessionState, …> constraints reject the field until every registry has an entry. That is why it has no safe partial state, and it is the answer to "why does a volume fix touch ten files."

4e08314a194 — the localOnly capture option and the split write: structure (root, ptyIdsByLeafId, titlesByLeafId) stays in the shared layout, bytes go to the local field. Threaded through the store, pane store-actions and store-bindings.

Worth not re-deriving: a shared capture now clears the local copy (setTabParkedScrollback(tabId, null)). Without that, force-park after an ordinary park leaves both homes holding versions of the same leaf and the resolver has to arbitrate staleness it cannot see. Closing it at the write side means the read side only ever has to merge, never to choose. That is the same drift the one-accessor rule guards, handled one layer earlier.

Remaining (all require #21285 in the tree)

  1. Pass localOnly at the three call sites — true for the ordinary worktree park and the per-tab park, false for the retention force-park.
  2. The single resolver, with restoreTerminalPaneLayout losing its direct read of initialLayoutRef.current.buffersByLeafId — that read is the drift vector.
  3. pruneLocalTerminalScrollbackBuffers capping both fields, with a test that fails if an uncapped path exists.
  4. Re-point survivedInventoryFrame at a force-park scenario (terminalRetentionLimit is an existing e2e override). Once ordinary parks stop writing buffersByLeafId, that assertion passes trivially — the split would otherwise convert a mutation-proven assertion into a survivor.
  5. Measure 20×2 upload before/after, and mutate both directions: an ordinary park forced down the inline path must fail the size assertion; removing the mirrored-layout retention fix must fail the force-park scenario.

Two properties a later tidy-up would otherwise undo

  • Top-level is load-bearing. exportRemoteWorkspaceSession is an explicit allowlist of named top-level fields, so the field is omitted from the upload for free. A field inside TerminalLayoutSnapshot would ride along, because layout entries are copied whole.
  • Immunity by construction. The mirrored-tab apply rewrites only ptyIdsByTabId and terminalLayoutsByTabId, so scrollback in a top-level field cannot be wiped by a host inventory frame at all. Moving it into the layout reintroduces the wipe this PR fixes.

Not measured, deliberately

No 20×2 number: the split is not callable yet, so a before/after would be measuring nothing.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in the delta — one minor coverage suggestion inline.

Reviewed changes — incremental delta since the prior review at 8d1b187:

  • Mirrored-layout rebuild now retains the capture — chooseRemoteTerminalLayout wraps the host-derived layout in retainLocalScrollbackInRemoteLayout(existingLayout, …), so an inventory frame landing between park and reveal no longer replaces the parked tab's layout with a bufferless one.
  • E2E probe forces the destroying frame — the paired spec creates an extra host terminal and asserts the parked tab's buffer survived the resulting inventory frame, so the regression case proves the rebuild path rather than a quiet window.
  • Comment pinned — workspace-session-terminal-buffers.ts records why the unhydrated-catalog fallback points local here and the opposite way in worktree-runtime-owner.ts.

ℹ️ Nitpicks

  • The new comment at terminal-surfaces.ts:204-209 says only bytes for leaves "the host itself names" are carried over, but remote.root falls back to existingLayout.root when the host publishes no parentLayout, so the retained leaves can be the client's own tree. A word of qualification would keep a future reader from over-trusting the filter.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@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 — the new client-only scrollback home is sound; one cleanup gap and a stale PR description below.

Reviewed changes — incremental delta since the prior review at f210dec:

  • Added a client-only scrollback home — localOnlyScrollbackByTabId is a new session/store field, zod schema entry, field-disposition row, and host-ownership classification for the ordinary park's bytes.
  • Routed ordinary parks to it — captureParkedTerminalBuffers gained a localOnly option; ordinary parks write the local-only home while force-parks keep writing the shared layout.
  • Unified the read across both homes — resolveLeafScrollbackBuffers merges the two homes (local wins a leaf conflict) and now backs the capture merge and the mount restore.
  • Split persistence by home — the session patch writes the two homes under independent keys, and a host inventory frame can only remove the local-only home for a retired tab.
  • Pinned the mirrored rebuild — a new applyWebSessionTabsSnapshot case asserts the rebuild carries the client's scrollback refs and bails the layout write; it fails when the retention call is removed.
  • Extended the paired e2e — the spec now reads both homes, adds a force-park scenario gated on ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING, and asserts where each park's bytes land.

ℹ️ The orphan sweep leaves the new local-only home behind

buildOrphanTerminalCleanupPatch deletes terminalLayoutsByTabId for every orphaned tab but has no matching delete for localOnlyScrollbackByTabId. The orphan sweep is the path that retires dead terminal rows after SSH relay loss, so a remote pane's captured park scrollback (up to the 512 KiB per-leaf cap) stays resident in the renderer store for the rest of the session. The disk write drops it — pruneLocalTerminalScrollbackBuffers prunes by tabsByWorktree — so this is an in-memory retention rather than a persisted leak, but every other per-tab cleanup path added in this PR does drop the field, which makes this the odd one out. A narrower consequence: createTab accepts a caller-supplied id once it no longer collides, so a host/mobile-hinted id reusing an orphan's id would make the fresh tab restore the dead tab's scrollback on reveal.

Technical details
# Orphan cleanup does not purge localOnlyScrollbackByTabId

## Affected sites
- `src/renderer/src/store/slices/terminal-orphan-helpers.ts:167-185` — the per-orphan delete loop removes `terminalLayoutsByTabId` but not `localOnlyScrollbackByTabId`.
- `src/renderer/src/store/terminals/terminal-tab-creation.ts:217-269` — spreads `orphanCleanupPatch` and never rewrites the local-only map.
- `src/renderer/src/store/slices/tabs/tabs-reconciliation.ts:253-255` — the other caller.
- Compare the paths that were updated: `terminal-tab-close.ts`, `repo-removal.ts`, `worktree-purge-state.ts`, `remove-worktree-store-cleanup.ts`.

## Required outcome
An orphaned tab must drop its local-only scrollback entry in the same commit that drops its layout, matching the other cleanup paths.

## Suggested approach (optional)
Add `localOnlyScrollbackByTabId` to the `OrphanTerminalCleanupState` pick, copy-on-write it, and `delete nextLocalOnlyScrollbackByTabId[orphanTabId]` in the loop. A focused case in `terminal-orphan-helpers.test.ts` asserting the entry is gone would pin it.

ℹ️ Nitpicks

  • The PR description still says "Upload inflation ... The carry-through does not fix it" and frames restart durability as unaddressed; both predate the local-only home. Worth updating so the body matches what the branch now does.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@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: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 703fe730-8d75-44e9-9f87-ad8ef3554462

📥 Commits

Reviewing files that changed from the base of the PR and between f210dec and c0a03e1.

📒 Files selected for processing (48)
  • src/main/orca-profiles/profile-project-session-field-disposition.ts
  • src/main/orca-profiles/profile-project-session-state.ts
  • src/main/orca-profiles/profile-project-session-transfer.ts
  • src/main/persistence/restoring-sessions/session-worktree-ownership.ts
  • src/renderer/src/components/terminal-pane/leaf-scrollback-resolution.test.ts
  • src/renderer/src/components/terminal-pane/leaf-scrollback-resolution.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-buffer-capture.test.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-buffer-capture.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-tab-capture-episodes.test.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-tab-capture-episodes.ts
  • src/renderer/src/components/terminal-pane/shutdown-buffer-captures.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-layout-restore.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-store-subscription-budget.test.tsx
  • src/renderer/src/components/terminal-pane/terminal-shutdown-layout-capture.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-store-actions.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-store-bindings.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-title-effects.ts
  • src/renderer/src/components/use-terminal-parking-pass.ts
  • src/renderer/src/lib/workspace-session-browser-history.test.ts
  • src/renderer/src/lib/workspace-session-editor-drafts.test.ts
  • src/renderer/src/lib/workspace-session-liveness.test.ts
  • src/renderer/src/lib/workspace-session-patch.test.ts
  • src/renderer/src/lib/workspace-session-patch.ts
  • src/renderer/src/lib/workspace-session-relevant-fields.test.ts
  • src/renderer/src/lib/workspace-session.ts
  • src/renderer/src/runtime/web-session-tabs-sync-layout-groups.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync/apply-final-patch.ts
  • src/renderer/src/runtime/web-session-tabs-sync/apply-terminal-records.ts
  • src/renderer/src/runtime/web-session-tabs-sync/state.ts
  • src/renderer/src/store/repos/repo-removal.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/renderer/src/store/slices/worktrees/teardown/remove-worktree-store-cleanup.ts
  • src/renderer/src/store/slices/worktrees/teardown/worktree-purge-state.ts
  • src/renderer/src/store/terminals/terminal-actions.ts
  • src/renderer/src/store/terminals/terminal-layout-state.ts
  • src/renderer/src/store/terminals/terminal-state.ts
  • src/renderer/src/store/terminals/terminal-tab-close.ts
  • src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts
  • src/renderer/src/store/terminals/workspace-terminal-hydration.ts
  • src/shared/remote-workspace-session-projection.test.ts
  • src/shared/workspace-session-host-field-ownership.ts
  • src/shared/workspace-session-schema-field-coverage.test.ts
  • src/shared/workspace-session-schema.ts
  • src/shared/workspace-session-state-types.ts
  • src/shared/workspace-session-terminal-buffers.test.ts
  • src/shared/workspace-session-terminal-buffers.ts
  • src/shared/workspace-session-terminal-tab-close.ts
  • tests/e2e/paired-remote-terminal-parked-scrollback-survives.spec.ts

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

Comment on lines +52 to +58
...(base.localOnlyScrollbackByTabId || incoming.localOnlyScrollbackByTabId
? {
localOnlyScrollbackByTabId: {
...base.localOnlyScrollbackByTabId,
...incoming.localOnlyScrollbackByTabId
}
}

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 | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- merge implementation ---'
sed -n '1,90p' src/main/orca-profiles/profile-project-session-state.ts
printf '%s\n' '--- direct callers ---'
rg -n -C 4 'mergeWorkspaceSessions|mergeHostWorkspaceSessions' src/main/orca-profiles/profile-project-transfer-payload.ts src/main/orca-profiles/profile-project-session-state.ts
printf '%s\n' '--- transfer extraction ---'
sed -n '35,70p' src/main/orca-profiles/profile-project-session-transfer.ts
sed -n '105,135p' src/main/orca-profiles/profile-project-session-transfer.ts
printf '%s\n' '--- patch shape ---'
sed -n '35,60p' src/renderer/src/lib/workspace-session-patch.ts

Repository: stablyai/orca

Length of output: 12142


Treat an incoming empty scrollback map as an explicit clear. mergeWorkspaceSessions merges an incoming {} with the base map, so stale entries survive a transfer-session clear. Preserve the base map only when the incoming field is absent. Keep additive merging for non-empty incoming maps.

Suggested fix
-    ...(base.localOnlyScrollbackByTabId || incoming.localOnlyScrollbackByTabId
+    ...(incoming.localOnlyScrollbackByTabId !== undefined
       ? {
           localOnlyScrollbackByTabId: {
-            ...base.localOnlyScrollbackByTabId,
-            ...incoming.localOnlyScrollbackByTabId
+            ...(Object.keys(incoming.localOnlyScrollbackByTabId).length === 0
+              ? {}
+              : {
+                  ...base.localOnlyScrollbackByTabId,
+                  ...incoming.localOnlyScrollbackByTabId
+                })
           }
         }
-      : {}),
+      : base.localOnlyScrollbackByTabId
+        ? { localOnlyScrollbackByTabId: base.localOnlyScrollbackByTabId }
+        : {}),

Comment on lines 101 to +138
@@ -108,14 +129,16 @@ export function useTerminalParkingPass(controller: TerminalParkingFoundation): v
...exemptRouteCounts
})
}
// Why shared: a force-park is rare, and its copy is what a second desktop cold-restores from.
if (
captureForceParkedWorktreeBuffers({
captureParkedTerminalBuffers({
worktreeId,
tabIds: evictableTabIds,
repos
repos,
localOnly: false

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 | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,190p' src/renderer/src/components/use-terminal-parking-pass.ts
rg -n "capturedParked|parkedCaptureDoneRef|forceParked|nextParked" src/renderer/src/components src/renderer/src/components/terminal-pane --glob '*.ts' --glob '*.tsx'

Repository: stablyai/orca

Length of output: 16766


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- parking pass candidates ---'
sed -n '1,180p' src/renderer/src/components/terminal-parking-pass-candidates.ts
printf '%s\n' '--- capture implementation and consumers ---'
rg -n -C 5 "function captureParkedTerminalBuffers|captureParkedTerminalBuffers|localOnlyScrollback|parkedTerminal|cold.?restore|restore.*scrollback|scrollback.*restore" src/renderer/src --glob '*.ts' --glob '*.tsx'
printf '%s\n' '--- foundation ref declaration ---'
sed -n '45,80p' src/renderer/src/components/use-terminal-parking-foundation.ts

Repository: stablyai/orca

Length of output: 50370


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/architecture /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 47515


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- capture module ---'
rg -l "captureParkedTerminalBuffers" src/renderer/src
capture_file="$(rg -l "captureParkedTerminalBuffers" src/renderer/src | head -n 1)"
printf 'capture_file=%s\n' "$capture_file"
sed -n '1,240p' "$capture_file"
printf '%s\n' '--- exact shared/local persistence and restore references ---'
rg -n -C 4 "localOnlyScrollbackByTabId|captureParkedTerminalBuffers|setTabLocalOnlyScrollback|resolveLeafScrollbackBuffers" \
  src/renderer/src/components/terminal-pane/parked-terminal-buffer-capture.ts \
  src/renderer/src/store/terminals/terminal-layout-state.ts \
  src/renderer/src/store/terminals/workspace-terminal-hydration.ts \
  src/renderer/src/lib/workspace-session.ts

Repository: stablyai/orca

Length of output: 16482


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- parked-terminal-buffer-capture.ts ---'
sed -n '1,260p' src/renderer/src/components/terminal-pane/parked-terminal-buffer-capture.ts
printf '%s\n' '--- capture tests ---'
sed -n '1,320p' src/renderer/src/components/terminal-pane/parked-terminal-buffer-capture.test.ts
printf '%s\n' '--- shared capture serialization readers ---'
rg -n -C 5 "captureParked|localOnly: false|setTabLayout|setTabLocalOnlyScrollback|resolveLeafScrollbackBuffers|scrollback" \
  src/renderer/src/components/terminal-pane/parked-terminal-buffer-capture.ts \
  src/renderer/src/components/terminal-pane/parked-terminal-buffer-capture.test.ts \
  src/renderer/src/store/terminals/terminal-layout-state.ts

Repository: stablyai/orca

Length of output: 17567


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- shutdown capture implementation ---'
sed -n '1,300p' src/renderer/src/components/terminal-pane/shutdown-buffer-captures.ts
printf '%s\n' '--- layout setter remainder ---'
sed -n '30,125p' src/renderer/src/store/terminals/terminal-layout-state.ts

Repository: stablyai/orca

Length of output: 6179


🏁 Script executed:

#!/bin/bash
set -e
sed -n '1,320p' src/renderer/src/components/terminal-pane/shutdown-buffer-captures.ts
sed -n '30,125p' src/renderer/src/store/terminals/terminal-layout-state.ts

Repository: stablyai/orca

Length of output: 6107


Store the capture mode with each worktree.

parkedCaptureDoneRef stores only worktree IDs. If an ordinary local-only capture marks an ID, a later force-park retains that ID because the worktree remains parked. The force branch then skips captureParkedTerminalBuffers({ localOnly: false }), so another desktop may not receive the current shared scrollback required for cold restore.

The reverse transition can leave shared bytes in terminalLayoutsByTabId, because the ordinary capture writes to the separate local-only store. Track the capture mode per worktree, recapture when localOnly changes, and clear stale data in the previous storage home.

Comment on lines +218 to +220
Object.entries(session.localOnlyScrollbackByTabId ?? {}).filter(([tabId]) =>
validTabIds.has(tabId)
)

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 | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '160,250p' src/renderer/src/store/terminals/workspace-terminal-hydration.ts
rg -n "buildWorkspaceTerminalRowPlan|canonicalTabIdBySubsumedTabId|validTabIds" src/renderer/src/store/terminals --glob '*.ts'

Repository: stablyai/orca

Length of output: 7694


🏁 Script executed:

sed -n '1,155p' src/renderer/src/store/terminals/workspace-terminal-hydration.ts
sed -n '1,130p' src/renderer/src/store/terminals/workspace-terminal-row-plan.ts
rg -n -C 4 "localOnlyScrollbackByTabId|canonicalTabIdBySubsumedTabId|subsumedTabIds|scrollback" src/renderer/src/store/terminals src/renderer/src --glob '*.ts' --glob '*.tsx' | head -n 260

Repository: stablyai/orca

Length of output: 38387


🏁 Script executed:

sed -n '1,280p' src/renderer/src/store/slices/terminal-session-row-hydration.ts
rg -n -C 6 "resolveLeafScrollbackBuffers|localOnlyScrollbackByTabId|WorkspaceSessionState|serialize.*session|persist.*session|toWorkspace|buffersByLeafId" src shared --glob '*.ts' --glob '*.tsx' | head -n 360
sed -n '190,250p' src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

rg -l "resolveLeafScrollbackBuffers|localOnlyScrollbackByTabId" src shared 2>/dev/null | head -n 80
rg -n -C 8 "resolveLeafScrollbackBuffers|localOnlyScrollbackByTabId" src/renderer/src/components src/renderer/src/store src/shared --glob '*.ts' --glob '*.tsx' 2>/dev/null | head -n 260
rg -n -C 5 "localOnlyScrollbackByTabId" src/shared src/renderer/src/lib src/renderer/src/hooks --glob '*.ts' --glob '*.tsx' 2>/dev/null | head -n 220

Repository: stablyai/orca

Length of output: 49472


🏁 Script executed:

sed -n '1,180p' src/renderer/src/components/terminal-pane/leaf-scrollback-resolution.ts
sed -n '1,185p' src/shared/workspace-session-terminal-buffers.ts
sed -n '45,75p' src/shared/workspace-session-state-types.ts
sed -n '35,65p' src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts

Repository: stablyai/orca

Length of output: 10703


Remap scrollback from subsumed tabs.

setTabLocalOnlyScrollback can persist scrollback under a tab ID before hydrateWorkspaceTerminalRows later subsumes that tab. The filter checks the source ID against validTabIds, so it drops the entry before applying canonicalTabIdBySubsumedTabId. The canonical tab can then restore without the captured scrollback.

Map each source ID to its canonical ID before validation. Merge the leaf-buffer records when multiple source IDs map to the same canonical tab.

@nwparker
nwparker force-pushed the fix/park-discards-only-scrollback-copy branch from c0a03e1 to 1156da9 Compare September 18, 2026 10:10
A remote-runtime pty's bytes never transit the client's main process, so the pane's
xterm buffer is the only client-side copy. The ordinary cold-park unmounted that pane
without capturing it, licensed by TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY — a static
build string that says nothing about whether the host retained this pty's buffer. On
reveal, a host that answers 'no-serializable-buffer' (or stays silent past the request
timeout) collapses to a null snapshot and the pane paints blank: tabs and splits survive,
the scrollback is gone.

Capture before every park, not only the retention-budget force-park, so the reveal has a
copy to replay when the host cannot answer. An unverifiable host answer is not proof the
pane was empty; keep the buffer, never discard it.

Adds ORCA_E2E_FORCE_REMOTE_TERMINAL_SNAPSHOT_UNAVAILABLE so an e2e can reproduce the
host-retains-nothing state, mirroring the existing forced-truncation lever.
…rs nothing

The oracle is a token the test types into the terminal before the park and the fixture
echoes back. Nothing replays stdin, so a respawned command cannot reproduce that line —
only the pre-park buffer can. An earlier argv marker passed vacuously for exactly that
reason.

The control ('host retains the buffer') is insensitive to the fix and fails if the harness
never parks, never reveals, or never echoed the token, so the regression case cannot be
green for a harness reason.
…ad of casting it

The merge-commit consistent-type-assertions gate flags every new `as`. Two were fixture
shapes that a type annotation states directly, and the third hid an unchecked RPC payload —
readCreatedTerminalTab now fails with the shape named rather than surfacing later as an
undefined surface id.
Reading state.repos unguarded threw out of the cold-park effect whenever the catalog was
absent, which would break parking itself. Capture is best-effort evidence; an empty catalog
also fails open in shouldPreserveTerminalScrollbackBuffers, the safe direction for a park.
…posite ways

shouldPreserveTerminalScrollbackBuffers fails open toward 'remote' because a worktree wrongly
judged local parks with no copy at all. worktree-runtime-owner.ts resolves the same unhydrated
catalog to 'local', which is safe there and would be data loss here. A reader pattern-matching
'fail open' across the two gets one of them backwards.
The direct-SSH pull replaces a replaced tab's layout wholesale, and a park capture does not
bump tab.generation — so a just-parked tab is not in locallyPreservedTabIds and the only
client-side copy of its remote scrollback went with the layout it replaced. That is the same
data loss this branch already fixes, one layer down, and it is the layer that decides whether
the fix survives the app update the user actually performed.

Carry the client's leaf-keyed scrollback into the host's layout, filtered to the host's own
root leaves. Structure stays the host's verbatim, so a split it added while we were away still
wins and a leaf it retired still drops its bytes. Local wins a conflict: neither copy is then
the only one, but remote-wins would overwrite the tail captured since the last upload and
propagate that backwards on the next replace-session patch.

Not a generation bump: the pane key is `${tab.id}-${tab.generation}`, so bumping would remount
the pane and destroy the very buffer the capture just serialized, lift the recovery-storm
ledger ceiling, and let a stale local ptyId win through preserveNewerLocalTerminalFields.
…layout rebuild

Found in review of this PR by rc-ssh-remoting. chooseRemoteTerminalLayout rebuilds a
mirrored tab's layout from the host's picture and never carried buffersByLeafId or
scrollbackRefsByLeafId forward, though it already receives existingLayout. The host
publishes no scrollback of its own, so ANY session-inventory frame landing between park and
reveal dropped the only client-side copy: the rebuild is bufferless, terminalLayoutEqual
compares buffers so the write is not bailed out, and apply-terminal-records assigns it
wholesale.

Measured before the fix: 336 bytes captured at park, 0 after one forced frame, blank pane on
reveal. After: 411 bytes survive the frame and the reveal repaints.

The e2e passed either way because no frame happened to land in its window, so it was not
covering the destroying event. It now forces one inside the park -> reveal window and asserts
the capture survives it.

An identical fix was written and reverted earlier in this branch as 'no measurable effect' —
that measurement ran on a harness deleting the client profile between launches, so nothing
downstream of persistence could register. It was never actually tested.
localOnlyScrollbackByTabId is a top-level session field, tabId -> leafId -> buffer, that never
rides the remote projection: exportRemoteWorkspaceSession is an explicit allowlist of named
top-level fields, so a new one is omitted for free, whereas anything added to
TerminalLayoutSnapshot is copied whole. It is also outside the two records the mirrored-tab apply
rewrites, so a host inventory frame cannot wipe it.

Registered in every exhaustive session registry ('tabKeyed'), hydrated and scoped like the layout
map, dropped with its tab on close/removal/purge/repo removal/mirrored retirement, copied on profile
transfer, emitted by the incremental patch builder, and capped by pruneLocalTerminalScrollbackBuffers
alongside the shared home — with a per-home test so an uncapped path cannot go unnoticed.

Known ceiling, not widened here: the field routes through the partition router that falls back to
'local' when the repo catalog is unknown at write time (#21295).
… both homes through one resolver

The ordinary cold park fires on every workspace hide. Its capture now splits: structure (root,
ptyIds, titles) stays in the shared layout, bytes go to localOnlyScrollbackByTabId. Force-park,
hibernate, sleep and shutdown keep writing buffersByLeafId, because that copy is what a second
desktop cold-restores from; a shared capture clears the local copy so the two homes never hold two
versions of one leaf.

resolveLeafScrollbackBuffers is the only read across the two homes (local wins a conflict: it is
the later write by construction). restoreTerminalPaneLayout no longer reads buffersByLeafId
directly, the capture's merge prior comes from the resolver, and the post-replay release covers
both homes.

Measured with the projection at 20 tabs x 2 panes at the per-leaf cap: the shared-layout shape
exports ~22 MiB per replace-session; the local-only shape exports the bufferless baseline.
…ck refs

The carry-through added in f210dec keeps scrollbackRefsByLeafId for leaves the host still
names (a ref is the only pointer to a local scrollback file), so the rebuilt layout equals the
stored one and the write bails. The old assertion expected the refs to be dropped and has been red
on this branch since that commit.
…ry-frame check at the force-park

Once ordinary parks stop writing buffersByLeafId, the existing survivedInventoryFrame assertion
passes trivially — there is nothing in the layout to wipe. The ordinary scenarios now assert the
store-level upload contract (bytes in the local-only home, shared home empty) and that the local
home is out of a host frame's reach; a third scenario reaches a force-park (host without paired
parking, client retention limit 1) and asserts the shared capture survives the forced frame, which
is where the mirrored-layout carry-through is load-bearing.
…f matching it loosely

expect.any(Boolean) reads as a check but cannot fail. The force-park reveal is served by the host
tail on a host without paired parking, so it is logged for diagnosis and the assertion carries the
three fields that are deterministic on this topology.
@nwparker
nwparker force-pushed the fix/park-discards-only-scrollback-copy branch from 1156da9 to 2a2c1a7 Compare September 18, 2026 11:24

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in the incremental delta — the force-park e2e assertion is now strict instead of vacuous. Prior review threads remain open, so this is not an approval.

Reviewed changes — incremental delta since the prior pullfrog run at 1156da9 (which submitted no review; the last reviewed content is 840e711):

  • Force-park e2e assertion made honest — the force-park scenario no longer matches tokenAfterReveal with expect.any(Boolean), which reads as a check but cannot fail. It now logs the reveal for diagnosis and asserts only the three fields that are deterministic on this topology (tokenBeforePark, parked, parkedHome), with FORCE_PARKED_SHARED retyped as Omit<ParkRevealOutcome, 'tokenAfterReveal'>. The load-bearing claim — the shared-layout capture surviving the forced inventory frame — is still asserted by survivedInventoryFrame inside runParkRevealScenario.

The rest of the range-diff against 1156da9 is a rebase onto a newer main (six base commits); the PR's eleven content commits match 1:1, so there is no production behavior change in this delta.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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