@devries-cameron20 / t3code Mirror · read-only / commits / beb528ce4d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 17:15 UTC

fix(server): queued scheduled deliveries follow the thread's current model (#34149)

Co-authored-by: Ali Alwan <Ali-Al1@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Ali-Al1 committed Nov 13, 2026 at 17:34 UTC beb528ce4d67aff726de1f5ac2f707f5f977aedd
4 files changed +506 -11
apps/server/src/orchestration-v2/Orchestrator.ts
+33 -10
@@ -909,16 +909,23 @@ function nextQueuedRun(
909 return queuedRunsInDeliveryOrder(projection).find((run) => run.queueHeld !== true);
910 }
911
912 +// Delegated completions, monitor notifications and unpinned scheduled deliveries never choose a
913 +// model, so a queued one runs on the thread's current pick rather than the one frozen at queue time.
914 function followsCurrentConversation(
915 message:
916 | Pick<
917 OrchestrationV2ConversationMessage,
916 - "createdBy" | "creationSource" | "notification" | "delegatedCompletion"
918 + | "createdBy"
919 + | "creationSource"
920 + | "notification"
921 + | "delegatedCompletion"
922 + | "followsThreadSelection"
923 >
924 | undefined,
925 ): boolean {
926 return (
927 message?.delegatedCompletion !== undefined ||
928 + message?.followsThreadSelection === true ||
929 (message?.notification?.source.kind === "monitor" && !isBufferedProviderNotification(message))
930 );
931 }
@@ -1490,7 +1497,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1497
1498 /** The driver when this provider runs `/goal` natively, else undefined. */
1499 const goalDriverFor = Effect.fn("Orchestrator.goalDriverFor")(function* (
1493 - command: OrchestrationV2ServerCommand,
1500 + command: Pick<OrchestrationV2ServerCommand, "commandId" | "type">,
1501 providerInstanceId: ProviderInstanceId,
1502 ) {
1503 const adapter = yield* providerAdapters.get(providerInstanceId).pipe(mapDispatchError(command));
@@ -1505,7 +1512,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1512 /** Unsupported goal controls can become new objectives in native providers. */
1513 const ensureGoalCommandSupported = Effect.fn("Orchestrator.ensureGoalCommandSupported")(
1514 function* (
1508 - command: OrchestrationV2ServerCommand,
1515 + command: Pick<OrchestrationV2ServerCommand, "commandId" | "type">,
1516 message: { readonly text: string; readonly attachments: ReadonlyArray<ChatAttachment> },
1517 providerInstanceId: ProviderInstanceId,
1518 ) {
@@ -1531,7 +1538,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1538 );
1539
1540 const mapDispatchError =
1534 - (command: OrchestrationV2ServerCommand) =>
1541 + (command: Pick<OrchestrationV2ServerCommand, "commandId" | "type">) =>
1542 <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, OrchestratorDispatchError, R> =>
1543 effect.pipe(
1544 Effect.mapError(
@@ -2452,6 +2459,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2459 cause: `Queued run ${queuedRun.id} is missing projection state.`,
2460 });
2461 }
2462 + // A scheduled delivery starts on the thread's current pick, so /goal must suit that provider.
2463 + yield* ensureGoalCommandSupported(
2464 + { commandId, type: "message.dispatch" },
2465 + queuedMessage,
2466 + queuedRun.providerInstanceId,
2467 + );
2468
2469 const now = yield* DateTime.now;
2470 const targetAdapter = yield* providerAdapters.get(queuedRun.providerInstanceId).pipe(
@@ -2478,7 +2491,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2491 ? activeProviderThread
2492 : rootProviderThreadsForProvider(projection, queuedRun.providerInstanceId)[0]
2493 : freshContext &&
2481 - (storedProviderThread.firstRunOrdinal !== null ||
2494 + // The reserved row belongs to the instance the run queued on, which may have changed.
2495 + (storedProviderThread.providerInstanceId !== queuedRun.providerInstanceId ||
2496 + storedProviderThread.firstRunOrdinal !== null ||
2497 storedProviderThread.nativeThreadRef !== null)
2498 ? undefined
2499 : storedProviderThread;
@@ -7439,6 +7454,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7454 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
7455 ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
7456 ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
7457 + ...(command.scheduledTaskId !== undefined && command.modelSelection === undefined
7458 + ? { followsThreadSelection: true as const }
7459 + : {}),
7460 id: command.messageId,
7461 threadId: command.threadId,
7462 runId,
@@ -7851,6 +7869,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7869 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
7870 ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
7871 ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
7872 + ...(command.scheduledTaskId !== undefined && command.modelSelection === undefined
7873 + ? { followsThreadSelection: true as const }
7874 + : {}),
7875 id: command.messageId,
7876 threadId: command.threadId,
7877 runId,
@@ -10965,10 +10986,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10986
10987 const now = yield* DateTime.now;
10988 const emitEvent = emit(events, command);
10989 + // A scheduled delivery steers on the thread's current pick, so /goal must suit that provider.
10990 + const modelSelection = queuedRunModelSelection(projection, queuedRun);
10991 const parsedGoalCommand = parseGoalCommand(queuedMessage);
10992 const goalCommand =
10993 parsedGoalCommand === null ||
10971 - (yield* goalDriverFor(command, queuedRun.providerInstanceId)) === undefined
10994 + (yield* goalDriverFor(command, modelSelection.instanceId)) === undefined
10995 ? null
10996 : parsedGoalCommand;
10997 const target = projection.runs.find((run) => run.id === command.targetRunId);
@@ -10982,7 +11005,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11005 isCompactionCommandMessage(targetMessage)
11006 ) {
11007 if (goalCommand !== null) {
10985 - yield* ensureGoalCommandSupported(command, queuedMessage, queuedRun.providerInstanceId);
11008 + yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId);
11009 }
11010 yield* emitEvent({
11011 type: "run.updated",
@@ -11015,7 +11038,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11038 });
11039 }
11040 if (goalCommand !== null) {
11018 - yield* ensureGoalCommandSupported(command, queuedMessage, queuedRun.providerInstanceId);
11041 + yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId);
11042 const goal = projection.providerThreads.find(
11043 (candidate) => candidate.id === target?.providerThreadId,
11044 )?.goal;
@@ -11124,7 +11147,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11147 events,
11148 effects,
11149 projection,
11127 - modelSelection: queuedRun.modelSelection,
11150 + modelSelection,
11151 targetRunId: command.targetRunId,
11152 messageId: queuedMessage.id,
11153 text: queuedMessage.text,
@@ -11348,7 +11371,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11371 yield* ensureGoalCommandSupported(
11372 command,
11373 { text: command.text, attachments: command.attachments ?? queuedMessage.attachments },
11351 - queuedRun.providerInstanceId,
11374 + queuedRunModelSelection(projection, queuedRun).instanceId,
11375 );
11376 const queuedTurnItem = projection.turnItems.find(
11377 (candidate) => candidate.type === "user_message" && candidate.messageId === queuedMessage.id,
apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+190 -1
@@ -11,6 +11,7 @@ import {
11 ProviderInstanceId,
12 ProviderThreadId,
13 ProviderTurnId,
14 + ScheduledTaskId,
15 ThreadId,
16 TurnItemId,
17 type ModelSelection,
@@ -511,6 +512,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
512 onSteer: (
513 turn: ProviderAdapter.ProviderAdapterV2SteerInput,
514 ) => Effect.Effect<void, ProviderAdapter.ProviderAdapterV2Error> = () => Effect.void,
515 + extraAdapters: ReadonlyArray<ProviderAdapter.ProviderAdapterV2["Service"]> = [],
516 ) {
517 const driver = ProviderDriverKind.make(nativeGoals === undefined ? "codex" : "opencode");
518 const cwd = yield* checkpointWorkspace(name);
@@ -647,7 +649,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
649 };
650 const layer = ProviderReplayHarness.layerWithRegistry(
651 { name },
650 - ProviderAdapterRegistry.layerSingle(adapter),
652 + ProviderAdapterRegistry.layerFromAdapters([adapter, ...extraAdapters]),
653 { runEffectWorker: false },
654 );
655 const startFirstTurn = Effect.gen(function* () {
@@ -2158,6 +2160,193 @@ it.effect("steers a promoted queued message with the selection it was queued wit
2160 }),
2161 );
2162
2163 +it.effect("steers a promoted scheduled delivery with the thread's current selection", () =>
2164 + Effect.scoped(
2165 + Effect.gen(function* () {
2166 + const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
2167 + "promote-scheduled-selection",
2168 + );
2169 + yield* Effect.gen(function* () {
2170 + const orchestrator = yield* Orchestrator.OrchestratorV2;
2171 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2172 + const threadId = yield* startFirstTurn;
2173 + // Bound scheduled tasks send like ScheduledTaskService: no model of their own.
2174 + yield* orchestrator.dispatch({
2175 + type: "message.dispatch",
2176 + commandId: CommandId.make("scheduled"),
2177 + threadId,
2178 + messageId: MessageId.make("message:scheduled"),
2179 + scheduledTaskId: ScheduledTaskId.make("task:scheduled"),
2180 + text: "scheduled",
2181 + attachments: [],
2182 + dispatchMode: { type: "queue_after_active" },
2183 + createdBy: "user",
2184 + creationSource: "web",
2185 + });
2186 + const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2187 + (run) => run.status === "queued",
2188 + )!;
2189 + assert.deepEqual(queuedRun.modelSelection, runSelection);
2190 + yield* orchestrator.dispatch({
2191 + type: "thread.model-selection.set",
2192 + commandId: CommandId.make("select-composer"),
2193 + threadId,
2194 + modelSelection: composerSelection,
2195 + });
2196 + yield* orchestrator.dispatch({
2197 + type: "queued-message.promote-to-steer",
2198 + commandId: CommandId.make("promote"),
2199 + threadId,
2200 + queuedRunId: queuedRun.id,
2201 + targetRunId: started[0]!.runId,
2202 + });
2203 + yield* worker.drain();
2204 +
2205 + const projection = yield* orchestrator.getThreadProjection(threadId);
2206 + assert.deepEqual(steered, ["scheduled"]);
2207 + assert.deepEqual(projection.thread.modelSelection, composerSelection);
2208 + }).pipe(Effect.provide(layer));
2209 + }),
2210 + ),
2211 +);
2212 +
2213 +const claudeSelection = {
2214 + instanceId: ProviderInstanceId.make("claudeAgent"),
2215 + model: "claude-test",
2216 +};
2217 +const claudeAdapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
2218 + instanceId: claudeSelection.instanceId,
2219 + driver: ProviderDriverKind.make("claudeAgent"),
2220 + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
2221 + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
2222 + openSession: () => Effect.die("the Claude instance never starts a turn here"),
2223 +};
2224 +
2225 +// Queues a scheduled delivery behind the Codex turn, stops that turn (Stop holds the queue), then
2226 +// switches the thread to Claude: a thread changes instance only while no run is active.
2227 +const scheduledDeliveryAfterClaudeSwitch = (name: string, text: string) =>
2228 + Effect.gen(function* () {
2229 + const harness = yield* nextTurnSelectionHarness(
2230 + name,
2231 + false,
2232 + true,
2233 + Effect.void,
2234 + true,
2235 + undefined,
2236 + undefined,
2237 + [claudeAdapter],
2238 + );
2239 + const queueAndSwitch = Effect.gen(function* () {
2240 + const orchestrator = yield* Orchestrator.OrchestratorV2;
2241 + const threadId = yield* harness.startFirstTurn;
2242 + yield* orchestrator.dispatch({
2243 + type: "message.dispatch",
2244 + commandId: CommandId.make("scheduled"),
2245 + threadId,
2246 + messageId: MessageId.make("message:scheduled"),
2247 + scheduledTaskId: ScheduledTaskId.make("task:scheduled"),
2248 + text,
2249 + attachments: [],
2250 + dispatchMode: { type: "queue_after_active" },
2251 + createdBy: "user",
2252 + creationSource: "web",
2253 + });
2254 + const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2255 + (run) => run.status === "queued",
2256 + )!;
2257 + assert.equal(queuedRun.providerInstanceId, instanceId);
2258 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2259 + const first = harness.started[0]!;
2260 + yield* orchestrator.dispatch({
2261 + type: "run.interrupt",
2262 + commandId: CommandId.make("stop"),
2263 + threadId,
2264 + runId: first.runId,
2265 + holdQueue: true,
2266 + });
2267 + yield* worker.drain();
2268 + const stopped = (yield* orchestrator.getThreadProjection(threadId)).runs;
2269 + assert.equal(stopped.find((run) => run.id === first.runId)?.status, "interrupted");
2270 + const held = stopped.find((run) => run.id === queuedRun.id);
2271 + assert.equal(held?.status, "queued");
2272 + assert.isTrue(held?.queueHeld);
2273 + yield* orchestrator.dispatch({
2274 + type: "thread.model-selection.set",
2275 + commandId: CommandId.make("select-claude"),
2276 + threadId,
2277 + modelSelection: claudeSelection,
2278 + });
2279 + return { threadId, queuedRun };
2280 + });
2281 + return { ...harness, queueAndSwitch };
2282 + });
2283 +
2284 +it.effect("checks an edited scheduled /goal against the thread's current provider", () =>
2285 + Effect.scoped(
2286 + Effect.gen(function* () {
2287 + const { layer, queueAndSwitch } = yield* scheduledDeliveryAfterClaudeSwitch(
2288 + "edit-scheduled-goal",
2289 + "scheduled",
2290 + );
2291 + yield* Effect.gen(function* () {
2292 + const orchestrator = yield* Orchestrator.OrchestratorV2;
2293 + const { threadId, queuedRun } = yield* queueAndSwitch;
2294 + const editError = yield* orchestrator
2295 + .dispatch({
2296 + type: "queued-run.edit",
2297 + commandId: CommandId.make("edit"),
2298 + threadId,
2299 + runId: queuedRun.id,
2300 + text: "/goal pause",
2301 + })
2302 + .pipe(Effect.flip);
2303 +
2304 + assert.match(String(editError.cause), /Claude goals cannot be paused or resumed/);
2305 + assert.equal(
2306 + (yield* orchestrator.getThreadProjection(threadId)).messages.find(
2307 + (message) => message.id === queuedRun.userMessageId,
2308 + )?.text,
2309 + "scheduled",
2310 + );
2311 + }).pipe(Effect.provide(layer));
2312 + }),
2313 + ),
2314 +);
2315 +
2316 +it.effect("checks a queued scheduled /goal against the thread's current provider at start", () =>
2317 + Effect.scoped(
2318 + Effect.gen(function* () {
2319 + const { started, layer, queueAndSwitch } = yield* scheduledDeliveryAfterClaudeSwitch(
2320 + "start-scheduled-goal",
2321 + "/goal pause",
2322 + );
2323 + yield* Effect.gen(function* () {
2324 + const orchestrator = yield* Orchestrator.OrchestratorV2;
2325 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2326 + const { threadId, queuedRun } = yield* queueAndSwitch;
2327 + yield* orchestrator.dispatch({
2328 + type: "queue.resume",
2329 + commandId: CommandId.make("resume"),
2330 + threadId,
2331 + });
2332 + yield* orchestrator.resumeQueuedRuns;
2333 + yield* worker.drain();
2334 +
2335 + const projection = yield* orchestrator.getThreadProjection(threadId);
2336 + const failure = projection.turnItems.find(
2337 + (item) => item.type === "error" && item.runId === queuedRun.id,
2338 + );
2339 + assert.equal(started.length, 1);
2340 + assert.equal(projection.runs.find((run) => run.id === queuedRun.id)?.status, "failed");
2341 + assert.equal(
2342 + failure?.type === "error" ? failure.failure.code : null,
2343 + "queued_start_failed",
2344 + );
2345 + }).pipe(Effect.provide(layer));
2346 + }),
2347 + ),
2348 +);
2349 +
2350 it.effect("marks the model switch on a promoted message that restarts the turn", () =>
2351 Effect.gen(function* () {
2352 const { started, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+281
@@ -8479,6 +8479,287 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
8479 }),
8480 );
8481
8482 + it.effect.each([
8483 + { ...modelSelection, model: "gpt-5.5", options: [{ id: "reasoningEffort", value: "high" }] },
8484 + { instanceId: alternateInstanceId, model: "gpt-5.5" },
8485 + ])(
8486 + "starts a queued scheduled delivery on a selection set while it waited: %j",
8487 + (newerSelection) =>
8488 + Effect.gen(function* () {
8489 + const orchestrator = yield* Orchestrator.OrchestratorV2;
8490 + const threadId = ThreadId.make(
8491 + `runtime-layer-queued-scheduled-selection-${newerSelection.instanceId}-${"options" in newerSelection}`,
8492 + );
8493 + const scheduledMessageId = MessageId.make(`${threadId}:scheduled`);
8494 + yield* orchestrator.dispatch({
8495 + type: "thread.create",
8496 + commandId: CommandId.make(`${threadId}:create`),
8497 + threadId,
8498 + projectId: ProjectId.make(`${threadId}:project`),
8499 + createdBy: "user",
8500 + creationSource: "web",
8501 + title: "Scheduled delivery selection",
8502 + modelSelection,
8503 + runtimeMode: "full-access",
8504 + interactionMode: "default",
8505 + branch: null,
8506 + worktreePath: process.cwd(),
8507 + });
8508 + yield* orchestrator.dispatch({
8509 + type: "message.dispatch",
8510 + commandId: CommandId.make(`${threadId}:active`),
8511 + threadId,
8512 + messageId: MessageId.make(`${threadId}:active`),
8513 + text: "Busy",
8514 + attachments: [],
8515 + modelSelection,
8516 + dispatchMode: { type: "start_immediately" },
8517 + createdBy: "user",
8518 + creationSource: "web",
8519 + });
8520 + const active = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
8521 + // Bound scheduled tasks send like ScheduledTaskService: no model of their own.
8522 + yield* orchestrator.dispatch({
8523 + type: "message.dispatch",
8524 + commandId: CommandId.make(`${threadId}:scheduled`),
8525 + threadId,
8526 + messageId: scheduledMessageId,
8527 + scheduledTaskId: ScheduledTaskId.make(`${threadId}:task`),
8528 + text: "Scheduled prompt",
8529 + attachments: [],
8530 + dispatchMode: { type: "queue_after_active" },
8531 + createdBy: "user",
8532 + creationSource: "web",
8533 + });
8534 + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
8535 + (run) => run.userMessageId === scheduledMessageId,
8536 + )!;
8537 + assert.equal(queued.status, "queued");
8538 + assert.deepEqual(queued.modelSelection, modelSelection);
8539 + // Stop holds the queue; a thread changes instance only while no run is active.
8540 + yield* orchestrator.dispatch({
8541 + type: "run.interrupt",
8542 + commandId: CommandId.make(`${threadId}:stop`),
8543 + threadId,
8544 + runId: active.id,
8545 + holdQueue: true,
8546 + });
8547 + yield* orchestrator.dispatch({
8548 + type: "thread.model-selection.set",
8549 + commandId: CommandId.make(`${threadId}:select-newer`),
8550 + threadId,
8551 + modelSelection: newerSelection,
8552 + });
8553 + yield* orchestrator.dispatch({
8554 + type: "queue.resume",
8555 + commandId: CommandId.make(`${threadId}:resume`),
8556 + threadId,
8557 + });
8558 + yield* orchestrator.resumeQueuedRuns;
8559 + const after = yield* orchestrator.getThreadProjection(threadId);
8560 + const delivered = after.runs.find((run) => run.userMessageId === scheduledMessageId)!;
8561 + assert.equal(delivered.status, "starting");
8562 + assert.deepEqual(delivered.modelSelection, newerSelection);
8563 + assert.equal(
8564 + after.attempts.find((attempt) => attempt.id === delivered.activeAttemptId)
8565 + ?.providerInstanceId,
8566 + newerSelection.instanceId,
8567 + );
8568 + assert.deepEqual(after.thread.modelSelection, newerSelection);
8569 + assert.equal(after.thread.providerInstanceId, newerSelection.instanceId);
8570 + }),
8571 + );
8572 +
8573 + it.effect(
8574 + "starts a queued scheduled delivery that pinned a model on its pin after the thread moved",
8575 + () =>
8576 + Effect.gen(function* () {
8577 + const orchestrator = yield* Orchestrator.OrchestratorV2;
8578 + const threadId = ThreadId.make("runtime-layer-queued-scheduled-pinned-selection");
8579 + const scheduledMessageId = MessageId.make(`${threadId}:scheduled`);
8580 + const pinnedSelection = { instanceId: modelSelection.instanceId, model: "gpt-5.5" };
8581 + yield* orchestrator.dispatch({
8582 + type: "thread.create",
8583 + commandId: CommandId.make(`${threadId}:create`),
8584 + threadId,
8585 + projectId: ProjectId.make(`${threadId}:project`),
8586 + createdBy: "user",
8587 + creationSource: "web",
8588 + title: "Pinned scheduled selection",
8589 + modelSelection,
8590 + runtimeMode: "full-access",
8591 + interactionMode: "default",
8592 + branch: null,
8593 + worktreePath: process.cwd(),
8594 + });
8595 + yield* orchestrator.dispatch({
8596 + type: "message.dispatch",
8597 + commandId: CommandId.make(`${threadId}:active`),
8598 + threadId,
8599 + messageId: MessageId.make(`${threadId}:active`),
8600 + text: "Busy",
8601 + attachments: [],
8602 + modelSelection,
8603 + dispatchMode: { type: "start_immediately" },
8604 + createdBy: "user",
8605 + creationSource: "web",
8606 + });
8607 + const active = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
8608 + // A task that pins a model names it on the delivery, as a fresh-thread launch seeds it.
8609 + yield* orchestrator.dispatch({
8610 + type: "message.dispatch",
8611 + commandId: CommandId.make(`${threadId}:scheduled`),
8612 + threadId,
8613 + messageId: scheduledMessageId,
8614 + scheduledTaskId: ScheduledTaskId.make(`${threadId}:task`),
8615 + modelSelection: pinnedSelection,
8616 + text: "Pinned scheduled prompt",
8617 + attachments: [],
8618 + dispatchMode: { type: "queue_after_active" },
8619 + createdBy: "user",
8620 + creationSource: "web",
8621 + });
8622 + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
8623 + (run) => run.userMessageId === scheduledMessageId,
8624 + )!;
8625 + assert.equal(queued.status, "queued");
8626 + assert.deepEqual(queued.modelSelection, pinnedSelection);
8627 + // Stop holds the queue; a thread changes instance only while no run is active.
8628 + yield* orchestrator.dispatch({
8629 + type: "run.interrupt",
8630 + commandId: CommandId.make(`${threadId}:stop`),
8631 + threadId,
8632 + runId: active.id,
8633 + holdQueue: true,
8634 + });
8635 + // The user moves the thread off the pinned model while the delivery is held.
8636 + const movedSelection = { instanceId: alternateInstanceId, model: "gpt-5.5" };
8637 + yield* orchestrator.dispatch({
8638 + type: "thread.model-selection.set",
8639 + commandId: CommandId.make(`${threadId}:select-moved`),
8640 + threadId,
8641 + modelSelection: movedSelection,
8642 + });
8643 + yield* orchestrator.dispatch({
8644 + type: "queue.resume",
8645 + commandId: CommandId.make(`${threadId}:resume`),
8646 + threadId,
8647 + });
8648 + yield* orchestrator.resumeQueuedRuns;
8649 + const after = yield* orchestrator.getThreadProjection(threadId);
8650 + const delivered = after.runs.find((run) => run.userMessageId === scheduledMessageId)!;
8651 + assert.equal(delivered.status, "starting");
8652 + // The pin wins: the run starts on the selection the delivery named, not the thread's later pick.
8653 + assert.deepEqual(delivered.modelSelection, pinnedSelection);
8654 + assert.equal(
8655 + after.attempts.find((attempt) => attempt.id === delivered.activeAttemptId)
8656 + ?.providerInstanceId,
8657 + pinnedSelection.instanceId,
8658 + );
8659 + // Pinned tasks keep today's behaviour: the thread follows the run's selection back.
8660 + assert.deepEqual(after.thread.modelSelection, pinnedSelection);
8661 + }),
8662 + );
8663 +
8664 + it.effect(
8665 + "starts a fresh scheduled delivery on a new provider thread after a provider switch",
8666 + () =>
8667 + Effect.gen(function* () {
8668 + const orchestrator = yield* Orchestrator.OrchestratorV2;
8669 + const threadId = ThreadId.make("runtime-layer-fresh-scheduled-provider-thread");
8670 + const switchedSelection = { instanceId: alternateInstanceId, model: "gpt-5.5" };
8671 + const scheduledMessageId = MessageId.make(`${threadId}:scheduled`);
8672 + yield* orchestrator.dispatch({
8673 + type: "thread.create",
8674 + commandId: CommandId.make(`${threadId}:create`),
8675 + threadId,
8676 + projectId: ProjectId.make(`${threadId}:project`),
8677 + createdBy: "user",
8678 + creationSource: "web",
8679 + title: "Fresh scheduled provider thread",
8680 + modelSelection,
8681 + runtimeMode: "full-access",
8682 + interactionMode: "default",
8683 + branch: null,
8684 + worktreePath: process.cwd(),
8685 + });
8686 + yield* orchestrator.dispatch({
8687 + type: "message.dispatch",
8688 + commandId: CommandId.make(`${threadId}:active`),
8689 + threadId,
8690 + messageId: MessageId.make(`${threadId}:active`),
8691 + text: "Busy",
8692 + attachments: [],
8693 + modelSelection,
8694 + dispatchMode: { type: "start_immediately" },
8695 + createdBy: "user",
8696 + creationSource: "web",
8697 + });
8698 + const active = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
8699 + yield* orchestrator.dispatch({
8700 + type: "message.dispatch",
8701 + commandId: CommandId.make(`${threadId}:scheduled`),
8702 + threadId,
8703 + messageId: scheduledMessageId,
8704 + scheduledTaskId: ScheduledTaskId.make(`${threadId}:task`),
8705 + text: "Scheduled prompt",
8706 + attachments: [],
8707 + freshContext: true,
8708 + dispatchMode: { type: "queue_after_active" },
8709 + createdBy: "user",
8710 + creationSource: "web",
8711 + });
8712 + const queuedProjection = yield* orchestrator.getThreadProjection(threadId);
8713 + const queued = queuedProjection.runs.find(
8714 + (run) => run.userMessageId === scheduledMessageId,
8715 + )!;
8716 + // The queue reserved an unused provider thread on the original instance.
8717 + const reserved = queuedProjection.providerThreads.find(
8718 + (providerThread) => providerThread.id === queued.providerThreadId,
8719 + )!;
8720 + assert.equal(reserved.providerInstanceId, modelSelection.instanceId);
8721 + assert.isNull(reserved.firstRunOrdinal);
8722 + assert.isNull(reserved.nativeThreadRef);
8723 + // Stop holds the queue; a thread changes instance only while no run is active.
8724 + yield* orchestrator.dispatch({
8725 + type: "run.interrupt",
8726 + commandId: CommandId.make(`${threadId}:stop`),
8727 + threadId,
8728 + runId: active.id,
8729 + holdQueue: true,
8730 + });
8731 + yield* orchestrator.dispatch({
8732 + type: "thread.model-selection.set",
8733 + commandId: CommandId.make(`${threadId}:select-switched`),
8734 + threadId,
8735 + modelSelection: switchedSelection,
8736 + });
8737 + yield* orchestrator.dispatch({
8738 + type: "queue.resume",
8739 + commandId: CommandId.make(`${threadId}:resume`),
8740 + threadId,
8741 + });
8742 + yield* orchestrator.resumeQueuedRuns;
8743 +
8744 + const after = yield* orchestrator.getThreadProjection(threadId);
8745 + const delivered = after.runs.find((run) => run.userMessageId === scheduledMessageId)!;
8746 + assert.equal(delivered.status, "starting");
8747 + assert.isTrue(delivered.freshContext === true);
8748 + assert.notEqual(delivered.providerThreadId, reserved.id);
8749 + assert.equal(
8750 + after.providerThreads.find(
8751 + (providerThread) => providerThread.id === delivered.providerThreadId,
8752 + )?.providerInstanceId,
8753 + switchedSelection.instanceId,
8754 + );
8755 + assert.equal(
8756 + after.providerThreads.find((providerThread) => providerThread.id === reserved.id)
8757 + ?.providerInstanceId,
8758 + modelSelection.instanceId,
8759 + );
8760 + }),
8761 + );
8762 +
8763 it.effect("keeps the queue after a user interrupts the active run", () =>
8764 Effect.gen(function* () {
8765 const orchestrator = yield* Orchestrator.OrchestratorV2;
packages/contracts/src/orchestrationV2.ts
+2
@@ -1370,6 +1370,8 @@ export const OrchestrationV2ConversationMessage = Schema.Struct({
1370 notification: Schema.optional(OrchestrationV2Notification),
1371 ...OrchestrationV2CreationFields,
1372 scheduledTaskId: Schema.optional(ScheduledTaskId),
1373 + /** A scheduled delivery that named no model; it runs on the thread's selection at start. */
1374 + followsThreadSelection: Schema.optional(Schema.Literal(true)),
1375 senderThreadId: Schema.optional(ThreadId),
1376 linkedSender: Schema.optional(OrchestrationV2LinkedSender),
1377 idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),