@devries-cameron20 / t3code-1 / commits / 04013723ef
Fork 0

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

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

Co-authored-by: SIngularity <56167379+Singularity777x@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

singul-oss committed Oct 19, 2026 at 22:25 UTC 04013723ef112ce052f97aa97b759644e6e7c0d1
3 files changed +173 -13
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+3 -7
@@ -1886,16 +1886,11 @@ describe("ClaudeAdapterV2 native fork", () => {
1886 prefix: "t3-claude-v2-fork-attachments-",
1887 });
1888 const openedQueries: Array<ClaudeAdapterV2.ClaudeAgentSdkQueryOpenInput> = [];
1889 - const forkCalls: Array<{
1890 - readonly sessionId: string;
1891 - readonly options: unknown;
1892 - readonly threadId: ThreadId;
1893 - readonly providerSessionId: ProviderSessionId;
1894 - }> = [];
1889 + const forkCalls: Array<ClaudeAdapterV2.ClaudeAgentSdkSessionForkInput> = [];
1890 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1891 instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
1892 settings: DEFAULT_CLAUDE_SETTINGS,
1898 - environment: {},
1893 + environment: { CLAUDE_CONFIG_DIR: "/custom/claude-home" },
1894 attachmentsDir,
1895 fileSystem,
1896 path: yield* Path.Path,
@@ -1987,6 +1982,7 @@ describe("ClaudeAdapterV2 native fork", () => {
1982 dir: "/workspace",
1983 upToMessageId: "assistant-message-cursor",
1984 },
1985 + environment: { CLAUDE_CONFIG_DIR: "/custom/claude-home" },
1986 threadId: targetThreadId,
1987 providerSessionId,
1988 },
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+77 -5
@@ -110,6 +110,8 @@ import * as Ref from "effect/Ref";
110 import * as Schema from "effect/Schema";
111 import * as Semaphore from "effect/Semaphore";
112 import * as Stream from "effect/Stream";
113 +import * as ChildProcess from "effect/process/ChildProcess";
114 +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
115
116 import { resolveAttachmentPath } from "../../attachmentStore.ts";
117 import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts";
@@ -121,6 +123,7 @@ import {
123 } from "../../claudeModelOptions.ts";
124 import * as ServerConfig from "../../config.ts";
125 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
126 +import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
127 import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
128 import {
129 claudeSignedOutMessage,
@@ -507,6 +510,7 @@ export class ClaudeAgentSdkQueryRunner extends Context.Service<
510 export interface ClaudeAgentSdkSessionForkInput {
511 readonly sessionId: string;
512 readonly options: ForkSessionOptions;
513 + readonly environment: NodeJS.ProcessEnv;
514 readonly threadId: ThreadId;
515 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
516 }
@@ -740,14 +744,72 @@ export function makeClaudeAgentSdkProtocolLogger(input: {
744 };
745 }
746
747 +const encodeClaudeHistoryOptions = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
748 +const decodeClaudeHistoryFork = Schema.decodeUnknownEffect(
749 + Schema.fromJsonString(Schema.Struct({ sessionId: Schema.String })),
750 +);
751 +
752 +const claudeConfigDirOf = (
753 + path: Path.Path,
754 + environment: NodeJS.ProcessEnv,
755 + homeDirectory: string,
756 +) => path.resolve(environment.CLAUDE_CONFIG_DIR ?? path.join(homeDirectory, ".claude"));
757 +
758 +// The SDK reads CLAUDE_CONFIG_DIR from process.env. Isolate custom homes in a
759 +// worker so concurrent providers keep the server's environment.
760 +const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(function* (
761 + input: ClaudeAgentSdkSessionForkInput,
762 +) {
763 + const path = yield* Path.Path;
764 + const fromSource = import.meta.url.endsWith(".ts");
765 + // A single executable hosts the worker itself; it has no sibling script.
766 + const workerArguments = (yield* HostProcess.IsExecutable)
767 + ? ["__claude-history"]
768 + : [
769 + ...(fromSource ? ["--experimental-strip-types"] : []),
770 + yield* path.fromFileUrl(
771 + new URL(
772 + fromSource ? "../../claude-history-worker.ts" : "./claude-history-worker.mjs",
773 + import.meta.url,
774 + ),
775 + ),
776 + ];
777 + const executablePath = yield* HostProcess.ExecutablePath;
778 + const result = yield* spawnAndCollect(
779 + executablePath,
780 + ChildProcess.make(
781 + executablePath,
782 + [
783 + ...workerArguments,
784 + "forkSession",
785 + input.sessionId,
786 + encodeClaudeHistoryOptions(input.options),
787 + ],
788 + { env: { ...input.environment, ELECTRON_RUN_AS_NODE: "1" } },
789 + ),
790 + ).pipe(Effect.timeout("30 seconds"));
791 + if (result.code !== 0) {
792 + return yield* new ClaudeAgentSdkQueryRunnerError({
793 + method: "forkSession",
794 + cause: result.stderr.trim() || `Claude history worker exited with code ${result.code}.`,
795 + });
796 + }
797 + return yield* decodeClaudeHistoryFork(result.stdout);
798 +});
799 +
800 export const layerQueryRunner: Layer.Layer<
801 ClaudeAgentSdkQueryRunner,
802 never,
746 - Crypto.Crypto | ProviderEventLoggers.ProviderEventLoggers
803 + | ChildProcessSpawner.ChildProcessSpawner
804 + | Crypto.Crypto
805 + | Path.Path
806 + | ProviderEventLoggers.ProviderEventLoggers
807 > = Layer.effect(
808 ClaudeAgentSdkQueryRunner,
809 Effect.gen(function* () {
810 const crypto = yield* Crypto.Crypto;
811 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
812 + const path = yield* Path.Path;
813 const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
814 const agentScope = yield* AgentScope;
815 const platform = yield* HostProcess.Platform;
@@ -1014,10 +1076,19 @@ export const layerQueryRunner: Layer.Layer<
1076 options: input.options,
1077 },
1078 });
1017 - const result = yield* Effect.tryPromise({
1018 - try: () => forkClaudeSession(input.sessionId, input.options),
1019 - catch: (cause) => queryRunnerError(cause, "forkSession"),
1020 - });
1079 + const hostEnvironment = yield* HostProcess.Environment;
1080 + const homeDirectory = yield* HostProcess.HomeDirectory;
1081 + const fork: Effect.Effect<ForkSessionResult, unknown> =
1082 + claudeConfigDirOf(path, input.environment, homeDirectory) ===
1083 + claudeConfigDirOf(path, hostEnvironment, homeDirectory)
1084 + ? Effect.tryPromise(() => forkClaudeSession(input.sessionId, input.options))
1085 + : forkClaudeSessionInWorker(input).pipe(
1086 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1087 + Effect.provideService(Path.Path, path),
1088 + );
1089 + const result = yield* fork.pipe(
1090 + Effect.mapError((cause) => queryRunnerError(cause, "forkSession")),
1091 + );
1092 yield* logProtocolEvent({
1093 direction: "incoming",
1094 stage: "decoded",
@@ -9646,6 +9717,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9717 const forked = yield* queryRunner.forkSession({
9718 sessionId: sourceNativeThreadId,
9719 options: forkOptions,
9720 + environment: adapterOptions.environment,
9721 threadId: forkInput.targetThreadId,
9722 providerSessionId: input.providerSessionId,
9723 });
apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+93 -1
@@ -9,11 +9,13 @@ import { assert, describe, it } from "@effect/vitest";
9 import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
10 import * as Effect from "effect/Effect";
11 import * as Exit from "effect/Exit";
12 +import * as FileSystem from "effect/FileSystem";
13 import * as Layer from "effect/Layer";
14 +import * as Path from "effect/Path";
15 import { vi } from "vite-plus/test";
16
15 -import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
17 import * as HostProcess from "@t3tools/shared/HostProcess";
18 +import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
19 import {
20 CLAUDE_AGENT_SDK_QUERY_PROTOCOL,
21 ClaudeAgentSdkQueryRunner,
@@ -85,6 +87,96 @@ it.effect("logs successful task stops for replay and omits failed stops", () =>
87 }).pipe(Effect.provide(NodeServices.layer)),
88 );
89
90 +const FORK_SESSION_ID = "11111111-1111-4111-8111-111111111111";
91 +
92 +const writeClaudeSession = Effect.fnUntraced(function* (configDir: string) {
93 + const fileSystem = yield* FileSystem.FileSystem;
94 + const path = yield* Path.Path;
95 + const projectDir = path.join(configDir, "projects", "-repo");
96 + const entry = (uuid: string, parentUuid: string | null, message: unknown) => ({
97 + type: parentUuid === null ? "user" : "assistant",
98 + uuid,
99 + parentUuid,
100 + sessionId: FORK_SESSION_ID,
101 + cwd: "/repo",
102 + isSidechain: false,
103 + timestamp: "2026-10-01T00:00:00.000Z",
104 + message,
105 + });
106 + yield* fileSystem.makeDirectory(projectDir, { recursive: true });
107 + yield* fileSystem.writeFileString(
108 + path.join(projectDir, `${FORK_SESSION_ID}.jsonl`),
109 + [
110 + entry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }),
111 + entry("aaaaaaaa-0000-4000-8000-000000000002", "aaaaaaaa-0000-4000-8000-000000000001", {
112 + role: "assistant",
113 + content: [{ type: "text", text: "hi" }],
114 + }),
115 + ]
116 + .map((line) => JSON.stringify(line))
117 + .join("\n"),
118 + );
119 + return projectDir;
120 +});
121 +
122 +const forkRunnerLayer = layerQueryRunner.pipe(
123 + Layer.provide(Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined })),
124 +);
125 +
126 +it.effect("forks a session stored under the instance's own CLAUDE_CONFIG_DIR", () =>
127 + Effect.scoped(
128 + Effect.gen(function* () {
129 + const fileSystem = yield* FileSystem.FileSystem;
130 + const path = yield* Path.Path;
131 + const configDir = yield* fileSystem.makeTempDirectoryScoped({
132 + prefix: "t3-claude-fork-config-",
133 + });
134 + const projectDir = yield* writeClaudeSession(configDir);
135 + const hostConfigDir = process.env.CLAUDE_CONFIG_DIR;
136 + const inProcessFork = vi.spyOn(ClaudeSdk, "forkSession");
137 + yield* Effect.addFinalizer(() => Effect.sync(() => inProcessFork.mockRestore()));
138 +
139 + const runner = yield* ClaudeAgentSdkQueryRunner;
140 + const forked = yield* runner.forkSession({
141 + sessionId: FORK_SESSION_ID,
142 + options: { dir: "/repo" },
143 + environment: { ...process.env, CLAUDE_CONFIG_DIR: configDir },
144 + threadId: ThreadId.make("thread-fork-config-dir"),
145 + providerSessionId: ProviderSessionId.make("session-fork-config-dir"),
146 + });
147 +
148 + assert.notEqual(forked.sessionId, FORK_SESSION_ID);
149 + const transcript = yield* fileSystem.readFileString(
150 + path.join(projectDir, `${forked.sessionId}.jsonl`),
151 + );
152 + assert.include(transcript, '"content":"hello"');
153 + assert.include(transcript, '"text":"hi"');
154 + assert.equal(process.env.CLAUDE_CONFIG_DIR, hostConfigDir);
155 + assert.equal(inProcessFork.mock.calls.length, 0);
156 + }).pipe(Effect.provide(forkRunnerLayer)),
157 + ).pipe(Effect.provide(NodeServices.layer)),
158 +);
159 +
160 +it.effect("forks in-process when the instance shares the server's config dir", () =>
161 + Effect.scoped(
162 + Effect.gen(function* () {
163 + const inProcessFork = vi
164 + .spyOn(ClaudeSdk, "forkSession")
165 + .mockResolvedValue({ sessionId: "forked-in-process" });
166 + yield* Effect.addFinalizer(() => Effect.sync(() => inProcessFork.mockRestore()));
167 + const runner = yield* ClaudeAgentSdkQueryRunner;
168 + const forked = yield* runner.forkSession({
169 + sessionId: FORK_SESSION_ID,
170 + options: { dir: "/repo" },
171 + environment: { ...process.env },
172 + threadId: ThreadId.make("thread-fork-shared-config-dir"),
173 + providerSessionId: ProviderSessionId.make("session-fork-shared-config-dir"),
174 + });
175 +
176 + assert.equal(forked.sessionId, "forked-in-process");
177 + }).pipe(Effect.provide(forkRunnerLayer)),
178 + ).pipe(Effect.provide(NodeServices.layer)),
179 +);
180 const realQueryRunner = layerQueryRunner.pipe(
181 Layer.provide(
182 Layer.succeed(ProviderEventLoggers, {