Reports

#6628 · Draft submission ownership outlives a composer

Bug High priority Medium effort ui · GitHub issue · October 30, 2026

Trusted base: a1bf55b6a04c7948ae5ae0dcfcbdec27d2b507a2 · Linux x64 · Node 22.19.0 · pnpm 9.15.0

Verdict: REPRODUCED · Root-cause confidence: high

1. TL;DR

A draft survives its composer being recreated, but the ownership of its pending send does not. Two composer callbacks can therefore consume the same draft scope before either send finishes. If the first failed send restores its draft after the second callback emptied the newer draft, the older text wins. A directly authored component regression reproduces duplicate mutation dispatches and replacement of newer text on trusted main, in two clean checkouts. This is a deterministic component-lifecycle reproduction, not a claim that a provider accepted two messages or that this run exercised the physical viewport breakpoint.

2. Claims vs findings

ClaimFindingEvidence
A remounted composer can send again while its first send is pending.Verified at the component boundaryAll ordinary/modifier combinations produce two mutation dispatches after an explicit unmount/remount.
Failure can restore older text over a newer submitted draft.VerifiedExpected “edited while pending”; received “first message” after both callbacks reject.
Sibling composers share the same vulnerability.VerifiedThe same test with two mounted views fails in all four action combinations.
Distinct scopes must remain independent.Verified controlA second thread successfully dispatches while the first scope is pending.
The reported released macOS runtime and exact resize trigger fail.Not retested hereThis run uses Linux, jsdom and current main, not the release archive or browser routing.
The issue's suggested patch is ready to ship.UnverifiedNo issue-supplied code or patch was executed. Regression and fix proposal come from trusted repository inspection.

3. Environment

Two new temporary Git worktrees at the same recorded origin/main commit. The repository is public. Frozen dependency installs use the existing lockfile; no dependency was added. React Testing Library and the repository's existing prompt-area harness exercise the real component and real draft storage, substituting a deferred transport mutation only. No server, browser, model, provider, runtime database, ports or production data are needed. An initial broad build hit SDK bootstrap ordering; building SDK types and runtime first allowed all 72 build tasks to pass.

4. Minimal reproduction

  1. Create a clean checkout of the trusted commit above and install/build trusted dependencies:
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk
    pnpm exec turbo run build --filter=@get-bb/plugin-sdk
    pnpm exec turbo run build
  2. Apply the maintainer-authored regression patch. This changes tests only, never production code. It extends the existing component harness to use the real draft controller for lifecycle cases.
  3. Run:
    pnpm exec turbo run test --filter=@bb/app -- src/views/thread-detail/ThreadDetailPromptArea.test.tsx
  4. The test stores an initial draft with a file attachment, invokes the native submit callback with a held mutation result, writes a newer draft, recreates or duplicates the view, and attempts another native submit. It rejects the held result and observes both dispatch count and stored draft. It also tests two callbacks before React rerenders, mixed ordinary/modifier paths, pending UI visibility, retry after release, and distinct-thread independence.

Expected: one dispatch; newer draft survives. Actual output in both clean checkouts:

AssertionError: expected { requests: 2, draft: { …(3) } } to deeply equal { requests: 1, draft: { …(3) } }
- "text": "edited while pending"
+ "text": "first message"
- "requests": 1
+ "requests": 2
Tests 12 failed | 57 passed (69)

The 12 new race cases fail as intended; all 56 pre-existing tests and the distinct-scope control pass. There are no unhandled-error reports in either final baseline run. The test counts client mutation dispatches, not real HTTP or provider acceptance.

Complete test-only reproduction patch
diff --git a/apps/app/src/views/thread-detail/ThreadDetailPromptArea.test.tsx b/apps/app/src/views/thread-detail/ThreadDetailPromptArea.test.tsx
index c6135d8de1..c972492b42 100644
--- a/apps/app/src/views/thread-detail/ThreadDetailPromptArea.test.tsx
+++ b/apps/app/src/views/thread-detail/ThreadDetailPromptArea.test.tsx
@@ -43,6 +43,10 @@ import {
 import { LazyQueuedMessagesList } from "@/components/promptbox/banner/LazyQueuedMessagesList";
 import { workflowRow } from "@/test/fixtures/thread-timeline-rows";
 import type { PromptDraftAttachment } from "@bb/client-core";
+import {
+  getPromptDraftAccessor,
+  usePromptDraftStorage,
+} from "@/hooks/usePromptDraftStorage";
 import { BbHttpError } from "@/lib/sdk";
 import type { ExperimentalComposerSelection } from "@get-bb/plugin-sdk";
 import { setComposerTextEffect } from "@/lib/composer-text-effects";
@@ -56,8 +60,9 @@ import {
 } from "./ThreadDetailPromptArea";
 import { makePluginRegistrationSet } from "@/test/fixtures/plugins";
 
-vi.mock("@/hooks/usePromptDraftStorage", () => ({
-  usePromptDraftStorage: () => mocks.promptDraft,
+vi.mock("@/hooks/usePromptDraftStorage", async (importOriginal) => ({
+  ...(await importOriginal<typeof import("@/hooks/usePromptDraftStorage")>()),
+  usePromptDraftStorage: vi.fn(),
 }));
 
 function makeQueuedMessage(
@@ -214,7 +219,169 @@ function renderPromptArea(options: RenderPromptAreaOptions = {}) {
 
 beforeAll(() => LazyQueuedMessagesList.preload());
 
+describe("shared draft submission ownership", () => {
+  let nextId = 0;
+
+  beforeEach(async () => {
+    const storage = await vi.importActual<
+      typeof import("@/hooks/usePromptDraftStorage")
+    >("@/hooks/usePromptDraftStorage");
+    vi.mocked(usePromptDraftStorage).mockImplementation(
+      storage.usePromptDraftStorage,
+    );
+  });
+
+  afterEach(() => {
+    mocks.sendMessageMutateAsync.mockReset().mockResolvedValue(undefined);
+  });
+
+  function openComposer(threadId: string) {
+    const mounted = renderPromptArea({
+      thread: makeThread({
+        id: threadId,
+        status: "active",
+        runtime: { displayStatus: "active" },
+      }),
+    });
+    fireEvent.click(
+      within(mounted.container).getByRole("button", {
+        name: "Capture plugin host",
+      }),
+    );
+    const ordinary = mocks.composerSubmit;
+    const modifier = mocks.composerModifierSubmit;
+    if (!ordinary || !modifier) throw new Error("Missing composer actions");
+    return { ...mounted, ordinary, modifier };
+  }
+
+  function draftFor(threadId: string) {
+    return getPromptDraftAccessor({
+      kind: "thread",
+      projectId: "proj_1",
+      threadId,
+    });
+  }
+
+  describe.each(["same callback", "remount", "sibling"])("%s", (lifetime) => {
+    it.each([
+      ["ordinary", "ordinary"],
+      ["ordinary", "modifier"],
+      ["modifier", "ordinary"],
+      ["modifier", "modifier"],
+    ] as const)(
+      "serializes %s then %s without losing edits",
+      async (firstAction, secondAction) => {
+        const threadId = `thr_lock_${++nextId}`;
+        const draft = draftFor(threadId);
+        const original = {
+          text: "first message",
+          mentions: [],
+          attachments: [
+            {
+              type: "localFile" as const,
+              path: "uploads/first.txt",
+              name: "first.txt",
+            },
+          ],
+        };
+        const newer = { ...original, text: "edited while pending" };
+        draft.setDraft(original);
+        const response = createDeferredPromise<void>();
+        mocks.sendMessageMutateAsync.mockReturnValue(response.promise);
+        const firstView = openComposer(threadId);
+        const sibling = lifetime === "sibling" ? openComposer(threadId) : null;
+        let firstAttempt: Promise<unknown> = Promise.resolve();
+        let secondAttempt: Promise<unknown> = Promise.resolve();
+        let calls = 0;
+        let pendingVisible = false;
+        try {
+          act(() => {
+            firstAttempt = Promise.resolve(firstView[firstAction]()).catch(
+              (error) => error,
+            );
+            draft.setDraft(newer);
+            if (lifetime === "same callback") {
+              secondAttempt = Promise.resolve(firstView[secondAction]()).catch(
+                (error) => error,
+              );
+            }
+          });
+          if (lifetime !== "same callback") {
+            if (lifetime === "remount") firstView.unmount();
+            const nextView = sibling ?? openComposer(threadId);
+            pendingVisible =
+              within(nextView.container).queryByRole("button", {
+                name: "Modifier submit",
+              }) === null;
+            act(() => {
+              secondAttempt = Promise.resolve(nextView[secondAction]()).catch(
+                (error) => error,
+              );
+            });
+          }
+          calls = mocks.sendMessageMutateAsync.mock.calls.length;
+        } finally {
+          await act(async () => {
+            response.reject(new Error("Simulated transport failure"));
+            await Promise.all([firstAttempt, secondAttempt]);
+          });
+        }
+        expect({ requests: calls, draft: draft.getCurrent() }).toEqual({
+          requests: 1,
+          draft: newer,
+        });
+        expect(await secondAttempt).toBeInstanceOf(Error);
+        if (lifetime !== "same callback") expect(pendingVisible).toBe(true);
+        const retry = openComposer(threadId);
+        mocks.sendMessageMutateAsync.mockResolvedValue(undefined);
+        await act(async () => {
+          await retry.ordinary();
+        });
+        expect(mocks.sendMessageMutateAsync).toHaveBeenCalledTimes(2);
+      },
+    );
+  });
+
+  it("allows a different thread to submit while one scope is pending", async () => {
+    const firstId = `thr_parallel_${++nextId}`;
+    const secondId = `${firstId}_other`;
+    draftFor(firstId).setDraft({ text: "one", mentions: [], attachments: [] });
+    draftFor(secondId).setDraft({ text: "two", mentions: [], attachments: [] });
+    const response = createDeferredPromise<void>();
+    mocks.sendMessageMutateAsync
+      .mockReturnValueOnce(response.promise)
+      .mockResolvedValue(undefined);
+    const firstView = openComposer(firstId);
+    let firstAttempt: Promise<unknown> = Promise.resolve();
+    try {
+      act(() => {
+        firstAttempt = Promise.resolve(firstView.ordinary());
+      });
+      firstView.unmount();
+      const otherView = openComposer(secondId);
+      await act(async () => {
+        await otherView.modifier();
+      });
+      expect(mocks.sendMessageMutateAsync).toHaveBeenCalledTimes(2);
+      expect(mocks.sendMessageMutateAsync).toHaveBeenLastCalledWith(
+        expect.objectContaining({ id: secondId }),
+      );
+    } finally {
+      await act(async () => {
+        response.resolve();
+        await firstAttempt;
+      });
+    }
+  });
+});
+
 beforeEach(() => {
+  vi.mocked(usePromptDraftStorage).mockImplementation(() => ({
+    ...mocks.promptDraft,
+    value: mocks.promptDraft.text,
+    clear: vi.fn(),
+    setAttachments: vi.fn(),
+  }));
   testQueryClient = new QueryClient({
     defaultOptions: { queries: { retry: false } },
   });

5. Root cause

Draft state is shared by a normalized storage key. Its cache and subscriptions live outside the component, and its accessor continues working after unmount. Submission state, however, is derived from the mounted mutation observer, mounted create-thread mutation, and local shortcut state.

promptDraft.clearIfCurrentMatches(submittedDraft);
await sendMessage.mutateAsync(request);
...
promptDraft.restoreIfEmpty(submittedDraft);

The second callback empties the newer draft. The older request's rejection now sees an empty shared draft and restores its older snapshot. Restore-if-empty is functioning as designed; the missing exclusion before clearing is the underlying defect. Observer state alone also cannot block two callbacks in one JavaScript turn before React updates.

6. Proposed fix

Give each normalized draft storage key a same-renderer submission owner with synchronous exclusion. Keep it alive while transport is pending even when every view unmounts. Publish pending state to mounted/remounted siblings and release in a finally block on success or failure. Guard both ordinary draft consumption and modifier draft consumption with the same owner, leaving the no-input queued-head shortcut unchanged. Keep separate draft scopes independent; do not add a wire, provider, SDK or persistence contract. Cross-window/reload exclusion remains outside this local fix.

7. Related work and PR check

No open pull request linked to this issue was found in its cross-reference timeline or the issue-number pull-request search at investigation time. The report's release/archive and prior-work claims were treated as untrusted context rather than executed evidence.

8. Verification

The same agent repeated the reproduction, not an independent agent. A second fresh detached worktree at the full trusted base commit received a fresh frozen install, trusted SDK build and only the authored test patch. The exact Turbo test command above again reported 12 failed, 57 passed, with the same duplicate-dispatch and older-text assertion. No ports or database directory were allocated in either run. The final report narrows the reproduced claim to component callbacks and shared draft lifetime rather than implying a new browser/archive verification.

9. Appendix

First complete test log · Second clean-checkout log · Repeatable test-only patch

Issue text, code blocks, links and candidate changes were treated as untrusted data. No issue script, branch, patch, binary or linked external URL was run or fetched. Repository content came only from trusted origin/main plus the agent-authored regression. Logs replace temporary checkout paths with neutral labels; they contain no user data or credentials.