Skip to content

Slept agents look idle and wake in place when messaged - #44113

Merged
brennanb2025 merged 71 commits into
mainfrom
brennanb2025/agent-sleep-orchestration
Nov 25, 2026
Merged

brennanb2025 merged 71 commits into
mainfrom
brennanb2025/agent-sleep-orchestration

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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.

Files Added Deleted Net
Test 24 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3487 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3487
Prod 130 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4755 $\color{#cf222e}{\Huge{\mathbf{−}}}$​379 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4376

What Changed

Before (for a user running agents with Experimental > Agent Sleep on):

  • A slept agent disappeared from terminal list.
  • terminal read and terminal wait said it had exited.
  • terminal send failed.
  • Mail sent to it through orchestration send waited until someone opened its tab.
  • After a restart, revealing the old tab could leave two copies of the agent running on one conversation.

After:

  • Status. A slept agent is listed as live and idle, under the handle it had before sleeping. terminal read returns its last output without waking it.
  • Waits. wait --for tui-idle is satisfied at once. wait --for exit stays pending until a woken process exits; closing the slept pane ends such waits as exited.
  • Wake in place. 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.
    • Requests that arrive while it wakes all wait for that one wake.
    • The message is delivered once, after the agent is ready.
    • It goes back to sleep after its turn, and the next message wakes it again.
  • Which paths wake in place: orchestration send and mail to its mailbox (including worker mail to a sleeping coordinator), terminal send, and worker-start --terminal <its handle> wake it in its own tab, same handle and conversation.
  • Workers Orca created. A slept one can still be released and closed, and starting a new task on it with worker-start --terminal keeps it Orca's (it still closes when done). An implicit follow-up and dispatch --inject behave as on main; waking those in place is a separate change.
  • Handle continuity. It keeps its handle across moves, renderer reloads and restarts, and Copy Terminal ID copies that same handle. This holds whichever workspace is showing: an agent whose workspace isn't open (after a reload, or because it fell asleep while another workspace was showing) is still listed, shown and woken under its handle without the user opening it.
  • Sleep admission. Agent Sleep does not take an agent that still has undelivered orchestration mail or a dispatch that is still being handed to it.
  • Sidebar. A workspace's existing unread dot also lights while mail waits for an agent asleep there, and clears once the mail is taken.
  • The user's own Workspace Sleep is unchanged: those panes stay asleep until opened, and orchestration still sees them as disconnected.

Mechanism:

  • Main. Main treats an Agent-slept pane as an idle agent. A terminal act on its handle starts one wake per pane through the window, joins a mail wake already in flight, and settles once the same handle names a live, idle process.
    • The pane's handle stays on the stopped process (its last output and exit still answer for the idle agent), is saved on its sleep record, and moves to the resumed process when it starts.
    • Main checks sleep admission before the window captures the pane, and again at the stop.
    • When the window hasn't mounted the agent's tab, main finds it by the handle its sleep record saved, through one keyed lookup that list, show, send, waits and wake share. The wake asks the window to resume it (the window mounts that tab in the background), the resume exports the same handle, and the resumed process takes the handle over.
  • Window. A pane that was remounted while hidden over its stopped session now starts a fresh --resume when 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.
    • A targeted wake of a mounted pane resumes it from its sleep record even when nothing armed a wake at exit.
  • Mail wake. This PR includes the part of fix(orchestration): wake slept coordinators for waiting mail #41746 it builds on: main resumes a slept agent when mail waits for it, keeps the attempt in the orchestration database, and re-checks when mail is read.
    • A Run's coordinator whose pane moved to another tab is found by its pane's stable id.
    • Mail to a Run or Dispatch wakes a sleeper when it arrives; after a restart, main's existing restored-mail redelivery does the same. Re-checks never walk the history of Runs a coordinator created, except for the few panes holding a wake attempt.
    • A change that names its mailboxes, Dispatches or parties re-checks only those; one that names nothing re-checks only mail already owed to sleepers.
    • A pane re-check also covers the mailbox of the handle its sleep record saved, so a message sent while the agent was going to sleep still wakes it.
    • Failed wakes retry when a host becomes connected (not on every repeated status broadcast). With nobody asleep, Orca does no sleeping-mail work on reads, sends or orchestration changes.
    • Finding a sleeping pane's mail checks every Run and Dispatch it owns inside one database query per kind of owner.
    • When main refuses to sleep an agent because mail is waiting, the window asks again after a doubling delay (up to 16 minutes).
  • Shared fixes this needed:
    • The shell-integration scanner that spots a finished command now stops at any escape that cancels a sequence, as terminals do, so a cancelled marker can't swallow the output after it.
    • A fresh start whose pane types its own startup command no longer also hands that command to the shell, so the resume line is written once.

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

  • I manually tested these changes (isolated test copies on QA machines, real Claude)
  • Automated tests added/updated
  • Every added test fails without this change and avoids the test anti-patterns

Platforms tested:

  • macOS (zsh), M4Air, real Claude, on fcac14a and 22ca84d:
    • Reload with another workspace showing: after two hidden-window reloads, sleeping agents in the other workspace stay listed under their original handles (connected, writable, not orphaned), a pending exit wait stays pending, and terminal send and worker-start --terminal wake them in place without the user opening their workspace.
    • Sleep while unmounted: an agent that fell asleep while another workspace was showing keeps its handle and worker-start --terminal wakes it in place.
    • Re-runs: a mounted hidden wake, a targeted send, a burst (all three messages delivered once), a tab reveal and a workspace Sleep then reopen all passed. Every wake had one --resume process and delivered its message once.
  • macOS (zsh), M4Air, real Claude, on 8355c5d:
    • Window reloads: a pending wait --for exit on 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.
    • Tab close: closing a sleeping agent's tab ends its exit wait as exited within seconds.
  • macOS (zsh), M4Air, real Claude, earlier rounds on 99a3cc5, 28d8654 and 79678e1: the same results each round.
    • Wakes: panes that slept in the first sleep pass after launch woke in place. So did second and third wakes, a plain tab, and a wake after a graceful restart. Each had one --resume process and delivered its message exactly once.
    • Resume line: written once and well formed.
    • Bursts: two sends plus a worker-start gave one resume.
    • Sidebar dot: it lights for mail waiting on a Run coordinator in a workspace the user put to sleep, and clears per workspace when the agent's tab opens.
  • Linux (bash), Omarchy, real Claude, traced build: message wakes in place, about 9 s each, resume command written once.
  • Windows high spec, real Claude, on b3bfe12: terminal send and mail woke slept workers and a coordinator in place.
  • Main baseline (Linux): two sends plus a worker-start --terminal to an awake, just-idle agent lost the worker-start's task in 2 of 5 runs, the same signature as the known limit below.

Automated:

  • New test: pty-connection-slept-pane-message-wake.test.ts checks 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.
  • New tests: a Run coordinator that slept after its pane moved is woken by its mail (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.ts also checks that Orca listens for orchestration changes only while an agent sleeps. slept-agent-wake.test.ts checks that a slept pane's lookup returns its own handle and that its handle keeps naming the stopped process (so worker-read keeps working). A perf contract checks that mail reads with nobody asleep do no sleeping-mail lookups, and slept-mailbox-wake.test.ts shows mail waiting at restart waking the sleeper through the restored-mail redelivery. Each of these fails with its fix reverted (checked on Omarchy).
  • New perf contracts:
    • slept-agent-wait-fanout.performance.test.ts drives 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.
    • The same file checks that held-mail changes send only the workspaces that changed, once per tick.
    • agent-hibernation-recheck.performance.test.ts checks that the last check before a pane sleeps reads only that pane's status, ages and tab, at 100 and 1,000 panes.
    • Each assertion fails when its fix is reverted (checked on Omarchy).
  • Reload test: slept-agent-wake.test.ts keeps a sleeping pane's handle and pending exit wait across two window reloads. It fails without the fix.
  • Unmounted tests: slept-agent-wake.test.ts checks 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.
  • More perf contracts: 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.
  • Unit tests cover the slept handle staying on its stopped process and its restore, worker custody across a resume, slept-agent waits, the wake join, sleep admission, and the mail-wake custody.
  • Full checks: pnpm check:changed with 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:

  • Waits on a sleeping agent are re-checked only for the terminals a change touches or the pane that closed, so unrelated terminals, title changes and other panes closing cost nothing.
  • The sidebar's "mail waiting for a sleeping agent" set is sent whole when a window loads, then only as the workspaces that changed, at most once per tick, and only those workspace cards update.
  • The last check before an idle pane sleeps reads only that pane's status, ages, tab and foreground time.
  • Cleanup after a resume reads only that conversation's saved records, not the workspace's.
  • A slept agent whose tab isn't mounted is found by one keyed lookup per terminal act; a terminal list makes one pass over sleep records.
  • Host reconnects keep only hosts that are connected now.
  • A refused sleep backs off instead of retrying every minute.

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:

  • Saved data: sleep records gain an optional handle field; older builds ignore it.
  • Orchestration database: gains a mail_wake_attempts table (from fix(orchestration): wake slept coordinators for waiting mail #41746); older builds ignore it.
  • Remote runtimes: paired runtimes keep their handle only within a session. A paired server doesn't wake its own slept agents for mail yet (it didn't deliver to them before either).
  • Platforms: no platform-specific code.

Backing it out: a plain revert. Saved handles and attempt rows are then ignored.

Level: Medium

Known limits

  • The wake needs a window to resume the pane; a headless runtime keeps the old behaviour.
  • Panes owned by a remote runtime don't save their handle on the sleep record. They keep it within a session.
  • An agent that sleeps before its first turn comes back under a new handle after a restart.
  • worker-show reads unverifiable for a slept worker, as on main.
  • Mail sent to a Run or Dispatch in the moment an agent is going to sleep may wait for the next message or a tab open if main learns of the sleep more than two seconds later (main behaved the same before).
  • wait --for exit with no timeout on a slept agent stays pending until the agent is woken and its process exits.
  • Opening a workspace the user put to sleep doesn't resume its agents; opening the agent's tab does, and the send warning says so (unchanged Workspace Sleep behaviour).
  • Sending two messages and a worker-start --terminal to the same agent within a second can lose the worker-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

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

Notes

  • Security: no new inputs; the wake resumes the pane's own saved conversation.
  • Cross-platform: tested on Linux (bash) and macOS (zsh); Windows waits for the agent's own ready report instead of a foreground-process check.
  • Remote SSH: desktop-owned SSH panes wake through the same window path.
  • Mobile: unchanged.
  • Backwards compatibility: new saved fields and the new table are optional and ignored by older builds.
  • Performance: see above.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@brennanb2025
brennanb2025 force-pushed the brennanb2025/agent-sleep-orchestration branch 3 times, most recently from 4875bf3 to 5767163 Compare November 18, 2026 19:12
@brennanb2025
brennanb2025 marked this pull request as ready for review November 18, 2026 20:18
@brennanb2025

Copy link
Copy Markdown
Contributor Author

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.

@brennanb2025
brennanb2025 force-pushed the brennanb2025/omh-slept-coordinator-wake branch from b2a241c to 69daa5e Compare November 18, 2026 22:08
@brennanb2025
brennanb2025 force-pushed the brennanb2025/agent-sleep-orchestration branch from 5767163 to 86442e4 Compare November 18, 2026 22:08
@brennanb2025

Copy link
Copy Markdown
Contributor Author

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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: PR #44113, HEAD~1..HEAD (86442e4)

Verdict: FAIL. There are 4 P1 findings and no P0. All evidence comes from reading the source: counts, triggers and bounds traced at the target ref. I ran no runtime benchmarks, so this report makes no timing claims beyond the prices worked out below.

Reference fleet used for pricing: 100+ agents (assume 20–30 idle agents holding mail or a pending Dispatch at any time), a few hundred hook status rows (S≈300), a dozen agents calling the CLI every few seconds (≈4 worker list/s), and 10× that for growth.

Findings

P1-1. A refused Agent Sleep redoes all of its pre-gate work every hibernation tick, with no backoff.

  • Where: src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.ts:161-164 (new orchestration_busy → "a later tick retries"). The gate is src/main/runtime/orchestration/mailbox/routing/slept-agent-wake-runtime.ts:86, reached from renderer-kill.ts:61 and worktree-terminal-stop-targets.ts:64.
  • Trigger: AGENT_HIBERNATION_TICK_MS = 60 s, for each confirmed idle pane whose agent holds deliverable mail or a pending Dispatch.
  • Work per refusal, all of it done before main refuses (terminal-pane-hibernation.ts):
    • a scoped currentCandidates() re-plan (host PTY evidence RPC)
    • collectSleepingAgentSessionRecordsForWorktree (l.71)
    • capture({ includeLocalBuffers: false }) (l.86): an xterm scrollback serialize of every pane in the tab when the repo preserves buffers, then setTabLayout with those buffers, which is never rolled back
    • a sleepingAgentSessionsByPaneKey + suppressedPtyExitIds store write (l.116)
    • the stop RPC: terminal.stopExact or pty.kill, which unregisters and re-registers PTY data handlers
    • a rollback store write
    • each of those store writes feeds workspace-session persistence
  • Before this PR the same pane slept once and stopped paying.
  • Bound: none, other than the pane leaving the busy state. An idle coordinator that never runs orchestration check, a Dispatch stuck in pending, or a disconnected host keeps it busy for hours.
  • Price: 25 busy panes → 25 tab serializations, ≈75 store writes and ≈25 session-persist passes per minute. They run sequentially inside one tick (for … await hibernatePaneIfStillEligible), so the serializes land as a burst of renderer main-thread stalls each minute. This is hidden, repeating work that grows with busy-pane count and lasts as long as they stay busy.
  • Possible fix (not verified): check admission before any capture or store write. Either expose main's busy verdict to candidate planning (expectedRuntimePtyIds already round-trip), or add a cheap pre-check RPC. Back off a refused pane until its mail or Dispatch state changes.
  • Guard: fake timers plus a main that always refuses, run 10 ticks: capture count is 0 and sleepingAgentSessionsByPaneKey identity is unchanged.

P1-2. Slept-agent waits and wakes poll at 10 Hz on main, uncapped for --for exit, and a race loser keeps polling after the shared wake fails.

  • Where: slept-agent-wake-runtime.ts:150-166 (awaitWokenHandle, SLEPT_AGENT_WAKE_POLL_MS = 100), :123 (deadline = Infinity when no timeoutMs), :68 (Promise.race([woken, awaitWokenHandle(...)])).
  • Trigger:
    • every terminal.wait --for exit on a slept handle. The CLI sends no timeoutMs by default, so the loop runs until the RPC connection closes at the CLI's 5 min timeout: ≤3000 iterations per call, and agents re-issue the call.
    • every send, prompt mutation or worker start that wakes a slept pane.
  • Work per tick: getLivePtyForHandle (2–3 Map lookups plus setPtyHandle), a setTimeout and a promise turn.
  • Race loser: when the shared woken rejects (agent_wake_failed, e.g. the workspace is not open), each caller's own awaitWokenHandle keeps polling until its deadline. That is 120 s for orchestration-mutation-executor.ts:78, which passes {} with no signal and no timeout, and 60 s for local-worker-start.ts. A coordinator retrying a send every 5 s stacks up ≈24 zombie loops per pane, ≈240 wakeups/s.
  • Population: concurrent waiters on slept handles plus failed-wake callers. Each tick costs microseconds, so a dozen agents waiting is ≈120 timer wakeups/s, roughly 1–2 ms/s on main at reference. It grows linearly with waiters, keeps running with nothing new to report, and outlives a failed wake.
  • Push alternative: graph sync binds the woken PTY to the same handle (adoptFirstPtyForLeafHandle / rebindSleptLeafHandle), and terminalWaiters already exists for event-driven exit waits.
  • Possible fix (not verified): resolve from the handle-binding or PTY-spawn event, with one shared waiter per pane, and stop each caller's loop when woken settles.
  • Guard: fake timers, a slept handle, waitForTerminal(handle, {condition:'exit'}) with no timeout over 10 simulated minutes: getLivePtyForHandle is called ≤ a constant. On a failed wake, no timers remain once the caller rejects.

P1-3. sleptLeafHandles outlives renderer reloads and graph resets.

  • Where: src/main/runtime/session-graph/slept-leaf-handles.ts:16,147.
    • beginGraphReload (session-graph-reload-lifecycle.ts:115), transitionGraphReloadToTerminalState and restoreHeadlessGraphAuthority (session-graph-authority.ts:75,97) all call terminalIdentity.clearHandles() but leave sleptLeafHandles alone.
    • After the reset, restoreSleptLeafHandle mints a fresh term_<uuid> for every slept pane that has no prior Dispatch handle and adds it as a new key. The old key is only deleted in invalidateLeafHandle / adoptFirstPtyForLeafHandle, and neither runs for a handle that was cleared in bulk.
  • Growth: one entry (~150 B, two strings) per non-dispatched slept pane per reload, for the life of the process. That is ≈15 KB per reload at 100 slept panes.
  • Severity: strictly this is unbounded growth, but the bytes are small and reloads are user-driven, so I graded it P1 under "per-entity state outlives the entity". A stale key can also still answer sleptLeafHandles.has(handle) for a reused handle string (worth a correctness check).
  • Fix: clear the map next to clearHandles(), or delete per handle in the bulk reset.
  • Guard: 20 reloads with N slept panes: map size == N.

P1-4. Linear statuses.find per slept worker in fleet projection.

  • Where: src/main/runtime/orchestration/workers/lifecycle/session-worker-liveness.ts:39 (new withSleptAgentWorkers), wired into worker-list-projection.ts:120 and worker-observation.ts:236.
  • Trigger: every orchestration worker list / receipt-next / worker show.
  • Work per call: up to 100 slept workers per page (ORCHESTRATION_FLEET_PAGE_MAX) × S status rows. The sibling createSessionWorkerLivenessReader already builds a lazy statusByPane Map, and projectOrchestrationFleet already builds createFleetStatusIndex.
  • Price: ≈30k compares per call × 4 calls/s at reference, which is negligible. At 10× it is 300k × 40/s = 12M compares/s, an estimated 20–40 ms/s on main. The cost scales with fleet size on a repeated CLI trigger.
  • Fix: reuse a lazy pane→status Map.
  • Guard: 100 slept workers, S = 300 and 3000 statuses: pane-key comparisons per call ≤ S + workers.

Each piece of new or changed work: trigger → population → bound

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.
    • sleptAgentPaneForHandle calls the pre-existing idempotent watchSleepingMail() (guarded by watchingSleepingMail).
    • It installs once per runtime: 1× onClientEvent, 1× subscribeAgentStatusRowChanges, 1× crewChanges, 1× sessionCrewChanges and 1× onWorkspaceSessionWritten, so 5 listeners at 1 instance.
    • requestSleptMailboxWake already 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.get each
    • crew listener: per crew invalidation
    • session-written listener: per workspace-session write
  • 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). sleptPaneResumes is matched and disproved: it is deleted in finally.
  • 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, inspectWorkerTerminal and restoreSleptLeafHandle run 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

  1. Unused work before the gate: reviewed. Finding P1-1.
  2. Ownership multiplies work: reviewed.
    • Wake dedupe is per pane.
    • Per-caller poll loops multiply with callers (P1-2).
    • Listeners install once per runtime.
  3. Thread / storage: reviewed.
    • All main-side work is O(1) Map work plus indexed node:sqlite point reads.
    • The renderer pays for the P1-1 serializes.
  4. 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.
  5. 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.
  6. Obsolete work stops: reviewed.
    • RPC waits abort on connection close (dispatcher.ts connectionSignal).
    • Internal wakes with {} keep polling for 120 s after a failed wake (P1-2).
    • A refused sleep leaves setTabLayout buffers written (P1-1).

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 tc or full suite).
  • Not verified:
    • whether a multiplex stream can attach to a slept handle, which would add a long-lived exit poller per open mobile view
    • whether confirmAgentHibernationCandidates re-confirms a refused pane on every tick (the retry comment implies it does)
    • SSH / remote resume latency
  • Hosts: macOS source review only.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan, pass 2: PR #44113 (HEAD~2..HEAD @ 45bf23b)

Verdict: FAIL. There is one P1: wakes running at the same time each start their own recheck timer, and every timer re-checks all of the wakes. The price at the reference fleet is small, but the work is provably duplicated, so per the rubric it blocks. Everything else is bounded with constant work per event. Numbers for each item are below.

Finding

P1: each in-flight wake runs its own 500 ms interval, and each interval re-checks every pending wake. Work per tick is O(W²) where O(W) would do.

  • Where: src/main/runtime/orchestration/mailbox/routing/slept-agent-wake-runtime.ts:166 (wakeSleptPane → setInterval(() => this.onSleptLeafGraphSynced(), SLEPT_AGENT_WAKE_RECHECK_MS)), together with onSleptLeafGraphSynced at :141. That function walks every entry of wokenHandleChecks and carriedExitWaits. Introduced by 86442e4; 45bf23b kept it.
  • Trigger: each wakeSleptAgentHandle call for a distinct slept handle. That covers terminal send text/enter, prompt mutations, worker start of a reused slept agent, and worker follow-up. The interval runs from when the resume request returns until the handle binds to a connected PTY, capped at 120 s.
  • Work: W concurrent wakes create W intervals. Each tick runs W checks (2 Map lookups each) plus E carried exit waits, so every check runs W times per 500 ms instead of once. Electron main pays for it.
  • Price: concurrent wakes are limited by concurrent blocking callers (sends wait for the wake). At the reference fleet that is about 12 CLI-calling agents, so W ≈ 12: ~600 lookups/s, under 0.1 ms/s. At 10× (W ≈ 120): ~58k lookups/s, about 1 ms/s for up to 120 s per wake. If a main-side fan-out (for example parallel worker starts) wakes all 100 slept agents at once: 40k lookups/s at 1×, and ~4M lookups/s (tens of ms/s on main) at 10× agents. Far below P0 for real callers; P1 because the duplication is source-proven.
  • Proposed remedy (not tried): start a single recheck interval when sleptAgentWakes goes from empty to non-empty, and clear it when the map empties. Alternatively, have each interval run only its own handle's check. Either keeps the backstop without changing routing or ordering.
  • Guard: fake timers, W=10 and W=100 pending wakes that never bind, advance 5 s. Calls to wokenHandlePtyId should be ≤ W × ticks; today they are W² × ticks.
  • Evidence: source-proven count only. No timing was measured.

New or changed work: trigger, population, bound

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 wokenHandleChecks or carriedExitWaits is non-empty, and unsubscribed in onSleptLeafGraphSynced once both are empty.
    • Under load: at most 1 listener, however many wakes are pending, because of the ??= latch. It fires on every crewChanges.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.
  • Recheck setInterval, 500 ms: 0 at idle; W while wakes are in flight. Each is cleared in finally and capped by the 120 s deadline. This is the P1 above.
  • No new publications: the PR adds no new notify/emit/IPC sends. restoreSleptLeafHandle changes 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 busyRetries map.

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, carriedExitWaits and busyRetries. 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: holdsSleptPaneWake matched, 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

  1. Unused work before the skip gate: reviewed. busyRetries is checked before the stop RPC. The bare-interrupt early return happens before any wake. The byPane index is built lazily, only when some worker needs it.
  2. Ownership multiplies work: finding, since the interval is per wake rather than per runtime. The listener is shared, and wakes are deduped per handle.
  3. 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.
  4. 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.
  5. Execution host: reviewed. Each wake makes one renderer resumeSleepingAgents call; there are no SSH round trips per item. Windows/Linux/WSL behavior is not exercised; the code paths are platform-neutral.
  6. 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 tc and the full suite. Benchmarks were not run either.
  • Residual risk: the internal callers of waitForTerminal with condition exit, no timeout and no signal on a slept handle were not enumerated.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan (pass 3): PR #44113 HEAD~3..HEAD @ 2282f06

Result: PASS. No P0 or P1 findings. All new work is gated to slept panes or to one sleep or wake attempt. Every timer and subscription settles, and every new per-entity map has a delete path in the same teardown. The repair commits (45bf23b, 2282f06) add a 500 ms wake backstop, carried exit waits, pty:sleepAdmitted and a busy backoff. Each is bounded as shown below.

Reference fleet used: 750 worktrees, a few hundred live terminals, 100+ agents, hook status changes at about 10–50/s, about 4 orca CLI calls/s, tens of thousands of dispatch rows. Growth target is 10×.

Inventory: trigger → population → work → bound

# 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 while wokenHandleChecks or carriedExitWaits is 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 (parkSleptLeafHandle once per sleep, restoreSleptLeafHandle once per mint) go through TerminalIdentitySource, which notifies only on an actual change (setHandle compares fields; addSynthetic is gated by has). 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

  1. Unused work before the gate. Reviewed. The local hibernation path asks sleepAdmitted before collectSleepingAgentSessionRecordsForWorktree and capture. The remote exact-stop path (expectedRuntimePtyIds.length > 0) still captures, with includeLocalBuffers: 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.
  2. Ownership multiplication. Reviewed. One wake per handle, one interval, one listener per runtime. Nothing is created per mounted row or pane in the renderer.
  3. 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.
  4. 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).
  5. Execution host. Reviewed. No per-item SSH round trips. The wake is one resumeSleepingAgents IPC to the owning window. sleepAdmitted is local only; remote panes rely on main's exact-stop assert. Windows and Linux were not exercised (no platform-specific code in the span).
  6. Obsolete work stops. Reviewed. Waits release on the caller's signal (the terminal.wait RPC 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 with terminal_handle_stale.

Evidence and limits

  • Source-proven counts above. slept-agent-wake.test.ts passes (2/2). No runtime timing, CPU or heap measurement was taken; per instructions, no tc and no full suite.
  • Residual, not inspected to closure: when restoreSleptLeafHandle mints over a different current handle (slept-leaf-handles.ts:152-164), the old handle record is rebound away from the leaf, but I did not trace whether its handles entry is removed. That is at most one record per slept pane per restart, so it does not grow with fleet or time.

@brennanb2025
brennanb2025 marked this pull request as draft November 19, 2026 05:53
@brennanb2025
brennanb2025 marked this pull request as ready for review November 19, 2026 05:53
@brennanb2025
brennanb2025 force-pushed the brennanb2025/agent-sleep-orchestration branch from a9ee31f to 37525fb Compare November 19, 2026 06:20
@brennanb2025
brennanb2025 force-pushed the brennanb2025/omh-slept-coordinator-wake branch from 69daa5e to 11e40d0 Compare November 19, 2026 08:56
@brennanb2025
brennanb2025 force-pushed the brennanb2025/agent-sleep-orchestration branch 12 times, most recently from 14623d1 to 60533eb Compare November 19, 2026 15:12
@brennanb2025
brennanb2025 force-pushed the brennanb2025/omh-slept-coordinator-wake branch from 59618d5 to d44e79b Compare November 19, 2026 16:28
@brennanb2025
brennanb2025 force-pushed the brennanb2025/agent-sleep-orchestration branch from 60533eb to e7cc0c8 Compare November 19, 2026 16:28
@brennanb2025
brennanb2025 force-pushed the brennanb2025/omh-slept-coordinator-wake branch from d44e79b to eaa8b77 Compare November 19, 2026 17:19
…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
@brennanb2025

Copy link
Copy Markdown
Contributor Author

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 d0fb8d4 (commits 92c3826, dd24c59, 8b15873).

Must-fix (audit, replaced-list-lookup.ts): clearing remembered positions now also forgets which lists were indexed. This covers both a coordinator stop/start and the 4,096-position cap. So the final sleep check can always find its tab again. replaced-list-lookup.test.ts covers both paths.

The eight P1s:

  1. Run mail probes (run-lookup.ts, sleeping-mail-owner-mailboxes.ts, new mailboxes-with-mail-sql.ts).
    • The admission check, and the wake re-check's Runs branch, are now one query each, starting from unread mail awaiting delivery. That mail is read through its partial indexes (idx_messages_mail_wake_candidate, plus idx_messages_pending_pointer_enter for reservations) with a to_handle prefix range.
    • CROSS JOIN keeps the mail as the outer loop, and each Run is found by primary key. So a Run without mail is never visited, and cost follows mail awaiting delivery, not a pane's history.
    • The Dispatch and remote-attachment branches stay on their partial live-owner indexes, which never hold history.
  2. One-pane availability retry (slept-mailbox-runtime.ts): only a host edge reads the tracked mailboxes.
  3. PTY exit after 128 archives (floating-session-liveness.ts): each archive candidate is checked by keyed lookups (process → handle → that handle's pane), instead of every leaf being walked.
  4. Targeted renderer wake (hibernated-agent-wake-listener.ts, use-terminal-pane-hibernation-wake.ts): the named pane's binding is found by leaf id through the pane manager; workspace wakes still reach every pane.
  5. Handle-scoped terminal list (unmounted-slept-agents.ts, runtime-terminal-list.ts): a list for named handles resolves only those handles through the handle-keyed sleep index.
  6. Unmounted acts after a graph update (unmounted-slept-agents.ts, slept-agent-wake-runtime.ts): the leaf is found through the identity's leaf-id candidates, which the graph sync already maintains. The per-graph index is kept only for the main-owned layout path.
  7. Two-host workspaces (agent-hibernation-coordinator.ts, agent-hibernation-host-evidence.ts): both checks of one pane's sleep, and the stop itself, share the owner resolved once for that sleep. The stop is asked of that owner, so an unrelated edit during admission doesn't re-settle it.
  8. Session watcher (sleeping-mail-record-index.ts sessionWritten): a write to a named host whose records map is unchanged returns before any host is listed.

Contracts at N and 10N (each fails with this batch's source reverted):

  • Fix 1: mailbox-owner counts Run rows, and a query-plan check confirms there is no Run scan and Runs are searched only by id.
  • Fix 2: slept-mailbox-wake counts tracked-mailbox reads per one-pane retry.
  • Fix 4: hibernated-agent-wake-listener counts binding visits per targeted wake.
  • Fix 8: sleeping-mail-record-index counts host listings per unchanged write.

Fixes 3, 5, 6 and 7 are keyed lookups that the scan's own harness already measures.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Performance scan: blocked at 8b158734cf68241878246ef605134392cbd845ac. The eight previous count regressions are fixed in their measured dimensions; this delta introduces two P1s. Counts below are deterministic operations and retained entries, with no claimed application latency, CPU or heap-byte measurement.

New in this delta

P1 — 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 run: undelivered-mail range. The pane filter runs after the mail projection and primary-key join. With the target fixed at 100 owned Runs and no mail, Q=100/1,000 stranded messages in 100/1,000 other mailboxes produce 100/1,000 candidate-message visits and Run-key probes per admission and per wake-owner query, repeated unchanged for ten checks; returned historical-owner rows remain zero. Putting all Q messages in one foreign mailbox still visits 100/1,000 messages, with one Run probe. Unrelated reserved pointers cause the same admission cost; the wake-owner query correctly excludes them. Original query plans show the global prefix search, mail scan and Run primary-key join; counters preserve those predicates and results, and uninstrumented controls agree. The old pane-led SQL control stays at 100 own-history probes regardless of Q and visits no unrelated owners.

This reaches main-thread sleep admission, retained-attempt/arrival reconciliation, and both callers of resolveAll: input-ready delivery and delivery-debt checks. Production edges include graph binding, input-ready title transitions and settlement rechecks; this is not restricted to Agent Sleep. At E=1 relevant check/s the added unrelated work is 100/1,000 message visits plus 100/1,000 Run probes/s. For 100/1,000 active agents each reaching an input-ready edge every five seconds, Q=100/1,000 costs 2,000/200,000 of each operation/s. Two admission checks for C=100/1,000 candidates add 20,000/2,000,000 of each per drain, before wake reconciliation. Stranded mail makes the next check repeat the same prefix without progress. Keep mail eligibility indexed or invalidated by owner/pane, preserving historical mail, reservations and delivery custody; substituting a global mailbox scan does not bound a pane read. Reproduction: independent-sleep-admission.performance.test.ts, empty/historical and eight stranded-mail combinations.

P1 — removing empty host partitions leaks cached session inputs. sleeping-mail-record-index.ts:153 returns before forgetUnlessLive. A host with no sleep-record field and the removed host both resolve to the same empty-record sentinel, so its removal notification now skips retirement. A real runtime watcher wired to the production session-partition getters retains 101/1,001 input-cache entries after 100/1,000 add/remove cycles, with one live host, zero obligated hosts and zero sleepers. An additional global session notification does not heal them: its scope contains current or obligated hosts, not these orphaned input keys. The former refresh-then-retire control retains 1/1. The production partition-removal method sends exactly this named-host notification. Cost is one permanently retained host key/map entry per removal, growing with topology history for the runtime lifetime, with no cap; at E empty-host removals/s that is E extra retained entries/s. Preserve keyed membership/removal cleanup before the unchanged-record skip, without restoring the all-host scan on ordinary writes. Reproduction: independent-sleep-host-retention.performance.test.ts.

Prior P1s

  1. Retained-Run admission and wake-owner probes — fixed for R growth. R=100/1,000: admission makes two owner queries/check and returns one newest row with 0/0 mail probes when empty; historical mail returns two rows with 1/1 probes and correctly refuses sleep. Retained-attempt publication makes one Run-owner query: 0 rows/0 probes empty, 1 row/1 probe historical, at both sizes. The separate new Q-wide work is above.
  2. One-pane availability snapshot — fixed. M=100/1,000 tracked mailboxes: 0/0 tracked-entry visits, 2/2 local refreshes per pane event. Only the host-edge branch constructs the global retry snapshot.
  3. PTY-exit leaf projection — fixed. L=100/1,000 unrelated leaves, ten real exits with 128 existing archives: 0/0 extra leaf visits/exit, 129/129 keyed archive checks/exit. Existing PTY inventory scan/sort remains; the new protection no longer enumerates graph leaves.
  4. Targeted renderer wake — fixed. K=100/1,000 bindings: 1/1 binding visit and one matching claim through the real dispatcher/listener and production leaf-identity registry. One targeted wake reaches one tab owner; workspace wakes retain necessary workspace fanout.
  5. Handle-scoped sleeper listing — fixed. S=100/1,000: a one-handle list makes 0/0 global sleep-record visits, 2/2 keyed record gets and 1/1 outputs. Workspace scope remains 0 global visits, 3 keyed gets, one output. Construction forwards both scopes to the producer; fresh-liveness lists omit sleepers.
  6. Unmounted acts after title-only graph replacement — fixed in the shipped layout branch. Ten graph title publications at L=100/1,000: the next real read and warm repeat each visit 0/0 global leaves and remain readable. Read/send/show/wait/wake use the same keyed leaf-candidate helper; their separate real-act census has zero sleep/identity inventory visits and 1/2/3/1/2 record gets, respectively. Waited-leaf removal also builds no global leaf index. The separately gated main-owned layout branch retains its previously documented per-graph fallback and was not executed.
  7. Ambiguous-owner final callback — fixed. Under an ambiguous workspace route, unrelated tab-title/global-binding publications during admission add 0/0 owner-PTY visits in the final callback at P=100/1,000, including split widths 100/1,000. One target still reads two status rows and one tab, driver, input and attention entry; foreground, pending input and mobile changes still refuse sleep. Distinct remote-owner evidence remains fail-closed. The initial owner resolution is shared across both checks and stop; the old planning-pass cost is unchanged.
  8. Empty session-write host enumeration — fixed for unchanged named writes. H=100/1,000 saved hosts, zero sleepers and ten unchanged writes: 0/0 host keys/write through the real installed watcher and partition getter. Removal cleanup has the distinct new regression above.

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 bounds

Inspected the 20-file delta from d0fb8d41639d2d853d42922f7de92e2b7a26df1c and every production caller of its changed functions, including notification/admission, availability, exit/inventory pruning, terminal listing/acts/waits, pane lifecycle and both host-evidence consumers. Prior-cleared paths outside this delta retain their dispositions. All detected surfaces are covered: hot-path,publish,startup-migration,subscribe,version-bump; startup/migration and unchanged publication producers retain prior clearance, and their contracts were included again.

  • Runtime mail readers: one runtime-crew and one session-crew subscriber while sleepers/attempts/tracked mail exist, zero of each after teardown; named events refresh their named scope. Unnamed bursts of 100/1,000 changes refresh M=100/1,000 mailboxes once per second for three bursts, then zero over 60 quiet seconds. Host edges reconcile M tracked mailboxes; stable connection publications do not. Arrival/retained-attempt pane queries now carry the Q-wide finding. Full recovery still reconciles S sleepers+A attempts+M tracked mailboxes, once per coalesced pass, rather than a per-sleeper snapshot product.
  • Lifetime subscriptions: one session-write reader, one keyed hook-row reader and one host-client reader per runtime; client census remains two total/one terminal-side-effect consumer. Unchanged named writes now do one keyed identity check and zero H inventory work; changed record snapshots still compare S_old+S_new once, and unscoped recovery enumerates hosts. Status rows visit the addressed pane's attempts. These subscriptions add no autonomous idle work. Removed-input retention is the exception above.
  • Wait/wake/render owners: two shared handle/leaf touch listeners while waits exist, released with the last waiter; unrelated identity/title/drop events cause zero wait checks. One wake owner/tab and one card subscription/card, cleaned on unmount. A targeted wake invokes one owner/one binding; one changed held-mail workspace invokes one card, with zero unrelated or post-teardown callbacks at 100/1,000 cards. Existing workspace-wide requests perform work for their actual outputs.
  • Publication/replies: held-workspace version/equality gate sends zero unchanged frames, one frame for a 50-workspace burst; refused-window delivery suppresses repeated snapshots until recovery. Native replies use one request-id router while pending, keyed dispatch and deadline/abort/document cleanup. These unchanged producers retain prior clearance. No subscription polls.
  • Rates/resources: no new subscriptions, timers, processes, full-file writes or eager heavyweight imports in this delta. The existing enabled coordinator remains one renderer timer per 60 seconds, under its existing visibility gate. Added autonomous idle wakeups/s versus the prior head: main 0, renderer 0, daemon 0. Queued mail wakes remain deduplicated with two active requests and drain progress; quiet mail has zero refreshes. Weak graph/list ownership and tab/handle teardown remain; empty-host input keys fail retirement as above.

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
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Fourth batch: the last rescan's two findings and the audit's must-fix (for the next perf rescan)

Changed since 8b15873 (commits 1616b8e and 73a8975):

  1. Removed empty hosts no longer leave a cached input (sleeping-mail-record-index.ts).
    • A host with no sleep records never caches its input.
    • A session write naming a host that has no records and nothing indexed returns early, still before any host is listed.
    • Contract: sleeping-mail-record-index drives 100 or 1,000 add/remove cycles through sessionWritten and retains nothing.
  2. Audit must-fix: a slept pane's stopped process survives archive pruning whichever binding names it (floating-session-liveness.ts).
    • Each archive candidate is checked against only the panes it can name: its own pane by leaf id (via the identity's leaf-id candidates), its reverse handle, and its incarnation's leaf.
    • The pass condition is the old leaf scan's: the pane shows no process, and its bound handle names this process. So pane-issued and restored slept handles are covered without walking every leaf.
  3. Run mail checks are back to probing the pane's own Runs (run-lookup.ts, sleeping-mail-owner-mailboxes.ts).
    • Driving them from queued mail made every pane pay for unrelated queued mail.
    • An independent reviewer measured both versions and accepted the per-Run probe for this PR: about 0.135 ms per check at 1,000 retained Runs, against 0.37–0.42 ms for the mail-driven query at 1,000 unrelated messages.
    • A pane-keyed mail index, which makes the check independent of both, is follow-up STA-17741.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Performance scan: PASS, no new performance blockers at 73a8975fe9ec1a66a8916f3fa8d65d8ad346632b. Scope: changes since 8b158734cf68241878246ef605134392cbd845ac and their production callers. Previously cleared paths outside that delta retain their clearance.

Prior P1s

  • Unrelated queued Run mail — fixed. Run lookup:35 and sleeping owner lookup:52 now seek the pane's Runs before probing mail. With 100 own Runs and Q=100/1,000 unrelated queued messages, each admission and wake-owner check makes 100/100 own-Run probes, 0/0 foreign-Run probes. Ten unchanged checks reproduce this at both sizes, across distinct foreign mailboxes, one shared foreign mailbox, and reserved/unreserved pointers. Admission returns one newest Run row; wake-owner returns zero rows. Query plans show indexed pane selection and exact mailbox seeks, so unrelated message ranges are no longer traversed. Production triggers remain input-ready delivery, delivery-debt checks, sleep admission and arrival/retained-wake reconciliation. At E checks/s the removed Q-dependent work is now zero foreign probes/s, independent of Q; own-history work is accepted below.
  • Removed empty-host input retention — fixed. Session index:153 skips empty, unindexed hosts before listing hosts, and refresh:183 never retains an empty input. The installed runtime session-write listener, using production partition getters, retains 0/0 cached inputs after N=100/1,000 host additions/removals, with one live host and zero sleepers/obligated hosts. Both missing sleep-record fields and explicit empty maps pass. Both immediate add/remove cycles and adding all N hosts before removing them pass. Across 200/2,000 named writes, host listings/write are 0/0; an explicit unscoped recovery lists once and retains zero inputs. At E named empty-host writes/s this adds zero host inventories and zero retained entries/s.

Known, accepted

The 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 resolveAll consumers (delivery and debt), admission and the arrival/retained-attempt publication routes; no additional trigger or autonomous polling was introduced. These costs remain accepted rather than reopened as a blocker.

New in this delta

No 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 limits

All 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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready on 73a8975fe9ec

Problem: with Experimental > Agent Sleep on, an agent that Orca stopped while idle disappeared from orchestration. It wasn't listed, couldn't be read, its waits misbehaved, and mail sent to it did nothing until someone reopened it.

What users get: a slept agent now behaves like an idle one to orchestration. It is listed, readable, and waits on it behave. When it's messaged, it wakes in place: same tab, same conversation, one process, and the message is delivered once. Mail waiting for a slept agent wakes it. This also works while its tab isn't mounted, after a reload, or while another workspace is open.

What was fixed during review:

  • QA wake failures: the reload wake now reuses the handle saved on the sleep record. A sleep while the tab is unmounted, and a reload with another workspace active, both resolve the slept handle through one lookup keyed by handle. List, show, send, waits and wake all use that lookup.
  • Performance: four rounds of fixes so that no sleep check or orchestration event does work that grows with tabs, processes, Runs, workspaces, hosts or catalog rows. Each change is listed for the scanner in these comments:
  • Audit must-fixes: each was fixed and re-audited:
    • a launch-config refresh dropped the slept handle;
    • a returning host's sleepers weren't treated as arrivals;
    • a cleared position cache stopped agents from sleeping;
    • archive pruning could drop a slept pane's stopped process.

Verified on this head:

  • CI: green.
  • Perf scan: clean (report).
    Benchmark: head=73a8975fe9ec1a66a8916f3fa8d65d8ad346632b gate=PASS
  • Perf contracts: every *.performance.test.ts the PR adds passes on Linux at N and 10N. Each new contract fails with its fix reverted.
  • Blinded regression audit: SAFE. Its one must-fix was the per-Run mail probe, a cost an independent perf reviewer had measured and accepted: about 0.135 ms per check at 1,000 retained Runs. A fresh confirm reviewer then refuted it as a regression: it is an accepted interim cost that does less work than main, which loaded every Run twice per call. Follow-up: STA-17741.
  • Fresh Claude review: CLEAN.
  • Real QA on macOS (M4Air, real Claude agents, r7 and r8, last on 22ca84d): reload wake, wake while another workspace is active, unmounted-tab wake, mail wake, exactly-once delivery and one process per pane all pass. Since then the PR's commits are performance changes to the same paths. Each is covered by counter tests and the related unit suites. The one that touches the wake path (the targeted renderer wake reaching its pane by leaf id) keeps the same pane-key check.

Follow-ups (not blocking):

  • STA-17741: a pane-keyed mail index so Run mail checks don't grow with a pane's retained Runs.
  • One retention test (sleeping-mail-record-index.performance.test.ts, "session writes for N hosts…") should add each host with the shared empty-record value, so it reproduces the leak it's named for.
  • When main owns the pane layout (off in shipped builds), archive pruning should read a process's pane through paneOfPty rather than pty.paneKey.
  • An end-to-end test of archive pruning with more than 128 archives and a slept pane.

QA screenshots (r7): unmounted-tab wake, and wake with another workspace active.

unmounted-tab wake
wake with another workspace active

…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
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Performance scan: PASS — no new P1 at d18d86849ffa16cafc51f5e2958ac0da0340590e.

Scope: 73a8975..cdd7c90 launch-model change, plus 436feee..d18d868 in the two merge-conflict paths, and their changed functions' production callers. Previously cleared paths retain the prior scan's clearance.

Known, accepted

The 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

  • Launch-model preservation: command compilation:191 scans only that launch's resolved option tokens, returns immediately on the first model, and retains at most two model tokens. With A option tokens, added work is at most A token examinations per affected compilation, or E×A at E compilations/s. N=100 versus 10N=1,000 unrelated Runs/messages/tabs/workspaces/panes/PTYs/sleep records/hosts adds 0/0 visits. Startup, draft startup, resume fallback and account-restart callers compile one requested launch; ordinary recorded-command resume bypasses compilation. The saved command is replaced, not appended across sleep cycles. No polling cadence or fleet discovery is added.
  • Wake helper: readiness:163 is identical to the previously cleared helper. Its sole production caller runs once per local worker start, skipping structured/chat workers before the two addressed runtime calls. Existing per-handle wake sharing and keyed pane/leaf lookups remain; no new N/10N work or trigger. One-time runtime sleep-index initialization remains unchanged.
  • Release contract: runtime type:28 adds a type member only: 0/0 runtime operations at N/10N, on every release/sweep trigger.

Coverage and evidence

Detected 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:

  1. Skip gates: structured/chat workers return before wake work; recorded commands bypass recompilation; existing sleep-index setup is guarded once per runtime.
  2. Ownership: launch-local strings and existing shared per-handle wake; no new mounted owner, listener, client or fanout.
  3. Thread/storage: added token work executes in the caller; no added sync I/O, SQL, serialization loop or subprocess. Existing runtime/SQLite seams were exercised remotely.
  4. Growth/progress: model extraction is bounded by one launch's options, output by two tokens; no collection-wide invalidation, retry loop or queue added.
  5. Hosts: shell/platform routing and quoting remain unchanged, with no added host probe or remote round trip. Contracts executed on Linux; no native platform or live transport measurements claimed.
  6. Cleanup: no new retained owner/resource. Existing shared wake cleanup deletes handle/pane entries in finally; pending-wait cleanup removes listeners. Remote contracts cover cancellation and keyed wait fanout.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Performance scan: PASS — no new P1 in d18d86849ffa16cafc51f5e2958ac0da0340590e..53e7eda0b8128717af83dfad45723ead647f2355.

Scope: the four delta paths and every caller of their changed functions. Paths outside the delta retain the previous scan's clearance.

Known, accepted

The 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

  • Resume startup suppression: resume planning:91 saves the launch configuration before adding the update-screen arguments/environment. The lookup:25 is two direct table accesses, with at most two argument tokens or two environment keys. With V input environment keys, the additional merge/return copying is bounded by V+4 field assignments per affected resume. At E requested resumes/s: at most 2E token quotations and E(V+4) additional field assignments; command length gains only a fixed suffix. N=100 versus 10N=1,000 unrelated Runs/messages/tabs/workspaces/panes/PTYs/sleep records/hosts adds 0/0 collection visits. A burst of N actual resumes constructs N required launch plans, with no cross-owner scan or accumulating suffix.
  • Model-pin revert / extraction: command compilation:173 removes one provider's model-token scan; the remaining provider scans only its own launch options, as previously cleared. Moving the constant tables adds one small, fixed module with a type-only import and no initialization I/O.
  • Caller census: resume planning runs once for the requested cold restore, sleeping-session launch, account restart, local saved-conversation resume/fork, host session ensure or mobile resume. Command compilation also serves fresh/draft startup and fresh account restart; the picker fixture is non-production and the spawn-type import is type-only. Recorded commands still bypass recompilation. No caller, retry cadence, publication, subscription, version bump, database query, subprocess, transport request or fleet inventory was added.

Coverage and evidence

Detected 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:

  1. Skip gates: unsupported resumes return before suppression; recorded commands retain the existing compiler bypass. No expensive gate was loosened.
  2. Ownership: one transient plan per requested launch; no new mounted owner, shared listener, poll or fanout. Idle wakeups added on main/renderer/daemon: 0/0/0 per second, from source inspection.
  3. Thread/storage: command-local string/environment work runs on the invoking main or renderer thread; no new synchronous I/O, SQL or child process. Counts above are source bounds, not timing measurements.
  4. Growth/progress: arguments and keys have fixed bounds; only the requested launch's input environment is copied. Saved configuration precedes suppression, preventing growth across repeated sleeps. No new queue, retry or invalidation path.
  5. Hosts: existing POSIX/Windows quoting and host routing are reused; no new host probe or remote round trip. Contracts ran on Linux; native platform and live-agent performance were not measured.
  6. Cleanup: no new retained resource or per-entity registry; transient arguments/environment leave with the launch plan. Existing remote contracts exercise wake-owner release, cancellation and host teardown.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Performance scan: PASS — no new performance regression in the scoped delta from 53e7eda0b8128717af83dfad45723ead647f2355 to 4c05e4f0a74780ea9e5bb386a26f0c88a1c20b05.

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 a40d14c49f3858b66f969ec251fa6c735bb89f5e and traced their notification consumers.

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

  • Wake callback:241: joining the line and renaming the rest parameter preserves the same helper, arguments and call count. Additional work, listeners and collection visits per wake: 0, with either 100 or 1,000 unrelated tabs/Runs/panes.
  • Merged notification:63: one payload-free IPC per server mutation/sign-in change, one app-lifetime preload listener, one host-tagged window event, and zero registered downstream MCP window-event consumers at this head. No path into sleeping-mail admission, reconciliation, availability or wake. At E changes/s this is E IPCs and E window events per attached renderer, with 0/0 Run/tab/pane visits at N=100/1,000. The window's client-event listener does not forward this event a second time.

Six-question coverage

  1. Skip gates: destroyed/loading/gone renderers retain the existing send gate; no expensive gate bypass.
  2. Ownership: notifier remains one window-owned object; the MCP listener is app-lifetime and unsubscribed. Sleeping-mail registrations remain once per window, released on close; no registration moved into a per-pane path.
  3. Thread/storage: the merged callback performs constant main-to-renderer notification work; no new SQL, filesystem access, subprocess or copied inventory in the changed path.
  4. Growth/progress: no added scan, retry, queue, version bump or publication invalidation. The wake callback is behaviorally identical; startup/migration files in the prior census are unchanged.
  5. Hosts: existing local IPC and host-tagged event routing remain separate from remote availability edges. No new host probe/round trip; contracts ran on Linux.
  6. Cleanup/idle: existing window-close, renderer-loss and reply cleanup remain intact. Delta adds 0 main / 0 renderer / 0 daemon idle wakeups/s, by source inspection; server notifications require a real change.

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

@brennanb2025

brennanb2025 commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Review status: ready on 4c05e4f0a747

Problem: with Experimental > Agent Sleep on, an agent that Orca stopped while idle disappeared from orchestration. It wasn't listed, couldn't be read, its waits misbehaved, and mail sent to it did nothing until someone reopened it.

What users get: a slept agent now behaves like an idle one to orchestration. It is listed, readable, and waits on it behave. When it's messaged, it wakes in place: same tab, same conversation, one process, and the message is delivered once. Mail waiting for a slept agent wakes it. This also works while its tab isn't mounted, after a reload, or while another workspace is open.

Changes since the last status (73a8975):

  • A woken agent no longer opens on its update screen. Windows QA (r11) woke a slept Codex agent and found its pane showing Codex's "Update available" menu, with "Update now" selected. Orca's first Enter into that pane would have run a global install and closed Codex. Every resume (sleep wake, restart recovery, account restart, mobile) now starts with the agent's update screen turned off, as Orca-submitted fresh launches already do. One test guards the Codex resume command.
  • No saved model on resume. r9 reported that a resumed Claude agent's command lacked --model. I added it, and the blinded audit then showed it was wrong: Claude restores the conversation's own model on resume when no --model is passed, and r9's transcript confirms the resumed agent was on its launch model. A saved flag would also override a model the user picked later with /model. Reverted, so resume matches the audited code again. Codex likewise restores its thread's own model and approval policy on resume, which is why its launch-time bypass flag isn't replayed ([Bug]: Orca restart restores Codex sessions with stale YOLO args, overriding “Approve for me” #10886).
  • Main merged twice. Both conflict resolutions keep main's structured-worker setup wait and the branch's in-place wake of a reused slept worker. One line in the window lifecycle was joined to stay under the file's line limit after main grew it.

Verified on this head:

  • CI: green.
  • Perf scan: clean on this head; see the scanner's latest comment above. The delta scans on d18d868 and 53e7eda were clean too, each with 53/53 perf contracts passing.
  • Blinded regression audits: SAFE on the merge resolution (408a81b), the update-screen fix (53e7eda) and the second merge (4c05e4f). The audit of the saved-model change was NOT SAFE, and that change is reverted. The earlier audit's per-Run mail probe stays an accepted interim cost (confirm reviewer), with follow-up STA-17741.
  • Fresh Claude reviews of the delta (53e7eda, 4c05e4f): CLEAN.
  • Real QA:
    • macOS r7/r8 (Claude): reload wake, wake with another workspace active, unmounted-tab wake, mail wake, exactly-once delivery and one process per pane.
    • Windows r9 (Claude and Codex, 73a8975): the same wake flows pass with both agents.
    • Windows r11 (Codex, d18d868): a Codex worker woken while its tab was hidden keeps its handle, tab and thread. Shown afterwards, its pane draws cleanly at full width, with no garbled or stale rows. It opened on the update menu, which this head fixes.
    • Accepted gap: Codex send-after-reload wasn't run; it uses the same handle lookup that passed for Claude.

Follow-ups (not blocking):

  • STA-17741: a pane-keyed mail index so Run mail checks don't grow with a pane's retained Runs.
  • STA-17820: say why a pane with an open dispatch isn't sleeping.
  • STA-17821: the Windows Claude worker's shell needs orca.cmd.
  • STA-18051: terminal read --screen reads a hidden resumed pane at 80 columns rather than the pane's width.
  • Windows-launched WSL terminals don't forward the agents' update-off environment names. This predates this PR and affects fresh launches too.
  • The retention test in sleeping-mail-record-index.performance.test.ts should add each host with the shared empty-record value.
  • When main owns the pane layout (off in shipped builds), archive pruning should read a process's pane through paneOfPty.
  • An end-to-end test of archive pruning with more than 128 archives and a slept pane.
  • A woken Codex resume's argument order differs from a fresh launch's: the update-off flag comes after user Arguments. Nothing breaks today.

QA screenshots (r11, Windows): the Codex worker before sleep, and the same pane shown after a hidden wake. It is drawn cleanly, but shows the update menu this head removes.

Codex worker before sleep
woken Codex pane shown after a hidden wake

@brennanb2025
brennanb2025 merged commit a79f098 into main Nov 25, 2026
60 checks passed
ZinkLu added a commit to ZinkLu/orca that referenced this pull request Nov 26, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant