Skip to content

Settle every turn input and every started turn - #6552

Closed
ymichael wants to merge 12 commits into
mainfrom
bb/swing-1b-every-turn-input-and-turn-settles-thr_mkz7kvezdf
Closed

ymichael wants to merge 12 commits into
mainfrom
bb/swing-1b-every-turn-input-and-turn-settles-thr_mkz7kvezdf

Conversation

@ymichael

@ymichael ymichael commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Stacked on #6493 (one inbox and dispatcher). Even with every input going through one dispatcher, nothing guaranteed that an input or a started turn ever settled:

What changed

  • Input ledger. Every turn input is a queued_thread_messages row in a new submitted state, written with client/turn/requested; only turn/input/accepted removes it. A refusal that doesn't end the run returns the input to the queue head and sends it when the turn ends. A failed run keeps its unaccepted input for Retry; any other new message moves it to a visible "Not sent" row that is never sent automatically. Inputs whose run ended unaccepted are returned only on a fact (acceptance, a landed stop, provider exit, a new daemon instance, or a reconnect report showing no turn or pending start), never by a timer while a submit may still land.
  • One owner of "running". threads.status decides. A provider process exit closes the turn it left open; a turn that hasn't started 10 minutes after its request is stopped and fails with a provider_turn_start_deadline error so Retry re-sends it; a turn that starts after its run was stopped is closed and stopped on the daemon. A stop that fails because the host dropped is re-sent once the daemon's socket is back. A stop's late result has no effect (no finalize, no background-task settlement) on a run requested after it. The start deadline counts from the last status change (new threads.status_changed_at), or the last turn completion if later, so title/read-state/section updates can't postpone it.
  • Reconnect sync. Session open carries each thread's open background tasks, the provider questions the daemon still waits on (including registrations in flight), and each active thread's running turn id. The server settles tasks the daemon no longer runs, interrupts pending questions it no longer waits on, re-sends answers the daemon still waits on (even while the thread's buffered events are still replaying, and again when a slow socket opens), marks delivered ones resolved, and tells the daemon to end waits on questions the server already closed (also sent live via a new interactive-requests.end message). A thread the server stopped is stopped again only if the daemon still runs a turn the server already closed, or if no request that may have reached the daemon came after the stop; a host_unavailable request counts as possibly delivered. A provider question for a turn the server already closed is rejected.
  • Model-based test (apps/server/test/threads/turn-lifecycle-model.test.ts): seeded random walks on a real server and SQLite with a fake daemon and provider covering sends in three modes, accept/refuse, turn start/complete/fail, stops (user, deadline, timed-out, host-lost, and acks that arrive after newer work), retries, batched events, background tasks, metadata updates, server restarts, same/new-instance reconnects in the daemon's real order (HTTP handshake, then socket, then replay of buffered events, sometimes with a socket slower than the 5 s transport wait), and the question lifecycle. Invariants checked after every step: no input lost or delivered twice, idle/error threads have no open turn, active threads have a turn or are within the deadline, the provider only waits on open questions, a delivered answer is never discarded, the server never settles a background task the provider still runs, an old stop is never re-sent over a newer request, and nothing is left unsettled once quiet. Seeds 1–2,000 pass locally. CI runs seeds 1–100 plus 110, 134, 223, 309, 472, 991, 1456, 1867 and 1899; together they fail on a revert of every fix except two (the unknown-outcome start refusal and the definitive-rejection re-stop rule), which are covered by targeted unit tests.

Wire/schema: HOST_DAEMON_PROTOCOL_VERSION 258 → 259 (session open openThreadWork and activeThreads[].activeTurnId, response endedInteractiveRequests, new interactive-requests.end); old daemons are refused and self-update. Migrations 0149_input_ledger and 0150_thread_status_changed_at (backfilled from updated_at). No plugin SDK or public API change.

Visible behaviour changes

  1. A refused steer no longer fails a live run; it is queued and sent when the turn ends.
  2. A start refused as a competing turn, or a steer that arrived after its turn ended, is queued and sent next (it used to be dropped).
  3. After a failed run, a new message moves the failed input to the queue as a visible "Not sent" row; Retry still re-sends it.
  4. Retry answers 409 retry_already_queued while the failed turn's submit may still land.
  5. A turn that never starts within 10 minutes is stopped and fails.
  6. A question the server closed during a disconnect ends the provider's wait (the provider sees it rejected).
  7. Send now / edit / delete on a row that is currently submitted answers 404, like a sent message.
  8. A failed run whose turn is still open on the provider closes that turn and stops it.
  9. A provider question for a turn the server already ended is rejected.

Kept as on main on purpose: a stop that times out still frees the thread (#4472), and start refusals other than "can't tell if it arrived" still fail the run (#3502).

How you verified

  • Two independent reviews reproduced eight bugs in earlier versions: a daemon crash on an ended in-flight question, a batched completion closing the next turn, a slow steer fallback delivered twice, a delivered answer erased on reconnect, an answer never re-sent after buffered events or a slow socket, an old stop re-sent over a newer request, a stale stop ack settling a newer run's background task, and a start deadline postponed by metadata updates. Each is fixed with a test that fails first, and the model test was extended so a seed fails on each before its fix.
  • The extended model then found five more, now fixed with failing-first tests: a stop lost when the socket opened late, a delivered answer interrupted by a stale reply to its redelivery, a question accepted for a turn the server had closed, a failed run leaving its turn running, and a stale stop result finalizing a newer run.
  • turbo run test typecheck lint --force for @bb/server (3,881), @bb/host-daemon (840), @bb/db (634), @bb/host-daemon-contract (76) and @bb/integration-tests (77): all pass. typecheck lint on every affected package: 134/134.
  • Model test: seeds 1–2,000 pass locally.

Fixes #4363
Fixes #6251

Partly addresses #6123 (a bridge that dies while the daemon stays connected still settles at the next reconnect) and #1706 (refused inputs now return and every ledger change is logged; the reporter's unexplained deletion wasn't reproduced). Supersedes #6254.

🤖 Generated with Claude Code

AGENT GENERATED

ymichael and others added 12 commits October 28, 2026 15:05
Every path that starts or steers a turn now goes through attemptDispatch,
and sendThreadMessage is only called by the dispatcher:

- Parent/system notices (child outcome, needs-attention, ownership,
  detached tool results, environment-directory continuation, legacy
  deferred) are dispatch attempts with a typed systemNotice
  (initiator: system). Their private executor and the drain's
  sendClaimedSystemNotice path are deleted; notices now run the plugin
  message.dispatch pass and the shared core waits.
- Child turn-end notices are a coalesced inbox row per parent
  (coalesce_key child-outcomes, 2 s sliding sendAt) instead of an
  in-memory Map, so they survive restarts and failed deliveries.
- The drain's hookless fast path is deleted.
- Edit-resend and compaction use the dispatcher's operation source.
- The first message of a pending thread keeps the sender the dispatcher
  resolved (#5010), and the provision context records the initiator for
  the cold start's permission escalation.
- Queued rows store their delivery mode, so a queue-mode row (tell
  --mode queue --send-at, retries, explicit queue) that comes due while
  a turn runs waits for it instead of steering in.
- idempotencyKey on threads.send / bb thread tell --idempotency-key,
  backed by thread_inbox_receipts written in the commit transaction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ntent

- A queued or direct /clear commits its claim consumption and idempotency
  receipt in the same transaction as the context-clear event, so claim
  recovery cannot clear twice and a repeated key clears once. The direct
  /clear path goes through the dispatcher's operation source.
- Parent/system notices are written to the inbox before any dispatch is
  attempted, then attempted through the normal drain, so a throwing or
  timed-out dispatch hook leaves a retryable row instead of losing the
  notice. Notice rows resolve the parent's execution options at delivery,
  as on main.
- A notice re-reads the thread before waiting on provisioning, so a parent
  that finished provisioning during a hook is not left waiting forever.
- Coalescing only merges into a window that has not expired, and editing a
  coalesced row detaches it from later merges.
- A row keeps the caller's delivery intent rather than the mode an attempt
  normalized it to, and rows with different delivery modes never group
  (invalid_delivery_mode).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The idle-recovery sweep also attempts wait-free system-notice rows on
  threads that are not idle or pending, so a notice whose first attempt
  never ran (server exit, a concurrent claim) is delivered to a parent that
  stays active on background work instead of sitting queued forever.
- After the dispatch hook pass, a queue-mode row re-checks main-run
  activity on the re-read thread and waits on thread-busy when the main run
  resumed during the hook, instead of joining the active turn.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Queue rows were deleted in the transaction that appended the turn request,
and inline sends never had a row, so an input whose submit was refused
without failing the run disappeared: a start refused as a competing turn,
a steer that reached the daemon after its turn ended, or a steer refused
while its turn kept running (which also failed the live run).

Turn inputs now go through an input ledger on queued_thread_messages:

- New row state `submitted` with `submitted_request_id` (migration 0149).
  The dispatcher moves drained rows claimed -> submitted, and writes a
  submitted row for an inline send, in the transaction that appends
  `client/turn/requested`. Submitted rows are not listed, edited, drained
  or returned by getQueuedThreadMessage.
- Accepted: `turn/input/accepted` for the request (in the event append
  transaction) or a successful steer `turn.submit` deletes the rows.
- Returned: a refusal that does not end the run (any steer refusal while
  its turn is open or after it completed, a competing-turn refusal of a
  start) puts the rows back at the head of the queue on a thread-busy wait.
  The run is no longer failed by a refused steer.
- Failed: `run.failed` hands the failed turn's rows to the failed turn,
  whose Retry re-sends the input, so it is never sent twice.
- A sweep returns submitted rows older than a minute whose request has no
  live RPC in this process once their thread is no longer running (server
  restart mid-submit, a run that ended before its turn started).
- Every ledger transition is logged at info with row and request ids.

A pending thread's first message and conversation operations (compaction,
edit re-send) keep their own owners and do not write ledger rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`threads.status` is the owner of "is a turn running"; the event-derived
open turn and the daemon's pending start are now bounded against it.

- Leaving a run closes its turn. Every lifecycle transition out of a run
  (run.succeeded, run.failed, stop.settled) closes a root turn that is
  still open, in the same transaction, with a matching synthetic
  turn/completed. Before, a provider process exit (run.failed) left the
  turn open on an errored thread.
- A run must start a turn. A periodic sweep stops an active thread on a
  connected host whose latest start request has had no root turn/started
  for ten minutes, with a system/error saying so and the existing
  provider-turn-idle interruption reason (run.failed). The stop clears
  the daemon's pending start, and the failed turn's Retry re-sends the
  input, which the provider never accepted. Before, the daemon only
  warned after 120 s and the thread stayed "Working" with follow-ups
  waiting on turn-starting forever (#4363).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A same-instance reconnect only compared "threads with a turn". Questions
and background tasks were reconciled only when a new daemon instance
opened a session, so:

- a question the server interrupted while the provider still waited left
  the provider blocked and every later steer unprocessed (#6251);
- a background task whose owner died while the daemon stayed up stayed
  "Running" forever (#6123, same-instance part).

Protocol 257 -> 259 (main took 258). Session open now carries `openThreadWork`: per
thread, the open background/delegation item ids the runtime tracks and
the provider question keys (threadId, providerId, providerThreadId,
providerRequestId) the interactive request registry still waits on,
including registrations still in flight. The server reconciles every
thread without undelivered events:

- open backgroundTask items the daemon no longer runs settle as stopped;
- pending/resolving provider questions the daemon no longer waits on are
  interrupted;
- reported questions whose interaction is no longer pending/resolving
  come back as `endedInteractiveRequests` in the open response, and the
  daemon rejects those provider waits so the turn continues. A reported
  question the server has not stored yet is left alone.

A new daemon instance keeps the existing blanket settle. Old daemons are
refused by the exact protocol match and self-update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A seeded random-walk test drives a real server and SQLite database through
a fake daemon and provider: sends in every mode, submit acceptance and
refusal, turn start/complete/fail, stops, retries, clock jumps with the
deadline and ledger sweeps. After every step it checks that no input is
lost (each is accepted, in a queue row, or owned by the retryable failed
turn), that no input is accepted twice or accepted while still queued, and
that an idle/error thread has no open turn; after each clock jump that an
active thread has a turn or a start inside the deadline; and once quiet
that nothing is left submitted outside a retryable failed turn. 100 seeds
run in CI; 2000 passed locally.

What it found and the fixes:

- A run that fails keeps its unaccepted input as `submitted` rows owned
  by the failed turn instead of deleting them. A retry of that turn
  replaces them; any other new message returns them to the queue as an
  unsent failure ("Not sent: ..."), never auto-sent. Before, sending a new
  message after a refused start lost it.
- A steer whose turn already ended falls back to starting a turn on the
  daemon, so a successful steer RPC no longer counts as acceptance; only
  `turn/input/accepted` does.
- Rows are never returned while their submit RPC is in flight, nor for a
  minute after it succeeded (the provider may still start the turn); the
  grace ends when the input is accepted or the thread's stop lands.
- A late refusal of a request that is no longer the thread's latest
  returns its input without failing the current run.
- A retry is refused while the failed turn's submit is still in flight,
  and only replaces rows of the turn it retries (rows returned from that
  request included, via returned_request_id in migration 0149).
- Main's carry of an undelivered retry into the next message moves only
  the carried agent-only rows with it, and no longer carries a retry whose
  submit is still in flight.
- The unsettled-input sweep returns leftovers as unsent failures and
  leaves a retryable failed turn's rows alone.
- A root turn that starts after its run was stopped is closed and the
  daemon is told to stop it, so an idle/error thread has no open turn.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…them

Review of the swing (thr_2pd76nhz55) reproduced four bugs the model test
could not see. Fixes:

1. Daemon: ending a provider wait whose registration was still in flight
   rejected a promise nobody had attached to yet, and the daemon exited
   on the unhandled rejection. The registry now pre-handles its wait
   promise and ignores a registration response for an entry that was
   ended or replaced meanwhile.
2. Server: leaving a run closed "the open turn" from inside the lifecycle
   wrapper, so a batch carrying turn/completed(A) then turn/started(B)
   closed B while applying A. The generic hook is gone; only a provider
   process exit closes a turn its provider left open.
3. Server: the 60 s acceptance grace let the sweep return a steer whose
   fallback start was still pending, and acceptance did not remove the
   returned copy. Delivery state now lives per server on lifecycleDedupers
   (TurnRequestDelivery) and is fact-based: a submit stays "may still be
   accepted" until it is accepted, a stop succeeds, the provider process
   exits, a new daemon instance connects, or a reconnect report shows the
   thread with no turn or pending start. host_unavailable/command_timeout
   are unknown outcomes resolved by the next report. A start the provider
   never confirms for ten minutes is stopped on the daemon even when the
   thread is idle or errored. Acceptance also deletes rows returned from
   the same request.
4. Server: a reconnect interrupted every question the daemon no longer
   waited on, including resolving ones whose answer was delivered but
   whose ack was lost. Only pending questions are interrupted now.

Model test: adds batched completion + fallback start, server restart
(fresh delivery state, lost RPC results), same- and new-instance
reconnects reporting the fake daemon's real open work, the question
lifecycle (ask, answer, deliver, lost ack), FIFO per-thread command lanes
and pending starts that persist until a stop. New invariants: a delivered
answer is never discarded, and after a reconnect the provider waits only
on open questions and every pending question is still asked. Reverting
fix 2, 3 or 4 makes it fail; fix 1 is daemon-side and covered by a
registry test that fails on the old code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… stale stop results

The server now tells a connected daemon to end a provider wait whenever it
closes that question (new interactive-requests.end message, part of the
259 bump), so a provider never waits on a question bb already closed.

Turn and stop ownership:
- The start deadline watches thread status age, so a run revived from a
  steer's fallback start is also bounded.
- A stop that fails host_unavailable after the daemon has already
  reconnected keeps the thread stopping, and a sweep re-sends stops for
  stopping threads on connected hosts.
- At reconnect, an idle or errored thread the daemon still runs is stopped
  again, not revived, when it was stopped after its last turn request
  that was not rejected. Turns the provider starts after a stop do not
  count as a new run.
- A stop result no longer settles a run the user started after the stop
  was sent.
- A start refused with an unknown outcome (host_unavailable,
  command_timeout) while a turn runs returns its input to the queue. Any
  other refusal still fails the run, as on main, and the open turn is now
  closed and stopped instead of being left running.

Questions: generic interrupts leave answered (resolving) provider questions
alone, and a host_unavailable resolve failure keeps the answer. At
reconnect, an answer the daemon still waits on is re-sent and one it no
longer waits on is marked resolved.

Model test: real server restarts on the same database, socket drops before
reopen, reconnects that open before the old socket closes, user stops
through the public route, stops that time out, and per-step checks that the
provider waits only on open questions and that an active thread's open turn
is the provider's turn. 2000 seeds pass locally. CI runs seeds 1-100 plus
one seed that catches the revert of each fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The in-flight thread RPC guard is per server now, so
hasLiveThreadStartInFlight takes the server deps. The integration harness
exposes its lifecycleDedupers and the reuse smoke test passes them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rder

Answers: a saved answer the daemon still waits on is re-sent at reconnect
even while that thread's buffered events are still replaying, and an
answer whose delivery failed because the socket was not up yet is re-sent
when the host's socket opens. A "stale" reply to a re-sent answer settles
it as resolved, like an unreported answer at reconnect. A provider
question for a turn the server already closed is rejected.

Stops: a stop's late result is ignored before any effect, so it no longer
settles a newer run's background tasks. A stop that fails host_unavailable
after the daemon reconnected is re-sent once the socket is up, unless a
newer request superseded it. Session open now reports each active
thread's running turn id: a thread the server stopped is stopped again if
the daemon still runs a turn the server already closed; otherwise only if
no request after the stop may have reached the daemon. A host_unavailable
rejection counts as possibly delivered, so it supersedes an older stop.

Deadline: the turn-start deadline counts from threads.status_changed_at
(new column, backfilled from updated_at) or the last turn completion, so
read-state, title and section updates no longer postpone it.

Model: the fake daemon does the HTTP handshake before opening its socket,
replays buffered events after it, sometimes opens the socket later than
the transport wait, runs background tasks, can deliver a stop ack after
newer work, and touches thread metadata. New invariants: the server never
settles a background task the provider still runs, and an older stop is
never re-sent over a newer request.

Protocol: activeThreads[].activeTurnId joins the unreleased 259 bump.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The extended model reshuffled every walk, so the old pinned seeds no
longer targeted anything. Seeds 1-100 plus 110, 134, 223, 309, 472, 991,
1456, 1867 and 1899 now fail on a revert of every fix except two (the
unknown-outcome start refusal and the definitive-rejection re-stop rule),
which stay covered by their unit tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/swing-1-one-inbox-per-thread-thr_ix35ge3jbm branch from ada5782 to 7b41cb2 Compare October 29, 2026 21:30
Base automatically changed from bb/swing-1-one-inbox-per-thread-thr_ix35ge3jbm to main October 30, 2026 17:13
@ymichael
ymichael marked this pull request as draft October 30, 2026 20:25
@seklow

seklow commented Oct 31, 2026

Copy link
Copy Markdown

This covers the reconnect path, but not the legacy rows from #6123, which were reported there twice with the warning in the server log (0.47.1 and 0.48.0). settleBackgroundTasksTheDaemonNoLongerRuns goes through the same parseStoredBackgroundTaskItem, which safeParses the raw row against threadEventBackgroundTaskItemSchema without convertLegacyStoredThreadEvent. That schema still requires foreground, so items stored before #5650 are skipped with "Skipping dangling background task with unparsable item payload" on this branch as well as on main. The conversion and a test for it are in #6124. Could they go in here, or land on their own?

AGENT GENERATED

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

ymichael commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded. Its pieces landed separately (#6728, #6870, #6736) or are in #6922, #6923, #6924 and #6925; the input ledger was dropped in favour of the event log.

@ymichael ymichael closed this Nov 3, 2026
ymichael added a commit that referenced this pull request Nov 3, 2026
…6923)

## Human comments

## What was wrong

When a daemon reconnects, `reconcileDaemonReportedThreads` re-sends a
stop for any thread the daemon still runs but the user stopped while it
was away. That call waits only 5 s for the daemon's socket
(`waitForReconnectingDaemon` in
`apps/server/src/services/hosts/online-rpc.ts`), then fails with
`host_unavailable`. `settleThreadStopCommandResult` settles the thread
to idle on that failure, and nothing re-sends the stop once the socket
opens. The stopped turn keeps running on the machine behind an idle
thread. This is item 1 of the investigation of #6552's stop fixes
against main.

## What changed

- `settleThreadStopCommandResult`
(`apps/server/src/services/threads/thread-lifecycle.ts`) now records an
interrupt stop that failed with `host_unavailable` while the host's
latest session is still open. It saves the thread, host and the time the
stop was sent. Any other outcome for that thread clears the record. Both
the reconnect stop and the Stop button settle here, so both are covered.
- `handleDaemonSocketOpened` calls the new `resendStopsAwaitingDaemon`,
next to the existing `redeliverAnswersAwaitingDaemon`. It re-sends that
host's recorded stops through `dispatchThreadStopCommand`, behind the
same in-flight guard.
- A re-sent stop can't interrupt a newer run. It is skipped unless the
thread is still idle or errored, and skipped if a
`client/turn/requested` event was recorded since the original stop went
out (new `hasStoredTurnRequestEventSince` in `@bb/db`). That window
starts when the stop was sent, not when it failed, so a run started
during the 5 s wait is also protected.
- Stops that fail while no session is open aren't recorded. The next
session open already re-stops those threads from the daemon's list of
active threads.
- Server only. No daemon wire change and no
`HOST_DAEMON_PROTOCOL_VERSION` bump.

## How you verified

Two regression tests were added to
`apps/server/test/internal/background-task-reconciliation.test.ts`, next
to the existing reconnect-stop tests:

| Test | Before fix | After fix |
|---|---|---|
| Re-sends a reconnect stop that missed the daemon once its socket opens
| fails (no stop sent) | passes |
| Does not re-send a missed stop once a newer run was requested | passes
(main never re-sends) | passes; fails if the newer-run check is removed
|

- `pnpm exec turbo run typecheck lint --filter='...[origin/main]'`
passes.
- `pnpm exec turbo run test --filter=@bb/server`: everything passes
except some tests in `test/app/install-machine-script.test.ts`. Those
tests spawn install processes, and a different set of them failed on
each run. This change doesn't touch them.

> AGENT GENERATED

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

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

2 participants