@anhlp/alp-daemon 0.0.1-beta.7 → 0.0.1-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/terminals.ts CHANGED
@@ -27,13 +27,23 @@ export type TerminalSink = { send(message: unknown): void; socket?: { writableLe
27
27
  type Disposable = { dispose(): void };
28
28
  /** Native owner interface; injected owners are used only by tests. */
29
29
  export type PtyProcess = {
30
- pid: number;
30
+ /**
31
+ * The shell's pid, read live on every access: never copy it at spawn. The win32 owner reports 0
32
+ * until node-pty's ConPTY output worker connects, then the real pid (windows-terminal.ts).
33
+ */
34
+ readonly pid: number;
31
35
  /** The PTY's device (node-pty's UnixTerminal), such as /dev/ttys004 or /dev/pts/3. */
32
36
  readonly ptsName?: string;
33
37
  write(data: string): void;
34
38
  resize(cols: number, rows: number): void;
35
39
  kill(signal?: string): void;
36
40
  cleanup?: () => Promise<CleanupResult>;
41
+ /**
42
+ * The win32 owner (no native cleanup): resolves once node-pty reports the killed shell's exit, or
43
+ * after `ms`. `kill` only asks node-pty to end the shell; until Windows has closed the shell's
44
+ * handles, its working directory (the workspace) stays open and cannot be removed (EBUSY, t-bfbd).
45
+ */
46
+ exited?: (ms: number) => Promise<void>;
37
47
  onData(listener: (data: string) => void): Disposable;
38
48
  onExit(listener: (event: { exitCode: number | null; signal?: number }) => void): Disposable;
39
49
  };
@@ -77,7 +87,6 @@ type Terminal = {
77
87
  rows: number;
78
88
  pty: PtyProcess;
79
89
  screen: TerminalScreen;
80
- pid: number;
81
90
  /** The PTY's device as ps names it (ttys004, pts/3): a controlling terminal outlives double forks. */
82
91
  tty?: string;
83
92
  createdAt: number;
@@ -257,7 +266,10 @@ export function createTerminalService(options: TerminalServiceOptions) {
257
266
  const cancel = (entry: Pending, reason: string) => { entry.reason ??= reason; entry.controller.abort(); };
258
267
  const refused = (reason: string) => new RpcError(ERROR.unavailable, 'Terminal startup was cancelled or its native owner is unavailable', { reason });
259
268
  async function cleanup(owner: PtyProcess, id?: string) {
260
- if (!owner.cleanup) { owner.kill(); return; } // test owners and the win32 node-pty owner (best-effort)
269
+ // Test owners and the win32 node-pty owner (best-effort): the win32 owner is waited for, so a
270
+ // closed terminal no longer holds its directory. No retry here: cleanup removes nothing; whoever
271
+ // removes the workspace afterwards (a worktree removal) reports its own failure.
272
+ if (!owner.cleanup) { owner.kill(); await owner.exited?.(killGraceMs); return; }
261
273
  const result = await owner.cleanup();
262
274
  if (result.coverage === 'root-only') log.info('terminal shell cleanup has reduced coverage; descendants are unmanaged', { code: 'ALPD_TERMINAL_ROOT_ONLY_CLEANUP', terminalId: id, outputOpen: result.outputOpen === true });
263
275
  if (result.live || result.uncertain) {
@@ -491,7 +503,7 @@ export function createTerminalService(options: TerminalServiceOptions) {
491
503
  }
492
504
  const terminal: Terminal = {
493
505
  id: `term_${randomBytes(16).toString('hex')}`, principal: { id: principal.id, epoch: principal.epoch }, workspaceId: params.workspaceId,
494
- root, ...(protection ? { protection } : {}), title: path.basename(file).slice(0, 64), cols: params.cols, rows: params.rows, pty: process_, pid: process_.pid, screen: new TerminalScreen(params.cols, params.rows),
506
+ root, ...(protection ? { protection } : {}), title: path.basename(file).slice(0, 64), cols: params.cols, rows: params.rows, pty: process_, screen: new TerminalScreen(params.cols, params.rows),
495
507
  ...(typeof process_.ptsName === 'string' && process_.ptsName.startsWith('/dev/') ? { tty: process_.ptsName.slice('/dev/'.length) } : {}),
496
508
  createdAt: at, lastActivityAt: at, expiresAt: at + limits.maxLifetimeMs, requestKey, ring: [], ringBytes: 0, nextSeq: 1,
497
509
  detachedAt: at, marker, disposables: [],
@@ -634,8 +646,8 @@ export function createTerminalService(options: TerminalServiceOptions) {
634
646
  if (cleanupFault || outcomes.some(result => result.status === 'rejected')) throw refused('terminal_cleanup_uncertain');
635
647
  },
636
648
 
637
- /** Test hook: pids of every running terminal's shell. */
638
- pids() { return [...terminals.values()].filter(terminal => !terminal.exit).map(terminal => terminal.pid); },
649
+ /** Test hook: pids of every running terminal's shell (read live: the win32 owner learns it after spawn). */
650
+ pids() { return [...terminals.values()].filter(terminal => !terminal.exit).map(terminal => terminal.pty.pid); },
639
651
  };
640
652
  }
641
653
  export type TerminalService = ReturnType<typeof createTerminalService>;
@@ -6,7 +6,8 @@
6
6
  import { createRequire } from 'node:module';
7
7
  import type { PtySpawn } from './terminals.js';
8
8
 
9
- type NodePty = { spawn(file: string, args: string[], options: Record<string, unknown>): {
9
+ /** The node-pty surface the win32 owner uses. */
10
+ export type NodePty = { spawn(file: string, args: string[], options: Record<string, unknown>): {
10
11
  pid: number; write(data: string): void; resize(cols: number, rows: number): void; kill(signal?: string): void;
11
12
  onData(listener: (data: string) => void): { dispose(): void }; onExit(listener: (event: { exitCode: number; signal?: number }) => void): { dispose(): void };
12
13
  } };
@@ -20,8 +21,9 @@ export function loadNodePty(): NodePty | undefined {
20
21
  return loaded ?? undefined;
21
22
  }
22
23
 
23
- export function windowsTerminalCapability(): { available: boolean; protection?: 'none'; reason?: string } {
24
- return loadNodePty() ? { available: true, protection: 'none' } : { available: false, reason: 'node_pty_unavailable' };
24
+ /** `load` is a test hook (tests/windows-terminal.test.js); production loads the installed node-pty. */
25
+ export function windowsTerminalCapability(load: () => NodePty | undefined = loadNodePty): { available: boolean; protection?: 'none'; reason?: string } {
26
+ return load() ? { available: true, protection: 'none' } : { available: false, reason: 'node_pty_unavailable' };
25
27
  }
26
28
 
27
29
  /** The shell for a Windows terminal: COMSPEC when absolute, else cmd.exe. */
@@ -30,20 +32,43 @@ export function windowsShell(env: NodeJS.ProcessEnv = process.env): string {
30
32
  return candidate && /^[a-zA-Z]:[\\/]/.test(candidate) ? candidate : 'cmd.exe';
31
33
  }
32
34
 
33
- export const windowsPtySpawn: PtySpawn = (file, args, options) => {
35
+ /** The win32 owner over `load`'s node-pty; `load` is a test hook, production uses {@link windowsPtySpawn}. */
36
+ export const createWindowsPtySpawn = (load: () => NodePty | undefined = loadNodePty): PtySpawn => (file, args, options) => {
34
37
  if (options.signal?.aborted) throw new Error('Terminal startup cancelled');
35
- const pty = loadNodePty();
38
+ const pty = load();
36
39
  if (!pty) throw new Error('node-pty is unavailable on this host');
37
40
  const child = pty.spawn(file, args, { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true });
38
41
  let killed = false;
42
+ // Waited for after kill so that a closed terminal no longer holds its working directory (t-bfbd).
43
+ // process.kill(pid, 0) is not that point: libuv reads the exit code, which Windows sets before it
44
+ // closes the shell's handles, the cwd among them (rmdir right after a TerminateProcess: EBUSY).
45
+ // node-pty emits exit when its output socket closes (after kill: ClosePseudoConsole, then the conout
46
+ // drain); the exit code it carries is set only by its native WaitForSingleObject on the shell's process
47
+ // handle, which returns once those handles are closed. A numeric exit code therefore means the
48
+ // directory was released; the order of the two is what node-pty does, not something it promises
49
+ // (every exit after a kill carried a numeric code here, 200 of 200 on Windows 10). Best-effort, like
50
+ // the rest of the Windows owner. Subscribed here, before any service listener.
51
+ let exit = false;
52
+ const exited = new Promise<void>(resolve => { child.onExit(() => { exit = true; resolve(); }); });
39
53
  return {
40
- pid: child.pid,
54
+ // node-pty reports the ConPTY shell's pid only once its output worker connects (0 until then), so
55
+ // the pid is read live rather than copied at spawn.
56
+ get pid() { return child.pid; },
41
57
  write(data: string) { if (!killed) child.write(data); },
42
58
  resize(cols: number, rows: number) { if (!killed) try { child.resize(cols, rows); } catch { /* exited */ } },
43
59
  // Best-effort: node-pty ends the ConPTY session and its shell; descendants are not guaranteed.
44
60
  kill() { if (killed) return; killed = true; try { child.kill(); } catch { /* already exited */ } },
61
+ // Bounded: node-pty defers a kill until the terminal is ready (its first output) and may never report
62
+ // an exit (a terminal that never becomes ready, a lost callback); that does not hold up close.
63
+ async exited(ms: number) {
64
+ if (exit) return;
65
+ let timer: NodeJS.Timeout | undefined;
66
+ await Promise.race([exited, new Promise<void>(resolve => { timer = setTimeout(resolve, ms); })]);
67
+ clearTimeout(timer);
68
+ },
45
69
  onData: listener => child.onData(listener),
46
70
  onExit: listener => child.onExit(({ exitCode, signal }) => listener({ exitCode, signal })),
47
71
  };
48
72
  };
49
73
 
74
+ export const windowsPtySpawn: PtySpawn = createWindowsPtySpawn();