diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 54d4be1f5e..dc060c19a6 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -1556,14 +1556,18 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti name: ORCHESTRATION_PROJECTOR_NAMES.projects, apply: applyProjectsProjection, }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages, - apply: applyThreadMessagesProjection, - }, + // queuedMessages must bootstrap before threadMessages: the revert + // handler in threadMessages reads the queued-message projection to + // retain queued attachments, so on replay that table has to be + // populated first or the prune deletes files still referenced. { name: ORCHESTRATION_PROJECTOR_NAMES.queuedMessages, apply: applyQueuedMessagesProjection, }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages, + apply: applyThreadMessagesProjection, + }, { name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans, apply: applyThreadProposedPlansProjection, diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index c68345c937..dbe5327ea9 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -492,7 +492,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { source_proposed_plan_id AS "sourceProposedPlanId", queued_at AS "queuedAt" FROM projection_queued_messages - ORDER BY thread_id ASC, queued_at ASC, message_id ASC + ORDER BY thread_id ASC, rowid ASC `, }); @@ -512,7 +512,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { queued_at AS "queuedAt" FROM projection_queued_messages WHERE thread_id = ${threadId} - ORDER BY queued_at ASC, message_id ASC + ORDER BY rowid ASC `, }); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index c49646b7a4..0546c3ac3c 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -418,9 +418,39 @@ describe("ProviderCommandReactor", () => { }), ); + // Queue-by-default holds turn.start commands while the session is + // starting/running. The mock provider never emits runtime events, so + // tests that send a follow-up on an idle thread must settle the session + // 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. + let settleIndex = 0; + const settleSession = async (threadId: ThreadId = ThreadId.make("thread-1")) => { + settleIndex += 1; + const readModel = await runtime.runPromise(snapshotQuery.getSnapshot()); + const session = readModel.threads.find((entry) => entry.id === threadId)?.session; + if (!session) { + return; + } + await runtime.runPromise( + engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make(`cmd-session-settle-${settleIndex}`), + threadId, + session: { + ...session, + status: "ready", + activeTurnId: null, + }, + createdAt: now, + }), + ); + }; + return { engine, readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()), + settleSession, startSession, sendTurn, interruptTurn, @@ -985,6 +1015,7 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.sendTurn.mock.calls.length === 1); + await harness.settleSession(); await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", @@ -1039,6 +1070,7 @@ describe("ProviderCommandReactor", () => { yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1)); + yield* Effect.promise(() => harness.settleSession()); yield* harness.engine.dispatch({ type: "thread.turn.start", commandId: CommandId.make("cmd-turn-start-restricted-2"), @@ -1159,6 +1191,7 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.startSession.mock.calls.length === 1); await waitFor(() => harness.sendTurn.mock.calls.length === 1); + await harness.settleSession(); await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", @@ -1208,6 +1241,7 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.sendTurn.mock.calls.length === 1); + await harness.settleSession(); await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", @@ -1284,6 +1318,7 @@ describe("ProviderCommandReactor", () => { }), ); + await harness.settleSession(); await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", @@ -1350,6 +1385,7 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.startSession.mock.calls.length === 1); await waitFor(() => harness.sendTurn.mock.calls.length === 1); + await harness.settleSession(); await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", @@ -1606,6 +1642,7 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.startSession.mock.calls.length === 1); await waitFor(() => harness.sendTurn.mock.calls.length === 1); + await harness.settleSession(); await Effect.runPromise( harness.engine.dispatch({ type: "thread.turn.start", diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 7e74ba077c..23d37d7e8f 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -860,10 +860,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" detail: `Queued message '${command.messageId}' does not exist on thread '${command.threadId}'.`, }); } - // While the session is still starting there is no provider turn to + // While a turn start is still pending there is no provider turn to // steer into — dispatching now would race the pending turn/start with // a second one. The message stays queued; steer again once running. - if (thread.session?.status === "starting") { + // 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) { return yield* new OrchestrationCommandInvariantError({ commandType: command.type, detail: `Thread '${command.threadId}' is still starting a turn; steer once it is running.`, diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index a9a98285fa..6434cb4fdf 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -318,6 +318,10 @@ export function projectEvent( threads: updateThread(nextBase.threads, payload.threadId, { deletedAt: payload.deletedAt, updatedAt: payload.deletedAt, + // Persistence drops this thread's queued-message rows on delete; + // mirror that here so queue commands can't act on a deleted + // thread's stale in-memory queue. + queuedMessages: [], }), })), ); diff --git a/apps/server/src/persistence/Layers/ProjectionQueuedMessages.ts b/apps/server/src/persistence/Layers/ProjectionQueuedMessages.ts index cd34c2652e..0e3d20e948 100644 --- a/apps/server/src/persistence/Layers/ProjectionQueuedMessages.ts +++ b/apps/server/src/persistence/Layers/ProjectionQueuedMessages.ts @@ -26,10 +26,14 @@ const ProjectionQueuedMessageDbRowSchema = ProjectionQueuedMessage.mapFields( const makeProjectionQueuedMessageRepository = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + // Replace-then-insert (not ON CONFLICT UPDATE) so a re-queued messageId + // gets a fresh rowid and moves to the queue tail — the same semantics as + // the in-memory projector. Drain order is rowid order: a monotonic + // insertion sequence that never ties, unlike queued_at timestamps. const upsertProjectionQueuedMessageRow = SqlSchema.void({ Request: ProjectionQueuedMessage, execute: (row) => sql` - INSERT INTO projection_queued_messages ( + INSERT OR REPLACE INTO projection_queued_messages ( message_id, thread_id, text, @@ -49,15 +53,6 @@ const makeProjectionQueuedMessageRepository = Effect.gen(function* () { ${row.sourceProposedPlanId}, ${row.queuedAt} ) - ON CONFLICT (message_id) - DO UPDATE SET - thread_id = excluded.thread_id, - text = excluded.text, - attachments_json = excluded.attachments_json, - model_selection_json = excluded.model_selection_json, - source_proposed_plan_thread_id = excluded.source_proposed_plan_thread_id, - source_proposed_plan_id = excluded.source_proposed_plan_id, - queued_at = excluded.queued_at `, }); @@ -76,7 +71,7 @@ const makeProjectionQueuedMessageRepository = Effect.gen(function* () { queued_at AS "queuedAt" FROM projection_queued_messages WHERE thread_id = ${threadId} - ORDER BY queued_at ASC, message_id ASC + ORDER BY rowid ASC `, }); diff --git a/apps/server/src/persistence/Migrations/034_ProjectionQueuedMessages.ts b/apps/server/src/persistence/Migrations/034_ProjectionQueuedMessages.ts index 6fd0294f00..33135eab60 100644 --- a/apps/server/src/persistence/Migrations/034_ProjectionQueuedMessages.ts +++ b/apps/server/src/persistence/Migrations/034_ProjectionQueuedMessages.ts @@ -17,8 +17,10 @@ export default Effect.gen(function* () { ) `; + // Drain order is rowid (insertion) order; the index only serves the + // per-thread filter. yield* sql` - CREATE INDEX IF NOT EXISTS idx_projection_queued_messages_thread_queued - ON projection_queued_messages(thread_id, queued_at) + CREATE INDEX IF NOT EXISTS idx_projection_queued_messages_thread + ON projection_queued_messages(thread_id) `; }); diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 928dfd51a7..b304141505 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -370,7 +370,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => { phase: "ready", latestTurn: completedTurn, latestUserMessageId: localDispatch.latestUserMessageId, - latestQueuedMessageId: localDispatch.latestQueuedMessageId, + projectedMessageIds: new Set(), session: readySession, hasPendingApproval: false, hasPendingUserInput: false, @@ -397,7 +397,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => { phase: "ready", latestTurn: newerTurn, latestUserMessageId: localDispatch.latestUserMessageId, - latestQueuedMessageId: localDispatch.latestQueuedMessageId, + projectedMessageIds: new Set(), session: { ...readySession, updatedAt: newerTurn.completedAt }, hasPendingApproval: false, hasPendingUserInput: false, @@ -425,7 +425,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => { phase: "running", latestTurn: runningTurn, latestUserMessageId: localDispatch.latestUserMessageId, - latestQueuedMessageId: localDispatch.latestQueuedMessageId, + projectedMessageIds: new Set(), session: { ...readySession, status: "running", @@ -442,7 +442,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => { phase: "running", latestTurn: runningTurn, latestUserMessageId: localDispatch.latestUserMessageId, - latestQueuedMessageId: localDispatch.latestQueuedMessageId, + projectedMessageIds: new Set(), session: { ...readySession, status: "running", @@ -484,13 +484,15 @@ describe("hasServerAcknowledgedLocalDispatch", () => { }), ); + // Dispatch without a known messageId keeps the legacy heuristic: a new + // latest user message acknowledges it. expect( hasServerAcknowledgedLocalDispatch({ localDispatch, phase: "running", latestTurn: runningTurn, latestUserMessageId: MessageId.make("message-steer"), - latestQueuedMessageId: localDispatch.latestQueuedMessageId, + projectedMessageIds: new Set(), session: runningSession, hasPendingApproval: false, hasPendingUserInput: false, @@ -498,22 +500,47 @@ describe("hasServerAcknowledgedLocalDispatch", () => { }), ).toBe(true); - // A send during a running turn can also land as a queued message - // instead of a steered timeline message; that projection must clear - // the composer's local "Sending" state too. + const correlatedDispatch = createLocalDispatchSnapshot( + makeThread({ latestTurn: runningTurn, session: runningSession }), + { messageId: MessageId.make("message-mine") }, + ); + + // A correlated dispatch acknowledges when its exact message appears in + // the timeline or the queue... + for (const projectedMessageIds of [ + new Set(["message-mine"]), + new Set(["message-other", "message-mine"]), + ]) { + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch: correlatedDispatch, + phase: "running", + latestTurn: runningTurn, + latestUserMessageId: correlatedDispatch.latestUserMessageId, + projectedMessageIds, + session: runningSession, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(true); + } + + // ...but ignores unrelated queue/timeline changes (another client's + // queued message, or a different queued chip being steered/removed). expect( hasServerAcknowledgedLocalDispatch({ - localDispatch, + localDispatch: correlatedDispatch, phase: "running", latestTurn: runningTurn, - latestUserMessageId: localDispatch.latestUserMessageId, - latestQueuedMessageId: MessageId.make("message-queued"), + latestUserMessageId: MessageId.make("message-someone-else"), + projectedMessageIds: new Set(["message-someone-else"]), session: runningSession, hasPendingApproval: false, hasPendingUserInput: false, threadError: null, }), - ).toBe(true); + ).toBe(false); }); it("acknowledges pending user interaction and errors immediately", () => { @@ -523,7 +550,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => { phase: "ready" as const, latestTurn: null, latestUserMessageId: localDispatch.latestUserMessageId, - latestQueuedMessageId: localDispatch.latestQueuedMessageId, + projectedMessageIds: new Set(), session: null, hasPendingApproval: false, hasPendingUserInput: false, diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index d6b35ca462..ca3a6eb339 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -390,8 +390,14 @@ export async function waitForStartedServerThread( export interface LocalDispatchSnapshot { startedAt: string; preparingWorktree: boolean; + /** + * The messageId of the send this dispatch is waiting on, when the send + * path knows it. Acknowledgment then correlates with this exact message + * being projected (timeline or queue) instead of global tail heuristics + * that other clients' activity could satisfy. + */ + expectedMessageId: ChatMessage["id"] | null; latestUserMessageId: ChatMessage["id"] | null; - latestQueuedMessageId: ChatMessage["id"] | null; latestTurnTurnId: TurnId | null; latestTurnRequestedAt: string | null; latestTurnStartedAt: string | null; @@ -402,7 +408,7 @@ export interface LocalDispatchSnapshot { export function createLocalDispatchSnapshot( activeThread: Thread | undefined, - options?: { preparingWorktree?: boolean }, + options?: { preparingWorktree?: boolean; messageId?: ChatMessage["id"] }, ): LocalDispatchSnapshot { const latestTurn = activeThread?.latestTurn ?? null; const session = activeThread?.session ?? null; @@ -410,8 +416,8 @@ export function createLocalDispatchSnapshot( return { startedAt: new Date().toISOString(), preparingWorktree: Boolean(options?.preparingWorktree), + expectedMessageId: options?.messageId ?? null, latestUserMessageId: latestUserMessage?.id ?? null, - latestQueuedMessageId: activeThread?.queuedMessages.at(-1)?.messageId ?? null, latestTurnTurnId: latestTurn?.turnId ?? null, latestTurnRequestedAt: latestTurn?.requestedAt ?? null, latestTurnStartedAt: latestTurn?.startedAt ?? null, @@ -426,7 +432,7 @@ export function hasServerAcknowledgedLocalDispatch(input: { phase: SessionPhase; latestTurn: Thread["latestTurn"] | null; latestUserMessageId: ChatMessage["id"] | null; - latestQueuedMessageId: ChatMessage["id"] | null; + projectedMessageIds: ReadonlySet; session: Thread["session"] | null; hasPendingApproval: boolean; hasPendingUserInput: boolean; @@ -441,9 +447,9 @@ export function hasServerAcknowledgedLocalDispatch(input: { const latestTurn = input.latestTurn ?? null; const session = input.session ?? null; + const expectedMessageId = input.localDispatch.expectedMessageId; const latestUserMessageChanged = - input.localDispatch.latestUserMessageId !== input.latestUserMessageId || - input.localDispatch.latestQueuedMessageId !== input.latestQueuedMessageId; + input.localDispatch.latestUserMessageId !== input.latestUserMessageId; const latestTurnChanged = input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) || input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) || @@ -453,10 +459,15 @@ export function hasServerAcknowledgedLocalDispatch(input: { 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. - // Treat either projection as the server acknowledgment so the composer - // does not remain stuck in its local "Sending" state until the turn - // settles. - if (latestUserMessageChanged) { + // 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) { return true; } if (!latestTurnChanged) { diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 83404e0382..d78f2e7bfa 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -457,7 +457,20 @@ function useLocalDispatchState(input: { const [localDispatch, setLocalDispatch] = useState(null); const latestUserMessageId = input.activeThread?.messages.findLast((message) => message.role === "user")?.id ?? null; - const latestQueuedMessageId = input.activeThread?.queuedMessages.at(-1)?.messageId ?? null; + const activeThreadMessages = input.activeThread?.messages; + const activeThreadQueuedMessages = input.activeThread?.queuedMessages; + // Every server-projected id for this thread — timeline messages plus the + // held queue — so acknowledgment can match the exact dispatched message. + const projectedMessageIds = useMemo(() => { + const ids = new Set(); + for (const message of activeThreadMessages ?? []) { + ids.add(message.id); + } + for (const queuedMessage of activeThreadQueuedMessages ?? []) { + ids.add(queuedMessage.messageId); + } + return ids; + }, [activeThreadMessages, activeThreadQueuedMessages]); const resetLocalDispatch = useCallback(() => { setLocalDispatch(null); @@ -470,7 +483,7 @@ function useLocalDispatchState(input: { phase: input.phase, latestTurn: input.activeLatestTurn, latestUserMessageId, - latestQueuedMessageId, + projectedMessageIds, session: input.activeThread?.session ?? null, hasPendingApproval: input.activePendingApproval !== null, hasPendingUserInput: input.activePendingUserInput !== null, @@ -484,13 +497,13 @@ function useLocalDispatchState(input: { input.phase, input.threadError, latestUserMessageId, - latestQueuedMessageId, + projectedMessageIds, localDispatch, ], ); const activeLocalDispatch = serverAcknowledgedLocalDispatch ? null : localDispatch; const beginLocalDispatch = useCallback( - (options?: { preparingWorktree?: boolean }) => { + (options?: { preparingWorktree?: boolean; messageId?: MessageId }) => { const preparingWorktree = Boolean(options?.preparingWorktree); setLocalDispatch((current) => { const active = serverAcknowledgedLocalDispatch ? null : current; @@ -4176,7 +4189,11 @@ function ChatViewContent(props: ChatViewProps) { void dockTransition.catch(() => resolveDockStarted?.()); await dockStarted; } - beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) }); + const messageIdForSend = newMessageId(); + beginLocalDispatch({ + preparingWorktree: Boolean(baseBranchForWorktree), + messageId: messageIdForSend, + }); const composerImagesSnapshot = [...composerImages]; const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts]; @@ -4195,7 +4212,6 @@ function ChatViewContent(props: ChatViewProps) { messageTextWithPreviewAnnotations, composerReviewCommentsSnapshot, ); - const messageIdForSend = newMessageId(); const messageCreatedAt = new Date().toISOString(); const outgoingMessageText = formatOutgoingPrompt({ provider: ctxSelectedProvider, @@ -4357,7 +4373,7 @@ function ChatViewContent(props: ChatViewProps) { : {}), } : undefined; - beginLocalDispatch({ preparingWorktree: false }); + beginLocalDispatch({ preparingWorktree: false, messageId: messageIdForSend }); const startResult = await startThreadTurn({ environmentId, input: { @@ -4690,7 +4706,7 @@ function ChatViewContent(props: ChatViewProps) { }); sendInFlightRef.current = true; - beginLocalDispatch({ preparingWorktree: false }); + beginLocalDispatch({ preparingWorktree: false, messageId: messageIdForSend }); setThreadError(threadIdForSend, null); // Position this sent row once LegendList has measured the anchored tail.