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 21, 17:15 UTC
fix(server): a hung network mount no longer freezes the server when it spawns a process (#36327)
Julius Marminge committed
Nov 13, 2026 at 12:45 UTC
65e4272db1d66a70dc8f44220875a799a55b5703
11 files changed
+567
-6
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+13
-2
@@ -374,10 +374,13 @@ const CLAUDE_ROOT_REFUSAL =
374
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
375
376
// fd 4 gates the launch until the server has recorded the process it is about to become.
377
+// The shell enters the cwd itself: as a native cwd, a mount that hangs chdir freezes the server.
378
const CLAUDE_GROUP_WATCH_SCRIPT = [
379
"read -r _ <&4 || exit 1",
380
"exec 4<&-",
381
"{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } </dev/null >/dev/null 2>&1 &",
382
+ 'cd -P -- "$1" || exit 125',
383
+ "shift",
384
'exec "$@" 3<&-',
385
].join("\n");
386
@@ -394,11 +397,19 @@ export function spawnClaudeProcessGroup(
397
onStderrClose: () => void = () => {},
398
register?: (pid: number) => () => void,
399
): ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid"> {
400
+ // Relative to the server's cwd, as a native cwd is; the `./` keeps CDPATH out of it.
401
+ const cwd = options.cwd ?? ".";
402
const child = NodeChildProcess.spawn(
403
"/bin/sh",
399
- ["-c", CLAUDE_GROUP_WATCH_SCRIPT, "t3-claude", options.command, ...options.args],
404
+ [
405
+ "-c",
406
+ CLAUDE_GROUP_WATCH_SCRIPT,
407
+ "t3-claude",
408
+ cwd.startsWith("/") ? cwd : `./${cwd}`,
409
+ options.command,
410
+ ...options.args,
411
+ ],
412
{
401
- cwd: options.cwd,
413
env: options.env,
414
signal: options.signal,
415
stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"],
apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+32
@@ -748,6 +748,38 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
748
}),
749
);
750
751
+ // A native cwd makes libuv wait for chdir, which a hung mount stalls with the whole server.
752
+ it.effect("enters the cwd in the child, so a missing one fails the CLI and not the spawn", () =>
753
+ Effect.gen(function* () {
754
+ const cli = fakeClaudeCli('pwd -P > "$(dirname "$0")/cwd"');
755
+ const dir = NodePath.dirname(cli);
756
+ const workspace = NodePath.join(dir, "work space");
757
+ NodeFS.mkdirSync(workspace);
758
+ yield* Effect.addFinalizer(() =>
759
+ Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })),
760
+ );
761
+ const exitCode = (cwd: string) =>
762
+ Effect.promise(
763
+ () =>
764
+ new Promise<number | null>((resolve) =>
765
+ spawnClaudeProcessGroup({
766
+ command: cli,
767
+ args: [],
768
+ cwd,
769
+ env: process.env,
770
+ signal: new AbortController().signal,
771
+ }).once("exit", resolve),
772
+ ),
773
+ );
774
+ assert.equal(yield* exitCode(workspace), 0);
775
+ assert.equal(
776
+ NodeFS.readFileSync(NodePath.join(dir, "cwd"), "utf8"),
777
+ `${NodeFS.realpathSync(workspace)}\n`,
778
+ );
779
+ assert.equal(yield* exitCode(NodePath.join(dir, "missing")), 125);
780
+ }),
781
+ );
782
+
783
// A restarted server reaps recorded CLIs, so a CLI must never run before its record exists.
784
it.effect("records the CLI before it runs and forgets it once it exits", () =>
785
Effect.gen(function* () {
apps/server/src/process/NonBlockingSpawner.test.ts
new
+200
@@ -0,0 +1,200 @@
1
+// @effect-diagnostics nodeBuiltinImport:off - the spawner's checks are node:fs/promises calls, which the test spies on.
2
+import * as NodeFSP from "node:fs/promises";
3
+
4
+import * as NodeServices from "@effect/platform-node/NodeServices";
5
+import { describe, expect, it } from "@effect/vitest";
6
+import { vi } from "vite-plus/test";
7
+import * as HostProcess from "@t3tools/shared/HostProcess";
8
+import * as Deferred from "effect/Deferred";
9
+import * as Effect from "effect/Effect";
10
+import * as Fiber from "effect/Fiber";
11
+import * as FileSystem from "effect/FileSystem";
12
+import * as Layer from "effect/Layer";
13
+import * as Path from "effect/Path";
14
+import * as ChildProcess from "effect/process/ChildProcess";
15
+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16
+
17
+import * as NonBlockingSpawner from "./NonBlockingSpawner.ts";
18
+
19
+vi.mock("node:fs/promises", { spy: true });
20
+
21
+const hostPath = process.env.PATH;
22
+
23
+const wrapped = NonBlockingSpawner.layer.pipe(Layer.provideMerge(NodeServices.layer));
24
+
25
+/** What a caller sees of a command: its output, or the error of a spawn that failed. */
26
+const outcome = (command: ChildProcess.Command) =>
27
+ ChildProcessSpawner.ChildProcessSpawner.use((spawner) => spawner.string(command)).pipe(
28
+ Effect.match({
29
+ onSuccess: (output) => ({ output }),
30
+ onFailure: (error) => ({ reason: error.reason._tag, message: error.message }),
31
+ }),
32
+ );
33
+
34
+describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("NonBlockingSpawner", () => {
35
+ it.live("gives callers what the native spawner gives them", () =>
36
+ Effect.gen(function* () {
37
+ const fileSystem = yield* FileSystem.FileSystem;
38
+ const root = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped());
39
+ for (const [file, mode] of [
40
+ ["stale/tool", 0o644],
41
+ ["fresh/tool", 0o755],
42
+ ["target/bin/tool", 0o755],
43
+ // GNU env reads a lone `-` as -i and `NAME=value` as an assignment, even after `--`.
44
+ ["fresh/-", 0o755],
45
+ ["fresh/launch=stable", 0o755],
46
+ ] as const) {
47
+ yield* fileSystem.makeDirectory(`${root}/${file.slice(0, file.lastIndexOf("/"))}`, {
48
+ recursive: true,
49
+ });
50
+ yield* fileSystem.writeFileString(`${root}/${file}`, `#!/bin/sh\necho ${file} "$@"\n`);
51
+ yield* fileSystem.chmod(`${root}/${file}`, mode);
52
+ }
53
+ yield* fileSystem.makeDirectory(`${root}/target/subdir`);
54
+ yield* fileSystem.symlink(`${root}/target/subdir`, `${root}/link`);
55
+ const PATH = `${root}/stale:${root}/fresh`;
56
+
57
+ const commands = {
58
+ "enters the cwd": ChildProcess.make("pwd", ["-P"], { cwd: root }),
59
+ "keeps argv": ChildProcess.make(
60
+ "printf",
61
+ ["%s\\n", "-n", "--", "a b", `it's "quoted"`, "$HOME", "; exit 3", "", "A=b"],
62
+ { cwd: root },
63
+ ),
64
+ // dash would drop the exported function and add PWD and OLDPWD.
65
+ "keeps the environment": ChildProcess.make("env", [], {
66
+ cwd: root,
67
+ env: { PATH: hostPath, A: "1", "BASH_FUNC_x%%": "() { echo exported\n}" },
68
+ }),
69
+ "skips a non-executable PATH entry": ChildProcess.make("tool", [], { env: { PATH } }),
70
+ "resolves `..` in PATH after a symlink": ChildProcess.make("tool", [], {
71
+ env: { PATH: `${root}/link/../bin` },
72
+ }),
73
+ "searches PATH relative to the cwd": ChildProcess.make("tool", [], {
74
+ cwd: root,
75
+ env: { PATH: "fresh" },
76
+ }),
77
+ "a command named -": ChildProcess.make("-", [], { cwd: root, env: { PATH } }),
78
+ "a command containing =": ChildProcess.make("launch=stable", [], { env: { PATH } }),
79
+ "shell mode": ChildProcess.make('pwd -P; echo "$0" "a b"', [], { cwd: root, shell: true }),
80
+ "a pipeline": ChildProcess.make("printf", ["a\\nb\\n"], { cwd: root }).pipe(
81
+ ChildProcess.pipeTo(ChildProcess.make("tail", ["-n", "1"])),
82
+ ),
83
+ "a missing command": ChildProcess.make("t3code-missing-command", ["--version"]),
84
+ "a missing command in a cwd": ChildProcess.make("t3code-missing-command", [], {
85
+ cwd: root,
86
+ }),
87
+ "a non-executable command": ChildProcess.make("tool", [], {
88
+ env: { PATH: `${root}/stale` },
89
+ }),
90
+ "a missing explicit path": ChildProcess.make("./missing", [], { cwd: root }),
91
+ "a non-executable explicit path": ChildProcess.make(`${root}/stale/tool`, []),
92
+ "a missing cwd": ChildProcess.make("true", [], { cwd: `${root}/missing` }),
93
+ // The native check sees `missing`, although the path resolves to an existing directory.
94
+ "a cwd through a missing directory": ChildProcess.make("true", [], {
95
+ cwd: `${root}/missing/..`,
96
+ }),
97
+ };
98
+ for (const [name, command] of Object.entries(commands)) {
99
+ const native = yield* outcome(command).pipe(Effect.provide(NodeServices.layer));
100
+ expect(yield* outcome(command).pipe(Effect.provide(wrapped)), name).toEqual(native);
101
+ }
102
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
103
+ );
104
+
105
+ it.live("hands the native spawner only `env`, never a cwd or a command to look up", () =>
106
+ Effect.gen(function* () {
107
+ const fileSystem = yield* FileSystem.FileSystem;
108
+ const directory = yield* fileSystem.makeTempDirectoryScoped();
109
+ const received: Array<ChildProcess.StandardCommand> = [];
110
+ const record = (command: ChildProcess.Command): void => {
111
+ if (command._tag === "StandardCommand") received.push(command);
112
+ else [command.left, command.right].forEach(record);
113
+ };
114
+ const recording = Layer.effect(
115
+ ChildProcessSpawner.ChildProcessSpawner,
116
+ Effect.map(ChildProcessSpawner.ChildProcessSpawner, (native) =>
117
+ ChildProcessSpawner.make((command) => {
118
+ record(command);
119
+ return native.spawn(command);
120
+ }),
121
+ ),
122
+ ).pipe(Layer.provideMerge(NodeServices.layer));
123
+ const commands = [
124
+ ChildProcess.make("true", [], { cwd: directory }),
125
+ ChildProcess.make("true", []),
126
+ ChildProcess.make("/bin/true", []),
127
+ ChildProcess.make("t3code-missing-command", []),
128
+ ChildProcess.make("true", [], { cwd: directory, shell: true }),
129
+ ChildProcess.make("printf", ["a"], { cwd: directory }).pipe(
130
+ ChildProcess.pipeTo(ChildProcess.make("cat", [], { cwd: directory })),
131
+ ),
132
+ ];
133
+ yield* Effect.forEach(commands, (command) =>
134
+ ChildProcessSpawner.ChildProcessSpawner.use((spawner) => spawner.exitCode(command)).pipe(
135
+ Effect.exit,
136
+ ),
137
+ ).pipe(Effect.provide(NonBlockingSpawner.layer.pipe(Layer.provide(recording))));
138
+
139
+ expect(received.map((command) => [command.command, command.options.cwd])).toEqual(
140
+ Array.from({ length: 6 }, () => ["/usr/bin/env", undefined]),
141
+ );
142
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
143
+ );
144
+
145
+ it.live("checks at most two paths at once, however many directories hang", () =>
146
+ Effect.gen(function* () {
147
+ const allArrived = yield* Deferred.make<void>();
148
+ let arrivals = 0;
149
+ // Each spawn resolves its cwd, then starts its check within microtasks.
150
+ const arrivalPath = Layer.effect(
151
+ Path.Path,
152
+ Effect.map(Path.Path, (path) => ({
153
+ ...path,
154
+ resolve: (...segments: ReadonlyArray<string>) => {
155
+ if (++arrivals === 3) setImmediate(() => Deferred.doneUnsafe(allArrived, Effect.void));
156
+ return path.resolve(...segments);
157
+ },
158
+ })),
159
+ );
160
+ const hung: Array<() => void> = [];
161
+ let releasing = false;
162
+ let running = 0;
163
+ let mostRunning = 0;
164
+ using _access = vi.spyOn(NodeFSP, "access").mockImplementation(
165
+ () =>
166
+ new Promise<void>((_resolve, reject) => {
167
+ mostRunning = Math.max(mostRunning, ++running);
168
+ const fail = () => {
169
+ running--;
170
+ reject(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
171
+ };
172
+ if (releasing) fail();
173
+ else hung.push(fail);
174
+ }),
175
+ );
176
+ const spawns = yield* Effect.forEach(
177
+ ["a", "b", "c"],
178
+ (name) =>
179
+ ChildProcessSpawner.ChildProcessSpawner.use((spawner) =>
180
+ spawner.exitCode(ChildProcess.make("true", [], { cwd: `/t3code-hung/${name}` })),
181
+ ).pipe(Effect.flip),
182
+ { concurrency: "unbounded" },
183
+ ).pipe(
184
+ Effect.provide(
185
+ NonBlockingSpawner.layer.pipe(
186
+ Layer.provide(arrivalPath),
187
+ Layer.provide(NodeServices.layer),
188
+ ),
189
+ ),
190
+ Effect.forkChild,
191
+ );
192
+ yield* Deferred.await(allArrived);
193
+ expect(mostRunning).toBe(2);
194
+ releasing = true;
195
+ for (const fail of hung.splice(0)) fail();
196
+ yield* Fiber.join(spawns);
197
+ expect(mostRunning).toBe(2);
198
+ }),
199
+ );
200
+});
apps/server/src/process/NonBlockingSpawner.ts
new
+178
@@ -0,0 +1,178 @@
1
+// @effect-diagnostics nodeBuiltinImport:off - execvp's X_OK test has no Effect FileSystem equivalent.
2
+import * as NodeFS from "node:fs";
3
+import * as NodeFSP from "node:fs/promises";
4
+
5
+import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline";
6
+import * as HostProcess from "@t3tools/shared/HostProcess";
7
+import * as Effect from "effect/Effect";
8
+import * as Layer from "effect/Layer";
9
+import * as Path from "effect/Path";
10
+import * as PlatformError from "effect/PlatformError";
11
+import * as Redacted from "effect/Redacted";
12
+import * as ChildProcess from "effect/process/ChildProcess";
13
+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14
+import * as CommandLine from "effect/process/CommandLine";
15
+
16
+// libuv's _PATH_DEFPATH, searched when the child environment has no PATH.
17
+const DEFAULT_PATH = "/usr/bin:/bin";
18
+
19
+// A check on a hung mount holds a libuv threadpool thread until the mount answers, and the
20
+// pool's four threads also compress every WebSocket frame. Checks therefore run one at a time
21
+// per directory and two at a time overall; the rest wait without holding a thread.
22
+const CHECK_LIMIT = 2;
23
+const directoryTails = new Map<string, Promise<unknown>>();
24
+const waiting: Array<() => void> = [];
25
+let running = 0;
26
+
27
+const access = async (path: string, mode: number) => {
28
+ if (running < CHECK_LIMIT) running++;
29
+ else await new Promise<void>((resume) => waiting.push(resume));
30
+ try {
31
+ await NodeFSP.access(path, mode);
32
+ return undefined;
33
+ } catch (error) {
34
+ return error as NodeJS.ErrnoException;
35
+ } finally {
36
+ // A waiter takes over the slot.
37
+ const next = waiting.shift();
38
+ if (next === undefined) running--;
39
+ else next();
40
+ }
41
+};
42
+
43
+/** The errno error of `access(path, mode)`, or undefined when it passes. */
44
+const check = (directory: string, path: string, mode: number) => {
45
+ const result = (directoryTails.get(directory) ?? Promise.resolve()).then(() =>
46
+ access(path, mode),
47
+ );
48
+ directoryTails.set(directory, result);
49
+ void result.then(() => {
50
+ if (directoryTails.get(directory) === result) directoryTails.delete(directory);
51
+ });
52
+ return Effect.promise(() => result);
53
+};
54
+
55
+// The PATH the child searches, from the environment Effect's Node spawner gives it.
56
+const childPath = ({ env, extendEnv }: ChildProcess.CommandOptions) => {
57
+ if (env === undefined) return process.env.PATH;
58
+ if (!Object.hasOwn(env, "PATH")) return extendEnv === true ? process.env.PATH : undefined;
59
+ const value = env.PATH;
60
+ return value === undefined || !Redacted.isRedacted(value) ? value : Redacted.value(value);
61
+};
62
+
63
+// The spawn error Effect's Node spawner reports when execvp fails with `code`.
64
+const spawnFailure = (command: ChildProcess.StandardCommand, code: "ENOENT" | "EACCES") => {
65
+ const syscall = `spawn ${command.command}`;
66
+ return PlatformError.systemError({
67
+ _tag: code === "ENOENT" ? "NotFound" : "PermissionDenied",
68
+ module: "ChildProcess",
69
+ method: "spawn",
70
+ pathOrDescriptor: CommandLine.display([command.command, ...command.args], { format: "posix" }),
71
+ syscall,
72
+ cause: Object.assign(new Error(`${syscall} ${code}`), {
73
+ errno: code === "ENOENT" ? -2 : -13,
74
+ code,
75
+ syscall,
76
+ path: command.command,
77
+ spawnargs: command.args.map((arg) => (Redacted.isRedacted(arg) ? "<redacted>" : arg)),
78
+ }),
79
+ });
80
+};
81
+
82
+// The error of the `FileSystem.access(cwd)` Effect's Node spawner runs before it spawns.
83
+const cwdFailure = (cwd: string, cause: NodeJS.ErrnoException) =>
84
+ PlatformError.systemError({
85
+ _tag:
86
+ cause.code === "ENOENT"
87
+ ? "NotFound"
88
+ : cause.code === "EACCES" || cause.code === "EPERM"
89
+ ? "PermissionDenied"
90
+ : cause.code === "ENOTDIR" || cause.code === "ELOOP"
91
+ ? "BadResource"
92
+ : "Unknown",
93
+ module: "FileSystem",
94
+ method: "access",
95
+ pathOrDescriptor: cwd,
96
+ syscall: cause.syscall,
97
+ cause,
98
+ });
99
+
100
+/**
101
+ * Fails as a native spawn does when the command is missing or not executable: callers read
102
+ * that error to tell a CLI that is not installed from one that failed. execvp reports EACCES
103
+ * when a candidate exists but cannot be run, and ENOENT otherwise.
104
+ */
105
+const findExecutable = Effect.fnUntraced(function* (
106
+ command: ChildProcess.StandardCommand,
107
+ cwd: string | undefined,
108
+) {
109
+ // Joined as text: the kernel resolves `..` after a symlink differently from a normalized path.
110
+ const fromCwd = (path: string) =>
111
+ cwd === undefined || path.startsWith("/") ? path : `${cwd}/${path}`;
112
+ const candidates = command.command.includes("/")
113
+ ? [fromCwd(command.command)]
114
+ : (childPath(command.options) ?? DEFAULT_PATH)
115
+ .split(":")
116
+ .map((entry) => `${fromCwd(entry || ".")}/${command.command}`);
117
+ let denied = false;
118
+ for (const candidate of candidates) {
119
+ const error = yield* check(
120
+ candidate.slice(0, candidate.lastIndexOf("/")) || "/",
121
+ candidate,
122
+ NodeFS.constants.X_OK,
123
+ );
124
+ // Any other errno is left for `env` to report through its exit code.
125
+ if (error === undefined || (error.code !== "ENOENT" && error.code !== "EACCES")) return;
126
+ denied ||= error.code === "EACCES";
127
+ }
128
+ return yield* spawnFailure(command, denied ? "EACCES" : "ENOENT");
129
+});
130
+
131
+const make = Effect.gen(function* () {
132
+ const native = yield* ChildProcessSpawner.ChildProcessSpawner;
133
+ if ((yield* HostProcess.Platform) !== "linux") return native;
134
+ if (!(yield* Effect.promise(supportsEnvChdir))) return native;
135
+ const path = yield* Path.Path;
136
+
137
+ // Runs inside the NonBlockingSpawner.spawn span.
138
+ const prepareStandard = Effect.fnUntraced(function* (input: ChildProcess.StandardCommand) {
139
+ const { cwd: givenCwd, shell, ...options } = input.options;
140
+ // Effect rejects a shell command with arguments, and a NUL, itself.
141
+ if ((shell && input.args.length > 0) || input.command.includes("\0")) return input;
142
+ // Node's shell mode on Unix, spelled out so the trampoline can run it.
143
+ const command = shell
144
+ ? ChildProcess.make(typeof shell === "string" ? shell : "/bin/sh", ["-c", input.command])
145
+ : input;
146
+ // Checked as given and entered resolved, as Effect's Node spawner does.
147
+ const cwd = givenCwd === undefined ? undefined : path.resolve(givenCwd);
148
+ const trampoline = envTrampoline(command.command, command.args, cwd);
149
+ if (trampoline === undefined) return input;
150
+ if (givenCwd !== undefined && cwd !== undefined) {
151
+ const error = yield* check(cwd, givenCwd, NodeFS.constants.F_OK);
152
+ if (error !== undefined) return yield* cwdFailure(givenCwd, error);
153
+ }
154
+ yield* findExecutable(ChildProcess.make(command.command, command.args, options), cwd);
155
+ return ChildProcess.make(trampoline.command, trampoline.args, options);
156
+ });
157
+
158
+ const prepare = (
159
+ command: ChildProcess.Command,
160
+ ): Effect.Effect<ChildProcess.Command, PlatformError.PlatformError> =>
161
+ command._tag === "StandardCommand"
162
+ ? prepareStandard(command)
163
+ : Effect.map(Effect.all([prepare(command.left), prepare(command.right)]), ([left, right]) =>
164
+ ChildProcess.pipeTo(left, right, command.options),
165
+ );
166
+
167
+ return ChildProcessSpawner.make(
168
+ Effect.fn("NonBlockingSpawner.spawn")(function* (command) {
169
+ return yield* native.spawn(yield* prepare(command));
170
+ }),
171
+ );
172
+});
173
+
174
+/**
175
+ * On Linux with GNU `env`, replaces the provided `ChildProcessSpawner` with one that never
176
+ * hands libuv a cwd or a PATH search; elsewhere it passes the provided one through.
177
+ */
178
+export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make);
apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts
+27
@@ -14,10 +14,13 @@ import {
14
buildClaudeCapabilitiesProbeQueryOptions,
15
probeClaudeCapabilities,
16
probeClaudeWorkspaceSnapshot,
17
+ spawnClaudeProbeThroughEnv,
18
} from "./ClaudeProvider.ts";
19
20
vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
21
22
+const hostPath = process.env.PATH;
23
+
24
const decodeClaudeSettings = Schema.decodeEffect(ClaudeSettings);
25
26
it("drops strict MCP mode, and only that, next to an administrator's managed-mcp.json", () => {
@@ -27,6 +30,7 @@ it("drops strict MCP mode, and only that, next to an administrator's managed-mcp
30
environment: { HOME: "/home/user" },
31
cwd: undefined,
32
managedMcpConfig: true,
33
+ spawnThroughEnv: false,
34
});
35
36
// Claude exits before initializing when handed --strict-mcp-config here.
@@ -35,6 +39,29 @@ it("drops strict MCP mode, and only that, next to an administrator's managed-mcp
39
assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false");
40
});
41
42
+// A shell trampoline would not do: dash drops the exported function, and the launcher exits 127.
43
+it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
44
+ "starts a Bash launcher that calls an exported function in the probe's workspace",
45
+ () =>
46
+ Effect.gen(function* () {
47
+ const fileSystem = yield* FileSystem.FileSystem;
48
+ const workspace = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped());
49
+ yield* fileSystem.writeFileString(`${workspace}/claude`, '#!/bin/bash\nt3_launch "$@"\n');
50
+ yield* fileSystem.chmod(`${workspace}/claude`, 0o755);
51
+ const child = spawnClaudeProbeThroughEnv({
52
+ command: "claude",
53
+ args: ["--probe"],
54
+ cwd: workspace,
55
+ env: { PATH: `.:${hostPath}`, "BASH_FUNC_t3_launch%%": '() { echo "$PWD $@"; }' },
56
+ // @effect-diagnostics-next-line abortControllerInEffect:off - The launcher exits on its own.
57
+ signal: new AbortController().signal,
58
+ });
59
+ assert.deepEqual(child.spawnargs.slice(0, 3), ["/usr/bin/env", "-C", workspace]);
60
+ const output = yield* Effect.promise(() => child.stdout.setEncoding("utf8").toArray());
61
+ assert.equal(output.join(""), `${workspace} --probe\n`);
62
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
63
+);
64
+
65
it.effect("reports a deleted worktree's scan as finished, not pending", () =>
66
Effect.gen(function* () {
67
const snapshot = yield* probeClaudeWorkspaceSnapshot(
apps/server/src/provider/ClaudeProvider.ts
+33
@@ -1,3 +1,6 @@
1
+// @effect-diagnostics-next-line nodeBuiltinImport:off -- the SDK's spawn hook returns a Node child process.
2
+import * as NodeChildProcess from "node:child_process";
3
+
4
import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe";
5
import {
6
type ClaudeSettings,
@@ -18,6 +21,8 @@ import * as Result from "effect/Result";
21
import * as Schema from "effect/Schema";
22
import { ChildProcess, ChildProcessSpawner } from "effect/process";
23
import { createModelCapabilities } from "@t3tools/shared/model";
24
+import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline";
25
+import * as HostProcess from "@t3tools/shared/HostProcess";
26
import { resolveSpawnCommand } from "@t3tools/shared/shell";
27
import {
28
query as claudeQuery,
@@ -27,6 +32,7 @@ import {
32
type SDKControlGetUsageResponse,
33
type SDKUserMessage,
34
type SettingSource,
35
+ type SpawnOptions as ClaudeSpawnOptions,
36
} from "@anthropic-ai/claude-agent-sdk";
37
38
import {
@@ -227,14 +233,38 @@ const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [
233
"local",
234
] as const satisfies ReadonlyArray<SettingSource>;
235
236
+/**
237
+ * The SDK's own spawn stats the executable and hands libuv the workspace as cwd, so a mount
238
+ * that stops answering freezes the server. `env` enters the cwd and finds the CLI in the child.
239
+ * A shell would not do: dash drops the exported Bash functions a launcher may call.
240
+ */
241
+export function spawnClaudeProbeThroughEnv({
242
+ command,
243
+ args,
244
+ cwd,
245
+ env,
246
+ signal,
247
+}: ClaudeSpawnOptions) {
248
+ const launch = envTrampoline(command, args, cwd) ?? { command, args, cwd };
249
+ return NodeChildProcess.spawn(launch.command, launch.args, {
250
+ ...("cwd" in launch ? { cwd: launch.cwd } : {}),
251
+ env,
252
+ signal,
253
+ // The probe ignores stderr.
254
+ stdio: ["pipe", "pipe", "ignore"],
255
+ });
256
+}
257
+
258
export function buildClaudeCapabilitiesProbeQueryOptions(input: {
259
readonly executablePath: string;
260
readonly abortController: AbortController;
261
readonly environment: NodeJS.ProcessEnv;
262
readonly cwd: string | undefined;
263
readonly managedMcpConfig: boolean;
264
+ readonly spawnThroughEnv: boolean;
265
}): ClaudeQueryOptions {
266
return {
267
+ ...(input.spawnThroughEnv ? { spawnClaudeCodeProcess: spawnClaudeProbeThroughEnv } : {}),
268
persistSession: false,
269
pathToClaudeCodeExecutable: input.executablePath,
270
abortController: input.abortController,
@@ -464,6 +494,8 @@ const probeClaudeCapabilities = (
494
...(yield* readClaudeSettingsEnv(claudeSettings, cwd, claudeEnvironment)),
495
})
496
: 0;
497
+ const spawnThroughEnv =
498
+ (yield* HostProcess.Platform) === "linux" && (yield* Effect.promise(supportsEnvChdir));
499
return yield* Effect.tryPromise({
500
try: async () => {
501
const q = claudeQuery({
@@ -477,6 +509,7 @@ const probeClaudeCapabilities = (
509
environment: claudeEnvironment,
510
cwd,
511
managedMcpConfig,
512
+ spawnThroughEnv,
513
}),
514
});
515
const init = await q.initializationResult();
apps/server/src/server.ts
+11
-2
@@ -29,6 +29,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
29
30
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
31
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
32
+import * as NonBlockingSpawner from "./process/NonBlockingSpawner.ts";
33
import * as KeepAwake from "./background/KeepAwake.ts";
34
import * as ServerConfig from "./config.ts";
35
import { withUntracedRequests } from "./http.ts";
@@ -382,9 +383,14 @@ const layerHttpServer = Layer.unwrap(
383
},
384
);
385
}),
385
-).pipe(Layer.provide(ManagedPolicy.layer));
386
+).pipe(
387
+ Layer.provide(ManagedPolicy.layer),
388
+ // NodeHttpServer.layer also outputs NodeServices, whose spawner would shadow the wrapped one.
389
+ (layer) => NonBlockingSpawner.layer.pipe(Layer.provideMerge(layer)),
390
+);
391
392
const layerPlatformServices = DocumentText.layer.pipe(
393
+ Layer.provideMerge(NonBlockingSpawner.layer),
394
Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
395
);
396
@@ -1302,4 +1308,7 @@ const layerMakeServer = Layer.unwrap(
1308
}),
1309
).pipe(Layer.provide(ProcessRunner.layer));
1310
1305
-export const runServer = Layer.launch(layerMakeServer);
1311
+export const runServer = Layer.launch(
1312
+ // For the layers above whose spawner requirement is met by the caller's runtime.
1313
+ layerMakeServer.pipe(Layer.provide(NonBlockingSpawner.layer)),
1314
+);
packages/provider-muse/src/server/sdk.test.ts
+23
@@ -290,6 +290,29 @@ describe("Muse launch", () => {
290
}),
291
);
292
293
+ // The SDK spawns natively: libuv would wait on a hung mount under the cwd or PATH.
294
+ it.effect("launches through env on Linux, which enters the cwd and searches PATH", () =>
295
+ Effect.gen(function* () {
296
+ if ((yield* HostProcess.Platform) !== "linux") return;
297
+ const launched = (options: Parameters<typeof createMuseSdkHostEffect>[0]) =>
298
+ Effect.gen(function* () {
299
+ const createHost = vi.fn(async (_options: unknown) => ({}) as MuseSdkHost);
300
+ yield* createMuseSdkHostEffect(options, createHost);
301
+ return createHost.mock.calls[0]?.[0];
302
+ });
303
+ const throughEnv = yield* launched({ binaryPath: "muse", cwd: "/work space" });
304
+ expect(throughEnv).toMatchObject({
305
+ launch: { command: "/usr/bin/env", args: ["-C", "/work space", "--", "muse"] },
306
+ });
307
+ expect(throughEnv).not.toHaveProperty("cwd");
308
+ // env would read this path as an assignment.
309
+ expect(yield* launched({ binaryPath: "/opt/a=b/muse", cwd: "/work" })).toMatchObject({
310
+ launch: { command: "/opt/a=b/muse", args: [] },
311
+ cwd: "/work",
312
+ });
313
+ }),
314
+ );
315
+
316
// cmd's quote rules only show with a real cmd.exe, spawning as the SDK does.
317
it.effect("starts a real launcher from a folder with spaces and cmd metacharacters", () =>
318
Effect.gen(function* () {
packages/provider-muse/src/server/sdk.ts
+14
-2
@@ -10,6 +10,7 @@ import {
10
type SpawnedMspConnection,
11
} from "@muse-code/sdk";
12
import type { RuntimeMode } from "@t3tools/contracts";
13
+import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline";
14
import * as HostProcess from "@t3tools/shared/HostProcess";
15
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
16
import * as Effect from "effect/Effect";
@@ -226,11 +227,22 @@ export const createMuseSdkHostEffect = Effect.fn("createMuseSdkHostEffect")(func
227
options: Omit<MuseSdkHostOptions, "signal">,
228
createHost: typeof createMuseSdkHost = createMuseSdkHost,
229
) {
229
- const launch = options.launch ?? (yield* museLaunch(options.binaryPath, options.environment));
230
+ const native = options.launch ?? (yield* museLaunch(options.binaryPath, options.environment));
231
+ // The Muse SDK hands libuv the cwd and the PATH search, which freeze the server while a
232
+ // mount under either hangs; `env` does both in the child.
233
+ const throughEnv =
234
+ (yield* HostProcess.Platform) === "linux" && (yield* Effect.promise(supportsEnvChdir))
235
+ ? envTrampoline(native.command, native.args, options.cwd)
236
+ : undefined;
237
+ const { cwd: _enteredByEnv, ...withoutCwd } = options;
238
+ const hostOptions =
239
+ throughEnv === undefined
240
+ ? { ...options, launch: native }
241
+ : { ...withoutCwd, launch: throughEnv };
242
let startup: Promise<MuseSdkHost> | undefined;
243
return yield* Effect.tryPromise({
244
try: (signal) => {
233
- startup = createHost({ ...options, launch, signal });
245
+ startup = createHost({ ...hostOptions, signal });
246
return startup;
247
},
248
catch: (cause) => new MuseSdkError({ operation: "start", cause }),
packages/shared/package.json
+4
@@ -99,6 +99,10 @@
99
"types": "./src/shell.ts",
100
"import": "./src/shell.ts"
101
},
102
+ "./envTrampoline": {
103
+ "types": "./src/envTrampoline.ts",
104
+ "import": "./src/envTrampoline.ts"
105
+ },
106
"./semver": {
107
"types": "./src/semver.ts",
108
"import": "./src/semver.ts"
packages/shared/src/envTrampoline.ts
new
+32
@@ -0,0 +1,32 @@
1
+// @effect-diagnostics nodeBuiltinImport:off
2
+import * as NodeChildProcess from "node:child_process";
3
+
4
+const ENV = "/usr/bin/env";
5
+
6
+let chdirSupport: Promise<boolean> | undefined;
7
+
8
+/** Whether `/usr/bin/env` takes `-C` (GNU coreutils 8.28 and later; BusyBox does not). */
9
+export const supportsEnvChdir = (): Promise<boolean> =>
10
+ (chdirSupport ??= new Promise((resolve) =>
11
+ // Run against `/` and absolute paths, so the check itself cannot wait on a mount.
12
+ NodeChildProcess.execFile(ENV, ["-C", "/", "--", "/bin/sh", "-c", ":"], (error) =>
13
+ resolve(error === null),
14
+ ),
15
+ ));
16
+
17
+/**
18
+ * libuv's spawn blocks until the child has run chdir(cwd) and the PATH search, which a hung
19
+ * mount stalls. Through `env` both run after exec, with argv and environment untouched.
20
+ * Undefined when `env` would read the command as `NAME=value` or `-`, which `--` does not stop.
21
+ */
22
+export function envTrampoline<Arg>(
23
+ command: string,
24
+ args: ReadonlyArray<Arg>,
25
+ cwd: string | undefined,
26
+): { readonly command: string; readonly args: Array<Arg | string> } | undefined {
27
+ if (command === "" || command === "-" || command.includes("=")) return undefined;
28
+ return {
29
+ command: ENV,
30
+ args: [...(cwd === undefined ? [] : ["-C", cwd]), "--", command, ...args],
31
+ };
32
+}