From f89be48445000df493def1487158fc0597c63608 Mon Sep 17 00:00:00 2001 From: Chris OHearn Date: Thu, 12 Nov 2026 21:56:21 -0700 Subject: [PATCH 1/3] fix(server): keep a stored snooze for awake threads; hold a scheduled model for default turns From the PR #94 delta review: - A default agent send to a thread that counted as awake only because of a pending request, guest message or error erased its dated snooze. It now delivers and keeps the stored snooze. So does a thread that has never run. The send's warning says it was delivered. - A scheduled model change was cleared once only explicit picks were ahead of it, so a later default message got the older pick. It now stays until a default-model turn starts with it, after everything queued before it, and a model named after the change replaces it. - Tests: a later completed run, such as a usage limit's resume, releases snooze-held turns only once the thread is awake. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/OrchestratorMcpService.ts | 8 +- apps/server/src/mcp/snoozeNotice.ts | 3 +- .../src/orchestration-v2/Orchestrator.ts | 53 +++++-- .../src/orchestration-v2/runtimeLayer.test.ts | 141 +++++++++++++++++- ...ect-snoozes-and-scheduled-model-changes.md | 4 +- .../orchestrator-mcp-server.md | 19 ++- docs/user/outside-agents.md | 5 +- 7 files changed, 202 insertions(+), 31 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 4bd094eed8b2..c237dcc9a913 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1318,7 +1318,7 @@ const make = Effect.gen(function* () { const snoozeOutcome = Effect.fn("OrchestratorMcpService.snoozeOutcome")(function* ( threadId: ThreadId, snoozedUntil: DateTime.Utc | null | undefined, - kept: "held" | "posted" | "steered", + kept: "held" | "posted" | "steered" | "delivered", ) { const nowMs = yield* Clock.currentTimeMillis; if (snoozedUntil == null || DateTime.toEpochMillis(snoozedUntil) <= nowMs) return {}; @@ -3539,7 +3539,11 @@ const make = Effect.gen(function* () { ...(yield* snoozeOutcome( input.threadId, target.thread.snoozedUntil, - result.run.snoozeDeferred === true ? "held" : "steered", + result.run.snoozeDeferred === true + ? "held" + : result.delivery === "steered" + ? "steered" + : "delivered", )), threadId: input.threadId, link: threadLinkFor(scope, input.threadId, target.thread.title), diff --git a/apps/server/src/mcp/snoozeNotice.ts b/apps/server/src/mcp/snoozeNotice.ts index 3c43b5072c84..984700ce2972 100644 --- a/apps/server/src/mcp/snoozeNotice.ts +++ b/apps/server/src/mcp/snoozeNotice.ts @@ -1,6 +1,6 @@ import * as DateTime from "effect/DateTime"; -export type SnoozeOutcome = "held" | "posted" | "steered" | "woke"; +export type SnoozeOutcome = "held" | "posted" | "steered" | "delivered" | "woke"; /** What a sender learns about a target's snooze; nothing when the thread was awake. */ export function snoozeNotice( @@ -15,6 +15,7 @@ export function snoozeNotice( held: `${prefix} The message waits, held, until it wakes. Pass respectSnooze: false to wake it now.`, posted: `${prefix} The message was recorded and the thread stays snoozed.`, steered: `${prefix} The message joined its running turn, and the thread stays snoozed.`, + delivered: `${prefix} It counts as awake for now (a pending request or an error), so the message was delivered; the snooze stays.`, woke: `${prefix} This message ended the snooze.`, }[outcome]; return { snoozedUntil: until, warning }; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 8908049aaf3e..1cc8bb98b38d 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -995,20 +995,34 @@ function queuedBeforeScheduledSelection( ); } -/** Drops a scheduled change once the run starting now leaves no run queued before it. */ +/** + * A scheduled change lasts until a turn on the default model takes it with nothing queued before + * the change still waiting, explicit picks included. A model named after the change replaces it. + */ function threadAtRunStart( projection: Pick, - startingRunId: OrchestrationV2Run["id"] | null, + starting: { + readonly runId: OrchestrationV2Run["id"] | null; + /** Null for a turn starting now, which is newer than any scheduled change. */ + readonly ordinal: number | null; + readonly namedModel: boolean; + }, ): OrchestrationV2ThreadProjection["thread"] { const scheduled = projection.thread.scheduledModelSelection; if (scheduled == null) return projection.thread; + const cleared = { ...projection.thread, scheduledModelSelection: null }; + if (starting.namedModel) { + return starting.ordinal !== null && starting.ordinal <= scheduled.queuedThroughOrdinal + ? projection.thread + : cleared; + } const waiting = projection.runs.some( (run) => - run.id !== startingRunId && + run.id !== starting.runId && run.status === "queued" && - queuedBeforeScheduledSelection(projection, run), + run.ordinal <= scheduled.queuedThroughOrdinal, ); - return waiting ? projection.thread : { ...projection.thread, scheduledModelSelection: null }; + return waiting ? projection.thread : cleared; } function queuedRunFollowsThread( @@ -2552,7 +2566,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection.thread.modelSelection, queuedRun.modelSelection, ); - const threadAtStart = threadAtRunStart(projection, queuedRun.id); + const threadAtStart = threadAtRunStart(projection, { + runId: queuedRun.id, + ordinal: queuedRun.ordinal, + namedModel: queuedRun.explicitModelSelection === true, + }); // The picker may already have moved ahead of the native conversation. const switchFromActiveProvider = followsCurrent && @@ -7045,20 +7063,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.notification !== undefined || command.delegatedCompletion !== undefined || serverNotice; - // A sender that respects the snooze leaves it: a post is only recorded, and a turn waits, - // held behind the thread's last run, until the thread wakes. A thread with no run wakes, - // and so does one the server snoozed until its usage limit resets: that is no one's hold. - // The snooze counts as the sidebar shows it: an error or a request has already woken it. + // A sender that respects the snooze keeps its dated hold (a usage-limit snooze is no one's). + // While the thread is snoozed as the sidebar shows it, a turn waits behind its last run; a + // thread that counts as awake, or never ran, gets the message now. const snoozeHeldUntil = projection.thread.snoozedUntil; const limitRecovery = projection.thread.limitRecovery; - const respectsSnooze = + const keepsSnooze = command.respectSnooze === true && !automaticWake && snoozeHeldUntil != null && + DateTime.toEpochMillis(snoozeHeldUntil) > DateTime.toEpochMillis(yield* DateTime.now) && !( limitRecovery?.snooze === true && DateTime.toEpochMillis(snoozeHeldUntil) === Date.parse(limitRecovery.resetAt) - ) && + ); + const respectsSnooze = + keepsSnooze && (command.postOnly === true || latestExecutedRun(projection.runs) != null) && isSnoozed( (yield* projectionStore @@ -7071,7 +7091,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, DateTime.toEpochMillis(yield* DateTime.now), ); - if (projection.thread.snoozedUntil != null && !automaticWake && !respectsSnooze) { + if (projection.thread.snoozedUntil != null && !automaticWake && !keepsSnooze) { const now = yield* DateTime.now; const thread: OrchestrationV2AppThread = { ...projection.thread, @@ -8063,7 +8083,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const selectionChanged = !modelSelectionsEqual(projection.thread.modelSelection, modelSelection) || projection.thread.providerInstanceId !== modelSelection.instanceId; - const threadAtStart = threadAtRunStart(projection, null); + // Server continuations repeat an earlier run's model; they name nothing new. + const threadAtStart = threadAtRunStart(projection, { + runId: null, + ordinal: null, + namedModel: command.modelSelection !== undefined && command.creationSource !== "server", + }); if (selectionChanged || threadAtStart !== projection.thread) { yield* emit( events, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 7014ee3e2a64..c022c93b5b91 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -7961,6 +7961,124 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect( + "a later completed run releases snooze-held messages only once the thread is awake", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make("runtime-layer-snooze-held-release"); + const { send, runFor, end, releasedAfter } = yield* queueTestThread(threadId); + const message = (key: string, extra: object) => + orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "mcp", + commandId: CommandId.make(`${threadId}:message:${key}`), + threadId, + messageId: MessageId.make(`${threadId}:message:${key}`), + text: key, + attachments: [], + dispatchMode: { type: "start_immediately" }, + ...extra, + }); + yield* send("first", "agent", true); + yield* end("first", "completed"); + yield* orchestrator.dispatch({ + type: "thread.snooze", + commandId: CommandId.make(`${threadId}:snooze`), + threadId, + snoozedUntil: "2099-01-01T00:00:00.000Z", + }); + yield* message("held", { respectSnooze: true }); + assert.isTrue((yield* runFor("held")).snoozeDeferred); + + // A background wake runs and completes while the thread sleeps: the held turn stays held. + yield* message("wake", { + createdBy: "agent", + creationSource: "provider", + dispatchMode: { type: "queue_after_active" }, + notification: { + source: { kind: "background_task" }, + outcome: "updated", + summary: "Background activity updated", + }, + }); + yield* end("wake", "completed"); + const stillHeld = yield* runFor("held"); + assert.isTrue(stillHeld.queueHeld); + assert.isTrue(stillHeld.snoozeDeferred); + + // Awake, the next completed run (a usage limit's resume, say) releases it like the others. + yield* orchestrator.dispatch({ + type: "thread.unsnooze", + commandId: CommandId.make(`${threadId}:unsnooze`), + threadId, + reason: "user", + }); + yield* send("resume", "agent", true); + yield* end("resume", "completed"); + yield* releasedAfter("held", "resume"); + assert.isUndefined((yield* runFor("held")).snoozeDeferred); + }), + ); + + it.effect("delivers to a snoozed thread that counts as awake without ending its snooze", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make("runtime-layer-snooze-awake-on-error"); + const { send, runFor, end } = yield* queueTestThread(threadId); + yield* send("first", "agent", true); + yield* end("first", "completed"); + yield* orchestrator.dispatch({ + type: "thread.snooze", + commandId: CommandId.make(`${threadId}:snooze`), + threadId, + snoozedUntil: "2099-01-01T00:00:00.000Z", + }); + yield* TestClock.adjust("1 second"); + // A background wake fails after the snooze, which wakes the thread as the sidebar shows it. + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "provider", + commandId: CommandId.make(`${threadId}:message:wake`), + threadId, + messageId: MessageId.make(`${threadId}:message:wake`), + text: "wake", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + notification: { + source: { kind: "background_task" }, + outcome: "updated", + summary: "Background activity updated", + }, + }); + yield* end("wake", "failed"); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "mcp", + commandId: CommandId.make(`${threadId}:message:respect`), + threadId, + messageId: MessageId.make(`${threadId}:message:respect`), + text: "respect", + attachments: [], + dispatchMode: { type: "start_immediately" }, + respectSnooze: true, + }); + const delivered = yield* runFor("respect"); + assert.equal(delivered.status, "starting"); + assert.isUndefined(delivered.snoozeDeferred); + const thread = (yield* orchestrator.getThreadProjection(threadId)).thread; + assert.equal( + thread.snoozedUntil === null || thread.snoozedUntil === undefined + ? null + : DateTime.formatIso(thread.snoozedUntil), + "2099-01-01T00:00:00.000Z", + ); + }), + ); + it.effect("keeps held agent messages while the thread's worktree setup is unresolved", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -8668,7 +8786,11 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { assert.isTrue(heldRun.snoozeDeferred); // Its own held turn does not stop the thread from being snoozed again. yield* snooze("2099-02-01T00:00:00.000Z"); - assert.deepEqual(yield* SnoozeDeferredDelivery.readSnoozeDeferredThreads(), [ + const ownDeferrals = () => + SnoozeDeferredDelivery.readSnoozeDeferredThreads().pipe( + Effect.map((rows) => rows.filter((row) => row.threadId === threadId)), + ); + assert.deepEqual(yield* ownDeferrals(), [ { threadId, snoozedUntil: "2099-02-01T00:00:00.000Z", firstRunId: heldRun.id }, ]); @@ -8678,7 +8800,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { threadId, reason: "user", }); - const [awake] = yield* SnoozeDeferredDelivery.readSnoozeDeferredThreads(); + const [awake] = yield* ownDeferrals(); assert.equal( SnoozeDeferredDelivery.snoozeDeferredReleases( [awake!], @@ -8696,7 +8818,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { assert.equal(releasedRun.status, "starting"); // Released, it is no longer the snooze's: a failure hold later must not release it again. assert.isUndefined(releasedRun.snoozeDeferred); - assert.deepEqual(yield* SnoozeDeferredDelivery.readSnoozeDeferredThreads(), []); + assert.deepEqual(yield* ownDeferrals(), []); }), ); @@ -8786,12 +8908,23 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { const started2 = secondBoundary.runs.find((run) => run.id === before2!.id)!; assert.equal(started2.status, "starting"); assert.deepEqual(started2.modelSelection, scheduledSelection); - assert.isNull(secondBoundary.thread.scheduledModelSelection ?? null); + // The pick still waits, so the change stays for the default turns after it. + assert.isNotNull(secondBoundary.thread.scheduledModelSelection ?? null); const thirdBoundary = yield* complete(before2!.id); const startedPick = thirdBoundary.runs.find((run) => run.id === picked!.id)!; assert.equal(startedPick.status, "starting"); assert.deepEqual(startedPick.modelSelection, pickedSelection); + assert.deepEqual(thirdBoundary.thread.modelSelection, pickedSelection); + assert.isNotNull(thirdBoundary.thread.scheduledModelSelection ?? null); + + // The next default turn goes back to the scheduled model, and that uses the change up. + const fourthBoundary = yield* complete(picked!.id); + const startedAfter = fourthBoundary.runs.find((run) => run.id === after!.id)!; + assert.equal(startedAfter.status, "starting"); + assert.deepEqual(startedAfter.modelSelection, scheduledSelection); + assert.deepEqual(fourthBoundary.thread.modelSelection, scheduledSelection); + assert.isNull(fourthBoundary.thread.scheduledModelSelection ?? null); }), ); diff --git a/docs/jarvis/decisions/0017-agent-sends-respect-snoozes-and-scheduled-model-changes.md b/docs/jarvis/decisions/0017-agent-sends-respect-snoozes-and-scheduled-model-changes.md index 7579f51a9ec4..1924ad62a414 100644 --- a/docs/jarvis/decisions/0017-agent-sends-respect-snoozes-and-scheduled-model-changes.md +++ b/docs/jarvis/decisions/0017-agent-sends-respect-snoozes-and-scheduled-model-changes.md @@ -10,12 +10,14 @@ Accepted 2026-11-13. Number provisional until merge. - A send's turn is queued and held until the snooze ends or someone wakes the thread, and the server then resumes the queue. A post is only recorded. - Both results return `snoozedUntil` and a warning. - `respectSnooze: false` wakes the thread, as every send did before. -- Messages a person sends from the app still wake it. So do sends to a thread that has never run, and to a thread the server snoozed until a usage limit resets. +- A thread that counts as awake (a pending request, a guest message, an error), or has never run, gets the message at once, and its dated hold stays stored. +- Messages a person sends from the app still end the snooze, and so does a send to a thread the server snoozed until a usage limit resets. **Scheduled model changes.** `t3_thread_configure` with `modelSelection` and `applyAt: "next_turn"` works on a busy thread instead of being refused. - The thread starts its next turn with the new model or options. - Messages already queued start with it too, unless their sender named a model. +- The change stays pending until a message on the default model starts with it, after everything queued before it. - Reading the configuration shows the pending change, and scheduling the current model cancels it. - Switching provider instance and changing `runtimeMode` still need an idle thread. diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 05b8af676d27..cc80fd60be99 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -459,14 +459,17 @@ Sends a message to any ordinary or delegated thread in the environment: applies: the provider cannot stop a turn, Stop has already reached the turn, or the turn or the new message is `/compact` or `/logout`. -A snoozed target stays snoozed unless `respectSnooze: false`. The message's run -is queued and held behind the thread's last run, marked `snoozeDeferred`, and -`SnoozeDeferredDelivery` resumes the queue once the thread wakes (as `isSnoozed` -decides, so an error or a request counts), with a fresh command id per attempt -so a refused resume is retried; a usage limit's resume releases the turn too. A held run that something else releases stops being deferred, so a later -failure hold is never released by that sweep. A thread that has never run, and a -snooze the server set until a usage limit resets, wake as before. Messages from -the app always wake the thread. +A snoozed target keeps its stored snooze unless `respectSnooze: false`. While the +thread is snoozed as `isSnoozed` decides, the message's run is queued and held +behind the thread's last run, marked `snoozeDeferred`. `SnoozeDeferredDelivery` +resumes the queue once the thread wakes, using a fresh command id per attempt +so a refused resume is retried, and a later completed run, such as a usage +limit's resume, releases the turn too. A held run that something else releases +stops being deferred, so a later failure hold is never released by that sweep. +When the thread counts as awake (a pending request, a guest message, an error) +or has never run, the message is delivered and the stored snooze stays. A snooze +the server set until a usage limit resets ends as before, and messages from the +app always end a snooze. The target runtime and interaction modes may not be broader than the caller's. Stable command and message IDs are derived from `clientRequestId` for diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index efc005896735..e1d352f793b1 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -103,7 +103,8 @@ T3 Code. call `t3_thread_configure` with `modelSelection` and `applyAt: "next_turn"`. Messages already queued start with it, and so do later agent messages, except a message that named its own model, such as one sent from the T3 app - with the composer's model. + with the composer's model. The change stays pending until a message on the + default model starts with it. Reading the configuration shows the pending change; scheduling the current model cancels it. Switching to another provider instance still needs an idle thread. @@ -112,6 +113,8 @@ T3 Code. been going. - A snoozed thread stays snoozed. `t3_thread_send` holds the message until the snooze ends or someone wakes the thread, and `t3_thread_post` only records it. + A thread that counts as awake, such as one waiting on a request, gets the + message at once and keeps its snooze. Both return `snoozedUntil` and a warning. Pass `respectSnooze: false` to wake the thread now. Messages sent from the T3 app still wake it. From 4c746ef5a6d00cf9ce49ef216c2068edd38cb437 Mon Sep 17 00:00:00 2001 From: Chris OHearn Date: Fri, 13 Nov 2026 10:01:03 -0700 Subject: [PATCH 2/3] fix(mcp): refuse applyAt together with acknowledgeOnly {acknowledgeOnly, applyAt} set the mode and silently dropped applyAt. It is now refused like modelSelection and runtimeMode. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/toolkits/core.test.ts | 1 + apps/server/src/mcp/toolkits/thread/handlers.ts | 9 +++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 9438795a5d0d..a08a2c5a873a 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1355,6 +1355,7 @@ it.effect("schedules a model change on a busy thread and shows it until it appli for (const [refused, code] of [ [{ runtimeMode: "approval-required", applyAt: "next_turn" }, "invalid_request"], [{ applyAt: "next_turn" }, "invalid_request"], + [{ acknowledgeOnly: true, applyAt: "next_turn" }, "invalid_request"], [ { modelSelection: { instanceId: "claudeAgent", model: "opus" }, applyAt: "next_turn" }, "invalid_request", diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 16870d252361..8833f8e7f073 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -123,13 +123,18 @@ const configureAcknowledgeOnly = Effect.fn("mcp.configureAcknowledgeOnly")(funct readonly acknowledgeOnly?: boolean | undefined; readonly modelSelection?: unknown; readonly runtimeMode?: unknown; + readonly applyAt?: unknown; }, ) { yield* McpToolAccess.requireFullAccess("change who answers a thread"); - if (input.modelSelection !== undefined || input.runtimeMode !== undefined) { + if ( + input.modelSelection !== undefined || + input.runtimeMode !== undefined || + input.applyAt !== undefined + ) { return yield* new OrchestratorMcpFailure({ code: "invalid_request", - message: "Set acknowledgeOnly separately from modelSelection and runtimeMode.", + message: "Set acknowledgeOnly separately from modelSelection, runtimeMode and applyAt.", }); } const acknowledgeOnly = yield* required(input.acknowledgeOnly, "acknowledgeOnly"); From 2437caa4692ba785515b4b831e9e9bfcbe5f37f8 Mon Sep 17 00:00:00 2001 From: Chris OHearn Date: Fri, 13 Nov 2026 10:18:30 -0700 Subject: [PATCH 3/3] fix(server): a server continuation leaves a scheduled model change pending A restart continuation names the run's own model from the server. It was treated as a default turn, so it cleared a scheduled change while running on the old model, and the change was lost. Such a turn now runs on its own model and leaves the schedule as it is. Later default sends skip it as the queue tail while a change is pending. The snooze notice's delivered text now also covers never-ran threads, guest messages and queued delivery. Tests: a server continuation, queued and started at once, keeps the schedule for the next default turn; a never-ran snoozed thread keeps its snooze while a send is delivered. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/snoozeNotice.ts | 2 +- .../src/orchestration-v2/Orchestrator.ts | 32 +++- .../src/orchestration-v2/runtimeLayer.test.ts | 150 ++++++++++++++++++ 3 files changed, 175 insertions(+), 9 deletions(-) diff --git a/apps/server/src/mcp/snoozeNotice.ts b/apps/server/src/mcp/snoozeNotice.ts index 984700ce2972..26852602bcbe 100644 --- a/apps/server/src/mcp/snoozeNotice.ts +++ b/apps/server/src/mcp/snoozeNotice.ts @@ -15,7 +15,7 @@ export function snoozeNotice( held: `${prefix} The message waits, held, until it wakes. Pass respectSnooze: false to wake it now.`, posted: `${prefix} The message was recorded and the thread stays snoozed.`, steered: `${prefix} The message joined its running turn, and the thread stays snoozed.`, - delivered: `${prefix} It counts as awake for now (a pending request or an error), so the message was delivered; the snooze stays.`, + delivered: `${prefix} It counts as awake for now (it never ran, or a request, guest message or error woke it), so the message went ahead as usual: started or queued. The snooze stays.`, woke: `${prefix} This message ended the snooze.`, }[outcome]; return { snoozedUntil: until, warning }; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 1cc8bb98b38d..48965594c533 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -998,6 +998,7 @@ function queuedBeforeScheduledSelection( /** * A scheduled change lasts until a turn on the default model takes it with nothing queued before * the change still waiting, explicit picks included. A model named after the change replaces it. + * A server continuation repeats an earlier run's model and leaves the change alone. */ function threadAtRunStart( projection: Pick, @@ -1005,13 +1006,13 @@ function threadAtRunStart( readonly runId: OrchestrationV2Run["id"] | null; /** Null for a turn starting now, which is newer than any scheduled change. */ readonly ordinal: number | null; - readonly namedModel: boolean; + readonly model: "default" | "named" | "server"; }, ): OrchestrationV2ThreadProjection["thread"] { const scheduled = projection.thread.scheduledModelSelection; - if (scheduled == null) return projection.thread; + if (scheduled == null || starting.model === "server") return projection.thread; const cleared = { ...projection.thread, scheduledModelSelection: null }; - if (starting.namedModel) { + if (starting.model === "named") { return starting.ordinal !== null && starting.ordinal <= scheduled.queuedThroughOrdinal ? projection.thread : cleared; @@ -1050,10 +1051,16 @@ function queuedRunModelSelection( function queueTailModelSelection( projection: Pick, ): ModelSelection { + const scheduled = projection.thread.scheduledModelSelection; + // With a change pending, a queued server continuation's repeated model is no one's new pick. + const serverRepeat = (run: OrchestrationV2Run) => + scheduled != null && + run.explicitModelSelection === true && + projection.messages.find((message) => message.id === run.userMessageId)?.creationSource === + "server"; const tail = queuedRunsInDeliveryOrder(projection).findLast( - (run) => !queuedRunFollowsThread(projection, run), + (run) => !queuedRunFollowsThread(projection, run) && !serverRepeat(run), ); - const scheduled = projection.thread.scheduledModelSelection; // A pick queued before a scheduled change is older than it; later sends take the change. return tail !== undefined && (scheduled == null || tail.ordinal > scheduled.queuedThroughOrdinal) ? tail.modelSelection @@ -2569,7 +2576,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const threadAtStart = threadAtRunStart(projection, { runId: queuedRun.id, ordinal: queuedRun.ordinal, - namedModel: queuedRun.explicitModelSelection === true, + model: + queuedRun.explicitModelSelection !== true + ? "default" + : queuedMessage?.creationSource === "server" + ? "server" + : "named", }); // The picker may already have moved ahead of the native conversation. const switchFromActiveProvider = @@ -8083,11 +8095,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const selectionChanged = !modelSelectionsEqual(projection.thread.modelSelection, modelSelection) || projection.thread.providerInstanceId !== modelSelection.instanceId; - // Server continuations repeat an earlier run's model; they name nothing new. const threadAtStart = threadAtRunStart(projection, { runId: null, ordinal: null, - namedModel: command.modelSelection !== undefined && command.creationSource !== "server", + model: + command.modelSelection === undefined + ? "default" + : command.creationSource === "server" + ? "server" + : "named", }); if (selectionChanged || threadAtStart !== projection.thread) { yield* emit( diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index c022c93b5b91..f04cee95c08e 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -8022,6 +8022,156 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect("keeps a scheduled model change through server continuations on the old model", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const scheduledSelection = { ...modelSelection, model: "gpt-5.5" }; + const scenario = (name: string) => + Effect.gen(function* () { + const threadId = ThreadId.make(`runtime-layer-schedule-server-${name}`); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + createdBy: "user", + creationSource: "web", + title: "Scheduled change and a restart", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + 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) => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:${key}`), + threadId, + messageId: MessageId.make(`${threadId}:${key}`), + text: key, + attachments: [], + ...(kind === "server" ? { modelSelection } : {}), + dispatchMode: { type: queue ? "queue_after_active" : "start_immediately" }, + createdBy: "agent", + creationSource: kind === "server" ? "server" : "mcp", + }); + const run = (key: string) => + orchestrator + .getThreadProjection(threadId) + .pipe( + Effect.map((projection) => + projection.runs.find( + (candidate) => candidate.userMessageId === MessageId.make(`${threadId}:${key}`), + )!, + ), + ); + const complete = (key: string) => + Effect.gen(function* () { + const current = yield* run(key); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${current.id}:completed`), + type: "run.updated", + threadId, + runId: current.id, + occurredAt: yield* DateTime.now, + payload: { ...current, status: "completed", completedAt: yield* DateTime.now }, + }, + ], + }); + yield* orchestrator.resumeQueuedRuns; + }); + const scheduledNow = () => + orchestrator + .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}:schedule`), + threadId, + modelSelection: scheduledSelection, + applyAt: "next_turn", + }); + return { threadId, send, run, complete, scheduledNow }; + }); + + // Queued behind the busy run. + const queued = yield* scenario("queued"); + yield* queued.send("continuation", "server", true); + yield* queued.send("after", "agent", true); + assert.deepEqual((yield* queued.run("after")).modelSelection, scheduledSelection); + yield* queued.complete("active"); + const continuation = yield* queued.run("continuation"); + assert.equal(continuation.status, "starting"); + assert.deepEqual(continuation.modelSelection, modelSelection); + assert.isNotNull(yield* queued.scheduledNow()); + yield* queued.complete("continuation"); + const after = yield* queued.run("after"); + assert.equal(after.status, "starting"); + assert.deepEqual(after.modelSelection, scheduledSelection); + assert.isNull(yield* queued.scheduledNow()); + + // 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"); + yield* immediate.send("next", "agent", false); + assert.deepEqual((yield* immediate.run("next")).modelSelection, scheduledSelection); + assert.isNull(yield* immediate.scheduledNow()); + }), + ); + + it.effect("keeps the snooze of a thread that never ran while delivering to it", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make("runtime-layer-snooze-never-ran"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + createdBy: "user", + creationSource: "web", + title: "Never ran", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "thread.snooze", + commandId: CommandId.make(`${threadId}:snooze`), + threadId, + snoozedUntil: "2099-01-01T00:00:00.000Z", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:first`), + threadId, + messageId: MessageId.make(`${threadId}:first`), + text: "first", + attachments: [], + dispatchMode: { type: "start_immediately" }, + respectSnooze: true, + createdBy: "agent", + creationSource: "mcp", + }); + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(projection.runs[0]?.status, "starting"); + assert.isUndefined(projection.runs[0]?.snoozeDeferred); + assert.isNotNull(projection.thread.snoozedUntil ?? null); + }), + ); + it.effect("delivers to a snoozed thread that counts as awake without ending its snooze", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2;