Skip to content

Keep Claude child threads active while subagents run - #633

Merged
SawyerHood merged 1 commit into
mainfrom
bb/worker-spawned-task-deadlock-thr_38mn6xhh6d
Jul 12, 2026
Merged

SawyerHood merged 1 commit into
mainfrom
bb/worker-spawned-task-deadlock-thr_38mn6xhh6d

Conversation

@SawyerHood

Copy link
Copy Markdown
Collaborator

Summary

  • keep a logical Claude turn open across successful SDK-loop results while bounded background agents or workflows are still running
  • leave detached shell commands and ambient tasks non-blocking, and preserve immediate failure completion
  • cover native agents, legacy subagents, workflows, synthetic no-response messages, and reinvocation ordering

Tests

  • pnpm exec turbo run test --filter=@bb/agent-runtime --force
  • pnpm exec turbo run typecheck --filter=@bb/agent-runtime
  • pnpm exec turbo run test typecheck --filter=@bb/agent-runtime

@SawyerHood
SawyerHood merged commit 6124af8 into main Jul 12, 2026
10 checks passed
@SawyerHood
SawyerHood deleted the bb/worker-spawned-task-deadlock-thr_38mn6xhh6d branch July 12, 2026 18:10
SawyerHood added a commit that referenced this pull request Jul 22, 2026
## Summary

A native Claude workflow (`local_workflow`) was treated as
completion-blocking by `hasCompletionBlockingClaudeTasks`, so the
logical bb turn stayed open for the workflow's entire run. That kept the
thread `active`, and `shouldQueueFollowUpMessage` queues on `active` —
so typing during a workflow queued the message instead of sending it.
Introduced in #633, which added the predicate for background agents and
folded workflows in alongside them.

Workflows now let the turn complete and the thread go idle. Background
agents and legacy subagents still block, unchanged. When the workflow
settles and reinvokes the parent model, that work opens a fresh turn.

**The busy status disappears with no UI change.** `displayStatus`
derives from `thread.status` plus host connectivity only — background
activity never feeds it. So once the turn completes, the thread-row
indicator falls through from the generic "Thread working" spinner to the
specific "Workflow running" glyph, while the timeline pill and the
composer workflow cards keep rendering off background-task activity. All
three workflow indicators survive; only the busy status goes.

Two consequences handled here:

- **Parent notification.** A child thread can now report an outcome
while its workflow is still running, so the notification says so
(`@thread:x completed, with 2 workflows still running:`) and tells the
parent to expect a second report rather than reading the excerpt as
final. The count is captured at queue time, the same instant as the
output excerpt.
- **Runtime eviction.** With the turn closed, the thread no longer sits
in the runtime's active set, so `evictIdleRuntimeEntries` could shut a
runtime down mid-workflow and SIGTERM the provider process running it.
`AgentRuntime` now tracks open background tasks from the event stream it
already observes and exposes `hasOpenBackgroundWork()`, which
`entryHasActiveRuntimeWork` counts as active work. This also fixes the
pre-existing case of a backgrounded dev server being killed by a
shell-env change.

`HOST_DAEMON_PROTOCOL_VERSION` 63 → 64 so enrolled daemons pick up the
new turn timing. The wire shape is unchanged, so an older daemon keeps
the old blocking behavior rather than entering an `invalid-message`
loop.

## Notes

- `RuntimeBackgroundWorkState` observes the normalized event stream
rather than plumbing the adapter's `hasOpenClaudeBackgroundTasks` up
through `AgentRuntime` — the adapter's copy is buried in a per-provider
turn-state registry reachable only by the LRU pruner, and reading events
keeps this provider-agnostic.
- Ambient (`skipTranscript`) tasks **do** count for eviction. #633
excluded them from turn completion because they're long-lived, but
hiding a task from the transcript doesn't make it survive a SIGTERM.
This matches the adapter's existing `isEvictable`.

## Tests

- `pnpm exec turbo run typecheck test --filter=@bb/agent-runtime` — 794
passed
- `pnpm exec turbo run typecheck test --filter=@bb/host-daemon` — 467
passed
- `pnpm exec turbo run typecheck test --filter=@bb/server` — 1249 passed
- `pnpm exec turbo run typecheck test --filter=@bb/app
--filter=@bb/thread-view` — passed

New coverage:
- the turn completes while a workflow stays open, leaving the task
pending
- a settled workflow's reinvocation opens a fresh turn (`turn-2`) and
completes it
- `RuntimeBackgroundWorkState` across multi-task settling,
terminal-status-via-progress, ambient tasks, and per-thread clearing
- an entry with open background work survives `replaceBaseShellEnv`,
then evicts once the work settles — **verified to fail without the fix**

One pre-existing local failure unrelated to this change:
`internal-skill-trees.test.ts` expects file mode `420` and gets `436`
(umask artifact); it fails identically on a clean tree.

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

Co-authored-by: Claude <[email protected]>
patleeman added a commit to patleeman/bb that referenced this pull request Oct 17, 2026
Claude Code keeps a logical turn open while background agents or workflows
run (get-bb#633), so the thread stayed active and a normal Enter
(queue-if-active) waited as thread-busy until every background task
finished, even though the main run was idle.

The Claude Code bridge now sends a turn.mainRun delta when it holds the
turn after the SDK result (idle) and when the next main run starts
(running). The assembler records it as turn/mainRun/updated. While the
active turn's main run is idle, dispatch delivers queue-if-active messages
into the held turn as steers, and thread-busy rows drain when the main run
goes idle. The thread still shows as running, and the turn still does not
complete until background work finishes. Bumps
HOST_DAEMON_PROTOCOL_VERSION to 242 for the new thread event.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
patleeman added a commit to patleeman/bb that referenced this pull request Oct 19, 2026
Claude Code keeps a logical turn open while background agents or workflows
run (get-bb#633), so the thread stayed active and a normal Enter
(queue-if-active) waited as thread-busy until every background task
finished, even though the main run was idle.

The Claude Code bridge now sends a turn.mainRun delta when it holds the
turn after the SDK result (idle) and when the next main run starts
(running). The assembler records it as turn/mainRun/updated. While the
active turn's main run is idle, dispatch delivers queue-if-active messages
into the held turn as steers, and thread-busy rows drain when the main run
goes idle. The thread still shows as running, and the turn still does not
complete until background work finishes. Bumps
HOST_DAEMON_PROTOCOL_VERSION to 242 for the new thread event.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
SawyerHood added a commit that referenced this pull request Oct 19, 2026
…rk (#5564)

## Human comments

## What was wrong

Claude Code keeps one logical turn open while background agents or
workflows run. #633 added this so a child thread is not reported done
while its sub-agents still work. The bridge holds back `turn.boundary`
on the SDK `result`
(`plugins/provider-claude-code/src/delta-translation.ts`,
`hasCompletionBlockingClaudeTasks`), so the thread stays `active`. A
`queue-if-active` send (`bb thread send --mode queue`,
`sdk.threads.send`, embedded chats, retries, or Enter when it is set to
queue) is something `resolveDispatchAttemptKind` treats as `start-turn`
on an active thread. `dispatch-attempt.ts` then waits with `thread-busy`
until every background task finishes, even though the main run is idle
and Claude Code would accept a new prompt right away. Smart Queue made
no decisions here; this is core dispatch.

## What changed

- **provider-bridge-protocol**: adds the delta `turn.mainRun { state:
"idle" | "running" }`. The assembler turns it into the thread event
`turn/mainRun/updated` on the open turn. This is an additive delta kind,
so the grammar snapshot is updated and
`PROVIDER_BRIDGE_PROTOCOL_VERSION` stays at 2.
- **domain / thread-view**: adds the `turn/mainRun/updated` event schema
and its scope policy (`turn`). The event is treated as timeline noise,
so it is not rendered.
- **Claude Code bridge**: when it holds the turn for background work, it
sends `idle` once. When the next top-level main run starts (an
`assistant` or `stream_event` message without a parent tool call), it
sends `running`. Turn completion is unchanged, so #633's guarantee
holds: no `turn/completed` while background agents or workflows run.
- **db**: adds `isStoredTurnMainRunIdle`, which reads the latest
`turn/mainRun/updated` event for a turn.
- **server**:
- `dispatch-attempt.ts`: when the active turn's main run is idle, a
`queue-if-active` message is sent as `steer-if-active`, so it is
delivered into the held turn.
- `queued-messages.ts`: `thread-busy` rows become eligible while the
main run is idle.
  - `internal/events.ts`: an `idle` event wakes the queue drain.
- While the main run is working, behavior is unchanged: Enter still
queues.
- **The thread keeps showing as running while it accepts messages.** Its
status stays `active` and the background-agent indicator is unchanged.
- **Wire change**: a new thread event on the daemon→server lane, so
`HOST_DAEMON_PROTOCOL_VERSION` goes from 241 to 242. The plugin SDK goes
from 0.6.55 to 0.6.56 for the `turn.mainRun` delta.
- **What reaches the held turn**: `queue-if-active` sends and
`thread-busy` queued rows, including rows queued from the composer when
Enter is set to queue. Enter's default already steers into an active
thread and is unchanged. A row queued while the turn is already held is
delivered right away (`createQueuedMessageForThread` wakes the drain
when the main run is idle), not only rows queued before the main run
went idle.
- **Deliberate trade-offs**: a message delivered into a held turn is a
steer, not a new turn. It skips a pending `restartBeforeNextTurn` Claude
session restart on purpose, since restarting would kill the background
agents holding the turn open; the restart still happens before the next
real turn. Dispatch hooks see `attempt: "join-turn"` for these messages.
A drained queued row shows with the Steer label in the timeline.
- **Docs**: `docs/provider-bridge-protocol.md` documents held turns.
- **Recordings**: none of the Claude Code recordings exercise a held
turn. `pnpm rerecord --provider claude-code` produced only unrelated
churn, so no recording changes are committed.

## How you verified

- New server test `turn held open for background work` in
`apps/server/test/threads/thread-send-dispatch.test.ts`. It fails before
the server change and passes after. It checks that:
- while the main run works, `queue-if-active` still queues as
`thread-busy`;
- once the main run goes `idle`, the queued row drains into the held
turn and a new Enter is sent right away as a steer, while the thread
stays `active`;
  - after `running`, Enter queues again.
- Extended Claude Code bridge tests in `task-translation.test.ts` and
`delta-translation.test.ts`:
- the held `result` sends `idle` once and no `turn/completed` (#633
guarantee);
  - a task notification does not clear it;
  - the next main-run assistant message sends `running` first;
  - the final `result` completes the turn.
- Maintainer follow-up: added tests that sub-agent
`assistant`/`stream_event` messages don't flip the held turn to
`running`, that the assembler drops `turn.mainRun` with no open turn,
and that the event never changes the built timeline;
`isStoredTurnMainRunIdle` now uses `json_extract`. End-to-end with
Claude Code 2.1.303: a message sent while only a background agent ran
was answered in ~3s (main: waited ~175s for the agent).
- `pnpm exec turbo run typecheck lint test` for `@bb/server`,
`@bb/domain`, `@bb/provider-bridge-protocol`, `@bb/thread-view`,
`@bb/db`, `@bb/host-daemon-contract`, `@bb/host-daemon`,
`@bb/agent-runtime`, `@bb/provider-parity`,
`bb-plugin-provider-claude-code`, `@bb/app`, `@bb/client-core`.
Everything passes except one `@bb/server` scrollback timing test
(`public-thread-timeline-scrollback`), which is flaky: it failed once in
the full run and passed in two runs of that file on its own.

> AGENT GENERATED

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

---------

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