From 9fc9e7c7ed699de161b9f90daa5d08172c975df1 Mon Sep 17 00:00:00 2001 From: Chris OHearn Date: Fri, 13 Nov 2026 13:57:29 -0700 Subject: [PATCH] fix(server): preserve one-shot cooldown bypasses --- .../src/orchestration-v2/Orchestrator.ts | 41 ++++++------- .../src/orchestration-v2/ProviderFailover.ts | 2 +- .../src/orchestration-v2/runtimeLayer.test.ts | 56 +++++++++++++++--- .../ProviderSwitch.integration.test.ts | 59 +++++++++++++++++-- 4 files changed, 124 insertions(+), 34 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index b5b30dd3fc77b..29c78cf8da09c 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -82,7 +82,7 @@ import { import * as ProviderFailover from "./ProviderFailover.ts"; import * as ProviderCooldown from "../provider/ProviderCooldown.ts"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; -import { modelSelectionsEqual } from "@t3tools/shared/model"; +import { draftModelPickMatchesThread, modelSelectionsEqual } from "@t3tools/shared/model"; import { modelSwitchSince } from "./modelSwitch.ts"; import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts"; import { recordThreadOpen } from "@t3tools/shared/paletteSearch"; @@ -2443,6 +2443,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (candidate) => candidate.id === storedQueuedRun.userMessageId, ); const requestedSelection = queuedRunModelSelection(projection, storedQueuedRun); + const consumesProviderCooldownBypass = + queuedMessage !== undefined && + ProviderFailover.resendable(queuedMessage) && + projection.thread.bypassProviderCooldown === true && + draftModelPickMatchesThread(requestedSelection, nextTurnModelSelection(projection.thread)); const modelSelection = queuedMessage === undefined ? requestedSelection @@ -2454,13 +2459,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio run: { ...storedQueuedRun, bypassProviderCooldown: - storedQueuedRun.bypassProviderCooldown === true || - projection.thread.bypassProviderCooldown === true || - (projection.thread.scheduledModelSelection != null && - modelSelectionsEqual( - requestedSelection, - projection.thread.scheduledModelSelection.modelSelection, - )), + storedQueuedRun.bypassProviderCooldown === true || consumesProviderCooldownBypass, }, message: queuedMessage, }); @@ -3122,7 +3121,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio [ ...(selectionChanged || threadAtStart !== projection.thread || - projection.thread.bypassProviderCooldown === true + consumesProviderCooldownBypass ? [ { type: !selectionChanged @@ -3137,7 +3136,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...threadAtStart, providerInstanceId: queuedRun.providerInstanceId, modelSelection: queuedRun.modelSelection, - bypassProviderCooldown: false, + ...(consumesProviderCooldownBypass ? { bypassProviderCooldown: false } : {}), updatedAt: now, }, }, @@ -5270,6 +5269,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return { ...thread, scheduledModelSelection: providerSwitchPlan.scheduled, + bypassProviderCooldown: true, updatedAt: now, }; } @@ -7818,15 +7818,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { modelSelection = queueTailModelSelection(projection); } + const resendablePrompt = ProviderFailover.resendable({ ...incomingMessage, role: "user" }); + const consumesProviderCooldownBypass = + resendablePrompt && + projection.thread.bypassProviderCooldown === true && + draftModelPickMatchesThread(modelSelection, nextTurnModelSelection(projection.thread)); const bypassProviderCooldown = - (command.modelSelection !== undefined && - !modelSelectionsEqual(command.modelSelection, projection.thread.modelSelection)) || - projection.thread.bypassProviderCooldown === true || - (projection.thread.scheduledModelSelection != null && - modelSelectionsEqual( - modelSelection, - projection.thread.scheduledModelSelection.modelSelection, - )); + (resendablePrompt && + command.modelSelection !== undefined && + !draftModelPickMatchesThread(command.modelSelection, projection.thread.modelSelection)) || + consumesProviderCooldownBypass; if ( command.failoverOfRunId === undefined && command.restartContinuationOfRunId === undefined && @@ -7838,10 +7839,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projectId: projection.thread.projectId, modelSelection, run: { bypassProviderCooldown }, - message: { ...command, role: "user" }, + message: { ...incomingMessage, role: "user" }, }); } - if (projection.thread.bypassProviderCooldown === true && startsOrQueuesRun) { + if (consumesProviderCooldownBypass && startsOrQueuesRun) { const now = yield* DateTime.now; const event = yield* emit( events, diff --git a/apps/server/src/orchestration-v2/ProviderFailover.ts b/apps/server/src/orchestration-v2/ProviderFailover.ts index 985f800d183c3..d92c57cf6d95c 100644 --- a/apps/server/src/orchestration-v2/ProviderFailover.ts +++ b/apps/server/src/orchestration-v2/ProviderFailover.ts @@ -37,7 +37,7 @@ export interface ProviderFailoverTargets { * Only a prompt someone sent is re-sent. Wakes, delegated results, compaction and slash * commands are provider-specific or have their own recovery. */ -function resendable( +export function resendable( message: Pick< OrchestrationV2ConversationMessage, "role" | "notification" | "delegatedCompletion" | "idleCompaction" | "workflowScript" | "text" diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 265292bebec26..1cb26d73d149b 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -8451,7 +8451,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { worktreePath: process.cwd(), }); // A restart continuation names the run's own model and comes from the server. - const send = (key: string, kind: "agent" | "server", queue: boolean) => + const send = (key: string, kind: "agent" | "server" | "notification", queue: boolean) => orchestrator.dispatch({ type: "message.dispatch", commandId: CommandId.make(`${threadId}:${key}`), @@ -8460,9 +8460,19 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { text: key, attachments: [], ...(kind === "server" ? { modelSelection } : {}), + ...(kind === "notification" + ? { + modelSelection: scheduledSelection, + notification: { + source: { kind: "monitor" as const }, + outcome: "updated" as const, + summary: key, + }, + } + : {}), dispatchMode: { type: queue ? "queue_after_active" : "start_immediately" }, createdBy: "agent", - creationSource: kind === "server" ? "server" : "mcp", + creationSource: kind === "agent" ? "mcp" : "server", }); const run = (key: string) => orchestrator @@ -8496,6 +8506,12 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { .getThreadProjection(threadId) .pipe(Effect.map(({ thread }) => thread.scheduledModelSelection ?? null)); yield* send("active", "agent", false); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make(`${threadId}:pick`), + threadId, + modelSelection, + }); yield* orchestrator.dispatch({ type: "thread.model-selection.set", commandId: CommandId.make(`${threadId}:schedule`), @@ -8503,12 +8519,16 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { modelSelection: scheduledSelection, applyAt: "next_turn", }); - return { threadId, send, run, complete, scheduledNow }; + const bypassNow = orchestrator + .getThreadProjection(threadId) + .pipe(Effect.map(({ thread }) => thread.bypassProviderCooldown === true)); + return { threadId, send, run, complete, scheduledNow, bypassNow }; }); // Queued behind the busy run. const queued = yield* scenario("queued"); yield* queued.send("continuation", "server", true); + assert.isTrue(yield* queued.bypassNow); yield* queued.send("after", "agent", true); assert.deepEqual((yield* queued.run("after")).modelSelection, scheduledSelection); yield* queued.complete("active"); @@ -8525,13 +8545,33 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { // Started at once on the idle thread, after the busy run ended. const immediate = yield* scenario("immediate"); yield* immediate.complete("active"); - yield* immediate.send("continuation", "server", false); - assert.deepEqual((yield* immediate.run("continuation")).modelSelection, modelSelection); - assert.isNotNull(yield* immediate.scheduledNow()); - yield* immediate.complete("continuation"); + for (const key of ["continuation", "another-continuation"]) { + yield* immediate.send(key, "server", false); + assert.deepEqual((yield* immediate.run(key)).modelSelection, modelSelection); + assert.isNotNull(yield* immediate.scheduledNow()); + assert.isTrue(yield* immediate.bypassNow); + yield* immediate.complete(key); + assert.isTrue(yield* immediate.bypassNow); + } yield* immediate.send("next", "agent", false); assert.deepEqual((yield* immediate.run("next")).modelSelection, scheduledSelection); assert.isNull(yield* immediate.scheduledNow()); + assert.isFalse(yield* immediate.bypassNow); + + const notifications = yield* scenario("notifications"); + yield* notifications.complete("active"); + for (const key of ["wake", "another-wake"]) { + yield* notifications.send(key, "notification", true); + assert.deepEqual((yield* notifications.run(key)).modelSelection, scheduledSelection); + assert.isNotNull(yield* notifications.scheduledNow()); + assert.isTrue(yield* notifications.bypassNow); + yield* notifications.complete(key); + assert.isTrue(yield* notifications.bypassNow); + } + yield* notifications.send("next", "agent", false); + assert.deepEqual((yield* notifications.run("next")).modelSelection, scheduledSelection); + assert.isNull(yield* notifications.scheduledNow()); + assert.isFalse(yield* notifications.bypassNow); }), ); @@ -9165,6 +9205,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { modelSelection: newerSelection, }); const waiting = yield* orchestrator.getThreadProjection(threadId); + assert.isTrue(waiting.thread.bypassProviderCooldown); yield* eventSink.write({ events: [ { @@ -9192,6 +9233,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { newerSelection.instanceId, ); assert.deepEqual(after.thread.modelSelection, newerSelection); + assert.isTrue(after.thread.bypassProviderCooldown); }), ); 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 e094fb5b3adbe..0d20b317d5fb9 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -3954,9 +3954,12 @@ describe("orchestration v2 provider switching", () => { "explicit", "picker", "scheduled", + "scheduled-dispatch", "immediate-default", "immediate-deferred", "immediate-same", + "immediate-fast-off", + "immediate-fast-omitted", "immediate-different", ] as const)("keeps queued %s routing safe while its requested account is cooling", (kind) => Effect.scoped( @@ -3965,7 +3968,7 @@ describe("orchestration v2 provider switching", () => { const capturedTurns = yield* Ref.make>([]); const started = yield* Deferred.make(); const immediate = kind.startsWith("immediate"); - const startsOnClaude = kind === "scheduled" || kind === "immediate-different"; + const startsOnClaude = kind.startsWith("scheduled") || kind === "immediate-different"; const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ makeTestAdapter({ instanceId: CODEX_MODEL_SELECTION.instanceId, @@ -3983,7 +3986,7 @@ describe("orchestration v2 provider switching", () => { modelSelection: CLAUDE_MODEL_SELECTION, responseByRunOrdinal: {}, capturedTurns, - ...(kind === "scheduled" ? { holdFirstTurn: started } : {}), + ...(kind.startsWith("scheduled") ? { holdFirstTurn: started } : {}), }), ]); yield* Effect.gen(function* () { @@ -3997,7 +4000,11 @@ describe("orchestration v2 provider switching", () => { threadId, projectId, title: "Cooldown queue", - modelSelection: startsOnClaude ? CLAUDE_MODEL_SELECTION : CODEX_MODEL_SELECTION, + modelSelection: startsOnClaude + ? CLAUDE_MODEL_SELECTION + : kind === "immediate-fast-omitted" + ? { ...CODEX_MODEL_SELECTION, options: [{ id: "fastMode", value: false }] } + : CODEX_MODEL_SELECTION, runtimeMode: "full-access", interactionMode: "default", branch: null, @@ -4024,7 +4031,12 @@ describe("orchestration v2 provider switching", () => { attachments: [], ...(kind === "immediate-default" || kind === "immediate-deferred" ? {} - : { modelSelection: CODEX_MODEL_SELECTION }), + : { + modelSelection: + kind === "immediate-fast-off" + ? { ...CODEX_MODEL_SELECTION, options: [{ id: "fastMode", value: false }] } + : CODEX_MODEL_SELECTION, + }), dispatchMode: { type: kind === "immediate-deferred" ? "defer_start" : "start_immediately", }, @@ -4076,13 +4088,13 @@ describe("orchestration v2 provider switching", () => { }); if (position === "first") yield* Deferred.await(started); } - if (kind === "picker" || kind === "scheduled") { + if (kind === "picker" || kind.startsWith("scheduled")) { yield* orchestrator.dispatch({ type: "thread.model-selection.set", commandId: CommandId.make("command:queued-cooldown:pick"), threadId, modelSelection: CODEX_MODEL_SELECTION, - ...(kind === "scheduled" ? { applyAt: "next_turn" as const } : {}), + ...(kind.startsWith("scheduled") ? { applyAt: "next_turn" as const } : {}), }); } const queued = yield* orchestrator.getThreadProjection(threadId); @@ -4101,6 +4113,7 @@ describe("orchestration v2 provider switching", () => { occurredAt: now, payload: { ...pending!, + ...(kind === "scheduled-dispatch" ? { queueHeld: true } : {}), ...(kind === "failover" ? { failoverOfRunId: active!.id } : {}), ...(kind === "restart" ? { restartContinuationOfRunId: active!.id } : {}), ...(kind === "claimed" @@ -4125,6 +4138,40 @@ describe("orchestration v2 provider switching", () => { }, ], }); + if (kind === "scheduled-dispatch") { + for (const position of ["picked", "later"] as const) { + yield* armCooldown; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`command:scheduled-cooldown:${position}`), + threadId, + messageId: MessageId.make(`message:scheduled-cooldown:${position}`), + text: position, + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "agent", + creationSource: "mcp", + }); + yield* worker.drain(); + yield* orchestrator.streamStoredEvents.pipe( + Stream.filter( + ({ event }) => + event.type === "run.updated" && + event.payload.userMessageId === + MessageId.make(`message:scheduled-cooldown:${position}`) && + event.payload.status === "completed", + ), + Stream.runHead, + ); + const after = yield* orchestrator.getThreadProjection(threadId); + const expected = + position === "picked" ? CODEX_MODEL_SELECTION : CLAUDE_MODEL_SELECTION; + assert.deepEqual(after.runs.at(-1)?.modelSelection, expected); + assert.deepEqual((yield* Ref.get(capturedTurns)).at(-1)?.modelSelection, expected); + assert.isNotNull(after.thread.scheduledModelSelection); + } + return; + } yield* orchestrator.resumeQueuedRuns; yield* worker.drain(); yield* orchestrator.streamStoredEvents.pipe(