Skip to content
TypeScript

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

Utkarsh Patilf460ddb23a49
diff --git a/apps/server/src/os-jank.test.ts b/apps/server/src/os-jank.test.ts
index fef7a2e440e..aaac95bc3e8 100644
--- a/apps/server/src/os-jank.test.ts
+++ b/apps/server/src/os-jank.test.ts
@@ -143,7 +143,7 @@ effectIt.effect("replaces a Path-spelled Windows PATH instead of adding a second
yield* fixPath().pipe(
Effect.provideService(HostProcess.Platform, "win32"),
Effect.provideService(HostProcess.Environment, env),
- Effect.provideService(WindowsShellEnvironment, () => ({ PATH: "C:\\Tools" })),
+ Effect.provideService(WindowsShellEnvironment, () => Effect.succeed({ PATH: "C:\\Tools" })),
Effect.provideService(CommandAvailability, () => Effect.succeed(true)),
Effect.provide(NodeServices.layer),
);
diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts
index 5940ef6bfeb..b7a656c885d 100644
--- a/packages/shared/src/shell.test.ts
+++ b/packages/shared/src/shell.test.ts
@@ -3,8 +3,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { it as effectIt } from "@effect/vitest";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
+import * as Option from "effect/Option";
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
@@ -33,13 +35,26 @@ import {
XcodeGitLocation,
} from "./shell.ts";
+const nativeProbe = vi.hoisted(() => ({
+ execFile: vi.fn<typeof import("node:child_process").execFile>(),
+}));
+
+vi.mock("node:child_process", async (importOriginal) => {
+ const original = await importOriginal<typeof import("node:child_process")>();
+ return { ...original, execFile: nativeProbe.execFile.mockImplementation(original.execFile) };
+});
+
const withWindowsEnvironmentMocks = <A, E, R>(
effect: Effect.Effect<A, E, R>,
- readEnvironment: WindowsShellEnvironmentReader,
+ readEnvironment: (
+ ...args: Parameters<WindowsShellEnvironmentReader>
+ ) => Partial<Record<string, string>>,
commandAvailable: CommandAvailabilityChecker,
) =>
effect.pipe(
- Effect.provideService(WindowsShellEnvironment, readEnvironment),
+ Effect.provideService(WindowsShellEnvironment, (...args) =>
+ Effect.sync(() => readEnvironment(...args)),
+ ),
Effect.provideService(CommandAvailability, commandAvailable),
);
@@ -178,49 +193,207 @@ describe("mergePathEntries", () => {
});
describe("readEnvironmentFromWindowsShell", () => {
- it("strips CRLF delimiters from captured PowerShell values", () => {
- const execFile = vi.fn<
- (
- file: string,
- args: ReadonlyArray<string>,
- options: { encoding: "utf8"; timeout: number },
- ) => string
- >(
- () =>
- "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
- );
+ effectIt.effect("yields while the native shell probe is pending", () =>
+ Effect.gen(function* () {
+ let completed = false;
+ const [environment, completedBeforeProbeReturned] = yield* Effect.all(
+ [
+ readEnvironmentFromWindowsShell(["PATH"]).pipe(
+ Effect.tap(() =>
+ Effect.sync(() => {
+ completed = true;
+ }),
+ ),
+ ),
+ Effect.sync(() => completed),
+ ],
+ { concurrency: 2 },
+ );
+ expect(completedBeforeProbeReturned).toBe(false);
+ expect(environment).toBeTypeOf("object");
+ }),
+ );
- expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
- FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
- });
+ effectIt.layer(NodeServices.layer)("synchronous spawn failures", (it) => {
+ it.effect("tries both shells and preserves baseline PATH repair", () =>
+ Effect.gen(function* () {
+ const execFile = nativeProbe.execFile;
+ execFile.mockImplementationOnce(() => {
+ throw new Error("spawn EPERM");
+ });
+ execFile.mockImplementationOnce(() => {
+ throw new Error("spawn EINVAL");
+ });
+ try {
+ const patch = yield* resolveWindowsEnvironment({
+ PATH: "C:\\Windows",
+ APPDATA: "C:\\Roaming",
+ }).pipe(Effect.provideService(CommandAvailability, () => Effect.succeed(true)));
+ expect(patch).toEqual({ PATH: "C:\\Windows;C:\\Roaming\\npm" });
+ expect(execFile.mock.calls.slice(-2).map(([file]) => file)).toEqual([
+ "pwsh.exe",
+ "powershell.exe",
+ ]);
+ } finally {
+ execFile.mockClear();
+ }
+ }),
+ );
});
- it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
- const execFile = vi.fn<
- (
- file: string,
- args: ReadonlyArray<string>,
- options: { encoding: "utf8"; timeout: number },
- ) => string
- >((file) => {
- if (file === "pwsh.exe") {
- throw new Error("spawn pwsh.exe ENOENT");
- }
- return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
- });
+ effectIt.effect("returns an empty environment after both shell candidates fail", () =>
+ Effect.gen(function* () {
+ const execFile = vi.fn(() => Effect.succeed(Option.none<string>()));
+ expect(yield* readEnvironmentFromWindowsShell(["PATH"], {}, execFile)).toEqual({});
+ expect(execFile).toHaveBeenCalledTimes(2);
+ }),
+ );
- expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
- PATH: "C:\\Tools",
- });
- expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
- encoding: "utf8",
- timeout: 5000,
- });
- expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
- encoding: "utf8",
- timeout: 5000,
- });
- });
+ effectIt.effect("does not launch a shell when no variables are requested", () =>
+ Effect.gen(function* () {
+ const execFile = vi.fn(() => Effect.succeed(Option.none<string>()));
+ expect(yield* readEnvironmentFromWindowsShell([], {}, execFile)).toEqual({});
+ expect(execFile).not.toHaveBeenCalled();
+ }),
+ );
+
+ effectIt.effect(
+ "kills the native probe child on interruption without trying the next shell",
+ () =>
+ Effect.gen(function* () {
+ const started = Promise.withResolvers<void>();
+ const kill = vi.fn(() => true);
+ const child = { kill } as unknown as ReturnType<
+ typeof import("node:child_process").execFile
+ >;
+ const execFile = nativeProbe.execFile;
+ execFile.mockClear();
+ execFile.mockImplementationOnce(() => {
+ started.resolve();
+ return child;
+ });
+ try {
+ const fiber = yield* readEnvironmentFromWindowsShell(["PATH"]).pipe(Effect.forkChild);
+ yield* Effect.promise(() => started.promise);
+ yield* Fiber.interrupt(fiber);
+ expect(kill).toHaveBeenCalledTimes(1);
+ expect(execFile).toHaveBeenCalledTimes(1);
+ expect(execFile.mock.calls[0]?.[0]).toBe("pwsh.exe");
+ } finally {
+ execFile.mockClear();
+ }
+ }),
+ );
+
+ effectIt.effect("extracts environment variables from a PowerShell command", () =>
+ Effect.gen(function* () {
+ const execFile = vi.fn<
+ (
+ file: string,
+ args: ReadonlyArray<string>,
+ options: { encoding: "utf8"; timeout: number },
+ ) => string
+ >(
+ () =>
+ "__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
+ );
+
+ expect(
+ yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
+ Effect.try(() => execFile(...args)).pipe(Effect.option),
+ ),
+ ).toEqual({
+ PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
+ });
+ expect(execFile).toHaveBeenCalledWith(
+ "pwsh.exe",
+ expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
+ { encoding: "utf8", timeout: 5000 },
+ );
+ }),
+ );
+
+ effectIt.effect("strips CRLF delimiters from captured PowerShell values", () =>
+ Effect.gen(function* () {
+ const execFile = vi.fn<
+ (
+ file: string,
+ args: ReadonlyArray<string>,
+ options: { encoding: "utf8"; timeout: number },
+ ) => string
+ >(
+ () =>
+ "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
+ );
+
+ expect(
+ yield* readEnvironmentFromWindowsShell(["FNM_DIR"], {}, (...args) =>
+ Effect.try(() => execFile(...args)).pipe(Effect.option),
+ ),
+ ).toEqual({
+ FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
+ });
+ }),
+ );
+
+ effectIt.effect("omits -NoProfile when loadProfile is enabled", () =>
+ Effect.gen(function* () {
+ const execFile = vi.fn<
+ (
+ file: string,
+ args: ReadonlyArray<string>,
+ options: { encoding: "utf8"; timeout: number },
+ ) => string
+ >(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
+
+ expect(
+ yield* readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, (...args) =>
+ Effect.try(() => execFile(...args)).pipe(Effect.option),
+ ),
+ ).toEqual({
+ PATH: "C:\\Tools",
+ });
+ expect(execFile).toHaveBeenCalledWith(
+ "pwsh.exe",
+ expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
+ { encoding: "utf8", timeout: 5000 },
+ );
+ expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
+ }),
+ );
+
+ effectIt.effect("falls back to Windows PowerShell when pwsh.exe is unavailable", () =>
+ Effect.gen(function* () {
+ const execFile = vi.fn<
+ (
+ file: string,
+ args: ReadonlyArray<string>,
+ options: { encoding: "utf8"; timeout: number },
+ ) => string
+ >((file) => {
+ if (file === "pwsh.exe") {
+ throw new Error("spawn pwsh.exe ENOENT");
+ }
+ return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
+ });
+
+ expect(
+ yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
+ Effect.try(() => execFile(...args)).pipe(Effect.option),
+ ),
+ ).toEqual({
+ PATH: "C:\\Tools",
+ });
+ expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
+ encoding: "utf8",
+ timeout: 5000,
+ });
+ expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
+ encoding: "utf8",
+ timeout: 5000,
+ });
+ }),
+ );
});
describe("mergePathValues", () => {
diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts
index 0d1ba878526..df3d32747c2 100644
--- a/packages/shared/src/shell.ts
+++ b/packages/shared/src/shell.ts
@@ -323,7 +323,7 @@ export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
export type WindowsShellEnvironmentReader = (
names: ReadonlyArray<string>,
options?: WindowsEnvironmentProbeOptions,
-) => Partial<Record<string, string>>;
+) => Effect.Effect<Partial<Record<string, string>>>;
export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
"@t3tools/shared/shell/WindowsShellEnvironment",
@@ -339,59 +339,62 @@ export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>
},
);
-export function readEnvironmentFromWindowsShell(
- names: ReadonlyArray<string>,
- execFile?: ExecFileSyncLike,
-): Partial<Record<string, string>>;
-export function readEnvironmentFromWindowsShell(
- names: ReadonlyArray<string>,
- options?: WindowsEnvironmentProbeOptions,
- execFile?: ExecFileSyncLike,
-): Partial<Record<string, string>>;
-export function readEnvironmentFromWindowsShell(
- names: ReadonlyArray<string>,
- optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
- maybeExecFile?: ExecFileSyncLike,
-): Partial<Record<string, string>> {
- if (names.length === 0) {
- return {};
- }
-
- const options =
- typeof optionsOrExecFile === "function"
- ? ({} satisfies WindowsEnvironmentProbeOptions)
- : (optionsOrExecFile ?? {});
- const execFile: ExecFileSyncLike =
- typeof optionsOrExecFile === "function"
- ? optionsOrExecFile
- : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));
- const command = buildWindowsEnvironmentCaptureCommand(names);
- const args = [
- "-NoLogo",
- ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
- "-NonInteractive",
- "-Command",
- command,
- ];
- for (const shell of WINDOWS_SHELL_CANDIDATES) {
+const execWindowsEnvironmentProbe = (
+ file: string,
+ args: ReadonlyArray<string>,
+ options: { encoding: "utf8"; timeout: number },
+) =>
+ Effect.callback<Option.Option<string>>((resume) => {
+ let child: NodeChildProcess.ChildProcess;
try {
- const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
+ child = NodeChildProcess.execFile(
+ file,
+ args,
+ { ...options, windowsHide: true },
+ (error, stdout) => {
+ resume(Effect.succeed(error ? Option.none() : Option.some(stdout)));
+ },
+ );
+ } catch {
+ resume(Effect.succeedNone);
+ return;
+ }
+ return Effect.sync(() => {
+ child.kill();
+ });
+ });
+
+export const readEnvironmentFromWindowsShell = Effect.fn("shell.readEnvironmentFromWindowsShell")(
+ function* (
+ names: ReadonlyArray<string>,
+ options: WindowsEnvironmentProbeOptions = {},
+ execFile: typeof execWindowsEnvironmentProbe = execWindowsEnvironmentProbe,
+ ) {
+ if (names.length === 0) return {};
+
+ const command = buildWindowsEnvironmentCaptureCommand(names);
+ const args = [
+ "-NoLogo",
+ ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
+ "-NonInteractive",
+ "-Command",
+ command,
+ ];
+ for (const shell of WINDOWS_SHELL_CANDIDATES) {
+ const output = yield* execFile(shell, args, { encoding: "utf8", timeout: 5000 });
+ if (Option.isNone(output)) continue;
const environment: Partial<Record<string, string>> = {};
for (const name of names) {
- const value = extractEnvironmentValue(output, name);
- if (value !== undefined) {
- environment[name] = value;
- }
+ const value = extractEnvironmentValue(output.value, name);
+ if (value !== undefined) environment[name] = value;
}
return environment;
- } catch {
- continue;
}
- }
- return {};
-}
+ return {};
+ },
+);
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
@@ -930,18 +933,6 @@ function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<strin
];
}
-function readWindowsEnvironmentSafely(
- readEnvironment: WindowsShellEnvironmentReader,
- names: ReadonlyArray<string>,
- options?: WindowsEnvironmentProbeOptions,
-): Partial<Record<string, string>> {
- try {
- return readEnvironment(names, options);
- } catch {
- return {};
- }
-}
-
/** Keep one PATH spelling in copied Windows environment records. */
export function setWindowsPath(env: NodeJS.ProcessEnv, value: string): void {
for (const key of Object.keys(env)) {
@@ -974,9 +965,7 @@ export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironm
const readEnvironment = yield* WindowsShellEnvironment;
const commandAvailable = yield* CommandAvailability;
const inheritedPath = readEnvPath(env);
- const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
- loadProfile: false,
- }).PATH;
+ const shellPath = (yield* readEnvironment(["PATH"], { loadProfile: false })).PATH;
const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
@@ -987,11 +976,9 @@ export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironm
return baselinePatch;
}
- const profiledEnvironment = readWindowsEnvironmentSafely(
- readEnvironment,
- ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
- { loadProfile: true },
- );
+ const profiledEnvironment = yield* readEnvironment(["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"], {
+ loadProfile: true,
+ });
const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
const profiledPatch: Partial<NodeJS.ProcessEnv> = {
...(profiledPath ? { PATH: profiledPath } : {}),