From 2218b91213dd6303e65cf14faea4af55587342e5 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 22 Jul 2026 16:24:38 -0700 Subject: [PATCH] review round 3: event-driven pending-start guard, queue ack in all phases, attachment cleanup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add pendingTurnStart to the thread read model, set by thread.turn-start-requested and cleared when the session adopts the turn (running with activeTurnId) or fails/stops. The decider's queue-by-default, drain, and steer guards now cover the window between dispatching a turn start and the provider reporting session status — a send racing in behind a drain queues instead of opening a second concurrent turn (Bugbot + Macroscope). Hydrated from the existing SQL pending-turn-start rows on restart; the settle guard keeps its timestamp heuristic (renamed hasRecentUnadoptedUserMessage) since client-supplied clocks must not drive dispatch decisions. - Acknowledge a projected expectedMessageId in every composer phase, not just running: sends during 'connecting' also queue server-side (Bugbot + Macroscope). - Prune attachment files when a queued message is removed by the user; dispatch removals keep them since the same attachments re-enter the timeline via the paired message-sent (Macroscope). - Restrict the Codex turn/steer fallback to receive-response request errors (server rejected the steer). Response-decode failures on an accepted steer propagate instead of double-sending the input via turn/start (Macroscope). Co-Authored-By: Claude Fable 5 --- apps/mobile/src/lib/threadActivity.test.ts | 1 + .../Layers/OrchestrationEngine.test.ts | 2 + .../Layers/ProjectionPipeline.ts | 30 ++++++- .../Layers/ProjectionSnapshotQuery.test.ts | 1 + .../Layers/ProjectionSnapshotQuery.ts | 70 +++++++++++++++ .../Layers/ProviderCommandReactor.test.ts | 25 +++++- .../orchestration/commandInvariants.test.ts | 2 + .../src/orchestration/decider.queue.test.ts | 36 ++++++++ .../src/orchestration/decider.settled.test.ts | 1 + apps/server/src/orchestration/decider.ts | 88 ++++++++++++------- .../src/orchestration/projector.test.ts | 1 + apps/server/src/orchestration/projector.ts | 39 ++++++++ .../provider/Layers/CodexSessionRuntime.ts | 27 +++--- apps/server/src/server.test.ts | 2 + .../web/src/components/ChatView.logic.test.ts | 1 + apps/web/src/components/ChatView.logic.ts | 17 ++-- .../components/CommandPalette.logic.test.ts | 1 + apps/web/src/components/Sidebar.logic.test.ts | 1 + apps/web/src/lib/threadSort.test.ts | 1 + apps/web/src/worktreeCleanup.test.ts | 1 + .../client-runtime/src/state/entities.test.ts | 2 + .../src/state/threadReducer.test.ts | 1 + .../client-runtime/src/state/threadReducer.ts | 18 ++++ .../src/state/threads-sync.test.ts | 1 + packages/contracts/src/orchestration.ts | 13 +++ 25 files changed, 326 insertions(+), 56 deletions(-) diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 681e873138..8072034079 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -46,6 +46,7 @@ function makeThread( deletedAt: null, messages: [], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], activities: [], checkpoints: [], diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts index 3a6967ee3f..9085b61e56 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts @@ -151,6 +151,7 @@ describe("OrchestrationEngine", () => { deletedAt: null, messages: [], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], activities: [], checkpoints: [], @@ -164,6 +165,7 @@ describe("OrchestrationEngine", () => { ...thread, messages: [], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], activities: [], checkpoints: [], diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index dc060c19a6..4dc0cf8083 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -936,7 +936,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti const applyQueuedMessagesProjection: ProjectorDefinition["apply"] = Effect.fn( "applyQueuedMessagesProjection", - )(function* (event, _attachmentSideEffects) { + )(function* (event, attachmentSideEffects) { switch (event.type) { case "thread.message-queued": yield* projectionQueuedMessageRepository.upsert({ @@ -951,12 +951,38 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti }); return; - case "thread.queued-message-removed": + case "thread.queued-message-removed": { + // A user removal orphans the removed message's attachment files — + // prune to what the timeline and remaining queue still reference. + // Dispatch removals keep everything: the same attachments re-enter + // the timeline via the paired thread.message-sent. + const removedQueuedMessage = + event.payload.reason === "user" + ? (yield* projectionQueuedMessageRepository.listByThreadId({ + threadId: event.payload.threadId, + })).find((entry) => entry.messageId === event.payload.messageId) + : undefined; yield* projectionQueuedMessageRepository.deleteByMessageId({ threadId: event.payload.threadId, messageId: event.payload.messageId, }); + if (removedQueuedMessage && (removedQueuedMessage.attachments?.length ?? 0) > 0) { + const retainedMessageRows = yield* projectionThreadMessageRepository.listByThreadId({ + threadId: event.payload.threadId, + }); + const retainedQueuedRows = yield* projectionQueuedMessageRepository.listByThreadId({ + threadId: event.payload.threadId, + }); + attachmentSideEffects.prunedThreadRelativePaths.set( + event.payload.threadId, + collectThreadAttachmentRelativePaths(event.payload.threadId, [ + ...retainedMessageRows, + ...retainedQueuedRows, + ]), + ); + } return; + } case "thread.deleted": yield* projectionQueuedMessageRepository.deleteByThreadId({ diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts index 77ae484bc4..24d883ee54 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -323,6 +323,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { }, ], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [ { id: "plan-1", diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index dbe5327ea9..5a00c9d5cb 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -655,6 +655,30 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { `, }); + const PendingTurnStartDbRowSchema = Schema.Struct({ + threadId: ThreadId, + messageId: MessageId, + requestedAt: IsoDateTime, + }); + + const listPendingTurnStartRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: PendingTurnStartDbRowSchema, + execute: () => + sql` + SELECT + thread_id AS "threadId", + pending_message_id AS "messageId", + requested_at AS "requestedAt" + FROM projection_turns + WHERE turn_id IS NULL + AND state = 'pending' + AND pending_message_id IS NOT NULL + AND checkpoint_turn_count IS NULL + ORDER BY thread_id ASC, requested_at DESC + `, + }); + const listActiveLatestTurnRows = SqlSchema.findAll({ Request: Schema.Void, Result: ProjectionLatestTurnDbRowSchema, @@ -1050,6 +1074,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ), ), ), + listPendingTurnStartRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getSnapshot:listPendingTurnStarts:query", + "ProjectionSnapshotQuery.getSnapshot:listPendingTurnStarts:decodeRows", + ), + ), + ), listThreadActivityRows(undefined).pipe( Effect.mapError( toPersistenceSqlOrDecodeError( @@ -1100,6 +1132,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { messageRows, proposedPlanRows, queuedMessageRows, + pendingTurnStartRows, activityRows, sessionRows, checkpointRows, @@ -1109,6 +1142,19 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { Effect.gen(function* () { const messagesByThread = new Map>(); const queuedMessagesByThread = new Map>(); + // Rows are ordered requested_at DESC per thread; first wins. + const pendingTurnStartByThread = new Map< + string, + { messageId: MessageId; requestedAt: string } + >(); + for (const row of pendingTurnStartRows) { + if (!pendingTurnStartByThread.has(row.threadId)) { + pendingTurnStartByThread.set(row.threadId, { + messageId: row.messageId, + requestedAt: row.requestedAt, + }); + } + } const proposedPlansByThread = new Map>(); const activitiesByThread = new Map>(); const checkpointsByThread = new Map>(); @@ -1283,6 +1329,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { deletedAt: row.deletedAt, messages: messagesByThread.get(row.threadId) ?? [], queuedMessages: queuedMessagesByThread.get(row.threadId) ?? [], + pendingTurnStart: pendingTurnStartByThread.get(row.threadId) ?? null, proposedPlans: proposedPlansByThread.get(row.threadId) ?? [], activities: activitiesByThread.get(row.threadId) ?? [], checkpoints: checkpointsByThread.get(row.threadId) ?? [], @@ -1347,6 +1394,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ), ), ), + listPendingTurnStartRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getCommandReadModel:listPendingTurnStarts:query", + "ProjectionSnapshotQuery.getCommandReadModel:listPendingTurnStarts:decodeRows", + ), + ), + ), listThreadSessionRows(undefined).pipe( Effect.mapError( toPersistenceSqlOrDecodeError( @@ -1380,6 +1435,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { threadRows, proposedPlanRows, queuedMessageRows, + pendingTurnStartRows, sessionRows, latestTurnRows, stateRows, @@ -1458,6 +1514,19 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { } const proposedPlansByThread = new Map>(); const queuedMessagesByThread = new Map>(); + // Rows are ordered requested_at DESC per thread; first wins. + const pendingTurnStartByThread = new Map< + string, + { messageId: MessageId; requestedAt: string } + >(); + for (const row of pendingTurnStartRows) { + if (!pendingTurnStartByThread.has(row.threadId)) { + pendingTurnStartByThread.set(row.threadId, { + messageId: row.messageId, + requestedAt: row.requestedAt, + }); + } + } const sessionByThread = new Map(); for (let index = 0; index < queuedMessageRows.length; index += 1) { @@ -1512,6 +1581,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { deletedAt: row.deletedAt, messages: [], queuedMessages: queuedMessagesByThread.get(row.threadId) ?? [], + pendingTurnStart: pendingTurnStartByThread.get(row.threadId) ?? null, proposedPlans: proposedPlansByThread.get(row.threadId) ?? [], activities: [], checkpoints: [], diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 0546c3ac3c..3629b1987e 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -424,15 +424,34 @@ describe("ProviderCommandReactor", () => { // back to ready first — in production, turn completion does this. The // projected session is preserved apart from status/activeTurnId so // provider identity fields survive the settle. + const harnessRuntime = runtime; let settleIndex = 0; const settleSession = async (threadId: ThreadId = ThreadId.make("thread-1")) => { settleIndex += 1; - const readModel = await runtime.runPromise(snapshotQuery.getSnapshot()); + const readModel = await harnessRuntime.runPromise(snapshotQuery.getSnapshot()); const session = readModel.threads.find((entry) => entry.id === threadId)?.session; if (!session) { return; } - await runtime.runPromise( + // Mirror the real lifecycle: report the turn running (stamping + // latestTurn so the decider's pending-turn-start guard clears), then + // settle back to ready. A lone ready-set would leave latestTurn null + // and the just-sent message would read as a still-pending start. + await harnessRuntime.runPromise( + engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make(`cmd-session-run-${settleIndex}`), + threadId, + session: { + ...session, + status: "running", + activeTurnId: asTurnId(`turn-settle-${settleIndex}`), + updatedAt: now, + }, + createdAt: now, + }), + ); + await harnessRuntime.runPromise( engine.dispatch({ type: "thread.session.set", commandId: CommandId.make(`cmd-session-settle-${settleIndex}`), @@ -441,6 +460,7 @@ describe("ProviderCommandReactor", () => { ...session, status: "ready", activeTurnId: null, + updatedAt: now, }, createdAt: now, }), @@ -1470,6 +1490,7 @@ describe("ProviderCommandReactor", () => { return thread?.runtimeMode === "approval-required"; }); await waitFor(() => harness.startSession.mock.calls.length === 2); + await harness.settleSession(); await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", diff --git a/apps/server/src/orchestration/commandInvariants.test.ts b/apps/server/src/orchestration/commandInvariants.test.ts index 1ad94a1d9b..bd0ef53344 100644 --- a/apps/server/src/orchestration/commandInvariants.test.ts +++ b/apps/server/src/orchestration/commandInvariants.test.ts @@ -73,6 +73,7 @@ const readModel: OrchestrationReadModel = { latestTurn: null, messages: [], queuedMessages: [], + pendingTurnStart: null, session: null, activities: [], proposedPlans: [], @@ -99,6 +100,7 @@ const readModel: OrchestrationReadModel = { latestTurn: null, messages: [], queuedMessages: [], + pendingTurnStart: null, session: null, activities: [], proposedPlans: [], diff --git a/apps/server/src/orchestration/decider.queue.test.ts b/apps/server/src/orchestration/decider.queue.test.ts index 2f9fea8e65..5aabf54ddc 100644 --- a/apps/server/src/orchestration/decider.queue.test.ts +++ b/apps/server/src/orchestration/decider.queue.test.ts @@ -176,6 +176,42 @@ it.layer(NodeServices.layer)("decider queue flows", (it) => { }), ); + it.effect("queues a follow-up racing in behind a just-dispatched turn start", () => + Effect.gen(function* () { + // First send on an idle thread: dispatches message-sent + + // turn-start-requested, but the provider has not reported any + // session status yet — the pending-start window. + let readModel = yield* seedReadModel; + readModel = yield* applyPlanned( + readModel, + yield* decideOrchestrationCommand({ command: turnStartCommand("pending-1"), readModel }), + ); + + // Second send in that window must queue, not open a second turn. + const planned = yield* decideOrchestrationCommand({ + command: turnStartCommand("pending-2"), + readModel, + }); + const events = Array.isArray(planned) ? planned : [planned]; + expect(events.map((event) => event.type)).toEqual(["thread.message-queued"]); + + // A drain in the same window is rejected and keeps the queue intact. + readModel = yield* applyPlanned(readModel, planned); + const drainError = yield* Effect.flip( + decideOrchestrationCommand({ + command: { + type: "thread.queue.drain", + commandId: asCommandId("cmd-drain-pending"), + threadId: THREAD_ID, + createdAt: NOW, + }, + readModel, + }), + ); + expect(drainError.message).toContain("busy"); + }), + ); + it.effect("rejects queueing past the per-thread cap", () => Effect.gen(function* () { let readModel = yield* withSessionStatus(yield* seedReadModel, "running", 3); diff --git a/apps/server/src/orchestration/decider.settled.test.ts b/apps/server/src/orchestration/decider.settled.test.ts index 0ba56d460d..45217534ac 100644 --- a/apps/server/src/orchestration/decider.settled.test.ts +++ b/apps/server/src/orchestration/decider.settled.test.ts @@ -47,6 +47,7 @@ function makeReadModel( deletedAt: null, messages, queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], activities, checkpoints: [], diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 23d37d7e8f..ed83947bf1 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -127,6 +127,41 @@ function isThreadTurnActive(thread: OrchestrationThread): boolean { return status === "running" || status === "starting"; } +/** + * Settle-guard heuristic: the latest user message is newer than any turn + * activity, i.e. a turn start that no session has picked up yet. Message + * timestamps are client-supplied, so queue/dispatch decisions must NOT + * hang off this (see `pendingTurnStart` on the thread for the event-driven + * signal); settle tolerates the skew — it merely delays settling within + * the grace window. + */ +function hasRecentUnadoptedUserMessage(thread: OrchestrationThread, occurredAt: string): boolean { + const latestUserMessageAtMs = thread.messages.reduce( + (latest, message) => + message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest, + Number.NEGATIVE_INFINITY, + ); + const latestTurnAtMs = + thread.latestTurn === null + ? Number.NEGATIVE_INFINITY + : Math.max( + ...[ + thread.latestTurn.requestedAt, + thread.latestTurn.startedAt, + thread.latestTurn.completedAt, + ].map((candidate) => + candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate), + ), + ); + const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs; + return ( + thread.session?.status !== "error" && + Number.isFinite(latestUserMessageAtMs) && + latestUserMessageAtMs > latestTurnAtMs && + Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS + ); +} + /** * Enforced here in the decider so a `thread.message-queued` event past the * cap is never emitted — projections and persistence stay in lockstep with @@ -599,35 +634,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // last user message postdates their turn timestamps (older-server // data, mid-turn messages) must stay settleable. A failed session // start (status "error") clears the block immediately. - const latestUserMessageAtMs = thread.messages.reduce( - (latest, message) => - message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest, - Number.NEGATIVE_INFINITY, - ); - const latestTurnAtMs = - thread.latestTurn === null - ? Number.NEGATIVE_INFINITY - : Math.max( - ...[ - thread.latestTurn.requestedAt, - thread.latestTurn.startedAt, - thread.latestTurn.completedAt, - ].map((candidate) => - candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate), - ), - ); - // The age check is bounded on BOTH sides: message timestamps are - // client-supplied, so a client clock ahead of the server yields a - // negative age. Without the lower bound that negative age satisfies - // `<= grace` for as long as the skew lasts, extending the settle - // block far past the intended two minutes. - const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs; - const hasQueuedTurnStart = - thread.session?.status !== "error" && - Number.isFinite(latestUserMessageAtMs) && - latestUserMessageAtMs > latestTurnAtMs && - Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS; - if (hasQueuedTurnStart) { + if (hasRecentUnadoptedUserMessage(thread, occurredAt)) { return yield* Effect.fail( new OrchestrationCommandInvariantError({ commandType: command.type, @@ -799,7 +806,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // held server-side and drained on natural turn completion. Explicit // 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)) { + // `pendingTurnStart` covers the window where a turn start was just + // dispatched (by a send or a queue drain) but the provider has not + // reported the session status yet — a send in that gap must queue, + // not open a second concurrent turn ahead of already-queued chips. + if ( + command.bootstrap === undefined && + (isThreadTurnActive(targetThread) || targetThread.pendingTurnStart !== null) + ) { if (targetThread.queuedMessages.length >= MAX_THREAD_QUEUED_MESSAGES) { return yield* new OrchestrationCommandInvariantError({ commandType: command.type, @@ -864,9 +878,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // steer into — dispatching now would race the pending turn/start with // a second one. The message stays queued; steer again once running. // A `starting` session that already tracks an active turn (provider - // reconnect mid-turn) is steerable, so only the pending-start shape - // — starting with no active turn — is rejected. - if (thread.session?.status === "starting" && thread.session.activeTurnId === null) { + // reconnect mid-turn) is steerable. Rejected shapes: starting with no + // active turn, and a seemingly-idle session whose just-dispatched + // turn start the provider has not adopted yet. + const steerRacesPendingStart = + (thread.session?.status === "starting" && thread.session.activeTurnId === null) || + (thread.session?.status !== "running" && thread.pendingTurnStart !== null); + if (steerRacesPendingStart) { return yield* new OrchestrationCommandInvariantError({ commandType: command.type, detail: `Thread '${command.threadId}' is still starting a turn; steer once it is running.`, @@ -931,7 +949,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" } // The user may have raced a new message in between turn completion and // this drain; keep the queue intact and let the next completion retry. - if (isThreadTurnActive(thread)) { + // The pending-start check also stops a duplicate drain from double- + // dispatching while the first drained turn's session is still unset. + if (isThreadTurnActive(thread) || thread.pendingTurnStart !== null) { return yield* new OrchestrationCommandInvariantError({ commandType: command.type, detail: `Thread '${command.threadId}' is busy; queued messages drain on turn completion.`, diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts index 8af9bb958d..24a25dcbba 100644 --- a/apps/server/src/orchestration/projector.test.ts +++ b/apps/server/src/orchestration/projector.test.ts @@ -94,6 +94,7 @@ describe("orchestration projector", () => { deletedAt: null, messages: [], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], activities: [], checkpoints: [], diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 6434cb4fdf..080de70d82 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -30,6 +30,7 @@ import { ThreadRevertedPayload, ThreadSessionSetPayload, ThreadTurnDiffCompletedPayload, + ThreadTurnStartRequestedPayload, } from "./Schemas.ts"; type ThreadPatch = Partial>; @@ -295,6 +296,7 @@ export function projectEvent( deletedAt: null, messages: [], queuedMessages: [], + pendingTurnStart: null, activities: [], checkpoints: [], session: null, @@ -538,6 +540,31 @@ export function projectEvent( }), ); + case "thread.turn-start-requested": + return decodeForEvent( + ThreadTurnStartRequestedPayload, + event.payload, + event.type, + "payload", + ).pipe( + Effect.map((payload) => { + const thread = nextBase.threads.find((entry) => entry.id === payload.threadId); + if (!thread) { + return nextBase; + } + return { + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + pendingTurnStart: { + messageId: payload.messageId, + requestedAt: payload.createdAt, + }, + updatedAt: event.occurredAt, + }), + }; + }), + ); + case "thread.session-set": return Effect.gen(function* () { const payload = yield* decodeForEvent( @@ -561,10 +588,22 @@ export function projectEvent( // Leaving the "running" session status is the turn-end signal: settle // a still-running latest turn so its duration reflects the whole turn. const settledTurnState = settledTurnStateForSessionStatus(session.status); + // Mirrors the SQL pipeline's pending-turn-start clearing: a running + // session with an active turn adopts the pending start, and terminal + // statuses (error/stopped/interrupted) abandon it. "starting" and + // idle-ish statuses leave it pending. + const pendingTurnStart = + (session.status === "running" && session.activeTurnId !== null) || + session.status === "error" || + session.status === "stopped" || + session.status === "interrupted" + ? null + : thread.pendingTurnStart; return { ...nextBase, threads: updateThread(nextBase.threads, payload.threadId, { session, + pendingTurnStart, latestTurn: session.status === "running" && session.activeTurnId !== null ? { diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index a830e82ee2..92144c7f3c 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -1292,9 +1292,12 @@ 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); only that request-level rejection falls - // back to a fresh `turn/start` — transport and protocol failures - // propagate rather than racing a duplicate turn. + // (e.g. review/compact); only a server rejection of the request + // itself (operation "receive-response" — the steer was NOT + // applied) falls back to a fresh `turn/start`. Decode failures on + // an accepted steer's response, and transport/protocol failures, + // propagate: the input may already be appended, and retrying via + // turn/start would duplicate it. const activeSession = yield* Ref.get(sessionRef); if (activeSession.status === "running" && activeSession.activeTurnId !== undefined) { const steeredTurnId = yield* client @@ -1305,13 +1308,17 @@ export const makeCodexSessionRuntime = ( }) .pipe( Effect.map((steerResponse) => TurnId.make(steerResponse.turnId)), - Effect.catchTag("CodexAppServerRequestError", (cause) => - Effect.as( - Effect.logDebug("Codex turn/steer rejected; falling back to turn/start.", { - cause, - }), - null, - ), + Effect.catchIf( + (cause): cause is CodexErrors.CodexAppServerRequestError => + cause._tag === "CodexAppServerRequestError" && + cause.operation === "receive-response", + (cause) => + Effect.as( + Effect.logDebug("Codex turn/steer rejected; falling back to turn/start.", { + cause, + }), + null, + ), ), ); if (steeredTurnId !== null) { diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 1a3e46015f..759c2b1e3a 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -169,6 +169,7 @@ const makeDefaultOrchestrationReadModel = () => { latestTurn: null, messages: [], queuedMessages: [], + pendingTurnStart: null, session: null, activities: [], proposedPlans: [], @@ -5512,6 +5513,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { latestTurn: null, messages: [], queuedMessages: [], + pendingTurnStart: null, session: null, activities: [], proposedPlans: [], diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index b304141505..96b498a427 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -44,6 +44,7 @@ function makeThread(overrides: Partial = {}): Thread { session: null, messages: [], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], activities: [], checkpoints: [], diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index ca3a6eb339..8d340ef75c 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -43,6 +43,7 @@ export function buildLocalDraftThread( session: null, messages: [], queuedMessages: [], + pendingTurnStart: null, createdAt: draftThread.createdAt, updatedAt: draftThread.createdAt, archivedAt: null, @@ -456,15 +457,15 @@ export function hasServerAcknowledgedLocalDispatch(input: { input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) || input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null); + // The dispatched message being projected (timeline or queue) is the + // strongest acknowledgment in every phase: the server also queues sends + // while a session is starting ("connecting" phase), where neither turn + // nor session fields necessarily change. + if (expectedMessageId !== null && input.projectedMessageIds.has(expectedMessageId)) { + return true; + } + if (input.phase === "running") { - // A send during a running turn lands as either a steered user message or - // a queued message, without necessarily changing any turn timestamps. - // Acknowledge only when the dispatched message itself is projected — - // tail heuristics would let another client's queue activity clear this - // composer's "Sending" state prematurely. - if (expectedMessageId !== null && input.projectedMessageIds.has(expectedMessageId)) { - return true; - } // Dispatches without a known messageId (e.g. plan-implementation flows) // keep the legacy latest-user-message heuristic. if (expectedMessageId === null && latestUserMessageChanged) { diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.ts index 3f9a8b3789..feee9dedc5 100644 --- a/apps/web/src/components/CommandPalette.logic.test.ts +++ b/apps/web/src/components/CommandPalette.logic.test.ts @@ -22,6 +22,7 @@ function makeThread(overrides: Partial = {}): Thread { session: null, messages: [], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], createdAt: "2026-03-01T00:00:00.000Z", archivedAt: null, diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 061419da79..da80defd6c 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -994,6 +994,7 @@ function makeThread(overrides: Partial = {}): Thread { session: null, messages: [], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], createdAt: "2026-03-09T10:00:00.000Z", archivedAt: null, diff --git a/apps/web/src/lib/threadSort.test.ts b/apps/web/src/lib/threadSort.test.ts index c697732a19..c7f6312c64 100644 --- a/apps/web/src/lib/threadSort.test.ts +++ b/apps/web/src/lib/threadSort.test.ts @@ -24,6 +24,7 @@ function makeThread(overrides: Partial = {}): Thread { session: null, messages: [], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], createdAt: "2026-03-09T10:00:00.000Z", archivedAt: null, diff --git a/apps/web/src/worktreeCleanup.test.ts b/apps/web/src/worktreeCleanup.test.ts index c0c2739914..16b01270da 100644 --- a/apps/web/src/worktreeCleanup.test.ts +++ b/apps/web/src/worktreeCleanup.test.ts @@ -21,6 +21,7 @@ function makeThread(overrides: Partial = {}): Thread { session: null, messages: [], queuedMessages: [], + pendingTurnStart: null, checkpoints: [], activities: [], proposedPlans: [], diff --git a/packages/client-runtime/src/state/entities.test.ts b/packages/client-runtime/src/state/entities.test.ts index 72f1b52cbc..e017986545 100644 --- a/packages/client-runtime/src/state/entities.test.ts +++ b/packages/client-runtime/src/state/entities.test.ts @@ -208,6 +208,7 @@ describe("environment entity projections", () => { deletedAt: null, messages, queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], activities: [], checkpoints: [], @@ -324,6 +325,7 @@ describe("environment entity projections", () => { deletedAt: null, messages: [], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], activities: [], checkpoints: [], diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.ts index 0772e86ed5..e46d8ce24d 100644 --- a/packages/client-runtime/src/state/threadReducer.test.ts +++ b/packages/client-runtime/src/state/threadReducer.test.ts @@ -39,6 +39,7 @@ const baseThread: OrchestrationThread = { deletedAt: null, messages: [], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], activities: [], checkpoints: [], diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.ts index db95b6ed15..fc464729fe 100644 --- a/packages/client-runtime/src/state/threadReducer.ts +++ b/packages/client-runtime/src/state/threadReducer.ts @@ -77,6 +77,7 @@ export function applyThreadDetailEvent( deletedAt: null, messages: [], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], activities: [], checkpoints: [], @@ -174,6 +175,10 @@ export function applyThreadDetailEvent( : {}), runtimeMode: event.payload.runtimeMode, interactionMode: event.payload.interactionMode, + pendingTurnStart: { + messageId: event.payload.messageId, + requestedAt: event.payload.createdAt, + }, updatedAt: event.occurredAt, }, }; @@ -375,12 +380,25 @@ export function applyThreadDetailEvent( } : thread.latestTurn; + // Mirrors the server projections' pending-turn-start clearing: a + // running session with an active turn adopts it; terminal statuses + // abandon it. + const sessionStatus = event.payload.session.status; + const pendingTurnStart = + (sessionStatus === "running" && event.payload.session.activeTurnId !== null) || + sessionStatus === "error" || + sessionStatus === "stopped" || + sessionStatus === "interrupted" + ? null + : thread.pendingTurnStart; + return { kind: "updated", thread: { ...thread, session: event.payload.session, latestTurn, + pendingTurnStart, updatedAt: event.occurredAt, }, }; diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 84f9bcf644..ddd609cb79 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -74,6 +74,7 @@ const BASE_THREAD: OrchestrationThread = { deletedAt: null, messages: [], queuedMessages: [], + pendingTurnStart: null, proposedPlans: [], activities: [], checkpoints: [], diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index b3020536b6..91e591e9da 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -381,6 +381,19 @@ export const OrchestrationThread = Schema.Struct({ queuedMessages: Schema.Array(OrchestrationQueuedMessage).pipe( Schema.withDecodingDefault(Effect.succeed([])), ), + /** + * The turn start that was requested but not yet adopted by a provider + * session. Non-null between `thread.turn-start-requested` and the session + * reporting running (or a terminal status / start failure). While set, + * follow-up sends queue and drains hold — the session status alone cannot + * see this window. Read-model twin of the SQL pending-turn-start row. + */ + pendingTurnStart: Schema.NullOr( + Schema.Struct({ + messageId: MessageId, + requestedAt: IsoDateTime, + }), + ).pipe(Schema.withDecodingDefault(Effect.succeed(null))), proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe( Schema.withDecodingDefault(Effect.succeed([])), ),