Skip to content

fix(agent-status): let never-ending background shells release a finished turn - #15041

Closed
marwie0904 wants to merge 1 commit into
stablyai:mainfrom
marwie0904:fix/background-shell-agent-status
Closed

marwie0904 wants to merge 1 commit into
stablyai:mainfrom
marwie0904:fix/background-shell-agent-status

Conversation

@marwie0904

@marwie0904 marwie0904 commented Aug 17, 2026 •

Copy link
Copy Markdown

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 dev no longer holds the spinner, while a script whose output the agent still needs does.

What Changed

Claude's Stop hook payload carries background_tasks. Orca counts any running non-agent entry as work in flight and forces the pane from done back to working, 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:

  • 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. dev matches npm run dev but not ./dev-check.sh.

Off by default. Settings → Experimental → Ignore background shells enables 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.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 — the setting is simply a no-op for that host until it updates. (The existing agent.hook envelope could not carry this: its claudeRunningNonAgentTask field is already the shell-OR-cron result, and payload.state has collapsed "lead still working" into the same working.)

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:

Background shell (dev server) Shell the agent waits on
Before 🟡 spinner, stuck indefinitely 🟡 spinner
After ⚪️ done 🟡 spinner (unchanged)

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.

Before: dev server running, pane stuck working

2. Before — probe.sh the agent is explicitly waiting on, pane spinning. Correct, and unchanged by this PR.

Before: dependent script running, pane working

3. After — same dev server still running (shell details: npm run dev, 38s), pane now idle. The fix.

After: dev server running, pane idle

4. After — dev server and a dependent probe.sh in the same session ("2 shells still running"), pane correctly stays working. The classification discriminating, not just suppressing.

After: dependent script running, pane still working

Testing

Manually tested on macOS with Claude Code v2.1.233, driving both cases in a real worktree: a npm run dev background 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.sh must not match dev), 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 — the inferInterrupt relaxation, including that an unrelated pattern does not retire the pane and a session cron still blocks it.

pnpm lint, pnpm typecheck, pnpm test, and pnpm build all pass locally. Full suite: 52,902 passing; the only failures are 4 pre-existing date-dependent cases in src/main/rate-limits/codex-fetcher-pty-settle.test.ts, which fail identically on a clean checkout.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Not covered: Windows/WSL and SSH were reasoned about and plumbed (the setStatusPolicy RPC 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

  • Security: no new trust boundary. The pattern list is user settings; the relay re-normalizes it on receipt (bounded length/count) the same way ingestRemote re-validates payloads.
  • Cross-platform: no platform-specific code paths; matching is plain string tokenization.
  • Remote SSH / WSL: new RPC is additive and version-tolerant (-32601 → previous behavior). No stream opcode, no envelope shape change, so no capability negotiation needed per docs/reference/remote-wire-compatibility.md.
  • Backwards compatibility: default off; with the setting off, behavior is byte-identical to today. Existing tests asserting the sticky behavior all still pass unchanged.
  • Performance: one Set build per running task per hook event, bounded at 100 patterns and a 4 KB command scan.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • 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)

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

coderabbitai Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 43.75% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR satisfies the background-shell portion of issue [#14253] while explicitly preserving active status for background subagents and session cron tasks.
Out of Scope Changes check ✅ Passed The settings, status-policy propagation, relay support, localization, and tests directly support the background-shell status objective.
Description check ✅ Passed The description explains the problem, solution, scope, linked issue, visual proof, testing, AI use, compatibility, and checklist items.
Title check ✅ Passed The title clearly and concisely describes the primary fix: finished turns can release despite never-ending background shells.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 77ef6bb and 5907f8b.

📒 Files selected for processing (21)
  • src/main/agent-hooks/server-interrupt-inference-guards.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/agent-hooks/wsl-hook-relay-manager.ts
  • src/main/index.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/agent-hook-server.ts
  • src/relay/relay.ts
  • src/relay/wsl-agent-hook-relay.ts
  • src/renderer/src/components/settings/BackgroundShellStatusExperimentalSetting.tsx
  • src/renderer/src/components/settings/ExperimentalPane.tsx
  • src/renderer/src/components/settings/background-shell-status-search-entry.ts
  • src/renderer/src/components/settings/experimental-search.ts
  • src/renderer/src/i18n/locales/en.json
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-hook-relay.ts
  • src/shared/claude-background-shell-patterns.test.ts
  • src/shared/claude-background-shell-patterns.ts
  • src/shared/claude-background-task-inventory.ts
  • src/shared/claude-background-task-status.test.ts
  • src/shared/constants.ts
  • src/shared/global-settings-types.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 9 remain after this review.

Comment on lines 315 to +318
void mux.request(AGENT_HOOK_REQUEST_REPLAY_METHOD).catch(() => {
// Fresh relays have nothing to replay; tolerate.
})
this.sendAgentHookStatusPolicy(mux)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Comment on lines +1471 to +1483
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.
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Suggested change
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)
}`
)
})
}

Comment on lines +194 to +200
export function setClaudeBackgroundShellIgnorePatterns(
state: HookListenerState,
patterns: readonly string[]
): void {
state.claudeBackgroundShellIgnorePatterns = patterns
if (patterns.length > 0) {
state.claudeRunningNonAgentTaskPaneKeys.clear()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment on lines +65 to +67
return patterns.some((pattern) =>
pattern.includes(' ') ? normalized.includes(pattern) : tokens.has(pattern)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

marwie0904 added a commit to marwie0904/orca that referenced this pull request Aug 17, 2026
marwie0904 added a commit to marwie0904/orca that referenced this pull request Aug 17, 2026
marwie0904 added a commit to marwie0904/orca that referenced this pull request Aug 17, 2026
marwie0904 added a commit to marwie0904/orca that referenced this pull request Aug 17, 2026
@nwparker nwparker removed the P1 label Aug 19, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor

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 working while a dev server runs is not one bug with two possible fixes — it is two correct complaints in tension. #11838 (merged) made background work hold working because settling to done while Claude's footer says 1 shell still running is wrong (#10997). STA-4119 says holding working after the lead turn ends is also wrong, because nobody is waiting and the completion notification never fires. Both are true, which is why each either/or fix reverts the other. We closed our own PR (#15189) for exactly that reason — it settled to done and re-opened #10997.

The resolution is a third state rather than a better rule for choosing between two. #14205 adds an optional workingMode: 'monitoring': the turn reads as finished, the spinner stops, and the pane still shows that background work is alive.

On the classifier specifically. The allowlist works on the commands it knows. Our concern is the ones it cannot know: ./scripts/dev.sh, make watch, a Procfile runner, pnpm start in a repo where that means a server, or any project-local wrapper. Those fall through to today's sticky behavior, so the reported symptom survives for anyone not using the listed tools — and "does this command have a natural exit" is not knowable from its name. The third-state approach needs no such judgement, which is the deciding factor rather than any defect in the implementation here.

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.

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.

[Bug]: Claude pane stays "working" and the finish notification never fires when the session holds a background shell/subagent (e.g. a dev server)

4 participants