review round 3: event-driven pending-start guard, queue ack in all phases, attachment cleanup
- 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 <[email protected]>
This commit is contained in:
1 parent
6cf940c8dc
commit
2218b91213
25 files changed
+326
-56
No files matched your search
@@ -46,6 +46,7 @@ function makeThread(
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
|
||||
@@ -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: [],
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -323,6 +323,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
},
|
||||
],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [
|
||||
{
|
||||
id: "plan-1",
|
||||
|
||||
@@ -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<string, Array<OrchestrationMessage>>();
|
||||
const queuedMessagesByThread = new Map<string, Array<OrchestrationQueuedMessage>>();
|
||||
// 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<string, Array<OrchestrationProposedPlan>>();
|
||||
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
|
||||
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
|
||||
@@ -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<string, Array<OrchestrationProposedPlan>>();
|
||||
const queuedMessagesByThread = new Map<string, Array<OrchestrationQueuedMessage>>();
|
||||
// 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<string, OrchestrationSession>();
|
||||
|
||||
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: [],
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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: [],
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -47,6 +47,7 @@ function makeReadModel(
|
||||
deletedAt: null,
|
||||
messages,
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
activities,
|
||||
checkpoints: [],
|
||||
|
||||
@@ -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.`,
|
||||
|
||||
@@ -94,6 +94,7 @@ describe("orchestration projector", () => {
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
ThreadTurnStartRequestedPayload,
|
||||
} from "./Schemas.ts";
|
||||
|
||||
type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
|
||||
@@ -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
|
||||
? {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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: [],
|
||||
|
||||
@@ -44,6 +44,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
session: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -22,6 +22,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
session: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
|
||||
@@ -994,6 +994,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
session: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
archivedAt: null,
|
||||
|
||||
@@ -24,6 +24,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
session: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
archivedAt: null,
|
||||
|
||||
@@ -21,6 +21,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
session: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -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: [],
|
||||
|
||||
@@ -39,6 +39,7 @@ const baseThread: OrchestrationThread = {
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -74,6 +74,7 @@ const BASE_THREAD: OrchestrationThread = {
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
queuedMessages: [],
|
||||
pendingTurnStart: null,
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
|
||||
@@ -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([])),
|
||||
),
|
||||
|
||||
Reference in new issue
Block a user