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, 23:30 UTC
fix(server): restart send stops a Claude turn and runs the message next (#32902)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 10, 2026 at 20:59 UTC
631ea1b6df900d15393cade6899fa6a3428fed8c
4 files changed
+210
-13
apps/server/src/orchestration-v2/Orchestrator.ts
+46
-10
@@ -6123,7 +6123,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6123
(yield* goalDriverFor(command, modelSelection.instanceId)) === undefined
6124
? null
6125
: parsedGoalCommand;
6126
- let goalStopRunId: RunId | undefined;
6126
+ let queuedRunStop:
6127
+ | { readonly runId: RunId; readonly reason: string; readonly skipsHeldQueue?: true }
6128
+ | undefined;
6129
if (goalCommand !== null) {
6130
// A goal command never joins a running turn. One that starts or ends goal
6131
// work stops the run and goes first in the queue; the rest wait. A send
@@ -6149,7 +6151,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6151
(targetMessage === undefined || !isNativeMaintenanceCommand(targetMessage)) &&
6152
!(yield* stopReachedRun(command, command.threadId, target.id))
6153
) {
6152
- goalStopRunId = target.id;
6154
+ queuedRunStop = { runId: target.id, reason: "Stopped to apply /goal" };
6155
}
6156
dispatchMode = { type: "queue_after_active" };
6157
}
@@ -6209,6 +6211,37 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6211
taskIds: delivery.taskIds,
6212
};
6213
}
6214
+ // A provider that can stop a turn but not restart it with new input runs a
6215
+ // restart as the next turn: first in the queue, with the running turn stopped.
6216
+ if (dispatchMode.type === "restart_active" && !isNativeMaintenanceCommand(command)) {
6217
+ const targetRunId = dispatchMode.targetRunId;
6218
+ const target = projection.runs.find((run) => run.id === targetRunId);
6219
+ const providerSessionId = projection.providerThreads.find(
6220
+ (candidate) => candidate.id === target?.providerThreadId,
6221
+ )?.providerSessionId;
6222
+ const turns = projection.providerSessions.find((session) => session.id === providerSessionId)
6223
+ ?.capabilities.turns;
6224
+ const targetMessage = projection.messages.find(
6225
+ (message) => message.id === target?.userMessageId,
6226
+ );
6227
+ if (
6228
+ target?.status === "running" &&
6229
+ turns !== undefined &&
6230
+ turns.supportsInterrupt &&
6231
+ turns.supportsQueuedMessages &&
6232
+ !turns.supportsSteeringByInterruptRestart &&
6233
+ (targetMessage === undefined || !isNativeMaintenanceCommand(targetMessage)) &&
6234
+ !(yield* stopReachedRun(command, command.threadId, target.id))
6235
+ ) {
6236
+ // The restart replaces the stopped turn, so an older held queue does not hold it.
6237
+ queuedRunStop = {
6238
+ runId: target.id,
6239
+ reason: "Stopped to send a new message",
6240
+ skipsHeldQueue: true,
6241
+ };
6242
+ dispatchMode = { type: "queue_after_active" };
6243
+ }
6244
+ }
6245
// Steer mailbox deliveries, delegated task questions, and command notices
6246
// into an active goal under the thread lock: queued behind a long turn or a
6247
// goal run, they are never seen. Never interrupt/restart a turn for one.
@@ -6361,14 +6394,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6394
dispatchMode.type === "start_immediately" ||
6395
dispatchMode.type === "queue_after_active";
6396
const shouldQueue = queueBehindRun !== undefined && startsOrQueuesRun;
6364
- // An explicit pick queued ahead reaches the thread only when its run starts. A goal
6365
- // command that stops the active run goes first, so nothing queued applies before it.
6397
+ // An explicit pick queued ahead reaches the thread only when its run starts. A goal or
6398
+ // restart command that stops the active run goes first, so nothing queued applies before it.
6399
// Buffered provider wakes drain output their own provider already produced.
6400
const incomingMessage = { ...command, delegatedCompletion };
6401
if (
6402
shouldQueue &&
6403
command.modelSelection === undefined &&
6371
- goalStopRunId === undefined &&
6404
+ queuedRunStop === undefined &&
6405
!followsCurrentConversation(incomingMessage) &&
6406
!isBufferedProviderNotification(incomingMessage)
6407
) {
@@ -6522,11 +6555,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6555
activeAttemptId: attemptId,
6556
status: "queued",
6557
...(worktreeMissingRun !== undefined ||
6525
- (heldRunsToRelease.length === 0 && queueIsHeld && !wakeSkipsHold)
6558
+ (heldRunsToRelease.length === 0 &&
6559
+ queueIsHeld &&
6560
+ !wakeSkipsHold &&
6561
+ queuedRunStop?.skipsHeldQueue !== true)
6562
? { queueHeld: true }
6563
: {}),
6564
queuePosition:
6529
- goalStopRunId !== undefined
6565
+ queuedRunStop !== undefined
6566
? 1
6567
: Math.max(
6568
0,
@@ -6684,15 +6720,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6720
},
6721
});
6722
}
6687
- if (goalStopRunId !== undefined) {
6723
+ if (queuedRunStop !== undefined) {
6724
return yield* stopRunForQueuedCommand({
6725
command,
6726
events,
6727
effects,
6728
projection: yield* getProjectionWithPendingEvents(command.threadId, events),
6729
queuedRunId: runId,
6694
- targetRunId: goalStopRunId,
6695
- reason: "Stopped to apply /goal",
6730
+ targetRunId: queuedRunStop.runId,
6731
+ reason: queuedRunStop.reason,
6732
now,
6733
});
6734
}
apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+145
@@ -29,6 +29,10 @@ import * as EventSink from "./EventSink.ts";
29
import * as Orchestrator from "./Orchestrator.ts";
30
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
31
import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
32
+import * as ThreadManagementService from "./ThreadManagementService.ts";
33
+import * as ServerSettings from "../serverSettings.ts";
34
+import * as SqlitePersistence from "../persistence/Sqlite.ts";
35
+import * as CommandReceiptStore from "./CommandReceiptStore.ts";
36
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
37
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
38
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
@@ -2181,6 +2185,147 @@ it.effect("starts a goal that names no model on the thread's model ahead of a qu
2185
),
2186
);
2187
2188
+it.effect("restarts by stopping the running turn when the provider cannot interrupt-restart", () =>
2189
+ Effect.scoped(
2190
+ Effect.gen(function* () {
2191
+ const { started, steered, layer, startFirstTurn, send, read } = yield* goalHarness(
2192
+ "restart-without-interrupt-restart",
2193
+ );
2194
+ yield* Effect.gen(function* () {
2195
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2196
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2197
+ const threadId = yield* startFirstTurn;
2198
+ yield* send("queued", "queued", "queue");
2199
+ yield* orchestrator.dispatch({
2200
+ type: "message.dispatch",
2201
+ commandId: CommandId.make("restart"),
2202
+ threadId,
2203
+ messageId: MessageId.make("message:restart"),
2204
+ text: "do this instead",
2205
+ attachments: [],
2206
+ modelSelection: runSelection,
2207
+ dispatchMode: { type: "restart_active", targetRunId: started[0]!.runId },
2208
+ createdBy: "agent",
2209
+ creationSource: "server",
2210
+ });
2211
+ yield* worker.drain();
2212
+
2213
+ assert.deepEqual(steered, []);
2214
+ assert.deepEqual(yield* read(threadId), {
2215
+ queue: ["queued"],
2216
+ started: ["first", "do this instead"],
2217
+ stopRequested: true,
2218
+ });
2219
+ }).pipe(Effect.provide(layer));
2220
+ }),
2221
+ ),
2222
+);
2223
+
2224
+it.effect("starts a restart that stops the running turn ahead of an older held queue", () =>
2225
+ Effect.scoped(
2226
+ Effect.gen(function* () {
2227
+ const { started, layer, startFirstTurn, send, read } =
2228
+ yield* goalHarness("restart-past-held-queue");
2229
+ yield* Effect.gen(function* () {
2230
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2231
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2232
+ const threadId = yield* startFirstTurn;
2233
+ yield* send("queued", "queued", "queue");
2234
+ yield* orchestrator.dispatch({
2235
+ type: "thread.stop",
2236
+ commandId: CommandId.make("stop"),
2237
+ threadId,
2238
+ });
2239
+ yield* worker.drain();
2240
+ const secondRunning = yield* orchestrator.streamDomainEvents.pipe(
2241
+ Stream.filter(
2242
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
2243
+ ),
2244
+ Stream.take(1),
2245
+ Stream.runDrain,
2246
+ Effect.forkScoped,
2247
+ );
2248
+ yield* orchestrator.dispatch({
2249
+ type: "message.dispatch",
2250
+ commandId: CommandId.make("second"),
2251
+ threadId,
2252
+ messageId: MessageId.make("message:second"),
2253
+ text: "second",
2254
+ attachments: [],
2255
+ dispatchMode: { type: "start_immediately" },
2256
+ createdBy: "agent",
2257
+ creationSource: "mcp",
2258
+ });
2259
+ yield* worker.drain();
2260
+ yield* Fiber.join(secondRunning);
2261
+ yield* orchestrator.dispatch({
2262
+ type: "message.dispatch",
2263
+ commandId: CommandId.make("restart"),
2264
+ threadId,
2265
+ messageId: MessageId.make("message:restart"),
2266
+ text: "do this instead",
2267
+ attachments: [],
2268
+ dispatchMode: { type: "restart_active", targetRunId: started[1]!.runId },
2269
+ createdBy: "agent",
2270
+ creationSource: "mcp",
2271
+ });
2272
+ yield* worker.drain();
2273
+
2274
+ const { queue, started: startedTexts } = yield* read(threadId);
2275
+ assert.deepEqual(
2276
+ { queue, started: startedTexts },
2277
+ { queue: ["queued"], started: ["first", "second", "do this instead"] },
2278
+ );
2279
+ }).pipe(Effect.provide(layer));
2280
+ }),
2281
+ ),
2282
+);
2283
+
2284
+it.effect("reports a restart that stops the running turn as restarted", () =>
2285
+ Effect.scoped(
2286
+ Effect.gen(function* () {
2287
+ const { started, layer, startFirstTurn } = yield* goalHarness("restart-send-delivery");
2288
+ yield* Effect.gen(function* () {
2289
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2290
+ const threadManagement = yield* ThreadManagementService.ThreadManagementService;
2291
+ const threadId = yield* startFirstTurn;
2292
+ const input = {
2293
+ projectId: ProjectId.make("project:restart-send-delivery"),
2294
+ commandId: CommandId.make("restart"),
2295
+ threadId,
2296
+ messageId: MessageId.make("message:restart"),
2297
+ text: "do this instead",
2298
+ attachments: [],
2299
+ mode: "restart",
2300
+ createdBy: "agent",
2301
+ creationSource: "mcp",
2302
+ } as const;
2303
+ const sent = yield* threadManagement.sendToThread(input);
2304
+ // Stop holds the replacement before it starts; a replay must still report the restart.
2305
+ yield* orchestrator.dispatch({
2306
+ type: "thread.stop",
2307
+ commandId: CommandId.make("stop-after-restart"),
2308
+ threadId,
2309
+ });
2310
+ const replayed = yield* threadManagement.sendToThread(input);
2311
+
2312
+ assert.equal(started.length, 1);
2313
+ assert.deepEqual([sent.delivery, replayed.delivery], ["restarted", "restarted"]);
2314
+ }).pipe(
2315
+ Effect.provide(
2316
+ ThreadManagementService.layer.pipe(
2317
+ Layer.provideMerge(layer),
2318
+ Layer.provide(ServerSettings.layerTest()),
2319
+ Layer.provide(
2320
+ CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
2321
+ ),
2322
+ ),
2323
+ ),
2324
+ );
2325
+ }),
2326
+ ),
2327
+);
2328
+
2329
it.effect("queues a goal clear without stopping work when no goal drives it", () =>
2330
Effect.scoped(
2331
Effect.gen(function* () {
apps/server/src/orchestration-v2/ThreadManagementService.ts
+13
-2
@@ -894,8 +894,19 @@ const make = Effect.gen(function* () {
894
messageId: input.messageId,
895
});
896
}
897
- const delivery: ThreadManagementSendResult["delivery"] =
898
- turnItem === null || turnItem.inputIntent === "queued_turn"
897
+ // A provider without interrupt-and-restart stops the turn and runs the
898
+ // restart as the next turn. Read from this command's own events, so a replay agrees.
899
+ const restartedAsNextTurn =
900
+ mode === "restart" &&
901
+ dispatched.storedEvents.some(
902
+ ({ event }) =>
903
+ event.type === "turn-item.updated" &&
904
+ event.payload.type === "run_interrupt_request" &&
905
+ event.payload.runId !== run.id,
906
+ );
907
+ const delivery: ThreadManagementSendResult["delivery"] = restartedAsNextTurn
908
+ ? "restarted"
909
+ : turnItem === null || turnItem.inputIntent === "queued_turn"
910
? "queued"
911
: turnItem.inputIntent === "turn_start"
912
? "started"
docs/orchestration-v2/orchestrator-mcp-server.md
+6
-1
@@ -445,7 +445,12 @@ Sends a message to any ordinary or delegated thread in the environment:
445
- `queue` creates a separate follow-up run after active work;
446
- `steer` requires a steerable active provider turn; and
447
- `restart` requires an active provider turn and uses the orchestrator's
448
- interrupt-and-restart path.
448
+ interrupt-and-restart path. On a provider that can stop a turn and queue
449
+ messages but not restart a turn with new input, it stops the turn and queues
450
+ the message ahead of other queued messages; an unheld delegated-task result
451
+ that survives the stop still runs first. It is rejected when neither path
452
+ applies: the provider cannot stop a turn, Stop has already reached the turn,
453
+ or the turn or the new message is `/compact` or `/logout`.
454
455
The target runtime and interaction modes may not be broader than the caller's.
456
Stable command and message IDs are derived from `clientRequestId` for