Skip to content
TypeScript

fix(server): forking a Claude thread works on instances with their own home (#18662)

singul-oss04013723ef11
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index c0f60c3411c..dbcd849e92e 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -1886,16 +1886,11 @@ describe("ClaudeAdapterV2 native fork", () => {
prefix: "t3-claude-v2-fork-attachments-",
});
const openedQueries: Array<ClaudeAdapterV2.ClaudeAgentSdkQueryOpenInput> = [];
- const forkCalls: Array<{
- readonly sessionId: string;
- readonly options: unknown;
- readonly threadId: ThreadId;
- readonly providerSessionId: ProviderSessionId;
- }> = [];
+ const forkCalls: Array<ClaudeAdapterV2.ClaudeAgentSdkSessionForkInput> = [];
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
settings: DEFAULT_CLAUDE_SETTINGS,
- environment: {},
+ environment: { CLAUDE_CONFIG_DIR: "/custom/claude-home" },
attachmentsDir,
fileSystem,
path: yield* Path.Path,
@@ -1987,6 +1982,7 @@ describe("ClaudeAdapterV2 native fork", () => {
dir: "/workspace",
upToMessageId: "assistant-message-cursor",
},
+ environment: { CLAUDE_CONFIG_DIR: "/custom/claude-home" },
threadId: targetThreadId,
providerSessionId,
},
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index a5e19ed1ca5..3a00dd04e5b 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -110,6 +110,8 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
+import * as ChildProcess from "effect/process/ChildProcess";
+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts";
@@ -121,6 +123,7 @@ import {
} from "../../claudeModelOptions.ts";
import * as ServerConfig from "../../config.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
+import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
import {
claudeSignedOutMessage,
@@ -507,6 +510,7 @@ export class ClaudeAgentSdkQueryRunner extends Context.Service<
export interface ClaudeAgentSdkSessionForkInput {
readonly sessionId: string;
readonly options: ForkSessionOptions;
+ readonly environment: NodeJS.ProcessEnv;
readonly threadId: ThreadId;
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
}
@@ -740,14 +744,72 @@ export function makeClaudeAgentSdkProtocolLogger(input: {
};
}
+const encodeClaudeHistoryOptions = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
+const decodeClaudeHistoryFork = Schema.decodeUnknownEffect(
+ Schema.fromJsonString(Schema.Struct({ sessionId: Schema.String })),
+);
+
+const claudeConfigDirOf = (
+ path: Path.Path,
+ environment: NodeJS.ProcessEnv,
+ homeDirectory: string,
+) => path.resolve(environment.CLAUDE_CONFIG_DIR ?? path.join(homeDirectory, ".claude"));
+
+// The SDK reads CLAUDE_CONFIG_DIR from process.env. Isolate custom homes in a
+// worker so concurrent providers keep the server's environment.
+const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(function* (
+ input: ClaudeAgentSdkSessionForkInput,
+) {
+ const path = yield* Path.Path;
+ const fromSource = import.meta.url.endsWith(".ts");
+ // A single executable hosts the worker itself; it has no sibling script.
+ const workerArguments = (yield* HostProcess.IsExecutable)
+ ? ["__claude-history"]
+ : [
+ ...(fromSource ? ["--experimental-strip-types"] : []),
+ yield* path.fromFileUrl(
+ new URL(
+ fromSource ? "../../claude-history-worker.ts" : "./claude-history-worker.mjs",
+ import.meta.url,
+ ),
+ ),
+ ];
+ const executablePath = yield* HostProcess.ExecutablePath;
+ const result = yield* spawnAndCollect(
+ executablePath,
+ ChildProcess.make(
+ executablePath,
+ [
+ ...workerArguments,
+ "forkSession",
+ input.sessionId,
+ encodeClaudeHistoryOptions(input.options),
+ ],
+ { env: { ...input.environment, ELECTRON_RUN_AS_NODE: "1" } },
+ ),
+ ).pipe(Effect.timeout("30 seconds"));
+ if (result.code !== 0) {
+ return yield* new ClaudeAgentSdkQueryRunnerError({
+ method: "forkSession",
+ cause: result.stderr.trim() || `Claude history worker exited with code ${result.code}.`,
+ });
+ }
+ return yield* decodeClaudeHistoryFork(result.stdout);
+});
+
export const layerQueryRunner: Layer.Layer<
ClaudeAgentSdkQueryRunner,
never,
- Crypto.Crypto | ProviderEventLoggers.ProviderEventLoggers
+ | ChildProcessSpawner.ChildProcessSpawner
+ | Crypto.Crypto
+ | Path.Path
+ | ProviderEventLoggers.ProviderEventLoggers
> = Layer.effect(
ClaudeAgentSdkQueryRunner,
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const path = yield* Path.Path;
const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
const agentScope = yield* AgentScope;
const platform = yield* HostProcess.Platform;
@@ -1014,10 +1076,19 @@ export const layerQueryRunner: Layer.Layer<
options: input.options,
},
});
- const result = yield* Effect.tryPromise({
- try: () => forkClaudeSession(input.sessionId, input.options),
- catch: (cause) => queryRunnerError(cause, "forkSession"),
- });
+ const hostEnvironment = yield* HostProcess.Environment;
+ const homeDirectory = yield* HostProcess.HomeDirectory;
+ const fork: Effect.Effect<ForkSessionResult, unknown> =
+ claudeConfigDirOf(path, input.environment, homeDirectory) ===
+ claudeConfigDirOf(path, hostEnvironment, homeDirectory)
+ ? Effect.tryPromise(() => forkClaudeSession(input.sessionId, input.options))
+ : forkClaudeSessionInWorker(input).pipe(
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
+ Effect.provideService(Path.Path, path),
+ );
+ const result = yield* fork.pipe(
+ Effect.mapError((cause) => queryRunnerError(cause, "forkSession")),
+ );
yield* logProtocolEvent({
direction: "incoming",
stage: "decoded",
@@ -9646,6 +9717,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
const forked = yield* queryRunner.forkSession({
sessionId: sourceNativeThreadId,
options: forkOptions,
+ environment: adapterOptions.environment,
threadId: forkInput.targetThreadId,
providerSessionId: input.providerSessionId,
});
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
index a691d7e8459..c9c091d0e75 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
@@ -9,11 +9,13 @@ import { assert, describe, it } from "@effect/vitest";
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
+import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
+import * as Path from "effect/Path";
import { vi } from "vite-plus/test";
-import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
import {
CLAUDE_AGENT_SDK_QUERY_PROTOCOL,
ClaudeAgentSdkQueryRunner,
@@ -85,6 +87,96 @@ it.effect("logs successful task stops for replay and omits failed stops", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
+const FORK_SESSION_ID = "11111111-1111-4111-8111-111111111111";
+
+const writeClaudeSession = Effect.fnUntraced(function* (configDir: string) {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const projectDir = path.join(configDir, "projects", "-repo");
+ const entry = (uuid: string, parentUuid: string | null, message: unknown) => ({
+ type: parentUuid === null ? "user" : "assistant",
+ uuid,
+ parentUuid,
+ sessionId: FORK_SESSION_ID,
+ cwd: "/repo",
+ isSidechain: false,
+ timestamp: "2026-10-01T00:00:00.000Z",
+ message,
+ });
+ yield* fileSystem.makeDirectory(projectDir, { recursive: true });
+ yield* fileSystem.writeFileString(
+ path.join(projectDir, `${FORK_SESSION_ID}.jsonl`),
+ [
+ entry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }),
+ entry("aaaaaaaa-0000-4000-8000-000000000002", "aaaaaaaa-0000-4000-8000-000000000001", {
+ role: "assistant",
+ content: [{ type: "text", text: "hi" }],
+ }),
+ ]
+ .map((line) => JSON.stringify(line))
+ .join("\n"),
+ );
+ return projectDir;
+});
+
+const forkRunnerLayer = layerQueryRunner.pipe(
+ Layer.provide(Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined })),
+);
+
+it.effect("forks a session stored under the instance's own CLAUDE_CONFIG_DIR", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const configDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-claude-fork-config-",
+ });
+ const projectDir = yield* writeClaudeSession(configDir);
+ const hostConfigDir = process.env.CLAUDE_CONFIG_DIR;
+ const inProcessFork = vi.spyOn(ClaudeSdk, "forkSession");
+ yield* Effect.addFinalizer(() => Effect.sync(() => inProcessFork.mockRestore()));
+
+ const runner = yield* ClaudeAgentSdkQueryRunner;
+ const forked = yield* runner.forkSession({
+ sessionId: FORK_SESSION_ID,
+ options: { dir: "/repo" },
+ environment: { ...process.env, CLAUDE_CONFIG_DIR: configDir },
+ threadId: ThreadId.make("thread-fork-config-dir"),
+ providerSessionId: ProviderSessionId.make("session-fork-config-dir"),
+ });
+
+ assert.notEqual(forked.sessionId, FORK_SESSION_ID);
+ const transcript = yield* fileSystem.readFileString(
+ path.join(projectDir, `${forked.sessionId}.jsonl`),
+ );
+ assert.include(transcript, '"content":"hello"');
+ assert.include(transcript, '"text":"hi"');
+ assert.equal(process.env.CLAUDE_CONFIG_DIR, hostConfigDir);
+ assert.equal(inProcessFork.mock.calls.length, 0);
+ }).pipe(Effect.provide(forkRunnerLayer)),
+ ).pipe(Effect.provide(NodeServices.layer)),
+);
+
+it.effect("forks in-process when the instance shares the server's config dir", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const inProcessFork = vi
+ .spyOn(ClaudeSdk, "forkSession")
+ .mockResolvedValue({ sessionId: "forked-in-process" });
+ yield* Effect.addFinalizer(() => Effect.sync(() => inProcessFork.mockRestore()));
+ const runner = yield* ClaudeAgentSdkQueryRunner;
+ const forked = yield* runner.forkSession({
+ sessionId: FORK_SESSION_ID,
+ options: { dir: "/repo" },
+ environment: { ...process.env },
+ threadId: ThreadId.make("thread-fork-shared-config-dir"),
+ providerSessionId: ProviderSessionId.make("session-fork-shared-config-dir"),
+ });
+
+ assert.equal(forked.sessionId, "forked-in-process");
+ }).pipe(Effect.provide(forkRunnerLayer)),
+ ).pipe(Effect.provide(NodeServices.layer)),
+);
const realQueryRunner = layerQueryRunner.pipe(
Layer.provide(
Layer.succeed(ProviderEventLoggers, {