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 22, 22:00 UTC
fix(server): rolling back a Claude fork's first run keeps its inherited history (#21188)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
fixfon committed
Oct 20, 2026 at 08:09 UTC
0c3943049c50108eb81c94d08abe8e34ff92e8db
5 files changed
+207
-16
apps/server/src/claudeHistoryWorker.ts
+6
-1
@@ -24,7 +24,12 @@ export async function runClaudeHistoryWorker(
24
method === "getSessionMessages"
25
? await getSessionMessages(sessionId, options)
26
: method === "forkSession"
27
- ? await forkSession(sessionId, options)
27
+ ? await forkSession(sessionId, options).then(async (forked) => {
28
+ const headMessageId = await getSessionMessages(forked.sessionId, options)
29
+ .then((messages) => messages.at(-1)?.uuid)
30
+ .catch(() => undefined);
31
+ return headMessageId === undefined ? forked : { ...forked, headMessageId };
32
+ })
33
: (() => {
34
throw new Error("Unknown Claude history operation.");
35
})();
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+104
-2
@@ -2536,6 +2536,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2536
readonly nativeSessionId?: string;
2537
readonly settings?: ClaudeSettings;
2538
readonly freshQueueOnReopen?: boolean;
2539
+ readonly forkSession?: ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerShape["forkSession"];
2540
+ readonly allocateSessionId?: Effect.Effect<string>;
2541
}) =>
2542
Effect.gen(function* () {
2543
const fileSystem = yield* FileSystem.FileSystem;
@@ -2600,7 +2602,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2602
}).pipe(Effect.andThen(Queue.offer(continuationReceipts, request))),
2603
},
2604
queryRunner: {
2603
- allocateSessionId: Effect.succeed(options?.nativeSessionId ?? WAKE_NATIVE_SESSION),
2605
+ allocateSessionId:
2606
+ options?.allocateSessionId ??
2607
+ Effect.succeed(options?.nativeSessionId ?? WAKE_NATIVE_SESSION),
2608
open: (input) =>
2609
Effect.gen(function* () {
2610
openedOptions = input.options;
@@ -2662,7 +2666,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2666
close: options?.close?.(sdkMessages) ?? Effect.void,
2667
};
2668
}),
2665
- forkSession: () => Effect.die("unused forkSession"),
2669
+ forkSession: options?.forkSession ?? (() => Effect.die("unused forkSession")),
2670
subagentLaunchToolUseId: () => Effect.succeed(options?.subagentLaunchToolUseId ?? null),
2671
assertComplete: Effect.void,
2672
},
@@ -3916,6 +3920,104 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3920
close: (sdkMessages) => Queue.shutdown(sdkMessages),
3921
});
3922
3923
+ it.effect.each([
3924
+ { kind: "fork with inherited head", fork: true, headMessageId: "remapped-inherited-head" },
3925
+ { kind: "fork without recorded head", fork: true, headMessageId: undefined },
3926
+ { kind: "ordinary thread", fork: false, headMessageId: undefined },
3927
+ ])("rolls back the first run of a $kind", ({ fork, headMessageId }) =>
3928
+ Effect.gen(function* () {
3929
+ let allocations = 0;
3930
+ const harness = yield* makeWakeHarnessWithOptions({
3931
+ close: (sdkMessages) => Queue.shutdown(sdkMessages),
3932
+ freshQueueOnReopen: true,
3933
+ allocateSessionId: Effect.sync(() =>
3934
+ allocations++ === 0 ? WAKE_NATIVE_SESSION : "fresh-native-session",
3935
+ ),
3936
+ forkSession: () =>
3937
+ Effect.succeed({
3938
+ sessionId: WAKE_NATIVE_SESSION,
3939
+ ...(headMessageId === undefined ? {} : { headMessageId }),
3940
+ }),
3941
+ });
3942
+ const providerThread = fork
3943
+ ? yield* harness.runtime.forkThread({
3944
+ sourceProviderThread: {
3945
+ ...harness.providerThread,
3946
+ nativeThreadRef: {
3947
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
3948
+ nativeId: "source-native-session",
3949
+ strength: "strong",
3950
+ },
3951
+ },
3952
+ targetThreadId: harness.threadId,
3953
+ })
3954
+ : harness.providerThread;
3955
+ const turnInput = makeClaudeTestTurnInput({
3956
+ threadId: harness.threadId,
3957
+ providerThread,
3958
+ now: yield* DateTime.now,
3959
+ attemptId: RunAttemptId.make("first-run"),
3960
+ text: "This run will be rolled back.",
3961
+ attachments: [],
3962
+ nativeThreadHasTurns: false,
3963
+ });
3964
+ yield* harness.runtime.startTurn(turnInput);
3965
+ yield* harness.offerAndWait(
3966
+ makeAssistantTextFrame({ uuid: "own-run-message", text: "Discard this answer." }),
3967
+ );
3968
+ yield* harness.offerAndWait(
3969
+ makeResultFrame({ uuid: "own-run-result", result: "Discard this answer." }),
3970
+ );
3971
+ assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed");
3972
+ const completed = harness.events.findLast(
3973
+ (event) => event.type === "provider_thread.updated",
3974
+ );
3975
+ assert.equal(completed?.type, "provider_thread.updated");
3976
+ if (completed?.type !== "provider_thread.updated") return;
3977
+ assert.equal(completed.providerThread.firstRunOrdinal, 1);
3978
+
3979
+ const rolledBack = yield* harness.runtime.rollbackThread({
3980
+ providerThread: completed.providerThread,
3981
+ target: {
3982
+ type: "thread_start",
3983
+ checkpointId: CheckpointId.make("checkpoint-before-first-run"),
3984
+ appRunOrdinal: 0,
3985
+ },
3986
+ providerThreadTurns: [lastProviderTurn(harness.events)],
3987
+ });
3988
+ assert.equal(
3989
+ rolledBack.providerThread.forkedFrom?.providerThreadId,
3990
+ providerThread.forkedFrom?.providerThreadId,
3991
+ );
3992
+ yield* harness.runtime.startTurn({
3993
+ ...turnInput,
3994
+ attemptId: RunAttemptId.make("after-rollback"),
3995
+ providerThread: rolledBack.providerThread,
3996
+ providerTurnOrdinal: 2,
3997
+ nativeThreadHasTurns: false,
3998
+ });
3999
+ const options = harness.getOpenedOptions();
4000
+ assert.equal(harness.processQueues.length, 2);
4001
+ if (headMessageId !== undefined) {
4002
+ assert.equal(rolledBack.providerThread.nativeThreadRef?.nativeId, WAKE_NATIVE_SESSION);
4003
+ assert.equal(rolledBack.providerThread.nativeConversationHeadRef?.nativeId, headMessageId);
4004
+ assert.equal(options?.resume, WAKE_NATIVE_SESSION);
4005
+ assert.equal(options?.resumeSessionAt, headMessageId);
4006
+ assert.isUndefined(options?.sessionId);
4007
+ } else {
4008
+ assert.equal(rolledBack.providerThread.nativeThreadRef?.nativeId, "fresh-native-session");
4009
+ assert.isNull(rolledBack.providerThread.nativeConversationHeadRef);
4010
+ assert.equal(options?.sessionId, "fresh-native-session");
4011
+ assert.isUndefined(options?.resume);
4012
+ assert.isUndefined(options?.resumeSessionAt);
4013
+ }
4014
+ }).pipe(
4015
+ Effect.provide(
4016
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
4017
+ ),
4018
+ ),
4019
+ );
4020
+
4021
it.effect(
4022
"rolls back to the main-thread assistant message when a subagent frame comes last",
4023
() =>
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+43
-13
@@ -26,6 +26,7 @@ import {
26
type EffortLevel,
27
type ForkSessionOptions,
28
type ForkSessionResult,
29
+ getSessionMessages,
30
getSubagentMessages,
31
query,
32
type Options as ClaudeQueryOptions,
@@ -514,7 +515,10 @@ export interface ClaudeAgentSdkQueryRunnerShape {
515
) => Effect.Effect<ClaudeAgentSdkQuerySession, ClaudeAgentSdkQueryRunnerError>;
516
readonly forkSession: (
517
input: ClaudeAgentSdkSessionForkInput,
517
- ) => Effect.Effect<ForkSessionResult, ClaudeAgentSdkQueryRunnerError>;
518
+ ) => Effect.Effect<
519
+ ForkSessionResult & { readonly headMessageId?: string },
520
+ ClaudeAgentSdkQueryRunnerError
521
+ >;
522
readonly subagentLaunchToolUseId: (
523
input: ClaudeAgentSdkSubagentLookupInput,
524
) => Effect.Effect<string | null, ClaudeAgentSdkQueryRunnerError>;
@@ -765,7 +769,9 @@ export function makeClaudeAgentSdkProtocolLogger(input: {
769
770
const encodeClaudeHistoryOptions = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
771
const decodeClaudeHistoryFork = Schema.decodeUnknownEffect(
768
- Schema.fromJsonString(Schema.Struct({ sessionId: Schema.String })),
772
+ Schema.fromJsonString(
773
+ Schema.Struct({ sessionId: Schema.String, headMessageId: Schema.optionalKey(Schema.String) }),
774
+ ),
775
);
776
777
const claudeConfigDirOf = (
@@ -1097,14 +1103,18 @@ export const layerQueryRunner: Layer.Layer<
1103
});
1104
const hostEnvironment = yield* HostProcess.Environment;
1105
const homeDirectory = yield* HostProcess.HomeDirectory;
1100
- const fork: Effect.Effect<ForkSessionResult, unknown> =
1106
+ const usesHostConfig =
1107
claudeConfigDirOf(path, input.environment, homeDirectory) ===
1102
- claudeConfigDirOf(path, hostEnvironment, homeDirectory)
1103
- ? Effect.tryPromise(() => forkClaudeSession(input.sessionId, input.options))
1104
- : forkClaudeSessionInWorker(input).pipe(
1105
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1106
- Effect.provideService(Path.Path, path),
1107
- );
1108
+ claudeConfigDirOf(path, hostEnvironment, homeDirectory);
1109
+ const fork: Effect.Effect<
1110
+ ForkSessionResult & { readonly headMessageId?: string },
1111
+ unknown
1112
+ > = usesHostConfig
1113
+ ? Effect.tryPromise(() => forkClaudeSession(input.sessionId, input.options))
1114
+ : forkClaudeSessionInWorker(input).pipe(
1115
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1116
+ Effect.provideService(Path.Path, path),
1117
+ );
1118
const result = yield* fork.pipe(
1119
Effect.mapError((cause) => queryRunnerError(cause, "forkSession")),
1120
);
@@ -1116,7 +1126,22 @@ export const layerQueryRunner: Layer.Layer<
1126
sessionId: result.sessionId,
1127
},
1128
});
1119
- return result;
1129
+ // The SDK remaps copied UUIDs. Capture the inherited head before the
1130
+ // fork's first run appends messages.
1131
+ const headMessageId = usesHostConfig
1132
+ ? yield* Effect.tryPromise({
1133
+ try: () =>
1134
+ getSessionMessages(
1135
+ result.sessionId,
1136
+ input.options.dir === undefined ? {} : { dir: input.options.dir },
1137
+ ),
1138
+ catch: (cause) => queryRunnerError(cause, "getSessionMessages"),
1139
+ }).pipe(
1140
+ Effect.map((messages) => messages.at(-1)?.uuid),
1141
+ Effect.orElseSucceed(() => undefined),
1142
+ )
1143
+ : result.headMessageId;
1144
+ return headMessageId === undefined ? result : { ...result, headMessageId };
1145
}),
1146
subagentLaunchToolUseId: Effect.fn("ClaudeAgentSdkQueryRunner.subagentLaunchToolUseId")(
1147
function* (input: ClaudeAgentSdkSubagentLookupInput) {
@@ -1496,6 +1521,7 @@ function makeProviderThread(input: {
1521
readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
1522
readonly nativeThreadId: string;
1523
readonly forkedFrom?: NonNullable<OrchestrationV2ProviderThread["forkedFrom"]>;
1524
+ readonly nativeMetadata?: NonNullable<OrchestrationV2ProviderThread["nativeMetadata"]>;
1525
readonly now: DateTime.Utc;
1526
}): OrchestrationV2ProviderThread {
1527
return {
@@ -1519,6 +1545,7 @@ function makeProviderThread(input: {
1545
lastRunOrdinal: null,
1546
handoffIds: [],
1547
forkedFrom: input.forkedFrom ?? null,
1548
+ ...(input.nativeMetadata === undefined ? {} : { nativeMetadata: input.nativeMetadata }),
1549
createdAt: input.now,
1550
updatedAt: input.now,
1551
};
@@ -1624,7 +1651,7 @@ const resolveClaudeRollbackResumeSessionAt = Effect.fn(
1651
)(function* (input: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) {
1652
switch (input.target.type) {
1653
case "thread_start":
1627
- return null;
1654
+ return input.providerThread.nativeMetadata?.forkHeadMessageId ?? null;
1655
case "provider_turn": {
1656
const target = input.target;
1657
if (target.providerTurn.providerThreadId !== input.providerThread.id) {
@@ -9870,8 +9897,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9897
const nativeThreadId = yield* getNativeThreadId(rollbackInput.providerThread);
9898
yield* closeLiveQueryForNativeThread(nativeThreadId);
9899
const now = yield* DateTime.now;
9900
+ const resumeSessionAt = yield* resolveClaudeRollbackResumeSessionAt(rollbackInput);
9901
9874
- if (rollbackInput.target.type === "thread_start") {
9902
+ if (rollbackInput.target.type === "thread_start" && resumeSessionAt === null) {
9903
const resetNativeThreadId = yield* queryRunner.allocateSessionId;
9904
return {
9905
providerThread: {
@@ -9897,7 +9925,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9925
};
9926
}
9927
9900
- const resumeSessionAt = yield* resolveClaudeRollbackResumeSessionAt(rollbackInput);
9928
return {
9929
providerThread: {
9930
...rollbackInput.providerThread,
@@ -9975,6 +10002,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10002
? {}
10003
: { providerTurnId: forkInput.providerTurnId }),
10004
},
10005
+ ...(forked.headMessageId === undefined
10006
+ ? {}
10007
+ : { nativeMetadata: { forkHeadMessageId: forked.headMessageId } }),
10008
now,
10009
});
10010
},
apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+53
@@ -151,6 +151,13 @@ it.effect("forks a session stored under the instance's own CLAUDE_CONFIG_DIR", (
151
);
152
assert.include(transcript, '"content":"hello"');
153
assert.include(transcript, '"text":"hi"');
154
+ const inheritedHead = transcript
155
+ .trim()
156
+ .split("\n")
157
+ .findLast((line) => line.includes('"type":"assistant"'))
158
+ ?.match(/"uuid"\s*:\s*"([^"]+)"/)?.[1];
159
+ assert.isString(inheritedHead);
160
+ assert.equal(forked.headMessageId, inheritedHead);
161
assert.equal(process.env.CLAUDE_CONFIG_DIR, hostConfigDir);
162
assert.equal(inProcessFork.mock.calls.length, 0);
163
}).pipe(Effect.provide(forkRunnerLayer)),
@@ -187,6 +194,52 @@ const realQueryRunner = layerQueryRunner.pipe(
194
Layer.provide(NodeServices.layer),
195
);
196
197
+it.effect.each(["readable", "unreadable"] as const)(
198
+ "forks with a %s transcript, retaining the inherited head when available",
199
+ (transcript) =>
200
+ Effect.gen(function* () {
201
+ let forkCompleted = false;
202
+ const fork = vi.spyOn(ClaudeSdk, "forkSession").mockImplementation(async () => {
203
+ forkCompleted = true;
204
+ return { sessionId: "forked-session" };
205
+ });
206
+ const read = vi.spyOn(ClaudeSdk, "getSessionMessages").mockImplementation(async () => {
207
+ assert.isTrue(forkCompleted);
208
+ if (transcript === "unreadable") throw new Error("transcript unreadable");
209
+ return ["remapped-user", "remapped-assistant"].map((uuid) => ({
210
+ type: "assistant" as const,
211
+ uuid,
212
+ session_id: "forked-session",
213
+ message: { role: "assistant", content: uuid },
214
+ parent_tool_use_id: null,
215
+ parent_agent_id: null,
216
+ }));
217
+ });
218
+ yield* Effect.addFinalizer(() =>
219
+ Effect.sync(() => {
220
+ fork.mockRestore();
221
+ read.mockRestore();
222
+ }),
223
+ );
224
+ const runner = yield* ClaudeAgentSdkQueryRunner;
225
+ const forked = yield* runner.forkSession({
226
+ sessionId: "source-session",
227
+ options: { dir: "/workspace", upToMessageId: "source-assistant" },
228
+ environment: process.env,
229
+ threadId: ThreadId.make("thread-fork-head"),
230
+ providerSessionId: ProviderSessionId.make("session-fork-head"),
231
+ });
232
+ assert.deepEqual(forked, {
233
+ sessionId: "forked-session",
234
+ ...(transcript === "readable" ? { headMessageId: "remapped-assistant" } : {}),
235
+ });
236
+ assert.deepEqual(fork.mock.calls, [
237
+ ["source-session", { dir: "/workspace", upToMessageId: "source-assistant" }],
238
+ ]);
239
+ assert.deepEqual(read.mock.calls, [["forked-session", { dir: "/workspace" }]]);
240
+ }).pipe(Effect.provide(realQueryRunner)),
241
+);
242
+
243
function fakeClaudeCli(script: string): string {
244
const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-cli-"));
245
const cli = NodePath.join(dir, "claude");
packages/contracts/src/orchestrationV2.ts
+1
@@ -847,6 +847,7 @@ export const OrchestrationV2ProviderThreadNativeMetadata = Schema.Struct({
847
title: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
848
updatedAt: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
849
itemIdentityVersion: Schema.optional(Schema.Literal(2)),
850
+ forkHeadMessageId: Schema.optional(TrimmedNonEmptyString),
851
});
852
export type OrchestrationV2ProviderThreadNativeMetadata =
853
typeof OrchestrationV2ProviderThreadNativeMetadata.Type;