Skip to content
TypeScript

fix(server): agent questions stay answerable after a server restart (#19229)

Dara Adedeji867112cda090
diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
index 6293d25025a..77e4cd11ba0 100644
--- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
@@ -15,11 +15,14 @@ import {
ProviderInstanceId,
ProviderThreadId,
RunId,
+ RuntimeRequestId,
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
+import * as Deferred from "effect/Deferred";
+import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
@@ -40,6 +43,7 @@ import * as EventSink from "./EventSink.ts";
import * as Orchestrator from "./Orchestrator.ts";
import { continueRestartedRun } from "./RestartContinuation.ts";
import * as RuntimeLayer from "./runtimeLayer.ts";
+import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
import * as ProviderTurnStartServiceTestkit from "./ProviderTurnStartService.testkit.ts";
import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
@@ -104,7 +108,11 @@ const layerTestProviderInstanceRegistry = Layer.succeed(
},
);
-const layerTest = Layer.mergeAll(RuntimeLayer.layer, RuntimeLayer.layerEventSink).pipe(
+const layerTest = Layer.mergeAll(
+ RuntimeLayer.layer,
+ RuntimeLayer.layerEventSink,
+ ThreadCommandExecutor.layer,
+).pipe(
Layer.provideMerge(RuntimeLayer.layerProjectService),
Layer.provide(
Layer.mock(WorkspacePaths.WorkspacePaths)({
@@ -1980,6 +1988,169 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
}
}),
);
+
+ it.effect("serializes a recovered child answer with its parent and tracks the follow-up", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const now = yield* DateTime.now;
+ const parentThreadId = ThreadId.make("thread:question-answer-parent");
+ const projectId = ProjectId.make("project:question-answer");
+ const parentRunId = RunId.make("run:question-answer-parent");
+ const rootNodeId = NodeId.make("node:question-answer-parent");
+ yield* seedParentWithTerminalTask({
+ threadId: parentThreadId,
+ projectId,
+ runId: parentRunId,
+ rootNodeId,
+ taskId: NodeId.make("node:question-answer-seed"),
+ deliveryState: "acknowledged",
+ now,
+ });
+ const child = yield* seedRestartCancelledChild({
+ parentThreadId,
+ projectId,
+ parentRunId,
+ rootNodeId,
+ name: "question-answer-child",
+ completionWake: "always",
+ continuationPending: false,
+ now,
+ });
+ // The cancelled result is published before anyone answers the question.
+ yield* orchestrator.recoverDelegatedTasks;
+ assert.isNotNull(
+ (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find(
+ (task) => task.id === child.taskId,
+ )?.result,
+ );
+ const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.find(
+ (run) => run.id === parentRunId,
+ )!;
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make("event:question-answer-parent-completed"),
+ type: "run.updated",
+ threadId: parentThreadId,
+ runId: parentRunId,
+ occurredAt: now,
+ payload: { ...parentRun, status: "completed", completedAt: now },
+ },
+ ],
+ });
+ const requestId = RuntimeRequestId.make("request:question-answer");
+ const nodeId = NodeId.make("node:question-answer-request");
+ yield* eventSink.write({
+ commandId: CommandId.make("command:seed-question-answer"),
+ events: [
+ {
+ id: EventId.make("event:question-answer-request"),
+ type: "runtime-request.updated",
+ threadId: child.childThreadId,
+ nodeId,
+ occurredAt: now,
+ payload: {
+ id: requestId,
+ nodeId,
+ providerTurnId: null,
+ nativeRequestRef: null,
+ kind: "user_input",
+ status: "pending",
+ responseCapability: { type: "message" },
+ createdAt: now,
+ resolvedAt: null,
+ },
+ },
+ {
+ id: EventId.make("event:question-answer-item"),
+ type: "turn-item.updated",
+ threadId: child.childThreadId,
+ nodeId,
+ occurredAt: now,
+ payload: {
+ id: TurnItemId.make("turn-item:question-answer"),
+ type: "user_input_request",
+ threadId: child.childThreadId,
+ runId: child.childRunId,
+ nodeId,
+ providerThreadId: null,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: 0,
+ status: "waiting",
+ title: null,
+ startedAt: now,
+ completedAt: null,
+ updatedAt: now,
+ requestId,
+ questions: [
+ { id: "color", header: "Color", question: "Which color?", options: [] },
+ ],
+ },
+ },
+ ],
+ });
+
+ const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor;
+ const parentHeld = yield* Deferred.make<void>();
+ const releaseParent = yield* Deferred.make<void>();
+ const answerWaiting = yield* Deferred.make<void>();
+ const withLock = executor.withLock;
+ const parentMutation = yield* withLock(
+ parentThreadId,
+ Deferred.succeed(parentHeld, undefined).pipe(
+ Effect.andThen(Deferred.await(releaseParent)),
+ ),
+ ).pipe(Effect.forkScoped({ startImmediately: true }));
+ yield* Deferred.await(parentHeld);
+ const observeLock: ThreadCommandExecutor.ThreadCommandExecutor["Service"]["withLock"] = (
+ key,
+ effect,
+ ) =>
+ key === parentThreadId
+ ? Deferred.succeed(answerWaiting, undefined).pipe(Effect.andThen(withLock(key, effect)))
+ : withLock(key, effect);
+ const spy = vi.spyOn(executor, "withLock").mockImplementation(observeLock);
+ yield* Effect.gen(function* () {
+ const answer = yield* orchestrator
+ .dispatch({
+ type: "runtime-request.respond",
+ commandId: CommandId.make("command:question-answer"),
+ threadId: child.childThreadId,
+ requestId,
+ answers: { color: "Blue" },
+ })
+ .pipe(Effect.forkScoped({ startImmediately: true }));
+ yield* Effect.raceFirst(Deferred.await(answerWaiting), Fiber.join(answer));
+ const waiting = yield* orchestrator.getThreadProjection(child.childThreadId);
+ assert.equal(
+ waiting.runtimeRequests.find((row) => row.id === requestId)?.status,
+ "pending",
+ );
+ assert.isFalse((yield* executor.activeKeys).includes(child.childThreadId));
+ yield* Deferred.succeed(releaseParent, undefined);
+ yield* Fiber.join(parentMutation);
+ yield* Fiber.join(answer);
+ }).pipe(Effect.ensuring(Effect.sync(() => spy.mockRestore())));
+
+ const answerRun = (yield* orchestrator.getThreadProjection(child.childThreadId)).runs.find(
+ (run) => run.userMessageId === MessageId.make(`async-answer:${requestId}`),
+ );
+ assert.isDefined(answerRun?.delegatedTaskId);
+ const followup = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find(
+ (task) => task.id === answerRun?.delegatedTaskId,
+ );
+ assert.equal(followup?.childThreadId, child.childThreadId);
+ assert.isNull(followup?.result);
+ assert.isTrue(
+ (yield* orchestrator.getThreadShell(parentThreadId))?.pendingBackgroundTasks?.some(
+ (task) => task.kind === "subagent" && task.childThreadId === child.childThreadId,
+ ),
+ );
+ }),
+ );
},
);
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 12338186078..eb65522fff9 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -62,12 +62,14 @@ import {
ProviderInstanceId,
ProviderInteractionMode,
resolveProviderInstanceEnabled,
+ resolveProjectProviderInstanceEnabled,
type ProviderSessionId,
RunId,
RuntimeMode,
ThreadLinkedPullRequest,
ThreadId,
TurnItemId,
+ TrimmedNonEmptyString,
} from "@t3tools/contracts";
import { modelSelectionsEqual } from "@t3tools/shared/model";
import { recordThreadOpen } from "@t3tools/shared/paletteSearch";
@@ -167,6 +169,10 @@ import { planThreadDeletion } from "./ThreadDeletion.ts";
import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import * as ServerSettings from "../serverSettings.ts";
+const isMessageQuestionAnswer = Schema.is(
+ Schema.Union([TrimmedNonEmptyString, Schema.NonEmptyArray(TrimmedNonEmptyString)]),
+);
+
export class OrchestratorDispatchError extends Schema.TaggedError<OrchestratorDispatchError>()(
"OrchestratorDispatchError",
{
@@ -8517,6 +8523,77 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
);
}
+ const approvalTurnItem = context.item;
+ const resolvedNodeStatus =
+ command.decision === "decline" || command.decision === "cancel"
+ ? ("cancelled" as const)
+ : ("completed" as const);
+ const replies: string[] = [];
+ if (
+ runtimeRequest.responseCapability.type === "message" &&
+ resolvedNodeStatus !== "cancelled"
+ ) {
+ if (approvalTurnItem?.type !== "user_input_request") {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "The question for this request was not found.",
+ });
+ }
+ const thread = yield* projectionStore
+ .getThread(command.threadId)
+ .pipe(mapDispatchError(command));
+ const settings = yield* serverSettings.getSettings.pipe(Effect.orDie);
+ if (
+ !resolveProjectProviderInstanceEnabled(
+ settings,
+ thread.projectId,
+ thread.providerInstanceId,
+ )
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "The provider for this project is disabled.",
+ });
+ }
+ const questionIds = new Set(approvalTurnItem.questions.map((question) => question.id));
+ if (
+ !Object.entries(answers ?? {}).every(
+ ([questionId, answer]) =>
+ questionIds.has(questionId) || isMessageQuestionAnswer(answer),
+ )
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "Answer each question before sending.",
+ });
+ }
+ for (const question of approvalTurnItem.questions) {
+ const answer = answers?.[question.id];
+ const answered = isMessageQuestionAnswer(answer);
+ // Clients send "" for a skipped optional question, such as an attachment-only answer.
+ if (!answered && question.required === false) continue;
+ if (!answered) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "Answer each question before sending.",
+ });
+ }
+ const text = typeof answer === "string" ? answer : answer.join(", ");
+ replies.push(`${question.question}\n${text.trim()}`);
+ }
+ if (replies.length === 0) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "Enter an answer before sending.",
+ });
+ }
+ }
+
const now = yield* DateTime.now;
const resolvedRequest = {
...runtimeRequest,
@@ -8590,10 +8667,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
},
});
}
- const resolvedNodeStatus =
- command.decision === "decline" || command.decision === "cancel"
- ? ("cancelled" as const)
- : ("completed" as const);
yield* emitEvent({
type: "runtime-request.updated",
threadId: command.threadId,
@@ -8629,7 +8702,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
});
}
- const approvalTurnItem = context.item;
if (approvalTurnItem !== undefined) {
yield* emitEvent({
type: "turn-item.updated",
@@ -8668,33 +8740,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}
if (runtimeRequest.responseCapability.type === "message") {
if (resolvedNodeStatus === "cancelled") return;
- if (approvalTurnItem?.type !== "user_input_request") {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "The question for this request was not found.",
- });
- }
- const replies: string[] = [];
- for (const question of approvalTurnItem.questions) {
- const answer = answers?.[question.id];
- if (typeof answer !== "string" || answer.trim().length === 0) {
- if (question.required === false) continue;
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "Answer each question before sending.",
- });
- }
- replies.push(`${question.question}\n${answer.trim()}`);
- }
- if (replies.length === 0) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "Enter an answer before sending.",
- });
- }
let dispatchMode: Extract<
OrchestrationV2Command,
{ type: "message.dispatch" }
@@ -8728,21 +8773,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
dispatchMode = { type: "steer_active", targetRunId: activeRun.id };
}
}
- return yield* dispatchMessage(
- {
- type: "message.dispatch",
- commandId: command.commandId,
- threadId: command.threadId,
- messageId: MessageId.make(`async-answer:${command.requestId}`),
- text: replies.join("\n\n"),
- attachments: [],
- createdBy: "user",
- creationSource: "server",
- dispatchMode,
- },
- events,
- effects,
- );
+ const answer = {
+ type: "message.dispatch" as const,
+ commandId: command.commandId,
+ threadId: command.threadId,
+ messageId: MessageId.make(`async-answer:${command.requestId}`),
+ text: replies.join("\n\n"),
+ attachments: [],
+ createdBy: "user" as const,
+ creationSource: "server" as const,
+ dispatchMode,
+ };
+ yield* dispatchMessage(answer, events, effects);
+ return yield* recordSubagentFollowup(answer, events).pipe(mapDispatchError(answer));
}
if (providerSessionId === null) return;
yield* Ref.update(effects, (existing) => [
@@ -12968,7 +13011,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
commandThreadId(command),
dispatchWithReceiptEffect(command),
);
- if (command.type !== "message.dispatch" || !mayStartSubagentFollowup(command))
+ // Answering a message-mode question can also start a follow-up.
+ if (
+ command.type !== "runtime-request.respond" &&
+ (command.type !== "message.dispatch" || !mayStartSubagentFollowup(command))
+ )
return yield* dispatch;
const parentThreadId = yield* appOwnedSubagentParentThreadId(command.threadId).pipe(
Effect.mapError(
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index 5f7247c0a59..a10710a2cc3 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -4508,6 +4508,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
AND node.status IN ('pending', 'starting', 'running', 'waiting')
AND (
(node.run_id IS NULL AND node.kind = 'root_turn')
+ OR node.node_id IN (
+ SELECT node_id FROM orchestration_v2_projection_runtime_requests
+ WHERE thread_id = ${threadId} AND status = 'pending' AND kind = 'user_input'
+ )
OR node.run_id IN (
SELECT run_id FROM orchestration_v2_projection_runs
WHERE thread_id = ${threadId}
@@ -4686,6 +4690,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
AND status IN ('queued', 'preparing', 'starting', 'running', 'waiting')
)
OR item.type IN ('command_execution', 'dynamic_tool', 'subagent')
+ OR (
+ item.type = 'user_input_request'
+ AND json_extract(item.payload_json, '$.requestId') IN (
+ SELECT runtime_request_id FROM orchestration_v2_projection_runtime_requests
+ WHERE thread_id = ${threadId} AND status = 'pending' AND kind = 'user_input'
+ )
+ )
OR (
item.run_id IS NULL
AND item.node_id IN (
diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
index 910dc97bfda..23a2a5b99b4 100644
--- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
+++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
@@ -2,6 +2,7 @@ import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import {
CommandId,
+ isProviderNativeSubagentThread,
type OrchestrationV2DomainEvent,
type ProviderThreadId,
type OrchestrationV2RestartCancelledBackgroundWork,
@@ -232,16 +233,37 @@ export const make = Effect.gen(function* () {
}
runs.push(run);
}
+ const pendingRequests = projection.runtimeRequests.filter(
+ (request) => request.status === "pending",
+ );
+ // The lost provider callback cannot resume; persisted questions can be
+ // answered by a new user message in threads that accept messages.
+ const questions = pendingRequests.filter(
+ (request) =>
+ request.kind === "user_input" &&
+ request.responseCapability.type === "live" &&
+ projection.turnItems.some(
+ (item) =>
+ item.type === "user_input_request" &&
+ item.requestId === request.id &&
+ item.nodeId === request.nodeId &&
+ item.questions.length > 0 &&
+ item.questions.every((question) => question.question.trim().length > 0),
+ ) &&
+ !isProviderNativeSubagentThread(projection.thread),
+ );
+ const recoveredRequestIds = new Set(questions.map((request) => request.id));
const messageRequestNodeIds = new Set(
- projection.runtimeRequests
+ pendingRequests
.filter(
(request) =>
- request.status === "pending" && request.responseCapability.type === "message",
+ request.responseCapability.type === "message" || recoveredRequestIds.has(request.id),
)
.map((request) => request.nodeId),
);
- const requests = projection.runtimeRequests.filter(
- (request) => request.status === "pending" && request.responseCapability.type !== "message",
+ const requests = pendingRequests.filter(
+ (request) =>
+ request.responseCapability.type !== "message" && !recoveredRequestIds.has(request.id),
);
// Delegated task rows, items and nodes stay open: the child settles them.
const delegatedTaskNodeIds = new Set<string>([
@@ -338,6 +360,16 @@ export const make = Effect.gen(function* () {
payload: { ...run, queueHeld: true },
});
}
+ for (const question of questions) {
+ events.push({
+ id: yield* allocateEventId(),
+ type: "runtime-request.updated",
+ threadId: projection.thread.id,
+ nodeId: question.nodeId,
+ occurredAt: now,
+ payload: { ...question, responseCapability: { type: "message" } },
+ });
+ }
for (const request of requests) {
events.push({
id: yield* allocateEventId(),
diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
index 3c635be6753..8398fca9cb6 100644
--- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
@@ -2900,6 +2900,92 @@ it.effect("ProviderSessionManagerV2 settles a request the event pump persists du
}),
);
+it.effect.each(["manual_shutdown", "server_shutdown"] as const)(
+ "ProviderSessionManagerV2 preserves questions only for server shutdown (%s)",
+ (reason) =>
+ Effect.gen(function* () {
+ const state = yield* Ref.make(emptyState);
+ const effect = Effect.gen(function* () {
+ const eventSink = yield* EventSink.EventSinkV2;
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
+ const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
+ const now = yield* DateTime.now;
+ const projectId = yield* idAllocator.allocate.project({
+ fixtureName: "provider-session-manager-request-expire",
+ });
+ const threadId = yield* idAllocator.allocate.thread({
+ fixtureName: "provider-session-manager-request-expire",
+ projectId,
+ });
+ const providerSessionId = yield* idAllocator.allocate.providerSession({
+ providerInstanceId: modelSelection.instanceId,
+ threadId,
+ });
+ const providerThread = makeProviderThread({
+ idAllocator,
+ threadId,
+ providerSessionId,
+ now,
+ });
+
+ yield* eventSink.write({
+ events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
+ });
+ const pendingRequest = yield* makePendingRuntimeRequestEvents({
+ idAllocator,
+ threadId,
+ providerSessionId,
+ providerThread,
+ now,
+ });
+ yield* eventSink.write({
+ events: pendingRequest.events.map((event) =>
+ event.type === "turn-item.updated"
+ ? {
+ ...event,
+ payload: {
+ ...event.payload,
+ type: "user_input_request",
+ questions: [
+ { id: "color", header: "Color", question: "Which color?", options: [] },
+ ],
+ },
+ }
+ : event.type === "runtime-request.updated"
+ ? { ...event, payload: { ...event.payload, kind: "user_input" } }
+ : event,
+ ),
+ });
+ yield* manager.open({
+ threadId,
+ providerSessionId,
+ modelSelection,
+ runtimePolicy,
+ });
+ yield* manager.release({
+ providerSessionId,
+ reason,
+ });
+
+ const projection = yield* projectionStore.getThreadProjection(threadId);
+ const request = projection.runtimeRequests.at(-1);
+ const requestNode = projection.nodes.find((node) => node.id === request?.nodeId);
+ const requestTurnItem = projection.turnItems.find(
+ (item) => item.type === "user_input_request" && item.requestId === request?.id,
+ );
+
+ const preserved = reason === "server_shutdown";
+ assert.equal(request?.status, preserved ? "pending" : "cancelled");
+ assert.equal(request?.responseCapability.type, preserved ? "live" : "not_resumable");
+ assert.equal(requestNode?.status, preserved ? "waiting" : "cancelled");
+ assert.equal(requestTurnItem?.status, preserved ? "waiting" : "cancelled");
+ });
+
+ yield* effect.pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1000 })));
+ }),
+);
+
it.effect("ProviderSessionManagerV2 persists session-scoped runtime requests without a run", () =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts
index 00b42d510bd..5c4be62c137 100644
--- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts
+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts
@@ -633,7 +633,9 @@ export const layerWithOptions = (
request.status === "pending" &&
request.responseCapability.type === "live" &&
request.responseCapability.providerSessionId === providerSessionId &&
- DateTime.isLessThanOrEqualTo(request.createdAt, input.releasedAt),
+ DateTime.isLessThanOrEqualTo(request.createdAt, input.releasedAt) &&
+ // Shutdown reconciliation decides which questions can survive the lost callback.
+ !(input.reason === "server_shutdown" && request.kind === "user_input"),
);
for (const request of releasedRequests) {
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index 425c00af4b1..87da6479adb 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -18,6 +18,7 @@ import {
TurnItemId,
type ModelSelection,
type OrchestrationV2Run,
+ type OrchestrationV2RuntimeRequest,
ProjectId,
type PullRequestDetail,
type PullRequestComment,
@@ -1077,15 +1078,288 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
}),
);
+ const seedPendingQuestion = Effect.fnUntraced(function* (
+ threadId: ThreadId,
+ runId: RunId | null,
+ responseCapability: OrchestrationV2RuntimeRequest["responseCapability"],
+ ) {
+ const eventSink = yield* EventSink.EventSinkV2;
+ const now = yield* DateTime.now;
+ const requestId = RuntimeRequestId.make(`${threadId}:request`);
+ const nodeId = NodeId.make(`${threadId}:node`);
+ const itemId = TurnItemId.make(`${threadId}:item`);
+ yield* eventSink.write({
+ commandId: CommandId.make(`${threadId}:seed`),
+ events: [
+ {
+ id: EventId.make(`${threadId}:node-event`),
+ type: "node.updated",
+ threadId,
+ nodeId,
+ occurredAt: now,
+ payload: {
+ id: nodeId,
+ threadId,
+ runId,
+ parentNodeId: null,
+ rootNodeId: nodeId,
+ kind: "user_input_request",
+ status: "waiting",
+ countsForRun: false,
+ providerThreadId: null,
+ providerTurnId: null,
+ nativeItemRef: null,
+ runtimeRequestId: requestId,
+ checkpointScopeId: null,
+ startedAt: now,
+ completedAt: null,
+ },
+ },
+ {
+ id: EventId.make(`${threadId}:request-event`),
+ type: "runtime-request.updated",
+ threadId,
+ nodeId,
+ occurredAt: now,
+ payload: {
+ id: requestId,
+ nodeId,
+ providerTurnId: null,
+ nativeRequestRef: null,
+ kind: "user_input",
+ status: "pending",
+ responseCapability,
+ createdAt: now,
+ resolvedAt: null,
+ },
+ },
+ {
+ id: EventId.make(`${threadId}:item-event`),
+ type: "turn-item.updated",
+ threadId,
+ nodeId,
+ occurredAt: now,
+ payload: {
+ id: itemId,
+ type: "user_input_request",
+ threadId,
+ runId,
+ nodeId,
+ providerThreadId: null,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: 0,
+ status: "waiting",
+ title: null,
+ startedAt: now,
+ completedAt: null,
+ updatedAt: now,
+ requestId,
+ questions: [
+ { id: "color", header: "Color", question: "Which color?", options: [] },
+ {
+ id: "sizes",
+ header: "Sizes",
+ question: "Which sizes?",
+ options: [],
+ multiSelect: true,
+ },
+ {
+ id: "note",
+ header: "Note",
+ question: "Anything else?",
+ options: [],
+ required: false,
+ },
+ ],
+ },
+ },
+ ],
+ });
+ return { requestId, nodeId, itemId };
+ });
+
+ it.effect.each([
+ { trigger: "startup", scope: "run" },
+ { trigger: "shutdown", scope: "session" },
+ ] as const)(
+ "recovers only reconstructable user questions and keeps their cards pending on $trigger ($scope)",
+ ({ trigger, scope }) =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const now = yield* DateTime.now;
+ const threadId = ThreadId.make(`runtime-recovered-question-${trigger}-${scope}`);
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make(`runtime-recovered-question-create-${trigger}-${scope}`),
+ createdBy: "user",
+ creationSource: "web",
+ threadId,
+ projectId: ProjectId.make(`runtime-recovered-question-project-${trigger}-${scope}`),
+ title: "Async question",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: process.cwd(),
+ });
+ if (scope === "run") {
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make(`${threadId}:run`),
+ threadId,
+ messageId: MessageId.make(`${threadId}:message`),
+ text: "Ask me a question",
+ attachments: [],
+ createdBy: "user",
+ creationSource: "web",
+ dispatchMode: { type: "start_immediately" },
+ });
+ }
+ const runId = (yield* orchestrator.getThreadProjection(threadId)).runs[0]?.id ?? null;
+ const { requestId, nodeId, itemId } = yield* seedPendingQuestion(threadId, runId, {
+ type: "live",
+ providerSessionId: ProviderSessionId.make(`lost-session-${trigger}-${scope}`),
+ });
+ const recovery = yield* ProviderRuntimeRecoveryService.ProviderRuntimeRecoveryService;
+ const original = yield* orchestrator.getThreadProjection(threadId);
+ const request = original.runtimeRequests[0]!;
+ const questionItem = original.turnItems.find((item) => item.type === "user_input_request")!;
+ const nativeThreadId = ThreadId.make(`runtime-recovered-native-child-${trigger}-${scope}`);
+ const nativeRequestId = RuntimeRequestId.make(
+ `runtime-recovered-native-request-${trigger}-${scope}`,
+ );
+ const approvalId = RuntimeRequestId.make(`runtime-recovered-approval-${trigger}-${scope}`);
+ const missingTextId = RuntimeRequestId.make(
+ `runtime-recovered-missing-text-${trigger}-${scope}`,
+ );
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make(`recovery-approval-${trigger}-${scope}`),
+ type: "runtime-request.updated",
+ threadId,
+ occurredAt: now,
+ payload: { ...request, id: approvalId, kind: "command" },
+ },
+ {
+ id: EventId.make(`recovery-missing-text-${trigger}-${scope}`),
+ type: "runtime-request.updated",
+ threadId,
+ occurredAt: now,
+ payload: { ...request, id: missingTextId },
+ },
+ {
+ id: EventId.make(`recovery-native-thread-${trigger}-${scope}`),
+ type: "thread.created",
+ threadId: nativeThreadId,
+ occurredAt: now,
+ payload: {
+ ...original.thread,
+ id: nativeThreadId,
+ creationSource: "provider",
+ lineage: {
+ parentThreadId: threadId,
+ rootThreadId: threadId,
+ relationshipToParent: "subagent",
+ },
+ },
+ },
+ {
+ id: EventId.make(`recovery-native-request-${trigger}-${scope}`),
+ type: "runtime-request.updated",
+ threadId: nativeThreadId,
+ occurredAt: now,
+ payload: { ...request, id: nativeRequestId },
+ },
+ {
+ id: EventId.make(`recovery-native-item-${trigger}-${scope}`),
+ type: "turn-item.updated",
+ threadId: nativeThreadId,
+ occurredAt: now,
+ payload: {
+ ...questionItem,
+ id: TurnItemId.make(`recovery-native-item-${trigger}-${scope}`),
+ type: "user_input_request",
+ threadId: nativeThreadId,
+ runId: null,
+ requestId: nativeRequestId,
+ questions: [
+ { id: "color", header: "Color", question: "Which color?", options: [] },
+ ],
+ },
+ },
+ ],
+ });
+ yield* recovery.reconcile(trigger);
+ const recovered = yield* orchestrator.getThreadProjection(threadId);
+ if (scope === "run") {
+ assert.equal(recovered.runs[0]?.status, "cancelled");
+ } else {
+ assert.isEmpty(recovered.runs);
+ }
+ assert.deepEqual(
+ recovered.runtimeRequests.find((row) => row.id === requestId),
+ {
+ ...request,
+ responseCapability: { type: "message" },
+ },
+ );
+ assert.equal(recovered.nodes.find((row) => row.id === nodeId)?.status, "waiting");
+ assert.equal(recovered.turnItems.find((row) => row.id === itemId)?.status, "waiting");
+ for (const id of [approvalId, missingTextId]) {
+ const closed = recovered.runtimeRequests.find((row) => row.id === id);
+ assert.equal(closed?.status, trigger === "startup" ? "expired" : "cancelled");
+ assert.equal(closed?.responseCapability.type, "not_resumable");
+ }
+ const native = yield* orchestrator.getThreadProjection(nativeThreadId);
+ assert.equal(
+ native.runtimeRequests[0]?.status,
+ trigger === "startup" ? "expired" : "cancelled",
+ );
+ assert.equal(native.runtimeRequests[0]?.responseCapability.type, "not_resumable");
+ yield* recovery.reconcile("shutdown");
+ yield* recovery.reconcile("startup");
+ assert.deepEqual(
+ (yield* orchestrator.getThreadProjection(threadId)).runtimeRequests,
+ recovered.runtimeRequests,
+ );
+ yield* orchestrator.dispatch({
+ type: "runtime-request.respond",
+ commandId: CommandId.make(`recovery-answer-${trigger}-${scope}`),
+ threadId,
+ requestId,
+ answers: { color: "Blue", sizes: ["Small", "Large"] },
+ });
+ const answered = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(
+ answered.runtimeRequests.find((row) => row.id === requestId)?.status,
+ "resolved",
+ );
+ assert.equal(answered.nodes.find((row) => row.id === nodeId)?.status, "completed");
+ assert.equal(answered.turnItems.find((row) => row.id === itemId)?.status, "completed");
+ assert.lengthOf(answered.runs, recovered.runs.length + 1);
+ assert.equal(answered.messages.at(-1)?.runId, answered.runs.at(-1)?.id);
+ assert.equal(
+ answered.messages.at(-1)?.text,
+ "Which color?\nBlue\n\nWhich sizes?\nSmall, Large",
+ );
+ assert.deepEqual(
+ (yield* (yield* EffectOutbox.EffectOutboxV2).listByCommandId(
+ CommandId.make(`recovery-answer-${trigger}-${scope}`),
+ )).map((effect) => effect.request.type),
+ ["provider-turn.start"],
+ );
+ }),
+ );
+
it.effect("answers an async question after its provider exits and commits the answer once", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const eventSink = yield* EventSink.EventSinkV2;
- const now = yield* DateTime.now;
const threadId = ThreadId.make("runtime-async-question");
- const requestId = RuntimeRequestId.make("runtime-async-question-request");
- const nodeId = NodeId.make("runtime-async-question-node");
- const itemId = TurnItemId.make("runtime-async-question-item");
yield* orchestrator.dispatch({
type: "thread.create",
commandId: CommandId.make("runtime-async-question-create"),
@@ -1100,100 +1374,40 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
branch: null,
worktreePath: process.cwd(),
});
- yield* eventSink.write({
- commandId: CommandId.make("runtime-async-question-seed"),
- events: [
- {
- id: EventId.make("runtime-async-question-node-event"),
- type: "node.updated",
- threadId,
- nodeId,
- occurredAt: now,
- payload: {
- id: nodeId,
- threadId,
- runId: null,
- parentNodeId: null,
- rootNodeId: nodeId,
- kind: "user_input_request",
- status: "waiting",
- countsForRun: false,
- providerThreadId: null,
- providerTurnId: null,
- nativeItemRef: null,
- runtimeRequestId: requestId,
- checkpointScopeId: null,
- startedAt: now,
- completedAt: null,
- },
- },
- {
- id: EventId.make("runtime-async-question-request-event"),
- type: "runtime-request.updated",
- threadId,
- nodeId,
- occurredAt: now,
- payload: {
- id: requestId,
- nodeId,
- providerTurnId: null,
- nativeRequestRef: null,
- kind: "user_input",
- status: "pending",
- responseCapability: { type: "message" },
- createdAt: now,
- resolvedAt: null,
- },
- },
- {
- id: EventId.make("runtime-async-question-item-event"),
- type: "turn-item.updated",
- threadId,
- nodeId,
- occurredAt: now,
- payload: {
- id: itemId,
- type: "user_input_request",
- threadId,
- runId: null,
- nodeId,
- providerThreadId: null,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: 0,
- status: "waiting",
- title: null,
- startedAt: now,
- completedAt: null,
- updatedAt: now,
- requestId,
- responseMode: "message",
- questions: [{ id: "color", header: "Color", question: "Which color?", options: [] }],
- },
- },
- ],
+ const { requestId, nodeId, itemId } = yield* seedPendingQuestion(threadId, null, {
+ type: "message",
});
- const invalid = yield* orchestrator
- .dispatch({
- type: "runtime-request.respond",
- commandId: CommandId.make("runtime-async-question-blank"),
- threadId,
- requestId,
- answers: { color: " " },
- })
- .pipe(Effect.result);
- assert.equal(invalid._tag, "Failure");
- const unanswered = yield* orchestrator.getThreadProjection(threadId);
- assert.equal(unanswered.runtimeRequests[0]?.status, "pending");
- assert.deepEqual(unanswered.messages, []);
+ const outbox = yield* EffectOutbox.EffectOutboxV2;
+ const beforeInvalid = yield* orchestrator.getThreadProjection(threadId);
+ const beforeSequence = yield* eventSink.latestSequence();
+ for (const [index, answers] of [
+ { color: " ", sizes: ["Small"] },
+ { color: "Blue", sizes: [] },
+ { color: "Blue", sizes: ["Small", " "] },
+ { color: "Blue", sizes: ["Small"], extra: " " },
+ ].entries()) {
+ const commandId = CommandId.make(`runtime-async-question-invalid:${index}`);
+ const invalid = yield* orchestrator
+ .dispatch({
+ type: "runtime-request.respond",
+ commandId,
+ threadId,
+ requestId,
+ answers,
+ })
+ .pipe(Effect.result);
+ assert.equal(invalid._tag, "Failure", JSON.stringify(answers));
+ assert.deepEqual(yield* orchestrator.getThreadProjection(threadId), beforeInvalid);
+ assert.equal(yield* eventSink.latestSequence(), beforeSequence);
+ assert.deepEqual(yield* outbox.listByCommandId(commandId), []);
+ }
const command = {
type: "runtime-request.respond" as const,
commandId: CommandId.make("runtime-async-question-answer"),
threadId,
requestId,
- answers: { color: " Blue " },
+ answers: { color: " Blue ", sizes: ["Small", "Large"], note: "" },
};
const accepted = yield* orchestrator.dispatch(command);
const repeated = yield* orchestrator.dispatch(command);
@@ -1210,13 +1424,21 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
requestId,
answers: command.answers,
attachmentsByQuestionId: {},
- questionTextById: { color: "Which color?" },
+ questionTextById: {
+ color: "Which color?",
+ sizes: "Which sizes?",
+ note: "Anything else?",
+ },
});
}
assert.equal(answered.messages.length, 1);
- assert.equal(answered.messages[0]?.text, "Which color?\nBlue");
+ assert.equal(answered.messages[0]?.text, "Which color?\nBlue\n\nWhich sizes?\nSmall, Large");
assert.equal(answered.messages[0]?.role, "user");
assert.equal(answered.runs.length, 1);
+ assert.deepEqual(
+ (yield* outbox.listByCommandId(command.commandId)).map((effect) => effect.request.type),
+ ["provider-turn.start"],
+ );
const duplicate = yield* orchestrator
.dispatch({