Repository navigation
fix(agent-status): keep the turn identity a disconnect clear removed (STA-3524) - #14635
brennanb2025 wants to merge 1 commit into
Conversation
…(STA-3524) An SSH teardown calls clearStatusEntriesForConnection, deleting every row the connection owned. The reconnect replay then re-ingests each cached status with no `previous` entry, so attachStatusTiming mints a fresh stateStartedAt. That timestamp is the completion-notification dedupe key, so the finished turn looks brand new and the task-complete notification fires again on every flap. Keep the deleted row's turn identity until the pane's next status. A replay that re-delivers the same connection/state/agentType/prompt reclaims its stateStartedAt; anything else -- a live event, another host, or a completion that landed while disconnected -- keeps live timing. receivedAt still advances so the row sorts after the clear watermark. Fixes #12747
|
Warning Review limit reached
Next review available in: 43 seconds You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Acknowledged — #12998 is now closed in favor of this PR. Keeping the turn identity across the disconnect clear is the right layer. The renderer |
Review statusState: What the review loop established. The renderer already has the right dedupe — The loop also rejected the obvious alternative with reasons, not preference. Gating on I confirmed the implementation shape in the diff: a Validation — this one is genuinely strong, with two caveats that belong hereLive rig: a throwaway Result — 12 induced relay drops, both arms:
Pre-fix, Caveat 1 — the agent binary was substituted. The container has Caveat 2 — counting happens at the One result that reads like a miss and is not: an earlier arm carried a stale pane over from a previous app run and fired one notification on that pane's first replay. That is the intended "a completion first seen on the replay still notifies" path, not a leaked duplicate — the pane was not live at cold start so observation was skipped, and the first live replay was the coordinator's first sight of that turn. Its Automated: two new suites. The main-side one drives the real Not done: full #14610 has been CLOSED since this body was written — the coordination note is staleThe body states #14610 is "still Supersedes
Both correctly identified where the notification fires. This PR fixes why the row looked new, rather than gating the observation. Wire / compat: no wire change, no IPC change, no renderer change in the fix itself. The tombstone is in-memory only and never serialized to Given the branch is 177 commits behind |
|
Thank you @brennanb2025. The client-side clear-on-disconnect this patched is no longer called: agent status is now owned by the execution host's store and readers subscribe to it, so a reconnect no longer replays a cleared turn as new. Closing as no longer applicable; please reopen if duplicate completion notifications still appear after reconnects. |
ELI5
When Orca loses an SSH connection it throws away everything it knew about the agents on that host. On reconnect the host re-sends ("replays") what it had. Orca had no memory of the turn it just threw away, so a job that finished an hour ago looked like it had just finished — and Orca announced it again. Every reconnect, another "Claude finished" notification. During a flapping connection, dozens in a few minutes.
This PR makes Orca remember the identity of the turn it cleared, just long enough for the replay to arrive, so it recognizes the re-sent status as the same turn instead of a new one.
What Changed
src/main/agent-hooks/server.ts:clearStatusEntriesForConnectionnow stashes the turn identity of each row it deletes —connectionId,state,agentType,prompt,stateStartedAt.attachStatusTimingconsults that stash when there is no cachedpreviousrow. If the incoming event is a replay from the same connection carrying the same state / agentType / prompt, it reclaims the originalstateStartedAt. Anything else keeps live timing.deleteStatusEntrywithoutpreserveAuthority,dropStatusEntriesByTabPrefix,clearPaneState), alongside the existingpromptSentDedupeByPaneKeyper-pane cache it now mirrors.receivedAtis deliberately not restored — it must keep advancing past the disconnect's clear watermark, or the renderer'stransientClearWatermarkguard drops the replayed row as a resurrected pre-disconnect status.No wire change, no IPC change, no renderer change.
Why
The renderer already has the right dedupe.
agent-completion-coordinator.tskeys completion notifications on a turn identity:and checks it twice — once against the live coordinator's
lastCompletionIdentity, once against the module-scopedlastCompletionIdentityByPaneKeythat outlives a coordinator remount. A repeateddonefor the same turn is supposed to be silent.The defect is that the key gets re-minted, not that the dedupe is missing:
ssh-relay-session.ts:1612—connection_lostteardown callsagentHookServer.clearStatusEntriesForConnection(targetId), whichdeleteStatusEntrys every row that connection owned.agent_hook.requestReplay; the host re-forwards its cache withisReplay: true.applyNormalizedStatus→attachStatusTimingfinds noprevious(step 1 deleted it), so it falls tostateStartedAt = now.done:claude:<old>becomesdone:claude:<now>. Both dedupe checks miss.dispatchCompletionfires.So the fix belongs where the identity is minted, not at a new bypass downstream.
Why not "skip notifications for replayed statuses"
That is what the two PRs below do — plumb
isReplayintoAgentStatusIpcPayloadand adddata.isReplay !== trueto the notification guard inuseIpcEvents.ts:3281. It suppresses the reported symptom, but that guard fences off the whole ofobserveAgentHookCompletionForNotification, not just the duplicate:dispatchAttentionforwaiting/ permission states. A replay is exactly how a client re-learns that an agent is blocked on the user after a flap; skipping observation means no "Needs You" — the inverse failure tracked as [Bug] No Notification When Agent Requires User Input #14426.dispatchHookLifecycleis skipped, which the notifications module explicitly wants to keep running independent of notification preferences ("accepted hooks must still release pane-owned cursor/cache effects after the quiet window").workingleavesworkingStatusObservedfalse and never clearspaneKeysRequiringFreshWorking, which can silently swallow the next real completion.stateStartedAtin place, so every other consumer of it stays wrong:WorktreeCardAgents.tsx:98anduseActivityUnreadCount.ts:71(ackAt < entry.stateStartedAt) re-mark the row unread on each reconnect;dashboard-agent-status-patch.ts:49re-stampsfinishedAt;web-session-tabs-sync.ts:1211lets a replayeddoneoutrank a newer clientworking;isMirroredCommandCodeTurnBumpreads it as a new Command Code turn.Restoring the identity fixes all of those at once and reuses the dedupe that already exists.
Relationship to #14610 (STA-4144)
Complementary, non-overlapping, and this PR closes the gap #14610 documented as out of scope.
previousstill exists, sostateStartedAtwas already preserved and the notification never re-fired; its bug wasreceivedAtbeing re-armed. It preservesreceivedAtfor a same-state replay.connection_lost). Therepreviousis gone, sostateStartedAtis re-minted — the notification bug. fix(agent-status): stop reconnect replay re-arming a stale working row (STA-4144) #14610's PR body names this exact case under "Known remaining gap (not fixed here)".They touch neighbouring lines of the same two functions but different branches: #14610 acts when
previousexists, this acts when it does not. #14610 argued the gap needed "a new optional wire field"; a client-side tombstone closes it with no wire change. Either can merge first; whichever lands second will need a trivial textual rebase inattachStatusTiming/applyNormalizedStatus, no logic conflict.Re-verified against both PRs as they stand today rather than asserted from memory: #14610 is still
OPENandCONFLICTING/DIRTYagainstmain, and touchessrc/main/agent-hooks/server.ts(+10/−1) plus one new test. Its hunk sits inapplyNormalizedStatusat ~line 1276, passingreplayPreservedReceivedAt ?? nowintoattachStatusTiming; this PR's nearest hunk ends insideattachStatusTimingat ~line 1102 — about 174 lines apart, no textual overlap. The branches are mutually exclusive: #14610 requirespreviousto exist, this PR's reclaim requires!previous, in which caseprevious?.receivedAtisundefinedandreceivedAtstays live. Either can merge first.Supersedes
isReplaythrough the IPC payload + renderer notification skip. Also addsisReplaytotoAgentStatusIpcPayload, which leaks the flag intogetStatusSnapshot()and the persisted last-status cache, so a pane whose last row happened to arrive as a replay stays marked replayed indefinitely.isReplayfield is not onAgentStatusIpcPayloadtoday, which is the observation the issue was filed on).Both correctly identified where the notification fires. This PR fixes why the row looked new instead of gating the observation.
Linked Issue
Fixes #12747
Linear STA-3524.
Visual Proof
No UI change, and the user-visible difference is the absence of a duplicate OS notification — which a single screenshot cannot show. So the proof is a count across repeated relay drops against a live SSH host, run in both directions.
Live rig
Throwaway
ubuntu:22.04Docker container as the SSH target (linux-arm64, key-only root login, node 22.14.0,build-essential+python3— required or node-pty will not compile on the host and remote PTYs never come up — a real git repo at/work/demo-project, andclaude2.1.233 onPATHso Orca's remote hook detector fires). The client was this worktree running as an isolated Electron dev instance (ownORCA_DEV_USER_DATA_PATH, own CDP port,getIdentity()re-verified before every interaction batch,repos: []on first attach confirming a genuinely fresh profile), connected through the realssh.connectpath. Orca installed its real managed hook on the remote —/root/.orca/agent-hooks/claude-hook.shplusSessionStart/UserPromptSubmit/Stopentries in/root/.claude/settings.json.The relay drop is the exact
connection_lostpath this PR is about: kill only the relay's--connectbridge inside the container by resolved numeric PID, leaving the detached relay daemon (which owns the cache that gets replayed) alive. That gives mux transport close →teardownProviders('connection_lost')→clearStatusEntriesForConnection→ auto-reconnect →agent_hook.requestReplay→ host re-forwards withisReplay: true.Result
Before the fix (
src/main/agent-hooks/server.tsreverted to its pre-PR state; the running main bundle verified to contain zero occurrences ofclearedStatusTimingByPaneKey):stateStartedAtwas re-minted on every replay —1786947531919 → 1786947619673 → … → 1786947736801— which is precisely the re-minted identity this PR describes.After the fix (same rig, same container, single pane, fresh profile):
Every cycle asserted (a) the client answered CDP before and after and (b) the remote relay logged a fresh
Socket client accepted, so no cycle is vacuous — the relay logged 13 accepts total (1 initial + 12 reconnects). This mirrors the 12-cycle unit test at the real wire.receivedAtstill advancesFinal row after the 12 drops:
Identity reclaimed,
receivedAtdeliberately not restored. Visible in the UI too: the sidebar agent row still reads3mold instead of resetting to "just now" on each reconnect.Two honest caveats
The agent binary was substituted. The container has
claudeinstalled but no credentials. So the turn was driven by invoking Orca's own installed managed hook script from inside the real remote pane with a real ClaudeUserPromptSubmitthenStoppayload on stdin — the same call the agent process makes. Everything downstream of that script is production code: hook script → relay hook server on127.0.0.1:$ORCA_AGENT_HOOK_PORT→agent.hooknotification over the relay →SshRelaySession.ingestRemote→applyNormalizedStatus/attachStatusTiming→ renderer completion coordinator →notifications:dispatch. The pane's genuinely injected env confirms the wiring (ORCA_AGENT_HOOK_PORT/_TOKEN/_ENV/_VERSION,ORCA_PANE_KEY,ORCA_TAB_ID,ORCA_WORKTREE_ID,ORCA_TERMINAL_HANDLE). Only the process that would have invoked the hook was simulated.That substitution was subsequently shown to be immaterial.
UserPromptSubmit/Stoppayloads were captured from a real authenticated Claude 2.1.233 — the same version the container had — and differentiated against the payloads this rig actually injected, both arms driven through productionnormalizeHookPayload(the relay's own/hook/claudecall) and the realAgentHookServerclear/replay, with the prompt text held identical so the arms differed only in payload shape:replayReclaimsClearedTurncompares —state,prompt,agentType— are byte-identical.lastAssistantMessageandproviderSession, appear in neither the tombstone predicate nor the completion identitystate:agentType:stateStartedAt.Stopcarries nopromptfield at all.resolvePromptrecovers it from the per-panelastPromptByPaneKeycache seeded byUserPromptSubmit, so thedonerow still carries the true prompt — asserted as equal to the actual text on both arms, not merely equal to each other, since empty-on-both would satisfy the predicate vacuously.isReplay(stateStartedAtre-minted to equalreceivedAt, advance 0 ms) and 1 with (advance 715,999 ms) — the same 13-vs-1 and the same shape as the live +161,665 ms.This differential is offline and single-process: it does not cross the relay wire and it is not the
notifications:dispatchmeasurement. It does not replace the live run above, and it is not a claim that the binary was un-substituted — it establishes that the payloads the live run injected were not a fiction.Why the substitution was not simply removed. Re-running with a genuinely authenticated Claude was attempted and is blocked on this machine: every
claudehere authenticates throughANTHROPIC_AUTH_TOKEN+ANTHROPIC_BASE_URLset in theenvblock of~/.claude/settings.json, so the OAuth file credentials rot unused —~/.claude/.credentials.jsonhas both its access and refresh tokens past expiry, and it answers401 OAuth access token has been revoked. Confirmed from inside a throwaway container with both credential files copied in and noANTHROPIC_*in its environment:Failed to authenticate: OAuth session expired and could not be refreshed. Worth knowing before rebuilding this rig.Counting happens at the
notifications:dispatchIPC handler, not at the OS banner. macOS refuses banners for an isolated dev bundle — the authorization read returnsdenied, sodeliverNativeNotification()is never reached in either arm.notifications:dispatchis the call that becomes the banner; the only gates past it are the 5 s per-worktree cooldown, focus suppression (disabled for the run), and authorization — all worktree-global and identical in both arms, and the cycles were spaced well beyond the cooldown. So the 13-vs-1 comparison is unaffected.One result that looks like a miss and is not
An earlier post-fix arm carried a stale pane over from a previous app run and produced one extra notification on that pane's first replay. That is the intended
a completion first seen on the replay still notifiespath (cases 2 and 4 below), not a leaked duplicate: at cold start the pane was not live yet so observation was skipped, and the first live replay was the coordinator's first sight of that turn. ItsstateStartedAtwas not re-minted (1786947736801preserved), and the remaining 11 cycles were silent. The 12/12 figures quoted above come from a clean single-pane profile so the number is unambiguous.Testing
New —
src/main/agent-hooks/reconnect-clear-replay-turn-identity.test.ts(7 cases). Drives the realAgentHookServerthroughingestRemote/clearStatusEntriesForConnectionand asserts on the realgetStatusSnapshot()row, using the samestate:agentType:stateStartedAtkey the renderer dedupes on.Red/green oracle — with the fix reverted (
git stash push -- src/main/agent-hooks/server.ts):The other six pass without the fix — they are guards on behavior that must NOT change:
receivedAtstill advances (fails without the fix)donefirst seen on the replay mints a new identity — the missed-completion path still notifiesNew —
src/renderer/src/components/terminal-pane/agent-completion-reconnect-replay.test.ts(5 cases). Drives the realcreateAgentCompletionCoordinatorand countsdispatchCompletioncalls, pinning why the identity matters:stateStartedAtfires a second notification (the pre-fix behavior, asserted explicitly)Both guard directions verified load-bearing by deleting the
connectionIdcomparison from the predicate and confirming case 4 fails.Scoped checks (full typecheck skipped per instruction — OOM risk):
vitest src/main/agent-hooks/ src/relay/agent-hook-server.test.ts src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts→ 42 files, 644 passed, 4 skippedvitest src/renderer/src/components/terminal-pane/agent-completion* src/renderer/src/hooks/agent-hook-completion-notifications.test.ts src/renderer/src/hooks/useIpcEvents.test.ts src/renderer/src/runtime/web-session-tabs-sync*→ 11 files, 359 passedtsc --noEmit -p config/tsconfig.node.json --composite false→ cleantsc --noEmit -p config/tsconfig.web.json --composite false→ cleancheck-changed-code-quality.mjs -- origin/main→ 0 findings across 3 changed files (all three scans)oxlint+oxfmt --checkon changed files → cleanPlatforms: no platform branch. The path it fixes is the SSH relay reconnect, covered by the integration suites above and exercised live — macOS client → Linux SSH remote — under Visual Proof.
Review
isReplay, which already crosses the wire.donenow carries its truestateStartedAt, so it stops re-marking rows unread (useActivityUnreadCount.ts:71) and stops outranking newer client state inweb-session-tabs-sync.ts.last-status.json.Checklist
N/Awith reasonAuthor