Skip to content

refactor(terminal): read the terminal screen through one TerminalScreen interface - #4657

Merged
devswha merged 2 commits into
mainfrom
refactor/screen-reader
Nov 25, 2026
Merged

devswha merged 2 commits into
mainfrom
refactor/screen-reader

Conversation

@devswha

@devswha devswha commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Summary

Step X1 of the terminal engine work: every place the client reads what an xterm terminal shows (rows and cells, cursor, history position, selection, OSC 8 links) now goes through one interface, TerminalScreen in src/lib/terminalScreen.ts, with xterm as its only implementation. No behaviour change; a later step can answer the same reads from libghostty (masked prompt first).

  • ScreenRows / ScreenLine / ScreenCell follow xterm's buffer API, so xterm's rows and cells serve as they are (no per-cell copies, same hot-path cost) and the existing tests that pass term.buffer.active still type-check.
  • terminalScreen(term) is cached per terminal and reads whichever buffer is active at the time of the read, as the old term.buffer.active reads did.
  • Moved behind it: input row and Claude at-rest (PaneTerminal, inputRow), masked prompt (secretScreen), Hermes/Grok stop key (useTypedKeys), file links (terminalFileLinks), folded view rows, cursor and taps (terminalFold), Find highlights and local history (TerminalViewportTools), the libghostty overlay's view position and drawn selection, and selection/cursor/history reads in useTerminalMount, useTerminalRefits and terminalWheel. hyperlinkAt (xterm internals) moved from terminalFold into the xterm implementation.
  • Out of scope: xterm's own IME composition placement (inside xterm, not our code), and writes such as clearSelection/scrollLines.

Direct reads outside terminalScreen.ts (git grep -nE '\.buffer\.active|\bIBuffer(Line|Cell)?\b|\b(term|terminal|shown)\.(hasSelection|getSelection|getSelectionPosition)\(|_oscLinkService|_selectionState' over non-test src/): 52 before (11 files) -> 0 after.

Validation

  • bun run check fast: passed (typecheck, build, 27444 unit tests).
  • Focused: bun test src/lib/inputRow.test.ts src/lib/secretScreen.test.ts src/lib/terminalFileLinks.test.ts src/lib/terminalFold.test.ts src/lib/terminalWheel.test.ts: 306 pass.
  • Browser regressions (terminal view, selection, focus): run by this PR's CI browser jobs in the runner image (UI suites + all other scripts).

No changelog fragment: internal refactor with no user-visible change.

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Refactor
    • Standardized how terminal screens, selections, cursor positions, and screen content are accessed across terminal features.
    • Terminal text reading, file links, viewport tools, and input handling now use a shared screen interface.
    • Screen-related features continue to work across normal and alternate terminal screens, including activating a file link after switching screens.

The pull request adds a cached terminal screen adapter with interfaces for screen rows, lines, and cells. Terminal components and library code use the adapter for buffer access, rendering, selection, cursor, viewport, and hyperlink state.

Changes: Terminal screen access

Layer / File(s) Summary
Define the terminal screen adapter
src/lib/terminalScreen.ts
Adds screen interfaces and a cached terminalScreen adapter. The adapter exposes active-buffer data, selection state, and hyperlink lookup.
Use the adapter for row and cell access
src/lib/inputRow.ts, src/lib/terminalFileLinks.ts, src/lib/terminalFileLinks.test.ts, src/lib/terminalFold.ts, src/components/PaneTerminal.tsx, src/components/TerminalViewportTools.tsx, src/lib/secretScreen.ts, src/lib/useTypedKeys.ts
Screen-reading and rendering code uses the adapter’s row and cell interfaces. File-link APIs accept ScreenRows; fold rendering uses ScreenLine and ScreenCell. A test checks link activation after a switch to the alternate screen.
Route selection and terminal interactions through the adapter
src/lib/ghostty/overlay.ts, src/lib/useTerminalMount.ts, src/lib/terminalWheel.ts, src/lib/useTerminalRefits.ts
Selection, cursor, viewport, alternate-screen, and hyperlink access now uses terminalScreen. The overlay reads drawn selection from the adapter, and hyperlinkAt is removed from terminalFold.ts.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Suggested reviewers: charleoyang

Merge Risk: Minimal · up to c08c1

This change moves terminal screen reads behind a shared adapter and is not intended to change behavior. No concrete merge-blocking risk was identified in the supplied evidence, and the author reports passing checks.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: a refactor that routes terminal screen reads through one TerminalScreen interface. It matches the summary and the objectives, and it follows the conventional commit st…
Description check Passed The description states the change, the scope, the no-behaviour-change intent, and the validation run. It does not follow the template: it has no CONTRIBUTING.md or changelog reference, and it omits th…
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: Title check

Explanation

The title names the main change: a refactor that routes terminal screen reads through one TerminalScreen interface. It matches the summary and the objectives, and it follows the conventional commit style.

Full details: Description check

Explanation

The description states the change, the scope, the no-behaviour-change intent, and the validation run. It does not follow the template: it has no CONTRIBUTING.md or changelog reference, and it omits the template's validation layout for skipped checks. It also says no changelog fragment is needed, which is a decision the template leaves to the author. The validation section lists the commands run, but browser regressions were only run in CI and not locally, which the template asks the author to state as skipped.

Resolution

Optionally add an explicit list of skipped checks (for example, the browser suites run only in CI) and a reference to CONTRIBUTING.md for the changelog decision. These are non-critical template gaps.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 42f6ae0 and c08c177.

Files selected for processing: 9

  • src/components/PaneTerminal.tsx
  • src/lib/ghostty/overlay.ts
  • src/lib/secretScreen.ts
  • src/lib/terminalFileLinks.test.ts
  • src/lib/terminalFileLinks.ts
  • src/lib/terminalFold.ts
  • src/lib/terminalScreen.ts
  • src/lib/useTerminalMount.ts
  • src/lib/useTypedKeys.ts

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

@devswha

devswha commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

Reviews on 42f6ae0: an omo gate review (BLOCK, one MEDIUM) and a Codex adversarial review (gpt-6.2-sol-fast, xhigh; two LOWs).

Fixed in the next commit:

  • MEDIUM (gate) / LOW (Codex): a file link found on the normal screen was rechecked at release against whichever buffer was up then, so a full-screen program starting between press and release dropped the click. TerminalScreen.active() returns the buffer that is up now, and the link provider captures it at provideLinks time again, as () => term.buffer.active did; its contents stay live, so the existing stale-row check still works. New test opens a link read on the normal screen when the alternate one comes up before the release: it fails with the live read and passes with the fix.
  • LOW (Codex): the masked-prompt scan looked up the active buffer on every row read (1 -> 74 lookups per 80x24 scan). Every reader that held one buffer for a whole pass does so again through active(): secretScreen, the input row, the Hermes/Grok stop key, the folded view's rows and taps, the overlay frame, and the OSC 8 / file link click.

Validation after the fix: bun run check fast passed (27445 unit tests). Direct reads outside terminalScreen.ts are still 0.

@devswha

devswha commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@devswha
devswha merged commit d122cc0 into main Nov 25, 2026
16 checks passed
@devswha

devswha commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

Merged through pr-merge at head c08c1778d. Seen before the merge was asked for: required checks green, no unresolved thread, no conflict, no hold, main not red, no release in progress. CodeRabbit reviewed this head.

Reviews on this PR: omo gate reviewer (BLOCK on 42f6ae0, one MEDIUM: file-link click across a buffer switch) and Codex adversarial review (gpt-6.2-sol-fast xhigh, two LOWs); all three fixed in c08c177 with a regression test that fails on the old wiring. CodeRabbit reviewed c08c177 with no actionable comments. Behaviour-neutral refactor; secretScreen.ts reads the same rows as before. Merged on the lane brief phone-engine-x1 (owner OK 2026-11-25).

@devswha
devswha deleted the refactor/screen-reader branch November 25, 2026 03:35
devswha added a commit that referenced this pull request Nov 25, 2026
…4669)

## Summary
Step 1 of moving the terminal's screen reads from xterm to libghostty
(after X1, #4657). Today every byte is parsed twice: libghostty draws
the screen and xterm's buffer answers every read. The goal is a phone on
herdr-core where xterm parses only the control sequences its input side
needs, so each reader has to move to libghostty first. The masked-prompt
detection goes first because it is the security-relevant one.

- `shared/ghostty/engine.ts`: adds `rowText(y)`, which returns a kept
row's code points, widths and graphemes plus its soft-wrap flag (no
style reads), and `rowCells(y)`, which returns styled cells. Both look
up one grid ref per row and step its `x` along the row, so a cell costs
one wasm call. Also adds `screenCursor()` and `alternate()`.
- `src/lib/ghostty/screenRows.ts`: `ghosttyRows(vt)` gives libghostty's
kept rows the shape of xterm's buffer (`ScreenRows`). History rows
beyond the configured scrollback are left out the way xterm drops them,
because libghostty frees history a page at a time.
- `src/lib/terminalScreen.ts`: `screenRows(term)` returns libghostty's
rows while the overlay holds the screen and xterm's otherwise. The
overlay registers itself after it attaches and unregisters on dispose.
If libghostty fails, it also gives up drawing, and reads go back to
xterm.
- `src/lib/secretScreen.ts` reads `screenRows(term)`. Every other reader
still reads xterm.

## Same answer as before
- `secretScreen.test.ts` runs all 16 cases twice, once on xterm's screen
and once on libghostty's (fed each byte before xterm parses it, as the
overlay does). All 32 pass. As a mutation check, I broke
`translateToString` in the libghostty rows; that made all 16 libghostty
cases fail and left the xterm cases passing.
- `screenRows.test.ts` compares the two engines on every row and every
cell. It covers text, wide cells, ZWJ/flag graphemes, bold, dim, italic,
underline, strike, overline, inverse and invisible, palette, 256-colour
and RGB colours, an erase that leaves only a background, soft wraps,
history with a wide cell pushed to the next row, the alternate screen,
the cursor, `length`, `baseY` and `viewportY`. The two engines match
exactly on all of it.
- Replay of a real 1.56 MB Claude Code recording, chunk by chunk (381
chunks, 80x37 with 2,000 lines of history and 49x35 with none): the
prompt verdict differed on 0 of 381 chunks.

## Known difference
xterm keeps a stale wrap flag on rows that DL/IL shift and on the row
after an erased one; libghostty clears it. With `erase-ends-wrap.patch`
(an erase from a row's first column, or a line feed onto a row, ends the
wrap into it, as in xterm), a 120x37 replay of the real recording
matches xterm on every row's text and wrap flag.

## Cost (phone emulation: 390x844, DPR 3, CPU 4x slower; real path:
isolated herdr-core -> Ovis -> WebSocket; 1.56 MB Claude recording)
- The masked-prompt reads themselves, timed in the page: main 113 ms
over ~108 reads, this branch 236 ms over ~109 reads (2 runs each, ABBA).
That is about +1.1 ms per read, or roughly +120 ms (about 3%) of
main-thread time for the whole replay.
- The whole replay, 5 runs each, ABBA, pinned to 8 idle cores (median
[min–max]; main = origin/main, branch = 571c62b):

| metric | main | branch |
|---|---:|---:|
| main thread ms | 3761 [3564–4467] | 4471 [3317–5127] |
| script ms | 2142 [1951–2486] | 2449 [1901–2862] |
| layout+style ms | 787 [775–922] | 946 [704–1069] |
| start to settled ms | 3969 [3730–5014] | 4858 [3539–5743] |
| long tasks over 50 ms | 7 [6–12] | 10 [4–25] |
| JS heap growth MB | 3.8 [2.8–3.9] | 3.5 [2.1–3.9] |
| browser CPU ms | 8000 [7540–9250] | 9130 [7380–10480] |

The whole-replay spread is wider than the difference: layout+style moved
by about the same share, and this change touches no DOM. The machine's
load was 37–82 during the runs. The direct timing above is the cost this
change adds. All 10 runs received the replay byte-exact.
- What this buys: in step 7 xterm stops parsing every byte. The earlier
prototype measured about 1.9x less main-thread time for the same replay.

## Validation
- See the validation comment for the checks that ran and their results.
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