diff --git a/config/patches/node-pty@1.1.0.patch b/config/patches/node-pty@1.1.0.patch index f3de8667f141..9e42c7545988 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..45197ddf4440b8599002b360bc50c4fe0cedf305 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,17 @@ 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); +@@ -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); @@ -360,7 +372,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e #if defined(__APPLE__) static char * pty_getproc(int); -@@ -237,13 +275,23 @@ pty_getproc(int, char *); +@@ -237,13 +279,23 @@ pty_getproc(int, char *); #endif #if defined(__APPLE__) || defined(__OpenBSD__) @@ -385,7 +397,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e #endif struct DelBuf { -@@ -345,8 +393,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 @@ -396,7 +408,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 +419,18 @@ Napi::Value PtyFork(const Napi::CallbackInfo& info) { argv[i + 3] = strdup(arg.c_str()); } @@ -419,7 +431,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 +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."); } @@ -429,7 +441,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e } #endif -@@ -586,6 +641,23 @@ pty_nonblock(int fd) { +@@ -586,6 +645,23 @@ pty_nonblock(int fd) { return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } @@ -453,7 +465,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e /** * pty_getproc * Taken from tmux. -@@ -684,15 +756,73 @@ pty_getproc(int fd, char *tty) { +@@ -684,15 +760,73 @@ pty_getproc(int fd, char *tty) { #endif #if defined(__APPLE__) @@ -529,7 +541,7 @@ 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,81 +840,461 @@ pty_posix_spawn(char** argv, char** env, POSIX_SPAWN_SETSID; *master = posix_openpt(O_RDWR); if (*master == -1) { @@ -662,16 +674,371 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..5e67653b45061e9a9cad4b2d461d563e + 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 ++ ++#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). 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 (size < sizeof(int) || sysctl(mib, 3, buf.data(), &size, NULL, 0) != 0 || ++ size < sizeof(int) || size > buf.size()) { ++ return false; ++ } ++ 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; ++ } ++ } ++ 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_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, 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, mib_length, 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) && ++ 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; ++ 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. ++// 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 (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 (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; ++ 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 }; ++ if (sysctl(mib, 2, &argmax, &argmax_size, NULL, 0) != 0 || argmax <= 0) { ++ 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) { ++ 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)); ++ } ++ 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()); ++ 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("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? }) -> 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()); ++ if (info.Length() < 1 || !info[0].IsObject()) { ++ throw Napi::TypeError::New(env, "Usage: readProcessTable({ command, pids, tty, ctype })"); ++ } ++ 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; ++ } ++ 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, orca_process_query query) ++ : Napi::AsyncWorker(env), ++ deferred_(Napi::Promise::Deferred::New(env)), ++ query_(std::move(query)), ++ status_(-1) {} ++ ++ Napi::Promise Promise() { return deferred_.Promise(); } ++ ++ void Execute() override { ++ status_ = orca_gather_process_table(query_, &rows_); ++ if (status_ < 0) { ++ SetError("orca: process table sysctl failed"); ++ } ++ } ++ ++ void OnOK() override { ++ 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 { ++ deferred_.Reject(error.Value()); ++ } ++ ++ private: ++ Napi::Promise::Deferred deferred_; ++ orca_process_query query_; ++ int status_; ++ std::vector rows_; ++}; ++ ++Napi::Value OrcaProcessTableAsync(const Napi::CallbackInfo& info) { ++ OrcaProcessTableWorker* worker = new OrcaProcessTableWorker(info.Env(), orca_read_process_query(info)); ++ 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, strnlen(vnode.pvi_cdir.vip_path, sizeof(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 || (size_t)length >= sizeof(path)) { ++ return env.Null(); ++ } ++ return Napi::String::New(env, path, length); } #endif + +@@ -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)); ++#if defined(__APPLE__) ++ 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 + return exports; + } + diff --git a/src/unixTerminal.ts b/src/unixTerminal.ts index 98733dc0cd752b554bd94e45904ca341ad141bba..3dd5ad9b3124dbd5ba7f76679b26650dad503ec6 100644 --- a/src/unixTerminal.ts 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 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8e6047af5701..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: 3072026a166d508c622ee025bfceb011ce97e2133efc93bd014e9374f3febf43 + 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=3072026a166d508c622ee025bfceb011ce97e2133efc93bd014e9374f3febf43) + 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=3072026a166d508c622ee025bfceb011ce97e2133efc93bd014e9374f3febf43): + node-pty@1.1.0(patch_hash=b56279c3729be0e79c21f4d6ab207052ed949e9a792ae326fa9bd473e23347a1): 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..ceb055e7e669 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 { readPsStdoutInProcess } 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 readPsStdoutInProcess(args, { env: psLocaleEnvironment(), timeoutMs }) + : null + if (inProcess !== null) { + return inProcess + } const { stdout } = await execFileAsync(file, args, { encoding: 'utf8', env: psLocaleEnvironment(), 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/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/provider-process/provider-process-row-read.ts b/src/main/provider-process/provider-process-row-read.ts index 4078bdb74089..81fce0c1252a 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,22 @@ 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, + timeoutMs: PROCESS_ROW_TIMEOUT_MS, + maxOutputBytes: 4096 + })) ?? + (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..3a4b78f27c0c 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-addon' // 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-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-libproc.test.ts b/src/main/pty-descendant-termination-libproc.test.ts new file mode 100644 index 000000000000..446dce1b59ed --- /dev/null +++ b/src/main/pty-descendant-termination-libproc.test.ts @@ -0,0 +1,133 @@ +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 + >() +})) +// 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, + 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 +const WALL_CLOCK = Date.UTC(2026, 9, 29, 12, 0, 0) + +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' + } +} + +/** 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() +}) + +describe('descendant teardown over the in-process process table', () => { + 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), row(300, 100)]) + setLibprocAddonForTests({ + readProcessTable, + processCwd: () => null, + processPath: () => null + }) + expect(await captureDescendantSnapshot(100, { timeoutMs: 10 })).toBeNull() + + 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() + // 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 a46ca7d65894..f623a32ae931 100644 --- a/src/main/pty-descendant-termination.ts +++ b/src/main/pty-descendant-termination.ts @@ -1,18 +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 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 @@ -28,49 +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 -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() - 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 }) - } - ) - }) -} - /** 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 } @@ -93,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) @@ -111,7 +88,10 @@ export function readProcessTableBeforeDeadline( clearTimeout(timer) resolve(capture) } - const timer = setTimeout(() => finish(null), timeoutMs) + const timer = setTimeout( + () => finish(null), + timeoutMs + (readTable.deadlineAllowanceMs?.(timeoutMs) ?? 0) + ) 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 2460b82a6d00..77f8c7526cab 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 { 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 @@ -28,12 +29,21 @@ 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, + const args = ['-p', String(pid), '-o', 'pid=,tpgid=,tty='] + // A native read stuck behind a busy pool leaves ps its full timeout before signalling. + const inProcess = await runPsInProcess(args, { + timeoutMs: inProcessSliceMs(PROCESS_TABLE_QUERY_TIMEOUT_MS), maxOutputBytes: PROCESS_TABLE_MAX_BYTES }) + const result = + inProcess && !inProcess.timedOut + ? inProcess + : 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..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 @@ -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, 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 } @@ -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, 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 d9a3eb034d3c..decdb5aa3c7e 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,20 @@ 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, + timeoutMs: PS_TIMEOUT_MS, + maxOutputBytes: PS_MAX_OUTPUT_BYTES + })) ?? + (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..873ed92a38d5 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 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..1d67a81b5ffd 100644 --- a/src/shared/darwin-process-table-capture.ts +++ b/src/shared/darwin-process-table-capture.ts @@ -1,13 +1,21 @@ import { nameDarwinTerminals } from './darwin-terminal-names' +import { + claimDarwinTerminalNaming, + isDarwinTerminalNamingInFlight, + resetDarwinTerminalNamingForTests +} 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' let deviceColumnUnsupported = false -let terminalNamingInFlight: Promise | null = null 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 { @@ -20,7 +28,12 @@ export async function captureDarwinProcessTable( return remaining } const canonicalCapture = (): Promise => capture(PS_ARGS, remainingBudget()) - if (deviceColumnUnsupported || terminalNamingInFlight) { + // 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 @@ -42,19 +55,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 subprocessCapture() } - void pending.then(clearNaming, clearNaming) let remainingMs: number try { remainingMs = remainingBudget() @@ -90,5 +98,5 @@ export async function captureDarwinProcessTable( export function resetDarwinProcessTableCaptureForTests(): void { deviceColumnUnsupported = false - terminalNamingInFlight = null + resetDarwinTerminalNamingForTests() } 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/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 new file mode 100644 index 000000000000..c1429ac0d3c0 --- /dev/null +++ b/src/shared/darwin-terminal-naming-single-flight.ts @@ -0,0 +1,59 @@ +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 { + if (namingInFlight) { + return null + } + const pending = name() + const pass: NamingPass = { claimedAtMs: monotonicNow(), drained: createSettleNotifier(pending) } + namingInFlight = pass + const release = (): void => { + if (namingInFlight === pass) { + namingInFlight = null + } + } + void pending.then(release, release) + return pending +} + +/** 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 { + return namingInFlight !== null +} + +export function resetDarwinTerminalNamingForTests(): void { + namingInFlight = null +} 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-addon.ts b/src/shared/libproc-addon.ts new file mode 100644 index 000000000000..35d26654d030 --- /dev/null +++ b/src/shared/libproc-addon.ts @@ -0,0 +1,120 @@ +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 + /** `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 + /** 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..57f7df54af6d --- /dev/null +++ b/src/shared/libproc-argv-completion.ts @@ -0,0 +1,117 @@ +import { runProcess } from '@orca/process-host' +import type { LibprocProcessRow } from './libproc-addon' +import { monotonicNow } from './deadline-settle-notifier' +import { NODEV } from './libproc-ps-format' + +const SZOMB_STATUS = 5 +const MAX_ANCESTOR_DEPTH = 64 + +/** 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 { + 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 + } + top = parent + } + return false +} + +type AuthoritativeCommand = { command: string; cachedAtMs: number } + +// 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 = 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 { + return [ctype, row.pid, row.startSec, row.startUsec ?? '', row.comm, row.command ?? ''].join('\0') +} + +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, + ctype: string, + env: NodeJS.ProcessEnv, + deadline: number +): Promise { + const byPid = new Map(rows.map((row) => [row.pid, row])) + const now = monotonicNow() + 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 { + missing.push({ row, key }) + } + } + const timeoutMs = Math.floor(deadline - monotonicNow()) + 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, key } of missing) { + const command = commands.get(row.pid) + if (command !== undefined) { + row.command = command + rememberCommand(key, command, now) + } + } +} diff --git a/src/shared/libproc-native-reads.ts b/src/shared/libproc-native-reads.ts new file mode 100644 index 000000000000..cbaffa8fec44 --- /dev/null +++ b/src/shared/libproc-native-reads.ts @@ -0,0 +1,146 @@ +import { + DEADLINE_PASSED, + createSettleNotifier, + monotonicNow, + type Settled +} from './deadline-settle-notifier' +import type { LibprocAddon, LibprocProcessRow, LibprocQuery } from './libproc-addon' + +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 +// Set when the cap outlived a caller's deadline; cleared once any read settles. +let poolStalled = false + +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 + poolStalled = false + 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 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' + } + 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 + poolStalled = false + unhealthyUntil = Number.NEGATIVE_INFINITY +} 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..419f8633739d --- /dev/null +++ b/src/shared/libproc-process-table-real-ps.test.ts @@ -0,0 +1,174 @@ +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', + // 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 + 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[] = [] + 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) + ? 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)}`) + } + } + // 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 + } + + 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`) + } + }) + } +) diff --git a/src/shared/libproc-process-table.test.ts b/src/shared/libproc-process-table.test.ts new file mode 100644 index 000000000000..7553f955e354 --- /dev/null +++ b/src/shared/libproc-process-table.test.ts @@ -0,0 +1,386 @@ +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 { + setLibprocAddonForTests, + type LibprocAddon, + type LibprocProcessRow, + 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' + +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 +// 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 { + pid: 1, + ppid: 0, + pgid: 1, + tpgid: 0, + tdev: -1, + status: 2, + flags: 0, + sessionLeader: false, + startSec: START, + comm: 'launchd', + command: '/sbin/launchd', + commandIncomplete: true, + ...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', + commandIncomplete: false + }), + row({ + pid: 4242, + ppid: 4200, + pgid: 4242, + tpgid: 4300, + tdev: TTYS004, + flags: 0x2, + sessionLeader: true, + comm: 'zsh', + command: '-zsh', + commandIncomplete: false + }), + // A pane's root login is root-owned and sits under the terminal host. + 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', + commandIncomplete: false + }), + row({ pid: 4401, ppid: 4242, pgid: 4401, status: 5, comm: 'sh', command: '' }), + row({}) +] + +function tableFor( + query: LibprocQuery, + table: readonly LibprocProcessRow[] = 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 = { + readProcessTable: vi.fn(async (query: LibprocQuery) => tableFor(query)), + processCwd: vi.fn(() => null), + processPath: vi.fn(() => null), + ...overrides + } + setLibprocAddonForTests(addon) + return addon +} + +afterEach(() => { + setLibprocAddonForTests(undefined) + resetNativeReadsForTests() + 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 = { 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({ + pid: 4300, + stat: 'S+', + tty: 'ttys004', + startTime: 'Thu Sep 3 16:02:01 2026', + command: 'node /usr/local/bin/claude --resume' + }) + ]) + // 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).at(-1)).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,4300', '-o', 'pid=,tdev='], BUDGET)).toMatchObject({ + code: 0, + stdout: '4300 16/4\n' + }) + 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'], 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'], 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({ + readProcessTable: async () => { + throw new Error('sysctl failed') + } + }) + expect(await runPsInProcess(['-axo', 'pid='], BUDGET)).toBeNull() + + setLibprocAddonForTests(null) + 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'] + }) + ) + }) + + 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 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([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 })) + ) + + // 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 () => { + 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 new file mode 100644 index 000000000000..f39db95504ad --- /dev/null +++ b/src/shared/libproc-process-table.ts @@ -0,0 +1,231 @@ +import { nameDarwinTerminalDevices } from './darwin-terminal-names' +import { + claimDarwinTerminalNaming, + 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 { + isNativeReaderHealthy, + readFreshNativeTable, + registerNativeRequest +} from './libproc-native-reads' +import { completeCommands } from './libproc-argv-completion' +import { + compareLikePs, + formatDarwinDevice, + formatLibprocStat, + formatLstart, + parsePsQuery +} from './libproc-ps-format' + +/** 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 +} + +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 TIMED_OUT: LibprocPsResult = { + code: null, + signal: 'SIGTERM', + stdout: '', + stderr: '', + timedOut: true, + outputTruncated: false +} + +/** 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' +} + +function lstartZoneIsUtc(env: NodeJS.ProcessEnv): boolean | null { + const zone = env.TZ + if (zone === undefined || zone === process.env.TZ) { + return false + } + return /^(?:UTC|GMT)0?$/.test(zone) ? true : null +} + +/** 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 | 'stalled'> { + 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 + } + const waited = await waitForDarwinTerminalNaming(deadline) + if (waited !== 'drained') { + return waited + } + } +} + +/** 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)) +} + +/** 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[], + options: InProcessPsOptions +): Promise { + const addon = loadLibprocAddon() + const query = addon ? parsePsQuery(args) : null + if (!addon || !query || !isNativeReaderHealthy()) { + return null + } + const registeredSequence = registerNativeRequest() + const deadline = monotonicNow() + options.timeoutMs + const env = options.env ?? process.env + const utc = lstartZoneIsUtc(env) + 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 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 { + const read = await readFreshNativeTable(addon, nativeQuery, registeredSequence, deadline) + if (read === 'stalled') { + return null + } + 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) + ) + if (devices.size > 0) { + const named = await nameTerminals(devices, deadline) + if (named === 'stalled') { + return null + } + if (named === DEADLINE_PASSED) { + return TIMED_OUT + } + ttyNames = named + } + } + if (rows && includeCommand) { + await completeCommands(rows, query.pids !== null, ctype, env, deadline) + } + } catch { + return null + } + 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 } + } + const ttyOf = (row: LibprocProcessRow): string => + ttyNames.get(formatDarwinDevice(row.tdev) ?? '') ?? '??' + const selected = rows.sort(compareLikePs) + 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 === true) + case 'command': + return row.command ?? `(${row.comm})` + case 'pid': + case 'ppid': + case 'pgid': + case 'tpgid': + return String(row[column]) + } + }) + .join(' ') + ) + 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, + stderr: '', + timedOut: false, + outputTruncated + } +} + +/** 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 + } + 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 } + ) + } + 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/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 diff --git a/src/shared/process-table-snapshot-reader.ts b/src/shared/process-table-snapshot-reader.ts index 4c0459eecd27..2233156d01f0 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 { readPsStdoutInProcess } from './libproc-process-table' import { captureDarwinProcessTable, resetDarwinProcessTableCaptureForTests @@ -242,15 +243,18 @@ async function readLinuxProcessStartTimes( return new Map(starts.filter((entry) => entry !== null)) } -async function captureProcessTable(args: readonly string[], timeout = PS_TIMEOUT_MS) { - let stdout: string +async function captureProcessTable(args: readonly string[], timeout = PS_TIMEOUT_MS, ps = false) { + const env = psLocaleEnvironment() + let stdout = ps ? null : 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 4fbc90873ef1..d6b2518c599d 100644 --- a/src/shared/shell-process-readiness.ts +++ b/src/shared/shell-process-readiness.ts @@ -4,6 +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 } from './libproc-addon' +import { readPsStdoutInProcess } from './libproc-process-table' import { PS_MAX_BUFFER_BYTES } from './process-table-snapshot' const execFile = promisify(execFileCallback) @@ -30,6 +32,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 +47,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 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', + 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 +82,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..b01e18751c7d 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, timeoutMs: 1000, maxOutputBytes: 65536 })) ?? + (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') }