Skip to content

Show foreground Claude Code commands and subagents as foreground work - #5650

Merged
ymichael merged 2 commits into
mainfrom
bb/fix-bb-issue-5641-thr_42mg9ub4ge
Oct 16, 2026
Merged

ymichael merged 2 commits into
mainfrom
bb/fix-bb-issue-5641-thr_42mg9ub4ge

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Claude Code sends a task_started message for long-running foreground work as well as background work, and marks which one it is with is_backgrounded. BB ignored that flag (#5641):

  • Every local_bash task became a backgroundTask item. A blocking foreground Bash command showed a "Background command" card above the composer and an extra "Running background command" row in the timeline. The thread looked like it had handed the command off, but a steer waited until the command finished.
  • Foreground subagents (local_agent with is_backgrounded: false) are kept as task items on purpose, because the delegation row reads their progress. Nothing recorded that they were foreground, though. The composer card said "Running background agent", and the thread activity counts included them.

What changed

Foreground Bash commands (plugins/provider-claude-code/src/task-translation.ts)

  • A local_bash task that starts with is_backgrounded: false is tracked but not materialized. It stays a normal running command.
  • If a later task_updated reports patch.is_backgrounded: true, the bridge opens the backgroundTask item then, and the usual completion closes it.

Foreground subagents

  • backgroundTask items carry a new foreground flag. The Claude Code bridge sets it from task_started.is_backgrounded and clears it on task_updated.patch.is_backgrounded.
  • The composer's running-task card (selectActiveBackgroundCommandMessages) and the activity count query (listActiveBackgroundTaskCountsByThreadIds) skip foreground tasks. The timeline row is unchanged, since the delegation row already hid these task items.

Wire and storage

  • Bridge delta shape: foreground is optional and the assembler fills false, so third-party bridges keep validating. The provider-bridge grammar stays v2; the v2 snapshot gains the optional field.
  • Stored and domain item: foreground is required. Rows stored before this change read as false (convertLegacyStoredThreadEvent), and the count query treats a missing value the same way.
  • HOST_DAEMON_PROTOCOL_VERSION 239 → 240, plugin SDK 0.6.54.
  • The Claude subagent replay lane (bridge→runtime.current.ndjson) gains only "foreground":true. That recording is a foreground subagent.

Not in this PR, from the issue's expected behavior:

  • a composer hint that a steer waits for a running foreground command and that Stop cancels it;
  • a control to move a running foreground command to the background. The SDK supports this through Query.backgroundTasks(toolUseId), and with this PR its result would display correctly.

How you verified

  • New tests, each of which fails without its fix:
    • provider: a foreground Bash command produces no task items; a foreground command moved to the background materializes and completes; a foreground subagent carries foreground: true until task_updated moves it.
    • thread-view: a foreground agent stays out of activeBackgroundCommands until a progress event clears foreground.
    • db: a foreground agent is excluded from the counts, and a pre-flag stored row is still counted.
    • domain: pre-flag stored rows read as foreground: false for item/started and the background-task progress/completed events.
  • Live SDK probe (Claude Agent SDK 0.3.245): a plain foreground sleep 8; echo done sends task_started with is_backgrounded: false and task_type: "local_bash", then task_notification.
  • Dev instance (pnpm start:worktree) with three Claude Code threads; the recorded events and thread list activity match:
    • a foreground 2-minute command records only a commandExecution item, with zero background counts;
    • a foreground subagent's task item records foreground: true, with activeBackgroundAgentCount: 0;
    • a run_in_background command records foreground: false, with activeBackgroundCommandCount: 1.
  • pnpm exec turbo run typecheck lint --filter='...[origin/main]' passes.
  • turbo run test passes for @bb/domain, @bb/db, @bb/provider-bridge-protocol, @bb/thread-view, @bb/agent-runtime, @bb/provider-parity, @bb/host-daemon-contract, @bb/server, @bb/app and bb-plugin-provider-claude-code.

Refs #5641

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 2 commits October 16, 2026 16:00
Claude Code sends task_started for long foreground Bash calls too, with
is_backgrounded: false. BB materialized every local_bash task as a
backgroundTask, so a blocking command looked like background work and
the thread seemed free to answer a steer.

Track foreground command tasks without materializing them, and open the
backgroundTask item only when task_updated moves the command to the
background.

Refs #5641

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude Code sends task_started for foreground subagents too, with
is_backgrounded: false. BB kept those task items (the delegation row
reads its progress from them) but could not tell them apart from
background agents, so the composer card said "Running background agent"
and the thread activity counts included them while the main agent was
blocked on the subagent.

Background task items now carry foreground. The Claude Code bridge sets
it from task_started.is_backgrounded and clears it when task_updated
moves the task to the background. The composer card and the activity
counts skip foreground tasks.

- Bridge delta: optional foreground, filled as false by the assembler,
  so the provider-bridge grammar stays v2.
- Stored items: required foreground; rows stored before this read as
  false, and the activity count query treats a missing value the same.
- HOST_DAEMON_PROTOCOL_VERSION 239 -> 240, plugin SDK 0.6.54.
- Claude subagent replay lane gains only the new field.

Refs #5641

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 6d11205 into main Oct 16, 2026
88 of 89 checks passed
@ymichael
ymichael deleted the bb/fix-bb-issue-5641-thr_42mg9ub4ge branch October 16, 2026 23:15
alexandre-vl added a commit to alexandre-vl/bb that referenced this pull request Oct 22, 2026
An item stored before get-bb#5650 has no foreground field. The settle paths
parsed stored rows with the current item schema alone, so they skipped
such a row as an unparsable payload, a thread stop included, and its
task stayed running forever while the running-task query, which reads a
missing flag as false, kept counting it. Every reader of stored events
first runs convertLegacyStoredThreadEvent, which adds the flag; the
settle paths now do the same, with the row's event type. The settle log
line is written only when a task was settled.
ymichael added a commit that referenced this pull request Nov 2, 2026
)

## Human comments

## What was wrong

When a host daemon reconnects, session open reports only which threads
are active
([`hostDaemonSessionOpenRequestSchema`](https://github.com/get-bb/bb/blob/c2365296a4503675fc721752a55f794db5e89b61/packages/host-daemon-contract/src/session.ts#L38-L40),
[`activeThreads`](https://github.com/get-bb/bb/blob/c2365296a4503675fc721752a55f794db5e89b61/packages/host-daemon-contract/src/session.ts#L168-L169)).
Nothing compares the daemon's open work with the server's. Background
tasks are settled only when a *new* daemon instance opens a session
([session-owner-side-effects.ts#L108-L122](https://github.com/get-bb/bb/blob/c2365296a4503675fc721752a55f794db5e89b61/apps/server/src/internal/session-owner-side-effects.ts#L108-L122)).
If the same instance reconnects after a task's provider process died,
the task stays "Running" (#6123). Nothing ends a provider's wait on a
question the server closed. A failed live `interactive.resolve`, for
example `host_unavailable` when the socket drops mid-delivery,
interrupts the interaction
([pending-interactions.ts#L829-L837](https://github.com/get-bb/bb/blob/c2365296a4503675fc721752a55f794db5e89b61/apps/server/src/services/interactions/pending-interactions.ts#L829-L837)).
The daemon's
[`InteractiveRequestRegistry`](https://github.com/get-bb/bb/blob/c2365296a4503675fc721752a55f794db5e89b61/apps/host-daemon/src/interactive-request-registry.ts#L106-L210)
keeps waiting, and
[`onSessionOpened`](https://github.com/get-bb/bb/blob/c2365296a4503675fc721752a55f794db5e89b61/apps/host-daemon/src/app.ts#L910-L946)
never looks at open waits. The turn stays active, and later messages are
accepted as steers that never run (#6251).

This ports the question and background-task sync out of #6552. It leaves
out #6552's input ledger, turn-start deadline and every stop-related
change.

## What changed

- **Wire, `HOST_DAEMON_PROTOCOL_VERSION` 258 → 259:**
- Session open sends `openThreadWork`: per thread, the open background
item ids and the provider questions the daemon still waits on, including
registrations in flight.
  - The session-open response returns `endedInteractiveRequests`.
  - New server→daemon message `interactive-requests.end`.
- **Server, `open-work-reconciliation.ts` (runs on every session
open):**
  - settles background tasks the daemon no longer runs;
  - interrupts pending questions it no longer waits on;
- re-sends saved answers it still waits on, and marks the other
in-flight answers resolved;
  - returns the questions it waits on that the server already closed.
- Threads whose buffered events are still replaying are skipped, except
that answers are still re-sent for them.
- **Server, `PendingInteractionLifecycle`:**
- An answer whose delivery fails with `host_unavailable` stays
`resolving` and is re-sent when the daemon's socket opens.
- A `stale_interactive_request` reply to a re-sent answer marks it
resolved instead of interrupting it.
- Bulk thread interrupts no longer discard `resolving` provider answers.
- Interrupting a provider question sends `interactive-requests.end` to
the connected daemon. Inside a transaction the send waits until after
commit.
  - A question registered for a turn that already ended is rejected.
- **Daemon:**
- reports open work from the runtime (`listOpenBackgroundWork`) and the
registry (`listOpenRequests`);
- ends waits named by `endedInteractiveRequests` or
`interactive-requests.end`;
- an ended registration still in flight no longer raises an unhandled
rejection.

**Visible behaviour changes:**
- After a reconnect, a question the server closed no longer leaves the
thread stuck `active`. The provider's turn ends, and the next message
starts a new turn.
- An answer sent while the connection drops is delivered once the daemon
is back, instead of the question turning "interrupted".
- A background task whose provider process died is shown as stopped once
the same daemon reconnects, instead of "Running" forever.

**#6123 is only partly fixed.** Tasks settle when the daemon comes back
as the same instance (a restarted daemon already settled them on main).
Settling tasks when the machine goes away, at shutdown or suspension, is
left to #6124. So is settling rows stored without the `foreground` field
(written before #5650), which the reconnect settle still skips.

## How you verified

New tests; each fails on main and passes here:
- `tests/integration/fake/recovery/reconnect-open-work.test.ts` (real
server, daemon and scripted-echo bridge):
- **#6251 shape:** while the daemon's socket is down, the server
interrupts a pending `ask_user` question, and the same instance
reconnects. The provider's wait ends and a later message runs. On main
the thread stays `active`.
- **#6123 shape:** the bridge that owns a `bg_task` is `SIGKILL`ed while
the daemon stays up, then the same instance reconnects. The task settles
as interrupted/stopped. On main it stays open.
- `apps/server/test/services/pending-interactions.test.ts`:
  - keeps, interrupts or ends questions according to the report;
  - an answer cut off by a socket drop is re-sent and resolves;
- a saved answer is re-sent while buffered events replay, and again when
a slow socket opens;
  - a stale reply to a re-sent answer resolves it;
  - a lost ack resolves the answer;
  - a question for an ended turn is rejected.
- `apps/server/test/internal/background-task-reconciliation.test.ts`:
the same instance settles a task it no longer runs, and keeps one it
still reports or whose events are still buffered.
- Daemon: `interactive-request-registry.test.ts`,
`server-connection.test.ts` and `app.test.ts` (the reconnect reports the
open question, and the server ends it).

Graceful shutdown and machine suspension followed by the daemon's return
already settle tasks on main (checked with an integration probe), so I
added no test for them.

Commands:
- `pnpm exec turbo run typecheck lint --filter='...[origin/main]'`
- `pnpm exec turbo run test --filter=@bb/server --filter=@bb/host-daemon
--filter=@bb/host-daemon-contract --filter=@bb/db
--filter=@bb/agent-runtime --filter=@bb/integration-tests`

Fixes #6251

🤖 Generated with [Claude Code](https://claude.com/claude-code)

> AGENT GENERATED

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 4, 2026
…at owns them stops (#6124)

## Human comments

## What was wrong

Only the process that owns a background task settles it. The provider
CLI owns it and reports through the bridge, the runtime and the daemon.
When that owner stopped, nothing settled the task:
- When a bridge process exited, the runtime dropped its threads' open
work without a word.
- Runtime shutdown cleared that state before it killed the provider
processes.
- When the Claude SDK stream ended, the bridge left the translator's
tasks open.

The only fallback was the server's settle for a new daemon instance. It
runs once the daemon comes back, so a task stayed "Running", with
`activeBackgroundCommandCount` at 1, for as long as the daemon stayed
down. It also skipped any task stored before #5650, logging `Skipping
dangling background task with unparsable item payload`, because those
items have no `foreground` field. See #6123.

## What changed

Whoever owns a task's state now settles the tasks it drops:

- `packages/agent-runtime`:
- `RuntimeBackgroundWorkState` keeps each open task's latest item
instead of only its id.
- When a bridge process exits, the runtime emits
`item/backgroundTask/completed` (`interrupted` / `stopped`, thread
scope) for every task still open on that bridge's threads.
- The runtime does the same on shutdown, after the provider processes
stop. The daemon flushes its event sink after
`runtimeManager.shutdownAll()` and before the connection closes, so a
graceful daemon shutdown (including a machine suspension) delivers these
settlements.
- It skips threads whose events are suppressed (rewind staging) and
tasks the provider already settled.
- `plugins/provider-claude-code`: when the SDK stream ends (the CLI
exited or was killed), the bridge settles the translator's open tasks.
The existing error path still settles the turn.
- `apps/server`:
- The settle paths read stored items through
`convertLegacyStoredThreadEvent`, like every other reader of stored
events, so tasks stored before #5650 settle too. `packages/db` now
returns each open-task row's event type for that upgrade.
- Each settle logs `Settled background tasks left open on the host` with
its reason: `host-daemon-restarted`, `host-connection-lost`,
`host-removed` or `host-daemon-no-longer-runs-task` (#6870's reconnect
reconcile). The line is written only when something settled.
- `Session opened` logs both instance ids, so the log shows whether the
new-instance settle ran.
- `docs/provider-bridge-protocol.md`: rule 5 now says what the runtime
settles on a bridge's behalf.

This was rebased onto main after #6870, #6923 and #6955, and keeps
main's session-open flow and reconnect reconcile. Compared with the
earlier revision, it drops:
- the server-side settle at machine suspension and its
`machine.shutdown-ack` tracking, since a suspension shuts the daemon
down gracefully and the runtime now settles first;
- the shared `stoppedBackgroundTaskItem` in `@bb/domain`, which is now
local to the runtime.

No wire change: the daemon emits an existing event type that the server
already accepts, so `HOST_DAEMON_PROTOCOL_VERSION` is unchanged. Two
cases are still not covered:
- A daemon that is SIGKILLed or loses power relies on the server's
settle for a new daemon instance.
- When Claude Code dies, the shell command it started (for example
`sleep`) keeps running. bb now shows the task as stopped, but it doesn't
kill that process.

## How you verified

Live, on `pnpm start:worktree` with real Claude Code threads, I ran each
case on main first and then on this branch:

| Case | main | this branch |
| --- | --- | --- |
| SIGKILL the provider bridge (literal PID) | task stays open,
`activeBackgroundCommandCount` 1, still open after another turn | all
three of the bridge's threads settled in the same second |
| SIGKILL the Claude Code CLI (SDK stream ends) | task stays open, count
1 | settled in the same second |
| Daemon SIGTERM while its launcher is SIGSTOPped, so it stays down like
a suspended machine | still "Running" after 70 s; settles only when a
new daemon instance connects | settled in the same second the session
closed; no duplicate after the daemon came back |
| Task stored before #5650 (`foreground` removed from the row), then the
daemon restarted | `Skipping dangling background task with unparsable
item payload` | settled with `foreground: false` |

Tests:
- `packages/agent-runtime`: "settles an idle thread's open background
task when its provider process dies", "settles open background tasks
when the runtime shuts down" and "does not settle a background task its
provider already settled" in `runtime.process-lifecycle.test.ts`. There
are also unit tests for `settleThread` and `settleAll`.
- `plugins/provider-claude-code`: "settles a background command when the
Claude SDK stream ends under it".
- `apps/server`: "settles a task stored before items carried the
foreground flag".
- `tests/integration/fake/recovery/reconnect-open-work.test.ts`: #6870's
test asserted that a task stayed open after its bridge was SIGKILLed
until the same daemon reconnected, which is the gap this PR closes. It
now asserts the task settles when the bridge dies and that the reconnect
reconcile adds no second completion.
- `tests/integration/fake/recovery/background-task-shutdown.test.ts`:
"records an idle thread's open background task as stopped when the
daemon shuts down" (real server, real daemon, scripted-echo bridge).

Commands:
- `turbo run typecheck lint` on the touched packages passes.
- Targeted `turbo run test` passes:
  - agent-runtime: 44 tests (both runtime files);
  - provider-claude-code: 107 (bridge tests);
  - apps/server: 22 (`background-task-reconciliation.test.ts`);
- integration: 3 (`background-task-shutdown.test.ts`,
`reconnect-open-work.test.ts`).

Fixes #6123

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Michael Yong <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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