Skip to content
TypeScript

fix(server): queued PR updates follow the takeover provider (#21314)

Lakshmi Tanmayf8bcc3cb0669
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 41077ee95db..1d50d19f59f 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -638,6 +638,45 @@ function nextQueuedRun(
return queuedRunsInDeliveryOrder(projection)[0];
}
+function followsCurrentConversation(
+ message: OrchestrationV2ConversationMessage | undefined,
+): boolean {
+ return (
+ message?.notification?.source.kind === "monitor" && !isBufferedProviderNotification(message)
+ );
+}
+
+function queuedRunModelSelection(
+ projection: Pick<OrchestrationV2ThreadProjection, "thread" | "messages">,
+ run: OrchestrationV2Run,
+): ModelSelection {
+ const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
+ // App-owned monitor updates follow the agent currently handling the thread.
+ return followsCurrentConversation(message)
+ ? projection.thread.modelSelection
+ : run.modelSelection;
+}
+
+function usageLimitHoldsQueue(
+ projection: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems" | "providerSessions">,
+ providerInstanceId: ModelSelection["instanceId"],
+): boolean {
+ let latestSession: OrchestrationV2ThreadProjection["providerSessions"][number] | undefined;
+ for (const session of projection.providerSessions) {
+ if (
+ session.providerInstanceId === providerInstanceId &&
+ (latestSession === undefined ||
+ DateTime.isGreaterThan(session.updatedAt, latestSession.updatedAt))
+ ) {
+ latestSession = session;
+ }
+ }
+ return (
+ usageLimitBlockedRun(projection.runs, projection.turnItems, latestSession?.lastError ?? null)
+ ?.providerInstanceId === providerInstanceId
+ );
+}
+
function latestStableRun(
projection: Pick<OrchestrationV2ThreadProjection, "runs">,
): OrchestrationV2Run | null {
@@ -1328,20 +1367,21 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return;
}
- // The limit already stopped this thread. Starting the queue would send
- // every waiting message and drop it from the queue as each one fails.
- const sessionError =
- projection.providerSessions
- .filter((session) => session.providerInstanceId === projection.thread.providerInstanceId)
- .toSorted(
- (left, right) =>
- DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
- )[0]?.lastError ?? null;
- if (usageLimitBlockedRun(projection.runs, projection.turnItems, sessionError) !== null) {
+ const storedQueuedRun = nextQueuedRun(projection);
+ if (storedQueuedRun === undefined) {
return;
}
- const queuedRun = nextQueuedRun(projection);
- if (queuedRun === undefined) {
+ const queuedMessage = projection.messages.find(
+ (candidate) => candidate.id === storedQueuedRun.userMessageId,
+ );
+ const modelSelection = queuedRunModelSelection(projection, storedQueuedRun);
+ const queuedRun = {
+ ...storedQueuedRun,
+ modelSelection,
+ providerInstanceId: modelSelection.instanceId,
+ };
+ // A limited provider would fail and consume every waiting message.
+ if (usageLimitHoldsQueue(projection, queuedRun.providerInstanceId)) {
return;
}
// A message queued behind a worktree that was cancelled or never created
@@ -1420,9 +1460,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const rootNode = projection.nodes.find((candidate) => candidate.id === rootNodeId);
const attempt = projection.attempts.find((candidate) => candidate.id === attemptId);
- const queuedMessage = projection.messages.find(
- (candidate) => candidate.id === queuedRun.userMessageId,
- );
const legacyQueuedTurnItem = projection.turnItems.find(
(
candidate,
@@ -1431,7 +1468,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
candidate.runId === queuedRun.id &&
candidate.messageId === queuedRun.userMessageId,
);
- const queuedProviderThread = projection.providerThreads.find(
+ const storedProviderThread = projection.providerThreads.find(
(candidate) => candidate.id === providerThreadId,
);
const storedCheckpointScope = projection.checkpointScopes.find(
@@ -1441,7 +1478,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
rootNode === undefined ||
attempt === undefined ||
queuedMessage === undefined ||
- queuedProviderThread === undefined ||
+ storedProviderThread === undefined ||
(rootNode.checkpointScopeId !== null && storedCheckpointScope === undefined)
) {
return yield* new OrchestratorDispatchError({
@@ -1453,27 +1490,83 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const commandId = CommandId.make(`command:system:start-queued:${queuedRun.id}`);
const now = yield* DateTime.now;
- const selectionChanged = !modelSelectionsEqual(
- projection.thread.modelSelection,
- queuedRun.modelSelection,
+ const targetAdapter = yield* providerAdapters.get(queuedRun.providerInstanceId).pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId,
+ commandType: "message.dispatch",
+ cause,
+ }),
+ ),
);
- const switchPlan = selectionChanged
- ? yield* providerSwitchService
- .plan({ projection, targetModelSelection: queuedRun.modelSelection })
- .pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId,
- commandType: "message.dispatch",
- cause,
- }),
- ),
- )
- : null;
const activeProviderThread = projection.providerThreads.find(
(candidate) => candidate.id === projection.thread.activeProviderThreadId,
);
+ const followsCurrent = followsCurrentConversation(queuedMessage);
+ const targetProviderThread = followsCurrent
+ ? activeProviderThread?.providerInstanceId === queuedRun.providerInstanceId
+ ? activeProviderThread
+ : rootProviderThreadsForProvider(projection, queuedRun.providerInstanceId)[0]
+ : storedProviderThread;
+ const queuedProviderThread: OrchestrationV2ProviderThread = targetProviderThread ?? {
+ id: idAllocator.derive.providerThread({
+ driver: targetAdapter.driver,
+ nativeThreadId: `pending:${queuedRun.id}`,
+ }),
+ driver: targetAdapter.driver,
+ providerInstanceId: queuedRun.providerInstanceId,
+ providerSessionId: null,
+ appThreadId: threadId,
+ ownerNodeId: null,
+ nativeThreadRef: null,
+ nativeConversationHeadRef: null,
+ status: "not_loaded",
+ firstRunOrdinal: null,
+ lastRunOrdinal: null,
+ handoffIds: [],
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+ const selectionChanged = !modelSelectionsEqual(
+ projection.thread.modelSelection,
+ queuedRun.modelSelection,
+ );
+ // The picker may already have moved ahead of the native conversation.
+ const switchFromActiveProvider =
+ followsCurrent &&
+ activeProviderThread !== undefined &&
+ activeProviderThread.providerInstanceId !== queuedRun.providerInstanceId;
+ const switchPlan =
+ selectionChanged || switchFromActiveProvider
+ ? yield* providerSwitchService
+ .plan({
+ projection: switchFromActiveProvider
+ ? {
+ ...projection,
+ thread: {
+ ...projection.thread,
+ modelSelection: {
+ ...projection.thread.modelSelection,
+ instanceId: activeProviderThread.providerInstanceId,
+ },
+ },
+ }
+ : projection,
+ targetModelSelection: queuedRun.modelSelection,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId,
+ commandType: "message.dispatch",
+ cause,
+ }),
+ ),
+ )
+ : null;
const canResumeAcrossInstances =
switchPlan?.instanceChanged === true &&
switchPlan.transition.type === "restart_and_resume" &&
@@ -1488,16 +1581,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
nativeMetadata: activeProviderThread.nativeMetadata,
}
: queuedProviderThread;
- const targetAdapter = yield* providerAdapters.get(queuedRun.providerInstanceId).pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId,
- commandType: "message.dispatch",
- cause,
- }),
- ),
- );
const targetCapabilities = yield* targetAdapter.getCapabilities().pipe(
Effect.mapError(
(cause) =>
@@ -1690,6 +1773,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
};
const startingRun: OrchestrationV2Run = {
...queuedRun,
+ providerThreadId: queuedProviderThread.id,
ordinal,
status: "starting",
queuePosition: null,
@@ -1728,6 +1812,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { senderThreadId: queuedMessage.senderThreadId }),
}),
+ providerThreadId: queuedProviderThread.id,
inputIntent: "queued_turn",
startedAt: now,
completedAt: now,
@@ -1774,26 +1859,45 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
strategy: activeHandoff.strategy,
summary: activeHandoff.summaryText,
};
- const checkpointEvents: ReadonlyArray<Omit<OrchestrationV2DomainEvent, "id">> =
- storedCheckpointScope === undefined
+ const executionIdentityEvents: ReadonlyArray<Omit<OrchestrationV2DomainEvent, "id">> =
+ storedCheckpointScope === undefined ||
+ storedProviderThread.id !== queuedProviderThread.id ||
+ attempt.providerInstanceId !== queuedRun.providerInstanceId
? [
{
type: "checkpoint-scope.created",
threadId,
runId: queuedRun.id,
- nodeId: rootNode.id,
+ nodeId: rootNodeId,
providerInstanceId: queuedRun.providerInstanceId,
occurredAt: now,
- payload: checkpointScope,
+ payload: { ...checkpointScope, providerThreadId: queuedProviderThread.id },
},
{
type: "node.updated",
threadId,
runId: queuedRun.id,
- nodeId: rootNode.id,
+ nodeId: rootNodeId,
+ providerInstanceId: queuedRun.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ ...rootNode,
+ providerThreadId: queuedProviderThread.id,
+ checkpointScopeId: checkpointScope.id,
+ },
+ },
+ {
+ type: "run-attempt.updated",
+ threadId,
+ runId: queuedRun.id,
+ nodeId: rootNodeId,
providerInstanceId: queuedRun.providerInstanceId,
occurredAt: now,
- payload: { ...rootNode, checkpointScopeId: checkpointScope.id },
+ payload: {
+ ...attempt,
+ providerInstanceId: queuedRun.providerInstanceId,
+ providerThreadId: queuedProviderThread.id,
+ },
},
]
: [];
@@ -1906,7 +2010,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
reason: "Provider or model selection changed.",
},
})),
- ...checkpointEvents,
+ ...executionIdentityEvents,
{
type: "provider-thread.updated",
threadId,
@@ -11250,8 +11354,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
case "queue.resume": {
const projection = yield* loadProjectionForCommand(
command,
- ["runs", "turnItems", "providerSessions"],
- { turnItemTypes: ["error"] },
+ ["runs", "turnItems", "providerSessions", "messages"],
+ { turnItemTypes: ["error"], messageRoles: ["user"] },
);
if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) {
return yield* new OrchestratorDispatchError({
@@ -11260,16 +11364,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
cause: `Thread ${command.threadId} is not active.`,
});
}
- const sessionError =
- projection.providerSessions
- .filter(
- (session) => session.providerInstanceId === projection.thread.providerInstanceId,
- )
- .toSorted(
- (left, right) =>
- DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
- )[0]?.lastError ?? null;
- if (usageLimitBlockedRun(projection.runs, projection.turnItems, sessionError) !== null) {
+ const nextRun = nextQueuedRun(projection);
+ if (
+ usageLimitHoldsQueue(
+ projection,
+ nextRun === undefined
+ ? projection.thread.providerInstanceId
+ : queuedRunModelSelection(projection, nextRun).instanceId,
+ )
+ ) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index 5ab27737554..e6ddf57b7e6 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -24,6 +24,7 @@ import {
PullRequestOperationError,
ProviderDriverKind,
ProviderInstanceId,
+ ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
RunId,
@@ -4921,6 +4922,267 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
+ it.effect("keeps queued user selections and pauses only the limited provider", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const threadId = ThreadId.make("runtime-layer-queue-provider-limit");
+ const queuedSelection = {
+ instanceId: alternateInstanceId,
+ model: "gpt-5.5",
+ options: [{ id: "reasoningEffort", value: "high" }],
+ };
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make(`${threadId}:create`),
+ threadId,
+ createdBy: "user",
+ creationSource: "web",
+ projectId: ProjectId.make(`${threadId}:project`),
+ title: "Limited queue",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: process.cwd(),
+ });
+ const selections = [modelSelection, modelSelection, queuedSelection];
+ for (const [index, selection] of selections.entries()) {
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make(`${threadId}:${index}`),
+ threadId,
+ messageId: MessageId.make(`${threadId}:${index}`),
+ text: `Prompt ${index}`,
+ attachments: [],
+ createdBy: "user",
+ creationSource: "web",
+ modelSelection: selection,
+ dispatchMode: { type: index === 0 ? "start_immediately" : "queue_after_active" },
+ });
+ }
+ const [active, limited, available] = (yield* orchestrator.getThreadProjection(threadId)).runs;
+ assert.isDefined(active);
+ assert.isDefined(limited);
+ assert.isDefined(available);
+ const now = yield* DateTime.now;
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make(`${threadId}:error`),
+ type: "turn-item.updated",
+ threadId,
+ runId: active.id,
+ nodeId: active.rootNodeId!,
+ providerInstanceId: active.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ id: TurnItemId.make(`${threadId}:error`),
+ type: "error",
+ threadId,
+ runId: active.id,
+ nodeId: active.rootNodeId!,
+ providerThreadId: active.providerThreadId,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: 2,
+ status: "failed",
+ title: "Usage limit",
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ failure: {
+ class: "usage_limit",
+ message: "Usage limit reached",
+ code: "usage_limit",
+ retryable: null,
+ },
+ },
+ },
+ {
+ id: EventId.make(`${threadId}:failed`),
+ type: "run.updated",
+ threadId,
+ runId: active.id,
+ providerInstanceId: active.providerInstanceId,
+ occurredAt: now,
+ payload: { ...active, status: "failed", completedAt: now },
+ },
+ {
+ id: EventId.make(`${threadId}:other-session`),
+ type: "provider-session.attached",
+ threadId,
+ providerInstanceId: alternateInstanceId,
+ occurredAt: now,
+ payload: {
+ id: ProviderSessionId.make(`${threadId}:other-session`),
+ driver,
+ providerInstanceId: alternateInstanceId,
+ status: "error",
+ cwd: process.cwd(),
+ model: queuedSelection.model,
+ capabilities: CodexProviderCapabilitiesV2,
+ createdAt: now,
+ updatedAt: now,
+ lastError: "Unrelated session error on the other provider",
+ },
+ },
+ ],
+ });
+ yield* orchestrator.dispatch({
+ type: "thread.model-selection.set",
+ commandId: CommandId.make(`${threadId}:select-other`),
+ threadId,
+ modelSelection: queuedSelection,
+ });
+ yield* orchestrator.resumeQueuedRuns;
+ const held = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(held.runs.find((run) => run.id === limited.id)?.status, "queued");
+ const blocked = yield* orchestrator
+ .dispatch({
+ type: "queue.resume",
+ commandId: CommandId.make(`${threadId}:blocked`),
+ threadId,
+ })
+ .pipe(Effect.flip);
+ assert.equal(blocked._tag, "OrchestratorDispatchError");
+
+ yield* orchestrator.dispatch({
+ type: "thread.model-selection.set",
+ commandId: CommandId.make(`${threadId}:select-original`),
+ threadId,
+ modelSelection,
+ });
+ yield* orchestrator.dispatch({
+ type: "queued-run.cancel",
+ commandId: CommandId.make(`${threadId}:cancel-limited`),
+ threadId,
+ runId: limited.id,
+ });
+ yield* orchestrator.resumeQueuedRuns;
+ const after = yield* orchestrator.getThreadProjection(threadId);
+ const started = after.runs.find((run) => run.id === available.id);
+ assert.equal(started?.status, "starting");
+ assert.deepEqual(started?.modelSelection, queuedSelection);
+ assert.deepEqual(after.thread.modelSelection, queuedSelection);
+ }),
+ );
+
+ it.effect.each([
+ ["server", modelSelection],
+ ["provider", modelSelection],
+ ["provider", { ...modelSelection, instanceId: alternateInstanceId }],
+ ] as const)(
+ "delivers a queued monitor update from %s after conversation selection %j",
+ ([creationSource, currentSelection]) =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const threadId = ThreadId.make(
+ `runtime-layer-queue-current-conversation-${creationSource}-${currentSelection.instanceId}`,
+ );
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make(`${threadId}:create`),
+ threadId,
+ projectId: ProjectId.make(`${threadId}:project`),
+ createdBy: "user",
+ creationSource: "web",
+ title: "Current conversation",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: process.cwd(),
+ });
+ for (const type of ["start_immediately", "queue_after_active"] as const) {
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make(`${threadId}:${type}`),
+ messageId: MessageId.make(`${threadId}:${type}`),
+ threadId,
+ text: type,
+ attachments: [],
+ createdBy: "agent",
+ creationSource,
+ dispatchMode: { type },
+ ...(type === "queue_after_active"
+ ? {
+ notification: {
+ source: { kind: "monitor" as const },
+ outcome: "updated" as const,
+ summary: "PR update",
+ },
+ }
+ : {}),
+ });
+ }
+ const before = yield* orchestrator.getThreadProjection(threadId);
+ const [active, queued] = before.runs;
+ assert.isDefined(active);
+ assert.isDefined(queued);
+ const now = yield* DateTime.now;
+ const current = {
+ ...before.providerThreads[0]!,
+ id: ProviderThreadId.make(`${threadId}:current`),
+ updatedAt: now,
+ };
+ yield* orchestrator.dispatch({
+ type: "thread.model-selection.set",
+ commandId: CommandId.make(`${threadId}:select-current`),
+ threadId,
+ modelSelection: currentSelection,
+ });
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make(`${threadId}:completed`),
+ type: "run.updated",
+ threadId,
+ runId: active.id,
+ occurredAt: now,
+ payload: { ...active, status: "completed", completedAt: now },
+ },
+ {
+ id: EventId.make(`${threadId}:conversation`),
+ type: "provider-thread.updated",
+ threadId,
+ occurredAt: now,
+ payload: current,
+ },
+ ],
+ });
+ const expectedThreadId =
+ creationSource === "provider" ? queued.providerThreadId : current.id;
+ yield* orchestrator.resumeQueuedRuns;
+ const after = yield* orchestrator.getThreadProjection(threadId);
+ const delivered = after.runs.find((run) => run.id === queued.id)!;
+ assert.equal(delivered.status, "starting");
+ assert.deepEqual(delivered.modelSelection, modelSelection);
+ assert.equal(delivered.providerInstanceId, modelSelection.instanceId);
+ assert.equal(
+ after.attempts.find((attempt) => attempt.id === delivered.activeAttemptId)
+ ?.providerInstanceId,
+ modelSelection.instanceId,
+ );
+ assert.equal(delivered.providerThreadId, expectedThreadId);
+ assert.equal(after.thread.activeProviderThreadId, expectedThreadId);
+ assert.equal(
+ after.attempts.find((attempt) => attempt.id === delivered.activeAttemptId)
+ ?.providerThreadId,
+ expectedThreadId,
+ );
+ const root = after.nodes.find((node) => node.id === delivered.rootNodeId)!;
+ assert.equal(root.providerThreadId, expectedThreadId);
+ assert.equal(
+ after.checkpointScopes.find((scope) => scope.id === root.checkpointScopeId)
+ ?.providerThreadId,
+ expectedThreadId,
+ );
+ }),
+ );
+
it.effect("keeps the queue after a user interrupts the active run", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
index e5bde378f5c..7f2e9cfabbf 100644
--- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
@@ -81,6 +81,7 @@ interface CapturedTurn {
readonly threadId: ThreadId;
readonly providerThreadId: ProviderThreadId;
readonly text: string;
+ readonly modelSelection: ModelSelection;
readonly attachments: ReadonlyArray<ChatAttachment>;
readonly nativeThreadId?: string | null;
readonly providerTurnOrdinal?: number;
@@ -112,6 +113,7 @@ function makeTestAdapter(input: {
readonly tokenUsageByRunOrdinal?: Readonly<
Record<number, Omit<OrchestrationV2ProviderTurnTokenUsage, "updatedAt">>
>;
+ readonly failure?: ReturnType<typeof makeProviderFailure>;
readonly failedRunOrdinals?: ReadonlySet<number>;
readonly interruptedRunOrdinals?: ReadonlySet<number>;
readonly holdRunOrdinal?: number;
@@ -243,6 +245,7 @@ function makeTestAdapter(input: {
threadId: turnInput.threadId,
providerThreadId: turnInput.providerThread.id,
text: turnInput.message.text,
+ modelSelection: turnInput.modelSelection,
attachments: turnInput.message.attachments,
nativeThreadId: turnInput.providerThread.nativeThreadRef?.nativeId ?? null,
providerTurnOrdinal: turnInput.providerTurnOrdinal,
@@ -330,11 +333,13 @@ function makeTestAdapter(input: {
? {
status: terminalStatus,
failureItemOrdinal: turnInput.runOrdinal * 100 + 2,
- failure: makeProviderFailure({
- message: "Simulated provider failure.",
- code: "simulated_failure",
- class: "provider_error",
- }),
+ failure:
+ input.failure ??
+ makeProviderFailure({
+ message: "Simulated provider failure.",
+ code: "simulated_failure",
+ class: "provider_error",
+ }),
}
: { status: terminalStatus, failure: null }),
threadDisposition: "reusable",
@@ -2229,6 +2234,239 @@ describe("orchestration v2 provider switching", () => {
),
);
+ it.live.each([
+ ["automatic", "Claude"],
+ ["queue.resume", "Claude"],
+ ["automatic", "compatible Codex"],
+ ["queue.resume", "compatible Codex"],
+ ] as const)(
+ "delivers a queued PR update on the current provider through %s (%s)",
+ ([delivery, target]) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const cwd = yield* checkpointWorkspace(`pr-wake-${delivery}`);
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
+ const started = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const compatible = target === "compatible Codex";
+ const selection = {
+ ...(compatible
+ ? { ...CODEX_MODEL_SELECTION, instanceId: ProviderInstanceId.make("codex-alternate") }
+ : CLAUDE_MODEL_SELECTION),
+ options: [{ id: "reasoningEffort", value: "low" }],
+ };
+ const targetCapabilities = compatible
+ ? {
+ ...CodexProviderCapabilitiesV2,
+ context: {
+ ...CodexProviderCapabilitiesV2.context,
+ canConsumeHandoffSummaries: false,
+ },
+ }
+ : ClaudeProviderCapabilitiesV2;
+ const adapters = [
+ makeTestAdapter({
+ instanceId: CODEX_MODEL_SELECTION.instanceId,
+ driver: CODEX_DRIVER,
+ capabilities: CodexProviderCapabilitiesV2,
+ modelSelection: CODEX_MODEL_SELECTION,
+ responseByRunOrdinal: {},
+ capturedTurns,
+ holdFirstTurn: started,
+ releaseFirstTurn: release,
+ failedRunOrdinals: new Set([1]),
+ failure: makeProviderFailure({
+ message: "Usage limit reached",
+ class: "usage_limit",
+ code: "usage_limit",
+ }),
+ }),
+ makeTestAdapter({
+ instanceId: selection.instanceId,
+ driver: compatible ? CODEX_DRIVER : CLAUDE_DRIVER,
+ capabilities: targetCapabilities,
+ modelSelection: selection,
+ responseByRunOrdinal: {},
+ capturedTurns,
+ }),
+ ];
+ const layerRegistry = compatible
+ ? Layer.succeed(
+ ProviderAdapterRegistry.ProviderAdapterRegistryV2,
+ ProviderAdapterRegistry.ProviderAdapterRegistryV2.of({
+ get: (instanceId) => {
+ const adapter = adapters.find(
+ (candidate) => candidate.instanceId === instanceId,
+ );
+ return adapter === undefined
+ ? Effect.fail(
+ new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({
+ instanceId,
+ }),
+ )
+ : Effect.succeed(adapter);
+ },
+ list: () => Effect.succeed(adapters.map((adapter) => adapter.instanceId)),
+ getMetadata: (instanceId) =>
+ Effect.succeed({
+ driver: CODEX_DRIVER,
+ continuationKey: "codex:shared-native-account-history",
+ enabled: true,
+ capabilities:
+ instanceId === selection.instanceId
+ ? targetCapabilities
+ : CodexProviderCapabilitiesV2,
+ }),
+ }),
+ )
+ : ProviderAdapterRegistry.layerFromAdapters(adapters);
+ yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ const dispatch = (text: string, modelSelection: ModelSelection) =>
+ orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make(text),
+ messageId: MessageId.make(text),
+ threadId,
+ text,
+ modelSelection,
+ attachments: [],
+ createdBy: "user",
+ creationSource: "web",
+ dispatchMode: { type: "start_immediately" },
+ });
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("create"),
+ threadId,
+ projectId,
+ createdBy: "user",
+ creationSource: "web",
+ title: "PR wake",
+ modelSelection: CODEX_MODEL_SELECTION,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: cwd,
+ });
+ yield* dispatch("Original work", CODEX_MODEL_SELECTION);
+ yield* Deferred.await(started);
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make("wake"),
+ messageId: MessageId.make("wake"),
+ threadId,
+ text: "Review the new PR comments",
+ attachments: [],
+ createdBy: "agent",
+ creationSource: "server",
+ dispatchMode: { type: "queue_after_active" },
+ notification: {
+ source: { kind: "monitor" },
+ outcome: "updated",
+ summary: "New PR comments",
+ },
+ });
+ const [active, wake] = (yield* orchestrator.getThreadProjection(threadId)).runs;
+ assert.isDefined(active);
+ assert.isDefined(wake);
+ assert.equal(wake.status, "queued");
+ yield* Deferred.succeed(release, undefined);
+ yield* orchestrator.streamStoredEvents.pipe(
+ Stream.filter(
+ ({ event }) =>
+ event.type === "run.updated" &&
+ event.runId === active.id &&
+ event.payload.status === "failed",
+ ),
+ Stream.runHead,
+ );
+ yield* worker.drain();
+
+ if (delivery === "automatic") {
+ yield* dispatch("Take over the work", selection);
+ } else {
+ yield* orchestrator.dispatch({
+ type: "thread.model-selection.set",
+ commandId: CommandId.make("select"),
+ threadId,
+ modelSelection: selection,
+ });
+ yield* orchestrator.dispatch({
+ type: "queue.resume",
+ commandId: CommandId.make("resume"),
+ threadId,
+ });
+ }
+ yield* orchestrator.streamStoredEvents.pipe(
+ Stream.filter(
+ ({ event }) =>
+ event.type === "run.updated" &&
+ event.runId === wake.id &&
+ (event.payload.status === "completed" || event.payload.status === "failed"),
+ ),
+ Stream.runHead,
+ );
+ yield* worker.drain();
+ const after = yield* orchestrator.getThreadProjection(threadId);
+ const turns = yield* Ref.get(capturedTurns);
+ assert.lengthOf(turns, delivery === "automatic" ? 3 : 2);
+ const executed = turns.at(-1)!;
+ assert.equal(executed.driver, compatible ? CODEX_DRIVER : CLAUDE_DRIVER);
+ assert.include(executed.text, "Review the new PR comments");
+ assert.deepEqual(executed.modelSelection, selection);
+ assert.deepEqual(after.thread.modelSelection, selection);
+ const delivered = after.runs.find((run) => run.id === wake.id)!;
+ assert.equal(delivered.status, "completed");
+ assert.deepEqual(delivered.modelSelection, selection);
+ assert.equal(delivered.providerInstanceId, selection.instanceId);
+ assert.equal(delivered.providerThreadId, executed.providerThreadId);
+ assert.equal(after.thread.activeProviderThreadId, delivered.providerThreadId);
+ if (delivery === "automatic") {
+ assert.equal(executed.providerThreadId, turns[1]!.providerThreadId);
+ assert.equal(executed.nativeThreadId, turns[1]!.nativeThreadId);
+ }
+ if (compatible) {
+ assert.equal(executed.nativeThreadId, turns[0]!.nativeThreadId);
+ assert.isEmpty(after.contextHandoffs);
+ if (delivery === "automatic") {
+ assert.equal(delivered.providerThreadId, wake.providerThreadId);
+ }
+ }
+ assert.equal(
+ after.providerThreads.find((entry) => entry.id === delivered.providerThreadId)
+ ?.providerInstanceId,
+ selection.instanceId,
+ );
+ assert.equal(
+ after.turnItems.find(
+ (entry) => entry.type === "notification" && entry.runId === wake.id,
+ )?.providerThreadId,
+ delivered.providerThreadId,
+ );
+ const attempt = after.attempts.find((entry) => entry.id === delivered.activeAttemptId);
+ const root = after.nodes.find((entry) => entry.id === delivered.rootNodeId);
+ assert.equal(attempt?.providerInstanceId, selection.instanceId);
+ assert.equal(attempt?.providerThreadId, delivered.providerThreadId);
+ assert.equal(root?.providerThreadId, delivered.providerThreadId);
+ assert.equal(
+ after.checkpointScopes.find((entry) => entry.id === root?.checkpointScopeId)
+ ?.providerThreadId,
+ delivered.providerThreadId,
+ );
+ }).pipe(
+ Effect.provide(
+ ProviderReplayHarness.layerWithRegistry(
+ { name: `pr-wake-${delivery}`, runtimePolicyOverride: { cwd } },
+ layerRegistry,
+ ),
+ ),
+ );
+ }),
+ ),
+ );
+
it.live("fails an unsupported queued handoff and advances to the next queued provider", () =>
Effect.scoped(
Effect.gen(function* () {