← reports

#6251 · Reconnect leaves terminal interaction waits unresolved

Bug High priority Medium effort host threads provider-claude-code ask-user-question

GitHub issue · October 25, 2026 · trusted base 7f3414a707a54519749d098165e3a98ff73a4b88

Verdict: REPRODUCED · Root-cause confidence: high

Scope: reproduced at the real server lifecycle and daemon reconnect boundaries using deterministic tests. A live Claude process, real network interruption, and multi-hour user incident were not replayed.

1. TL;DR

A provider can remain blocked waiting for a user response after the server has already ended the interaction. Main still allows an undeliverable answer to interrupt the interaction without ending its active turn. The daemon keeps its own unresolved provider promise, and opening a replacement session does not compare that promise with server state. A focused daemon test fails on main in two clean checkouts because the provider remains waiting after reconnect; a separate real-database server test confirms the terminal interaction, active thread, and rejected registration replay. Reusing the existing registration endpoint on reconnect releases terminal waits without changing the protocol.

2. Claims vs findings

ClaimFindingEvidence
Main can interrupt an interaction after a failed answer delivery.VerifiedThe server evidence test injects a failed interactive.resolve response through the normal host RPC response handler; persisted status becomes interrupted.
The thread can remain active after that interruption.VerifiedThe same test reads the real SQLite thread row and asserts active after settlement.
Same-instance reconnect leaves an existing provider wait open.VerifiedThe daemon app reconnect test starts a wait, opens a second session on the same app and instance, and receives still waiting rather than the server rejection.
The existing registration route can distinguish ended requests.VerifiedThe real server test replays the identical request and receives outcome=rejected.
A five-second disconnect timer triggers this on main.Not currentCommit 061685c4a, merged through #4271, removed that historical trigger. The current reproduced trigger is a failed answer command.
Real Claude steers remain unread for hours and stopping the thread recovers it.Unverified hereNo real provider session or production instance was used. The tests establish the blocking state, not the historical duration or a live provider recovery.

3. Environment

4. Minimal reproduction

Save the patch below as /tmp/issue-6251-reconnect.patch. It only extends the trusted daemon test fixture and adds one test. Save the server test below as apps/server/test/internal/issue-6251-evidence.test.ts.

git clone https://github.com/get-bb/bb.git /tmp/issue-6251-source
cd /tmp/issue-6251-source
git checkout --detach 7f3414a707a54519749d098165e3a98ff73a4b88
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@get-bb/plugin-sdk
pnpm exec turbo run build
git apply /tmp/issue-6251-reconnect.patch
pnpm exec turbo run test --filter=@bb/host-daemon -- --testNamePattern='releases a provider wait when a reconnected session'
pnpm exec turbo run test --filter=@bb/server -- test/internal/issue-6251-evidence.test.ts

Building the SDK first avoids an unrelated first-build plugin/SDK output race encountered during the first setup. The subsequent full builds succeeded in both checkouts.

  1. The app starts with a single daemon instance and a scripted session ID.
  2. A real daemon interactive-request registry opens a provider wait. The transport registers it as pending.
  3. The same app reconnects and receives a second session ID. The scripted server would reject another registration because the interaction has ended.
  4. Expected: the daemon checks its outstanding request, consumes that rejection, and ends the provider wait.
  5. Actual on unchanged main: it never makes the second registration, so the wait remains open. The bounded assertion fails rather than leaving the test hanging.
FAIL src/app.test.ts > createHostDaemonApp > releases a provider wait when a reconnected session rejects its request
AssertionError: expected 'still waiting' to be 'Provider request was already handled'
Expected: "Provider request was already handled"
Received: "still waiting"
Test Files  1 failed | 74 skipped (75)
Tests       1 failed | 828 skipped (829)
Complete reconnect reproduction patch
diff --git a/apps/host-daemon/src/app.test.ts b/apps/host-daemon/src/app.test.ts
index 6931666e6..953fb4e8b 100644
--- a/apps/host-daemon/src/app.test.ts
+++ b/apps/host-daemon/src/app.test.ts
@@ -54,6 +54,7 @@ interface CreateFetchRecorderArgs {
   inactiveSessionOnFirstEventPost?: boolean;
   interactiveRequestError?: Error;
   interactiveRequestResponse?: HostDaemonInteractiveRequestResponse;
+  interactiveRequestResponses?: HostDaemonInteractiveRequestResponse[];
   interruptResponses?: Array<() => Response>;
   retiredEnvironmentIds?: string[];
   sessionIds?: string[];
@@ -112,6 +113,7 @@ function createFetchRecorder(
   let eventPostCount = 0;
   let interruptCount = 0;
   let sessionOpenCount = 0;
+  let interactiveRequestCount = 0;
   const fetchFn: FetchFn = async (input, init) => {
     const url = readFetchUrl(input);
     const request = {
@@ -165,7 +167,8 @@ function createFetchRecorder(
       if (args.interactiveRequestError) {
         throw args.interactiveRequestError;
       }
-      const response: HostDaemonInteractiveRequestResponse =
+      const response: HostDaemonInteractiveRequestResponse = args
+        .interactiveRequestResponses?.[interactiveRequestCount++] ??
         args.interactiveRequestResponse ?? {
           outcome: "created",
           interactionId: "pint_app_test",
@@ -420,6 +423,81 @@ async function createAppFixture(
 }
 
 describe("createHostDaemonApp", () => {
+  it("releases a provider wait when a reconnected session rejects its request", async () => {
+    let socket: ReconnectingWebSocketLike | undefined;
+    const { app, runtimeOptions, fetchRecorder } = await createAppFixture(
+      {
+        sessionIds: ["session-before", "session-after"],
+        interactiveRequestResponses: [
+          {
+            outcome: "created",
+            interactionId: "pint_app_test",
+            status: "pending",
+          },
+          {
+            outcome: "rejected",
+            reason: "Provider request was already handled",
+          },
+        ],
+      },
+      {
+        createWebSocket: createOpeningWebSocket((created) => {
+          socket = created;
+        }),
+      },
+    );
+    try {
+      await app.daemon.start();
+      await app.runtimeManager.ensureEnvironment({
+        environmentId: "env-reconnect",
+        workspacePath: await makeTempDir("bb-reconnect-workspace-"),
+      });
+      const onInteractiveRequest = runtimeOptions.current?.onInteractiveRequest;
+      if (!onInteractiveRequest || !socket) {
+        throw new Error("Expected runtime callback and socket");
+      }
+      const request = createCommandApprovalRequest();
+      const outcome = onInteractiveRequest(request).then(
+        () => "resolved",
+        (error: Error) => error.message,
+      );
+      await vi.waitFor(() => {
+        expect(
+          fetchRecorder.requests.filter(
+            (record) =>
+              record.pathname === "/internal/session/interactive-request",
+          ),
+        ).toHaveLength(1);
+      });
+      socket.reconnect();
+      await vi.waitFor(() => {
+        expect(
+          fetchRecorder.requests.filter(
+            (record) => record.pathname === "/internal/session/open",
+          ),
+        ).toHaveLength(2);
+      });
+      await expect(
+        Promise.race([
+          outcome,
+          new Promise<string>((resolve) =>
+            setTimeout(() => resolve("still waiting"), 300),
+          ),
+        ]),
+      ).resolves.toBe("Provider request was already handled");
+      const registrations = fetchRecorder.requests.filter(
+        (record) => record.pathname === "/internal/session/interactive-request",
+      );
+      expect(registrations).toHaveLength(2);
+      expect(JSON.parse(registrations[1]!.body!)).toMatchObject({
+        sessionId: "session-after",
+        interaction: request,
+      });
+    } finally {
+      await app.daemon.shutdown("test", 0);
+    }
+  });
+
   it("installs machine variables into the daemon and child processes before work, then removes overrides live", async () => {
     vi.stubEnv("MACHINE_DAEMON_TEST", "original");
     let socket: ReconnectingWebSocketLike | undefined;

Real server evidence test

This passing test proves the main-side prerequisite, not the daemon repair: an answer delivery error creates an interrupted interaction while leaving the thread active. It also verifies the actual endpoint response used by the daemon reproduction. The database is not mocked.

Complete server test
import { getThread, listPendingInteractionsByThread } from "@bb/db";
import { describe, expect, it, vi } from "vitest";
import {
  internalAuthHeaders,
  reportQueuedCommandError,
  waitForQueuedCommand,
} from "../helpers/commands.js";
import { readJson } from "../helpers/json.js";
import { seedThreadFixture, seedTurnStarted } from "../helpers/seed.js";
import {
  createUserAnswerResolution,
  createUserQuestionPayload,
} from "../helpers/pending-interactions.js";
import { withTestHarness } from "../helpers/test-app.js";

describe("issue 6251 server evidence", () => {
  it("interrupts an undelivered answer without ending the active turn and rejects registration replay", async () => {
    await withTestHarness(async (harness) => {
      const { session, thread } = seedThreadFixture(harness, {
        thread: { status: "active" },
      });
      seedTurnStarted(harness.deps, {
        threadId: thread.id,
        turnId: "turn-evidence",
        providerThreadId: "provider-evidence",
      });
      const request = {
        sessionId: session.id,
        interaction: {
          threadId: thread.id,
          turnId: "turn-evidence",
          providerId: "codex",
          providerThreadId: "provider-evidence",
          providerRequestId: "request-evidence",
          payload: createUserQuestionPayload(),
        },
      };
      const register = () =>
        harness.app.request("/internal/session/interactive-request", {
          method: "POST",
          headers: internalAuthHeaders(harness),
          body: JSON.stringify(request),
        });
      const registration = await register();
      expect(registration.status).toBe(200);
      expect(await readJson(registration)).toMatchObject({
        outcome: "created",
        status: "pending",
      });
      const interaction = listPendingInteractionsByThread(harness.db, {
        threadId: thread.id,
      })[0];
      if (!interaction) throw new Error("Expected persisted question");
      harness.deps.pendingInteractions.resolvePendingInteraction({
        threadId: thread.id,
        interactionId: interaction.id,
        resolution: createUserAnswerResolution(),
      });
      const command = await waitForQueuedCommand(
        harness,
        ({ command }) =>
          command.type === "interactive.resolve" &&
          command.interactionId === interaction.id,
      );
      await reportQueuedCommandError(harness, command, {
        errorCode: "host_unavailable",
        errorMessage: "Synthetic transport disconnect before delivery",
      });
      await vi.waitFor(() => {
        expect(
          listPendingInteractionsByThread(harness.db, {
            threadId: thread.id,
          })[0],
        ).toMatchObject({
          status: "interrupted",
          statusReason: "Synthetic transport disconnect before delivery",
        });
      });
      expect(getThread(harness.db, thread.id)).toMatchObject({
        status: "active",
      });
      const replay = await register();
      expect(replay.status).toBe(200);
      expect(await readJson(replay)).toMatchObject({ outcome: "rejected" });
    });
  });
});
✓ test/internal/issue-6251-evidence.test.ts (1 test)
Test Files  1 passed (1)
Tests       1 passed (1)

5. Root cause

Failed interactive.resolve command settlement interrupts the interaction on every failed report:

if (!args.report.ok) {
  this.interruptPendingInteractionInTransaction(args.deps, {
    interactionId: args.command.interactionId,
    reason: args.report.errorMessage,
  });
  return;
}

Terminal settlement updates the interaction timeline and listeners; it does not end the host-local provider promise. The server test confirms that the thread remains active.

InteractiveRequestRegistry stores a promise per provider request. Registration and resolution can settle it, but no reconciliation runs when a session is replaced. onSessionOpened reconciles plugins, environments, watches, event delivery, and outbound interruptions, not these surviving waits.

The missing link is not a new endpoint: registration already returns existing for open requests and rejected for ended requests. The daemon simply does not ask again. This is a split lifecycle state: the server no longer exposes an answerable question while the provider still waits for its answer.

6. Proposed fix and verification

Replay the outstanding registrations when a session opens, using the existing endpoint and the current session ID. Share terminal-response handling with initial registration. Preserve still-pending/resolving waits and retain them on transient replay errors. Ignore late responses for entries already delivered, interrupted, or replaced. Return the provider promise immediately so reconciliation can settle it safely even while the original registration is still in flight.

The local repair stays inside the host-daemon subsystem and changes no wire fields, schema, dependency, stored data, CLI surface, or packaging. The original failing app test passes after the repair. Additional tests cover pending and resolving requests, transient failures, and late/in-flight registration races.

pnpm exec turbo run test --filter=@bb/host-daemon -- src/app.test.ts src/interactive-request-registry.test.ts src/server-client.test.ts src/server-connection.test.ts src/command-dispatch.test.ts
Test Files  5 passed (5)
Tests       107 passed (107)

pnpm exec turbo run typecheck --filter=@bb/host-daemon
Tasks: 5 successful, 5 total

The broader daemon suite had two unrelated failures: systemd file mode expected 0644 but received 0600 under umask 0077; server-move diskFreeBytes was null instead of numeric in this environment. Both identical failures also occur in checkout B with unchanged production code. They are not represented as a passing full suite and were not modified.

7. Linked PR review

PR #6252 was closed without merge before this investigation. Metadata and diff were read only after the reproduction test and initial repair were authored; its branch was never checked out or executed. Static inspection shows the same general repair direction: session-open revalidation through the existing endpoint, with explicit treatment of in-flight registrations. This is consistent with the independently observed lifecycle gap. No blocker is asserted from static review alone, and the closed PR itself is not runtime-verified. All executable evidence in this report comes from trusted main plus the tests and repair authored during this investigation. No linked open PR was found before opening a replacement.

8. Related issues

#1650 and #4364 are reporter-supplied comparisons, not independently reproduced here. The verified relevant history is #4271: it removed disconnect-triggered cancellation but did not add provider-wait reconciliation to the session-open callback.

9. Verification

RunCheckout and commandResult
First, 00:18:07 UTCClean checkout A at the full trusted SHA; frozen install and full build; daemon test-name command above.Expected failure: still waiting instead of the rejection.
Repeat, 00:18:58 UTCSecond clean temporary checkout B at the identical SHA; its own frozen install, full build, and only the test patch; same command.Same assertion and same expected/received values. Production files were unchanged.
Server evidence, 00:21:53 UTCCheckout B; real server harness and server evidence command above.One test passed, proving interrupted interaction, active thread, and rejected replay.
Repair, 00:22:33 UTCCheckout A; five relevant daemon suites and scoped typecheck.107 tests passed; typecheck passed.

The same agent performed both clean runs; this is a repeat reproduction, not an independent review. Root-cause permalinks were checked against the recorded base. No screenshot is applicable to this nonvisual lifecycle bug. No live-provider conclusions were upgraded based on unit-level evidence, and no report correction was required after the second run.

10. Appendix and trust boundary

The embedded patch and server test are sufficient to repeat the evidence. Raw logs, local test files, and temporary checkout identifiers remain in private local evidence storage; repository publication policy permits the self-contained report and summary metadata, not raw logs or script directories.

Read-only GitHub metadata was used to classify the issue as Bug / High / Medium and identify linked PRs. Existing classifications were preserved; initially none existed. Labels applied: host, threads, provider-claude-code, ask-user-question. The verified reproduction label is confirmed-repro.

Issue text, quoted commands, links, and PR contents were treated as untrusted claims. No issue-provided script, branch, patch, test, or external URL was executed or fetched. The report uses newly authored test fixtures, not production user data.