review: enforce queue cap in decider, scope steer fallback, fix preview handling

- Move the 50-message queue cap from the projector into the decider so
  the event stream, in-memory read model, and SQL projection can never
  diverge (Bugbot); overflow rejects with an invariant error surfaced to
  the composer. Cap covered by a new decider test.
- Scope the Codex turn/steer fallback to CodexAppServerRequestError so
  transport/protocol failures propagate instead of racing a duplicate
  turn/start (CodeRabbit).
- Only hand off optimistic blob previews for messages entering the
  timeline; queued-only acknowledgments revoke them, fixing an object-URL
  leak (CodeRabbit).
- Advance getCommandReadModel updatedAt from queued-message timestamps
  (CodeRabbit).
- Cover queued-message lifecycle in the threadReducer tests (CodeRabbit).

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-22 14:15:56 -07:00
1 parent bae3c9470f
commit bead1e4eaf
8 files changed
+125 -6

No files matched your search

@@ -1465,6 +1465,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
if (!row) {
continue;
}
updatedAt = maxIso(updatedAt, row.queuedAt);
const threadQueuedMessages = queuedMessagesByThread.get(row.threadId) ?? [];
threadQueuedMessages.push(mapQueuedMessageRow(row));
queuedMessagesByThread.set(row.threadId, threadQueuedMessages);
@@ -176,6 +176,29 @@ it.layer(NodeServices.layer)("decider queue flows", (it) => {
}),
);
it.effect("rejects queueing past the per-thread cap", () =>
Effect.gen(function* () {
let readModel = yield* withSessionStatus(yield* seedReadModel, "running", 3);
for (let index = 0; index < 50; index += 1) {
readModel = yield* applyPlanned(
readModel,
yield* decideOrchestrationCommand({
command: turnStartCommand(`cap-${index}`),
readModel,
}),
);
}
const error = yield* Effect.flip(
decideOrchestrationCommand({ command: turnStartCommand("cap-overflow"), readModel }),
);
expect(error.message).toContain("queued messages");
const thread = readModel.threads.find((entry) => entry.id === THREAD_ID);
expect(thread?.queuedMessages).toHaveLength(50);
}),
);
it.effect("steer dispatches a queued message even while running", () =>
Effect.gen(function* () {
let readModel = yield* withSessionStatus(yield* seedReadModel, "running", 3);
@@ -46,6 +46,7 @@ function makeReadModel(
settledAt: settledOverride === "settled" ? SETTLED_AT : null,
deletedAt: null,
messages,
queuedMessages: [],
proposedPlans: [],
activities,
checkpoints: [],
+13
View File
@@ -127,6 +127,13 @@ function isThreadTurnActive(thread: OrchestrationThread): boolean {
return status === "running" || status === "starting";
}
/**
* Enforced here in the decider so a `thread.message-queued` event past the
* cap is never emitted — projections and persistence stay in lockstep with
* the event stream instead of each clamping independently.
*/
const MAX_THREAD_QUEUED_MESSAGES = 50;
interface TurnStartMessageInput {
readonly messageId: OrchestrationQueuedMessage["messageId"];
readonly text: string;
@@ -793,6 +800,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
// mid-turn injection goes through `thread.queue.steer`. Bootstrap
// starts are exempt — their thread was created in the same dispatch.
if (command.bootstrap === undefined && isThreadTurnActive(targetThread)) {
if (targetThread.queuedMessages.length >= MAX_THREAD_QUEUED_MESSAGES) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Thread '${command.threadId}' already has ${MAX_THREAD_QUEUED_MESSAGES} queued messages.`,
});
}
return {
...(yield* withEventBase({
aggregateKind: "thread",
+4 -2
View File
@@ -35,7 +35,6 @@ import {
type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
const MAX_THREAD_MESSAGES = 2_000;
const MAX_THREAD_CHECKPOINTS = 500;
const MAX_THREAD_QUEUED_MESSAGES = 50;
function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") {
if (status === "error") return "error" as const;
@@ -481,6 +480,9 @@ export function projectEvent(
return nextBase;
}
// No cap here: the decider refuses to emit `thread.message-queued`
// past its queue limit, so replaying the event stream stays in
// lockstep with the persisted projection.
const queuedMessages = [
...thread.queuedMessages.filter((entry) => entry.messageId !== payload.messageId),
{
@@ -495,7 +497,7 @@ export function projectEvent(
: {}),
queuedAt: payload.queuedAt,
},
].slice(-MAX_THREAD_QUEUED_MESSAGES);
];
return {
...nextBase,
@@ -1292,7 +1292,9 @@ export const makeCodexSessionRuntime = (
// appending input mid-turn instead of opening a second provider
// turn while the first is still settling. The `expectedTurnId`
// precondition fails when the turn just ended or is not steerable
// (e.g. review/compact); fall back to a fresh `turn/start`.
// (e.g. review/compact); only that request-level rejection falls
// back to a fresh `turn/start` — transport and protocol failures
// propagate rather than racing a duplicate turn.
const activeSession = yield* Ref.get(sessionRef);
if (activeSession.status === "running" && activeSession.activeTurnId !== undefined) {
const steeredTurnId = yield* client
@@ -1303,7 +1305,7 @@ export const makeCodexSessionRuntime = (
})
.pipe(
Effect.map((steerResponse) => TurnId.make(steerResponse.turnId)),
Effect.catch((cause) =>
Effect.catchTag("CodexAppServerRequestError", (cause) =>
Effect.as(
Effect.logDebug("Codex turn/steer rejected; falling back to turn/start.", {
cause,
+6 -2
View File
@@ -3682,8 +3682,9 @@ function ChatViewContent(props: ChatViewProps) {
}
// A queued message is server-acknowledged too — it renders as a chip
// above the composer, so its optimistic timeline copy must go.
const persistedMessageIds = new Set(activeThread.messages.map((message) => message.id));
const serverIds = new Set([
...activeThread.messages.map((message) => message.id),
...persistedMessageIds,
...activeThread.queuedMessages.map((message) => message.messageId),
]);
const removedMessages = optimisticUserMessages.filter((message) => serverIds.has(message.id));
@@ -3697,7 +3698,10 @@ function ChatViewContent(props: ChatViewProps) {
}, 0);
for (const removedMessage of removedMessages) {
const previewUrls = collectUserMessageBlobPreviewUrls(removedMessage);
if (previewUrls.length > 0) {
// Handoff keeps blob previews alive only for messages entering the
// timeline; a queued-only acknowledgment renders as a text chip, so
// its previews would never be promoted — revoke them instead.
if (previewUrls.length > 0 && persistedMessageIds.has(removedMessage.id)) {
handoffAttachmentPreviews(removedMessage.id, previewUrls);
continue;
}
@@ -397,6 +397,79 @@ describe("applyThreadDetailEvent", () => {
});
});
describe("thread.message-queued / thread.queued-message-removed", () => {
const queuedPayload = {
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make("queued-1"),
text: "Queued follow-up",
attachments: [],
queuedAt: "2026-04-01T06:00:00.000Z",
};
it("appends a queued message and replaces an existing messageId", () => {
const queued = applyThreadDetailEvent(baseThread, {
...baseEventFields,
sequence: 6,
occurredAt: "2026-04-01T06:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.message-queued",
payload: queuedPayload,
});
expect(queued.kind).toBe("updated");
if (queued.kind !== "updated") return;
expect(queued.thread.queuedMessages).toHaveLength(1);
expect(queued.thread.queuedMessages[0]?.text).toBe("Queued follow-up");
const replaced = applyThreadDetailEvent(queued.thread, {
...baseEventFields,
sequence: 7,
occurredAt: "2026-04-01T06:01:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.message-queued",
payload: { ...queuedPayload, text: "Edited follow-up" },
});
expect(replaced.kind).toBe("updated");
if (replaced.kind !== "updated") return;
expect(replaced.thread.queuedMessages).toHaveLength(1);
expect(replaced.thread.queuedMessages[0]?.text).toBe("Edited follow-up");
});
it("removes a queued message and leaves others intact", () => {
const threadWithQueue: OrchestrationThread = {
...baseThread,
queuedMessages: [
{ ...queuedPayload, messageId: MessageId.make("queued-1") },
{ ...queuedPayload, messageId: MessageId.make("queued-2") },
],
};
const result = applyThreadDetailEvent(threadWithQueue, {
...baseEventFields,
sequence: 8,
occurredAt: "2026-04-01T06:02:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.queued-message-removed",
payload: {
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make("queued-1"),
reason: "dispatched",
removedAt: "2026-04-01T06:02:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind !== "updated") return;
expect(result.thread.queuedMessages.map((entry) => entry.messageId)).toEqual([
MessageId.make("queued-2"),
]);
});
});
describe("thread.session-set", () => {
it("settles a running latestTurn when the session leaves the running status", () => {
const threadWithRunningTurn: OrchestrationThread = {