Skip to content

perf(terminal): read background terminal screens from the daemon's model instead of re-parsing them on main - #46516

Merged
brennanb2025 merged 8 commits into
mainfrom
brennanb2025/terminal-parse-off-main
Nov 22, 2026
Merged

brennanb2025 merged 8 commits into
mainfrom
brennanb2025/terminal-parse-off-main

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When Orca needs to see what's on the screen of a terminal it isn't showing (for example to check whether an agent is waiting at a prompt), it sometimes has to ask the background terminal service for it. Until now the service sent back the whole screen as raw terminal codes, and Orca's main process re-drew that screen from scratch just to read its text. Now the service, which already has the screen drawn, sends back the finished lines. The main process does less work, and nothing looks different.

Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​201 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​200
Prod 36 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​636 $\color{#cf222e}{\Huge{\mathbf{−}}}$​178 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​458

What Changed

  • The daemon's getSnapshot request accepts an optional visibleProjection: true. With it, the session returns the visible rows, row metadata and composer draft computed on its own emulator (projectTerminalVisibleLines), plus size, modes, title, terminal owner and output sequence, and skips ANSI serialization.
  • projectTerminalVisibleLines / projectTerminalTailLines moved to src/main/daemon/emulation/terminal-screen-projection.ts so the daemon and the runtime share one implementation; RuntimeTerminalProjection moved to the shared runtime terminal contracts.
  • The provider contract carries an optional visibleProjection request option and response field. Only the provider-preferred visible screen read (captureProviderVisibleState) asks for it; adoptProviderVisibleSnapshot uses the returned rows and parses ANSI only when they are absent. All existing generation, sequence, mode-transition and retry checks are unchanged.
  • Both visible-screen-only read sites ask for the projection: captureProviderVisibleState and the readProviderTerminalTailLines visible-screen fallback, so a slow read and its fallback share one pending request.
  • The daemon advertises visibleProjectionSnapshots: true in its authenticated control hello (an optional field, like the existing resizeModel). The client records it per connection, replaces it on reconnect and clears it on disconnect, so the adapter knows before sending anything whether a projection can be asked for. A daemon without it (one that survived an app update) gets plain zero-scrollback ANSI requests in the single shared acquisition slot, exactly as today, so visible reads still share one request with an overlapping replay. Visible and ANSI acquisitions are tracked separately only for daemons that advertise projection, so replay readers never receive a projection-only snapshot. No protocol version change, so no second daemon is started on update.
  • After a shrink, the daemon's projection bounds visible rows and the composer-draft cursor context to the applied width (clipToGrid, used only by SessionOutputPlane.getVisibleProjection), through one shared rule (terminal-line-applied-columns.ts): a wide glyph split by the right edge reads as blank, matching the ANSI round trip it replaces, and rows whose overhang is blank reuse xterm's cached row text. Every other reader (main's live-model reads, waits, prompt checks, tail reads, the renderer's composer and IME reads) runs exactly the code and cost it runs today.
  • terminateOwnedTree moved from session.ts to session-process-inspection.ts unchanged, to keep session.ts under the 300-line limit.

Why

This is the first step of moving terminal output parsing off Electron's main process: the daemon already parses every byte of a session, so screen reads should come from that model instead of being rebuilt on main. The capability is negotiated in the daemon hello: daemons that survive an app update don't advertise it and keep today's path, and an older app never sends the new option.

Linked Issue

N/A (maintainer change; part of the backend move).

Visual Proof

N/A: no visual or interaction change; screen text read for background terminals is identical.

Testing

  • Automated tests added/updated, or explained why not below
  • Every added test fails without this change and avoids the test anti-patterns
  • Daemon server test: a requested projection returns the active screen rows and stream position with no ANSI fields.
  • Runtime test: a provider-preferred visible read adopts returned rows without building a parse emulator, and falls back to parsing when the provider returns ANSI.
  • Perf contract (provider-buffer-acquisition.performance.test.ts): a screen read held past its 750 ms wait plus its fallback, and an older daemon's screen read overlapping a zero-row replay, each make exactly one provider request per terminal at 2 and 20 terminals.
  • Shrink tests (daemon projection): a 10-column alternate screen shrunk to 9 columns reads abcdefghi (not abcdefghij) and its composer draft abcdefg (not abcdefgh); split and exactly-fitting wide glyphs; scrollback keeps its text.
  • Hello tests: the daemon advertises the capability; a reconnect replaces it.
  • Windows (ConPTY) and macOS QA: restart, reattach and many terminals under load (results in the status comment).

Performance

Less work: on Omarchy, main-thread time per provider-preferred screen read drops from 0.27-0.75 ms to about 0.01 ms (identical lines), and the daemon's side is 43-126 us per read including the post-shrink worst case. A provider-preferred visible screen read no longer serializes the screen to ANSI in the daemon, sends it over the socket, and re-parses it in a fresh emulator on main; the daemon reads rows from the emulator it already has. Nothing new runs per output chunk or on a timer. Measurements on the exact head are in the status comment.

Risk

Level: Medium. The riskiest part is screen text for background terminals coming from a different code path; if it were wrong, an agent-waiting or idle check could read the wrong screen. The rows come from the same projection function over the daemon's live model at the same read point a snapshot uses. Older daemons and other providers keep today's path. A plain revert backs it out.

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

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)
  • I stated the risk: what could break, for whom, and how to back it out
  • 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)

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan blocked

P1 — One slow screen read can launch two snapshots for the same PTY. The format split in terminal-buffer-selection.ts:143–158 changes what happens when a provider-preferred terminal read --screen reaches the 750 ms visible wait and the original request is still pending. The visible path schedules late adoption, then readRenderedScreen falls through to a zero-scrollback ANSI read. The base joined the pending acquisition because both requests qualified for the same zero-row slot. The head starts a second getSnapshot if the ANSI slot is empty and waits on that request with the existing 8 s ANSI caller budget. This takes one reader and does not require a second consumer or output between the captures. The original reply can populate the cache while the fallback still waits for its own reply. Acquisition split · Visible deadline and late adoption · Screen fallback · ANSI selection

  • Work and impact. Per affected miss, control RPCs, ownership/write fences, and completed wire replies go from one to two when both requests land. On a current daemon the daemon JS thread can project one grid and serialize a zero-scrollback ANSI snapshot for the same read. The base serialized one. Electron main decodes both replies and has a second live mode tracker for this PTY's chunks while both captures are pending. Its normal projection savings still apply to the first reply. A delayed screen read can wait for a second queue turn and add ANSI work while the daemon is already behind. The 750 ms deadline leaves its request live, and the 30 s control deadline drops the client entry without canceling server snapshot work. Daemon settle · Reply encoding · Chunk scans · Control deadline
  • Older daemon overlap. A still-running compatible daemon ignores the new option and returns ANSI. If a zero-row ANSI replay request overlaps a pending visible acquisition on the same PTY, both replies on the head carry ANSI, where the base shared one serialization and reply. A mobile or paired viewer's zero-row ACK recovery snapshot is one production replay caller. A projected reply and a real ANSI replay can legitimately overlap on a current daemon. The duplicate legacy capture and the self-triggered timeout fallback are the excess work. Adapter · Replay caller
  • Fleet price and regression check. For 12 CLI callers reading every 3 s, one affected miss per read means 4 additional RPCs, fences, and daemon grid captures per second, with zero added at idle. A simultaneous one-read burst across 300 affected PTYs adds 300 of each, or 3,000 at 10×, with no scan over unaffected PTYs. These are conditional operation counts. A deterministic regression check can hold the first response past 750 ms, release a sequence-current frame, and assert one provider request per addressed PTY at N and 10N. Also test a simultaneous zero-row legacy replay, a current-daemon replay that still receives ANSI, stale-frame rejection, and teardown. Reuse the pending screen result within the caller's budget, and share a sufficient ANSI request when legacy capability is known. The existing tests exercise the happy path and legacy output. The timeout count above comes from the pinned source trace.

Changed work by trigger and owner

R and C below are the addressed PTY's applied rows and columns. B is the encoded reply size. Counts are per acquisition unless a row specifies otherwise.

Trigger and population Daemon JS thread Electron main
Eligible provider-visible cache miss from an explicit screen read, tail/preview fallback, or prompt/readiness probe One session-map lookup and request dispatch. Checks liveness, waits for the existing ownership proof and parser fence, then runs the existing startup ingress snapshot barrier on that session. The proof wait defaults to 750 ms, released on settle or disposal. The parser fence follows queued work for that session. The barrier can drain already-held ingress. The new branch reads applied dimensions, modes, title/CWD, owner, sequence and incarnation. These are existing metadata reads plus the incarnation field. A missing or disposed session ends without walking the grid. For the addressed PTY only, the controller and provider routes forward one optional flag with zero requested scrollback and issue one ordinary control RPC. The current request adds 25 JSON bytes for the flag. Protocol and provider contracts are type-only. Foreign, unsupported and non-daemon routes have no new daemon RPC.
Projection and reply for that miss One sweep of R visible rows, up to two text translations per row for wrap provenance, and one cursor-context pass over at most R live rows, with a text translation and cell/style scan per context row plus cursor-line slices. The composer classifier and row trim/metadata mapping run on those rows. Cost follows visible cell/text volume, roughly O(R×C) for ordinary cells, plus JSON encode and byte sizing O(B). There is no history traversal. Output is up to R text rows and R metadata pairs plus an optional grid-derived draft and metadata. For 24 nonblank rows with zero trailing spaces, metadata objects alone contribute 889 bytes including array delimiters. The existing frame limit is 16 MiB and is checked after stringify. One NDJSON decode and JSON parse O(B), shallow adapter/capture wrappers and constant-size mode reconciliation using the mode bit. The visible state reuses the row arrays and keeps the existing generation/sequence checks. Removes one temporary zero-scrollback emulator, ANSI write/parse and disposal from a successful current-daemon miss. Final read shaping still slices/trims within the existing line/character limits per caller.
Old daemon or unchanged ANSI consumer Compatible legacy daemon serves the same ANSI response for zero requested scrollback. Full replay, checkpoint and renderer/phone attach requests still select ANSI, with the existing 0–50,000 requested-row clamp and live history window of 1,000 rows by default. Full snapshots now construct and spread one fixed-shape metadata object and obtain dimensions through the size accessor. The projection branch skips ANSI serialization, cursor/rehydration strings, OSC link extraction, alternate frame-restore fields and pending escape-tail packaging. A legacy visible reply still uses one temporary zero-scrollback emulator per parse, disposed in finally. Existing visible-only tail, renderer and other ANSI paths still do their own parsing when selected. Projection and a zero-row legacy response skip durable overlay. Larger ANSI requests retain their existing overlay admission and 5 s caller deadline. Format conversion adds a discriminator and builds one adapter result per reply.
Concurrent consumers, output and teardown The daemon still processes each admitted request separately. One-pair overlap can yield two parser fences and two completed replies on one session. No subscription is created. One pending visible read per PTY/generation, one cached frame per PTY, and now up to two indexed provider acquisitions, one per format. A stronger ANSI request could replace its indexed predecessor and leave that request live at the base as well. Each new acquisition adds one temporary mode tracker. For an overlapping ANSI and visible pair the active capture scans can go from one to two per chunk of that PTY, in addition to the settled tracker if present. Matching promise entries clear on settlement, and exit/retirement and generation changes clear the acquisition index and cached frame. Late adoption still checks generation and sequence. Null visible reads use the existing 1 s demand-driven retry gate, and a timed-out visible read awaits late adoption off the caller path.
Cold startup and native teardown The daemon import graph takes the projection, draft classifier and placeholder modules once per process, 16,770 bytes of source across three small modules. The new dependency chain has no startup I/O or await. The moved process-tree termination method still makes one existing subprocess-handle call per invocation in native teardown. The same projection logic was already imported by runtime reads. The moved type and updated import sites add no main-side initialization or teardown work.

Visible gates and cache · Daemon output plane · Snapshot metadata · Projection · Cursor context · Request route · Cleanup

Six questions and regression classes

  1. Unused work before admission. Same provider preference, current-frame cache, known-normal-mode and demand gates. A cache hit sends zero daemon RPCs at 300 or 3,000 resident PTYs. On a miss, the full visible grid supplies the shared frame before per-caller line limits. The slow-read duplicate described above is a finding.
  2. Owner multiplication. Concurrent screen readers share one pending screen read per generation. Separate replay/visible acquisitions legitimately carry different output on a current daemon. Duplicate fallback and overlapping legacy replay match the repeated-read and pending-work classes above. Checked subscription entry, initial reads, replay/recovery and renderer serializers. There is no new subscriber, listener, terminal output publication or change to its idle/load frame cadence. This adds only request/reply traffic, zero projected replies per second without reads and one per completed current-daemon projected request under load.
  3. Thread and storage. Covered daemon ownership/ingress settlement, grid traversal, encoding, main decode, mode reconciliation, parsing and the older-provider path. No new synchronous filesystem, SQLite, or subprocess call. The pre-existing optional slow-snapshot diagnostics can run for each affected extra request. No new history overlay on visible reads.
  4. Growth and progress. One targeted PTY per acquisition. Work is independent of repos, worktrees, remotes, refs, chat count and scrollback depth for the projection and its cache. Existing ANSI parsing and overlay still depend on requested replay volume. Width, height and encoded text determine the new frame cost. The daemon size normalizer has no upper bound for positive finite geometry, so the 16 MiB transport check is not an allocation ceiling. The lack of an early byte cap is shared with the ANSI path. Large-grid payload sizes and stalls remain unmeasured.
  5. Execution host. Traced the local daemon, old-daemon compatibility, degraded routing, unsupported/direct PTY, SSH/remote ownership routing and mobile/paired replay. The option adds no host discovery or SSH round trip. The projection reads the active buffer for either screen mode. Native OS, WSL, live SSH and phone pairing were assessed by source only.
  6. Obsolete work. Steady-idle wakeup delta is 0/s on daemon, main and renderer. Exit, floating retirement and generation invalidation remove cached state and acquisition references. RPC timeout still is not server cancellation. Distinct format slots increase the number of requests that can outlive a timed-out screen caller as described above.

The recurring classes matched here are re-reading unchanged input and overlapping pending work (P1), per-chunk rescans (one extra capture tracker in that P1 overlap), per-entity retention (one additional indexed slot, cleared as above), eager startup imports (the fixed one-time daemon graph above), and idle wakeups/hidden owner work (no new cadence at idle, with requests still gated by active callers). The request-scoped deadlines predate this change, and the idle-wait poll still reads the live main-side model. The changed test files add a daemon wire check, concurrent current-daemon replay and legacy parsing checks, an ownership assertion adjustment, and test import updates. They add no shipped work.

Verification. 201 tests passed across four named files through the test gate on macOS. The daemon server test exercised the real local control socket with simulated PTY output, including alternate-screen rows with no ANSI fields and a separate legacy-form request. The runtime suite covered successful projection, replay, legacy ANSI, and stale or replaced terminal rejection. Row provenance and settled shell ownership tests passed. No app build, launch, live fleet profile, or captured cross-platform latency. The P1 is a source-proven request-count regression, with user-visible latency magnitude unmeasured.

Reviewed f2be6077d0559f7d516932795213d01d6497ed7f..2bcb9c91af28444dbcbaf7cdbe23b4abf3e69285.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan blocked

P1 — The first screen read can still duplicate a zero-row replay on a compatible older daemon. In terminal-buffer-selection.ts:145–174, the repair learns ansiOnly after a successful response. Start a provider-preferred screen read on a PTY with no learned capability, keep its response pending, then start a zero-row replay for the same PTY. Mobile and paired-viewer ACK recovery requests zero rows when the link lacks room for history. The base joins the pending zero-row acquisition. The reviewed head creates a separate ANSI acquisition. An older daemon ignores the flag, so both captures serialize the same ANSI frame when no output intervenes. The replay can wait behind redundant work on a daemon already catching up. Head acquisition · Base acquisition · Legacy daemon dispatch · Zero-row recovery · Authoritative replay

  • Work and fleet price. Per cold overlapping pair, one extra control RPC, ownership/parse fence, ANSI capture, encode, socket reply and main decode. Both captures also scan each live chunk of their PTY while pending, up from one capture scan, alongside any existing settled mode tracker. There is no traffic increase at idle. A simultaneous first-read plus replay burst on 300 affected PTYs adds 300 of each operation, or 3,000 at 10×. Twelve callers making one affected pair every three seconds would add four captures/s during that cold workload. Successful capability learning stops the duplication for subsequent pairs on each generation. These are conditional operation counts. Daemon fence · Wire reply · Chunk scans · Legacy adapter routing
  • Regression check. Hold the first projection-request response from an ANSI-only provider, start zero-row authoritative replay, then release the ANSI frame. Assert one provider request per PTY and verify both screen and replay outputs. Run at two populations. The existing legacy overlap test first resolves a warm-up screen, so it exercises the learned flag. Preserve the current-daemon control in which concurrent replay still receives ANSI. Provider capability known before admission, or bounded sharing until the pending reply identifies its format, could close this case. Those remedies are unverified. Warmed legacy control · Current-daemon replay control

Original 750 ms repro passed. The gated performance test starts provider-preferred screen reads, holds the first reply past 750 ms, and releases a sequence-current projection at 751 ms. It got 2 requests for 2 PTYs and 20 for 20, all projection requests, and every caller returned the projected screen. The fallback now joins the original acquisition under the existing 8 s caller budget. The tests also passed for ANSI-first sharing with a 50-row replay and visible-first sharing after legacy capability is learned. The remaining cold-overlap finding comes from the pinned source trace. Original input and count assertions · Screen fallback · Wait budgets

Changed work by trigger and owner

R and C are the addressed PTY’s applied rows and columns. B is one encoded reply’s byte size.

Trigger and population Daemon JS thread Electron main
Eligible miss from a screen read, tail/preview request, prompt or permission check, or the one-shot adopted-terminal readiness probe One dispatch and session lookup. The request router adds two shallow options copies on the fixed production payload. A missing or dead session returns before grid work. A live session takes the existing ownership proof wait (750 ms default), queued parser fence and startup ingress snapshot barrier. Any retained ingress drained is for that session. The branch reads dimensions, modes, title, CWD, optional shell owner and output sequence. The repair removed the PTY incarnation ID from projection replies. One provider lookup and one control RPC per admitted acquisition, with zero requested history and a 25-byte JSON flag when projection is requested. The controller and router pass the options through to the owner. Unsupported and foreign routes issue zero local-daemon requests. Type-only protocol, provider and shared contracts add zero runtime operations.
Successful projection of a current daemon’s active grid One visible-row sweep, at most two row translations per visible row for wrap provenance, and a cursor-context pass over up to R live rows with a translation and a cell/style scan per context row plus cursor-line slices. Draft detection, trims and output mapping follow visible text/cells. The reply has up to R text rows, R provenance pairs and one optional draft. Twenty-four nonblank rows with zero trailing spaces contribute 889 bytes of row metadata including array delimiters. JSON serialization and UTF-8 sizing are O(B). No scrollback traversal, ANSI serialization, OSC-link scan, rehydration or frame-restore strings, or partial escape packaging on this path. UTF-8 decode, framing and JSON parse are O(B). One adapter object and capture wrapper reuse the row arrays. Mode reconciliation uses the mode bit. A successful projected capture removes the temporary zero-scrollback emulator, ANSI replay, and disposal on main. It still checks generation, mode and sequence for cache adoption. Each CLI result still shapes its output with the existing 2,000-line maximum and 32 KiB tail budget.
ANSI request for replay, hydration or inspection, or an older provider’s response to the flag The existing ANSI path now allocates and spreads one metadata object and reads size through the accessor. The existing 0–50,000 requested-row clamp and default 1,000-row daemon live history apply. Checkpoint, attach and final teardown still use ANSI. The process-tree termination method moved to the parent class and still calls the existing subprocess handle once per invocation. One response shape check and result wrapper. Legacy visible replies still parse through a temporary zero-scrollback emulator disposed in finally. A zero-row reply skips durable-history overlay. Larger ANSI requests still use the existing overlay admission and 5 s wait deadline. Screen readers can join a pending, unretired ANSI capture when there is no usable projection in flight. If that ANSI result carries history, only its visible buffer is parsed for the screen.
Overlap, output after capture, timeout, or teardown One fence and encode per admitted request. The current daemon can legitimately fulfill ANSI and projected requests concurrently. The excess legacy pair is priced above. No new periodic sweep, stream, or server cancellation. One indexed ANSI and one indexed visible acquisition at most per PTY, shared by matching callers. Stronger ANSI demands can displace an indexed request while the earlier request is live, as on the base. One projection completion continuation learns a single boolean per visited legacy PTY generation. Matching slots clear on settlement. Exit, floating retirement and generation advance clear the index and visible cache; late completion cannot install a new acquisition in the cleared index. There is still one cached visible frame per PTY and one tracker per actual pending capture. A null visible capture keeps the existing demand-driven 1 s retry gate.
Daemon cold startup and first eligible read Three existing code modules enter the daemon’s eager import graph once per process, totaling 16,770 source bytes. They initialize fixed regexes, functions and two small sets. There is no extra startup I/O or await. The first grid walk occurs on demand. The same projection code was already imported by runtime readers. Updated import sites and type moves add no main-side initialization. Tests and the replay test-harness import change add no shipped work.

Routing · Snapshot metadata · Projection · Rows · Cursor context · Provider adapter · Provider fallback · Visible cache · Generation cleanup

Six scan questions and regression classes

  1. Admission and unused work. A sequence-current cache hit sends zero daemon requests at 300 or 3,000 resident PTYs. Provider preference, the known-normal and main-model gates, and the existing read/preview fallback admission still apply. The full grid supplies a reusable frame and cursor context before per-caller clipping. The cold legacy overlap pays for a second equivalent capture. On a late legacy reply shared between late cache adoption and one explicit screen fallback, there can still be two main parses of the same ANSI data. That also occurs on the base. Four affected calls per second can drive eight main parses per second when both consumers run. The projected reply removes both parses. Visible admission and adoption · Explicit screen fallback
  2. Owner and consumer count. One terminal per direct read. The optional worktree agent-wait listing is existing fan-out over eligible terminal-backed rows on the returned page, with one shared in-flight visible read per affected PTY. A page visiting 100 or 1,000 distinct eligible PTYs can therefore start 100 or 1,000 captures if all miss, in both revisions. No additional listener, subscription, or stream publication. A successful current projection sends one reply per completed acquisition. The existing periodic idle-wait path still reads the main emulator. Optional listing · Agent row callers · Permission gate · Idle-wait source
  3. Thread and storage. The daemon does the grid and reply encoding synchronously on its JS thread after the existing fences. Main still pays bytes received and decoded. Screen reads add zero filesystem I/O, SQLite work or subprocesses on either thread. ANSI overlay and optional slow-snapshot diagnostics retain their existing gates; the P1 can invoke diagnostics a second time if the second capture crosses the existing 25 ms threshold. Reply encode · Main response decode · Diagnostics
  4. Growth and progress. The projection follows grid cells and text, independent of scrollback depth, repository/worktree count, remotes, refs and chat history for a single read. Mobile fit clamps at 1,024×500. The daemon size normalizer itself accepts positive finite geometry without an upper bound, and the pre-existing 16 MiB frame gate applies after stringify. Applied desktop geometry and long cell text can therefore dominate bytes and service time. Large-grid timing and heap cost were unmeasured. The 750 ms/8 s waits and 30 s control deadline bound caller/client retention, with live daemon capture work still governed by session parsing and disposal. Fit clamp · Daemon size · Encode limit · Transport deadline
  5. Execution host. Traced local daemon and legacy routing, degraded/direct PTY, paired and mobile replay, and foreign/SSH dispatch. The flag adds zero host discovery calls and zero SSH round trips. The projection uses the applied active grid for alternate and normal screens. The macOS socket test used a simulated subprocess. Live older-daemon overlap, paired/mobile transport, native Windows/ConPTY, WSL, Linux and SSH were assessed by source. Provider dispatch · Daemon wire test
  6. Obsolete work and idle. Change in steady-idle wakeups is 0/s on daemon, main and renderer by source. Request-only waits, sequence checks and exit/retirement cleanup cover ordinary completion and invalidation. Caller timeout can leave an admitted request live and the transport timeout drops the client entry without server cancellation. This behavior predates the PR. The P1 puts one extra request through it per affected pair. Acquisition retirement · PTY exit cleanup · Floating cleanup

Matched classes are repeated reads of unchanged input, pending-work multiplication and extra per-chunk scans (P1 above), per-entity retention (one additional indexed slot and one boolean, cleared with the PTY generation), eager startup imports (three small modules once per daemon process), and idle or hidden-owner work (zero added idle cadence, with requests admitted by demand). No newly bypassed feature gate, store churn, new process spawn, storage rewrite, or full-state publication was found in the changed paths.

Verification. 205 tests passed across five named suites through the macOS test gate. The performance suite exercised the runtime controller/provider boundary with synthetic replies. The runtime suite covered concurrent current-daemon replay, legacy parsing, stale output and replacement generations. The daemon server suite exercised a real local control socket and validated both response formats with simulated PTY output. Row provenance and settled shell ownership tests passed. Source counts and the executed cases above are separate from estimates of fleet impact. No live fleet latency, CPU, or heap profile was collected.

Reviewed f2be6077d0559f7d516932795213d01d6497ed7f..39132ce64dc4a220ebe84d36c11a44fc5e2dd902. At posting, GitHub listed the preceding commit as the PR head. This report and its marker apply to the local repair commit above.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan blocked

P1 — Clipping bypasses the row string cache on Electron main, including grids that never shrank. In bb886ca88fe, readHeadlessTerminalRows always supplies an end column, even when it equals the stored row width. The installed buffer's translateToString only reads and populates its row cache when the end column is omitted. For a warm, unchanged, unwrapped 120×24 ASCII grid, the base row pass makes 24 cache hits. The head adds 2,880 cell decodes, 24 temporary arrays and 24 joins per projection, plus 24 backward trim probes. Existing cursor context and final projection work are outside that delta. The 2 s idle-wait sweep can run the affected screen read for each eligible pending waiter with a live emulator. At one projection per sweep for 100/1,000 such waiters, the added work is 144,000/1,440,000 cell decodes and 1,200/12,000 row joins per second on main. Twelve explicit readers reading every 3 s add 11,520 decodes and 96 joins per second when they hit unchanged live grids. These counts describe direct work competing with main's input and IPC handling. A deterministic guard can warm the actual emulator's row cache, read unchanged full-width rows twice, and count trim/translation slow paths at both populations. Preserve the clipped wide-glyph and wrapped provenance outputs on the oversized-row branch. The source proves the cache miss. The current shrink test checks output only. Rows · Main projection · Timer admission and sweep · Screen-read wiring · Shrink fixture

P1 — The daemon projection does width-dependent work for invisible cells after a shrink. The daemon call introduced in 2bcb9c91af projects straight from the live buffer. The bb886ca88fe row clipping caps forward translation, but the projection's cursor-context translator and style scan still use stored line length. The clipped row's trim lookup also starts at the stored right edge. The existing alternate-screen shrink fixture exercises retained wide rows. The base ANSI serializer and link walk worked within the applied width, and main's newly allocated parsing emulator had that same width. For a 24-row alternate screen shrunk from 1,024 to 120 columns with retained rows, just the context style scan visits 24,576 cells per request. Of those, 21,696 are outside the applied grid. Four fresh reads/s add 86,784 such visits/s on the daemon JS thread. A one-read burst on 300/3,000 affected PTYs adds 6,508,800/65,088,000 visits, before other translation and trimming. This can delay other PTYs' requests and output on that daemon. The cost persists when the width shrinks and the underlying rows survive subsequent paint. A guard can hold applied geometry and visible output fixed, vary retained width 10×, and count cell visits through the daemon snapshot. Include blank off-grid tails, off-grid text and a wide glyph at the edge to check both traversal and composer evidence. The counts follow the pinned source and the installed buffer's trim loop. The larger workload was unexecuted. Projection branch · Cursor context · Context row and cursor bounds · Base-parity width in link capture · ANSI fallback geometry

P1 — The version bump adds steady idle work while the previous daemon still owns live terminals. Protocol 62 selects a different endpoint and startup eagerly starts and leases a v62 daemon even with a healthy v61 daemon serving the old terminals. The base reused the v61 endpoint on that input. On default launched profiles, the new process schedules one host terminal-policy refresh every 3 s when the host policy path is available and there is no environment override (up to 1 KiB, guarded against overlapping reads), one host-ledger tick every 60 s, and one process-growth timer every 30 s at idle. Unix also runs one synchronous endpoint stat every 30 s. For those four timers, the v61 process stays at 25 callbacks/min on Unix or 23 on Windows, while v62 goes from absent to 25/min or 23/min. The added daemon goes from 0 to about 0.417 callbacks/s on Unix or 0.383/s on Windows. Totals grow from 25 to 50/min on Unix and from 23 to 46/min on Windows. The extra timer count on main and renderer is 0/s. With a policy override, subtract the policy's 20 ticks/min per process. The ledger tick writes only after that process has published its share. In ordinary observe mode the idle growth tick schedules its next run without reading the process table. In enforce mode two generations with live PTYs can each request one host process inventory per idle 30 s, where one generation made one request. The extra daemon and timers are per upgraded profile at both 300 and 3,000 terminals, with two generations retained while the old sessions stay live. This adds wakeups and duplicate host-policy I/O without a screen read. Verify with a healthy v61 owner kept alive across init, no new terminals or screen reads, and count daemon processes, timers and I/O before/after with a fake clock over 60 s. Separately exercise active v62 sessions and v61 retirement. The rates are source-derived. Protocol · Versioned endpoint · Provider init · Lease and legacy discovery · Policy · Ledger · Growth timer · Unix ownership timer

Prior findings verified at this head

  • Delayed screen fallback, comment 7069338601. Held the first projected reply through 750 ms and released it at 751 ms. The exact contract passed at 2 and 20 PTYs with 2 and 20 requests respectively and every caller got the projected screen. The fallback joins the original slot within the 8 s caller budget. Timeout contract · Fallback
  • Cold old-daemon overlap, comment 7069672609. Held the first screen reply and requested zero-row replay before it settled, without a warm-up. The exact contract passed at 2 and 20 PTYs with 2 and 20 ANSI requests respectively, and both consumers got the expected outputs. The provider double reports its format capability through the real runtime/controller boundary. Source confirms the routed adapter decides from the already-known protocol version, so both consumers take the ANSI slot on the first read of a v61 PTY. The ACK recovery caller still selects zero rows on a constrained link. Current-daemon screen-first overlap still returns distinct projection and ANSI results, and ANSI-first with 50 requested rows still shares the existing ANSI capture. Cold overlap contract · Admission · Capability · Current-daemon control · ACK recovery

Work by trigger and owner

R and C are the addressed PTY's applied height and width. W is its stored row width and B is the encoded reply size.

Trigger and population Daemon JS thread Electron main
Explicit screen read, summary/preview or eligible tail fallback, prompt/resubmit, permission query, or one-shot adopted-terminal readiness probe One request on an admitted miss, one session lookup, two fixed-shape option copies for the production RPC, existing liveness check, shell proof wait (750 ms default), parser fence and ingress barrier. Only the addressed session's pending writes and held ingress can be drained. The slow-snapshot diagnostic remains opt-in and sees completed calls taking at least 25 ms. One host/provider lookup and one routed adapter lookup per capability query, before choosing the acquisition slot. One local version comparison, repeated by the adapter when making a projected request. A cache hit, known-normal branch with live model, or pending request join can avoid the RPC. Unsupported capabilities choose ANSI; foreign dispatch cannot reach a local daemon. No host discovery on this path.
Current-daemon projection, per admitted capture One scan of R visible rows with one trimmed translation per row and a second translation for each row followed by a wrapped row. There is one length/width check per row and up to one cell lookup without a reusable cell per oversized row. Cursor context takes up to R live rows with a translation and a style pass per row and cursor-line slices. Translation and style work can follow W after resize, as above. Draft detection and row trimming/mapping follow the text produced. No history traversal. Returns up to R text rows and R provenance objects, optional draft, dimensions, modes, CWD/title, owner and output sequence. Encode and UTF-8 sizing are O(B). 24 nonblank rows with zero trailing spaces add 889 bytes of row metadata, including delimiters. Decode, framing and JSON parse O(B), fixed-shape adapter and reconciliation objects, shared projection arrays, mode/sequence/generation checks. Replaces the temporary emulator, ANSI replay and visible re-projection for this response. Each screen-read result still shapes up to 2,000 lines and 32,768 UTF-16 code units of preview text.
ANSI, hydration, attach/replay, checkpoint or final teardown Existing ANSI work plus fixed-size metadata and size objects. Snapshot options still cap requested history at 50,000 rows, with a default 1,000-row live history. ANSI still handles links, rehydration, frame restore, and partial escape state. Process-tree termination moved to its base class and makes the same single handle call when invoked. One format discrimination and adapter result. Visible ANSI fallback, including an earlier ANSI replay joined by a screen read, parses only the visible frame with a temporary zero-scrollback emulator. Renderer fallback does the same. Non-visible provider tail still concatenates the two ANSI fields, parses into a disposable emulator with scrollback up to the requested line limit, and projects the tail. Zero-row legacy ANSI bypasses durable overlay, and larger ANSI replies still use the existing 5 s overlay wait.
Concurrency, completion, stale output, close or disconnect One capture and reply per admitted request. Current projection and ANSI replay can coexist. Distinct wire formats require distinct replies. No new stream publication or screen subscription. One indexed request per format per PTY generation; matching waiters join. Stronger ANSI demands can supersede a live indexed request as on the base. One temporary mode tracker per live acquisition. A genuine concurrent pair adds one scan of that PTY's chunk while both are pending, with a plain-text precheck and up to 4,096 code units of carry per tracker. For K chunks/s per affected PTY, the added tracker makes K scans/s during overlap, or 300K/3,000K across 300/3,000 simultaneous pairs. Plain-text chunks use the two control-byte checks; escape-bearing chunks can also take the regex and carry path. Per-format trackers preserve their respective observation windows. One pending visible read and up to one cached frame per PTY. The repair leaves no learned per-PTY capability flag after settlement.
Cold startup, mixed generations and build selection The projection, composer classifier and placeholder modules enter the eager daemon graph once, totaling 16,770 source bytes. The modules initialize fixed functions, regexes and two sets. The mixed-generation daemon also runs normal startup once per launch, including the existing OS PTY-limit probe (one bounded child on macOS, two bounded file reads on Linux). One small controller module, 732 source bytes, splits existing buffer dispatch and adds the capability handler. The protocol change adds one legacy endpoint check per provider initialization. On Unix an absent endpoint costs one existence check and PID read attempt plus up to two stale unlinks; a reachable endpoint can take one probe with a 1 s deadline and one legacy adapter. Projection capability itself adds zero startup waits. Mixed-generation adoption adds an empty current inventory to discovery of the live legacy inventory and adds one adapter to provider fan-out where routed ownership must be refreshed. A missing-session close can consult one more protocol record or provider. Build/host preflight and explicit stop enumerate one extra protocol candidate. The generated build compatibility contracts carry one more integer. Tests and the test-harness import move have zero shipped work.

Request routing · Existing fences · Proof and parser fence · Provider dispatch · Projection · Legacy discovery · Hold and ordinary snapshots · Chunk scanning · Separate mode boundaries · Close inventory · Host preflight

Every production caller of the clipped row read

Call chain Trigger, population and bound
Daemon getVisibleProjection → projectTerminalVisibleLines → getVisibleRows One R-row pass per projected RPC; the first and second findings price the per-row translation and retained-width passes.
Main readHeadlessVisibleTerminalState → getVisibleRows One R-row pass for a live model on demand, during an eligible provider mode-transition fallback, or on the existing idle-wait blocked-screen check. The 2 s timer belongs to the runtime and sweeps active wait entries. An initial weak-ready tick and scheduled rechecks can also run. The blocked-screen path gates on verdict and one in-flight read per waiter. It can project for multiple waiters on one PTY.
Main readLiveTerminalScreenLines → getVisibleRows One R-row pass per admitted whole-model read. This serves lazy TUI screen evidence on wait entry/tick/resample and input-delivery decisions, untitled interactive-wait identity, dialog holds on terminal/mailbox delivery, and the launch-composer settle check on readiness events or its deadline. The lazy evidence reader memoizes one read per verdict. An eligible wait tick can also run the separate blocked-screen read above, giving two projections in that tick. Trusted rules that use the raw screen take getVisibleLines and bypass this helper.
Main parseVisibleSnapshot → getVisibleRows One R-row pass for each nonempty ANSI replay in a fresh zero-scrollback emulator from legacy/provider, renderer, or explicit screen fallback. A late legacy response shared by cache adoption and one explicit fallback can still be parsed twice. That also occurs on the base.
Main readRenderedTerminalTailLines / readProviderTerminalTailLines → projectTerminalTailLines → getBufferTailRows + getVisibleRows One live ConPTY fallback or one scrollback-capable ANSI parse per eligible demand. The live path reads up to min(active buffer length, line limit + applied PTY rows) tail rows, then R visible rows. The provider parse reads up to min(active buffer length, line limit) tail rows, then R visible rows. The line limit defaults to 120 and caps at 2,000. Where tail and viewport overlap, rows can be translated twice. For 120 columns and 24 rows with enough history, default live demand visits 168 rows, up to 20,160 cell decodes on full unwrapped rows. The provider-tail default visits 144 rows, up to 17,280 decodes. Those are full translation counts; the per-read excess depends on cache warmth. The live screen-only ConPTY branch uses exactly one R-row pass.

Live-model gates and raw-rule path · Wait tick gates · Lazy verdict read · Titleless permission read · Delivery dialog read · Launch-composer read · Tail caller bounds · Tail/visible passes

Six scan questions

  1. Admission. Grid creation is behind demand, generation/sequence cache and route gates. Warm, sequence-current reads send zero new daemon requests with 300 or 3,000 resident PTYs. The live main row cache bypass and previously wider daemon rows are the proven wasted construction. Direct optional wait listings can start one capture per distinct eligible PTY on the page, up to 100/1,000 captures for 100/1,000 qualifying PTYs in both revisions. Cache/admission · Page callers
  2. Ownership. Screen/replay snapshot work follows addressed PTYs, acquisitions and callers. No new steady screen publication, renderer listener, or per-mounted-pane effect. The idle-wait timer stays shared and the extra provider generation owns the callbacks priced above. Current-daemon dual capture also duplicates chunk inspection during the overlap. That window carries distinct capture-order evidence and ends on either capture's settlement. Legacy and same-format work shares a capture. Slots · Per-capture tracker
  3. Thread/storage. Projection, encode and byte count run synchronously on daemon JS after the fence. Main receives/decodes, then does the live or ANSI work only on the branches above. Projection adds zero SQLite calls, filesystem requests or process spawns per screen read. Mixed-version lifecycle I/O is covered above. Encode/error path · Main decode
  4. Growth/progress. One screen RPC has no scan over worktrees, repos, remotes, refs or chat history. Geometry, stored width, character volume and concurrent request count vary independently. Mobile fit caps at 1,024×500. Desktop daemon size normalization accepts finite positive dimensions without a maximum. The 16 MiB line cap is checked after stringify, so it bounds accepted bytes and leaves large encode work before a rejected reply. Failure returns through existing null/retry handling. Live geometry and heap/latency at that limit were unmeasured. Mobile bounds · Daemon bounds · Frame cap
  5. Execution host. Traced current and legacy local-daemon routes, degraded/direct PTY, native Windows and WSL paths, Linux, foreign/SSH dispatch, and paired/mobile replay. Capability adds zero remote discovery calls and zero SSH round trips. The executed server suite used a real macOS local socket with simulated PTY output. Native, paired/mobile and mixed-version startup traffic was reviewed by source. Host dispatch · Degraded routing · Socket test
  6. Obsolete work and idle. Shared visible/ANSI slots and temporary trackers release on settlement. Exit, generation advance and floating retirement clear the indexed state, and late adoption checks generation and output order. Visible waits use 750 ms, authoritative waits default to 8 s, and null demand uses a 1 s retry gate. The 30 s control deadline drops the client pending entry. Server work can still finish after caller/client timeout, as on the base. Snapshot-only change in no-demand main, daemon and renderer wakeups is 0/s. Mixed-version daemon callbacks are the third finding. Generation cleanup · Exit cleanup · Floating cleanup · Late adoption

Regression classes screened. Re-reading unchanged input and hot-path rescans are findings on main and daemon. Fixed-cadence polling/steady-idle wakeups and newly reachable host I/O are findings during mixed-version operation. Per-entity acquisition retention is scoped to a live generation and teardown. Format-split fan-out shares matching requests and retains the base's supersession/deadline behavior, demonstrated for the two prior failures. Eager imports add the fixed source sizes above once per process. Wire replies stay demand-driven, one response per acquisition. Existing per-waiter screen polling and optional per-page fan-out predate this span. The clipping change increases their per-read work.

Verification. 223 tests passed across nine named suites through the macOS test gate. They covered the two original inputs, concurrent current-daemon replay, freshness and generation handling, live wait polling, wrapped-row provenance and wide-glyph clipping, socket wire formats, shell ownership and protocol compatibility. The three findings above use source-proven operation counts. No fleet CPU, latency, heap or packaged startup measurements were collected.

Reviewed local f2be6077d0559f7d516932795213d01d6497ed7f..bb886ca88fed8a07048ebbe65fcba9102572892e. At verification, GitHub still listed 2bcb9c91af28 as the PR head. This report and marker apply to the requested local head.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan blocked

P1 — A one-column shrink still bypasses warm row-string caches on main and the renderer. 82c8501f9cd restores canonical translation for rows that fit, but an alternate-screen row can retain its old width after a shrink and a repaint. For an unwrapped 121→120×24 grid with 120 visible ASCII cells per row and an empty off-grid column, warm both revisions on the same unchanged grid. The base hits the row-string cache for each full-row translation. The head passes an explicit end column on every clipped translation, bypassing that cache. An admitted main live-screen projection translates the same 24 rows once for the projection and once for cursor context. That adds 5,760 cell decodes and 48 temporary arrays/joins per read, plus the clip-edge and trim probes. The context's style pass saves only 24 visits across the grid and one visit in the cursor suffix. For 100/1,000 eligible live-model waiters taking this path once per 2 s sweep, that is 288,000/2,880,000 extra decodes and 2,400/24,000 extra joins per second on main. Twelve explicit live-screen readers at one read every 3 s add 23,040 decodes and 192 joins per second.

The renderer's IME mask runs the same context reader on session start and on each render while composition is active. One warm 120×24 pane adds 2,880 decodes and 24 arrays/joins per call. At an illustrative 60 delivered renders/s, one active composition adds 172,800 decodes and 1,440 joins per second on the interaction thread, independent of 300 versus 3,000 resident terminals. Blank retained rows instead add up to 120 public cell loads per row to find the visible trim boundary, even if the result stays empty. These are source-derived operation counts for the shipped buffer implementations and production caller gates. The cost repeats after a single resize and competes with input, render and IPC work. A deterministic guard should count slow translations and trim probes after warming the same-width and 121→120 grids, then mutate one row and verify both fresh output and reuse for the unchanged rows. Exercise repeated active-composition renders and the live main projection at N/10N. Keep applied width, wide-cell behavior, wrapped provenance and cursor style evidence in the oracle. Main visible rows · Context translation · Clipped helper · Main projection · Wait admission · Wait screen gates · IME render gate

Pass 3 inputs at this head

  • Warm unshrunk 120×24 ASCII grid. Every unwrapped row again calls the canonical trimmed translation, so both row passes hit the warm cache. Compared with pass 3, the visible-row pass drops all 2,880 extra forward decodes, 24 joins and 24 trim probes per projection. The head adds one width comparison per visited full-width row in each pass and no clipping-cell allocation; the context also adds one length check when testing hidden-cursor evidence. At 100/1,000 reads each 2 s this is 2,400/24,000 width comparisons per second across both passes. The cache bypass remaining after a shrink is the finding above. Visible rows · Context gate
  • 24-row alternate screen retaining 1,024 columns after a shrink to 120. Under the original input all 24 cursor-context style passes now visit at most 2,880 cells, down from 24,576 at pass 3. Every clip-edge probe, trim probe, forward decode and cursor suffix lookup stays at columns 0–119. Off-grid visits fall from at least 21,696 to zero per projection, including at four reads/s and bursts of 300/3,000 PTYs. The branch never trims retained storage past the applied right edge. On daemon JS, the 24-row visible pass makes at most two applied-width translations per row for text and wrapped provenance, and the context does one style scan and one raw translation per row plus cursor-row slices. A conservative upper bound is 18,000 cell probes/decodes per projected call on this geometry, counting each trim and translation pass separately. At four fresh reads/s that is at most 72,000/s of on-grid work on daemon JS. A 300/3,000-PTY burst is at most 5.4/54 million on-grid operations for 300/3,000 distinct screens. These are work bounds for the projected body, separate from wire and existing fence costs. It no longer grows with retained width. Existing shrink controls passed for off-grid text, an edge-split glyph, a fully fitting glyph, wrapped spaces, clipped draft and preserved historical tail. The 1,024→120 count is a source comparison. Column and translation limits · Cursor slices · Daemon output branch · Shrink controls
  • Healthy pre-upgrade v61 daemon owning live terminals. The base and head both select v61 socket/pipe, PID and token names, with the same 60 legacy protocol candidates and no changes to version-selection or recycling policy. The launcher takes the existing endpoint's authenticated adoption path. A hello without the field chooses zero-row ANSI immediately, including on the first request. This adds zero daemon processes or generation inventories on the original upgrade input at 300/3,000 PTYs. For the four timers from pass 3, steady default totals stay 25 callbacks/min on Unix and 23/min on Windows, with zero added timer callbacks/s on main, renderer or daemon. Source establishes endpoint reuse and the idle delta. The local-socket client test independently exercised absent, malformed and true advertisements across disconnect/reconnect. Protocol · Legacy set · Endpoint names · Adoption · Client test
  • The two earlier acquisition contracts also passed. At 2/20 PTYs, delayed screen responses released at 751 ms made 2/20 requests and the explicit fallback shared them. At 2/20 PTYs, a cold pre-capability screen read plus concurrent zero-row replay made 2/20 ANSI requests. The capable-daemon controls preserved distinct projection/replay when the visible read starts first and reuse of a pending 50-row ANSI request in the reverse order. They also exercised stale output, generation and handle guards. Acquisition contracts · Runtime behavior controls · Explicit screen fallback

Work by trigger, owner and bound

R/C are applied rows/columns for one PTY. W is retained row width. B is the encoded response size. Glyph strings may hold more than one code unit per cell.

Trigger and population Daemon JS thread Main process
Startup, adoption and reconnect, per existing authenticated pair One additive 34-byte field on the control hello. No extra stream frame, connection, timer, process or disk operation. New eager projection, composer, placeholder and clipping sources total 18,479 source bytes, once per started daemon. One boolean on the client, set after both authenticated identities match and cleared on failure and teardown. One small hello argument/closure refactor per connect attempt, still two handshakes and one existing token read. No version change, launch wait or capability probe. The added controller source is 732 bytes. The clipping module adds 1,709 source bytes where the shared context reader loads on main and renderer. The existing shared reader grows by 1,558 source bytes on each graph. These are source sizes and no startup durations were measured.
Explicit screen, eligible read/preview fallback, or provider screen evidence for waits, prompts and readiness Zero work on cache hits. On an admitted miss, one routed request, one session lookup and liveness check, bounded option normalization and one choice of reply format. Existing shell proof can wait up to 750 ms per pending proof, with 262,144 bytes of queued proof output per session. Existing parse/ingress barriers drain that session only. The slow-snapshot diagnostic still records completions taking at least 25 ms when enabled. One capability query per admitted acquisition call before choosing a slot, then one recheck inside a new projected capture. Normal routing uses indexed ownership. A degraded missing-route lookup visits at most 62 known providers via in-memory membership tests, can memoize a found owner, and performs zero inventories or remote probes. Authoritative capability gates remain.
Projected response, per capable snapshot miss One metadata read for applied dimensions, modes, cwd/title, shell ownership and sequence. One viewport row pass, plus one live-screen cursor context over at most R rows and C columns per pass. One composer classification and at most R draft row replacements, blank filters and metadata projections. No scrollback, ANSI serialization, OSC link walk or frame restore. A translated row pays at most one trim and one forward pass per requested representation. One NDJSON read/parse proportional to B, one shallow conversion/reconciliation and generation/mode/output-order checks. New request member adds 25 bytes. Reply has up to R nonblank strings, R wrap/trailing-space records, a draft bounded by the live screen's text, and fixed-field metadata. False/zero wrap metadata takes 37R + 1 bytes for a nonempty R-record array, before the field name. The ANSI and projected byte ratio depends on styling, wraps and content. A sequence-current cached frame serves repeated reads with zero RPCs. Accepted projection avoids allocating, feeding and disposing a parsing emulator. Existing consumers still copy/limit output or join it for preview and wait evidence, proportional to returned rows and text.
ANSI catch-up, seed, replay, older daemon or renderer fallback, per admitted capture Ordinary requests retain the ANSI serializer, mode restore, OSC link collection, and scrollback cap of 50,000 requested rows. Metadata extraction adds one small temporary object instead of direct fields. Mode and cursor restore still use the same source. The process-tree termination method moved to a base class with the same one subprocess-handle call on close and zero work at snapshot time. Unsupported hello and ANSI-first sharing preserve the original replay path. Visible-only parses allocate one grid at the reported dimensions with zero scrollback, feed the ANSI once and dispose it. The late ANSI cache adopter and a concurrent explicit fallback can each parse the shared response, as on the base. Authorized scrollback reads still use the existing durable overlay where requested. Projected reads bypass that overlay.
Concurrent demand for one PTY, generation and wire format One reply for callers sharing a slot. If a capable visible request starts first and replay also needs ANSI, the existing control connection carries one additional request/reply for the overlap, for two distinct results. An ANSI-first pending capture of sufficient size can satisfy both. Larger ANSI requests can supersede a smaller one as on the base. One indexed pair of current acquisition slots, plus the existing per-caller timer/promise. Each true capture owns a temporary mode tracker. During visible/ANSI overlap the extra tracker adds one scan per incoming chunk, or K/s at K chunks/s for one PTY and 300K/3,000K if that many PTYs are simultaneously in overlap. Each scan has control-byte admission, potentially a regex pass over the chunk and at most 4,096 code units of carry. The trackers cover the distinct capture start times and leave on settlement. Existing output consumers otherwise see the same stream.
Main live-grid row reads and tail reads No daemon request for an admitted whole live model. Visible projections and direct cursor-context readers pay the same width checks and clipped costs as the daemon, plus the warm-cache regression above. Raw rule grids use the separate plain-line reader. Rendered tail reads still visit up to min(buffer length, L + R) historical rows on live ConPTY, or min(buffer length, L) on parsed provider tail, followed by R visible rows and one context. L defaults to 120 and caps at 2,000. History keeps stored-width text. A wrap can require a second translation to reconstruct spaces, as on the base.
Active renderer composition and native-chat draft read Zero provider work added. Zero provider work added. In the renderer the shared reader checks width once per row over the active pane's live screen. The IME mask makes one read on accepted composition start, one per delivered render during composition, and a possible read on a mismatched end while a newer composition is active. Matching end/blur/dispose clears the gate. The native-chat route reads one selected pane on draft pickup, option/send/paste verification. The existing paste verification samples at most once per 100 ms for up to 5 s per eligible send. At 10 cache misses/s on the 121→120 sample, this is 28,800 extra decodes and 240 joins/s during that send. The existing revision and cursor-row key gate avoids context on cache hits. It retains the unchanged one-row canonical read before that gate. On an unshrunk 120×24 pane the delta per context is 24 width checks, zero extra scans or joins. At 60 delivered reads/s that is 1,440 width checks/s for that pane and zero when there is no admitted read. An oversized row adds one edge check, up to C trim probes and up to C forward decodes per raw read, while the style scan and slices cap at C.

Controller route · Host registry · Degraded dispatch · Degraded membership · Hello wire · Pair handshake · Request routing · Snapshot fence · Parser and ingress fences · Shell proof limits · Ordinary and projected serialization · Projection work · Adapter fallback and overlay · Acquisitions · Mode tracker lifetime · Output scan · Main tail bounds · Renderer draft cache · Draft pickup · Paste verification cadence

Main live grid callers include the ordinary visible-state path, late mode-transition reconciliation, the waiter blocked-screen path, and lazy TUI evidence during wait entry/tick/resample, input delivery and launch readiness. A wait sample memoizes one lazy evidence read, and can also run a separate gated blocked-screen projection. Titleless eligibility, permission/delivery and launch-composer checks each address one PTY. Direct context calls also run on a guarded mailbox/delivery draft check, prompt-render arm or admitted output/settle callback (one proof read in flight per gate), and eligible prompt resubmission after the current screen has settled. A prompt proof can run both a visible projection and a second typed-context read. Ordinary key handling adds no new call to cursor context. Echo or key input can cause a render, and that render takes the IME path only while a composition is active. The moved readiness rule helper lazily reconstructs draft text once per admitted rule read with up to one reverse row search, one draft split and one output copy. Unchanged replay callers, bridge/type moves and test wiring add no shipped recurring work. Lazy wait evidence · Titleless read · Permission read · Launch composer · Delivery draft hold · Prompt render gate · Resubmit · Readiness probe

Six scan questions and class dispositions

  1. Admission. Generation, sequence, pending-read and normal-mode gates precede provider capture. At 300/3,000 cached valid frames, rereading them adds zero captures. Optional wait listing can fan out to 100/1,000 captures on a page with 100/1,000 distinct eligible PTYs in both revisions. The pre-existing sweep can also sample multiple waiters on one PTY. Re-reading unchanged input and hot-path rescans are findings on warm retained-width rows. Full-width paths keep canonical translation. Visible admission and retry · Listing caller
  2. Ownership and fan-out. One acquisition of a matching format per addressed PTY in the ordinary case, as verified by the delayed and cold-overlap contracts. The format split leaves one additional tracker only while distinct consumers need both formats. No per-mounted-pane request or new subscriber, publication, feed or full-state notification. The renderer's existing IME callbacks address their own terminal, and parse/resize draft revision listeners remain one pair per terminal with demand. Same-format and ANSI reuse · Renderer listener lifecycle
  3. Thread and storage. Projection, stringify and byte count run synchronously on daemon JS. Main decodes and only parses ANSI on its fallback or replay branches. Per projected read there are zero new filesystem/SQLite operations, transactions or subprocesses. Eager imports add the fixed source sizes above once; no new synchronous startup I/O. Wire encoding · Wire decoding
  4. Growth and progress. One projection has no traversal over worktrees, repositories, remotes, refs, agents or transcript history. Geometry, glyph bytes and admitted concurrent PTYs scale independently. Mobile fit caps at 1,024×500 and daemon desktop dimensions use the existing finite-positive validation. The 16 MiB wire cap applies after stringify, and existing socket writes can still queue replies during a stalled consumer. There is no new global snapshot queue. Oversize replies return through existing error handling, with per-PTY retry and caller deadlines. Large-geometry encode latency, queued-byte high water and packed-app CPU/heap were unmeasured. Mobile dimensions · Daemon dimensions · Wire cap
  5. Host. Traced healthy/current, earlier v61, older supported generation, degraded/direct local and foreign/SSH dispatch. Native Windows/WSL, Linux and paired/mobile replay keep the old routing and replay request. Projection adds zero SSH round trips and no newly reachable discovery or host I/O gate. Local macOS sockets exercised capability and both reply shapes with simulated PTY output. Native-host, remote-device and packaged-adoption paths were source-reviewed. Snapshot socket controls · Provider routing · Constrained replay
  6. Obsolescence and idle. Existing caller budgets are 750 ms visible, 8 s authoritative by default, 1 s retry for a failed adopted frame and a 30 s control request deadline. Format slots and temporary trackers release on settlement. Exit, generation change and floating retirement clear indexed state. The cache retains up to one visible frame per live PTY. Existing server work may finish after a caller times out. Fixed-cadence and steady-idle screens found zero added callbacks/s with no demand on daemon, main and renderer, including the original v61 upgrade. Active wait and composition callback rates stay unchanged. Their extra per-read work after a shrink is priced above. Generation teardown · Exit teardown · Floating teardown · Late adoption

Verification. 89 tests passed across 11 named unit files, plus six targeted tests in the runtime aggregate through the macOS test gate. They covered the socket contract, handshake reset, provider acquisition counts, resize and cursor-context output, idle wait, wrapped-row metadata, shell-ownership snapshot and renderer composition behavior. The cache and fleet figures are source-derived operation counts. The exact 121→120 warm-grid cost has no executed counting contract. No packaged-app or native IME timing, live fleet CPU, heap, or startup measurements were collected.

Reviewed local f2be6077d0559f7d516932795213d01d6497ed7f..82c8501f9cd10889996619cda4e3e4cb4f3feddd. GitHub listed 2bcb9c91af28 as the PR head when this report was prepared. The findings and marker apply to the requested local head.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan pass 5 — blocked

P1 — Retained-width rows still redo clipping work on every warm read. Width clipping introduced in the PR bypasses the warmed full-row string cache whenever retained columns contain text. The final repair in 4a60caf513f restores the cache path only when it proves the overhang blank. In an unwrapped 121→120×24 alternate-screen grid with 120 visible ASCII cells per row, leave one previously painted ASCII cell or literal space in column 121 and make repeated reads after paint and resize stop. The retained rows survive the shrink. Base repeatedly hits its canonical full-row string cache. Head polls the edge and overhang, then passes an explicit end to the translation cache's bypass path. The otherwise unchanged row now pays 120 forward decodes and one array/join per full-row translation, plus clipping and trim probes. Main's live projection makes two full-row passes, which adds 5,760 full-row decodes and 48 arrays/joins per read. Active renderer IME makes one, adding 2,880 full-row decodes and 24 arrays/joins per read. The context saves 24 style-cell visits and one cursor-suffix cell visit on this input. The extra decoding repeats for every admitted read of the same rows. Applied-column reader · Visible rows · Cursor context · Main live-grid projection · IME composition gate

The final blank-overhang check also adds recurrent scanning even when canonical translation hits. On a warm 240→120×24 grid with 120 visible ASCII cells and 120 empty retained cells per row, the two main passes issue 5,808 edge/overhang cell loads per projection, including 5,760 off-grid loads. Subtracting 2,880 fewer style-cell visits and 120 fewer cursor-suffix visits leaves 2,808 additional public cell loads before cursor trim and encoding costs. The IME has one blank-proof pass of 2,904 loads. On that renderer input, most of those replace visits from the old full-width style scan. The main headless row pass alone adds 2,904 loads to what was a cache hit per row. Both shapes matter because repeated reads after repaint still encounter the same retained width and cells. Applied-column reader · Visible rows · Cursor context

At one admitted live-grid projection per existing two-second sweep for 100/1,000 eligible waiters, the occupied case adds 288,000/2,880,000 full-row decodes and 2,400/24,000 joins per second on Electron main. The blank case adds 140,400/1,404,000 public cell loads per second after the style and suffix savings described above. Twelve CLI readers at one read every three seconds add 23,040 full-row decodes and 192 joins/s in the occupied case. At an illustrative 60 delivered renders/s, one composing renderer adds 172,800 full-row decodes and 1,440 joins/s in the occupied case, with 300 or 3,000 resident terminals. Main wait work is conditional on the existing evidence gates and can take a separate blocked-screen read. A fresh daemon projection also makes both row passes, with 5,760 uncached full-row decodes and 48 joins on the occupied sample. Daemon cache hits at the main caller avoid that request entirely. These are source-derived counts and assumed admission rates, with no measured interaction latency. The repeated work competes with main RPC and renderer composition work. Sweep admission · Sweep cadence · Wait runtime wiring · Daemon snapshot branches · Cached frame checks and late adoption · IME composition gate

A deterministic guard should warm the same real buffer at base and head, then count translated cells, arrays/joins and clipping probes on repeated reads of an unchanged 120×24 grid and after 121→120 and 240→120 shrinks. Drive the live main projection and active IME context at N/10N, include occupied and blank overhangs, then mutate one visible row and verify changed output with reuse for the other rows. Preserve the applied width, wide-edge behavior, wrapped provenance and cursor styling. Reusing the clipped row result would require invalidation on the actual row mutation and applied width. Applied-column reader · Cursor context · Projection · Geometry and correctness controls

Original pass-4 failing input

  • Warm 121→120×24, 120 visible ASCII cells per row, one empty off-grid cell, unwrapped. I traced both installed buffer implementations and both production readers. The clipping check sees a one-cell blank overhang and calls the canonical trimmed translation. Warm full-row cache hits return to base behavior on the original input. Main uses 48 hits and IME uses 24. Relative to pass 4, that removes the original 5,760/2,880 full-row decodes and 48/24 joins per main/IME read. Main now pays 96 edge/overhang cell loads and up to 48 short-lived clipping records over the two passes. IME pays 48 loads and up to 24 records. The context style visit saves 24 cells and the cursor-row suffix saves one when the cursor is within the grid. Cursor prefix and suffix slices still do their bounded, partial translation work. The regular 120×24 control uses the same canonical calls with width checks only. These are source counts. The named tests cover related geometry and IME behavior, and none counts this exact 121→120 workload. No final-head wall-clock timing was collected in this pass. Applied-column reader · Visible rows · Cursor context · Main live-grid projection · IME composition gate · Geometry and correctness controls
  • Retained 1,024→120×24 control. The overhang exceeds 120, so the new blank check visits zero off-grid cells. The edge check, trim walk, forward decode, style check and cursor fragments are bounded by applied columns. The style pass visits at most 2,880 cells, down from up to 24,576 visits on retained-width context before clipping. No projection traverses scrollback. The existing shrink controls exercised off-grid text, edge-split and fully fitting wide glyphs, wrap/trailing-space provenance, a clipped draft and preserved historical-tail text. Applied-column reader · Cursor context · Visible rows · Geometry and correctness controls

Work by production trigger, owner and bound

R is applied screen rows, C is applied columns, W is retained row width, L is the requested tail limit and B is encoded control-reply bytes. A cell can contain multiple code units. Each request addresses one PTY.

Trigger and population Daemon JS thread Electron main and renderer
Daemon startup, app adoption and reconnect, once per started daemon or authenticated socket pair Eager projection, draft classifier, placeholder and clipping modules add about 19 KB of source once per daemon. Control hello adds 34 bytes, with zero additional stream frames, process starts, listeners or disk operations. Same protocol v61 endpoint and 60 legacy candidates. One capability boolean per connection, recorded after both authenticated identities match, reset on failed connect and disconnect. The argument/closure refactor still reads the token once and sends two hellos per pair. Controller module adds 732 source bytes and the common clipping module adds 2,384 on graphs that use it. Source sizes only.
Admitted explicit screen, preview or tail fallback, or screen evidence for a wait, prompt or readiness check Cached main hits do zero daemon work. One addressed session lookup and liveness check per RPC. Legal options carry at most two non-ID fields through normalization. Existing ownership proof, startup ingress fence and slow-snapshot diagnostic still run as applicable. The proof holds up to 262,144 bytes per session and uses the existing 750 ms snapshot-proof wait. The pending-read and valid-frame caches use one keyed lookup per PTY. Generation, sequence and tracked-mode gates precede capture. A visible acquisition checks capability once and a new projected RPC checks it again at the adapter. Normal provider dispatch is indexed, degraded missing-route lookup visits at most 62 known providers with in-memory membership tests. No extra inventory or remote round trip.
Capable projected cache miss, per admitted request One metadata read for geometry, modes, cwd/title, owner and sequence. Up to R visible rows and R live context rows, one composer classification, up to R draft-row replacements and linear row filtering/copying. The full-width path uses canonical row translation. Each oversized row triggers an edge probe, up to W−C off-grid blank probes when W−C ≤ C, and either one canonical translation per requested text representation or applied-width trim and decode passes. Cold canonical translation on that branch reads at most 2C retained cells. Style and cursor-slice passes stay within C. Wrapped rows may request a second representation for trailing spaces. Work is proportional to R×C plus the text bytes. It avoids ANSI serialization, OSC-link collection and frame restoration. Request member adds 25 bytes. Response carries up to R nonblank strings, R wrap/trailing-space records, optional draft bounded by context text, and shared metadata including cwd/title strings. The false/zero metadata array is 37R+1 bytes before its field name for R>0. One decode and JSON parse proportional to B, shallow DTO conversion and sequence/title/mode reconciliation. Accepted projection avoids creating, feeding or disposing a temporary ANSI emulator. Existing consumer copies, line limits and preview/wait joins are proportional to rows/text returned.
ANSI replay, catch-up, durable seed, older daemon and renderer fallback, per admitted capture The ANSI serializer, rehydrate and frame state, OSC-link ranges and scrollback work remain on this branch. The router caps requested rows at 50,000. Metadata extraction adds a small temporary object and spread per ANSI snapshot. The relocated termination method still calls the same owned-tree handle once when asked. A daemon without capability uses zero-row ANSI for visible requests from the first capture. Where ANSI is returned, a visible read allocates one grid at reported dimensions with zero scrollback, feeds the ANSI, projects and disposes. A late ANSI cache adopter and explicit screen fallback can each parse the shared ANSI response, as on base. Replay/history calls keep their original renderer/ANSI options and durable overlay admission. Projection skips the durable overlay entirely.
Overlapping reads, per PTY and generation Same-format waiters share one request/reply. Visible-first plus a simultaneous replay can require two replies for two formats, while a pending sufficient ANSI capture can serve both. Larger ANSI requests can supersede a smaller one as on base. Two indexed current slots per PTY, one per shape, plus existing per-caller promises/deadlines. Each live capture owns a temporary mode tracker. One extra concurrent format adds at most one tracker invocation per chunk for the overlap, or K/s at K chunks/s on one active PTY and 300K/3,000K if all those PTYs are simultaneously in overlap. The tracker first gates on control bytes, may scan the chunk and carries at most 4,096 code units. These trackers cover their own capture windows and remove themselves on settlement. Two slots bound indexed work, while superseded ANSI calls can still finish later.
Main live-grid reads and rendered tails, per admitted read Zero RPCs when the existing live model serves the read. Main uses the same width checks, row clipping and context as the daemon. Raw rule-screen reads use their existing plain-line path. Live rendered tails use up to min(buffer rows, L+R) historical rows, then up to R visible rows and one context. Parsed provider tails visit up to L historical rows. L defaults to 120 and the public limit is 2,000. Stored-width historical text is preserved. The readiness helper only rebuilds draft rows when invoked by a rule, with one reverse search, one draft split and copies linear in the returned rows/text.
Renderer composition and native draft reads, per selected terminal Zero RPCs or daemon reads. Composition start and each delivered render during composition read one screen context. An out-of-order end can read it while a newer composition is active. Matching end, blur and disposal stop context reads. The draft reader checks a weakly held revision and cursor-row key before context, retains one existing whole-row read for that key, and runs full context on misses during pickup/option/send or paste verification. Paste sampling is every 100 ms for up to five seconds per admitted send. No ordinary keystroke path or per-mounted-pane data request was added.

Control hello · Client handshake · Daemon adoption · Versioned endpoint names · Protocol version and fallback generations · Controller lookup · Host registry · Daemon adapter route · Degraded provider route · Degraded lookup · Snapshot request · Shell-ownership and session admission · Ingress barrier · Proof queue and deadline

Daemon snapshot branches · Projection · ANSI metadata and serializer · Wire selection and conversion · Acquisition slots · Capture and tracker lifetime · Per-output-chunk gate · Mode tracker limits · Replay request · Explicit screen fallback · Temporary replay grid · Rendered tail and compatibility branch · Raw rule grid and whole-model gate · Readiness probe · Draft revision cache · Paste verification · Process termination move

Main callers of the shared grid code include explicit reads, late mode-transition reconciliation, live waiter screen/blocker checks, titleless agent evidence, permission/delivery and launch-composer checks. A waiter evaluation memoizes one lazy evidence read and can also run a gated blocked-screen pass. The prompt proof can read one screen and a separate typed context after its existing admission checks. Prompt resubmission and the delivery draft hold each address one terminal. Optional worktree listings can request agent-wait status for each eligible row on the requested page. Production cadence is demand plus the pre-existing waiter sweep/recheck, prompt settle/output and composition callbacks. Type moves, bridge forwarding and test fixtures introduce zero recurring work themselves. Main live-grid projection · Lazy evidence · Titleless agent evidence · Permission and delivery evidence · Launch composer evidence · Delivery draft hold · Prompt proof · Prompt resubmission · Optional agent-wait listing · Wait runtime wiring

Six scan questions and matched classes

  1. Unused work before admission. Valid cached frames make zero snapshot RPCs at 300 or 3,000 PTYs. Distinct eligible misses require one response per screen, and viewport, sequence and mode gates remain. Unchanged input and hot-path rescans match the P1 above. ANSI-first sharing and legacy fallback keep their original request counts on the tested inputs. There is no new per-output serialization or unchanged-frame publication. Cached frame checks and late adoption · Acquisition slots · Acquisition contracts
  2. Ownership and fan-out. One addressed PTY per request, one slot per format and one stored visible frame per live PTY. A 300/3,000 distinct-PTY cold burst needs up to 300/3,000 projected responses, plus ANSI only where independently requested. Reconnect resets the capability on the same authenticated pair. No new feed, subscriber, mounted owner or broadcast. The existing renderer IME listener group is three element listeners and one render hook per installed mask, with one active ID. Draft revisions add zero new listeners in this span. Client handshake · Acquisition slots · IME composition gate · Draft revision cache
  3. Thread, storage and startup. Daemon runs projection, stringify, UTF-8 byte counting and socket enqueue on its JS thread. Main does decode/parse and only pays temporary emulator replay for ANSI branches. Projected reads add zero filesystem operations, SQLite transactions or subprocesses. The eager-import class matches the fixed source additions priced above. No startup I/O or probe was added and startup timing was unmeasured. Reply encoding and socket write · Main control decoder · Record cap · Daemon snapshot branches · Temporary replay grid · Wire selection and conversion
  4. Growth and progress. Per-read work is driven by independent dimensions of grid, glyph bytes, and admitted PTYs. Worktrees, repos, remotes, refs, chats and transcript bytes contribute zero visits to each projection. Mobile fit is capped at 1,024×500. Daemon desktop validation requires finite positive dimensions and supplies no universal upper geometry bound. The existing 16 MiB record cap runs after stringify. Socket backpressure can still retain encoded replies under a stalled peer. The patch adds no server queue or send cadence, and the legal reply size depends on grid content. Oversize encode fails through the existing RPC error and caller retry paths. Row-string caching is bounded by live buffer lifetime. Daemon normal rows can retain one warmed canonical string per read row until replacement or eviction, and its default live scrollback is 1,000 rows with an override up to 5,000. Heap and large-grid encode high water were unmeasured. Mobile fit cap · Desktop size validation · Record cap · Reply encoding and socket write · Daemon scrollback window · Cached frame checks and late adoption
  5. Host effects. Reviewed current and pre-upgrade v61 adoption, legacy generation selection, degraded/direct local routing, SSH/foreign refusal and mobile replay. The authenticated control hello negotiates format with no extra connection, launch or probe. The Linux and Windows/WSL paths keep the existing endpoint selection and transport, and the projection reads applied geometry. Current/legacy/reset behavior was exercised with macOS local socket tests and mocked PTYs. Packaged adoption, native-host timing and paired-device runs were outside the executed scope. Protocol version and fallback generations · Versioned endpoint names · Daemon adoption · Host registry · Daemon adapter route · Replay request · Handshake controls · Socket controls
  6. Obsolete work and idle. Existing visible wait is 750 ms, authoritative default 8 s, retry for a failed adopted frame 1 s and control deadline 30 s. Old-generation responses cannot populate the visible cache. Slot references release on settlement or generation/exit/floating retirement. A timed-out caller can leave server work running until settlement, with existing late adoption and same-format sharing. Diff adds 0 steady-idle wakeups/s on daemon, main and renderer, with zero projection frames/s without request demand. Existing wait/IME callbacks and listener teardown are unchanged. No new steady-idle work, lifetime leak, or multiplied background polling was found. Caller budgets · Control request deadline · Exit teardown · Generation teardown · Floating PTY teardown · Cached frame checks and late adoption · IME composition gate

Verification. 85 tests passed through the named macOS unit-test gate. Ten files contributed 79 tests and the runtime aggregate contributed six targeted cases. The acquisition contracts made 2/20 requests for 2/20 delayed screens released at 751 ms and for 2/20 cold legacy screen-plus-replay pairs. The test suite also checked ANSI-first sharing, distinct formats when projection starts first, sequence/generation/handle rejection, snapshot ownership, resize semantics, wait and renderer composition behavior. Pass-5 fleet, byte-format and row counts above come from source, with no packaged-app CPU, heap, native IME or final-head timing measurement. Acquisition contracts · Staleness and replay controls · Socket controls · Geometry and correctness controls

Reviewed f2be6077d0559f7d516932795213d01d6497ed7f..4a60caf513f938ff3b5bb54576b5d1978b899220. GitHub reported the same final head.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan pass 6 — findings

P1 — A screen read followed by a concurrent zero-scrollback replay adds a daemon snapshot and a second main-process scan of live output. The base reused the outstanding zero-row ANSI capture for both consumers. The new format split starts a projected RPC for the first read and a zero-row ANSI RPC for the second. This order is reachable when an explicit screen read or a restored-terminal readiness probe overlaps a client snapshot request with zero or omitted scrollback for the same PTY. The capable-provider test holds the screen response open and checks that both formats are delivered. The count follows directly from the two slots and the old single-slot admission predicate. ANSI-first and legacy zero-row pairs still share one RPC. Format selection and sharing · Zero-row client snapshot · Production snapshot request handler · Screen-first control

Each overlap adds one daemon ownership/write fence, ingress barrier, visible-grid projection, JSON encode and reply. Main gains one reply decode and one temporary capture-mode tracker, and saves the screen consumer's ANSI replay and projection. Both captures register trackers in the same PTY's set, and main sends every arriving chunk to each tracker. For the overlapping phase of a zero-row pair, main goes from one to two in-flight scans per chunk, in addition to the unchanged settled tracker when present. The extra scan checks the entire chunk for escape bytes and can run the mode parser over escape-bearing output. The duplicated coverage lasts until either capture settles. On a delayed daemon this window can outlive the screen caller's 750 ms wait, up to the existing control deadline for connected captures. This raises work on the shared daemon during concurrent screen and replay requests and on main's output-delivery path while the affected PTYs paint. Tracker registration and cleanup · Per-chunk scans · Control deadline

A sensitivity check at 100/1,000 eligible PTYs with one overlapping pair per PTY every two seconds adds 50/500 RPCs and projected replies per second. At the slowest median below, the projection alone costs 6.3/63.2 ms/s on the daemon, before the extra fence and JSON work. With 100/1,000 pairs concurrently in flight and 10 output chunks/s per PTY, the extra main cost is 1,000/10,000 scan calls/s. At 4 KiB per chunk that is 3.9/39 MiB/s of input to the extra scanner. These conditional loads use the stated rates. Production overlap frequency and main-thread latency were unmeasured. The existing two-second wait sweep reads the main emulator. The provider overlaps require separate admitted screen and replay demand. A regression check should hold the screen-first, zero-row pair at 100 and 1,000 independent PTYs, deliver chunks while both requests are pending, and count daemon captures and main mode scans. Preserve ANSI replay, fresh screen rows, split escape handling and generation rejection. Sharing the underlying mode scan across captures would remove the per-chunk amplification even when the two formats need separate responses. Existing local-grid wait sweep · Mode scan fast path · Legacy and ANSI-first controls

Pass-5 finding and daemon cost

The pass-5 main and renderer cell-work regression is resolved. I compared the fallback reader bodies to the base byte for byte. Main's local screen and historical-tail projections enter the original row loop after one branch per reader call. Main's live cursor context and the renderer's IME and draft readers enter the original cursor loop after one branch. Those paths add zero clipped column visits, sliced translations or row-string cache misses per read. The renderer callers are unchanged. Direct ruled-screen and paste-check readers have the same path as the base. The daemon is the sole production caller that enables clipping. Main row reader · Shared cursor reader · Main screen caller · Renderer composition caller · Renderer draft caller · Daemon opt-in

The completed Linux source probe measured microseconds per read, using the median of seven 2,000-read batches on warm alternate-screen fixtures. The base and final probe commits differ from their reviewed parents only by the probe. The live-reader arms run on a persistent grid. The daemon arm calls the clipped projection directly. These timings exclude ownership settling, socket/JSON, ANSI serialization, and main replay. The final 121→120 blank live arm ranged 45.7–89.8 µs within the run. The byte-for-byte comparison establishes the unchanged loop work. The timing arms do not isolate a change in live-reader latency.

120×24 grid Base live read Previous clipped live read Final live read Final daemon projection
Unshrunk 43.7 37.1 34.4 42.9
121→120, blank overhang 44.8 43.1 82.6 52.5
121→120, occupied overhang 44.3 96.5 49.4 126.3
240→120, blank overhang 78.0 92.3 88.1 115.7
240→120, occupied overhang 78.4 98.2 65.8 101.6

Comparison with the actual ANSI route. Let R be applied height, C applied width, and B the string bytes including combining glyphs. A zero-row ANSI read serializes the last R normal rows and, when active, R alternate rows, at up to C cells each. At 120×24 that is 2,880 normal-screen or 5,760 alternate-screen serializer cell visits before wrap/cursor work and any enabled link-range scan. The daemon also constructs ANSI mode/frame state and encodes the reply. Main decodes it, creates and initializes a temporary grid, feeds the ANSI bytes to its parser, projects its rows and cursor context, and disposes it. The new route skips those ANSI operations and the temporary grid. It walks at most R viewport rows and R live cursor-context rows on the daemon, with one C-wide glyph/style scan per context row and an extra cursor suffix scan of at most C cells. It emits up to R nonblank lines and R metadata entries plus draft text, then main decodes and adopts those arrays. ANSI path and metadata · ANSI cursor work · ANSI link gate and scan · Temporary grid and parse · Projected rows and draft

For each overwidth row in either daemon pass, classification examines one edge cell plus at most C retained cells. Widths above 2C skip the retained-suffix scan. For 24 retained rows at 121→120, classification costs at most 96 public cell loads across the two passes. At 240→120 with a blank retained suffix it costs up to 5,808 loads, before the up-to-2,880 style loads. The blank case can reuse the full-row translation. Occupied or split-wide edges can require bounded reverse trim scans and explicit range translations instead, including another translation for wrapped-row spacing. Each visible row has at most two translations, each cursor-context row one, and the cursor has two additional ranges. This is geometry and glyph-byte work independent of history length or retained pre-shrink width beyond 2C. It can exceed the old daemon's raw serializer visit count, so the projection timings alone leave the daemon CPU delta unmeasured. The removed main grid and parse are source-proven. A paired timing for the complete ANSI and projected RPCs was unavailable. Viewport loop · Cursor context scan · Width and trimming bounds

Work inventory and six scan questions

  1. Admission and unused work. Explicit reads, previews, restored-dialog checks, permission and prompt evidence, and the one-shot readiness probe address one PTY. A valid cached frame returns before capture. Generation, output sequence, mode, known-normal fallback, and live model/write-chain gates remain. An explicit screen read can also join the pending provider capture after the short wait. A capable cold screen-only read sends one zero-scrollback projection, including the existing settle, write flush and ingress barrier, one metadata read, row/draft construction, and one response. Main performs one keyed capability lookup before selection, one extra check before setting the option on a new capable wire request, and constant-size shape, title/mode, sequence and generation handling apart from the response decode and existing consumer work. There is no idle frame, new output-triggered snapshot publisher or new renderer subscription. The acquisition contracts passed at 2 and 20 independent PTYs for delayed screen-only demand and legacy overlaps. Cache, admission and late adoption · Screen and fallback caller · Readiness probe · Provider dispatch, conversion and history gate · Request-count controls
  2. Ownership and fan-out. There is one session lookup per RPC, one current acquisition slot per PTY/format, and one cached visible frame per PTY. An adequate pending ANSI request can serve a visible read, and an older daemon or unsupported provider uses the existing ANSI slot. The second slot and the inherited per-capture scanner are the P1 above. Larger ANSI requests could already supersede a smaller pending ANSI request and leave it running. Slot count is a reference bound, not a cap on all outstanding work. One cold read per PTY at 300/3,000 PTYs gives 300/3,000 required replies. Screen-first zero-row pairs give 600/6,000 instead of 300/3,000. One hot PTY's capture never visits other PTYs, mounted panes or waiters. Acquisition lifetimes · Host snapshot lookup · Main cache and retry resources
  3. Thread, storage and startup. The daemon pays snapshot fences, projection/ANSI, reply stringify, UTF-8 sizing and socket enqueue. Main pays decode, JSON parse, capture reconciliation and consumer handling. Projected reads add zero disk, SQLite, subprocess or network-host lookups. Regular ANSI requests, replays, history overlays and checkpointing keep their existing work plus constant format dispatch and an extra small metadata object. The bridge moves one wrapper and adds a synchronous capability query. Startup adds two small pure clipping modules (~8.4 KiB total source), a 732-byte source adapter and the daemon's static draft/projection functions. These add module loading and fixed constants with no new startup I/O, timers or native initialization. The process-termination method move preserves one existing call on the same receiver and adds no teardown work. Reply encoding · Reply decoding · Bridge · Termination move
  4. Growth and progress. Projection work grows with R, C and glyph bytes. Repo, worktree, ref, remote and transcript population contributes zero visits per read. It does zero scrollback rows and no durable history overlay. The existing desktop geometry check accepts positive finite dimensions and has no universal upper cap. Mobile fit caps geometry at 1,024×500. Row-string caches remain owned by the buffer and the main visible cache holds one frame per PTY. The daemon live history window defaults to 1,000 rows and can be raised to 5,000. JSON still has a 16 MiB record limit after stringify. A backpressured control socket can retain replies, and the diff adds no send cadence or server queue. Frame bytes vary with text and metadata, so a uniformly smaller wire shape or a measured heap high-water mark is unverified. Desktop geometry · Mobile fit cap · Live history window · JSON record bound
  5. Host routing. The authenticated control hello carries one field. The client gains one per-connection bit and a small options object and closure per existing connection attempt. It clears the bit on failure or disconnect. There are zero additional hello messages, connections, launches, sockets or host probes. Protocol and endpoint naming are unchanged. Old daemons fall back to one zero-row ANSI request and the original main parse. Direct local fallback, nonlocal rejection, Windows daemon routing and mobile replay keep their existing routing. The local socket tests cover capable/legacy hello and reset behavior, and the resize tests cover a split wide glyph, wrap metadata, a clipped draft and retained historical tail. Native-host and paired-device timing and packaged startup were unmeasured. Control hello field · Connection and reset · Provider registry · Geometry controls
  6. Obsolete work and idle. The existing 750 ms visible wait, 1 s failed-frame backoff, 8 s authoritative wait and 30 s control deadline remain. One late adopted frame may complete after the caller leaves, and generation/sequence/handle checks reject stale results. Settlement and generation/exit/floating retirement drop slot, cache or tracker references. Caller timeouts don't cancel server work. The added concurrent capture extends this existing cost only for the overlap described above. Idle without read demand adds 0 wakeups/s on the daemon, main and renderer. Existing local wait sweeps and IME callback ownership remain. Caller budgets · Late frame guards · Generation teardown · Exit teardown · Floating teardown

Matched classes. Hot-path rescans and concurrent fan-out have the P1 above. Unchanged-input reads are skipped by the normal provider-visible cache. Further explicitly requested snapshots and legacy fallbacks remain demand-driven. The clipping re-scan is confined to the replacement daemon path and bounded as priced above. Per-entity state retires at the existing boundaries, subject to the outstanding RPC lifetime. Whole-snapshot publication covers one requested screen with zero new streaming or broadcast publications. Eager imports add the fixed startup work described above. No added timer, polling loop, hidden-pane capture, per-row mount work or bypassed visibility/admission gate was found.

Verification. 91 named macOS unit tests passed, including 72 across nine files and 19 selected runtime, cursor and IME cases across three files. The remaining 198 cases in the selected aggregate were filtered out. The capable/legacy sharing and stale-frame controls ran. The overlap RPC and scanner counts are source-derived. The Linux timings are from the separate warm-grid probe, and its result excludes end-to-end daemon contention and main-process latency. No build or app launch was used. GitHub and the reviewed worktree both identified d11603de43aa34a8a6b86df70e54215c2f0e30d0. Reviewed base f2be6077d0559f7d516932795213d01d6497ed7f.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan pass 7 · CLEAN

No P0 or P1 findings in f2be6077d0559f7d516932795213d01d6497ed7f..fe3d44fe3d4e2a58a4bed12f967dcae965d9d5bd. The pass-6 finding is resolved. A live chunk reaches one shared in-flight mode scanner for its PTY, whether one format or both formats are pending. The pre-existing settled tracker can still scan the same chunk once. With two pending formats and a settled tracker, that is at most two total scanner calls per chunk, down from three in pass 6 and equal to the ordinary single-capture base path. Without a pending capture there are zero in-flight scanner calls. No scan iterates the capture population or other PTYs. Output ingestion · Capture ownership

The count test drives two chunks at 100 and 1,000 PTYs with both requests held open and no settled tracker. It observed 200 and 2,000 calls, respectively. Pass 6 would have made 400 and 4,000 calls. The corresponding counts at 300 and 3,000 PTYs are 600 and 6,000. The split-escape test confirms that a capture started after the escape began does not inherit that switch, while the earlier capture uses the post-switch live grid. The offset and last switch each occupy one scalar. The existing escape carry and mode stacks remain capped at 4,096 code units and 16 frames per screen. Each tracker still gates regex parsing on an escape introducer or an incomplete carry. The offset bookkeeping also runs in existing daemon-ingress and renderer trackers, adding constant work per gated chunk and recognized switch without another byte pass. Count contract · Split-switch test · Scanner

Work and bounds

  1. Admission and unused work. A CLI or runtime screen read, terminal preview, restored-dialog check, permission or prompt probe, or one-shot readiness read addresses one PTY. The cached-frame, compatible pending read, known-normal and local-model gates run before requesting a new provider frame. The existing readiness poll still reads the local model rather than hitting the daemon. The explicit screen fallback can join the same pending acquisition after the short wait. A capable cold screen-only request asks for zero history rows and makes a keyed provider capability lookup. A new request makes one further check at wire dispatch. Main reuses the decoded row arrays and does its existing title, mode, sequence, generation, handle and output-limit handling. Per-caller output shaping still slices the requested tail and metadata. History and cursor reads keep their existing paths. Admission and cache · Screen fallback · Short-wait path · Readiness poll · Result limits
  2. Ownership and fan-out. Main holds one current acquisition slot per PTY and wire format. An adequate pending ANSI replay can serve a screen read, even when that replay also fetches history. Legacy daemons share the single ANSI slot. On a capable daemon, a pending projection cannot serve a later ANSI replay. A screen-first pair therefore sends two requests and produces one row projection and one ANSI replay, with two sets of existing snapshot fences and reply encodes and one existing control deadline per RPC. At 300 or 3,000 simultaneously demanded PTYs, screen-only demand costs 300 or 3,000 replies. Screen-first pairs cost 600 or 6,000 replies. The extra projection serves one separately requested output and the in-flight main scan count is unchanged from one capture. Explicit replay, stream recovery, and one-shot screen demand are event-driven. The existing replay byte fallback tries up to seven distinct row counts per attempt and stops at the first acceptable reply or at zero rows. A zero-row request takes one attempt unless the existing stream overflow handler requests a fresh snapshot. There is no new broadcast, frame publisher, subscription, listener or per-pane capture. The pre-existing ANSI path can supersede a smaller pending request with a larger one and leave the smaller RPC running. The two current slots are a reference bound, not a total outstanding-RPC cap. Acquisition selection · Requested replay · Recovery replay
  3. Thread and storage cost. Daemon JavaScript does one session lookup, awaits the existing ownership proof and write flush, and takes one ingress barrier per RPC. A projected reply reads applied geometry, modes, title, owner and sequence, then builds rows and draft from the live grid. It omits ANSI serialization, cursor/frame restore escapes, scrollback and link extraction. The daemon still stringifies, sizes and writes one reply. Electron main still decodes and parses JSON, with zero temporary emulator grids or ANSI parses on projected replies. Legacy or ANSI-first screen reads still parse the ANSI frame and dispose the temporary grid. The shape dispatch and metadata extraction add constant work per ANSI snapshot, and history overlay admission is unchanged. Projected reads add zero disk, SQLite, subprocess or host-probe work. The moved process-termination method still delegates once to the same subprocess at teardown. Startup adds fixed module loading for the projection, clipping and provider bridge. The two clipping modules total about 8.4 KiB of source and the bridge about 0.7 KiB. There are zero added startup RPCs, filesystem probes, or awaits. Daemon dispatch · Session fences · Projected reply · ANSI metadata and serialization · Wire encode · Wire decode · Main parse fallback · Termination
  4. Geometry, bytes and growth. With applied height R and width C, the daemon reads at most R viewport rows and R cursor-context rows. Each viewport row has at most two translations, each context row one translation and one C-wide glyph/style pass, with two extra translations and one up-to-C suffix pass for the cursor. Draft classification and row filtering take a bounded number of passes over that text and produce at most R line/metadata pairs plus draft text. Each retained overwidth row checks one edge cell and at most C overhang cells. Width above 2C skips the overhang scan. Blank overhang within 2C may reuse full-row translation. An occupied or split-wide edge takes bounded reverse trim and range translation. For 24 overwidth rows in both passes, 121→120 costs at most 96 classification cell loads and 240→120 at most 5,808 before up to 2,880 style loads. Only daemon projection opts into clipping. Existing main screen/tail reads and renderer draft/IME reads take one optional dispatch check and keep their existing row loops. An old zero-row reply can serialize up to R normal rows and R alternate rows at C cells each, before cursor and applicable link work. The projected cost depends on applied geometry and glyph bytes, with zero visits to scrollback, worktree, repo, ref, remote or transcript inventories. Mobile fit caps geometry at 1,024×500. The existing desktop path accepts positive finite geometry without a universal maximum. The existing 16 MiB line limit applies after reply construction. The router retains its existing slow-read diagnostic threshold of 25 ms. Viewport projection · Cursor context · Clipping · Projection output · Geometry · Mobile cap · Wire limit
  5. Host routing and fallback. One optional control-hello field per authenticated connection and one client capability bit. The client adds a small options object and closure per existing connection attempt. There is no added token read, handshake, socket, reconnect, process launch or host round trip. The bit resets on failed connection or disconnect. Provider dispatch is keyed by the same PTY. Older daemons and providers without the capability use ANSI when available. Paired runtimes resolve their own hosts, and local fallback, native Windows routing and mobile ANSI restore retain their existing paths. Hello · Client lifecycle · Provider registry · Provider dispatch and history gate
  6. Obsolete work and idle. Added idle wakeups are 0/s on daemon, main and renderer. Existing waits are 750 ms for the short visible path and 8 s for the authoritative path, with a 1 s failure backoff and a 30 s control-request deadline. A visible capture may finish after the caller stops waiting and populate the cache. Sequence, generation and handle checks protect adoption. Settlement removes its matching slot and releases the shared scanner after the last capture. Each overlapping capture carries one scalar checkpoint and an existing promise lifetime. Generation, exit and floating retirement remove the tracker and its map references immediately. Late completion cannot delete a successor's tracker. Main retains one cached visible frame per PTY. Caller timeouts still do not cancel daemon work. Socket backpressure can still retain encoded replies and callers can still leave outstanding waits on a shared capture. The distinct-format overlap in item 2 adds one reply per overlapping pair and no new queue or retry cadence. Wait budgets · Late adoption · Scanner release · Generation cleanup · Exit cleanup · Floating cleanup

Regression classes. Hot-path rescans are bounded by the shared tracker and the geometry work above. Unchanged-input reads use the existing cache and in-flight sharing. Fan-out is one reply per demanded format, with the existing stronger-ANSI supersession noted above. Per-entity state ends on settlement or retirement. Whole-snapshot traffic is one response to a requested screen, with zero new streaming or broadcast frames. Eager imports are fixed-size startup work. No added polling loop, hidden or unobserved capture, per-row mount work, persistence write, or bypass of live-model and freshness gates was found.

Evidence and limits. 102 named macOS unit cases passed, including the two overlap counts, capable and legacy sharing, slow responses, both formats, clipped wide glyph and draft, retained history, connection reset, split mode switches, and stale sequence, generation and handle rejection. The selected runtime aggregate skipped 177 unrelated cases. GitHub and the worktree both identified fe3d44fe3d4e2a58a4bed12f967dcae965d9d5bd. Supplied Linux timings at d11603de43a put daemon projection at 43–126 µs/read, the old main parse at 270–750 µs/read, and main reads back at base cost. At 300 independent demanded reads that is 12.9–37.8 ms of projection work and 81–225 ms of removed parse work, as separate cumulative costs. At 3,000 reads the corresponding totals are 129–378 ms and 810–2,250 ms. A single-PTY event reaches one PTY at either fleet size. Final-head socket latency, large-geometry heap high-water, packaged startup and native or paired-device timings were not measured in this pass. The work counts and idle disposition come from source and unit evidence.

@brennanb2025
brennanb2025 marked this pull request as ready for review November 22, 2026 01:02
@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The daemon now supports opt-in visible-projection snapshots and advertises that capability to control clients. Grid-reading code can clip visible rows and cursor context to terminal dimensions. Runtime provider capture can request and adopt a projection, while maintaining separate visible and ANSI acquisitions and sharing mode scans across overlapping captures. The changes also add performance tests for snapshot acquisition and move the owned-tree termination method from Session to SessionProcessInspection.

Merge Risk: Minimal · up to eaeb4

Background terminal screen reads now use daemon-side projections, with ANSI parsing kept as the fallback. No concrete merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: background terminal screen reads now come from the daemon's emulator model rather than being re-parsed on the Electron main process. The changeset adds the daemon visi…
Description check Passed The description follows the repository template closely. It includes ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, Performance, Risk, and Checklist sections, with concrete detail on 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: background terminal screen reads now come from the daemon's emulator model rather than being re-parsed on the Electron main process. The changeset adds the daemon visible-projection path, the capability negotiation, and the main-side adoption of returned rows, which matches the title. The title is a single line of 107 characters, which is long but within a reasonable range for a conventional-commit style title.

Full details: Description check

Explanation

The description follows the repository template closely. It includes ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, Performance, Risk, and Checklist sections, with concrete detail on the mechanism, fallback behavior, and test coverage. The Performance section gives a measured before and after. Gaps: the Linked Issue section says N/A for a maintainer change rather than linking an issue, the Risk section does not give an explicit backout note beyond a plain revert, the AI Disclosure section is empty, the Review section is empty, and the Testing checklist leaves the lint/typecheck/test/build item unchecked. Several sections are mostly complete, so the check passes.

  • 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

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cdb935dc-f964-4d7a-b893-09d528bedd27
Commits

Reviewing files that changed from the base of the PR and between fe3d44f and eaeb4dc.

Files selected for processing: 2

  • src/main/daemon/sessions/session-process-inspection.ts
  • src/main/daemon/transport/client/daemon-client.ts

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status: ready for review at fe3d44f

Problem. When Orca's own copy of a terminal screen isn't authoritative (right after a restart reattaches terminals the terminal daemon kept running, or after a terminal's execution context changes), reading the screen of a terminal that isn't on screen asked the daemon for the whole screen as ANSI and re-drew it on Electron's main process in a throwaway emulator just to read the text. This is the first step of moving terminal output parsing off the main process.

User-facing change. None visible: the same screen text, read with far less main-process work. Daemons that announce support in their handshake send finished rows; a daemon started by an older Orca keeps today's path.

What changed during review.

  • A slow screen read and its fallback, or a screen read and an overlapping replay, now share one daemon request (the only remaining overlap is a screen read and a replay that genuinely need different formats in the same few milliseconds; main scans each output chunk once per terminal regardless).
  • Support is negotiated through an optional field in the daemon handshake, so there is no protocol version change and no second daemon on update.
  • After a terminal narrows, the daemon's rows and composer draft stop at the new right edge, matching the ANSI round trip it replaces. Every other screen reader (main's live model, waits, prompt checks, the renderer's composer and IME reads) runs exactly the code it runs on main today.

Verified.

  • Reviews: three review passes, then two design councils (handshake capability; clipping only in the daemon's projection), each followed by a fresh check. Final head: Claude review READY, blinded regression audit SAFE, perf scan CLEAN (comment 7071400363).
  • pnpm check:changed passed on the final commit; CI green (66 pass).
  • Benchmark: head=fe3d44fe3d4e2a58a4bed12f967dcae965d9d5bd gate=PASS (Omarchy, interleaved). Main-process time per background screen read 0.32–0.90 ms → 0.011–0.021 ms with identical lines; daemon side 0.18–0.81 ms → 0.08–0.37 ms. Output-storm probe (150 terminals through the real output path, no subscribers mounted) base/head/head/base: main output handling 662/646/695/1,183 ms, no regression. After a shrink the daemon's projection costs 43–126 µs per read; main and renderer reads are unchanged from main.
  • Fleet A/B on macOS at 1,901 workspaces with 40 active terminals (base f2be607 vs head, 8 interleaved launches): restart window main-process screen-snapshot parsing 4.3 ms → 0 (0 in every head launch), main event-loop p99 18.7 → 17.4 ms; storm window main JS busy 8.2 → 7.4 s, main CPU 11.2 → 10.6 s, event-loop max 263 → 124 ms, daemon CPU 26.4 → 24.3 s. Keystroke-to-echo p95 was inconclusive under heavy host load (restart 14.5 → 27.5 ms, launches 10–75 vs 10–58; storm 217.5 → 385.5 ms, launches 144–297 vs 116–619); main-thread measures in the same windows did not rise. Screen-read parity 10/10 and the shrink check passed.
  • Windows (ConPTY) QA on the final head: reattach to a daemon started by the previous build (reads before reveal equal the revealed screens), restart on the new daemon, shrink from 69 to 33 columns (rows no wider than 33, draft exact), and about 20 terminals under load with 119/119 correct screen reads (event-loop p99 11 ms). WSL not run: it needs the separate WSL QA slot; the change has no WSL-specific path.

Deferred / follow-ups.

  • Main's own live screen and the renderer's composer/IME reads can still include leftover text past the right edge after a terminal narrows (pre-existing on main; unchanged here).
  • Seen in QA, not from this PR: after switching between two Orca builds across a restart, the sidebar's agent row stays empty until the terminals are revealed (both directions).

@brennanb2025

Copy link
Copy Markdown
Contributor Author

QA screenshots (final head fe3d44f)

macOS fleet run, after a graceful restart that kept the terminals running: a Codex terminal that was hidden through the restart, revealed. Its screen read before reveal (daemon finished rows) matched this screen (10/10 terminals matched).

macOS: Codex terminal revealed after restart

macOS: vim terminal revealed after restart

Windows (ConPTY): Claude terminal with an unsent hello draft, narrowed from 69 to 33 columns, hidden, restarted, then revealed. The read before reveal reported the draft as exactly hello draft and no row wider than 33 columns, matching this screen.

Windows: narrowed Claude terminal revealed after restart

…-parse-off-main

# Conflicts:
#	src/main/daemon/emulation/testing/headless-emulator-shrink-snapshot.test.ts
#	src/main/daemon/server/testing/daemon-server.test.ts
#	src/main/daemon/terminal-host/testing/terminal-host-spawn-input-retention.test.ts
#	src/main/daemon/transport/client/daemon-client.ts
#	src/main/daemon/transport/client/testing/client.test.ts
#	src/main/runtime/terminal/query/terminal-creation-and-readiness-part-10.spec.ts
#	src/main/runtime/terminal/wait/agent-transcript-replay-test-harness.ts
@brennanb2025
brennanb2025 merged commit 44f9868 into main Nov 22, 2026
50 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant