Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(local-file-shell): extract ShellBackend abstraction with ChildProcessBackend (#20003)

Arvin Xub88bc48342df
diff --git a/packages/local-file-shell/src/shell/__tests__/backend.test.ts b/packages/local-file-shell/src/shell/__tests__/backend.test.ts
new file mode 100644
index 00000000000..0c583f10ffb
--- /dev/null
+++ b/packages/local-file-shell/src/shell/__tests__/backend.test.ts
@@ -0,0 +1,173 @@
+import { EventEmitter } from 'node:events';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ShellBackend, ShellHandle, ShellLaunchCommand, ShellSpawnOptions } from '../backend';
+import { ChildProcessBackend } from '../child-process-backend';
+import { ShellProcessManager } from '../process-manager';
+import { runCommand } from '../runner';
+
+type FakeHandle = EventEmitter & {
+ exitCode: number | null;
+ pid?: number;
+ signalCode: NodeJS.Signals | null;
+};
+
+/** Backend double: never starts a process, records what it was asked to do. */
+class FakeBackend implements ShellBackend {
+ readonly capabilities = { interactive: true, persistent: false, streaming: true };
+ readonly name = 'fake';
+
+ readonly handles = new Map<string, FakeHandle>();
+ readonly spawnCalls: { command: ShellLaunchCommand; options: ShellSpawnOptions }[] = [];
+ readonly kill = vi.fn((shellId: string) => {
+ const handle = this.handles.get(shellId);
+ if (!handle) throw new Error(`Shell ID ${shellId} not found`);
+ Object.assign(handle, { signalCode: 'SIGKILL' });
+ handle.emit('exit', null, 'SIGKILL');
+ handle.emit('close', null, 'SIGKILL');
+ });
+
+ readonly release = vi.fn((shellId: string) => {
+ this.handles.delete(shellId);
+ });
+
+ spawn(command: ShellLaunchCommand, options: ShellSpawnOptions): ShellHandle {
+ this.spawnCalls.push({ command, options });
+ const handle: FakeHandle = Object.assign(new EventEmitter(), {
+ exitCode: null,
+ signalCode: null,
+ });
+ this.handles.set(options.shellId, handle);
+ return handle;
+ }
+
+ /** Simulate the command writing `output` to stdout and exiting with `code`. */
+ finish(shellId: string, output: string, code: number): void {
+ const handle = this.handles.get(shellId)!;
+ fs.appendFileSync(this.spawnCalls.at(-1)!.options.outputFiles.stdout.path, output);
+ handle.exitCode = code;
+ handle.emit('exit', code, null);
+ handle.emit('close', code, null);
+ }
+}
+
+describe('ShellBackend injection', () => {
+ let tmpDir: string;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lobehub-shell-backend-'));
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpDir, { force: true, recursive: true });
+ });
+
+ it('should default ShellProcessManager to the non-interactive ChildProcessBackend', () => {
+ const manager = new ShellProcessManager(tmpDir);
+
+ expect(manager.backend).toBeInstanceOf(ChildProcessBackend);
+ expect(manager.backend.capabilities).toEqual({
+ interactive: false,
+ persistent: false,
+ streaming: false,
+ });
+ expect(manager.backend.write).toBeUndefined();
+ expect(manager.backend.onOutput).toBeUndefined();
+ manager.cleanupAll();
+ });
+
+ it('should spawn, observe and kill through the manager backend', async () => {
+ const backend = new FakeBackend();
+ const manager = new ShellProcessManager(tmpDir, backend);
+
+ const started = await runCommand(
+ { command: 'echo hi', cwd: tmpDir, env: { FOO: 'bar' }, run_in_background: true },
+ { processManager: manager },
+ );
+
+ expect(started).toMatchObject({ success: true });
+ // Shell ids carry a per-process token (see `ShellProcessManager.createShellId`).
+ expect(started.shell_id).toMatch(/^sh-[\da-f]{6}-1$/);
+ const shellId = started.shell_id!;
+ expect(backend.spawnCalls).toHaveLength(1);
+ const [{ command, options }] = backend.spawnCalls;
+ expect(command.args.at(-1)).toContain('echo hi');
+ expect(options).toMatchObject({ cwd: tmpDir, shellId });
+ expect(options.env.FOO).toBe('bar');
+ expect(options.outputFiles.stdout.path).toContain(path.join(shellId, 'stdout.log'));
+
+ backend.finish(shellId, 'from fake backend\n', 3);
+ const output = await manager.getOutput({ shell_id: shellId, timeout: 1000 });
+ expect(output).toMatchObject({
+ exit_code: 3,
+ running: false,
+ stdout: 'from fake backend\n',
+ success: true,
+ });
+
+ expect(manager.kill(shellId)).toEqual({ success: true });
+ expect(backend.kill).toHaveBeenCalledWith(shellId);
+
+ manager.cleanupAll();
+ expect(backend.release).toHaveBeenCalledWith(shellId);
+ });
+
+ it('should let runCommand override the backend and still kill through it', async () => {
+ const manager = new ShellProcessManager(tmpDir);
+ const backend = new FakeBackend();
+
+ const started = await runCommand(
+ { command: 'sleep 100', run_in_background: true },
+ { backend, processManager: manager },
+ );
+
+ expect(backend.spawnCalls).toHaveLength(1);
+ expect(manager.kill(started.shell_id!)).toEqual({ success: true });
+ expect(backend.kill).toHaveBeenCalledWith(started.shell_id);
+
+ const output = await manager.getOutput({ shell_id: started.shell_id!, timeout: 1000 });
+ expect(output).toMatchObject({ running: false, signal: 'SIGKILL' });
+ manager.cleanupAll();
+ });
+
+ it('should spawn through a caller-supplied spawnProcess on the default backend', async () => {
+ // The desktop passes a spawn that registers each process with its
+ // managed-process tracker; the backend abstraction must keep using it.
+ const manager = new ShellProcessManager(tmpDir);
+ const { spawn } = await import('node:child_process');
+ const spawnProcess = vi.fn(spawn);
+
+ const result = await runCommand(
+ { command: 'echo tracked' },
+ { processManager: manager, spawnProcess: spawnProcess as unknown as typeof spawn },
+ );
+
+ expect(spawnProcess).toHaveBeenCalledOnce();
+ expect(result).toMatchObject({ success: true });
+ expect(result.stdout).toContain('tracked');
+ manager.cleanupAll();
+ });
+
+ it('should report a backend spawn failure as a failed command', async () => {
+ const manager = new ShellProcessManager(tmpDir);
+ const backend = new FakeBackend();
+ vi.spyOn(backend, 'spawn').mockImplementation(() => {
+ throw new Error('backend unavailable');
+ });
+
+ const result = await runCommand({ command: 'echo hi' }, { backend, processManager: manager });
+
+ expect(result).toEqual({ error: 'backend unavailable', success: false });
+ manager.cleanupAll();
+ });
+});
+
+describe('ChildProcessBackend', () => {
+ it('should refuse to kill an id it never spawned', () => {
+ expect(() => new ChildProcessBackend().kill('sh-404')).toThrow('Shell ID sh-404 not found');
+ });
+});
diff --git a/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts b/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts
index 86892f99418..aa4d489f469 100644
--- a/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts
+++ b/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts
@@ -1,3 +1,4 @@
+import type * as ChildProcessModule from 'node:child_process';
import type { ChildProcess } from 'node:child_process';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
@@ -9,6 +10,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ShellProcess } from '../process-manager';
import { MAX_OBSERVATION_TIMEOUT_MS, ShellProcessManager } from '../process-manager';
+const spawnSpy = vi.hoisted(() => vi.fn());
+
+vi.mock('node:child_process', async (importOriginal) => ({
+ ...(await importOriginal<typeof ChildProcessModule>()),
+ spawn: spawnSpy,
+}));
+
function createMockProcess(exitCode: number | null = null, pid?: number): ChildProcess {
const process = new EventEmitter() as ChildProcess;
// Node types expose `exitCode` as readonly; make the test double writable so
@@ -31,9 +39,15 @@ function createShellProcess(
shellId: string,
process: ChildProcess,
): ShellProcess {
+ const outputFiles = manager.createOutputFiles(shellId);
+ // Hand the double out through the default ChildProcessBackend so kill paths
+ // run through the real backend.
+ spawnSpy.mockReturnValueOnce(process);
+ manager.backend.spawn({ args: [], cmd: 'mock' }, { env: {}, outputFiles, shellId });
+
return {
exitCode: process.exitCode,
- outputFiles: manager.createOutputFiles(shellId),
+ outputFiles,
process,
};
}
diff --git a/packages/local-file-shell/src/shell/backend.ts b/packages/local-file-shell/src/shell/backend.ts
new file mode 100644
index 00000000000..0b1553808ec
--- /dev/null
+++ b/packages/local-file-shell/src/shell/backend.ts
@@ -0,0 +1,95 @@
+/**
+ * Pluggable execution layer under `runCommand`.
+ *
+ * `ShellProcessManager` owns everything a caller sees β€” shell ids, output
+ * files, observation windows, previews β€” and delegates only the process
+ * lifecycle to a backend. The contract is shaped for three implementations:
+ * the non-interactive `child_process` one used today, a pseudo-terminal one
+ * (interactive + streaming) and a tmux one (interactive + streaming +
+ * persistent). Everything beyond spawn/kill is optional and advertised through
+ * `capabilities`, so callers branch on a flag instead of on the backend type.
+ */
+
+/** Output files a command writes into; created by the manager before spawn. */
+export interface ShellOutputFile {
+ fd: number;
+ /** Tracks the parent fd only; child stdio close is tracked by ShellProcess.closedAt. */
+ fdClosed?: boolean;
+ path: string;
+}
+
+export interface ShellOutputFiles {
+ stderr: ShellOutputFile;
+ stdout: ShellOutputFile;
+}
+
+/** A fully resolved launch β€” shell selection and sandbox wrapping already applied. */
+export interface ShellLaunchCommand {
+ args: string[];
+ cmd: string;
+}
+
+export interface ShellSpawnOptions {
+ /** Terminal width, for backends that allocate a terminal. */
+ cols?: number;
+ cwd?: string;
+ // Structural type instead of NodeJS.ProcessEnv: app tsconfigs augment
+ // ProcessEnv with required members, which would leak into this shared
+ // package's API and break callers/tests that build plain env objects.
+ env: Record<string, string | undefined>;
+ /**
+ * Where output must land. The manager closes its own copies of these fds as
+ * soon as `spawn` returns, so a backend that writes output itself (rather
+ * than handing the fds to the child) has to open its own streams on `path`.
+ */
+ outputFiles: ShellOutputFiles;
+ /** Terminal height, for backends that allocate a terminal. */
+ rows?: number;
+ /** Id the manager will address this command by in `write` / `kill` / `onOutput`. */
+ shellId: string;
+}
+
+/**
+ * Lifecycle view of a running command. `ChildProcess` satisfies it as-is;
+ * other backends adapt their native process object to the same events:
+ * `exit` when the command ends, `close` once its output is fully flushed,
+ * `error` when it could not be started.
+ */
+export interface ShellHandle {
+ readonly exitCode: number | null;
+ off: (event: 'close' | 'error' | 'exit', listener: (...args: any[]) => void) => unknown;
+ on: (event: 'close' | 'error' | 'exit', listener: (...args: any[]) => void) => unknown;
+ once: (event: 'close' | 'error' | 'exit', listener: (...args: any[]) => void) => unknown;
+ readonly pid?: number;
+ readonly signalCode: NodeJS.Signals | null;
+}
+
+export interface ShellBackendCapabilities {
+ /** `write` can feed input to a running command. */
+ interactive: boolean;
+ /** Commands survive the host process and can be reattached. */
+ persistent: boolean;
+ /** `onOutput` delivers output as it is produced. */
+ streaming: boolean;
+}
+
+export interface ShellOutputChunk {
+ data: string;
+ stream: 'stderr' | 'stdout';
+}
+
+export interface ShellBackend {
+ readonly capabilities: ShellBackendCapabilities;
+ /** Whether this backend can run on the current host (e.g. tmux installed). Absent means always. */
+ isAvailable?: () => boolean | Promise<boolean>;
+ /** Terminate the command and everything it started. Throws when that fails. */
+ kill: (shellId: string) => void;
+ readonly name: string;
+ /** Subscribe to live output. Present only when `capabilities.streaming`. Returns an unsubscribe. */
+ onOutput?: (shellId: string, listener: (chunk: ShellOutputChunk) => void) => () => void;
+ /** Forget a command the manager no longer tracks. */
+ release?: (shellId: string) => void;
+ spawn: (command: ShellLaunchCommand, options: ShellSpawnOptions) => ShellHandle;
+ /** Send input to a running command. Present only when `capabilities.interactive`. */
+ write?: (shellId: string, data: string) => void;
+}
diff --git a/packages/local-file-shell/src/shell/child-process-backend.ts b/packages/local-file-shell/src/shell/child-process-backend.ts
new file mode 100644
index 00000000000..65a7fe82c5a
--- /dev/null
+++ b/packages/local-file-shell/src/shell/child-process-backend.ts
@@ -0,0 +1,73 @@
+import type { ChildProcess } from 'node:child_process';
+import { spawn as spawnChildProcess } from 'node:child_process';
+
+import treeKill from 'tree-kill';
+
+import type {
+ ShellBackend,
+ ShellBackendCapabilities,
+ ShellHandle,
+ ShellLaunchCommand,
+ ShellSpawnOptions,
+} from './backend';
+
+const KILL_SIGNAL: NodeJS.Signals = 'SIGKILL';
+
+/**
+ * Non-interactive backend: a plain `child_process` with stdin left as an
+ * unused pipe and stdout/stderr inherited straight into the output files.
+ */
+export class ChildProcessBackend implements ShellBackend {
+ readonly capabilities: ShellBackendCapabilities = {
+ interactive: false,
+ persistent: false,
+ streaming: false,
+ };
+
+ readonly name = 'child-process';
+
+ private processes = new Map<string, ChildProcess>();
+
+ /**
+ * @param spawnProcess - spawn implementation; a caller can pass one that
+ * registers each process with a tracker. Defaults to `child_process.spawn`.
+ */
+ constructor(private readonly spawnProcess: typeof spawnChildProcess = spawnChildProcess) {}
+
+ spawn(
+ { cmd, args }: ShellLaunchCommand,
+ { cwd, env, outputFiles, shellId }: ShellSpawnOptions,
+ ): ShellHandle {
+ const childProcess = this.spawnProcess(cmd, args, {
+ cwd,
+ detached: process.platform !== 'win32',
+ env: env as NodeJS.ProcessEnv,
+ shell: false,
+ stdio: ['pipe', outputFiles.stdout.fd, outputFiles.stderr.fd],
+ // The Electron main process is a GUI process without a console, so on
+ // Windows spawning a console program (powershell.exe / cmd.exe) allocates
+ // a new console window that flashes up for every command. windowsHide
+ // defaults to false in Node, so it must be set explicitly.
+ windowsHide: true,
+ });
+ this.processes.set(shellId, childProcess);
+
+ return childProcess;
+ }
+
+ kill(shellId: string): void {
+ const childProcess = this.processes.get(shellId);
+ if (!childProcess) throw new Error(`Shell ID ${shellId} not found`);
+
+ if (childProcess.pid) {
+ treeKill(childProcess.pid, KILL_SIGNAL);
+ return;
+ }
+
+ childProcess.kill(KILL_SIGNAL);
+ }
+
+ release(shellId: string): void {
+ this.processes.delete(shellId);
+ }
+}
diff --git a/packages/local-file-shell/src/shell/index.ts b/packages/local-file-shell/src/shell/index.ts
index 8d658027ac0..9bda50af350 100644
--- a/packages/local-file-shell/src/shell/index.ts
+++ b/packages/local-file-shell/src/shell/index.ts
@@ -1,3 +1,14 @@
+export type {
+ ShellBackend,
+ ShellBackendCapabilities,
+ ShellHandle,
+ ShellLaunchCommand,
+ ShellOutputChunk,
+ ShellOutputFile,
+ ShellOutputFiles,
+ ShellSpawnOptions,
+} from './backend';
+export { ChildProcessBackend } from './child-process-backend';
export { decodeClixml } from './clixml';
export type { ShellProcess } from './process-manager';
export { ShellProcessManager } from './process-manager';
diff --git a/packages/local-file-shell/src/shell/process-manager.ts b/packages/local-file-shell/src/shell/process-manager.ts
index 3a6f0aaa7a2..4c47e427c9a 100644
--- a/packages/local-file-shell/src/shell/process-manager.ts
+++ b/packages/local-file-shell/src/shell/process-manager.ts
@@ -1,12 +1,11 @@
-import type { ChildProcess } from 'node:child_process';
import { randomBytes } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import treeKill from 'tree-kill';
-
import type { GetCommandOutputParams, GetCommandOutputResult, KillCommandResult } from '../types';
+import type { ShellBackend, ShellHandle, ShellOutputFile, ShellOutputFiles } from './backend';
+import { ChildProcessBackend } from './child-process-backend';
import { decodeClixml } from './clixml';
import { buildOutputPreview } from './utils';
@@ -68,27 +67,18 @@ const GET_COMMAND_OUTPUT_HEAD_RATIO = 0;
const OUTPUT_PREVIEW_TOTAL_MAX_BYTES = 22 * 1024;
const OUTPUT_PREVIEW_STREAM_MAX_BYTES = 18 * 1024;
const OUTPUT_PREVIEW_SECONDARY_MIN_BYTES = 4 * 1024;
-const KILL_SIGNAL: NodeJS.Signals = 'SIGKILL';
-export interface ShellOutputFile {
- fd: number;
- /** Tracks the parent fd only; child stdio close is tracked by ShellProcess.closedAt. */
- fdClosed?: boolean;
- path: string;
-}
-
-export interface ShellOutputFiles {
- stderr: ShellOutputFile;
- stdout: ShellOutputFile;
-}
+export type { ShellOutputFile, ShellOutputFiles } from './backend';
export interface ShellProcess {
+ /** Backend that spawned the command; defaults to the manager's own. */
+ backend?: ShellBackend;
closed?: Promise<void>;
closedAt?: number;
endedAt?: number;
exitCode: number | null;
outputFiles: ShellOutputFiles;
- process: ChildProcess;
+ process: ShellHandle;
spawnError?: Error;
startedAt?: number;
}
@@ -104,6 +94,9 @@ const shellNotFoundError = (shellId: string): string =>
`Shell ID ${shellId} not found in this device process. It may have been started by a different or restarted process; its output is not available here.`;
export class ShellProcessManager {
+ /** Default backend for commands spawned through this manager. */
+ readonly backend: ShellBackend;
+
private nextShellId = 1;
/**
@@ -118,7 +111,8 @@ export class ShellProcessManager {
private processes = new Map<string, ShellProcess>();
- constructor(outputRoot?: string) {
+ constructor(outputRoot?: string, backend: ShellBackend = new ChildProcessBackend()) {
+ this.backend = backend;
const date = new Date();
this.outputRunDir = path.join(
@@ -222,13 +216,13 @@ export class ShellProcessManager {
};
}
- const { process: childProcess } = shellProcess;
+ const { process: handle } = shellProcess;
- let exitCode = childProcess.exitCode ?? shellProcess.exitCode;
+ let exitCode = handle.exitCode ?? shellProcess.exitCode;
// A signal-terminated child (killCommand on POSIX) never gets an exitCode
// and its 'exit' event has already fired β€” waiting would just burn the
// full observation timeout before returning the killed command's output.
- if (exitCode === null && childProcess.signalCode == null) {
+ if (exitCode === null && handle.signalCode == null) {
const budget =
typeof timeout === 'number' && Number.isFinite(timeout)
? Math.min(Math.max(Math.trunc(timeout), 0), MAX_OBSERVATION_TIMEOUT_MS)
@@ -244,11 +238,11 @@ export class ShellProcessManager {
await Promise.race([
new Promise<void>((resolve) => {
onError = resolve;
- childProcess.once('error', onError);
+ handle.once('error', onError);
}),
new Promise<void>((resolve) => {
onExit = resolve;
- childProcess.once('exit', onExit);
+ handle.once('exit', onExit);
}),
new Promise<void>((resolve) => {
timer = setTimeout(resolve, waitTimeout);
@@ -256,13 +250,13 @@ export class ShellProcessManager {
]);
} finally {
if (timer) clearTimeout(timer);
- if (onError) childProcess.off('error', onError);
- if (onExit) childProcess.off('exit', onExit);
+ if (onError) handle.off('error', onError);
+ if (onExit) handle.off('exit', onExit);
}
}
}
- exitCode = childProcess.exitCode ?? shellProcess.exitCode;
+ exitCode = handle.exitCode ?? shellProcess.exitCode;
if (exitCode !== null) {
shellProcess.endedAt ??= Date.now();
await shellProcess.closed;
@@ -310,7 +304,7 @@ export class ShellProcessManager {
// without one, and so does a child that failed to spawn. Leaving the caller
// to guess from `exit_code` alone is how a killed session gets described as
// still running.
- const signal = childProcess.signalCode ?? undefined;
+ const signal = handle.signalCode ?? undefined;
const running = exitCode === null && !signal && !shellProcess.spawnError;
return {
@@ -345,7 +339,7 @@ export class ShellProcessManager {
}
try {
- killProcessTree(shellProcess.process);
+ (shellProcess.backend ?? this.backend).kill(shell_id);
// Keep the registry entry: getCommandOutput after a kill must still be
// able to return the output produced before termination, exactly like a
// naturally-exited command. Output fds are closed by the 'close' handler
@@ -358,11 +352,13 @@ export class ShellProcessManager {
cleanupAll(): void {
for (const [id, sp] of this.processes) {
+ const backend = sp.backend ?? this.backend;
try {
- killProcessTree(sp.process);
+ backend.kill(id);
} catch {
// Ignore
}
+ backend.release?.(id);
this.closeOutputFiles(sp.outputFiles);
this.processes.delete(id);
}
@@ -398,17 +394,6 @@ export class ShellProcessManager {
}
}
-const killProcessTree = (childProcess: ChildProcess): void => {
- const { pid } = childProcess;
-
- if (pid) {
- treeKill(pid, KILL_SIGNAL);
- return;
- }
-
- childProcess.kill(KILL_SIGNAL);
-};
-
// Keep the inline preview under the model-facing budget while preserving both
// streams when stdout and stderr are both present.
const allocateOutputPreviewBytes = (
diff --git a/packages/local-file-shell/src/shell/runner.ts b/packages/local-file-shell/src/shell/runner.ts
index e5de5690c8b..031f8b8e174 100644
--- a/packages/local-file-shell/src/shell/runner.ts
+++ b/packages/local-file-shell/src/shell/runner.ts
@@ -1,15 +1,19 @@
-import { spawn } from 'node:child_process';
+import type { spawn } from 'node:child_process';
import { stat } from 'node:fs/promises';
import os from 'node:os';
import type { SandboxPolicy } from '@lobechat/device-sandbox';
import type { RunCommandParams, RunCommandResult } from '../types';
-import type { ShellOutputFiles, ShellProcess, ShellProcessManager } from './process-manager';
+import type { ShellBackend, ShellOutputFiles } from './backend';
+import { ChildProcessBackend } from './child-process-backend';
+import type { ShellProcess, ShellProcessManager } from './process-manager';
import { DEFAULT_OBSERVATION_TIMEOUT_MS } from './process-manager';
import { detectWindowsShell, getShellConfig, normalizeEnvVarRefs } from './utils';
export interface RunCommandOptions {
+ /** Backend to spawn with; defaults to the process manager's own. */
+ backend?: ShellBackend;
logger?: {
debug: (...args: any[]) => void;
error: (...args: any[]) => void;
@@ -30,6 +34,10 @@ export interface RunCommandOptions {
onSandboxUnavailable?: (error: Error) => void;
processManager: ShellProcessManager;
sandboxPolicy?: SandboxPolicy;
+ /**
+ * Spawn function for the default child-process backend (e.g. one that
+ * registers the process with a tracker). Ignored when {@link backend} is set.
+ */
spawnProcess?: typeof spawn;
}
@@ -59,17 +67,23 @@ export async function runCommand(
timeout = DEFAULT_OBSERVATION_TIMEOUT_MS,
}: RunCommandParams,
{
+ backend: backendOverride,
processManager,
logger,
onSandboxUnavailable,
sandboxPolicy,
- spawnProcess = spawn,
+ spawnProcess,
}: RunCommandOptions,
): Promise<RunCommandResult> {
if (!command) {
return { error: 'command is required', success: false };
}
+ // A caller-supplied spawn function (the desktop's managed-process tracker)
+ // still runs through the child-process backend, so kill / release reach it.
+ const backend =
+ backendOverride ??
+ (spawnProcess ? new ChildProcessBackend(spawnProcess) : processManager.backend);
const logPrefix = `[runCommand: ${description || command.slice(0, 50)}]`;
logger?.debug(`${logPrefix} Starting`, { background: run_in_background, cwd, timeout });
@@ -128,31 +142,24 @@ export async function runCommand(
const shellId = processManager.createShellId();
const shellOutputFiles = processManager.createOutputFiles(shellId);
outputFiles = shellOutputFiles;
- const childProcess = spawnProcess(launchCommand.cmd, launchCommand.args, {
- cwd,
- detached: process.platform !== 'win32',
- env: launchEnv,
- shell: false,
- stdio: ['pipe', shellOutputFiles.stdout.fd, shellOutputFiles.stderr.fd],
- // The Electron main process is a GUI process without a console, so on
- // Windows spawning a console program (powershell.exe / cmd.exe) allocates
- // a new console window that flashes up for every command. windowsHide
- // defaults to false in Node, so it must be set explicitly.
- windowsHide: true,
- });
+ const handle = backend.spawn(
+ { args: launchCommand.args, cmd: launchCommand.cmd },
+ { cwd, env: launchEnv, outputFiles: shellOutputFiles, shellId },
+ );
const shellProcess: ShellProcess = {
+ backend,
exitCode: null,
outputFiles: shellOutputFiles,
- process: childProcess,
+ process: handle,
};
- childProcess.on('exit', (code) => {
+ handle.on('exit', (code: number | null) => {
logger?.debug(`${logPrefix} Process exited`, { code, shellId });
shellProcess.exitCode = code ?? 0;
});
- childProcess.on('error', (error) => {
+ handle.on('error', (error: Error) => {
logger?.error(`${logPrefix} Command failed:`, error);
const cwdContext = cwd ? ` (working directory: ${cwd})` : '';
shellProcess.spawnError = new Error(
@@ -163,7 +170,7 @@ export async function runCommand(
);
shellProcess.exitCode = 1;
});
- childProcess.once('close', () => releaseSandbox?.());
+ handle.once('close', () => releaseSandbox?.());
processManager.register(shellId, shellProcess);
// Close our fd copy only after error/close listeners are registered; spawn errors are asynchronous.