Repository navigation
perf(terminal): cut cold worktree-switch attach latency - #17667
Conversation
Greptile SummaryThe PR reduces cold worktree-switch terminal attach latency by allowing concurrent terminal spawns while preserving exclusive sleep/adoption operations, and by caching unchanged headless terminal snapshots.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| src/main/daemon/headless-emulator.ts | Routes memoized terminal-state mutations through cache invalidation while keeping freshly read metadata and zero-byte parse fences cache-neutral. |
| src/main/daemon/headless-snapshot-cache.ts | Introduces bounded, scrollback-window-keyed snapshot memoization with cloned mutable return values. |
| src/main/runtime/worktree-terminal-mutation-lock.ts | Implements a writer-preferring shared/exclusive per-worktree lock with deadline abandonment and idempotent release. |
| src/main/runtime/orca-runtime.ts | Integrates shared locking for concurrent spawns and exclusive locking for sleep and adoption. |
| src/main/daemon/headless-emulator-snapshot-cache.test.ts | Covers cache hits, invalidation paths, no-op fences and resizes, alias isolation, and public mutator-surface review. |
| src/main/runtime/worktree-terminal-mutation-lock.test.ts | Covers concurrency, key isolation, writer preference, timeout cleanup, waiter handoff, and repeated release. |
| src/main/runtime/folder-workspace-pty-identity.test.ts | Updates integration expectations to permit concurrent same-worktree spawns while retaining sleep exclusion and workspace identity isolation. |
Sequence Diagram
sequenceDiagram
participant UI as Worktree activation
participant Runtime as Orca runtime
participant Lock as Per-worktree lock
participant PTY as Terminal spawns
participant Emulator as Headless emulator
participant Cache as Snapshot cache
UI->>Runtime: Activate worktree terminals
par Terminal A
Runtime->>Lock: Acquire shared
Lock-->>Runtime: Grant
Runtime->>PTY: Spawn/attach A
and Terminal B
Runtime->>Lock: Acquire shared
Lock-->>Runtime: Grant
Runtime->>PTY: Spawn/attach B
end
PTY->>Emulator: Request settled snapshot
Emulator->>Cache: Build for mutation state/window
alt Cached unchanged snapshot
Cache-->>Emulator: Clone retained parts
else Cache miss or mutation
Cache->>Emulator: Serialize current terminal
Emulator-->>Cache: Snapshot parts
Cache-->>Emulator: Fresh snapshot
end
Emulator-->>UI: Current terminal snapshot
Note over Runtime,Lock: Sleep and adoption acquire exclusive access
Reviews (6): Last reviewed commit: "perf(terminal): do not invalidate the sn..." | Re-trigger Greptile
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review. 📝 WalkthroughWalkthroughThe change adds mutation-aware snapshot caching to Merge Risk: 🔵 Low · up to The PR makes terminal worktree switches faster by parallelizing attaches and reusing unchanged snapshots. It is mergeable with owner awareness for bounded lifecycle and memory-retention edge cases, plus deadline handling for idle terminal operations. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives detailed context, rationale, measurements, risks, scope, and testing. However, it omits several required template sections or required content, including Linked Issue with a completed Fixes reference, Visual Proof or an explicit N/A reason, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist items. Resolution Add all required template sections. Provide the linked issue after “Fixes #”, add Visual Proof or write exactly “N/A” with a reason, complete AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections, and retain the existing technical details and testing results.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b332a9d2-ddf1-491c-b241-580bc6d29f39
📒 Files selected for processing (7)
src/main/daemon/headless-emulator-snapshot-cache.test.tssrc/main/daemon/headless-emulator.tssrc/main/daemon/headless-snapshot-cache.tssrc/main/runtime/folder-workspace-pty-identity.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/worktree-terminal-mutation-lock.test.tssrc/main/runtime/worktree-terminal-mutation-lock.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
| // Why length-gated: see MAX_CACHED_SNAPSHOT_CHARS. Declining to retain | ||
| // costs the pre-existing serialize, never correctness. | ||
| this.retained = | ||
| computed.snapshotAnsi.length + computed.scrollbackAnsi.length <= MAX_CACHED_SNAPSHOT_CHARS |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Include OSC link metadata in the retention limit.
Line 68 counts only ANSI strings. retained also stores oscLinks, including each link URI. A terminal with many OSC link ranges can pass this condition and retain large metadata for the session lifetime. Multiple parked sessions can then exhaust daemon memory.
Count OSC link entries and URI lengths in the budget, or decline retention when either exceeds a fixed limit.
|
|
||
| it('rejects immediately when the deadline has already passed', async () => { | ||
| const lock = new WorktreeTerminalMutationLock() | ||
| const releaseSpawn = await lock.acquire(KEY, 'spawn') |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Reject an expired deadline before an immediate grant.
Line 127 forces the queued path. WorktreeTerminalMutationLock.acquire grants an idle sleep lock before it checks deadline, so lock.acquire(KEY, 'sleep', Date.now() - 1) succeeds when no spawn is active. Add a pre-grant deadline check and test this idle-key case.
Suggested regression test
it('rejects immediately when the deadline has already passed', async () => {
const lock = new WorktreeTerminalMutationLock()
- const releaseSpawn = await lock.acquire(KEY, 'spawn')
await expect(lock.acquire(KEY, 'sleep', Date.now() - 1)).rejects.toThrow(
WORKTREE_TERMINAL_SLEEP_TIMEOUT_ERROR
)
- releaseSpawn()
})There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Two independent, main-process/daemon-only latency fixes to the cold worktree-switch terminal attach path.
- Concurrent per-worktree terminal spawns — replaces the FIFO mutation mutex (
terminalMutationTailByWorktreeId) withWorktreeTerminalMutationLock, a shared/exclusive lock where'spawn'acquisitions share and'sleep'acquisitions exclude with writer preference, so a multi-tab worktree no longer pays the activation staircase. - Memoized headless snapshot —
HeadlessSnapshotCachememoizes the serialized snapshot on a mutation epoch, so a reattach of a quiescent session skips the whole-buffer serialize instead of re-emitting identical bytes. - Epoch invalidation coverage —
HeadlessEmulator.markMutated()is wired to every buffer/mode/osc-link mutation site (write entry + async-parse completion, tryWriteSync, resize, setCwd, setLastTitle, setRestoredOscLinks, clearScrollback, applyPushedViewAttributes); cached values are cloned on hit to prevent caller aliasing.
The lock semantics, deadline/abandon handoff, and key cleanup are correct, and every worktree-scoped mutable state write happens under the exclusive sleep lock while spawn-side state is per-pane/per-pty, so concurrent same-worktree spawns cannot race. The three new/changed test files pass (17 + 12 tests).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes (delta since prior review at a3c7977)
- Zero-byte parse fence no longer evicts the snapshot cache —
write()(entry, async completion, andtryWriteSync) now skipsmarkMutated()whendata.length === 0, soflushParsedWrites()/getSettledSnapshotno longer forces a full re-serialize on every checkpoint read. dispose()invalidates the cache — a post-dispose read can never be served a pre-dispose cached entry.- New tests — fence warm-cache proof (serialize call count), fence-follows-write still reflected, dispose invalidation, and a prototype-surface freeze guarding against unreviewed public mutators.
The zero-byte exemption is sound: an empty write performs no buffer/mode/osc-link mutation (oscText.scan('') and mouseModes.scan('') are no-ops, advancePartialEscapeTail is fold-idempotent on an empty chunk, and writeSync('') writes nothing), and any real write the fence is waiting on has already bumped the epoch on its own completion. 12 + 12 tests pass.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes (delta since prior review at 2b032763)
The elegance commit refactors the two attach-latency fixes without changing their behavior.
- Extracted a
markWrittenlength-gate helper — the three emulator write sites (write entry, async parse-completion,tryWriteSync) now route throughmarkWritten(data), which skipsmarkMutated()on zero bytes; a pure refactor, no behavior change. - Unified the snapshot retention cap into bytes —
MAX_CACHED_SNAPSHOT_CHARS = 2_000_000becomesMAX_CACHED_SNAPSHOT_BYTES = 4 MiB, measured with the samelength * 2code-unit rule asgetColdRestorePayloadBytes; the effective char budget (~2.1M) is essentially unchanged. - Removed the
abandonedtombstone flag and the localwaitForMutationGrant— the lock now reuses the sharedsettleBeforeDeadline, anddraincollapses to amarkActive-driven loop. The flag was genuinely dead:grant()only ever fires synchronously indrainright aftershift(), so a queued waiter is never granted, and the catch splices a timed-out waiter with no intervening await (microtasks drain before any release macrotask could grant it), making grant-after-timeout unrepresentable.
The lock simplification is behaviorally equivalent to the flag-carrying version across all drain orderings (spawn-into-empty, spawn-then-sleep, sleep-with-in-flight-spawns, abandoned-waiter handoff), and the shared settleBeforeDeadline preserves the deadline-already-passed immediate rejection plus the terminal_worktree_sleep_timeout error the caller expects.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
The per-worktree terminal mutation guard was a FIFO mutex, so activating a multi-tab worktree made each tab wait for every predecessor's whole spawn. Measured with ORCA_PTY_SPAWN_TIMING=1 on a 4-tab worktree, the `options` phase was a pure-queueing staircase: 0 / 125 / 212 / 291ms. The invariant that guard protects is spawn-vs-sleep exclusion, never spawn-vs-spawn. Replace it with a writer-preferring shared/exclusive lock: spawns share, sleep still excludes, and a queued sleep blocks later spawns so a stream of spawns cannot starve it into its 12s deadline. Same worktree after: options = 2 / 3 / 12 / 34ms, and stable_adoption flattens from 65/398/398/312ms to a steady ~253ms. The existing folder-workspace control assertion asserted the FIFO behavior this removes, so it is re-based on sleep-vs-spawn (which still queues) and joined by a case asserting concurrent same-worktree spawns.
Attaching a viewer serializes the session's whole headless buffer synchronously on the daemon event loop, so every reattach of a quiescent session re-serialized identical bytes. Measured with ORCA_PTY_SPAWN_TIMING=1, stable_adoption was 253-281ms per session on reattach. Move snapshot assembly into HeadlessSnapshotCache and memoize its expensive parts (the serialize, the OSC link walk, the frame-restore fields) on a mutation epoch that every emulator state mutation bumps, so a cache hit is byte-identical by construction rather than merely fresh-enough. The async write path bumps on entry and again in the parse-completion callback, so a snapshot taken mid-parse can never be retained. Reattach of a quiescent session after: stable_adoption 12ms. Sessions with output since their last snapshot re-serialize exactly as before. Retention is capped: an entry is held for the session's lifetime once it goes quiescent, and a renderer may request 50k scrollback rows, so oversized payloads serve normally but are not retained. Cache hits clone nested values so a caller mutating its snapshot cannot corrupt later ones.
…ences
Review follow-up. flushParsedWrites() is write(''), used purely as a parse
fence, and every getSettledSnapshot runs one — so the epoch bump on an empty
write evicted the attach entry on each checkpoint read, defeating the cache
for any session that gets checkpointed.
Zero bytes cannot mutate the buffer: the OSC and mouse-mode scans are no-ops
on '' and the partial-escape tail is idempotent, so skip the bump for empty
data. Real writes still bracket themselves, and any write a fence orders
behind has already bumped on its own completion.
Also invalidate on dispose, so a post-dispose read can never be served a
pre-dispose entry, and freeze the emulator's public method surface in a test:
the cache's correctness rests on every mutator calling markMutated(), which is
convention rather than a type, so a new method should be a deliberate decision
about invalidation instead of a silent stale-snapshot bug.
Reuse: waitForMutationGrant hand-rolled the deadline race that settleBeforeDeadline (same directory, four existing callers) already owns. Using it also picks up the timer.unref() the local copy lacked, which was keeping the Node event loop alive for up to the 12s sleep deadline. Simplify: drop the waiter `abandoned` flag. The timeout path sets it and splices the waiter out in the same synchronous block, so no queued waiter can ever be observed abandoned and both reads were unreachable. The splice is what actually does the work; the comment now carries why that makes a grant-after-timeout unrepresentable. drain() then collapses into its loop condition and reuses markActive() instead of inlining it twice. Extract markWritten() so the zero-byte parse-fence rationale lives at one mutation gate instead of being restated at three call sites. Match the daemon's byte-accounting convention: the retention cap is now expressed in bytes with code-unit sizing, like MAX_COLD_RESTORE_CACHE_BYTES next door, so the two retention budgets read in one unit. Same effective cap. The public-surface guard test caught markWritten on the first run, which is the behavior it was added for.
…elds Second elegance round, and it found the same class of bug as the parse-fence one: cwd and lastTitle are read fresh on every build and were never memoized, yet setCwd/setLastTitle bumped the epoch — discarding a whole serialize to update a field the cache does not hold. OSC 7 cwd updates land on every `cd`, so this was a live cost on exactly the busy sessions the cache targets. The invariant is "every mutation of a memoized part", not "every state mutation"; both docblocks said the latter and are corrected. Drop the dispose bump too. A post-dispose getSnapshot re-serializes the disposed terminal to byte-identical content, so the bump bought nothing and only reached into a disposed xterm — verified by probe, not assumed. Its test asserted zero serializations after dispose, which no implementation could violate; it passed with the bump deleted. Also memoize rehydrateSequences (a string, so no clone needed) instead of rebuilding it on every hit, derive the frameRestore type from buildFrameRestoreSnapshotFields so a new field cannot flow through at runtime while the type omits it, inline the single-caller resolve() into build(), and move the write() entry bump after the sync early-return so the three bumps map 1:1 onto sync / async-pre-parse / async-post-parse. The surface guard is sorted in source and renamed to say what it freezes: the prototype, TS-private members included.
…indow
The markWritten docblock claimed "zero bytes cannot mutate the buffer". That
is false, and I verified it: `_core.writeSync('')` drains xterm's pending queue
and applies it. The exemption is still correct, but for a different reason —
a fence cannot introduce an *unattributed* mutation, because any bytes it
drains belong to a queued async write whose own completion callback bumps
first. The two write regimes are exhaustive: with writeSync present nothing
can queue, without it every write is async and self-bumps. A comment asserting
a false invariant is worse than no comment, since the next change may rely on
it, so it now states the real one.
Key the cache by scrollback window instead of a single slot. Consumers ask for
different windows against the same emulator — attach passes the full window
while agent/text reads pass 0 — so one slot thrashed to a 0% hit rate whenever
they alternated, silently removing the benefit on runtime-side emulators. Two
entries cover every caller pair in the tree.
Drop the epoch counter: markMutated already nulls the retained entry and an
entry is only ever stored under the current epoch, so the comparison could
never fail. Invalidation is simply "clear the cache".
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes (delta since prior review at 8eee420827)
- Stopped invalidating the snapshot cache on non-memoized fields —
setCwdandsetLastTitleno longer bump the epoch, sincebuild()reads both fresh on every call (cwd: source.cwd,lastTitle: source.lastTitle) even on a cache hit; this also ends the per-cdserialize eviction (OSC 7) the prior commit had accidentally introduced. - Reversed the
dispose()invalidation — serving the retained entry after dispose is byte-identical (dispose mutates nothing memoized) and avoids re-serializing a disposed xterm, which the prior bump would have forced. - Memoized
rehydrateSequencesalongsidemodes— it derives solely from the already-memoizedmodesand returns astring, so the shared cached reference cannot be aliased by a caller. - Moved the
write()entry bump after thetryWriteSyncattempt — removing a double-bump on the sync path while preserving the entry+completion double-bump on the async path that guards against retaining a mid-parse buffer.
I verified that the only fresh-read fields (cwd, lastTitle, partialEscapeTail, cols, rows, scrollbackLines) are pulled from source on every build including cache hits, that rehydrateSequences/frameRestoreAnsi are immutable strings (so the new shared references can't be mutated), and that oscText.scan(data) placement is unchanged. The updated tests assert the intended behavior precisely (serialize-call count stays 0 across setCwd/setLastTitle, and the surface-freeze list is now a hardcoded sorted literal with a corrected comment about TS-private members).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…caller Rebasing onto main surfaced a semantic conflict the merge applied cleanly: main added runWorktreeTerminalMutation (terminal orphan adoption, #17159) as a third caller of the guard this PR changed. It needs the exclusive side — adoption reconciles a worktree's terminal records, so it must not interleave with a spawn registering a pty or with a sleep, which is exactly the semantics it was written under when the guard was a plain mutex. With three operations, naming the sides after two of them no longer fits, so the kinds are now `shared` (spawn) and `exclusive` (sleep, adoption) — what they do rather than who calls them.
153c4f8 to
2cda2e8
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes (delta since prior review at 241f86c8c1)
- Keyed the snapshot cache by
scrollbackRowswindow — replaced the single retained slot with aMap<number | undefined, CachedParts>capped at two windows, so the attach (full window) and agent/text (0) reads stop thrashing each other to a 0% hit rate.markMutated()is nowentries.clear()and the epoch counter is gone. - Corrected the zero-byte fence justification — comment-only; the prior claim that "zero bytes cannot mutate the buffer" was wrong (
_core.writeSync('')drains and applies xterm's pending queue). The accurate argument is that a fence can never introduce an unattributed mutation: withwriteSyncpresent every write is synchronous (nothing queues to drain), and without it every async write self-bumps via its FIFO completion callback before the fence's own. - Adjusted tests — renamed the window re-serialize case to "first time", and added a proof that two alternating windows both stay warm (serialize call count 0 across
0/undefined).
I traced the eviction path (the map never exceeds two entries; a third distinct window deletes the first-inserted key) and confirmed the new test would fail under the previous single-slot implementation, so it meaningfully covers the fixed behavior. The worst case for more than two live windows is a serialize miss — the pre-PR behavior, never staleness.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes (delta since prior review; the branch was rebased onto a main that has since merged #17159, so the prior SHA for this delta is the equivalent commit 153c4f82e6)
- Renamed the lock kinds to
shared/exclusive—'spawn'became'shared'and'sleep'became'exclusive', since the guard now has a third caller and naming the sides after two of them no longer fits. - Wired orphan adoption (
runWorktreeTerminalMutation, from #17159) to'exclusive'— the third caller merged in by the rebase takes the exclusive side, which is correct: adoption reconciles a worktree's terminal records, so it must not interleave with a spawn registering a PTY or with a sleep alike. That is exactly the total-serialization behavior it had under the old plain FIFO mutex, andexclusivestill serializes against otherexclusives (a second exclusive blocks behind the active one), so adoption-vs-adoption ordering is preserved.
I verified the rename is complete (no stray 'spawn'/'sleep' kind literals remain; the sleep-timeout error string intentionally keeps "sleep" since only the sleep path passes a deadline), and that the exclusive-without-deadline acquisition for adoption matches the pre-mutex-deadline behavior (adoption never carried a deadline). No re-entrant acquisition occurs inside the adoption operation, so there is no self-deadlock.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Re-measuring the final rebased build caught the cache barely working on the path it exists for. Every attach re-asserts the pane's dimensions, and resize() bumped unconditionally, so a reattach of a fully idle session missed its own cached snapshot and re-serialized. Measured on the same 4-tab worktree, reattach of sessions verified quiescent (no buffer change over 4s), stable_adoption per session: before this commit: 98 / 382 / 395 / 418 ms after: 16 / 67 / 78 / 87 ms A resize to the size already applied changes nothing the snapshot reads, so it now returns early — which also stops it clearing restoredOscLinks, correct since no rows shifted.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes (delta since prior review at 2cda2e817a)
- No-op
resizekeeps the snapshot cache warm —HeadlessEmulator.resize()now early-returns when the requested dimensions already matchterminal.cols/terminal.rows, skippingmarkMutated()(and therestoredOscLinks = []reset) so an attach that re-asserts a pane's existing size serves its cached snapshot instead of re-serializing (~382ms per idle session per the author's measurement). - New test — "keeps the cache across a resize to the size already applied" asserts
serialize.calls() === 0after a same-dimensionresize.
I verified the gate is sound: a resize to an already-applied size causes no reflow, so the memoized snapshotAnsi/scrollbackAnsi and the oscLinks derived from restoredOscLinks cannot go stale, and the restored links stay valid because no line indices shifted. The test is meaningful — under the prior unconditional markMutated() it fails with a serialize call count of 1. The suite (13 tests) passes.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…#17752) Removes the snapshot memoization added in #17667 and everything that served it: the epoch, markMutated/markWritten, the no-op resize gate, and the HeadlessSnapshotCache module. The shared/exclusive spawn lock from the same PR stays — it is the half that carries the measured win. Why: a controlled A/B on merged main could not show the cache paying for its memory. Same worktree, same sessions, reattach stable_adoption per session: cache + resize gate (as merged) 16 / 67 / 78 / 87 ms cache off, gate on 17 / 55 / 68 / 80 ms cache off, gate off 13 / 62 / 73 / 83 ms Indistinguishable. Cold 4-tab activation was likewise unchanged (217-296ms without the cache vs 226-309ms with), which is expected — a first attach is always a miss. The reason it under-delivers is a design fact the original PR missed: attach does not request the full buffer. terminal-host-session-create.ts passes resolveDaemonSessionScrollbackRows() — a deliberate 1000-row live window, capped because unbounded retention once OOM-killed a host. Serializing 1000 rows is cheap, so there was little for a cache to save on that path. Against that, the cache retained up to MAX_CACHED_SNAPSHOT_BYTES (4MB) per entry across MAX_CACHED_SNAPSHOT_WINDOWS (2) entries per emulator, for the session's lifetime, with no aggregate budget across sessions. It also carried an invalidation contract that produced three separate over-invalidation bugs during review (the parse fence, setCwd/setLastTitle, and the no-op resize). The lock fix is unaffected and independently measured: the `options` phase, which is pure queueing, went 0/125/212/291ms -> 1/1/1/1ms across a 4-tab worktree activation and stays there.
Cold restore seeded a checkpoint's OSC-8 link ranges and then replayed records that resize, so any resize record after the checkpoint dropped them and restored hyperlinks in scrollback lost clickability. Same-size resize records reach the durable log routinely, because every attach re-asserts the pane's dimensions and session-output-plane records each one without a same-size dedupe — so an ordinary reattach was enough to lose the links. Restored ranges are row-indexed, so clearing them on a reflow is right; a resize to the size already applied is not a reflow. Gate on the dimensions actually changing. Introduced in d46349c ("fix: improve mobile link modifier handling", #5597), which added setRestoredOscLinks along with unconditional clearing in both resize() and clearScrollback(). clearScrollback's clearing is correct and is unchanged, with a test pinning it. Found during adversarial review of #17752 and filed as #17756. Not a regression from that PR: #17667 had incidentally masked it by gating no-op resizes to protect a snapshot cache, and removing the cache removed the gate. The same gate returns here on its own terms — as a correctness fix with tests, rather than as a side effect of a cache.
…-refactor main advanced 45 commits, six of them landing inside the orca-runtime.ts this branch splits apart. Git resolves that as a plain "take one side", and either side silently loses work, so each was ported into the module that now owns the code: - stablyai#17655 bound ref and worktree scans -> runtime-repository-ref-queries - stablyai#17448 preserve user-set workspace names -> the worktree-create modules - stablyai#17667 cut cold worktree-switch attach latency -> the mutation lock, including the deletion half (worktree-terminal-mutation-wait.ts is gone) - stablyai#17718 preserve large agent prompt pastes -> the agent-prompt write path - stablyai#17486 unblock targeted SSH session tab refresh -> the mobile refresh modules - stablyai#17159 close readiness gaps -> 34 runtime hunks and 5 test hunks Every added line of the six was checked against the merged tree; the unmatched ones are all renames or line splits, verified individually. Two defects surfaced while porting, both predating this merge: - isMobileSessionSurfaceMembershipAllowed read a session accessor that answers null where main's answers undefined, so main's `session !== undefined` guard was always true and the fence stopped fencing. Three clauses found in neither main nor the split base had been added ahead of it to compensate, and one of them dropped a freshly published split leaf out of syncWindowGraph. Restored to main's control flow with the sentinel normalized; stablyai#17159's two new tests cover it from both directions. - retiredMobileSessionPtyIds was write-only state this branch invented. Its only reader was the clause above, and it exists in neither main nor the split base. - RuntimeTerminalWriter.writeAgentPrompt had no callers and still carried the chunked-paste shape stablyai#17718 replaced.
* perf(terminal): let a worktree's terminal spawns run concurrently
The per-worktree terminal mutation guard was a FIFO mutex, so activating a
multi-tab worktree made each tab wait for every predecessor's whole spawn.
Measured with ORCA_PTY_SPAWN_TIMING=1 on a 4-tab worktree, the `options`
phase was a pure-queueing staircase: 0 / 125 / 212 / 291ms.
The invariant that guard protects is spawn-vs-sleep exclusion, never
spawn-vs-spawn. Replace it with a writer-preferring shared/exclusive lock:
spawns share, sleep still excludes, and a queued sleep blocks later spawns
so a stream of spawns cannot starve it into its 12s deadline.
Same worktree after: options = 2 / 3 / 12 / 34ms, and stable_adoption
flattens from 65/398/398/312ms to a steady ~253ms.
The existing folder-workspace control assertion asserted the FIFO behavior
this removes, so it is re-based on sleep-vs-spawn (which still queues) and
joined by a case asserting concurrent same-worktree spawns.
* perf(terminal): memoize the headless snapshot per mutation epoch
Attaching a viewer serializes the session's whole headless buffer
synchronously on the daemon event loop, so every reattach of a quiescent
session re-serialized identical bytes. Measured with ORCA_PTY_SPAWN_TIMING=1,
stable_adoption was 253-281ms per session on reattach.
Move snapshot assembly into HeadlessSnapshotCache and memoize its expensive
parts (the serialize, the OSC link walk, the frame-restore fields) on a
mutation epoch that every emulator state mutation bumps, so a cache hit is
byte-identical by construction rather than merely fresh-enough. The async
write path bumps on entry and again in the parse-completion callback, so a
snapshot taken mid-parse can never be retained.
Reattach of a quiescent session after: stable_adoption 12ms. Sessions with
output since their last snapshot re-serialize exactly as before.
Retention is capped: an entry is held for the session's lifetime once it goes
quiescent, and a renderer may request 50k scrollback rows, so oversized
payloads serve normally but are not retained. Cache hits clone nested values
so a caller mutating its snapshot cannot corrupt later ones.
* perf(terminal): keep the snapshot cache warm across zero-byte parse fences
Review follow-up. flushParsedWrites() is write(''), used purely as a parse
fence, and every getSettledSnapshot runs one — so the epoch bump on an empty
write evicted the attach entry on each checkpoint read, defeating the cache
for any session that gets checkpointed.
Zero bytes cannot mutate the buffer: the OSC and mouse-mode scans are no-ops
on '' and the partial-escape tail is idempotent, so skip the bump for empty
data. Real writes still bracket themselves, and any write a fence orders
behind has already bumped on its own completion.
Also invalidate on dispose, so a post-dispose read can never be served a
pre-dispose entry, and freeze the emulator's public method surface in a test:
the cache's correctness rests on every mutator calling markMutated(), which is
convention rather than a type, so a new method should be a deliberate decision
about invalidation instead of a silent stale-snapshot bug.
* refactor(terminal): apply elegance review to the attach-latency fixes
Reuse: waitForMutationGrant hand-rolled the deadline race that
settleBeforeDeadline (same directory, four existing callers) already owns.
Using it also picks up the timer.unref() the local copy lacked, which was
keeping the Node event loop alive for up to the 12s sleep deadline.
Simplify: drop the waiter `abandoned` flag. The timeout path sets it and
splices the waiter out in the same synchronous block, so no queued waiter can
ever be observed abandoned and both reads were unreachable. The splice is what
actually does the work; the comment now carries why that makes a
grant-after-timeout unrepresentable. drain() then collapses into its loop
condition and reuses markActive() instead of inlining it twice.
Extract markWritten() so the zero-byte parse-fence rationale lives at one
mutation gate instead of being restated at three call sites.
Match the daemon's byte-accounting convention: the retention cap is now
expressed in bytes with code-unit sizing, like MAX_COLD_RESTORE_CACHE_BYTES
next door, so the two retention budgets read in one unit. Same effective cap.
The public-surface guard test caught markWritten on the first run, which is
the behavior it was added for.
* perf(terminal): stop discarding the snapshot cache on non-memoized fields
Second elegance round, and it found the same class of bug as the parse-fence
one: cwd and lastTitle are read fresh on every build and were never memoized,
yet setCwd/setLastTitle bumped the epoch — discarding a whole serialize to
update a field the cache does not hold. OSC 7 cwd updates land on every `cd`,
so this was a live cost on exactly the busy sessions the cache targets. The
invariant is "every mutation of a memoized part", not "every state mutation";
both docblocks said the latter and are corrected.
Drop the dispose bump too. A post-dispose getSnapshot re-serializes the
disposed terminal to byte-identical content, so the bump bought nothing and
only reached into a disposed xterm — verified by probe, not assumed. Its test
asserted zero serializations after dispose, which no implementation could
violate; it passed with the bump deleted.
Also memoize rehydrateSequences (a string, so no clone needed) instead of
rebuilding it on every hit, derive the frameRestore type from
buildFrameRestoreSnapshotFields so a new field cannot flow through at runtime
while the type omits it, inline the single-caller resolve() into build(), and
move the write() entry bump after the sync early-return so the three bumps map
1:1 onto sync / async-pre-parse / async-post-parse.
The surface guard is sorted in source and renamed to say what it freezes: the
prototype, TS-private members included.
* fix(terminal): correct the fence justification and key the cache by window
The markWritten docblock claimed "zero bytes cannot mutate the buffer". That
is false, and I verified it: `_core.writeSync('')` drains xterm's pending queue
and applies it. The exemption is still correct, but for a different reason —
a fence cannot introduce an *unattributed* mutation, because any bytes it
drains belong to a queued async write whose own completion callback bumps
first. The two write regimes are exhaustive: with writeSync present nothing
can queue, without it every write is async and self-bumps. A comment asserting
a false invariant is worse than no comment, since the next change may rely on
it, so it now states the real one.
Key the cache by scrollback window instead of a single slot. Consumers ask for
different windows against the same emulator — attach passes the full window
while agent/text reads pass 0 — so one slot thrashed to a 0% hit rate whenever
they alternated, silently removing the benefit on runtime-side emulators. Two
entries cover every caller pair in the tree.
Drop the epoch counter: markMutated already nulls the retained entry and an
entry is only ever stored under the current epoch, so the comparison could
never fail. Invalidation is simply "clear the cache".
* refactor(terminal): name the lock sides shared/exclusive for a third caller
Rebasing onto main surfaced a semantic conflict the merge applied cleanly:
main added runWorktreeTerminalMutation (terminal orphan adoption, stablyai#17159) as a
third caller of the guard this PR changed. It needs the exclusive side —
adoption reconciles a worktree's terminal records, so it must not interleave
with a spawn registering a pty or with a sleep, which is exactly the semantics
it was written under when the guard was a plain mutex.
With three operations, naming the sides after two of them no longer fits, so
the kinds are now `shared` (spawn) and `exclusive` (sleep, adoption) — what
they do rather than who calls them.
* perf(terminal): do not invalidate the snapshot cache on a no-op resize
Re-measuring the final rebased build caught the cache barely working on the
path it exists for. Every attach re-asserts the pane's dimensions, and resize()
bumped unconditionally, so a reattach of a fully idle session missed its own
cached snapshot and re-serialized.
Measured on the same 4-tab worktree, reattach of sessions verified quiescent
(no buffer change over 4s), stable_adoption per session:
before this commit: 98 / 382 / 395 / 418 ms
after: 16 / 67 / 78 / 87 ms
A resize to the size already applied changes nothing the snapshot reads, so it
now returns early — which also stops it clearing restoredOscLinks, correct
since no rows shifted.
…stablyai#17752) Removes the snapshot memoization added in stablyai#17667 and everything that served it: the epoch, markMutated/markWritten, the no-op resize gate, and the HeadlessSnapshotCache module. The shared/exclusive spawn lock from the same PR stays — it is the half that carries the measured win. Why: a controlled A/B on merged main could not show the cache paying for its memory. Same worktree, same sessions, reattach stable_adoption per session: cache + resize gate (as merged) 16 / 67 / 78 / 87 ms cache off, gate on 17 / 55 / 68 / 80 ms cache off, gate off 13 / 62 / 73 / 83 ms Indistinguishable. Cold 4-tab activation was likewise unchanged (217-296ms without the cache vs 226-309ms with), which is expected — a first attach is always a miss. The reason it under-delivers is a design fact the original PR missed: attach does not request the full buffer. terminal-host-session-create.ts passes resolveDaemonSessionScrollbackRows() — a deliberate 1000-row live window, capped because unbounded retention once OOM-killed a host. Serializing 1000 rows is cheap, so there was little for a cache to save on that path. Against that, the cache retained up to MAX_CACHED_SNAPSHOT_BYTES (4MB) per entry across MAX_CACHED_SNAPSHOT_WINDOWS (2) entries per emulator, for the session's lifetime, with no aggregate budget across sessions. It also carried an invalidation contract that produced three separate over-invalidation bugs during review (the parse fence, setCwd/setLastTitle, and the no-op resize). The lock fix is unaffected and independently measured: the `options` phase, which is pure queueing, went 0/125/212/291ms -> 1/1/1/1ms across a 4-tab worktree activation and stays there.
…lyai#17759) Cold restore seeded a checkpoint's OSC-8 link ranges and then replayed records that resize, so any resize record after the checkpoint dropped them and restored hyperlinks in scrollback lost clickability. Same-size resize records reach the durable log routinely, because every attach re-asserts the pane's dimensions and session-output-plane records each one without a same-size dedupe — so an ordinary reattach was enough to lose the links. Restored ranges are row-indexed, so clearing them on a reflow is right; a resize to the size already applied is not a reflow. Gate on the dimensions actually changing. Introduced in 10fe9a0 ("fix: improve mobile link modifier handling", stablyai#5597), which added setRestoredOscLinks along with unconditional clearing in both resize() and clearScrollback(). clearScrollback's clearing is correct and is unchanged, with a test pinning it. Found during adversarial review of stablyai#17752 and filed as stablyai#17756. Not a regression from that PR: stablyai#17667 had incidentally masked it by gating no-op resizes to protect a snapshot cache, and removing the cache removed the gate. The same gate returns here on its own terms — as a correctness fix with tests, rather than as a side effect of a cache.

ELI5
When you click a different worktree in the sidebar, Orca has to reconnect to the terminals already running there. Two things made that slow, and neither was doing any actual work.
One at a time. If a worktree had 4 terminal tabs, Orca reconnected them in single file — each tab waited for the one before it to finish. There is a lock there on purpose, to stop a reconnect from colliding with "put these terminals to sleep". But it was a plain queue, so it also made reconnects wait for each other, which was never necessary. Now reconnects happen side by side; only sleep still gets the room to itself.
Redrawing from scratch every time. To paint a terminal, Orca asks the background process for a snapshot of everything that terminal has printed. It rebuilt that snapshot from nothing on every single request — even when not one character had changed since the last one. Now it keeps the last snapshot and hands the same one back, and throws it away the instant anything in that terminal changes, so it can never show you stale output.
What you'll notice: switching to a worktree with several terminal tabs is meaningfully quicker, and returning to one you've already visited is close to instant.
What
Two independent latency bugs in the terminal attach path, found by profiling a slow worktree switch. Both are pure latency — no behavior change.
This started as an investigation into hover-prefetching parked worktrees (speculation-rules style). Profiling killed that idea: a parked worktree already reveals in ~55ms. The 2–3s users feel is the cold path, and it is ~95% PTY attach latency. So this PR fixes the latency instead of speculating around it.
Measurements
All numbers from
ORCA_PTY_SPAWN_TIMING=1(the repo's existing phase instrumentation), macOS, dev build, same machine and same worktrees before/after.1. A worktree's terminal spawns no longer queue behind each other
The per-worktree terminal mutation guard was a FIFO mutex, so each tab of a multi-tab worktree waited for every predecessor's entire spawn. The invariant it protects is spawn-vs-sleep exclusion, never spawn-vs-spawn.
Same 4-tab worktree, same PTY ids, before vs the final rebased build:
optionsstable_adoptionThe
optionsstaircase is textbook queueing — near-equal increments, no work. It is gone, andstable_adoptionflattens.Replaced with a writer-preferring shared/exclusive lock: spawns share, sleep excludes, and a queued sleep blocks later spawns so a stream of spawns cannot starve it into its 12s deadline.
2. The daemon no longer re-serializes an unchanged buffer on every attach
Attaching a viewer serializes the session's whole headless buffer synchronously on the daemon event loop. Reattaching a quiescent session re-serialized identical bytes.
Reattach of sessions verified quiescent (no buffer change over 4s), per session:
stable_adoptionSessions with output since their last snapshot re-serialize exactly as before, which is correct.
Re-measuring the final build is what caught the last commit: every attach re-asserts the pane's dimensions, and
resize()bumped unconditionally, so a reattach of an idle session was missing its own cached snapshot. The numbers above are from the code being merged, not an earlier revision.The cache is keyed on a mutation epoch bumped by every emulator state mutation, so a hit is byte-identical by construction rather than merely fresh-enough — not a staleness tradeoff.
Correctness notes
write(entry and the async parse-completion callback),tryWriteSync,resize,setCwd,setLastTitle,setRestoredOscLinks,clearScrollback,applyPushedViewAttributes,dispose. The double bump onwriteis what prevents a snapshot taken mid-parse from being retained.modes, eachoscLinksentry,frameRestore) so a caller mutating its snapshot cannot corrupt later ones.headless-emulator.tswould have exceededmax-lines, so snapshot assembly moved intoheadless-snapshot-cache.tsrather than adding a suppression.Review follow-up
An adversarial review found no correctness bug in either fix, but did find one that blunted the second:
flushParsedWrites()iswrite('')used as a parse fence, and everygetSettledSnapshotruns one — so the epoch bump on a zero-byte write evicted the attach entry on every checkpoint read. Empty writes are now exempt (the OSC and mouse-mode scans are no-ops on'', the escape tail is idempotent, and any write a fence orders behind has already bumped on its own completion).Also from review: invalidate on
dispose(), and freeze the emulator's public method surface in a test — the cache's correctness rests on every mutator callingmarkMutated(), which is convention rather than a type, so adding a method should force a deliberate decision about invalidation.Tests
New: 9 lock cases (concurrency, key isolation, writer preference, deadline expiry, abandoned-waiter handoff, idempotent release, no key leak) and 12 snapshot-cache cases (a real cache-hit proof via serialize-call count, one per invalidation trigger, the zero-byte fence, dispose, aliasing, and the public-surface guard).
One existing assertion changed: the folder-workspace "control" asserted the spawn-vs-spawn FIFO behavior this PR deliberately removes. It is re-based on sleep-vs-spawn (which still queues) so it still proves the lock blocks, plus a new case asserting concurrent same-worktree spawns.
pnpm tc,src/main/daemon(1708 passing) and the runtime suites pass; changed-file lint clean.Not in scope
Profiling also surfaced a
host_envphase of ~2100ms on first attach — bigger than either bug here. It is being fixed separately in #17669. Note the phase name is misleading: it spans all of the Codex home/hook/auth-readiness setup rather than justbuildPtyHostEnv, and the 0ms on repeat attaches is a skip (guarded bypreAdoptedStablePane) rather than a cache.Trade-off
Not free.
MAX_CACHED_SNAPSHOT_BYTES(4MB) is a per-entry cap and the cache keeps up toMAX_CACHED_SNAPSHOT_WINDOWS(2) entries per emulator, so the ceiling is ~8MB per emulator, held for the session's lifetime once quiescent. Sessions with a runtime-side mirror have two emulators. Typical is far lower — a 5k-row buffer serializes to a few hundred KB — but it is steady-state, not transient, and there is no aggregate budget across sessions.Lifetime retention is where the win comes from (a reattach minutes later is exactly the case measured above), so a TTL would give most of it back. Worth revisiting if daemon RSS becomes a complaint; the honest fix is an aggregate budget like
cold-restore-payload-cache.tsalready has one directory over.Risk
Main-process/daemon only; no renderer, wire, or persisted-format change. Cross-platform paths untouched.
Rebased onto main after #17159 added a third caller of the guard this PR changes (terminal orphan adoption). It takes the exclusive side, matching the plain-mutex semantics it was written under; the lock's kinds are now named
shared/exclusiverather than after two of three callers.