Terminal performance initiative: pipeline fixes + term-speed-2 revival + PTY flow control (integration branch) (#7214)
* 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>
This commit is contained in:
co-authored by
Orca
Neil
Neil
parent
e1de59aaa8
commit
e84a8ddec9
@@ -1,34 +1,35 @@
|
||||
/**
|
||||
* Compatibility barrel for terminal-title agent detection — used by the main
|
||||
* process (stats collection), the renderer (activity indicators, unread
|
||||
* badges), and shared siblings.
|
||||
* Compatibility barrel for shared terminal agent-title detection.
|
||||
*
|
||||
* The implementation was split into domain modules in Phase 3 of the title
|
||||
* evidence work: identity/label detection → `terminal-title-agent-type`, status
|
||||
* classification → `terminal-title-status`, and display normalization →
|
||||
* `terminal-title-display`. This barrel is kept so the existing main/mobile/
|
||||
* renderer import paths that reference `agent-detection` stay stable.
|
||||
* Why shared: main and renderer both consume OSC titles for facts, stats, and
|
||||
* UI state. Keep existing imports stable while the implementation stays split
|
||||
* into focused modules that satisfy max-lines. (main's #7612 split into
|
||||
* `terminal-title-*` modules coexists — those files stay on disk for their
|
||||
* direct `resolveTerminalTitleAgentType`/`synthetic-agent-title` consumers.)
|
||||
*/
|
||||
|
||||
export { titleHasAgentName } from './agent-name-token-match'
|
||||
export type { AgentStatus } from './agent-title-core'
|
||||
export {
|
||||
isClaudeManagementTitle,
|
||||
isCursorNativeAgentTitle,
|
||||
isGeminiTerminalTitle,
|
||||
isPiTerminalTitle,
|
||||
STRONG_IDLE_KEYWORDS_RE,
|
||||
STRONG_WORKING_KEYWORDS_RE
|
||||
} from './agent-title-core'
|
||||
export { getAgentLabel, isClaudeAgent } from './agent-title-identity'
|
||||
export {
|
||||
clearWorkingIndicators,
|
||||
createAgentStatusTracker,
|
||||
detectAgentStatusFromTitle,
|
||||
normalizeTerminalTitle
|
||||
} from './agent-title-status'
|
||||
|
||||
// Re-export so existing `agent-detection` importers keep working.
|
||||
export { AGENT_NAMES, titleHasAgentName } from './agent-name-token-match'
|
||||
export {
|
||||
extractAllOscTitles,
|
||||
extractLastOscTitle,
|
||||
MAX_OSC_TITLE_CHARS
|
||||
} from './osc-title-extraction'
|
||||
export { isShellProcess } from './shell-process-detection'
|
||||
export {
|
||||
getAgentLabel,
|
||||
isClaudeAgent,
|
||||
isClaudeManagementTitle,
|
||||
isGeminiTerminalTitle,
|
||||
isPiTerminalTitle
|
||||
} from './terminal-title-agent-type'
|
||||
export type { AgentStatus } from './terminal-title-status'
|
||||
export {
|
||||
createAgentStatusTracker,
|
||||
detectAgentStatusFromTitle,
|
||||
STRONG_IDLE_KEYWORDS_RE,
|
||||
STRONG_WORKING_KEYWORDS_RE
|
||||
} from './terminal-title-status'
|
||||
export { clearWorkingIndicators, normalizeTerminalTitle } from './terminal-title-display'
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import {
|
||||
AGY_AGENT_NAME_RE,
|
||||
DROID_AGENT_NAME_RE,
|
||||
HERMES_AGENT_NAME_RE,
|
||||
titleHasAgentName,
|
||||
titleHasAnyLegacyAgentName
|
||||
} from './agent-name-token-match'
|
||||
import { isLegacyPiCompatibleTitle } from './pi-compatible-synthetic-title'
|
||||
|
||||
export { AGY_AGENT_NAME_RE, DROID_AGENT_NAME_RE, HERMES_AGENT_NAME_RE, titleHasAgentName }
|
||||
|
||||
export type AgentStatus = 'working' | 'permission' | 'idle'
|
||||
|
||||
export const CLAUDE_IDLE = '\u2733' // ✳
|
||||
const CLAUDE_COMMAND_RE = String.raw`(?:.*[\\/])?claude(?:\.(?:exe|cmd|bat|ps1))?`
|
||||
export const CLAUDE_MANAGEMENT_TITLE_RE = new RegExp(
|
||||
String.raw`^\s*(?:"${CLAUDE_COMMAND_RE}"|'${CLAUDE_COMMAND_RE}'|${CLAUDE_COMMAND_RE})\s+agents\s*$`,
|
||||
'i'
|
||||
)
|
||||
|
||||
export const GEMINI_WORKING = '\u2726' // ✦
|
||||
export const GEMINI_SILENT_WORKING = '\u23f2' // ⏲
|
||||
export const GEMINI_IDLE = '\u25c7' // ◇
|
||||
export const GEMINI_PERMISSION = '\u270b' // ✋
|
||||
|
||||
const STRONG_IDLE_KEYWORDS = ['ready', 'idle', 'done'] as const
|
||||
const STRONG_WORKING_KEYWORDS = ['working', 'thinking', 'running'] as const
|
||||
|
||||
// Why: plain `\b` matches inside hyphenated tokens and cwd paths such as
|
||||
// "~/codex/ready"; the left side also blocks path separators for Windows/Unix.
|
||||
export const STRONG_IDLE_KEYWORDS_RE = new RegExp(
|
||||
`(?<![\\w./\\\\-])(${STRONG_IDLE_KEYWORDS.join('|')})(?![\\w\\-])`,
|
||||
'i'
|
||||
)
|
||||
|
||||
// Why: mirrors the idle matcher so titles like "reworking" or
|
||||
// "is-thinking-cap" do not drive false active-agent UI.
|
||||
export const STRONG_WORKING_KEYWORDS_RE = new RegExp(
|
||||
`(?<![\\w./\\\\-])(${STRONG_WORKING_KEYWORDS.join('|')})(?![\\w\\-])`,
|
||||
'i'
|
||||
)
|
||||
|
||||
export const STRONG_WORKING_KEYWORDS_RE_GLOBAL = new RegExp(STRONG_WORKING_KEYWORDS_RE.source, 'gi')
|
||||
|
||||
export const CURSOR_NATIVE_TITLE_LOWER = 'cursor agent'
|
||||
|
||||
// eslint-disable-next-line no-control-regex -- intentional unicode range
|
||||
export const BRAILLE_SPINNER_RE = /[\u2800-\u28ff]/g
|
||||
|
||||
export function isGeminiTerminalTitle(title: string): boolean {
|
||||
// Why: Gemini OSC glyphs are stronger evidence than any cwd/session text.
|
||||
if (
|
||||
title.includes(GEMINI_PERMISSION) ||
|
||||
title.includes(GEMINI_WORKING) ||
|
||||
title.includes(GEMINI_SILENT_WORKING) ||
|
||||
title.includes(GEMINI_IDLE)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
// Why: Pi/OMP titles include cwd/session text; substring matching made
|
||||
// paths like "gemini-project" masquerade as Gemini CLI.
|
||||
if (isPiAgentTitle(title)) {
|
||||
return false
|
||||
}
|
||||
return titleHasAgentName(title, 'gemini')
|
||||
}
|
||||
|
||||
export function isPiTerminalTitle(title: string): boolean {
|
||||
return isLegacyPiCompatibleTitle(title) && !containsBrailleSpinner(title)
|
||||
}
|
||||
|
||||
export function isPiAgentTitle(title: string): boolean {
|
||||
return isLegacyPiCompatibleTitle(title)
|
||||
}
|
||||
|
||||
export function containsBrailleSpinner(title: string): boolean {
|
||||
for (const char of title) {
|
||||
const codePoint = char.codePointAt(0)
|
||||
if (codePoint !== undefined && codePoint >= 0x2800 && codePoint <= 0x28ff) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function containsLegacyAgentName(title: string): boolean {
|
||||
return titleHasAnyLegacyAgentName(title)
|
||||
}
|
||||
|
||||
export function containsAgentName(title: string): boolean {
|
||||
return (
|
||||
containsLegacyAgentName(title) ||
|
||||
AGY_AGENT_NAME_RE.test(title) ||
|
||||
DROID_AGENT_NAME_RE.test(title) ||
|
||||
HERMES_AGENT_NAME_RE.test(title)
|
||||
)
|
||||
}
|
||||
|
||||
export function containsAny(title: string, words: readonly string[]): boolean {
|
||||
const lower = title.toLowerCase()
|
||||
return words.some((word) => lower.includes(word))
|
||||
}
|
||||
|
||||
export function isClaudeManagementTitle(title: string): boolean {
|
||||
return CLAUDE_MANAGEMENT_TITLE_RE.test(title)
|
||||
}
|
||||
|
||||
export function isCursorNativeAgentTitle(title: string): boolean {
|
||||
return title.trim().toLowerCase() === CURSOR_NATIVE_TITLE_LOWER
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import {
|
||||
AGY_AGENT_NAME_RE,
|
||||
CLAUDE_IDLE,
|
||||
DROID_AGENT_NAME_RE,
|
||||
HERMES_AGENT_NAME_RE,
|
||||
containsBrailleSpinner,
|
||||
isClaudeManagementTitle,
|
||||
isGeminiTerminalTitle,
|
||||
isPiAgentTitle,
|
||||
titleHasAgentName
|
||||
} from './agent-title-core'
|
||||
import { getPiCompatibleSyntheticAgentLabel } from './pi-compatible-synthetic-title'
|
||||
|
||||
/**
|
||||
* Returns true when the terminal title matches Claude Code's title conventions.
|
||||
* Used to scope prompt-cache-timer behavior to Claude sessions only.
|
||||
*/
|
||||
export function isClaudeAgent(title: string): boolean {
|
||||
if (!title || isClaudeManagementTitle(title)) {
|
||||
return false
|
||||
}
|
||||
const lower = title.toLowerCase()
|
||||
|
||||
// Why: Claude title prefixes are stronger than task text, which can mention
|
||||
// other agents without changing the owning CLI.
|
||||
if (title.startsWith(`${CLAUDE_IDLE} `) || title === CLAUDE_IDLE) {
|
||||
return true
|
||||
}
|
||||
if (title.startsWith('. ') || title.startsWith('* ')) {
|
||||
return true
|
||||
}
|
||||
if (containsBrailleSpinner(title)) {
|
||||
return !lower.includes('cursor') && !lower.includes('openclaude')
|
||||
}
|
||||
|
||||
const trimmedTitle = title.trimStart()
|
||||
return (
|
||||
trimmedTitle.toLowerCase().startsWith('claude') && titleHasAgentName(trimmedTitle, 'claude')
|
||||
)
|
||||
}
|
||||
|
||||
export function getAgentLabel(title: string): string | null {
|
||||
if (isClaudeManagementTitle(title)) {
|
||||
return null
|
||||
}
|
||||
// Why: Claude task titles can mention another CLI; the prefix is the identity
|
||||
// signal, not arbitrary task text.
|
||||
if (
|
||||
title.startsWith(`${CLAUDE_IDLE} `) ||
|
||||
title === CLAUDE_IDLE ||
|
||||
title.startsWith('. ') ||
|
||||
title.startsWith('* ')
|
||||
) {
|
||||
return 'Claude Code'
|
||||
}
|
||||
if (isGeminiTerminalTitle(title)) {
|
||||
return 'Gemini CLI'
|
||||
}
|
||||
// Why: Pi-compatible synthetic titles can carry braille spinners, which the
|
||||
// generic agent-title heuristics would otherwise claim first.
|
||||
const piCompatibleSyntheticAgentLabel = getPiCompatibleSyntheticAgentLabel(title)
|
||||
if (piCompatibleSyntheticAgentLabel) {
|
||||
return piCompatibleSyntheticAgentLabel
|
||||
}
|
||||
if (isPiAgentTitle(title)) {
|
||||
return 'Pi'
|
||||
}
|
||||
|
||||
if (titleHasAgentName(title, 'codex')) {
|
||||
return 'Codex'
|
||||
}
|
||||
if (titleHasAgentName(title, 'openclaude')) {
|
||||
return 'OpenClaude'
|
||||
}
|
||||
if (titleHasAgentName(title, 'copilot')) {
|
||||
return 'GitHub Copilot'
|
||||
}
|
||||
if (titleHasAgentName(title, 'grok')) {
|
||||
return 'Grok'
|
||||
}
|
||||
if (titleHasAgentName(title, 'devin')) {
|
||||
return 'Devin'
|
||||
}
|
||||
if (titleHasAgentName(title, 'antigravity') || AGY_AGENT_NAME_RE.test(title)) {
|
||||
return 'Antigravity'
|
||||
}
|
||||
if (titleHasAgentName(title, 'opencode')) {
|
||||
return 'OpenCode'
|
||||
}
|
||||
if (titleHasAgentName(title, 'mimo')) {
|
||||
return 'MiMo Code'
|
||||
}
|
||||
if (titleHasAgentName(title, 'aider')) {
|
||||
return 'Aider'
|
||||
}
|
||||
// Why: match explicit names before Claude's generic braille heuristic.
|
||||
if (titleHasAgentName(title, 'cursor')) {
|
||||
return 'Cursor'
|
||||
}
|
||||
if (DROID_AGENT_NAME_RE.test(title)) {
|
||||
return 'Droid'
|
||||
}
|
||||
if (HERMES_AGENT_NAME_RE.test(title)) {
|
||||
return 'Hermes'
|
||||
}
|
||||
if (isClaudeAgent(title)) {
|
||||
return 'Claude Code'
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import {
|
||||
AGY_AGENT_NAME_RE,
|
||||
BRAILLE_SPINNER_RE,
|
||||
CLAUDE_IDLE,
|
||||
CURSOR_NATIVE_TITLE_LOWER,
|
||||
DROID_AGENT_NAME_RE,
|
||||
GEMINI_IDLE,
|
||||
GEMINI_PERMISSION,
|
||||
GEMINI_SILENT_WORKING,
|
||||
GEMINI_WORKING,
|
||||
HERMES_AGENT_NAME_RE,
|
||||
STRONG_IDLE_KEYWORDS_RE,
|
||||
STRONG_WORKING_KEYWORDS_RE,
|
||||
STRONG_WORKING_KEYWORDS_RE_GLOBAL,
|
||||
containsAgentName,
|
||||
containsAny,
|
||||
containsBrailleSpinner,
|
||||
containsLegacyAgentName,
|
||||
isClaudeManagementTitle,
|
||||
isGeminiTerminalTitle,
|
||||
isPiAgentTitle,
|
||||
isPiTerminalTitle
|
||||
} from './agent-title-core'
|
||||
import type { AgentStatus } from './agent-title-core'
|
||||
import { getPiCompatibleSyntheticAgentStatus } from './pi-compatible-synthetic-title'
|
||||
import { isGrokRotatingWorkingTitle } from './terminal-title-agent-type'
|
||||
|
||||
/**
|
||||
* Strip working-status indicators so stale exit titles stop reporting working.
|
||||
*/
|
||||
export function clearWorkingIndicators(title: string): string {
|
||||
let cleaned = title
|
||||
|
||||
cleaned = cleaned.replace(GEMINI_WORKING, '')
|
||||
cleaned = cleaned.replace(GEMINI_SILENT_WORKING, '')
|
||||
cleaned = cleaned.replace(BRAILLE_SPINNER_RE, '')
|
||||
if (cleaned.startsWith('. ')) {
|
||||
cleaned = cleaned.slice(2)
|
||||
}
|
||||
if (containsAgentName(cleaned)) {
|
||||
cleaned = cleaned.replace(STRONG_WORKING_KEYWORDS_RE_GLOBAL, '')
|
||||
}
|
||||
|
||||
cleaned = cleaned.replace(/\s{2,}/g, ' ').trim()
|
||||
return cleaned || title
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks agent status transitions from terminal title changes.
|
||||
*/
|
||||
export function createAgentStatusTracker(
|
||||
onBecameIdle: (title: string) => void,
|
||||
onBecameWorking?: () => void,
|
||||
onAgentExited?: () => void,
|
||||
initialTitle?: string
|
||||
): {
|
||||
handleTitle: (title: string) => void
|
||||
seedTitle: (title: string) => void
|
||||
reset: () => void
|
||||
} {
|
||||
// Why: trackers restored mid-session need a last-known status without firing
|
||||
// callbacks, or a hidden working agent can miss its later idle transition.
|
||||
let lastStatus: AgentStatus | null =
|
||||
initialTitle !== undefined ? detectAgentStatusFromTitle(initialTitle) : null
|
||||
|
||||
return {
|
||||
handleTitle(title: string): void {
|
||||
const newStatus = detectAgentStatusFromTitle(title)
|
||||
if (lastStatus === 'working' && newStatus !== null && newStatus !== 'working') {
|
||||
onBecameIdle(title)
|
||||
}
|
||||
if (lastStatus !== 'working' && newStatus === 'working') {
|
||||
onBecameWorking?.()
|
||||
}
|
||||
// Why: reverting to a plain shell prompt after idle/permission means the
|
||||
// agent exited; while working it can just be a transient internal title.
|
||||
if (lastStatus !== null && lastStatus !== 'working' && newStatus === null) {
|
||||
lastStatus = null
|
||||
onAgentExited?.()
|
||||
}
|
||||
if (newStatus !== null) {
|
||||
lastStatus = newStatus
|
||||
}
|
||||
},
|
||||
seedTitle(title: string): void {
|
||||
lastStatus = detectAgentStatusFromTitle(title)
|
||||
},
|
||||
reset(): void {
|
||||
lastStatus = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize high-churn agent titles into stable display labels before storage.
|
||||
*/
|
||||
export function normalizeTerminalTitle(title: string): string {
|
||||
if (!title) {
|
||||
return title
|
||||
}
|
||||
|
||||
if (isGeminiTerminalTitle(title)) {
|
||||
const status = detectAgentStatusFromTitle(title)
|
||||
if (status === 'permission') {
|
||||
return `${GEMINI_PERMISSION} Gemini CLI`
|
||||
}
|
||||
if (status === 'working') {
|
||||
return `${GEMINI_WORKING} Gemini CLI`
|
||||
}
|
||||
if (status === 'idle') {
|
||||
return `${GEMINI_IDLE} Gemini CLI`
|
||||
}
|
||||
}
|
||||
|
||||
// Why: Pi animates every 80ms; collapse frames while preserving status.
|
||||
if (isPiAgentTitle(title)) {
|
||||
const status = detectAgentStatusFromTitle(title)
|
||||
if (status === 'working') {
|
||||
return '\u280b Pi'
|
||||
}
|
||||
if (status === 'idle') {
|
||||
return 'Pi'
|
||||
}
|
||||
}
|
||||
|
||||
// Why: Grok Build interpolates a rotating status/tool phrase between the
|
||||
// spinner and its name, so its working frames change the title many times per
|
||||
// turn. Collapse them to one stable label; idle/session titles carry no
|
||||
// spinner and pass through, so the meaningful final title still shows (#7863).
|
||||
if (isGrokRotatingWorkingTitle(title)) {
|
||||
return '\u280b Grok'
|
||||
}
|
||||
|
||||
return title
|
||||
}
|
||||
|
||||
export function detectAgentStatusFromTitle(title: string): AgentStatus | null {
|
||||
if (!title || isClaudeManagementTitle(title)) {
|
||||
return null
|
||||
}
|
||||
if (title.trim().toLowerCase() === CURSOR_NATIVE_TITLE_LOWER) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (title.includes(GEMINI_PERMISSION)) {
|
||||
return 'permission'
|
||||
}
|
||||
if (title.includes(GEMINI_WORKING) || title.includes(GEMINI_SILENT_WORKING)) {
|
||||
return 'working'
|
||||
}
|
||||
if (title.includes(GEMINI_IDLE)) {
|
||||
return 'idle'
|
||||
}
|
||||
|
||||
// Why: resolve synthetic Pi/OMP permission/idle labels before the broader
|
||||
// Pi and braille-spinner checks below.
|
||||
const piCompatibleSyntheticAgentStatus = getPiCompatibleSyntheticAgentStatus(title)
|
||||
if (piCompatibleSyntheticAgentStatus) {
|
||||
return piCompatibleSyntheticAgentStatus
|
||||
}
|
||||
|
||||
if (title.startsWith(`${CLAUDE_IDLE} `) || title === CLAUDE_IDLE) {
|
||||
return 'idle'
|
||||
}
|
||||
if (isPiTerminalTitle(title)) {
|
||||
return 'idle'
|
||||
}
|
||||
if (containsBrailleSpinner(title)) {
|
||||
return 'working'
|
||||
}
|
||||
|
||||
const hasDroidAgentName = DROID_AGENT_NAME_RE.test(title)
|
||||
const hasHermesAgentName = HERMES_AGENT_NAME_RE.test(title)
|
||||
const hasAgyAgentName = AGY_AGENT_NAME_RE.test(title)
|
||||
const hasLegacyAgentName = containsLegacyAgentName(title)
|
||||
if (!hasLegacyAgentName && !hasDroidAgentName && !hasHermesAgentName && !hasAgyAgentName) {
|
||||
return null
|
||||
}
|
||||
if (containsAny(title, ['action required', 'permission', 'waiting'])) {
|
||||
return 'permission'
|
||||
}
|
||||
// Why: boundary-aware regexes avoid cwd/path and substring false positives.
|
||||
if (STRONG_IDLE_KEYWORDS_RE.test(title)) {
|
||||
return 'idle'
|
||||
}
|
||||
if (STRONG_WORKING_KEYWORDS_RE.test(title)) {
|
||||
return 'working'
|
||||
}
|
||||
if (title.startsWith('. ')) {
|
||||
return 'working'
|
||||
}
|
||||
if (title.startsWith('* ')) {
|
||||
return 'idle'
|
||||
}
|
||||
|
||||
// Why: Droid hook events are authoritative; native name-only titles should
|
||||
// not turn a still-sleeping execute tool into completion.
|
||||
if (hasDroidAgentName && !hasLegacyAgentName) {
|
||||
return null
|
||||
}
|
||||
|
||||
return 'idle'
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
// Seeded ANSI byte-stream generator for the terminal garble differential
|
||||
// fuzz suites (headless-emulator-fidelity.fuzz.test.ts and
|
||||
// hidden-reveal-reconciliation.fuzz.test.ts). The op mix models real agent
|
||||
// TUI output (Claude Code / Codex): CR status-line redraws, cursor-up panel
|
||||
// repaints, DEC 2026 synchronized frames, SGR color runs, wide CJK and ZWJ
|
||||
// emoji, wrapped long lines, alt-screen sessions, and scroll regions.
|
||||
//
|
||||
// Deliberately excluded ops (they would fuzz behavior the snapshot/restore
|
||||
// contract does not promise to preserve, so any diff would be noise, not a
|
||||
// garble bug):
|
||||
// - DECAWM (?7l) and IRM (CSI 4h): SerializeAddon does not re-emit them and
|
||||
// rehydrateSequences (headless-emulator.ts buildRehydrateSequences) only
|
||||
// covers alt-screen/bracketed-paste/app-cursor/mouse modes.
|
||||
// - Terminal queries (DA/DSR/DECRQM): the emulator is write-only by contract
|
||||
// (headless-emulator.ts onQueryReply gating); replies are a separate
|
||||
// authority problem with its own pinned tests (session.test.ts).
|
||||
|
||||
/** Same seeded PRNG as retained-tail-redraw-window.equivalence.test.ts. */
|
||||
export function mulberry32(seed: number): () => number {
|
||||
let a = seed >>> 0
|
||||
return () => {
|
||||
a = (a + 0x6d2b79f5) | 0
|
||||
let t = Math.imul(a ^ (a >>> 15), 1 | a)
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
|
||||
}
|
||||
}
|
||||
|
||||
export type AgentTuiStreamDims = { cols: number; rows: number }
|
||||
|
||||
export type AgentTuiStreamProfile = {
|
||||
/** Mouse-mode toggles require mirroring TerminalMouseModeMirror to build
|
||||
* rehydrate parity; the renderer-side fuzz cannot import that main-only
|
||||
* module (tsconfig.tc.web.json excludes src/main/daemon), so it opts out. */
|
||||
includeMouseModes: boolean
|
||||
/** OSC 8 hyperlinks mark their cells underlined in the xterm buffer, but
|
||||
* SerializeAddon never re-emits OSC 8 — production restores link ranges
|
||||
* out-of-band via snapshot.oscLinks (collectHeadlessOscLinkRanges), so
|
||||
* byte-replay fidelity legitimately drops that underline. The suites pin
|
||||
* the metadata compensation in a targeted test instead of fuzzing it. */
|
||||
includeOscHyperlinks: boolean
|
||||
opCount: number
|
||||
}
|
||||
|
||||
function int(rng: () => number, min: number, max: number): number {
|
||||
return min + Math.floor(rng() * (max - min + 1))
|
||||
}
|
||||
|
||||
function pick<T>(rng: () => number, values: readonly T[]): T {
|
||||
return values[Math.floor(rng() * values.length)]!
|
||||
}
|
||||
|
||||
const WORDS = [
|
||||
'reading',
|
||||
'src/main/daemon/session.ts',
|
||||
'tokens 12.4k',
|
||||
'esc to interrupt',
|
||||
'Thinking…',
|
||||
'bash: pnpm typecheck',
|
||||
'+142 -37',
|
||||
'PASS terminal.test.ts',
|
||||
'waiting for approval',
|
||||
'diff --git a/pty.ts'
|
||||
] as const
|
||||
|
||||
const WIDE_RUNS = [
|
||||
'你好世界',
|
||||
'터미널 상태 확인',
|
||||
'進捗を表示中',
|
||||
'🟢 working',
|
||||
'🤖 codex',
|
||||
'✅ done ✨',
|
||||
// ZWJ emoji join — the exact width divergence the Orca unicode provider
|
||||
// exists for (shared/terminal-unicode-provider.ts).
|
||||
'👨👩👧👦 team',
|
||||
'🇰🇷 locale'
|
||||
] as const
|
||||
|
||||
const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧'] as const
|
||||
|
||||
function sgr(rng: () => number): string {
|
||||
const roll = rng()
|
||||
if (roll < 0.2) {
|
||||
return `\x1b[${pick(rng, ['0', '1', '2', '3', '4', '7', '9', '22', '24', '39', '49'])}m`
|
||||
}
|
||||
if (roll < 0.55) {
|
||||
return `\x1b[${int(rng, 30, 37) + (rng() < 0.3 ? 60 : 0)}m`
|
||||
}
|
||||
if (roll < 0.8) {
|
||||
return `\x1b[38;5;${int(rng, 0, 255)}m`
|
||||
}
|
||||
return `\x1b[38;2;${int(rng, 0, 255)};${int(rng, 0, 255)};${int(rng, 0, 255)}m`
|
||||
}
|
||||
|
||||
function textRun(rng: () => number): string {
|
||||
const parts: string[] = []
|
||||
const count = int(rng, 1, 3)
|
||||
for (let i = 0; i < count; i++) {
|
||||
parts.push(rng() < 0.25 ? pick(rng, WIDE_RUNS) : pick(rng, WORDS))
|
||||
}
|
||||
return parts.join(' ')
|
||||
}
|
||||
|
||||
function styledLine(rng: () => number): string {
|
||||
return `${sgr(rng)}${textRun(rng)}\x1b[0m\r\n`
|
||||
}
|
||||
|
||||
function panelRedraw(rng: () => number, dims: AgentTuiStreamDims): string {
|
||||
const height = int(rng, 1, Math.min(6, dims.rows - 2))
|
||||
const lines: string[] = [`\x1b[${height}A\r`]
|
||||
if (rng() < 0.5) {
|
||||
lines.push('\x1b[0J')
|
||||
}
|
||||
for (let i = 0; i < height; i++) {
|
||||
lines.push(`\x1b[2K${sgr(rng)}│ ${textRun(rng)}\x1b[0m\r\n`)
|
||||
}
|
||||
return lines.join('')
|
||||
}
|
||||
|
||||
function statusLineRewrite(rng: () => number): string {
|
||||
return `\r\x1b[2K${sgr(rng)}${pick(rng, SPINNER)} ${textRun(rng)}\x1b[0m`
|
||||
}
|
||||
|
||||
function cursorMotion(rng: () => number, dims: AgentTuiStreamDims): string {
|
||||
const roll = rng()
|
||||
if (roll < 0.4) {
|
||||
return `\x1b[${int(rng, 1, dims.rows)};${int(rng, 1, dims.cols)}H`
|
||||
}
|
||||
if (roll < 0.55) {
|
||||
return `\x1b[${int(rng, 1, dims.cols)}G`
|
||||
}
|
||||
return `\x1b[${int(rng, 1, 4)}${pick(rng, ['A', 'B', 'C', 'D'] as const)}`
|
||||
}
|
||||
|
||||
function eraseOp(rng: () => number): string {
|
||||
return pick(rng, ['\x1b[K', '\x1b[1K', '\x1b[2K', '\x1b[0J', '\x1b[1J'] as const)
|
||||
}
|
||||
|
||||
function wrappedLongLine(rng: () => number, dims: AgentTuiStreamDims): string {
|
||||
const unit = `${textRun(rng)} `
|
||||
const repeats = Math.ceil((dims.cols * int(rng, 1, 3)) / Math.max(unit.length, 1)) + 1
|
||||
return `${sgr(rng)}${unit.repeat(repeats)}\x1b[0m\r\n`
|
||||
}
|
||||
|
||||
function scrollRegionBurst(rng: () => number, dims: AgentTuiStreamDims): string {
|
||||
const top = int(rng, 1, Math.max(1, dims.rows - 4))
|
||||
const bottom = int(rng, top + 1, dims.rows)
|
||||
const body: string[] = [`\x1b[${top};${bottom}r`, `\x1b[${bottom};1H`]
|
||||
for (let i = 0; i < int(rng, 1, 4); i++) {
|
||||
body.push(`${textRun(rng)}\r\n`)
|
||||
}
|
||||
body.push('\x1b[r')
|
||||
return body.join('')
|
||||
}
|
||||
|
||||
function altScreenFrame(rng: () => number, dims: AgentTuiStreamDims): string {
|
||||
const rows = int(rng, 2, Math.min(8, dims.rows))
|
||||
const body: string[] = ['\x1b[?1049h', '\x1b[2J\x1b[H', '\x1b[?25l']
|
||||
for (let i = 0; i < rows; i++) {
|
||||
body.push(`${sgr(rng)}│ ${textRun(rng)}\x1b[0m${i === rows - 1 ? '' : '\r\n'}`)
|
||||
}
|
||||
body.push(`\x1b[${int(rng, 1, dims.rows)};${int(rng, 1, dims.cols)}H\x1b[?25h`)
|
||||
if (rng() < 0.5) {
|
||||
body.push('\x1b[?1049l')
|
||||
}
|
||||
return body.join('')
|
||||
}
|
||||
|
||||
function synchronizedFrame(rng: () => number, dims: AgentTuiStreamDims): string {
|
||||
return `\x1b[?2026h${rng() < 0.5 ? panelRedraw(rng, dims) : statusLineRewrite(rng)}\x1b[?2026l`
|
||||
}
|
||||
|
||||
function savedCursorDetour(rng: () => number, dims: AgentTuiStreamDims): string {
|
||||
return `\x1b7${cursorMotion(rng, dims)}${sgr(rng)}${textRun(rng)}\x1b[0m\x1b8`
|
||||
}
|
||||
|
||||
function oscOp(rng: () => number, profile: AgentTuiStreamProfile): string {
|
||||
const roll = rng()
|
||||
if (roll < 0.5) {
|
||||
return `\x1b]0;${textRun(rng)}\x07`
|
||||
}
|
||||
if (roll < 0.8) {
|
||||
return profile.includeOscHyperlinks
|
||||
? `\x1b]8;;https://example.com/${int(rng, 1, 999)}\x07link\x1b]8;;\x07`
|
||||
: `https://example.com/pr/${int(rng, 1, 999)}\r\n`
|
||||
}
|
||||
return '\x1b]133;A\x07'
|
||||
}
|
||||
|
||||
function modeToggle(rng: () => number, profile: AgentTuiStreamProfile): string {
|
||||
const toggles = ['\x1b[?2004h', '\x1b[?2004l', '\x1b[?1h', '\x1b[?1l', '\x1b[?25l', '\x1b[?25h']
|
||||
if (profile.includeMouseModes) {
|
||||
toggles.push(
|
||||
'\x1b[?1000h',
|
||||
'\x1b[?1002h',
|
||||
'\x1b[?1003h',
|
||||
'\x1b[?1006h',
|
||||
'\x1b[?1000l',
|
||||
'\x1b[?1006l'
|
||||
)
|
||||
}
|
||||
return pick(rng, toggles)
|
||||
}
|
||||
|
||||
/** One seeded agent-TUI-shaped op. Weights favor the redraw ops that have
|
||||
* historically produced hidden-restore garble (CR rewrites, cursor-up panel
|
||||
* repaints, DEC 2026 frames, alt-screen churn). */
|
||||
function nextOp(
|
||||
rng: () => number,
|
||||
dims: AgentTuiStreamDims,
|
||||
profile: AgentTuiStreamProfile
|
||||
): string {
|
||||
const roll = rng()
|
||||
if (roll < 0.18) {
|
||||
return styledLine(rng)
|
||||
}
|
||||
if (roll < 0.32) {
|
||||
return statusLineRewrite(rng)
|
||||
}
|
||||
if (roll < 0.46) {
|
||||
return panelRedraw(rng, dims)
|
||||
}
|
||||
if (roll < 0.54) {
|
||||
return synchronizedFrame(rng, dims)
|
||||
}
|
||||
if (roll < 0.62) {
|
||||
return wrappedLongLine(rng, dims)
|
||||
}
|
||||
if (roll < 0.7) {
|
||||
return cursorMotion(rng, dims) + eraseOp(rng)
|
||||
}
|
||||
if (roll < 0.76) {
|
||||
return altScreenFrame(rng, dims)
|
||||
}
|
||||
if (roll < 0.82) {
|
||||
return scrollRegionBurst(rng, dims)
|
||||
}
|
||||
if (roll < 0.88) {
|
||||
return savedCursorDetour(rng, dims)
|
||||
}
|
||||
if (roll < 0.94) {
|
||||
return oscOp(rng, profile)
|
||||
}
|
||||
return modeToggle(rng, profile)
|
||||
}
|
||||
|
||||
export function buildAgentTuiStreamOps(
|
||||
rng: () => number,
|
||||
dims: AgentTuiStreamDims,
|
||||
profile: AgentTuiStreamProfile
|
||||
): string[] {
|
||||
const ops: string[] = []
|
||||
for (let i = 0; i < profile.opCount; i++) {
|
||||
ops.push(nextOp(rng, dims, profile))
|
||||
}
|
||||
return ops
|
||||
}
|
||||
|
||||
/** Splits a stream at random boundaries, including inside escape sequences
|
||||
* (PTY chunking does that constantly). Never splits a surrogate pair: PTY
|
||||
* bytes are decoded to complete code points before reaching JS strings. */
|
||||
export function splitIntoRandomChunks(
|
||||
rng: () => number,
|
||||
stream: string,
|
||||
bounds: { minLen: number; maxLen: number }
|
||||
): string[] {
|
||||
const chunks: string[] = []
|
||||
let cursor = 0
|
||||
while (cursor < stream.length) {
|
||||
let end = Math.min(stream.length, cursor + int(rng, bounds.minLen, bounds.maxLen))
|
||||
const boundaryCode = stream.charCodeAt(end - 1)
|
||||
if (end < stream.length && boundaryCode >= 0xd800 && boundaryCode <= 0xdbff) {
|
||||
end += 1
|
||||
}
|
||||
chunks.push(stream.slice(cursor, end))
|
||||
cursor = end
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createCommandCodeOutputStatusDetector } from './command-code-output-status'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('createCommandCodeOutputStatusDetector', () => {
|
||||
it('marks Command Code working with the submitted prompt when the TUI starts thinking', () => {
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: 'command-code --trust',
|
||||
onWorking
|
||||
})
|
||||
|
||||
expect(detector.observe('❯ Fix the yellow spinner\r\n\x1b[35m✻ Thinking...\x1b[0m')).toBe(true)
|
||||
|
||||
expect(onWorking).toHaveBeenCalledWith('Fix the yellow spinner')
|
||||
})
|
||||
|
||||
it('waits for the Command Code banner before trusting generic status text', () => {
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: null,
|
||||
onWorking
|
||||
})
|
||||
|
||||
expect(detector.observe('Thinking about unrelated shell output')).toBe(false)
|
||||
expect(detector.observe('# Command Code v0.27.2')).toBe(false)
|
||||
expect(detector.observe('⌘ Parsing...')).toBe(true)
|
||||
|
||||
expect(onWorking).toHaveBeenCalledWith('')
|
||||
})
|
||||
|
||||
it('detects the Command Code banner across PTY chunk boundaries', () => {
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: null,
|
||||
onWorking
|
||||
})
|
||||
|
||||
expect(detector.observe('# Command')).toBe(false)
|
||||
expect(detector.observe(' Code v0.27.2')).toBe(false)
|
||||
expect(detector.observe('⌘ Parsing...')).toBe(true)
|
||||
|
||||
expect(onWorking).toHaveBeenCalledWith('')
|
||||
})
|
||||
|
||||
it('detects the Command Code banner when ANSI styling splits the words', () => {
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: null,
|
||||
onWorking
|
||||
})
|
||||
|
||||
expect(detector.observe('# C\x1b[35mommand Co\x1b[0mde v0.27.2')).toBe(false)
|
||||
expect(detector.observe('⌘ Parsing...')).toBe(true)
|
||||
|
||||
expect(onWorking).toHaveBeenCalledWith('')
|
||||
})
|
||||
|
||||
it('does not trust near-miss Command Code banner text', () => {
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: null,
|
||||
onWorking
|
||||
})
|
||||
|
||||
expect(detector.observe('NotCommand CodeX\r\n⌘ Parsing...')).toBe(false)
|
||||
|
||||
expect(onWorking).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
'Pondering',
|
||||
'Contemplating',
|
||||
'Reasoning',
|
||||
'Reflecting',
|
||||
'Considering',
|
||||
'Deliberating',
|
||||
'Analyzing',
|
||||
'Evaluating',
|
||||
'Examining',
|
||||
'Inspecting',
|
||||
'Investigating',
|
||||
'Reviewing',
|
||||
'Researching',
|
||||
'Studying',
|
||||
'Exploring',
|
||||
'Mapping',
|
||||
'Tracing',
|
||||
'Parsing',
|
||||
'Processing',
|
||||
'Calculating',
|
||||
'Computing',
|
||||
'Synthesizing',
|
||||
'Planning',
|
||||
'Outlining',
|
||||
'Sketching',
|
||||
'Drafting',
|
||||
'Composing',
|
||||
'Crafting',
|
||||
'Building',
|
||||
'Assembling',
|
||||
'Constructing',
|
||||
'Designing',
|
||||
'Formulating',
|
||||
'Structuring',
|
||||
'Organizing',
|
||||
'Preparing',
|
||||
'Refining',
|
||||
'Polishing',
|
||||
'Honing',
|
||||
'Tuning',
|
||||
'Aligning',
|
||||
'Connecting',
|
||||
'Resolving',
|
||||
'Weaving',
|
||||
'Threading',
|
||||
'Sculpting',
|
||||
'Crystallizing',
|
||||
'Channeling',
|
||||
'Conjuring',
|
||||
'Brewing',
|
||||
'Working',
|
||||
'Cogitating',
|
||||
'Ruminating',
|
||||
'Hypothesizing',
|
||||
'Conceptualizing',
|
||||
'Philosophizing',
|
||||
'Deciphering',
|
||||
'Demystifying',
|
||||
'Articulating',
|
||||
'Illuminating',
|
||||
'Elaborating',
|
||||
'Orchestrating',
|
||||
'Choreographing',
|
||||
'Architecting',
|
||||
'Calibrating',
|
||||
'Materializing',
|
||||
'Visualizing',
|
||||
'Harmonizing',
|
||||
'Contemplificating',
|
||||
'Supercalifragilisting',
|
||||
'Bibbidibobbidibooing',
|
||||
'Abracadabraing',
|
||||
'Hocuspocusing',
|
||||
'Razzmatazzing'
|
||||
])('marks Command Code working when the TUI reports %s', (statusText) => {
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: 'command-code --trust',
|
||||
onWorking
|
||||
})
|
||||
|
||||
expect(detector.observe(`❯ Fix the yellow spinner\r\n${statusText}...`)).toBe(true)
|
||||
|
||||
expect(onWorking).toHaveBeenCalledWith('Fix the yellow spinner')
|
||||
})
|
||||
|
||||
it.each(['Executing: sleep 8 && echo done', '⎿ Running (1s | 0)'])(
|
||||
'marks Command Code working when the TUI reports %s',
|
||||
(statusText) => {
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: 'command-code --trust',
|
||||
onWorking
|
||||
})
|
||||
|
||||
expect(detector.observe(`❯ Fix the yellow spinner\r\n${statusText}`)).toBe(true)
|
||||
|
||||
expect(onWorking).toHaveBeenCalledWith('Fix the yellow spinner')
|
||||
}
|
||||
)
|
||||
|
||||
it('marks Command Code working when active status text is split across PTY chunks', () => {
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: 'command-code --trust',
|
||||
onWorking
|
||||
})
|
||||
|
||||
expect(detector.observe('❯ Fix the yellow spinner\r\nExpl')).toBe(false)
|
||||
expect(detector.observe('oring...')).toBe(true)
|
||||
|
||||
expect(onWorking).toHaveBeenCalledWith('Fix the yellow spinner')
|
||||
})
|
||||
|
||||
it('does not capture a styled idle composer as the submitted prompt', () => {
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: 'command-code --trust',
|
||||
onWorking
|
||||
})
|
||||
|
||||
expect(detector.observe('# Command Code v0.27.3\r\n❯ A\x1b')).toBe(false)
|
||||
expect(detector.observe('[27msk your question...\r\n✻ Thinking...')).toBe(true)
|
||||
|
||||
expect(onWorking).toHaveBeenCalledWith('')
|
||||
expect(onWorking).not.toHaveBeenCalledWith(expect.stringContaining('[27m'))
|
||||
})
|
||||
|
||||
it('captures a submitted prompt when styling is split across PTY chunks', () => {
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: 'command-code --trust',
|
||||
onWorking
|
||||
})
|
||||
|
||||
expect(detector.observe('❯ Fix the \x1b')).toBe(false)
|
||||
expect(detector.observe('[38;2;99;109;131mstatus row\r\n✻ Thinking...')).toBe(true)
|
||||
|
||||
expect(onWorking).toHaveBeenCalledWith('Fix the status row')
|
||||
})
|
||||
|
||||
it('folds whitespace-heavy submitted prompts without whitespace regex replacement', () => {
|
||||
const replaceSpy = vi.spyOn(String.prototype, 'replace')
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: 'command-code --trust',
|
||||
onWorking
|
||||
})
|
||||
const nonBreakingSpace = String.fromCharCode(160)
|
||||
const prompt = `❯ Fix\t the${nonBreakingSpace}${nonBreakingSpace}status row\r\n✻ Thinking...`
|
||||
|
||||
expect(detector.observe(prompt)).toBe(true)
|
||||
|
||||
expect(onWorking).toHaveBeenCalledWith('Fix the status row')
|
||||
expect(
|
||||
replaceSpy.mock.calls.filter(
|
||||
([pattern]) => pattern instanceof RegExp && pattern.source === '\\s+'
|
||||
)
|
||||
).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('marks Command Code done when a no-tool turn returns to the idle prompt', () => {
|
||||
const onWorking = vi.fn()
|
||||
const onDone = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: 'command-code --trust',
|
||||
onWorking,
|
||||
onDone
|
||||
})
|
||||
|
||||
expect(detector.observe('❯ say hi\r\n✻ Thinking...')).toBe(true)
|
||||
expect(
|
||||
detector.observe(
|
||||
'\r\n✻ Thought for 1 second\r\n:: Hi! How can I help you today?\r\n❯ Ask your question...'
|
||||
)
|
||||
).toBe(true)
|
||||
|
||||
expect(onWorking).toHaveBeenCalledWith('say hi')
|
||||
expect(onDone).toHaveBeenCalledWith('say hi')
|
||||
})
|
||||
|
||||
it('does not mark the initial idle composer as done before a submitted prompt', () => {
|
||||
const onDone = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: 'command-code --trust',
|
||||
onWorking: vi.fn(),
|
||||
onDone
|
||||
})
|
||||
|
||||
expect(detector.observe('# Command Code v0.27.3\r\n❯ Ask your question...')).toBe(false)
|
||||
|
||||
expect(onDone).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not treat completed thought text as a working status', () => {
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: 'command-code --trust',
|
||||
onWorking
|
||||
})
|
||||
|
||||
expect(detector.observe('❯ Fix the yellow spinner\r\nThought for 1 second')).toBe(false)
|
||||
expect(onWorking).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('bounds scan work for large echoed paste output in Command Code terminals', () => {
|
||||
const replaceSpy = vi.spyOn(String.prototype, 'replace')
|
||||
const matchAllSpy = vi.spyOn(String.prototype, 'matchAll')
|
||||
const onWorking = vi.fn()
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: 'command-code --trust',
|
||||
onWorking
|
||||
})
|
||||
const largeEchoedPaste = `${'pasted Command Code \x1b[35mnoise\r\n'.repeat(10_000)}❯ Fix bounded scans\r\n✻ Thinking...`
|
||||
|
||||
expect(detector.observe(largeEchoedPaste)).toBe(true)
|
||||
|
||||
expect(onWorking).toHaveBeenCalledWith('Fix bounded scans')
|
||||
expect(maxStringContextLength(replaceSpy.mock.contexts)).toBeLessThan(10_000)
|
||||
expect(maxStringContextLength(matchAllSpy.mock.contexts)).toBeLessThan(10_000)
|
||||
})
|
||||
|
||||
it('bounds pre-banner scans for large non-Command-Code terminal output', () => {
|
||||
const replaceSpy = vi.spyOn(String.prototype, 'replace')
|
||||
const matchAllSpy = vi.spyOn(String.prototype, 'matchAll')
|
||||
const detector = createCommandCodeOutputStatusDetector({
|
||||
startupCommand: null,
|
||||
onWorking: vi.fn()
|
||||
})
|
||||
|
||||
expect(detector.observe(`${'Coded shell output\r\n'.repeat(10_000)}`)).toBe(false)
|
||||
|
||||
expect(maxStringContextLength(replaceSpy.mock.contexts)).toBeLessThan(10_000)
|
||||
expect(maxStringContextLength(matchAllSpy.mock.contexts)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
function maxStringContextLength(contexts: unknown[]): number {
|
||||
return Math.max(
|
||||
0,
|
||||
...contexts.map((context) => (typeof context === 'string' ? context.length : 0))
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
/**
|
||||
* Command Code TUI output scrape — that CLI lacks hooks, so working/done
|
||||
* agent-status rows are seeded from its rendered status words and idle
|
||||
* composer. Shared because main runs this per-PTY under side-effect authority
|
||||
* (emitting command-code facts) while the renderer keeps the byte path for
|
||||
* remote-runtime PTYs and the kill switch
|
||||
* (docs/reference/terminal-side-effect-authority.md).
|
||||
*/
|
||||
import {
|
||||
cleanCommandCodePromptCandidate,
|
||||
isCommandCodeIdlePromptCandidate
|
||||
} from './command-code-prompt-text'
|
||||
|
||||
type CommandCodeOutputStatusDetector = {
|
||||
observe: (data: string) => boolean
|
||||
}
|
||||
|
||||
const ESC = String.fromCharCode(0x1b)
|
||||
const BEL = String.fromCharCode(0x07)
|
||||
const ANSI_ESCAPE_RE = new RegExp(
|
||||
`${ESC}(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~]|\\][^${BEL}]*(?:${BEL}|${ESC}\\\\))`,
|
||||
'g'
|
||||
)
|
||||
const INCOMPLETE_ANSI_ESCAPE_RE = new RegExp(
|
||||
`${ESC}(?:\\[[0-?]*[ -/]*|\\][^${BEL}${ESC}]*|\\S?)?$`,
|
||||
'g'
|
||||
)
|
||||
const RECENT_TEXT_LIMIT = 300
|
||||
const STATUS_SCAN_TEXT_LIMIT = 4096
|
||||
const COMMAND_CODE_STATUS_GLYPH_RE_SOURCE = '[·○◇☆✧⌘✻⎿]'
|
||||
// Why: Command Code 0.27.3 randomizes its in-flight LLM status from this
|
||||
// package-local list, so checking only a few examples misses real active turns.
|
||||
const COMMAND_CODE_LLM_STATUS_WORDS = [
|
||||
'Thinking',
|
||||
'Pondering',
|
||||
'Contemplating',
|
||||
'Reasoning',
|
||||
'Reflecting',
|
||||
'Considering',
|
||||
'Deliberating',
|
||||
'Analyzing',
|
||||
'Evaluating',
|
||||
'Examining',
|
||||
'Inspecting',
|
||||
'Investigating',
|
||||
'Reviewing',
|
||||
'Researching',
|
||||
'Studying',
|
||||
'Exploring',
|
||||
'Mapping',
|
||||
'Tracing',
|
||||
'Parsing',
|
||||
'Processing',
|
||||
'Calculating',
|
||||
'Computing',
|
||||
'Synthesizing',
|
||||
'Planning',
|
||||
'Outlining',
|
||||
'Sketching',
|
||||
'Drafting',
|
||||
'Composing',
|
||||
'Crafting',
|
||||
'Building',
|
||||
'Assembling',
|
||||
'Constructing',
|
||||
'Designing',
|
||||
'Formulating',
|
||||
'Structuring',
|
||||
'Organizing',
|
||||
'Preparing',
|
||||
'Refining',
|
||||
'Polishing',
|
||||
'Honing',
|
||||
'Tuning',
|
||||
'Aligning',
|
||||
'Connecting',
|
||||
'Resolving',
|
||||
'Weaving',
|
||||
'Threading',
|
||||
'Sculpting',
|
||||
'Crystallizing',
|
||||
'Channeling',
|
||||
'Conjuring',
|
||||
'Brewing',
|
||||
'Working',
|
||||
'Cogitating',
|
||||
'Ruminating',
|
||||
'Hypothesizing',
|
||||
'Conceptualizing',
|
||||
'Philosophizing',
|
||||
'Deciphering',
|
||||
'Demystifying',
|
||||
'Articulating',
|
||||
'Illuminating',
|
||||
'Elaborating',
|
||||
'Orchestrating',
|
||||
'Choreographing',
|
||||
'Architecting',
|
||||
'Calibrating',
|
||||
'Materializing',
|
||||
'Visualizing',
|
||||
'Harmonizing',
|
||||
'Contemplificating',
|
||||
'Supercalifragilisting',
|
||||
'Bibbidibobbidibooing',
|
||||
'Abracadabraing',
|
||||
'Hocuspocusing',
|
||||
'Razzmatazzing'
|
||||
] as const
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
}
|
||||
|
||||
const LLM_STATUS_WORDS_RE_SOURCE = COMMAND_CODE_LLM_STATUS_WORDS.map(escapeRegExp).join('|')
|
||||
const ACTIVE_LLM_STATUS_RE = new RegExp(
|
||||
`(?:^|[\\r\\n])\\s*(?:${COMMAND_CODE_STATUS_GLYPH_RE_SOURCE}\\s*)?(?:${LLM_STATUS_WORDS_RE_SOURCE})\\b(?:…|\\.\\.\\.)`
|
||||
)
|
||||
const ACTIVE_EXECUTION_STATUS_RE = new RegExp(
|
||||
`(?:^|[\\r\\n])\\s*(?:${COMMAND_CODE_STATUS_GLYPH_RE_SOURCE}\\s*)?(?:Executing:\\s+\\S|Running\\s*\\()`
|
||||
)
|
||||
const IDLE_PROMPT_RE = /(?:^|[\r\n])\s*[❯>]\s+Ask your question\.\.\./
|
||||
const COMMAND_CODE_BANNER_RE = /\bCommand Code\b/
|
||||
|
||||
function stripTerminalControl(data: string): string {
|
||||
if (!terminalControlMayAffectText(data)) {
|
||||
return data
|
||||
}
|
||||
const withoutAnsi = data.replace(ANSI_ESCAPE_RE, '').replace(INCOMPLETE_ANSI_ESCAPE_RE, '')
|
||||
let output = ''
|
||||
for (let index = 0; index < withoutAnsi.length; index += 1) {
|
||||
const code = withoutAnsi.charCodeAt(index)
|
||||
if ((code <= 0x1f && code !== 0x0a && code !== 0x0d) || (code >= 0x7f && code <= 0x9f)) {
|
||||
continue
|
||||
}
|
||||
output += withoutAnsi[index]
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
function terminalControlMayAffectText(data: string): boolean {
|
||||
for (let index = 0; index < data.length; index += 1) {
|
||||
const code = data.charCodeAt(index)
|
||||
if (
|
||||
code === 0x0d ||
|
||||
code === 0x1b ||
|
||||
(code <= 0x1f && code !== 0x0a) ||
|
||||
(code >= 0x7f && code <= 0x9f)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function cleanPromptCandidate(value: string): string {
|
||||
return cleanCommandCodePromptCandidate(stripTerminalControl(value))
|
||||
}
|
||||
|
||||
function isIdlePromptCandidate(value: string): boolean {
|
||||
return isCommandCodeIdlePromptCandidate(value)
|
||||
}
|
||||
|
||||
function isCommandCodeLaunchCommand(command: string | null | undefined): boolean {
|
||||
if (!command) {
|
||||
return false
|
||||
}
|
||||
return /(?:^|[\s;&|])(?:command-code|commandcode|cmdc)(?:\s|$)/.test(command)
|
||||
}
|
||||
|
||||
function rawTextMayContainCommandCodeBanner(rawText: string): boolean {
|
||||
// Why: every terminal pane observes this detector, but only Command Code
|
||||
// panes need the ANSI/control stripping path. Use a broad no-false-negative
|
||||
// letter prefilter so ANSI styling inside the banner words still works.
|
||||
return rawText.includes('C') && rawText.includes('o') && rawText.includes('d')
|
||||
}
|
||||
|
||||
function appendRecentRawText(previousRawText: string, data: string): string {
|
||||
if (data.length >= RECENT_TEXT_LIMIT) {
|
||||
return data.slice(-RECENT_TEXT_LIMIT)
|
||||
}
|
||||
return (previousRawText + data).slice(-RECENT_TEXT_LIMIT)
|
||||
}
|
||||
|
||||
function buildStatusScanRawText(prefix: string, data: string): string {
|
||||
const boundedPrefix =
|
||||
prefix.length > RECENT_TEXT_LIMIT + 1 ? prefix.slice(-(RECENT_TEXT_LIMIT + 1)) : prefix
|
||||
const dataBudget = STATUS_SCAN_TEXT_LIMIT - boundedPrefix.length
|
||||
|
||||
if (dataBudget <= 0) {
|
||||
return boundedPrefix.slice(-STATUS_SCAN_TEXT_LIMIT)
|
||||
}
|
||||
if (data.length <= dataBudget) {
|
||||
return boundedPrefix + data
|
||||
}
|
||||
|
||||
const headBudget = Math.max(0, Math.floor((dataBudget - 1) / 2))
|
||||
const tailBudget = Math.max(0, dataBudget - headBudget - 1)
|
||||
const head = headBudget > 0 ? data.slice(0, headBudget) : ''
|
||||
const tail = tailBudget > 0 ? data.slice(-tailBudget) : ''
|
||||
// Why: pasted terminal echoes can produce megabyte-sized chunks. Status
|
||||
// detection only needs chunk-boundary context plus recent output, so scan the
|
||||
// start and end windows instead of regex-stripping the full PTY payload.
|
||||
return `${boundedPrefix}${head}\n${tail}`
|
||||
}
|
||||
|
||||
function patternOverlapsSanitizedText(
|
||||
pattern: RegExp,
|
||||
previousTextLength: number,
|
||||
combinedText: string
|
||||
): boolean {
|
||||
const re = new RegExp(pattern.source, 'g')
|
||||
for (const match of combinedText.matchAll(re)) {
|
||||
const start = match.index ?? 0
|
||||
if (start + match[0].length > previousTextLength) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type StatusScanContext = {
|
||||
combinedText: string
|
||||
previousTextLength: number
|
||||
combinedTextWithChunkBoundary: string
|
||||
previousTextWithChunkBoundaryLength: number
|
||||
}
|
||||
|
||||
function patternOverlapsStatusContext(pattern: RegExp, context: StatusScanContext): boolean {
|
||||
return (
|
||||
patternOverlapsSanitizedText(pattern, context.previousTextLength, context.combinedText) ||
|
||||
patternOverlapsSanitizedText(
|
||||
pattern,
|
||||
context.previousTextWithChunkBoundaryLength,
|
||||
context.combinedTextWithChunkBoundary
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
function isActiveStatusText(context: StatusScanContext): boolean {
|
||||
return (
|
||||
patternOverlapsStatusContext(ACTIVE_LLM_STATUS_RE, context) ||
|
||||
patternOverlapsStatusContext(ACTIVE_EXECUTION_STATUS_RE, context)
|
||||
)
|
||||
}
|
||||
|
||||
function isIdlePromptText(context: StatusScanContext): boolean {
|
||||
return patternOverlapsStatusContext(IDLE_PROMPT_RE, context)
|
||||
}
|
||||
|
||||
export function createCommandCodeOutputStatusDetector(args: {
|
||||
startupCommand?: string | null
|
||||
onWorking: (prompt: string) => void
|
||||
onDone?: (prompt: string) => void
|
||||
}): CommandCodeOutputStatusDetector {
|
||||
let hasSeenCommandCodeUi = isCommandCodeLaunchCommand(args.startupCommand)
|
||||
let lastSubmittedPrompt = ''
|
||||
let recentRawText = ''
|
||||
|
||||
return {
|
||||
observe(data: string): boolean {
|
||||
const previousRawText = recentRawText
|
||||
recentRawText = appendRecentRawText(previousRawText, data)
|
||||
const scanRawText = buildStatusScanRawText(previousRawText, data)
|
||||
const scanRawTextWithChunkBoundary = previousRawText
|
||||
? buildStatusScanRawText(`${previousRawText}\n`, data)
|
||||
: scanRawText
|
||||
|
||||
if (!hasSeenCommandCodeUi) {
|
||||
if (
|
||||
!rawTextMayContainCommandCodeBanner(scanRawText) &&
|
||||
!rawTextMayContainCommandCodeBanner(scanRawTextWithChunkBoundary)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
const scanText = stripTerminalControl(scanRawText)
|
||||
const scanTextWithChunkBoundary = stripTerminalControl(scanRawTextWithChunkBoundary)
|
||||
if (
|
||||
!COMMAND_CODE_BANNER_RE.test(scanText) &&
|
||||
!COMMAND_CODE_BANNER_RE.test(scanTextWithChunkBoundary)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
hasSeenCommandCodeUi = true
|
||||
}
|
||||
|
||||
const scanText = stripTerminalControl(scanRawText)
|
||||
const scanTextWithChunkBoundary = stripTerminalControl(scanRawTextWithChunkBoundary)
|
||||
const previousTextLength = previousRawText ? stripTerminalControl(previousRawText).length : 0
|
||||
const previousTextWithChunkBoundaryLength = previousRawText
|
||||
? stripTerminalControl(`${previousRawText}\n`).length
|
||||
: 0
|
||||
const statusContext: StatusScanContext = {
|
||||
combinedText: scanText,
|
||||
previousTextLength,
|
||||
combinedTextWithChunkBoundary: scanTextWithChunkBoundary,
|
||||
previousTextWithChunkBoundaryLength
|
||||
}
|
||||
for (const promptMatch of scanText.matchAll(/(?:^|[\r\n])\s*[❯>]\s+([^\r\n]+)(?=[\r\n])/g)) {
|
||||
const prompt = cleanPromptCandidate(promptMatch[1] ?? '')
|
||||
if (prompt && !isIdlePromptCandidate(prompt)) {
|
||||
lastSubmittedPrompt = prompt
|
||||
}
|
||||
}
|
||||
// Why: Command Code lacks a prompt-start hook. Its TUI prints these
|
||||
// status words while a submitted prompt is actively running, including
|
||||
// no-tool turns that would otherwise jump straight from idle to done.
|
||||
if (isActiveStatusText(statusContext)) {
|
||||
args.onWorking(lastSubmittedPrompt)
|
||||
return true
|
||||
}
|
||||
// Why: Command Code does not reliably emit a Stop hook for no-tool turns.
|
||||
// When a submitted prompt has returned to the idle composer, let the pane
|
||||
// connection settle-check the current row and mark that turn done.
|
||||
if (lastSubmittedPrompt && isIdlePromptText(statusContext)) {
|
||||
args.onDone?.(lastSubmittedPrompt)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
const ORPHAN_SGR_RE = /\[(?:\d{1,3}(?:;\d{1,3})*)?m/g
|
||||
|
||||
export function cleanCommandCodePromptCandidate(value: string): string {
|
||||
return foldCommandCodePromptWhitespace(value)
|
||||
}
|
||||
|
||||
export function isCommandCodeIdlePromptCandidate(value: string): boolean {
|
||||
return equalsCommandCodePromptIgnoringWhitespace(
|
||||
value.replace(ORPHAN_SGR_RE, ''),
|
||||
'Askyourquestion...'
|
||||
)
|
||||
}
|
||||
|
||||
// Why: this runs inside PTY output observation; prompt labels only need
|
||||
// collapsed display whitespace, not regex normalization on every status frame.
|
||||
function foldCommandCodePromptWhitespace(value: string): string {
|
||||
let normalized = ''
|
||||
let pendingWhitespace = false
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
const code = value.charCodeAt(index)
|
||||
if (isCommandCodePromptWhitespace(code)) {
|
||||
pendingWhitespace = normalized.length > 0
|
||||
continue
|
||||
}
|
||||
if (pendingWhitespace) {
|
||||
normalized += ' '
|
||||
pendingWhitespace = false
|
||||
}
|
||||
normalized += value.charAt(index)
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
function equalsCommandCodePromptIgnoringWhitespace(value: string, expected: string): boolean {
|
||||
let expectedIndex = 0
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
const code = value.charCodeAt(index)
|
||||
if (isCommandCodePromptWhitespace(code)) {
|
||||
continue
|
||||
}
|
||||
if (value.charAt(index) !== expected.charAt(expectedIndex)) {
|
||||
return false
|
||||
}
|
||||
expectedIndex += 1
|
||||
}
|
||||
return expectedIndex === expected.length
|
||||
}
|
||||
|
||||
function isCommandCodePromptWhitespace(code: number): boolean {
|
||||
return (
|
||||
code === 32 ||
|
||||
(code >= 9 && code <= 13) ||
|
||||
code === 160 ||
|
||||
code === 5760 ||
|
||||
(code >= 8192 && code <= 8202) ||
|
||||
code === 8232 ||
|
||||
code === 8233 ||
|
||||
code === 8239 ||
|
||||
code === 8287 ||
|
||||
code === 12288 ||
|
||||
code === 65279
|
||||
)
|
||||
}
|
||||
@@ -309,6 +309,10 @@ export function getDefaultSettings(homedir: string): GlobalSettings {
|
||||
claudeManagedAccounts: [],
|
||||
activeClaudeManagedAccountId: null,
|
||||
terminalScopeHistoryByWorktree: true,
|
||||
terminalHiddenViewParking: true,
|
||||
terminalMainSideEffectAuthority: true,
|
||||
terminalHiddenDeliveryGate: true,
|
||||
terminalModelQueryAuthority: true,
|
||||
defaultTuiAgent: null,
|
||||
disabledTuiAgents: [...DEFAULT_DISABLED_TUI_AGENTS],
|
||||
claudeAgentTeamsDefaultDisabledMigrated: true,
|
||||
|
||||
@@ -3,23 +3,34 @@ export type E2EConfig = {
|
||||
headless: boolean
|
||||
exposeStore: boolean
|
||||
userDataDir: string | null
|
||||
/** Test-only override (ORCA_E2E_TERMINAL_PARKING_DELAY_MS) shrinking the
|
||||
* terminal hidden-view parking delays. null means use production timing. */
|
||||
terminalParkingDelayMs: number | null
|
||||
}
|
||||
|
||||
type E2EConfigInput = {
|
||||
headless?: boolean
|
||||
exposeStore?: boolean
|
||||
userDataDir?: string | null
|
||||
terminalParkingDelayMs?: number | null
|
||||
}
|
||||
|
||||
export function createE2EConfig(input: E2EConfigInput): E2EConfig {
|
||||
const userDataDir = input.userDataDir?.trim() || null
|
||||
const headless = Boolean(input.headless)
|
||||
const exposeStore = Boolean(input.exposeStore)
|
||||
const terminalParkingDelayMs =
|
||||
typeof input.terminalParkingDelayMs === 'number' &&
|
||||
Number.isFinite(input.terminalParkingDelayMs) &&
|
||||
input.terminalParkingDelayMs > 0
|
||||
? input.terminalParkingDelayMs
|
||||
: null
|
||||
|
||||
return {
|
||||
enabled: headless || exposeStore || userDataDir !== null,
|
||||
headless,
|
||||
exposeStore,
|
||||
userDataDir
|
||||
userDataDir,
|
||||
terminalParkingDelayMs
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// Why shared: main's terminal side-effect tracker emits pr-link facts
|
||||
// (terminal-side-effect-authority.md, slice 3) and needs the same GitHub URL
|
||||
// parsing core the renderer link picker uses.
|
||||
const GH_ITEM_PATH_RE = /^\/([^/]+)\/([^/]+)\/(issues|pull)\/(\d+)(?:\/.*)?$/i
|
||||
|
||||
export type RepoSlug = {
|
||||
owner: string
|
||||
repo: string
|
||||
}
|
||||
|
||||
export type GitHubIssueOrPRLink = {
|
||||
slug: RepoSlug
|
||||
number: number
|
||||
type: 'issue' | 'pr'
|
||||
}
|
||||
|
||||
export function buildGitHubRepoUrl(slug: RepoSlug | null | undefined): string | null {
|
||||
if (!slug?.owner || !slug.repo) {
|
||||
return null
|
||||
}
|
||||
return `https://github.com/${encodeURIComponent(slug.owner)}/${encodeURIComponent(slug.repo)}`
|
||||
}
|
||||
|
||||
function matchGitHubItemPath(url: URL): RegExpExecArray | null {
|
||||
return GH_ITEM_PATH_RE.exec(url.pathname.replace(/\/+$/, ''))
|
||||
}
|
||||
|
||||
function parseGitHubItemNumber(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10)
|
||||
return parsed > 0 ? parsed : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a GitHub issue/PR reference from plain input.
|
||||
* Supports issue/PR numbers (e.g. "42"), "#42", and full GitHub URLs.
|
||||
*/
|
||||
export function parseGitHubIssueOrPRNumber(input: string): number | null {
|
||||
const trimmed = input.trim()
|
||||
if (!trimmed) {
|
||||
return null
|
||||
}
|
||||
|
||||
const numeric = trimmed.startsWith('#') ? trimmed.slice(1) : trimmed
|
||||
if (/^\d+$/.test(numeric)) {
|
||||
return parseGitHubItemNumber(numeric)
|
||||
}
|
||||
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(trimmed)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
|
||||
return null
|
||||
}
|
||||
|
||||
const match = matchGitHubItemPath(url)
|
||||
if (!match) {
|
||||
return null
|
||||
}
|
||||
|
||||
return parseGitHubItemNumber(match[4])
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an owner/repo slug plus issue/PR number from a GitHub URL. Returns
|
||||
* null for anything that isn't a recognizable GitHub-shaped issue or pull URL.
|
||||
*/
|
||||
export function parseGitHubIssueOrPRLink(input: string): GitHubIssueOrPRLink | null {
|
||||
const trimmed = input.trim()
|
||||
if (!trimmed) {
|
||||
return null
|
||||
}
|
||||
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(trimmed)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
|
||||
return null
|
||||
}
|
||||
|
||||
const match = matchGitHubItemPath(url)
|
||||
if (!match) {
|
||||
return null
|
||||
}
|
||||
const number = parseGitHubItemNumber(match[4])
|
||||
if (number === null) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
slug: { owner: match[1], repo: match[2] },
|
||||
type: match[3].toLowerCase() === 'pull' ? 'pr' : 'issue',
|
||||
number
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { extractOscTitleScanTail } from './osc-title-scan-tail'
|
||||
|
||||
describe('extractOscTitleScanTail', () => {
|
||||
it('keeps incomplete OSC title candidates only', () => {
|
||||
expect(extractOscTitleScanTail('\x1b]0;Codex work')).toBe('\x1b]0;Codex work')
|
||||
expect(extractOscTitleScanTail('\x1b]2;Codex working\x1b')).toBe('\x1b]2;Codex working\x1b')
|
||||
expect(extractOscTitleScanTail('\x1b]')).toBe('\x1b]')
|
||||
expect(extractOscTitleScanTail('\x1b]1')).toBe('\x1b]1')
|
||||
})
|
||||
|
||||
it('does not carry non-title OSC payloads into the title scanner', () => {
|
||||
expect(extractOscTitleScanTail('\x1b]133;D;13')).toBe('')
|
||||
expect(extractOscTitleScanTail('\x1b]7;file://host/tmp')).toBe('')
|
||||
expect(extractOscTitleScanTail('\x1b]133;D;0\x07\x1b')).toBe('\x1b')
|
||||
})
|
||||
})
|
||||
@@ -1,18 +1,29 @@
|
||||
const OSC_TITLE_SCAN_TAIL_LIMIT = 4096
|
||||
const OSC_TITLE_PREFIX_LENGTH = 4
|
||||
const OSC_TITLE_CODES = new Set(['0', '1', '2'])
|
||||
|
||||
export function extractOscTitleScanTail(input: string): string {
|
||||
const lastOsc = input.lastIndexOf('\x1b]')
|
||||
if (lastOsc !== -1) {
|
||||
const suffix = input.slice(lastOsc)
|
||||
if (!suffix.includes('\x07') && !suffix.includes('\x1b\\')) {
|
||||
return trimOscTitleScanTail(suffix)
|
||||
return extractIncompleteTitleOscTail(suffix)
|
||||
}
|
||||
return input.endsWith('\x1b') ? '\x1b' : ''
|
||||
}
|
||||
return input.endsWith('\x1b') ? '\x1b' : ''
|
||||
}
|
||||
|
||||
function extractIncompleteTitleOscTail(suffix: string): string {
|
||||
const parameterEnd = suffix.indexOf(';', 2)
|
||||
if (parameterEnd === -1) {
|
||||
const partialParameter = suffix.slice(2)
|
||||
return ['', '0', '1', '2'].includes(partialParameter) ? trimOscTitleScanTail(suffix) : ''
|
||||
}
|
||||
const parameter = suffix.slice(2, parameterEnd)
|
||||
return OSC_TITLE_CODES.has(parameter) ? trimOscTitleScanTail(suffix) : ''
|
||||
}
|
||||
|
||||
function trimOscTitleScanTail(value: string): string {
|
||||
if (value.length <= OSC_TITLE_SCAN_TAIL_LIMIT) {
|
||||
return value
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
// Why: pins the freeze-report primitives — the breadcrumb ring must stay
|
||||
// bounded and coalesce repeat events (a flood costs one slot per second, not
|
||||
// unbounded memory), and pty-id redaction must keep the correlatable suffix
|
||||
// while dropping the path-bearing worktree prefix.
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
createPtyDeliveryBreadcrumbRing,
|
||||
redactPtyIdForDiagnostics
|
||||
} from './pty-delivery-diagnostics'
|
||||
|
||||
describe('pty delivery breadcrumb ring', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('coalesces same-kind events inside the window and separates them outside it', () => {
|
||||
const ring = createPtyDeliveryBreadcrumbRing(10, 1_000)
|
||||
ring.record('gate-mark', { id: 'a' })
|
||||
vi.advanceTimersByTime(200)
|
||||
ring.record('gate-mark', { id: 'b' })
|
||||
vi.advanceTimersByTime(200)
|
||||
ring.record('gate-mark')
|
||||
|
||||
let entries = ring.snapshot()
|
||||
expect(entries).toHaveLength(1)
|
||||
expect(entries[0].repeats).toBe(3)
|
||||
// The freshest detail wins so the report shows the latest actor.
|
||||
expect(entries[0].detail).toEqual({ id: 'b' })
|
||||
|
||||
vi.advanceTimersByTime(2_000)
|
||||
ring.record('gate-mark', { id: 'c' })
|
||||
entries = ring.snapshot()
|
||||
expect(entries).toHaveLength(2)
|
||||
expect(entries[1].repeats).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not coalesce across different kinds and stays bounded at capacity', () => {
|
||||
const ring = createPtyDeliveryBreadcrumbRing(5, 1_000)
|
||||
ring.record('gate-mark')
|
||||
ring.record('gate-unmark')
|
||||
expect(ring.snapshot()).toHaveLength(2)
|
||||
|
||||
for (let i = 0; i < 20; i++) {
|
||||
vi.advanceTimersByTime(2_000)
|
||||
ring.record(`kind-${i}`)
|
||||
}
|
||||
const entries = ring.snapshot()
|
||||
expect(entries).toHaveLength(5)
|
||||
expect(entries[4].kind).toBe('kind-19')
|
||||
})
|
||||
|
||||
it('snapshot returns copies and reset empties the ring', () => {
|
||||
const ring = createPtyDeliveryBreadcrumbRing(5, 1_000)
|
||||
ring.record('watchdog-heal', { healCount: 1 })
|
||||
const entries = ring.snapshot()
|
||||
entries[0].kind = 'tampered'
|
||||
expect(ring.snapshot()[0].kind).toBe('watchdog-heal')
|
||||
ring.reset()
|
||||
expect(ring.snapshot()).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('redactPtyIdForDiagnostics', () => {
|
||||
it('keeps the @@ suffix and drops the path-bearing worktree prefix', () => {
|
||||
expect(redactPtyIdForDiagnostics('/Users/someone/repo@@ab12cd34')).toBe('…@@ab12cd34')
|
||||
})
|
||||
|
||||
it('truncates long ids without a separator and passes short ids through', () => {
|
||||
expect(redactPtyIdForDiagnostics('pty-1')).toBe('pty-1')
|
||||
const long = 'x'.repeat(40)
|
||||
expect(redactPtyIdForDiagnostics(long)).toBe(`…${'x'.repeat(12)}`)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* One-paste terminal freeze diagnostics: shared shapes for the breadcrumb
|
||||
* rings kept in BOTH processes and for the per-pty delivery table main embeds
|
||||
* in its debug snapshot. The goal is that a single console command captures
|
||||
* enough history + state to attribute any frozen-terminal report without
|
||||
* asking the user for more logs.
|
||||
*/
|
||||
|
||||
export type PtyDeliveryBreadcrumb = {
|
||||
atMs: number
|
||||
kind: string
|
||||
detail?: Record<string, string | number | boolean | null>
|
||||
/** Same-kind events within the coalesce window fold into this counter. */
|
||||
repeats?: number
|
||||
}
|
||||
|
||||
export type PtyDeliveryBreadcrumbRing = {
|
||||
record: (kind: string, detail?: PtyDeliveryBreadcrumb['detail']) => void
|
||||
snapshot: () => PtyDeliveryBreadcrumb[]
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
const BREADCRUMB_RING_CAPACITY = 100
|
||||
const BREADCRUMB_COALESCE_MS = 1_000
|
||||
|
||||
// Why a ring with same-kind coalescing: breadcrumbs record rare transitions,
|
||||
// but a pathological loop (marker flood, gate flapping) must cost one array
|
||||
// slot + counter bump per second, never unbounded memory or GC churn.
|
||||
export function createPtyDeliveryBreadcrumbRing(
|
||||
capacity = BREADCRUMB_RING_CAPACITY,
|
||||
coalesceMs = BREADCRUMB_COALESCE_MS
|
||||
): PtyDeliveryBreadcrumbRing {
|
||||
let entries: PtyDeliveryBreadcrumb[] = []
|
||||
return {
|
||||
record(kind, detail) {
|
||||
const now = Date.now()
|
||||
const last = entries.at(-1)
|
||||
if (last && last.kind === kind && now - last.atMs < coalesceMs) {
|
||||
last.repeats = (last.repeats ?? 1) + 1
|
||||
last.atMs = now
|
||||
if (detail !== undefined) {
|
||||
last.detail = detail
|
||||
}
|
||||
return
|
||||
}
|
||||
entries.push(detail === undefined ? { atMs: now, kind } : { atMs: now, kind, detail })
|
||||
if (entries.length > capacity) {
|
||||
entries = entries.slice(entries.length - capacity)
|
||||
}
|
||||
},
|
||||
snapshot() {
|
||||
return entries.map((entry) => ({ ...entry }))
|
||||
},
|
||||
reset() {
|
||||
entries = []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Why redact: daemon session ids embed worktree paths
|
||||
// (`${worktreeId}@@${shortUuid}`). The `@@` suffix is unique enough to
|
||||
// correlate a pty across the renderer/main sections of one report without
|
||||
// shipping the user's filesystem layout.
|
||||
export function redactPtyIdForDiagnostics(id: string): string {
|
||||
const separatorIdx = id.lastIndexOf('@@')
|
||||
if (separatorIdx !== -1) {
|
||||
return `…${id.slice(separatorIdx)}`
|
||||
}
|
||||
return id.length <= 12 ? id : `…${id.slice(-12)}`
|
||||
}
|
||||
|
||||
export type PtyPerPtyDeliveryDiagnostics = {
|
||||
id: string
|
||||
sentChars: number
|
||||
ackedChars: number
|
||||
inFlightChars: number
|
||||
pendingChars: number
|
||||
hidden: boolean
|
||||
visible: boolean
|
||||
active: boolean
|
||||
msSinceLastSend: number | null
|
||||
msSinceLastAck: number | null
|
||||
}
|
||||
|
||||
export type PtyMainDeliveryDiagnostics = {
|
||||
appVersion: string
|
||||
mainUptimeMs: number
|
||||
windowFocused: boolean | null
|
||||
windowVisible: boolean | null
|
||||
windowMinimized: boolean | null
|
||||
msSinceLastPowerSuspend: number | null
|
||||
msSinceLastPowerResume: number | null
|
||||
perPty: PtyPerPtyDeliveryDiagnostics[]
|
||||
breadcrumbs: PtyDeliveryBreadcrumb[]
|
||||
}
|
||||
|
||||
export const EMPTY_PTY_MAIN_DELIVERY_DIAGNOSTICS: PtyMainDeliveryDiagnostics = {
|
||||
appVersion: '',
|
||||
mainUptimeMs: 0,
|
||||
windowFocused: null,
|
||||
windowVisible: null,
|
||||
windowMinimized: null,
|
||||
msSinceLastPowerSuspend: null,
|
||||
msSinceLastPowerResume: null,
|
||||
perPty: [],
|
||||
breadcrumbs: []
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Out-of-band `pty:modelRestoreNeeded` (main → renderer) payload.
|
||||
*
|
||||
* Why a dedicated channel instead of an in-band sentinel chunk: an empty
|
||||
* `pty:data` chunk is indistinguishable from a real chunk whose bytes were
|
||||
* entirely stripped by renderer-side OSC-9999 cleaning, so an in-band marker
|
||||
* could spuriously trigger full snapshot restores on visible panes. The
|
||||
* marker is delivery machinery, not PTY data — remote-runtime transports
|
||||
* never see it.
|
||||
*/
|
||||
export type PtyModelRestoreReason = 'hidden-drop' | 'unhide' | 'pending-cap' | 'delivery-heal'
|
||||
|
||||
export type PtyModelRestoreNeededEvent = {
|
||||
id: string
|
||||
reason: PtyModelRestoreReason
|
||||
/** Main's PTY output sequence at emit time — everything at or before this
|
||||
* point is only recoverable from the model snapshot. */
|
||||
markerSeq?: number
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* `pty:reportRendererDeliveryState` (renderer → main, invoke) payload/reply.
|
||||
*
|
||||
* Why invoke and renderer-initiated: field evidence (v1.4.121-rc.0 snapshot,
|
||||
* 2026-07-06) proved a wedge where main→renderer push delivery (`pty:data`,
|
||||
* `pty:requestDeliveryResync`, `pty:modelRestoreNeeded`) goes silently dead
|
||||
* while renderer→main invoke IPC stays healthy. Every push-initiated recovery
|
||||
* path (cumulative-ACK self-heal, solicited resync, wake relay) is unreachable
|
||||
* in that state, so the delivery watchdog reports and heals over invoke — the
|
||||
* direction proven alive.
|
||||
*/
|
||||
export type PtyRendererDeliveryStateReport = {
|
||||
/** Cumulative chars received per PTY, counted at dispatcher enqueue —
|
||||
* BEFORE parse-deferred ACK crediting. The gap between main's sentChars
|
||||
* and this total is bytes provably lost in the push channel, distinct
|
||||
* from bytes received but still queued for parsing. */
|
||||
receivedCharsByPty: Record<string, number>
|
||||
/** Cumulative processed (ACK-credited) chars per PTY — same totals the
|
||||
* ACK path and resync response carry; merging them here is a free extra
|
||||
* repair lane for the lost-ACK variant. */
|
||||
processedCharsByPty: Record<string, number>
|
||||
/** Set on the confirming tick: main may write off provably-lost bytes and
|
||||
* answer with restore markers for the renderer to route locally. */
|
||||
heal?: boolean
|
||||
/** `ipcRenderer.listenerCount('pty:data')` at heal time — discriminates
|
||||
* "listener detached" from "channel dead" in field logs. */
|
||||
rendererPtyDataListenerCount?: number | null
|
||||
}
|
||||
|
||||
export type PtyDeliveryWriteOff = {
|
||||
id: string
|
||||
/** Main's PTY output sequence at write-off — everything at or before this
|
||||
* is only recoverable from the model snapshot (pulled restore marker). */
|
||||
markerSeq?: number
|
||||
writtenOffChars: number
|
||||
}
|
||||
|
||||
export type PtyRendererDeliveryHealthReply = {
|
||||
inFlightTotalChars: number
|
||||
inFlightPtyCount: number
|
||||
/** null = no ACK received since main-side counters were (re)created. */
|
||||
msSinceLastAck: number | null
|
||||
/** Present only on a heal report that actually wrote off lost bytes. */
|
||||
writtenOff?: PtyDeliveryWriteOff[]
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createBellDetector } from './terminal-bell-detector'
|
||||
|
||||
describe('createBellDetector', () => {
|
||||
it('skips ANSI chunks without losing later real bells', () => {
|
||||
const detector = createBellDetector()
|
||||
|
||||
expect(detector.chunkContainsBell('\x1b[32mbuild\x1b[0m output')).toBe(false)
|
||||
expect(detector.chunkContainsBell('\x07')).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps split OSC state so title terminators are not reported as bells', () => {
|
||||
const detector = createBellDetector()
|
||||
|
||||
expect(detector.chunkContainsBell('\x1b]0;Codex working')).toBe(false)
|
||||
expect(detector.chunkContainsBell('\x07')).toBe(false)
|
||||
expect(detector.chunkContainsBell('\x07')).toBe(true)
|
||||
})
|
||||
|
||||
it('treats BEL after a split non-OSC escape as a real bell', () => {
|
||||
const detector = createBellDetector()
|
||||
|
||||
expect(detector.chunkContainsBell('\x1b')).toBe(false)
|
||||
expect(detector.chunkContainsBell('\x07')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* Stateful BEL detector that correctly ignores BEL (0x07) bytes
|
||||
* occurring inside OSC escape sequences.
|
||||
*
|
||||
* Shared between the renderer transport processor and main's per-PTY
|
||||
* side-effect tracker (docs/reference/terminal-side-effect-authority.md):
|
||||
* bell semantics must not drift between the two parsing authorities.
|
||||
*
|
||||
* Why stateful: PTY data arrives in arbitrary chunks, so an OSC sequence
|
||||
* may span multiple calls. The detector tracks in-progress escape state
|
||||
* across invocations so a BEL used as an OSC terminator is never
|
||||
* misinterpreted as a terminal bell.
|
||||
*
|
||||
* CAN (0x18) / SUB (0x1A) handling: per ECMA-48, these bytes cancel any
|
||||
* in-progress escape sequence. Without this, a malformed or truncated OSC
|
||||
* string (e.g. from a crashed TUI) would pin `inOsc = true` indefinitely
|
||||
* and silently drop the next real BEL as if it were an OSC terminator.
|
||||
*
|
||||
* reset(): callers should invoke this whenever the underlying byte stream
|
||||
* is replaced (e.g. on PTY detach/attach) so state from a previous stream
|
||||
* that ended mid-escape does not leak into the next stream.
|
||||
*/
|
||||
export type BellDetector = {
|
||||
/** `hints.containsOscIntroducer` lets a caller that already scanned for
|
||||
* `\x1b]` (the title-extraction gate) share the result instead of paying
|
||||
* a second includes() pass per chunk on the hot path. */
|
||||
chunkContainsBell(data: string, hints?: { containsOscIntroducer?: boolean }): boolean
|
||||
reset(): void
|
||||
}
|
||||
|
||||
export function createBellDetector(): BellDetector {
|
||||
let pendingEscape = false
|
||||
let inOsc = false
|
||||
let pendingOscEscape = false
|
||||
|
||||
return {
|
||||
chunkContainsBell(data: string, hints: { containsOscIntroducer?: boolean } = {}): boolean {
|
||||
if (!inOsc && !pendingEscape && !data.includes('\x07')) {
|
||||
// Why: CSI/plain chunks with no BEL and no OSC start cannot affect
|
||||
// bell state; avoid walking every byte of normal terminal output.
|
||||
if (!(hints.containsOscIntroducer ?? data.includes('\x1b]'))) {
|
||||
pendingEscape = data.endsWith('\x1b')
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < data.length; i += 1) {
|
||||
const char = data[i]
|
||||
|
||||
if (inOsc) {
|
||||
if (char === '\x18' || char === '\x1a') {
|
||||
// ECMA-48 escape-cancel codes — abort the in-progress OSC string
|
||||
// so a malformed/truncated OSC does not swallow the next BEL.
|
||||
inOsc = false
|
||||
pendingOscEscape = false
|
||||
continue
|
||||
}
|
||||
|
||||
if (pendingOscEscape) {
|
||||
pendingOscEscape = char === '\x1b'
|
||||
if (char === '\\') {
|
||||
inOsc = false
|
||||
pendingOscEscape = false
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (char === '\x07') {
|
||||
inOsc = false
|
||||
continue
|
||||
}
|
||||
|
||||
pendingOscEscape = char === '\x1b'
|
||||
continue
|
||||
}
|
||||
|
||||
if (pendingEscape) {
|
||||
if (char === '\x18' || char === '\x1a') {
|
||||
// ECMA-48 escape-cancel codes also abort a pending ESC.
|
||||
pendingEscape = false
|
||||
continue
|
||||
}
|
||||
pendingEscape = false
|
||||
if (char === ']') {
|
||||
inOsc = true
|
||||
pendingOscEscape = false
|
||||
} else if (char === '\x1b') {
|
||||
pendingEscape = true
|
||||
} else if (char === '\x07') {
|
||||
// A bare ESC is not a valid introducer for any sequence that
|
||||
// consumes a following BEL. Treat the BEL as a real terminal
|
||||
// bell rather than silently swallowing it with the orphan ESC.
|
||||
return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (char === '\x1b') {
|
||||
pendingEscape = true
|
||||
continue
|
||||
}
|
||||
|
||||
if (char === '\x07') {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
reset(): void {
|
||||
pendingEscape = false
|
||||
inOsc = false
|
||||
pendingOscEscape = false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createTerminalGitHubPRLinkDetector } from './terminal-github-pr-link-detector'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('createTerminalGitHubPRLinkDetector', () => {
|
||||
it('extracts GitHub pull request URLs from terminal output', () => {
|
||||
const observe = createTerminalGitHubPRLinkDetector()
|
||||
|
||||
expect(observe('Created https://github.com/acme/orca/pull/42\r\n')).toEqual([
|
||||
{
|
||||
url: 'https://github.com/acme/orca/pull/42',
|
||||
slug: { owner: 'acme', repo: 'orca' },
|
||||
number: 42
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('waits for a boundary when the URL is split across PTY chunks', () => {
|
||||
const observe = createTerminalGitHubPRLinkDetector()
|
||||
|
||||
expect(observe('https://github.com/acme/orca/pull/4')).toEqual([])
|
||||
expect(observe('2\r\n')).toEqual([
|
||||
{
|
||||
url: 'https://github.com/acme/orca/pull/42',
|
||||
slug: { owner: 'acme', repo: 'orca' },
|
||||
number: 42
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('detects a URL split inside the GitHub prefix', () => {
|
||||
const observe = createTerminalGitHubPRLinkDetector()
|
||||
|
||||
expect(observe('created https://gith')).toEqual([])
|
||||
expect(observe('ub.com/acme/orca/pull/42\n')).toEqual([
|
||||
{
|
||||
url: 'https://github.com/acme/orca/pull/42',
|
||||
slug: { owner: 'acme', repo: 'orca' },
|
||||
number: 42
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('trims terminal punctuation around printed URLs', () => {
|
||||
const observe = createTerminalGitHubPRLinkDetector()
|
||||
|
||||
expect(observe('Opened (https://github.com/acme/orca/pull/42).\n')[0]?.url).toBe(
|
||||
'https://github.com/acme/orca/pull/42'
|
||||
)
|
||||
})
|
||||
|
||||
it('does not repeat the same PR URL from overlapping carry text', () => {
|
||||
const observe = createTerminalGitHubPRLinkDetector()
|
||||
|
||||
expect(observe('https://github.com/acme/orca/pull/42\n')).toHaveLength(1)
|
||||
expect(observe('more output\n')).toEqual([])
|
||||
})
|
||||
|
||||
it('ignores non-PR GitHub-shaped links', () => {
|
||||
const observe = createTerminalGitHubPRLinkDetector()
|
||||
|
||||
expect(observe('https://github.com/acme/orca/issues/42\n')).toEqual([])
|
||||
})
|
||||
|
||||
it('extracts GitHub Enterprise pull request URLs from terminal output', () => {
|
||||
const observe = createTerminalGitHubPRLinkDetector()
|
||||
|
||||
expect(observe('Created https://github.my-company.net/MyOrg/my_repo/pull/395\r\n')).toEqual([
|
||||
{
|
||||
url: 'https://github.my-company.net/MyOrg/my_repo/pull/395',
|
||||
slug: { owner: 'MyOrg', repo: 'my_repo' },
|
||||
number: 395
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('extracts HTTP GitHub Enterprise pull request URLs from terminal output', () => {
|
||||
const observe = createTerminalGitHubPRLinkDetector()
|
||||
|
||||
expect(observe('Created http://github.internal/MyOrg/my_repo/pull/395\r\n')).toEqual([
|
||||
{
|
||||
url: 'http://github.internal/MyOrg/my_repo/pull/395',
|
||||
slug: { owner: 'MyOrg', repo: 'my_repo' },
|
||||
number: 395
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('extracts GitHub Enterprise pull request URLs with a custom port', () => {
|
||||
const observe = createTerminalGitHubPRLinkDetector()
|
||||
|
||||
expect(observe('Created https://github.internal:8443/MyOrg/my_repo/pull/397\r\n')).toEqual([
|
||||
{
|
||||
url: 'https://github.internal:8443/MyOrg/my_repo/pull/397',
|
||||
slug: { owner: 'MyOrg', repo: 'my_repo' },
|
||||
number: 397
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('scans huge terminal chunks containing pull markers without global regex iteration', () => {
|
||||
const matchAll = vi.spyOn(String.prototype, 'matchAll')
|
||||
const observe = createTerminalGitHubPRLinkDetector()
|
||||
const noise = `${'/pull/not-a-url '.repeat(20_000)}\n`
|
||||
|
||||
expect(observe(`${noise}Created https://github.com/acme/orca/pull/42\r\n`)).toEqual([
|
||||
{
|
||||
url: 'https://github.com/acme/orca/pull/42',
|
||||
slug: { owner: 'acme', repo: 'orca' },
|
||||
number: 42
|
||||
}
|
||||
])
|
||||
expect(matchAll).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('drops overlong incomplete URL carry instead of retaining pasted megabytes', () => {
|
||||
const observe = createTerminalGitHubPRLinkDetector()
|
||||
|
||||
expect(observe(`https://github.com/acme/orca/pull/${'4'.repeat(10_000)}`)).toEqual([])
|
||||
expect(observe('2\r\n')).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Chunk-boundary-safe GitHub PR URL scan over PTY output.
|
||||
*
|
||||
* Why shared: terminal-side-effect-authority.md (slice 3) makes main emit
|
||||
* `pr-link` facts from its per-PTY tracker for local/SSH PTYs, while the
|
||||
* renderer keeps byte-scanning for remote-runtime PTYs and the kill-switch-off
|
||||
* path. Both paths must share the carry/dedupe semantics or links split across
|
||||
* chunks would resolve differently per authority mode.
|
||||
*/
|
||||
import type { RepoSlug } from './github-links'
|
||||
import { parseGitHubIssueOrPRLink } from './github-links'
|
||||
|
||||
const GITHUB_PR_PATH_MARKER = '/pull/'
|
||||
const HTTP_SCHEME_PREFIXES = ['https://', 'http://'] as const
|
||||
const TRAILING_TERMINAL_PUNCTUATION_RE = /[),.;\]}]+$/
|
||||
const MAX_CARRY_LENGTH = 512
|
||||
const MAX_TERMINAL_GITHUB_PR_URL_LENGTH = 2048
|
||||
|
||||
export type TerminalGitHubPRLink = {
|
||||
url: string
|
||||
slug: RepoSlug
|
||||
number: number
|
||||
}
|
||||
|
||||
function trimTerminalUrl(candidate: string): string {
|
||||
return candidate.replace(TRAILING_TERMINAL_PUNCTUATION_RE, '')
|
||||
}
|
||||
|
||||
function parseTerminalGitHubPRUrl(candidate: string): TerminalGitHubPRLink | null {
|
||||
const url = trimTerminalUrl(candidate)
|
||||
const parsed = parseGitHubIssueOrPRLink(url)
|
||||
if (!parsed || parsed.type !== 'pr') {
|
||||
return null
|
||||
}
|
||||
return { url, slug: parsed.slug, number: parsed.number }
|
||||
}
|
||||
|
||||
function endsWithHttpSchemePrefixFragment(value: string): string {
|
||||
for (const prefix of HTTP_SCHEME_PREFIXES) {
|
||||
for (let length = Math.min(prefix.length - 1, value.length); length > 0; length--) {
|
||||
if (value.endsWith(prefix.slice(0, length))) {
|
||||
return value.slice(value.length - length)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function getPotentialGitHubPRCarry(value: string): string {
|
||||
const schemeIndex = Math.max(...HTTP_SCHEME_PREFIXES.map((prefix) => value.lastIndexOf(prefix)))
|
||||
if (schemeIndex !== -1) {
|
||||
const tailLength = value.length - schemeIndex
|
||||
if (tailLength > MAX_CARRY_LENGTH) {
|
||||
return ''
|
||||
}
|
||||
return hasTerminalUrlWhitespace(value, schemeIndex, value.length)
|
||||
? ''
|
||||
: value.slice(schemeIndex)
|
||||
}
|
||||
|
||||
return endsWithHttpSchemePrefixFragment(value)
|
||||
}
|
||||
|
||||
function hasTerminalUrlWhitespace(value: string, start: number, end: number): boolean {
|
||||
for (let index = start; index < end; index += 1) {
|
||||
if (/\s/.test(value.charAt(index))) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type TerminalUrlCandidate = {
|
||||
rawUrl: string
|
||||
endIndex: number
|
||||
}
|
||||
|
||||
function findNextHttpSchemeIndex(value: string, start: number): number {
|
||||
let nextIndex = -1
|
||||
for (const prefix of HTTP_SCHEME_PREFIXES) {
|
||||
const candidate = value.indexOf(prefix, start)
|
||||
if (candidate !== -1 && (nextIndex === -1 || candidate < nextIndex)) {
|
||||
nextIndex = candidate
|
||||
}
|
||||
}
|
||||
return nextIndex
|
||||
}
|
||||
|
||||
function isTerminalUrlTerminator(char: string): boolean {
|
||||
return char === '"' || char === "'" || char === '<' || char === '>' || /\s/.test(char)
|
||||
}
|
||||
|
||||
function findTerminalUrlCandidateEnd(value: string, start: number): number {
|
||||
const scanEnd = Math.min(value.length, start + MAX_TERMINAL_GITHUB_PR_URL_LENGTH + 1)
|
||||
for (let index = start; index < scanEnd; index += 1) {
|
||||
if (isTerminalUrlTerminator(value.charAt(index))) {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return scanEnd
|
||||
}
|
||||
|
||||
function* iterateTerminalUrlCandidates(value: string): Generator<TerminalUrlCandidate> {
|
||||
let searchStart = 0
|
||||
|
||||
while (searchStart < value.length) {
|
||||
const candidateStart = findNextHttpSchemeIndex(value, searchStart)
|
||||
if (candidateStart === -1) {
|
||||
return
|
||||
}
|
||||
|
||||
const candidateEnd = findTerminalUrlCandidateEnd(value, candidateStart)
|
||||
const rawUrl = value.slice(candidateStart, candidateEnd)
|
||||
searchStart = Math.max(candidateEnd, candidateStart + 1)
|
||||
if (
|
||||
rawUrl.length > MAX_TERMINAL_GITHUB_PR_URL_LENGTH ||
|
||||
!rawUrl.includes(GITHUB_PR_PATH_MARKER)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
yield { rawUrl, endIndex: candidateEnd }
|
||||
}
|
||||
}
|
||||
|
||||
export function createTerminalGitHubPRLinkDetector(): (data: string) => TerminalGitHubPRLink[] {
|
||||
let carry = ''
|
||||
const seenUrls = new Set<string>()
|
||||
|
||||
return (data: string): TerminalGitHubPRLink[] => {
|
||||
const combined = carry ? carry + data : data
|
||||
|
||||
if (!combined.includes(GITHUB_PR_PATH_MARKER)) {
|
||||
carry = getPotentialGitHubPRCarry(combined)
|
||||
return []
|
||||
}
|
||||
|
||||
const links: TerminalGitHubPRLink[] = []
|
||||
// Why: PTY data may echo a huge pasted line. Scan URL candidates directly
|
||||
// instead of running a global regex across the whole chunk when it contains
|
||||
// a /pull/ substring.
|
||||
for (const { rawUrl, endIndex } of iterateTerminalUrlCandidates(combined)) {
|
||||
// Why: PTY chunks can split the PR number; wait for a boundary before
|
||||
// treating a URL at chunk-end as complete.
|
||||
if (endIndex === combined.length) {
|
||||
continue
|
||||
}
|
||||
|
||||
const parsed = parseTerminalGitHubPRUrl(rawUrl)
|
||||
if (!parsed || seenUrls.has(parsed.url)) {
|
||||
continue
|
||||
}
|
||||
seenUrls.add(parsed.url)
|
||||
links.push(parsed)
|
||||
}
|
||||
|
||||
carry = getPotentialGitHubPRCarry(combined)
|
||||
return links
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Chunk-boundary-safe OSC 133;D (command finished) scanner.
|
||||
*
|
||||
* Why shared: terminal-side-effect-authority.md (slice 3) makes main emit
|
||||
* `command-finished` facts from its per-PTY tracker for local/SSH PTYs, while
|
||||
* the renderer keeps byte-parsing for remote-runtime PTYs and the
|
||||
* kill-switch-off path. The carry semantics (split prefixes, BEL/ST
|
||||
* terminators, best-effort exit codes) must be identical in both.
|
||||
*/
|
||||
|
||||
type OscTerminator = {
|
||||
index: number
|
||||
length: number
|
||||
}
|
||||
|
||||
const OSC_133_PREFIX = '\x1b]133;'
|
||||
const MAX_OSC_CARRY_LENGTH = 4096
|
||||
|
||||
function findOscTerminator(data: string, startIndex: number): OscTerminator | null {
|
||||
const bel = data.indexOf('\x07', startIndex)
|
||||
const st = data.indexOf('\x1b\\', startIndex)
|
||||
|
||||
if (bel === -1 && st === -1) {
|
||||
return null
|
||||
}
|
||||
if (bel !== -1 && (st === -1 || bel < st)) {
|
||||
return { index: bel, length: 1 }
|
||||
}
|
||||
return { index: st, length: 2 }
|
||||
}
|
||||
|
||||
function parseBestEffortExitCode(value: string | undefined): number | null {
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
const parsed = Number.parseInt(value, 10)
|
||||
return Number.isNaN(parsed) ? null : parsed
|
||||
}
|
||||
|
||||
function findPrefixCarry(data: string): string {
|
||||
const maxCarryLength = Math.min(data.length, OSC_133_PREFIX.length - 1)
|
||||
for (let length = maxCarryLength; length > 0; length -= 1) {
|
||||
const suffix = data.slice(data.length - length)
|
||||
if (OSC_133_PREFIX.startsWith(suffix)) {
|
||||
return suffix
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
export type Osc133CommandFinishedScanner = {
|
||||
/** Feed one raw PTY chunk; fires once per complete OSC 133;D sequence. */
|
||||
scan: (data: string) => void
|
||||
/** Drop the cross-chunk carry (transport teardown / parser reset). */
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
export function createOsc133CommandFinishedScanner(
|
||||
onCommandFinished: (bestEffortExitCode: number | null) => void,
|
||||
/** OSC 133;C — the shell exec'd a command; the pane's foreground changed. */
|
||||
onCommandStarted?: () => void
|
||||
): Osc133CommandFinishedScanner {
|
||||
let carry = ''
|
||||
|
||||
const handleOsc133 = (payload: string): void => {
|
||||
const [sequence, exitCode] = payload.split(';')
|
||||
if (sequence === 'C') {
|
||||
onCommandStarted?.()
|
||||
return
|
||||
}
|
||||
if (sequence === 'D') {
|
||||
onCommandFinished(parseBestEffortExitCode(exitCode))
|
||||
}
|
||||
}
|
||||
|
||||
const scan = (data: string): void => {
|
||||
let combined = carry + data
|
||||
carry = ''
|
||||
|
||||
while (combined.length > 0) {
|
||||
const start = combined.indexOf(OSC_133_PREFIX)
|
||||
if (start === -1) {
|
||||
carry = findPrefixCarry(combined)
|
||||
return
|
||||
}
|
||||
|
||||
const payloadStart = start + OSC_133_PREFIX.length
|
||||
const terminator = findOscTerminator(combined, payloadStart)
|
||||
if (!terminator) {
|
||||
carry = combined.slice(start)
|
||||
if (carry.length > MAX_OSC_CARRY_LENGTH) {
|
||||
carry = carry.slice(carry.length - MAX_OSC_CARRY_LENGTH)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
handleOsc133(combined.slice(payloadStart, terminator.index))
|
||||
combined = combined.slice(terminator.index + terminator.length)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
scan,
|
||||
reset() {
|
||||
carry = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
// Why: slice 3 of terminal-side-effect-authority.md adds OSC 133;D
|
||||
// command-finished and GitHub pr-link scanning to the shared tracker so main
|
||||
// emits those facts for local/SSH PTYs. These tests pin the chunk-boundary
|
||||
// carry, exit-code best-effort, dedupe, and synthetic-frame isolation rules.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
createTerminalTitleTracker,
|
||||
type TerminalTitleTrackerCallbacks
|
||||
} from './terminal-output-side-effects'
|
||||
|
||||
const ESC = '\x1b'
|
||||
const BEL = '\x07'
|
||||
const ST = `${ESC}\\`
|
||||
|
||||
type RecordedEvent =
|
||||
| ['title', string]
|
||||
| ['bell']
|
||||
| ['finished', number | null]
|
||||
| ['pr', string, number]
|
||||
| ['2031-subscribe']
|
||||
|
||||
function createRecordingTracker(overrides: TerminalTitleTrackerCallbacks = {}): {
|
||||
events: RecordedEvent[]
|
||||
tracker: ReturnType<typeof createTerminalTitleTracker>
|
||||
} {
|
||||
const events: RecordedEvent[] = []
|
||||
const tracker = createTerminalTitleTracker({
|
||||
onTitle: (normalized) => events.push(['title', normalized]),
|
||||
onBell: () => events.push(['bell']),
|
||||
onCommandFinished: (exitCode) => events.push(['finished', exitCode]),
|
||||
onPrLink: (link) => events.push(['pr', link.url, link.number]),
|
||||
onMode2031Subscribe: () => events.push(['2031-subscribe']),
|
||||
...overrides
|
||||
})
|
||||
return { events, tracker }
|
||||
}
|
||||
|
||||
describe('createTerminalTitleTracker command-finished facts', () => {
|
||||
it('emits command-finished with best-effort exit codes', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
tracker.handleChunk(`before${ESC}]133;A${BEL}prompt${ESC}]133;B${BEL}`)
|
||||
tracker.handleChunk(`${ESC}]133;C${BEL}running${ESC}]133;D;0${BEL}`)
|
||||
tracker.handleChunk(`${ESC}]133;D;130${BEL}`)
|
||||
tracker.handleChunk(`${ESC}]133;D;not-a-number${BEL}`)
|
||||
tracker.handleChunk(`${ESC}]133;D${BEL}`)
|
||||
|
||||
expect(events).toEqual([
|
||||
['finished', 0],
|
||||
['finished', 130],
|
||||
['finished', null],
|
||||
['finished', null]
|
||||
])
|
||||
})
|
||||
|
||||
it('detects OSC 133;D split across chunk boundaries (BEL and ST terminated)', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
tracker.handleChunk(`chunk${ESC}]133`)
|
||||
tracker.handleChunk(';D;1')
|
||||
expect(events).toEqual([])
|
||||
tracker.handleChunk(`30${BEL}rest`)
|
||||
tracker.handleChunk(`${ESC}]133;D;7${ST}`)
|
||||
|
||||
expect(events).toEqual([
|
||||
['finished', 130],
|
||||
['finished', 7]
|
||||
])
|
||||
})
|
||||
|
||||
it('orders chunk facts titles → command-finished → bell', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
tracker.handleChunk(`${ESC}]0;zsh${BEL}${ESC}]133;D;0${BEL}done${BEL}`)
|
||||
|
||||
expect(events).toEqual([['title', 'zsh'], ['finished', 0], ['bell']])
|
||||
})
|
||||
})
|
||||
|
||||
describe('createTerminalTitleTracker pr-link facts', () => {
|
||||
it('emits one fact per PR URL including multiple links in one chunk', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
tracker.handleChunk(
|
||||
'see https://github.com/acme/orca/pull/42 and https://github.com/acme/orca/pull/43 \r\n'
|
||||
)
|
||||
|
||||
expect(events).toEqual([
|
||||
['pr', 'https://github.com/acme/orca/pull/42', 42],
|
||||
['pr', 'https://github.com/acme/orca/pull/43', 43]
|
||||
])
|
||||
})
|
||||
|
||||
it('waits for a boundary when a URL splits across chunks and dedupes repeats', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
tracker.handleChunk('PR: https://github.com/acme/orca/pull/4')
|
||||
expect(events).toEqual([])
|
||||
tracker.handleChunk('2\r\n')
|
||||
tracker.handleChunk('again https://github.com/acme/orca/pull/42\r\n')
|
||||
|
||||
expect(events).toEqual([['pr', 'https://github.com/acme/orca/pull/42', 42]])
|
||||
})
|
||||
|
||||
it('skips the 133/URL scans entirely when no consumer is registered', () => {
|
||||
// Mirrors headless serve: no pty:sideEffect consumer means no callbacks,
|
||||
// so the scanners must not be created (no carry state, no scan cost).
|
||||
const titles: string[] = []
|
||||
const tracker = createTerminalTitleTracker({
|
||||
onTitle: (normalized) => titles.push(normalized)
|
||||
})
|
||||
|
||||
tracker.handleChunk(`${ESC}]133;D;0${BEL}https://github.com/acme/orca/pull/42\r\n`)
|
||||
|
||||
expect(titles).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('createTerminalTitleTracker 2031-subscribe facts', () => {
|
||||
it('emits a fact per chunk containing a DECSET 2031 subscribe, before the bell', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
tracker.handleChunk(`${ESC}[?2031hready${BEL}`)
|
||||
|
||||
expect(events).toEqual([['2031-subscribe'], ['bell']])
|
||||
})
|
||||
|
||||
it('detects a subscribe split across chunk boundaries', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
tracker.handleChunk(`${ESC}[?20`)
|
||||
tracker.handleChunk('31h')
|
||||
|
||||
expect(events).toEqual([['2031-subscribe']])
|
||||
})
|
||||
|
||||
it('ignores DECSET 2031 unsubscribes', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
tracker.handleChunk(`${ESC}[?2031l`)
|
||||
|
||||
expect(events).toEqual([])
|
||||
})
|
||||
|
||||
it('skips the 2031 scan entirely when no consumer is registered', () => {
|
||||
const { events, tracker } = createRecordingTracker({ onMode2031Subscribe: undefined })
|
||||
|
||||
tracker.handleChunk(`${ESC}[?2031h`)
|
||||
|
||||
expect(events).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('createTerminalTitleTracker synthetic-frame isolation', () => {
|
||||
it('never feeds synthetic frames to the 133/PR scanners', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
tracker.applySyntheticTitleFrame(
|
||||
`${ESC}]0;⠋ Cursor Agent${BEL}${ESC}]133;D;0${BEL}https://github.com/acme/orca/pull/42\r\n`
|
||||
)
|
||||
|
||||
expect(events).toEqual([['title', '⠋ Cursor Agent']])
|
||||
})
|
||||
|
||||
it('keeps a split 133 carry intact across an interleaved synthetic frame', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
tracker.handleChunk(`out${ESC}]133;D;`)
|
||||
// An 80ms spinner tick lands between the two halves of the real OSC.
|
||||
tracker.applySyntheticTitleFrame(`${ESC}]0;⠋ Cursor Agent${BEL}`)
|
||||
tracker.handleChunk(`130${BEL}`)
|
||||
|
||||
expect(events).toEqual([
|
||||
['title', '⠋ Cursor Agent'],
|
||||
['finished', 130]
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('createTerminalTitleTracker transient-fact scanning suppression', () => {
|
||||
it('skips bell/133/pr-link/2031 while suppressed but keeps title processing', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
tracker.setTransientFactScanningSuppressed(true)
|
||||
tracker.handleChunk(
|
||||
`${ESC}]0;zsh${BEL}${ESC}]133;D;0${BEL}ding${BEL}https://github.com/acme/orca/pull/42\r\n${ESC}[?2031h`
|
||||
)
|
||||
|
||||
expect(events).toEqual([['title', 'zsh']])
|
||||
})
|
||||
|
||||
it('resets cross-chunk carry on un-suppress so a pre-gap half-open OSC cannot swallow bells', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
// The OSC terminator (and everything after) is lost in a delivery gap
|
||||
// while scanning is suppressed.
|
||||
tracker.handleChunk(`${ESC}]0;my long title without terminator`)
|
||||
tracker.setTransientFactScanningSuppressed(true)
|
||||
tracker.setTransientFactScanningSuppressed(false)
|
||||
// Post-gap: a real standalone bell. A stale "inside OSC" state would
|
||||
// swallow it.
|
||||
tracker.handleChunk(`done${BEL}`)
|
||||
|
||||
expect(events).toEqual([['bell']])
|
||||
})
|
||||
|
||||
it('a handoff scan seed re-primes a split sequence so its fact fires once, without a phantom bell', () => {
|
||||
const { events, tracker } = createRecordingTracker()
|
||||
|
||||
// The 133 intro was consumed before scan authority moved away; the carry
|
||||
// is reset on un-suppress. The transport hands back the emulator's
|
||||
// partial escape tail as a seed, so the continuation completes normally:
|
||||
// one command-finished, and its terminator BEL is NOT a standalone bell.
|
||||
tracker.handleChunk(`out${ESC}]133;D;`)
|
||||
tracker.setTransientFactScanningSuppressed(true)
|
||||
tracker.setTransientFactScanningSuppressed(false)
|
||||
tracker.handleChunk(`${ESC}]133;D;`, { titleScanData: '' })
|
||||
tracker.handleChunk(`130${BEL}`)
|
||||
|
||||
expect(events).toEqual([['finished', 130]])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,326 @@
|
||||
/**
|
||||
* Shared per-PTY terminal title side-effect tracking — the parser core behind
|
||||
* both the renderer transport (`createPtyOutputProcessor`) and main's
|
||||
* per-PTY tracker in `OrcaRuntimeService.onPtyData`.
|
||||
*
|
||||
* Why shared: docs/reference/terminal-side-effect-authority.md makes main the
|
||||
* side-effect parser for every PTY whose bytes transit local main. Title
|
||||
* semantics (all-titles ordering, cursor-agent literal drop, normalization,
|
||||
* stale-working-title clearing) must not drift between the two paths.
|
||||
*/
|
||||
|
||||
import {
|
||||
clearWorkingIndicators,
|
||||
createAgentStatusTracker,
|
||||
detectAgentStatusFromTitle,
|
||||
extractAllOscTitles,
|
||||
isCursorNativeAgentTitle,
|
||||
normalizeTerminalTitle
|
||||
} from './agent-detection'
|
||||
import { createBellDetector } from './terminal-bell-detector'
|
||||
import { scanMode2031Sequences } from './terminal-color-scheme-protocol'
|
||||
import {
|
||||
createTerminalGitHubPRLinkDetector,
|
||||
type TerminalGitHubPRLink
|
||||
} from './terminal-github-pr-link-detector'
|
||||
import { createOsc133CommandFinishedScanner } from './terminal-osc133-command-finished'
|
||||
|
||||
/** Ms of title-less output after a working title before it is cleared. */
|
||||
export const STALE_WORKING_TITLE_TIMEOUT_MS = 3000
|
||||
|
||||
// Braille spinner frame glyphs (U+2800–U+28FF) — the decorative animation
|
||||
// class agents rotate through while working. Mirrors the range
|
||||
// clearWorkingIndicators strips in agent-detection.ts.
|
||||
// eslint-disable-next-line no-control-regex -- intentional unicode range
|
||||
const BRAILLE_SPINNER_RE = /[\u2800-\u28FF]/g
|
||||
|
||||
/**
|
||||
* Strip decorative braille spinner frame glyphs for change comparisons.
|
||||
* Two working titles that differ only by the animation frame (e.g.
|
||||
* "⠋ Cursor Agent" vs "⠙ Cursor Agent") compare equal after stripping —
|
||||
* the gate consumers use to avoid fan-out churn on spinner ticks.
|
||||
*/
|
||||
export function stripBrailleSpinnerGlyphs(title: string): string {
|
||||
return title.replace(BRAILLE_SPINNER_RE, '').trim()
|
||||
}
|
||||
|
||||
/** Provenance for title/idle facts. `staleWorkingTitleClear` marks facts
|
||||
* synthesized by the 3s stale-working-title timer rather than observed
|
||||
* bytes — consumers must not treat them as genuine task completions. */
|
||||
export type TerminalTitleFactMeta = {
|
||||
staleWorkingTitleClear?: boolean
|
||||
}
|
||||
|
||||
export type TerminalTitleTrackerCallbacks = {
|
||||
/**
|
||||
* Fired once per observed OSC title, in byte order — including the
|
||||
* synthesized cleared title when the stale-working timer fires.
|
||||
*/
|
||||
onTitle?: (normalizedTitle: string, rawTitle: string, meta?: TerminalTitleFactMeta) => void
|
||||
onAgentBecameIdle?: (title: string, meta?: TerminalTitleFactMeta) => void
|
||||
onAgentBecameWorking?: () => void
|
||||
onAgentExited?: () => void
|
||||
/**
|
||||
* Fired once per chunk containing a real BEL (OSC-aware, escape state kept
|
||||
* across chunks), after the chunk's title facts — the renderer drain order.
|
||||
*/
|
||||
onBell?: () => void
|
||||
/**
|
||||
* Fired per complete OSC 133;D (chunk-boundary-safe) with the sequence's
|
||||
* best-effort exit code — mirrors the renderer terminal-command-lifecycle
|
||||
* semantics so the fact path drops stale agent rows exactly like byte mode.
|
||||
*/
|
||||
onCommandFinished?: (bestEffortExitCode: number | null) => void
|
||||
/** Fired once per newly observed GitHub PR URL (chunk-boundary-safe,
|
||||
* deduplicated per tracker like the renderer detector). */
|
||||
onPrLink?: (link: TerminalGitHubPRLink) => void
|
||||
/**
|
||||
* Fired per chunk containing a DECSET 2031 subscribe (chunk-boundary-safe).
|
||||
* Lets hidden-delivery-gated renderer views answer the color-scheme query
|
||||
* without byte access; the reply itself stays with the view.
|
||||
*/
|
||||
onMode2031Subscribe?: () => void
|
||||
}
|
||||
|
||||
export type TerminalTitleTracker = {
|
||||
/** Feed one raw PTY chunk; titles are applied synchronously in byte order. */
|
||||
handleChunk: (data: string, options?: { titleScanData?: string }) => void
|
||||
/**
|
||||
* Apply a main-fabricated OSC title/BEL frame (agent hook spinner frames).
|
||||
* Parsed statelessly — never through the chunk bell detector — so a
|
||||
* synthetic tick landing between two real chunks that split an OSC cannot
|
||||
* corrupt the cross-chunk escape state into phantom or swallowed bells.
|
||||
*/
|
||||
applySyntheticTitleFrame: (frame: string) => void
|
||||
/**
|
||||
* Seed the last-known title for a tracker created mid-session (app relaunch
|
||||
* with persisted/snapshot titles). No-ops once any title has been observed
|
||||
* or seeded — live state always wins. Fires no callbacks.
|
||||
*/
|
||||
seedInitialTitle: (rawTitle: string) => void
|
||||
/** Last title surfaced through onTitle, after normalization. */
|
||||
getLastNormalizedTitle: () => string | null
|
||||
/**
|
||||
* While suppressed, handleChunk skips the four transient-fact scanners
|
||||
* (bell/133/pr-link/2031) — a thinning transport holds scan authority for
|
||||
* this PTY and relays their facts itself; feeding the (possibly gapped)
|
||||
* delivered bytes here would mint phantom or duplicate facts. Title
|
||||
* processing is unaffected. Un-suppressing resets the scanners' cross-chunk
|
||||
* carry: their last-fed byte predates the gap.
|
||||
*/
|
||||
setTransientFactScanningSuppressed: (suppressed: boolean) => void
|
||||
/** Cancel the stale-title timer and clear accumulated tracker state. */
|
||||
dispose: () => void
|
||||
}
|
||||
|
||||
export function createTerminalTitleTracker(
|
||||
callbacks: TerminalTitleTrackerCallbacks,
|
||||
options: { initialTitle?: string } = {}
|
||||
): TerminalTitleTracker {
|
||||
const {
|
||||
onTitle,
|
||||
onAgentBecameIdle,
|
||||
onAgentBecameWorking,
|
||||
onAgentExited,
|
||||
onBell,
|
||||
onCommandFinished,
|
||||
onPrLink,
|
||||
onMode2031Subscribe
|
||||
} = callbacks
|
||||
const bellDetector = onBell ? createBellDetector() : null
|
||||
// Why: created only when a consumer exists (like the bell detector) so
|
||||
// headless serve never pays the per-chunk 133/URL scans.
|
||||
const commandFinishedScanner = onCommandFinished
|
||||
? createOsc133CommandFinishedScanner(onCommandFinished)
|
||||
: null
|
||||
let prLinkDetector = onPrLink ? createTerminalGitHubPRLinkDetector() : null
|
||||
let transientFactScanningSuppressed = false
|
||||
// Why: a DECSET 2031 subscribe can be split across PTY chunks; carry a
|
||||
// bounded tail between chunks so split sequences still match.
|
||||
let mode2031ScanTail = ''
|
||||
// Why: seed both the emitted-title memory (stale-title probe) and the agent
|
||||
// tracker so a mid-session tracker behaves as if it had observed the pane's
|
||||
// last live title — parity with the renderer processor's seeding.
|
||||
let lastEmittedTitle: string | null =
|
||||
options.initialTitle !== undefined ? normalizeTerminalTitle(options.initialTitle) : null
|
||||
let staleTitleTimer: ReturnType<typeof setTimeout> | null = null
|
||||
// Why: set while the stale timer's cleared title flows through the agent
|
||||
// tracker so the resulting idle callback carries timer provenance — the
|
||||
// renderer must not turn a stale clear into a task-complete notification.
|
||||
let applyingStaleWorkingTitleClear = false
|
||||
const agentTracker =
|
||||
onAgentBecameIdle || onAgentBecameWorking || onAgentExited
|
||||
? createAgentStatusTracker(
|
||||
(title) => {
|
||||
onAgentBecameIdle?.(
|
||||
title,
|
||||
applyingStaleWorkingTitleClear ? { staleWorkingTitleClear: true } : undefined
|
||||
)
|
||||
},
|
||||
onAgentBecameWorking,
|
||||
onAgentExited,
|
||||
options.initialTitle
|
||||
)
|
||||
: null
|
||||
|
||||
function clearStaleTitleTimer(): void {
|
||||
if (staleTitleTimer) {
|
||||
clearTimeout(staleTitleTimer)
|
||||
staleTitleTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
function applyObservedTitle(rawTitle: string): void {
|
||||
// Why: cursor-agent re-emits its bare native title many times per turn
|
||||
// while still working; letting it through would stomp Orca's synthesized
|
||||
// "⠋ Cursor Agent" spinner state back to agentless within a second.
|
||||
if (isCursorNativeAgentTitle(rawTitle)) {
|
||||
return
|
||||
}
|
||||
lastEmittedTitle = normalizeTerminalTitle(rawTitle)
|
||||
onTitle?.(lastEmittedTitle, rawTitle)
|
||||
agentTracker?.handleTitle(rawTitle)
|
||||
}
|
||||
|
||||
function handleChunk(data: string, options: { titleScanData?: string } = {}): void {
|
||||
const titleScanData = options.titleScanData ?? data
|
||||
// Why: this is main's per-chunk hot path — scan for the OSC introducer
|
||||
// once and share the result with the bell detector's fast-path gate.
|
||||
const containsOscIntroducer = data.includes('\x1b]')
|
||||
// Why: the bell detector must consume EVERY chunk so OSC sequences that
|
||||
// span chunk boundaries keep their escape state, even when the chunk has
|
||||
// no title. The fact itself is surfaced after the chunk's titles, the
|
||||
// renderer drain's order (payloads → titles → bell). While suppressed it
|
||||
// must consume NONE: the delivered bytes may be gapped.
|
||||
const containsBell =
|
||||
bellDetector && !transientFactScanningSuppressed
|
||||
? bellDetector.chunkContainsBell(data, { containsOscIntroducer })
|
||||
: false
|
||||
// Why: feed EVERY OSC title in the chunk in byte order, never just the
|
||||
// last one. node-pty plus the main-process batch window commonly coalesce
|
||||
// multiple title updates into a single payload; a last-title reader drops
|
||||
// intra-chunk working→idle transitions (issue #1083).
|
||||
const titles = titleScanData.includes('\x1b]') ? extractAllOscTitles(titleScanData) : []
|
||||
if (titles.length > 0) {
|
||||
clearStaleTitleTimer()
|
||||
for (const title of titles) {
|
||||
applyObservedTitle(title)
|
||||
}
|
||||
} else if (
|
||||
// Why: agents that exit without resetting their title leave a stale
|
||||
// working spinner behind. Any title-less output while the last title
|
||||
// classifies as working restarts a 3s timer that rewrites the title to
|
||||
// its cleared form — the renderer transport's stale-title semantics.
|
||||
data.length > 0 &&
|
||||
lastEmittedTitle !== null &&
|
||||
detectAgentStatusFromTitle(lastEmittedTitle) === 'working'
|
||||
) {
|
||||
clearStaleTitleTimer()
|
||||
staleTitleTimer = setTimeout(() => {
|
||||
staleTitleTimer = null
|
||||
if (lastEmittedTitle && detectAgentStatusFromTitle(lastEmittedTitle) === 'working') {
|
||||
const cleared = clearWorkingIndicators(lastEmittedTitle)
|
||||
lastEmittedTitle = cleared
|
||||
// Why: tag timer-synthesized facts. Main's timer is unthrottled
|
||||
// (unlike the renderer timers that previously damped this path in
|
||||
// hidden windows), so a merely-paused agent must be distinguishable
|
||||
// from a genuine working→idle completion downstream.
|
||||
applyingStaleWorkingTitleClear = true
|
||||
try {
|
||||
onTitle?.(cleared, cleared, { staleWorkingTitleClear: true })
|
||||
agentTracker?.handleTitle(cleared)
|
||||
} finally {
|
||||
applyingStaleWorkingTitleClear = false
|
||||
}
|
||||
}
|
||||
}, STALE_WORKING_TITLE_TIMEOUT_MS)
|
||||
}
|
||||
// Per-chunk fact order: titles → command-finished → pr-link →
|
||||
// 2031-subscribe → bell. The bell stays last (the renderer drain's
|
||||
// order); the byte scanners keep their own cross-chunk carry so split
|
||||
// sequences/URLs still resolve.
|
||||
if (!transientFactScanningSuppressed) {
|
||||
commandFinishedScanner?.scan(data)
|
||||
if (prLinkDetector) {
|
||||
for (const link of prLinkDetector(data)) {
|
||||
onPrLink?.(link)
|
||||
}
|
||||
}
|
||||
if (onMode2031Subscribe) {
|
||||
const mode2031Scan = scanMode2031Sequences(mode2031ScanTail, data)
|
||||
mode2031ScanTail = mode2031Scan.tail
|
||||
if (mode2031Scan.subscribe) {
|
||||
onMode2031Subscribe()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (containsBell) {
|
||||
onBell?.()
|
||||
}
|
||||
}
|
||||
|
||||
function applySyntheticTitleFrame(frame: string): void {
|
||||
// Why: synthetic frames have an exact main-fabricated shape, so they are
|
||||
// parsed statelessly here. Feeding them through handleChunk would run the
|
||||
// stateful bell detector: a tick landing while a REAL OSC is split across
|
||||
// two chunks would consume the pending escape state, minting a phantom
|
||||
// bell from the continuation chunk or swallowing a real one.
|
||||
const titles = extractAllOscTitles(frame)
|
||||
if (titles.length > 0) {
|
||||
clearStaleTitleTimer()
|
||||
for (const title of titles) {
|
||||
applyObservedTitle(title)
|
||||
}
|
||||
}
|
||||
// The deliberate permission BEL rides outside the OSC title sequence. A
|
||||
// FRESH detector instance keeps the OSC-terminator-vs-bell semantics
|
||||
// while guaranteeing zero interaction with the chunk detector's state.
|
||||
// Synthetic frames never reach the 133/PR-link scanners: fabricated bytes
|
||||
// contain neither and must not perturb their cross-chunk carry state.
|
||||
if (onBell && createBellDetector().chunkContainsBell(frame)) {
|
||||
onBell()
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
handleChunk,
|
||||
applySyntheticTitleFrame,
|
||||
seedInitialTitle(rawTitle: string): void {
|
||||
// Why: the cursor-agent literal drop applies to seeds too — restoring
|
||||
// the bare native title would stomp synthesized spinner state exactly
|
||||
// like emitting it live would.
|
||||
if (lastEmittedTitle !== null || !rawTitle || isCursorNativeAgentTitle(rawTitle)) {
|
||||
return
|
||||
}
|
||||
lastEmittedTitle = normalizeTerminalTitle(rawTitle)
|
||||
agentTracker?.seedTitle(rawTitle)
|
||||
},
|
||||
getLastNormalizedTitle: () => lastEmittedTitle,
|
||||
setTransientFactScanningSuppressed(suppressed: boolean): void {
|
||||
if (suppressed === transientFactScanningSuppressed) {
|
||||
return
|
||||
}
|
||||
transientFactScanningSuppressed = suppressed
|
||||
if (!suppressed) {
|
||||
// Cross-chunk carry predates the suppressed (gapped) span — a stale
|
||||
// half-open OSC would swallow real bells; a stale 133/2031 tail or
|
||||
// URL fragment would mint phantom facts. The PR-link dedup memory is
|
||||
// lost with the recreate; a re-printed link may re-fire (consumers
|
||||
// treat pr-link as a latest-association update).
|
||||
bellDetector?.reset()
|
||||
commandFinishedScanner?.reset()
|
||||
mode2031ScanTail = ''
|
||||
if (prLinkDetector) {
|
||||
prLinkDetector = createTerminalGitHubPRLinkDetector()
|
||||
}
|
||||
}
|
||||
},
|
||||
dispose(): void {
|
||||
clearStaleTitleTimer()
|
||||
agentTracker?.reset()
|
||||
bellDetector?.reset()
|
||||
commandFinishedScanner?.reset()
|
||||
mode2031ScanTail = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// Terminal-output scanning for reply-eliciting query sequences (DSR/CPR,
|
||||
// DA1/DA2, DECRQM, XTGETTCAP-adjacent CSI queries, OSC 10/11 color probes).
|
||||
// Shared because both sides must salvage queries out of bytes they are about
|
||||
// to drop: the renderer's hidden-output restore queue and main's pending-cap
|
||||
// bulk drop. A swallowed query means the program that sent it waits forever
|
||||
// for a reply (the bench DSR timeout).
|
||||
import { parseTerminalOscColorQuery } from './terminal-osc-color-reply'
|
||||
|
||||
export const HIDDEN_STARTUP_RENDERER_QUERY_PENDING_CHARS = 64
|
||||
|
||||
export type ExtractedRendererQueryData = {
|
||||
statelessQueryData: string
|
||||
statefulQueryData: string
|
||||
oscColorQueryData: string
|
||||
pending: string
|
||||
}
|
||||
|
||||
export function extractHiddenStartupRendererQueryData(
|
||||
data: string,
|
||||
pending: string
|
||||
): ExtractedRendererQueryData {
|
||||
const input = pending + data
|
||||
let statelessQueryData = ''
|
||||
let statefulQueryData = ''
|
||||
let oscColorQueryData = ''
|
||||
let offset = 0
|
||||
|
||||
while (offset < input.length) {
|
||||
const candidateIndex = input.indexOf('\x1b', offset)
|
||||
if (candidateIndex === -1) {
|
||||
break
|
||||
}
|
||||
if (candidateIndex + 1 >= input.length) {
|
||||
return {
|
||||
statelessQueryData,
|
||||
statefulQueryData,
|
||||
oscColorQueryData,
|
||||
pending: input.slice(candidateIndex)
|
||||
}
|
||||
}
|
||||
if (input.startsWith('\x1b[', candidateIndex)) {
|
||||
const finalByteIndex = findCsiFinalByteIndex(input, candidateIndex + 2)
|
||||
if (finalByteIndex === -1) {
|
||||
return {
|
||||
statelessQueryData,
|
||||
statefulQueryData,
|
||||
oscColorQueryData,
|
||||
pending: input.slice(
|
||||
candidateIndex,
|
||||
candidateIndex + HIDDEN_STARTUP_RENDERER_QUERY_PENDING_CHARS
|
||||
)
|
||||
}
|
||||
}
|
||||
const sequence = input.slice(candidateIndex, finalByteIndex + 1)
|
||||
if (isStatelessRendererReplyCsiQuery(sequence)) {
|
||||
statelessQueryData += sequence
|
||||
} else if (isStatefulRendererReplyCsiQuery(sequence)) {
|
||||
statefulQueryData += sequence
|
||||
}
|
||||
offset = finalByteIndex + 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (input.startsWith('\x1b]', candidateIndex)) {
|
||||
const query = parseTerminalOscColorQuery(input, candidateIndex)
|
||||
if (query.kind === 'partial') {
|
||||
return {
|
||||
statelessQueryData,
|
||||
statefulQueryData,
|
||||
oscColorQueryData,
|
||||
pending: input.slice(
|
||||
candidateIndex,
|
||||
candidateIndex + HIDDEN_STARTUP_RENDERER_QUERY_PENDING_CHARS
|
||||
)
|
||||
}
|
||||
}
|
||||
if (query.kind === 'none') {
|
||||
offset = candidateIndex + 2
|
||||
continue
|
||||
}
|
||||
oscColorQueryData += input.slice(candidateIndex, query.endIndex)
|
||||
offset = query.endIndex
|
||||
continue
|
||||
}
|
||||
|
||||
if (parseTerminalOscColorQuery(input, candidateIndex).kind === 'partial') {
|
||||
return {
|
||||
statelessQueryData,
|
||||
statefulQueryData,
|
||||
oscColorQueryData,
|
||||
pending: input.slice(candidateIndex)
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
offset = candidateIndex + 1
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
return { statelessQueryData, statefulQueryData, oscColorQueryData, pending: '' }
|
||||
}
|
||||
|
||||
export function containsCsiRendererQuery(data: string): boolean {
|
||||
let offset = data.indexOf('\x1b[')
|
||||
while (offset !== -1) {
|
||||
const finalByteIndex = findCsiFinalByteIndex(data, offset + 2)
|
||||
if (finalByteIndex === -1) {
|
||||
return false
|
||||
}
|
||||
const sequence = data.slice(offset, finalByteIndex + 1)
|
||||
if (isStatelessRendererReplyCsiQuery(sequence) || isStatefulRendererReplyCsiQuery(sequence)) {
|
||||
return true
|
||||
}
|
||||
offset = data.indexOf('\x1b[', finalByteIndex + 1)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function containsStatefulRendererQuery(data: string): boolean {
|
||||
let offset = data.indexOf('\x1b[')
|
||||
while (offset !== -1) {
|
||||
const finalByteIndex = findCsiFinalByteIndex(data, offset + 2)
|
||||
if (finalByteIndex === -1) {
|
||||
return false
|
||||
}
|
||||
const sequence = data.slice(offset, finalByteIndex + 1)
|
||||
if (isStatefulRendererReplyCsiQuery(sequence)) {
|
||||
return true
|
||||
}
|
||||
offset = data.indexOf('\x1b[', finalByteIndex + 1)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function findCsiFinalByteIndex(data: string, offset: number): number {
|
||||
for (let index = offset; index < data.length; index++) {
|
||||
const code = data.charCodeAt(index)
|
||||
if (code >= 0x40 && code <= 0x7e) {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
export function isStatelessRendererReplyCsiQuery(sequence: string): boolean {
|
||||
if (sequence.endsWith('c')) {
|
||||
return true
|
||||
}
|
||||
return (
|
||||
sequence === '\x1b[5n' ||
|
||||
sequence === '\x1b[>q' ||
|
||||
sequence === '\x1b[14t' ||
|
||||
sequence === '\x1b[16t'
|
||||
)
|
||||
}
|
||||
|
||||
export function isStatefulRendererReplyCsiQuery(sequence: string): boolean {
|
||||
return sequence === '\x1b[6n' || (sequence.startsWith('\x1b[?') && sequence.endsWith('$p'))
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
// Renderer-parity headless terminal + snapshot/replay mirrors for the garble
|
||||
// differential fuzz suites (headless-emulator-fidelity.fuzz.test.ts and
|
||||
// hidden-reveal-reconciliation.fuzz.test.ts). Lives in src/shared because the
|
||||
// main-side and renderer-side fuzz suites both consume it and neither
|
||||
// tsconfig (tsconfig.node.json / tsconfig.tc.web.json) includes the other
|
||||
// side's sources.
|
||||
import { Terminal } from '@xterm/headless'
|
||||
import { SerializeAddon } from '@xterm/addon-serialize'
|
||||
import { Unicode11Addon } from '@xterm/addon-unicode11'
|
||||
import { activateOrcaTerminalUnicodeProvider } from './terminal-unicode-provider'
|
||||
import { DESKTOP_TERMINAL_SCROLLBACK_ROWS_DEFAULT } from './terminal-scrollback-policy'
|
||||
import {
|
||||
readSavedCursorRegister,
|
||||
serializeWithAbsoluteCursor
|
||||
} from './terminal-serialize-absolute-cursor'
|
||||
|
||||
export type ParityTerminal = {
|
||||
terminal: Terminal
|
||||
serializeAddon: SerializeAddon
|
||||
}
|
||||
|
||||
/** Builds an @xterm/headless terminal configured exactly like the renderer
|
||||
* pane where buffer state is concerned: scrollback + kitty vtExtensions from
|
||||
* buildDefaultTerminalOptions (pane-terminal-options.ts), Unicode11Addon
|
||||
* (pane-dom-creation.ts) and the Orca ZWJ provider (pane-lifecycle.ts).
|
||||
* Font/cursor/render options are omitted — they never alter buffer cells. */
|
||||
export function createRendererParityTerminal(dims: { cols: number; rows: number }): ParityTerminal {
|
||||
const terminal = new Terminal({
|
||||
cols: dims.cols,
|
||||
rows: dims.rows,
|
||||
scrollback: DESKTOP_TERMINAL_SCROLLBACK_ROWS_DEFAULT,
|
||||
allowProposedApi: true,
|
||||
vtExtensions: { kittyKeyboard: true }
|
||||
})
|
||||
const serializeAddon = new SerializeAddon()
|
||||
terminal.loadAddon(serializeAddon)
|
||||
terminal.loadAddon(new Unicode11Addon())
|
||||
activateOrcaTerminalUnicodeProvider(terminal)
|
||||
return { terminal, serializeAddon }
|
||||
}
|
||||
|
||||
export function writeToTerminal(terminal: Terminal, data: string): Promise<void> {
|
||||
return new Promise((resolve) => terminal.write(data, resolve))
|
||||
}
|
||||
|
||||
export async function writeChunksToTerminal(terminal: Terminal, chunks: string[]): Promise<void> {
|
||||
for (const chunk of chunks) {
|
||||
await writeToTerminal(terminal, chunk)
|
||||
}
|
||||
}
|
||||
|
||||
/** Bottom-anchored visible screen rows (baseY, not viewportY — scroll intent
|
||||
* is enforced separately by the production restore path). */
|
||||
export function visibleRows(terminal: Terminal): string[] {
|
||||
const buffer = terminal.buffer.active
|
||||
const rows: string[] = []
|
||||
for (let y = 0; y < terminal.rows; y++) {
|
||||
rows.push(buffer.getLine(buffer.baseY + y)?.translateToString(true) ?? '')
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// xterm attribute color modes (Attributes CM_* in xterm's buffer model).
|
||||
const COLOR_MODE_P16 = 16777216
|
||||
const COLOR_MODE_P256 = 33554432
|
||||
|
||||
/** Known-legitimate serializer normalization: SerializeAddon re-emits palette
|
||||
* indices 0-15 written via 38;5;N / 48;5;N as classic SGR 30-37/90-97, so a
|
||||
* restored cell reports CM_P16 where the live cell reported CM_P256. Both
|
||||
* modes resolve through the same 16 theme slots — no visual difference. */
|
||||
function canonicalColorMode(mode: number, color: number): number {
|
||||
return mode === COLOR_MODE_P256 && color >= 0 && color < 16 ? COLOR_MODE_P16 : mode
|
||||
}
|
||||
|
||||
/** Per-cell descriptor rows so SGR runs that shift cells are caught even
|
||||
* when the text matches. Encodes only VISUALLY EFFECTIVE state:
|
||||
* - glyph cells: char, width, fg, bg, all attribute flags;
|
||||
* - blank cells (null cells and spaces render identically): width, bg,
|
||||
* underline/strikethrough (drawn across blanks), and fg only when inverse
|
||||
* swaps it into the cell background. SerializeAddon legitimately skips
|
||||
* null cells with cursor motion, dropping their invisible fg/bold/italic
|
||||
* state, and may materialize a skipped run as plain spaces — neither can
|
||||
* be seen, so neither may fail the garble gate.
|
||||
* Trailing default blanks are trimmed: the serializer does not re-emit
|
||||
* pristine cells past the last written column. */
|
||||
export function visibleRowStyles(terminal: Terminal): string[] {
|
||||
const buffer = terminal.buffer.active
|
||||
const out: string[] = []
|
||||
for (let y = 0; y < terminal.rows; y++) {
|
||||
const line = buffer.getLine(buffer.baseY + y)
|
||||
const cells: string[] = []
|
||||
for (let x = 0; line && x < line.length; x++) {
|
||||
const cell = line.getCell(x)
|
||||
if (!cell) {
|
||||
continue
|
||||
}
|
||||
const chars = cell.getChars()
|
||||
const fgMode = canonicalColorMode(cell.getFgColorMode(), cell.getFgColor())
|
||||
const bgMode = canonicalColorMode(cell.getBgColorMode(), cell.getBgColor())
|
||||
if (chars === '' || chars === ' ') {
|
||||
const blankFlags = [cell.isUnderline(), cell.isStrikethrough()]
|
||||
.map((flag) => (flag ? '1' : '0'))
|
||||
.join('')
|
||||
const inverseFg = cell.isInverse() ? `·if${fgMode}:${cell.getFgColor()}` : ''
|
||||
cells.push(
|
||||
`▯·w${cell.getWidth()}·b${bgMode}:${cell.getBgColor()}·${blankFlags}${inverseFg}`
|
||||
)
|
||||
continue
|
||||
}
|
||||
const flags = [
|
||||
cell.isBold(),
|
||||
cell.isDim(),
|
||||
cell.isItalic(),
|
||||
cell.isUnderline(),
|
||||
cell.isInverse(),
|
||||
cell.isStrikethrough()
|
||||
]
|
||||
.map((flag) => (flag ? '1' : '0'))
|
||||
.join('')
|
||||
cells.push(
|
||||
`${chars}·w${cell.getWidth()}·f${fgMode}:${cell.getFgColor()}·b${bgMode}:${cell.getBgColor()}·${flags}`
|
||||
)
|
||||
}
|
||||
const defaultBlank = `▯·w1·b0:-1·00`
|
||||
while (cells.length > 0 && cells.at(-1) === defaultBlank) {
|
||||
cells.pop()
|
||||
}
|
||||
out.push(cells.join('|'))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function cursorPosition(terminal: Terminal): { x: number; y: number } {
|
||||
return { x: terminal.buffer.active.cursorX, y: terminal.buffer.active.cursorY }
|
||||
}
|
||||
|
||||
/** KNOWN UPSTREAM BUG predicate (@xterm/addon-serialize 0.15.0-beta.287):
|
||||
* null cells touching a soft-wrap boundary do not round-trip. Two confirmed
|
||||
* variants (see the skipped repros in headless-emulator-fidelity.fuzz.test.ts):
|
||||
* - V1 (cell loss): a wrapped continuation row starting with a NULL cell
|
||||
* (only erasure creates those — typed spaces have chars ' ') passes the
|
||||
* addon's wrap-validity ternary (SerializeAddon.ts ~L214 binds as
|
||||
* `(chars && isDoubleWidth) ? ...`), so the blank is skipped with CUF —
|
||||
* which clamps at the right margin instead of crossing the wrap boundary,
|
||||
* overwriting the previous row's last cell and shifting the tail left.
|
||||
* - V2 (filler artifact): a wrapped pair whose SOURCE row is entirely null
|
||||
* takes the forced-wrap "magic" path, whose cleanup emits `ESC[0C`; CSI
|
||||
* param 0 means 1, so the erase lands one cell right and the first filler
|
||||
* '-' stays visible on the restored screen.
|
||||
* The fuzz suites use this predicate to tolerate (and count) exactly these
|
||||
* divergences without masking unknown ones. */
|
||||
export function bufferHasSerializeHostileWrappedRow(terminal: Terminal): boolean {
|
||||
const buffer = terminal.buffer.active
|
||||
for (let y = 1; y < buffer.length; y++) {
|
||||
const line = buffer.getLine(y)
|
||||
if (!line?.isWrapped) {
|
||||
continue
|
||||
}
|
||||
if (line.getCell(0)?.getChars() === '') {
|
||||
return true
|
||||
}
|
||||
const previous = buffer.getLine(y - 1)
|
||||
let previousIsAllNull = previous !== undefined
|
||||
for (let x = 0; previous && x < previous.length; x++) {
|
||||
if (previous.getCell(x)?.getChars() !== '') {
|
||||
previousIsAllNull = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if (previousIsAllNull) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Full normal-buffer text with trailing blank rows trimmed (SerializeAddon
|
||||
* restores content rows; both sides may differ only in trailing blanks). */
|
||||
export function normalBufferRowsTrimmed(terminal: Terminal): string[] {
|
||||
const buffer = terminal.buffer.normal
|
||||
const rows: string[] = []
|
||||
for (let y = 0; y < buffer.length; y++) {
|
||||
rows.push(buffer.getLine(y)?.translateToString(true) ?? '')
|
||||
}
|
||||
while (rows.length > 0 && rows.at(-1) === '') {
|
||||
rows.pop()
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// Mirror of applyMainBufferSnapshot's clear preamble (pty-connection.ts):
|
||||
// normal-buffer restores wipe screen+scrollback+home; alt-screen restores
|
||||
// clear only the alt screen so the normal buffer's scrollback survives.
|
||||
export const SNAPSHOT_REPLAY_PREAMBLE_NORMAL = '\x1b[2J\x1b[3J\x1b[H'
|
||||
export const SNAPSHOT_REPLAY_PREAMBLE_ALT = '\x1b[0m\x1b[?1049h\x1b[2J\x1b[H'
|
||||
|
||||
// Twin of POST_REPLAY_LIVE_SNAPSHOT_RESET (layout-serialization.ts) — the
|
||||
// renderer suite pins equality against the real constant so drift fails fast.
|
||||
export const POST_REPLAY_LIVE_SNAPSHOT_RESET_PARITY = '\x1b[0 q\x1b[?25h\x1b[?1004l'
|
||||
|
||||
export type ParityMainSnapshot = {
|
||||
data: string
|
||||
scrollbackAnsi?: string
|
||||
cols: number
|
||||
rows: number
|
||||
seq: number
|
||||
alternateScreen: boolean
|
||||
pendingDeliveryStartSeq?: number
|
||||
/** Mirror of TerminalSnapshot.pendingEscapeTailAnsi: the trailing
|
||||
* incomplete escape of the hidden byte stream. The restorer writes it
|
||||
* LAST, after its post-replay resets (Bug E fix). */
|
||||
pendingEscapeTailAnsi?: string
|
||||
}
|
||||
|
||||
/** Mirror of the production main-buffer snapshot the renderer restore path
|
||||
* consumes: HeadlessEmulator.getSnapshot (snapshotAnsi normalization +
|
||||
* rehydrateSequences + absolute-cursor/DECSC epilogue) composed exactly like
|
||||
* OrcaRuntime.serializeHeadlessTerminalBuffer (normal buffer separated from
|
||||
* an active alt frame). The renderer fuzz cannot import
|
||||
* HeadlessEmulator itself — tsconfig.tc.web.json excludes src/main/daemon. */
|
||||
export function buildParityMainBufferSnapshot(
|
||||
parity: ParityTerminal,
|
||||
seq: number,
|
||||
opts: {
|
||||
pendingDeliveryStartSeq?: number
|
||||
scrollbackRows?: number
|
||||
/** The hidden byte stream's trailing incomplete escape, exactly as the
|
||||
* emulator's ingest tracker would have accumulated it. */
|
||||
pendingEscapeTail?: string
|
||||
} = {}
|
||||
): ParityMainSnapshot {
|
||||
const { terminal } = parity
|
||||
const alternateScreen = terminal.buffer.active.type === 'alternate'
|
||||
const scrollback = opts.scrollbackRows ?? DESKTOP_TERMINAL_SCROLLBACK_ROWS_DEFAULT
|
||||
// Same composition as HeadlessEmulator.getSnapshot: absolute-cursor CUP for
|
||||
// the wrap-pending relative-restore defect plus the DECSC register epilogue.
|
||||
let snapshotAnsi = serializeWithAbsoluteCursor(
|
||||
parity.serializeAddon,
|
||||
terminal,
|
||||
{ scrollback },
|
||||
readSavedCursorRegister(terminal)
|
||||
)
|
||||
let scrollbackAnsi: string | undefined
|
||||
if (alternateScreen) {
|
||||
// Why: HeadlessEmulator splits the normal buffer from the active alt frame;
|
||||
// rehydrateSequences owns the transition between them.
|
||||
const marker = '\x1b[?1049h'
|
||||
const start = snapshotAnsi.lastIndexOf(marker)
|
||||
if (start !== -1) {
|
||||
scrollbackAnsi = snapshotAnsi.slice(0, start)
|
||||
snapshotAnsi = snapshotAnsi.slice(start + marker.length)
|
||||
}
|
||||
}
|
||||
const seqs: string[] = []
|
||||
if (alternateScreen) {
|
||||
seqs.push('\x1b[0m\x1b[?1049h')
|
||||
}
|
||||
if (terminal.modes.bracketedPasteMode) {
|
||||
seqs.push('\x1b[?2004h')
|
||||
}
|
||||
// Why normal-buffer-only: HeadlessEmulator.getModes reports
|
||||
// applicationCursor false while the alternate buffer is active, so the
|
||||
// production rehydrate omits ?1h for alt-screen snapshots.
|
||||
if (!alternateScreen && terminal.modes.applicationCursorKeysMode) {
|
||||
seqs.push('\x1b[?1h')
|
||||
}
|
||||
// Mouse-mode rehydrate omitted: TerminalMouseModeMirror is main-only and
|
||||
// mouse reporting is input encoding — it cannot alter rendered output.
|
||||
const snapshot: ParityMainSnapshot = {
|
||||
data: seqs.join('') + snapshotAnsi,
|
||||
cols: terminal.cols,
|
||||
rows: terminal.rows,
|
||||
seq,
|
||||
alternateScreen,
|
||||
...(scrollbackAnsi !== undefined ? { scrollbackAnsi } : {})
|
||||
}
|
||||
if (opts.pendingDeliveryStartSeq !== undefined) {
|
||||
snapshot.pendingDeliveryStartSeq = opts.pendingDeliveryStartSeq
|
||||
}
|
||||
if (opts.pendingEscapeTail) {
|
||||
snapshot.pendingEscapeTailAnsi = opts.pendingEscapeTail
|
||||
}
|
||||
return snapshot
|
||||
}
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
DESKTOP_TERMINAL_SCROLLBACK_ROWS_MIN,
|
||||
legacyTerminalScrollbackBytesToRows,
|
||||
normalizeDesktopTerminalScrollbackRows,
|
||||
normalizeDesktopTerminalSnapshotRows
|
||||
normalizeDesktopTerminalSnapshotRows,
|
||||
TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS,
|
||||
terminalOutputBacklogCapChars
|
||||
} from './terminal-scrollback-policy'
|
||||
|
||||
describe('terminal scrollback policy', () => {
|
||||
@@ -35,6 +37,18 @@ describe('terminal scrollback policy', () => {
|
||||
expect(normalizeDesktopTerminalSnapshotRows(100_000)).toBe(50_000)
|
||||
})
|
||||
|
||||
it('scales the output backlog cap with scrollback rows above a 2 MB floor', () => {
|
||||
// Default and small scrollbacks stay on the floor; large scrollbacks get
|
||||
// proportionally more so the cap never drops lines scrollback would keep.
|
||||
expect(terminalOutputBacklogCapChars(undefined)).toBe(TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS)
|
||||
expect(terminalOutputBacklogCapChars(5_000)).toBe(TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS)
|
||||
expect(terminalOutputBacklogCapChars('garbage')).toBe(TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS)
|
||||
expect(terminalOutputBacklogCapChars(25_000)).toBe(3_000_000)
|
||||
expect(terminalOutputBacklogCapChars(50_000)).toBe(6_000_000)
|
||||
// Values beyond the settings max clamp like the setting itself does.
|
||||
expect(terminalOutputBacklogCapChars(1_000_000)).toBe(6_000_000)
|
||||
})
|
||||
|
||||
it('migrates legacy decimal MB buckets by intent, not byte-to-row math', () => {
|
||||
expect(legacyTerminalScrollbackBytesToRows(undefined)).toBe(5_000)
|
||||
expect(legacyTerminalScrollbackBytesToRows(0)).toBe(5_000)
|
||||
|
||||
@@ -28,6 +28,23 @@ export function normalizeDesktopTerminalScrollbackRows(value: unknown): number {
|
||||
return clampRows(value, DESKTOP_TERMINAL_SCROLLBACK_ROWS_MIN)
|
||||
}
|
||||
|
||||
// Why the backlog cap scales with scrollback: pending-output caps exist to
|
||||
// bound memory while a starved display catches up, but a user who raised
|
||||
// scrollback to 50k rows can retain more history than the flat 2 MB floor —
|
||||
// dropping at the floor would discard lines their scrollback would have kept.
|
||||
// 120 chars/row ≈ 80-col text plus escape-sequence overhead; the cap is a
|
||||
// memory bound, not an exact retention guarantee.
|
||||
export const TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS = 2 * 1024 * 1024
|
||||
const OUTPUT_BACKLOG_CHARS_PER_SCROLLBACK_ROW = 120
|
||||
|
||||
export function terminalOutputBacklogCapChars(scrollbackRows: unknown): number {
|
||||
const rows = normalizeDesktopTerminalScrollbackRows(scrollbackRows)
|
||||
return Math.max(
|
||||
TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS,
|
||||
rows * OUTPUT_BACKLOG_CHARS_PER_SCROLLBACK_ROW
|
||||
)
|
||||
}
|
||||
|
||||
export function normalizeDesktopTerminalSnapshotRows(value: unknown): number | undefined {
|
||||
if (!isFiniteNumber(value)) {
|
||||
return undefined
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
// Why this module exists: @xterm/addon-serialize restores the cursor with
|
||||
// RELATIVE moves (CUD/CUB) computed from where it assumes replay leaves the
|
||||
// cursor. When the final content row is filled exactly to the right margin,
|
||||
// replay leaves the fresh terminal wrap-pending (internal x == cols), so the
|
||||
// relative math lands one column short of the real cursor. Every Orca buffer
|
||||
// snapshot that will be replayed into another terminal must therefore end
|
||||
// with an absolute CUP derived from the SOURCE terminal's authoritative
|
||||
// cursor position. Snapshot producers that also need the VT100 DECSC
|
||||
// saved-cursor register carried across the restore compose it here too.
|
||||
|
||||
type SerializeCursorTerminal = {
|
||||
cols: number
|
||||
rows: number
|
||||
buffer: { active: { cursorX: number; cursorY: number } }
|
||||
}
|
||||
|
||||
type BufferSerializer<TOpts> = {
|
||||
serialize: (opts?: TOpts) => string
|
||||
}
|
||||
|
||||
/** VT100 DECSC saved-cursor register (0-based, viewport-relative row). */
|
||||
export type SavedCursorRegister = { x: number; y: number }
|
||||
|
||||
// xterm keeps the DECSC register on each Buffer (savedY is absolute:
|
||||
// ybase-included). It is not exposed through the public API, so snapshot
|
||||
// producers read the core buffer directly — `_core.buffer` is the ACTIVE
|
||||
// buffer, so an alt-screen TUI yields the alternate screen's own register,
|
||||
// matching the one a post-restore DECRC would consult.
|
||||
type TerminalWithSavedCursorCore = SerializeCursorTerminal & {
|
||||
_core?: { buffer?: { savedX?: number; savedY?: number; ybase?: number } }
|
||||
}
|
||||
|
||||
/** Reads the source terminal's active-buffer DECSC register, or null when it
|
||||
* is unavailable or indistinguishable from the never-saved default. */
|
||||
export function readSavedCursorRegister(
|
||||
terminal: SerializeCursorTerminal
|
||||
): SavedCursorRegister | null {
|
||||
const core = (terminal as TerminalWithSavedCursorCore)._core?.buffer
|
||||
if (
|
||||
typeof core?.savedX !== 'number' ||
|
||||
typeof core.savedY !== 'number' ||
|
||||
typeof core.ybase !== 'number'
|
||||
) {
|
||||
return null
|
||||
}
|
||||
// savedY is absolute; DECRC restores it relative to the ybase current at
|
||||
// restore time, clamping at the top — mirror that clamp here. savedX can be
|
||||
// cols (DECSC during wrap-pending); CUP cannot re-create pending, so clamp.
|
||||
const y = Math.min(Math.max(core.savedY - core.ybase, 0), terminal.rows - 1)
|
||||
const x = Math.min(Math.max(core.savedX, 0), terminal.cols - 1)
|
||||
if (x === 0 && y === 0) {
|
||||
// Home is xterm's never-saved default: a fresh restore terminal already
|
||||
// sends DECRC to home, and skipping the injection avoids overwriting the
|
||||
// fresh terminal's default saved SGR/charset when nothing was ever saved.
|
||||
return null
|
||||
}
|
||||
return { x, y }
|
||||
}
|
||||
|
||||
export function serializeWithAbsoluteCursor<TOpts>(
|
||||
serializer: BufferSerializer<TOpts>,
|
||||
terminal: SerializeCursorTerminal,
|
||||
opts?: TOpts,
|
||||
savedCursor?: SavedCursorRegister | null
|
||||
): string {
|
||||
const serialized = serializer.serialize(opts)
|
||||
// Why skip empty snapshots: several callers treat '' as "nothing to
|
||||
// restore" (e.g. shutdown layout capture drops empty buffers); a bare CUP
|
||||
// would turn every idle pane into a persisted snapshot.
|
||||
if (serialized.length === 0) {
|
||||
return serialized
|
||||
}
|
||||
const { cursorX, cursorY } = terminal.buffer.active
|
||||
// Why skip wrap-pending sources (cursorX == cols): plain replay already
|
||||
// reproduces that state exactly, while CUP would clamp to the last column
|
||||
// and clear the pending-wrap flag, changing how the next byte renders.
|
||||
// The remaining bounds checks are defensive: never emit a clamping CUP.
|
||||
// The saved-cursor injection is skipped with it — it moves the cursor, so
|
||||
// it may only ride along when the absolute CUP restores the position after.
|
||||
if (cursorX < 0 || cursorX >= terminal.cols || cursorY < 0 || cursorY >= terminal.rows) {
|
||||
return serialized
|
||||
}
|
||||
// Why the DECSC injection: the serialized screen cannot carry the VT100
|
||||
// saved-cursor register, so a hidden DECSC followed by a post-reveal DECRC
|
||||
// restored to home and clobbered live cells (Bug D in
|
||||
// notes/garble-fuzz-divergences.md). Re-establish the register by saving at
|
||||
// the source's saved position, then CUP back to the real cursor. Saved SGR/
|
||||
// charset are not carried — the synthetic ESC 7 saves the serializer's
|
||||
// final pen, a deliberate position-only fidelity trade.
|
||||
const savedRestore = savedCursor ? `\x1b[${savedCursor.y + 1};${savedCursor.x + 1}H\x1b7` : ''
|
||||
// cursorY is viewport-relative (0 at the buffer's base row), which is the
|
||||
// same coordinate space CUP addresses after replay; scrollback length
|
||||
// differences between source and destination do not shift it.
|
||||
return `${serialized}${savedRestore}\x1b[${cursorY + 1};${cursorX + 1}H`
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Derived terminal side-effect facts carried on the `pty:sideEffect` channel
|
||||
* (main → renderer). Events are facts, not decisions: main parses every
|
||||
* local-daemon/SSH PTY byte exactly once and emits what it observed; the
|
||||
* renderer store handler owns notification/unread policy.
|
||||
* See docs/reference/terminal-side-effect-authority.md.
|
||||
*/
|
||||
|
||||
import type { TerminalGitHubPRLink } from './terminal-github-pr-link-detector'
|
||||
|
||||
/** Why tagged: stale-clear facts come from main's unthrottled 3s timer, not
|
||||
* observed bytes. Renderer policy clears title/cache state from them but
|
||||
* must not schedule task-complete notifications or unread attention — a
|
||||
* merely-paused agent (>3s silent mid-task) is not a completion. */
|
||||
export type TerminalSideEffectFact =
|
||||
| { kind: 'title'; normalizedTitle: string; rawTitle: string; staleWorkingTitleClear?: boolean }
|
||||
| { kind: 'bell' }
|
||||
| { kind: 'agent-working' }
|
||||
| { kind: 'agent-idle'; title: string; staleWorkingTitleClear?: boolean }
|
||||
| { kind: 'agent-exited' }
|
||||
/** OSC 133;D — foreground shell command exited (exit code best-effort). */
|
||||
| { kind: 'command-finished'; exitCode: number | null }
|
||||
/** Carries the parsed link so the renderer store consumer never re-parses
|
||||
* the URL (parse drift would break the per-PTY dedupe contract). */
|
||||
| { kind: 'pr-link'; link: TerminalGitHubPRLink }
|
||||
/** Command Code output scrape (that CLI lacks hooks). Working seeds the
|
||||
* agent-status row immediately; done is a hint the renderer settle-checks
|
||||
* against its live status row before completing the turn. */
|
||||
| { kind: 'command-code-working'; prompt: string }
|
||||
| { kind: 'command-code-done'; prompt: string }
|
||||
/** DECSET 2031 color-scheme subscribe observed in the byte stream. Emitted
|
||||
* so hidden-delivery-gated views (whose bytes never arrive) can still send
|
||||
* the theme reply — the reply stays renderer-side because query authority
|
||||
* belongs to the view (model/view contract invariant 6). */
|
||||
| { kind: '2031-subscribe' }
|
||||
|
||||
export type TerminalSideEffectBatch = {
|
||||
ptyId: string
|
||||
/** PTY output byte sequence at emission. Replay batches carry the sequence
|
||||
* their title state was current at, so the handler can drop a replay title
|
||||
* older than the last live title fact it applied. */
|
||||
seq: number
|
||||
/** Facts from one chunk, in byte order: titles in sequence, then bell.
|
||||
* Command Code scrape facts trail the chunk's parser facts — their policy
|
||||
* (status-row seeding) never interacts with title/bell ordering. */
|
||||
facts: TerminalSideEffectFact[]
|
||||
/** True for (re)attach snapshots. Replay batches restore title state only —
|
||||
* attention facts (bell, agent transitions) never replay. */
|
||||
replay?: boolean
|
||||
/** Main-known attribution from runtime leaf/PTY records (same resolution as
|
||||
* agent-status events). Absent when main has no binding for the PTY yet. */
|
||||
worktreeId?: string
|
||||
tabId?: string
|
||||
paneKey?: string
|
||||
connectionId?: string | null
|
||||
}
|
||||
@@ -123,6 +123,21 @@ describe('terminal-stream-protocol', () => {
|
||||
expect(unsubscribe?.streamId).toBe(12)
|
||||
})
|
||||
|
||||
it('round-trips output acknowledgement frames', () => {
|
||||
const ack = decodeTerminalStreamFrame(
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.Ack,
|
||||
streamId: 12,
|
||||
seq: 4,
|
||||
payload: encodeTerminalStreamJson({ bytes: 4096 })
|
||||
})
|
||||
)
|
||||
|
||||
expect(ack?.opcode).toBe(TerminalStreamOpcode.Ack)
|
||||
expect(ack?.streamId).toBe(12)
|
||||
expect(ack && decodeTerminalStreamJson(ack.payload)).toEqual({ bytes: 4096 })
|
||||
})
|
||||
|
||||
it('rejects unknown frame versions and opcodes', () => {
|
||||
const encoded = encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.Output,
|
||||
|
||||
@@ -14,7 +14,10 @@ export enum TerminalStreamOpcode {
|
||||
Subscribe = 9,
|
||||
Unsubscribe = 10,
|
||||
SnapshotRequest = 11,
|
||||
Metadata = 12
|
||||
Metadata = 12,
|
||||
// Why 13: Metadata=12 shipped to mobile clients in v1.4.120; Ack (branch-only
|
||||
// remote-multiplex flow control) renumbers to stay wire-compatible.
|
||||
Ack = 13
|
||||
}
|
||||
|
||||
export type TerminalStreamFrame = {
|
||||
@@ -94,6 +97,7 @@ function isTerminalStreamOpcode(value: number): value is TerminalStreamOpcode {
|
||||
value === TerminalStreamOpcode.Subscribe ||
|
||||
value === TerminalStreamOpcode.Unsubscribe ||
|
||||
value === TerminalStreamOpcode.SnapshotRequest ||
|
||||
value === TerminalStreamOpcode.Metadata
|
||||
value === TerminalStreamOpcode.Metadata ||
|
||||
value === TerminalStreamOpcode.Ack
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* View-attribute bridge (terminal-query-authority.md §View-attribute bridge):
|
||||
* the XParseColor mirrors must match the bundled xterm grammar exactly —
|
||||
* main's replies for hidden PTYs must be byte-identical to a visible
|
||||
* renderer xterm's.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
formatXColorRgbSpec,
|
||||
parseXColorSpec,
|
||||
terminalViewAttributesEqual,
|
||||
validateTerminalViewAttributes,
|
||||
type TerminalViewAttributes,
|
||||
type TerminalViewRgb
|
||||
} from './terminal-view-attributes'
|
||||
|
||||
describe('parseXColorSpec', () => {
|
||||
// Scaling fixtures mirror XParseColor.parseColor: h|hh|hhh|hhhh channels
|
||||
// scale from their base (15/255/4095/65535) to 8 bit.
|
||||
it.each([
|
||||
['rgb:f/f/f', [255, 255, 255]],
|
||||
['rgb:0/8/f', [0, 136, 255]],
|
||||
['rgb:ff/00/80', [255, 0, 128]],
|
||||
['rgb:fff/000/888', [255, 0, 136]],
|
||||
['rgb:ffff/0000/8888', [255, 0, 136]],
|
||||
['RGB:FF/00/80', [255, 0, 128]],
|
||||
['#abc', [0xa0, 0xb0, 0xc0]],
|
||||
['#aabbcc', [0xaa, 0xbb, 0xcc]],
|
||||
['#aaabbbccc', [0xaa, 0xbb, 0xcc]],
|
||||
['#aaaabbbbcccc', [0xaa, 0xbb, 0xcc]]
|
||||
])('parses %s like xterm', (spec, expected) => {
|
||||
expect(parseXColorSpec(spec)).toEqual(expected)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['', 'empty'],
|
||||
['red', 'named colors (xterm rejects them too)'],
|
||||
['rgb:ff/ff', 'missing channel'],
|
||||
['rgb:ggg/000/000', 'non-hex'],
|
||||
['#abcd', 'hash length 4 is not a valid xparsecolor width'],
|
||||
['rgbi:1/1/1', 'rgbi is unsupported']
|
||||
])('rejects %s — %s', (spec) => {
|
||||
expect(parseXColorSpec(spec)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatXColorRgbSpec', () => {
|
||||
it('reports 16-bit channels by doubling the 8-bit byte (toRgbString parity)', () => {
|
||||
expect(formatXColorRgbSpec([0x1e, 0x1e, 0x2e])).toBe('rgb:1e1e/1e1e/2e2e')
|
||||
expect(formatXColorRgbSpec([0, 8, 255])).toBe('rgb:0000/0808/ffff')
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateTerminalViewAttributes', () => {
|
||||
const valid = (): TerminalViewAttributes => ({
|
||||
foreground: [1, 2, 3],
|
||||
background: [4, 5, 6],
|
||||
cursor: [7, 8, 9],
|
||||
ansi: Array.from({ length: 256 }, (_, i) => [i % 256, 0, 0] as TerminalViewRgb),
|
||||
colorSchemeMode: 'dark',
|
||||
cursorStyle: 'block',
|
||||
cursorBlink: true
|
||||
})
|
||||
|
||||
it('accepts and normalizes a well-formed payload', () => {
|
||||
const attrs = validateTerminalViewAttributes(valid())
|
||||
expect(attrs).not.toBeNull()
|
||||
expect(attrs?.ansi).toHaveLength(256)
|
||||
expect(attrs?.colorSchemeMode).toBe('dark')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['null payload', null],
|
||||
['missing foreground', { ...valid(), foreground: undefined }],
|
||||
['short triple', { ...valid(), background: [1, 2] }],
|
||||
['out-of-range channel', { ...valid(), cursor: [0, 0, 300] }],
|
||||
['non-integer channel', { ...valid(), cursor: [0, 0, 1.5] }],
|
||||
['short palette', { ...valid(), ansi: valid().ansi.slice(0, 16) }],
|
||||
['bad palette entry', { ...valid(), ansi: [...valid().ansi.slice(0, 255), 'red'] }],
|
||||
['bad mode', { ...valid(), colorSchemeMode: 'auto' }],
|
||||
['bad cursor style', { ...valid(), cursorStyle: 'beam' }],
|
||||
['non-boolean blink', { ...valid(), cursorBlink: 1 }]
|
||||
])('rejects %s', (_label, payload) => {
|
||||
expect(validateTerminalViewAttributes(payload)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('terminalViewAttributesEqual', () => {
|
||||
// The store's idempotence gate: a deep-equal snapshot from a fresh renderer
|
||||
// process must compare equal so the re-push never fans out as a theme apply.
|
||||
const snapshot = (): TerminalViewAttributes => ({
|
||||
foreground: [1, 2, 3],
|
||||
background: [4, 5, 6],
|
||||
cursor: [7, 8, 9],
|
||||
ansi: Array.from({ length: 256 }, (_, i) => [i % 256, 0, 0] as TerminalViewRgb),
|
||||
colorSchemeMode: 'dark',
|
||||
cursorStyle: 'block',
|
||||
cursorBlink: true
|
||||
})
|
||||
|
||||
it('treats two independently built identical snapshots as equal', () => {
|
||||
expect(terminalViewAttributesEqual(snapshot(), snapshot())).toBe(true)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['foreground', { ...snapshot(), foreground: [1, 2, 4] as TerminalViewRgb }],
|
||||
['background', { ...snapshot(), background: [0, 0, 0] as TerminalViewRgb }],
|
||||
['cursor', { ...snapshot(), cursor: [7, 8, 10] as TerminalViewRgb }],
|
||||
[
|
||||
'an ansi entry',
|
||||
{ ...snapshot(), ansi: snapshot().ansi.map((rgb, i) => (i === 200 ? [9, 9, 9] : rgb)) }
|
||||
],
|
||||
['colorSchemeMode', { ...snapshot(), colorSchemeMode: 'light' as const }],
|
||||
['cursorStyle', { ...snapshot(), cursorStyle: 'bar' as const }],
|
||||
['cursorBlink', { ...snapshot(), cursorBlink: false }]
|
||||
])('detects a change in %s', (_label, changed) => {
|
||||
expect(terminalViewAttributesEqual(snapshot(), changed as TerminalViewAttributes)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* Phase 5 slice 2 (docs/reference/terminal-query-authority.md §View-attribute
|
||||
* bridge): payload contract for the renderer→main `pty:terminalViewAttributes`
|
||||
* push, plus main/renderer mirrors of xterm's XParseColor color-spec grammar
|
||||
* so main's responder replies byte-identically to a visible renderer xterm.
|
||||
*/
|
||||
|
||||
/** 8-bit-per-channel RGB triple — the same resolution xterm's theme service
|
||||
* stores internally (`color.toColorRGB`). */
|
||||
export type TerminalViewRgb = [number, number, number]
|
||||
|
||||
export const TERMINAL_VIEW_ANSI_COLOR_COUNT = 256
|
||||
|
||||
export type TerminalViewCursorStyle = 'bar' | 'block' | 'underline'
|
||||
|
||||
/** One app-global snapshot of the renderer's composed terminal appearance —
|
||||
* per-pane font zoom never affects these, and terminalColorOverrides /
|
||||
* cursor settings are global, so one push covers all PTYs. */
|
||||
export type TerminalViewAttributes = {
|
||||
foreground: TerminalViewRgb
|
||||
background: TerminalViewRgb
|
||||
/** Already blended over the background (xterm ThemeService blends the
|
||||
* cursor color's alpha at theme-set time, e.g. terminalCursorOpacity). */
|
||||
cursor: TerminalViewRgb
|
||||
/** Full 256-entry palette: theme's 16 named colors + extendedAnsi/default
|
||||
* tail, exactly as the renderer ThemeService resolves them. */
|
||||
ansi: TerminalViewRgb[]
|
||||
/** Resolved APP color-scheme mode (the 2031/997 flip source). NOT the DSR
|
||||
* ?996n answer: that is computed from background/foreground relative
|
||||
* luminance like a visible xterm (_reportColorScheme), and the two can
|
||||
* disagree (e.g. dark terminal theme in light app mode). */
|
||||
colorSchemeMode: 'dark' | 'light'
|
||||
cursorStyle: TerminalViewCursorStyle
|
||||
cursorBlink: boolean
|
||||
}
|
||||
|
||||
// Mirror of @xterm XParseColor RGB_REX: r/g/b channels in 1-4 hex digits.
|
||||
const X_RGB_SPEC_RE =
|
||||
/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/
|
||||
const X_HASH_SPEC_RE = /^[\da-f]+$/
|
||||
|
||||
/** Mirror of xterm's XParseColor `parseColor` (the grammar the renderer
|
||||
* accepts for OSC 4/10/11/12 SET payloads): `rgb:h/h/h`..`rgb:hhhh/hhhh/hhhh`
|
||||
* and `#RGB|#RRGGBB|#RRRGGGBBB|#RRRRGGGGBBBB`. Anything else (named colors,
|
||||
* rgbi:) is rejected exactly like the renderer rejects it. */
|
||||
export function parseXColorSpec(spec: string): TerminalViewRgb | null {
|
||||
if (!spec) {
|
||||
return null
|
||||
}
|
||||
let low = spec.toLowerCase()
|
||||
if (low.startsWith('rgb:')) {
|
||||
low = low.slice(4)
|
||||
const m = X_RGB_SPEC_RE.exec(low)
|
||||
if (m) {
|
||||
const base = m[1] ? 15 : m[4] ? 255 : m[7] ? 4095 : 65535
|
||||
return [
|
||||
Math.round((Number.parseInt(m[1] || m[4] || m[7] || m[10], 16) / base) * 255),
|
||||
Math.round((Number.parseInt(m[2] || m[5] || m[8] || m[11], 16) / base) * 255),
|
||||
Math.round((Number.parseInt(m[3] || m[6] || m[9] || m[12], 16) / base) * 255)
|
||||
]
|
||||
}
|
||||
return null
|
||||
}
|
||||
if (low.startsWith('#')) {
|
||||
low = low.slice(1)
|
||||
if (X_HASH_SPEC_RE.exec(low) && [3, 6, 9, 12].includes(low.length)) {
|
||||
const adv = low.length / 3
|
||||
const result: TerminalViewRgb = [0, 0, 0]
|
||||
for (let i = 0; i < 3; ++i) {
|
||||
const c = Number.parseInt(low.slice(adv * i, adv * i + adv), 16)
|
||||
result[i] = adv === 1 ? c << 4 : adv === 2 ? c : adv === 3 ? c >> 4 : c >> 8
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function padChannelTo16Bit(value: number): string {
|
||||
const hex = value.toString(16)
|
||||
const byte = hex.length < 2 ? `0${hex}` : hex
|
||||
// Why doubled: xterm reports 16-bit channels by repeating the 8-bit byte
|
||||
// (XParseColor.toRgbString with bits=16) — pinned reply-format parity.
|
||||
return byte + byte
|
||||
}
|
||||
|
||||
/** Mirror of xterm's `toRgbString(color, 16)` — the exact channel format a
|
||||
* visible renderer xterm uses in OSC 4/10/11/12 query replies. */
|
||||
export function formatXColorRgbSpec(rgb: TerminalViewRgb): string {
|
||||
return `rgb:${padChannelTo16Bit(rgb[0])}/${padChannelTo16Bit(rgb[1])}/${padChannelTo16Bit(rgb[2])}`
|
||||
}
|
||||
|
||||
function rgbEqual(a: TerminalViewRgb, b: TerminalViewRgb): boolean {
|
||||
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]
|
||||
}
|
||||
|
||||
/** Value equality over the whole snapshot. Lets main's store treat a
|
||||
* re-push of identical attributes (fresh renderer process: second window,
|
||||
* reload, macOS re-activation) as a no-op instead of a theme apply. */
|
||||
export function terminalViewAttributesEqual(
|
||||
a: TerminalViewAttributes,
|
||||
b: TerminalViewAttributes
|
||||
): boolean {
|
||||
if (a === b) {
|
||||
return true
|
||||
}
|
||||
if (
|
||||
!rgbEqual(a.foreground, b.foreground) ||
|
||||
!rgbEqual(a.background, b.background) ||
|
||||
!rgbEqual(a.cursor, b.cursor) ||
|
||||
a.colorSchemeMode !== b.colorSchemeMode ||
|
||||
a.cursorStyle !== b.cursorStyle ||
|
||||
a.cursorBlink !== b.cursorBlink ||
|
||||
a.ansi.length !== b.ansi.length
|
||||
) {
|
||||
return false
|
||||
}
|
||||
for (let i = 0; i < a.ansi.length; i++) {
|
||||
if (!rgbEqual(a.ansi[i], b.ansi[i])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function isRgbChannel(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 255
|
||||
}
|
||||
|
||||
function validateRgbTriple(value: unknown): TerminalViewRgb | null {
|
||||
if (!Array.isArray(value) || value.length !== 3) {
|
||||
return null
|
||||
}
|
||||
const [r, g, b] = value
|
||||
if (!isRgbChannel(r) || !isRgbChannel(g) || !isRgbChannel(b)) {
|
||||
return null
|
||||
}
|
||||
return [r, g, b]
|
||||
}
|
||||
|
||||
/** IPC-boundary validation for the `pty:terminalViewAttributes` push. Returns
|
||||
* a normalized copy or null — main must never store a malformed palette (a
|
||||
* wrong color reply is worse than silence, the OSC-11 lesson). */
|
||||
export function validateTerminalViewAttributes(payload: unknown): TerminalViewAttributes | null {
|
||||
if (typeof payload !== 'object' || payload === null) {
|
||||
return null
|
||||
}
|
||||
const candidate = payload as Record<string, unknown>
|
||||
const foreground = validateRgbTriple(candidate.foreground)
|
||||
const background = validateRgbTriple(candidate.background)
|
||||
const cursor = validateRgbTriple(candidate.cursor)
|
||||
if (!foreground || !background || !cursor) {
|
||||
return null
|
||||
}
|
||||
if (!Array.isArray(candidate.ansi) || candidate.ansi.length !== TERMINAL_VIEW_ANSI_COLOR_COUNT) {
|
||||
return null
|
||||
}
|
||||
const ansi: TerminalViewRgb[] = []
|
||||
for (const entry of candidate.ansi) {
|
||||
const triple = validateRgbTriple(entry)
|
||||
if (!triple) {
|
||||
return null
|
||||
}
|
||||
ansi.push(triple)
|
||||
}
|
||||
if (candidate.colorSchemeMode !== 'dark' && candidate.colorSchemeMode !== 'light') {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
candidate.cursorStyle !== 'bar' &&
|
||||
candidate.cursorStyle !== 'block' &&
|
||||
candidate.cursorStyle !== 'underline'
|
||||
) {
|
||||
return null
|
||||
}
|
||||
if (typeof candidate.cursorBlink !== 'boolean') {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
foreground,
|
||||
background,
|
||||
cursor,
|
||||
ansi,
|
||||
colorSchemeMode: candidate.colorSchemeMode,
|
||||
cursorStyle: candidate.cursorStyle,
|
||||
cursorBlink: candidate.cursorBlink
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Lib-safe sink for WebGL renderer breadcrumbs (context loss/restore, atlas
|
||||
* resets). The renderer breadcrumb ring lives in the components layer
|
||||
* (terminal-freeze-breadcrumbs.ts), which may import from lib/pane-manager but
|
||||
* not the reverse. This indirection lets lib-layer WebGL code record a crumb
|
||||
* without a backward import: components registers the recorder at startup;
|
||||
* until then (and in non-renderer contexts) recording is a silent no-op.
|
||||
*/
|
||||
|
||||
export type WebglDiagnosticRecorder = (
|
||||
kind: string,
|
||||
detail?: Record<string, string | number | boolean | null>
|
||||
) => void
|
||||
|
||||
let recorder: WebglDiagnosticRecorder | null = null
|
||||
|
||||
export function setTerminalWebglDiagnosticRecorder(next: WebglDiagnosticRecorder | null): void {
|
||||
recorder = next
|
||||
}
|
||||
|
||||
export function recordTerminalWebglDiagnostic(
|
||||
kind: string,
|
||||
detail?: Record<string, string | number | boolean | null>
|
||||
): void {
|
||||
recorder?.(kind, detail)
|
||||
}
|
||||
@@ -2722,6 +2722,28 @@ export type GlobalSettings = {
|
||||
* does not surface commands from other worktrees. Defaults to true.
|
||||
* Disable to revert to shared global shell history. */
|
||||
terminalScopeHistoryByWorktree: boolean
|
||||
/** Kill switch for hidden terminal view parking — unmounting long-hidden
|
||||
* terminal panes while a pane-less watcher keeps PTY side effects alive.
|
||||
* Defaults to true; `false` disables parking entirely.
|
||||
* See docs/reference/terminal-hidden-view-parking.md. */
|
||||
terminalHiddenViewParking?: boolean
|
||||
/** Kill switch for main-process terminal side-effect authority: when true
|
||||
* (default), local-daemon/SSH PTY title/bell/agent facts are consumed from
|
||||
* the `pty:sideEffect` channel and renderer byte parsers stay unregistered
|
||||
* for those PTYs; `false` restores renderer byte parsing.
|
||||
* See docs/reference/terminal-side-effect-authority.md. */
|
||||
terminalMainSideEffectAuthority?: boolean
|
||||
/** Kill switch for main's hidden-delivery gate (Phase 4): when true
|
||||
* (default) AND terminalMainSideEffectAuthority is on, main drops PTY byte
|
||||
* delivery to hidden renderer views after model ingestion; reveal restores
|
||||
* from the model snapshot. `false` restores hidden byte delivery. */
|
||||
terminalHiddenDeliveryGate?: boolean
|
||||
/** Kill switch for the main model query responder (Phase 5): when true
|
||||
* (default) AND both Phase-4 gate switches are on, main answers terminal
|
||||
* queries (DA1/CPR/DECRPM, …) embedded in hidden-dropped chunks from the
|
||||
* runtime emulator. `false` silences the responder without changing drops.
|
||||
* See docs/reference/terminal-query-authority.md. */
|
||||
terminalModelQueryAuthority?: boolean
|
||||
/** Which agent to pre-select in the new-workspace composer.
|
||||
* - null: auto (first detected agent)
|
||||
* - 'blank': blank terminal (no agent launched)
|
||||
|
||||
Reference in New Issue
Block a user