Repository navigation
fix(agent-hooks): let a respawned pane's status come back on any provider - #17267
brennanb2025 wants to merge 8 commits into
Conversation
…launch Pi/OMP auto-discover every file in the agent's extensions dir. When a user-owned `orca-agent-status.ts` already holds that name, `writeManagedExtension` refuses to overwrite it (no `@orca-managed-pi-extension` marker) and Orca side-loads its managed copy with `-e` instead. Both then run in the same process and post the same pane key to `/hook/omp` — but the user-owned copy is frozen at whatever Orca version wrote it, so it can post a completion the managed copy deliberately withheld and settle a pane that is still working. Measured against omp 17.0.5 with both copies live: the unmanaged copy is discovered with no flag, its `agent_end` lands *before* the managed one, and only the managed copy carries a `launchToken` in the post body. Fence the pane on that token. A tokened post always wins and becomes the pane's owner; a tokenless post is dropped only once the same pane and source have proven a tokened poster is live. Fails open in every other direction — with no tokened post the gate never arms, so a bare shell (where the managed copy itself posts `launchToken: ''`) cannot be stranded on "working". Orca does not touch the user's file. A one-shot toast names the agent so the user can find and remove it themselves.
…a's relaunch a token The fence dropped tokenless status posts permanently once a tokened poster had been seen on a pane, so a managed poster that posted once and then died left the pane claiming work forever. Measured against main with the same post sequence: main settles to done, the fence stranded on working. Suppression is now provisional. A tokenless post is held, not dropped: a following tokened post discards it -- and is the only real proof that two posters share one pane, so that is when the warning fires -- while silence past the confirmation window re-opens the gate and delivers the held post. Every held post is therefore superseded or delivered, so no sequence of posts can strand a pane. Orca's detached Codex account-switch restart respawned into the same pane key without ORCA_AGENT_LAUNCH_TOKEN, so Orca's own replacement read as a poster Orca did not launch. Mint the token there: it is the contract every token-keyed gate depends on, not just this fence.
…it spawns The relay builds each PTY's env from its own process.env, and a relay is routinely started *from* an Orca pane — so that pane's ORCA_PANE_KEY, TAB_ID, WORKTREE_ID and ORCA_AGENT_LAUNCH_TOKEN rode into every pane the relay spawned, fresh or revived. The launch token is the damaging member: it is Orca's only in-band proof of authorship, and the retired-pane status fence is keyed on it, so one leaked token let any pane on the relay satisfy a fence a different pane had set. The daemon already scrubbed exactly these four keys. Hoist that scrub into src/shared/pane-identity-env.ts and give the relay the same call, so the two PTY hosts cannot drift again. Adds a spawn-site ratchet: 52 files name the launch token but nothing stated the rule producing it, and two paths shipped without it (#17243's detached-pane restart, and this one) — each found by accident. A new pane-identity env site now has to be classified deliberately instead of silently joining the broken half.
…e count
The comment justified the ratchet with 52, which is the repo-wide count
including tests on main. The ratchet scans non-test src/**/*.{ts,tsx},
where 34 files name the token and 10 actually author it.
Greptile SummaryThis PR expands provider-specific session-start recognition and records launch generations at PTY spawn time to restore status after pane respawns and remote replay.
Confidence Score: 3/5The PR does not appear safe to merge until tokenless stale replays and displaced-process session boundaries can no longer overwrite the current pane generation. Tokenless replays still bypass the recorded replay generation, while a recognized session-start can replace the live fence without proving that its token belongs to the current process. Files Needing Attention: src/main/agent-hooks/server.ts
|
| Filename | Overview |
|---|---|
| src/main/agent-hooks/server.ts | Extends live-pane re-fencing and replay-generation handling and adds spawn-time launch-token observation. |
| src/main/ipc/pty/ipc/spawn-commit.ts | Reports the committed pane’s resolved launch token to the agent-hook server. |
| src/main/ipc/pty/pane/launch-authority.ts | Adds a helper that extracts spawn launch identity while excluding reattachments. |
| src/shared/agent-hook-listener/provider-event-routing.ts | Adds exhaustive provider-specific session-start classification. |
| src/main/agent-hooks/server-live-pane-refence.test.ts | Adds broad regression coverage for provider boundaries, spawn re-fencing, and relay replay generations. |
Sequence Diagram
sequenceDiagram
participant P as PTY spawn
participant M as Main hook server
participant A as Agent process
participant R as Remote relay
participant U as Pane status
P->>M: note pane launch token
A->>M: provider session-start/status
M->>M: classify boundary and generation
R->>M: replay cached status after reconnect
M->>M: apply replay-generation fence
M-->>U: publish accepted current status
Reviews (3): Last reviewed commit: "test(agent-hooks): pin the untokened-rel..." | Re-trigger Greptile
…ider A live pane's launch-token fence could only be handed to a new process by a hook event literally named `SessionStart`. Measured across the source matrix, 11 of 13 providers never send that name, so once Orca respawned an agent into a pane the fence kept answering for the process the respawn replaced and every post from the replacement was dropped for the life of the main process, with no user-reachable recovery. The retired-pane branch forty lines below had already been fixed for exactly this — raw event-name literals strand the providers that spell their boundary differently — and the live-pane branch still had the literal. Two source-level fixes, no exemptions to the fence: - Ask the provider. `isSessionStartEvent` names each source's own process boundary beside `isNewTurnEvent`, as an exhaustive switch so a new source fails typecheck rather than silently joining the half that can never re-fence. Deliberately not `isNewTurnEvent`: a turn boundary recurs inside one process and so cannot order two processes sharing a pane. - Tell the gate at the source. Gemini, Antigravity, mimo-code, omp and Command Code emit no session boundary at all, so no event can ever prove a new process owns their pane. Main mints the token, so main reports it: a fresh PTY for a pane now tells the hook server which launch token it carries. That also fixes the relay spool-replay fence, which compared a replay against the last token main happened to observe -- older than the generation being replayed whenever an agent launched over SSH lost contact before its first live post, which silently discarded that agent's entire spool including its final status. The status fence is only ever replaced here, never armed, so no pane that a revive never fenced starts suppressing its tokenless posters. Neither fence changes what either side puts on the wire. Ablations (serial, each verified applied, tree restored between runs): literal boundary 14 red, spawn re-fence 5 red, replay generation 2 red, reattach guard 1 red, spawn wiring 1 red, two providers zeroed in the classifier 4 red.
…enless spool A poster whose process never received ORCA_AGENT_LAUNCH_TOKEN reports it as an empty string, so raising the replay expectation at spawn made the fence read "no token" as "the wrong generation" and drop that pane's entire reconnect spool -- the same silent frozen row this fence exists to prevent, moved onto the WSL and SSH population where the variable can be lost in transit. Read-side symmetry with the write side: a record carrying no token is not evidence about any generation, so it is admitted rather than rejected. Every wrong-generation rejection that names a real token is unchanged. Also pins the two safety directions the PR argues but did not test (the expectation is only raised, never cleared), drops the kimi session-boundary branch no event can reach, and gives every armable source spawn-path coverage.
…sifier branch assumed
86df8bd to
489f78d
Compare
| expectedLaunchTokenHash && | ||
| actualLaunchTokenHash && | ||
| actualLaunchTokenHash !== expectedLaunchTokenHash | ||
| ) { |
There was a problem hiding this comment.
Tokenless replay bypasses generation fence
When a delayed SSH or WSL replay from a replaced process carries an empty launch token, this condition admits it despite the pane's recorded current generation. For a live pane without an armed restarted-status fence, the replay then overwrites the replacement agent's prompt or state with stale status.
Knowledge Base Used:
…ape of the tokenless discard An ordinary relaunch mints no token (orca-runtime only mints one with a launchConfig), so its posts and its spool are tokenless while the first launch's expectation still stands -- which is how a real pane reaches the discarded-spool case.
747b72a to
7fa4d79
Compare
|
Each agent's restart events are now recognized through #15344. Some new processes can still have their status reports rejected; rebuild that remaining fix without the unrelated delayed-extension changes in this branch. |
Stacked on #17257 (
brennanb2025/pane-identity-env-leak). Base it on that branch, notmain.ELI5
Every agent Orca launches gets a secret sticker. When a pane's agent finishes but the shell stays open, Orca puts a lock on that pane saying "only the process holding sticker #1 may report status here" — that lock stops a leftover, orphaned agent from stealing the pane's row.
The lock could only be handed to a new process by one specific announcement: a hook event literally named
SessionStart. Only 5 of the 18 agents call it that. Cursor sayssessionStart, Amp sayssession.start, Pi sayssession_start, Copilot sayssessionStart, Hermes sayson_session_start— and Gemini, Antigravity and several others never say anything of the kind. So when Orca started a new agent in that pane, the new agent held sticker #2, could never announce itself in the one way the lock understood, and the lock kept turning it away — forever. The pane went quiet and there was nothing the user could do about it.This teaches the lock every agent's own way of saying "I just started", and — for the handful that never say it at all — has Orca tell the lock directly at launch, since Orca is the one handing out the stickers.
There is a third door, on remote hosts. When the connection to an SSH or WSL agent drops, the relay saves everything the agent says and hands it over on reconnect. Orca checks each saved message's sticker against the pane's current one. But an agent whose process never received a sticker reports a blank one — and a blank sticker is not the wrong sticker, it is no evidence either way. Reading blank as wrong threw that agent's whole saved history away, including its final "done".
What a person running Orca over SSH sees
Before. You have a remote pane where an agent finished a task. You start another agent in the same pane. The sidebar row for that pane never updates again — no spinner, no "done", no prompt text — for as long as the app stays open. The agent is running fine; the terminal shows its output. Only Orca's view of it is dead. Closing and reopening the tab is the only escape, and it loses the row's history. Which agents this hits depends on which provider you use, which is why it reads as random.
Same shape, second door: you launch an agent on a remote host and the SSH connection drops before its first status post lands. The relay dutifully spools everything the agent emits, including its final "done". On reconnect, main throws the entire spool away — it compares the replay against the last token it happened to see, which is the previous agent's. The pane stays showing the old agent's status, and since the new agent has already finished, nothing ever corrects it.
Third door, found while reviewing the second: your remote agent's hook scripts emit
launchToken=""whenever the process did not receiveORCA_AGENT_LAUNCH_TOKEN— which happens whenever the variable is lost in transit, and both the WSL passthrough and an SSH host's accepted-env list can lose it. On reconnect the spool is compared against the pane's generation, an empty token is not that generation, and the whole spool is dropped. Identical symptom to the second door, different population.After. All three panes come back. A replacement agent takes the row on its own session boundary; if its provider has no session boundary, the launch itself hands over the lock. A reconnecting relay's spool is measured against the generation the pane was actually launched with, and a spool that names no generation at all is admitted rather than read as the wrong one — so the offline agent's final status lands on every remote topology, not only the ones where the token survived the trip.
Unchanged: a genuinely stale process still cannot reclaim a pane, and a spool that names a different generation is still discarded. Every "still fences the token it replaced" case in the new suite pins the first, and "still discards a replay from the generation that spawn replaced" pins the second.
The three gates
All three live in
src/main/agent-hooks/server.ts(the original report citedsrc/relay/server.ts:1206/:2338; no such file exists on any branch — the line numbers map onto this file).1. Live-pane launch-token fence (
getAgentStatusDisposition, the!paneRetiredbranch). Confirmed wrong. The claim was "suppresses and can never re-fence, because re-fencing itself requires a token". Half right: re-fencing requires a token and a literalSessionStart. Measured across the source matrix — arm the fence, then post from a genuinely new process holding a fresh token — 11 of the 13 sources in that probe matrix were suppressed permanently; onlyclaudeandcodexrecovered. (13 is the size of that probe, not the provider population:AGENT_HOOK_SOURCEShas 18, and the classifier covers all of them. Measured over all 18, five spell itSessionStartand thirteen do not.) The suppression is unbounded:restartedStatusLaunchTokenHashByPaneKeyis only cleared by pane retirement or PTY-exit cleanup, andrestorePaneAuthority— the escape hatch added for exactly this class of bug (STA-4114) — lifts the retirement tombstone but leaves this map untouched.Forty lines below, the retired-pane branch carries the comment "Why the classifier, not literals: only 5 of 18 sources name their boundary
UserPromptSubmit/SessionStart; the rest stayed retired forever." The same defect survived in the branch above it, where the consequence is worse: the retired branch fails open on an unknown provider by design, this one fails closed.2. Relay spool replay fence (the
envelope.isReplay === truegate). Confirmed wrong, different mechanism. It is not too strict about absence; it compares against the wrong generation.hydratedLaunchTokenHashByPaneKeyis written byrecordCurrentAuthorityObservationon every live tokened post, so "expected" is the last token main observed, which can be strictly older than the one being replayed. An agent launched over SSH that loses contact before its first live post has its whole spool discarded as stale — including its terminal status, so nothing ever repairs the row.3. The same replay fence read against a tokenless poster. Found by review of the fix for gate 2, reproduced before it was changed. Supplying gate 2 with the pane's current generation at spawn time is correct, but it also arms an expectation on panes that never had one — and every shell-side poster emits
"launchToken":"${ORCA_AGENT_LAUNCH_TOKEN:-}", so a process that never received the variable reports an empty token, not an absent one.launchTokenHash('')isnull,null !== <hash>, and the fence returned. Before this PR such a pane had no expectation at all — both pre-existing writers (recordCurrentAuthorityObservationand disk hydration) require a token — so its spool landed unconditionally. Reproduced with a differential probe against the realAgentHookServer: with the spawn notification, the tokenless replay leaves the rowundefined; without it, the same replay lands. The fix is the read side of the rule the write side already argues — a record carrying no token is not evidence about any generation, so it is admitted rather than rejected as the wrong one. Every rejection that names a real, different token is untouched.Which way each fence fails
Both fail closed and silently: an early
return, no telemetry, no user-visible signal, and no decay. Neither states anything about the pane's process. That is correct and preserved — retirement and this fence are authorship claims, not liveness verdicts, and nothing here assertslive/unverifiable/exitedabout a process or lets a boolean stand in for one.RetiredPaneSurfaceRegistry's own doc comment makes the same commitment on the relay side.The fix, at the source
Deliberately no exemption to either gate; matching #17257's sibling commit "Mint the token there: it is the contract every token-keyed gate depends on."
isSessionStartEvent(source, eventName)inprovider-event-routing.ts, besideisNewTurnEvent. Exhaustive switch, so a newAgentHookSourcefails typecheck instead of silently joining the half that can never re-fence. NotisNewTurnEvent: a turn boundary recurs inside one process and therefore cannot order two processes sharing a pane. Each name is taken from the provider's own normalizer —kimiwas the one exception (its names are Claude-compatible, butnormalizeKimiEventhas noSessionStartcase andKIMI_HOOK_EVENTSnever subscribes to one, so the branch was unreachable on every path) and it now returnsfalsewith a tripwire in the listener characterization suite that reddens the moment kimi gains one.cursorkeeps its name:normalizeCursorEventdoes mapsessionStart, so a hand-written hook reaches the gate even thoughCURSOR_EVENTSdeliberately does not subscribe to it.agentHookServer.noteAgentPaneLaunchToken(paneKey, launchToken), called fromspawn-commit.tsthrough a pureresolveSpawnedPaneLaunchTokenhelper. Gemini, Antigravity, mimo-code, omp and Command Code emit no session boundary at all, so no event can ever prove a new process owns their pane — main mints the tokens, so main reports them. This also supplies gate 2 with the pane's current generation instead of its last-observed one.else { delete }to the tokenless arm reddens 1; dropping the.has()guard so the status fence arms unconditionally reddens 2. The second half was previously asserted only in prose and reddened nothing.cursor) or never normalizes (kimi); scoping that suite to the no-boundary bucket left those two covered only by an event production never sends.The other five token gates
Of the files naming
ORCA_AGENT_LAUNCH_TOKEN, the ones where the token's value or presence changes an outcome, beyond the two above:unmanaged-status-extension-fence.ts— was wrong the same way; already fixed on the parent stack. Verified here that its provisional hold is wired on both the local HTTP and the remote relay ingress (releaseIfUnconfirmedat both call sites), so a held remote post is released rather than dropped.orca-runtime.ts: the runtime launch mints a token only when alaunchConfigis present (launchOpts.launchConfig ? (launchOpts.launchToken ?? randomUUID()) : undefined). Every other launch runs untokened and each token-keyed gate quietly drops to its fail-open path. Worth promoting: it is the reason "tokenless" is a normal state rather than an edge case, and it is why the tokenless arm ofnoteAgentPaneLaunchTokenclears the fence rather than leaving one nothing can satisfy.wsl-orca-env.ts: the token reaches a WSL guest only via theWSLENVpassthrough list, and nothing asserts the guest received it. A distro that drops it makes every guest hook post tokenless with no signal.hook-stdin-contract.ts: the spool writer emits"launchToken":""when the env var is unset, so "this process has no token" and "the token was lost in transit" are the same bytes on disk. Those last two are exactly the population gate 3 was discarding: the same ambiguity that makes them degraded is what made reading an empty token as the wrong generation a data-loss bug rather than a strictness choice.The remaining readers (
liveness.ts,spawn-env.ts,local-pty-launch-helpers.ts,spawn-environment.ts,remote-cli-env.ts,ssh-remote-cli-host-passthrough.ts) are scrub or passthrough lists, not gates.Both worlds, and the wire
Under the pre-#17257 leak, a relay started from an Orca pane pushed its own launch token into every pane it spawned, so a wrong-but-present token satisfied gate 1 and made gate 2's mismatch look like ordinary staleness. That masked both defects rather than causing them — the strand needs only a token change, which a legitimate respawn produces on its own. With identity correct, both are plainly reachable, and gate 1's tokenless arm becomes ordinary rather than exotic.
Wire compatibility. No wire change: no new field, no new stream opcode, no change to what the host publishes. Combinations reasoned about: new client + old relay — the relay omits
source, so the classifier falls through to the pre-existingSessionStartliteral, which is exactly today's behaviour; new client + new relay — the classifier applies; old client + new relay — untouched, both gates are main-side only. The spawn notification is a main-process call, so it works identically for local, WSL and SSH panes and depends on no patched module reaching a relay.Verification
pnpm tc— exit 0,0×error TS, run in the foreground. Proven non-vacuous by plantingconst wlPlanted: number = actualLaunchTokenHash→ exit 1 with 2 ×error TS(TS2322, TS6133); restored → exit 0.src/main/agent-hooks+src/shared/agent-hook-listener: 92 files / 998 passed, 6 skipped, 0 failed.src/main/agent-hooks+src/shared/agent-hook-listener+src/main/ipc/pty: 157 files / 1636 passed, 12 skipped, 0 failed.oxlint --deny-warningson every changed file: exit 0, stdout retained and empty (so no config failure was smuggled onto stdout). Proven live by plantingconst wlAny: any = paneKey→ exit 1 withtypescript(no-explicit-any)printed to stdout.oxfmt --check: all formatted. Gates run directly, not through the changed-code quality gate.Ablations — re-measured on this head, serial, one mutation at a time, each verified applied before the run (one mutation silently failed to apply and was caught by that check, not by its red count), tree asserted clean between runs. Scope: the three changed spec files plus
src/shared/agent-hook-listener*, baseline 251/251 green across 18 files.SessionStartliteralnoteAgentPaneLaunchToken's status-fence block deletednoteAgentPaneLaunchToken's replay-generation line deletedresolveSpawnedPaneLaunchToken's reattach guard deletedspawn-commit.tscall deletedcursor+ampzeroed in the classifierelse { delete }).has()guard dropped)normalizeKimiEventtaught aSessionStartcaseThe first ablation reddens exactly 7 sources × 2 cases — amp, cursor, pi, prime-agent, grok, copilot, hermes — and leaves
claude/codex/droid/devin/opencodegreen, because those five genuinely do spell itSessionStart. That is the positive control that the matrix is measuring the classifier and not the branch.kimiused to sit in the green half and its green was vacuous: it was filed as aSessionStartsource, so the ablation could not distinguish it, and it never reached the spawn path that actually rescues it. The last row is that branch's replacement tripwire, and it reddens.Gate 3 was reproduced before it was fixed: a probe with the spawn notification left the row
undefined, the same probe without it landed the spool. The reverted-fix ablation reddens exactly the two tests that pin it and leaves "still discards a replay from the generation that spawn replaced" green, so the fix narrows the rejection to wrong-generation replays and does not loosen it further.The second of those two names the shape a real pane reaches it by:
orca-runtime.tsmints a launch token only when alaunchConfigis present, so an ordinary relaunch into an already-tokened pane is untokened — its posts and its spool carry no token while the first launch's expectation still stands, and that expectation is deliberately never cleared by a tokenless launch. Verified host-independent:src/relay/wsl-agent-hook-relay.tsconstructs the sameRelayAgentHookServerthat drains and replays the spool as the SSH relay does, so both remote topologies reach this fence through identical code.