@devries-cameron20 / t3code-1 / commits / bd7d264401
Fork 0

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

fix(server): a fresh-session scheduled run no longer takes over the thread's conversation (#36103)

Julius Marminge committed Nov 13, 2026 at 01:49 UTC bd7d264401e581687d0055891a8fb536f8ca9543
2 files changed +217 -18
apps/server/src/orchestration-v2/Orchestrator.ts
+85 -18
@@ -1267,22 +1267,35 @@ function appendContextHandoffId(
1267 return handoffId === null ? handoffIds : Array.from(new Set([...handoffIds, handoffId]));
1268 }
1269
1270 +/** A fresh-session schedule run starts a side conversation; the thread's own one continues past it. */
1271 +function isScheduledFreshRun(
1272 + run: Pick<OrchestrationV2Run, "freshContext" | "userMessageId">,
1273 + turnItems: OrchestrationV2ThreadProjection["turnItems"],
1274 +): boolean {
1275 + // Turn items, unlike messages, are not narrowed to the runs since the latest compaction.
1276 + return (
1277 + run.freshContext === true &&
1278 + turnItems.some(
1279 + (item) =>
1280 + item.type === "user_message" &&
1281 + item.messageId === run.userMessageId &&
1282 + item.scheduledTaskId !== undefined,
1283 + )
1284 + );
1285 +}
1286 +
1287 /** Ordinal of the latest started fresh-context run. Runs before it never reach a provider again. */
1288 function contextBoundaryOrdinal(
1272 - runs: ReadonlyArray<
1273 - Pick<
1274 - OrchestrationV2Run,
1275 - "ordinal" | "freshContext" | "status" | "startedAt" | "restartContinuationOfRunId"
1276 - >
1277 - >,
1289 + projection: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems">,
1290 ): number {
1291 let boundary = 0;
1280 - for (const run of runs) {
1292 + for (const run of projection.runs) {
1293 if (
1294 run.freshContext === true &&
1295 run.status !== "queued" &&
1296 !cancelledBeforeStart(run) &&
1285 - run.ordinal > boundary
1297 + run.ordinal > boundary &&
1298 + !isScheduledFreshRun(run, projection.turnItems)
1299 ) {
1300 boundary = run.ordinal;
1301 }
@@ -1290,6 +1303,57 @@ function contextBoundaryOrdinal(
1303 return boundary;
1304 }
1305
1306 +/** The provider thread a message continues: the active one, unless a fresh-session schedule run started it. */
1307 +function conversationProviderThread(
1308 + projection: Pick<
1309 + OrchestrationV2ThreadProjection,
1310 + "thread" | "providerThreads" | "runs" | "turnItems"
1311 + >,
1312 +): OrchestrationV2ProviderThread | undefined {
1313 + const startedByScheduledFreshRun = (providerThread: OrchestrationV2ProviderThread) =>
1314 + projection.runs.some(
1315 + (run) =>
1316 + run.ordinal === providerThread.firstRunOrdinal &&
1317 + isScheduledFreshRun(run, projection.turnItems),
1318 + );
1319 + const active = projection.providerThreads.find(
1320 + (candidate) => candidate.id === projection.thread.activeProviderThreadId,
1321 + );
1322 + if (active === undefined || !startedByScheduledFreshRun(active)) return active;
1323 + const boundary = contextBoundaryOrdinal(projection);
1324 + return (
1325 + projection.providerThreads
1326 + .filter(
1327 + (candidate) =>
1328 + candidate.appThreadId === projection.thread.id &&
1329 + candidate.ownerNodeId === null &&
1330 + candidate.lastRunOrdinal !== null &&
1331 + !providerThreadPredatesBoundary(candidate, boundary) &&
1332 + !startedByScheduledFreshRun(candidate),
1333 + )
1334 + .toSorted((left, right) => (right.lastRunOrdinal ?? 0) - (left.lastRunOrdinal ?? 0))[0] ??
1335 + active
1336 + );
1337 +}
1338 +
1339 +/** Wakes and fresh starts act on the active session; a message continues the conversation. */
1340 +function dispatchProviderThread(
1341 + projection: Pick<
1342 + OrchestrationV2ThreadProjection,
1343 + "thread" | "providerThreads" | "runs" | "turnItems"
1344 + >,
1345 + message: Pick<OrchestrationV2ConversationMessage, "notification" | "delegatedCompletion">,
1346 + freshContext: boolean,
1347 +): OrchestrationV2ProviderThread | undefined {
1348 + return freshContext ||
1349 + message.notification !== undefined ||
1350 + message.delegatedCompletion !== undefined
1351 + ? projection.providerThreads.find(
1352 + (candidate) => candidate.id === projection.thread.activeProviderThreadId,
1353 + )
1354 + : conversationProviderThread(projection);
1355 +}
1356 +
1357 /** Threads with no started run (imported, or reserved by another queued run) never cross it. */
1358 function providerThreadPredatesBoundary(
1359 providerThread: Pick<OrchestrationV2ProviderThread, "firstRunOrdinal">,
@@ -1325,10 +1389,13 @@ function uniqueSessions(
1389 }
1390
1391 function rootProviderThreadsForProvider(
1328 - projection: Pick<OrchestrationV2ThreadProjection, "providerThreads" | "thread" | "runs">,
1392 + projection: Pick<
1393 + OrchestrationV2ThreadProjection,
1394 + "providerThreads" | "thread" | "runs" | "turnItems"
1395 + >,
1396 providerInstanceId: ModelSelection["instanceId"],
1397 ): ReadonlyArray<OrchestrationV2ProviderThread> {
1331 - const boundary = contextBoundaryOrdinal(projection.runs);
1398 + const boundary = contextBoundaryOrdinal(projection);
1399 return projection.providerThreads
1400 .filter(
1401 (providerThread) =>
@@ -2390,12 +2457,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2457 }),
2458 ),
2459 );
2393 - const activeProviderThread = projection.providerThreads.find(
2394 - (candidate) => candidate.id === projection.thread.activeProviderThreadId,
2395 - );
2460 const followsCurrent = followsCurrentConversation(queuedMessage);
2461 const freshContext = queuedRun.freshContext === true;
2398 - const contextBoundary = freshContext ? ordinal : contextBoundaryOrdinal(projection.runs);
2462 + const activeProviderThread = dispatchProviderThread(projection, queuedMessage, freshContext);
2463 + const contextBoundary = freshContext ? ordinal : contextBoundaryOrdinal(projection);
2464 // A run queued before a fresh run started is bound to the conversation that run left behind.
2465 const followsLatestContext =
2466 !freshContext &&
@@ -6116,7 +6181,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6181 type: "provider_handoff",
6182 }),
6183 );
6119 - const contextBoundary = contextBoundaryOrdinal(input.projection.runs);
6184 + const contextBoundary = contextBoundaryOrdinal(input.projection);
6185 restartHandoff = yield* contextHandoffService
6186 .prepareProviderHandoff({
6187 threadId: input.command.threadId,
@@ -7080,8 +7145,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7145 return;
7146 }
7147
7083 - const activeProviderThread = projection.providerThreads.find(
7084 - (candidate) => candidate.id === projection.thread.activeProviderThreadId,
7148 + const activeProviderThread = dispatchProviderThread(
7149 + projection,
7150 + { ...command, delegatedCompletion },
7151 + freshContext,
7152 );
7153 const activeRun = projection.runs.find(isActiveRun);
7154 // Messages after failed or stopped worktree setup must wait for a worktree,
@@ -7544,7 +7611,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7611 }
7612 const ordinal = nextRunOrdinal(projection);
7613 const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
7547 - const contextBoundary = freshContext ? ordinal : contextBoundaryOrdinal(projection.runs);
7614 + const contextBoundary = freshContext ? ordinal : contextBoundaryOrdinal(projection);
7615 const latestCompletedRun = projection.runs.findLast((run) => run.status === "completed");
7616 const latestHandoffRun = projection.runs.findLast(isHandoffSourceRun);
7617 const legacyImportItems =
apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+132
@@ -3417,6 +3417,138 @@ describe("orchestration v2 provider switching", () => {
3417 }),
3418 );
3419
3420 + it.live("keeps the user's conversation after a scheduled fresh run in the same thread", () =>
3421 + Effect.gen(function* () {
3422 + const cwd = yield* checkpointWorkspace("scheduled-fresh-user-chat");
3423 + const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
3424 + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
3425 + makeTestAdapter({
3426 + instanceId: CLAUDE_MODEL_SELECTION.instanceId,
3427 + driver: CLAUDE_DRIVER,
3428 + capabilities: ClaudeProviderCapabilitiesV2,
3429 + modelSelection: CLAUDE_MODEL_SELECTION,
3430 + responseByRunOrdinal: {},
3431 + capturedTurns,
3432 + nativeThreadGeneration: yield* Ref.make(0),
3433 + }),
3434 + ]);
3435 + const threadId = ThreadId.make("thread:scheduled-fresh-user-chat");
3436 + yield* Effect.gen(function* () {
3437 + const orchestrator = yield* Orchestrator.OrchestratorV2;
3438 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
3439 + const send = (name: string, scheduled: boolean) =>
3440 + orchestrator.dispatch({
3441 + type: "message.dispatch",
3442 + createdBy: "user",
3443 + creationSource: "web",
3444 + commandId: CommandId.make(`command:scheduled-fresh-user-chat:${name}`),
3445 + threadId,
3446 + messageId: MessageId.make(`message:scheduled-fresh-user-chat:${name}`),
3447 + text: name,
3448 + attachments: [],
3449 + modelSelection: CLAUDE_MODEL_SELECTION,
3450 + dispatchMode: { type: "queue_after_active" },
3451 + ...(scheduled
3452 + ? {
3453 + scheduledTaskId: ScheduledTaskId.make("scheduled-fresh-user-chat"),
3454 + freshContext: true,
3455 + }
3456 + : {}),
3457 + });
3458 + yield* orchestrator.dispatch({
3459 + type: "thread.create",
3460 + createdBy: "user",
3461 + creationSource: "web",
3462 + commandId: CommandId.make("command:scheduled-fresh-user-chat:create"),
3463 + threadId,
3464 + projectId: ProjectId.make("project:scheduled-fresh-user-chat"),
3465 + title: "User chat with a fresh-session schedule",
3466 + modelSelection: CLAUDE_MODEL_SELECTION,
3467 + runtimeMode: "full-access",
3468 + interactionMode: "default",
3469 + branch: null,
3470 + worktreePath: cwd,
3471 + });
3472 + const eventSink = yield* EventSink.EventSinkV2;
3473 + for (const [name, scheduled] of [
3474 + ["user-first", false],
3475 + ["scheduled", true],
3476 + ["user-second", false],
3477 + ["compaction", false],
3478 + ["scheduled-after-compaction", true],
3479 + ["user-third", false],
3480 + ] as const) {
3481 + if (name === "compaction") {
3482 + // The user's run compacts, so later dispatches no longer read the first scheduled run's message.
3483 + const run = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
3484 + const compactedAt = yield* DateTime.now;
3485 + yield* eventSink.write({
3486 + events: [
3487 + {
3488 + id: EventId.make("event:scheduled-fresh-user-chat:compaction"),
3489 + type: "turn-item.updated",
3490 + threadId,
3491 + runId: run.id,
3492 + nodeId: run.rootNodeId!,
3493 + occurredAt: compactedAt,
3494 + payload: {
3495 + id: TurnItemId.make("item:scheduled-fresh-user-chat:compaction"),
3496 + threadId,
3497 + runId: run.id,
3498 + nodeId: run.rootNodeId,
3499 + providerThreadId: null,
3500 + providerTurnId: null,
3501 + nativeItemRef: null,
3502 + parentItemId: null,
3503 + ordinal: 1_000,
3504 + status: "completed",
3505 + title: null,
3506 + startedAt: compactedAt,
3507 + completedAt: compactedAt,
3508 + updatedAt: compactedAt,
3509 + type: "compaction",
3510 + driver: CLAUDE_DRIVER,
3511 + },
3512 + },
3513 + ],
3514 + });
3515 + continue;
3516 + }
3517 + yield* send(name, scheduled);
3518 + yield* worker.drain();
3519 + yield* waitForIdle(threadId);
3520 + }
3521 + const turns = yield* Ref.get(capturedTurns);
3522 + const turnFor = (name: string) => turns.find((turn) => turn.text.endsWith(name));
3523 + assert.notEqual(
3524 + turnFor("scheduled")!.nativeThreadId,
3525 + turnFor("user-first")!.nativeThreadId,
3526 + );
3527 + // The scheduled run's fresh session must not replace the user's conversation.
3528 + assert.equal(turnFor("user-second")!.nativeThreadId, turnFor("user-first")!.nativeThreadId);
3529 + assert.equal(turnFor("user-third")!.nativeThreadId, turnFor("user-first")!.nativeThreadId);
3530 + }).pipe(
3531 + Effect.provide(
3532 + ProviderReplayHarness.layerWithRegistry(
3533 + {
3534 + name: "scheduled-fresh-user-chat",
3535 + runtimePolicyOverride: {
3536 + cwd,
3537 + approvalPolicy: "never",
3538 + sandboxPolicy: {
3539 + type: "readOnly",
3540 + access: { type: "fullAccess" },
3541 + networkAccess: false,
3542 + },
3543 + },
3544 + },
3545 + layerRegistry,
3546 + ),
3547 + ),
3548 + );
3549 + }),
3550 + );
3551 +
3552 it.live("keeps the thread a queued fresh run reserved for that run", () =>
3553 Effect.gen(function* () {
3554 const cwd = yield* checkpointWorkspace("fresh-context-reserved");