Skip to content

fix(agent-status): stop reconnect replay re-arming a stale working row (STA-4144) - #14610

Closed
brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/claude-stuck-loading-4144
Closed

brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/claude-stuck-loading-4144

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

ELI5

When Orca reconnects to an agent host, the host re-sends ("replays") the last status it had for each pane. Orca was treating that re-send as if it were brand-new news that just happened. So a pane that had finished long ago came back looking busy again, and the "it's been quiet for 30 minutes, stop the spinner" safety net kept getting reset. Every reconnect restarted the clock, so the spinner never stopped.

What Changed

In applyNormalizedStatus, a replayed event that carries the same state we already have cached now keeps the cached receivedAt instead of being stamped with the current time.

A replay carrying a new state still gets live timing — that path is how a client learns about a completion it missed while disconnected, so it must stay fresh.

One-line behavioral diff; 10 lines with the comment.

Why

attachStatusTiming deliberately preserves stateStartedAt when the state is unchanged, but unconditionally sets receivedAt = now:

const stateStartedAt =
  previous && previous.payload.state === payload.payload.state && !commandCodeNewTurn
    ? previous.stateStartedAt   // preserved
    : now
return { ...payload, receivedAt: now, stateStartedAt }   // always advanced

receivedAt becomes the renderer's updatedAt (useIpcEvents.ts → setAgentStatus), which is the only input to the staleness gate:

// pane-agent-evidence.ts
return entry.restoredUnconfirmed !== true && now - entry.updatedAt <= staleAfterMs

Stale working rows are supposed to decay to idle in worktree-agent-rows.ts:236. That decay is the only recovery when a terminating hook is lost — and a lost Stop is exactly what a sleep, an app restart, or a relay drop produces.

So the failure is: turn ends while disconnected → Stop never arrives → row frozen at working → reconnect replays the cached working → receivedAt jumps to now, stateStartedAt stays put → row is "fresh working" again, showing an hours-old age → decay can never fire, and every subsequent reconnect re-arms it.

That reproduces the reported artifact exactly: an amber spinner with tool detail (Bash: pnpm run typecheck…, which only renders when state === 'working') next to an age of 6h.

isReplay already rides the envelope through ingestRemote and was consulted for interrupt-suppression and claudeRunningNonAgentTask, but never for timing.

Which reconnects hit this

The replay must land while the cached entry still exists, so stateStartedAt survives:

  • WSL relay — wsl-hook-relay-manager.ts:295 requests a replay on every (re)connect and never clears cached statuses first (no clearStatusEntriesForConnection in that manager at all).
  • Host-side relay restart — relay.ts → replayCachedPayloadsForPanes() replays while the client session stays up, so the client never tore down.

The local setListener replay (server.ts:640) was already safe: it re-emits enriched payloads with their original receivedAt.

Linked Issue

Linear STA-4144 — "Claude code stuck in loading after work completes" (Urgent, In Progress).
Duplicates: STA-3532, STA-3522 (both Urgent, screenshot-only reports of the same symptom).
Related: STA-3524 (reconnect replays are not idempotent — same root, notification-side symptom).

No GitHub issue exists for this one; it came in via Slack.

Fixes #

Visual Proof

Not captured — stating this plainly rather than approximating it. The stuck state needs a lost Stop plus a relay reconnect, which I could not stage live inside this worktree without disrupting the running desktop session.

The "before" artifact is the reporter's screenshot on STA-4144: sidebar row Fix issues - Bash: pnpm run typecheck > /tm… showing the amber working spinner at age 6h, while the pane's TUI is plainly idle (❯ prompt, recap printed). That combination is only reachable with a fresh updatedAt and an old stateStartedAt, which is the state this PR makes unreachable for replays.

The behavior is pinned by a deterministic test on real state transitions instead (below).

Testing

New: src/main/agent-hooks/reconnect-replay-status-freshness.test.ts — drives the real AgentHookServer through ingestRemote (no mocking of the logic under test) and asserts on the real cached row via getStatusSnapshot(), gated by the shared isFreshNonDoneAgentStatus predicate the UI actually uses.

Red/green oracle — with the fix reverted, case 1 fails on the real symptom:

AssertionError: expected 1700001860000 to be 1700000000000
  ❯ expect(row.updatedAt).toBe(T0)

i.e. the replay pushed updatedAt forward 31 minutes. The other two cases pass without the fix (they assert preserved behavior, so they are guards, not filler):

  1. replayed unchanged working past the stale window stays stale → decays to idle (fails without the fix)
  2. a replay carrying done still applies with live timing — the missed-completion path
  3. a live same-state working ping still refreshes freshness, and still reports stateStartedAt as the state's start

Scoped checks run (per instruction, no full typecheck):

  • vitest src/main/agent-hooks/ → 40 files, 615 passed, 4 skipped
  • vitest src/relay/agent-hook-server.test.ts src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts → 25 passed
  • tsc --noEmit -p config/tsconfig.node.json --composite false → clean
  • oxlint + oxfmt --check on both changed files → clean

Platforms: logic is platform-independent and sits in the shared ingest path. The two reconnect paths it fixes are WSL (Windows) and SSH/remote relay; exercised through the integration suites above, not on live Windows/SSH hosts.

Investigated and ruled out

Recorded so the next person doesn't re-walk these:

  • Backgrounded Bash leaving an unbalanced hook pair — disproved on real Claude Code 2.1.227 with a hook recorder: run_in_background yields PreToolUse → PostToolUse 0.11s apart, then Stop. Perfectly balanced, no late tool event.
  • Replay resetting the clock via the local path — disproved by reading setListener; it preserves receivedAt.
  • Renderer burst-queue coalescing (perf(renderer): publish agent status bursts once #13974) dropping the terminal done — real but separate: teardown at useIpcEvents.ts clears liveAgentStatusBurstQueue without draining, so a done sitting in the 33ms window is discarded on effect teardown. Narrow, and not the reported mechanism. Not touched here.

Known remaining gap (not fixed here)

When a reconnect does clear first — the SSH path calls clearStatusEntriesForConnection on teardown — the replay recreates the row with both receivedAt and stateStartedAt set to now. The pane then shows a working spinner aged "now" for 30 minutes even if the agent finished long ago. Closing that needs the original observation time carried on the replay envelope (a new optional wire field, safe per docs/reference/remote-wire-compatibility.md). Deliberately out of scope to keep this focused.

Review

  • Security — none; no new input, no trust-boundary change.
  • Cross-platform — no platform branch; fixes a WSL-only reconnect path and a shared relay path.
  • Remote SSH — the changed path is remote ingest. No wire change, so mixed client/host versions are unaffected: the fix is entirely client-side over a field (isReplay) that already crosses the wire.
  • Mobile — reads the same status rows; strictly fewer spurious working rows.
  • Backwards compatibility — no persisted-format or wire change.
  • Performance — one comparison per ingested event.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes — not captured; reasoned above
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • Scoped lint / typecheck / tests pass locally (full typecheck skipped per instruction — OOM risk)

Author

  • X / Twitter: @BrennanKB5

…w (STA-4144)

A reconnect replay re-delivers a status this client already holds, but
applyNormalizedStatus stamped it receivedAt = now while attachStatusTiming
kept the cached stateStartedAt. A pane whose Stop was lost (sleep, app
restart, relay drop) therefore came back "working" with a fresh freshness
clock and an hours-old displayed age, and every reconnect re-armed it — so
the 30-minute stale-decay safety net could never fire.

Preserve the cached receivedAt when a replay carries the same state. A
replay carrying a NEW state is real news (it can be the completion this
client missed) and keeps live timing.

Refs STA-3532, STA-3522 (duplicates), STA-3524.
@coderabbitai

coderabbitai Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@brennanb2025, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 24 minutes

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 90017c1a-f7ff-46ec-9197-02e2bc2c3946

📥 Commits

Reviewing files that changed from the base of the PR and between 9bb8836 and 4afc232.

📒 Files selected for processing (2)
  • src/main/agent-hooks/reconnect-replay-status-freshness.test.ts
  • src/main/agent-hooks/server.ts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing this. The mechanism it describes is real — I re-verified that a same-state relay replay still re-arms receivedAt on current main, and the test in this PR goes red when the fix is reverted. But it is not the mechanism STA-4144's evidence shows, and the fix has the wrong shape.

It cannot execute on the reported pane

isReplay: true only reaches applyNormalizedStatus through ingestRemote — SSH/WSL relay ingest. The local replay path (server.ts:743-757) hands cached enriched payloads straight to the listener and already preserves receivedAt, which this PR's body notes.

The pane in the STA-4144 screenshot is a local worktree — its card carries no host chip, and the transcript references a locally-installed toolchain. So this change is inert on the pane it was written for.

What the evidence actually shows

The pane footer reads Baked for 5m 17s · 1 shell still running. A running non-agent entry in background_tasks sets claudeRunningNonAgentTaskPaneKeys, and resolveClaudePaneState (agent-hook-listener.ts:2596-2611) rewrites the finished turn's done back to working on that flag alone. That gate is refreshed only on a lead-turn boundary, and it fails active on anything it cannot parse — so a shell that ends without waking the agent pins the pane at working. That is STA-4119, not a lost Stop.

The 6h in the row is not a stuck stateStartedAt. getCompactAgentTime falls back to stateHistory[0].startedAt when the pane has no completion — it is the session's age. The turn ran 5m 17s, as the footer says. The premise that "a fresh receivedAt next to an hours-old stateStartedAt" produced that row does not hold.

Two measured regressions

Both are probes against a real AgentHookServer via ingestRemote. Both pass on main and fail on this branch rebased onto main.

F1 — an actively working remote agent decays to idle. isReplay means "this frame is a re-send," not "the observation behind it is as old as your cached copy." The host keeps observing while the client is away, so a same-state replay routinely carries newer evidence. Probe: client sees PreToolUse(Bash, "pnpm build"), disconnects 45 min while the agent never stops working, reconnects, host replays its current cache — PreToolUse(Edit, "src/index.ts"), five seconds old. The tool name visibly advanced, so this is demonstrably not a re-send of what the client held. This PR back-stamps it with the client's 45-minute-old receivedAt; it fails isExplicitAgentStatusFresh and worktree-agent-rows.ts:237-241 rewrites the row to idle.

main:            PASS  (row renders working — correct)
this PR rebased: FAIL  (expected true to be false)

That trades a false-positive spinner on a finished agent for a false-negative idle on a live one, with no signal that can distinguish them — and >30-minute disconnects during a long turn are exactly the sleep/lid-close case this targets.

F2 — a new Command Code turn is back-dated. The preserved value is passed as attachStatusTiming's now parameter, which is also the stateStartedAt fallback (server.ts:1190-1198). The guard here is previous.state === incoming.state, but isCommandCodeNewTurnWhileWorking fires precisely on a same-state working → working transition with a new prompt or promptInteractionKey.

main:            stateStartedAt = reconnectAt  (correct)
this PR rebased: stateStartedAt = T0           (previous turn's timestamp)

stateStartedAt is a turn identity — completion-notification dedupe, unread marking (useActivityUnreadCount.ts:71, WorktreeCardAgents.tsx:98), finishedAt patching, and paired-client ranking all key on it. So the diff is not confined to receivedAt.

The better fix is the one this PR already identified

Under "Known remaining gap": carry the host's original observation time on the replay envelope, as an additive optional field. That answers the question the staleness gate is actually asking — how old is this evidence — and fixes F1 by construction. Better still, STA-4612's liveness join makes the whole class unrepresentable rather than reconciling timestamps after the fact. Tracking it there.

Relationship to #14635

Checked by cherry-pick rather than by reading bodies: #14635 rebases cleanly onto main, and cherry-picking this PR on top of rebased #14635 produces a conflict hunk byte-identical to the one against main alone (its HEAD side contains nothing from #14635). There is no collision, so closing this neither helps nor harms #14635. That PR stands on its own ticket and its own mechanism.

STA-4144 stays open

Closing this PR does not fix the reported bug. The evidence is being re-homed onto STA-4119, with the durable fix in STA-4612. Leaving the branch in place.

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