Skip to content
TypeScript

fix(server): held queues release agent and scheduled messages once the thread completes a run (#27221)

Julius Marminge8ab098a4a8d6
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index c464a8743f3..05b5601e5a8 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -741,6 +741,20 @@ function delegatedTaskTerminalStatus(
}
}
+/** Failed worktree setup keeps the queue held so queued messages cannot start in the project checkout. */
+function worktreeSetupPending(
+ projection: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,
+): boolean {
+ return (
+ projection.thread.worktreePath === null &&
+ projection.runs.some(
+ (run) =>
+ (run.status === "failed" || run.status === "interrupted") &&
+ run.workspacePreparation?.type === "worktree",
+ )
+ );
+}
+
function nextQueuedRun(
projection: Pick<OrchestrationV2ThreadProjection, "runs" | "messages">,
): OrchestrationV2Run | undefined {
@@ -2195,6 +2209,52 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
),
);
+ // A hold waits for a person to review what they queued. Nobody reviews messages from agents,
+ // the server or scheduled tasks, so a later completed run releases those unless it was stopped.
+ const releaseUnattendedHolds = Effect.fn("Orchestrator.releaseUnattendedHolds")(function* (
+ threadId: ThreadId,
+ completedRunId: RunId,
+ ) {
+ const held = yield* projectionStore.getHeldQueuedRuns(threadId);
+ if (held.length === 0) return;
+ const projection = yield* projectionStore.getThreadRecords(
+ threadId,
+ ["runs", "messages", "turnItems"],
+ {
+ messageIds: held.map((run) => run.userMessageId),
+ turnItemTypes: ["run_interrupt_request"],
+ turnItemRunIds: [completedRunId],
+ },
+ );
+ // Only the newest run completing shows the thread moved past the hold; a late or
+ // bookkeeping update to an older run, overtaken by a failure or Stop, does not.
+ if (
+ latestExecutedRun(projection.runs)?.id !== completedRunId ||
+ projection.turnItems.length > 0 ||
+ worktreeSetupPending(projection)
+ )
+ return;
+ const { messages } = projection;
+ const unattended = new Set(
+ messages
+ .filter((message) => message.createdBy !== "user" || message.scheduledTaskId !== undefined)
+ .map((message) => message.id),
+ );
+ const now = yield* DateTime.now;
+ const released = held.filter((run) => unattended.has(run.userMessageId));
+ if (released.length === 0) return;
+ yield* writeSystemEvents(
+ released.map((run) => ({
+ type: "run.updated" as const,
+ threadId,
+ runId: run.id,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: { ...run, queueHeld: false },
+ })),
+ );
+ });
+
const resumeQueuedRuns = Effect.gen(function* () {
const threadIds = yield* projectionStore.getRecoveryThreadIds("queued-runs");
let resumed = 0;
@@ -5539,15 +5599,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
dispatchMode.type === "queue_after_active";
const shouldQueue = queueBehindRun !== undefined && startsOrQueuesRun;
// Client messages resume held queues; server continuations and scheduled tasks do not.
- // Provider failure or usage limits re-hold the queue. Failed worktree setup keeps it held
- // until a worktree exists, so queued messages cannot start in the project checkout.
- const worktreeSetupUnresolved =
- projection.thread.worktreePath === null &&
- projection.runs.some(
- (run) =>
- (run.status === "failed" || run.status === "interrupted") &&
- run.workspacePreparation?.type === "worktree",
- );
+ // Provider failure or usage limits re-hold the queue.
+ const worktreeSetupUnresolved = worktreeSetupPending(projection);
const sentByUserFromClient =
command.createdBy === "user" &&
(command.creationSource === "web" || command.creationSource === "mobile") &&
@@ -13083,10 +13136,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
yield* threadDispatch
.withLock(
threadId,
- startNextQueuedRun(threadId, {
- endedRunId: run.id,
- ...(run.status === "failed" ? { failedRunId: run.id } : {}),
- }),
+ (run.status === "completed"
+ ? releaseUnattendedHolds(threadId, run.id)
+ : Effect.void
+ ).pipe(
+ Effect.andThen(
+ startNextQueuedRun(threadId, {
+ endedRunId: run.id,
+ ...(run.status === "failed" ? { failedRunId: run.id } : {}),
+ }),
+ ),
+ ),
)
.pipe(
Effect.catchCause((cause) =>
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index 6bb04041c75..88a9073117d 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -612,6 +612,9 @@ export interface ProjectionStoreV2Shape {
readonly canStartQueuedRun: (
threadId: ThreadId,
) => Effect.Effect<boolean, ProjectionStoreV2Error>;
+ readonly getHeldQueuedRuns: (
+ threadId: ThreadId,
+ ) => Effect.Effect<ReadonlyArray<OrchestrationV2Run>, ProjectionStoreV2Error>;
readonly getRecoveryThreadIds: (
kind: ProjectionRecoveryKind,
) => Effect.Effect<ReadonlyArray<ThreadId>, ProjectionStoreV2Error>;
@@ -5183,6 +5186,17 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
)
.pipe(Effect.mapError(controlReadError(threadId)));
+ const getHeldQueuedRuns: ProjectionStoreV2Shape["getHeldQueuedRuns"] = (threadId) =>
+ sql<PayloadRow>`
+ SELECT payload_json FROM orchestration_v2_projection_runs
+ WHERE thread_id = ${threadId} AND status = 'queued'
+ AND json_extract(payload_json, '$.queueHeld') IS 1
+ ORDER BY ordinal ASC
+ `.pipe(
+ Effect.flatMap(decodeRows(decodeRunPayload, threadId)),
+ Effect.mapError(controlReadError(threadId)),
+ );
+
const getMessageCount: ProjectionStoreV2Shape["getMessageCount"] = (threadId) =>
sql<{
count: number;
@@ -6899,6 +6913,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
getCheckpointRollbackContext: readOnReader(getCheckpointRollbackContext),
getRunMessage: readOnReader(getRunMessage),
canStartQueuedRun: readOnReader(canStartQueuedRun),
+ getHeldQueuedRuns: readOnReader(getHeldQueuedRuns),
getPendingNativeUserInputs: readOnReader(getPendingNativeUserInputs),
hasUnpairedRunInterruptRequest: readOnReader(hasUnpairedRunInterruptRequest),
isNodeStored: readOnReader(isNodeStored),
diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
index 1d79e87eb9b..bab115f6e24 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
@@ -263,6 +263,7 @@ it.effect(
getRunMessage: () => Effect.die("not used"),
isNodeStored: () => Effect.die("not used"),
canStartQueuedRun: () => Effect.die("not used"),
+ getHeldQueuedRuns: () => Effect.die("not used"),
getRecoveryThreadIds: () => Effect.die("unused getRecoveryThreadIds"),
getUnreadableThreadIds: () => Effect.die("unused getUnreadableThreadIds"),
getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"),
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index 428202d17b6..11eb866b5fb 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -4768,6 +4768,265 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
+ // A thread fed by agent messages, with helpers to end its runs as a provider would.
+ const queueTestThread = (threadId: ThreadId) =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`${threadId}:create`),
+ threadId,
+ projectId: ProjectId.make(`${threadId}:project`),
+ title: "Dispatcher",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: process.cwd(),
+ });
+ const send = (key: string, createdBy: "user" | "agent", start: boolean) =>
+ orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy,
+ creationSource: createdBy === "user" ? "web" : "server",
+ commandId: CommandId.make(`${threadId}:message:${key}`),
+ threadId,
+ messageId: MessageId.make(`${threadId}:message:${key}`),
+ text: key,
+ attachments: [],
+ modelSelection,
+ dispatchMode: { type: start ? "start_immediately" : "queue_after_active" },
+ });
+ const runFor = (key: string) =>
+ Effect.map(orchestrator.getThreadProjection(threadId), ({ runs }) => {
+ const run = runs.find(
+ (candidate) => candidate.userMessageId === MessageId.make(`${threadId}:message:${key}`),
+ );
+ assert.isDefined(run);
+ return run;
+ });
+ const startedRunIds = yield* Queue.unbounded<RunId>();
+ // Run updates in commit order; the run-update listener handles them in this order too.
+ const runUpdates: Array<OrchestrationV2Run> = [];
+ yield* eventSink
+ .stream({ threadId, afterSequence: yield* orchestrator.getThreadEventSequence(threadId) })
+ .pipe(
+ Stream.runForEach((stored) => {
+ if (stored.event.type !== "run.updated") return Effect.void;
+ runUpdates.push(stored.event.payload);
+ return stored.event.payload.status === "starting"
+ ? Queue.offer(startedRunIds, stored.event.payload.id)
+ : Effect.void;
+ }),
+ Effect.forkScoped,
+ );
+ yield* Effect.yieldNow;
+ const releasedAfter = (key: string, completedKey: string) =>
+ Effect.gen(function* () {
+ const [run, completed] = [yield* runFor(key), yield* runFor(completedKey)];
+ const released = runUpdates.findIndex(
+ (update) => update.id === run.id && update.queueHeld === false,
+ );
+ const completion = runUpdates.findIndex(
+ (update) => update.id === completed.id && update.status === "completed",
+ );
+ assert.isAbove(released, completion, `${key} was released before ${completedKey} ended`);
+ });
+ const end = (
+ key: string,
+ status: "completed" | "failed",
+ revision = "",
+ patch: Partial<OrchestrationV2Run> = {},
+ ) =>
+ Effect.gen(function* () {
+ const run = yield* runFor(key);
+ assert.isNotNull(run.rootNodeId);
+ const now = yield* DateTime.now;
+ yield* eventSink.write({
+ events: [
+ ...(status === "failed"
+ ? [
+ {
+ id: EventId.make(`${threadId}:${key}:error`),
+ type: "turn-item.updated" as const,
+ threadId,
+ runId: run.id,
+ nodeId: run.rootNodeId,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ id: TurnItemId.make(`${threadId}:${key}:error`),
+ type: "error" as const,
+ threadId,
+ runId: run.id,
+ nodeId: run.rootNodeId,
+ providerThreadId: run.providerThreadId,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: 2,
+ status: "failed" as const,
+ title: "Provider failure",
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ failure: {
+ class: "provider_error" as const,
+ message: "Provider failed.",
+ code: "provider_failed",
+ retryable: null,
+ },
+ },
+ },
+ ]
+ : []),
+ {
+ id: EventId.make(`${threadId}:${key}:${status}${revision}`),
+ type: "run.updated",
+ threadId,
+ runId: run.id,
+ nodeId: run.rootNodeId,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: { ...run, ...patch, status, startedAt: now, completedAt: now },
+ },
+ ],
+ });
+ });
+
+ // The run-update listener places failure holds after the terminal event commits.
+ const awaitHeld = (key: string) =>
+ Effect.gen(function* () {
+ const run = yield* runFor(key);
+ yield* eventSink.stream({ threadId, afterSequence: 0, eventType: "run.updated" }).pipe(
+ Stream.filter(
+ (stored) =>
+ stored.event.type === "run.updated" &&
+ stored.event.payload.id === run.id &&
+ stored.event.payload.queueHeld === true,
+ ),
+ Stream.runHead,
+ );
+ });
+ return { send, runFor, end, startedRunIds, releasedAfter, awaitHeld };
+ });
+
+ it.effect("releases held agent messages once a later run completes, not the user's", () =>
+ Effect.gen(function* () {
+ const eventSink = yield* EventSink.EventSinkV2;
+ const threadId = ThreadId.make("runtime-layer-failed-queue-agent-messages");
+ const { send, runFor, end, startedRunIds, releasedAfter, awaitHeld } =
+ yield* queueTestThread(threadId);
+ yield* send("earlier", "agent", true);
+ yield* end("earlier", "completed");
+ yield* send("active", "agent", true);
+ yield* send("issue", "agent", false);
+ yield* send("user", "user", false);
+ yield* end("active", "failed");
+ yield* awaitHeld("issue");
+ assert.isTrue((yield* runFor("issue")).queueHeld);
+ // Delivery bookkeeping rewrites an older completed run; the thread has not moved on.
+ yield* end("earlier", "completed", ":bookkeeping");
+ // A scheduled tick finds the thread idle and starts past the held queue.
+ yield* send("tick", "agent", true);
+ assert.equal((yield* runFor("tick")).status, "starting");
+ yield* end("tick", "completed");
+ assert.equal(yield* Queue.take(startedRunIds), (yield* runFor("issue")).id);
+ yield* releasedAfter("issue", "tick");
+ const user = yield* runFor("user");
+ assert.equal(user.status, "queued");
+ assert.isTrue(user.queueHeld);
+
+ // A run that finishes despite a stop request does not release what the stop held.
+ yield* send("after-stop", "agent", false);
+ assert.isTrue((yield* runFor("after-stop")).queueHeld);
+ const issue = yield* runFor("issue");
+ assert.isNotNull(issue.rootNodeId);
+ const now = yield* DateTime.now;
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make(`${threadId}:issue:interrupt-request`),
+ type: "turn-item.updated",
+ threadId,
+ runId: issue.id,
+ nodeId: issue.rootNodeId,
+ providerInstanceId: issue.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ id: TurnItemId.make(`${threadId}:issue:interrupt-request`),
+ type: "run_interrupt_request",
+ threadId,
+ runId: issue.id,
+ nodeId: issue.rootNodeId,
+ providerThreadId: issue.providerThreadId,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: 2,
+ status: "completed",
+ title: "Interrupt requested",
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ message: "Stopped by user",
+ },
+ },
+ ],
+ });
+ yield* end("issue", "completed");
+ // The next completed run releases it, which also shows the listener handled the stopped one.
+ yield* send("probe", "agent", true);
+ assert.equal((yield* runFor("probe")).status, "starting");
+ yield* end("probe", "completed");
+ assert.equal(yield* Queue.take(startedRunIds), (yield* runFor("after-stop")).id);
+ yield* releasedAfter("after-stop", "probe");
+ }),
+ );
+
+ it.effect("keeps held agent messages while the thread's worktree setup is unresolved", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const dispatcherId = ThreadId.make("runtime-layer-held-queue-worktree");
+ const dispatcher = yield* queueTestThread(dispatcherId);
+ const witness = yield* queueTestThread(ThreadId.make("runtime-layer-held-queue-witness"));
+ yield* dispatcher.send("setup", "agent", true);
+ yield* dispatcher.send("issue", "agent", false);
+ yield* dispatcher.end("setup", "failed", "", {
+ workspacePreparation: { type: "worktree", baseRef: "main" },
+ });
+ yield* dispatcher.awaitHeld("issue");
+ assert.isTrue((yield* dispatcher.runFor("issue")).queueHeld);
+ yield* dispatcher.send("tick", "agent", true);
+ assert.equal((yield* dispatcher.runFor("tick")).status, "starting");
+ yield* witness.send("active", "agent", true);
+ yield* witness.send("queued", "agent", false);
+ // The failed setup never produced the thread's worktree.
+ const { thread } = yield* orchestrator.getThreadProjection(dispatcherId);
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make(`${dispatcherId}:worktree-missing`),
+ type: "thread.metadata-updated",
+ threadId: dispatcherId,
+ occurredAt: yield* DateTime.now,
+ payload: { ...thread, worktreePath: null },
+ },
+ ],
+ });
+ yield* dispatcher.end("tick", "completed");
+ // One listener handles every thread's completions in order, so the witness starting
+ // means the tick's completion was handled too.
+ yield* witness.end("active", "completed");
+ assert.equal(yield* Queue.take(witness.startedRunIds), (yield* witness.runFor("queued")).id);
+ assert.isTrue((yield* dispatcher.runFor("issue")).queueHeld);
+ }),
+ );
+
it.effect("keeps queued user selections and pauses only the limited provider", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -5372,9 +5631,10 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
after.runs.find((run) => run.id === held.id),
held,
);
+ // Nobody will resume a server message, so the completed run released it behind the wake.
assert.deepEqual(
after.runs.find((run) => run.id === textContinuation.id),
- textContinuation,
+ { ...textContinuation, queueHeld: false },
);
}),
);
@@ -5714,7 +5974,7 @@ it.layer(layerTest)("snooze queued runs", (it) => {
payload:
run.status === "queued"
? { ...run, queueHeld: true }
- : { ...run, status: "completed" as const, completedAt: now },
+ : { ...run, status: "cancelled" as const, completedAt: now },
})),
effects: [],
});