← reports

#5481 · Background-task state across provider identity replacement

BugPriority: LowEffort: Medium threadsprovider-claude-code GitHub issueOctober 14, 2026

Trusted base: a7d5dfcc8c27df1fea42847526ee62a338fe8052 (origin/main).

Verdict: PARTIALLY REPRODUCED · Root-cause confidence: medium

1. TL;DR

The real server accepts a new provider identity while retaining an earlier session's unfinished background-command item. Two clean-source runs show zero terminal task events and one active background command after the identity changes. That is enough to explain persistent activity if the old runtime has actually ended, but it does not establish how the reported message edit was admitted. The current edit service rejects this fixture with status 409 before any rewind, and that guard was already present when message editing was introduced on August 11, 2026. This report therefore verifies the lifecycle-state gap, not the historical desktop interaction or process termination.

2. Claims vs findings

ClaimFindingEvidence
Changing the provider session can leave an older background command active in BB.Verified at the event-ingestion boundaryBoth runs persist the replacement identity, emit no task completion, and retain an active-command count of one.
A message edit with active background work caused this transition.UnverifiedThe fixture's edit request is rejected by the actual edit service with 409. No real provider or historical desktop was driven.
The current edit guard prevents the straightforward reproduction.VerifiedThe test checks the guard's exact error before injecting the replacement identity separately.
The guard may be newly added in version 0.46.0.Not supported by repository historyThe same rejection text and activity check exist in trusted commit 969948206ecb6acaba269791d1af188fc8fd65e7, dated August 11, 2026. The reporter's earlier installed build remains unknown.
The old process no longer exists and the UI timer continues for a day.UnverifiedNo reporter runtime, private thread, attachment, or real process was accessed. UI persistence follows from the state projection but was not visually replayed.
A successful thread stop has a settlement path.Verified in source and existing testsSuccessful stop settlement; all 17 existing reconciliation tests and 48 edit tests pass.

3. Environment and isolation

4. Minimal reproduction

  1. Check out the trusted public base in a fresh directory and install/build:
    git clone https://github.com/get-bb/bb.git bb-5481
    cd bb-5481
    git checkout --detach a7d5dfcc8c27df1fea42847526ee62a338fe8052
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build
  2. Save the reproduction test as apps/server/test/internal/issue-5481.repro.test.ts. It uses the existing repository harness, without adding dependencies.
  3. Run the focused test:
    pnpm exec turbo run test --filter=@bb/server -- test/internal/issue-5481.repro.test.ts
  4. The test submits an initial identity, a root turn start, one running local_bash task, and a completed foreground turn to the actual authenticated internal event route. It verifies that the task is open and that message editing rejects it. It then submits a replacement identity separately, verifies that the new identity was stored, and checks for a task-completion event.

Expected cleanup invariant, conditional on replacement retiring the old runtime: one task-completion event and zero active background commands. Actual: the route accepts the new identity, but no completion is emitted and activity remains one.

{"editGuard":409,"replacement":200,"completionCount":0,"activeCommandCount":1}
AssertionError: expected [] to have a length of 1 but got +0
Test Files  1 failed (1)
Tests  1 failed (1)

The failure is intentional evidence against unchanged production code. It is not a passing regression test or a complete message-edit reproduction. The background task is supplied as a schema-valid provider event; no Claude process is created or terminated by this test.

Full reproduction test
import {
  getLastStoredProviderThreadId,
  listActiveBackgroundTaskCountsByThreadIds,
  listEvents,
  listOpenBackgroundTaskItemRowsForThread,
} from "@bb/db";
import { threadScope, turnScope } from "@bb/domain";
import {
  groupHostDaemonEvents,
  type HostDaemonEventEnvelope,
} from "@bb/host-daemon-contract";
import { expect, it } from "vitest";
import { editThreadMessage } from "../../src/services/threads/thread-edit-message.js";
import { internalAuthHeaders } from "../helpers/commands.js";
import { seedThreadFixture } from "../helpers/seed.js";
import { withTestHarness } from "../helpers/test-app.js";

it("settles an old-session background command when provider identity changes", async () => {
  await withTestHarness(async (harness) => {
    const { environment, session, thread } = seedThreadFixture(harness, {
      thread: { providerId: "claude-code", status: "idle" },
    });
    const providerThreadId = "repro-session-before";
    const postEvents = (events: HostDaemonEventEnvelope[]) =>
      harness.app.request("/internal/session/events", {
        method: "POST",
        headers: internalAuthHeaders(harness),
        body: JSON.stringify({
          sessionId: session.id,
          eventGroups: groupHostDaemonEvents(events),
        }),
      });
    const initial = await postEvents([
      {
        threadId: thread.id,
        event: {
          threadId: thread.id,
          type: "thread/identity",
          providerThreadId,
          scope: threadScope(),
        },
      },
      {
        threadId: thread.id,
        event: {
          threadId: thread.id,
          type: "turn/started",
          providerThreadId,
          scope: turnScope("repro-turn"),
        },
      },
      {
        threadId: thread.id,
        event: {
          threadId: thread.id,
          type: "item/started",
          providerThreadId,
          scope: turnScope("repro-turn"),
          item: {
            id: "repro-command",
            type: "backgroundTask",
            taskType: "local_bash",
            description: "fixture background command",
            status: "pending",
            taskStatus: "running",
            skipTranscript: false,
          },
        },
      },
      {
        threadId: thread.id,
        event: {
          threadId: thread.id,
          type: "turn/completed",
          providerThreadId,
          scope: turnScope("repro-turn"),
          status: "completed",
        },
      },
    ]);
    expect(initial.status).toBe(200);
    expect(
      listOpenBackgroundTaskItemRowsForThread(harness.db, {
        threadId: thread.id,
      }),
    ).toHaveLength(1);
    await expect(
      editThreadMessage(harness.deps, {
        environment,
        thread,
        payload: {
          operationId: "repro-edit",
          expectedRequestSequence: 1,
          input: [{ type: "text", text: "replacement", mentions: [] }],
        },
      }),
    ).rejects.toMatchObject({
      status: 409,
      message: "Wait for background work to finish before editing the message",
    });
    const replacement = await postEvents([
      {
        threadId: thread.id,
        event: {
          threadId: thread.id,
          type: "thread/identity",
          providerThreadId: "repro-session-after",
          scope: threadScope(),
        },
      },
    ]);
    expect(replacement.status).toBe(200);
    expect(getLastStoredProviderThreadId(harness.db, thread.id)).toBe(
      "repro-session-after",
    );
    const completions = listEvents(harness.db, { threadId: thread.id }).filter(
      (event) => event.type === "item/backgroundTask/completed",
    );
    const activity = listActiveBackgroundTaskCountsByThreadIds(harness.db, {
      threadIds: [thread.id],
    });
    console.log(
      JSON.stringify({
        editGuard: 409,
        replacement: replacement.status,
        completionCount: completions.length,
        activeCommandCount: activity[0]?.activeBackgroundCommandCount ?? 0,
      }),
    );
    expect(completions).toHaveLength(1);
    expect(activity[0]?.activeBackgroundCommandCount ?? 0).toBe(0);
  });
});

5. Root cause and limits

Daemon event persistence and dispatch persists incoming identity changes and dispatches their side effects. Server event side effects has no identity-transition background-task settlement branch. Open-task query treats an item as open until a matching terminal task event exists. Thread activity-count query similarly counts a pending command by thread and item, without filtering it against the latest provider identity. Consequently a newly stored identity does not invalidate the old activity record.

Background-task projection consumes task begin/progress/end events and only sets the completion timestamp on an end event:

if (lifecycle.kind === "end" && message.completedAt === null) {
  message.completedAt = meta.createdAt;
}
This supports the explanation for a card retaining running state, but the actual desktop rendering and timer were not exercised.

By contrast, Successful stop settlement explicitly invokes Terminal background-task event writer after a successful runtime stop that does not retain an active turn. The existing helper writes item/backgroundTask/completed with item status interrupted and task status stopped for an unfinished task. That explicit teardown evidence is missing from the identity-only reproduction.

Message-edit activity guard is reached through Shared public edit-message route, so source does not establish a UI-only escape from the check. The introduction commit already contained the guard. Its presence is not evidence that the historical bug was recently fixed. The missing historical fact is why that particular edit was accepted despite background activity.

6. Proposed next experiment and fix boundary

Recreate the desktop Escape/edit interaction in an isolated current build with a real long-lived Claude background task. Record the edit request, the activity query immediately before the guard, the host stop/rewind result, and both provider identities. This distinguishes a guard bypass or race from a record whose task metadata was not counted.

If runtime teardown is confirmed without a terminal task event, reuse the existing settlement path at that confirmed teardown boundary, scoped to the retired session. Do not blindly settle all thread tasks on any identity announcement: initial/repeated announcements and already-batched new-session tasks need preservation tests. For the existing orphan, first verify the current stop path safely clears it in an isolated fixture; do not mutate the reporter's event store.

No fix PR: only the event-state portion is reproduced; the current edit trigger is blocked and old-runtime termination is not established by the synthetic event. The evidence does not yet justify changing runtime-lifecycle policy as an automatic simple fix. No production patch, branch, or dependency was created.

7. Related work

The existing reconciliation suite owns successful-stop and daemon-disconnect cleanup behavior; it passes unchanged. The message-edit suite also passes unchanged. GitHub metadata showed no linked or matching open pull request for #5481 at the time of investigation. No pull request code or issue attachments were fetched or executed.

8. Verification

The same investigator created a second clean detached worktree from the exact recorded base and confirmed a clean status before copying only the reproduction test. A separate frozen install and Turbo build completed there, followed by the same focused command. The actual test reran (failed test results were not cached); upstream dependency tasks could reuse Turbo cache.

RunResult
Checkout 1, focused reproduction409 guard; identity accepted with 200; completions 0; active commands 1; expected assertion fails. Vitest duration 7.51s.
Checkout 2, same base and testSame 409/200/0/1 result and same failed assertion. Vitest duration 7.66s.
Existing related suites, checkout 12 files, 65 tests pass: reconciliation 17; editing 48. Vitest duration 13.45s.

Report correction: the final verdict is PARTIALLY REPRODUCED, not a complete desktop-edit reproduction. Confidence is medium for the reported historical root cause, despite high confidence in the demonstrated server-state behavior. The second run supports this narrower conclusion; it does not add evidence of a real provider's termination.

9. Appendix and artifacts

pnpm exec turbo run test --filter=@bb/server -- test/internal/background-task-reconciliation.test.ts test/threads/thread-edit-message.test.ts
git log -1 -S 'Wait for background work to finish before editing the message' -- apps/server/src/services/threads/thread-edit-message.ts
git fetch https://github.com/get-bb/bb.git main:refs/remotes/origin/main
git rev-parse origin/main
gh pr list --repo get-bb/bb --state open --search 5481

Trust note: issue content was treated only as untrusted claims. No embedded instructions, issue commands, attachments, linked code, or reporter runtime data were used. All executed project code came from trusted public main plus the test authored from repository contracts. No GitHub issue comment was posted by the report publisher.