Skip to content

fix(terminal): one process-boundary ground for every known or proven boundary - #22735

Merged
Jinwoo-H merged 10 commits into
mainfrom
scroll-freeze-ground
Sep 25, 2026
Merged

Jinwoo-H merged 10 commits into
mainfrom
scroll-freeze-ground

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​210 $\color{#cf222e}{\Huge{\mathbf{−}}}$​31 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​179
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​44 $\color{#cf222e}{\Huge{\mathbf{−}}}$​24 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​20

ELI5

When a program in a terminal dies, Orca has to switch off the settings it had asked for: mouse capture, full-screen mode, special paste handling and so on. Orca had three separate "switch it all off" lists that had drifted apart. The one used after a restart only switched off the mouse and colors, so the new program inherited the old one's other settings. This PR replaces the three lists with one complete list and uses it everywhere.

Stacked on #22732 (review that first).

What Changed

Before:

  • After a daemon restart (cold restore), the dead process's focus reporting (?1004h), bracketed paste (?2004h), application cursor (?1h) and keypad (?66h) modes stayed armed. They stayed in the daemon's live emulator, the first durable checkpoint, and main's mirror, which mobile reads.
  • The seed wrote the dead process's half-written escape sequence after the reset, so the new shell's first bytes could finish it. For example, a torn title escape would retitle the pane.
  • The recovery barrier, which runs when a TUI dies with the alt screen up under a shell, left application cursor and keypad armed.

Mechanism: three drifting copies of the process-boundary reset:

  • COLD_RESTORE_SEED_MODE_RESET: pen and mouse only.
  • The barrier's use of the renderer's POST_REPLAY_DEAD_TUI_RESET.
  • Nothing at all on the cold-restore payload.

After: one PROCESS_BOUNDARY_GROUND in terminal-mode-reset-profiles.ts, built from existing named pieces:

  • Kitty flags popped on the screen the pane is on. xterm keeps a kitty stack per screen, so a dead TUI's alt-screen flags would otherwise reach the next alt-screen app (vim or less would get Esc and Ctrl-C as CSI-u).
  • ?1049l, preceded by a DECSC. xterm's ?1049l always restores the saved cursor, so the save keeps the normal-buffer cursor in place. On the alt buffer, it still returns to the shell's pre-TUI position.
  • Every mouse protocol and encoding off.
  • Focus, paste, application cursor and keypad off.
  • Cursor shown, cursor style reset, normal-screen kitty flags popped, SGR reset, and a grounded DECSC.

It stays inert for the lifecycle scanner: no OSC 133, and nothing it treats as a new owner.

Where it's used:

  • The cold-restore seed, which also no longer carries the torn escape tail.
  • The recovery barrier. It emits the ground before the shell's queued prompt, so bash, zsh, fish and PowerShell re-arm their own paste mode at the prompt.
  • The cold-restore payload.

The renderer's own reset profiles are unchanged; they remain the policy for hosts without a daemon model.

On the first fold after a cold restore, the live terminal was seeded with the saved checkpoint plus the ground, so the saved copy never matches it. #22732's "skip the rebase when disk already agrees with live" shortcut is therefore skipped on that first fold.

Why

One constant used at every boundary Orca knows about (a cold restore) or proves (the barrier) removes the drift at its source. Adding the missing bits to each copy would keep three copies that drift again. The ground only turns modes off, so it can't arm anything for a live program.

Linked Issue

Related: #13077. This clears the stale modes that make a shell print mouse reports as garbage after a cold restore. The in-stream detector for normal-buffer programs that die is a follow-up, so this doesn't close #13077.

Visual Proof

N/A. This changes daemon and main-process terminal state, not the UI; it's covered by tests that assert emulator modes, cursor position and the pane title. I didn't demo it in the running app.

Testing

New tests fail on #22732's head and pass here:

  • A cold restore leaves no dead-process input modes in live or in the first rebased checkpoint.
  • A zero-record first fold rebases even when TerminalModes can't see the stale modes.
  • The new shell can't complete a torn escape.
  • The barrier grounds a dead TUI before the prompt re-arms its own modes.

Also covered:

  • The cursor stays in place.
  • The ground is inert for the lifecycle scanner.

Test suites:

  • src/main/daemon, the shared reset-profile tests and renderer terminal-pane: 6,709 pass. The only failures are two repro-13767 real-PTY tests that also fail on the base commit on this machine.
  • cross-version-terminal-wire: passes.

Checks: pnpm tc, oxlint and check:code-quality:changed are clean.

Platform: tests ran on macOS only.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Independently reviewed and ready.

  • The DECSC-before-?1049l choice: checked against xterm's source (?1049l always calls restoreCursor, and the saved cursor is per buffer) and with scratch tests on both buffers. In one normal-buffer case, the old bytes jumped the cursor up and overwrote a line; the new ones don't.
  • Paste-mode safety: confirmed. Shells re-arm paste at every prompt, and shells that never arm it had it off anyway.
  • Every consumer of the cold-restore payload was traced: the renderer, main's mirror, mobile and remote clients.

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

  • SSH relay: unchanged (no host emulator).
  • Remote wire: no new fields. The only content change is about 150 bytes of disable-only escapes at the end of the cold-restore payload, which old clients simply write.
  • Windows: ?1005/?1015 are ignored by xterm and only disable modes on other hosts.
  • Known and pre-existing: a TUI that dies on ?47/?1047 (not ?1049) still restores a stale normal-buffer cursor. The old bytes did the same.

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)

A durable checkpoint was folded from the previous checkpoint plus recorded
output, so it inherited that checkpoint's modes forever. After a daemon
restart killed a full-screen TUI and a new process started inline, the chain
kept the dead TUI's alt screen and mouse tracking (?1049h ?1003h ?1006h)
while the live emulator was clean. Every reattach and getBufferSnapshot
served the stale chain, the renderer re-armed mouse tracking, and wheel
scrolling went to a program that never asked for it: scrolling froze.

Each full checkpoint is now the live snapshot verbatim (screen, layout,
alt frame, modes, owner) with only the normal-buffer rows live has evicted
taken from the durable replay. A checkpoint can no longer carry a dead
process's modes, and checkpoints already poisoned on disk heal on the next
compaction.

- The first fold after a cold restore replays the same seed segments live
  was given, so rows line up even over a dead TUI's alt screen.
- Idle zero-record folds keep the disk copy when it already agrees with
  live, so quit and relaunch bursts don't replay every session.
- Held teardown bytes are already in the drained records and the live
  snapshot, so they are no longer replayed twice or appended as a tail.
- The bounded getBufferSnapshot path honors the requested depth even when
  the live window is deeper, without phantom link rows.
- The fold's ownership scanner and frame merge are removed; owner and
  frame come from live.
…boundary

Three copies of the "the process that armed these modes is gone" reset had
drifted: the cold-restore seed cleared only pen and mouse, the recovery
barrier used the renderer's dead-TUI profile, and the cold-restore payload
had none. A cold restore therefore left the dead process's focus reporting,
bracketed paste, application cursor and keypad modes armed in the live
emulator, the first checkpoint, and main's mirror. And the seed wrote the
dead process's torn escape after the reset, so the new shell's first bytes
could complete it (for example retitling the pane).

PROCESS_BOUNDARY_GROUND replaces them: CAN, leave the alt screen without
moving the normal-buffer cursor, every mouse protocol and encoding off,
focus/paste/app-cursor/keypad off, cursor shown and style reset, kitty
popped, SGR reset, grounded DECSC. It stays inert for the lifecycle
scanner. The seed, the recovery barrier, and the cold-restore payload all
use it, and the seed no longer carries the torn tail.

The first fold after a cold restore now always rebases on live, because
focus and keypad are not in TerminalModes and the zero-record shortcut
could not see them differ.

@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 — minor suggestions inline.

Reviewed changes

  • One process-boundary ground: new PROCESS_BOUNDARY_GROUND in src/shared/terminal-mode-reset-profiles.ts replaces both COLD_RESTORE_SEED_MODE_RESET and the recovery barrier's use of the renderer's POST_REPLAY_DEAD_TUI_RESET; it adds focus reporting, bracketed paste, application cursor/keypad, legacy mouse encodings, a leading CAN, and a DECSC-before-?1049l.
  • Cold-restore seed: getRecoveredHistorySeedSegments now appends the ground and drops pendingEscapeTailAnsi, so a new process never completes the dead process's torn escape.
  • Cold-restore payload: buildColdRestorePayload appends the ground, so main's mirror — not only the renderer's reset — gets grounded.
  • Forced first-fold rebase: buildDurableCheckpointSnapshot skips the disk-agrees shortcut when pendingRecordsAreComplete (take.seq === 1), because focus/keypad are invisible to TerminalModes.
  • Tests: new process-boundary-ground.test.ts plus updates pinning the ground at the seed, scanner, barrier and profile layers.

I verified the load-bearing ?1049l claim against xterm and xterm.js source: the saved-cursor register is per-buffer and ?1049l restores unconditionally, so the DECSC ordering is correct on both buffers.

ℹ️ The renderer's dead-TUI reset is deliberately left un-grounded

The PR grounds every daemon boundary but leaves POST_REPLAY_DEAD_TUI_RESET (src/shared/terminal-mode-reset-profiles.ts:28) without ?1l/?66l/?2004l; the body describes that profile as the policy "for hosts without a daemon model." On such a host, does a daemon-side ground still reach the pane on the dead-TUI boundary, or is grounding the renderer profile a follow-up? This is a scope question with no line to anchor.

Technical details
# Renderer dead-TUI reset scope

## Affected sites
- `src/shared/terminal-mode-reset-profiles.ts:28` — `POST_REPLAY_DEAD_TUI_RESET` = `?1049l` + `POST_REPLAY_REATTACH_RESET`; includes `?1004l` but not `?1l`/`?66l`/`?2004l`/`?1005l`/`?1015l`.
- `src/renderer/src/components/terminal-pane/pty-connection/hidden-output-restore-snapshot.ts:154` — used when `terminalOwner === 'shell'` and alt-screen.
- `src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-follow-reset.ts:148` — same for the reattach reset sequence.

## Required outcome
- Confirm whether the daemonless path reaches a state where a dead TUI's app cursor/keypad/paste bits persist in the renderer's xterm, or whether some daemon ground always precedes it.

## Open questions for the human
- Is the renderer profile intended to remain the boundary reset for daemonless hosts indefinitely, or is it a follow-up?

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

Comment on lines +29 to +35
// Why no pendingEscapeTailAnsi: every seed starts a new process, whose first bytes
// must not complete an escape the dead one left half-written.
const [firstRecovered, ...remainingRecovered] = recovered
const groundedRecovered = firstRecovered
? [`${RESET_GRAPHIC_RENDITION}${firstRecovered}`, ...remainingRecovered]
: []
return [...groundedRecovered, COLD_RESTORE_SEED_MODE_RESET, ...(escapeTail ? [escapeTail] : [])]
return [
`${RESET_GRAPHIC_RENDITION}${firstRecovered}`,
...remainingRecovered,
PROCESS_BOUNDARY_GROUND

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 seed now drops pendingEscapeTailAnsi, but restoreSegments in daemon-durable-history-snapshot.ts:155-163 — used by buildDurableCheckpointSnapshot on every non-first fold — still replays it ahead of the pending records. The disk-reconstruction path therefore keeps the exact torn-escape completion this PR removes from the live seed, so the two base-segment builders now disagree about the tail. I could not construct a deterministic live corruption from it (the first fold commits a tail-free checkpoint that later folds read), but the non-first-fold path is untested and the fix is one line.

Technical details
# Torn-tail policy differs between the live seed and the durable replay

## Affected sites
- `src/main/daemon/terminal-history-seed-segments.ts:29-35` — seed drops `pendingEscapeTailAnsi` and appends `PROCESS_BOUNDARY_GROUND`.
- `src/main/daemon/daemon-durable-history-snapshot.ts:64-66` — non-first folds call `restoreSegments` instead of the seed.
- `src/main/daemon/daemon-durable-history-snapshot.ts:155-163` — `restoreSegments` still appends `restoreInfo.pendingEscapeTailAnsi` last, before the replayed pending records.
- `src/main/daemon/history-reader.ts:294` — the `restoreInfo` handed to `restoreSegments` can already carry a disk tail.
- `src/main/daemon/process-boundary-ground.test.ts:78-100` — both rebuild calls pass `pendingRecordsAreComplete: true`, so `restoreSegments` is never exercised here.

## Required outcome
- The base reconstructed for the durable replay must match the base the live emulator was seeded with, so replayed pending records parse from the same parser state.

## Suggested approach (optional)
- Drop (or CAN-abort) `pendingEscapeTailAnsi` in `restoreSegments` to match the seed, and add a non-first-fold fixture carrying a tail to pin the invariant.

…t folds and trims

Stop seeding persisted OSC link ranges into the fold replay: they index the
base buffer, so rows evicted by pending output left a link on the wrong text.
The serializer already writes OSC 8 into the ANSI the fold replays.

Re-apply kitty keyboard flags when replaying a snapshot for trimming, since
rehydrateSequences omits them.

Bound a smaller restore request by trimming the committed checkpoint instead
of re-reading disk and rebasing the live window at a smaller depth.
# Conflicts:
#	src/main/daemon/daemon-durable-history-snapshot.ts
…ble fold

The live window's override cap now derives from the restore depth, so live can
never be deeper than the fold. pendingRecords and isFirstTake are required.
@Jinwoo-H
Jinwoo-H changed the base branch from scroll-freeze to main September 25, 2026 03:09
# Conflicts:
#	src/main/daemon/daemon-durable-history-snapshot.ts
@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

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: b16ed7ab-14f5-43a6-b130-d2651b248ff4

📥 Commits

Reviewing files that changed from the base of the PR and between 1c1b782 and f6da89e.

📒 Files selected for processing (11)
  • src/main/daemon/daemon-durable-history-snapshot.ts
  • src/main/daemon/daemon-pty-adapter-cold-restore-reanchor.test.ts
  • src/main/daemon/daemon-pty-session-control.ts
  • src/main/daemon/process-boundary-ground.test.ts
  • src/main/daemon/terminal-history-seed-segments.test.ts
  • src/main/daemon/terminal-history-seed-segments.ts
  • src/main/daemon/terminal-shell-lifecycle-scanner.test.ts
  • src/main/daemon/terminal-shell-recovery-barrier.test.ts
  • src/main/daemon/terminal-shell-recovery-barrier.ts
  • src/shared/terminal-mode-reset-profiles.test.ts
  • src/shared/terminal-mode-reset-profiles.ts

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


📝 Walkthrough

Walkthrough

Cold-restore and confirmed-crash recovery now append or emit PROCESS_BOUNDARY_GROUND, which resets terminal input modes and related state. Recovered history no longer includes a pending torn escape tail. First durable takes replay and rebuild the snapshot instead of returning a matching disk checkpoint directly. Tests cover reset behavior, recovered terminal state, and recovery output ordering.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to f6da8

No additional merge-blocking risk was established for the terminal grounding change. Complete normal checks before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to f6da8

The change clears terminal settings left by a dead process before the next shell runs. No new access path or demonstrated security regression was found, though coverage of all terminal environments is incomplete.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The affected exposure is terminal state inherited by the next shell and by consumers of recovered terminal history; the inspected cold-restore path adds no endpoint or payload field.

Trust Boundaries and Controls

  • observed — Recovery treats output from the dead process as a boundary: it omits the pending escape tail, and the confirmed-crash path emits grounding before releasing queued output from the surviving shell.

Resilience and Maintainability Implications

  • observed — Failed or stale crash confirmation cannot take the confirmed-reset branch, and downstream release failures do not intentionally strand the remaining queued output.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 11 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Issue #13077 is closed and supplies historical context only. It adds no coding requirements for this pull request. No active directly linked issue remains.
Out of Scope Changes check ✅ Passed The changes stay within the stated process-boundary reset and cold-restore scope. The shared PROCESS_BOUNDARY_GROUND, checkpoint rebase changes, torn-escape handling, recovery-barrier updates, and r…
Title check ✅ Passed The title clearly identifies the main change: using one shared process-boundary ground for terminal cleanup. It is concise and specific.
Description check ✅ Passed The description is detailed and covers the required explanation, changes, rationale, issue reference, visual proof, testing, review notes, compatibility considerations, and checklist. It uses “Related…
  • Fix all pre-merge checks with AI
✨ 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.

…round

Kitty keyboard stacks are per screen, so resetting only after ?1049l left
a dead TUI's alt-screen flags for the next alt-screen app. Also drop the
inert CAN from the ground (every site grounds after complete bytes) and
correct two stale comments.
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.

[Bug] Orca terminals start spawning random characters

1 participant