#4939 · ACP bridge loses recovery state when its agent exits
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
A local ACP agent really exits after an external signal, but its BB bridge stays alive. The bridge deletes the thread’s session, so submitting another turn in an idle thread returns No active ACP session instead of relaunching the agent. A second defect appears when the agent exits during a pending prompt: the bridge clears its active-prompt flag before emitting the exit error, leaving the runtime’s turn active. Both failures reproduce using the repository’s own ACP fixture, without external agents or account credentials. Retaining the session construction state, completing interrupted turns, and invoking the existing resume path restores subsequent turns.
2. Claims vs findings
| Claim tested | Status | Evidence |
|---|---|---|
| An external clean agent exit prevents subsequent work in the same thread. | Verified | Real fixture PID receives SIGTERM and exits 0. Three idle-session regression variants return JSON-RPC -32000; runtime idle reproduction also returns the missing-session error. |
| The interrupted turn always becomes failed. | Not true for the reproduced child-exit topology | Four active-turn regression variants emit no failed completion. The runtime still has an active turn and rejects a new turn as competing. |
| Exit code 0 is treated as unexpected while the thread is live. | Verified | The existing fixture handles SIGTERM with process.exit(0). The bridge emits exactly one unexpected-exit error notification. |
| The host’s provider_process_exited event is the root cause of every missing session. | Different boundary; not observed here | The host handler concerns the outer bridge process. These checks keep the outer ACP bridge running and kill only its agent child. The runtime receives provider/warning, not provider_process_exited. |
| A session/load path is available but never used for recovery. | Verified for this exit path | Explicit resume and execution-setting rebuilds already support load. Deletion makes that path unreachable on the next normal turn. |
| A new thread is the only possible recovery; the reported macOS agent behaves identically. | Unverified | Normal resubmission is broken; manual thread/resume exists. The external implementation and macOS environment were not executed. |
3. Environment
- Public repository get-bb/bb, trusted origin/main commit
53e06758f2c3fdf712f29b3a715787d351e51900, package version 0.45.0. - Linux 4.19.0-gvisor x86_64; Node v22.19.0; pnpm 9.15.0.
- Only the repository’s
fake-acp-agent.mjsis used. The bridge, child connection, translator, and runtime are real production modules. - Each test uses a fresh temporary workspace and real subprocesses. Runtime checks create separate temporary launch-data directories and remove them on shutdown.
- No HTTP servers, ports, real BB data, or account providers are used. No browser screenshots are relevant to this process-lifecycle bug.
4. Minimal reproduction
- Make a clean checkout at the trusted commit and build normally:
git clone https://github.com/get-bb/bb.git bb-4939 cd bb-4939 git checkout 53e06758f2c3fdf712f29b3a715787d351e51900 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build
- Download and apply the authored regression-only patch, then run the focused tests:
curl -fsS https://get-bb.github.io/reports/issues/4939/repro/regression-test.patch -o /tmp/bb-4939-regression.patch git apply /tmp/bb-4939-regression.patch pnpm exec turbo run test --filter=@bb/provider-bridge-acp -- --testNamePattern='recovers after an external agent exit|reports unexpected agent exits'
The test starts the trusted fixture, sends a completed or pending prompt, signals its recorded PID, waits for an exit error, and submits again. Six table cases cover idle/active turns with absent, successful, and failing session/load. The existing nonzero-exit test also checks completion and recovery.
Expected: interrupted turns complete as failed; the next turn completes; session/load preserves the provider session ID where available; unsupported/failed load falls back with contextLost=true. Actual on unchanged production code: Idle: { "code": -32000, "message": "No active ACP session" } Active: expected undefined to match object { status: 'failed' } Tests: 7 failed | 370 skipped (377) Exit status: 1 - For a real runtime-to-bridge-to-child check, download the standalone diagnostic and run both modes:
curl -fsS https://get-bb.github.io/reports/issues/4939/repro/runtime-check.mjs -o /tmp/bb-4939-runtime-check.mjs node --conditions=source --import tsx /tmp/bb-4939-runtime-check.mjs idle node --conditions=source --import tsx /tmp/bb-4939-runtime-check.mjs active
Idle before fix: FAIL: No active ACP session Active before fix: FAIL: Refusing to start a competing turn for thread "repro-4939" while another turn is active or starting Both after fix: PASS: follow-up turn completes on the restored provider session
Regression-only patch · Runtime diagnostic
Complete regression patch
diff --git a/packages/provider-bridge-acp/src/bridge/bridge.test.ts b/packages/provider-bridge-acp/src/bridge/bridge.test.ts
index ebb2868b8..9bf3e6043 100644
--- a/packages/provider-bridge-acp/src/bridge/bridge.test.ts
+++ b/packages/provider-bridge-acp/src/bridge/bridge.test.ts
@@ -3554,9 +3554,110 @@ describe("acp bridge", () => {
}, "agent exit error notification");
expect(errors).toHaveLength(1);
expect(errors[0]?.params).toMatchObject({ threadId: bbThreadId });
- startedProviderThreadIds.pop();
+ expect(threadEventsOfType("turn/completed").at(-1)).toMatchObject({
+ status: "failed",
+ });
+ const response = await waitForResponse(
+ sendTurnRequest("turn/start", providerThreadId, {
+ input: [{ type: "text", text: "after", mentions: [] }],
+ }),
+ );
+ expect(response.error).toBeUndefined();
+ expect(await waitForTurnCompleted()).toMatchObject({ status: "completed" });
+ expect(agentMessageTexts()).toContain("echo:after");
});
+ it.each([
+ { loadSession: "0", failLoad: "0", activeTurn: false },
+ { loadSession: "1", failLoad: "0", activeTurn: false },
+ { loadSession: "1", failLoad: "1", activeTurn: false },
+ { loadSession: "0", failLoad: "0", activeTurn: true },
+ { loadSession: "1", failLoad: "0", activeTurn: true },
+ { loadSession: "1", failLoad: "1", activeTurn: true },
+ ])(
+ "recovers after an external agent exit (load=$loadSession, failLoad=$failLoad, active=$activeTurn)",
+ async ({ loadSession, failLoad, activeTurn }) => {
+ const readyFile = join(workspaceDir, "agent-ready");
+ const promptLog = join(workspaceDir, "prompts.jsonl");
+ const requestLog = join(workspaceDir, "requests.jsonl");
+ const { bbThreadId, providerThreadId } = await startThread({
+ envVars: {
+ FAKE_ACP_LOAD_SESSION: loadSession,
+ FAKE_ACP_FAIL_LOAD: failLoad,
+ FAKE_ACP_READY_FILE: readyFile,
+ FAKE_ACP_PROMPT_LOG: promptLog,
+ FAKE_ACP_REQUEST_LOG: requestLog,
+ },
+ });
+ await waitForResponse(
+ sendTurnRequest("turn/start", providerThreadId, {
+ input: [
+ {
+ type: "text",
+ text: activeTurn ? "hang" : "before",
+ mentions: [],
+ },
+ ],
+ }),
+ );
+ if (activeTurn) {
+ await waitFor(
+ () => loggedPrompts(promptLog).includes("hang") || undefined,
+ "pending prompt before exit",
+ );
+ } else {
+ expect(await waitForTurnCompleted()).toMatchObject({
+ status: "completed",
+ });
+ }
+ process.kill(Number(readFileSync(readyFile, "utf8")), "SIGTERM");
+ await waitForAgentExit(readyFile);
+ const error = await waitFor(
+ () => notifications("error").at(-1),
+ "external agent exit notification",
+ );
+ expect(error.params).toMatchObject({
+ threadId: bbThreadId,
+ message: expect.stringContaining("(code 0)"),
+ });
+ expect(notifications("error")).toHaveLength(1);
+ if (activeTurn) {
+ expect(threadEventsOfType("turn/completed").at(-1)).toMatchObject({
+ status: "failed",
+ });
+ }
+ const completionCount = threadEventsOfType("turn/completed").length;
+ const response = await waitForResponse(
+ sendTurnRequest("turn/start", providerThreadId, {
+ input: [{ type: "text", text: "after", mentions: [] }],
+ }),
+ );
+ expect(response.error).toBeUndefined();
+ const completed = await waitFor(
+ () => threadEventsOfType("turn/completed")[completionCount],
+ "recovered turn completion",
+ );
+ expect(completed).toMatchObject({ status: "completed" });
+ expect(agentMessageTexts()).toContain("echo:after");
+ const contextLost = loadSession === "0" || failLoad === "1";
+ expect(notifications("session/replaced").at(-1)?.params).toMatchObject({
+ threadId: bbThreadId,
+ contextLost,
+ });
+ expect(
+ loggedAcpRequests(requestLog).filter(
+ (request) => request.method === "session/load",
+ ),
+ ).toHaveLength(loadSession === "1" ? 1 : 0);
+ if (!contextLost) {
+ expect(notifications("thread/identity").at(-1)?.params).toMatchObject({
+ threadId: bbThreadId,
+ providerThreadId,
+ });
+ }
+ },
+ );
+
it("releases a session still under construction: the agent is reaped and the pending thread/start fails", async () => {
const readyFile = join(workspaceDir, "agent-ready");
const threadId = "thread-release-during-construction";
5. Root cause
- The child exit handler rejects pending requests first, then asynchronously stops the process tree before invoking onExit.
- The prompt rejection handler clears activePromptKind. By the time onExit calls emitSessionError, the error emitter sees no active prompt and emits no failed-turn delta. The runtime adapter maps the remaining error notification to a warning, which does not end the turn.
- The agent onExit callback unconditionally calls removeSession, deleting the saved construction and provider-session mapping even for unexpected exits of established sessions.
- turn/start looks up that deleted session and returns -32000 before any restart logic runs.
- The existing rebuild mechanism already resumes using saved construction state. Session initialization already uses session/load and warns when it must fall back to session/new. This mechanism is not missing globally; unexpected exits discard the state needed to reach it.
onExit: cancelPendingPermissions(session);
removeSession(session);
... emitSessionError(session, ...);
runTurn catch: ... session.activePromptKind = null;
turn/start: liveSessionForThread(threadId) === undefined
→ sendError(id, -32000, "No active ACP session")
The host unexpected-provider-exit event builder is a separate outer-process boundary. Editing that event builder alone cannot restore an agent child whose still-running ACP bridge deleted its session.
6. Proposed fix and validation
Keep construction state for an unexpectedly exited, established ACP session; continue deleting it for explicit stops, releases, stale callbacks, and failed construction. Preserve the active-prompt marker until the exit callback emits the failed completion, then clear it. Treat an exited connection as a reason for the existing execution-settings reconciliation to rebuild the session before the next turn. Reject dynamic-tool calls against retained but dead connections. Reuse existing session/load, fresh-session fallback, identity, and session/replaced notifications; no new public protocol or dependency is needed.
The implemented candidate changes two ACP bridge files, 126 added-plus-deleted text lines (119 additions and 7 deletions). Seven focused cases pass after the candidate fix. The complete ACP suite passes 373 tests with 4 existing skips; the complete agent-runtime suite passes 307 tests. Both packages’ typechecks and lints pass, as does git diff --check. Real runtime checks pass for idle and active child exits and retain the original provider session ID.
The local fixture confirms correct use of session/load and session identity; it does not prove persisted conversation history for the external agent. If the external implementation refuses restoration, existing fallback deliberately reports context loss.
7. Verification
The same investigating agent repeated the reproduction in a second clean detached checkout at the exact recorded commit, before any production change. Only the authored regression patch was applied. Frozen installation and the full build succeeded there; the same focused command produced the same seven expected failures. Both standalone runtime modes also failed as described above, with new temporary workspaces and launch-data directories. This is a second clean verification, not an independent-agent check.
Test development corrections: an early draft incorrectly assumed the captured event helper populated event identity fields, and waited for an active-turn completion before investigating why it was missing. Identity preservation is now checked on actual thread/identity notifications; failed completion is a direct assertion. Both checkouts reran the final corrected regression. Discovering the missing completion expanded the root cause and fixed candidate before publication.
8. Related issues
- #2509 concerns an initialize hangup causing process death (closed); this report covers established sessions after an external exit.
- #3820 concerns third-party bridge delta handling and worker lifecycle, not this deleted-session recovery path.
- #1028 requests ACP session import; existing internal session/load is sufficient for this focused repair.
No linked open pull request was found in issue timeline metadata or an open-PR search for the trusted numeric issue. No PR code or external issue link was executed.
9. Appendix
- First checkout, unchanged-production regression log
- Second clean checkout regression log
- Focused post-fix log
- Full relevant tests, typechecks, and lints
- Runtime idle before · Runtime active before
- Runtime idle after · Runtime active after
pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build pnpm exec turbo run test --filter=@bb/provider-bridge-acp -- --testNamePattern='recovers after an external agent exit|reports unexpected agent exits' pnpm exec turbo run test typecheck lint --filter=@bb/provider-bridge-acp --filter=@bb/agent-runtime git diff --check git diff --numstat origin/main
Issue text and links were treated as untrusted claims only. Reproduction code was authored from trusted origin/main and existing in-repository fixtures; no issue-supplied script, patch, branch, binary, or external agent was run. Public logs redact checkout paths and contain only synthetic fixture data.
> AGENT GENERATED