#5064 · Inline edits do not reserve queued messages
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
Starting an inline edit does not reserve the queued message against automatic claiming. The editor stores a separate unsaved draft while the database continues to hold the previous saved text. When a busy thread becomes idle, the real automatic eligibility predicate and transactional queue claimer accept that saved message, despite the open edit session. A save then receives the database's claimed result; after the claim is consumed and the queue snapshot refreshes, the actual React hook discards its editing state. Two fresh source checkouts reproduce this lifecycle; provider delivery and a live desktop session were not exercised.
2. Claims vs findings
| Claim | Status | Evidence |
|---|---|---|
| An open edit leaves the previous saved payload eligible when the thread becomes idle. | Verified | Actual React edit hook, real automatic server eligibility predicate, and migrated SQLite claim transaction produce one claimed row containing queued-before-edit. |
| Typing changes only the local draft, not the stored queued payload. | Verified | The stored payload is unchanged while the local draft contains still-editing. |
| Removing the consumed row dismisses the unsaved inline editor. | Verified | The hook's visible state and current-state ref are both null after the actual consume operation and a refreshed queue snapshot. |
| Save-time checks reject a claimed message but do not protect the editing interval. | Verified | Claiming already succeeded; an attempted update returns claimed. |
| The reported desktop build sends a provider prompt during the race. | Unverified | No desktop binary, real turn, daemon, transport notification delivery, or provider was used in this investigation. |
3. Environment
- Linux; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.1; frozen repository dependencies.
- Two separate clean checkouts at
587ac3e908468c7b2b6aafd81ea1e84975211162; only the newly authored reproduction test was added. - Each execution creates and migrates its own SQLite :memory: database and creates synthetic host, project, thread, and queue data.
- React hook mounted in jsdom using the repository's testing-library dependency. No mock database, provider, user conversation, real runtime store, development port, or external account.
- Relevant source files remain unchanged at refreshed origin/main
c505f22e61117c7a172f0b378055be81c8457c44; the intervening change concerns prompt-library selection.
4. Minimal reproduction
- Prepare a source checkout and use the ordinary frozen install and Turbo build.
git clone https://github.com/get-bb/bb.git queue-edit-checkout cd queue-edit-checkout git checkout --detach 587ac3e908468c7b2b6aafd81ea1e84975211162 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@bb/app --filter=@bb/db # Save the inline test below at apps/app/src/components/thread/embedded-chat/queued-edit-lifecycle.repro.test.tsx pnpm exec turbo run test --filter=@bb/app -- src/components/thread/embedded-chat/queued-edit-lifecycle.repro.test.tsx
- The test creates an active thread and a queued message waiting on thread-busy, then mounts the actual editing hook with the production server-to-UI queue converter.
- Begin editing and change only the local draft. Confirm the queue payload is still queued-before-edit and no automatic claim is possible while the thread is active.
- Simulate completion by changing only that thread's stored status to idle. Run the actual automatic eligibility function and transactional group claimer.
- Record the claim, attempt a save, consume the claimed row using the production consume function, and refresh the hook's queue snapshot.
Expected: automaticClaimCount = 0 and the inline draft remains still-editing until an explicit edit completion. Actual, verbatim in both runs:
QUEUE_EDIT_EVIDENCE {"draftBeforeClaim":"still-editing","automaticClaimCount":1,"claimedSavedText":[{"type":"text","text":"queued-before-edit","mentions":[]}],"saveResult":"claimed","removed":true,"editorAfterRemoval":"dismissed"}
AssertionError: expected 1 to be +0
Test Files 1 failed (1)
Tests 1 failed (1)
This regression test intentionally fails on unchanged production code. Its assertion failure is the bug evidence, not a setup/import/native-module error. The fixture manually performs the consume and rerender steps to isolate their actual behavior; it does not pretend that a provider was invoked.
Complete inline reproduction test
// @vitest-environment jsdom
import { act, cleanup, renderHook } from "@testing-library/react";
import { expect, it } from "vitest";
import type { PromptInput } from "@bb/domain";
import {
claimNextQueuedThreadMessageGroup,
createConnection,
createProject,
createQueuedThreadMessage,
createThread,
deleteClaimedQueuedThreadMessageBatchInTransaction,
getThread,
listQueuedThreadMessages,
migrate,
noopNotifier,
updateQueuedThreadMessage,
upsertHost,
} from "../../../../../../packages/db/src/index";
import { createAutomaticQueuedMessageGroupEligibility } from "../../../../../../apps/server/src/services/threads/queued-messages";
import { toThreadQueuedMessage } from "../../../../../../apps/server/src/services/threads/thread-queued-messages";
import { NotificationHub } from "../../../../../../apps/server/src/ws/hub";
import { useInlineQueuedMessageEditing } from "./useInlineQueuedMessageEditing";
function messageInput(text: string): PromptInput[] {
return [{ type: "text", text, mentions: [] }];
}
it("keeps a queued message unclaimed until its inline edit finishes", () => {
const connection = createConnection(":memory:");
migrate(connection);
try {
const host = upsertHost(connection, noopNotifier, { name: "repro-host" });
const { project } = createProject(connection, noopNotifier, {
name: "queue-edit-repro",
source: {
type: "local_path",
hostId: host.id,
path: "/tmp/queue-edit-repro-workspace",
},
});
const thread = createThread(connection, noopNotifier, {
projectId: project.id,
providerId: "repro-provider",
status: "active",
});
const queued = createQueuedThreadMessage(connection, noopNotifier, {
threadId: thread.id,
content: messageInput("queued-before-edit"),
model: "repro-model",
reasoningLevel: "medium",
permissionMode: "full",
serviceTier: "default",
waitingOn: { kind: "thread-busy" },
sendAt: null,
payload: { kind: "inline" },
systemNotice: null,
});
const hub = new NotificationHub();
const claimEligibleMessages = () => {
const snapshot = getThread(connection, thread.id);
if (!snapshot) throw new Error("Fixture thread disappeared");
return claimNextQueuedThreadMessageGroup(
connection,
noopNotifier,
thread.id,
createAutomaticQueuedMessageGroupEligibility(
{ db: connection, hub },
{ now: Date.now(), retryingFailure: false, thread: snapshot },
),
);
};
const initialProps = {
ownerThreadId: thread.id,
queuedMessages: listQueuedThreadMessages(connection, thread.id).map(
toThreadQueuedMessage,
),
};
const editor = renderHook(useInlineQueuedMessageEditing, { initialProps });
act(() => {
editor.result.current.beginEditQueuedMessage({
queuedMessageId: queued.id,
queuedMessageIndex: 0,
});
});
act(() => {
const draftSession = editor.result.current.queuedMessageDraftSession;
if (!draftSession) throw new Error("Inline edit did not open");
draftSession.setDraft((draft) => ({ ...draft, text: "still-editing" }));
});
expect(editor.result.current.inlineEditingQueuedMessage?.draft.text).toBe(
"still-editing",
);
expect(claimEligibleMessages()).toBeNull();
expect(listQueuedThreadMessages(connection, thread.id)[0]?.content).toBe(
JSON.stringify(messageInput("queued-before-edit")),
);
connection.$client
.prepare("UPDATE threads SET status = ? WHERE id = ?")
.run("idle", thread.id);
const claimed = claimEligibleMessages();
const evidence = {
draftBeforeClaim:
editor.result.current.inlineEditingQueuedMessage?.draft.text,
automaticClaimCount: claimed?.length ?? 0,
claimedSavedText: claimed?.[0]
? toThreadQueuedMessage(claimed[0]).content
: null,
saveResult: "not-attempted",
removed: false,
editorAfterRemoval: "not-observed",
};
if (claimed) {
evidence.saveResult = updateQueuedThreadMessage(
connection,
noopNotifier,
{
id: queued.id,
threadId: thread.id,
content: messageInput("still-editing"),
expectedUpdatedAt: queued.updatedAt,
},
).kind;
evidence.removed = connection.transaction((transaction) =>
deleteClaimedQueuedThreadMessageBatchInTransaction(transaction, {
queuedMessages: claimed,
}),
);
editor.rerender({
ownerThreadId: thread.id,
queuedMessages: listQueuedThreadMessages(connection, thread.id).map(
toThreadQueuedMessage,
),
});
evidence.editorAfterRemoval =
editor.result.current.inlineEditingQueuedMessage === null &&
editor.result.current.inlineEditingQueuedMessageRef.current === null
? "dismissed"
: "retained";
}
console.info("QUEUE_EDIT_EVIDENCE", JSON.stringify(evidence));
expect(evidence.automaticClaimCount).toBe(0);
expect(editor.result.current.inlineEditingQueuedMessage?.draft.text).toBe(
"still-editing",
);
} finally {
cleanup();
connection.$client.close();
}
});
5. Root cause
Begin-edit is synchronous and local. It copies the existing content and version into React state and invokes an optional UI callback; it neither acquires a server reservation nor changes queue eligibility.
apps/app/src/components/thread/embedded-chat/useInlineQueuedMessageEditing.ts:115
const beginEditQueuedMessage = useCallback(
({ queuedMessageId, queuedMessageIndex }: QueuedMessageEditRequest) => {
const queuedMessage = queuedMessagesByIdRef.current.get(queuedMessageId);
if (!queuedMessage) {
return;
}
commitInlineQueuedMessage({
draft: queuedInputToDraft(queuedMessage.content),
editSessionId: (inlineEditSessionIdRef.current += 1),
expectedUpdatedAt: queuedMessage.updatedAt,
model: queuedMessage.model,
ownerThreadId,
permissionMode: queuedMessage.permissionMode,
queuedMessageId,
queuedMessageIndex,
reasoningLevel: queuedMessage.reasoningLevel,
serviceTier: queuedMessage.serviceTier,
});
onBeginEdit?.();
},
[commitInlineQueuedMessage, onBeginEdit, ownerThreadId],
The production automatic predicate resolves a thread-busy wait when the thread becomes idle or pending. There is no edit-session condition in this decision.
apps/server/src/services/threads/queued-messages.ts:132
export function createAutomaticQueuedMessageGroupEligibility(
deps: Pick<AppDeps, "db" | "hub">,
args: { now: number; retryingFailure: boolean; thread: Thread },
): QueuedThreadMessageGroupEligibility {
const activeTurnId = getActiveTurnId(deps, args.thread.id);
return (group) =>
group.every((member) => {
if (member.failureReason !== null && !args.retryingFailure) return false;
const waitingOn = parseStoredQueuedThreadMessageWaitingOn(member);
switch (waitingOn?.kind) {
case undefined:
case "plugin":
return true;
case "time":
return member.sendAt !== null && member.sendAt <= args.now;
case "thread-busy":
case "stopping":
return (
args.thread.status === "idle" || args.thread.status === "pending"
);
case "turn-starting":
return (
args.thread.status === "idle" ||
(args.thread.status === "active" && activeTurnId !== null)
);
case "host-offline": {
const environment =
The immediate transaction partitions queued messages, checks existing eligibility and the manual-stop pause, then claims all members of the chosen group. The atomic transaction protects existing claim policy, but no editing reservation exists for it to enforce.
packages/db/src/data/queued-thread-messages.ts:1048
const queuedMessages = listQueuedThreadMessages(tx, threadId);
const pauseOrdinaryMessages = isThreadQueueAutoSendPaused(tx, threadId);
const group =
partitionQueuedMessageGroups(queuedMessages).find((rows) => {
const eligible =
rows.some(isIdleDrainableQueuedMessage) && isGroupEligible(rows);
return (
eligible &&
isAutomaticQueuedThreadMessageGroupClaimAllowed(
rows,
pauseOrdinaryMessages,
false,
)
);
}) ?? null;
if (group === null) {
return null;
}
return claimQueuedThreadMessageIdsInTransaction(
tx,
group.map((row) => row.id),
);
},
{ behavior: "immediate" },
);
Normal completion schedules a queue-dispatch wake, and the automatic drain uses exactly this eligibility/claim pair. This source-backed connection explains why the isolated active-to-idle transition reaches the same claim policy.
apps/server/src/internal/events.ts:474
}
if (
event.status === "completed" &&
turnCompleted.nextStatus === "idle"
) {
followUps.push({
kind: "queued-message-dispatch",
wake: { kind: "thread-ready", threadId: entry.threadId },
});
}
apps/server/src/services/threads/queued-messages.ts:846
export async function sendNextQueuedMessageIfPresent(
deps: LoggedPendingInteractionWorkSessionDeps,
args: { threadId: string },
): Promise<boolean> {
const initialThread = getThread(deps.db, args.threadId);
if (!isQueuedMessageAutoSendCandidate(initialThread)) {
return false;
}
const nextQueuedMessages = claimNextQueuedThreadMessageGroup(
deps.db,
deps.hub,
args.threadId,
createAutomaticQueuedMessageGroupEligibility(deps, {
now: Date.now(),
retryingFailure: false,
thread: initialThread,
}),
);
if (!nextQueuedMessages) {
return false;
}
After removal, the hook derives null editing state from absence of the queue row and actively dismisses its stored state. Save-time version checks do not protect the interval before Save.
apps/app/src/components/thread/embedded-chat/useInlineQueuedMessageEditing.ts:90
const inlineEditingQueuedMessage = useMemo(
() =>
inlineEditingQueuedMessageState !== null &&
inlineEditingQueuedMessageState.ownerThreadId === ownerThreadId &&
queuedMessages.some(
(message) =>
message.id === inlineEditingQueuedMessageState.queuedMessageId,
)
? inlineEditingQueuedMessageState
: null,
[inlineEditingQueuedMessageState, ownerThreadId, queuedMessages],
);
useEffect(() => {
if (
inlineEditingQueuedMessageState !== null &&
inlineEditingQueuedMessage === null
) {
dismissInlineQueuedMessageEditor();
}
packages/server-contract/src/api/threads.ts:378
export const updateQueuedMessageRequestSchema = z.object({
expectedUpdatedAt: z.number().int().nonnegative(),
input: z.array(promptInputSchema).min(1),
});
export type UpdateQueuedMessageRequest = z.infer<
typeof updateQueuedMessageRequestSchema
>;
apps/server/src/routes/threads/actions.ts:333
const result = updateQueuedThreadMessage(deps.db, deps.hub, {
content: input,
expectedUpdatedAt: payload.expectedUpdatedAt,
id: context.req.param("queuedMessageId"),
threadId: thread.id,
});
if (result.kind === "not_found") {
throw new ApiError(404, "invalid_request", "Queued message not found");
}
if (result.kind === "claimed") {
throw new ApiError(
409,
"invalid_request",
"Queued message is already being sent",
);
6. Proposed fix and simple-fix gate
Introduce server-recognized edit admission ordered atomically against dispatch claiming. If dispatch has already claimed the item, do not open an editable session; if editing wins, exclude the held row and its dispatch group until Save or Cancel. Save must atomically update the payload and release the hold; Cancel must release the hold without changing the saved payload. Group membership and explicit-send behavior must respect the same admission rule.
The ownership, disconnected-client cleanup, expiry/recovery, and multi-client behavior require an explicit lifecycle design. Reusing the existing manual-stop pause would block unrelated messages and does not implement per-item admission. Merely retaining the React draft would leave the saved payload dispatchable.
No pull request: a root-cause repair spans UI and server/queue lifecycle and requires a new coordinated edit-admission contract. That violates this rule's one-subsystem/no-public-contract/no-design-decision simple-fix conditions. No production patch or stopped fix was pushed. No open pull request links to the issue in the reviewed issue timeline or repository search.
7. Verification
The same agent repeated the test in a second clean temporary checkout at the exact recorded base commit. Both checkouts were clean before adding the newly authored test, both used separate installs and builds, and every test execution created a new migrated in-memory database. No ports or persistent data directory were required. This is a repeated clean verification, not an independent-agent review.
Command in each checkout: pnpm exec turbo run test --filter=@bb/app -- src/components/thread/embedded-chat/queued-edit-lifecycle.repro.test.tsx. Result in each: exit 1 at the intended zero-claims assertion with identical evidence. No report correction was needed.
Second checkout evidence
QUEUE_EDIT_EVIDENCE {"draftBeforeClaim":"still-editing","automaticClaimCount":1,"claimedSavedText":[{"type":"text","text":"queued-before-edit","mentions":[]}],"saveResult":"claimed","removed":true,"editorAfterRemoval":"dismissed"}
AssertionError: expected 1 to be +0
Test Files 1 failed (1)
Tests 1 failed (1)
Relevant existing database tests pass unchanged:
pnpm exec turbo run test --filter=@bb/db -- test/data/queued-thread-messages.test.ts test/data/queued-message-waits.test.ts test/data/queued-message-waits.test.ts: 13 passed test/data/queued-thread-messages.test.ts: 31 passed Test Files 2 passed (2) Tests 44 passed (44)
Both scoped Turbo builds passed. git diff --check passed. All code excerpts come from git show at the recorded trusted commit.
8. Related issues
Repository search also found #1585 (queued-message keyboard editing) and #1864 (queued-message execution-setting editing). Neither establishes per-item exclusion from automatic claiming. No linked open pull request was available for review.
9. Appendix and limits
Issue content was treated only as untrusted claims. Its scripts, commands, proposed changes, and external links were not executed or fetched. This test was authored from trusted origin/main source and existing test patterns.
Additional investigation commands: git fetch origin main; git log 587ac3e908468c7b2b6aafd81ea1e84975211162..origin/main --oneline; path-limited git diff against refreshed origin/main; read-only GitHub issue-property, label, comment, cross-reference, and pull-request queries; pnpm exec oxfmt on the newly authored test; git diff --check.
Raw build/test logs and the runnable test remain outside the public reports repository. Repository publication policy requires reproduction code and sanitized evidence inline rather than committed script/log artifacts. This is a queue/editor lifecycle defect, not a screenshot-based appearance assessment; no visual screenshot or live provider-delivery claim is made. Synthetic strings are used throughout. A live multi-client/provider test remains appropriate when implementing the lifecycle contract.