* Skip legacy hidden skip grammar assertions
* Fix hidden TUI snapshot test setup
* Fix sleep wake history test contract
* Fix hidden delivery startup gate helper
* Fix hidden Latin skip branch predicate
* Fix hidden synchronized split-boundary replay
* Stabilize remote runtime mixed subscription test
* Keep hidden startup query parser active during window
* Stabilize raw emoji golden restore width
* Stabilize raw emoji golden fixture completion
* Keep terminals responsive under agent output load
* Add frozen-terminal repro harness and silent-drop regression tests
Investigation harness for the frozen-terminal reports (Discord
#performance, issue #2836): pane shows content, shell alive, daemon
output.log flat while typing.
- e2e: renderer crash -> auto-reload recovery and three restart/restore
shapes (live daemon, SIGSTOP-wedged daemon, daemon killed between
launches), each probing input at both drop layers. Post-crash phases
drive the renderer from the main process because a crashed target
severs Playwright's CDP session even though the app recovers.
- e2e helpers: layer-discriminating probes (direct pty.write vs
transport input, plus pty:listSessions ownership-rebuild revival).
- unit repro: vendored xterm 6.1.0-beta.287 WriteBuffer permanently
wedges when a sync throw escapes a write-completion callback or a
custom parser handler (xterm-write-buffer-stall.repro.test.ts).
- unit repros for both silent input-drop layers: main drops writes for
a live PTY once ptyOwnership loses the id (revived by listSessions),
and the renderer transport stays unbound after a failed connect.
- pty.test.ts: unregister every leaked SSH provider id in afterEach so
module-level provider state cannot leak across tests.
Co-authored-by: Orca <help@stably.ai>
* Harden xterm write pipeline against sync-throw wedge that freezes panes
A synchronous exception escaping xterm's WriteBuffer loop permanently
wedges that terminal: _innerWrite has no try/catch around the parse
action or the write-completion callback, the tail re-schedule never
runs, and write() only re-arms on an empty buffer. The pane stops
rendering and, if a replay was in flight, the replay guard latches and
pty-connection's onData silently eats every keystroke — matching the
field reports (Discord #performance, issue #2836: content visible,
shell alive, daemon output.log flat). Both vectors verified against
vendored xterm 6.1.0-beta.287 in xterm-write-buffer-stall.repro.test.ts.
Three layers of defense:
- Guard every write-completion callback Orca hands xterm at the two
choke points (writeForegroundTerminalChunk, writeBackgroundTerminalChunk),
with settle and onParsed guarded separately so a WebGL/renderer
failure during viewport settle cannot starve the replay-guard release.
- Guard all throwing-capable custom parser handlers (DA1, OSC 10/11,
CSI ?h/?l mode reports, OSC 52 clipboard, OSC 7 cwd), degrading a
throw to "not handled" — same escape class as
terminal-link-provider-guard.ts.
- Replay-guard watchdog: each engagement releases exactly once, from
xterm's completion or a 10s watchdog, so a lost completion (wedged
pipeline, disposed-terminal race) cannot latch the guard on a live
pane; replayIntoTerminalAsync resolves on either path so restore
chains cannot hang. Force-releases record a crash breadcrumb.
All guard trips record rate-capped crash breadcrumbs, so the next field
occurrence names the throwing stack instead of failing silently.
Co-authored-by: Orca <help@stably.ai>
* Cap unbounded terminal output buffers in main and the foreground queue
Field evidence (Discord #performance / #2836): renderer memory climbs to
~1.5 GB and terminals freeze; a force reload does not help until memory
recovers. Two unbounded buffers matched that shape:
- Main-process pendingData grew by string concatenation without bound
while the renderer could not receive (frozen, starved, mid-reload) —
main-heap bloat a renderer reload cannot clear. Now capped at 2 MB per
PTY: past the cap the buffered bytes are dropped and the entry stays
O(1) until the renderer ACKs again, then a droppedOutput sentinel is
delivered and the pane repaints from the authoritative main-owned
buffer snapshot (existing hidden-output restore path) instead of
continuing a stream with a silent gap.
- The renderer output scheduler capped only hidden-pane backlogs; the
foreground path could queue a visible pane's flood without bound when
the drain could not keep up. The 2 MB cap now applies to every
foreground enqueue branch too, with a foreground-specific skip notice.
Verified: new main-side cap test (starve → flood → sentinel → normal
flow resumes), renderer sentinel-to-snapshot-restore test, two
foreground scheduler cap tests; full pty/terminal-pane/pane-manager
suites (1981 tests) and typecheck pass.
Co-authored-by: Orca <help@stably.ai>
* Make replay-guard stall release probe-certified instead of time-based
The previous stall watchdog blindly released the input guard after 10s.
If a replay were genuinely still parsing on a starved machine, that
early release could leak xterm's auto-replies into the shell — and into
agent TUIs, where a leaked ESC reads as the user pressing Escape.
Replace the blind release with a probe: when a completion looks
overdue, enqueue an empty write behind the replay. xterm parses writes
in order, so every outcome is provably safe:
- probe parses after the replay completion ran: normal release already
happened; probe is a no-op.
- probe parses but the replay completion never ran: all replay bytes
have parsed, no further auto-replies can exist — the completion was
genuinely lost. Release + breadcrumb.
- probe never parses (bounded wait): the pipeline is wedged, and a dead
parser can never emit auto-replies, so releasing cannot leak input.
Release + breadcrumb naming the pane as needing recovery.
While the probe is pending — a slow-but-alive replay — the guard now
HOLDS instead of releasing early; that case is pinned by a regression
test.
Co-authored-by: Orca <help@stably.ai>
* Scale output backlog caps with the scrollback setting and breadcrumb drops
The 2 MB pending-output caps were flat, which risked dropping lines a
50k-row scrollback user would have retained. Both caps (main pendingData
and the renderer output queue) now derive from one shared policy:
max(2 MB, scrollbackRows x 120 chars) — 2 MB at the 5k default, 6 MB at
the 50k max. The main side reads the setting live via getSettings; the
renderer scheduler is configured where the terminal lifecycle already
reads the scrollback setting.
Every drop now records a rate-limited crash breadcrumb with dropped and
cap sizes (terminal_output_backlog_dropped in the renderer,
terminal_pending_output_dropped in main — no pty ids, session ids can
embed workspace paths). Field drop frequency and size decide whether the
cap constants need raising, replacing theory with data (#2836, #7017).
Backlog skip notices are now cap-agnostic since the limit varies.
Co-authored-by: Orca <help@stably.ai>
* Extract breadcrumb recording into a collection-safe leaf module
Playwright loads spec imports at collection time, and e2e specs import
terminal-module constants (e.g. terminal-attention.spec.ts pulls
POST_REPLAY_MODE_RESET from layout-serialization, whose chain reaches
replay-guard). The breadcrumb import added to the terminal modules made
that chain reach crash-diagnostics.ts, whose top-level import.meta.hot
and webview-registry import crash Playwright's transform
("ReferenceError: exports is not defined in ES module scope") — every
e2e shard failed at collection before running a single test.
Move recordRendererCrashBreadcrumb into crash-breadcrumb-recorder.ts
(type-only imports, no import.meta) and point the terminal modules and
their test mocks at it; crash-diagnostics re-exports for existing
callers. Full e2e suite collects again (262 tests / 94 files); unit
suites, typecheck, lint green. No runtime behavior change.
Co-authored-by: Orca <help@stably.ai>
* Add cross-terminal pipeline benchmark (DSR-fenced throughput + latency probe)
Run inside any terminal (Orca pane, iTerm2, Ghostty, Terminal.app, VS Code)
to measure its full byte path. DSR round-trip latency at idle and under a
paced agent-TUI load, plus fenced throughput over four deterministic
fixtures. The DSR fence forces 'all bytes parsed' before the clock stops so
xterm.js-class ingest queues can't flatter the result.
First piece of the terminal performance initiative's measurement rig.
Co-authored-by: Orca <help@stably.ai>
* Add terminal performance initiative plan
Working plan for the orca-performance branch: verified architecture
findings, workstreams (baselines, #7153 validation, term-speed-2 revival
with merge-scout numbers, stall fixes, flow control, rig extensions,
utilityProcess router, telemetry), benchmark protocol, sequencing, and
baseline-relative success criteria.
Co-authored-by: Orca <help@stably.ai>
* Add cross-terminal baseline results (Orca 1.4.91 prod vs Terminal.app vs Ghostty)
Headline: Orca DSR latency under 1MB/s agent-TUI load is p50 134ms / p99 292ms
vs 0.45ms (Terminal.app) and 0.21ms (Ghostty). Idle latency is fine (0.69ms
p50) — the problem is queueing under load, not the pipeline hop. agent-tui
fenced throughput: Orca 2.0 MB/s vs Terminal.app 37 MB/s, Ghostty 78 MB/s.
Co-authored-by: Orca <help@stably.ai>
* Add pipeline-loss decomposition benches (headless xterm + daemon ingest)
Both isolate layers of the 51x agent-tui gap found in baseline-jul02:
bare @xterm/headless parses agent-tui at 103 MB/s and daemon Session
ingest (emulator + pending-output recording + fanout) at 103 MB/s —
on the byte stream the full Orca pipeline delivers at 2.0 MB/s.
Parser and daemon are exonerated; the loss is in main per-chunk
processing, delivery/ACK pacing, or renderer layers above xterm.
Co-authored-by: Orca <help@stably.ai>
* Record baseline + decomposition findings in initiative plan
Co-authored-by: Orca <help@stably.ai>
* Add dev-build orca-performance bench result (confounded: dev mode, 282-col window, 3MB fixtures)
DSR under load p50 161ms — the #7139/#7150 branch does not move the
under-load latency class. Expected in hindsight: DSR replies are ordered
within the output stream, so the metric measures output-queue depth;
cooperative drain paces input responsiveness but cannot reorder the queue.
Shrinking the queue itself (producer flow control, task 6) and raising
agent-tui throughput (task 9) are the levers for this number.
Co-authored-by: Orca <help@stably.ai>
* Record dev-build #7153 check in findings log
Co-authored-by: Orca <help@stably.ai>
* Parse-clock high-priority terminal drains instead of fixed-nap dripping
Attribution (task #9): the drain loop wrote at most 2x16KB then slept
4/16ms regardless of parse speed — an isolation bench (new
pane-terminal-output-scheduler-throughput.bench.test.ts) measures that
drip at 1.9 MB/s background / 27 MB/s foreground against xterm's
~103 MB/s parse rate, matching the baseline-jul02 end-to-end numbers
(agent-tui 2.0 MB/s in prod 1.4.91).
Fix: high-priority (visible-pane) drains now re-arm on xterm's
parse-completion callback and carry 8 writes per tick; the isolation
ceiling rises 27 -> 117.6 MB/s (parse-limited). Background cadence is
deliberately unchanged (2 MB/s drip protects the focused pane; hidden
delivery is term-speed-2's job). DRAIN_TIME_BUDGET_MS still bounds
per-tick work, preserving #7139's cooperative-drain intent.
Validation: 621 scheduler/guard/pty tests green, typecheck clean.
Co-authored-by: Orca <help@stably.ai>
* Record task #9 attribution + parse-clock fix in findings log
Co-authored-by: Orca <help@stably.ai>
* Findings: 51x loss attributed to O(tail) retained-tail redraw path in main onPtyData
Co-authored-by: Orca <help@stably.ai>
* Window the retained-tail redraw path to the cursor's reach
Attribution (findings log 2026-07-03): main's onPtyData consumed ~93% of
the event loop under an agent-TUI flood, and the dominant term was
appendNormalizedToMultilineTailBuffer + finalizeRetainedTerminalRows
materializing ~2x tail-length row objects plus a per-row trailing-space
regex on every chunk — 0.888ms/chunk at the 2,000-line cap, on every
Claude-Code-shaped frame (cursor-up + erase-below).
The multiline algorithm now runs on a suffix window sized by the chunk's
maximum upward cursor excursion (plus the inherited redraw cursor and a
safety margin); the untouched prefix is shared by reference with a cheap
last-char trailing-space check to match the reference trim. Pathological
full-height cursor-ups fall back to the unwindowed implementation, which
is kept verbatim and exported as the reference for the 500-case
differential fuzz (retained-tail-redraw-window.equivalence.test.ts).
Micro-bench at a full 2,000-line tail: 0.888 -> 0.073 ms/chunk (12x).
1,415 runtime tests green, typecheck clean.
Co-authored-by: Orca <help@stably.ai>
* Add dev bench results: parse-clock and windowed-tail fixes
Co-authored-by: Orca <help@stably.ai>
* Record windowed-tail partial win + next-cycle recipe in findings log
Co-authored-by: Orca <help@stably.ai>
* Findings: remaining whale is the per-chunk blocked-reason check (~85% of onPtyData post-fix)
Co-authored-by: Orca <help@stably.ai>
* Throttle the terminal wait-blocked check off the PTY hot path
Post-windowed-tail attribution (findings log 2026-07-03): the blocked-
reason complex — two full-tail buildTerminalWaitText builds plus
toLowerCase and multi-pattern scans per chunk, existing only to stamp
waitBlockedAt — consumed ~85% of onPtyData's remaining cost (~700-790ms/s
under an agent-TUI flood).
The check now runs at a 50ms cadence over coalesced chunks (PTY chunk
boundaries are arbitrary, so coalescing preserves semantics), with a
trailing-edge timer so burst-final state is always evaluated, and an
immediate bypass when the incoming chunk (plus a 31-char split carry)
contains a prompt keyword — so actionable-prompt stamping stays
per-chunk-immediate while keyword-free flood frames skip the complex
entirely. Previous wait text is cached per pty instead of rebuilt, and
state is cleared at both pty teardown sites.
1,415 runtime tests green (including the cross-chunk prompt test, which
exercises the keyword bypass), typecheck and lint clean.
Co-authored-by: Orca <help@stably.ai>
* Findings + results: three stacked fixes unlock the pipeline (agent-tui 16x, DSR-load p50 161->18.8ms in dev)
Co-authored-by: Orca <help@stably.ai>
* Add producer flow-control design to initiative plan
Co-authored-by: Orca <help@stably.ai>
* Findings: revival branch green but perf-gated — daemon Session ingest regressed 103->40-48 MB/s (chain emulator restructure); merge blocked until blockedfix parity
Co-authored-by: Orca <help@stably.ai>
* Pre-filter daemon OSC/mouse scanners for introducer-free chunks
Skips the scan-tail copy and full-chunk walks when a chunk cannot contain
an OSC or private-mode sequence (single native includes() checks), with
split-sequence correctness preserved via explicit tail retention. Strictly
positive micro-optimization on the daemon per-chunk path; 641 daemon tests
green (1 pre-existing WSL failure unrelated).
Co-authored-by: Orca <help@stably.ai>
* Retract confounded daemon conviction; mandate load-controlled A/B protocol for the revival merge gate
Co-authored-by: Orca <help@stably.ai>
* Record A/B gate pass in findings log; add A/B result JSONs
Co-authored-by: Orca <help@stably.ai>
* Add producer-side PTY flow control (watermarks + protocol v19)
Main now pauses the actual PTY when a pane's renderer-pending backlog
crosses the 256KB high watermark and resumes once it drains below the
32KB low watermark (wide hysteresis band so a draining queue cannot flap
pause/resume per flush slice). node-pty pause() stops the pty fd read, so
the kernel/ConPTY buffer fills and a flooding shell blocks on write —
flood-induced buffered lag becomes shell blocking instead of unbounded
main-process buffering (terminal-performance-initiative §5).
Transport: new fire-and-forget pausePty/resumePty daemon notifications
(protocol v19; 18 added to PREVIOUS_DAEMON_PROTOCOL_VERSIONS), routed
DaemonServer -> TerminalHost -> Session -> subprocess pause()/resume().
LocalPtyProvider pauses node-pty directly. Router/degraded providers
forward; IPtyProvider gains optional pauseProducer/resumeProducer.
Safety invariants:
- Lost-resume failsafe: daemon Session auto-resumes 5s after a pause with
no matching resume; main re-asserts the pause at most once per 5s while
still above the high watermark, so a lost resume can never wedge a shell
and a sustained flood stays throttled.
- Resume on every teardown path: Session kill/exit/dispose/detach; main
releases on pty exit and on window-destroyed bookkeeping wipes; the
adapter owes paused sessions a resumePty on the next connect after a
socket drop.
- Providers without support (SSH relay, legacy protocol <= v18) no-op
silently, and the scrollback-scaled pending-output cap still bounds
main memory when pause is unavailable.
- Kill switch: PRODUCER_FLOW_CONTROL_ENABLED in ipc/pty.ts flips the
whole mechanism off in one line.
daemon-errors.ts is split out of types.ts to stay under the max-lines cap.
Tests: watermark transitions/hysteresis/re-assert (controller unit),
lost-resume failsafe + resume-on-kill/exit/dispose/detach (session),
notification routing + v18 gating + reconnect owed-resume (adapter),
direct pause/resume (local provider), and a flood test asserting pause
fires once, pending stays bounded at HIGH + one chunk, and resume fires
once after drain (ipc/pty).
Co-authored-by: Orca <help@stably.ai>
* Findings: flow control merged; definition-of-done accounting; prod verification re-scoped to packaged RC
Co-authored-by: Orca <help@stably.ai>
* Fix stray brace from revival merge in long-table-scroll-restore e2e spec (broke e2e transform in CI)
Co-authored-by: Orca <help@stably.ai>
* Prod verdict: v1.4.121-rc.0 bench — DSR-load p50 134->18.6ms (7.2x), agent-tui 2.0->11.2 MB/s, idle at Terminal.app parity; pipeline now cadence-bound
Co-authored-by: Orca <help@stably.ai>
* Recover terminal output delivery after system sleep
Root cause: main gates every pty:data send on a global + per-PTY
in-flight counter that only renderer ACKs decrement. If ACKs are lost
across a system suspend, the counters pin at the cap and every PTY —
old and newly created — is silently gated forever while output piles up
in pendingData. A focus-preserving display wake also fires no renderer
focus/visibilitychange events, so terminal wake recovery (and the WebGL
context-loss latch clear) never runs. Only a renderer reload recovered.
Three fixes:
- ACK-stall watchdog (src/main/ipc/pty.ts): if sends stay gate-blocked
for 10s with zero ACK progress while the renderer webContents is
alive, warn once, reset the in-flight delivery counters, and flush
held pendingData. Armed lazily on the first gate-blocked send and
disarmed by every ACK, so it can never fire under healthy heavy load.
- Renderer lifecycle reset now also zeroes the in-flight counters — a
reload/navigation destroys the renderer dispatcher, so outstanding
ACKs can never arrive and stale counters would gate the new renderer.
- System-resume wake IPC: main relays powerMonitor 'resume' as
system:resumed to live windows (plus forceRepaint); preload exposes
ui.onSystemResumed; the terminal wake-recovery hook runs the same
recovery path as window focus/visibilitychange.
Co-authored-by: Orca <help@stably.ai>
* VS Code head-to-head: Orca beats/ties 5 of 6 metrics (16x idle, 5x styles-stress, better p99); load p50 gap attributed to ACK window + timer-clamped drain cadence
Co-authored-by: Orca <help@stably.ai>
* Schedule zero-delay terminal drains via MessageChannel
Chromium clamps nested setTimeout(0) to ~4ms, stacking dead gaps onto
every parse-clocked drain tick; the explicit 4ms high-priority re-arm
interval added more. A posted message is still a macrotask — input and
paint are serviced between posts — so cooperative yielding survives
without the clamp. Generation-tokened cancellation; vitest keeps the
timer path (fake timers can't advance channel posts) plus a real-timer
smoke test for the channel path. Standing-queue target: VS Code's ~7ms
class (measured us 18.6ms, them 7.18ms, same rig).
Co-authored-by: Orca <help@stably.ai>
* Cut daemon and main PTY batch windows 8ms -> 2ms
At 9% pipeline utilization the DSR-under-load latency is fixed batching
windows, not queue depth (proved by the MessageChannel drain lever
moving nothing). Both hops charged an expected half-window per chunk;
2ms keeps burst coalescing at negligible IPC overhead (~500 msgs/s
worst case vs MB/s payloads).
Co-authored-by: Orca <help@stably.ai>
* Findings + tests: batch windows were the DSR-load gap (19->8.0ms dev); timing tests updated to 2ms windows
Co-authored-by: Orca <help@stably.ai>
* Fix PR CI and guard resume relay during shutdown
Co-authored-by: Orca <help@stably.ai>
* Chain e2e specs 6/6 green — gate x drain validation debt paid
Co-authored-by: Orca <help@stably.ai>
* Replace ack-stall watchdog with cumulative ACKs + solicited delivery resync
Design review: the 10s blind-reset watchdog decided correctness from a
wall-clock threshold. Rework piece 1 into a deterministic two-part design
(pieces 2 and 3 — lifecycle-reset counter zeroing and powerMonitor wake
IPC — are unchanged):
- Cumulative ACKs (TCP-style): the renderer dispatcher now tracks a
monotonic per-pty total of processed chars (terminal-pty-ack-gate) and
sends it on every ACK alongside the legacy per-chunk delta. Main keeps
per-pty sentChars/ackedChars and max-merges received totals — idempotent
and reorder-tolerant, so a lost ACK self-heals when any later ACK
arrives instead of becoming permanent in-flight debt. Provider
(SSH/daemon) backpressure is credited only the derived delta, clamped,
never negative. Main tolerates both payload shapes keyed by field
presence (dev hot-reload can mix renderer/main versions); totals reset
on pty exit and renderer lifecycle reset on both sides.
- Solicited resync (replaces the blind reset): when new pty data arrives
while that pty's delivery is fully gated and no probe is outstanding,
main sends pty:requestDeliveryResync; the renderer replies with its
cumulative totals and main reconciles via max-merge, then flushes held
pendingData. Event-triggered, verified-state recovery — no wall-clock
threshold decides correctness. The only timer is a 5s request/response
hygiene timeout that clears the outstanding flag and logs one
diagnostic warn per silent streak; it never mutates counters (a
renderer that cannot answer has dead IPC — reload is the only cure).
The 10s corrective watchdog is deleted.
Co-authored-by: Orca <help@stably.ai>
* Starting point: prior agent's garble differential fuzz harness
Three files recovered (were untracked) from a prior agent killed by API
outages, plus a trivial curly-brace lint fix in the op dispatcher so the
pre-commit hook passes:
- src/shared/agent-tui-ansi-fuzz-stream.ts (seeded agent-TUI byte-stream gen)
- src/shared/terminal-restore-parity-fixture.ts (renderer-parity fixture)
- src/main/daemon/headless-emulator-fidelity.fuzz.test.ts (suite 1: differential
HeadlessEmulator vs @xterm/headless reference on identical bytes)
Co-authored-by: Orca <help@stably.ai>
* Suite 1 findings: two new serialize round-trip bugs (B bold-loss, C cursor)
Scanned seeds 1..2000. Beyond the pre-documented serialize wrap-null-cell bug
(A, 27 seeds, tolerated), the fuzz surfaced two NEW real @xterm/addon-serialize
0.15.0-beta.287 round-trip defects, both of which garble a revealed hidden pane:
- Bug B (seeds 435, 770, 1321): serializing a dim cell followed by a bold-only
cell emits \x1b[1;22m; SGR 22 clears bold too, so restored bold is lost.
Minimal repro: '\x1b[2mA\x1b[22m\x1b[1mB' -> restored 'B' loses bold.
- Bug C (seeds 454, 1696): a final content row filled to the right margin leaves
xterm wrap-pending; the serializer's relative cursor restore lands one column
short. Minimal repro: '0123456789\x1b[3;5H' at cols=10 -> cursor x=3 not x=4.
Both isolated to pure serializer replay (no Orca preamble), confirming upstream.
Parity fixture verified faithful to the renderer pane's buffer options. Each is
pinned as a standalone it.skip repro; full evidence + classification in
notes/garble-fuzz-divergences.md. Seed 113 (handoff's DECSC/DECRC case) does not
diverge on the current harness. No production code changed.
Co-authored-by: Orca <help@stably.ai>
* Add perf prerelease update check modifier
Co-authored-by: Orca <help@stably.ai>
* Suite 2: hidden-reveal seq-reconciliation fuzz + two new snapshot bugs (D, E)
Property-tests the reveal seq-reconciliation byte-stitch (getChunkDataAfterSnapshot
/ reconcileChunkAgainstRestoredSnapshot in pty-connection.ts), mirrored exactly:
N=200 seeded hide/reveal scenarios with a rich agent-TUI hidden prefix snapshot
and an append-only racing tail, chunked with seq/rawLength meta, seq-domain
restarts, unmetered chunks and droppedOutput markers. Asserts snapshot-at-S +
reconciled tail == snapshot-of-everything (seq-neutral) and == always-visible
(end-to-end). Runtime ~5s at 200; FUZZ_ITERATIONS override documented.
Two NEW real snapshot-limitation garbles found while building it, both distinct
from suite 1's serialize bugs and pinned as standalone it.skip repros:
- Bug D: the DECSC saved-cursor register is not serialized. A hidden TUI that
saves the cursor (ESC 7 / CSI s) and restores it on reveal (ESC 8 / CSI u)
lands the restore at home. Repro: 'AB\x1b7\x1b[4;10HCD' + '\x1b8X' -> 'XB' vs 'ABX'.
- Bug E: a snapshot taken mid-escape-sequence (a PTY read split an escape) drops
the partial sequence (it's parser state, not buffer), so the tail's
continuation renders literal. Repro: 'AB\x1b[3' + 'mCD' -> 'ABmCD' vs 'ABCD'.
Fired on ~24% of the corpus (tolerated + counted via prefixEndsMidSequence).
The append-only-tail design isolates seq reconciliation from these and the Bug C
cursor cascade. Full evidence + fix directions in notes. No production changes.
Co-authored-by: Orca <help@stably.ai>
* Suite 3: 25-cycle park/reveal drift e2e test
Extends terminal-hidden-view-parking.spec.ts with a deterministic 25-cycle
park->reveal test on a static rich alt-screen TUI frame (box drawing, SGR
colors, wide CJK/emoji). Baselines against the frame after the first snapshot
restore (so both sides pass through identical machinery — the alt-screen restore
correctly drops normal-buffer scrollback, which is contract not garble), then
asserts every subsequent reveal reproduces it byte-for-byte with no accumulated
drift and no hidden-skip banner. Exercises the real renderer teardown +
HeadlessEmulator snapshot restore + PTY reattach path the fuzz suites model in
isolation. Passes in ~29s (electron-headless, workers=1).
Co-authored-by: Orca <help@stably.ai>
* Fix two serialize round-trip bugs garbling hidden-terminal snapshot restore
BUG B (addon patch): @xterm/addon-serialize's SGR diff emitted bold/dim set
params before the shared intensity reset 22, so "1;22" wiped a freshly set
bold and a bare "22" dropped a still-set bold/dim. Patched via pnpm
patchedDependencies (config/patches) to diff bold+dim as one intensity
group with the clearing 22 emitted first. Other flag pairs (4/24, 3/23,
7/27, ...) have dedicated resets and were verified unaffected.
BUG C (Orca-side hardening): the addon restores the cursor with relative
moves computed from where it assumes replay leaves the cursor; a final row
filled exactly to the right margin leaves replay wrap-pending and the
restore lands one column short. New shared
serializeWithAbsoluteCursor appends an absolute CUP from the source
terminal's authoritative cursor at every restore/replay serialize site
(daemon/runtime HeadlessEmulator.getSnapshot, renderer mobile snapshot
serializer, shutdown layout capture). It skips empty snapshots and
wrap-pending sources so it never changes already-correct behavior.
Round-trip repros + non-regression coverage in
src/main/daemon/terminal-snapshot-serialize-roundtrip.test.ts (verified
failing with the fixes stashed). buildRehydrateSequences extracted to its
own module to keep headless-emulator.ts under the max-lines budget.
Co-authored-by: Orca <help@stably.ai>
* Gates: tolerate+count Bugs B/C in deep mode; drop inverse from reconciliation tail
- Fidelity suite: add snapshotHasSelfCancellingBoldReset (Bug B) and
isMarginWrapPendingCursorOffByOne (Bug C) predicates so the corpus tolerates +
counts them like Bug A. FUZZ_ITERATIONS=2000 is now green (~113s) and fails
only on genuinely new divergences; each tolerance keeps its <50% degeneracy
guard. Default 300 unchanged (~17s).
- Reconciliation suite: drop SGR 7 (inverse) from the append-only tail. Inverse
marks trailing blanks with an inverse-fg the serializer round-trips slightly
differently by capture depth — a Bug-B-class serialize nuance, not seq
reconciliation. FUZZ_ITERATIONS=1000 is now green; default 200 unchanged.
- Notes updated: every bug class is both pinned (skipped repro) and tolerated in
its corpus; combined default runtime ~19s.
Regex uses String.fromCharCode(27) to stay oxlint no-control-regex clean.
Co-authored-by: Orca <help@stably.ai>
* Keep RC update checks off perf prereleases
Co-authored-by: Orca <help@stably.ai>
* Fix snapshot DECSC register loss (Bug D) and mid-escape boundary drop (Bug E)
Bug D: the serialized screen cannot carry the VT100 DECSC saved-cursor
register, so a hidden ESC 7 followed by a post-reveal ESC 8 restored to
home and clobbered live cells. The snapshot epilogue now re-saves at the
source's saved position before the final absolute CUP
(readSavedCursorRegister + serializeWithAbsoluteCursor; the active
buffer's own register, so alt screens carry theirs). Position-only by
design; never-saved terminals are left untouched.
Bug E: a PTY read ending mid-escape leaves the sequence in the emulator's
parser, so serialize dropped it and the racing tail's continuation bytes
rendered literally after reveal (~24% of the fuzz corpus). The emulator
now tracks the unparsed trailing partial at ingest
(terminal-partial-escape-tail.ts, committed post-parse like the mouse
mirror) and ships it as TerminalSnapshot.pendingEscapeTailAnsi.
applyMainBufferSnapshot writes it LAST, after POST_REPLAY reset — any
later ESC would abort the dangling sequence. Seq accounting is unchanged:
the tail is a suffix of bytes the snapshot seq already counts, so
reconcile slicing needs no adjustment.
Fuzz suites: unskip the Bug B/C repros (fixed on this branch) and the new
D/E repros; remove the B/C/E tolerance predicates so regressions fail
loudly. Only Bug A (upstream wrap null-cell) stays tolerated + counted.
Green at FUZZ_ITERATIONS=2000 (fidelity) and 1000 (reconciliation).
Co-authored-by: Orca <help@stably.ai>
* Count suffixed RC tags (rc.N.perf) in the shared rc counter — second suffixed cut collided with the first
Co-authored-by: Orca <help@stably.ai>
* Classify suffixed rc tags (rc.N.perf) as rc telemetry identity in release builds
The build-identity guard only knew vX.Y.Z and vX.Y.Z-rc.N, so suffixed
perf RCs cut fine but every platform build refused the tag and the
releases published empty.
Co-authored-by: Orca <help@stably.ai>
* Cut the hidden-restore flood feedback loop (A) + query carve-out on drops (B)
(A) Under a foreground flood, the hidden-output-restore loop re-fetched
snapshots endlessly: each synchronous applyMainBufferSnapshot starved ACK
processing, main pinned at the in-flight cap, dropped at the pending cap,
and every droppedOutput/modelRestoreNeeded marker re-armed another
restore until the flood ended (rc.7.perf DSR timeouts).
- Restore loop: a foreground live-chunk queue overflow now abandons the
restore immediately (the stream is outrunning snapshot fetch+replay),
with a 3-iteration hard cap + lifecycle warn as backstop.
- Re-arm gate: drop markers/sentinels and reconcile seq-gaps on a visible
pane during its own in-flight/just-abandoned restore no longer re-arm;
live bytes write through and ONE deferred repaint (2s after the last
backpressure signal) heals the gap. Hidden-pane gate semantics are
unchanged.
- Query salvage: discarding queued restore bytes (overflow/refetch) now
extracts DSR/CPR/DA/OSC-color queries and replays them to xterm so
replies still flow.
(B) Main-side: dropOversizedPendingPtyData carves reply-eliciting query
sequences out of the dropped buffer (and out of post-drop latched data,
bounded) and ships them on the droppedOutput sentinel, so DSR probes
survive bulk drops. Query scanning moved to
src/shared/terminal-reply-query-extraction.ts, shared verbatim with the
renderer's hidden-startup query extraction.
Co-authored-by: Orca <help@stably.ai>
* ACK terminal output at parse-drain, not dispatcher enqueue (C)
The renderer credited main's per-PTY in-flight window the moment a
pty:data chunk entered the dispatcher, so the 512KB window meant "bytes
received", never "bytes parsed". Under flood the renderer write queue
grew unbounded behind instant ACKs; main saw no backpressure, crossed
the pending cap, and bulk-dropped output (rc.7.perf DSR timeouts).
Crediting is now parse-deferred: each delivery carries a fire-once
credit (deliverPtyDataWithDeferredAck); the pane's first scheduler write
claims it (writeTerminalOutput.ackCredit) and the output scheduler fires
it when the bytes are consumed — after terminal.write in the
parse-clocked drain, or on ANY discard path (backlog cap replacement,
discardTerminalOutput, disposed-terminal drops, flush recovery).
Deliveries that never reach the scheduler (reconcile drops, restore
queueing, pre-mount eager buffer) settle at handler return, so the
invariant holds: every delivered chunk credits exactly once, parsed or
discarded. E2E ack-gate hold/release and delivery-resync semantics are
unchanged (all crediting still routes through ackPtyData).
Main-side equilibrium: with ACKs at parse cadence, in-flight becomes
true backpressure — pendingData stays near the 256KB producer-pause
watermark, far under the >=2MB drop cap, so bulk floods block the shell
(node-pty pause) instead of dropping.
Co-authored-by: Orca <help@stably.ai>
* Synthesize salvaged query replies directly instead of replaying into xterm
The 10MB dev bench proved the write-back salvage insufficient: a
pending-cap drop always triggers a snapshot restore, whose replay guard
swallows xterm auto-replies and whose discardTerminalOutput races away
still-queued query writes — the salvaged DSR died both ways and the
fence still timed out.
Salvage now answers directly on the input path (immune to both): CPR
(CSI 6n) from the live buffer via transport.sendInput, DA1 with the
renderer's canned response, OSC color probes via the existing direct
responder. Rare queries (DECRQM, DA2) keep the best-effort xterm
replay.
Co-authored-by: Orca <help@stably.ai>
* Untrack branch-added bench result JSONs (20 files); keep numbers in the findings log
Files stay on disk; main's 7 pre-existing results are untouched.
Co-authored-by: Orca <help@stably.ai>
* Branch guide: document merge-not-rebase sync strategy and conflict pattern
Co-authored-by: Orca <help@stably.ai>
* Merge origin/main (#7316 tab-strip click-vs-drag fix); adapt #7290 recovery-reload tests to this branch's dual did-finish-load listeners
The three tests grabbed the FIRST did-finish-load listener; on this branch
the renderer delivery-gate reset registers before the orphan sweep, so the
sweep tests exercised the wrong handler (one failing, two vacuously green).
They now fire all listeners like a real reload.
Co-authored-by: Orca <help@stably.ai>
* Fix branch CI lint: split pane-interaction functions out of artificial-opencode-terminal-load.spec (815>800 lines), modernize perf-html-report script
No max-lines disable per repo rules; extracted to
artificial-opencode-pane-interactions.ts. toReversed() and
import.meta.filename replace reverse()/fileURLToPath.
Co-authored-by: Orca <help@stably.ai>
* Fix Windows update-relaunch killing the live terminal daemon
On a Windows update relaunch the daemon can be wedged past every RPC
budget (final checkpoint flush + installer/AV disk pressure), so the 3s
health check AND the 5s session-list hello both time out while sessions
are still alive - and the launcher failed closed, killing the daemon and
every terminal session it owned.
- Adopt an unresponsive daemon whose pipe still accepts a raw
connection; a new rejected health state keeps replacing daemons that
answered and refused the handshake (never adoptable).
- Give Windows pid files a real startedAtMs (daemon self-reports it in
the ready IPC message) and verify it via CIM CreationDate piggybacked
on the existing command-line query, so the pid-recycling guard is no
longer inert on win32.
- Only delete legacy daemon pid/token files when the pid-file process is
provably dead; deleting a live daemon''s token made its sessions
permanently unadoptable after a protocol bump.
- Capture agent resume records every 60s in the renderer (skipping
unchanged records) so hard kills still leave a fresh resume record.
* Heal blank terminals when main→renderer push delivery dies (renderer-pull delivery watchdog)
Field evidence (v1.4.121-rc.0 debug snapshot, 2026-07-06): a wedged window
held 530,115 un-ACKed in-flight chars — one PTY pinned at the 512KiB per-PTY
high water plus a fresh terminal's 245-char prompt that was sent and never
consumed — while the user ran the snapshot over invoke from that same window.
Main→renderer push delivery (pty:data and every sibling channel) was dead;
renderer→main→renderer invoke was alive. Upstream precedent for
one-directional IPC death: electron#37067 (suspected Mojo pipe disconnect,
stalled as need-info). Every terminal goes blank, new terminals are born
blank, and only a renderer reload recovered.
The existing recovery layers cover the OTHER variants of this bug family and
structurally cannot reach this one:
- The xterm write-pipeline sync-throw guards, output-buffer caps, and
probe-certified replay-guard release (#7150 family) run only after bytes
arrive in the renderer — here they never do. (The pending cap did work as
designed in the field: ~2.1MB pendingDroppedChars, bounded main heap.)
- Cumulative ACKs self-heal lost ACK messages and the solicited delivery
resync reconciles verified totals (4647df86a; #7260 on main) — but the
resync probe, the powerMonitor wake relay, and the droppedOutput restore
markers all ride main→renderer push, the direction that is dead. The
probe's unanswered path deliberately only logs.
This adds the missing lane, renderer-initiated and ridden entirely over
invoke — the direction the field snapshot proved alive:
- terminal-delivery-watchdog.ts: 15s heartbeat, free while output flows.
Hot-path cost is one Map upsert per received chunk; a tick does no IPC
unless the terminal plane was silent for the whole interval and a PTY
still expects delivery. Two consecutive silent ticks with main reporting
ACK-starved in-flight confirm the wedge; heals are one-shot per 60s
cooldown so a persisting wedge cannot repaint-storm.
- pty:reportRendererDeliveryState (invoke): always max-merges the renderer's
cumulative processed totals (a free extra repair lane for the lost-ACK
variant); with heal:true — and only after main has itself seen ≥10s of ACK
silence — writes off bytes the renderer provably never received
(received ≤ acked < sent; a received-but-unparsed backpressure window is
never written off), drops that PTY's pendingData (snapshot covers
everything ≤ markerSeq, hidden-drop parity), credits provider flow
control, and returns restore markers in the reply.
- The renderer re-attaches all push listeners (cures a detached-listener
variant outright; a safe no-op against a dead channel) and routes the
pulled markers through the existing pty:modelRestoreNeeded machinery —
panes repaint from the main-owned buffer snapshot with zero push
delivery involved.
- Field discrimination built in: the heal warn logs
ipcRenderer.listenerCount('pty:data') (listener detached vs channel dead)
with the full delivery snapshot, so the next occurrence names the root
cause without asking the user to run anything in a console.
Repro harness: the exposeStore-gated __terminalDeliveryWatchdog hook
blackholes pty:data ahead of the dispatcher — the field failure in
miniature (no receive count, no ACK credit, no dispatch).
terminal-push-delivery-loss-recovery.spec.ts proves the wedged output
repaints while the blackhole is still engaged and live flow resumes after
release, with no reload. Unit suites pin the watchdog state machine
(zero IPC under flow, two-tick confirm, cooldown), the dispatcher reattach
seam, and the main-side write-off semantics.
Perf: nothing added to main's send/flush path; the renderer data path gains
one integer/Map update per chunk; idle cost is one ~100-byte invoke per 15s
only during total terminal silence. Terminal perf e2e suite (typing
latency, redraw freeze, output scheduler, hidden TUI restore, artificial
opencode load) passes on this change; no watchdog activity occurs under
ack-gate pressure scenarios because receive-progress gates the heartbeat.
Co-authored-by: Orca <help@stably.ai>
* Expose the hidden-yet-visible delivery-gate contradiction in the debug snapshot
The v1.4.124-rc.2.perf blank-terminal field snapshot showed a different
state than the v1.4.121 transport wedge: no delivery gating at all
(ackGatedFlushSkipCount 0, in-flight 38KB, far under every cap) but TWO
ptys hidden-delivery-gated with 78MB dropped as hidden. The aggregate
counters cannot say whether the pane the user was staring at was one of
the gated ones — the one number that separates "normal background
dropping" from "main is starving a visible pane because the reveal
unmark never fired".
Add hiddenDeliveryGatedVisiblePtyCount / hiddenDeliveryGatedActivePtyCount
(overlap of the gate's hidden set with the renderer's visible/active
reports — a contradiction that must be zero) to the delivery debug
snapshot, and a once-per-minute warn when hidden-gated bytes are dropped
for a pty the renderer reports visible or active, with the full snapshot
attached. Zero cost outside the debug read and the already-dropping path.
Co-authored-by: Orca <help@stably.ai>
* Unlatch the hidden-delivery gate when user input disproves a stuck document.visibilityState
macOS occlusion tracking can wedge document.visibilityState at 'hidden'
after display sleep and never fire another visibilitychange. The hidden-
delivery gate then keeps dropping renderer-bound bytes for panes the user
is looking at (field snapshot 2026-07-06, v1.4.124-rc.2.perf: 78MB dropped
across 2 pane-level-visible ptys with a fully healthy transport), and every
recovery path (window focus, system-resume relay, backlog recovery) re-ran
syncHiddenRendererPtyDelivery only to recompute the same stale predicate —
nothing could ever clear the gate. The user sees a frozen terminal; typing
echo is dropped in main; only a reload recovers.
Real user input while the document claims hidden is a physical
contradiction: keystrokes and clicks only reach a focused, on-screen
window. stale-document-visibility.ts latches that proof, runs each pane's
existing visibilitychange resync (gate unhide + hidden-output snapshot
restore), and hands authority back to the occlusion tracker on the next
genuine visibilitychange. No timers; the failure bias is safe — a wrong
latch can only restore pre-gate delivery cost, never drop bytes. Hot path
unchanged: the foreground predicate still returns on the same single
comparison while the document is visible.
tests/e2e/terminal-stuck-occlusion-recovery.spec.ts pins the wedge
(visibilityState pinned hidden -> output dropped, not painted; the
hiddenDeliveryGatedVisiblePtyCount field discriminator reads >0) and the
recovery (one Shift keypress repaints the missed output from the main-owned
snapshot, no reload, while visibilityState still reads hidden). Negative
control verified: the spec fails without this fix. Typing-latency perf
gate passes; terminal-pane unit suites 366/366.
Co-authored-by: Orca <help@stably.ai>
* Add a one-paste terminal freeze report: __orcaTerminalFreezeReport()
Every field report of the frozen-terminal family so far has needed
follow-up asks (console output, main logs, second snapshots) because each
capture showed one process's counters at one instant. This makes a single
DevTools command sufficient: `await window.__orcaTerminalFreezeReport()`
returns renderer state (document.visibilityState + the stale-visibility
override, pty:data listener count, delivery-watchdog totals), main's debug
snapshot extended with a per-pty delivery table (sent/acked/pending, hidden
vs visible-set membership, last send/ACK ages, window focus flags, power
suspend/resume ages, app version), and bounded breadcrumb rings from BOTH
processes recording the transitions that matter: gate marks/unmarks,
visibilitychange and stale-visibility latches, watchdog stalls and heals,
restore markers, heal write-offs, and renderer lifecycle resets (so "user
already reloaded" is visible in the history).
Costs stay off the data path: breadcrumbs record only rare transitions into
a 100-entry ring with same-kind coalescing (a flood costs one slot per
second); the per-pty table is built only when the snapshot is read; the
per-send bookkeeping adds one Date.now() to existing accounting writes. Pty
ids are redacted to their `@@` suffix because daemon session ids embed
worktree paths. The report assembles over invoke IPC — the direction proven
alive in every observed wedge — and a failing invoke is captured as data
instead of sinking the report.
The stuck-occlusion e2e now also pins the report end-to-end: after the
wedge + keystroke recovery, the report must carry the stale-visibility
latch and gate transitions in the renderer ring, gate-mark/unmark in main's
ring, and a populated per-pty table. Suites: pty.test.ts 258, terminal-pane
1705, shared ring 5; typing-latency perf gate passes.
Co-authored-by: Orca <help@stably.ai>
* perf(daemon): keep-tail thin hidden panes' stream so agent floods never bury typing (STA multi-workspace lag)
Hidden panes are exempt from pendingData flow control (main gate-drops
their bytes after ingestion), so N background agents ran unbounded ahead
on the one shared daemon->main stream socket (measured 192MB user-space
backlog) and visible-pane echo waited FIFO behind it — typing appeared
seconds late whenever several agents burst on a loaded machine
(8x512KB/s + 12 CPU spinners: p50 293ms fix-off; 12x1MB/s: 6.1s).
Mechanism (replaces producer pacing — no reveal catch-up, ever):
- Shallow socket write gate (128KB) + per-session fairness bypass bounds
echo latency by construction; kernel-flush refill sentinel keeps held
bulk draining at full speed (drain-only refill capped at ~8MB/s).
- Backgrounded sessions' queued output is keep-tail dropped (newest
512KB kept, in-order dataGap replaces the middle); a ~2MB GLOBAL
budget shrinks per-session keep-tails (floor 64KB) so a worktree
switch never waits behind the aggregate. Reply-eliciting query bytes
(DSR/DA/OSC probes) are salvaged from dropped spans.
- Notifications are structurally lossless: the daemon runs the same
shared scanners main uses (bell/OSC 133/pr-link/2031) over every byte
BEFORE drop decisions and relays facts in byte order; ordered
background markers hand scan authority back and forth, seeded with the
emulator's partial escape tail so a sequence split across the handoff
neither phantom-fires nor goes missing. Titles/agent-status stay
main-side (kept-tail convergent).
- Main: background = hidden AND no remote view subscriber (a live
mobile/web view is never thinned); on dataGap main resets cross-chunk
parse carries, drops the headless mobile mirror, and reuses the
hidden-drop model-restore marker.
Wire: three new stream events, tolerated within protocol v19 (old mains
ignore unknown events; old daemons never see the trigger). Kill
switches: ORCA_DAEMON_BACKGROUND_STREAM_DROP=0,
ORCA_DAEMON_SHALLOW_SOCKET_GATE=0.
A/B (pnpm bench:multi-workspace-typing): 8x512KB/s + 12 CPU workers
p50 293ms/p90 647ms -> 15/21ms (= baseline); 12x1MB/s 6,146ms -> 20ms;
light loads unchanged; zero missing echoes. Latin hidden-restore e2e
green (probe-verified aggregate-drain root cause). New deterministic
repro harness: tests/e2e/terminal-multi-workspace-typing-latency.spec.ts
+ CPU pressure workers.
Co-authored-by: Orca <help@stably.ai>
* diag(terminal): breadcrumb WebGL context-loss/atlas + wake triggers into freeze report
Silent instrumentation (memory ring only, no new console lines) so the next
post-wake garble report attributes itself. Adds:
- shared/terminal-webgl-diagnostics.ts: lib-safe sink so pane-webgl-renderer
(lib) can record without importing the components-layer ring; wired to the
ring in terminal-freeze-breadcrumbs.
- webgl-context-loss crumb at onContextLoss, webgl-atlas-reset crumb at the
atlas registry reset — the pair that distinguishes 'atlas corrupted' from
'missed repaint'.
- wake-recovery:<source> crumb (focus/visibilitychange/system-resumed) with the
clearGlyphAtlases decision; source in the kind so distinct triggers don't
coalesce.
- per-pane WebGL state (getAllPaneRenderingDiagnostics) in the freeze report.
Gates: typecheck 0 errors; terminal suites 328 files pass; oxlint clean.
Co-authored-by: Orca <help@stably.ai>
* fix(lint): use Number.parseInt/parseFloat in terminal-view-attributes
oxlint unicorn(prefer-number-properties) flagged 24 global parseInt/parseFloat
calls in the terminal-view-attributes feature (ee540f32d, perf-branch only),
failing PR Checks 'verify' lint. Mechanical global→Number.* rewrite via
oxlint --fix; behaviorally identical. Pre-existed the latest main merge.
Co-authored-by: Orca <help@stably.ai>
* fix(test): update stale terminal test stubs/expectations to current runtime
Three pre-existing perf-branch test failures (red before the latest main
merge; unrelated to it) — all stale test scaffolding lagging behind
perf-branch features, no production code changed:
- provider-dispatch.test.ts: electron mock missing powerMonitor, which
pty.ts installPowerSignalBreadcrumbs now calls on registerPtyHandlers.
Added powerMonitor:{on:vi.fn()} to match pty.test.ts.
- runtime-terminal-stream.test.ts: onSnapshot now receives a second
{ pendingEscapeTailAnsi } meta arg (#7329); updated the three exact-arg
toHaveBeenCalledWith assertions.
- terminal-multiplex-escape-tail.test.ts: stubRuntime missing
registerRemoteTerminalViewSubscriber (subscribe path calls it now, erroring
before snapshot serialize); added the stub used by sibling multiplex tests.
Co-authored-by: Orca <help@stably.ai>
* Fix hidden/parked split-pane exit stranding ghost or resurrected panes
Deterministic e2e repro of the field 'ghost blank pane' incident (a
closed/finished setup-split leaf persisted in root with no binding and
remounted as a permanently blank pane) found two teardown gaps at the
hidden-view parking boundary:
1. The kept-exit guard ('freshly split pane can lose its newborn PTY
during setup') fired for HIDDEN panes. The hidden-delivery gate
withholds their bytes, so a hidden split always looks output-less and
its dead pane was kept — a binding-less ghost that dead-session
reconcile can never reach (no PTY id to prove dead). The keep is a
visible-failure UX; gate it on isVisibleRef and close hidden panes.
2. A PTY exit landing while the tab is PARKED reached only the parked
watcher's exit sidecar (hosts' onPtyExit requires a mounted
TerminalPane), which only disposed the watcher. The leaf's stale
binding then reattached on reveal and the daemon re-created the
exited session id as a fresh shell — silent pane resurrection. The
sidecar now collapses the dead leaf out of the stored layout via
detachTerminalLayoutLeaf (the observed-exit teardown's data half).
New e2e suite terminal-pane-close-layout-consistency.spec.ts sweeps
close/shell-exit at every hidden/park lifecycle phase and asserts
leaves(root) == bindings == live panes; all 7 scenarios pass. Unit
regressions added for both fixes.
Co-authored-by: Orca <help@stably.ai>
* Harden terminal delivery and snapshot recovery
Co-authored-by: Orca <help@stably.ai>
* Fix inherited lint failures
Co-authored-by: Orca <help@stably.ai>
* Align merged runtime recovery tests
Co-authored-by: Orca <help@stably.ai>
---------
Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>
Co-authored-by: Neil <neil@stably.ai>
Co-authored-by: Orca <help@stably.ai>
31 KiB
Terminal Performance Initiative
Working plan for the orca-performance branch. Goal: make Orca's terminal as
performant as the architecture allows, with every claim backed by a number.
Started 2026-07-02.
Why (user-reported, from the team meeting)
- Typing in the terminal is sometimes laggy — occasionally seconds of delay.
- Users say the terminal is slower than iTerm (unclear if typing or scrolling).
- Scrolling in Claude Code / OpenCode is slow.
- Idle memory is high (1–2 GB).
- Battery usage is high.
Goals: legit performance complaints ≤ 1/week; sampled P90 typing/scrolling latency down significantly; lower memory with 0–1 agents.
Ground truth (verified against source, 2026-07-02)
Research corpus: xterm.js 6 / VS Code / Ghostty internals study (verified file:line claims) — see the archived digest and the "xterm.js vs Ghostty" deep-dive. The Orca-specific findings below were re-verified against this repo's code:
- Electron main sits on every terminal byte's path (daemon → main → renderer). VS Code ships the same xterm.js but bypasses main entirely: its ptyHost is a UtilityProcess with a direct MessagePort to each renderer.
- The PTY producer is never paused.
acknowledgeDataEventis a no-op in bothLocalPtyProviderandDaemonPtyAdapter. Only main→renderer delivery is watermarked (512 KB,src/main/ipc/pty.ts:1374); main's own buffer can grow toward a 512 MB cap under flood. VS Code pauses the actual pty at 100k unacked chars (kernel backpressure blocks the shell). - Renderer terminals share one thread with the entire React app; xterm.js parses in 12 ms slices at a documented 5–35 MB/s ceiling.
- Renderer scrollback default is 5,000 rows (
src/shared/terminal-scrollback-policy.ts), 5× VS Code's default; 12 B/cell plus per-line JS objects; O(all lines) reflow on column resize. - Latency physics: Ghostty ~4 ms median keypress latency, VS Code ~31 ms (same-library reference), native class 5–10 ms. Realistic target: beat VS Code, close on iTerm2, eliminate the stall/jank class entirely (P99 dominates perception).
Current state
Branch orca-performance (long-lived testing line, from main @ 8e8a08ac7):
tools/benchmarks/terminal-pipeline-bench.mjs— cross-terminal rig (see Benchmark protocol below).- Merge of PR #7153 = #7150 (freeze/memory: backlog caps, wedge guards,
probe-certified replay release) + #7139 (cooperative drain: paced backlog
draining keeps typing responsive under floods). Post-merge on this base:
pnpm typecheckclean, 626 targeted tests green (scheduler, guards, pty/pty-connection/pty-transport suites). #7153 itself is a disposable testing PR; #7139 and #7150 land separately on main.
Workstreams
1. Baseline benchmarks (now; human-in-terminal required)
Run the rig in each terminal on the same machine — Orca pane, iTerm2, Ghostty, Terminal.app, VS Code (T3Code if available):
node tools/benchmarks/terminal-pipeline-bench.mjs --label <machine>-<date>
node tools/benchmarks/terminal-pipeline-bench.mjs report
These numbers answer "are we actually slower than iTerm, and where," and are the before/after for everything below.
2. Validate #7153 on orca-performance (this week, extended testing)
Watch for: typing responsiveness under agent floods, bounded memory, skip-notice + snapshot repaint on overflow, no permanent input loss. When validated, land #7139 and #7150 as separate PRs on main.
3. Revive term-speed-2 (the headline structural work)
History: nwparker's ~38-branch chain (+20k lines) implementing the terminal
model/view contract — hidden view parking, hidden delivery gate, side-effect
authority in main, model query authority, skip-grammar deletion — all
kill-switched, documented in
origin/nwparker/term-speed-2-architecture-docs:docs/reference/terminal-model-view-contract.md.
It shipped only in v1.4.78-rc.1, a deliberate personal-testing build; it was
never rejected and never reached main. Directly targets complaints 3–5
(hidden panes stop receiving bytes and unmount their xterm + WebGL atlases).
Merge scout (2026-07-02, chain tip into orca-performance): 144 files, 34
conflicted, 115 hunks. Hotspots: pty-connection.ts (31), pty.ts (16),
daemon-pty-adapter.ts (6), orca-runtime.ts (5).
pane-terminal-output-scheduler.ts does NOT conflict — #7139/#7150 and the
chain touch different layers; runtime interaction (drain pacing × hidden
gate) still needs deliberate testing.
Execution: dedicated focused session; resolve on revive/term-speed-2 off
orca-performance; keep both sides' kill switches; validate with typecheck +
the contract tests listed in the model-view-contract doc + #7153's suites;
merge back to orca-performance for extended testing. Estimated ~1 day of
careful resolution + validation.
4. Remaining stall-bug fixes (parallel, independently shippable)
The "seconds of delay" class = discrete thread-blocking events, not steady-state latency:
- PR #7105 (open): skip synchronous cold-restore replay for live daemon sessions in doSpawn.
SerializeAddon.serialize()audit: ~1.2 s renderer block at 50k scrollback rows (#5096 follow-up, never done). Call sites include the mobile snapshot path (pty-connection.ts:2861) and sleep/hibernate serialization.- #2836 frozen-terminal leads: replay-guard latch, codex-stale gate, uncapped buffers (repro harness exists).
- Checkpoint-RPC main-thread scrub (measured ~2–10 ms bursts per hot 5 s tick; small, part of the same program).
5. Producer-side PTY flow control
Ack-driven pause/resume of the actual PTY through the daemon protocol (node-pty supports it), watermarks per the xterm.js flow-control guide (≤500 KB). Converts flood-induced buffered lag into shell blocking — the correct physics. Sequence after #7139 lands (interacts with its drain pacing).
Design (2026-07-03, implement after the term-speed-2 revival merges — same files):
- Signal source: main already tracks per-pty pending + in-flight
(
pendingData,rendererInFlightCharsByPtyinipc/pty.ts). When a pty's pending exceeds HIGH (256 KB), main asks the producer to pause; below LOW (32 KB), resume. - Producer side: two new protocol notifications (
pausePty/resumePty, protocol vNext, version-gated likesupportsIncrementalCheckpoints); daemonSessioncalls node-ptypause()/resume()— stops reading the pty fd, kernel buffer fills, the shell blocks on write: true kernel backpressure, identical physics to VS Code's 100k/5k design.LocalPtyProvidercalls pause/resume directly. - Safety invariants: (1) failsafe auto-resume after 5 s regardless of watermark, so a lost resume can never wedge a shell; (2) resume on detach/exit/kill/daemon-reconnect; (3) pause must not suppress the interactive-echo bypass — with the pipeline fixed (11.5 MB/s dev), the HIGH watermark is only reachable during genuine floods where echo is already queued; (4) PTY reads never stop for model/tail ingestion (term-speed-2 invariant #1) — pause gates the fd read, so daemon-side emulator state pauses with it, which is correct (state = what was read).
- Tests: watermark transition unit tests, lost-resume failsafe, kill/exit
cleanup, plus an e2e pressure scenario asserting bounded main memory and
a blocked producer (
yesexits promptly on SIGINT while paused).
6. Extend the measurement rig
- True keypress→pixel latency: Typometer manual protocol (the DSR probe stops at the parser reply, before paint).
- Idle memory + battery: per-process RSS breakdown +
powermetricssampling at 0/1/5 agents (goal-3 metric). - FPS under flood; event-loop-delay probes (
monitorEventLoopDelay) in main/daemon/renderer behind a debug flag for pipeline attribution.
7. utilityProcess terminal router (structural endgame; gated on data)
An Electron UtilityProcess owns the daemon socket and hands each renderer a MessagePort — VS Code's topology while keeping Orca's detached daemon (warm reattach). Takes main off the terminal data path entirely; daemon-side history persistence falls out naturally. Prototype only after baselines show how much tail latency lives in the main hop.
8. Production P90 telemetry
Sampled keypress→echo latency + long-task/stall counts from real users; defines the success criterion and becomes the permanent regression gate. Design after the local rig stabilizes so the metrics match.
Benchmark protocol
tools/benchmarks/terminal-pipeline-bench.mjs measures, from inside any
terminal:
- DSR idle latency — ESC[6n round trips (p50/p90/p99); replies come only after the parser reaches the query, so it proxies the input pipeline without keystroke injection.
- Fenced throughput — 4 deterministic fixtures (
ascii-log,cjk-emoji,agent-tui— Claude-Code-shaped transcript + DEC-2026 status repaints — and labeled-pathologicalstyles-stress), each run ended by a DSR fence so xterm.js-class ingest queues can't flatter the result. - DSR under load — latency sampled during a paced 1 MB/s agent-TUI stream: "typing while the agent works," quantified.
Rules: same machine, AC power, comparable window size, no tmux/screen, hands off the keyboard during runs. Never compare numbers across machines.
Sequencing
now: [1] baselines [2] #7153 testing (parallel)
next: [3] term-speed-2 revival (dedicated session)
parallel: [4] stall fixes, [6] rig extensions
after 2/3: [5] flow control
gated: [7] utility router [8] telemetry
BMW-group crash work remains the team's priority gate above all of this (#7150's wedge guards overlap it); this plan runs measurement and revival prep in parallel without displacing it.
Findings log
2026-07-02 — baseline + decomposition (results committed in tools/benchmarks/results/)
Same machine, unattended serial runs (Orca 1.4.91 prod, Terminal.app, Ghostty 1.3.1; iTerm2 not installed, VS Code pending):
| metric | Orca prod | Terminal.app | Ghostty |
|---|---|---|---|
| DSR idle p50/p99 (ms) | 0.69 / 22.7 | 0.35 / 0.68 | 0.19 / 0.72 |
| DSR under 1 MB/s agent load p50/p99 (ms) | 134 / 292 | 0.45 / 7.9 | 0.21 / 6.1 |
| agent-tui fenced throughput | 2.0 MB/s | 37 | 78 |
| ascii-log fenced throughput | 13 MB/s | 39 | 93 |
Decomposition of the 51× agent-tui gap — both pipeline ends are fast:
- Bare
@xterm/headless(114×85, scrollback 5000): agent-tui 103 MB/s (terminal-headless-parse-bench.mjs). The xterm parser is not the problem. - Daemon
Sessioningest (emulator + pending-output recording + fanout): agent-tui 103 MB/s (session-ingest-throughput.bench.test.ts,ORCA_TERMINAL_PERF_BENCH=1). The daemon is not the problem.
Conclusions: (1) idle latency is fine — the extra process hop costs ~0.5 ms, so the utilityProcess router is deprioritized by data; (2) the crisis is queueing between daemon egress and renderer parse completion — main per-chunk processing, the 512 KB delivery/ACK pacing (ACKs fire after renderer write callbacks, so renderer slowness throttles delivery multiplicatively), and renderer per-chunk layers above xterm; (3) the agent-TUI shape (DEC-2026 frames + erase/repaint) is 6.5× worse than plain text inside Orca while being equal-cost everywhere else — profile it in the renderer first (task #9).
2026-07-02 — dev-build check of #7139/#7150 (confounded; directional only)
Dev build of orca-performance (282-col window, 3MB fixtures, dev-mode
overhead): DSR idle p50 0.64 ms (unchanged), DSR under load p50 161 ms —
the cooperative-drain branch does not move the under-load class. In
hindsight this is structural: DSR replies are ordered within the output
stream, so the metric measures output-queue depth; #7139 paces draining to
protect input-send responsiveness but cannot reorder the queue. Implications:
(1) the 134 ms-class number is fixed only by shrinking the queue (producer
flow control) or raising drain rate (the 51× throughput hunt); (2) #7153's
own wins (freeze class, bounded memory, input-loss guards) must be validated
with freeze scenarios and real typing, not DSR. Also learned: dev-mode runs
are ~2× slower across the board and fences need --dsr-timeout-ms headroom.
2026-07-02 — 51× loss attributed: scheduler fixed-nap drip (task #9)
The renderer output scheduler (pane-terminal-output-scheduler.ts) drained
at most 2×16KB per tick, then slept 4ms (high-priority) / 16ms (background)
regardless of parse speed. Isolation bench (fake timers, instant-parse
terminal — pane-terminal-output-scheduler-throughput.bench.test.ts,
ORCA_TERMINAL_PERF_BENCH=1): background cadence = 1.9 MB/s — matching
prod's measured 2.0 MB/s agent-tui ceiling; foreground = 27 MB/s (only
when arrivals re-poke 0ms drains; Chromium's ~4ms timer clamp makes the
sustained real-world HP ceiling ~8 MB/s). Classification: pty-connection's
isLatencySensitiveForegroundOutput routes sizable no-recent-input chunks
to the queue, so floods always ride the drip.
Fix (committed 9e8bb2243): high-priority drains are now parse-clocked —
a pacer re-arms a 0ms drain when xterm's write callback confirms the batch
parsed — and carry 8 writes/tick (128KB ≈ 1.3ms parse). Isolation ceiling:
27 → 117.6 MB/s (parse-limited). Background cadence deliberately
unchanged (protects the focused pane; hidden panes are term-speed-2's job).
DRAIN_TIME_BUDGET_MS still bounds tick work (cooperative-drain intent of
#7139 preserved; its budget-yield test still passes). 621 tests green.
Open follow-ups from this attribution: (a) end-to-end dev verification (in
progress); (b) whether main's background:true delivery marking demotes
visible-pane floods to the background drip — check
window.__terminalOutputSchedulerDebug counters in a dev run; (c) ascii-log
gap (13 vs 83 MB/s headless) — likely per-chunk beforeWrite side-effect
scanning; profile after (a).
2026-07-03 — THE WHALE: main's retained-tail redraw path is O(tail) per chunk
Parse-clock fix didn't move end-to-end (agent-tui still 0.7 MB/s dev). Layered probes (renderer scheduler counters → main whole-method timer → per-section timers → targeted micro-benches) attributed it fully:
- Renderer receives only ~350–770 KB/s — it is starved, not slow.
OrcaRuntime.onPtyDataconsumes ~93% of main's event loop during the flood (~950 ms/s at ~450 chunks/s ≈ 2.1 ms/chunk).- All wrapped sub-calls (OSC scanners, agent detect, watchers, headless track, leaves loop, mobile touch) together: ~3.5%. The remainder is the pty-record tail block.
- Micro-bench (
appendNormalizedToTailBufferwith a real agent-TUI frame containingESC[10A ESC[0J): 0.888 ms/chunk at a 2,000-line tail — 32× the plain-append path. Cause:appendNormalizedToMultilineTailBuffermaterializes ~2,001 row objects per chunk (orca-runtime.ts:22324) andfinalizeRetainedTerminalRowsallocates them all again plus runs a trailing-whitespace regex per row (:22458) — ~4k allocations + 2k regexes per tiny chunk, twice the tail length in O(n) passes. Every Claude-Code frame (cursor-up + erase-below) takes this path; plain logs don't — which is exactly the measured agent-tui vs ascii asymmetry.
Chain: TUI flood → O(tail) work per chunk in main → main event loop saturates → daemon socket backpressures → renderer starved at ~0.4 MB/s → deep queue → 134 ms DSR-under-load.
Fix (in progress): run the existing algorithm on a lazy suffix window (the cursor's maximum upward reach, computed from the chunk) with the untouched prefix shared by reference; differential fuzz test proves output equality against the original implementation. Worst case (pathological full-height cursor-up) falls back to today's cost.
2026-07-03 — windowed-tail fix: partial end-to-end win; next suspect queued
Dev-build bench after the windowed redraw-tail fix (label dev-tailfix, same protocol as dev-parseclock): agent-tui 0.7 → 1.0 MB/s (+43%), DSR-under- load p50 161 → 108 ms, p99 624 → 154 ms (4×). Real movement for the first time, but the pipeline is still far from the renderer's 27–117 MB/s capacity — another main-side consumer remains hot.
Next cycle (exact recipe): re-apply the whole-method main probe
(onPtyDataMs sampler in pty.ts bindProviderListeners) on the fixed
build. If onPtyData still dominates, the remaining O(tail)/per-chunk
suspects in priority order: (1) buildTerminalWaitText ×2 per chunk (full
tail join, 0.116 ms/chunk in prod-node isolation — likely 2-4× that in
dev); (2) normalizeTerminalChunk (regex over every chunk, never measured);
(3) the per-leaf duplicate tail path when tailStateMatches fails. If
onPtyData no longer dominates, probe the main→renderer delivery batching
next. The probe/bench cycle is mechanical: relaunch dev
(ELECTRON_ENABLE_LOGGING=1 pnpm dev), orca-dev terminal create --command "<bench> --label X --size-mb 3 --dsr-timeout-ms 120000", grep the log.
2026-07-03 — post-fix attribution: blockedCheck is the remaining whale
Post-windowed-tail probe run (dev build, agent-tui): onPtyData still
~90% of main's event loop (~930 ms/s). Bucket split per second:
blockedCheck ≈ 700–790 ms (~85%), waitText ≈ 70, append ≈ 25 (windowed
fix confirmed), normalize ≈ 7, preview ≈ 0.
Mechanism (orca-runtime.ts:23128 nextTailHasNewerBlockedReason + its
callers): per chunk, TWO full wait texts are built (buildTerminalWaitText
joins the whole ≤256KB tail), then the check calls .toLowerCase() on both
(another ~512KB of string allocation per chunk) and runs multi-pattern
blocked/ready scans (findTerminalWaitBlockedSignal,
findKnownReadyPromptIndex — lastIndexOf/regex passes over the full text)
— all to timestamp waitBlockedAt for terminal wait.
Fix design (next session): blocked/ready prompts are end-anchored — an
actionable prompt is at the END of output. (1) Run the check on a bounded
suffix of the wait text (last ~64 lines / 16KB) instead of the full tail;
(2) cheap pre-filter: skip entirely unless the appended chunk (plus a small
carry for split keywords) can contain a blocked keyword; (3) build the two
wait texts only when the check runs. Verification mirrors the windowed-tail
pattern: keep the full-text check as reference + differential fuzz over
randomized tails/prompts (split-across-chunks cases included — the
appendCandidateSignal ordering semantics at :23146 must be preserved),
plus the terminal-wait contract tests. Expected effect: removes ~85% of
remaining onPtyData cost; combined with the two landed fixes should
finally unlock the pipeline toward the renderer's measured 27–117 MB/s.
2026-07-03 — pipeline unlocked: three stacked fixes, 16× throughput, 9× latency
Dev-build bench with all three fixes (parse-clocked drains 9e8bb2243,
windowed tail 4e08a28cd, throttled blocked-check 66f20258e), label
dev-blockedfix, same protocol/config as prior dev rows:
| metric | pre-fix dev | +tail fix | +blocked fix |
|---|---|---|---|
| agent-tui MB/s | 0.7 | 1.0 | 11.5 |
| DSR load p50/p99 (ms) | 161 / 624 | 108 / 154 | 18.8 / 24.9 |
| DSR idle p50/p99 (ms) | 0.95 / 21 | 1.09 / 18 | 0.52 / 8.6 |
| ascii-log MB/s | 6.4 | 4.7 | 9.6 |
The agent-TUI-specific penalty is gone (agent-tui ≈ cjk ≈ ascii now). The throttled blocked-check delivered the predicted ~85% cut. Dev mode carries ~2× overhead vs prod, so the prod build should land near ~10ms DSR-under- load — from the 134ms baseline (~13×) — pending a packaged-build rerun. Remaining floor is structural cadence (8ms daemon batch + 4ms HP drain ticks + xterm 12ms slices), which flow control (#6) does not target; re-evaluate the "within 10× of Terminal.app" goal line after a prod measurement. Next: term-speed-2 revival (#4), then flow control (#6).
2026-07-03 — term-speed-2 revival: merged, green, NOT yet mergeable (perf gate)
revive/term-speed-2 pushed (merge a5052c35f, tip 64b6f7abe): 144 files,
typecheck clean, ~2,776 targeted tests green, all three of our fixes
verified present, chain features present and kill-switched (subagent's
six review risks recorded in its report). Bench verdict on the revived
build (dev): DSR-load p50 ~19ms holds, but throughput regressed ~35%
unconditionally (agent-tui 11.5 → 7.2–7.4 MB/s; all-switches-OFF round
proved the kill switches are NOT the cost) and idle p50 doubled.
Attribution so far: main exonerated (whole-method probe: onPtyData ~60ms/s
≈ 6%); renderer reconcile + HP-first selection O(1)-checked; daemon
CONVICTED by unit bench — Session ingest 103 → 39.5/47.7 MB/s (2.2–2.6×)
on the revive branch (session-ingest-throughput.bench.test.ts,
ORCA_TERMINAL_PERF_BENCH=1). Cause: the chain's headless-emulator
restructure (scanner classes / query-reply forwarding / view-attribute
responder) added per-byte cost to the daemon hot path. Chunks reaching
main are now ~5.8KB vs ~650B (daemon emits slower, batches bigger).
NEXT (fast inner loop — pure unit bench, no app restarts): on
revive/term-speed-2, diff headless-emulator.ts/session.ts vs
7839fb9db, find the per-chunk scanner cost, restore our bounded-parser
fast paths (the daemon emulator must never pay per-byte JS scanning for
bytes that contain no ESC — same pre-filter pattern as the blocked-check
keyword bypass), verify with the ingest bench back at ~100 MB/s, then
full dev bench expecting blockedfix parity (~11.5 MB/s), THEN merge to
orca-performance. A residual renderer-side share is possible once the
daemon is fixed — re-attribute after.
Merge gate: revive branch merges only at ≥ blockedfix numbers.
RETRACTION (2026-07-03, later): the daemon conviction above was a confounded measurement — the 39–48 MB/s ingest runs executed while a dev app was still running. On a quiet machine the revive branch ingests at 82–109 MB/s (≈ pre-merge) and its HeadlessEmulator alone does 99.5 MB/s vs raw xterm 77.7. The daemon is innocent. Consequently the end-to-end revival delta (11.5 → 7.2/7.4 dev) is also UNTRUSTED — none of those runs were load-controlled, and unit benches show up to 2.6× machine-load variance. Scanner pre-filters landed anyway on revive (71c89da9b; strictly positive, 641 daemon tests green).
New measurement protocol (mandatory from here): quiet machine (no dev apps or benches concurrent), paired A/B runs back-to-back alternating branches, n≥2 per side, report spread not just p50. The merge-gate comparison (blockedfix vs revive) must be redone under this protocol before any verdict. Next: run the controlled A/B; if the delta disappears, merge revive into orca-performance and proceed to flow control (#6); if it persists, resume attribution renderer-side (probe pty-connection dataCallback additions per chunk).
2026-07-03 — A/B gate passed; term-speed-2 MERGED to orca-performance
Load-controlled alternating A/B (fresh app per run, n=2/side, agent-tui + DSR-load): perf 6.7/5.2 MB/s, dsr p50 19.9/21.3, p99 107.8/218.1; revive 6.1/3.6 MB/s, dsr p50 21.4/20.3, p99 63.4/26.1. Verdict: latency p50 tied, p99 better on revive, throughput within overlapping noise (revive2's 3.6 followed two runtime-busy create failures). The earlier "35% regression" is confirmed noise. Note: both branches ~5-7 MB/s today vs 11.5 yesterday — dev benches carry ~2x day-to-day machine variance; absolute dev numbers are only comparable within one A/B session.
Merged revive/term-speed-2 → orca-performance; typecheck clean, 288 post-merge spot tests green. orca-performance now = main-ish base + #7153
- three perf fixes + full term-speed-2 chain (kill-switched, default ON)
- scanner pre-filters. Extended user testing now covers everything. Remaining from the revival agent's risk list: gate×drain e2e specs (terminal-hidden-*, parked-memory, sleep-wake) still not run — queue them. Next: producer flow control (#6) per design §5; prod packaged-build bench for the real headline numbers.
2026-07-03 — flow control merged; goal-state accounting
Producer flow control merged to orca-performance (348aeb325): protocol
v19 pausePty/resumePty, 256KB/32KB watermarks on main's pendingData,
node-pty kernel backpressure, 5s daemon-side lost-resume failsafe +
main-side pause re-assert, resume on every teardown path, version-gated
(v≤18/SSH no-op), kill switch PRODUCER_FLOW_CONTROL_ENABLED
(ipc/pty.ts:143), 29 new tests. Typecheck + 292 post-merge spot tests
green.
Definition-of-done accounting:
- 51× loss: ATTRIBUTED AND FIXED (three fixes; agent-tui 0.7→11.5 MB/s and DSR-load p50 161→18.8 dev, results committed).
- term-speed-2: REVIVED AND MERGED (A/B gate passed).
- Flow control: IMPLEMENTED AND MERGED.
- "Within 10× of Terminal.app (4.5ms)": RE-SCOPED to pending a packaged RC measurement. Evidence: dev = 18.8ms with ~2× dev overhead → prod projection ~9-10ms ≈ 20× Terminal.app (vs 300× at baseline). The remaining gap is structural cadence (daemon 8ms batch, renderer drain ticks, xterm 12ms parse slices) — tunable follow-ups, distinct from the waste class this initiative eliminated. Prod verification path: electron-vite preview CANNOT host the bench (CLI-created panes are not adopted by the preview window's renderer → no ACKs → pending-cap drop; two attempts, documented) — measure on the next packaged RC cut from orca-performance using the committed rig + protocol instead.
Deferred, ordered: (1) sync orca-performance with main — conflicts
incl. stream-opcode collision (chain Ack=12 vs main's #7205-era
Metadata=12; renumber chain side, audit mobile/web stream consumers);
(2) chain's e2e specs (hidden parking / parked memory / sleep-wake) —
gate×drain risk; (3) cadence tuning toward the 10× line; (4) rig
extensions + P90 telemetry (tasks #3/#8).
2026-07-03 — PROD VERDICT: v1.4.121-rc.0 benchmarked (the headline numbers)
Same rig, same protocol, same machine as the 1.4.91 baseline:
| metric | 1.4.91 baseline | v1.4.121-rc.0 | change |
|---|---|---|---|
| DSR idle p50 | 0.69 ms | 0.44 ms | = Terminal.app (0.45) |
| DSR under load p50 | 134 ms | 18.6 ms | 7.2x |
| DSR under load p99 | 292 ms | 29.7 ms | 9.8x |
| agent-tui | 2.0 MB/s | 11.2 MB/s | 5.6x |
| styles-stress | 7.8 MB/s | 10.4 MB/s | 1.3x |
| ascii-log | 13 MB/s | 11.0 MB/s | ~0.85x |
| cjk-emoji | 15 MB/s | 12.2 MB/s | ~0.81x |
Reading: the anomalous TUI penalty is GONE — all four fixtures now sit at a uniform ~11-12 MB/s, which is the scheduler pacing ceiling, not parse CPU (prod ≈ dev for both latency and throughput; the pipeline is cadence-bound, so faster prod code changes nothing). That uniform cap also explains plain-text dipping slightly below baseline: ascii/cjk used to run unpaced ahead of the old scheduler; now everything flows through the same parse-clocked path. Goal line check: 18.6 ms = 41x Terminal.app under load (goal was 10x = 4.5 ms) — NOT met; down from 300x. Idle IS at parity. The remaining 4x is the named cadence stack (daemon 8 ms batch, scheduler drain ticks + 8x16KB per-tick budget, xterm 12 ms slices) — next lever, tunable, tracked as follow-up. p99 tail (the freeze class) is 29.7 ms — users cannot perceive it.
Caveat: measured on the user's live app (this session active in it); idle p99 118 ms reflects that activity, not the terminal path.
2026-07-03 — Same-engine reference: VS Code head-to-head (same machine, same rig)
| metric | Orca v1.4.121-rc.0 | VS Code | verdict |
|---|---|---|---|
| DSR idle p50 | 0.44 ms | 7.00 ms | Orca 16x faster |
| DSR load p50 | 18.6 ms | 7.18 ms | VS Code 2.6x faster |
| DSR load p99 | 29.7 ms | 43.4 ms | Orca 1.5x better tail |
| ascii-log | 11.0 MB/s | 9.0 | Orca +22% |
| cjk-emoji | 12.2 | 11.3 | tie |
| agent-tui | 11.2 | 11.7 | tie |
| styles-stress | 10.4 MB/s | 2.0 | Orca 5.2x |
Orca now beats or ties the best-known xterm.js terminal on 5 of 6 metrics — including 16x at idle (what users feel all day) and 5x on SGR-heavy output — and holds a better p99 tail under load. Throughput sits at the shared engine ceiling (~9-12 MB/s), confirming the class limit.
The one loss (load p50) has a clean mechanism: VS Code's producer flow control caps unacked output at ~100KB, so its standing queue is ~100KB / 11.7 MB/s ≈ 8.5 ms — matching its 7.18. Our standing queue (18.6 ms ≈ ~200KB at 11 MB/s) is set by the main→renderer ACK window (512KB/pty high water) + drain re-arm cadence (Chromium clamps nested setTimeout to ~4ms). Two levers, both cheap to test: (1) MessageChannel drain scheduling (sub-ms re-arm; also raises the throughput ceiling); (2) tighter effective in-flight window on the renderer delivery path. Target: VS Code's ~7ms class or below without giving back throughput.
2026-07-03 — Batch windows were the gap: dev DSR-load p50 19 -> 8.0ms
Lever results (dev, 3MB protocol, same session):
- MessageChannel drains (
2434dfaae): 19.01ms — NO change. Proved the ~19ms was NOT queue depth: at 1MB/s vs ~11MB/s capacity (9% util) there is no standing queue. Kept (correct, removes a real clamp). - Batch windows 8->2ms on BOTH hops (
e67a91d7a: daemon STREAM_DATA_BATCH_INTERVAL_MS + main PTY_BATCH_INTERVAL_MS): p50 8.00 / p90 10.13 / p99 12.26ms (from 19.01/22.7/28.1). Throughput unchanged (agent-tui 9.8 vs 9.1, ambient noise). 239 batcher+pty tests green after timing updates.
Dev-mode 8.0ms already matches VS Code prod (7.18); prod build should land BELOW VS Code. p99: ours 12.3 vs VS Code 43.4. The remaining fixed-latency terms are renderer/xterm-internal (12ms parse slices). Note: main's interactive bypass (input-gated) means real keystroke echo skips batching entirely — the DSR metric understates real typing responsiveness; VS Code measured on the same freight path, comparison fair.
Next: cut RC, confirm in prod, re-baseline vs Terminal.app (expect ~8-15x from 300x at baseline; goal line 10x = 4.5ms now plausibly in reach).
2026-07-03 — Chain e2e debt PAID: all 6 hidden-pane specs green
terminal-hidden-view-parking (parks + restores rich TUI on reveal; bell/ title side effects live while parked), terminal-sleep-wake-restore (output restored + input accepted after wake), terminal-parked-memory (renderer memory released on park; views retained when kill-switched off): 6/6 passed, electron-headless, 1.1m. The gate x drain interplay — the revival's top flagged risk — now has e2e coverage on the exact branch the RC ships from. Remaining garble-hardening: differential hide/reveal fuzz harness (next build), reveal-time seq diagnostics.
Success criteria (baseline-relative; finalize after task 1)
- DSR-under-load p90 in Orca within striking distance of iTerm2 on the same box; zero DSR timeouts (today's freeze class).
- Fenced agent-tui throughput ≥ VS Code on the same box.
- Idle RSS with 0–1 agents materially down (target set after the memory harness lands; hidden-pane parking is the main lever).
- Zero >100 ms event-loop stalls in main/renderer during a 10 MB flood.
- Production P90 typing latency down and monitored continuously.