Repository navigation
Slept agents look idle and wake in place when messaged - #44113
Conversation
4875bf3 to
5767163
Compare
|
Status: marked ready so GitHub CI runs the typecheck and tests. CI stands in for remote-check because Omarchy was down. This PR is still stacked on #41746 → #41701 → #43529 and is not for merging until those land and it is rebased onto main. M4Air QA: round 3 woke slept agents in place (one resume, same session and tab, no duplicates) but single sends timed out undelivered. The fix is in 5767163, and round-4 QA is queued. |
b2a241c to
69daa5e
Compare
5767163 to
86442e4
Compare
|
CI update: PR Checks (typecheck + unit) pass on 86442e4, which folds the test-fixture and mail-hold fixes into the stack. GitHub CI still stands in for remote-check (Omarchy down). Round-4 M4Air QA is still queued. |
Perf scan: PR #44113,
|
| Work | Trigger | Population | Bound / disposition |
|---|---|---|---|
sleptLeafHandle / agentSleepStopPtyId (hook snapshot read: Map get plus one stitched row alloc) |
issueHandle slow path, terminal.list per non-running leaf, read/wait/send/isRunning per handle, graph sync per leaf whose ptyId changed |
leaves without a connected PTY | O(1) per leaf, a constant factor on scans that were already O(leaves). Connected leaves short-circuit before the snapshot read. ≤1000 leaves ≈ <0.5 ms per list. OK. |
restoreSleptLeafHandle: sync SQLite getLatestDispatchForTerminal plus a synthetic handle |
first read of a slept pane after a restart or reload | slept panes | once per pane per reload (cached via sleptLeafHandles); ≈100 indexed queries per reload. OK as a one-time cost; the retention is P1-3. |
terminal.list isSleptAgentLeaf + summary sleptAgentHandle |
per terminal.list |
leaves in live worktrees | O(1) per leaf. OK. |
retainLeafHandle / park / rebind in graph sync |
a leaf's ptyId changes | changed leaves only | O(1) per changed leaf. OK. |
sleptPaneHandleForSpawn in assemblePtyIpcSpawnEnv |
per PTY spawn | 1 | O(1). OK. |
startRestoredHandlePane now ungated by ORCA_LAYOUT_OWNER_IS_MAIN → wakeSleptAgentHandle |
per send / prompt | 1 handle | O(1) when not slept; the send RPC checks twice (method plus dispatch), both O(1). OK. |
wakeSleptAgentHandle: queued wake workspace command → notifier.resumeSleepingAgents |
first act on a slept pane | 1 per pane (deduped in sleptPaneResumes, deleted in finally) |
one resume per pane. OK. Its polling is P1-2. |
waitForSleptAgent |
terminal.wait on a slept handle |
waiters | tui-idle resolves immediately (OK); exit is P1-2. |
readSleptAgentTerminal |
terminal.read on a slept handle |
1 | bounded tail read over existing buffers (readTerminalTail with cursor/limit). OK. |
isTerminalRunningAgent slept short-circuit |
per call (dispatch, follow-up, federation, terminal.show) |
1 handle | O(1), and it skips the presence probe for slept agents. OK. |
assertAgentSleepAdmitted: 1 mailbox-terminal lookup, ≤P getActiveDispatchForIdentity, hasDeliverableMail (indexed SQLite per owned mailbox) |
per sleep attempt | 1 pane | O(paneKeys + owned mailboxes) per attempt. The per-attempt cost is OK; the retry cadence is P1-1. |
SleptMailboxWake.ownerPane handlePane fallback |
batch / selection when mailboxOwnerPane is null |
per mailbox request | O(1). OK. |
holdsSleptPaneWake in the custody-clear loop |
crew change for affected panes | affected panes | O(1) per pane. OK. |
withSleptAgentWorkers |
worker list / show | ≤100 per page | P1-4. |
inspectWorkerTerminal slept branch: 1–2 indexed SQLite reads plus showTerminal |
single-worker RPCs (stop / release / control / follow-up) | 1 | constant per RPC; never called in a loop (5 call sites checked). OK. |
userTabHoldingSession / openWorkerTerminal slept lookup |
follow-up | matching rows | O(1) per matching row. OK. |
liveResumeRecordChange sleptSameTurn guard |
status-to-resume record sync | 1 row | O(1); it removes a record write. OK. |
| Message-pointer backticks | mail pointer formatting | 1 | constant. OK. |
Subscriptions and publications census
- New subscriptions: none.
sleptAgentPaneForHandlecalls the pre-existing idempotentwatchSleepingMail()(guarded bywatchingSleepingMail).- It installs once per runtime: 1×
onClientEvent, 1×subscribeAgentStatusRowChanges, 1×crewChanges, 1×sessionCrewChangesand 1×onWorkspaceSessionWritten, so 5 listeners at 1 instance. requestSleptMailboxWakealready installed these on the first mail send. The PR can only install them earlier, when orchestration first touches a slept agent.
- Rates once installed:
- status-row listener: at hook rate (>1/s per active agent at idle-busy, 100+/s under load), O(1)
custodyRecords.geteach - crew listener: per crew invalidation
- session-written listener: per workspace-session write
- status-row listener: at hook rate (>1/s per active agent at idle-busy, 100+/s under load), O(1)
- New publications: none. No new emit, version bump or notify sites in the diff.
- Renderer: the only change is the hibernation catch. Its write amplification is P1-1.
Regression classes touched
- Fixed-cadence poll that never settles: finding P1-2.
- Polling where a push exists: finding P1-2.
- Per-entity state outlives entity: finding P1-3 (
sleptLeafHandles).sleptPaneResumesis matched and disproved: it is deleted infinally. - Hot-path rescans: finding P1-4.
- Unused work before the skip gate / whole-file rewrite per change: finding P1-1 (the capture and the session-persist writes run before main's admission gate, on every tick).
- Sync fs or SQLite on Electron main:
assertAgentSleepAdmitted,inspectWorkerTerminalandrestoreSleptLeafHandlerun indexed point reads per RPC, per sleep attempt, or once per reload.- None runs per keystroke, PTY chunk or poll. Matched and disproved.
- Unbounded fan-out: wake is one per pane and goes through
queueTerminalWorkspaceCommand. Matched and disproved, apart from the per-caller poll loops (P1-2). - Not matched: no-op store write / selector, streaming, eager imports and subprocess per item. None of these patterns are in the diff.
Six questions
- Unused work before the gate: reviewed. Finding P1-1.
- Ownership multiplies work: reviewed.
- Wake dedupe is per pane.
- Per-caller poll loops multiply with callers (P1-2).
- Listeners install once per runtime.
- Thread / storage: reviewed.
- All main-side work is O(1) Map work plus indexed
node:sqlitepoint reads. - The renderer pays for the P1-1 serializes.
- All main-side work is O(1) Map work plus indexed
- Growth / progress: reviewed.
- P1-3: map growth per reload.
- P1-1: retries have no cursor or state change.
- P1-4: scan grows with the status count.
- Execution host: reviewed.
- The wake goes through the renderer's
resumeSleepingAgents. Polling is local Map reads, with no SSH round trip per tick. - Remote and SSH resumes were not exercised.
- Windows and Linux behaviour is not affected by the platform code in this diff.
- The wake goes through the renderer's
- Obsolete work stops: reviewed.
- RPC waits abort on connection close (
dispatcher.tsconnectionSignal). - Internal wakes with
{}keep polling for 120 s after a failed wake (P1-2). - A refused sleep leaves
setTabLayoutbuffers written (P1-1).
- RPC waits abort on connection close (
Coverage and gaps
- Examined: all 35 changed files. Callers traced:
terminal.wait/terminal.read/terminal.send/terminal.list, plus the multiplex exit waiter- worker list / show / follow-up / stop / release
- orchestration mutation executor
- PTY spawn env, graph sync, graph reload / reset
- hibernation tick →
shutdownCompletedAgentPaneForHibernation→terminal.stopExact/pty.kill
- Not executed: no tests, benchmarks or app runs, per the instructions (no
tcor full suite). - Not verified:
- whether a multiplex stream can attach to a slept handle, which would add a long-lived
exitpoller per open mobile view - whether
confirmAgentHibernationCandidatesre-confirms a refused pane on every tick (the retry comment implies it does) - SSH / remote resume latency
- whether a multiplex stream can attach to a slept handle, which would add a long-lived
- Hosts: macOS source review only.
Perf scan, pass 2: PR #44113 (
|
| Work | Trigger / rate | Population | Bound / disposition |
|---|---|---|---|
sleptLeafHandle(leaf) from issueLeafHandleRecord, the terminal summary (sleptAgentHandle), RuntimeTerminalList.isSleptAgentLeaf, and sleptPaneHandleForSpawn |
each terminal list/show (≈12 agents × every few s), each issue miss, each PTY spawn | listed leaves (few hundred) | Constant per leaf. A connected leaf exits after ~3 Map lookups. A PTY-less or disconnected leaf adds one getStatusSnapshotForPane (indexed by pane, O(subjects in that pane)). About 4 lists/s × 300 leaves × ~1 µs ≈ 1 ms/s. The list was already O(leaves), so this is not amplification. |
restoreSleptLeafHandle (identity mint plus getLatestDispatchForTerminal SQLite read) |
first read of a slept pane after restart/reload | slept panes | Once per pane: after it runs, sleptLeafHandles and the leaf binding make later reads return early. Graph sync with the same ptyId does not invalidate it. setHandle/bindLeaf do not notify crewChanges. |
pruneSleptLeafHandles |
every renderer graph sync | sleptLeafHandles size (≤ slept panes) |
O(S) per sync, where S is the number of slept panes. It also runs onSleptLeafGraphSynced (O(W+E) where W is pending wakes and E is carried waits; both 0 at idle). Entries are also deleted in invalidateLeafHandle and adoptFirstPtyForLeafHandle. No growth. |
sleptAgentPaneForHandle → watchSleepingMail() + sleepingMailRecord |
isRunning checks, wait, send, mailbox routing, mail ownerPane fallback |
per call | watchSleepingMail is an existing one-time latch, reached only once a slept handle is confirmed. The record read is a Map get. Constant. |
wakeSleptAgentHandle in startRestoredHandlePane (the ORCA_LAYOUT_OWNER_IS_MAIN gate moved inside restoredPaneToStart), send RPC, mutation executor, local worker start |
each send/prompt | per call | Map get plus the constant path above. Deduped: one wake per handle in sleptAgentWakes, deleted in finally. One queueTerminalWorkspaceCommand and one renderer resumeSleepingAgents per wake. Joiners use joinWithin, which removes its timer and abort listener on settle. |
awaitWokenHandle / waitForSleptAgent |
per wake, per exit wait on a slept handle | pending waits | Settles on bind, timeout or abort, and each removes the check, timer and listener. An exit wait with no deadline is held until its caller's request aborts. That is the requested semantics, and the cost per held wait is O(1) per crewChanges event. |
carrySleptAgentExitWait and RuntimeTerminalWaiterRegistry.move |
PTY exit of a slept agent with an exit waiter | carried waits | O(1) move. Waits that were dropped are cleaned up on the next sync or notify. |
withSleptAgentWorkers |
each worker-list/fleet projection | workers + statuses | Runs only for workers observe did not resolve. One lazy byPane index per projection, O(statuses), then an O(1) lookup per worker. Linear, no per-worker rescans. |
inspectWorkerTerminal / openWorkerTerminal / userTabHoldingSession additions |
per worker RPC (show/wait/stop/follow-up) | 1 dispatch | 1–2 indexed SQLite reads on main per RPC, plus one showTerminal. Constant. Not called in a loop over workers (callers checked). |
assertAgentSleepAdmitted (renderer-kill keepHistory, worktree exact stop) |
each sleep attempt | 1 PTY (worktree stop: each expected PTY) | A few indexed SQLite reads (getActiveDispatchForIdentity per pane key, plus hasDeliverableMail). The trigger is the hibernation tick (60 s, drained sequentially) or a user worktree sleep. Constant per attempt. |
Renderer busyRetries backoff |
hibernation tick, 60 s | candidates | It checks admission before calling the stop RPC, so it reduces work: busy panes back off from 5 min to 30 min instead of retrying every 60 s. Entries are pruned every tick against the current candidates and cleared on reset. |
holdsSleptPaneWake linear scan of sleptAgentWakes |
each coalesced publishSleepingMail microtask, for affected custody panes not owed mail |
custody panes C × wakes W | O(C×W) string compares. With W ≤ concurrent blocking callers (about 12), at C=100 that is about 1.2k compares per publication (well under 0.1 ms). At 10× (C=1000, W=120) it is about 120k compares (around 1 ms) per publication. Dismissed with those numbers; a Set of waking pane keys would make it O(1). |
liveResumeRecordChange sleep-record guard; formatMessagePointer backticks |
per checkpoint / per pointer | 1 | Constant. No change in cost. |
Subscription / publication census
crewChanges.subscribe(onSleptLeafGraphSynced)(watchWokenHandles)- Idle: 0 listeners. It is subscribed only while
wokenHandleChecksorcarriedExitWaitsis non-empty, and unsubscribed inonSleptLeafGraphSyncedonce both are empty. - Under load: at most 1 listener, however many wakes are pending, because of the
??=latch. It fires on everycrewChanges.notify, which is synchronous and not coalesced. That includes agent status transitions, so with hook status >1/s × 100 agents it fires about 100+ times per second. Each call costs O(W+E) Map lookups. With 12 pending wakes that is about 2.4k lookups/s at 1× and about 24k/s at 10×. Bounded.
- Idle: 0 listeners. It is subscribed only while
- Recheck
setInterval, 500 ms: 0 at idle; W while wakes are in flight. Each is cleared infinallyand capped by the 120 s deadline. This is the P1 above. - No new publications: the PR adds no new
notify/emit/IPC sends.restoreSleptLeafHandlechanges identity on a read path without notifying, and only once per pane. - Renderer: no new store subscriptions or selectors. The hibernation coordinator only gained the
busyRetriesmap.
Regression classes touched
- Fixed-cadence poll: finding (the duplicated interval). It does settle: cleared on bind, timeout or failure.
- Per-entity state outlives entity: disproved. Every new map or set is cleaned up, including
sleptLeafHandles,sleptAgentWakes,wokenHandleChecks,carriedExitWaitsandbusyRetries. Each table row above names its cleanup. - Sync SQLite on main: disproved. Every new query is per RPC, per sleep attempt or once per restore, and indexed. None runs per keystroke, chunk or poll.
- Per-row derivation over the whole collection: disproved. The added per-leaf and per-worker work is O(1), with a lazy index built once per projection.
- Hot-path rescans:
holdsSleptPaneWakematched, but is O(W) with W bounded by concurrent callers. Dismissed with the numbers in the table. - Update published when nothing changed: no matching code. The PR only subscribes; it does not publish.
- Unbounded fan-out: disproved. Wakes are deduped per handle and resumes are serialized per worktree through
queueTerminalWorkspaceCommand. - Hidden-owner work: at idle there is zero timer and zero listener activity.
Six questions
- Unused work before the skip gate: reviewed.
busyRetriesis checked before the stop RPC. The bare-interrupt early return happens before any wake. ThebyPaneindex is built lazily, only when some worker needs it. - Ownership multiplies work: finding, since the interval is per wake rather than per runtime. The listener is shared, and wakes are deduped per handle.
- Which thread pays: reviewed. Everything runs on Electron main as Map lookups plus a few indexed SQLite reads, each per RPC or per sleep attempt. The renderer change is cheap and once per tick.
- Growth and progress: reviewed. The restore runs once per pane, the backoff doubles up to 30 min, the wake deadline is 120 s, and dropped carried waits are cleaned on the next sync.
- Execution host: reviewed. Each wake makes one renderer
resumeSleepingAgentscall; there are no SSH round trips per item. Windows/Linux/WSL behavior is not exercised; the code paths are platform-neutral. - Obsolete work stops: reviewed. Abort and timeout remove the timer, the listener and the check. An exit wait with no deadline lives as long as its caller's request. Internal callers that pass no signal were not enumerated (residual).
Evidence and limits
- All findings are proven from source; no timing, CPU or heap measurements were taken.
- I ran
pnpm test src/main/runtime/orchestration/mailbox/routing/slept-agent-wake.test.ts --maxWorkers=2: 1 test, passed. It is a correctness test only and does not cover perf. - Not run, as instructed:
pnpm tcand the full suite. Benchmarks were not run either. - Residual risk: the internal callers of
waitForTerminalwith conditionexit, no timeout and no signal on a slept handle were not enumerated.
Perf scan (pass 3): PR #44113
|
| # | Work (file) | Trigger / rate | Population | Work per event | Bound / invalidation |
|---|---|---|---|---|---|
| 1 | sleptLeafHandle / isAgentSleepStop (session-graph/slept-leaf-handles.ts:102) |
read paths below | one leaf | Live connected leaf: 3 Map gets, then short-circuits before the hook lookup (:113, :132). PTY-less or dead leaf: one getStatusSnapshotForPane (Map get plus rows for one pane) |
O(1) per leaf. No collection scans |
| 2 | restoreSleptLeafHandle mint (:124) |
first read of a slept pane after restart or renderer reload | slept panes only | ≤3 indexed SQLite gets (getLatestDispatchForTerminal('', paneKey): byHandle, byPaneKey, suffix via expression index) + addSynthetic/setHandle/bindLeaf (each notifies only on change) |
Runs once. After that current === parked or the first branch returns. Invalidated only by invalidateLeafHandle or first-PTY adoption |
| 3 | Terminal list isSleptAgentLeaf (runtime-terminal-list.ts:137) + summary sleptAgentHandle (write-orchestration-pointer-pty.ts:578) |
terminal list / show, about 4/s |
listed leaves (hundreds) | #1 per leaf. issueHandle still runs once per leaf because it moved up and was not duplicated |
Same O(leaves) as the summary it decorates. At 10× fleet: about 3000 leaves × Map gets ≪ 1 ms per call |
| 4 | issueLeafHandleRecord slept branch (terminal-handle-bindings.ts:285) |
epoch or PTY mismatch only (fast path precedes) | leaves changed since the last epoch | #1 | Once per leaf per epoch. Non-slept leaves fall through to the existing mint, which restores the fast path |
| 5 | Graph sync: retainLeafHandle (session-window-graph.ts:843) + pruneSleptLeafHandles (slept-leaf-handles.ts:22) |
each renderer graph sync | changed-PTY leaves; sleptLeafHandles entries |
#1 per changed leaf; one leaves.has per slept entry; onSleptLeafGraphSynced is O(pending wakes + carried waits), usually 0 |
O(slept panes) ≤ O(leaves), the same order as the existing replaceLeaves/rebuildLeafPtyIndex passes. Skipped while reloading |
| 6 | wakeSleptAgentHandle gate (slept-agent-wake-runtime.ts:198) via terminal.send, startRestoredHandlePane, prompt mutations, startLocalWorker |
every send or prompt | one handle | One Map get + #1. Not slept → null |
O(1). restoredPaneToStart is still guarded by ORCA_LAYOUT_OWNER_IS_MAIN (restored-handle-pane-start.ts:41), so it adds no work in other builds |
| 7 | Wake itself (wakeSleptPane, :322) |
a send to a slept agent | one per slept handle (deduped in sleptAgentWakes, deleted in finally) |
1 workspace command + 1 resumeSleepingAgents IPC + tui-idle wait |
Hard 120 s deadline. Callers' joinWithin releases on abort or timeout; the shared wake keeps running at most to its deadline |
| 8 | 500 ms setInterval backstop (:330) |
only while wakesInFlight > 0 |
one interval shared by all in-flight wakes | onSleptLeafGraphSynced: O(in-flight checks), each 2–3 Map gets |
Cleared in finally when the count hits 0. At most 240 ticks per wake (120 s). 0 ticks at idle |
| 9 | waitForSleptAgent (:243) / carrySleptAgentExitWait (:283) |
terminal wait on a slept handle; mobile live-stream exit waiter (terminal-multiplex-live-stream.ts:122); a slept PTY's exit |
one check or carried waiter per wait | O(1) per re-check | Released by the caller's signal (RPC and stream both pass one), by timeout, on wake (move to the new PTY) or on pane close (resolved as exited). Waiters that abort are pruned on the next event |
| 10 | assertAgentSleepAdmitted (:228) via pty:sleepAdmitted, pty:kill{keepHistory}, exact stop |
one per sleep attempt | confirmed hibernation candidates | 1 IPC + 1 indexed getActiveDispatchForIdentity per pane key + the existing hasDeliverableMail |
Gated in hibernatePaneIfStillEligible before any owner/liveness RPC, and in the renderer before capture (local path) |
| 11 | Busy backoff busyRetries (agent-hibernation-coordinator.ts:51) |
60 s hibernation tick | busy idle agents | 1 Map get per candidate; prune loop O(busyRetries) per tick | Retry delay doubles from 5 to 30 min. Entries are pruned to current candidates every tick and deleted on success |
| 12 | withSleptAgentWorkers (session-worker-liveness.ts:31) |
worker list / show, CLI cadence |
terminal workers the existing reader returns undefined for |
#1 per worker. byPane index built lazily once per projection (O(statuses)) and only if a worker is actually slept |
Same multiplicity as the existing liveness reader. No per-worker scan of statuses |
| 13 | inspectWorkerTerminal slept check (worker-observation.ts:44) |
single-worker show, stop, release, follow-up | one dispatch | +1–2 indexed gets (idx_worker_terminal_resources_owner UNIQUE, dispatch PK) |
Per single-worker RPC. No loop callers (all 8 call sites take one dispatchId) |
| 14 | SleptMailboxWake.ownerPane fallback (slept-mailbox-wake.ts:99) |
mail wake batch/selection | one mailbox | handlePane, O(1) Map gets, only after the existing DB lookup misses |
O(1) |
| 15 | holdsSleptPaneWake (slept-agent-wake-runtime.ts:218) |
sleeping-mail publication, per affected pane | in-flight wakes | linear over sleptAgentWakes |
Bounded by concurrent wakes, usually 0–few |
Subscription and publication census
crewChanges.subscribe(slept-agent-wake-runtime.ts:424): at most one listener per runtime (??=). It exists only whilewokenHandleChecksorcarriedExitWaitsis non-empty and is removed on the first event that finds both empty.- Idle (no wake, no wait on a slept handle): 0 listeners, 0 work.
- Idle with a held wait, e.g. a mobile stream open on a slept pane: 1 listener. It runs only when crew changes, which is about 0/s at idle.
- Under load: about 10–50 notifies/s × K pending checks × about 3 Map ops. At K = 10 that is ≤ 1.5k Map ops/s, ≪ 0.1 ms/s on main.
- A check settled by timeout or abort can leave the listener attached until the next notify or graph sync. That is one no-op call, and it heals itself.
- New publications: the PR adds no emit sites. Identity mutations (
parkSleptLeafHandleonce per sleep,restoreSleptLeafHandleonce per mint) go throughTerminalIdentitySource, which notifies only on an actual change (setHandlecompares fields;addSyntheticis gated byhas). That is one notify per slept pane per sleep or restart. No re-entry loop: the listener above never mints. - IPC
pty:sleepAdmitted: invoke/handle with no push stream. Its rate is set by Add card gap and quick-create in worktree dialog #10 and Capitalize app name to Orca for desktop installs #11.
Regression classes touched
| Class | Disposition |
|---|---|
| Fixed-cadence poll that never settles | Matched the 500 ms interval. Disproved: it exists only while wakes are in flight, each capped at 120 s, and is cleared in finally (#8). The busy retry backs off from 5 to 30 min, is pruned per tick and runs on the existing 60 s tick (#11) |
| Hidden or unheard owners keep working | Matched the crewChanges listener. Disproved: it is attached only while a wait or wake is pending; census above |
| Per-entity state outlives the entity | sleptLeafHandles (pruned on graph sync, invalidateLeafHandle, first-PTY adopt), carriedExitWaits, wokenHandleChecks, sleptAgentWakes (finally), busyRetries (per-tick prune). Disproved: each has a delete in the owning teardown |
| Sync fs/SQLite on Electron main | #2, #10, #13: indexed point gets, per sleep attempt, per single-worker RPC or once per slept-pane mint. Disproved: none are reached per keystroke, chunk, poll or list row |
| Per-row derivation over the whole collection | withSleptAgentWorkers byPane. Disproved: built once per projection and only when a slept worker exists |
| Hot-path rescans | holdsSleptPaneWake and the pruneSleptLeafHandles loop. Disproved: bounded by in-flight wakes and slept panes, not nested in per-leaf loops |
| Unbounded fan-out | Wakes deduped per handle; there is one interval. Disproved |
| Update published when nothing changed | No new emit sites; identity setters compare before notifying. No matching code |
| Eager startup imports | Only node:crypto randomUUID (core). No matching code |
Six questions
- Unused work before the gate. Reviewed. The local hibernation path asks
sleepAdmittedbeforecollectSleepingAgentSessionRecordsForWorktreeand capture. The remote exact-stop path (expectedRuntimePtyIds.length > 0) still captures, withincludeLocalBuffers: false(layout only, no scrollback serialization), plus 2 store writes before main refuses. Per busy remote pane that is at most 1 attempt per 5–30 min. At 10× fleet with 100 busy remote panes at the 30 min cap: about 0.06 attempts/s × (one layout capture + 2 writes). Bounded by the backoff and below every threshold, so it is not a finding. - Ownership multiplication. Reviewed. One wake per handle, one interval, one listener per runtime. Nothing is created per mounted row or pane in the renderer.
- Thread and storage. Reviewed. All new work runs on Electron main (runtime) or the renderer store (Capitalize app name to Orca for desktop installs #11). SQLite use is limited to the indexed point gets in Fix Ctrl+Backspace not deleting word in terminal #2, Add card gap and quick-create in worktree dialog #10 and Add Orca logo and polish README header #13.
- Growth and progress. Reviewed. Every per-event cost is O(1) or O(in-flight wakes). Per-list cost is O(listed leaves), the same order as the existing output. The mint does not repeat (Fix Ctrl+Backspace not deleting word in terminal #2). Retries back off (Capitalize app name to Orca for desktop installs #11).
- Execution host. Reviewed. No per-item SSH round trips. The wake is one
resumeSleepingAgentsIPC to the owning window.sleepAdmittedis local only; remote panes rely on main's exact-stop assert. Windows and Linux were not exercised (no platform-specific code in the span). - Obsolete work stops. Reviewed. Waits release on the caller's
signal(theterminal.waitRPC and the mobile stream both pass one) or on timeout. A shared wake outlives an aborted caller by at most its 120 s deadline. Pane close resolves carried waits and settles checks withterminal_handle_stale.
Evidence and limits
- Source-proven counts above.
slept-agent-wake.test.tspasses (2/2). No runtime timing, CPU or heap measurement was taken; per instructions, notcand no full suite. - Residual, not inspected to closure: when
restoreSleptLeafHandlemints over a differentcurrenthandle (slept-leaf-handles.ts:152-164), the old handle record is rebound away from the leaf, but I did not trace whether itshandlesentry is removed. That is at most one record per slept pane per restart, so it does not grow with fleet or time.
a9ee31f to
37525fb
Compare
69daa5e to
11e40d0
Compare
14623d1 to
60533eb
Compare
59618d5 to
d44e79b
Compare
60533eb to
e7cc0c8
Compare
d44e79b to
eaa8b77
Compare
…ator restarts or its cached positions overflow
…uns from mail awaiting delivery, a pane's retry, a PTY exit, a targeted wake, a handle-scoped list and an unmounted act read only their own target, the final check keeps its owner, and session writes that change no sleeper list no hosts
Third batch: the last rescan's eight findings and the audit's must-fix (for the next perf rescan)The last rescan audited all 31 per-event paths in this PR. This batch fixes every P1 it named, plus the blinded audit's must-fix. Only these paths changed since Must-fix (audit, The eight P1s:
Contracts at N and 10N (each fails with this batch's source reverted):
Fixes 3, 5, 6 and 7 are keyed lookups that the scan's own harness already measures. |
|
Performance scan: blocked at New in this deltaP1 — each pane's mail query scans unrelated queued Run mail. mailboxes-with-mail-sql.ts:13, run-lookup.ts:37 and sleeping-mail-owner-mailboxes.ts:60 replace pane-owned history with the entire This reaches main-thread sleep admission, retained-attempt/arrival reconciliation, and both callers of P1 — removing empty host partitions leaks cached session inputs. sleeping-mail-record-index.ts:153 returns before Prior P1s
The position-cache correctness fix also passes: after teardown or capacity eviction the requested entry is found again at N=100/1,000; rebuilding visits N entries once, warm lookups read one key and absent entries remain absent. No production source was altered for these measurements. Scope, subscriptions and boundsInspected the 20-file delta from
Six questions: 1, before-skip work is fixed except global mail selection; 2, owner/listener multiplication checked at N/10N, targeted binding work is one; 3, synchronous main SQL amplification is reproduced, renderer final checks stay scoped; 4, repeated global-mail scans make no target progress, necessary snapshot/output scans retain stated bounds; 5, Linux execution and source inspection of host-qualified routing, with native/live-transport limits below; 6, wait/reply/host-reader teardown and bounded queues pass, session-input retirement fails. Touched regression classes: hot rescans/history rereads/synchronous SQL/newly reached work → new global-mail finding; per-entity retention → new removed-input finding; broad subscriptions/per-instance collection work → keyed N/10N controls pass; no-op publication/version/whole snapshots → equality, delta and zero-listener controls pass; idle/hidden work → no added cadence; cache invalidation → final checks and clear/eviction recovery pass. Other previously cleared classes were not reopened. Benchmark: head=8b158734cf68241878246ef605134392cbd845ac gate=FAIL mounted=OrcaRuntimeService+OrchestrationDb+registered-mailbox-pane+retained-wake-publication+SleptMailboxWake+slept-handle/exit-waits+real-hibernation-coordinator/planner/host-evidence/input-driver-age-sources+split-bindings/PaneIdentityRegistry+unmounted-terminal-acts+real-session-host-partition-getters+card-subscriptions+native-reply-router N=100,1000 admission-queries=2,2 admission-empty-rows/probes=1/0,1/0 admission-historical-rows/probes=2/1,2/1 wake-owner-empty-rows/probes=0/0,0/0 wake-owner-historical-rows/probes=1/1,1/1 unrelated-mail-candidates/probes-per-check=100/100,1000/1000 repeated-checks=10 single-foreign-mailbox-candidates/probes=100/1,1000/1 pane-retry-tracked-visits=0,0 pane-refreshes=2,2 archive-candidates=129,129 archive-extra-leaf-visits=0,0 targeted-binding-visits=1,1 handle-list-global-visits/keyed-gets/output=0/2/1,0/2/1 graph-title-invalidated-read-leaf-visits=0,0 final-ambiguous-owner-visits-after-publication=0,0 unchanged-empty-session-host-visits=0,0 removed-empty-host-cache-inputs=101,1001 Execution: final Linux batch 143/143 cases in 25/25 files, including all 51 contracts in the PR's 12 added performance files. The first batch identified the retention regression and two harness adaptation errors; both adaptations were corrected before the complete final batch. Passing assertions record observed costs; they do not turn the two measured regressions into a passing performance gate. Only committed temporary performance harness files differ from the requested head. The earlier schema/index startup measurements stand; this delta adds no schema/index DDL. Limits: deterministic service/coordinator and subscription seams, controlled launch/route boundaries; no real-agent exactly-once journey, rendered/packaged frame/CPU/heap capture, native macOS/Windows/WSL, or live SSH/mobile/relay run. The ambiguous route is supplied at the ownership boundary while the real coordinator/planner/host-evidence code runs. The title-invalidation workload executes reads; other acts share its inspected keyed helper and have a separate direct-act census. The gated main-layout fallback remains unexecuted and is not claimed clean. No tests, builds or benchmarks ran on the reviewing Mac. |
…ning whichever binding names it, and a removed host with no sleepers keeps no cached input
…ot every queued Run message; a pane-keyed mail index is the follow-up
Fourth batch: the last rescan's two findings and the audit's must-fix (for the next perf rescan)Changed since
|
|
Performance scan: PASS, no new performance blockers at Prior P1s
Known, acceptedThe pane's own retained-Run probe remains R Run rows examined and R indexed mailbox seeks per check, as accepted for this PR; follow-up STA-17741 owns the pane-keyed mail index. Uninstrumented Linux medians, seven batches of 200 calls after warmup, including statement preparation and result decoding: R=100/1,000/10,000 → 0.036/0.171/1.461 ms for pointer-work lookup; sleeping-owner lookup including its three owner-kind statements is 0.047/0.110/0.710 ms. These measurements do not establish a materially different cost from the accepted measurements. Full admission with historical mail, including the refusal/error path, measured 0.336/0.414/1.555 ms; that is a broader operation than the SQL probe. At R=100/1,000, real sleep admission executes two Run queries and returns one row when empty, two when historical mail exists; the probe count is 100/1,000 in both cases. Real retained-attempt publication executes one Run query with 100/1,000 probes, returning zero rows empty and one historical owner with mail. Historical mail correctly refuses sleep and remains discoverable. Source tracing covers both New in this deltaNo new P1 found. The archive fix at line 117 checks indexed candidate panes instead of projecting all graph leaves. With L=100/1,000 unrelated panes, five slept panes, 128 ordinary archives and ten real PTY exits, each exit performs 134/134 archive checks, 4/4 matching leaf-index candidate visits, 6/6 keyed leaf gets and 0/0 global leaf visits. All five stopped archives survive: pane-issued, restored, reverse-bound, restored after a tab move, and incarnation-only. Closing their panes makes the archives eligible for removal again; ordinary archive retention remains 128. The existing PTY-inventory traversal/sort is unchanged. Cost is per exit and inventory refresh, not per PTY chunk; at E exits/s the changed lookup performs 4E matching-candidate visits + 6E keyed leaf gets, independent of unrelated L. No new cache or archive lifetime is created beyond the live pane's required stopped-process identity. Coverage and limitsAll detected surfaces are accounted for: hot-path,publish,startup-migration,subscribe,version-bump. The delta and callers cover hot SQL, session invalidation, wake publication and exit/inventory cleanup; untouched startup/migration and version/publication producers retain prior clearance. There is no new schema/index DDL. All 53 cases in the PR's 12 added performance-contract files passed; the two remote batches passed 70/70 and 6/6 cases, including the focused workloads above. Only temporary committed harness files differed from the pinned production head; the checkout is restored clean and detached at that head. Six questions: 1 skip gates precede empty-host inventories; 2 SQL remains per addressed pane and archive lookups per candidate, without new owners; 3 synchronous main SQL is measured above, with indexed plans; 4 unrelated-mail growth is eliminated, own-history cost is accepted, and unchanged/full-recovery scopes remain distinct; 5 executed on Linux, inspected host-qualified partition and pane routing, with no added host probes; 6 removed-host inputs return to zero and slept archives become removable when panes close. No new timers, subscriptions, subprocesses, whole-file writes or eager heavy imports; added autonomous idle wakeups/s versus the preceding head are main 0, renderer 0, daemon 0, source-proven rather than a new live idle capture. Touched regression classes: per-entity retention → zero-input teardown passes; unused work before skip / repeated host inventory → zero named-write inventories; history rereads / synchronous SQL / hot rescans → foreign-mail amplification fixed, own-Run cost accepted; per-event collection projection / cleanup → zero global leaf visits, bounded matching lookups and close cleanup pass. Other classes and previously cleared paths were not reopened. Deterministic counts use real runtime/DB/identity seams with SQL counters and controlled process boundaries; timings use uninstrumented in-memory DB calls, not packaged UI latency. No live agent, native macOS/Windows/WSL, SSH transport, frame/CPU or heap-byte measurements are claimed. No tests, builds or benchmarks ran on the reviewing Mac. Benchmark: head=73a8975fe9ec1a66a8916f3fa8d65d8ad346632b gate=PASS mounted=OrcaRuntimeService+OrchestrationDb+real-session-write-listener/partition-getters+registered-mailbox-pane/sleep-admission+retained-wake-publication+terminal-identity-bindings/real-PTY-exit N=100,1000 removed-host-inputs=0,0 host-listings-per-named-write=0,0 unrelated-mail-probes=0,0 own-Run-probes=100,1000 pointer-ms=0.036,0.171 archive-checks-per-exit=134,134 archive-global-leaf-visits=0,0 archive-matching-candidates=4,4 archive-keyed-leaf-gets=6,6 survived=all-five-binding-forms closed-pane-archives=removed contracts=53/53 |
Review status: ready on
|
…sleep-b # Conflicts: # src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-runtime.ts # src/main/runtime/rpc/methods/orchestration/worker/start/readiness/placed-worker-readiness.ts
|
Performance scan: PASS — no new P1 at Scope: Known, acceptedThe pane's retained-Run mail probe remains accepted, tracked in STA-17741: R own Run rows and R indexed mailbox seeks/check; R=100/1,000 means 100/1,000 probes. At E checks/s that is 100E/1,000E probes/s, triggered by delivery/debt checks, sleep admission and mail/wake reconciliation. This delta adds no trigger or wider query. Prior measurements stand; they were not remeasured here. New in this delta
Coverage and evidenceDetected surfaces: hot-path,publish,startup-migration,subscribe,version-bump. Hot-path and startup command changes were traced above. Untouched publication, subscription, version and migration paths retain prior clearance. No new autonomous idle wakeups: added main/renderer/daemon wakeups/s = 0/0/0, source inspection, not a live idle capture. Six questions:
Touched regression classes: hot-path rescans → bounded to one launch's options; expensive work past a gate / ownership multiplication → no new reachability or owner; per-entity retention → fixed-size launch configuration, existing wake teardown unchanged. Other classes have no new matching code in the scoped delta. The requested exact-head command ran once on Linux: 12/12 files, 53/53 contracts passed. It instantiated the real runtime and in-memory orchestration database with controlled stores/notifiers, sleep/host indexes, pending waits, tab/pane wake registries, reply routing with a fake window, and a mocked hibernation environment. Populations include 100/1,000 owners and 1,000/10,000 stranded mailboxes. Checks cover targeted delivery, no-op publications, unrelated updates, host teardown, cancellation and wake-owner release. This is operation-count evidence, not a rendered application or live agent benchmark; no frame/CPU/heap timing claim. No tests, typechecks, builds or benchmarks ran on the reviewing Mac; the shared checkout remains unchanged. Benchmark: head=d18d86849ffa16cafc51f5e2958ac0da0340590e gate=PASS mounted=OrcaRuntimeService+OrchestrationDb(in-memory)+controlled-session-stores/notifiers+sleep/host-indexes+pending-waits+tab/pane-wake-registries+fake-window-reply-router+mocked-hibernation-environment host=Linux N=100,1000 stranded-mailboxes=1000,10000 contracts=53/53 files=12/12 |
…eported, falling back to its launch model
…aude restores the conversation's own model, which a saved flag would override
…so a woken Codex can't take Orca's first Enter as 'Update now'
…ter main's growth
|
Performance scan: PASS — no new P1 in Scope: the four delta paths and every caller of their changed functions. Paths outside the delta retain the previous scan's clearance. Known, acceptedThe retained-Run mail probe remains accepted, tracked in STA-17741: R own Run rows and R indexed mailbox seeks/check; R=100/1,000 costs 100/1,000 probes. At E checks/s, that is 100E/1,000E probes/s on delivery/debt checks, sleep admission and mail/wake reconciliation. This delta adds no trigger or wider query; prior measurements stand. New in this delta
Coverage and evidenceDetected surfaces: hot-path,publish,startup-migration,subscribe,version-bump. Hot-path/startup changes and their callers were inspected at the target head; unchanged publication/subscription/version/migration paths retain prior clearance. Six questions:
Touched regression classes: hot-path rescans → bounded to one launch's inputs; per-entity retention → no accumulated suppression in saved configuration; eager imports → fixed constants/type-only dependency; expensive work past a gate / ownership multiplication → no added reachability or owner. Other classes have no new matching code in this delta. The requested exact-head command ran once on Linux: 12/12 files, 53/53 contracts passed. It instantiated the real runtime and in-memory orchestration database with controlled stores/notifiers, sleep/host indexes, pending waits, tab/pane wake registries, a fake IPC window, and a mocked hibernation environment. Populations include 100/1,000 owners and 1,000/10,000 stranded mailboxes. This is operation-count evidence for wake plumbing; suppression itself was assessed from source, without launching live agents. No rendered app, frame/CPU/heap or native-platform timing claim. No tests, typechecks, builds or benchmarks ran on the reviewing Mac; the shared checkout and HEAD remain unchanged. Benchmark: head=53e7eda0b8128717af83dfad45723ead647f2355 gate=PASS mounted=runtime+in-memory-db+controlled-stores/notifiers+sleep/host-indexes+pending-waits+tab/pane-wake-registries+fake-window-reply-router+mocked-hibernation-environment host=Linux N=100,1000 stranded-mailboxes=1000,10000 contracts=53/53 files=12/12 |
|
Performance scan: PASS — no new performance regression in the scoped delta from All 13 production files listed by the prior scan are byte-identical. Their clearance and paths outside this delta stand. Checked the window lifecycle changes against merged main Known, accepted The retained-Run mail probe remains accepted, tracked in STA-17741: R own Run rows and R indexed mailbox seeks per check. At R=100/1,000 and E checks/s, that remains 100E/1,000E probes/s. No added trigger or query widening in this delta. New in this delta
Six-question coverage
Touched regression classes: ownership multiplication/per-instance work, unchanged publication, hot-path rescans and retained listeners were matched and disproved by the census and counts above; expensive work past a gate, sync main I/O and new idle wakeups have no added matching code. Detected PR surfaces: hot-path,publish,startup-migration,subscribe,version-bump; unchanged surfaces retain prior clearance. The requested command ran once at the exact head: 12/12 files, 53/53 contracts passed. It covers real runtime/in-memory orchestration DB routes with controlled stores/notifiers, pending waits, sleep/host indexes, tab/pane wake registries, fake renderer replies and a mocked hibernation environment. No tests/typechecks/builds ran on the reviewing Mac; checkout and HEAD stayed unchanged. Evidence is source bounds and Linux operation-count contracts; live Electron CPU/heap/frame timings and native-platform performance were not measured. Benchmark: head=4c05e4f0a74780ea9e5bb386a26f0c88a1c20b05 gate=PASS mounted=runtime+in-memory-db+controlled-stores/notifiers+sleep/host-indexes+pending-waits+tab/pane-wake-registries+fake-window-reply-router+mocked-hibernation-environment host=Linux N=100,1000 stranded-mailboxes=1000,10000 contracts=53/53 files=12/12 |
Review status: ready on
|
Conflict: src/shared/agent-launch/startup/tui-agent-launch-command.ts. main moved the startup update-prompt suppression tables into agent-startup-update-prompt.ts (stablyai#44113), so DimAgent's DIMCODE_UPDATE_CHECK=0 entry moves there with them. Co-Authored-By: Claude Opus 5.5 <[email protected]>




ELI5
When Agent Sleep stops an idle agent in a background tab to save resources, the rest of Orca used to treat that agent as gone. Messages to it opened a brand-new tab, or failed. Now a sleeping agent looks like an idle one: it keeps its name, it can be listed and read, and sending it a message wakes it up in its own tab, in the same conversation, and delivers the message once.
What Changed
Before (for a user running agents with Experimental > Agent Sleep on):
terminal list.terminal readandterminal waitsaid it had exited.terminal sendfailed.orchestration sendwaited until someone opened its tab.After:
terminal readreturns its last output without waking it.wait --for tui-idleis satisfied at once.wait --for exitstays pending until a woken process exits; closing the slept pane ends such waits as exited.terminal send,orchestration send,worker-start --terminal <handle>and mail waiting in its mailbox wake it in its own tab: same handle, same conversation (--resume), one process.orchestration sendand mail to its mailbox (including worker mail to a sleeping coordinator),terminal send, andworker-start --terminal <its handle>wake it in its own tab, same handle and conversation.worker-start --terminalkeeps it Orca's (it still closes when done). An implicit follow-up anddispatch --injectbehave as on main; waking those in place is a separate change.Mechanism:
--resumewhen woken, instead of reattaching to the session that no longer exists. That reattach is what left round 4's first-tick sleepers stuck with no process.Why
Orchestration's model is that an agent is either running or gone. Agent Sleep added a third state that nothing understood, so every orchestration path broke for slept agents and users saw duplicate tabs, lost messages and duplicate agents.
The alternative of exempting orchestrated agents from Agent Sleep was rejected, because it reverses the product decision that sleeping agents stay addressable and wake on demand. Making a slept agent answer as an idle one keeps a single model for every caller, and the wake reuses the same resume path a click on the tab already uses.
Linked Issue
N/A: maintainer change (Experimental > Agent Sleep x orchestration, tracked internally as item 69). Builds on #41746 (its mail-wake part is folded in here).
Visual Proof
N/A: no new visuals. The only on-screen change reuses the workspace card's existing unread dot, which now also lights while mail waits for a sleeping agent; it looks exactly as it does today. Everything else is in how orchestration commands see and wake a sleeping agent, recorded below as each command's output.
Testing
Platforms tested:
connected,writable, not orphaned), a pending exit wait stays pending, andterminal sendandworker-start --terminalwake them in place without the user opening their workspace.worker-start --terminalwakes it in place.--resumeprocess and delivered its message once.wait --for exiton a sleeping agent stays pending through two window reloads. Every sleeping agent keeps its original handle, including one that woke and slept again between the reloads. A send to the original handle wakes it in place.--resumeprocess and delivered its message exactly once.worker-startgave one resume.terminal sendand mail woke slept workers and a coordinator in place.worker-start --terminalto an awake, just-idle agent lost theworker-start's task in 2 of 5 runs, the same signature as the known limit below.Automated:
pty-connection-slept-pane-message-wake.test.tschecks that a message wake of a hidden pane remounted over its stopped session starts a fresh resume and never reattaches the dead session. I confirmed on Omarchy that it fails with the fix reverted.slept-mailbox-wake.test.ts), and perf contracts (slept-mailbox-wake.performance.test.ts) check that a change naming only Dispatches no sleeper owns does no per-sleeper lookups at 100 and 1,000 sleepers, and that availability re-checks and unnamed changes read no owner of 1,000 or 10,000 stranded mailboxes.slept-mailbox-wake.test.tsalso checks that Orca listens for orchestration changes only while an agent sleeps.slept-agent-wake.test.tschecks that a slept pane's lookup returns its own handle and that its handle keeps naming the stopped process (soworker-readkeeps working). A perf contract checks that mail reads with nobody asleep do no sleeping-mail lookups, andslept-mailbox-wake.test.tsshows mail waiting at restart waking the sleeper through the restored-mail redelivery. Each of these fails with its fix reverted (checked on Omarchy).slept-agent-wait-fanout.performance.test.tsdrives 100 and 1,000 pending waits through three kinds of unrelated activity: terminal changes, title-only window updates, and other panes opening or closing. It asserts zero checks, and that nothing is still listening once the waits are cancelled.agent-hibernation-recheck.performance.test.tschecks that the last check before a pane sleeps reads only that pane's status, ages and tab, at 100 and 1,000 panes.slept-agent-wake.test.tskeeps a sleeping pane's handle and pending exit wait across two window reloads. It fails without the fix.slept-agent-wake.test.tschecks that an agent stays listed, shown and wakeable under its handle after a reload with another workspace showing, and when it fell asleep while its tab was unmounted (one resume, same handle). Both fail with the fix reverted.sleeping-record-access.performance.test.ts(cleanup after a resume reads one conversation's records, at 100 and 1,000 agents),sleeping-mail-crew-watch.performance.test.ts(no host kept after 100 and 1,000 connect/disconnect cycles, one retry per real connect), and the last-check contract now uses the real foreground history. Each fails with its fix reverted.pnpm check:changedwith related tests passes on Omarchy for this head.Performance
Bounded. Terminal acts on a slept handle add one record lookup. Marking mail read adds one indexed read per batch. Sleeping-mail checks follow the mailboxes and panes a change names, plus mail already owed to sleepers; they never scan old mail or a coordinator's Run history (apart from the few panes holding a wake attempt). With no agent asleep, reads, sends and orchestration changes do no sleeping-mail work.
Repeated triggers stay bounded:
Idle panes, typing and terminal output are untouched. Perf contracts drive each trigger at two sizes, and a perf scan of the final head is posted on the PR.
Risk
The riskiest part is the wake path for mounted panes. If it went wrong, a message to a slept agent could time out without waking it (the old failure). Revealing the tab still wakes it, as before.
Boundaries:
mail_wake_attemptstable (from fix(orchestration): wake slept coordinators for waiting mail #41746); older builds ignore it.Backing it out: a plain revert. Saved handles and attempt rows are then ignored.
Level: Medium
Known limits
worker-showreadsunverifiablefor a slept worker, as on main.wait --for exitwith no timeout on a slept agent stays pending until the agent is woken and its process exits.worker-start --terminalto the same agent within a second can lose theworker-start's task (outcome_unknown, nothing typed reaches the agent). Main does the same with an awake agent (2 of 5 runs on Linux), so this is not new here.AI Disclosure
Review
Reviewed by fresh Claude and Codex reviewers, a blinded regression audit with a second confirming reviewer, and a separate perf scan; the status comment on the PR has the verdicts and follow-ups.
Agent skill upstream boundary
Notes
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)