From b12ee82b58c16f6ea22820edb446ff207334da7a Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 00:49:16 -0700 Subject: [PATCH 01/13] perf(terminal): read the macOS process table in process instead of forking setuid ps (#31783) /bin/ps is setuid root, so every exec costs an uncached syspolicyd assessment and an EDR inspection. The terminal host forked ~7-10 ps/lsof per second with 4 agent panes, and each stale daemon multiplied that. node-pty's patched pty.node now exports processTable (sysctl KERN_PROC_ALL/KERN_PROCARGS2 on a worker thread), processCwd (PROC_PIDVNODEPATHINFO) and processPath (proc_pidpath). runPsInProcess renders the same ps column text for the invocations Orca issues, so the existing parsers and callers are unchanged; anything it cannot reproduce, non-macOS hosts, and builds without the exports keep running ps/lsof. Measured with 4 anchored panes polled every 750 ms for 60 s: ~440 ps/lsof children before, 0 after. --- config/patches/node-pty@1.1.0.patch | 274 ++++++++++++++- pnpm-lock.yaml | 6 +- src/main/daemon/daemon-process-inspection.ts | 8 + .../provider-process-row-read.ts | 21 +- src/main/providers/process-cwd.ts | 6 + src/main/pty-descendant-termination.ts | 31 +- src/main/pty/posix-pty-foreground-group.ts | 16 +- .../agent-session-process-identity-probe.ts | 23 +- src/main/runtime/terminal-foreground-group.ts | 18 +- src/shared/agent-process-presence-probe.ts | 21 +- .../cheap-process-table-snapshot-reader.ts | 5 + src/shared/darwin-terminal-names.ts | 18 +- src/shared/libproc-process-table.test.ts | 158 +++++++++ src/shared/libproc-process-table.ts | 318 ++++++++++++++++++ src/shared/process-table-snapshot-reader.ts | 5 + src/shared/shell-process-readiness.ts | 36 +- src/shared/tmux-host-attachment-probe.ts | 13 +- 17 files changed, 875 insertions(+), 102 deletions(-) create mode 100644 src/shared/libproc-process-table.test.ts create mode 100644 src/shared/libproc-process-table.ts diff --git a/config/patches/node-pty@1.1.0.patch b/config/patches/node-pty@1.1.0.patch index f3de8667f141..6cd57d06a86e 100644 --- a/config/patches/node-pty@1.1.0.patch +++ b/config/patches/node-pty@1.1.0.patch @@ -297,10 +297,10 @@ index 181ccabbbe9c4948a9725fb1db907a68e9de01fc..67f31facf85562b67adbfbd04ce28ddd process.send!({ consoleProcessList }); process.exit(0); diff --git a/src/unix/pty.cc b/src/unix/pty.cc -index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e7baac249 100644 +index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e1938e9ca 100644 --- a/src/unix/pty.cc +++ b/src/unix/pty.cc -@@ -23,7 +23,9 @@ +@@ -23,8 +23,11 @@ #include #include #include @@ -308,9 +308,11 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e #include +#include #include ++#include #include -@@ -47,6 +49,39 @@ + #include +@@ -47,6 +50,39 @@ #include #endif @@ -350,7 +352,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e /* Some platforms name VWERASE and VDISCARD differently */ #if !defined(VWERASE) && defined(VWERSE) #define VWERASE VWERSE -@@ -228,6 +263,9 @@ Napi::Value PtyGetProc(const Napi::CallbackInfo& info); +@@ -228,6 +264,9 @@ Napi::Value PtyGetProc(const Napi::CallbackInfo& info); static int pty_nonblock(int); @@ -360,7 +362,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e #if defined(__APPLE__) static char * pty_getproc(int); -@@ -237,13 +275,23 @@ pty_getproc(int, char *); +@@ -237,13 +276,23 @@ pty_getproc(int, char *); #endif #if defined(__APPLE__) || defined(__OpenBSD__) @@ -385,7 +387,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e #endif struct DelBuf { -@@ -345,8 +393,8 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { +@@ -345,8 +394,8 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { term->c_cc[VSTATUS] = 20; #endif @@ -396,7 +398,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e // helperPath std::string helper_path = info[9].As(); -@@ -367,14 +415,18 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { +@@ -367,14 +416,18 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { argv[i + 3] = strdup(arg.c_str()); } @@ -419,7 +421,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e #else int argc = argv_.Length(); int argl = argc + 2; -@@ -445,6 +497,9 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { +@@ -445,6 +498,9 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { if (pty_nonblock(master) == -1) { throw Napi::Error::New(napiEnv, "Could not set master fd to nonblocking."); } @@ -429,7 +431,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e } #endif -@@ -586,6 +641,23 @@ pty_nonblock(int fd) { +@@ -586,6 +642,23 @@ pty_nonblock(int fd) { return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } @@ -453,7 +455,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e /** * pty_getproc * Taken from tmux. -@@ -684,15 +756,73 @@ pty_getproc(int fd, char *tty) { +@@ -684,15 +757,73 @@ pty_getproc(int fd, char *tty) { #endif #if defined(__APPLE__) @@ -529,25 +531,25 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e for (; count < 3; count++) { low_fds[count] = posix_openpt(O_RDWR); -@@ -706,80 +836,118 @@ pty_posix_spawn(char** argv, char** env, +@@ -706,84 +837,342 @@ pty_posix_spawn(char** argv, char** env, POSIX_SPAWN_SETSID; *master = posix_openpt(O_RDWR); if (*master == -1) { - return; + pty_set_spawn_error(err, "posix_openpt", errno); ++ goto done; ++ } ++ ++ res = grantpt(*master); ++ if (res == -1) { ++ pty_set_spawn_error(err, "grantpt", errno); + goto done; } - int res = grantpt(*master) || unlockpt(*master); -+ res = grantpt(*master); ++ res = unlockpt(*master); if (res == -1) { - return; -+ pty_set_spawn_error(err, "grantpt", errno); -+ goto done; -+ } -+ -+ res = unlockpt(*master); -+ if (res == -1) { + pty_set_spawn_error(err, "unlockpt", errno); + goto done; } @@ -672,6 +674,242 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e } } #endif + ++#if defined(__APPLE__) ++/** ++ * Orca: in-process libproc/sysctl process table ++ * ++ * /bin/ps is setuid root, so every exec triggers an uncached syspolicyd ++ * assessment; pollers read the table here instead (#31783). ++ */ ++ ++static bool ++orca_read_process_args(pid_t pid, std::vector& buf, std::string* out) { ++ int mib[3] = { CTL_KERN, KERN_PROCARGS2, pid }; ++ size_t size = buf.size(); ++ if (sysctl(mib, 3, buf.data(), &size, NULL, 0) != 0 || size <= sizeof(int)) { ++ return false; ++ } ++ int argc; ++ memcpy(&argc, buf.data(), sizeof(argc)); ++ const char* cursor = buf.data() + sizeof(argc); ++ const char* end = buf.data() + size; ++ while (cursor < end && *cursor != '\0') cursor++; ++ while (cursor < end && *cursor == '\0') cursor++; ++ out->clear(); ++ for (int i = 0; i < argc && cursor < end; i++) { ++ size_t length = strnlen(cursor, end - cursor); ++ if (i > 0) out->push_back(' '); ++ out->append(cursor, length); ++ cursor += length + 1; ++ } ++ return argc > 0; ++} ++ ++static bool ++orca_read_kinfo_all(std::vector* procs) { ++ int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 }; ++ for (int attempt = 0; attempt < 8; attempt++) { ++ size_t size = 0; ++ if (sysctl(mib, 3, NULL, &size, NULL, 0) != 0) return false; ++ size += size / 8 + sizeof(struct kinfo_proc) * 16; ++ procs->resize(size / sizeof(struct kinfo_proc)); ++ if (sysctl(mib, 3, procs->data(), &size, NULL, 0) == 0) { ++ procs->resize(size / sizeof(struct kinfo_proc)); ++ return true; ++ } ++ if (errno != ENOMEM) return false; ++ } ++ return false; ++} ++ ++static bool ++orca_read_kinfo_pid(pid_t pid, struct kinfo_proc* proc) { ++ int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }; ++ size_t size = sizeof(*proc); ++ return sysctl(mib, 4, proc, &size, NULL, 0) == 0 && size == sizeof(*proc); ++} ++ ++struct orca_process_row { ++ struct kinfo_proc proc; ++ bool has_command; ++ std::string command; ++}; ++ ++// Runs on a worker thread: argv for ~2,000 processes costs ~17ms of syscalls. ++static bool ++orca_gather_process_table(bool include_command, ++ const std::vector* pids, ++ std::vector* rows) { ++ std::vector procs; ++ if (pids) { ++ for (pid_t pid : *pids) { ++ struct kinfo_proc proc; ++ if (orca_read_kinfo_pid(pid, &proc)) { ++ procs.push_back(proc); ++ } ++ } ++ } else if (!orca_read_kinfo_all(&procs)) { ++ return false; ++ } ++ std::vector args_buf; ++ if (include_command) { ++ int argmax = 0; ++ size_t argmax_size = sizeof(argmax); ++ int mib[2] = { CTL_KERN, KERN_ARGMAX }; ++ if (sysctl(mib, 2, &argmax, &argmax_size, NULL, 0) != 0 || argmax <= 0) { ++ argmax = 1024 * 1024; ++ } ++ args_buf.resize(argmax); ++ } ++ rows->reserve(procs.size()); ++ for (const struct kinfo_proc& proc : procs) { ++ pid_t pid = proc.kp_proc.p_pid; ++ if (pid <= 0) continue; ++ orca_process_row row = { proc, false, "" }; ++ if (include_command) { ++ row.has_command = orca_read_process_args(pid, args_buf, &row.command); ++ if (!row.has_command) { ++ // Another user's argv needs setuid ps; the executable path still names the program. ++ char path[PROC_PIDPATHINFO_MAXSIZE]; ++ int length = proc_pidpath(pid, path, sizeof(path)); ++ if (length > 0) { ++ row.command.assign(path, length); ++ row.has_command = true; ++ } ++ } ++ } ++ rows->push_back(std::move(row)); ++ } ++ return true; ++} ++ ++static Napi::Array ++orca_process_rows_to_js(Napi::Env env, bool include_command, const std::vector& rows) { ++ Napi::Array result = Napi::Array::New(env, rows.size()); ++ uint32_t index = 0; ++ for (const orca_process_row& entry : rows) { ++ const struct kinfo_proc& proc = entry.proc; ++ Napi::Object row = Napi::Object::New(env); ++ row.Set("pid", Napi::Number::New(env, proc.kp_proc.p_pid)); ++ row.Set("ppid", Napi::Number::New(env, proc.kp_eproc.e_ppid)); ++ row.Set("pgid", Napi::Number::New(env, proc.kp_eproc.e_pgid)); ++ row.Set("tpgid", Napi::Number::New(env, proc.kp_eproc.e_tpgid)); ++ row.Set("tdev", Napi::Number::New(env, proc.kp_eproc.e_tdev)); ++ row.Set("status", Napi::Number::New(env, proc.kp_proc.p_stat)); ++ row.Set("flags", Napi::Number::New(env, proc.kp_proc.p_flag)); ++ row.Set("sessionLeader", Napi::Boolean::New(env, (proc.kp_eproc.e_flag & EPROC_SLEADER) != 0)); ++ row.Set("startSec", Napi::Number::New(env, (double)proc.kp_proc.p_starttime.tv_sec)); ++ row.Set("comm", Napi::String::New(env, proc.kp_proc.p_comm, strnlen(proc.kp_proc.p_comm, sizeof(proc.kp_proc.p_comm)))); ++ if (include_command) { ++ row.Set("command", entry.has_command ? Napi::Value(Napi::String::New(env, entry.command)) : env.Null()); ++ } ++ result.Set(index++, row); ++ } ++ return result; ++} ++ ++static bool ++orca_read_pid_list(const Napi::CallbackInfo& info, std::vector* pids) { ++ if (info.Length() < 2 || !info[1].IsArray()) { ++ return false; ++ } ++ Napi::Array list = info[1].As(); ++ for (uint32_t i = 0; i < list.Length(); i++) { ++ Napi::Value pid = list.Get(i); ++ if (pid.IsNumber()) { ++ pids->push_back(pid.As().Int32Value()); ++ } ++ } ++ return true; ++} ++ ++class OrcaProcessTableWorker : public Napi::AsyncWorker { ++ public: ++ OrcaProcessTableWorker(Napi::Env env, bool include_command, std::vector pids, bool selected) ++ : Napi::AsyncWorker(env), ++ deferred_(Napi::Promise::Deferred::New(env)), ++ include_command_(include_command), ++ pids_(std::move(pids)), ++ selected_(selected) {} ++ ++ Napi::Promise Promise() { return deferred_.Promise(); } ++ ++ void Execute() override { ++ if (!orca_gather_process_table(include_command_, selected_ ? &pids_ : NULL, &rows_)) { ++ SetError("orca: process table sysctl failed"); ++ } ++ } ++ ++ void OnOK() override { ++ deferred_.Resolve(orca_process_rows_to_js(Env(), include_command_, rows_)); ++ } ++ ++ void OnError(const Napi::Error& error) override { ++ deferred_.Reject(error.Value()); ++ } ++ ++ private: ++ Napi::Promise::Deferred deferred_; ++ bool include_command_; ++ std::vector pids_; ++ bool selected_; ++ std::vector rows_; ++}; ++ ++Napi::Value OrcaProcessTableAsync(const Napi::CallbackInfo& info) { ++ bool include_command = info.Length() > 0 && info[0].ToBoolean().Value(); ++ std::vector pids; ++ bool selected = orca_read_pid_list(info, &pids); ++ OrcaProcessTableWorker* worker = ++ new OrcaProcessTableWorker(info.Env(), include_command, std::move(pids), selected); ++ Napi::Promise promise = worker->Promise(); ++ worker->Queue(); ++ return promise; ++} ++ ++Napi::Value OrcaProcessCwd(const Napi::CallbackInfo& info) { ++ Napi::Env env(info.Env()); ++ if (info.Length() < 1 || !info[0].IsNumber()) { ++ throw Napi::Error::New(env, "Usage: processCwd(pid)"); ++ } ++ struct proc_vnodepathinfo vnode; ++ int size = proc_pidinfo(info[0].As().Int32Value(), PROC_PIDVNODEPATHINFO, 0, &vnode, sizeof(vnode)); ++ if (size != (int)sizeof(vnode) || vnode.pvi_cdir.vip_path[0] == '\0') { ++ return env.Null(); ++ } ++ return Napi::String::New(env, vnode.pvi_cdir.vip_path); ++} ++ ++Napi::Value OrcaProcessPath(const Napi::CallbackInfo& info) { ++ Napi::Env env(info.Env()); ++ if (info.Length() < 1 || !info[0].IsNumber()) { ++ throw Napi::Error::New(env, "Usage: processPath(pid)"); ++ } ++ char path[PROC_PIDPATHINFO_MAXSIZE]; ++ int length = proc_pidpath(info[0].As().Int32Value(), path, sizeof(path)); ++ if (length <= 0) { ++ return env.Null(); ++ } ++ return Napi::String::New(env, path, length); ++} ++#endif ++ + /** + * Init + */ +@@ -793,6 +1182,11 @@ Napi::Object init(Napi::Env env, Napi::Object exports) { + exports.Set("open", Napi::Function::New(env, PtyOpen)); + exports.Set("resize", Napi::Function::New(env, PtyResize)); + exports.Set("process", Napi::Function::New(env, PtyGetProc)); ++#if defined(__APPLE__) ++ exports.Set("processTable", Napi::Function::New(env, OrcaProcessTableAsync)); ++ exports.Set("processCwd", Napi::Function::New(env, OrcaProcessCwd)); ++ exports.Set("processPath", Napi::Function::New(env, OrcaProcessPath)); ++#endif + return exports; + } + diff --git a/src/unixTerminal.ts b/src/unixTerminal.ts index 98733dc0cd752b554bd94e45904ca341ad141bba..3dd5ad9b3124dbd5ba7f76679b26650dad503ec6 100644 --- a/src/unixTerminal.ts diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8e6047af5701..854084c11f0a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -184,7 +184,7 @@ patchedDependencies: i18next-cli@1.74.2: 2ee32eef742615cd133e1a6940f027deb3723a8430bb7953bba3a6769b0aac47 lint-staged@16.4.0: 7333b3837f80a7fbd045964db6d76ba4fc118e49134bdbabb00585b6b7b60673 monaco-editor@0.55.1: 53b71f7d8a7c00b76ffdb73ce83d18e31692f193f5fafa6a390e48f5b3fdd636 - node-pty@1.1.0: 3072026a166d508c622ee025bfceb011ce97e2133efc93bd014e9374f3febf43 + node-pty@1.1.0: f60c52f7ee0a77bb259267c3232c723eca466b535ec277677cf061e7187a37a8 oxlint-plugin-anti-slop@0.1.2: c10c871702365a0c2c59e9f1c5fb92df97cae5755d534c0a3d83c6368f6feafe sprintf-js@1.1.3: 05316a8b01f155fe19a1e0cb4042c81d43d798a76755c407684e1199a18b1e08 vitest@5.0.5: 166c034c864f98267e7d479f083b8d37ea9a7b08d6662313dd38e7c69c9a3eb4 @@ -232,7 +232,7 @@ importers: version: 3.3.1 node-pty: specifier: ^1.1.0 - version: 1.1.0(patch_hash=3072026a166d508c622ee025bfceb011ce97e2133efc93bd014e9374f3febf43) + version: 1.1.0(patch_hash=f60c52f7ee0a77bb259267c3232c723eca466b535ec277677cf061e7187a37a8) posthog-node: specifier: ^5.52.5 version: 5.52.5 @@ -13748,7 +13748,7 @@ snapshots: node-int64@0.4.0: {} - node-pty@1.1.0(patch_hash=3072026a166d508c622ee025bfceb011ce97e2133efc93bd014e9374f3febf43): + node-pty@1.1.0(patch_hash=f60c52f7ee0a77bb259267c3232c723eca466b535ec277677cf061e7187a37a8): dependencies: node-addon-api: 7.1.1 diff --git a/src/main/daemon/daemon-process-inspection.ts b/src/main/daemon/daemon-process-inspection.ts index d78cb2f593ce..4a4af61982e1 100644 --- a/src/main/daemon/daemon-process-inspection.ts +++ b/src/main/daemon/daemon-process-inspection.ts @@ -2,6 +2,7 @@ import { execFile } from 'node:child_process' import { readFile } from 'node:fs/promises' import { promisify } from 'node:util' import { psLocaleEnvironment } from '../../shared/ps-locale-environment' +import { runPsInProcess } from '../../shared/libproc-process-table' import { parseLinuxBootTimeSeconds, parseLinuxProcStartTicks } from './daemon-process-start-time' import type { LinuxStatEvidence, @@ -202,6 +203,13 @@ async function runInspectionCommand( args: string[], timeoutMs: number ): Promise { + const inProcess = file === 'ps' ? await runPsInProcess(args, psLocaleEnvironment()) : null + if (inProcess) { + if (inProcess.code !== 0) { + throw new Error(`ps ${args.join(' ')} matched no process`) + } + return inProcess.stdout + } const { stdout } = await execFileAsync(file, args, { encoding: 'utf8', env: psLocaleEnvironment(), diff --git a/src/main/provider-process/provider-process-row-read.ts b/src/main/provider-process/provider-process-row-read.ts index 4078bdb74089..159d7b3783d2 100644 --- a/src/main/provider-process/provider-process-row-read.ts +++ b/src/main/provider-process/provider-process-row-read.ts @@ -1,5 +1,6 @@ import { readFile } from 'node:fs/promises' import { runProcess } from '@orca/process-host' +import { runPsInProcess } from '../../shared/libproc-process-table' import { parseProcessTable, type ProcessTableRow } from '../pty-process-table-parser' const PROCESS_ROW_TIMEOUT_MS = 2_000 @@ -43,14 +44,18 @@ async function readLinuxProcStatRow(pid: number): Promise { async function readPsProcessRow(pid: number): Promise { try { - const result = await runProcess({ - program: 'ps', - args: ['-o', 'pid=,ppid=,pgid=,lstart=', '-p', String(pid)], - // Stable locale makes repeated start markers comparable. - env: { ...process.env, LANG: 'C', LC_ALL: 'C' }, - timeoutMs: PROCESS_ROW_TIMEOUT_MS, - maxOutputBytes: 4096 - }) + const args = ['-o', 'pid=,ppid=,pgid=,lstart=', '-p', String(pid)] + // Stable locale makes repeated start markers comparable. + const env = { ...process.env, LANG: 'C', LC_ALL: 'C' } + const result = + (await runPsInProcess(args, env)) ?? + (await runProcess({ + program: 'ps', + args, + env, + timeoutMs: PROCESS_ROW_TIMEOUT_MS, + maxOutputBytes: 4096 + })) const row = parseProcessTable(result.stdout).find((entry) => entry.pid === pid) if (row) { return { ...row, startResolution: 'second' } diff --git a/src/main/providers/process-cwd.ts b/src/main/providers/process-cwd.ts index 336e16af94c2..2a1ec987f315 100644 --- a/src/main/providers/process-cwd.ts +++ b/src/main/providers/process-cwd.ts @@ -1,6 +1,7 @@ import { execFile as execFileCb } from 'node:child_process' import { readlink } from 'node:fs/promises' import { LSOF_NONBLOCKING_ARGS } from '../../shared/lsof-nonblocking-args' +import { readLibprocProcessCwd } from '../../shared/libproc-process-table' // Coalesce/cache per-PID cwd reads briefly so rapid pane actions cannot accumulate lsof subprocesses. const CACHE_TTL_MS = 1500 @@ -61,6 +62,11 @@ async function doResolve(pid: number): Promise { /* fall through */ } + const inProcess = readLibprocProcessCwd(pid) + if (inProcess !== undefined) { + return inProcess ?? '' + } + try { // lsof needs -a to AND PID/cwd filters; OR would return unrelated process cwd records. const stdout = await readCwdWithLsof(pid) diff --git a/src/main/pty-descendant-termination.ts b/src/main/pty-descendant-termination.ts index a46ca7d65894..924df78e626b 100644 --- a/src/main/pty-descendant-termination.ts +++ b/src/main/pty-descendant-termination.ts @@ -6,6 +6,7 @@ import { type WindowsTreeKillTarget } from './windows-pty-root-identity' import { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' +import { runPsInProcess } from '../shared/libproc-process-table' export { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' @@ -37,29 +38,23 @@ export type ProcessTableCapture = { export type ProcessTableReader = (timeoutMs?: number) => Promise export type SignalSender = (pid: number, signal: NodeJS.Signals) => void -function readFreshProcessTable( +const DESCENDANT_PS_ARGS = ['-axo', 'pid=,ppid=,pgid=,tpgid=,lstart='] + +async function readFreshProcessTable( timeoutMs = DESCENDANT_SNAPSHOT_TIMEOUT_MS ): Promise { // Stamp before ps starts so a capture-second PID cannot appear older after a clock rollover. const capturedAtMs = Date.now() + // Pin lstart’s locale so delayed identity checks parse it consistently. + const env = { ...process.env, LANG: 'C', LC_ALL: 'C' } + const inProcess = await runPsInProcess(DESCENDANT_PS_ARGS, env) + if (inProcess) { + return { rows: parseProcessTable(inProcess.stdout), capturedAtMs } + } + const options = { maxBuffer: PS_MAX_BUFFER_BYTES, timeout: timeoutMs, env } return new Promise((resolve, reject) => { - execFile( - 'ps', - ['-axo', 'pid=,ppid=,pgid=,tpgid=,lstart='], - { - maxBuffer: PS_MAX_BUFFER_BYTES, - timeout: timeoutMs, - killSignal: 'SIGKILL', - // Pin lstart’s locale so delayed identity checks parse it consistently. - env: { ...process.env, LANG: 'C', LC_ALL: 'C' } - }, - (error, stdout) => { - if (error) { - reject(error) - return - } - resolve({ rows: parseProcessTable(stdout), capturedAtMs }) - } + execFile('ps', DESCENDANT_PS_ARGS, { ...options, killSignal: 'SIGKILL' }, (error, stdout) => + error ? reject(error) : resolve({ rows: parseProcessTable(stdout), capturedAtMs }) ) }) } diff --git a/src/main/pty/posix-pty-foreground-group.ts b/src/main/pty/posix-pty-foreground-group.ts index 2460b82a6d00..00e790706038 100644 --- a/src/main/pty/posix-pty-foreground-group.ts +++ b/src/main/pty/posix-pty-foreground-group.ts @@ -1,4 +1,5 @@ import { runProcess } from '@orca/process-host' +import { runPsInProcess } from '../../shared/libproc-process-table' const PROCESS_TABLE_LOOKUP_TIMEOUT_MS = 250 const PROCESS_TABLE_QUERY_TIMEOUT_MS = PROCESS_TABLE_LOOKUP_TIMEOUT_MS / 2 @@ -28,12 +29,15 @@ function hasUsableTty(tty: string): boolean { } async function runPs(pid: number): Promise { - const result = await runProcess({ - program: 'ps', - args: ['-p', String(pid), '-o', 'pid=,tpgid=,tty='], - timeoutMs: PROCESS_TABLE_QUERY_TIMEOUT_MS, - maxOutputBytes: PROCESS_TABLE_MAX_BYTES - }) + const args = ['-p', String(pid), '-o', 'pid=,tpgid=,tty='] + const result = + (await runPsInProcess(args)) ?? + (await runProcess({ + program: 'ps', + args, + timeoutMs: PROCESS_TABLE_QUERY_TIMEOUT_MS, + maxOutputBytes: PROCESS_TABLE_MAX_BYTES + })) if (result.code !== 0 || result.timedOut || result.outputTruncated) { throw new Error('PTY foreground group is unavailable') } diff --git a/src/main/runtime/agent-session/ownership/agent-session-process-identity-probe.ts b/src/main/runtime/agent-session/ownership/agent-session-process-identity-probe.ts index f77778fd4c9a..05673341b874 100644 --- a/src/main/runtime/agent-session/ownership/agent-session-process-identity-probe.ts +++ b/src/main/runtime/agent-session/ownership/agent-session-process-identity-probe.ts @@ -9,6 +9,7 @@ import type { import type { AgentSessionProcessIdentity } from '../../../../shared/agent-session-record' import { runProcess } from '@orca/process-host' import { psLocaleEnvironment } from '../../../../shared/ps-locale-environment' +import { runPsInProcess } from '../../../../shared/libproc-process-table' import { isWindowsProcessStartTimeAvailable, readWindowsProcessIdentityTableFresh @@ -59,12 +60,11 @@ async function readLinuxProcessStartTimeMs(pid: number): Promise async function readDarwinProcessStartTimeMs(pid: number): Promise { try { - const result = await runProcess({ - program: 'ps', - args: ['-o', 'lstart=', '-p', String(pid)], - env: psLocaleEnvironment(), - timeoutMs: PROCESS_START_TIME_TIMEOUT_MS - }) + const args = ['-o', 'lstart=', '-p', String(pid)] + const env = psLocaleEnvironment() + const result = + (await runPsInProcess(args, env)) ?? + (await runProcess({ program: 'ps', args, env, timeoutMs: PROCESS_START_TIME_TIMEOUT_MS })) if (result.timedOut || result.code !== 0) { return null } @@ -83,12 +83,11 @@ async function readDarwinProcessStartTimesMs( return observed } try { - const result = await runProcess({ - program: 'ps', - args: ['-o', 'pid=,lstart=', '-p', pids.join(',')], - env: psLocaleEnvironment(), - timeoutMs: PROCESS_START_TIME_TIMEOUT_MS - }) + const args = ['-o', 'pid=,lstart=', '-p', pids.join(',')] + const env = psLocaleEnvironment() + const result = + (await runPsInProcess(args, env)) ?? + (await runProcess({ program: 'ps', args, env, timeoutMs: PROCESS_START_TIME_TIMEOUT_MS })) if (result.timedOut || result.code !== 0) { return observed } diff --git a/src/main/runtime/terminal-foreground-group.ts b/src/main/runtime/terminal-foreground-group.ts index d9a3eb034d3c..d49447523085 100644 --- a/src/main/runtime/terminal-foreground-group.ts +++ b/src/main/runtime/terminal-foreground-group.ts @@ -2,6 +2,7 @@ import { recognizeAgentProcessFromCommandLine } from '../../shared/agent-process-recognition' import { runProcess } from '@orca/process-host' +import { runPsInProcess } from '../../shared/libproc-process-table' import { parseShellForegroundRows, type ProcessTableRow } from '../../shared/process-table-snapshot' import { psLocaleEnvironment } from '../../shared/ps-locale-environment' import { isShellProcess } from '../../shared/shell-process-detection' @@ -15,13 +16,16 @@ const TTY_CACHE_LIMIT = 256 async function ps(args: readonly string[]): Promise { try { - const result = await runProcess({ - program: 'ps', - args, - env: psLocaleEnvironment(), - timeoutMs: PS_TIMEOUT_MS, - maxOutputBytes: PS_MAX_OUTPUT_BYTES - }) + const env = psLocaleEnvironment() + const result = + (await runPsInProcess(args, env)) ?? + (await runProcess({ + program: 'ps', + args, + env, + timeoutMs: PS_TIMEOUT_MS, + maxOutputBytes: PS_MAX_OUTPUT_BYTES + })) return result.code === 0 ? result.stdout : null } catch { return null diff --git a/src/shared/agent-process-presence-probe.ts b/src/shared/agent-process-presence-probe.ts index bc3cd9bf178d..46910085b4ac 100644 --- a/src/shared/agent-process-presence-probe.ts +++ b/src/shared/agent-process-presence-probe.ts @@ -1,5 +1,6 @@ import { readFile } from 'node:fs/promises' import { runProcess } from '@orca/process-host' +import { runPsInProcess } from './libproc-process-table' import type { AgentProcessIdentity, AgentProcessVerdict } from './agent-process-presence' export type AgentProcessObservation = @@ -42,14 +43,18 @@ export async function readAgentProcess(pid: number): Promise({ runPs: async () => { + const inProcess = await runPsInProcess(CHEAP_PS_ARGS, psLocaleEnvironment()) + if (inProcess) { + return parseCheapProcessTableRows(inProcess.stdout) + } const result = await runProcess({ program: 'ps', args: CHEAP_PS_ARGS, diff --git a/src/shared/darwin-terminal-names.ts b/src/shared/darwin-terminal-names.ts index 442ffeee768e..224637a3be5d 100644 --- a/src/shared/darwin-terminal-names.ts +++ b/src/shared/darwin-terminal-names.ts @@ -95,6 +95,19 @@ async function readTerminalNames( signal?.throwIfAborted() } +/** Names keyed by `major/minor` device token, as ps's `tdev` column prints them. */ +export async function nameDarwinTerminalDevices( + devices: ReadonlySet, + deps: DarwinTerminalNameDeps = deviceFilesystem, + signal?: AbortSignal +): Promise> { + const names = await readPtyNames(devices, deps, signal) + if (names.size < devices.size) { + await readTerminalNames(devices, names, deps, signal) + } + return names +} + /** Use this capture’s /dev inventory without caching hits or misses. */ export async function nameDarwinTerminals( stdout: string, @@ -116,10 +129,7 @@ export async function nameDarwinTerminals( devices.add(device) } } - const names = await readPtyNames(devices, deps, signal) - if (names.size < devices.size) { - await readTerminalNames(devices, names, deps, signal) - } + const names = await nameDarwinTerminalDevices(devices, deps, signal) return stdout.replace(TDEV_COLUMNS, (_row, head: string, device: string) => { return head + (names.get(deviceToken(device) ?? '') ?? '??') }) diff --git a/src/shared/libproc-process-table.test.ts b/src/shared/libproc-process-table.test.ts new file mode 100644 index 000000000000..39031f988c9f --- /dev/null +++ b/src/shared/libproc-process-table.test.ts @@ -0,0 +1,158 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('./darwin-terminal-names', () => ({ + nameDarwinTerminalDevices: async (devices: ReadonlySet) => + new Map([...devices].filter((device) => device === '16/4').map((device) => [device, 'ttys004'])) +})) + +import { + runPsInProcess, + setLibprocAddonForTests, + type LibprocAddon, + type LibprocProcessRow +} from './libproc-process-table' +import { parseCheapProcessTableRows, parseStrictProcessTableRows } from './process-table-snapshot' + +const TTYS004 = (16 << 24) | 4 +// 2026-09-03T16:02:01Z, a single-digit day so lstart pads it. +const START = Date.UTC(2026, 8, 3, 16, 2, 1) / 1000 + +function row(overrides: Partial): LibprocProcessRow { + return { + pid: 1, + ppid: 0, + pgid: 1, + tpgid: 0, + tdev: -1, + status: 2, + flags: 0, + sessionLeader: false, + startSec: START, + comm: 'launchd', + ...overrides + } +} + +const TABLE = [ + row({ + pid: 4300, + ppid: 4242, + pgid: 4300, + tpgid: 4300, + tdev: TTYS004, + flags: 0x2, + comm: 'node', + command: 'node /usr/local/bin/claude --resume' + }), + row({ + pid: 4242, + ppid: 4200, + pgid: 4242, + tpgid: 4300, + tdev: TTYS004, + flags: 0x2, + sessionLeader: true, + comm: 'zsh', + command: '-zsh' + }), + row({ + pid: 4200, + ppid: 1, + pgid: 4200, + tdev: TTYS004, + flags: 0x2, + comm: 'login', + command: '/usr/bin/login' + }), + row({ pid: 4400, ppid: 4242, pgid: 4400, tpgid: 4300, status: 4, comm: 'vim', command: 'vim' }), + row({ pid: 4401, ppid: 4242, pgid: 4401, status: 5, comm: 'sh', command: null }) +] + +function installAddon(overrides: Partial = {}): LibprocAddon { + const addon: LibprocAddon = { + processTable: vi.fn(async (includeCommand: boolean, pids?: readonly number[]) => + TABLE.filter((entry) => !pids || pids.includes(entry.pid)).map((entry) => + includeCommand ? entry : { ...entry, command: undefined } + ) + ), + processCwd: vi.fn(() => null), + processPath: vi.fn(() => null), + ...overrides + } + setLibprocAddonForTests(addon) + return addon +} + +afterEach(() => { + setLibprocAddonForTests(undefined) +}) + +describe('runPsInProcess', () => { + it('prints a whole-table capture the strict and cheap parsers read like ps output', async () => { + installAddon() + const utc = { TZ: 'UTC0' } + + const full = await runPsInProcess( + ['-axo', 'pid=,ppid=,pgid=,tpgid=,stat=,tty=,lstart=,command='], + utc + ) + expect(full?.code).toBe(0) + expect(parseStrictProcessTableRows(full!.stdout)).toEqual([ + expect.objectContaining({ pid: 4200, stat: 'S', tty: 'ttys004', command: '/usr/bin/login' }), + expect.objectContaining({ pid: 4242, stat: 'Ss', tty: 'ttys004', command: '-zsh' }), + expect.objectContaining({ + pid: 4300, + stat: 'S+', + tty: 'ttys004', + startTime: 'Thu Sep 3 16:02:01 2026', + command: 'node /usr/local/bin/claude --resume' + }), + expect.objectContaining({ pid: 4400, stat: 'T', tty: '??', command: 'vim' }), + expect.objectContaining({ pid: 4401, stat: 'Z', command: '(sh)' }) + ]) + + const cheap = await runPsInProcess(['-axo', 'pid=,ppid=,pgid=,tpgid=,stat=,lstart='], utc) + expect(parseCheapProcessTableRows(cheap!.stdout)[2]).toEqual({ + pid: 4300, + ppid: 4242, + pgid: 4300, + tpgid: 4300, + stat: 'S+', + startTime: 'Thu Sep 3 16:02:01 2026' + }) + }) + + it('selects by pid or terminal and exits 1 like ps when nothing matches', async () => { + const addon = installAddon() + + expect(await runPsInProcess(['-p', '4300', '-o', 'pid=,tdev='])).toMatchObject({ + code: 0, + stdout: '4300 16/4\n' + }) + expect(addon.processTable).toHaveBeenLastCalledWith(false, [4300]) + expect(await runPsInProcess(['-p', '9999', '-o', 'stat=,lstart='])).toMatchObject({ + code: 1, + stdout: '' + }) + const tty = await runPsInProcess(['-o', 'pid=,stat=', '-t', '/dev/ttys004']) + expect(tty?.stdout).toBe('4200 S\n4242 Ss\n4300 S+\n') + }) + + it('keeps the real ps for invocations it cannot reproduce or a failing addon', async () => { + installAddon() + expect(await runPsInProcess(['-axo', 'pid=PROCESS_ID'])).toBeNull() + expect(await runPsInProcess(['-axo', 'pid=,uid='])).toBeNull() + expect(await runPsInProcess(['-p', '1', '-t', 'ttys004', '-o', 'pid='])).toBeNull() + expect(await runPsInProcess(['-axo', 'lstart='], { TZ: 'America/New_York' })).toBeNull() + + installAddon({ + processTable: async () => { + throw new Error('sysctl failed') + } + }) + expect(await runPsInProcess(['-axo', 'pid='])).toBeNull() + + setLibprocAddonForTests(null) + expect(await runPsInProcess(['-axo', 'pid='])).toBeNull() + }) +}) diff --git a/src/shared/libproc-process-table.ts b/src/shared/libproc-process-table.ts new file mode 100644 index 000000000000..69f629ff450d --- /dev/null +++ b/src/shared/libproc-process-table.ts @@ -0,0 +1,318 @@ +import { createRequire } from 'node:module' +import { nameDarwinTerminalDevices } from './darwin-terminal-names' + +/** One `kinfo_proc` from node-pty's patched macOS addon (config/patches/node-pty@1.1.0.patch). */ +export type LibprocProcessRow = { + pid: number + ppid: number + pgid: number + tpgid: number + /** `e_tdev`; -1 (NODEV) without a controlling terminal. */ + tdev: number + /** `p_stat`: SIDL 1, SRUN 2, SSLEEP 3, SSTOP 4, SZOMB 5. */ + status: number + flags: number + sessionLeader: boolean + startSec: number + comm: string + /** Joined KERN_PROCARGS2 argv, else the executable path for another user's process; null when neither is readable. */ + command?: string | null +} + +export type LibprocAddon = { + /** Reads on a worker thread; argv for a whole table costs ~17ms of syscalls. */ + processTable: (includeCommand: boolean, pids?: readonly number[]) => Promise + processCwd: (pid: number) => string | null + processPath: (pid: number) => string | null +} + +const requireFromHere = createRequire(__filename) +let cachedAddon: LibprocAddon | null | undefined +let addonOverride: LibprocAddon | null | undefined + +function isLibprocAddon(native: unknown): native is LibprocAddon { + return ( + typeof native === 'object' && + native !== null && + 'processTable' in native && + typeof native.processTable === 'function' && + 'processCwd' in native && + typeof native.processCwd === 'function' && + 'processPath' in native && + typeof native.processPath === 'function' + ) +} + +/** The in-process reader, or null where ps/lsof must still run (non-macOS, an unpatched or unloadable node-pty). + * Vitest keeps the subprocess path so ps fixtures stay authoritative. */ +export function loadLibprocAddon(): LibprocAddon | null { + if (addonOverride !== undefined) { + return addonOverride + } + if (process.platform !== 'darwin' || process.env.VITEST === 'true') { + return null + } + if (cachedAddon !== undefined) { + return cachedAddon + } + try { + const utils: unknown = requireFromHere('node-pty/lib/utils') + const native: unknown = + typeof utils === 'object' && + utils !== null && + 'loadNativeModule' in utils && + typeof utils.loadNativeModule === 'function' + ? utils.loadNativeModule('pty')?.module + : null + cachedAddon = isLibprocAddon(native) ? native : null + } catch { + cachedAddon = null + } + if (cachedAddon === null) { + // A packaging regression would otherwise silently restore one setuid ps exec per poll (#31783). + console.warn('[process-table] node-pty lacks the libproc reader; falling back to ps and lsof') + } + return cachedAddon +} + +export function setLibprocAddonForTests(addon: LibprocAddon | null | undefined): void { + addonOverride = addon +} + +const SIDL = 1 +const SSTOP = 4 +const SZOMB = 5 +const P_CONTROLT = 0x2 +const P_WEXIT = 0x2000 +const NODEV = -1 + +/** ps's state letters, except running vs sleeping: that needs another task's thread states (ps is setuid for it), so live processes read `S`. */ +export function formatLibprocStat(row: LibprocProcessRow): string { + const state = + row.status === SZOMB ? 'Z' : row.status === SSTOP ? 'T' : row.status === SIDL ? 'R' : 'S' + return ( + state + + (row.flags & P_WEXIT && row.status !== SZOMB ? 'E' : '') + + (row.sessionLeader ? 's' : '') + + (row.flags & P_CONTROLT && row.pgid === row.tpgid ? '+' : '') + ) +} + +export function formatDarwinDevice(tdev: number): string | null { + return tdev === NODEV ? null : `${(tdev >>> 24) & 0xff}/${tdev & 0xffffff}` +} + +const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] + +/** ps `lstart` (`%c` in the C and en_US locales): `Thu Sep 3 16:02:01 2026`. */ +export function formatLstart(startSec: number, utc: boolean): string { + const date = new Date(startSec * 1000) + const [weekday, month, day, hours, minutes, seconds, year] = utc + ? [ + date.getUTCDay(), + date.getUTCMonth(), + date.getUTCDate(), + date.getUTCHours(), + date.getUTCMinutes(), + date.getUTCSeconds(), + date.getUTCFullYear() + ] + : [ + date.getDay(), + date.getMonth(), + date.getDate(), + date.getHours(), + date.getMinutes(), + date.getSeconds(), + date.getFullYear() + ] + const two = (value: number): string => String(value).padStart(2, '0') + return `${WEEKDAYS[weekday]} ${MONTHS[month]} ${String(day).padStart(2, ' ')} ${two(hours)}:${two(minutes)}:${two(seconds)} ${year}` +} + +const COLUMN_ALIASES: Readonly> = { + pid: 'pid', + ppid: 'ppid', + pgid: 'pgid', + tpgid: 'tpgid', + stat: 'stat', + state: 'stat', + tdev: 'tdev', + tty: 'tty', + lstart: 'lstart', + command: 'command', + args: 'command' +} + +type Column = 'pid' | 'ppid' | 'pgid' | 'tpgid' | 'stat' | 'tdev' | 'tty' | 'lstart' | 'command' + +export type PsQuery = { + columns: Column[] + pids: number[] | null + tty: string | null +} + +/** The `ps` invocations Orca issues (`-axo`, `-e -o`, `-p`, `-t`, empty headers); anything else returns null and keeps the real ps. */ +export function parsePsQuery(args: readonly string[]): PsQuery | null { + const columns: Column[] = [] + let all = false + let pids: number[] | null = null + let tty: string | null = null + for (let index = 0; index < args.length; index += 1) { + const arg = args[index] + const value = (): string | undefined => args[++index] + if (arg === '-axo' || arg === '-o') { + all ||= arg === '-axo' + const spec = value() + if (spec === undefined) { + return null + } + for (const field of spec.split(',')) { + const match = /^([a-z]+)=$/.exec(field) + const column = match ? COLUMN_ALIASES[match[1]] : undefined + if (!column) { + return null + } + columns.push(column) + } + } else if (arg === '-ax' || arg === '-A' || arg === '-e') { + all = true + } else if (arg === '-ww') { + continue + } else if (arg === '-p') { + const list = value()?.split(',').map(Number) + if (!list || list.some((pid) => !Number.isSafeInteger(pid) || pid <= 0)) { + return null + } + pids = [...(pids ?? []), ...list] + } else if (arg === '-t') { + const name = value()?.replace(/^\/dev\//, '') + if (!name) { + return null + } + tty = name + } else { + return null + } + } + // ps unions selections; Orca never combines them, so keep the real ps for that. + const selections = Number(all) + Number(pids !== null) + Number(tty !== null) + return columns.length > 0 && selections === 1 ? { columns, pids, tty } : null +} + +/** Shaped like a process-host ProcessResult so call sites can substitute it for ps's. */ +export type LibprocPsResult = { + code: 0 | 1 + signal: null + stdout: string + stderr: '' + timedOut: false + outputTruncated: false +} + +function sanitizeCommand(command: string): string { + return command.replace(/[\r\n\t]/g, ' ') +} + +function readCommand(row: LibprocProcessRow): string { + return sanitizeCommand(row.command?.trim() ? row.command : `(${row.comm})`) +} + +function lstartZoneIsUtc(env: NodeJS.ProcessEnv | undefined): boolean | null { + const zone = env?.TZ + if (zone === undefined || zone === process.env.TZ) { + return false + } + return /^(?:UTC|GMT)0?$/.test(zone) ? true : null +} + +/** ps output for `args`, read in process; null when the addon or the invocation is unsupported so callers run ps. */ +export async function runPsInProcess( + args: readonly string[], + env?: NodeJS.ProcessEnv +): Promise { + const addon = loadLibprocAddon() + const query = addon ? parsePsQuery(args) : null + const utc = lstartZoneIsUtc(env) + if (!addon || !query || utc === null) { + return null + } + const needsTty = query.columns.includes('tty') || query.tty !== null + let rows: LibprocProcessRow[] + let ttyNames: ReadonlyMap = new Map() + try { + rows = await addon.processTable(query.columns.includes('command'), query.pids ?? undefined) + if (needsTty) { + const devices = new Set( + rows.map((row) => formatDarwinDevice(row.tdev)).filter((device) => device !== null) + ) + ttyNames = await nameDarwinTerminalDevices(devices) + } + } catch { + return null + } + const ttyOf = (row: LibprocProcessRow): string => + ttyNames.get(formatDarwinDevice(row.tdev) ?? '') ?? '??' + const selected = (query.tty === null ? rows : rows.filter((row) => ttyOf(row) === query.tty)) + .slice() + .sort((a, b) => a.pid - b.pid) + const lines = selected.map((row) => + query.columns + .map((column) => { + switch (column) { + case 'stat': + return formatLibprocStat(row) + case 'tdev': + return formatDarwinDevice(row.tdev) ?? '??' + case 'tty': + return ttyOf(row) + case 'lstart': + return formatLstart(row.startSec, utc) + case 'command': + return readCommand(row) + case 'pid': + case 'ppid': + case 'pgid': + case 'tpgid': + return String(row[column]) + } + }) + .join(' ') + ) + // ps exits 1 when a -p/-t selection matched nothing. + return { + code: query.pids === null && query.tty === null ? 0 : selected.length > 0 ? 0 : 1, + signal: null, + stdout: lines.length > 0 ? `${lines.join('\n')}\n` : '', + stderr: '', + timedOut: false, + outputTruncated: false + } +} + +/** PROC_PIDVNODEPATHINFO cwd, or undefined when only lsof can answer. */ +export function readLibprocProcessCwd(pid: number): string | null | undefined { + const addon = loadLibprocAddon() + if (!addon) { + return undefined + } + try { + return addon.processCwd(pid) + } catch { + return undefined + } +} + +/** proc_pidpath executable, or undefined when only lsof can answer. */ +export function readLibprocProcessPath(pid: number): string | null | undefined { + const addon = loadLibprocAddon() + if (!addon) { + return undefined + } + try { + return addon.processPath(pid) + } catch { + return undefined + } +} diff --git a/src/shared/process-table-snapshot-reader.ts b/src/shared/process-table-snapshot-reader.ts index 4c0459eecd27..1819d8687991 100644 --- a/src/shared/process-table-snapshot-reader.ts +++ b/src/shared/process-table-snapshot-reader.ts @@ -2,6 +2,7 @@ import { execFile as execFileCb } from 'node:child_process' import { readFile } from 'node:fs/promises' import { promisify } from 'node:util' import { psLocaleEnvironment } from './ps-locale-environment' +import { runPsInProcess } from './libproc-process-table' import { captureDarwinProcessTable, resetDarwinProcessTableCaptureForTests @@ -243,6 +244,10 @@ async function readLinuxProcessStartTimes( } async function captureProcessTable(args: readonly string[], timeout = PS_TIMEOUT_MS) { + const inProcess = await runPsInProcess(args, psLocaleEnvironment()) + if (inProcess) { + return assertWholeCapture(inProcess.stdout) + } let stdout: string try { ;({ stdout } = await execFile('ps', [...args], { diff --git a/src/shared/shell-process-readiness.ts b/src/shared/shell-process-readiness.ts index 4fbc90873ef1..7e2833869f0e 100644 --- a/src/shared/shell-process-readiness.ts +++ b/src/shared/shell-process-readiness.ts @@ -4,6 +4,7 @@ import { access, readlink, realpath, stat } from 'node:fs/promises' import { delimiter, isAbsolute, resolve } from 'node:path' import { promisify } from 'node:util' import { LSOF_NONBLOCKING_ARGS } from './lsof-nonblocking-args' +import { readLibprocProcessPath, runPsInProcess } from './libproc-process-table' import { PS_MAX_BUFFER_BYTES } from './process-table-snapshot' const execFile = promisify(execFileCallback) @@ -30,6 +31,10 @@ async function readExecutablePath(pid: number): Promise { if (process.platform !== 'darwin') { return null } + const inProcess = readLibprocProcessPath(pid) + if (inProcess !== undefined) { + return inProcess + } const { stdout } = await execFile( '/usr/sbin/lsof', [...LSOF_NONBLOCKING_ARGS, '-a', '-p', String(pid), '-d', 'txt', '-Fn'], @@ -41,16 +46,29 @@ async function readExecutablePath(pid: number): Promise { return parseDarwinExecutablePath(stdout) } +/** Rejects like execFile when ps exits nonzero, so callers keep their error paths. */ +async function readPs(args: string[]): Promise { + const inProcess = await runPsInProcess(args) + if (inProcess) { + if (inProcess.code !== 0) { + throw new Error(`ps ${args.join(' ')} matched no process`) + } + return inProcess.stdout + } + const { stdout } = await execFile('ps', args, { + encoding: 'utf8', + timeout: PROCESS_READINESS_TIMEOUT_MS, + maxBuffer: PS_MAX_BUFFER_BYTES + }) + return stdout +} + export async function readShellProcessReadiness( pid: number ): Promise { - const [executablePath, { stdout }] = await Promise.all([ + const [executablePath, stdout] = await Promise.all([ readExecutablePath(pid), - execFile('ps', ['-p', String(pid), '-o', 'stat=,tty='], { - encoding: 'utf8', - timeout: PROCESS_READINESS_TIMEOUT_MS, - maxBuffer: PS_MAX_BUFFER_BYTES - }) + readPs(['-p', String(pid), '-o', 'stat=,tty=']) ]) const [status, ttyName] = stdout.trim().split(/\s+/) return status && executablePath @@ -63,11 +81,7 @@ export async function readShellProcessReadiness( } export async function listChildProcessIds(pid: number): Promise { - const { stdout } = await execFile('ps', ['-axo', 'pid=,ppid='], { - encoding: 'utf8', - timeout: PROCESS_READINESS_TIMEOUT_MS, - maxBuffer: PS_MAX_BUFFER_BYTES - }) + const stdout = await readPs(['-axo', 'pid=,ppid=']) return stdout .split('\n') .map((line) => line.trim().split(/\s+/)) diff --git a/src/shared/tmux-host-attachment-probe.ts b/src/shared/tmux-host-attachment-probe.ts index 877b62ac5eff..557265a6a7c6 100644 --- a/src/shared/tmux-host-attachment-probe.ts +++ b/src/shared/tmux-host-attachment-probe.ts @@ -1,6 +1,7 @@ import { stat } from 'node:fs/promises' import { readAgentProcess } from './agent-process-presence-probe' import { runProcess } from '@orca/process-host' +import { runPsInProcess } from './libproc-process-table' import { PS_ARGS, parseStrictProcessTableRows, @@ -22,13 +23,11 @@ async function readSelectedRows(pids: readonly number[]): Promise readSelectedRows([pid]))) return rows.flat() } - const result = await runProcess({ - program: '/bin/ps', - args: ['-p', pids.join(','), '-o', PS_ARGS[1]], - env: { ...process.env, LC_ALL: 'C', LANG: 'C', TZ: 'UTC0' }, - timeoutMs: 1000, - maxOutputBytes: 65536 - }) + const args = ['-p', pids.join(','), '-o', PS_ARGS[1]] + const env = { ...process.env, LC_ALL: 'C', LANG: 'C', TZ: 'UTC0' } + const result = + (await runPsInProcess(args, env)) ?? + (await runProcess({ program: '/bin/ps', args, env, timeoutMs: 1000, maxOutputBytes: 65536 })) if (result.timedOut || result.code !== 0 || result.stdout.length >= 65536) { throw new Error('tmux_process_capture_unverifiable') } From f415bbf1c68cf3abd3c592b7961450292af1474b Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 00:49:34 -0700 Subject: [PATCH 02/13] fix(daemon): roll the in-process macOS process table into a fresh v54 daemon (#31783) --- src/main/daemon/daemon-protocol-version.ts | 6 ++++-- src/shared/local-build-compatibility-contract.json | 4 ++-- src/shared/local-build-compatibility-contract.ts | 4 ++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/daemon/daemon-protocol-version.ts b/src/main/daemon/daemon-protocol-version.ts index 6e563eea9b5e..091383b5d8a8 100644 --- a/src/main/daemon/daemon-protocol-version.ts +++ b/src/main/daemon/daemon-protocol-version.ts @@ -1,4 +1,5 @@ // Why: daemons survive app updates, so wire behavior must be version-gated. +// v54 reads the macOS process table in process instead of forking setuid ps on every poll (#31783). // v53 rolls the daemon-side terminal fixes since v1.4.241 (foreground confirmation for chat continuation, ConPTY reflow, WSL malloc tunables) into a fresh daemon. // v52 rolls the daemon-side terminal fixes since v1.4.240 (ConPTY, teardown, spawn pane keys) into a fresh daemon. // v51 checks terminal identity, ownership and attachments before reserving teardown. @@ -11,7 +12,7 @@ // v43 dropped it with the revert); v41 stages long startup commands as sourced scripts; v40 rolled // the #25130/#24636 shell-wrapper changes and the wider agent list into a fresh daemon; older owners // stay attachable. -export const PROTOCOL_VERSION = 53 +export const PROTOCOL_VERSION = 54 export const FENCED_TERMINATION_PROTOCOL_VERSION = 51 export const CLAUDE_ACCOUNT_FUNCTION_DAEMON_PROTOCOL_VERSION = 42 export const CLAUDE_ACCOUNT_FUNCTION_REVERTED_DAEMON_PROTOCOL_VERSION = 43 @@ -46,7 +47,8 @@ export const CLEAN_DISCONNECT_PROTOCOL_VERSION = 24 export const MODE_2031_UNSUBSCRIBE_FACT_PROTOCOL_VERSION = 29 export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [ 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 + 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 ] as const export function supportsColorQueryReplyColors(protocolVersion: number): boolean { diff --git a/src/shared/local-build-compatibility-contract.json b/src/shared/local-build-compatibility-contract.json index a832ce1301ee..f878cefa3d2c 100644 --- a/src/shared/local-build-compatibility-contract.json +++ b/src/shared/local-build-compatibility-contract.json @@ -3,10 +3,10 @@ "appId": "com.stablyai.orca", "stateSchemaVersion": 1, "readableStateSchemaVersions": [1], - "daemonProtocolVersion": 53, + "daemonProtocolVersion": 54, "attachableDaemonProtocolVersions": [ 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 + 51, 52, 53, 54 ] } diff --git a/src/shared/local-build-compatibility-contract.ts b/src/shared/local-build-compatibility-contract.ts index e04456f5009a..244e01dc6a1c 100644 --- a/src/shared/local-build-compatibility-contract.ts +++ b/src/shared/local-build-compatibility-contract.ts @@ -3,10 +3,10 @@ export const LOCAL_BUILD_COMPATIBILITY_CONTRACT = { appId: 'com.stablyai.orca', stateSchemaVersion: 1, readableStateSchemaVersions: [1], - daemonProtocolVersion: 53, + daemonProtocolVersion: 54, attachableDaemonProtocolVersions: [ 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 + 51, 52, 53, 54 ] } as const From 2cea31fe1efd64467b88cbb49f369331c9cc8a3f Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 02:35:29 -0700 Subject: [PATCH 03/13] fix(terminal): bound, escape and complete the in-process macOS process table like ps (#31783) Review follow-ups for the libproc reader: - Timeouts: every caller passes its ps timeout; a read stalled behind a saturated libuv pool resolves timed out (code null, timedOut) at that budget, exactly as the killed ps would. Identical native reads share one worker, each caller racing its own deadline; past 8 distinct reads in flight callers run ps. execFile-shaped callers reject like a failed child. - tty naming shares one slot with captureDarwinProcessTable's guard, so a draining naming pass sends both paths to ps instead of naming again. - Commands: the addon renders argv with adv_cmds' getproclline and strnvis (VIS_TAB|VIS_NL|VIS_NOSLASH) under the caller's LC_CTYPE via a thread-scoped uselocale, so newlines print as \012 instead of splitting tokens; zombies print . - Other users' processes: unreadable argv is marked commandIncomplete. Only -p selections and processes on a terminal under the user's own readable process there (sudo in a pane) get a targeted `ps -p ... -o pid=,command=`, cached by (locale, pid, start time); root daemons and a pane's root login never spawn ps. - -t selects with KERN_PROC_TTY after ps's addelem_tty path resolution, so per-terminal reads skip argv for every other process (~0.3 ms vs 4 ms ps). - -p deduplicates; rows sort by terminal then pid as pscomp(); stat adds ps's < N X V L modifiers. The export is renamed readProcessTable so an older pty.node falls back to ps rather than misreading the new query. --- config/patches/node-pty@1.1.0.patch | 338 +++++++++----- pnpm-lock.yaml | 6 +- src/main/daemon/daemon-process-inspection.ts | 14 +- .../provider-process-row-read.ts | 6 +- src/main/providers/process-cwd.ts | 2 +- src/main/pty-descendant-termination.ts | 8 +- src/main/pty/posix-pty-foreground-group.ts | 5 +- .../agent-session-process-identity-probe.ts | 4 +- src/main/runtime/terminal-foreground-group.ts | 6 +- src/shared/agent-process-presence-probe.ts | 2 +- .../cheap-process-table-snapshot-reader.ts | 13 +- src/shared/darwin-process-table-capture.ts | 27 +- src/shared/darwin-terminal-naming-slot.ts | 25 ++ src/shared/libproc-addon.ts | 118 +++++ src/shared/libproc-argv-completion.ts | 101 +++++ src/shared/libproc-process-table.test.ts | 153 +++++-- src/shared/libproc-process-table.ts | 416 +++++++----------- src/shared/libproc-ps-format.ts | 139 ++++++ src/shared/process-table-snapshot-reader.ts | 23 +- src/shared/shell-process-readiness.ts | 15 +- src/shared/tmux-host-attachment-probe.ts | 2 +- 21 files changed, 982 insertions(+), 441 deletions(-) create mode 100644 src/shared/darwin-terminal-naming-slot.ts create mode 100644 src/shared/libproc-addon.ts create mode 100644 src/shared/libproc-argv-completion.ts create mode 100644 src/shared/libproc-ps-format.ts diff --git a/config/patches/node-pty@1.1.0.patch b/config/patches/node-pty@1.1.0.patch index 6cd57d06a86e..00fe9883eb84 100644 --- a/config/patches/node-pty@1.1.0.patch +++ b/config/patches/node-pty@1.1.0.patch @@ -297,7 +297,7 @@ index 181ccabbbe9c4948a9725fb1db907a68e9de01fc..67f31facf85562b67adbfbd04ce28ddd process.send!({ consoleProcessList }); process.exit(0); diff --git a/src/unix/pty.cc b/src/unix/pty.cc -index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e1938e9ca 100644 +index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af387224f243 100644 --- a/src/unix/pty.cc +++ b/src/unix/pty.cc @@ -23,8 +23,11 @@ @@ -352,7 +352,17 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e /* Some platforms name VWERASE and VDISCARD differently */ #if !defined(VWERASE) && defined(VWERSE) #define VWERASE VWERSE -@@ -228,6 +264,9 @@ Napi::Value PtyGetProc(const Napi::CallbackInfo& info); +@@ -67,6 +103,9 @@ + #include + #include + #include ++#include ++#include ++#include + #endif + + /* NSIG - macro for highest signal + 1, should be defined */ +@@ -228,6 +267,9 @@ Napi::Value PtyGetProc(const Napi::CallbackInfo& info); static int pty_nonblock(int); @@ -362,7 +372,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e #if defined(__APPLE__) static char * pty_getproc(int); -@@ -237,13 +276,23 @@ pty_getproc(int, char *); +@@ -237,13 +279,23 @@ pty_getproc(int, char *); #endif #if defined(__APPLE__) || defined(__OpenBSD__) @@ -387,7 +397,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e #endif struct DelBuf { -@@ -345,8 +394,8 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { +@@ -345,8 +397,8 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { term->c_cc[VSTATUS] = 20; #endif @@ -398,7 +408,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e // helperPath std::string helper_path = info[9].As(); -@@ -367,14 +416,18 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { +@@ -367,14 +419,18 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { argv[i + 3] = strdup(arg.c_str()); } @@ -421,7 +431,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e #else int argc = argv_.Length(); int argl = argc + 2; -@@ -445,6 +498,9 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { +@@ -445,6 +501,9 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { if (pty_nonblock(master) == -1) { throw Napi::Error::New(napiEnv, "Could not set master fd to nonblocking."); } @@ -431,7 +441,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e } #endif -@@ -586,6 +642,23 @@ pty_nonblock(int fd) { +@@ -586,6 +645,23 @@ pty_nonblock(int fd) { return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } @@ -455,7 +465,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e /** * pty_getproc * Taken from tmux. -@@ -684,15 +757,73 @@ pty_getproc(int fd, char *tty) { +@@ -684,15 +760,73 @@ pty_getproc(int fd, char *tty) { #endif #if defined(__APPLE__) @@ -531,25 +541,25 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e for (; count < 3; count++) { low_fds[count] = posix_openpt(O_RDWR); -@@ -706,84 +837,342 @@ pty_posix_spawn(char** argv, char** env, +@@ -706,81 +840,460 @@ pty_posix_spawn(char** argv, char** env, POSIX_SPAWN_SETSID; *master = posix_openpt(O_RDWR); if (*master == -1) { - return; + pty_set_spawn_error(err, "posix_openpt", errno); -+ goto done; -+ } -+ -+ res = grantpt(*master); -+ if (res == -1) { -+ pty_set_spawn_error(err, "grantpt", errno); + goto done; } - int res = grantpt(*master) || unlockpt(*master); -+ res = unlockpt(*master); ++ res = grantpt(*master); if (res == -1) { - return; ++ pty_set_spawn_error(err, "grantpt", errno); ++ goto done; ++ } ++ ++ res = unlockpt(*master); ++ if (res == -1) { + pty_set_spawn_error(err, "unlockpt", errno); + goto done; } @@ -664,57 +674,78 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e + close(*master); + *master = -1; + } - -- for (; count > 0; count--) { -- close(low_fds[count]); ++ + for (size_t i = 0; i <= count && i < 3; i++) { + if (low_fds[i] != -1) { + close(low_fds[i]); + } - } - } - #endif - ++ } ++} ++#endif ++ +#if defined(__APPLE__) +/** + * Orca: in-process libproc/sysctl process table + * + * /bin/ps is setuid root, so every exec triggers an uncached syspolicyd -+ * assessment; pollers read the table here instead (#31783). ++ * assessment; pollers read the table here instead (#31783). Commands are ++ * rendered exactly as adv_cmds ps does (getproclline + strvis). + */ + ++// adv_cmds ps/print.c getproclline() with show_args and without -E. +static bool +orca_read_process_args(pid_t pid, std::vector& buf, std::string* out) { + int mib[3] = { CTL_KERN, KERN_PROCARGS2, pid }; + size_t size = buf.size(); -+ if (sysctl(mib, 3, buf.data(), &size, NULL, 0) != 0 || size <= sizeof(int)) { ++ if (size < sizeof(int) || sysctl(mib, 3, buf.data(), &size, NULL, 0) != 0 || ++ size < sizeof(int) || size > buf.size()) { + return false; + } -+ int argc; -+ memcpy(&argc, buf.data(), sizeof(argc)); -+ const char* cursor = buf.data() + sizeof(argc); -+ const char* end = buf.data() + size; -+ while (cursor < end && *cursor != '\0') cursor++; -+ while (cursor < end && *cursor == '\0') cursor++; -+ out->clear(); -+ for (int i = 0; i < argc && cursor < end; i++) { -+ size_t length = strnlen(cursor, end - cursor); -+ if (i > 0) out->push_back(' '); -+ out->append(cursor, length); -+ cursor += length + 1; ++ char* procargs = buf.data(); ++ char* end = procargs + size; ++ int nargs; ++ memcpy(&nargs, procargs, sizeof(nargs)); ++ char* cp = procargs + sizeof(nargs); ++ while (cp < end && *cp != '\0') cp++; ++ if (cp == end) return false; ++ while (cp < end && *cp == '\0') cp++; ++ if (cp == end) return false; ++ char* sp = cp; ++ char* np = NULL; ++ for (int c = 0; c < nargs && cp < end; cp++) { ++ if (*cp == '\0') { ++ c++; ++ if (np != NULL) *np = ' '; ++ np = cp; ++ } + } -+ return argc > 0; ++ if (np == NULL || np == sp) return false; ++ out->assign(sp, strnlen(sp, end - sp)); ++ return true; +} + ++// ps vis-encodes the whole command (print.c get_command_and_or_args). +static bool -+orca_read_kinfo_all(std::vector* procs) { -+ int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 }; ++orca_vis_command(const std::string& raw, std::string* out) { ++ // ps sizes strvis output at 4x; strnvis encodes the same but fails instead of overflowing. ++ if (raw.size() > (SIZE_MAX - 1) / 4) return false; ++ std::vector encoded(raw.size() * 4 + 1); ++ int length = strnvis(encoded.data(), encoded.size(), raw.c_str(), VIS_TAB | VIS_NL | VIS_NOSLASH); ++ if (length < 0 || (size_t)length >= encoded.size()) return false; ++ out->assign(encoded.data(), length); ++ return true; ++} ++ ++static bool ++orca_read_kinfo(int what, int flag, std::vector* procs) { ++ int mib[4] = { CTL_KERN, KERN_PROC, what, flag }; ++ u_int mib_length = what == KERN_PROC_ALL ? 3 : 4; + for (int attempt = 0; attempt < 8; attempt++) { + size_t size = 0; -+ if (sysctl(mib, 3, NULL, &size, NULL, 0) != 0) return false; ++ if (sysctl(mib, mib_length, NULL, &size, NULL, 0) != 0) return false; + size += size / 8 + sizeof(struct kinfo_proc) * 16; + procs->resize(size / sizeof(struct kinfo_proc)); -+ if (sysctl(mib, 3, procs->data(), &size, NULL, 0) == 0) { ++ if (sysctl(mib, mib_length, procs->data(), &size, NULL, 0) == 0) { + procs->resize(size / sizeof(struct kinfo_proc)); + return true; + } @@ -727,33 +758,102 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e +orca_read_kinfo_pid(pid_t pid, struct kinfo_proc* proc) { + int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }; + size_t size = sizeof(*proc); -+ return sysctl(mib, 4, proc, &size, NULL, 0) == 0 && size == sizeof(*proc); ++ return sysctl(mib, 4, proc, &size, NULL, 0) == 0 && size == sizeof(*proc) && ++ proc->kp_proc.p_pid == pid; ++} ++ ++static bool ++orca_is_char_device(const char* path, dev_t* dev) { ++ struct stat sb; ++ if (stat(path, &sb) != 0 || !S_ISCHR(sb.st_mode)) return false; ++ *dev = sb.st_rdev; ++ return true; ++} ++ ++// adv_cmds ps/ps.c addelem_tty(): "/dev/ttys001", "ttys001", "s001" and "co" all name a terminal. ++static bool ++orca_resolve_tty(const std::string& elem, dev_t* dev) { ++ if (elem.empty()) return false; ++ std::string path; ++ if (elem[0] == '/') { ++ path = elem; ++ } else if (elem == "co") { ++ path = _PATH_CONSOLE; ++ } else { ++ path = std::string(_PATH_DEV) + elem; ++ bool literal = path.compare(0, strlen(_PATH_TTY), _PATH_TTY) == 0 || path == _PATH_CONSOLE; ++ if (!literal && orca_is_char_device((std::string(_PATH_TTY) + elem).c_str(), dev)) { ++ return true; ++ } ++ } ++ return access(path.c_str(), F_OK) == 0 && orca_is_char_device(path.c_str(), dev); +} + +struct orca_process_row { + struct kinfo_proc proc; -+ bool has_command; + std::string command; ++ // argv was unreadable (another user's process): ps, being setuid root, would print more. ++ bool command_incomplete; ++}; ++ ++struct orca_process_query { ++ bool include_command; ++ bool select_pids; ++ std::vector pids; ++ bool select_tty; ++ std::string tty; ++ std::string ctype; +}; + ++static void ++orca_fill_command(const struct kinfo_proc& proc, std::vector& args_buf, orca_process_row* row) { ++ pid_t pid = proc.kp_proc.p_pid; ++ std::string raw; ++ if (proc.kp_proc.p_stat == SZOMB) { ++ raw = ""; ++ } else if (!orca_read_process_args(pid, args_buf, &raw)) { ++ row->command_incomplete = true; ++ char path[PROC_PIDPATHINFO_MAXSIZE]; ++ int length = proc_pidpath(pid, path, sizeof(path)); ++ if (length > 0 && (size_t)length < sizeof(path)) { ++ raw.assign(path, length); ++ } else { ++ raw = std::string("(") + ++ std::string(proc.kp_proc.p_comm, strnlen(proc.kp_proc.p_comm, sizeof(proc.kp_proc.p_comm))) + ++ ")"; ++ } ++ } ++ if (!orca_vis_command(raw, &row->command)) { ++ row->command = "(" + ++ std::string(proc.kp_proc.p_comm, strnlen(proc.kp_proc.p_comm, sizeof(proc.kp_proc.p_comm))) + ++ ")"; ++ row->command_incomplete = true; ++ } ++} ++ +// Runs on a worker thread: argv for ~2,000 processes costs ~17ms of syscalls. -+static bool -+orca_gather_process_table(bool include_command, -+ const std::vector* pids, -+ std::vector* rows) { ++// Returns 0 on success, 1 when the -t terminal does not exist, -1 on failure. ++static int ++orca_gather_process_table(const orca_process_query& query, std::vector* rows) { + std::vector procs; -+ if (pids) { -+ for (pid_t pid : *pids) { ++ if (query.select_pids) { ++ for (pid_t pid : query.pids) { + struct kinfo_proc proc; + if (orca_read_kinfo_pid(pid, &proc)) { + procs.push_back(proc); + } + } -+ } else if (!orca_read_kinfo_all(&procs)) { -+ return false; ++ } else if (query.select_tty) { ++ dev_t dev; ++ if (!orca_resolve_tty(query.tty, &dev)) return 1; ++ if (!orca_read_kinfo(KERN_PROC_TTY, (int)dev, &procs)) return -1; ++ } else if (!orca_read_kinfo(KERN_PROC_ALL, 0, &procs)) { ++ return -1; + } + std::vector args_buf; -+ if (include_command) { ++ locale_t ctype = (locale_t)0; ++ locale_t previous = (locale_t)0; ++ if (query.include_command) { + int argmax = 0; + size_t argmax_size = sizeof(argmax); + int mib[2] = { CTL_KERN, KERN_ARGMAX }; @@ -761,29 +861,34 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e + argmax = 1024 * 1024; + } + args_buf.resize(argmax); ++ // ps runs setlocale(LC_ALL, ""), so strvis escapes per the caller's LC_CTYPE; scope it to this thread. ++ ctype = newlocale(LC_CTYPE_MASK, query.ctype.c_str(), (locale_t)0); ++ if (ctype == (locale_t)0) ctype = newlocale(LC_CTYPE_MASK, "C", (locale_t)0); ++ if (ctype == (locale_t)0) return -1; ++ previous = uselocale(ctype); ++ if (previous == (locale_t)0) { ++ freelocale(ctype); ++ return -1; ++ } + } + rows->reserve(procs.size()); + for (const struct kinfo_proc& proc : procs) { -+ pid_t pid = proc.kp_proc.p_pid; -+ if (pid <= 0) continue; -+ orca_process_row row = { proc, false, "" }; -+ if (include_command) { -+ row.has_command = orca_read_process_args(pid, args_buf, &row.command); -+ if (!row.has_command) { -+ // Another user's argv needs setuid ps; the executable path still names the program. -+ char path[PROC_PIDPATHINFO_MAXSIZE]; -+ int length = proc_pidpath(pid, path, sizeof(path)); -+ if (length > 0) { -+ row.command.assign(path, length); -+ row.has_command = true; -+ } -+ } ++ if (proc.kp_proc.p_pid <= 0) continue; ++ orca_process_row row = { proc, "", false }; ++ if (query.include_command) { ++ orca_fill_command(proc, args_buf, &row); + } + rows->push_back(std::move(row)); + } -+ return true; ++ if (query.include_command) { ++ uselocale(previous); ++ freelocale(ctype); ++ } ++ return 0; +} -+ + +- for (; count > 0; count--) { +- close(low_fds[count]); +static Napi::Array +orca_process_rows_to_js(Napi::Env env, bool include_command, const std::vector& rows) { + Napi::Array result = Napi::Array::New(env, rows.size()); @@ -798,51 +903,82 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e + row.Set("tdev", Napi::Number::New(env, proc.kp_eproc.e_tdev)); + row.Set("status", Napi::Number::New(env, proc.kp_proc.p_stat)); + row.Set("flags", Napi::Number::New(env, proc.kp_proc.p_flag)); ++ row.Set("nice", Napi::Number::New(env, proc.kp_proc.p_nice)); + row.Set("sessionLeader", Napi::Boolean::New(env, (proc.kp_eproc.e_flag & EPROC_SLEADER) != 0)); + row.Set("startSec", Napi::Number::New(env, (double)proc.kp_proc.p_starttime.tv_sec)); + row.Set("comm", Napi::String::New(env, proc.kp_proc.p_comm, strnlen(proc.kp_proc.p_comm, sizeof(proc.kp_proc.p_comm)))); + if (include_command) { -+ row.Set("command", entry.has_command ? Napi::Value(Napi::String::New(env, entry.command)) : env.Null()); ++ row.Set("command", Napi::String::New(env, entry.command)); ++ row.Set("commandIncomplete", Napi::Boolean::New(env, entry.command_incomplete)); + } + result.Set(index++, row); -+ } + } + return result; +} + -+static bool -+orca_read_pid_list(const Napi::CallbackInfo& info, std::vector* pids) { -+ if (info.Length() < 2 || !info[1].IsArray()) { -+ return false; ++// readProcessTable({ command, pids?, tty?, ctype? }): pids and tty are exclusive selections, as Orca issues them. ++static orca_process_query ++orca_read_process_query(const Napi::CallbackInfo& info) { ++ Napi::Env env(info.Env()); ++ if (info.Length() < 1 || !info[0].IsObject()) { ++ throw Napi::TypeError::New(env, "Usage: readProcessTable({ command, pids, tty, ctype })"); + } -+ Napi::Array list = info[1].As(); -+ for (uint32_t i = 0; i < list.Length(); i++) { -+ Napi::Value pid = list.Get(i); -+ if (pid.IsNumber()) { -+ pids->push_back(pid.As().Int32Value()); ++ Napi::Object options = info[0].As(); ++ orca_process_query query = { false, false, {}, false, "", "C" }; ++ query.include_command = options.Get("command").ToBoolean().Value(); ++ Napi::Value pids = options.Get("pids"); ++ if (pids.IsArray()) { ++ Napi::Array list = pids.As(); ++ for (uint32_t i = 0; i < list.Length(); i++) { ++ Napi::Value pid = list.Get(i); ++ double value = pid.IsNumber() ? pid.As().DoubleValue() : 0; ++ if (!(value >= 1 && value <= INT32_MAX) || value != (double)(int32_t)value) { ++ throw Napi::TypeError::New(env, "readProcessTable: pids must be positive integers"); ++ } ++ pid_t candidate = (pid_t)value; ++ if (std::find(query.pids.begin(), query.pids.end(), candidate) == query.pids.end()) { ++ query.pids.push_back(candidate); ++ } + } ++ query.select_pids = true; + } -+ return true; ++ Napi::Value tty = options.Get("tty"); ++ if (tty.IsString()) { ++ if (query.select_pids) { ++ throw Napi::TypeError::New(env, "readProcessTable: pids and tty are exclusive"); ++ } ++ query.tty = tty.As().Utf8Value(); ++ query.select_tty = true; ++ } ++ Napi::Value ctype = options.Get("ctype"); ++ if (ctype.IsString()) { ++ query.ctype = ctype.As().Utf8Value(); ++ } ++ return query; +} + +class OrcaProcessTableWorker : public Napi::AsyncWorker { + public: -+ OrcaProcessTableWorker(Napi::Env env, bool include_command, std::vector pids, bool selected) ++ OrcaProcessTableWorker(Napi::Env env, orca_process_query query) + : Napi::AsyncWorker(env), + deferred_(Napi::Promise::Deferred::New(env)), -+ include_command_(include_command), -+ pids_(std::move(pids)), -+ selected_(selected) {} ++ query_(std::move(query)), ++ status_(-1) {} + + Napi::Promise Promise() { return deferred_.Promise(); } + + void Execute() override { -+ if (!orca_gather_process_table(include_command_, selected_ ? &pids_ : NULL, &rows_)) { ++ status_ = orca_gather_process_table(query_, &rows_); ++ if (status_ < 0) { + SetError("orca: process table sysctl failed"); + } + } + + void OnOK() override { -+ deferred_.Resolve(orca_process_rows_to_js(Env(), include_command_, rows_)); ++ Napi::Env env = Env(); ++ // ps exits 1 without output when -t names no terminal. ++ deferred_.Resolve(status_ == 1 ? env.Null() ++ : Napi::Value(orca_process_rows_to_js(env, query_.include_command, rows_))); + } + + void OnError(const Napi::Error& error) override { @@ -851,18 +987,13 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e + + private: + Napi::Promise::Deferred deferred_; -+ bool include_command_; -+ std::vector pids_; -+ bool selected_; ++ orca_process_query query_; ++ int status_; + std::vector rows_; +}; + +Napi::Value OrcaProcessTableAsync(const Napi::CallbackInfo& info) { -+ bool include_command = info.Length() > 0 && info[0].ToBoolean().Value(); -+ std::vector pids; -+ bool selected = orca_read_pid_list(info, &pids); -+ OrcaProcessTableWorker* worker = -+ new OrcaProcessTableWorker(info.Env(), include_command, std::move(pids), selected); ++ OrcaProcessTableWorker* worker = new OrcaProcessTableWorker(info.Env(), orca_read_process_query(info)); + Napi::Promise promise = worker->Promise(); + worker->Queue(); + return promise; @@ -878,7 +1009,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e + if (size != (int)sizeof(vnode) || vnode.pvi_cdir.vip_path[0] == '\0') { + return env.Null(); + } -+ return Napi::String::New(env, vnode.pvi_cdir.vip_path); ++ return Napi::String::New(env, vnode.pvi_cdir.vip_path, strnlen(vnode.pvi_cdir.vip_path, sizeof(vnode.pvi_cdir.vip_path))); +} + +Napi::Value OrcaProcessPath(const Napi::CallbackInfo& info) { @@ -888,22 +1019,19 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e487438a0f9361b51faa6c44583a0e5e + } + char path[PROC_PIDPATHINFO_MAXSIZE]; + int length = proc_pidpath(info[0].As().Int32Value(), path, sizeof(path)); -+ if (length <= 0) { ++ if (length <= 0 || (size_t)length >= sizeof(path)) { + return env.Null(); + } + return Napi::String::New(env, path, length); -+} -+#endif -+ - /** - * Init - */ -@@ -793,6 +1182,11 @@ Napi::Object init(Napi::Env env, Napi::Object exports) { + } + #endif + +@@ -793,6 +1306,11 @@ Napi::Object init(Napi::Env env, Napi::Object exports) { exports.Set("open", Napi::Function::New(env, PtyOpen)); exports.Set("resize", Napi::Function::New(env, PtyResize)); exports.Set("process", Napi::Function::New(env, PtyGetProc)); +#if defined(__APPLE__) -+ exports.Set("processTable", Napi::Function::New(env, OrcaProcessTableAsync)); ++ exports.Set("readProcessTable", Napi::Function::New(env, OrcaProcessTableAsync)); + exports.Set("processCwd", Napi::Function::New(env, OrcaProcessCwd)); + exports.Set("processPath", Napi::Function::New(env, OrcaProcessPath)); +#endif diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 854084c11f0a..4caccb642ebf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -184,7 +184,7 @@ patchedDependencies: i18next-cli@1.74.2: 2ee32eef742615cd133e1a6940f027deb3723a8430bb7953bba3a6769b0aac47 lint-staged@16.4.0: 7333b3837f80a7fbd045964db6d76ba4fc118e49134bdbabb00585b6b7b60673 monaco-editor@0.55.1: 53b71f7d8a7c00b76ffdb73ce83d18e31692f193f5fafa6a390e48f5b3fdd636 - node-pty@1.1.0: f60c52f7ee0a77bb259267c3232c723eca466b535ec277677cf061e7187a37a8 + node-pty@1.1.0: 47ebb5c7a5c70106f439576efaf8335f147fe78cd54357cba11d6fd5b1bc975e oxlint-plugin-anti-slop@0.1.2: c10c871702365a0c2c59e9f1c5fb92df97cae5755d534c0a3d83c6368f6feafe sprintf-js@1.1.3: 05316a8b01f155fe19a1e0cb4042c81d43d798a76755c407684e1199a18b1e08 vitest@5.0.5: 166c034c864f98267e7d479f083b8d37ea9a7b08d6662313dd38e7c69c9a3eb4 @@ -232,7 +232,7 @@ importers: version: 3.3.1 node-pty: specifier: ^1.1.0 - version: 1.1.0(patch_hash=f60c52f7ee0a77bb259267c3232c723eca466b535ec277677cf061e7187a37a8) + version: 1.1.0(patch_hash=47ebb5c7a5c70106f439576efaf8335f147fe78cd54357cba11d6fd5b1bc975e) posthog-node: specifier: ^5.52.5 version: 5.52.5 @@ -13748,7 +13748,7 @@ snapshots: node-int64@0.4.0: {} - node-pty@1.1.0(patch_hash=f60c52f7ee0a77bb259267c3232c723eca466b535ec277677cf061e7187a37a8): + node-pty@1.1.0(patch_hash=47ebb5c7a5c70106f439576efaf8335f147fe78cd54357cba11d6fd5b1bc975e): dependencies: node-addon-api: 7.1.1 diff --git a/src/main/daemon/daemon-process-inspection.ts b/src/main/daemon/daemon-process-inspection.ts index 4a4af61982e1..ceb055e7e669 100644 --- a/src/main/daemon/daemon-process-inspection.ts +++ b/src/main/daemon/daemon-process-inspection.ts @@ -2,7 +2,7 @@ import { execFile } from 'node:child_process' import { readFile } from 'node:fs/promises' import { promisify } from 'node:util' import { psLocaleEnvironment } from '../../shared/ps-locale-environment' -import { runPsInProcess } from '../../shared/libproc-process-table' +import { readPsStdoutInProcess } from '../../shared/libproc-process-table' import { parseLinuxBootTimeSeconds, parseLinuxProcStartTicks } from './daemon-process-start-time' import type { LinuxStatEvidence, @@ -203,12 +203,12 @@ async function runInspectionCommand( args: string[], timeoutMs: number ): Promise { - const inProcess = file === 'ps' ? await runPsInProcess(args, psLocaleEnvironment()) : null - if (inProcess) { - if (inProcess.code !== 0) { - throw new Error(`ps ${args.join(' ')} matched no process`) - } - return inProcess.stdout + const inProcess = + file === 'ps' + ? await readPsStdoutInProcess(args, { env: psLocaleEnvironment(), timeoutMs }) + : null + if (inProcess !== null) { + return inProcess } const { stdout } = await execFileAsync(file, args, { encoding: 'utf8', diff --git a/src/main/provider-process/provider-process-row-read.ts b/src/main/provider-process/provider-process-row-read.ts index 159d7b3783d2..81fce0c1252a 100644 --- a/src/main/provider-process/provider-process-row-read.ts +++ b/src/main/provider-process/provider-process-row-read.ts @@ -48,7 +48,11 @@ async function readPsProcessRow(pid: number): Promise { // Stable locale makes repeated start markers comparable. const env = { ...process.env, LANG: 'C', LC_ALL: 'C' } const result = - (await runPsInProcess(args, env)) ?? + (await runPsInProcess(args, { + env, + timeoutMs: PROCESS_ROW_TIMEOUT_MS, + maxOutputBytes: 4096 + })) ?? (await runProcess({ program: 'ps', args, diff --git a/src/main/providers/process-cwd.ts b/src/main/providers/process-cwd.ts index 2a1ec987f315..3a4b78f27c0c 100644 --- a/src/main/providers/process-cwd.ts +++ b/src/main/providers/process-cwd.ts @@ -1,7 +1,7 @@ import { execFile as execFileCb } from 'node:child_process' import { readlink } from 'node:fs/promises' import { LSOF_NONBLOCKING_ARGS } from '../../shared/lsof-nonblocking-args' -import { readLibprocProcessCwd } from '../../shared/libproc-process-table' +import { readLibprocProcessCwd } from '../../shared/libproc-addon' // Coalesce/cache per-PID cwd reads briefly so rapid pane actions cannot accumulate lsof subprocesses. const CACHE_TTL_MS = 1500 diff --git a/src/main/pty-descendant-termination.ts b/src/main/pty-descendant-termination.ts index 924df78e626b..a2b642807983 100644 --- a/src/main/pty-descendant-termination.ts +++ b/src/main/pty-descendant-termination.ts @@ -6,7 +6,7 @@ import { type WindowsTreeKillTarget } from './windows-pty-root-identity' import { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' -import { runPsInProcess } from '../shared/libproc-process-table' +import { readPsStdoutInProcess } from '../shared/libproc-process-table' export { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' @@ -47,9 +47,9 @@ async function readFreshProcessTable( const capturedAtMs = Date.now() // Pin lstart’s locale so delayed identity checks parse it consistently. const env = { ...process.env, LANG: 'C', LC_ALL: 'C' } - const inProcess = await runPsInProcess(DESCENDANT_PS_ARGS, env) - if (inProcess) { - return { rows: parseProcessTable(inProcess.stdout), capturedAtMs } + const inProcess = await readPsStdoutInProcess(DESCENDANT_PS_ARGS, { env, timeoutMs }) + if (inProcess !== null) { + return { rows: parseProcessTable(inProcess), capturedAtMs } } const options = { maxBuffer: PS_MAX_BUFFER_BYTES, timeout: timeoutMs, env } return new Promise((resolve, reject) => { diff --git a/src/main/pty/posix-pty-foreground-group.ts b/src/main/pty/posix-pty-foreground-group.ts index 00e790706038..9f25327cc468 100644 --- a/src/main/pty/posix-pty-foreground-group.ts +++ b/src/main/pty/posix-pty-foreground-group.ts @@ -31,7 +31,10 @@ function hasUsableTty(tty: string): boolean { async function runPs(pid: number): Promise { const args = ['-p', String(pid), '-o', 'pid=,tpgid=,tty='] const result = - (await runPsInProcess(args)) ?? + (await runPsInProcess(args, { + timeoutMs: PROCESS_TABLE_QUERY_TIMEOUT_MS, + maxOutputBytes: PROCESS_TABLE_MAX_BYTES + })) ?? (await runProcess({ program: 'ps', args, diff --git a/src/main/runtime/agent-session/ownership/agent-session-process-identity-probe.ts b/src/main/runtime/agent-session/ownership/agent-session-process-identity-probe.ts index 05673341b874..6a2773accb74 100644 --- a/src/main/runtime/agent-session/ownership/agent-session-process-identity-probe.ts +++ b/src/main/runtime/agent-session/ownership/agent-session-process-identity-probe.ts @@ -63,7 +63,7 @@ async function readDarwinProcessStartTimeMs(pid: number): Promise const args = ['-o', 'lstart=', '-p', String(pid)] const env = psLocaleEnvironment() const result = - (await runPsInProcess(args, env)) ?? + (await runPsInProcess(args, { env, timeoutMs: PROCESS_START_TIME_TIMEOUT_MS })) ?? (await runProcess({ program: 'ps', args, env, timeoutMs: PROCESS_START_TIME_TIMEOUT_MS })) if (result.timedOut || result.code !== 0) { return null @@ -86,7 +86,7 @@ async function readDarwinProcessStartTimesMs( const args = ['-o', 'pid=,lstart=', '-p', pids.join(',')] const env = psLocaleEnvironment() const result = - (await runPsInProcess(args, env)) ?? + (await runPsInProcess(args, { env, timeoutMs: PROCESS_START_TIME_TIMEOUT_MS })) ?? (await runProcess({ program: 'ps', args, env, timeoutMs: PROCESS_START_TIME_TIMEOUT_MS })) if (result.timedOut || result.code !== 0) { return observed diff --git a/src/main/runtime/terminal-foreground-group.ts b/src/main/runtime/terminal-foreground-group.ts index d49447523085..decdb5aa3c7e 100644 --- a/src/main/runtime/terminal-foreground-group.ts +++ b/src/main/runtime/terminal-foreground-group.ts @@ -18,7 +18,11 @@ async function ps(args: readonly string[]): Promise { try { const env = psLocaleEnvironment() const result = - (await runPsInProcess(args, env)) ?? + (await runPsInProcess(args, { + env, + timeoutMs: PS_TIMEOUT_MS, + maxOutputBytes: PS_MAX_OUTPUT_BYTES + })) ?? (await runProcess({ program: 'ps', args, diff --git a/src/shared/agent-process-presence-probe.ts b/src/shared/agent-process-presence-probe.ts index 46910085b4ac..873ed92a38d5 100644 --- a/src/shared/agent-process-presence-probe.ts +++ b/src/shared/agent-process-presence-probe.ts @@ -47,7 +47,7 @@ export async function readAgentProcess(pid: number): Promise({ runPs: async () => { - const inProcess = await runPsInProcess(CHEAP_PS_ARGS, psLocaleEnvironment()) - if (inProcess) { - return parseCheapProcessTableRows(inProcess.stdout) - } - const result = await runProcess({ - program: 'ps', - args: CHEAP_PS_ARGS, + const options = { env: psLocaleEnvironment(), timeoutMs: PS_TIMEOUT_MS, maxOutputBytes: PS_MAX_BUFFER_BYTES - }) + } + const result = + (await runPsInProcess(CHEAP_PS_ARGS, options)) ?? + (await runProcess({ program: 'ps', args: CHEAP_PS_ARGS, ...options })) // A ceiling hit is truncation, not absence: name it in the domain vocabulary. if (result.outputTruncated) { throw new ProcessTableCaptureError('capture_truncated') diff --git a/src/shared/darwin-process-table-capture.ts b/src/shared/darwin-process-table-capture.ts index 6d8c36404dd9..2ac09f574a3d 100644 --- a/src/shared/darwin-process-table-capture.ts +++ b/src/shared/darwin-process-table-capture.ts @@ -1,10 +1,14 @@ import { nameDarwinTerminals } from './darwin-terminal-names' +import { + claimDarwinTerminalNaming, + isDarwinTerminalNamingInFlight, + resetDarwinTerminalNamingForTests +} from './darwin-terminal-naming-slot' import { errorMessage } from './error-message' import { ProcessTableCaptureError, PS_ARGS } from './process-table-snapshot' import { withTimeout } from './promise-timeout-fallback' let deviceColumnUnsupported = false -let terminalNamingInFlight: Promise | null = null export async function captureDarwinProcessTable( capture: (args: readonly string[], timeoutMs?: number) => Promise, @@ -20,7 +24,7 @@ export async function captureDarwinProcessTable( return remaining } const canonicalCapture = (): Promise => capture(PS_ARGS, remainingBudget()) - if (deviceColumnUnsupported || terminalNamingInFlight) { + if (deviceColumnUnsupported || isDarwinTerminalNamingInFlight()) { return canonicalCapture() } let captured: string @@ -42,19 +46,14 @@ export async function captureDarwinProcessTable( return canonicalCapture() } remainingBudget() - if (terminalNamingInFlight) { - return canonicalCapture() - } const controller = new AbortController() - const pending = nameDarwinTerminals(captured, undefined, controller.signal) - terminalNamingInFlight = pending - // Uncancelable filesystem calls keep the slot until they drain. - const clearNaming = (): void => { - if (terminalNamingInFlight === pending) { - terminalNamingInFlight = null - } + // In-process `tty=` captures share this slot, so the canonical fallback never names concurrently either. + const pending = claimDarwinTerminalNaming(() => + nameDarwinTerminals(captured, undefined, controller.signal) + ) + if (!pending) { + return canonicalCapture() } - void pending.then(clearNaming, clearNaming) let remainingMs: number try { remainingMs = remainingBudget() @@ -90,5 +89,5 @@ export async function captureDarwinProcessTable( export function resetDarwinProcessTableCaptureForTests(): void { deviceColumnUnsupported = false - terminalNamingInFlight = null + resetDarwinTerminalNamingForTests() } diff --git a/src/shared/darwin-terminal-naming-slot.ts b/src/shared/darwin-terminal-naming-slot.ts new file mode 100644 index 000000000000..7984ad6ab741 --- /dev/null +++ b/src/shared/darwin-terminal-naming-slot.ts @@ -0,0 +1,25 @@ +let namingInFlight: Promise | null = null + +/** One /dev naming pass at a time: aborted lstat/opendir calls hold libuv pool threads until they drain. Null while one drains. */ +export function claimDarwinTerminalNaming(name: () => Promise): Promise | null { + if (namingInFlight) { + return null + } + const pending = name() + namingInFlight = pending + const release = (): void => { + if (namingInFlight === pending) { + namingInFlight = null + } + } + void pending.then(release, release) + return pending +} + +export function isDarwinTerminalNamingInFlight(): boolean { + return namingInFlight !== null +} + +export function resetDarwinTerminalNamingForTests(): void { + namingInFlight = null +} diff --git a/src/shared/libproc-addon.ts b/src/shared/libproc-addon.ts new file mode 100644 index 000000000000..33b87f0861a1 --- /dev/null +++ b/src/shared/libproc-addon.ts @@ -0,0 +1,118 @@ +import { createRequire } from 'node:module' + +/** One `kinfo_proc` from node-pty's patched macOS addon (config/patches/node-pty@1.1.0.patch). */ +export type LibprocProcessRow = { + pid: number + ppid: number + pgid: number + tpgid: number + /** `e_tdev`; -1 (NODEV) without a controlling terminal. */ + tdev: number + /** `p_stat`: SIDL 1, SRUN 2, SSLEEP 3, SSTOP 4, SZOMB 5. */ + status: number + flags: number + /** `p_nice`; absent from older builds. */ + nice?: number + sessionLeader: boolean + startSec: number + comm: string + /** ps's command text (getproclline + strvis in the query's LC_CTYPE). */ + command?: string + /** argv was unreadable (another user's process): `command` holds the executable path, where setuid ps prints argv. */ + commandIncomplete?: boolean +} + +/** `pids` and `tty` are exclusive; `tty` follows ps -t naming. Null when the terminal does not exist. */ +export type LibprocQuery = { + command: boolean + pids?: readonly number[] + tty?: string + ctype?: string +} + +export type LibprocAddon = { + /** Reads on a libuv worker thread; argv for a whole table costs ~20ms of syscalls. */ + readProcessTable: (query: LibprocQuery) => Promise + processCwd: (pid: number) => string | null + processPath: (pid: number) => string | null +} + +const requireFromHere = createRequire(__filename) +let cachedAddon: LibprocAddon | null | undefined +let addonOverride: LibprocAddon | null | undefined + +function isLibprocAddon(native: unknown): native is LibprocAddon { + return ( + typeof native === 'object' && + native !== null && + 'readProcessTable' in native && + typeof native.readProcessTable === 'function' && + 'processCwd' in native && + typeof native.processCwd === 'function' && + 'processPath' in native && + typeof native.processPath === 'function' + ) +} + +/** The in-process reader, or null where ps/lsof must still run (non-macOS, an unpatched or unloadable node-pty). + * Vitest keeps the subprocess path so ps fixtures stay authoritative. */ +export function loadLibprocAddon(): LibprocAddon | null { + if (addonOverride !== undefined) { + return addonOverride + } + if (process.platform !== 'darwin' || process.env.VITEST === 'true') { + return null + } + if (cachedAddon !== undefined) { + return cachedAddon + } + try { + const utils: unknown = requireFromHere('node-pty/lib/utils') + const native: unknown = + typeof utils === 'object' && + utils !== null && + 'loadNativeModule' in utils && + typeof utils.loadNativeModule === 'function' + ? utils.loadNativeModule('pty')?.module + : null + // An older pty.node exports positional processTable() instead; it must not match. + cachedAddon = isLibprocAddon(native) ? native : null + } catch { + cachedAddon = null + } + if (cachedAddon === null) { + // A packaging regression would otherwise silently restore one setuid ps exec per poll (#31783). + console.warn('[process-table] node-pty lacks the libproc reader; falling back to ps and lsof') + } + return cachedAddon +} + +export function setLibprocAddonForTests(addon: LibprocAddon | null | undefined): void { + addonOverride = addon +} + +/** PROC_PIDVNODEPATHINFO cwd, or undefined when only lsof can answer. */ +export function readLibprocProcessCwd(pid: number): string | null | undefined { + const addon = loadLibprocAddon() + if (!addon) { + return undefined + } + try { + return addon.processCwd(pid) + } catch { + return undefined + } +} + +/** proc_pidpath executable, or undefined when only lsof can answer. */ +export function readLibprocProcessPath(pid: number): string | null | undefined { + const addon = loadLibprocAddon() + if (!addon) { + return undefined + } + try { + return addon.processPath(pid) + } catch { + return undefined + } +} diff --git a/src/shared/libproc-argv-completion.ts b/src/shared/libproc-argv-completion.ts new file mode 100644 index 000000000000..fcaa21149879 --- /dev/null +++ b/src/shared/libproc-argv-completion.ts @@ -0,0 +1,101 @@ +import { runProcess } from '@orca/process-host' +import type { LibprocProcessRow } from './libproc-addon' +import { NODEV } from './libproc-ps-format' + +const SZOMB_STATUS = 5 +const MAX_ANCESTOR_DEPTH = 64 + +/** A pane descendant: on a terminal, under one of the user's own (argv-readable) processes on that terminal, e.g. `sudo` under the pane shell. + * Root daemons have no terminal and a pane's root `login` sits under the terminal host, so neither costs a ps. */ +function isOnUsersTerminal( + row: LibprocProcessRow, + byPid: ReadonlyMap +): boolean { + if (row.tdev === NODEV) { + return false + } + let ancestor = byPid.get(row.ppid) + for (let depth = 0; ancestor && depth < MAX_ANCESTOR_DEPTH; depth += 1) { + if (ancestor.tdev === row.tdev && !ancestor.commandIncomplete) { + return true + } + ancestor = ancestor.pid === ancestor.ppid ? undefined : byPid.get(ancestor.ppid) + } + return false +} + +// Keyed by locale, pid and start time so a long-lived sudo agent costs one ps, not one per poll. +const authoritativeCommands = new Map() +const AUTHORITATIVE_COMMAND_LIMIT = 512 + +function commandKey(ctype: string, row: LibprocProcessRow): string { + return `${ctype}\0${row.pid}\0${row.startSec}` +} + +/** Fill argv only setuid ps can read, for the rows this caller selected or that run on a user's terminal. */ +export async function completeCommands( + rows: LibprocProcessRow[], + selectedByPid: boolean, + ctype: string, + env: NodeJS.ProcessEnv, + deadline: number +): Promise { + const byPid = new Map(rows.map((row) => [row.pid, row])) + const needed = rows.filter( + (row) => + row.commandIncomplete && + row.status !== SZOMB_STATUS && + (selectedByPid || isOnUsersTerminal(row, byPid)) + ) + const missing: LibprocProcessRow[] = [] + for (const row of needed) { + const cached = authoritativeCommands.get(commandKey(ctype, row)) + if (cached === undefined) { + missing.push(row) + } else { + row.command = cached + } + } + const timeoutMs = deadline - Date.now() + if (missing.length === 0 || timeoutMs <= 0) { + return + } + let stdout: string + try { + const result = await runProcess({ + program: '/bin/ps', + args: ['-ww', '-o', 'pid=,command=', '-p', missing.map((row) => row.pid).join(',')], + env, + timeoutMs, + maxOutputBytes: 1024 * 1024 + }) + // Unreadable rows keep the executable path and retry next read. + if (result.timedOut || result.outputTruncated || (result.code !== 0 && result.code !== 1)) { + return + } + stdout = result.stdout + } catch { + return + } + const commands = new Map() + for (const line of stdout.split('\n')) { + const match = /^\s*(\d+) (.*)$/.exec(line) + if (match) { + commands.set(Number(match[1]), match[2]) + } + } + for (const row of missing) { + const command = commands.get(row.pid) + if (command === undefined) { + continue + } + row.command = command + for (const oldest of authoritativeCommands.keys()) { + if (authoritativeCommands.size < AUTHORITATIVE_COMMAND_LIMIT) { + break + } + authoritativeCommands.delete(oldest) + } + authoritativeCommands.set(commandKey(ctype, row), command) + } +} diff --git a/src/shared/libproc-process-table.test.ts b/src/shared/libproc-process-table.test.ts index 39031f988c9f..5c712c36279d 100644 --- a/src/shared/libproc-process-table.test.ts +++ b/src/shared/libproc-process-table.test.ts @@ -1,21 +1,25 @@ import { afterEach, describe, expect, it, vi } from 'vitest' +const { runProcess } = vi.hoisted(() => ({ runProcess: vi.fn() })) +vi.mock('@orca/process-host', () => ({ runProcess })) vi.mock('./darwin-terminal-names', () => ({ nameDarwinTerminalDevices: async (devices: ReadonlySet) => new Map([...devices].filter((device) => device === '16/4').map((device) => [device, 'ttys004'])) })) import { - runPsInProcess, setLibprocAddonForTests, type LibprocAddon, - type LibprocProcessRow -} from './libproc-process-table' + type LibprocProcessRow, + type LibprocQuery +} from './libproc-addon' +import { runPsInProcess } from './libproc-process-table' import { parseCheapProcessTableRows, parseStrictProcessTableRows } from './process-table-snapshot' const TTYS004 = (16 << 24) | 4 // 2026-09-03T16:02:01Z, a single-digit day so lstart pads it. const START = Date.UTC(2026, 8, 3, 16, 2, 1) / 1000 +const BUDGET = { timeoutMs: 1000 } function row(overrides: Partial): LibprocProcessRow { return { @@ -29,6 +33,8 @@ function row(overrides: Partial): LibprocProcessRow { sessionLeader: false, startSec: START, comm: 'launchd', + command: '/sbin/launchd', + commandIncomplete: true, ...overrides } } @@ -42,7 +48,8 @@ const TABLE = [ tdev: TTYS004, flags: 0x2, comm: 'node', - command: 'node /usr/local/bin/claude --resume' + command: 'node /usr/local/bin/claude --resume', + commandIncomplete: false }), row({ pid: 4242, @@ -53,8 +60,10 @@ const TABLE = [ flags: 0x2, sessionLeader: true, comm: 'zsh', - command: '-zsh' + command: '-zsh', + commandIncomplete: false }), + // A pane's root login is root-owned and sits under the terminal host. row({ pid: 4200, ppid: 1, @@ -64,17 +73,35 @@ const TABLE = [ comm: 'login', command: '/usr/bin/login' }), - row({ pid: 4400, ppid: 4242, pgid: 4400, tpgid: 4300, status: 4, comm: 'vim', command: 'vim' }), - row({ pid: 4401, ppid: 4242, pgid: 4401, status: 5, comm: 'sh', command: null }) + row({ + pid: 4400, + ppid: 4242, + pgid: 4400, + tpgid: 4300, + status: 4, + comm: 'vim', + command: 'vim', + commandIncomplete: false + }), + row({ pid: 4401, ppid: 4242, pgid: 4401, status: 5, comm: 'sh', command: '' }), + row({}) ] +function tableFor(query: LibprocQuery, table = TABLE): LibprocProcessRow[] | null { + if (query.tty !== undefined && !/^(?:\/dev\/)?ttys004$/.test(query.tty)) { + return null + } + return table + .filter((entry) => !query.pids || query.pids.includes(entry.pid)) + .filter((entry) => query.tty === undefined || entry.tdev === TTYS004) + .map((entry) => + query.command ? entry : { ...entry, command: undefined, commandIncomplete: undefined } + ) +} + function installAddon(overrides: Partial = {}): LibprocAddon { const addon: LibprocAddon = { - processTable: vi.fn(async (includeCommand: boolean, pids?: readonly number[]) => - TABLE.filter((entry) => !pids || pids.includes(entry.pid)).map((entry) => - includeCommand ? entry : { ...entry, command: undefined } - ) - ), + readProcessTable: vi.fn(async (query: LibprocQuery) => tableFor(query)), processCwd: vi.fn(() => null), processPath: vi.fn(() => null), ...overrides @@ -85,19 +112,25 @@ function installAddon(overrides: Partial = {}): LibprocAddon { afterEach(() => { setLibprocAddonForTests(undefined) + runProcess.mockReset() + vi.useRealTimers() }) describe('runPsInProcess', () => { it('prints a whole-table capture the strict and cheap parsers read like ps output', async () => { installAddon() - const utc = { TZ: 'UTC0' } + const utc = { env: { TZ: 'UTC0', LC_ALL: 'C' }, timeoutMs: 1000 } const full = await runPsInProcess( ['-axo', 'pid=,ppid=,pgid=,tpgid=,stat=,tty=,lstart=,command='], utc ) expect(full?.code).toBe(0) + // ps sorts by terminal, then pid. expect(parseStrictProcessTableRows(full!.stdout)).toEqual([ + expect.objectContaining({ pid: 1, tty: '??', command: '/sbin/launchd' }), + expect.objectContaining({ pid: 4400, stat: 'T', tty: '??', command: 'vim' }), + expect.objectContaining({ pid: 4401, stat: 'Z', command: '' }), expect.objectContaining({ pid: 4200, stat: 'S', tty: 'ttys004', command: '/usr/bin/login' }), expect.objectContaining({ pid: 4242, stat: 'Ss', tty: 'ttys004', command: '-zsh' }), expect.objectContaining({ @@ -106,13 +139,13 @@ describe('runPsInProcess', () => { tty: 'ttys004', startTime: 'Thu Sep 3 16:02:01 2026', command: 'node /usr/local/bin/claude --resume' - }), - expect.objectContaining({ pid: 4400, stat: 'T', tty: '??', command: 'vim' }), - expect.objectContaining({ pid: 4401, stat: 'Z', command: '(sh)' }) + }) ]) + // Neither the root daemon nor the pane's root login is a pane descendant worth a setuid ps. + expect(runProcess).not.toHaveBeenCalled() const cheap = await runPsInProcess(['-axo', 'pid=,ppid=,pgid=,tpgid=,stat=,lstart='], utc) - expect(parseCheapProcessTableRows(cheap!.stdout)[2]).toEqual({ + expect(parseCheapProcessTableRows(cheap!.stdout).at(-1)).toEqual({ pid: 4300, ppid: 4242, pgid: 4300, @@ -125,34 +158,98 @@ describe('runPsInProcess', () => { it('selects by pid or terminal and exits 1 like ps when nothing matches', async () => { const addon = installAddon() - expect(await runPsInProcess(['-p', '4300', '-o', 'pid=,tdev='])).toMatchObject({ + expect(await runPsInProcess(['-p', '4300,4300', '-o', 'pid=,tdev='], BUDGET)).toMatchObject({ code: 0, stdout: '4300 16/4\n' }) - expect(addon.processTable).toHaveBeenLastCalledWith(false, [4300]) - expect(await runPsInProcess(['-p', '9999', '-o', 'stat=,lstart='])).toMatchObject({ + expect(addon.readProcessTable).toHaveBeenLastCalledWith({ command: false, pids: [4300] }) + expect(await runPsInProcess(['-p', '9999', '-o', 'stat=,lstart='], BUDGET)).toMatchObject({ code: 1, stdout: '' }) - const tty = await runPsInProcess(['-o', 'pid=,stat=', '-t', '/dev/ttys004']) + const tty = await runPsInProcess(['-o', 'pid=,stat=', '-t', '/dev/ttys004'], BUDGET) expect(tty?.stdout).toBe('4200 S\n4242 Ss\n4300 S+\n') + expect(addon.readProcessTable).toHaveBeenLastCalledWith({ command: false, tty: '/dev/ttys004' }) + expect(await runPsInProcess(['-o', 'pid=', '-t', 'ttys999'], BUDGET)).toMatchObject({ + code: 1, + timedOut: false + }) }) it('keeps the real ps for invocations it cannot reproduce or a failing addon', async () => { installAddon() - expect(await runPsInProcess(['-axo', 'pid=PROCESS_ID'])).toBeNull() - expect(await runPsInProcess(['-axo', 'pid=,uid='])).toBeNull() - expect(await runPsInProcess(['-p', '1', '-t', 'ttys004', '-o', 'pid='])).toBeNull() - expect(await runPsInProcess(['-axo', 'lstart='], { TZ: 'America/New_York' })).toBeNull() + expect(await runPsInProcess(['-axo', 'pid=PROCESS_ID'], BUDGET)).toBeNull() + expect(await runPsInProcess(['-axo', 'pid=,uid='], BUDGET)).toBeNull() + expect(await runPsInProcess(['-e', '-o', 'pid='], BUDGET)).toBeNull() + expect(await runPsInProcess(['-p', '1', '-t', 'ttys004', '-o', 'pid='], BUDGET)).toBeNull() + expect( + await runPsInProcess(['-axo', 'lstart='], { env: { TZ: 'America/New_York' }, timeoutMs: 1 }) + ).toBeNull() + expect( + await runPsInProcess(['-axo', 'lstart='], { env: { LC_ALL: 'de_DE.UTF-8' }, timeoutMs: 1 }) + ).toBeNull() installAddon({ - processTable: async () => { + readProcessTable: async () => { throw new Error('sysctl failed') } }) - expect(await runPsInProcess(['-axo', 'pid='])).toBeNull() + expect(await runPsInProcess(['-axo', 'pid='], BUDGET)).toBeNull() setLibprocAddonForTests(null) - expect(await runPsInProcess(['-axo', 'pid='])).toBeNull() + expect(await runPsInProcess(['-axo', 'pid='], BUDGET)).toBeNull() + }) + + it('times out each caller of a stalled shared read like a killed ps', async () => { + vi.useFakeTimers() + const addon = installAddon({ readProcessTable: vi.fn(() => new Promise(() => {})) }) + + const short = runPsInProcess(['-p', '4300', '-o', 'pid=,tpgid=,tty='], { timeoutMs: 125 }) + const long = runPsInProcess(['-p', '4300', '-o', 'pid=,tpgid=,tty='], { timeoutMs: 1000 }) + await vi.advanceTimersByTimeAsync(125) + await expect(short).resolves.toMatchObject({ code: null, timedOut: true, stdout: '' }) + await vi.advanceTimersByTimeAsync(875) + await expect(long).resolves.toMatchObject({ timedOut: true }) + expect(addon.readProcessTable).toHaveBeenCalledTimes(1) + }) + + it('asks ps once for argv only it can read, for another user’s process under a pane shell', async () => { + const sudo = row({ + pid: 4500, + ppid: 4242, + pgid: 4500, + tpgid: 4300, + tdev: TTYS004, + flags: 0x2, + comm: 'node', + command: '/usr/local/bin/node' + }) + installAddon({ + readProcessTable: vi.fn(async (query: LibprocQuery) => tableFor(query, [...TABLE, sudo])) + }) + runProcess.mockResolvedValue({ + code: 0, + signal: null, + stdout: ' 4500 node /usr/local/lib/claude-code/cli.js\n', + stderr: '', + timedOut: false + }) + const args = ['-o', 'pid=,ppid=,pgid=,tpgid=,stat=,command=', '-t', 'ttys004'] + const options = { env: { LC_ALL: 'en_US.UTF-8' }, timeoutMs: 1000 } + + for (let poll = 0; poll < 2; poll += 1) { + const result = await runPsInProcess(args, options) + expect(result?.stdout).toContain( + '4500 4242 4500 4300 S node /usr/local/lib/claude-code/cli.js' + ) + expect(result?.stdout).toContain('4200 1 4200 0 S /usr/bin/login') + } + expect(runProcess).toHaveBeenCalledTimes(1) + expect(runProcess).toHaveBeenCalledWith( + expect.objectContaining({ + program: '/bin/ps', + args: ['-ww', '-o', 'pid=,command=', '-p', '4500'] + }) + ) }) }) diff --git a/src/shared/libproc-process-table.ts b/src/shared/libproc-process-table.ts index 69f629ff450d..8a6cd7bed6bc 100644 --- a/src/shared/libproc-process-table.ts +++ b/src/shared/libproc-process-table.ts @@ -1,262 +1,186 @@ -import { createRequire } from 'node:module' import { nameDarwinTerminalDevices } from './darwin-terminal-names' +import { claimDarwinTerminalNaming } from './darwin-terminal-naming-slot' +import { + loadLibprocAddon, + type LibprocAddon, + type LibprocProcessRow, + type LibprocQuery +} from './libproc-addon' +import { completeCommands } from './libproc-argv-completion' +import { + compareLikePs, + formatDarwinDevice, + formatLibprocStat, + formatLstart, + parsePsQuery +} from './libproc-ps-format' -/** One `kinfo_proc` from node-pty's patched macOS addon (config/patches/node-pty@1.1.0.patch). */ -export type LibprocProcessRow = { - pid: number - ppid: number - pgid: number - tpgid: number - /** `e_tdev`; -1 (NODEV) without a controlling terminal. */ - tdev: number - /** `p_stat`: SIDL 1, SRUN 2, SSLEEP 3, SSTOP 4, SZOMB 5. */ - status: number - flags: number - sessionLeader: boolean - startSec: number - comm: string - /** Joined KERN_PROCARGS2 argv, else the executable path for another user's process; null when neither is readable. */ - command?: string | null -} - -export type LibprocAddon = { - /** Reads on a worker thread; argv for a whole table costs ~17ms of syscalls. */ - processTable: (includeCommand: boolean, pids?: readonly number[]) => Promise - processCwd: (pid: number) => string | null - processPath: (pid: number) => string | null -} - -const requireFromHere = createRequire(__filename) -let cachedAddon: LibprocAddon | null | undefined -let addonOverride: LibprocAddon | null | undefined - -function isLibprocAddon(native: unknown): native is LibprocAddon { - return ( - typeof native === 'object' && - native !== null && - 'processTable' in native && - typeof native.processTable === 'function' && - 'processCwd' in native && - typeof native.processCwd === 'function' && - 'processPath' in native && - typeof native.processPath === 'function' - ) -} - -/** The in-process reader, or null where ps/lsof must still run (non-macOS, an unpatched or unloadable node-pty). - * Vitest keeps the subprocess path so ps fixtures stay authoritative. */ -export function loadLibprocAddon(): LibprocAddon | null { - if (addonOverride !== undefined) { - return addonOverride - } - if (process.platform !== 'darwin' || process.env.VITEST === 'true') { - return null - } - if (cachedAddon !== undefined) { - return cachedAddon - } - try { - const utils: unknown = requireFromHere('node-pty/lib/utils') - const native: unknown = - typeof utils === 'object' && - utils !== null && - 'loadNativeModule' in utils && - typeof utils.loadNativeModule === 'function' - ? utils.loadNativeModule('pty')?.module - : null - cachedAddon = isLibprocAddon(native) ? native : null - } catch { - cachedAddon = null - } - if (cachedAddon === null) { - // A packaging regression would otherwise silently restore one setuid ps exec per poll (#31783). - console.warn('[process-table] node-pty lacks the libproc reader; falling back to ps and lsof') - } - return cachedAddon -} - -export function setLibprocAddonForTests(addon: LibprocAddon | null | undefined): void { - addonOverride = addon -} - -const SIDL = 1 -const SSTOP = 4 -const SZOMB = 5 -const P_CONTROLT = 0x2 -const P_WEXIT = 0x2000 -const NODEV = -1 - -/** ps's state letters, except running vs sleeping: that needs another task's thread states (ps is setuid for it), so live processes read `S`. */ -export function formatLibprocStat(row: LibprocProcessRow): string { - const state = - row.status === SZOMB ? 'Z' : row.status === SSTOP ? 'T' : row.status === SIDL ? 'R' : 'S' - return ( - state + - (row.flags & P_WEXIT && row.status !== SZOMB ? 'E' : '') + - (row.sessionLeader ? 's' : '') + - (row.flags & P_CONTROLT && row.pgid === row.tpgid ? '+' : '') - ) -} - -export function formatDarwinDevice(tdev: number): string | null { - return tdev === NODEV ? null : `${(tdev >>> 24) & 0xff}/${tdev & 0xffffff}` +/** Shaped like a process-host ProcessResult so call sites can substitute it for ps's. */ +export type LibprocPsResult = { + code: 0 | 1 | null + signal: NodeJS.Signals | null + stdout: string + stderr: '' + timedOut: boolean + outputTruncated: boolean } -const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] -const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] - -/** ps `lstart` (`%c` in the C and en_US locales): `Thu Sep 3 16:02:01 2026`. */ -export function formatLstart(startSec: number, utc: boolean): string { - const date = new Date(startSec * 1000) - const [weekday, month, day, hours, minutes, seconds, year] = utc - ? [ - date.getUTCDay(), - date.getUTCMonth(), - date.getUTCDate(), - date.getUTCHours(), - date.getUTCMinutes(), - date.getUTCSeconds(), - date.getUTCFullYear() - ] - : [ - date.getDay(), - date.getMonth(), - date.getDate(), - date.getHours(), - date.getMinutes(), - date.getSeconds(), - date.getFullYear() - ] - const two = (value: number): string => String(value).padStart(2, '0') - return `${WEEKDAYS[weekday]} ${MONTHS[month]} ${String(day).padStart(2, ' ')} ${two(hours)}:${two(minutes)}:${two(seconds)} ${year}` +export type InProcessPsOptions = { + /** The environment ps would run with; its TZ and locale shape lstart and command escaping. */ + env?: NodeJS.ProcessEnv + /** The caller's ps timeout: past it the read resolves timed out, as the killed ps would. */ + timeoutMs: number + maxOutputBytes?: number } -const COLUMN_ALIASES: Readonly> = { - pid: 'pid', - ppid: 'ppid', - pgid: 'pgid', - tpgid: 'tpgid', - stat: 'stat', - state: 'stat', - tdev: 'tdev', - tty: 'tty', - lstart: 'lstart', - command: 'command', - args: 'command' +const TIMED_OUT: LibprocPsResult = { + code: null, + signal: 'SIGTERM', + stdout: '', + stderr: '', + timedOut: true, + outputTruncated: false } -type Column = 'pid' | 'ppid' | 'pgid' | 'tpgid' | 'stat' | 'tdev' | 'tty' | 'lstart' | 'command' - -export type PsQuery = { - columns: Column[] - pids: number[] | null - tty: string | null +/** ps runs setlocale(LC_ALL, ""). */ +function localeCategory(env: NodeJS.ProcessEnv, category: 'LC_CTYPE' | 'LC_TIME'): string { + return env.LC_ALL || env[category] || env.LANG || 'C' } -/** The `ps` invocations Orca issues (`-axo`, `-e -o`, `-p`, `-t`, empty headers); anything else returns null and keeps the real ps. */ -export function parsePsQuery(args: readonly string[]): PsQuery | null { - const columns: Column[] = [] - let all = false - let pids: number[] | null = null - let tty: string | null = null - for (let index = 0; index < args.length; index += 1) { - const arg = args[index] - const value = (): string | undefined => args[++index] - if (arg === '-axo' || arg === '-o') { - all ||= arg === '-axo' - const spec = value() - if (spec === undefined) { - return null - } - for (const field of spec.split(',')) { - const match = /^([a-z]+)=$/.exec(field) - const column = match ? COLUMN_ALIASES[match[1]] : undefined - if (!column) { - return null - } - columns.push(column) - } - } else if (arg === '-ax' || arg === '-A' || arg === '-e') { - all = true - } else if (arg === '-ww') { - continue - } else if (arg === '-p') { - const list = value()?.split(',').map(Number) - if (!list || list.some((pid) => !Number.isSafeInteger(pid) || pid <= 0)) { - return null - } - pids = [...(pids ?? []), ...list] - } else if (arg === '-t') { - const name = value()?.replace(/^\/dev\//, '') - if (!name) { - return null - } - tty = name - } else { - return null - } +function lstartZoneIsUtc(env: NodeJS.ProcessEnv): boolean | null { + const zone = env.TZ + if (zone === undefined || zone === process.env.TZ) { + return false } - // ps unions selections; Orca never combines them, so keep the real ps for that. - const selections = Number(all) + Number(pids !== null) + Number(tty !== null) - return columns.length > 0 && selections === 1 ? { columns, pids, tty } : null + return /^(?:UTC|GMT)0?$/.test(zone) ? true : null } -/** Shaped like a process-host ProcessResult so call sites can substitute it for ps's. */ -export type LibprocPsResult = { - code: 0 | 1 - signal: null - stdout: string - stderr: '' - timedOut: false - outputTruncated: false -} +const DEADLINE_PASSED = Symbol('deadline') -function sanitizeCommand(command: string): string { - return command.replace(/[\r\n\t]/g, ' ') +async function beforeDeadline( + pending: Promise, + deadline: number +): Promise { + let timer: ReturnType | undefined + try { + return await Promise.race([ + pending, + new Promise((resolve) => { + timer = setTimeout(() => resolve(DEADLINE_PASSED), Math.max(0, deadline - Date.now())) + }) + ]) + } finally { + clearTimeout(timer) + } } -function readCommand(row: LibprocProcessRow): string { - return sanitizeCommand(row.command?.trim() ? row.command : `(${row.comm})`) -} +// Identical reads share one worker; each caller still races its own deadline, so a stalled pool times them all out. +const nativeReadsInFlight = new Map>() +// Workers queued behind a saturated libuv pool would otherwise pile up one per poll. +const MAX_NATIVE_READS_IN_FLIGHT = 8 -function lstartZoneIsUtc(env: NodeJS.ProcessEnv | undefined): boolean | null { - const zone = env?.TZ - if (zone === undefined || zone === process.env.TZ) { - return false +function readNativeTable( + addon: LibprocAddon, + query: LibprocQuery +): Promise | null { + const key = JSON.stringify(query) + const shared = nativeReadsInFlight.get(key) + if (shared) { + return shared } - return /^(?:UTC|GMT)0?$/.test(zone) ? true : null + if (nativeReadsInFlight.size >= MAX_NATIVE_READS_IN_FLIGHT) { + return null + } + const pending = addon.readProcessTable(query) + nativeReadsInFlight.set(key, pending) + const release = (): void => { + if (nativeReadsInFlight.get(key) === pending) { + nativeReadsInFlight.delete(key) + } + } + pending.then(release, release) + return pending } /** ps output for `args`, read in process; null when the addon or the invocation is unsupported so callers run ps. */ export async function runPsInProcess( args: readonly string[], - env?: NodeJS.ProcessEnv + options: InProcessPsOptions ): Promise { const addon = loadLibprocAddon() const query = addon ? parsePsQuery(args) : null + if (!addon || !query) { + return null + } + const deadline = Date.now() + options.timeoutMs + const env = options.env ?? process.env const utc = lstartZoneIsUtc(env) - if (!addon || !query || utc === null) { + const needsLstart = query.columns.includes('lstart') + // lstart is `%c`: only the C and en_US forms are reproduced. + if ( + needsLstart && + (utc === null || !/^(?:C|POSIX|en_US(?:\..*)?)$/.test(localeCategory(env, 'LC_TIME'))) + ) { return null } - const needsTty = query.columns.includes('tty') || query.tty !== null - let rows: LibprocProcessRow[] + const includeCommand = query.columns.includes('command') + const ctype = localeCategory(env, 'LC_CTYPE') + const nativeQuery: LibprocQuery = { + command: includeCommand, + ...(query.pids ? { pids: query.pids } : {}), + ...(query.tty !== null ? { tty: query.tty } : {}), + ...(includeCommand ? { ctype } : {}) + } + let rows: LibprocProcessRow[] | null let ttyNames: ReadonlyMap = new Map() try { - rows = await addon.processTable(query.columns.includes('command'), query.pids ?? undefined) - if (needsTty) { + const pending = readNativeTable(addon, nativeQuery) + if (!pending) { + return null + } + const read = await beforeDeadline(pending, deadline) + if (read === DEADLINE_PASSED) { + return TIMED_OUT + } + // Shared reads hand every caller the same rows; command completion writes per caller. + rows = read?.map((row) => ({ ...row })) ?? null + if (rows && query.columns.includes('tty')) { const devices = new Set( rows.map((row) => formatDarwinDevice(row.tdev)).filter((device) => device !== null) ) - ttyNames = await nameDarwinTerminalDevices(devices) + if (devices.size > 0) { + const controller = new AbortController() + const naming = claimDarwinTerminalNaming(() => + nameDarwinTerminalDevices(devices, undefined, controller.signal) + ) + // Another naming pass is still draining the pool: run ps, as the capture's guard always has. + if (!naming) { + return null + } + const named = await beforeDeadline(naming, deadline) + if (named === DEADLINE_PASSED) { + controller.abort() + return TIMED_OUT + } + ttyNames = named + } + } + if (rows && includeCommand) { + await completeCommands(rows, query.pids !== null, ctype, env, deadline) } } catch { return null } + if (Date.now() > deadline) { + return TIMED_OUT + } + // ps exits 1 when -t names no terminal or a -p/-t selection matched nothing. + if (rows === null) { + return { ...TIMED_OUT, code: 1, signal: null, timedOut: false } + } const ttyOf = (row: LibprocProcessRow): string => ttyNames.get(formatDarwinDevice(row.tdev) ?? '') ?? '??' - const selected = (query.tty === null ? rows : rows.filter((row) => ttyOf(row) === query.tty)) - .slice() - .sort((a, b) => a.pid - b.pid) + const selected = rows.sort(compareLikePs) const lines = selected.map((row) => query.columns .map((column) => { @@ -268,9 +192,9 @@ export async function runPsInProcess( case 'tty': return ttyOf(row) case 'lstart': - return formatLstart(row.startSec, utc) + return formatLstart(row.startSec, utc === true) case 'command': - return readCommand(row) + return row.command ?? `(${row.comm})` case 'pid': case 'ppid': case 'pgid': @@ -280,39 +204,41 @@ export async function runPsInProcess( }) .join(' ') ) - // ps exits 1 when a -p/-t selection matched nothing. + let stdout = lines.length > 0 ? `${lines.join('\n')}\n` : '' + const maxBytes = options.maxOutputBytes + const outputTruncated = maxBytes !== undefined && Buffer.byteLength(stdout, 'utf8') > maxBytes + if (outputTruncated) { + stdout = Buffer.from(stdout, 'utf8').subarray(0, maxBytes).toString('utf8') + } return { code: query.pids === null && query.tty === null ? 0 : selected.length > 0 ? 0 : 1, signal: null, - stdout: lines.length > 0 ? `${lines.join('\n')}\n` : '', + stdout, stderr: '', timedOut: false, - outputTruncated: false + outputTruncated } } -/** PROC_PIDVNODEPATHINFO cwd, or undefined when only lsof can answer. */ -export function readLibprocProcessCwd(pid: number): string | null | undefined { - const addon = loadLibprocAddon() - if (!addon) { - return undefined - } - try { - return addon.processCwd(pid) - } catch { - return undefined +/** execFile-shaped: rejects on a nonzero exit or timeout like a failed ps child; null when ps must run. */ +export async function readPsStdoutInProcess( + args: readonly string[], + options: InProcessPsOptions +): Promise { + const result = await runPsInProcess(args, options) + if (!result) { + return null } -} - -/** proc_pidpath executable, or undefined when only lsof can answer. */ -export function readLibprocProcessPath(pid: number): string | null | undefined { - const addon = loadLibprocAddon() - if (!addon) { - return undefined + if (result.timedOut || result.code !== 0) { + throw Object.assign( + new Error(`Command failed: ps ${args.join(' ')}${result.timedOut ? ' (timed out)' : ''}`), + { code: result.code, killed: result.timedOut, signal: result.signal } + ) } - try { - return addon.processPath(pid) - } catch { - return undefined + if (result.outputTruncated) { + throw Object.assign(new Error(`ps ${args.join(' ')} exceeded maxBuffer`), { + code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' + }) } + return result.stdout } diff --git a/src/shared/libproc-ps-format.ts b/src/shared/libproc-ps-format.ts new file mode 100644 index 000000000000..a3da57b7cd12 --- /dev/null +++ b/src/shared/libproc-ps-format.ts @@ -0,0 +1,139 @@ +import type { LibprocProcessRow } from './libproc-addon' + +const SIDL = 1 +const SSTOP = 4 +const SZOMB = 5 +const P_CONTROLT = 0x2 +const P_PPWAIT = 0x10 +const P_SYSTEM = 0x200 +const P_TRACED = 0x800 +const P_WEXIT = 0x2000 +export const NODEV = -1 + +/** ps's state letters, except running vs sleeping: that needs another task's thread states (ps is setuid for it), so live processes read `S`. */ +export function formatLibprocStat(row: LibprocProcessRow): string { + const state = + row.status === SZOMB ? 'Z' : row.status === SSTOP ? 'T' : row.status === SIDL ? 'R' : 'S' + const nice = row.nice ?? 0 + // adv_cmds ps/print.c state(). + return ( + state + + (nice < 0 ? '<' : nice > 0 ? 'N' : '') + + (row.flags & P_TRACED ? 'X' : '') + + (row.flags & P_WEXIT && row.status !== SZOMB ? 'E' : '') + + (row.flags & P_PPWAIT ? 'V' : '') + + (row.flags & P_SYSTEM ? 'L' : '') + + (row.sessionLeader ? 's' : '') + + (row.flags & P_CONTROLT && row.pgid === row.tpgid ? '+' : '') + ) +} + +export function formatDarwinDevice(tdev: number): string | null { + return tdev === NODEV ? null : `${(tdev >>> 24) & 0xff}/${tdev & 0xffffff}` +} + +const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] + +/** ps `lstart` (`%c` in the C and en_US locales): `Thu Sep 3 16:02:01 2026`. */ +export function formatLstart(startSec: number, utc: boolean): string { + const date = new Date(startSec * 1000) + const [weekday, month, day, hours, minutes, seconds, year] = utc + ? [ + date.getUTCDay(), + date.getUTCMonth(), + date.getUTCDate(), + date.getUTCHours(), + date.getUTCMinutes(), + date.getUTCSeconds(), + date.getUTCFullYear() + ] + : [ + date.getDay(), + date.getMonth(), + date.getDate(), + date.getHours(), + date.getMinutes(), + date.getSeconds(), + date.getFullYear() + ] + const two = (value: number): string => String(value).padStart(2, '0') + return `${WEEKDAYS[weekday]} ${MONTHS[month]} ${String(day).padStart(2, ' ')} ${two(hours)}:${two(minutes)}:${two(seconds)} ${year}` +} + +const COLUMN_ALIASES: Readonly> = { + pid: 'pid', + ppid: 'ppid', + pgid: 'pgid', + tpgid: 'tpgid', + stat: 'stat', + state: 'stat', + tdev: 'tdev', + tty: 'tty', + lstart: 'lstart', + command: 'command', + args: 'command' +} + +type Column = 'pid' | 'ppid' | 'pgid' | 'tpgid' | 'stat' | 'tdev' | 'tty' | 'lstart' | 'command' + +export type PsQuery = { + columns: Column[] + pids: number[] | null + tty: string | null +} + +/** The `ps` invocations Orca issues (`-axo`, `-p`, `-t`, empty headers); anything else returns null and keeps the real ps. */ +export function parsePsQuery(args: readonly string[]): PsQuery | null { + const columns: Column[] = [] + let all = false + let pids: number[] | null = null + let tty: string | null = null + for (let index = 0; index < args.length; index += 1) { + const arg = args[index] + const value = (): string | undefined => args[++index] + if (arg === '-axo' || arg === '-o') { + all ||= arg === '-axo' + const spec = value() + if (spec === undefined) { + return null + } + for (const field of spec.split(',')) { + const match = /^([a-z]+)=$/.exec(field) + const column = match ? COLUMN_ALIASES[match[1]] : undefined + if (!column) { + return null + } + columns.push(column) + } + } else if (arg === '-ax' || arg === '-A') { + all = true + } else if (arg === '-ww') { + continue + } else if (arg === '-p') { + const list = value()?.split(',').map(Number) + if (!list || list.some((pid) => !Number.isSafeInteger(pid) || pid <= 0 || pid > 0x7fffffff)) { + return null + } + // ps keeps each matching process once however often -p names it. + pids = [...new Set([...(pids ?? []), ...list])] + } else if (arg === '-t') { + const name = value() + // ps -t also takes lists; Orca names one terminal. + if (!name || tty !== null || /[\s,]/.test(name)) { + return null + } + tty = name + } else { + return null + } + } + // ps unions selections; Orca never combines them, so keep the real ps for that. + const selections = Number(all) + Number(pids !== null) + Number(tty !== null) + return columns.length > 0 && selections === 1 ? { columns, pids, tty } : null +} + +/** ps's pscomp(): terminal, then pid (int subtraction, as C wraps it). */ +export function compareLikePs(a: LibprocProcessRow, b: LibprocProcessRow): number { + return (a.tdev - b.tdev) | 0 || a.pid - b.pid +} diff --git a/src/shared/process-table-snapshot-reader.ts b/src/shared/process-table-snapshot-reader.ts index 1819d8687991..1339f44b2eb4 100644 --- a/src/shared/process-table-snapshot-reader.ts +++ b/src/shared/process-table-snapshot-reader.ts @@ -2,7 +2,7 @@ import { execFile as execFileCb } from 'node:child_process' import { readFile } from 'node:fs/promises' import { promisify } from 'node:util' import { psLocaleEnvironment } from './ps-locale-environment' -import { runPsInProcess } from './libproc-process-table' +import { readPsStdoutInProcess } from './libproc-process-table' import { captureDarwinProcessTable, resetDarwinProcessTableCaptureForTests @@ -244,18 +244,17 @@ async function readLinuxProcessStartTimes( } async function captureProcessTable(args: readonly string[], timeout = PS_TIMEOUT_MS) { - const inProcess = await runPsInProcess(args, psLocaleEnvironment()) - if (inProcess) { - return assertWholeCapture(inProcess.stdout) - } - let stdout: string + const env = psLocaleEnvironment() + let stdout = await readPsStdoutInProcess(args, { env, timeoutMs: timeout }) try { - ;({ stdout } = await execFile('ps', [...args], { - encoding: 'utf-8', - env: psLocaleEnvironment(), - timeout, - maxBuffer: PS_MAX_BUFFER_BYTES - })) + stdout ??= ( + await execFile('ps', [...args], { + encoding: 'utf-8', + env, + timeout, + maxBuffer: PS_MAX_BUFFER_BYTES + }) + ).stdout } catch (error) { // A ceiling hit is truncation, not absence: name it in the domain vocabulary. if ((error as { code?: unknown } | null)?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') { diff --git a/src/shared/shell-process-readiness.ts b/src/shared/shell-process-readiness.ts index 7e2833869f0e..d6b2518c599d 100644 --- a/src/shared/shell-process-readiness.ts +++ b/src/shared/shell-process-readiness.ts @@ -4,7 +4,8 @@ import { access, readlink, realpath, stat } from 'node:fs/promises' import { delimiter, isAbsolute, resolve } from 'node:path' import { promisify } from 'node:util' import { LSOF_NONBLOCKING_ARGS } from './lsof-nonblocking-args' -import { readLibprocProcessPath, runPsInProcess } from './libproc-process-table' +import { readLibprocProcessPath } from './libproc-addon' +import { readPsStdoutInProcess } from './libproc-process-table' import { PS_MAX_BUFFER_BYTES } from './process-table-snapshot' const execFile = promisify(execFileCallback) @@ -48,12 +49,12 @@ async function readExecutablePath(pid: number): Promise { /** Rejects like execFile when ps exits nonzero, so callers keep their error paths. */ async function readPs(args: string[]): Promise { - const inProcess = await runPsInProcess(args) - if (inProcess) { - if (inProcess.code !== 0) { - throw new Error(`ps ${args.join(' ')} matched no process`) - } - return inProcess.stdout + const inProcess = await readPsStdoutInProcess(args, { + timeoutMs: PROCESS_READINESS_TIMEOUT_MS, + maxOutputBytes: PS_MAX_BUFFER_BYTES + }) + if (inProcess !== null) { + return inProcess } const { stdout } = await execFile('ps', args, { encoding: 'utf8', diff --git a/src/shared/tmux-host-attachment-probe.ts b/src/shared/tmux-host-attachment-probe.ts index 557265a6a7c6..b01e18751c7d 100644 --- a/src/shared/tmux-host-attachment-probe.ts +++ b/src/shared/tmux-host-attachment-probe.ts @@ -26,7 +26,7 @@ async function readSelectedRows(pids: readonly number[]): Promise= 65536) { throw new Error('tmux_process_capture_unverifiable') From 53f0dfb7a35898175b4b0d3b7fe8e504b3eb6cc5 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 02:35:49 -0700 Subject: [PATCH 04/13] test(terminal): diff the real libproc addon against /bin/ps on macOS (#31783) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Spawns a pty holder whose argv carries a newline, tab, invalid UTF-8 and é, then compares Orca's ps invocations column by column: pid/ppid/pgid/tpgid/ lstart/tdev/tty exactly, commands for the user's own processes, and stat modulo running/idle (thread state needs setuid ps). Rows are compared only when two in-process reads around the ps run agree, so churn cannot flake it. --- .../libproc-process-table-real-ps.test.ts | 164 ++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 src/shared/libproc-process-table-real-ps.test.ts diff --git a/src/shared/libproc-process-table-real-ps.test.ts b/src/shared/libproc-process-table-real-ps.test.ts new file mode 100644 index 000000000000..d1fca9bd883c --- /dev/null +++ b/src/shared/libproc-process-table-real-ps.test.ts @@ -0,0 +1,164 @@ +import { type ChildProcess, execFileSync, spawn } from 'node:child_process' +import { createRequire } from 'node:module' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { setLibprocAddonForTests, type LibprocAddon } from './libproc-addon' +import { runPsInProcess } from './libproc-process-table' +import { CHEAP_PS_ARGS, PS_ARGS, SHELL_FOREGROUND_PS_ARGS } from './process-table-snapshot' + +const C_UTC = { ...process.env, LC_ALL: 'C', LANG: 'C', TZ: 'UTC0' } +const UTF8 = { ...process.env, LC_ALL: 'en_US.UTF-8' } +// Argv ps must vis-encode: newline, tab, invalid UTF-8, a lone continuation byte, and UTF-8 é. +const HOLDER_SCRIPT = + 'exec {"/usr/bin/perl"} "perl", "-e", "sleep 30", "a\\nb", "c\\td", "bad\\xff\\xfeutf", "\\x80", "\\xc3\\xa9"' + +function loadRealAddon(): LibprocAddon { + const utils = createRequire(__filename)('node-pty/lib/utils') + return utils.loadNativeModule('pty').module +} + +function columnsOf(args: readonly string[]): string[] { + const spec = args[args.findIndex((arg) => arg === '-o' || arg === '-axo') + 1] + return spec.split(',').map((field) => field.replace('=', '')) +} + +const LSTART = String.raw`\S+\s+\S+\s+\d+\s+\d+:\d+:\d+\s+\d+` + +/** Rows keyed by pid; `stat` folds running/idle/uninterruptible into sleeping since thread states need setuid ps. */ +function rowsOf(stdout: string, columns: readonly string[]): Map { + const pattern = new RegExp( + `^\\s*${columns + .map((column) => + column === 'lstart' ? `(${LSTART})` : column === 'command' ? '(.*)' : '(\\S+)' + ) + .join('\\s+')}\\s*$` + ) + const rows = new Map() + for (const line of stdout.split('\n').filter((entry) => entry.trim())) { + const match = pattern.exec(line) + expect(match, line).not.toBeNull() + const fields = match! + .slice(1) + .map((field, index) => + columns[index] === 'stat' + ? field.replace(/^[RSIU?]/, 'S') + : columns[index] === 'lstart' + ? field.replace(/\s+/g, ' ') + : field + ) + rows.set(Number(fields[columns.indexOf('pid')]), fields) + } + return rows +} + +async function inProcess(args: readonly string[], env: NodeJS.ProcessEnv): Promise { + const result = await runPsInProcess(args, { env, timeoutMs: 5000 }) + expect(result?.timedOut).toBe(false) + return result!.stdout +} + +describe.runIf(process.platform === 'darwin')( + 'runPsInProcess with the real addon against /bin/ps', + () => { + let holder: ChildProcess | undefined + let holderPid = 0 + let holderTty = '' + let ownPids = new Set() + + beforeAll(async () => { + setLibprocAddonForTests(loadRealAddon()) + // `script` gives the holder a real pty, so a headless host still has a terminal to select. + holder = spawn('script', ['-q', '/dev/null', 'perl', '-e', HOLDER_SCRIPT], { + stdio: 'ignore' + }) + await vi.waitFor( + () => { + holderPid = Number( + execFileSync('pgrep', ['-P', String(holder!.pid)], { encoding: 'utf8' }) + ) + const command = execFileSync('ps', ['-o', 'command=', '-p', String(holderPid)], { + encoding: 'utf8' + }) + expect(command).toContain('sleep 30 a') + holderTty = execFileSync('ps', ['-o', 'tty=', '-p', String(holderPid)], { + encoding: 'utf8' + }).trim() + }, + { timeout: 5000, interval: 20 } + ) + const uid = String(process.getuid?.()) + ownPids = new Set( + execFileSync('ps', ['-axo', 'pid=,uid='], { encoding: 'utf8' }) + .split('\n') + .map((line) => line.trim().split(/\s+/)) + .filter(([, owner]) => owner === uid) + .map(([pid]) => Number(pid)) + ) + }) + afterAll(() => { + holder?.kill() + setLibprocAddonForTests(undefined) + }) + + /** Read ours, ps, ours: a row is compared only when both of ours agree, so processes changing mid-read cannot flake. */ + async function mismatches(args: readonly string[], env: NodeJS.ProcessEnv): Promise { + const columns = columnsOf(args) + const before = rowsOf(await inProcess(args, env), columns) + const ps = rowsOf(execFileSync('/bin/ps', [...args], { encoding: 'utf8', env }), columns) + const after = rowsOf(await inProcess(args, env), columns) + const commandAt = columns.indexOf('command') + const failures: string[] = [] + for (const [pid, ours] of before) { + const real = ps.get(pid) + if (!real || JSON.stringify(after.get(pid)) !== JSON.stringify(ours)) { + continue + } + // Another user's argv needs setuid ps; only pane descendants get that fallback. + const comparable = + commandAt === -1 || ownPids.has(pid) + ? ours + : ours.filter((_, index) => index !== commandAt) + const expected = + commandAt === -1 || ownPids.has(pid) + ? real + : real.filter((_, index) => index !== commandAt) + if (JSON.stringify(comparable) !== JSON.stringify(expected)) { + failures.push(`${pid}: ${JSON.stringify(comparable)} != ${JSON.stringify(expected)}`) + } + } + return failures + } + + it('finds the holder on its terminal', () => { + expect(holderTty).toMatch(/^ttys\d+$/) + }) + + it.each([ + ['full snapshot', PS_ARGS, UTF8], + ['full snapshot (tdev)', ['-axo', PS_ARGS[1].replace('tty=', 'tdev=')], UTF8], + ['cheap snapshot', CHEAP_PS_ARGS, UTF8], + ['shell foreground', SHELL_FOREGROUND_PS_ARGS, UTF8], + ['descendant termination', ['-axo', 'pid=,ppid=,pgid=,tpgid=,lstart='], C_UTC] + ])('matches ps for the %s table', async (_name, args, env) => { + expect(await mismatches(args, env)).toEqual([]) + }) + + it('matches ps for pid and terminal selections, escaping argv in each locale', async () => { + const pids = `${holderPid},${holderPid},${process.pid},1` + for (const env of [UTF8, C_UTC]) { + expect(await mismatches(['-p', pids, '-o', PS_ARGS[1]], env)).toEqual([]) + expect(await mismatches(['-p', pids, '-o', 'pid=,tpgid=,tty='], env)).toEqual([]) + expect( + await mismatches(['-o', 'pid=,ppid=,pgid=,tpgid=,stat=,command=', '-t', holderTty], env) + ).toEqual([]) + const holder = await inProcess(['-o', 'command=', '-p', `${holderPid},${holderPid}`], env) + expect(holder).toBe( + execFileSync('/bin/ps', ['-o', 'command=', '-p', String(holderPid)], { + encoding: 'utf8', + env + }) + ) + expect(holder).toContain(String.raw`a\012b c\011d`) + } + }) + } +) From d9a47933018d3385a75b8d60c6e56de46c0ed2ca Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 03:44:56 -0700 Subject: [PATCH 05/13] fix(terminal): never serve a native process table read begun before the request (#31783) A timed-out read stayed shareable, so a later descendant capture could join an earlier poll's abandoned worker and take its rows as fresh; a descendant that exited meanwhile could have its reused pid SIGTERMed. The addon now reports when its worker actually began reading (startedAtMs), and runPsInProcess refuses a shared read that began before its own request and reads again, so every consumer that signals from rows (descendant teardown, foreground-group signalling, identity probes) only sees rows scanned after its stamp. Regression: pty-descendant-termination-libproc. Also from review: - argv recovered with setuid ps is keyed by pid, start time to the microsecond, comm and executable path (exec changes the latter two) with a 10 min TTL and 512-entry bound. - Recovery covers a sudo use_pty tree: the unreadable chain must start on the terminal of the user's own readable process, so the root shell and agent on sudo's own pty qualify while root daemons, GUI helpers and a pane's root login (own pty, under a terminal-less or tty-inheriting host) do not. - Concurrent tty= readers wait out the single naming pass, and readers past the 8-read cap queue behind one, within their deadlines, instead of bursting /bin/ps at startup restore (24 panes polled at once: 0 ps). - darwin-terminal-naming-slot.ts is now darwin-terminal-naming-single-flight.ts. --- config/patches/node-pty@1.1.0.patch | 66 ++++++----- pnpm-lock.yaml | 6 +- ...pty-descendant-termination-libproc.test.ts | 67 +++++++++++ src/main/pty-descendant-termination.ts | 1 + src/shared/darwin-process-table-capture.ts | 2 +- ...> darwin-terminal-naming-single-flight.ts} | 8 ++ src/shared/libproc-addon.ts | 10 +- src/shared/libproc-argv-completion.ts | 92 ++++++++------- src/shared/libproc-process-table.test.ts | 107 ++++++++++++++++- src/shared/libproc-process-table.ts | 108 +++++++++++++----- 10 files changed, 363 insertions(+), 104 deletions(-) create mode 100644 src/main/pty-descendant-termination-libproc.test.ts rename src/shared/{darwin-terminal-naming-slot.ts => darwin-terminal-naming-single-flight.ts} (76%) diff --git a/config/patches/node-pty@1.1.0.patch b/config/patches/node-pty@1.1.0.patch index 00fe9883eb84..c9ab81362f0b 100644 --- a/config/patches/node-pty@1.1.0.patch +++ b/config/patches/node-pty@1.1.0.patch @@ -297,7 +297,7 @@ index 181ccabbbe9c4948a9725fb1db907a68e9de01fc..67f31facf85562b67adbfbd04ce28ddd process.send!({ consoleProcessList }); process.exit(0); diff --git a/src/unix/pty.cc b/src/unix/pty.cc -index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af387224f243 100644 +index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b4d1e928e 100644 --- a/src/unix/pty.cc +++ b/src/unix/pty.cc @@ -23,8 +23,11 @@ @@ -352,17 +352,18 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 /* Some platforms name VWERASE and VDISCARD differently */ #if !defined(VWERASE) && defined(VWERSE) #define VWERASE VWERSE -@@ -67,6 +103,9 @@ +@@ -67,6 +103,10 @@ #include #include #include ++#include +#include +#include +#include #endif /* NSIG - macro for highest signal + 1, should be defined */ -@@ -228,6 +267,9 @@ Napi::Value PtyGetProc(const Napi::CallbackInfo& info); +@@ -228,6 +268,9 @@ Napi::Value PtyGetProc(const Napi::CallbackInfo& info); static int pty_nonblock(int); @@ -372,7 +373,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 #if defined(__APPLE__) static char * pty_getproc(int); -@@ -237,13 +279,23 @@ pty_getproc(int, char *); +@@ -237,13 +280,23 @@ pty_getproc(int, char *); #endif #if defined(__APPLE__) || defined(__OpenBSD__) @@ -397,7 +398,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 #endif struct DelBuf { -@@ -345,8 +397,8 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { +@@ -345,8 +398,8 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { term->c_cc[VSTATUS] = 20; #endif @@ -408,7 +409,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 // helperPath std::string helper_path = info[9].As(); -@@ -367,14 +419,18 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { +@@ -367,14 +420,18 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { argv[i + 3] = strdup(arg.c_str()); } @@ -431,7 +432,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 #else int argc = argv_.Length(); int argl = argc + 2; -@@ -445,6 +501,9 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { +@@ -445,6 +502,9 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { if (pty_nonblock(master) == -1) { throw Napi::Error::New(napiEnv, "Could not set master fd to nonblocking."); } @@ -441,7 +442,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 } #endif -@@ -586,6 +645,23 @@ pty_nonblock(int fd) { +@@ -586,6 +646,23 @@ pty_nonblock(int fd) { return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } @@ -465,7 +466,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 /** * pty_getproc * Taken from tmux. -@@ -684,15 +760,73 @@ pty_getproc(int fd, char *tty) { +@@ -684,15 +761,73 @@ pty_getproc(int fd, char *tty) { #endif #if defined(__APPLE__) @@ -541,25 +542,25 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 for (; count < 3; count++) { low_fds[count] = posix_openpt(O_RDWR); -@@ -706,81 +840,460 @@ pty_posix_spawn(char** argv, char** env, +@@ -706,81 +841,469 @@ pty_posix_spawn(char** argv, char** env, POSIX_SPAWN_SETSID; *master = posix_openpt(O_RDWR); if (*master == -1) { - return; + pty_set_spawn_error(err, "posix_openpt", errno); ++ goto done; ++ } ++ ++ res = grantpt(*master); ++ if (res == -1) { ++ pty_set_spawn_error(err, "grantpt", errno); + goto done; } - int res = grantpt(*master) || unlockpt(*master); -+ res = grantpt(*master); ++ res = unlockpt(*master); if (res == -1) { - return; -+ pty_set_spawn_error(err, "grantpt", errno); -+ goto done; -+ } -+ -+ res = unlockpt(*master); -+ if (res == -1) { + pty_set_spawn_error(err, "unlockpt", errno); + goto done; } @@ -735,7 +736,9 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 + out->assign(encoded.data(), length); + return true; +} -+ + +- for (; count > 0; count--) { +- close(low_fds[count]); +static bool +orca_read_kinfo(int what, int flag, std::vector* procs) { + int mib[4] = { CTL_KERN, KERN_PROC, what, flag }; @@ -886,9 +889,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 + } + return 0; +} - -- for (; count > 0; count--) { -- close(low_fds[count]); ++ +static Napi::Array +orca_process_rows_to_js(Napi::Env env, bool include_command, const std::vector& rows) { + Napi::Array result = Napi::Array::New(env, rows.size()); @@ -906,17 +907,18 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 + row.Set("nice", Napi::Number::New(env, proc.kp_proc.p_nice)); + row.Set("sessionLeader", Napi::Boolean::New(env, (proc.kp_eproc.e_flag & EPROC_SLEADER) != 0)); + row.Set("startSec", Napi::Number::New(env, (double)proc.kp_proc.p_starttime.tv_sec)); ++ row.Set("startUsec", Napi::Number::New(env, (double)proc.kp_proc.p_starttime.tv_usec)); + row.Set("comm", Napi::String::New(env, proc.kp_proc.p_comm, strnlen(proc.kp_proc.p_comm, sizeof(proc.kp_proc.p_comm)))); + if (include_command) { + row.Set("command", Napi::String::New(env, entry.command)); + row.Set("commandIncomplete", Napi::Boolean::New(env, entry.command_incomplete)); + } + result.Set(index++, row); - } ++ } + return result; +} + -+// readProcessTable({ command, pids?, tty?, ctype? }): pids and tty are exclusive selections, as Orca issues them. ++// readProcessTable({ command, pids?, tty?, ctype? }) -> { startedAtMs, rows | null }: pids and tty are exclusive selections, as Orca issues them. +static orca_process_query +orca_read_process_query(const Napi::CallbackInfo& info) { + Napi::Env env(info.Env()); @@ -941,7 +943,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 + } + } + query.select_pids = true; -+ } + } + Napi::Value tty = options.Get("tty"); + if (tty.IsString()) { + if (query.select_pids) { @@ -963,11 +965,15 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 + : Napi::AsyncWorker(env), + deferred_(Napi::Promise::Deferred::New(env)), + query_(std::move(query)), -+ status_(-1) {} ++ status_(-1), ++ started_at_ms_(0) {} + + Napi::Promise Promise() { return deferred_.Promise(); } + + void Execute() override { ++ // Callers must not mistake a read queued before their request for a fresh one. ++ struct timeval now; ++ started_at_ms_ = gettimeofday(&now, NULL) == 0 ? (double)now.tv_sec * 1000.0 + (double)now.tv_usec / 1000.0 : 0; + status_ = orca_gather_process_table(query_, &rows_); + if (status_ < 0) { + SetError("orca: process table sysctl failed"); @@ -976,9 +982,12 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 + + void OnOK() override { + Napi::Env env = Env(); ++ Napi::Object result = Napi::Object::New(env); ++ result.Set("startedAtMs", Napi::Number::New(env, started_at_ms_)); + // ps exits 1 without output when -t names no terminal. -+ deferred_.Resolve(status_ == 1 ? env.Null() -+ : Napi::Value(orca_process_rows_to_js(env, query_.include_command, rows_))); ++ result.Set("rows", status_ == 1 ? env.Null() ++ : Napi::Value(orca_process_rows_to_js(env, query_.include_command, rows_))); ++ deferred_.Resolve(result); + } + + void OnError(const Napi::Error& error) override { @@ -989,6 +998,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 + Napi::Promise::Deferred deferred_; + orca_process_query query_; + int status_; ++ double started_at_ms_; + std::vector rows_; +}; + @@ -1026,7 +1036,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..e2073f38a38b918a731f8c7b2258af38 } #endif -@@ -793,6 +1306,11 @@ Napi::Object init(Napi::Env env, Napi::Object exports) { +@@ -793,6 +1316,11 @@ Napi::Object init(Napi::Env env, Napi::Object exports) { exports.Set("open", Napi::Function::New(env, PtyOpen)); exports.Set("resize", Napi::Function::New(env, PtyResize)); exports.Set("process", Napi::Function::New(env, PtyGetProc)); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4caccb642ebf..2cdc42fff226 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -184,7 +184,7 @@ patchedDependencies: i18next-cli@1.74.2: 2ee32eef742615cd133e1a6940f027deb3723a8430bb7953bba3a6769b0aac47 lint-staged@16.4.0: 7333b3837f80a7fbd045964db6d76ba4fc118e49134bdbabb00585b6b7b60673 monaco-editor@0.55.1: 53b71f7d8a7c00b76ffdb73ce83d18e31692f193f5fafa6a390e48f5b3fdd636 - node-pty@1.1.0: 47ebb5c7a5c70106f439576efaf8335f147fe78cd54357cba11d6fd5b1bc975e + node-pty@1.1.0: f1d7035aa5be94fe40ec766ae082741f09ced85c3f387e5b38bfd65fd2450395 oxlint-plugin-anti-slop@0.1.2: c10c871702365a0c2c59e9f1c5fb92df97cae5755d534c0a3d83c6368f6feafe sprintf-js@1.1.3: 05316a8b01f155fe19a1e0cb4042c81d43d798a76755c407684e1199a18b1e08 vitest@5.0.5: 166c034c864f98267e7d479f083b8d37ea9a7b08d6662313dd38e7c69c9a3eb4 @@ -232,7 +232,7 @@ importers: version: 3.3.1 node-pty: specifier: ^1.1.0 - version: 1.1.0(patch_hash=47ebb5c7a5c70106f439576efaf8335f147fe78cd54357cba11d6fd5b1bc975e) + version: 1.1.0(patch_hash=f1d7035aa5be94fe40ec766ae082741f09ced85c3f387e5b38bfd65fd2450395) posthog-node: specifier: ^5.52.5 version: 5.52.5 @@ -13748,7 +13748,7 @@ snapshots: node-int64@0.4.0: {} - node-pty@1.1.0(patch_hash=47ebb5c7a5c70106f439576efaf8335f147fe78cd54357cba11d6fd5b1bc975e): + node-pty@1.1.0(patch_hash=f1d7035aa5be94fe40ec766ae082741f09ced85c3f387e5b38bfd65fd2450395): dependencies: node-addon-api: 7.1.1 diff --git a/src/main/pty-descendant-termination-libproc.test.ts b/src/main/pty-descendant-termination-libproc.test.ts new file mode 100644 index 000000000000..64ad3a243a3f --- /dev/null +++ b/src/main/pty-descendant-termination-libproc.test.ts @@ -0,0 +1,67 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + setLibprocAddonForTests, + type LibprocProcessRow, + type LibprocQuery, + type LibprocTableRead +} from '../shared/libproc-addon' +import { captureDescendantSnapshot, killWithDescendantSweep } from './pty-descendant-termination' + +const START = Date.UTC(2026, 8, 3, 16, 2, 1) / 1000 + +function row(pid: number, ppid: number): LibprocProcessRow { + return { + pid, + ppid, + pgid: pid, + tpgid: 0, + tdev: -1, + status: 3, + flags: 0, + sessionLeader: false, + startSec: START, + comm: 'node' + } +} + +afterEach(() => { + setLibprocAddonForTests(undefined) +}) + +describe('descendant teardown over the in-process process table', () => { + it('never signals a reused pid from an earlier poll’s abandoned native read', async () => { + let finishAbandoned: (read: LibprocTableRead) => void = () => {} + const abandoned = new Promise((resolve) => { + finishAbandoned = resolve + }) + const readProcessTable = vi + .fn<(query: LibprocQuery) => Promise>() + .mockReturnValueOnce(abandoned) + // Since that read began, descendant 200 exited and an unrelated process took its pid. + .mockImplementation(async () => ({ + startedAtMs: Date.now(), + rows: [row(1, 0), row(100, 1), row(200, 1)] + })) + setLibprocAddonForTests({ + readProcessTable, + processCwd: () => null, + processPath: () => null + }) + const abandonedAtMs = Date.now() + expect(await captureDescendantSnapshot(100, { timeoutMs: 10 })).toBeNull() + + const sendSignal = vi.fn() + const killRoot = vi.fn() + const teardown = killWithDescendantSweep(100, killRoot, { + sendSignal, + timeoutMs: 1_000, + graceMs: 60_000 + }) + finishAbandoned({ startedAtMs: abandonedAtMs, rows: [row(1, 0), row(100, 1), row(200, 100)] }) + await teardown + + expect(killRoot).toHaveBeenCalledOnce() + expect(sendSignal).not.toHaveBeenCalled() + expect(readProcessTable).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/pty-descendant-termination.ts b/src/main/pty-descendant-termination.ts index a2b642807983..13c70e93e110 100644 --- a/src/main/pty-descendant-termination.ts +++ b/src/main/pty-descendant-termination.ts @@ -47,6 +47,7 @@ async function readFreshProcessTable( const capturedAtMs = Date.now() // Pin lstart’s locale so delayed identity checks parse it consistently. const env = { ...process.env, LANG: 'C', LC_ALL: 'C' } + // The in-process reader never serves a scan begun before this stamp (an abandoned earlier one). const inProcess = await readPsStdoutInProcess(DESCENDANT_PS_ARGS, { env, timeoutMs }) if (inProcess !== null) { return { rows: parseProcessTable(inProcess), capturedAtMs } diff --git a/src/shared/darwin-process-table-capture.ts b/src/shared/darwin-process-table-capture.ts index 2ac09f574a3d..8dcc924aaccc 100644 --- a/src/shared/darwin-process-table-capture.ts +++ b/src/shared/darwin-process-table-capture.ts @@ -3,7 +3,7 @@ import { claimDarwinTerminalNaming, isDarwinTerminalNamingInFlight, resetDarwinTerminalNamingForTests -} from './darwin-terminal-naming-slot' +} from './darwin-terminal-naming-single-flight' import { errorMessage } from './error-message' import { ProcessTableCaptureError, PS_ARGS } from './process-table-snapshot' import { withTimeout } from './promise-timeout-fallback' diff --git a/src/shared/darwin-terminal-naming-slot.ts b/src/shared/darwin-terminal-naming-single-flight.ts similarity index 76% rename from src/shared/darwin-terminal-naming-slot.ts rename to src/shared/darwin-terminal-naming-single-flight.ts index 7984ad6ab741..e2bf940d9757 100644 --- a/src/shared/darwin-terminal-naming-slot.ts +++ b/src/shared/darwin-terminal-naming-single-flight.ts @@ -16,6 +16,14 @@ export function claimDarwinTerminalNaming(name: () => Promise): Promise return pending } +/** Settles once the in-flight pass drains, whatever its outcome. */ +export function darwinTerminalNamingDrained(): Promise { + return (namingInFlight ?? Promise.resolve()).then( + () => {}, + () => {} + ) +} + export function isDarwinTerminalNamingInFlight(): boolean { return namingInFlight !== null } diff --git a/src/shared/libproc-addon.ts b/src/shared/libproc-addon.ts index 33b87f0861a1..8f3627aab813 100644 --- a/src/shared/libproc-addon.ts +++ b/src/shared/libproc-addon.ts @@ -15,6 +15,8 @@ export type LibprocProcessRow = { nice?: number sessionLeader: boolean startSec: number + /** `p_starttime.tv_usec`, telling apart processes a reused pid started within one second. */ + startUsec?: number comm: string /** ps's command text (getproclline + strvis in the query's LC_CTYPE). */ command?: string @@ -30,9 +32,15 @@ export type LibprocQuery = { ctype?: string } +export type LibprocTableRead = { + /** Wall clock when the worker began reading; a read queued behind a busy pool starts late. */ + startedAtMs: number + rows: LibprocProcessRow[] | null +} + export type LibprocAddon = { /** Reads on a libuv worker thread; argv for a whole table costs ~20ms of syscalls. */ - readProcessTable: (query: LibprocQuery) => Promise + readProcessTable: (query: LibprocQuery) => Promise processCwd: (pid: number) => string | null processPath: (pid: number) => string | null } diff --git a/src/shared/libproc-argv-completion.ts b/src/shared/libproc-argv-completion.ts index fcaa21149879..3c3afb23406f 100644 --- a/src/shared/libproc-argv-completion.ts +++ b/src/shared/libproc-argv-completion.ts @@ -5,34 +5,52 @@ import { NODEV } from './libproc-ps-format' const SZOMB_STATUS = 5 const MAX_ANCESTOR_DEPTH = 64 -/** A pane descendant: on a terminal, under one of the user's own (argv-readable) processes on that terminal, e.g. `sudo` under the pane shell. - * Root daemons have no terminal and a pane's root `login` sits under the terminal host, so neither costs a ps. */ -function isOnUsersTerminal( +/** A pane descendant: the unreadable chain above it starts on the terminal of one of the user's own (argv-readable) + * processes, e.g. `sudo` under the pane shell, and the root shell and agent `sudo -i` puts on its own pty (use_pty). + * Root daemons descend only from launchd, and a pane's root `login` opens its own pty under the terminal host, so + * neither costs a ps. */ +function descendsFromUsersTerminal( row: LibprocProcessRow, byPid: ReadonlyMap ): boolean { - if (row.tdev === NODEV) { - return false - } - let ancestor = byPid.get(row.ppid) - for (let depth = 0; ancestor && depth < MAX_ANCESTOR_DEPTH; depth += 1) { - if (ancestor.tdev === row.tdev && !ancestor.commandIncomplete) { - return true + let top = row + for (let depth = 0; depth < MAX_ANCESTOR_DEPTH; depth += 1) { + const parent = top.pid === top.ppid ? undefined : byPid.get(top.ppid) + if (!parent) { + return false + } + if (!parent.commandIncomplete) { + return parent.tdev !== NODEV && parent.tdev === top.tdev } - ancestor = ancestor.pid === ancestor.ppid ? undefined : byPid.get(ancestor.ppid) + top = parent } return false } -// Keyed by locale, pid and start time so a long-lived sudo agent costs one ps, not one per poll. -const authoritativeCommands = new Map() +type AuthoritativeCommand = { command: string; cachedAtMs: number } + +// A long-lived sudo agent costs one ps per TTL, not one per poll. +const authoritativeCommands = new Map() const AUTHORITATIVE_COMMAND_LIMIT = 512 +const AUTHORITATIVE_COMMAND_TTL_MS = 10 * 60_000 +/** exec keeps pid and start time but changes comm and the executable path; microseconds split same-second pid reuse. */ function commandKey(ctype: string, row: LibprocProcessRow): string { - return `${ctype}\0${row.pid}\0${row.startSec}` + return [ctype, row.pid, row.startSec, row.startUsec ?? '', row.comm, row.command ?? ''].join('\0') } -/** Fill argv only setuid ps can read, for the rows this caller selected or that run on a user's terminal. */ +function rememberCommand(key: string, command: string, now: number): void { + authoritativeCommands.delete(key) + for (const oldest of authoritativeCommands.keys()) { + if (authoritativeCommands.size < AUTHORITATIVE_COMMAND_LIMIT) { + break + } + authoritativeCommands.delete(oldest) + } + authoritativeCommands.set(key, { command, cachedAtMs: now }) +} + +/** Fill argv only setuid ps can read, for the rows this caller selected or that descend from a user's terminal. */ export async function completeCommands( rows: LibprocProcessRow[], selectedByPid: boolean, @@ -41,19 +59,22 @@ export async function completeCommands( deadline: number ): Promise { const byPid = new Map(rows.map((row) => [row.pid, row])) - const needed = rows.filter( - (row) => - row.commandIncomplete && - row.status !== SZOMB_STATUS && - (selectedByPid || isOnUsersTerminal(row, byPid)) - ) - const missing: LibprocProcessRow[] = [] - for (const row of needed) { - const cached = authoritativeCommands.get(commandKey(ctype, row)) - if (cached === undefined) { - missing.push(row) + const now = Date.now() + const missing: { row: LibprocProcessRow; key: string }[] = [] + for (const row of rows) { + if ( + !row.commandIncomplete || + row.status === SZOMB_STATUS || + !(selectedByPid || descendsFromUsersTerminal(row, byPid)) + ) { + continue + } + const key = commandKey(ctype, row) + const cached = authoritativeCommands.get(key) + if (cached && now - cached.cachedAtMs < AUTHORITATIVE_COMMAND_TTL_MS) { + row.command = cached.command } else { - row.command = cached + missing.push({ row, key }) } } const timeoutMs = deadline - Date.now() @@ -64,7 +85,7 @@ export async function completeCommands( try { const result = await runProcess({ program: '/bin/ps', - args: ['-ww', '-o', 'pid=,command=', '-p', missing.map((row) => row.pid).join(',')], + args: ['-ww', '-o', 'pid=,command=', '-p', missing.map(({ row }) => row.pid).join(',')], env, timeoutMs, maxOutputBytes: 1024 * 1024 @@ -84,18 +105,11 @@ export async function completeCommands( commands.set(Number(match[1]), match[2]) } } - for (const row of missing) { + for (const { row, key } of missing) { const command = commands.get(row.pid) - if (command === undefined) { - continue - } - row.command = command - for (const oldest of authoritativeCommands.keys()) { - if (authoritativeCommands.size < AUTHORITATIVE_COMMAND_LIMIT) { - break - } - authoritativeCommands.delete(oldest) + if (command !== undefined) { + row.command = command + rememberCommand(key, command, now) } - authoritativeCommands.set(commandKey(ctype, row), command) } } diff --git a/src/shared/libproc-process-table.test.ts b/src/shared/libproc-process-table.test.ts index 5c712c36279d..a150e2fff82c 100644 --- a/src/shared/libproc-process-table.test.ts +++ b/src/shared/libproc-process-table.test.ts @@ -11,7 +11,8 @@ import { setLibprocAddonForTests, type LibprocAddon, type LibprocProcessRow, - type LibprocQuery + type LibprocQuery, + type LibprocTableRead } from './libproc-addon' import { runPsInProcess } from './libproc-process-table' import { parseCheapProcessTableRows, parseStrictProcessTableRows } from './process-table-snapshot' @@ -87,7 +88,14 @@ const TABLE = [ row({}) ] -function tableFor(query: LibprocQuery, table = TABLE): LibprocProcessRow[] | null { +function tableFor(query: LibprocQuery, table = TABLE): LibprocTableRead { + return { startedAtMs: Date.now(), rows: rowsFor(query, table) } +} + +function rowsFor( + query: LibprocQuery, + table: readonly LibprocProcessRow[] +): LibprocProcessRow[] | null { if (query.tty !== undefined && !/^(?:\/dev\/)?ttys004$/.test(query.tty)) { return null } @@ -252,4 +260,99 @@ describe('runPsInProcess', () => { }) ) }) + + it('refuses a shared read that began before the request, so stale rows never reach a caller', async () => { + let finishStale: (read: LibprocTableRead) => void = () => {} + const stale = new Promise((resolve) => { + finishStale = resolve + }) + const startedBefore = Date.now() - 5_000 + const readProcessTable = vi + .fn<(query: LibprocQuery) => Promise>() + .mockReturnValueOnce(stale) + .mockImplementation(async (query) => tableFor(query)) + installAddon({ readProcessTable }) + const args = ['-axo', 'pid=,ppid='] + + expect(await runPsInProcess(args, { timeoutMs: 10 })).toMatchObject({ timedOut: true }) + const fresh = runPsInProcess(args, BUDGET) + finishStale({ startedAtMs: startedBefore, rows: [row({ pid: 9999, ppid: 4242 })] }) + const result = await fresh + expect(result?.stdout).not.toContain('9999') + expect(result?.startedAtMs).toBeGreaterThan(startedBefore) + expect(readProcessTable).toHaveBeenCalledTimes(2) + }) + + it('recovers argv for a sudo use_pty tree on its own pty, but not for root daemons or GUI helpers', async () => { + const TTYS005 = (16 << 24) | 5 + const root = { commandIncomplete: true, flags: 0x2 } + const table = [ + ...TABLE, + row({ + ...root, + pid: 4600, + ppid: 4242, + tdev: TTYS004, + comm: 'sudo', + command: '/usr/bin/sudo' + }), + row({ + ...root, + pid: 4601, + ppid: 4600, + tdev: TTYS005, + comm: 'sudo', + command: '/usr/bin/sudo' + }), + row({ ...root, pid: 4602, ppid: 4601, tdev: TTYS005, comm: 'zsh', command: '/bin/zsh' }), + row({ ...root, pid: 4603, ppid: 4602, tdev: TTYS005, comm: 'node', command: '/opt/node' }), + row({ pid: 300, ppid: 1, comm: 'syslogd', command: '/usr/sbin/syslogd' }), + row({ + pid: 700, + ppid: 1, + comm: 'Orca', + command: '/Applications/Orca', + commandIncomplete: false + }), + row({ pid: 701, ppid: 700, comm: 'helper', command: '/usr/libexec/helper' }) + ] + installAddon({ readProcessTable: vi.fn(async (query: LibprocQuery) => tableFor(query, table)) }) + runProcess.mockResolvedValue({ code: 0, signal: null, stdout: '', stderr: '', timedOut: false }) + + await runPsInProcess(['-axo', 'pid=,command='], { env: { LC_ALL: 'C' }, timeoutMs: 1000 }) + const pids = runProcess.mock.calls[0]?.[0].args.at(-1).split(',').map(Number).sort() + expect(pids).toEqual([4600, 4601, 4602, 4603]) + }) + + it('asks ps again once exec changes the program behind a cached pid and start time', async () => { + const shell = row({ pid: 4700, ppid: 4242, tdev: TTYS004, comm: 'zsh', command: '/bin/zsh' }) + let current = shell + installAddon({ + readProcessTable: vi.fn(async (query: LibprocQuery) => tableFor(query, [...TABLE, current])) + }) + runProcess.mockImplementation(async () => ({ + code: 0, + signal: null, + stdout: current === shell ? ' 4700 -zsh\n' : ' 4700 node /opt/claude/cli.js\n', + stderr: '', + timedOut: false + })) + const args = ['-p', '4700', '-o', 'command='] + const options = { env: { LC_ALL: 'C' }, timeoutMs: 1000 } + + expect((await runPsInProcess(args, options))?.stdout).toBe('-zsh\n') + expect((await runPsInProcess(args, options))?.stdout).toBe('-zsh\n') + current = { ...shell, comm: 'node', command: '/opt/node' } + expect((await runPsInProcess(args, options))?.stdout).toBe('node /opt/claude/cli.js\n') + expect(runProcess).toHaveBeenCalledTimes(2) + }) + + it('lets concurrent tty= readers wait out one naming pass instead of running ps', async () => { + installAddon() + // 4300's read is still stalled from the timeout case above. + const args = ['-o', 'pid=,tty=', '-p', '4242'] + const results = await Promise.all([1, 2, 3].map(() => runPsInProcess(args, BUDGET))) + expect(results.map((result) => result?.stdout)).toEqual(Array(3).fill('4242 ttys004\n')) + expect(runProcess).not.toHaveBeenCalled() + }) }) diff --git a/src/shared/libproc-process-table.ts b/src/shared/libproc-process-table.ts index 8a6cd7bed6bc..c265f96261aa 100644 --- a/src/shared/libproc-process-table.ts +++ b/src/shared/libproc-process-table.ts @@ -1,10 +1,14 @@ import { nameDarwinTerminalDevices } from './darwin-terminal-names' -import { claimDarwinTerminalNaming } from './darwin-terminal-naming-slot' +import { + claimDarwinTerminalNaming, + darwinTerminalNamingDrained +} from './darwin-terminal-naming-single-flight' import { loadLibprocAddon, type LibprocAddon, type LibprocProcessRow, - type LibprocQuery + type LibprocQuery, + type LibprocTableRead } from './libproc-addon' import { completeCommands } from './libproc-argv-completion' import { @@ -23,6 +27,8 @@ export type LibprocPsResult = { stderr: '' timedOut: boolean outputTruncated: boolean + /** When the native read began, never before the request: identity boundaries may rely on it. */ + startedAtMs?: number } export type InProcessPsOptions = { @@ -75,19 +81,15 @@ async function beforeDeadline( } // Identical reads share one worker; each caller still races its own deadline, so a stalled pool times them all out. -const nativeReadsInFlight = new Map>() +const nativeReadsInFlight = new Map>() // Workers queued behind a saturated libuv pool would otherwise pile up one per poll. const MAX_NATIVE_READS_IN_FLIGHT = 8 -function readNativeTable( +function startNativeRead( addon: LibprocAddon, - query: LibprocQuery -): Promise | null { - const key = JSON.stringify(query) - const shared = nativeReadsInFlight.get(key) - if (shared) { - return shared - } + query: LibprocQuery, + key: string +): Promise | null { if (nativeReadsInFlight.size >= MAX_NATIVE_READS_IN_FLIGHT) { return null } @@ -102,6 +104,61 @@ function readNativeTable( return pending } +/** Rows read no earlier than `requestedAtMs`. A shared read that began before this request (an earlier + * poll's abandoned one) is refused: its exited pids may since be reused, and teardown would signal them. */ +async function readNativeTableSince( + addon: LibprocAddon, + query: LibprocQuery, + requestedAtMs: number, + deadline: number +): Promise { + const key = JSON.stringify(query) + for (;;) { + const pending = nativeReadsInFlight.get(key) ?? startNativeRead(addon, query, key) + if (!pending) { + // At the cap (a startup-restore burst, or a stalled pool): queue behind a read instead of bursting ps. + const settled = Promise.race(nativeReadsInFlight.values()).then( + () => {}, + () => {} + ) + if ((await beforeDeadline(settled, deadline)) === DEADLINE_PASSED) { + return DEADLINE_PASSED + } + continue + } + const read = await beforeDeadline(pending, deadline) + if (read === DEADLINE_PASSED || read.startedAtMs >= requestedAtMs) { + return read + } + if (nativeReadsInFlight.get(key) === pending) { + nativeReadsInFlight.delete(key) + } + } +} + +/** One naming pass at a time; wait out another (within the deadline) rather than burst /bin/ps at startup restore. */ +async function nameTerminals( + devices: ReadonlySet, + deadline: number +): Promise | typeof DEADLINE_PASSED> { + for (;;) { + const controller = new AbortController() + const naming = claimDarwinTerminalNaming(() => + nameDarwinTerminalDevices(devices, undefined, controller.signal) + ) + if (naming) { + const named = await beforeDeadline(naming, deadline) + if (named === DEADLINE_PASSED) { + controller.abort() + } + return named + } + if ((await beforeDeadline(darwinTerminalNamingDrained(), deadline)) === DEADLINE_PASSED) { + return DEADLINE_PASSED + } + } +} + /** ps output for `args`, read in process; null when the addon or the invocation is unsupported so callers run ps. */ export async function runPsInProcess( args: readonly string[], @@ -112,7 +169,8 @@ export async function runPsInProcess( if (!addon || !query) { return null } - const deadline = Date.now() + options.timeoutMs + const requestedAtMs = Date.now() + const deadline = requestedAtMs + options.timeoutMs const env = options.env ?? process.env const utc = lstartZoneIsUtc(env) const needsLstart = query.columns.includes('lstart') @@ -132,34 +190,23 @@ export async function runPsInProcess( ...(includeCommand ? { ctype } : {}) } let rows: LibprocProcessRow[] | null + let startedAtMs: number let ttyNames: ReadonlyMap = new Map() try { - const pending = readNativeTable(addon, nativeQuery) - if (!pending) { - return null - } - const read = await beforeDeadline(pending, deadline) + const read = await readNativeTableSince(addon, nativeQuery, requestedAtMs, deadline) if (read === DEADLINE_PASSED) { return TIMED_OUT } + startedAtMs = read.startedAtMs // Shared reads hand every caller the same rows; command completion writes per caller. - rows = read?.map((row) => ({ ...row })) ?? null + rows = read.rows?.map((row) => ({ ...row })) ?? null if (rows && query.columns.includes('tty')) { const devices = new Set( rows.map((row) => formatDarwinDevice(row.tdev)).filter((device) => device !== null) ) if (devices.size > 0) { - const controller = new AbortController() - const naming = claimDarwinTerminalNaming(() => - nameDarwinTerminalDevices(devices, undefined, controller.signal) - ) - // Another naming pass is still draining the pool: run ps, as the capture's guard always has. - if (!naming) { - return null - } - const named = await beforeDeadline(naming, deadline) + const named = await nameTerminals(devices, deadline) if (named === DEADLINE_PASSED) { - controller.abort() return TIMED_OUT } ttyNames = named @@ -176,7 +223,7 @@ export async function runPsInProcess( } // ps exits 1 when -t names no terminal or a -p/-t selection matched nothing. if (rows === null) { - return { ...TIMED_OUT, code: 1, signal: null, timedOut: false } + return { ...TIMED_OUT, code: 1, signal: null, timedOut: false, startedAtMs } } const ttyOf = (row: LibprocProcessRow): string => ttyNames.get(formatDarwinDevice(row.tdev) ?? '') ?? '??' @@ -216,7 +263,8 @@ export async function runPsInProcess( stdout, stderr: '', timedOut: false, - outputTruncated + outputTruncated, + startedAtMs } } From 1472b0613474487d1434ad15d668d8cf0b9ba5fa Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 03:45:00 -0700 Subject: [PATCH 06/13] test(terminal): require /bin/ps row order in the libproc parity test (#31783) Parsers that take the first matching row depend on ps's terminal-then-pid order, so compare the order of the rows both captures share, not just their contents. --- src/shared/libproc-process-table-real-ps.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/shared/libproc-process-table-real-ps.test.ts b/src/shared/libproc-process-table-real-ps.test.ts index d1fca9bd883c..4c8f16ca56a7 100644 --- a/src/shared/libproc-process-table-real-ps.test.ts +++ b/src/shared/libproc-process-table-real-ps.test.ts @@ -107,11 +107,13 @@ describe.runIf(process.platform === 'darwin')( const after = rowsOf(await inProcess(args, env), columns) const commandAt = columns.indexOf('command') const failures: string[] = [] + const shared: number[] = [] for (const [pid, ours] of before) { const real = ps.get(pid) if (!real || JSON.stringify(after.get(pid)) !== JSON.stringify(ours)) { continue } + shared.push(pid) // Another user's argv needs setuid ps; only pane descendants get that fallback. const comparable = commandAt === -1 || ownPids.has(pid) @@ -125,6 +127,12 @@ describe.runIf(process.platform === 'darwin')( failures.push(`${pid}: ${JSON.stringify(comparable)} != ${JSON.stringify(expected)}`) } } + // ps sorts by terminal, then pid; parsers that take the first match rely on that order. + const comparedPids = new Set(shared) + const psOrder = [...ps.keys()].filter((pid) => comparedPids.has(pid)) + if (JSON.stringify(psOrder) !== JSON.stringify(shared)) { + failures.push(`row order differs from ps for ${args.join(' ')}`) + } return failures } From 11602347fd073fbf0bb4eda92565ccdf17335505 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 04:20:33 -0700 Subject: [PATCH 07/13] test(terminal): pin libproc read start times instead of reading the wall clock (#31783) --- src/main/pty-descendant-termination-libproc.test.ts | 11 ++++++++--- src/shared/libproc-process-table.test.ts | 6 ++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/main/pty-descendant-termination-libproc.test.ts b/src/main/pty-descendant-termination-libproc.test.ts index 64ad3a243a3f..af0ee425597d 100644 --- a/src/main/pty-descendant-termination-libproc.test.ts +++ b/src/main/pty-descendant-termination-libproc.test.ts @@ -8,6 +8,9 @@ import { import { captureDescendantSnapshot, killWithDescendantSweep } from './pty-descendant-termination' const START = Date.UTC(2026, 8, 3, 16, 2, 1) / 1000 +// Fixed read start times on either side of any request: one long before, one after. +const ABANDONED_READ_STARTED_AT_MS = 0 +const FRESH_READ_STARTED_AT_MS = Date.UTC(2100, 0, 1) function row(pid: number, ppid: number): LibprocProcessRow { return { @@ -39,7 +42,7 @@ describe('descendant teardown over the in-process process table', () => { .mockReturnValueOnce(abandoned) // Since that read began, descendant 200 exited and an unrelated process took its pid. .mockImplementation(async () => ({ - startedAtMs: Date.now(), + startedAtMs: FRESH_READ_STARTED_AT_MS, rows: [row(1, 0), row(100, 1), row(200, 1)] })) setLibprocAddonForTests({ @@ -47,7 +50,6 @@ describe('descendant teardown over the in-process process table', () => { processCwd: () => null, processPath: () => null }) - const abandonedAtMs = Date.now() expect(await captureDescendantSnapshot(100, { timeoutMs: 10 })).toBeNull() const sendSignal = vi.fn() @@ -57,7 +59,10 @@ describe('descendant teardown over the in-process process table', () => { timeoutMs: 1_000, graceMs: 60_000 }) - finishAbandoned({ startedAtMs: abandonedAtMs, rows: [row(1, 0), row(100, 1), row(200, 100)] }) + finishAbandoned({ + startedAtMs: ABANDONED_READ_STARTED_AT_MS, + rows: [row(1, 0), row(100, 1), row(200, 100)] + }) await teardown expect(killRoot).toHaveBeenCalledOnce() diff --git a/src/shared/libproc-process-table.test.ts b/src/shared/libproc-process-table.test.ts index a150e2fff82c..eb8cc4f28734 100644 --- a/src/shared/libproc-process-table.test.ts +++ b/src/shared/libproc-process-table.test.ts @@ -21,6 +21,8 @@ const TTYS004 = (16 << 24) | 4 // 2026-09-03T16:02:01Z, a single-digit day so lstart pads it. const START = Date.UTC(2026, 8, 3, 16, 2, 1) / 1000 const BUDGET = { timeoutMs: 1000 } +// After any request, so mocked reads always count as fresh. +const FRESH_READ_STARTED_AT_MS = Date.UTC(2100, 0, 1) function row(overrides: Partial): LibprocProcessRow { return { @@ -89,7 +91,7 @@ const TABLE = [ ] function tableFor(query: LibprocQuery, table = TABLE): LibprocTableRead { - return { startedAtMs: Date.now(), rows: rowsFor(query, table) } + return { startedAtMs: FRESH_READ_STARTED_AT_MS, rows: rowsFor(query, table) } } function rowsFor( @@ -266,7 +268,7 @@ describe('runPsInProcess', () => { const stale = new Promise((resolve) => { finishStale = resolve }) - const startedBefore = Date.now() - 5_000 + const startedBefore = 0 const readProcessTable = vi .fn<(query: LibprocQuery) => Promise>() .mockReturnValueOnce(stale) From 03022ca1001c4a472c6224751fc43d2993f57a7f Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 05:07:15 -0700 Subject: [PATCH 08/13] fix(terminal): match native process table reads to requests by sequence, not wall clock (#31783) Freshness compared the worker's gettimeofday with Date.now(), so a clock step back let an abandoned read's rows through (wrong-pid SIGTERM) and a step forward could reject fresh reads until the deadline. Each read now takes a JS-side sequence number when created and is submitted a microtask later; a caller joins only a read not yet submitted or created after it registered, so callers in one turn share a worker and nothing submitted before a request serves it. The addon drops startedAtMs again. Deadlines, timeouts and the argv cache use performance.now(). Callers past the 8-read cap wait on one slot notifier and each joined read has one settle notifier; both unsubscribe on timeout, so a stalled pool retains no per-caller reactions. If the pool is still at the cap when an overflow caller's deadline passes, the reader is marked stalled for 30s and callers run ps, as before this branch. Recovered argv is trusted for 30s: exec can keep pid, start time, comm and executable (node -> node with another script) and no cheap field shows it, so a sudo pane costs one targeted ps per process per 30s. --- config/patches/node-pty@1.1.0.patch | 65 +++--- pnpm-lock.yaml | 6 +- ...pty-descendant-termination-libproc.test.ts | 86 ++++---- src/shared/libproc-addon.ts | 8 +- src/shared/libproc-argv-completion.ts | 10 +- src/shared/libproc-native-reads.ts | 190 ++++++++++++++++++ src/shared/libproc-process-table.test.ts | 54 +++-- src/shared/libproc-process-table.ts | 113 ++--------- 8 files changed, 328 insertions(+), 204 deletions(-) create mode 100644 src/shared/libproc-native-reads.ts diff --git a/config/patches/node-pty@1.1.0.patch b/config/patches/node-pty@1.1.0.patch index c9ab81362f0b..9e42c7545988 100644 --- a/config/patches/node-pty@1.1.0.patch +++ b/config/patches/node-pty@1.1.0.patch @@ -297,7 +297,7 @@ index 181ccabbbe9c4948a9725fb1db907a68e9de01fc..67f31facf85562b67adbfbd04ce28ddd process.send!({ consoleProcessList }); process.exit(0); diff --git a/src/unix/pty.cc b/src/unix/pty.cc -index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b4d1e928e 100644 +index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..45197ddf4440b8599002b360bc50c4fe0cedf305 100644 --- a/src/unix/pty.cc +++ b/src/unix/pty.cc @@ -23,8 +23,11 @@ @@ -352,18 +352,17 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b /* Some platforms name VWERASE and VDISCARD differently */ #if !defined(VWERASE) && defined(VWERSE) #define VWERASE VWERSE -@@ -67,6 +103,10 @@ +@@ -67,6 +103,9 @@ #include #include #include -+#include +#include +#include +#include #endif /* NSIG - macro for highest signal + 1, should be defined */ -@@ -228,6 +268,9 @@ Napi::Value PtyGetProc(const Napi::CallbackInfo& info); +@@ -228,6 +267,9 @@ Napi::Value PtyGetProc(const Napi::CallbackInfo& info); static int pty_nonblock(int); @@ -373,7 +372,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b #if defined(__APPLE__) static char * pty_getproc(int); -@@ -237,13 +280,23 @@ pty_getproc(int, char *); +@@ -237,13 +279,23 @@ pty_getproc(int, char *); #endif #if defined(__APPLE__) || defined(__OpenBSD__) @@ -398,7 +397,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b #endif struct DelBuf { -@@ -345,8 +398,8 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { +@@ -345,8 +397,8 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { term->c_cc[VSTATUS] = 20; #endif @@ -409,7 +408,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b // helperPath std::string helper_path = info[9].As(); -@@ -367,14 +420,18 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { +@@ -367,14 +419,18 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { argv[i + 3] = strdup(arg.c_str()); } @@ -432,7 +431,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b #else int argc = argv_.Length(); int argl = argc + 2; -@@ -445,6 +502,9 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { +@@ -445,6 +501,9 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { if (pty_nonblock(master) == -1) { throw Napi::Error::New(napiEnv, "Could not set master fd to nonblocking."); } @@ -442,7 +441,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b } #endif -@@ -586,6 +646,23 @@ pty_nonblock(int fd) { +@@ -586,6 +645,23 @@ pty_nonblock(int fd) { return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } @@ -466,7 +465,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b /** * pty_getproc * Taken from tmux. -@@ -684,15 +761,73 @@ pty_getproc(int fd, char *tty) { +@@ -684,15 +760,73 @@ pty_getproc(int fd, char *tty) { #endif #if defined(__APPLE__) @@ -542,25 +541,25 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b for (; count < 3; count++) { low_fds[count] = posix_openpt(O_RDWR); -@@ -706,81 +841,469 @@ pty_posix_spawn(char** argv, char** env, +@@ -706,81 +840,461 @@ pty_posix_spawn(char** argv, char** env, POSIX_SPAWN_SETSID; *master = posix_openpt(O_RDWR); if (*master == -1) { - return; + pty_set_spawn_error(err, "posix_openpt", errno); -+ goto done; -+ } -+ -+ res = grantpt(*master); -+ if (res == -1) { -+ pty_set_spawn_error(err, "grantpt", errno); + goto done; } - int res = grantpt(*master) || unlockpt(*master); -+ res = unlockpt(*master); ++ res = grantpt(*master); if (res == -1) { - return; ++ pty_set_spawn_error(err, "grantpt", errno); ++ goto done; ++ } ++ ++ res = unlockpt(*master); ++ if (res == -1) { + pty_set_spawn_error(err, "unlockpt", errno); + goto done; } @@ -736,9 +735,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b + out->assign(encoded.data(), length); + return true; +} - -- for (; count > 0; count--) { -- close(low_fds[count]); ++ +static bool +orca_read_kinfo(int what, int flag, std::vector* procs) { + int mib[4] = { CTL_KERN, KERN_PROC, what, flag }; @@ -889,7 +886,9 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b + } + return 0; +} -+ + +- for (; count > 0; count--) { +- close(low_fds[count]); +static Napi::Array +orca_process_rows_to_js(Napi::Env env, bool include_command, const std::vector& rows) { + Napi::Array result = Napi::Array::New(env, rows.size()); @@ -914,11 +913,11 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b + row.Set("commandIncomplete", Napi::Boolean::New(env, entry.command_incomplete)); + } + result.Set(index++, row); -+ } + } + return result; +} + -+// readProcessTable({ command, pids?, tty?, ctype? }) -> { startedAtMs, rows | null }: pids and tty are exclusive selections, as Orca issues them. ++// readProcessTable({ command, pids?, tty?, ctype? }) -> rows | null: pids and tty are exclusive selections, as Orca issues them. +static orca_process_query +orca_read_process_query(const Napi::CallbackInfo& info) { + Napi::Env env(info.Env()); @@ -943,7 +942,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b + } + } + query.select_pids = true; - } ++ } + Napi::Value tty = options.Get("tty"); + if (tty.IsString()) { + if (query.select_pids) { @@ -965,15 +964,11 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b + : Napi::AsyncWorker(env), + deferred_(Napi::Promise::Deferred::New(env)), + query_(std::move(query)), -+ status_(-1), -+ started_at_ms_(0) {} ++ status_(-1) {} + + Napi::Promise Promise() { return deferred_.Promise(); } + + void Execute() override { -+ // Callers must not mistake a read queued before their request for a fresh one. -+ struct timeval now; -+ started_at_ms_ = gettimeofday(&now, NULL) == 0 ? (double)now.tv_sec * 1000.0 + (double)now.tv_usec / 1000.0 : 0; + status_ = orca_gather_process_table(query_, &rows_); + if (status_ < 0) { + SetError("orca: process table sysctl failed"); @@ -982,12 +977,9 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b + + void OnOK() override { + Napi::Env env = Env(); -+ Napi::Object result = Napi::Object::New(env); -+ result.Set("startedAtMs", Napi::Number::New(env, started_at_ms_)); + // ps exits 1 without output when -t names no terminal. -+ result.Set("rows", status_ == 1 ? env.Null() -+ : Napi::Value(orca_process_rows_to_js(env, query_.include_command, rows_))); -+ deferred_.Resolve(result); ++ deferred_.Resolve(status_ == 1 ? env.Null() ++ : Napi::Value(orca_process_rows_to_js(env, query_.include_command, rows_))); + } + + void OnError(const Napi::Error& error) override { @@ -998,7 +990,6 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b + Napi::Promise::Deferred deferred_; + orca_process_query query_; + int status_; -+ double started_at_ms_; + std::vector rows_; +}; + @@ -1036,7 +1027,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..896d51812c5c3fe9c8ca5d403a785f0b } #endif -@@ -793,6 +1316,11 @@ Napi::Object init(Napi::Env env, Napi::Object exports) { +@@ -793,6 +1307,11 @@ Napi::Object init(Napi::Env env, Napi::Object exports) { exports.Set("open", Napi::Function::New(env, PtyOpen)); exports.Set("resize", Napi::Function::New(env, PtyResize)); exports.Set("process", Napi::Function::New(env, PtyGetProc)); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2cdc42fff226..9f3762426fbe 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -184,7 +184,7 @@ patchedDependencies: i18next-cli@1.74.2: 2ee32eef742615cd133e1a6940f027deb3723a8430bb7953bba3a6769b0aac47 lint-staged@16.4.0: 7333b3837f80a7fbd045964db6d76ba4fc118e49134bdbabb00585b6b7b60673 monaco-editor@0.55.1: 53b71f7d8a7c00b76ffdb73ce83d18e31692f193f5fafa6a390e48f5b3fdd636 - node-pty@1.1.0: f1d7035aa5be94fe40ec766ae082741f09ced85c3f387e5b38bfd65fd2450395 + node-pty@1.1.0: b56279c3729be0e79c21f4d6ab207052ed949e9a792ae326fa9bd473e23347a1 oxlint-plugin-anti-slop@0.1.2: c10c871702365a0c2c59e9f1c5fb92df97cae5755d534c0a3d83c6368f6feafe sprintf-js@1.1.3: 05316a8b01f155fe19a1e0cb4042c81d43d798a76755c407684e1199a18b1e08 vitest@5.0.5: 166c034c864f98267e7d479f083b8d37ea9a7b08d6662313dd38e7c69c9a3eb4 @@ -232,7 +232,7 @@ importers: version: 3.3.1 node-pty: specifier: ^1.1.0 - version: 1.1.0(patch_hash=f1d7035aa5be94fe40ec766ae082741f09ced85c3f387e5b38bfd65fd2450395) + version: 1.1.0(patch_hash=b56279c3729be0e79c21f4d6ab207052ed949e9a792ae326fa9bd473e23347a1) posthog-node: specifier: ^5.52.5 version: 5.52.5 @@ -13748,7 +13748,7 @@ snapshots: node-int64@0.4.0: {} - node-pty@1.1.0(patch_hash=f1d7035aa5be94fe40ec766ae082741f09ced85c3f387e5b38bfd65fd2450395): + node-pty@1.1.0(patch_hash=b56279c3729be0e79c21f4d6ab207052ed949e9a792ae326fa9bd473e23347a1): dependencies: node-addon-api: 7.1.1 diff --git a/src/main/pty-descendant-termination-libproc.test.ts b/src/main/pty-descendant-termination-libproc.test.ts index af0ee425597d..db65ff483a65 100644 --- a/src/main/pty-descendant-termination-libproc.test.ts +++ b/src/main/pty-descendant-termination-libproc.test.ts @@ -2,15 +2,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { setLibprocAddonForTests, type LibprocProcessRow, - type LibprocQuery, - type LibprocTableRead + type LibprocQuery } from '../shared/libproc-addon' +import { resetNativeReadsForTests } from '../shared/libproc-native-reads' import { captureDescendantSnapshot, killWithDescendantSweep } from './pty-descendant-termination' const START = Date.UTC(2026, 8, 3, 16, 2, 1) / 1000 -// Fixed read start times on either side of any request: one long before, one after. -const ABANDONED_READ_STARTED_AT_MS = 0 -const FRESH_READ_STARTED_AT_MS = Date.UTC(2100, 0, 1) +const WALL_CLOCK = Date.UTC(2026, 9, 29, 12, 0, 0) function row(pid: number, ppid: number): LibprocProcessRow { return { @@ -29,44 +27,52 @@ function row(pid: number, ppid: number): LibprocProcessRow { afterEach(() => { setLibprocAddonForTests(undefined) + resetNativeReadsForTests() + vi.useRealTimers() }) describe('descendant teardown over the in-process process table', () => { - it('never signals a reused pid from an earlier poll’s abandoned native read', async () => { - let finishAbandoned: (read: LibprocTableRead) => void = () => {} - const abandoned = new Promise((resolve) => { - finishAbandoned = resolve - }) - const readProcessTable = vi - .fn<(query: LibprocQuery) => Promise>() - .mockReturnValueOnce(abandoned) - // Since that read began, descendant 200 exited and an unrelated process took its pid. - .mockImplementation(async () => ({ - startedAtMs: FRESH_READ_STARTED_AT_MS, - rows: [row(1, 0), row(100, 1), row(200, 1)] - })) - setLibprocAddonForTests({ - readProcessTable, - processCwd: () => null, - processPath: () => null - }) - expect(await captureDescendantSnapshot(100, { timeoutMs: 10 })).toBeNull() + it.each([ + ['a steady clock', 0], + ['the wall clock stepped back 100ms', -100], + ['the wall clock stepped back an hour', -3_600_000], + ['the wall clock stepped forward an hour', 3_600_000] + ])( + 'never signals a reused pid from an earlier poll’s abandoned native read with %s', + async (_name, stepMs) => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(WALL_CLOCK) + type Rows = LibprocProcessRow[] | null + let finishAbandoned: (rows: Rows) => void = () => {} + const abandoned = new Promise((resolve) => { + finishAbandoned = resolve + }) + const readProcessTable = vi + .fn<(query: LibprocQuery) => Promise>() + .mockReturnValueOnce(abandoned) + // Since that read was submitted, descendant 200 exited and an unrelated process took its pid. + .mockImplementation(async () => [row(1, 0), row(100, 1), row(200, 1)]) + setLibprocAddonForTests({ + readProcessTable, + processCwd: () => null, + processPath: () => null + }) + expect(await captureDescendantSnapshot(100, { timeoutMs: 10 })).toBeNull() - const sendSignal = vi.fn() - const killRoot = vi.fn() - const teardown = killWithDescendantSweep(100, killRoot, { - sendSignal, - timeoutMs: 1_000, - graceMs: 60_000 - }) - finishAbandoned({ - startedAtMs: ABANDONED_READ_STARTED_AT_MS, - rows: [row(1, 0), row(100, 1), row(200, 100)] - }) - await teardown + vi.setSystemTime(WALL_CLOCK + stepMs) + const sendSignal = vi.fn() + const killRoot = vi.fn() + const teardown = killWithDescendantSweep(100, killRoot, { + sendSignal, + timeoutMs: 1_000, + graceMs: 60_000 + }) + finishAbandoned([row(1, 0), row(100, 1), row(200, 100)]) + await teardown - expect(killRoot).toHaveBeenCalledOnce() - expect(sendSignal).not.toHaveBeenCalled() - expect(readProcessTable).toHaveBeenCalledTimes(2) - }) + expect(killRoot).toHaveBeenCalledOnce() + expect(sendSignal).not.toHaveBeenCalled() + expect(readProcessTable).toHaveBeenCalledTimes(2) + } + ) }) diff --git a/src/shared/libproc-addon.ts b/src/shared/libproc-addon.ts index 8f3627aab813..35d26654d030 100644 --- a/src/shared/libproc-addon.ts +++ b/src/shared/libproc-addon.ts @@ -32,15 +32,9 @@ export type LibprocQuery = { ctype?: string } -export type LibprocTableRead = { - /** Wall clock when the worker began reading; a read queued behind a busy pool starts late. */ - startedAtMs: number - rows: LibprocProcessRow[] | null -} - export type LibprocAddon = { /** Reads on a libuv worker thread; argv for a whole table costs ~20ms of syscalls. */ - readProcessTable: (query: LibprocQuery) => Promise + readProcessTable: (query: LibprocQuery) => Promise processCwd: (pid: number) => string | null processPath: (pid: number) => string | null } diff --git a/src/shared/libproc-argv-completion.ts b/src/shared/libproc-argv-completion.ts index 3c3afb23406f..5ceb62c811a6 100644 --- a/src/shared/libproc-argv-completion.ts +++ b/src/shared/libproc-argv-completion.ts @@ -1,5 +1,6 @@ import { runProcess } from '@orca/process-host' import type { LibprocProcessRow } from './libproc-addon' +import { monotonicNow } from './libproc-native-reads' import { NODEV } from './libproc-ps-format' const SZOMB_STATUS = 5 @@ -29,10 +30,11 @@ function descendsFromUsersTerminal( type AuthoritativeCommand = { command: string; cachedAtMs: number } -// A long-lived sudo agent costs one ps per TTL, not one per poll. +// exec can keep pid, start time, comm and executable (node → node with another script) and no cheap field shows it, +// so a recovered argv is trusted for 30s: a sudo pane costs one targeted ps per process per TTL, other users none. const authoritativeCommands = new Map() const AUTHORITATIVE_COMMAND_LIMIT = 512 -const AUTHORITATIVE_COMMAND_TTL_MS = 10 * 60_000 +const AUTHORITATIVE_COMMAND_TTL_MS = 30_000 /** exec keeps pid and start time but changes comm and the executable path; microseconds split same-second pid reuse. */ function commandKey(ctype: string, row: LibprocProcessRow): string { @@ -59,7 +61,7 @@ export async function completeCommands( deadline: number ): Promise { const byPid = new Map(rows.map((row) => [row.pid, row])) - const now = Date.now() + const now = monotonicNow() const missing: { row: LibprocProcessRow; key: string }[] = [] for (const row of rows) { if ( @@ -77,7 +79,7 @@ export async function completeCommands( missing.push({ row, key }) } } - const timeoutMs = deadline - Date.now() + const timeoutMs = Math.floor(deadline - monotonicNow()) if (missing.length === 0 || timeoutMs <= 0) { return } diff --git a/src/shared/libproc-native-reads.ts b/src/shared/libproc-native-reads.ts new file mode 100644 index 000000000000..b2d6f65e0b49 --- /dev/null +++ b/src/shared/libproc-native-reads.ts @@ -0,0 +1,190 @@ +import type { LibprocAddon, LibprocProcessRow, LibprocQuery } from './libproc-addon' + +/** Deadlines run on the monotonic clock: a wall-clock step must neither extend nor cut a caller's budget. */ +export function monotonicNow(): number { + return performance.now() +} + +export const DEADLINE_PASSED = Symbol('deadline') + +type Settled = { ok: true; value: T } | { ok: false; error: unknown } + +/** One reaction on the shared promise; each caller subscribes with its own deadline and unsubscribes when it lapses. */ +function createSettleNotifier( + promise: Promise +): (deadline: number) => Promise | typeof DEADLINE_PASSED> { + const waiters = new Set<(settled: Settled) => void>() + let result: Settled | undefined + const settle = (settled: Settled): void => { + result = settled + for (const waiter of waiters) { + waiter(settled) + } + waiters.clear() + } + promise.then( + (value) => settle({ ok: true, value }), + (error: unknown) => settle({ ok: false, error }) + ) + return (deadline) => + result + ? Promise.resolve(result) + : new Promise((resolve) => { + const waiter = (settled: Settled): void => { + clearTimeout(timer) + resolve(settled) + } + waiters.add(waiter) + const timer = setTimeout( + () => { + waiters.delete(waiter) + resolve(DEADLINE_PASSED) + }, + Math.max(0, deadline - monotonicNow()) + ) + }) +} + +export async function beforeDeadline( + pending: Promise, + deadline: number +): Promise { + const settled = await createSettleNotifier(pending)(deadline) + if (settled === DEADLINE_PASSED) { + return DEADLINE_PASSED + } + if (!settled.ok) { + throw settled.error + } + return settled.value +} + +type NativeRead = { + /** Creation order; once submitted, a read serves only callers registered before it was created. */ + sequence: number + /** Submission waits a microtask so callers registered in the same turn share one worker. */ + readonly submitted: boolean + wait: (deadline: number) => Promise | typeof DEADLINE_PASSED> +} + +// Identical fresh reads share one worker; each caller still races its own deadline, so a stalled pool times them all out. +const sharedReads = new Map() +let nextSequence = 0 +let outstandingReads = 0 +// Workers queued behind a saturated libuv pool would otherwise pile up one per poll. +const MAX_OUTSTANDING_READS = 8 +const slotWaiters = new Set<() => void>() +// A pool pinned at the cap past a caller's whole deadline is stalled: hand callers back to ps for a while. +const STALLED_POOL_COOL_DOWN_MS = 30_000 +let unhealthyUntil = Number.NEGATIVE_INFINITY + +export function isNativeReaderHealthy(): boolean { + return monotonicNow() >= unhealthyUntil +} + +/** Register a request: only reads submitted from now on may serve it, so an earlier poll's abandoned read + * (whose exited pids may since be reused, and which teardown would signal) never does. Clock-free. */ +export function registerNativeRequest(): number { + return nextSequence +} + +function submitRead(addon: LibprocAddon, query: LibprocQuery, key: string): NativeRead { + const submission = { submitted: false } + const pending = new Promise((resolve, reject) => { + queueMicrotask(() => { + submission.submitted = true + try { + addon.readProcessTable(query).then(resolve, reject) + } catch (error) { + reject(error) + } + }) + }) + const read: NativeRead = { + sequence: nextSequence++, + get submitted() { + return submission.submitted + }, + wait: createSettleNotifier(pending) + } + outstandingReads += 1 + sharedReads.set(key, read) + const release = (): void => { + outstandingReads -= 1 + if (sharedReads.get(key) === read) { + sharedReads.delete(key) + } + for (const waiter of slotWaiters) { + waiter() + } + slotWaiters.clear() + } + pending.then(release, release) + return read +} + +function waitForSlot(deadline: number): Promise { + return new Promise((resolve) => { + const waiter = (): void => { + clearTimeout(timer) + resolve(true) + } + slotWaiters.add(waiter) + const timer = setTimeout( + () => { + slotWaiters.delete(waiter) + resolve(false) + }, + Math.max(0, deadline - monotonicNow()) + ) + }) +} + +/** Rows from a read submitted after `registeredSequence` (null: -t named no terminal); 'stalled' sends the caller to ps. */ +export async function readFreshNativeTable( + addon: LibprocAddon, + query: LibprocQuery, + registeredSequence: number, + deadline: number +): Promise { + const key = JSON.stringify(query) + for (;;) { + const shared = sharedReads.get(key) + let read: NativeRead + if (shared && (!shared.submitted || shared.sequence >= registeredSequence)) { + read = shared + } else if (outstandingReads < MAX_OUTSTANDING_READS) { + read = submitRead(addon, query, key) + } else { + // Queue behind the cap (a startup-restore burst) instead of bursting ps. + if (!(await waitForSlot(deadline))) { + if (outstandingReads >= MAX_OUTSTANDING_READS) { + unhealthyUntil = monotonicNow() + STALLED_POOL_COOL_DOWN_MS + console.warn('[process-table] libuv pool stalled; using ps for 30s') + return 'stalled' + } + return DEADLINE_PASSED + } + continue + } + const settled = await read.wait(deadline) + if (settled === DEADLINE_PASSED) { + return DEADLINE_PASSED + } + if (!settled.ok) { + throw settled.error + } + return settled.value + } +} + +export function nativeReadWaitersForTests(): number { + return slotWaiters.size +} + +export function resetNativeReadsForTests(): void { + sharedReads.clear() + slotWaiters.clear() + outstandingReads = 0 + unhealthyUntil = Number.NEGATIVE_INFINITY +} diff --git a/src/shared/libproc-process-table.test.ts b/src/shared/libproc-process-table.test.ts index eb8cc4f28734..fab2c1ab4eeb 100644 --- a/src/shared/libproc-process-table.test.ts +++ b/src/shared/libproc-process-table.test.ts @@ -11,9 +11,9 @@ import { setLibprocAddonForTests, type LibprocAddon, type LibprocProcessRow, - type LibprocQuery, - type LibprocTableRead + type LibprocQuery } from './libproc-addon' +import { nativeReadWaitersForTests, resetNativeReadsForTests } from './libproc-native-reads' import { runPsInProcess } from './libproc-process-table' import { parseCheapProcessTableRows, parseStrictProcessTableRows } from './process-table-snapshot' @@ -21,8 +21,6 @@ const TTYS004 = (16 << 24) | 4 // 2026-09-03T16:02:01Z, a single-digit day so lstart pads it. const START = Date.UTC(2026, 8, 3, 16, 2, 1) / 1000 const BUDGET = { timeoutMs: 1000 } -// After any request, so mocked reads always count as fresh. -const FRESH_READ_STARTED_AT_MS = Date.UTC(2100, 0, 1) function row(overrides: Partial): LibprocProcessRow { return { @@ -90,13 +88,9 @@ const TABLE = [ row({}) ] -function tableFor(query: LibprocQuery, table = TABLE): LibprocTableRead { - return { startedAtMs: FRESH_READ_STARTED_AT_MS, rows: rowsFor(query, table) } -} - -function rowsFor( +function tableFor( query: LibprocQuery, - table: readonly LibprocProcessRow[] + table: readonly LibprocProcessRow[] = TABLE ): LibprocProcessRow[] | null { if (query.tty !== undefined && !/^(?:\/dev\/)?ttys004$/.test(query.tty)) { return null @@ -122,6 +116,7 @@ function installAddon(overrides: Partial = {}): LibprocAddon { afterEach(() => { setLibprocAddonForTests(undefined) + resetNativeReadsForTests() runProcess.mockReset() vi.useRealTimers() }) @@ -263,14 +258,14 @@ describe('runPsInProcess', () => { ) }) - it('refuses a shared read that began before the request, so stale rows never reach a caller', async () => { - let finishStale: (read: LibprocTableRead) => void = () => {} - const stale = new Promise((resolve) => { + it('never joins a read submitted before the request, so stale rows never reach a caller', async () => { + type Rows = LibprocProcessRow[] | null + let finishStale: (rows: Rows) => void = () => {} + const stale = new Promise((resolve) => { finishStale = resolve }) - const startedBefore = 0 const readProcessTable = vi - .fn<(query: LibprocQuery) => Promise>() + .fn<(query: LibprocQuery) => Promise>() .mockReturnValueOnce(stale) .mockImplementation(async (query) => tableFor(query)) installAddon({ readProcessTable }) @@ -278,13 +273,34 @@ describe('runPsInProcess', () => { expect(await runPsInProcess(args, { timeoutMs: 10 })).toMatchObject({ timedOut: true }) const fresh = runPsInProcess(args, BUDGET) - finishStale({ startedAtMs: startedBefore, rows: [row({ pid: 9999, ppid: 4242 })] }) - const result = await fresh - expect(result?.stdout).not.toContain('9999') - expect(result?.startedAtMs).toBeGreaterThan(startedBefore) + finishStale([row({ pid: 9999, ppid: 4242 })]) + expect((await fresh)?.stdout).not.toContain('9999') expect(readProcessTable).toHaveBeenCalledTimes(2) }) + it('queues past the read cap without retaining timed-out waiters, then hands a stalled pool to ps', async () => { + vi.useFakeTimers() + installAddon({ readProcessTable: vi.fn(() => new Promise(() => {})) }) + const read = (pid: number, timeoutMs = 50) => + runPsInProcess(['-p', String(pid), '-o', 'pid='], { timeoutMs }) + + // Eight distinct reads fill the cap and stall; overflow callers wait on one slot notifier. + const capped = Array.from({ length: 8 }, (_, index) => read(5000 + index, 10_000)) + const overflow = Array.from({ length: 300 }, (_, index) => read(6000 + index)) + expect(nativeReadWaitersForTests()).toBe(300) + await vi.advanceTimersByTimeAsync(50) + expect(nativeReadWaitersForTests()).toBe(0) + expect(await Promise.all(overflow)).toEqual(Array(300).fill(null)) + + // The breaker stays open for its cool-down: callers run ps without queueing. + expect(await read(7000)).toBeNull() + expect(nativeReadWaitersForTests()).toBe(0) + await vi.advanceTimersByTimeAsync(10_000) + expect(await Promise.all(capped)).toEqual( + Array(8).fill(expect.objectContaining({ timedOut: true })) + ) + }) + it('recovers argv for a sudo use_pty tree on its own pty, but not for root daemons or GUI helpers', async () => { const TTYS005 = (16 << 24) | 5 const root = { commandIncomplete: true, flags: 0x2 } diff --git a/src/shared/libproc-process-table.ts b/src/shared/libproc-process-table.ts index c265f96261aa..aa9d6ded58f2 100644 --- a/src/shared/libproc-process-table.ts +++ b/src/shared/libproc-process-table.ts @@ -3,13 +3,15 @@ import { claimDarwinTerminalNaming, darwinTerminalNamingDrained } from './darwin-terminal-naming-single-flight' +import { loadLibprocAddon, type LibprocProcessRow, type LibprocQuery } from './libproc-addon' import { - loadLibprocAddon, - type LibprocAddon, - type LibprocProcessRow, - type LibprocQuery, - type LibprocTableRead -} from './libproc-addon' + DEADLINE_PASSED, + beforeDeadline, + isNativeReaderHealthy, + monotonicNow, + readFreshNativeTable, + registerNativeRequest +} from './libproc-native-reads' import { completeCommands } from './libproc-argv-completion' import { compareLikePs, @@ -27,8 +29,6 @@ export type LibprocPsResult = { stderr: '' timedOut: boolean outputTruncated: boolean - /** When the native read began, never before the request: identity boundaries may rely on it. */ - startedAtMs?: number } export type InProcessPsOptions = { @@ -61,81 +61,6 @@ function lstartZoneIsUtc(env: NodeJS.ProcessEnv): boolean | null { return /^(?:UTC|GMT)0?$/.test(zone) ? true : null } -const DEADLINE_PASSED = Symbol('deadline') - -async function beforeDeadline( - pending: Promise, - deadline: number -): Promise { - let timer: ReturnType | undefined - try { - return await Promise.race([ - pending, - new Promise((resolve) => { - timer = setTimeout(() => resolve(DEADLINE_PASSED), Math.max(0, deadline - Date.now())) - }) - ]) - } finally { - clearTimeout(timer) - } -} - -// Identical reads share one worker; each caller still races its own deadline, so a stalled pool times them all out. -const nativeReadsInFlight = new Map>() -// Workers queued behind a saturated libuv pool would otherwise pile up one per poll. -const MAX_NATIVE_READS_IN_FLIGHT = 8 - -function startNativeRead( - addon: LibprocAddon, - query: LibprocQuery, - key: string -): Promise | null { - if (nativeReadsInFlight.size >= MAX_NATIVE_READS_IN_FLIGHT) { - return null - } - const pending = addon.readProcessTable(query) - nativeReadsInFlight.set(key, pending) - const release = (): void => { - if (nativeReadsInFlight.get(key) === pending) { - nativeReadsInFlight.delete(key) - } - } - pending.then(release, release) - return pending -} - -/** Rows read no earlier than `requestedAtMs`. A shared read that began before this request (an earlier - * poll's abandoned one) is refused: its exited pids may since be reused, and teardown would signal them. */ -async function readNativeTableSince( - addon: LibprocAddon, - query: LibprocQuery, - requestedAtMs: number, - deadline: number -): Promise { - const key = JSON.stringify(query) - for (;;) { - const pending = nativeReadsInFlight.get(key) ?? startNativeRead(addon, query, key) - if (!pending) { - // At the cap (a startup-restore burst, or a stalled pool): queue behind a read instead of bursting ps. - const settled = Promise.race(nativeReadsInFlight.values()).then( - () => {}, - () => {} - ) - if ((await beforeDeadline(settled, deadline)) === DEADLINE_PASSED) { - return DEADLINE_PASSED - } - continue - } - const read = await beforeDeadline(pending, deadline) - if (read === DEADLINE_PASSED || read.startedAtMs >= requestedAtMs) { - return read - } - if (nativeReadsInFlight.get(key) === pending) { - nativeReadsInFlight.delete(key) - } - } -} - /** One naming pass at a time; wait out another (within the deadline) rather than burst /bin/ps at startup restore. */ async function nameTerminals( devices: ReadonlySet, @@ -166,11 +91,11 @@ export async function runPsInProcess( ): Promise { const addon = loadLibprocAddon() const query = addon ? parsePsQuery(args) : null - if (!addon || !query) { + if (!addon || !query || !isNativeReaderHealthy()) { return null } - const requestedAtMs = Date.now() - const deadline = requestedAtMs + options.timeoutMs + const registeredSequence = registerNativeRequest() + const deadline = monotonicNow() + options.timeoutMs const env = options.env ?? process.env const utc = lstartZoneIsUtc(env) const needsLstart = query.columns.includes('lstart') @@ -190,16 +115,17 @@ export async function runPsInProcess( ...(includeCommand ? { ctype } : {}) } let rows: LibprocProcessRow[] | null - let startedAtMs: number let ttyNames: ReadonlyMap = new Map() try { - const read = await readNativeTableSince(addon, nativeQuery, requestedAtMs, deadline) + const read = await readFreshNativeTable(addon, nativeQuery, registeredSequence, deadline) + if (read === 'stalled') { + return null + } if (read === DEADLINE_PASSED) { return TIMED_OUT } - startedAtMs = read.startedAtMs // Shared reads hand every caller the same rows; command completion writes per caller. - rows = read.rows?.map((row) => ({ ...row })) ?? null + rows = read?.map((row) => ({ ...row })) ?? null if (rows && query.columns.includes('tty')) { const devices = new Set( rows.map((row) => formatDarwinDevice(row.tdev)).filter((device) => device !== null) @@ -218,12 +144,12 @@ export async function runPsInProcess( } catch { return null } - if (Date.now() > deadline) { + if (monotonicNow() > deadline) { return TIMED_OUT } // ps exits 1 when -t names no terminal or a -p/-t selection matched nothing. if (rows === null) { - return { ...TIMED_OUT, code: 1, signal: null, timedOut: false, startedAtMs } + return { ...TIMED_OUT, code: 1, signal: null, timedOut: false } } const ttyOf = (row: LibprocProcessRow): string => ttyNames.get(formatDarwinDevice(row.tdev) ?? '') ?? '??' @@ -263,8 +189,7 @@ export async function runPsInProcess( stdout, stderr: '', timedOut: false, - outputTruncated, - startedAtMs + outputTruncated } } From 65987bbb993e4a8ef5da76e397cfc1759215d6aa Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 06:07:16 -0700 Subject: [PATCH 09/13] fix(terminal): keep ps fallbacks off a stuck terminal naming pass (#31783) - captureDarwinProcessTable's canonical fallback, taken while the naming slot is busy, now runs /bin/ps directly instead of re-entering the in-process reader and waiting on that same slot (a held lstat timed out every strict capture without one subprocess fallback). - In-process tty= readers wait out a short pass (startup restore) but hand a pass older than 500ms to ps, which names terminals out of process. - The naming single flight keeps one settle notifier per pass; waiters sit in a Set and drop off on timeout, so timed-out callers leave no reactions on a stuck pass (was one per call). The notifier moves to deadline-settle-notifier.ts, shared with the native read scheduler. - Once the native read breaker has tripped, a caller finding the cap still held after the cool-down returns to ps at once instead of waiting out its timeout. - Descendant teardown and foreground-group signalling give the native read half their budget and fall back to a fresh ps on a native timeout, so a partly stalled pool cannot cost a kill. --- ...pty-descendant-termination-libproc.test.ts | 6 ++ src/main/pty-descendant-termination.ts | 15 ++-- src/main/pty/posix-pty-foreground-group.ts | 24 +++--- src/shared/darwin-process-table-capture.ts | 15 +++- ...rwin-terminal-naming-single-flight.test.ts | 84 +++++++++++++++++++ .../darwin-terminal-naming-single-flight.ts | 44 ++++++++-- src/shared/deadline-settle-notifier.ts | 58 +++++++++++++ src/shared/libproc-argv-completion.ts | 2 +- src/shared/libproc-native-reads.ts | 74 ++++------------ src/shared/libproc-process-table.test.ts | 9 ++ src/shared/libproc-process-table.ts | 19 +++-- src/shared/process-table-snapshot-reader.ts | 4 +- 12 files changed, 256 insertions(+), 98 deletions(-) create mode 100644 src/shared/darwin-terminal-naming-single-flight.test.ts create mode 100644 src/shared/deadline-settle-notifier.ts diff --git a/src/main/pty-descendant-termination-libproc.test.ts b/src/main/pty-descendant-termination-libproc.test.ts index db65ff483a65..454562287b87 100644 --- a/src/main/pty-descendant-termination-libproc.test.ts +++ b/src/main/pty-descendant-termination-libproc.test.ts @@ -1,4 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' + +// A native read that times out falls back to ps; keep that fallback from reading the real host. +vi.mock('node:child_process', () => ({ + execFile: (_file: string, _args: string[], _options: unknown, callback: (error: Error) => void) => + callback(new Error('ps unavailable in this test')) +})) import { setLibprocAddonForTests, type LibprocProcessRow, diff --git a/src/main/pty-descendant-termination.ts b/src/main/pty-descendant-termination.ts index 13c70e93e110..8fa05ec5d28a 100644 --- a/src/main/pty-descendant-termination.ts +++ b/src/main/pty-descendant-termination.ts @@ -6,7 +6,7 @@ import { type WindowsTreeKillTarget } from './windows-pty-root-identity' import { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' -import { readPsStdoutInProcess } from '../shared/libproc-process-table' +import { runPsInProcess } from '../shared/libproc-process-table' export { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' @@ -47,12 +47,15 @@ async function readFreshProcessTable( const capturedAtMs = Date.now() // Pin lstart’s locale so delayed identity checks parse it consistently. const env = { ...process.env, LANG: 'C', LC_ALL: 'C' } - // The in-process reader never serves a scan begun before this stamp (an abandoned earlier one). - const inProcess = await readPsStdoutInProcess(DESCENDANT_PS_ARGS, { env, timeoutMs }) - if (inProcess !== null) { - return { rows: parseProcessTable(inProcess), capturedAtMs } + // Registered now, so no native read submitted before this request can serve it. Half the budget: a read stuck + // behind a busy pool still leaves ps time to find descendants to signal. + const nativeTimeoutMs = Math.floor(timeoutMs / 2) + const inProcess = await runPsInProcess(DESCENDANT_PS_ARGS, { env, timeoutMs: nativeTimeoutMs }) + if (inProcess && !inProcess.timedOut) { + return { rows: parseProcessTable(inProcess.stdout), capturedAtMs } } - const options = { maxBuffer: PS_MAX_BUFFER_BYTES, timeout: timeoutMs, env } + const remainingMs = inProcess ? timeoutMs - nativeTimeoutMs : timeoutMs + const options = { maxBuffer: PS_MAX_BUFFER_BYTES, timeout: remainingMs, env } return new Promise((resolve, reject) => { execFile('ps', DESCENDANT_PS_ARGS, { ...options, killSignal: 'SIGKILL' }, (error, stdout) => error ? reject(error) : resolve({ rows: parseProcessTable(stdout), capturedAtMs }) diff --git a/src/main/pty/posix-pty-foreground-group.ts b/src/main/pty/posix-pty-foreground-group.ts index 9f25327cc468..79e90fc29949 100644 --- a/src/main/pty/posix-pty-foreground-group.ts +++ b/src/main/pty/posix-pty-foreground-group.ts @@ -30,17 +30,21 @@ function hasUsableTty(tty: string): boolean { async function runPs(pid: number): Promise { const args = ['-p', String(pid), '-o', 'pid=,tpgid=,tty='] + // Half the budget in process: a read stuck behind a busy pool still leaves ps time before signalling. + const nativeTimeoutMs = Math.floor(PROCESS_TABLE_QUERY_TIMEOUT_MS / 2) + const inProcess = await runPsInProcess(args, { + timeoutMs: nativeTimeoutMs, + maxOutputBytes: PROCESS_TABLE_MAX_BYTES + }) const result = - (await runPsInProcess(args, { - timeoutMs: PROCESS_TABLE_QUERY_TIMEOUT_MS, - maxOutputBytes: PROCESS_TABLE_MAX_BYTES - })) ?? - (await runProcess({ - program: 'ps', - args, - timeoutMs: PROCESS_TABLE_QUERY_TIMEOUT_MS, - maxOutputBytes: PROCESS_TABLE_MAX_BYTES - })) + inProcess && !inProcess.timedOut + ? inProcess + : await runProcess({ + program: 'ps', + args, + timeoutMs: PROCESS_TABLE_QUERY_TIMEOUT_MS - (inProcess ? nativeTimeoutMs : 0), + maxOutputBytes: PROCESS_TABLE_MAX_BYTES + }) if (result.code !== 0 || result.timedOut || result.outputTruncated) { throw new Error('PTY foreground group is unavailable') } diff --git a/src/shared/darwin-process-table-capture.ts b/src/shared/darwin-process-table-capture.ts index 8dcc924aaccc..1d67a81b5ffd 100644 --- a/src/shared/darwin-process-table-capture.ts +++ b/src/shared/darwin-process-table-capture.ts @@ -11,7 +11,11 @@ import { withTimeout } from './promise-timeout-fallback' let deviceColumnUnsupported = false export async function captureDarwinProcessTable( - capture: (args: readonly string[], timeoutMs?: number) => Promise, + capture: ( + args: readonly string[], + timeoutMs?: number, + /** Skip the in-process reader. */ subprocess?: boolean + ) => Promise, validate: (stdout: string) => string, budgetMs: number ): Promise { @@ -24,7 +28,12 @@ export async function captureDarwinProcessTable( return remaining } const canonicalCapture = (): Promise => capture(PS_ARGS, remainingBudget()) - if (deviceColumnUnsupported || isDarwinTerminalNamingInFlight()) { + // ps names terminals out of process, so a busy naming slot (perhaps a stalled lstat) never blocks it. + const subprocessCapture = (): Promise => capture(PS_ARGS, remainingBudget(), true) + if (isDarwinTerminalNamingInFlight()) { + return subprocessCapture() + } + if (deviceColumnUnsupported) { return canonicalCapture() } let captured: string @@ -52,7 +61,7 @@ export async function captureDarwinProcessTable( nameDarwinTerminals(captured, undefined, controller.signal) ) if (!pending) { - return canonicalCapture() + return subprocessCapture() } let remainingMs: number try { diff --git a/src/shared/darwin-terminal-naming-single-flight.test.ts b/src/shared/darwin-terminal-naming-single-flight.test.ts new file mode 100644 index 000000000000..6c19b73aafa0 --- /dev/null +++ b/src/shared/darwin-terminal-naming-single-flight.test.ts @@ -0,0 +1,84 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { captureDarwinProcessTable } from './darwin-process-table-capture' +import { + DARWIN_TERMINAL_NAMING_STALL_MS, + claimDarwinTerminalNaming, + resetDarwinTerminalNamingForTests, + waitForDarwinTerminalNaming +} from './darwin-terminal-naming-single-flight' +import { monotonicNow } from './deadline-settle-notifier' +import { setLibprocAddonForTests, type LibprocProcessRow } from './libproc-addon' +import { resetNativeReadsForTests } from './libproc-native-reads' +import { runPsInProcess } from './libproc-process-table' +import { PS_ARGS } from './process-table-snapshot' + +const ROW: LibprocProcessRow = { + pid: 4300, + ppid: 1, + pgid: 4300, + tpgid: 4300, + tdev: (16 << 24) | 4, + status: 3, + flags: 0x2, + sessionLeader: false, + startSec: 0, + comm: 'zsh' +} + +/** A naming pass stuck in an lstat that never returns; the spy counts reactions attached to it. */ +function holdNamingSlot() { + const held = new Promise(() => {}) + const reactions = vi.spyOn(held, 'then') + expect(claimDarwinTerminalNaming(() => held)).toBe(held) + return reactions +} + +beforeEach(() => { + vi.useFakeTimers() + resetDarwinTerminalNamingForTests() + resetNativeReadsForTests() +}) +afterEach(() => { + setLibprocAddonForTests(undefined) + vi.useRealTimers() +}) + +describe('terminal naming single flight', () => { + it('sends canonical captures straight to ps while a naming pass is stuck', async () => { + holdNamingSlot() + const capture = vi.fn(async () => 'canonical') + for (let attempt = 0; attempt < 3; attempt += 1) { + expect(await captureDarwinProcessTable(capture, (stdout) => stdout, 1_000)).toBe('canonical') + } + expect(capture.mock.calls).toEqual( + Array.from({ length: 3 }, () => [PS_ARGS, expect.any(Number), true]) + ) + }) + + it('hands in-process tty= readers to ps once the pass outlives the stall threshold', async () => { + holdNamingSlot() + setLibprocAddonForTests({ + readProcessTable: async () => [ROW], + processCwd: () => null, + processPath: () => null + }) + const args = ['-p', '4300', '-o', 'pid=,tty='] + + const waiting = runPsInProcess(args, { timeoutMs: 5_000 }) + await vi.advanceTimersByTimeAsync(DARWIN_TERMINAL_NAMING_STALL_MS) + expect(await waiting).toBeNull() + expect(await runPsInProcess(args, { timeoutMs: 5_000 })).toBeNull() + }) + + it('keeps one reaction on a stuck pass however many waiters time out', async () => { + const reactions = holdNamingSlot() + const waits = Array.from({ length: 300 }, () => + waitForDarwinTerminalNaming(monotonicNow() + 10) + ) + await vi.advanceTimersByTimeAsync(10) + await Promise.all(waits) + // The notifier's and the slot release's. + expect(reactions).toHaveBeenCalledTimes(2) + expect(vi.getTimerCount()).toBe(0) + }) +}) diff --git a/src/shared/darwin-terminal-naming-single-flight.ts b/src/shared/darwin-terminal-naming-single-flight.ts index e2bf940d9757..c1429ac0d3c0 100644 --- a/src/shared/darwin-terminal-naming-single-flight.ts +++ b/src/shared/darwin-terminal-naming-single-flight.ts @@ -1,4 +1,19 @@ -let namingInFlight: Promise | null = null +import { + DEADLINE_PASSED, + createSettleNotifier, + monotonicNow, + type Settled +} from './deadline-settle-notifier' + +type NamingPass = { + claimedAtMs: number + /** One reaction on the pass; waiters subscribe with their deadline and drop off when it lapses. */ + drained: (deadline: number) => Promise | typeof DEADLINE_PASSED> +} + +let namingInFlight: NamingPass | null = null +// A pass normally takes milliseconds; one held this long is stuck in an lstat/opendir, so callers use ps instead. +export const DARWIN_TERMINAL_NAMING_STALL_MS = 500 /** One /dev naming pass at a time: aborted lstat/opendir calls hold libuv pool threads until they drain. Null while one drains. */ export function claimDarwinTerminalNaming(name: () => Promise): Promise | null { @@ -6,9 +21,10 @@ export function claimDarwinTerminalNaming(name: () => Promise): Promise return null } const pending = name() - namingInFlight = pending + const pass: NamingPass = { claimedAtMs: monotonicNow(), drained: createSettleNotifier(pending) } + namingInFlight = pass const release = (): void => { - if (namingInFlight === pending) { + if (namingInFlight === pass) { namingInFlight = null } } @@ -16,12 +32,22 @@ export function claimDarwinTerminalNaming(name: () => Promise): Promise return pending } -/** Settles once the in-flight pass drains, whatever its outcome. */ -export function darwinTerminalNamingDrained(): Promise { - return (namingInFlight ?? Promise.resolve()).then( - () => {}, - () => {} - ) +/** Wait for the in-flight pass to drain: 'stalled' once it has run past the stall threshold, so callers run ps. */ +export async function waitForDarwinTerminalNaming( + deadline: number +): Promise<'drained' | 'stalled' | typeof DEADLINE_PASSED> { + const pass = namingInFlight + if (!pass) { + return 'drained' + } + const stallAt = pass.claimedAtMs + DARWIN_TERMINAL_NAMING_STALL_MS + if (monotonicNow() >= stallAt) { + return 'stalled' + } + if ((await pass.drained(Math.min(deadline, stallAt))) !== DEADLINE_PASSED) { + return 'drained' + } + return monotonicNow() >= deadline ? DEADLINE_PASSED : 'stalled' } export function isDarwinTerminalNamingInFlight(): boolean { diff --git a/src/shared/deadline-settle-notifier.ts b/src/shared/deadline-settle-notifier.ts new file mode 100644 index 000000000000..a06593c7514c --- /dev/null +++ b/src/shared/deadline-settle-notifier.ts @@ -0,0 +1,58 @@ +/** Deadlines run on the monotonic clock: a wall-clock step must neither extend nor cut a caller's budget. */ +export function monotonicNow(): number { + return performance.now() +} + +export const DEADLINE_PASSED = Symbol('deadline') + +export type Settled = { ok: true; value: T } | { ok: false; error: unknown } + +/** One reaction on the shared promise; each caller subscribes with its own deadline and unsubscribes when it lapses. */ +export function createSettleNotifier( + promise: Promise +): (deadline: number) => Promise | typeof DEADLINE_PASSED> { + const waiters = new Set<(settled: Settled) => void>() + let result: Settled | undefined + const settle = (settled: Settled): void => { + result = settled + for (const waiter of waiters) { + waiter(settled) + } + waiters.clear() + } + promise.then( + (value) => settle({ ok: true, value }), + (error: unknown) => settle({ ok: false, error }) + ) + return (deadline) => + result + ? Promise.resolve(result) + : new Promise((resolve) => { + const waiter = (settled: Settled): void => { + clearTimeout(timer) + resolve(settled) + } + waiters.add(waiter) + const timer = setTimeout( + () => { + waiters.delete(waiter) + resolve(DEADLINE_PASSED) + }, + Math.max(0, deadline - monotonicNow()) + ) + }) +} + +export async function beforeDeadline( + pending: Promise, + deadline: number +): Promise { + const settled = await createSettleNotifier(pending)(deadline) + if (settled === DEADLINE_PASSED) { + return DEADLINE_PASSED + } + if (!settled.ok) { + throw settled.error + } + return settled.value +} diff --git a/src/shared/libproc-argv-completion.ts b/src/shared/libproc-argv-completion.ts index 5ceb62c811a6..57f7df54af6d 100644 --- a/src/shared/libproc-argv-completion.ts +++ b/src/shared/libproc-argv-completion.ts @@ -1,6 +1,6 @@ import { runProcess } from '@orca/process-host' import type { LibprocProcessRow } from './libproc-addon' -import { monotonicNow } from './libproc-native-reads' +import { monotonicNow } from './deadline-settle-notifier' import { NODEV } from './libproc-ps-format' const SZOMB_STATUS = 5 diff --git a/src/shared/libproc-native-reads.ts b/src/shared/libproc-native-reads.ts index b2d6f65e0b49..cbaffa8fec44 100644 --- a/src/shared/libproc-native-reads.ts +++ b/src/shared/libproc-native-reads.ts @@ -1,64 +1,11 @@ +import { + DEADLINE_PASSED, + createSettleNotifier, + monotonicNow, + type Settled +} from './deadline-settle-notifier' import type { LibprocAddon, LibprocProcessRow, LibprocQuery } from './libproc-addon' -/** Deadlines run on the monotonic clock: a wall-clock step must neither extend nor cut a caller's budget. */ -export function monotonicNow(): number { - return performance.now() -} - -export const DEADLINE_PASSED = Symbol('deadline') - -type Settled = { ok: true; value: T } | { ok: false; error: unknown } - -/** One reaction on the shared promise; each caller subscribes with its own deadline and unsubscribes when it lapses. */ -function createSettleNotifier( - promise: Promise -): (deadline: number) => Promise | typeof DEADLINE_PASSED> { - const waiters = new Set<(settled: Settled) => void>() - let result: Settled | undefined - const settle = (settled: Settled): void => { - result = settled - for (const waiter of waiters) { - waiter(settled) - } - waiters.clear() - } - promise.then( - (value) => settle({ ok: true, value }), - (error: unknown) => settle({ ok: false, error }) - ) - return (deadline) => - result - ? Promise.resolve(result) - : new Promise((resolve) => { - const waiter = (settled: Settled): void => { - clearTimeout(timer) - resolve(settled) - } - waiters.add(waiter) - const timer = setTimeout( - () => { - waiters.delete(waiter) - resolve(DEADLINE_PASSED) - }, - Math.max(0, deadline - monotonicNow()) - ) - }) -} - -export async function beforeDeadline( - pending: Promise, - deadline: number -): Promise { - const settled = await createSettleNotifier(pending)(deadline) - if (settled === DEADLINE_PASSED) { - return DEADLINE_PASSED - } - if (!settled.ok) { - throw settled.error - } - return settled.value -} - type NativeRead = { /** Creation order; once submitted, a read serves only callers registered before it was created. */ sequence: number @@ -77,6 +24,8 @@ const slotWaiters = new Set<() => void>() // A pool pinned at the cap past a caller's whole deadline is stalled: hand callers back to ps for a while. const STALLED_POOL_COOL_DOWN_MS = 30_000 let unhealthyUntil = Number.NEGATIVE_INFINITY +// Set when the cap outlived a caller's deadline; cleared once any read settles. +let poolStalled = false export function isNativeReaderHealthy(): boolean { return monotonicNow() >= unhealthyUntil @@ -111,6 +60,7 @@ function submitRead(addon: LibprocAddon, query: LibprocQuery, key: string): Nati sharedReads.set(key, read) const release = (): void => { outstandingReads -= 1 + poolStalled = false if (sharedReads.get(key) === read) { sharedReads.delete(key) } @@ -155,10 +105,15 @@ export async function readFreshNativeTable( read = shared } else if (outstandingReads < MAX_OUTSTANDING_READS) { read = submitRead(addon, query, key) + } else if (poolStalled) { + // Cool-down over but the stalled reads still hold the cap: no caller should wait its timeout to learn that. + unhealthyUntil = monotonicNow() + STALLED_POOL_COOL_DOWN_MS + return 'stalled' } else { // Queue behind the cap (a startup-restore burst) instead of bursting ps. if (!(await waitForSlot(deadline))) { if (outstandingReads >= MAX_OUTSTANDING_READS) { + poolStalled = true unhealthyUntil = monotonicNow() + STALLED_POOL_COOL_DOWN_MS console.warn('[process-table] libuv pool stalled; using ps for 30s') return 'stalled' @@ -186,5 +141,6 @@ export function resetNativeReadsForTests(): void { sharedReads.clear() slotWaiters.clear() outstandingReads = 0 + poolStalled = false unhealthyUntil = Number.NEGATIVE_INFINITY } diff --git a/src/shared/libproc-process-table.test.ts b/src/shared/libproc-process-table.test.ts index fab2c1ab4eeb..59e8657db732 100644 --- a/src/shared/libproc-process-table.test.ts +++ b/src/shared/libproc-process-table.test.ts @@ -299,6 +299,15 @@ describe('runPsInProcess', () => { expect(await Promise.all(capped)).toEqual( Array(8).fill(expect.objectContaining({ timedOut: true })) ) + + // Past the cool-down with the cap still held, callers learn it at once instead of after their timeout. + await vi.advanceTimersByTimeAsync(30_000) + let settled: unknown = 'pending' + void read(8000, 5_000).then((result) => { + settled = result + }) + await vi.advanceTimersByTimeAsync(0) + expect(settled).toBeNull() }) it('recovers argv for a sudo use_pty tree on its own pty, but not for root daemons or GUI helpers', async () => { diff --git a/src/shared/libproc-process-table.ts b/src/shared/libproc-process-table.ts index aa9d6ded58f2..0e8612e81055 100644 --- a/src/shared/libproc-process-table.ts +++ b/src/shared/libproc-process-table.ts @@ -1,14 +1,12 @@ import { nameDarwinTerminalDevices } from './darwin-terminal-names' import { claimDarwinTerminalNaming, - darwinTerminalNamingDrained + waitForDarwinTerminalNaming } from './darwin-terminal-naming-single-flight' import { loadLibprocAddon, type LibprocProcessRow, type LibprocQuery } from './libproc-addon' +import { DEADLINE_PASSED, beforeDeadline, monotonicNow } from './deadline-settle-notifier' import { - DEADLINE_PASSED, - beforeDeadline, isNativeReaderHealthy, - monotonicNow, readFreshNativeTable, registerNativeRequest } from './libproc-native-reads' @@ -61,11 +59,12 @@ function lstartZoneIsUtc(env: NodeJS.ProcessEnv): boolean | null { return /^(?:UTC|GMT)0?$/.test(zone) ? true : null } -/** One naming pass at a time; wait out another (within the deadline) rather than burst /bin/ps at startup restore. */ +/** One naming pass at a time: wait out a short one (startup restore) rather than burst /bin/ps; a stalled one + * returns 'stalled' so the caller runs ps, which names terminals out of process. */ async function nameTerminals( devices: ReadonlySet, deadline: number -): Promise | typeof DEADLINE_PASSED> { +): Promise | typeof DEADLINE_PASSED | 'stalled'> { for (;;) { const controller = new AbortController() const naming = claimDarwinTerminalNaming(() => @@ -78,8 +77,9 @@ async function nameTerminals( } return named } - if ((await beforeDeadline(darwinTerminalNamingDrained(), deadline)) === DEADLINE_PASSED) { - return DEADLINE_PASSED + const waited = await waitForDarwinTerminalNaming(deadline) + if (waited !== 'drained') { + return waited } } } @@ -132,6 +132,9 @@ export async function runPsInProcess( ) if (devices.size > 0) { const named = await nameTerminals(devices, deadline) + if (named === 'stalled') { + return null + } if (named === DEADLINE_PASSED) { return TIMED_OUT } diff --git a/src/shared/process-table-snapshot-reader.ts b/src/shared/process-table-snapshot-reader.ts index 1339f44b2eb4..2233156d01f0 100644 --- a/src/shared/process-table-snapshot-reader.ts +++ b/src/shared/process-table-snapshot-reader.ts @@ -243,9 +243,9 @@ async function readLinuxProcessStartTimes( return new Map(starts.filter((entry) => entry !== null)) } -async function captureProcessTable(args: readonly string[], timeout = PS_TIMEOUT_MS) { +async function captureProcessTable(args: readonly string[], timeout = PS_TIMEOUT_MS, ps = false) { const env = psLocaleEnvironment() - let stdout = await readPsStdoutInProcess(args, { env, timeoutMs: timeout }) + let stdout = ps ? null : await readPsStdoutInProcess(args, { env, timeoutMs: timeout }) try { stdout ??= ( await execFile('ps', [...args], { From 165c987d74fcb492c9862b9310c500951d45725c Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 06:43:22 -0700 Subject: [PATCH 10/13] fix(terminal): give signalling ps fallbacks their full baseline timeout (#31783) Splitting the budget in half shrank ps's window behind a stalled native read: a 750ms ps lost descendant SIGTERMs and an 80ms foreground ps lost group SIGWINCH. Descendant teardown and foreground-group signalling now try the native reader for min(150ms, timeout/4) (inProcessSliceMs), then give ps the whole original timeout; readProcessTableBeforeDeadline extends the production reader's outer deadline by that slice, so ps succeeds exactly when it did on main. The stale-read regression test now also asserts the fresh rows' real descendant is signalled. --- ...pty-descendant-termination-libproc.test.ts | 63 +++++++++++-- src/main/pty-descendant-termination.ts | 18 ++-- ...posix-pty-foreground-group-libproc.test.ts | 90 +++++++++++++++++++ src/main/pty/posix-pty-foreground-group.ts | 9 +- src/shared/libproc-process-table.ts | 6 ++ 5 files changed, 166 insertions(+), 20 deletions(-) create mode 100644 src/main/pty/posix-pty-foreground-group-libproc.test.ts diff --git a/src/main/pty-descendant-termination-libproc.test.ts b/src/main/pty-descendant-termination-libproc.test.ts index 454562287b87..446dce1b59ed 100644 --- a/src/main/pty-descendant-termination-libproc.test.ts +++ b/src/main/pty-descendant-termination-libproc.test.ts @@ -1,10 +1,19 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -// A native read that times out falls back to ps; keep that fallback from reading the real host. -vi.mock('node:child_process', () => ({ - execFile: (_file: string, _args: string[], _options: unknown, callback: (error: Error) => void) => - callback(new Error('ps unavailable in this test')) +type ExecFileCallback = (error: Error | null, stdout?: string) => void +const { execFile } = vi.hoisted(() => ({ + execFile: + vi.fn< + ( + file: string, + args: string[], + options: { timeout: number }, + callback: ExecFileCallback + ) => void + >() })) +// A native read that times out falls back to ps; keep that fallback from reading the real host. +vi.mock('node:child_process', () => ({ execFile })) import { setLibprocAddonForTests, type LibprocProcessRow, @@ -31,7 +40,17 @@ function row(pid: number, ppid: number): LibprocProcessRow { } } +/** ps `lstart` in the C locale and UTC, as the descendant reader's env pins it. */ +const LSTART = 'Thu Sep 3 16:02:01 2026' + +beforeEach(() => { + execFile.mockImplementation((_file, _args, _options, callback) => + callback(new Error('ps unavailable in this test')) + ) +}) + afterEach(() => { + execFile.mockReset() setLibprocAddonForTests(undefined) resetNativeReadsForTests() vi.useRealTimers() @@ -57,7 +76,7 @@ describe('descendant teardown over the in-process process table', () => { .fn<(query: LibprocQuery) => Promise>() .mockReturnValueOnce(abandoned) // Since that read was submitted, descendant 200 exited and an unrelated process took its pid. - .mockImplementation(async () => [row(1, 0), row(100, 1), row(200, 1)]) + .mockImplementation(async () => [row(1, 0), row(100, 1), row(200, 1), row(300, 100)]) setLibprocAddonForTests({ readProcessTable, processCwd: () => null, @@ -77,8 +96,38 @@ describe('descendant teardown over the in-process process table', () => { await teardown expect(killRoot).toHaveBeenCalledOnce() - expect(sendSignal).not.toHaveBeenCalled() + // The fresh rows were used: their real descendant is signalled, the reused pid is not. + expect(sendSignal.mock.calls).toEqual([[300, 'SIGTERM']]) expect(readProcessTable).toHaveBeenCalledTimes(2) } ) + + it('gives a slow ps its whole timeout when the native read is stalled', async () => { + vi.useFakeTimers() + setLibprocAddonForTests({ + readProcessTable: () => new Promise(() => {}), + processCwd: () => null, + processPath: () => null + }) + // A 750ms ps, killed at its timeout like execFile. + execFile.mockImplementation((_file, _args, { timeout }, callback) => { + const done = setTimeout(() => { + clearTimeout(killed) + callback(null, ` 100 1 100 0 ${LSTART}\n 200 100 200 0 ${LSTART}\n`) + }, 750) + const killed = setTimeout(() => { + clearTimeout(done) + callback(new Error('ps timed out')) + }, timeout) + }) + const sendSignal = vi.fn() + const killRoot = vi.fn() + + const teardown = killWithDescendantSweep(100, killRoot, { sendSignal, graceMs: 60_000 }) + await vi.advanceTimersByTimeAsync(2_000) + await teardown + + expect(killRoot).toHaveBeenCalledOnce() + expect(sendSignal.mock.calls).toEqual([[200, 'SIGTERM']]) + }) }) diff --git a/src/main/pty-descendant-termination.ts b/src/main/pty-descendant-termination.ts index 8fa05ec5d28a..79aa48d4aa61 100644 --- a/src/main/pty-descendant-termination.ts +++ b/src/main/pty-descendant-termination.ts @@ -6,7 +6,7 @@ import { type WindowsTreeKillTarget } from './windows-pty-root-identity' import { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' -import { runPsInProcess } from '../shared/libproc-process-table' +import { inProcessSliceMs, runPsInProcess } from '../shared/libproc-process-table' export { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' @@ -47,15 +47,15 @@ async function readFreshProcessTable( const capturedAtMs = Date.now() // Pin lstart’s locale so delayed identity checks parse it consistently. const env = { ...process.env, LANG: 'C', LC_ALL: 'C' } - // Registered now, so no native read submitted before this request can serve it. Half the budget: a read stuck - // behind a busy pool still leaves ps time to find descendants to signal. - const nativeTimeoutMs = Math.floor(timeoutMs / 2) - const inProcess = await runPsInProcess(DESCENDANT_PS_ARGS, { env, timeoutMs: nativeTimeoutMs }) + // Registered now, so no native read submitted before this request serves it; a stalled one leaves ps its full timeout. + const inProcess = await runPsInProcess(DESCENDANT_PS_ARGS, { + env, + timeoutMs: inProcessSliceMs(timeoutMs) + }) if (inProcess && !inProcess.timedOut) { return { rows: parseProcessTable(inProcess.stdout), capturedAtMs } } - const remainingMs = inProcess ? timeoutMs - nativeTimeoutMs : timeoutMs - const options = { maxBuffer: PS_MAX_BUFFER_BYTES, timeout: remainingMs, env } + const options = { maxBuffer: PS_MAX_BUFFER_BYTES, timeout: timeoutMs, env } return new Promise((resolve, reject) => { execFile('ps', DESCENDANT_PS_ARGS, { ...options, killSignal: 'SIGKILL' }, (error, stdout) => error ? reject(error) : resolve({ rows: parseProcessTable(stdout), capturedAtMs }) @@ -110,7 +110,9 @@ export function readProcessTableBeforeDeadline( clearTimeout(timer) resolve(capture) } - const timer = setTimeout(() => finish(null), timeoutMs) + // The production reader may spend inProcessSliceMs in process before giving ps the whole timeout. + const slackMs = readTable === readProcessTable ? inProcessSliceMs(timeoutMs) : 0 + const timer = setTimeout(() => finish(null), timeoutMs + slackMs) timer.unref?.() try { void readTable(timeoutMs).then( diff --git a/src/main/pty/posix-pty-foreground-group-libproc.test.ts b/src/main/pty/posix-pty-foreground-group-libproc.test.ts new file mode 100644 index 000000000000..fd222f48b91f --- /dev/null +++ b/src/main/pty/posix-pty-foreground-group-libproc.test.ts @@ -0,0 +1,90 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { runProcess } = vi.hoisted(() => ({ runProcess: vi.fn() })) +vi.mock('@orca/process-host', () => ({ runProcess })) + +import { + claimDarwinTerminalNaming, + resetDarwinTerminalNamingForTests +} from '../../shared/darwin-terminal-naming-single-flight' +import { setLibprocAddonForTests, type LibprocProcessRow } from '../../shared/libproc-addon' +import { resetNativeReadsForTests } from '../../shared/libproc-native-reads' +import { + resetPosixPtyForegroundGroupOwnRowCache, + signalPosixPtyForegroundGroup +} from './posix-pty-foreground-group' + +const ROOT_PID = 4200 +const CURRENT_PID = 900 +const FOREGROUND_PGID = 4300 + +function row(pid: number): LibprocProcessRow { + return { + pid, + ppid: 1, + pgid: pid, + tpgid: FOREGROUND_PGID, + tdev: (16 << 24) | 4, + status: 3, + flags: 0x2, + sessionLeader: false, + startSec: 0, + comm: 'zsh' + } +} + +beforeEach(() => { + vi.useFakeTimers() + resetDarwinTerminalNamingForTests() + resetNativeReadsForTests() + resetPosixPtyForegroundGroupOwnRowCache() +}) +afterEach(() => { + setLibprocAddonForTests(undefined) + runProcess.mockReset() + vi.restoreAllMocks() + vi.useRealTimers() +}) + +describe('foreground group signalling over the in-process reader', () => { + it('gives an 80ms ps its whole timeout while a terminal naming pass is held', async () => { + setLibprocAddonForTests({ + readProcessTable: async () => [row(ROOT_PID)], + processCwd: () => null, + processPath: () => null + }) + claimDarwinTerminalNaming(() => new Promise(() => {})) + // An 80ms ps, killed at its timeout like process-host's runProcess. + runProcess.mockImplementation( + ({ args, timeoutMs }: { args: string[]; timeoutMs: number }) => + new Promise((resolve) => { + const pid = Number(args[1]) + const stdout = + pid === ROOT_PID ? `${ROOT_PID} ${FOREGROUND_PGID} ttys004\n` : `${pid} 0 ??\n` + const done = setTimeout(() => { + clearTimeout(killed) + resolve({ code: 0, signal: null, stdout, stderr: '', timedOut: false }) + }, 80) + const killed = setTimeout(() => { + clearTimeout(done) + resolve({ code: null, signal: 'SIGTERM', stdout: '', stderr: '', timedOut: true }) + }, timeoutMs) + }) + ) + const kill = vi.spyOn(process, 'kill').mockReturnValue(true) + const fallback = vi.fn() + + const signalled = signalPosixPtyForegroundGroup( + ROOT_PID, + '/dev/ttys004', + 'SIGWINCH', + fallback, + { platform: 'darwin', currentPid: CURRENT_PID } + ) + await vi.advanceTimersByTimeAsync(1_000) + await signalled + + expect(fallback).not.toHaveBeenCalled() + expect(kill).toHaveBeenCalledWith(-FOREGROUND_PGID, 'SIGWINCH') + }) +}) diff --git a/src/main/pty/posix-pty-foreground-group.ts b/src/main/pty/posix-pty-foreground-group.ts index 79e90fc29949..77f8c7526cab 100644 --- a/src/main/pty/posix-pty-foreground-group.ts +++ b/src/main/pty/posix-pty-foreground-group.ts @@ -1,5 +1,5 @@ import { runProcess } from '@orca/process-host' -import { runPsInProcess } from '../../shared/libproc-process-table' +import { inProcessSliceMs, runPsInProcess } from '../../shared/libproc-process-table' const PROCESS_TABLE_LOOKUP_TIMEOUT_MS = 250 const PROCESS_TABLE_QUERY_TIMEOUT_MS = PROCESS_TABLE_LOOKUP_TIMEOUT_MS / 2 @@ -30,10 +30,9 @@ function hasUsableTty(tty: string): boolean { async function runPs(pid: number): Promise { const args = ['-p', String(pid), '-o', 'pid=,tpgid=,tty='] - // Half the budget in process: a read stuck behind a busy pool still leaves ps time before signalling. - const nativeTimeoutMs = Math.floor(PROCESS_TABLE_QUERY_TIMEOUT_MS / 2) + // A native read stuck behind a busy pool leaves ps its full timeout before signalling. const inProcess = await runPsInProcess(args, { - timeoutMs: nativeTimeoutMs, + timeoutMs: inProcessSliceMs(PROCESS_TABLE_QUERY_TIMEOUT_MS), maxOutputBytes: PROCESS_TABLE_MAX_BYTES }) const result = @@ -42,7 +41,7 @@ async function runPs(pid: number): Promise { : await runProcess({ program: 'ps', args, - timeoutMs: PROCESS_TABLE_QUERY_TIMEOUT_MS - (inProcess ? nativeTimeoutMs : 0), + timeoutMs: PROCESS_TABLE_QUERY_TIMEOUT_MS, maxOutputBytes: PROCESS_TABLE_MAX_BYTES }) if (result.code !== 0 || result.timedOut || result.outputTruncated) { diff --git a/src/shared/libproc-process-table.ts b/src/shared/libproc-process-table.ts index 0e8612e81055..247fa967504b 100644 --- a/src/shared/libproc-process-table.ts +++ b/src/shared/libproc-process-table.ts @@ -84,6 +84,12 @@ async function nameTerminals( } } +/** Native reads take milliseconds: a signalling caller tries them for this slice, then gives ps its whole + * original timeout (extending any outer deadline by the slice), so a slow ps succeeds exactly as before. */ +export function inProcessSliceMs(timeoutMs: number): number { + return Math.min(150, Math.floor(timeoutMs / 4)) +} + /** ps output for `args`, read in process; null when the addon or the invocation is unsupported so callers run ps. */ export async function runPsInProcess( args: readonly string[], From f7b289ac09358154a6847b84d9fbac4a93d392a7 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 07:27:38 -0700 Subject: [PATCH 11/13] fix(terminal): carry the in-process deadline allowance through every descendant reader (#31783) readProcessTableBeforeDeadline granted the native slice only when the reader was readProcessTable by identity, so the daemon shutdown sweep's sharing wrapper kept a bare 250ms deadline: a stalled native read plus a 200ms ps missed it on every retry and descendants survived shutdown. ProcessTableReader now declares deadlineAllowanceMs; the fresh reader sets it (0 without the addon or with a stalled pool, so Linux and ps-only hosts keep their exact deadlines), createProcessTableSnapshotReader and the shutdown wrapper inherit it, and injected readers default to none. The fresh reader moves to pty-descendant-fresh-table.ts. The real-ps parity test gets a 30s per-case timeout, since whole-table /bin/ps runs slow under suite load. --- ...rminal-descendant-shutdown-libproc.test.ts | 66 +++++++++++++++++++ .../daemon/terminal-descendant-shutdown.ts | 3 + src/main/pty-descendant-fresh-table.ts | 52 +++++++++++++++ src/main/pty-descendant-termination.ts | 63 ++++++------------ .../libproc-process-table-real-ps.test.ts | 2 + src/shared/libproc-process-table.ts | 5 ++ 6 files changed, 149 insertions(+), 42 deletions(-) create mode 100644 src/main/daemon/terminal-descendant-shutdown-libproc.test.ts create mode 100644 src/main/pty-descendant-fresh-table.ts diff --git a/src/main/daemon/terminal-descendant-shutdown-libproc.test.ts b/src/main/daemon/terminal-descendant-shutdown-libproc.test.ts new file mode 100644 index 000000000000..92d1798e648c --- /dev/null +++ b/src/main/daemon/terminal-descendant-shutdown-libproc.test.ts @@ -0,0 +1,66 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +type ExecFileCallback = (error: Error | null, stdout?: string) => void +const { execFile } = vi.hoisted(() => ({ + execFile: + vi.fn< + ( + file: string, + args: string[], + options: { timeout: number }, + callback: ExecFileCallback + ) => void + >() +})) +vi.mock('node:child_process', () => ({ execFile })) + +import { setLibprocAddonForTests } from '../../shared/libproc-addon' +import { resetNativeReadsForTests } from '../../shared/libproc-native-reads' +import { collectDescendantRows, parseProcessTable } from '../pty-descendant-termination' +import { terminateShutdownDescendants } from './terminal-descendant-shutdown' + +const STARTED = 'Mon Jul 13 12:54:47 2026' +const PS_OUTPUT = ` 100 1 100 0 ${STARTED}\n 200 100 100 0 ${STARTED}\n` + +beforeEach(() => { + vi.useFakeTimers() + resetNativeReadsForTests() + // A stalled libuv pool: native reads never finish. + setLibprocAddonForTests({ + readProcessTable: () => new Promise(() => {}), + processCwd: () => null, + processPath: () => null + }) + // A 200ms ps, killed at its timeout like execFile. + execFile.mockImplementation((_file, _args, { timeout }, callback) => { + const done = setTimeout(() => { + clearTimeout(killed) + callback(null, PS_OUTPUT) + }, 200) + const killed = setTimeout(() => { + clearTimeout(done) + callback(new Error('ps timed out')) + }, timeout) + }) +}) +afterEach(() => { + execFile.mockReset() + setLibprocAddonForTests(undefined) + vi.restoreAllMocks() + vi.useRealTimers() +}) + +describe('terminal shutdown descendant sweep over a stalled native reader', () => { + it('still terminates then kills a surviving descendant through a 200ms ps', async () => { + const kill = vi.spyOn(process, 'kill').mockReturnValue(true) + const snapshot = collectDescendantRows(100, parseProcessTable(PS_OUTPUT), Date.now()) + + const verdict = terminateShutdownDescendants(snapshot) + await vi.advanceTimersByTimeAsync(4_000) + await verdict + + const signals = kill.mock.calls.filter(([pid]) => pid === 200).map(([, signal]) => signal) + expect(signals[0]).toBe('SIGTERM') + expect(signals).toContain('SIGKILL') + }) +}) diff --git a/src/main/daemon/terminal-descendant-shutdown.ts b/src/main/daemon/terminal-descendant-shutdown.ts index cd8eb07de66f..dce400db855b 100644 --- a/src/main/daemon/terminal-descendant-shutdown.ts +++ b/src/main/daemon/terminal-descendant-shutdown.ts @@ -35,6 +35,9 @@ const readShutdownProcessTable: ProcessTableReader = (timeoutMs) => { }, clear) return promise } +// Wrapping the production reader keeps its in-process allowance, so a stalled native read still leaves ps the whole window. +readShutdownProcessTable.deadlineAllowanceMs = (timeoutMs) => + descendantTermination.readProcessTable.deadlineAllowanceMs?.(timeoutMs) ?? 0 export function terminateShutdownDescendants( snapshot: DescendantSnapshot diff --git a/src/main/pty-descendant-fresh-table.ts b/src/main/pty-descendant-fresh-table.ts new file mode 100644 index 000000000000..0248d51bd1bd --- /dev/null +++ b/src/main/pty-descendant-fresh-table.ts @@ -0,0 +1,52 @@ +import { execFile } from 'node:child_process' +import { + inProcessDeadlineAllowanceMs, + inProcessSliceMs, + runPsInProcess +} from '../shared/libproc-process-table' +import { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' + +export const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000 +// Busy hosts can exceed execFile’s 1MB default; truncated output would omit descendants. +const PS_MAX_BUFFER_BYTES = 32 * 1024 * 1024 + +export type ProcessTableCapture = { + rows: ProcessTableRow[] + /** Start boundary of the scan that produced rows, never a later consumer's time. */ + capturedAtMs: number +} + +export type ProcessTableReader = { + (timeoutMs?: number): Promise + /** Time the reader may spend in process before giving ps its whole timeout; outer deadlines add it. Absent: none. */ + deadlineAllowanceMs?: (timeoutMs: number) => number +} + +const DESCENDANT_PS_ARGS = ['-axo', 'pid=,ppid=,pgid=,tpgid=,lstart='] + +export const readFreshProcessTable: ProcessTableReader = Object.assign(readFreshProcessTableOnce, { + deadlineAllowanceMs: inProcessDeadlineAllowanceMs +}) + +async function readFreshProcessTableOnce( + timeoutMs = DESCENDANT_SNAPSHOT_TIMEOUT_MS +): Promise { + // Stamp before ps starts so a capture-second PID cannot appear older after a clock rollover. + const capturedAtMs = Date.now() + // Pin lstart’s locale so delayed identity checks parse it consistently. + const env = { ...process.env, LANG: 'C', LC_ALL: 'C' } + // Registered now, so no native read submitted before this request serves it; a stalled one leaves ps its full timeout. + const inProcess = await runPsInProcess(DESCENDANT_PS_ARGS, { + env, + timeoutMs: inProcessSliceMs(timeoutMs) + }) + if (inProcess && !inProcess.timedOut) { + return { rows: parseProcessTable(inProcess.stdout), capturedAtMs } + } + const options = { maxBuffer: PS_MAX_BUFFER_BYTES, timeout: timeoutMs, env } + return new Promise((resolve, reject) => { + execFile('ps', DESCENDANT_PS_ARGS, { ...options, killSignal: 'SIGKILL' }, (error, stdout) => + error ? reject(error) : resolve({ rows: parseProcessTable(stdout), capturedAtMs }) + ) + }) +} diff --git a/src/main/pty-descendant-termination.ts b/src/main/pty-descendant-termination.ts index 79aa48d4aa61..f623a32ae931 100644 --- a/src/main/pty-descendant-termination.ts +++ b/src/main/pty-descendant-termination.ts @@ -1,19 +1,26 @@ -import { execFile } from 'node:child_process' import type { JobTerminationOutcome } from './windows/windows-pty-job' import { terminateWindowsProcessTree, type WindowsTreeKiller } from './windows-process-tree-kill' import { verifyWindowsTreeKillTarget, type WindowsTreeKillTarget } from './windows-pty-root-identity' -import { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' -import { inProcessSliceMs, runPsInProcess } from '../shared/libproc-process-table' +import type { ProcessTableRow } from './pty-process-table-parser' +import { + DESCENDANT_SNAPSHOT_TIMEOUT_MS, + readFreshProcessTable, + type ProcessTableCapture, + type ProcessTableReader +} from './pty-descendant-fresh-table' export { parseProcessTable, type ProcessTableRow } from './pty-process-table-parser' +export { + DESCENDANT_SNAPSHOT_TIMEOUT_MS, + type ProcessTableCapture, + type ProcessTableReader +} from './pty-descendant-fresh-table' + export const DESCENDANT_KILL_GRACE_MS = 2_000 -export const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000 -// Busy hosts can exceed execFile’s 1MB default; truncated output would omit descendants. -const PS_MAX_BUFFER_BYTES = 32 * 1024 * 1024 export type PosixProcessIdentity = Pick @@ -29,47 +36,15 @@ export type DescendantSnapshot = { reDerivedPids?: ReadonlySet } -export type ProcessTableCapture = { - rows: ProcessTableRow[] - /** Start boundary of the scan that produced rows, never a later consumer's time. */ - capturedAtMs: number -} - -export type ProcessTableReader = (timeoutMs?: number) => Promise export type SignalSender = (pid: number, signal: NodeJS.Signals) => void -const DESCENDANT_PS_ARGS = ['-axo', 'pid=,ppid=,pgid=,tpgid=,lstart='] - -async function readFreshProcessTable( - timeoutMs = DESCENDANT_SNAPSHOT_TIMEOUT_MS -): Promise { - // Stamp before ps starts so a capture-second PID cannot appear older after a clock rollover. - const capturedAtMs = Date.now() - // Pin lstart’s locale so delayed identity checks parse it consistently. - const env = { ...process.env, LANG: 'C', LC_ALL: 'C' } - // Registered now, so no native read submitted before this request serves it; a stalled one leaves ps its full timeout. - const inProcess = await runPsInProcess(DESCENDANT_PS_ARGS, { - env, - timeoutMs: inProcessSliceMs(timeoutMs) - }) - if (inProcess && !inProcess.timedOut) { - return { rows: parseProcessTable(inProcess.stdout), capturedAtMs } - } - const options = { maxBuffer: PS_MAX_BUFFER_BYTES, timeout: timeoutMs, env } - return new Promise((resolve, reject) => { - execFile('ps', DESCENDANT_PS_ARGS, { ...options, killSignal: 'SIGKILL' }, (error, stdout) => - error ? reject(error) : resolve({ rows: parseProcessTable(stdout), capturedAtMs }) - ) - }) -} - /** Share only scans not yet started; later requests need fresh identities before signalling. */ export function createProcessTableSnapshotReader( readFresh: ProcessTableReader ): ProcessTableReader { let queued: { promise: Promise; started: boolean } | null = null - return (timeoutMs) => { + const read: ProcessTableReader = (timeoutMs) => { if (queued && !queued.started) { return queued.promise } @@ -92,6 +67,9 @@ export function createProcessTableSnapshotReader( void entry.promise.then(clearQueued, clearQueued) return entry.promise } + // Sharing a scan keeps the wrapped reader's in-process allowance. + read.deadlineAllowanceMs = readFresh.deadlineAllowanceMs + return read } export const readProcessTable = createProcessTableSnapshotReader(readFreshProcessTable) @@ -110,9 +88,10 @@ export function readProcessTableBeforeDeadline( clearTimeout(timer) resolve(capture) } - // The production reader may spend inProcessSliceMs in process before giving ps the whole timeout. - const slackMs = readTable === readProcessTable ? inProcessSliceMs(timeoutMs) : 0 - const timer = setTimeout(() => finish(null), timeoutMs + slackMs) + const timer = setTimeout( + () => finish(null), + timeoutMs + (readTable.deadlineAllowanceMs?.(timeoutMs) ?? 0) + ) timer.unref?.() try { void readTable(timeoutMs).then( diff --git a/src/shared/libproc-process-table-real-ps.test.ts b/src/shared/libproc-process-table-real-ps.test.ts index 4c8f16ca56a7..419f8633739d 100644 --- a/src/shared/libproc-process-table-real-ps.test.ts +++ b/src/shared/libproc-process-table-real-ps.test.ts @@ -58,6 +58,8 @@ async function inProcess(args: readonly string[], env: NodeJS.ProcessEnv): Promi describe.runIf(process.platform === 'darwin')( 'runPsInProcess with the real addon against /bin/ps', + // Each case runs whole-table /bin/ps with command= (~1-3s alone, longer when the suite loads the host). + { timeout: 30_000 }, () => { let holder: ChildProcess | undefined let holderPid = 0 diff --git a/src/shared/libproc-process-table.ts b/src/shared/libproc-process-table.ts index 247fa967504b..f39db95504ad 100644 --- a/src/shared/libproc-process-table.ts +++ b/src/shared/libproc-process-table.ts @@ -90,6 +90,11 @@ export function inProcessSliceMs(timeoutMs: number): number { return Math.min(150, Math.floor(timeoutMs / 4)) } +/** The outer-deadline allowance for that slice: none where the in-process reader will not run (Linux, no addon, stalled). */ +export function inProcessDeadlineAllowanceMs(timeoutMs: number): number { + return loadLibprocAddon() && isNativeReaderHealthy() ? inProcessSliceMs(timeoutMs) : 0 +} + /** ps output for `args`, read in process; null when the addon or the invocation is unsupported so callers run ps. */ export async function runPsInProcess( args: readonly string[], From 816cd1500c0fe545715f9647d8161e58f564cb8f Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 07:48:50 -0700 Subject: [PATCH 12/13] chore(terminal): move the descendant reader's child_process baseline entry with it (#31783) --- config/process-host-direct-import-baseline.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/process-host-direct-import-baseline.txt b/config/process-host-direct-import-baseline.txt index f4400b3e94ee..f179b6bc8db3 100644 --- a/config/process-host-direct-import-baseline.txt +++ b/config/process-host-direct-import-baseline.txt @@ -86,7 +86,7 @@ src/main/plugins/catalog/plugin-private-marketplace-ssh-shim.cjs src/main/ports/port-scan-command-execution.ts src/main/providers/macos-login-session-pty-probe.ts src/main/providers/process-cwd.ts -src/main/pty-descendant-termination.ts +src/main/pty-descendant-fresh-table.ts src/main/pty/windows-environment-path.ts src/main/rate-limits/gemini-cli-oauth-extractor.ts src/main/runtime/windows-default-route-interfaces.ts From 7ae71b331cd7edab418b1854ede83b660ec5a0ec Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 29 Oct 2026 08:43:56 -0700 Subject: [PATCH 13/13] test(terminal): pin the libproc test locale so lstart doesn't follow the runner's LANG (#31783) --- src/shared/libproc-process-table.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/shared/libproc-process-table.test.ts b/src/shared/libproc-process-table.test.ts index 59e8657db732..7553f955e354 100644 --- a/src/shared/libproc-process-table.test.ts +++ b/src/shared/libproc-process-table.test.ts @@ -20,7 +20,8 @@ import { parseCheapProcessTableRows, parseStrictProcessTableRows } from './proce const TTYS004 = (16 << 24) | 4 // 2026-09-03T16:02:01Z, a single-digit day so lstart pads it. const START = Date.UTC(2026, 8, 3, 16, 2, 1) / 1000 -const BUDGET = { timeoutMs: 1000 } +// Pin the locale so lstart formatting doesn't depend on the runner's LANG. +const BUDGET = { timeoutMs: 1000, env: { LC_ALL: 'C' } } function row(overrides: Partial): LibprocProcessRow { return {