Improve Windows/WSL command resolution and process handling

- Extract shared command/path executable resolution into `commandResolution`
- Resolve Windows relative launchers from `cwd` and fix batch argument quoting
- Use managed Effect runtime lifecycle in `CodexAppServerManager`
- Surface signal-based provider health failures clearly and expand tests
- Exclude `*.browser.ts(x)` from web TypeScript project
This commit is contained in:
Julius Marminge committed 2026-03-05 14:31:11 -08:00
1 parent c11666f8bc
commit aff26b834e
10 files changed
+382 -323

No files matched your search

@@ -179,6 +179,13 @@ describe("messageFromCodexProcessCause", () => {
});
});
describe("constructor", () => {
it("supports the optional no-services path without unsafe casting", () => {
const manager = new CodexAppServerManager();
expect(() => manager.stopAll()).not.toThrow();
});
});
describe("startSession", () => {
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
const manager = createManager();
+18 -9
View File
@@ -16,8 +16,8 @@ import {
type ProviderSessionStartInput,
type ProviderTurnStartResult,
} from "@t3tools/contracts";
import type * as NodeServices from "@effect/platform-node/NodeServices";
import { Cause, Effect, Exit, ServiceMap, Scope, Stream } from "effect";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Cause, Effect, Exit, ManagedRuntime, ServiceMap, Scope, Stream } from "effect";
import type { ChildProcessSpawner } from "effect/unstable/process";
import { makeRuntimeCommand, spawnManagedCommand } from "./processRunner";
@@ -164,6 +164,9 @@ export interface CodexAppServerManagerEvents {
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();
private readonly ownedRuntime:
| ManagedRuntime.ManagedRuntime<NodeServices.NodeServices, unknown>
| null;
private readonly runPromise: <A, E>(
effect: Effect.Effect<A, E, NodeServices.NodeServices>,
options?: Effect.RunOptions | undefined,
@@ -171,13 +174,15 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
constructor(services?: ServiceMap.ServiceMap<NodeServices.NodeServices>) {
super();
this.runPromise = services
? Effect.runPromiseWith(services)
: ((effect, options) =>
Effect.runPromise(
effect as unknown as Effect.Effect<unknown, never>,
options,
)) as typeof this.runPromise;
if (services) {
this.ownedRuntime = null;
this.runPromise = Effect.runPromiseWith(services);
return;
}
const runtime = ManagedRuntime.make(NodeServices.layer);
this.ownedRuntime = runtime;
this.runPromise = runtime.runPromise.bind(runtime);
}
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
@@ -520,6 +525,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
for (const sessionId of this.sessions.keys()) {
this.stopSession(sessionId);
}
if (this.ownedRuntime) {
void this.ownedRuntime.dispose();
}
}
private requireSession(sessionId: ProviderSessionId): CodexSessionContext {
+92
View File
@@ -0,0 +1,92 @@
import { accessSync, constants, statSync } from "node:fs";
import { extname, isAbsolute, resolve } from "node:path";
export function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
export function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return env.PATH ?? env.Path ?? env.path ?? "";
}
export function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
export function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
if (platform !== "win32") {
return [command];
}
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]),
);
}
const candidates: string[] = [command];
for (const candidateExtension of windowsPathExtensions) {
candidates.push(`${command}${candidateExtension}`);
candidates.push(`${command}${candidateExtension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
interface ResolveExecutableFileOptions {
readonly platform: NodeJS.Platform;
readonly windowsPathExtensions: ReadonlyArray<string>;
readonly cwd?: string | undefined;
}
export function resolveExecutableFile(
filePath: string,
options: ResolveExecutableFileOptions,
): string | null {
const candidatePath =
options.cwd !== undefined && !isAbsolute(filePath) ? resolve(options.cwd, filePath) : filePath;
try {
const stat = statSync(candidatePath);
if (!stat.isFile()) return null;
if (options.platform === "win32") {
const extension = extname(candidatePath);
if (extension.length === 0) return null;
return options.windowsPathExtensions.includes(extension.toUpperCase()) ? candidatePath : null;
}
accessSync(candidatePath, constants.X_OK);
return candidatePath;
} catch {
return null;
}
}
export function isExecutableFile(
filePath: string,
options: ResolveExecutableFileOptions,
): boolean {
return resolveExecutableFile(filePath, options) !== null;
}
+156 -141
View File
@@ -1,8 +1,9 @@
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, describe, it } from "@effect/vitest";
import { describe, expect, it } from "vitest";
import {
isCommandAvailable,
@@ -12,117 +13,130 @@ import {
resolveEditorLaunch,
} from "./open";
import { Effect } from "effect";
import { assertSuccess } from "@effect/vitest/utils";
describe("resolveEditorLaunch", () => {
it.effect("returns commands for command-based editors", () =>
Effect.gen(function* () {
const cursorLaunch = yield* resolveEditorLaunch(
it("returns commands for command-based editors", async () => {
const cursorLaunch = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "cursor" },
{ platform: "darwin" },
);
assert.deepEqual(cursorLaunch, {
command: "cursor",
args: ["/tmp/workspace"],
});
),
);
assert.deepEqual(cursorLaunch, {
command: "cursor",
args: ["/tmp/workspace"],
});
const vscodeLaunch = yield* resolveEditorLaunch(
const vscodeLaunch = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode" },
{ platform: "darwin" },
);
assert.deepEqual(vscodeLaunch, {
command: "code",
args: ["/tmp/workspace"],
});
),
);
assert.deepEqual(vscodeLaunch, {
command: "code",
args: ["/tmp/workspace"],
});
const zedLaunch = yield* resolveEditorLaunch(
const zedLaunch = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "zed" },
{ platform: "darwin" },
);
assert.deepEqual(zedLaunch, {
command: "zed",
args: ["/tmp/workspace"],
});
}),
);
),
);
assert.deepEqual(zedLaunch, {
command: "zed",
args: ["/tmp/workspace"],
});
});
it.effect("uses --goto when editor supports line/column suffixes", () =>
Effect.gen(function* () {
const lineOnly = yield* resolveEditorLaunch(
it("uses --goto when editor supports line/column suffixes", async () => {
const lineOnly = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
{ platform: "darwin" },
);
assert.deepEqual(lineOnly, {
command: "cursor",
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
});
),
);
assert.deepEqual(lineOnly, {
command: "cursor",
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
});
const lineAndColumn = yield* resolveEditorLaunch(
const lineAndColumn = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
{ platform: "darwin" },
);
assert.deepEqual(lineAndColumn, {
command: "cursor",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
),
);
assert.deepEqual(lineAndColumn, {
command: "cursor",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
const vscodeLineAndColumn = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
{ platform: "darwin" },
);
assert.deepEqual(vscodeLineAndColumn, {
command: "code",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
),
);
assert.deepEqual(vscodeLineAndColumn, {
command: "code",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const zedLineAndColumn = yield* resolveEditorLaunch(
const zedLineAndColumn = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
{ platform: "darwin" },
);
assert.deepEqual(zedLineAndColumn, {
command: "zed",
args: ["/tmp/workspace/src/open.ts:71:5"],
});
}),
);
),
);
assert.deepEqual(zedLineAndColumn, {
command: "zed",
args: ["/tmp/workspace/src/open.ts:71:5"],
});
});
it.effect("maps file-manager editor to OS open commands", () =>
Effect.gen(function* () {
const launch1 = yield* resolveEditorLaunch(
it("maps file-manager editor to OS open commands", async () => {
const launch1 = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "file-manager" },
{ platform: "darwin" },
);
assert.deepEqual(launch1, {
command: "open",
args: ["/tmp/workspace"],
});
),
);
assert.deepEqual(launch1, {
command: "open",
args: ["/tmp/workspace"],
});
const launch2 = yield* resolveEditorLaunch(
const launch2 = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "C:\\workspace", editor: "file-manager" },
{ platform: "win32" },
);
assert.deepEqual(launch2, {
command: "explorer",
args: ["C:\\workspace"],
});
),
);
assert.deepEqual(launch2, {
command: "explorer",
args: ["C:\\workspace"],
});
const launch3 = yield* resolveEditorLaunch(
const launch3 = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "file-manager" },
{ platform: "linux" },
);
assert.deepEqual(launch3, {
command: "xdg-open",
args: ["/tmp/workspace"],
});
}),
);
),
);
assert.deepEqual(launch3, {
command: "xdg-open",
args: ["/tmp/workspace"],
});
});
it.effect("prefers linux editor shims in wsl-hosted mode when available", () =>
Effect.gen(function* () {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-linux-editor-"));
try {
fs.writeFileSync(path.join(dir, "code"), "#!/bin/sh\n", { mode: 0o755 });
const launch = yield* resolveEditorLaunch(
it("prefers linux editor shims in wsl-hosted mode when available", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-linux-editor-"));
try {
fs.writeFileSync(path.join(dir, "code"), "#!/bin/sh\n", { mode: 0o755 });
const launch = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
{
platform: "linux",
@@ -137,23 +151,23 @@ describe("resolveEditorLaunch", () => {
PATH: dir,
},
},
);
assert.deepEqual(launch, {
command: "code",
args: ["--goto", "/home/julius/project/src/open.ts:71:5"],
});
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}),
);
),
);
assert.deepEqual(launch, {
command: "code",
args: ["--goto", "/home/julius/project/src/open.ts:71:5"],
});
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it.effect("falls back to windows editor executables in wsl-hosted mode", () =>
Effect.gen(function* () {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-win-editor-"));
try {
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
const launch = yield* resolveEditorLaunch(
it("falls back to windows editor executables in wsl-hosted mode", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-win-editor-"));
try {
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
const launch = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
{
platform: "linux",
@@ -173,26 +187,26 @@ describe("resolveEditorLaunch", () => {
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
),
},
);
assert.deepEqual(launch, {
command: "code.exe",
args: [
"--goto",
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts:71:5",
],
});
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}),
);
),
);
assert.deepEqual(launch, {
command: "code.exe",
args: [
"--goto",
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts:71:5",
],
});
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it.effect("translates file-manager targets for wsl-hosted mode", () =>
Effect.gen(function* () {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-file-manager-"));
try {
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
const launch = yield* resolveEditorLaunch(
it("translates file-manager targets for wsl-hosted mode", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-file-manager-"));
try {
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
const launch = await Effect.runPromise(
resolveEditorLaunch(
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "file-manager" },
{
platform: "linux",
@@ -212,38 +226,39 @@ describe("resolveEditorLaunch", () => {
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
),
},
);
assert.deepEqual(launch, {
command: "explorer.exe",
args: ["\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts"],
});
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}),
);
),
);
assert.deepEqual(launch, {
command: "explorer.exe",
args: ["\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts"],
});
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
});
describe("launchDetached", () => {
it.effect("resolves when command can be spawned", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
command: process.execPath,
args: ["-e", "process.exit(0)"],
}).pipe(Effect.result);
assertSuccess(result, undefined);
}),
);
it("resolves when command can be spawned", async () => {
await expect(
Effect.runPromise(
launchDetached({
command: process.execPath,
args: ["-e", "process.exit(0)"],
}),
),
).resolves.toBeUndefined();
});
it.effect("rejects when command does not exist", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
it("rejects when command does not exist", async () => {
const result = await Effect.runPromise(
launchDetached({
command: `t3code-no-such-command-${Date.now()}`,
args: [],
}).pipe(Effect.result);
assert.equal(result._tag, "Failure");
}),
);
}).pipe(Effect.result),
);
assert.equal(result._tag, "Failure");
});
});
describe("isCommandAvailable", () => {
+10 -73
View File
@@ -6,11 +6,17 @@
*
* @module Open
*/
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import { join } from "node:path";
import { EDITORS, type EditorId, type ServerRuntimeEnvironment } from "@t3tools/contracts";
import { ServiceMap, Schema, Effect, Layer } from "effect";
import {
isExecutableFile,
resolveCommandCandidates,
resolvePathEnvironmentVariable,
resolveWindowsPathExtensions,
stripWrappingQuotes,
} from "./commandResolution";
import { spawnDetachedProcess, spawnProcessSync } from "./processRunner";
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
@@ -72,75 +78,6 @@ function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
}
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return env.PATH ?? env.Path ?? env.path ?? "";
}
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
if (platform !== "win32") return [command];
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]),
);
}
const candidates: string[] = [];
for (const extension of windowsPathExtensions) {
candidates.push(`${command}${extension}`);
candidates.push(`${command}${extension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
function resolvePathDelimiter(platform: NodeJS.Platform): string {
return platform === "win32" ? ";" : ":";
}
@@ -156,7 +93,7 @@ export function isCommandAvailable(
if (command.includes("/") || command.includes("\\")) {
return commandCandidates.some((candidate) =>
isExecutableFile(candidate, platform, windowsPathExtensions),
isExecutableFile(candidate, { platform, windowsPathExtensions }),
);
}
@@ -169,7 +106,7 @@ export function isCommandAvailable(
for (const pathEntry of pathEntries) {
for (const candidate of commandCandidates) {
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
if (isExecutableFile(join(pathEntry, candidate), { platform, windowsPathExtensions })) {
return true;
}
}
+28 -2
View File
@@ -104,11 +104,37 @@ describe("resolveProcessLaunchPlan", () => {
expect(plan.command).toBe("C:\\Windows\\System32\\cmd.exe");
expect(plan.args.slice(0, 3)).toEqual(["/d", "/s", "/c"]);
expect(plan.args[3]).toBe(`"${wrapperPath}" "C:\\repo\\a^&b.ts"`);
expect(plan.args[3]).toBe(`"${wrapperPath}" "C:\\repo\\a&b.ts"`);
expect(plan.shell).toBe(false);
});
});
it("resolves relative batch launchers against the configured cwd", () => {
withTempDir((dir) => {
const wrapperPath = path.join(dir, "code.CMD");
fs.writeFileSync(wrapperPath, "@echo off\r\n");
const plan = resolveProcessLaunchPlan("./code", ["pkg@^1.0"], {
cwd: dir,
env: {
PATHEXT: ".COM;.EXE;.BAT;.CMD",
COMSPEC: "C:\\Windows\\System32\\cmd.exe",
},
inheritParentEnv: false,
runtimeEnvironment: {
platform: "windows",
pathStyle: "windows",
isWsl: false,
windowsInteropMode: "windows-native",
wslDistroName: null,
},
});
expect(plan.command).toBe("C:\\Windows\\System32\\cmd.exe");
expect(plan.args[3]).toBe(`"${wrapperPath}" "pkg@^1.0"`);
});
});
it("keeps wsl-hosted commands on the linux direct exec path", () => {
const plan = resolveProcessLaunchPlan("code", ["/home/julius/repo"], {
runtimeEnvironment: {
@@ -166,7 +192,7 @@ describe("makeRuntimeCommand", () => {
});
expect(command.command).toBe("C:\\Windows\\System32\\cmd.exe");
expect(command.args).toEqual(["/d", "/s", "/c", `"${wrapperPath}" "C:\\repo\\a^&b.ts"`]);
expect(command.args).toEqual(["/d", "/s", "/c", `"${wrapperPath}" "C:\\repo\\a&b.ts"`]);
expect(command.options.shell).toBe(false);
});
});
+40 -97
View File
@@ -5,13 +5,19 @@ import {
spawnSync,
type StdioOptions,
} from "node:child_process";
import { statSync } from "node:fs";
import { extname, join } from "node:path";
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
import { Effect, Exit, Scope } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
resolveCommandCandidates,
resolveExecutableFile,
resolvePathEnvironmentVariable,
resolveWindowsPathExtensions,
stripWrappingQuotes,
} from "./commandResolution";
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
interface ProcessSpawnBaseOptions {
@@ -27,11 +33,12 @@ interface RuntimeShellOptions {
}
interface ProcessLaunchPlanOptions extends RuntimeShellOptions {
cwd?: string | undefined;
env?: NodeJS.ProcessEnv | Record<string, string | undefined> | undefined;
inheritParentEnv?: boolean | undefined;
}
export interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
stdio?: StdioOptions | undefined;
detached?: boolean | undefined;
}
@@ -40,7 +47,7 @@ export interface RuntimeCommandOptions extends ChildProcess.CommandOptions {
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
}
export interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
stdio?: StdioOptions | undefined;
detached?: boolean | undefined;
encoding?: BufferEncoding | undefined;
@@ -93,71 +100,6 @@ function resolveRuntimeEnvironment(
return runtimeEnvironment ?? detectServerRuntimeEnvironment();
}
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return env.PATH ?? env.Path ?? env.path ?? "";
}
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveCommandCandidates(
command: string,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]),
);
}
const candidates: string[] = [command];
for (const candidateExtension of windowsPathExtensions) {
candidates.push(`${command}${candidateExtension}`);
candidates.push(`${command}${candidateExtension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
function isExecutableFile(
filePath: string,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
const extension = extname(filePath);
if (extension.length === 0) return false;
if (windowsPathExtensions.length === 0) {
return true;
}
return windowsPathExtensions.includes(extension.toUpperCase());
} catch {
return false;
}
}
function resolveEffectiveEnvironment(options: ProcessLaunchPlanOptions): NodeJS.ProcessEnv {
const env = (options.env ?? {}) as NodeJS.ProcessEnv;
if (options.inheritParentEnv === false) {
@@ -173,9 +115,10 @@ function resolveEffectiveEnvironment(options: ProcessLaunchPlanOptions): NodeJS.
function resolveWindowsCommand(
command: string,
env: NodeJS.ProcessEnv,
cwd?: string,
): ResolvedWindowsCommand | null {
const windowsPathExtensions = resolveWindowsPathExtensions(env);
const candidates = resolveCommandCandidates(command, windowsPathExtensions);
const candidates = resolveCommandCandidates(command, "win32", windowsPathExtensions);
const classify = (filePath: string): ResolvedWindowsCommand => {
const extension = extname(filePath).toUpperCase();
@@ -187,8 +130,13 @@ function resolveWindowsCommand(
if (command.includes("/") || command.includes("\\")) {
for (const candidate of candidates) {
if (isExecutableFile(candidate, windowsPathExtensions)) {
return classify(candidate);
const resolvedCandidate = resolveExecutableFile(candidate, {
platform: "win32",
windowsPathExtensions,
cwd,
});
if (resolvedCandidate) {
return classify(resolvedCandidate);
}
}
return null;
@@ -202,7 +150,12 @@ function resolveWindowsCommand(
for (const pathEntry of pathEntries) {
for (const candidate of candidates) {
const candidatePath = join(pathEntry, candidate);
if (isExecutableFile(candidatePath, windowsPathExtensions)) {
if (
resolveExecutableFile(candidatePath, {
platform: "win32",
windowsPathExtensions,
})
) {
return classify(candidatePath);
}
}
@@ -217,16 +170,9 @@ function quoteWindowsBatchArgument(argument: string): string {
}
const escaped = argument
.replaceAll("^", "^^")
.replaceAll("%", "%%")
.replaceAll("!", "^!")
.replaceAll("&", "^&")
.replaceAll("|", "^|")
.replaceAll("<", "^<")
.replaceAll(">", "^>")
.replaceAll("(", "^(")
.replaceAll(")", "^)")
.replaceAll('"', '""');
.replace(/(\\*)"/g, (_match, slashes: string) => `${slashes}${slashes}\\"`)
.replace(/(\\+)$/g, "$1$1");
return `"${escaped}"`;
}
@@ -266,7 +212,7 @@ export function resolveProcessLaunchPlan(
}
const env = resolveEffectiveEnvironment(options);
const resolved = resolveWindowsCommand(command, env);
const resolved = resolveWindowsCommand(command, env, options.cwd);
if (!resolved) {
return {
command,
@@ -306,19 +252,14 @@ function toSpawnOptions(
};
}
export function toRuntimeCommandOptions(
function toRuntimeCommandOptions(
options: RuntimeCommandOptions = {},
shell: boolean | string,
): ChildProcess.CommandOptions {
const launchPlan = resolveProcessLaunchPlan("", [], {
env: options.env,
runtimeEnvironment: options.runtimeEnvironment,
shell: options.shell,
inheritParentEnv: options.extendEnv !== false,
});
const { runtimeEnvironment: _runtimeEnvironment, shell: _shell, ...commandOptions } = options;
return {
...options,
shell: launchPlan.shell,
...commandOptions,
shell,
};
}
@@ -328,18 +269,18 @@ export function makeRuntimeCommand(
options: RuntimeCommandOptions = {},
): ChildProcess.StandardCommand {
const launchPlan = resolveProcessLaunchPlan(command, args, {
cwd: options.cwd,
env: options.env,
runtimeEnvironment: options.runtimeEnvironment,
shell: options.shell,
inheritParentEnv: options.extendEnv !== false,
});
return ChildProcess.make(launchPlan.command, launchPlan.args, {
...toRuntimeCommandOptions(options),
shell: launchPlan.shell,
...toRuntimeCommandOptions(options, launchPlan.shell),
});
}
export interface ManagedChildProcess {
interface ManagedChildProcess {
readonly scope: Scope.Closeable;
readonly handle: ChildProcessSpawner.ChildProcessHandle;
}
@@ -365,6 +306,7 @@ function spawnProcess(
options: ProcessSpawnOptions = {},
): ChildProcessHandle {
const launchPlan = resolveProcessLaunchPlan(command, args, {
cwd: options.cwd,
env: options.env,
runtimeEnvironment: options.runtimeEnvironment,
shell: options.shell,
@@ -374,7 +316,7 @@ function spawnProcess(
return spawn(launchPlan.command, launchPlan.args, toSpawnOptions(options, launchPlan));
}
export function spawnPipedProcess(
function spawnPipedProcess(
command: string,
args: readonly string[],
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
@@ -391,6 +333,7 @@ export function spawnProcessSync(
options: ProcessSpawnSyncOptions = {},
) {
const launchPlan = resolveProcessLaunchPlan(command, args, {
cwd: options.cwd,
env: options.env,
runtimeEnvironment: options.runtimeEnvironment,
shell: options.shell,
@@ -499,7 +442,7 @@ const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
* terminates the wrapper, leaving the actual command running. Use
* `taskkill /T` to kill the entire process tree instead.
*/
export function killProcessTree(
function killProcessTree(
child: ChildProcessHandle,
options: {
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
@@ -11,6 +11,7 @@ function mockRunner(
stdout: string;
stderr: string;
code: number | null;
signal?: NodeJS.Signals | null;
timedOut?: boolean;
},
) {
@@ -147,6 +148,27 @@ it("parseAuthStatusFromOutput: timed out auth check is warning", () => {
assert.strictEqual(parsed.message, "Timed out while checking Codex authentication status.");
});
it.effect("reports signal-based auth probe failures without 'code null'", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus(
mockRunner((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "", code: null, signal: "SIGTERM" };
}
throw new Error(`Unexpected args: ${joined}`);
}),
);
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Could not verify Codex authentication status. Command exited from signal SIGTERM.",
);
}),
);
// ── Pure function tests ─────────────────────────────────────────────
it("parseAuthStatusFromOutput: exit code 0 with no auth markers is ready", () => {
@@ -32,6 +32,7 @@ export interface CommandResult {
readonly stdout: string;
readonly stderr: string;
readonly code: number | null;
readonly signal?: NodeJS.Signals | null;
readonly timedOut?: boolean;
}
@@ -76,6 +77,11 @@ function detailFromResult(
if (stderr) return stderr;
const stdout = nonEmptyTrimmed(result.stdout);
if (stdout) return stdout;
if (result.code === null) {
return result.signal
? `Command exited from signal ${result.signal}.`
: "Command exited without an exit code.";
}
if (result.code !== 0) {
return `Command exited with code ${result.code}.`;
}
@@ -208,6 +214,7 @@ const defaultRunCodexCommand: RunProviderHealthCommand = async (args) => {
stdout: result.stdout,
stderr: result.stderr,
code: result.code,
signal: result.signal,
timedOut: result.timedOut,
} satisfies CommandResult;
};
+2 -1
View File
@@ -21,5 +21,6 @@
}
]
},
"include": ["src", "vite.config.ts"]
"include": ["src", "vite.config.ts"],
"exclude": ["src/**/*.browser.ts", "src/**/*.browser.tsx"]
}