-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathLocalBaseRuntime.ts
More file actions
456 lines (406 loc) · 16.5 KB
/
LocalBaseRuntime.ts
File metadata and controls
456 lines (406 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
import { spawn } from "child_process";
import * as fs from "fs";
import * as fsPromises from "fs/promises";
import * as path from "path";
import { Readable, Writable } from "stream";
import type {
Runtime,
ExecOptions,
ExecStream,
FileStat,
WorkspaceCreationParams,
WorkspaceCreationResult,
WorkspaceInitParams,
WorkspaceInitResult,
WorkspaceForkParams,
WorkspaceForkResult,
InitLogger,
} from "./Runtime";
import { RuntimeError as RuntimeErrorClass } from "./Runtime";
import { NON_INTERACTIVE_ENV_VARS } from "@/common/constants/env";
import { getPreferredSpawnConfig } from "@/node/utils/main/bashPath";
import { EXIT_CODE_ABORTED, EXIT_CODE_TIMEOUT } from "@/common/constants/exitCodes";
import { DisposableProcess } from "@/node/utils/disposableExec";
import { expandTilde } from "./tildeExpansion";
import { log } from "@/node/services/log";
import {
checkInitHookExists,
getInitHookPath,
createLineBufferedLoggers,
getInitHookEnv,
} from "./initHook";
/**
* Abstract base class for local runtimes (both WorktreeRuntime and LocalRuntime).
*
* Provides shared implementation for:
* - exec() - Command execution with streaming I/O
* - readFile() - File reading with streaming
* - writeFile() - Atomic file writes with streaming
* - stat() - File statistics
* - resolvePath() - Path resolution with tilde expansion
* - normalizePath() - Path normalization
*
* Subclasses must implement workspace-specific methods:
* - getWorkspacePath()
* - createWorkspace()
* - initWorkspace()
* - deleteWorkspace()
* - renameWorkspace()
* - forkWorkspace()
*/
export abstract class LocalBaseRuntime implements Runtime {
async exec(command: string, options: ExecOptions): Promise<ExecStream> {
const startTime = performance.now();
// Use the specified working directory (must be a specific workspace path)
const cwd = options.cwd;
// Check if working directory exists before spawning
// This prevents confusing ENOENT errors from spawn()
try {
await fsPromises.access(cwd);
} catch (err) {
throw new RuntimeErrorClass(
`Working directory does not exist: ${cwd}`,
"exec",
err instanceof Error ? err : undefined
);
}
// Get spawn config for the preferred bash runtime
// This handles Git for Windows, WSL, and Unix/macOS automatically
// For WSL, paths in the command and cwd are translated to /mnt/... format
const {
command: bashCommand,
args: bashArgs,
cwd: spawnCwd,
} = getPreferredSpawnConfig(command, cwd);
// Debug logging for Windows WSL issues (skip noisy git status commands)
const isGitStatusCmd = command.includes("git status") || command.includes("show-branch") || command.includes("PRIMARY_BRANCH");
if (!isGitStatusCmd) {
log.info(`[LocalBaseRuntime.exec] Original command: ${command.substring(0, 100)}${command.length > 100 ? "..." : ""}`);
log.info(`[LocalBaseRuntime.exec] Spawn command: ${bashCommand}`);
log.info(`[LocalBaseRuntime.exec] Spawn args: ${JSON.stringify(bashArgs).substring(0, 200)}...`);
}
// If niceness is specified on Unix/Linux, spawn nice directly to avoid escaping issues
// Windows doesn't have nice command, so just spawn bash directly
const isWindows = process.platform === "win32";
const spawnCommand = options.niceness !== undefined && !isWindows ? "nice" : bashCommand;
const spawnArgs =
options.niceness !== undefined && !isWindows
? ["-n", options.niceness.toString(), bashCommand, ...bashArgs]
: bashArgs;
// On Windows with PowerShell wrapper, detached:true creates a separate console
// which interferes with output capture. Only use detached on non-Windows.
// On Windows, PowerShell's -WindowStyle Hidden handles console hiding.
const useDetached = !isWindows;
const childProcess = spawn(spawnCommand, spawnArgs, {
cwd: spawnCwd,
env: {
...process.env,
...(options.env ?? {}),
...NON_INTERACTIVE_ENV_VARS,
},
stdio: ["pipe", "pipe", "pipe"],
// CRITICAL: Spawn as detached process group leader to enable cleanup of background processes.
// When a bash script spawns background processes (e.g., `sleep 100 &`), we need to kill
// the entire process group (including all backgrounded children) via process.kill(-pid).
// NOTE: detached:true does NOT cause bash to wait for background jobs when using 'exit' event
// instead of 'close' event. The 'exit' event fires when bash exits, ignoring background children.
// WINDOWS NOTE: detached:true causes issues with PowerShell wrapper output capture.
detached: useDetached,
// Prevent console window from appearing on Windows (WSL bash spawns steal focus otherwise)
windowsHide: true,
});
// Wrap in DisposableProcess for automatic cleanup
const disposable = new DisposableProcess(childProcess);
// Convert Node.js streams to Web Streams
const stdout = Readable.toWeb(childProcess.stdout) as unknown as ReadableStream<Uint8Array>;
const stderr = Readable.toWeb(childProcess.stderr) as unknown as ReadableStream<Uint8Array>;
const stdin = Writable.toWeb(childProcess.stdin) as unknown as WritableStream<Uint8Array>;
// No stream cleanup in DisposableProcess - streams close naturally when process exits
// bash.ts handles cleanup after waiting for exitCode
// Track if we killed the process due to timeout or abort
let timedOut = false;
let aborted = false;
// Debug: log raw stdout/stderr from the child process (only for non-git-status commands)
let debugStdout = "";
let debugStderr = "";
if (!isGitStatusCmd) {
childProcess.stdout?.on("data", (chunk: Buffer) => {
debugStdout += chunk.toString();
});
childProcess.stderr?.on("data", (chunk: Buffer) => {
debugStderr += chunk.toString();
});
}
// Create promises for exit code and duration
// Uses special exit codes (EXIT_CODE_ABORTED, EXIT_CODE_TIMEOUT) for expected error conditions
const exitCode = new Promise<number>((resolve, reject) => {
// Use 'exit' event instead of 'close' to handle background processes correctly.
// The 'close' event waits for ALL child processes (including background ones) to exit,
// which causes hangs when users spawn background processes like servers.
// The 'exit' event fires when the main bash process exits, which is what we want.
childProcess.on("exit", (code) => {
if (!isGitStatusCmd) {
log.info(`[LocalBaseRuntime.exec] Process exited with code: ${code}`);
log.info(`[LocalBaseRuntime.exec] stdout length: ${debugStdout.length}`);
log.info(`[LocalBaseRuntime.exec] stdout: ${debugStdout.substring(0, 500)}${debugStdout.length > 500 ? "..." : ""}`);
if (debugStderr) {
log.info(`[LocalBaseRuntime.exec] stderr: ${debugStderr.substring(0, 500)}${debugStderr.length > 500 ? "..." : ""}`);
}
}
// Clean up any background processes (process group cleanup)
// This prevents zombie processes when scripts spawn background tasks
if (childProcess.pid !== undefined) {
try {
// Kill entire process group with SIGKILL - cannot be caught/ignored
// Use negative PID to signal the entire process group
process.kill(-childProcess.pid, "SIGKILL");
} catch {
// Process group already dead or doesn't exist - ignore
}
}
// Check abort first (highest priority)
if (aborted || options.abortSignal?.aborted) {
resolve(EXIT_CODE_ABORTED);
return;
}
// Check if we killed the process due to timeout
if (timedOut) {
resolve(EXIT_CODE_TIMEOUT);
return;
}
resolve(code ?? 0);
// Cleanup runs automatically via DisposableProcess
});
childProcess.on("error", (err) => {
reject(new RuntimeErrorClass(`Failed to execute command: ${err.message}`, "exec", err));
});
});
const duration = exitCode.then(() => performance.now() - startTime);
// Register process group cleanup with DisposableProcess
// This ensures ALL background children are killed when process exits
disposable.addCleanup(() => {
if (childProcess.pid === undefined) return;
try {
// Kill entire process group with SIGKILL - cannot be caught/ignored
process.kill(-childProcess.pid, "SIGKILL");
} catch {
// Process group already dead or doesn't exist - ignore
}
});
// Handle abort signal
if (options.abortSignal) {
options.abortSignal.addEventListener("abort", () => {
aborted = true;
disposable[Symbol.dispose](); // Kill process and run cleanup
});
}
// Handle timeout
if (options.timeout !== undefined) {
const timeoutHandle = setTimeout(() => {
timedOut = true;
disposable[Symbol.dispose](); // Kill process and run cleanup
}, options.timeout * 1000);
// Clear timeout if process exits naturally
void exitCode.finally(() => clearTimeout(timeoutHandle));
}
return { stdout, stderr, stdin, exitCode, duration };
}
readFile(filePath: string, _abortSignal?: AbortSignal): ReadableStream<Uint8Array> {
// Note: _abortSignal ignored for local operations (fast, no need for cancellation)
const nodeStream = fs.createReadStream(filePath);
// Handle errors by wrapping in a transform
const webStream = Readable.toWeb(nodeStream) as unknown as ReadableStream<Uint8Array>;
return new ReadableStream<Uint8Array>({
async start(controller: ReadableStreamDefaultController<Uint8Array>) {
try {
const reader = webStream.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
controller.enqueue(value);
}
controller.close();
} catch (err) {
controller.error(
new RuntimeErrorClass(
`Failed to read file ${filePath}: ${err instanceof Error ? err.message : String(err)}`,
"file_io",
err instanceof Error ? err : undefined
)
);
}
},
});
}
writeFile(filePath: string, _abortSignal?: AbortSignal): WritableStream<Uint8Array> {
// Note: _abortSignal ignored for local operations (fast, no need for cancellation)
let tempPath: string;
let writer: WritableStreamDefaultWriter<Uint8Array>;
let resolvedPath: string;
let originalMode: number | undefined;
return new WritableStream<Uint8Array>({
async start() {
// Resolve symlinks to write through them (preserves the symlink)
try {
resolvedPath = await fsPromises.realpath(filePath);
// Save original permissions to restore after write
const stat = await fsPromises.stat(resolvedPath);
originalMode = stat.mode;
} catch {
// If file doesn't exist, use the original path and default permissions
resolvedPath = filePath;
originalMode = undefined;
}
// Create parent directories if they don't exist
const parentDir = path.dirname(resolvedPath);
await fsPromises.mkdir(parentDir, { recursive: true });
// Create temp file for atomic write
tempPath = `${resolvedPath}.tmp.${Date.now()}`;
const nodeStream = fs.createWriteStream(tempPath);
const webStream = Writable.toWeb(nodeStream) as WritableStream<Uint8Array>;
writer = webStream.getWriter();
},
async write(chunk: Uint8Array) {
await writer.write(chunk);
},
async close() {
// Close the writer and rename to final location
await writer.close();
try {
// If we have original permissions, apply them to temp file before rename
if (originalMode !== undefined) {
await fsPromises.chmod(tempPath, originalMode);
}
await fsPromises.rename(tempPath, resolvedPath);
} catch (err) {
throw new RuntimeErrorClass(
`Failed to write file ${filePath}: ${err instanceof Error ? err.message : String(err)}`,
"file_io",
err instanceof Error ? err : undefined
);
}
},
async abort(reason?: unknown) {
// Clean up temp file on abort
await writer.abort();
try {
await fsPromises.unlink(tempPath);
} catch {
// Ignore errors cleaning up temp file
}
throw new RuntimeErrorClass(
`Failed to write file ${filePath}: ${String(reason)}`,
"file_io"
);
},
});
}
async stat(filePath: string, _abortSignal?: AbortSignal): Promise<FileStat> {
// Note: _abortSignal ignored for local operations (fast, no need for cancellation)
try {
const stats = await fsPromises.stat(filePath);
return {
size: stats.size,
modifiedTime: stats.mtime,
isDirectory: stats.isDirectory(),
};
} catch (err) {
throw new RuntimeErrorClass(
`Failed to stat ${filePath}: ${err instanceof Error ? err.message : String(err)}`,
"file_io",
err instanceof Error ? err : undefined
);
}
}
resolvePath(filePath: string): Promise<string> {
// Expand tilde to actual home directory path
const expanded = expandTilde(filePath);
// Resolve to absolute path (handles relative paths like "./foo")
return Promise.resolve(path.resolve(expanded));
}
normalizePath(targetPath: string, basePath: string): string {
// For local runtime, use Node.js path resolution
// Handle special case: current directory
const target = targetPath.trim();
if (target === ".") {
return path.resolve(basePath);
}
return path.resolve(basePath, target);
}
// Abstract methods that subclasses must implement
abstract getWorkspacePath(projectPath: string, workspaceName: string): string;
abstract createWorkspace(params: WorkspaceCreationParams): Promise<WorkspaceCreationResult>;
abstract initWorkspace(params: WorkspaceInitParams): Promise<WorkspaceInitResult>;
abstract renameWorkspace(
projectPath: string,
oldName: string,
newName: string,
abortSignal?: AbortSignal
): Promise<
{ success: true; oldPath: string; newPath: string } | { success: false; error: string }
>;
abstract deleteWorkspace(
projectPath: string,
workspaceName: string,
force: boolean,
abortSignal?: AbortSignal
): Promise<{ success: true; deletedPath: string } | { success: false; error: string }>;
abstract forkWorkspace(params: WorkspaceForkParams): Promise<WorkspaceForkResult>;
/**
* Helper to run .mux/init hook if it exists and is executable.
* Shared between WorktreeRuntime and LocalRuntime.
*/
protected async runInitHook(
projectPath: string,
workspacePath: string,
initLogger: InitLogger,
runtimeType: "local" | "worktree"
): Promise<void> {
// Check if hook exists and is executable
const hookExists = await checkInitHookExists(projectPath);
if (!hookExists) {
return;
}
const hookPath = getInitHookPath(projectPath);
initLogger.logStep(`Running init hook: ${hookPath}`);
// Create line-buffered loggers
const loggers = createLineBufferedLoggers(initLogger);
return new Promise<void>((resolve) => {
// Get spawn config for the preferred bash runtime
// For WSL, the hook path and cwd are translated to /mnt/... format
const {
command: bashCommand,
args: bashArgs,
cwd: spawnCwd,
} = getPreferredSpawnConfig(`"${hookPath}"`, workspacePath);
const proc = spawn(bashCommand, bashArgs, {
cwd: spawnCwd,
stdio: ["ignore", "pipe", "pipe"],
env: {
...process.env,
...getInitHookEnv(projectPath, runtimeType),
},
// Prevent console window from appearing on Windows
windowsHide: true,
});
proc.stdout?.on("data", (data: Buffer) => {
loggers.stdout.append(data.toString());
});
proc.stderr?.on("data", (data: Buffer) => {
loggers.stderr.append(data.toString());
});
proc.on("close", (code) => {
// Flush any remaining buffered output
loggers.stdout.flush();
loggers.stderr.flush();
initLogger.logComplete(code ?? 0);
resolve();
});
proc.on("error", (err) => {
initLogger.logStderr(`Error running init hook: ${err.message}`);
initLogger.logComplete(-1);
resolve();
});
});
}
}