From 935e7c6ceae0a909bcaabd36a2fbdd4b0061bb41 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 31 Mar 2026 12:15:04 -0700 Subject: [PATCH] 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 --- apps/server/src/git/Layers/GitCore.ts | 14 ++-- .../src/process/Layers/DesktopLauncher.ts | 26 ++----- apps/server/src/process/killTree.test.ts | 47 ++++++++++++ apps/server/src/process/killTree.ts | 32 ++++++++ apps/server/src/process/outputBuffer.test.ts | 34 +++++++++ apps/server/src/process/outputBuffer.ts | 57 ++++++++++++++ .../src/process/runProbeProcess.test.ts | 35 +++++++++ apps/server/src/process/runProbeProcess.ts | 17 +++++ .../server/src/process/windowsCommand.test.ts | 65 ++++++++++++++++ apps/server/src/process/windowsCommand.ts | 35 +++++++++ apps/server/src/processRunner.ts | 76 +++++-------------- apps/server/src/provider/codexAppServer.ts | 14 +--- apps/server/src/provider/providerSnapshot.ts | 2 +- apps/server/src/terminal/Layers/Manager.ts | 16 ++-- 14 files changed, 365 insertions(+), 105 deletions(-) create mode 100644 apps/server/src/process/killTree.test.ts create mode 100644 apps/server/src/process/killTree.ts create mode 100644 apps/server/src/process/outputBuffer.test.ts create mode 100644 apps/server/src/process/outputBuffer.ts create mode 100644 apps/server/src/process/runProbeProcess.test.ts create mode 100644 apps/server/src/process/runProbeProcess.ts create mode 100644 apps/server/src/process/windowsCommand.test.ts create mode 100644 apps/server/src/process/windowsCommand.ts diff --git a/apps/server/src/git/Layers/GitCore.ts b/apps/server/src/git/Layers/GitCore.ts index 81d6cbb549..b94278095a 100644 --- a/apps/server/src/git/Layers/GitCore.ts +++ b/apps/server/src/git/Layers/GitCore.ts @@ -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* ( 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* ( }); } - 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; diff --git a/apps/server/src/process/Layers/DesktopLauncher.ts b/apps/server/src/process/Layers/DesktopLauncher.ts index a89bb9c70c..e276abad06 100644 --- a/apps/server/src/process/Layers/DesktopLauncher.ts +++ b/apps/server/src/process/Layers/DesktopLauncher.ts @@ -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 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 { - 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); } diff --git a/apps/server/src/process/killTree.test.ts b/apps/server/src/process/killTree.test.ts new file mode 100644 index 0000000000..9e48e106f4 --- /dev/null +++ b/apps/server/src/process/killTree.test.ts @@ -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"); + }); +}); diff --git a/apps/server/src/process/killTree.ts b/apps/server/src/process/killTree.ts new file mode 100644 index 0000000000..dd78574718 --- /dev/null +++ b/apps/server/src/process/killTree.ts @@ -0,0 +1,32 @@ +import { spawnSync, type ChildProcess as NodeChildProcess } from "node:child_process"; + +type KillableChildProcess = Pick; + +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); +} diff --git a/apps/server/src/process/outputBuffer.test.ts b/apps/server/src/process/outputBuffer.test.ts new file mode 100644 index 0000000000..4c9a727a0b --- /dev/null +++ b/apps/server/src/process/outputBuffer.test.ts @@ -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, + }); + }); +}); diff --git a/apps/server/src/process/outputBuffer.ts b/apps/server/src/process/outputBuffer.ts new file mode 100644 index 0000000000..0258f06e69 --- /dev/null +++ b/apps/server/src/process/outputBuffer.ts @@ -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, + }; +} diff --git a/apps/server/src/process/runProbeProcess.test.ts b/apps/server/src/process/runProbeProcess.test.ts new file mode 100644 index 0000000000..5eff1e525e --- /dev/null +++ b/apps/server/src/process/runProbeProcess.test.ts @@ -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", + }); + }); +}); diff --git a/apps/server/src/process/runProbeProcess.ts b/apps/server/src/process/runProbeProcess.ts new file mode 100644 index 0000000000..cd0b4bb0ce --- /dev/null +++ b/apps/server/src/process/runProbeProcess.ts @@ -0,0 +1,17 @@ +import { runProcess, type ProcessRunOptions, type ProcessRunResult } from "../processRunner"; + +type ProcessRunner = typeof runProcess; + +export type ProbeProcessOptions = Omit; + +export function runProbeProcess( + command: string, + args: readonly string[], + options: ProbeProcessOptions = {}, + runner: ProcessRunner = runProcess, +): Promise { + return runner(command, args, { + ...options, + outputMode: "truncate", + }); +} diff --git a/apps/server/src/process/windowsCommand.test.ts b/apps/server/src/process/windowsCommand.test.ts new file mode 100644 index 0000000000..6edcfbcd40 --- /dev/null +++ b/apps/server/src/process/windowsCommand.test.ts @@ -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""', + ]); +}); diff --git a/apps/server/src/process/windowsCommand.ts b/apps/server/src/process/windowsCommand.ts new file mode 100644 index 0000000000..5f0d35b511 --- /dev/null +++ b/apps/server/src/process/windowsCommand.ts @@ -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 { + return `"${[commandPath, ...args].map(quoteForWindowsCmd).join(" ")}"`; +} + +export function makeWindowsCmdSpawnArguments( + commandPath: string, + args: ReadonlyArray, +): ReadonlyArray { + return ["/d", "/v:off", "/s", "/c", makeWindowsCmdCommandLine(commandPath, args)]; +} diff --git a/apps/server/src/processRunner.ts b/apps/server/src/processRunner.ts index 5402612887..63c83bf2e4 100644 --- a/apps/server/src/processRunner.ts +++ b/apps/server/src/processRunner.ts @@ -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; diff --git a/apps/server/src/provider/codexAppServer.ts b/apps/server/src/provider/codexAppServer.ts index d25fc3533e..6b1439bc26 100644 --- a/apps/server/src/provider/codexAppServer.ts +++ b/apps/server/src/provider/codexAppServer.ts @@ -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: { diff --git a/apps/server/src/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.ts index e1243c4bd0..3a6a0b7a93 100644 --- a/apps/server/src/provider/providerSnapshot.ts +++ b/apps/server/src/provider/providerSnapshot.ts @@ -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; diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index 7ef18b1655..bcb9864502 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -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 { 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({