Refactor process helpers for Windows handling and output limits

- Extract shared Windows command/process utilities
- Add process tree kill and probe process wrappers
- Cover output truncation and Windows command behavior with tests
This commit is contained in:
Julius Marminge committed 2026-03-31 12:15:04 -07:00
1 parent 439e8bcd42
commit 935e7c6cea
14 files changed
+365 -105

No files matched your search

+6 -8
View File
@@ -29,6 +29,7 @@ import {
} from "../Services/GitCore.ts";
import { ServerConfig } from "../../config.ts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { limitChunkToByteLimit } from "../../process/outputBuffer";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
@@ -520,8 +521,8 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
if (truncateOutputAtMaxBytes && truncated) {
return;
}
const nextBytes = bytes + chunk.byteLength;
if (!truncateOutputAtMaxBytes && nextBytes > maxOutputBytes) {
const limitedChunk = limitChunkToByteLimit(chunk, bytes, maxOutputBytes);
if (!truncateOutputAtMaxBytes && limitedChunk.overflow) {
return yield* new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
@@ -530,12 +531,9 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
});
}
const chunkToDecode =
truncateOutputAtMaxBytes && nextBytes > maxOutputBytes
? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes))
: chunk;
bytes += chunkToDecode.byteLength;
truncated = truncateOutputAtMaxBytes && nextBytes > maxOutputBytes;
const chunkToDecode = truncateOutputAtMaxBytes ? limitedChunk.chunk : chunk;
bytes = truncateOutputAtMaxBytes ? limitedChunk.nextBytes : bytes + chunk.byteLength;
truncated = truncateOutputAtMaxBytes && limitedChunk.truncated;
const decoded = decoder.decode(chunkToDecode, { stream: !truncated });
text += decoded;
@@ -13,6 +13,11 @@ import { spawn as spawnNodeChildProcess } from "node:child_process";
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { Array, Effect, FileSystem, Layer, Option, Path, Scope } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
isWindowsBatchShim,
makeWindowsCmdSpawnArguments,
resolveWindowsCommandShell,
} from "../windowsCommand";
import {
DesktopLauncherCommandNotFoundError,
DesktopLauncherDiscoveryError,
@@ -113,7 +118,6 @@ const WSL_POWERSHELL_CANDIDATES = [
"powershell.exe",
"pwsh.exe",
] as const;
const WINDOWS_BATCH_EXTENSIONS = [".CMD", ".BAT"] as const;
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
@@ -141,10 +145,6 @@ function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<str
return parsed.length > 0 ? Array.dedupe(parsed) : fallback;
}
function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string {
return env.ComSpec ?? env.COMSPEC ?? "cmd.exe";
}
function resolveCommandCandidates(
command: string,
runtime: LaunchRuntime,
@@ -378,18 +378,6 @@ function resolveExternalPlans(
return plans;
}
function isWindowsBatchShim(pathService: Path.Path, filePath: string): boolean {
return WINDOWS_BATCH_EXTENSIONS.includes(pathService.extname(filePath).toUpperCase() as never);
}
function quoteForWindowsCmd(value: string): string {
return `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
}
function makeWindowsCmdCommandLine(commandPath: string, args: ReadonlyArray<string>): string {
return `"${[commandPath, ...args].map(quoteForWindowsCmd).join(" ")}"`;
}
function resolveSpawnInput(
runtime: LaunchRuntime,
plan: LaunchPlan,
@@ -400,7 +388,7 @@ function resolveSpawnInput(
? resolveWindowsCommandShell(runtime.env)
: resolvedCommand.path,
args: resolvedCommand.usesCmdWrapper
? ["/d", "/v:off", "/s", "/c", makeWindowsCmdCommandLine(resolvedCommand.path, plan.args)]
? makeWindowsCmdSpawnArguments(resolvedCommand.path, plan.args)
: [...plan.args],
...(plan.detached !== undefined ? { detached: plan.detached } : {}),
...(plan.shell !== undefined ? { shell: plan.shell } : {}),
@@ -583,7 +571,7 @@ export const make = Effect.fn("makeDesktopLauncher")(function* (
return Option.some({
path: filePath,
usesCmdWrapper: isWindowsBatchShim(pathService, filePath),
usesCmdWrapper: isWindowsBatchShim(filePath),
} satisfies ResolvedCommand);
}
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it, vi } from "vitest";
import { killChildProcessTree } from "./killTree";
describe("killChildProcessTree", () => {
it("uses taskkill on Windows when a pid is available", () => {
const kill = vi.fn();
const spawnSyncImpl = vi.fn();
killChildProcessTree({ pid: 123, kill } as never, "SIGTERM", {
platform: "win32",
spawnSyncImpl,
});
expect(spawnSyncImpl).toHaveBeenCalledWith("taskkill", ["/pid", "123", "/T", "/F"], {
stdio: "ignore",
});
expect(kill).not.toHaveBeenCalled();
});
it("falls back to direct kill when taskkill fails", () => {
const kill = vi.fn();
const spawnSyncImpl = vi.fn(() => {
throw new Error("taskkill unavailable");
});
killChildProcessTree({ pid: 456, kill } as never, "SIGKILL", {
platform: "win32",
spawnSyncImpl,
});
expect(kill).toHaveBeenCalledWith("SIGKILL");
});
it("kills directly on non-Windows platforms", () => {
const kill = vi.fn();
const spawnSyncImpl = vi.fn();
killChildProcessTree({ pid: 789, kill } as never, "SIGTERM", {
platform: "darwin",
spawnSyncImpl,
});
expect(spawnSyncImpl).not.toHaveBeenCalled();
expect(kill).toHaveBeenCalledWith("SIGTERM");
});
});
+32
View File
@@ -0,0 +1,32 @@
import { spawnSync, type ChildProcess as NodeChildProcess } from "node:child_process";
type KillableChildProcess = Pick<NodeChildProcess, "kill" | "pid">;
interface KillChildProcessTreeOptions {
readonly platform?: NodeJS.Platform;
readonly spawnSyncImpl?: typeof spawnSync;
}
/**
* On Windows with shell-backed processes, direct kill only terminates the
* wrapper process. Use `taskkill /T` first so the spawned process tree exits.
*/
export function killChildProcessTree(
child: KillableChildProcess,
signal: NodeJS.Signals = "SIGTERM",
options: KillChildProcessTreeOptions = {},
): void {
const platform = options.platform ?? process.platform;
if (platform === "win32" && child.pid !== undefined) {
try {
(options.spawnSyncImpl ?? spawnSync)("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
stdio: "ignore",
});
return;
} catch {
// Fall through to direct kill when taskkill is unavailable.
}
}
child.kill(signal);
}
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { appendTextChunkWithinByteLimit, limitChunkToByteLimit } from "./outputBuffer";
describe("outputBuffer", () => {
it("keeps a full chunk when it fits within the byte limit", () => {
const chunk = Buffer.from("hello");
expect(limitChunkToByteLimit(chunk, 2, 10)).toEqual({
chunk,
nextBytes: 7,
truncated: false,
overflow: false,
});
});
it("truncates a chunk to the remaining byte budget", () => {
const chunk = Buffer.from("abcdef");
const limited = limitChunkToByteLimit(chunk, 3, 5);
expect(Buffer.from(limited.chunk).toString()).toBe("ab");
expect(limited.nextBytes).toBe(5);
expect(limited.truncated).toBe(true);
expect(limited.overflow).toBe(true);
});
it("appends only the bytes that fit", () => {
expect(appendTextChunkWithinByteLimit("pre", 3, Buffer.from("abcdef"), 7)).toEqual({
next: "preabcd",
nextBytes: 7,
truncated: true,
});
});
});
+57
View File
@@ -0,0 +1,57 @@
export interface LimitedChunk {
readonly chunk: Uint8Array;
readonly nextBytes: number;
readonly truncated: boolean;
readonly overflow: boolean;
}
export function limitChunkToByteLimit(
chunk: Uint8Array,
currentBytes: number,
maxBytes: number,
): LimitedChunk {
const remaining = maxBytes - currentBytes;
if (remaining <= 0) {
return {
chunk: new Uint8Array(),
nextBytes: currentBytes,
truncated: true,
overflow: true,
};
}
if (chunk.byteLength <= remaining) {
return {
chunk,
nextBytes: currentBytes + chunk.byteLength,
truncated: false,
overflow: false,
};
}
return {
chunk: chunk.subarray(0, remaining),
nextBytes: currentBytes + remaining,
truncated: true,
overflow: true,
};
}
export function appendTextChunkWithinByteLimit(
target: string,
currentBytes: number,
chunk: Uint8Array,
maxBytes: number,
): {
readonly next: string;
readonly nextBytes: number;
readonly truncated: boolean;
} {
const limited = limitChunkToByteLimit(chunk, currentBytes, maxBytes);
return {
next: `${target}${Buffer.from(limited.chunk).toString()}`,
nextBytes: limited.nextBytes,
truncated: limited.truncated,
};
}
@@ -0,0 +1,35 @@
import { describe, expect, it, vi } from "vitest";
import { runProbeProcess } from "./runProbeProcess";
describe("runProbeProcess", () => {
it("forces truncated output mode while preserving other options", async () => {
const runner = vi.fn().mockResolvedValue({
stdout: "",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
await runProbeProcess(
"ps",
["-eo", "pid=,ppid="],
{
timeoutMs: 500,
allowNonZeroExit: true,
maxBufferBytes: 1024,
cwd: "/tmp",
},
runner,
);
expect(runner).toHaveBeenCalledWith("ps", ["-eo", "pid=,ppid="], {
timeoutMs: 500,
allowNonZeroExit: true,
maxBufferBytes: 1024,
cwd: "/tmp",
outputMode: "truncate",
});
});
});
@@ -0,0 +1,17 @@
import { runProcess, type ProcessRunOptions, type ProcessRunResult } from "../processRunner";
type ProcessRunner = typeof runProcess;
export type ProbeProcessOptions = Omit<ProcessRunOptions, "stdin" | "outputMode">;
export function runProbeProcess(
command: string,
args: readonly string[],
options: ProbeProcessOptions = {},
runner: ProcessRunner = runProcess,
): Promise<ProcessRunResult> {
return runner(command, args, {
...options,
outputMode: "truncate",
});
}
@@ -0,0 +1,65 @@
import { assert, it } from "@effect/vitest";
import {
isWindowsBatchShim,
isWindowsCommandNotFound,
makeWindowsCmdCommandLine,
makeWindowsCmdSpawnArguments,
quoteForWindowsCmd,
resolveWindowsCommandShell,
} from "./windowsCommand";
it("resolves cmd.exe from Windows command shell environment variables", () => {
assert.equal(resolveWindowsCommandShell({}), "cmd.exe");
assert.equal(
resolveWindowsCommandShell({ COMSPEC: "C:\\Windows\\System32\\cmd.exe" }),
"C:\\Windows\\System32\\cmd.exe",
);
assert.equal(
resolveWindowsCommandShell({ ComSpec: "C:\\custom\\cmd.exe" }),
"C:\\custom\\cmd.exe",
);
});
it("detects Windows batch shims case-insensitively", () => {
assert.equal(isWindowsBatchShim("code.cmd"), true);
assert.equal(isWindowsBatchShim("C:\\tools\\launcher.BAT"), true);
assert.equal(isWindowsBatchShim("/tmp/code.exe"), false);
});
it("detects Windows command-not-found exits", () => {
assert.equal(isWindowsCommandNotFound(9009, "", "win32"), true);
assert.equal(
isWindowsCommandNotFound(
1,
"'foo' is not recognized as an internal or external command",
"win32",
),
true,
);
assert.equal(isWindowsCommandNotFound(9009, "", "darwin"), false);
});
it("quotes Windows cmd values safely", () => {
assert.equal(
quoteForWindowsCmd('C:\\work\\100% real\\"quoted".ts:12:4'),
'"C:\\work\\100%% real\\""quoted"".ts:12:4"',
);
});
it("builds Windows cmd command lines safely", () => {
assert.equal(
makeWindowsCmdCommandLine("code.cmd", ["--goto", "file.ts:12:4"]),
'""code.cmd" "--goto" "file.ts:12:4""',
);
});
it("builds Windows cmd spawn arguments with cmd control flags", () => {
assert.deepEqual(makeWindowsCmdSpawnArguments("code.cmd", ["--goto", "file.ts:1:1"]), [
"/d",
"/v:off",
"/s",
"/c",
'""code.cmd" "--goto" "file.ts:1:1""',
]);
});
+35
View File
@@ -0,0 +1,35 @@
export function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string {
return env.ComSpec ?? env.COMSPEC ?? "cmd.exe";
}
export function isWindowsCommandNotFound(
code: number | null,
stderr: string,
platform: NodeJS.Platform = process.platform,
): boolean {
if (platform !== "win32") return false;
if (code === 9009) return true;
return /is not recognized as an internal or external command/i.test(stderr);
}
export function isWindowsBatchShim(filePath: string): boolean {
return /\.(cmd|bat)$/i.test(filePath);
}
export function quoteForWindowsCmd(value: string): string {
return `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
}
export function makeWindowsCmdCommandLine(
commandPath: string,
args: ReadonlyArray<string>,
): string {
return `"${[commandPath, ...args].map(quoteForWindowsCmd).join(" ")}"`;
}
export function makeWindowsCmdSpawnArguments(
commandPath: string,
args: ReadonlyArray<string>,
): ReadonlyArray<string> {
return ["/d", "/v:off", "/s", "/c", makeWindowsCmdCommandLine(commandPath, args)];
}
+19 -57
View File
@@ -1,4 +1,7 @@
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
import { spawn } from "node:child_process";
import { killChildProcessTree } from "./process/killTree";
import { appendTextChunkWithinByteLimit } from "./process/outputBuffer";
import { isWindowsCommandNotFound } from "./process/windowsCommand";
export interface ProcessRunOptions {
cwd?: string | undefined;
@@ -37,12 +40,6 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
}
export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
if (process.platform !== "win32") return false;
if (code === 9009) return true;
return /is not recognized as an internal or external command/i.test(stderr);
}
function normalizeExitError(
command: string,
args: readonly string[],
@@ -80,51 +77,6 @@ function normalizeBufferError(
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// fallback to direct kill
}
}
child.kill(signal);
}
function appendChunkWithinLimit(
target: string,
currentBytes: number,
chunk: Buffer,
maxBytes: number,
): {
next: string;
nextBytes: number;
truncated: boolean;
} {
const remaining = maxBytes - currentBytes;
if (remaining <= 0) {
return { next: target, nextBytes: currentBytes, truncated: true };
}
if (chunk.length <= remaining) {
return {
next: `${target}${chunk.toString()}`,
nextBytes: currentBytes + chunk.length,
truncated: false,
};
}
return {
next: `${target}${chunk.subarray(0, remaining).toString()}`,
nextBytes: currentBytes + remaining,
truncated: true,
};
}
export async function runProcess(
command: string,
args: readonly string[],
@@ -154,9 +106,9 @@ export async function runProcess(
const timeoutTimer = setTimeout(() => {
timedOut = true;
killChild(child, "SIGTERM");
killChildProcessTree(child, "SIGTERM");
forceKillTimer = setTimeout(() => {
killChild(child, "SIGKILL");
killChildProcessTree(child, "SIGKILL");
}, 1_000);
}, timeoutMs);
@@ -171,7 +123,7 @@ export async function runProcess(
};
const fail = (error: Error): void => {
killChild(child, "SIGTERM");
killChildProcessTree(child, "SIGTERM");
finalize(() => {
reject(error);
});
@@ -183,7 +135,12 @@ export async function runProcess(
const byteLength = chunkBuffer.length;
if (stream === "stdout") {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
const appended = appendTextChunkWithinByteLimit(
stdout,
stdoutBytes,
chunkBuffer,
maxBufferBytes,
);
stdout = appended.next;
stdoutBytes = appended.nextBytes;
stdoutTruncated = stdoutTruncated || appended.truncated;
@@ -196,7 +153,12 @@ export async function runProcess(
}
} else {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
const appended = appendTextChunkWithinByteLimit(
stderr,
stderrBytes,
chunkBuffer,
maxBufferBytes,
);
stderr = appended.next;
stderrBytes = appended.nextBytes;
stderrTruncated = stderrTruncated || appended.truncated;
+3 -11
View File
@@ -1,6 +1,7 @@
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import readline from "node:readline";
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount";
import { killChildProcessTree } from "../process/killTree";
interface JsonRpcProbeResponse {
readonly id?: unknown;
@@ -28,16 +29,7 @@ export function buildCodexInitializeParams() {
}
export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// Fall through to direct kill when taskkill is unavailable.
}
}
child.kill();
killChildProcessTree(child);
}
export async function probeCodexAccount(input: {
+1 -1
View File
@@ -7,7 +7,7 @@ import type {
import { Effect, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { isWindowsCommandNotFound } from "../processRunner";
import { isWindowsCommandNotFound } from "../process/windowsCommand";
export const DEFAULT_TIMEOUT_MS = 4_000;
+7 -9
View File
@@ -23,7 +23,8 @@ import {
} from "effect";
import { ServerConfig } from "../../config";
import { runProcess } from "../../processRunner";
import { runProbeProcess } from "../../process/runProbeProcess";
import { resolveWindowsCommandShell } from "../../process/windowsCommand";
import {
TerminalCwdError,
TerminalHistoryError,
@@ -174,7 +175,7 @@ function enqueueProcessEvent(
function defaultShellResolver(): string {
if (process.platform === "win32") {
return process.env.ComSpec ?? "cmd.exe";
return resolveWindowsCommandShell(process.env);
}
return process.env.SHELL ?? "bash";
}
@@ -226,7 +227,7 @@ function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
if (process.platform === "win32") {
return uniqueShellCandidates([
requested,
shellCandidateFromCommand(process.env.ComSpec ?? null),
shellCandidateFromCommand(resolveWindowsCommandShell(process.env)),
shellCandidateFromCommand("powershell.exe"),
shellCandidateFromCommand("cmd.exe"),
]);
@@ -301,11 +302,10 @@ function checkWindowsSubprocessActivity(
].join("; ");
return Effect.tryPromise({
try: () =>
runProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
runProbeProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
timeoutMs: 1_500,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
@@ -322,11 +322,10 @@ const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessAct
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
const runPgrep = Effect.tryPromise({
try: () =>
runProcess("pgrep", ["-P", String(terminalPid)], {
runProbeProcess("pgrep", ["-P", String(terminalPid)], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
@@ -339,11 +338,10 @@ const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessAct
const runPs = Effect.tryPromise({
try: () =>
runProcess("ps", ["-eo", "pid=,ppid="], {
runProbeProcess("ps", ["-eo", "pid=,ppid="], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 262_144,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({