Repository navigation
fix(agent-status): let never-ending background shells release a finished turn - #15041
marwie0904 wants to merge 1 commit into
Conversation
…hed turn Claude's Stop hook carries `background_tasks`, and Orca counts any running non-agent entry as work in flight, forcing the pane from `done` back to `working`. A dev server or watcher the agent started and walked away from therefore pins the spinner indefinitely and the completion notification never fires (stablyai#14253). Classify the shell instead of assuming it. A command with no natural exit condition (`npm run dev`, `tsc --watch`, `uvicorn --reload`) no longer holds the turn; anything else — a test script or build whose result the agent may still be waiting on — keeps today's sticky behavior. Matching is an allowlist of whole-word command tokens, so an unrecognized command fails toward the visible spinner rather than a silently idle agent. Off by default. Settings -> Experimental -> "Ignore background shells" enables it and exposes the editable pattern list. Filtering happens where the task inventory is read, so the pane gate, Esc / Ctrl-C interrupt inference and the relay envelope all follow from one decision. The sibling gates are deliberately untouched: a working subagent roster or an active session cron still holds the pane at `working`. SSH and WSL relays normalize hooks themselves and own no settings store, so the pattern list ships to them over a new `agent_hook.setStatusPolicy` RPC, pushed at hook wire-up and on every later change. A relay predating the handler answers -32601 and keeps the pre-setting behavior. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
📝 WalkthroughWalkthroughAdds configurable Claude background-shell ignore patterns and experimental settings controls. Normalized token and phrase matching now affects background-task status evaluation. The resolved policy updates local hook listeners and propagates through WSL, SSH, and remote relays. Relays retain and replay the policy across connections. Tests cover matching, normalization, settings resolution, task status, cache updates, and Escape interrupt inference. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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 |
There was a problem hiding this comment.
Actionable comments posted: 5
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1162cef0-9b41-4b25-b397-0f1405af451c
📒 Files selected for processing (21)
src/main/agent-hooks/server-interrupt-inference-guards.test.tssrc/main/agent-hooks/server.tssrc/main/agent-hooks/wsl-hook-relay-manager.tssrc/main/index.tssrc/main/ssh/ssh-relay-session.tssrc/relay/agent-hook-server.tssrc/relay/relay.tssrc/relay/wsl-agent-hook-relay.tssrc/renderer/src/components/settings/BackgroundShellStatusExperimentalSetting.tsxsrc/renderer/src/components/settings/ExperimentalPane.tsxsrc/renderer/src/components/settings/background-shell-status-search-entry.tssrc/renderer/src/components/settings/experimental-search.tssrc/renderer/src/i18n/locales/en.jsonsrc/shared/agent-hook-listener.tssrc/shared/agent-hook-relay.tssrc/shared/claude-background-shell-patterns.test.tssrc/shared/claude-background-shell-patterns.tssrc/shared/claude-background-task-inventory.tssrc/shared/claude-background-task-status.test.tssrc/shared/constants.tssrc/shared/global-settings-types.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 9 remain after this review.
| void mux.request(AGENT_HOOK_REQUEST_REPLAY_METHOD).catch(() => { | ||
| // Fresh relays have nothing to replay; tolerate. | ||
| }) | ||
| this.sendAgentHookStatusPolicy(mux) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Apply the policy before cache replay.
Line 315 replays cached statuses before Line 318 sends the current policy. The guest can replay a working status calculated with the default policy. setStatusPolicy does not recompute or forward cached statuses, so the host can retain that stale status until another hook arrives.
Send and await agent_hook.setStatusPolicy before agent_hook.requestReplay. Continue with replay when an older guest rejects the method.
| private sendAgentHookStatusPolicy(mux: SshChannelMultiplexer): void { | ||
| const store = this.store as { getSettings?: Store['getSettings'] } | ||
| void mux | ||
| .request(AGENT_HOOK_SET_STATUS_POLICY_METHOD, { | ||
| backgroundShellIgnorePatterns: resolveClaudeBackgroundShellIgnorePatterns( | ||
| store.getSettings?.() | ||
| ) | ||
| }) | ||
| .catch(() => { | ||
| // Why: a relay predating the handler answers -32601 and keeps the pre-setting behavior. | ||
| }) | ||
| } | ||
|
|
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Do not swallow all status-policy request failures.
Line [1479] treats every rejection as an old-relay compatibility case. A timeout, protocol error, or remote handler failure can leave the relay with stale backgroundShellIgnorePatterns and provide no diagnostic.
Suppress only expected errors such as -32601, CONNECTION_LOST, and DISPOSED. Log or retry other failures, as installPluginsOnRelay already does.
Handle only expected compatibility failures
- .catch(() => {
- // Why: a relay predating the handler answers -32601 and keeps the pre-setting behavior.
+ .catch((error) => {
+ const code = (error as { code?: unknown })?.code
+ if (code === -32601 || code === 'CONNECTION_LOST' || code === 'DISPOSED') {
+ return
+ }
+ if (mux.isDisposed()) {
+ return
+ }
+ console.warn(
+ `[ssh-relay-session] agent_hook.setStatusPolicy failed for ${this.targetId}: ${
+ error instanceof Error ? error.message : String(error)
+ }`
+ )
})📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| private sendAgentHookStatusPolicy(mux: SshChannelMultiplexer): void { | |
| const store = this.store as { getSettings?: Store['getSettings'] } | |
| void mux | |
| .request(AGENT_HOOK_SET_STATUS_POLICY_METHOD, { | |
| backgroundShellIgnorePatterns: resolveClaudeBackgroundShellIgnorePatterns( | |
| store.getSettings?.() | |
| ) | |
| }) | |
| .catch(() => { | |
| // Why: a relay predating the handler answers -32601 and keeps the pre-setting behavior. | |
| }) | |
| } | |
| private sendAgentHookStatusPolicy(mux: SshChannelMultiplexer): void { | |
| const store = this.store as { getSettings?: Store['getSettings'] } | |
| void mux | |
| .request(AGENT_HOOK_SET_STATUS_POLICY_METHOD, { | |
| backgroundShellIgnorePatterns: resolveClaudeBackgroundShellIgnorePatterns( | |
| store.getSettings?.() | |
| ) | |
| }) | |
| .catch((error) => { | |
| const code = (error as { code?: unknown })?.code | |
| if (code === -32601 || code === 'CONNECTION_LOST' || code === 'DISPOSED') { | |
| return | |
| } | |
| if (mux.isDisposed()) { | |
| return | |
| } | |
| console.warn( | |
| `[ssh-relay-session] agent_hook.setStatusPolicy failed for ${this.targetId}: ${ | |
| error instanceof Error ? error.message : String(error) | |
| }` | |
| ) | |
| }) | |
| } |
| export function setClaudeBackgroundShellIgnorePatterns( | ||
| state: HookListenerState, | ||
| patterns: readonly string[] | ||
| ): void { | ||
| state.claudeBackgroundShellIgnorePatterns = patterns | ||
| if (patterns.length > 0) { | ||
| state.claudeRunningNonAgentTaskPaneKeys.clear() |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Do not clear task evidence for unrelated commands.
Line 200 clears every pane when any non-empty pattern list is applied. A pane held by ./scripts/api-smoke.sh loses its active-task guard when the user adds dev. inferInterrupt can then mark that pane done although its shell still runs.
Retain per-pane command inventory and re-evaluate it against the new policy. If that state is unavailable, retain the existing guard until a fresh authoritative inventory arrives. Add a policy-update test with an already pinned unmatched command.
| 'caddy', | ||
| 'mongod', | ||
| 'redis-server', | ||
| 'tail', |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Replace the bare tail pattern.
tail file terminates after it reads the file. With this default enabled, it can release the agent status before the command result is available. Use tail -f instead, while retaining --follow for long-form usage.
| return patterns.some((pattern) => | ||
| pattern.includes(' ') ? normalized.includes(pattern) : tokens.has(pattern) | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Match phrase patterns as complete token sequences.
normalized.includes(pattern) matches partial final tokens. For example, npm run dev:check matches a configured npm run dev pattern. That can incorrectly ignore a finite command. Compare normalized phrase tokens against contiguous command tokens, and add this regression case.
…ne-still-working)
|
Thanks for this — the diagnosis is right, and it named a real problem that three separate efforts have now converged on. Closing it in favour of #14205, and it is worth being precise about why, because it is not that this is broken. Where we landed. The pane holding The resolution is a third state rather than a better rule for choosing between two. #14205 adds an optional On the classifier specifically. The allowlist works on the commands it knows. Our concern is the ones it cannot know: What we kept from your framing. The distinction you drew — a dev server nobody is waiting on versus a build whose result the agent still needs — is the correct user-facing insight, and it is what the monitoring state expresses without having to guess which one a command is. Not deleting the branch. If #14205 stalls, the classifier is a reasonable fallback for the subset it can identify confidently, and we would come back to it. |
ELI5
When Claude starts a dev server and then finishes talking to you, Orca kept showing the agent as still "working" forever — because something was technically still running. But a dev server never stops on its own; nobody is waiting for it. This teaches Orca to tell those apart: a
npm run devno longer holds the spinner, while a script whose output the agent still needs does.What Changed
Claude's
Stophook payload carriesbackground_tasks. Orca counts any running non-agent entry as work in flight and forces the pane fromdoneback toworking, so a dev server or watcher the agent started and walked away from pins the spinner indefinitely and the completion notification never fires.This classifies the shell instead of assuming it:
npm run dev,tsc --watch,uvicorn --reload) no longer holds the turn.Matching is an allowlist of whole-word command tokens, so an unrecognized command fails toward the visible spinner rather than a silently idle agent.
devmatchesnpm run devbut not./dev-check.sh.Off by default.
Settings → Experimental → Ignore background shellsenables it and exposes the editable pattern list (17 built-in defaults, "Restore defaults" button).The filtering happens where the task inventory is read (
readClaudeBackgroundAgentTasks), so the pane gate, Esc/Ctrl-C interrupt inference, and the relay envelope all follow from one decision rather than three copies of it.Deliberately unchanged: a working subagent roster or an active session cron still holds the pane at
working. Only the shell gate relaxes.Remote: SSH and WSL relays normalize hooks themselves and own no settings store, so the pattern list ships to them over a new
agent_hook.setStatusPolicyRPC, pushed at hook wire-up and on every later change. A relay predating the handler answers-32601and keeps the pre-setting behavior — the setting is simply a no-op for that host until it updates. (The existingagent.hookenvelope could not carry this: itsclaudeRunningNonAgentTaskfield is already the shell-OR-cron result, andpayload.statehas collapsed "lead still working" into the sameworking.)Why
Reported in #14253: a session that ends its turn while holding a background shell stays "working" forever, with no completion notification. Starting a dev server is extremely common agent behavior, so this hits many normal sessions.
The alternative — a simple on/off switch that ignores all running shells — was the first cut, but it can't tell a dev server from a test script the agent backgrounded and is genuinely waiting on. Classifying by command keeps the useful signal while dropping the noisy one, and the allowlist direction means the failure mode is "a spinner I didn't want" (visible, fixable by adding a line) rather than "my agent silently went idle while I was waiting on it".
Linked Issue
Partially fixes #14253
That issue describes both a background shell and a background subagent holding the pane. This PR addresses the shell half only — a running subagent is real agent work and still legitimately holds
working, so the issue stays open for that half.Visual Proof
Sidebar status dot, dev server (
npm run dev) still running in both cases:The "after" case for the dependent shell is the important one: with a dev server and a 60s script the agent depends on running in the same session, the pane correctly stays
working— the ignore is selective, not blanket.1. Before — dev server (
npm run dev) still running, pane stuck spinning. The bug.2. Before —
probe.shthe agent is explicitly waiting on, pane spinning. Correct, and unchanged by this PR.3. After — same dev server still running (shell details:
npm run dev, 38s), pane now idle. The fix.4. After — dev server and a dependent
probe.shin the same session ("2 shells still running"), pane correctly stays working. The classification discriminating, not just suppressing.Testing
Manually tested on macOS with Claude Code v2.1.233, driving both cases in a real worktree: a
npm run devbackground shell (pane goes idle at turn end) and a 60-second script the agent explicitly waits on (pane stays working). Verified the settings toggle, the editable pattern list, blur-commit, and "Restore defaults".Automated:
src/shared/claude-background-shell-patterns.test.ts(new) — classification across ecosystems, whole-token matching (./dev-check.shmust not matchdev), normalization/dedupe/bounds.src/shared/claude-background-task-status.test.ts— a listed command releases the turn; an unlisted one holds it; any unlisted task among several holds it; a working subagent roster and an active session cron still hold it; malformed/untyped entries still fail active.src/main/agent-hooks/server-interrupt-inference-guards.test.ts— theinferInterruptrelaxation, including that an unrelated pattern does not retire the pane and a session cron still blocks it.pnpm lint,pnpm typecheck,pnpm test, andpnpm buildall pass locally. Full suite: 52,902 passing; the only failures are 4 pre-existing date-dependent cases insrc/main/rate-limits/codex-fetcher-pty-settle.test.ts, which fail identically on a clean checkout.Not covered: Windows/WSL and SSH were reasoned about and plumbed (the
setStatusPolicyRPC is wired for both relays) but not manually exercised — I don't have those hosts. The relay handler degrades to a no-op on older relays, so the risk is "setting doesn't apply yet", not breakage.AI Disclosure
Implemented with Claude Opus 5 (Claude Code), reviewed and manually tested by the author.
Review
ingestRemotere-validates payloads.-32601→ previous behavior). No stream opcode, no envelope shape change, so no capability negotiation needed perdocs/reference/remote-wire-compatibility.md.Setbuild per running task per hook event, bounded at 100 patterns and a 4 KB command scan.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)