The best way to control Claude Code, Codex and more from any computer or phone
fix(server): /clear after a side chat's failed first run drops the main thread's digest (#39132)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Viktor Leukocyte committed
Nov 19, 2026 at 14:33 UTC
975b9577ab0739fa4c5bcc0ecf090db331410f47
4 files changed
+238
-17
apps/server/src/orchestration-v2/Orchestrator.ts
+45
-14
@@ -1343,6 +1343,28 @@ function pendingForkTransferForThread(
1343
);
1344
}
1345
1346
+/** A fork transfer still pending when a fresh run starts would bring the parent's context back. */
1347
+function forkTransferSupersededEvent(
1348
+ transfer: OrchestrationV2ContextTransfer,
1349
+ runId: RunId,
1350
+ providerInstanceId: ProviderInstanceId,
1351
+ now: DateTime.Utc,
1352
+): Omit<OrchestrationV2DomainEvent, "id"> {
1353
+ return {
1354
+ type: "context-transfer.updated",
1355
+ threadId: transfer.targetThreadId,
1356
+ runId,
1357
+ providerInstanceId,
1358
+ occurredAt: now,
1359
+ payload: {
1360
+ ...transfer,
1361
+ status: "superseded",
1362
+ error: "Superseded by a fresh session.",
1363
+ updatedAt: now,
1364
+ },
1365
+ };
1366
+}
1367
+
1368
function pendingMergeBackTransfersForThread(
1369
projection: Pick<OrchestrationV2ThreadProjection, "contextTransfers" | "thread">,
1370
): ReadonlyArray<OrchestrationV2ContextTransfer> {
@@ -2617,6 +2639,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2639
);
2640
const followsCurrent = followsCurrentConversation(queuedMessage);
2641
const freshContext = queuedRun.freshContext === true;
2642
+ // A scheduled fresh run is a side conversation, so it must not drop the fork's context.
2643
+ const supersededForkTransfer =
2644
+ freshContext && queuedMessage.scheduledTaskId === undefined
2645
+ ? pendingForkTransferForThread(projection)
2646
+ : undefined;
2647
const activeProviderThread = dispatchProviderThread(projection, queuedMessage, freshContext);
2648
const contextBoundary = freshContext ? ordinal : contextBoundaryOrdinal(projection);
2649
// A run queued before a fresh run started is bound to the conversation that run left behind.
@@ -3192,6 +3219,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3219
payload: legacyImportRecoveryHandoff,
3220
},
3221
]),
3222
+ ...(supersededForkTransfer === undefined
3223
+ ? []
3224
+ : [
3225
+ forkTransferSupersededEvent(
3226
+ supersededForkTransfer,
3227
+ queuedRun.id,
3228
+ queuedRun.providerInstanceId,
3229
+ now,
3230
+ ),
3231
+ ]),
3232
...(handoffTurnItem === null
3233
? []
3234
: [
@@ -8522,20 +8559,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8559
? pendingForkTransferForThread(projection)
8560
: undefined;
8561
if (supersededForkTransfer !== undefined) {
8525
- // Superseded, or the next ordinary send would bring the parent's context back.
8526
- yield* emitEvent({
8527
- type: "context-transfer.updated",
8528
- threadId: command.threadId,
8529
- runId,
8530
- providerInstanceId: modelSelection.instanceId,
8531
- occurredAt: now,
8532
- payload: {
8533
- ...supersededForkTransfer,
8534
- status: "superseded",
8535
- error: "Superseded by a fresh session.",
8536
- updatedAt: now,
8537
- },
8538
- });
8562
+ yield* emitEvent(
8563
+ forkTransferSupersededEvent(
8564
+ supersededForkTransfer,
8565
+ runId,
8566
+ modelSelection.instanceId,
8567
+ now,
8568
+ ),
8569
+ );
8570
}
8571
yield* emitEvent({
8572
type: "run-attempt.created",
apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
+68
@@ -22,6 +22,7 @@ import {
22
ProviderSetupError,
23
RunAttemptId,
24
RunId,
25
+ ScheduledTaskId,
26
ThreadId,
27
TurnItemId,
28
ProjectId,
@@ -2363,6 +2364,73 @@ effectIt.effect.each([
2364
}),
2365
);
2366
2367
+effectIt.effect.each([
2368
+ { scheduled: false, status: "superseded" },
2369
+ { scheduled: true, status: "ready" },
2370
+] as const)(
2371
+ "a fresh run starts without failed runs' side chat notes; an unscheduled one retires them: %j",
2372
+ ({ scheduled, status }) =>
2373
+ Effect.gen(function* () {
2374
+ const harness = makeLocalCommandHarness({
2375
+ text: "Start over",
2376
+ sideChat: { contextRun: "failed" },
2377
+ });
2378
+ const projection = harness.projection();
2379
+ const current = projection.runs.at(-1)!;
2380
+ const [note] = projection.contextHandoffs;
2381
+ harness.setProjection({
2382
+ ...projection,
2383
+ runs: projection.runs.map((run) =>
2384
+ run.id === current.id ? { ...run, freshContext: true } : run,
2385
+ ),
2386
+ // Each send that fails before the side chat's fork resolves leaves its own note.
2387
+ contextHandoffs: [
2388
+ ...projection.contextHandoffs,
2389
+ { ...note!, id: ContextHandoffId.make("side-chat-context-retry") },
2390
+ ],
2391
+ turnItems: scheduled
2392
+ ? [
2393
+ ...projection.turnItems,
2394
+ {
2395
+ type: "user_message",
2396
+ id: TurnItemId.make("scheduled-fresh-message"),
2397
+ threadId: projection.thread.id,
2398
+ runId: current.id,
2399
+ nodeId: null,
2400
+ providerThreadId: current.providerThreadId,
2401
+ providerTurnId: null,
2402
+ nativeItemRef: null,
2403
+ parentItemId: null,
2404
+ ordinal: 0,
2405
+ status: "completed",
2406
+ title: null,
2407
+ startedAt: projection.updatedAt,
2408
+ completedAt: projection.updatedAt,
2409
+ updatedAt: projection.updatedAt,
2410
+ createdBy: "user",
2411
+ creationSource: "server",
2412
+ messageId: current.userMessageId,
2413
+ text: "Start over",
2414
+ inputIntent: "turn_start",
2415
+ attachments: [],
2416
+ scheduledTaskId: ScheduledTaskId.make("fresh-session-task"),
2417
+ },
2418
+ ]
2419
+ : projection.turnItems,
2420
+ });
2421
+
2422
+ yield* harness.start;
2423
+
2424
+ expect(harness.startTurn.mock.calls[0]?.[0].message.text).toBe("Start over");
2425
+ expect(
2426
+ harness.projection().contextHandoffs.map((handoff) => [handoff.status, handoff.delivery]),
2427
+ ).toEqual([
2428
+ [status, undefined],
2429
+ [status, undefined],
2430
+ ]);
2431
+ }),
2432
+);
2433
+
2434
effectIt.effect.each([
2435
{
2436
nativeForkFrom: "idle",
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+31
-3
@@ -46,7 +46,7 @@ import * as EventSink from "./EventSink.ts";
46
import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts";
47
import * as ContextHandoffService from "./ContextHandoffService.ts";
48
import { canForkBusySourceNatively, isActiveRun } from "./CommandPolicy.ts";
49
-import { contextBoundaryOrdinal } from "./contextBoundary.ts";
49
+import { contextBoundaryOrdinal, isScheduledFreshRun } from "./contextBoundary.ts";
50
import {
51
DEFAULT_HANDOFF_TOKEN_CAP,
52
handoffTokenCapConfig,
@@ -570,13 +570,16 @@ export const layer: Layer.Layer<
570
(handoff.transferId == null || !subagentResultTransfers.has(handoff.transferId)) &&
571
isPendingForRun(handoff),
572
);
573
- // Carried forward until a provider turn accepts it, also after a provider switch.
574
- const sideChatHandoff = projection.contextHandoffs.find(
573
+ // Carried forward until a provider turn accepts them, also after a provider switch. A fresh
574
+ // session starts without them, and an unscheduled fresh run retires them. A schedule's fresh
575
+ // run is a side conversation, so the thread's next turn still gets them.
576
+ const carriedSideChatHandoffs = projection.contextHandoffs.filter(
577
(handoff) =>
578
isSideChatHandoff(handoff) &&
579
handoff.delivery === undefined &&
580
isPendingForRun(handoff, true),
581
);
582
+ const sideChatHandoff = run.freshContext === true ? undefined : carriedSideChatHandoffs[0];
583
const nativeForkTransfer = projection.contextTransfers.find(
584
(transfer) =>
585
transfer.type === "fork" &&
@@ -598,6 +601,31 @@ export const layer: Layer.Layer<
601
cause: `Run ${runId} is missing its execution projection state.`,
602
});
603
}
604
+ if (
605
+ carriedSideChatHandoffs.length > 0 &&
606
+ run.freshContext === true &&
607
+ !isScheduledFreshRun(run, projection.turnItems)
608
+ ) {
609
+ const updatedAt = yield* DateTime.now;
610
+ const retired = yield* eventSink.writeIfRunCurrent({
611
+ threadId: run.threadId,
612
+ runId,
613
+ activeAttemptId: attempt.id,
614
+ expectedStatus: "starting",
615
+ events: yield* Effect.forEach(carriedSideChatHandoffs, (handoff) =>
616
+ Effect.map(idAllocator.allocate.event({ threadId: projection.thread.id }), (id) => ({
617
+ id,
618
+ type: "context-handoff.updated" as const,
619
+ threadId: projection.thread.id,
620
+ runId: run.id,
621
+ providerInstanceId: run.providerInstanceId,
622
+ occurredAt: updatedAt,
623
+ payload: { ...handoff, status: "superseded" as const, updatedAt },
624
+ })),
625
+ ),
626
+ });
627
+ if (!retired.committed) return;
628
+ }
629
const manualResume =
630
run.manualContinuationOfRunId !== undefined && attempt.reason !== "steering_restart";
631
const resumeSource = manualResume
apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
+94
@@ -997,6 +997,100 @@ it.effect("a fresh send in a fork that has not run yet starts without the fork's
997
}).pipe(Effect.provide(forkCases[0]!.layer)),
998
);
999
1000
+it.effect.each([
1001
+ {
1002
+ name: "a fresh send queued behind a side chat's failed first run gives later sends no note",
1003
+ scheduled: false,
1004
+ },
1005
+ {
1006
+ name: "a scheduled fresh run queued behind a side chat's failed first run keeps the fork",
1007
+ scheduled: true,
1008
+ },
1009
+] as const)("$name", ({ scheduled }) =>
1010
+ Effect.gen(function* () {
1011
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1012
+ const eventSink = yield* EventSink.EventSinkV2;
1013
+ const key = scheduled ? "queued-scheduled-side-chat" : "queued-fresh-side-chat";
1014
+ const parentId = ThreadId.make(`${key}-parent`);
1015
+ const sideChatId = ThreadId.make(`${key}-child`);
1016
+ yield* createParent(parentId);
1017
+ yield* writeParentRun({
1018
+ threadId: parentId,
1019
+ runId: RunId.make(`${key}-parent-run`),
1020
+ ordinal: 1,
1021
+ status: "completed",
1022
+ text: "Work",
1023
+ stable: true,
1024
+ });
1025
+ yield* forkSideChat(`${key}-fork`, parentId, sideChatId);
1026
+ const send = (name: string, freshContext = false) =>
1027
+ orchestrator.dispatch({
1028
+ type: "message.dispatch",
1029
+ commandId: CommandId.make(`${key}-${name}`),
1030
+ threadId: sideChatId,
1031
+ messageId: MessageId.make(`${key}-${name}`),
1032
+ text: name,
1033
+ attachments: [],
1034
+ dispatchMode: { type: "queue_after_active" },
1035
+ createdBy: "user",
1036
+ creationSource: "web",
1037
+ ...(freshContext ? { freshContext } : {}),
1038
+ ...(freshContext && scheduled
1039
+ ? { scheduledTaskId: ScheduledTaskId.make(`${key}-task`) }
1040
+ : {}),
1041
+ });
1042
+ const settle = (name: string, status: "failed" | "completed") =>
1043
+ Effect.gen(function* () {
1044
+ const run = (yield* orchestrator.getThreadProjection(sideChatId)).runs.find(
1045
+ (candidate) => candidate.userMessageId === MessageId.make(`${key}-${name}`),
1046
+ )!;
1047
+ const now = yield* DateTime.now;
1048
+ yield* eventSink.write({
1049
+ events: [
1050
+ {
1051
+ id: EventId.make(`${key}-${name}-${status}`),
1052
+ type: "run.updated",
1053
+ threadId: sideChatId,
1054
+ runId: run.id,
1055
+ occurredAt: now,
1056
+ payload: { ...run, status, completedAt: now },
1057
+ },
1058
+ ],
1059
+ });
1060
+ });
1061
+ yield* send("first");
1062
+ yield* send("fresh", true);
1063
+ // The first run fails before its provider forks the parent's session.
1064
+ yield* settle("first", "failed");
1065
+ yield* orchestrator.dispatch({
1066
+ type: "queue.resume",
1067
+ commandId: CommandId.make(`${key}-resume`),
1068
+ threadId: sideChatId,
1069
+ });
1070
+ assert.equal(
1071
+ (yield* orchestrator.getThreadProjection(sideChatId)).runs.find(
1072
+ (run) => run.userMessageId === MessageId.make(`${key}-fresh`),
1073
+ )?.status,
1074
+ "starting",
1075
+ );
1076
+ yield* settle("fresh", "completed");
1077
+ yield* send("next");
1078
+
1079
+ const sideChat = yield* orchestrator.getThreadProjection(sideChatId);
1080
+ assert.deepEqual(
1081
+ sideChat.contextTransfers.filter((transfer) => transfer.type === "fork").map((t) => t.status),
1082
+ [scheduled ? "pending" : "superseded"],
1083
+ );
1084
+ if (scheduled) return;
1085
+ const next = sideChat.runs.find((run) => run.userMessageId === MessageId.make(`${key}-next`));
1086
+ // A fork still pending would give the next send a new note, with a digest of the main thread.
1087
+ assert.deepEqual(
1088
+ sideChat.contextHandoffs.filter((handoff) => handoff.targetRunId === next?.id),
1089
+ [],
1090
+ );
1091
+ }).pipe(Effect.provide(forkCases[0]!.layer)),
1092
+);
1093
+
1094
it.effect("a side chat of a busy parent points history recovery at the parent", () =>
1095
Effect.gen(function* () {
1096
const orchestrator = yield* Orchestrator.OrchestratorV2;