@devries-cameron20 / t3code-1 / commits / f460ddb23a
Fork 0

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

fix(server): probe the Windows startup environment asynchronously (#21720)

Utkarsh Patil committed Oct 22, 2026 at 22:53 UTC f460ddb23a49e459575f6dbcc0101212d8640a2e
3 files changed +268 -108
apps/server/src/os-jank.test.ts
+1 -1
@@ -143,7 +143,7 @@ effectIt.effect("replaces a Path-spelled Windows PATH instead of adding a second
143 yield* fixPath().pipe(
144 Effect.provideService(HostProcess.Platform, "win32"),
145 Effect.provideService(HostProcess.Environment, env),
146 - Effect.provideService(WindowsShellEnvironment, () => ({ PATH: "C:\\Tools" })),
146 + Effect.provideService(WindowsShellEnvironment, () => Effect.succeed({ PATH: "C:\\Tools" })),
147 Effect.provideService(CommandAvailability, () => Effect.succeed(true)),
148 Effect.provide(NodeServices.layer),
149 );
packages/shared/src/shell.test.ts
+214 -41
@@ -3,8 +3,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { it as effectIt } from "@effect/vitest";
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 import * as Effect from "effect/Effect";
6 +import * as Fiber from "effect/Fiber";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Path from "effect/Path";
9 +import * as Option from "effect/Option";
10 import * as NodeChildProcess from "node:child_process";
11 import * as NodeFS from "node:fs";
12 import * as NodeOS from "node:os";
@@ -33,13 +35,26 @@ import {
35 XcodeGitLocation,
36 } from "./shell.ts";
37
38 +const nativeProbe = vi.hoisted(() => ({
39 + execFile: vi.fn<typeof import("node:child_process").execFile>(),
40 +}));
41 +
42 +vi.mock("node:child_process", async (importOriginal) => {
43 + const original = await importOriginal<typeof import("node:child_process")>();
44 + return { ...original, execFile: nativeProbe.execFile.mockImplementation(original.execFile) };
45 +});
46 +
47 const withWindowsEnvironmentMocks = <A, E, R>(
48 effect: Effect.Effect<A, E, R>,
38 - readEnvironment: WindowsShellEnvironmentReader,
49 + readEnvironment: (
50 + ...args: Parameters<WindowsShellEnvironmentReader>
51 + ) => Partial<Record<string, string>>,
52 commandAvailable: CommandAvailabilityChecker,
53 ) =>
54 effect.pipe(
42 - Effect.provideService(WindowsShellEnvironment, readEnvironment),
55 + Effect.provideService(WindowsShellEnvironment, (...args) =>
56 + Effect.sync(() => readEnvironment(...args)),
57 + ),
58 Effect.provideService(CommandAvailability, commandAvailable),
59 );
60
@@ -178,49 +193,207 @@ describe("mergePathEntries", () => {
193 });
194
195 describe("readEnvironmentFromWindowsShell", () => {
181 - it("strips CRLF delimiters from captured PowerShell values", () => {
182 - const execFile = vi.fn<
183 - (
184 - file: string,
185 - args: ReadonlyArray<string>,
186 - options: { encoding: "utf8"; timeout: number },
187 - ) => string
188 - >(
189 - () =>
190 - "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
191 - );
196 + effectIt.effect("yields while the native shell probe is pending", () =>
197 + Effect.gen(function* () {
198 + let completed = false;
199 + const [environment, completedBeforeProbeReturned] = yield* Effect.all(
200 + [
201 + readEnvironmentFromWindowsShell(["PATH"]).pipe(
202 + Effect.tap(() =>
203 + Effect.sync(() => {
204 + completed = true;
205 + }),
206 + ),
207 + ),
208 + Effect.sync(() => completed),
209 + ],
210 + { concurrency: 2 },
211 + );
212 + expect(completedBeforeProbeReturned).toBe(false);
213 + expect(environment).toBeTypeOf("object");
214 + }),
215 + );
216
193 - expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
194 - FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
195 - });
217 + effectIt.layer(NodeServices.layer)("synchronous spawn failures", (it) => {
218 + it.effect("tries both shells and preserves baseline PATH repair", () =>
219 + Effect.gen(function* () {
220 + const execFile = nativeProbe.execFile;
221 + execFile.mockImplementationOnce(() => {
222 + throw new Error("spawn EPERM");
223 + });
224 + execFile.mockImplementationOnce(() => {
225 + throw new Error("spawn EINVAL");
226 + });
227 + try {
228 + const patch = yield* resolveWindowsEnvironment({
229 + PATH: "C:\\Windows",
230 + APPDATA: "C:\\Roaming",
231 + }).pipe(Effect.provideService(CommandAvailability, () => Effect.succeed(true)));
232 + expect(patch).toEqual({ PATH: "C:\\Windows;C:\\Roaming\\npm" });
233 + expect(execFile.mock.calls.slice(-2).map(([file]) => file)).toEqual([
234 + "pwsh.exe",
235 + "powershell.exe",
236 + ]);
237 + } finally {
238 + execFile.mockClear();
239 + }
240 + }),
241 + );
242 });
243
198 - it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
199 - const execFile = vi.fn<
200 - (
201 - file: string,
202 - args: ReadonlyArray<string>,
203 - options: { encoding: "utf8"; timeout: number },
204 - ) => string
205 - >((file) => {
206 - if (file === "pwsh.exe") {
207 - throw new Error("spawn pwsh.exe ENOENT");
208 - }
209 - return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
210 - });
244 + effectIt.effect("returns an empty environment after both shell candidates fail", () =>
245 + Effect.gen(function* () {
246 + const execFile = vi.fn(() => Effect.succeed(Option.none<string>()));
247 + expect(yield* readEnvironmentFromWindowsShell(["PATH"], {}, execFile)).toEqual({});
248 + expect(execFile).toHaveBeenCalledTimes(2);
249 + }),
250 + );
251
212 - expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
213 - PATH: "C:\\Tools",
214 - });
215 - expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
216 - encoding: "utf8",
217 - timeout: 5000,
218 - });
219 - expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
220 - encoding: "utf8",
221 - timeout: 5000,
222 - });
223 - });
252 + effectIt.effect("does not launch a shell when no variables are requested", () =>
253 + Effect.gen(function* () {
254 + const execFile = vi.fn(() => Effect.succeed(Option.none<string>()));
255 + expect(yield* readEnvironmentFromWindowsShell([], {}, execFile)).toEqual({});
256 + expect(execFile).not.toHaveBeenCalled();
257 + }),
258 + );
259 +
260 + effectIt.effect(
261 + "kills the native probe child on interruption without trying the next shell",
262 + () =>
263 + Effect.gen(function* () {
264 + const started = Promise.withResolvers<void>();
265 + const kill = vi.fn(() => true);
266 + const child = { kill } as unknown as ReturnType<
267 + typeof import("node:child_process").execFile
268 + >;
269 + const execFile = nativeProbe.execFile;
270 + execFile.mockClear();
271 + execFile.mockImplementationOnce(() => {
272 + started.resolve();
273 + return child;
274 + });
275 + try {
276 + const fiber = yield* readEnvironmentFromWindowsShell(["PATH"]).pipe(Effect.forkChild);
277 + yield* Effect.promise(() => started.promise);
278 + yield* Fiber.interrupt(fiber);
279 + expect(kill).toHaveBeenCalledTimes(1);
280 + expect(execFile).toHaveBeenCalledTimes(1);
281 + expect(execFile.mock.calls[0]?.[0]).toBe("pwsh.exe");
282 + } finally {
283 + execFile.mockClear();
284 + }
285 + }),
286 + );
287 +
288 + effectIt.effect("extracts environment variables from a PowerShell command", () =>
289 + Effect.gen(function* () {
290 + const execFile = vi.fn<
291 + (
292 + file: string,
293 + args: ReadonlyArray<string>,
294 + options: { encoding: "utf8"; timeout: number },
295 + ) => string
296 + >(
297 + () =>
298 + "__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
299 + );
300 +
301 + expect(
302 + yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
303 + Effect.try(() => execFile(...args)).pipe(Effect.option),
304 + ),
305 + ).toEqual({
306 + PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
307 + });
308 + expect(execFile).toHaveBeenCalledWith(
309 + "pwsh.exe",
310 + expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
311 + { encoding: "utf8", timeout: 5000 },
312 + );
313 + }),
314 + );
315 +
316 + effectIt.effect("strips CRLF delimiters from captured PowerShell values", () =>
317 + Effect.gen(function* () {
318 + const execFile = vi.fn<
319 + (
320 + file: string,
321 + args: ReadonlyArray<string>,
322 + options: { encoding: "utf8"; timeout: number },
323 + ) => string
324 + >(
325 + () =>
326 + "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
327 + );
328 +
329 + expect(
330 + yield* readEnvironmentFromWindowsShell(["FNM_DIR"], {}, (...args) =>
331 + Effect.try(() => execFile(...args)).pipe(Effect.option),
332 + ),
333 + ).toEqual({
334 + FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
335 + });
336 + }),
337 + );
338 +
339 + effectIt.effect("omits -NoProfile when loadProfile is enabled", () =>
340 + Effect.gen(function* () {
341 + const execFile = vi.fn<
342 + (
343 + file: string,
344 + args: ReadonlyArray<string>,
345 + options: { encoding: "utf8"; timeout: number },
346 + ) => string
347 + >(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
348 +
349 + expect(
350 + yield* readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, (...args) =>
351 + Effect.try(() => execFile(...args)).pipe(Effect.option),
352 + ),
353 + ).toEqual({
354 + PATH: "C:\\Tools",
355 + });
356 + expect(execFile).toHaveBeenCalledWith(
357 + "pwsh.exe",
358 + expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
359 + { encoding: "utf8", timeout: 5000 },
360 + );
361 + expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
362 + }),
363 + );
364 +
365 + effectIt.effect("falls back to Windows PowerShell when pwsh.exe is unavailable", () =>
366 + Effect.gen(function* () {
367 + const execFile = vi.fn<
368 + (
369 + file: string,
370 + args: ReadonlyArray<string>,
371 + options: { encoding: "utf8"; timeout: number },
372 + ) => string
373 + >((file) => {
374 + if (file === "pwsh.exe") {
375 + throw new Error("spawn pwsh.exe ENOENT");
376 + }
377 + return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
378 + });
379 +
380 + expect(
381 + yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
382 + Effect.try(() => execFile(...args)).pipe(Effect.option),
383 + ),
384 + ).toEqual({
385 + PATH: "C:\\Tools",
386 + });
387 + expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
388 + encoding: "utf8",
389 + timeout: 5000,
390 + });
391 + expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
392 + encoding: "utf8",
393 + timeout: 5000,
394 + });
395 + }),
396 + );
397 });
398
399 describe("mergePathValues", () => {
packages/shared/src/shell.ts
+53 -66
@@ -323,7 +323,7 @@ export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
323 export type WindowsShellEnvironmentReader = (
324 names: ReadonlyArray<string>,
325 options?: WindowsEnvironmentProbeOptions,
326 -) => Partial<Record<string, string>>;
326 +) => Effect.Effect<Partial<Record<string, string>>>;
327
328 export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
329 "@t3tools/shared/shell/WindowsShellEnvironment",
@@ -339,59 +339,62 @@ export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>
339 },
340 );
341
342 -export function readEnvironmentFromWindowsShell(
343 - names: ReadonlyArray<string>,
344 - execFile?: ExecFileSyncLike,
345 -): Partial<Record<string, string>>;
346 -export function readEnvironmentFromWindowsShell(
347 - names: ReadonlyArray<string>,
348 - options?: WindowsEnvironmentProbeOptions,
349 - execFile?: ExecFileSyncLike,
350 -): Partial<Record<string, string>>;
351 -export function readEnvironmentFromWindowsShell(
352 - names: ReadonlyArray<string>,
353 - optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
354 - maybeExecFile?: ExecFileSyncLike,
355 -): Partial<Record<string, string>> {
356 - if (names.length === 0) {
357 - return {};
358 - }
359 -
360 - const options =
361 - typeof optionsOrExecFile === "function"
362 - ? ({} satisfies WindowsEnvironmentProbeOptions)
363 - : (optionsOrExecFile ?? {});
364 - const execFile: ExecFileSyncLike =
365 - typeof optionsOrExecFile === "function"
366 - ? optionsOrExecFile
367 - : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));
368 - const command = buildWindowsEnvironmentCaptureCommand(names);
369 - const args = [
370 - "-NoLogo",
371 - ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
372 - "-NonInteractive",
373 - "-Command",
374 - command,
375 - ];
376 - for (const shell of WINDOWS_SHELL_CANDIDATES) {
342 +const execWindowsEnvironmentProbe = (
343 + file: string,
344 + args: ReadonlyArray<string>,
345 + options: { encoding: "utf8"; timeout: number },
346 +) =>
347 + Effect.callback<Option.Option<string>>((resume) => {
348 + let child: NodeChildProcess.ChildProcess;
349 try {
378 - const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
350 + child = NodeChildProcess.execFile(
351 + file,
352 + args,
353 + { ...options, windowsHide: true },
354 + (error, stdout) => {
355 + resume(Effect.succeed(error ? Option.none() : Option.some(stdout)));
356 + },
357 + );
358 + } catch {
359 + resume(Effect.succeedNone);
360 + return;
361 + }
362 + return Effect.sync(() => {
363 + child.kill();
364 + });
365 + });
366 +
367 +export const readEnvironmentFromWindowsShell = Effect.fn("shell.readEnvironmentFromWindowsShell")(
368 + function* (
369 + names: ReadonlyArray<string>,
370 + options: WindowsEnvironmentProbeOptions = {},
371 + execFile: typeof execWindowsEnvironmentProbe = execWindowsEnvironmentProbe,
372 + ) {
373 + if (names.length === 0) return {};
374 +
375 + const command = buildWindowsEnvironmentCaptureCommand(names);
376 + const args = [
377 + "-NoLogo",
378 + ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
379 + "-NonInteractive",
380 + "-Command",
381 + command,
382 + ];
383 + for (const shell of WINDOWS_SHELL_CANDIDATES) {
384 + const output = yield* execFile(shell, args, { encoding: "utf8", timeout: 5000 });
385 + if (Option.isNone(output)) continue;
386
387 const environment: Partial<Record<string, string>> = {};
388 for (const name of names) {
382 - const value = extractEnvironmentValue(output, name);
383 - if (value !== undefined) {
384 - environment[name] = value;
385 - }
389 + const value = extractEnvironmentValue(output.value, name);
390 + if (value !== undefined) environment[name] = value;
391 }
392 return environment;
388 - } catch {
389 - continue;
393 }
391 - }
394
393 - return {};
394 -}
395 + return {};
396 + },
397 +);
398
399 function stripWrappingQuotes(value: string): string {
400 return value.replace(/^"+|"+$/g, "");
@@ -930,18 +933,6 @@ function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<strin
933 ];
934 }
935
933 -function readWindowsEnvironmentSafely(
934 - readEnvironment: WindowsShellEnvironmentReader,
935 - names: ReadonlyArray<string>,
936 - options?: WindowsEnvironmentProbeOptions,
937 -): Partial<Record<string, string>> {
938 - try {
939 - return readEnvironment(names, options);
940 - } catch {
941 - return {};
942 - }
943 -}
944 -
936 /** Keep one PATH spelling in copied Windows environment records. */
937 export function setWindowsPath(env: NodeJS.ProcessEnv, value: string): void {
938 for (const key of Object.keys(env)) {
@@ -974,9 +965,7 @@ export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironm
965 const readEnvironment = yield* WindowsShellEnvironment;
966 const commandAvailable = yield* CommandAvailability;
967 const inheritedPath = readEnvPath(env);
977 - const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
978 - loadProfile: false,
979 - }).PATH;
968 + const shellPath = (yield* readEnvironment(["PATH"], { loadProfile: false })).PATH;
969 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
970 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
971 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
@@ -987,11 +976,9 @@ export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironm
976 return baselinePatch;
977 }
978
990 - const profiledEnvironment = readWindowsEnvironmentSafely(
991 - readEnvironment,
992 - ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
993 - { loadProfile: true },
994 - );
979 + const profiledEnvironment = yield* readEnvironment(["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"], {
980 + loadProfile: true,
981 + });
982 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
983 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
984 ...(profiledPath ? { PATH: profiledPath } : {}),