diff --git a/apps/desktop/src/main/lib/terminal/daemon/daemon-manager.ts b/apps/desktop/src/main/lib/terminal/daemon/daemon-manager.ts index 39f9c3cdd1d..8aeea32d9ed 100644 --- a/apps/desktop/src/main/lib/terminal/daemon/daemon-manager.ts +++ b/apps/desktop/src/main/lib/terminal/daemon/daemon-manager.ts @@ -191,7 +191,7 @@ export class DaemonTerminalManager extends EventEmitter { session.lastActive = Date.now(); } - portManager.checkOutputForHint(data); + portManager.checkOutputForHint(paneId, data); this.historyManager.writeToHistory(paneId, data, () => this.sessions.get(paneId), ); diff --git a/packages/host-service/src/terminal/terminal.ts b/packages/host-service/src/terminal/terminal.ts index cd117aa74d3..9e6d38367cb 100644 --- a/packages/host-service/src/terminal/terminal.ts +++ b/packages/host-service/src/terminal/terminal.ts @@ -1228,7 +1228,9 @@ export async function createTerminalSessionInternal({ ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), ); - if (hintText.length > 0) portManager.checkOutputForHint(hintText); + // Runs even when the decoder buffers a partial codepoint into "" + // — the chunk is still output and must refresh the idle clock. + portManager.checkOutputForHint(terminalId, hintText); // Feed the tracker on every byte — broadcast skips the FIFO, // so this is the only path that catches startup mode escapes. diff --git a/packages/port-scanner/src/index.ts b/packages/port-scanner/src/index.ts index 6a7e6efe696..eff8db66d19 100644 --- a/packages/port-scanner/src/index.ts +++ b/packages/port-scanner/src/index.ts @@ -5,7 +5,7 @@ export { } from "./port-manager.ts"; export { getListeningPortsForPids, - getProcessTree, + getProcessTreesForPids, type PortInfo, } from "./scanner.ts"; export { diff --git a/packages/port-scanner/src/port-manager.test.ts b/packages/port-scanner/src/port-manager.test.ts index c8f0faa4302..3790fe7ced1 100644 --- a/packages/port-scanner/src/port-manager.test.ts +++ b/packages/port-scanner/src/port-manager.test.ts @@ -1,6 +1,21 @@ -import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test"; +import { + afterAll, + afterEach, + beforeEach, + describe, + expect, + it, + mock, +} from "bun:test"; import type { DetectedPort } from "./types"; +// mock.module leaks across test files in the same bun process — hold the real +// module and restore it after this file so scanner.test.ts tests the real one. +const realScanner = { ...(await import("./scanner.ts")) }; +afterAll(() => { + mock.module("./scanner", () => realScanner); +}); + /** * Regression tests for #3372 ("excessive lsof spawning"). * @@ -17,7 +32,8 @@ import type { DetectedPort } from "./types"; */ interface ScannerSpy { - getProcessTree: number; + getProcessTrees: number; + lastTreeRootPids: number[]; getListeningPortsForPids: number; inFlight: number; maxInFlight: number; @@ -33,7 +49,8 @@ interface MockPortInfo { } const spy: ScannerSpy = { - getProcessTree: 0, + getProcessTrees: 0, + lastTreeRootPids: [], getListeningPortsForPids: 0, inFlight: 0, maxInFlight: 0, @@ -43,11 +60,15 @@ const spy: ScannerSpy = { let lsofDelayMs = 0; let listeningPorts: MockPortInfo[] = []; +/** When set, the tree mock blocks until the test resolves this promise. */ +let treeGate: Promise | null = null; mock.module("./scanner", () => ({ - getProcessTree: async (pid: number) => { - spy.getProcessTree++; - return [pid, pid + 1]; + getProcessTreesForPids: async (rootPids: number[]) => { + spy.getProcessTrees++; + spy.lastTreeRootPids = rootPids; + if (treeGate) await treeGate; + return new Map(rootPids.map((pid) => [pid, [pid, pid + 1]])); }, getListeningPortsForPids: async (_pids: number[], signal?: AbortSignal) => { spy.getListeningPortsForPids++; @@ -74,7 +95,9 @@ mock.module("./scanner", () => ({ }, })); -const { PortManager } = await import("./port-manager"); +const { PortManager, IDLE_AFTER_MS, IDLE_SCAN_INTERVAL_MS } = await import( + "./port-manager" +); const HINT_DEBOUNCE_MS = 500; const PAST_DEBOUNCE_MS = HINT_DEBOUNCE_MS + 50; @@ -88,10 +111,21 @@ let manager: InstanceType; const pmInternals = () => manager as unknown as { scanInterval: ReturnType | null; + sessions: Map< + string, + { + workspaceId: string; + pid: number | null; + lastActivityAt: number; + lastScannedAt: number; + } + >; + scanAllSessions: (force?: boolean) => Promise; }; function resetSpy(): void { - spy.getProcessTree = 0; + spy.getProcessTrees = 0; + spy.lastTreeRootPids = []; spy.getListeningPortsForPids = 0; spy.inFlight = 0; spy.maxInFlight = 0; @@ -99,6 +133,7 @@ function resetSpy(): void { spy.aborted = 0; lsofDelayMs = 0; listeningPorts = []; + treeGate = null; } beforeEach(() => { @@ -113,7 +148,7 @@ afterEach(() => { describe("PortManager — #3372 lifecycle (interval runs only with sessions)", () => { it("forceScan is a no-op when no sessions are registered", async () => { await manager.forceScan(); - expect(spy.getProcessTree).toBe(0); + expect(spy.getProcessTrees).toBe(0); expect(spy.getListeningPortsForPids).toBe(0); }); @@ -159,18 +194,22 @@ describe("PortManager — #3372 lifecycle (interval runs only with sessions)", ( manager.upsertSession("p1", "ws1", null); await manager.forceScan(); // No PID → no process-tree walk and no lsof batch. - expect(spy.getProcessTree).toBe(0); + expect(spy.getProcessTrees).toBe(0); expect(spy.getListeningPortsForPids).toBe(0); }); }); describe("PortManager — #3372 concurrency (at most one lsof in flight)", () => { - it("bulk scan batches every session into a single lsof call", async () => { + it("bulk scan batches every session into one tree read and one lsof call", async () => { for (let i = 0; i < 10; i++) { manager.upsertSession(`p${i}`, `ws${i}`, 1000 + i); } await manager.forceScan(); + // One system-wide process-table read covers all sessions — a + // per-session pidtree call spawned a full `ps` each. + expect(spy.getProcessTrees).toBe(1); + expect(spy.lastTreeRootPids).toHaveLength(10); expect(spy.getListeningPortsForPids).toBe(1); expect(spy.maxInFlight).toBe(1); }); @@ -183,7 +222,7 @@ describe("PortManager — #3372 concurrency (at most one lsof in flight)", () => // 100 hints while the first scan is running — all on the hot path. for (let i = 0; i < 100; i++) { - manager.checkOutputForHint("listening on port 3000\n"); + manager.checkOutputForHint("p1", "listening on port 3000\n"); } await firstScan; @@ -376,43 +415,47 @@ describe("PortManager — #3372 hint regex narrowing", () => { }); it("does NOT scan on a bare 'port 22' (old loose pattern)", async () => { - manager.checkOutputForHint("connection reached port 22\n"); + manager.checkOutputForHint("p1", "connection reached port 22\n"); await sleep(PAST_DEBOUNCE_MS); expect(spy.getListeningPortsForPids).toBe(0); }); it("does NOT scan on a trailing ':12345' (old loose pattern)", async () => { - manager.checkOutputForHint("commit abc123def:12345\n"); + manager.checkOutputForHint("p1", "commit abc123def:12345\n"); await sleep(PAST_DEBOUNCE_MS); expect(spy.getListeningPortsForPids).toBe(0); }); it("DOES scan on 'listening on port 3000'", async () => { - manager.checkOutputForHint("listening on port 3000\n"); + manager.checkOutputForHint("p1", "listening on port 3000\n"); await sleep(PAST_DEBOUNCE_MS); expect(spy.getListeningPortsForPids).toBe(1); }); it("DOES scan on 'server running at http://localhost:3000'", async () => { - manager.checkOutputForHint("server running at http://localhost:3000\n"); + manager.checkOutputForHint( + "p1", + "server running at http://localhost:3000\n", + ); await sleep(PAST_DEBOUNCE_MS); expect(spy.getListeningPortsForPids).toBe(1); }); it("DOES scan on 'ready on http://localhost:5173' (Vite-style)", async () => { - manager.checkOutputForHint("ready on http://localhost:5173\n"); + manager.checkOutputForHint("p1", "ready on http://localhost:5173\n"); await sleep(PAST_DEBOUNCE_MS); expect(spy.getListeningPortsForPids).toBe(1); }); it("DOES scan on Vite's 'Local: http://localhost:5173/' banner", async () => { - manager.checkOutputForHint(" ➜ Local: http://localhost:5173/\n"); + manager.checkOutputForHint("p1", " ➜ Local: http://localhost:5173/\n"); await sleep(PAST_DEBOUNCE_MS); expect(spy.getListeningPortsForPids).toBe(1); }); it("DOES scan on Django's 'Starting development server at http://...'", async () => { manager.checkOutputForHint( + "p1", "Starting development server at http://127.0.0.1:8000/\n", ); await sleep(PAST_DEBOUNCE_MS); @@ -458,9 +501,9 @@ describe("PortManager — #3372 teardown (no orphan children)", () => { // rather than passing `undefined` and losing abortability. manager.upsertSession("p1", "ws1", 1000); - manager.checkOutputForHint("listening on port 3000\n"); - // Unregister immediately — this triggers stopPeriodicScanIfIdle which - // clears the hint timer. If any code path regresses and the timer + manager.checkOutputForHint("p1", "listening on port 3000\n"); + // Unregister immediately — this triggers stopPeriodicScanIfNoSessions + // which clears the hint timer. If any code path regresses and the timer // survives past abort-nulling, ensureScanAbort must still produce a // valid signal rather than throwing. manager.unregisterSession("p1"); @@ -471,3 +514,145 @@ describe("PortManager — #3372 teardown (no orphan children)", () => { expect(spy.getListeningPortsForPids).toBeGreaterThanOrEqual(1); }); }); + +describe("PortManager — idle decay (sessions without output scan rarely)", () => { + const scan = () => pmInternals().scanAllSessions(); + const session = (terminalId: string) => { + const entry = pmInternals().sessions.get(terminalId); + if (!entry) throw new Error(`session ${terminalId} not registered`); + return entry; + }; + + it("a freshly registered session is scanned on periodic ticks", async () => { + manager.upsertSession("p1", "ws1", 1000); + await scan(); + expect(spy.getProcessTrees).toBe(1); + }); + + it("an idle session is skipped until the slow cadence elapses", async () => { + manager.upsertSession("p1", "ws1", 1000); + const entry = session("p1"); + entry.lastActivityAt = Date.now() - IDLE_AFTER_MS - 1; + entry.lastScannedAt = Date.now(); + + await scan(); + expect(spy.getProcessTrees).toBe(0); + expect(spy.getListeningPortsForPids).toBe(0); + + entry.lastScannedAt = Date.now() - IDLE_SCAN_INTERVAL_MS - 1; + await scan(); + expect(spy.getProcessTrees).toBe(1); + }); + + it("any PTY output puts a session back on the fast cadence", async () => { + manager.upsertSession("p1", "ws1", 1000); + const entry = session("p1"); + entry.lastActivityAt = Date.now() - IDLE_AFTER_MS - 1; + entry.lastScannedAt = Date.now(); + + // Plain output — not a port hint — still counts as activity. + manager.checkOutputForHint("p1", "make: nothing to be done\n"); + await scan(); + expect(spy.getProcessTrees).toBe(1); + }); + + it("re-upserting the same pid does not reset the idle clock", async () => { + manager.upsertSession("p1", "ws1", 1000); + const entry = session("p1"); + entry.lastActivityAt = Date.now() - IDLE_AFTER_MS - 1; + entry.lastScannedAt = Date.now(); + + // The reaper's periodic port-scan sync re-registers unattached + // sessions every pass; that must not count as activity. + manager.upsertSession("p1", "ws1", 1000); + await scan(); + expect(spy.getProcessTrees).toBe(0); + + // A new shell pid is a fresh session and is active again. + manager.upsertSession("p1", "ws1", 2000); + await scan(); + expect(spy.getProcessTrees).toBe(1); + }); + + it("only due sessions are included in the batch", async () => { + manager.upsertSession("active", "ws1", 1000); + manager.upsertSession("idle", "ws1", 2000); + const entry = session("idle"); + entry.lastActivityAt = Date.now() - IDLE_AFTER_MS - 1; + entry.lastScannedAt = Date.now(); + + await scan(); + expect(spy.lastTreeRootPids).toEqual([1000]); + }); + + it("a skipped idle session keeps its previously detected ports", async () => { + manager.upsertSession("p1", "ws1", 1000); + listeningPorts = [ + { port: 3000, pid: 1001, address: "127.0.0.1", processName: "node" }, + ]; + await manager.forceScan(); + expect(manager.getAllPorts()).toHaveLength(1); + + const entry = session("p1"); + entry.lastActivityAt = Date.now() - IDLE_AFTER_MS - 1; + entry.lastScannedAt = Date.now(); + + // The server "dies" while the session is skipped — its port must + // survive untouched until the session's own next scan. + listeningPorts = []; + await scan(); + expect(manager.getAllPorts()).toHaveLength(1); + + await manager.forceScan(); + expect(manager.getAllPorts()).toHaveLength(0); + }); + + it("forceScan includes idle sessions regardless of cadence", async () => { + manager.upsertSession("p1", "ws1", 1000); + const entry = session("p1"); + entry.lastActivityAt = Date.now() - IDLE_AFTER_MS - 1; + entry.lastScannedAt = Date.now(); + + await manager.forceScan(); + expect(spy.getProcessTrees).toBe(1); + }); + + it("forceScan arriving mid-scan keeps its bypass in the coalesced follow-up", async () => { + manager.upsertSession("active", "ws1", 1000); + manager.upsertSession("idle", "ws1", 2000); + const entry = session("idle"); + entry.lastActivityAt = Date.now() - IDLE_AFTER_MS - 1; + entry.lastScannedAt = Date.now(); + + // scanAllSessions marks itself in-flight synchronously, so with no await + // in between the force scan is guaranteed to coalesce — and the follow-up + // is awaited inside the periodic promise, so no timers are needed. + const periodic = scan(); + await manager.forceScan(); + await periodic; + + // The follow-up must run forced: the idle session's pid is included. + expect(spy.lastTreeRootPids).toContain(2000); + }); + + it("discards results for a session whose pid changed during the table read", async () => { + let release!: () => void; + treeGate = new Promise((resolve) => { + release = resolve; + }); + manager.upsertSession("p1", "ws1", 1000); + listeningPorts = [ + { port: 3000, pid: 1000, address: "127.0.0.1", processName: "node" }, + ]; + + const scanPromise = scan(); + // The shell is replaced (new pid) while the table read is blocked — the + // stale tree for pid 1000 must not be attributed to the new session. + manager.upsertSession("p1", "ws1", 9999); + release(); + await scanPromise; + + expect(manager.getAllPorts()).toHaveLength(0); + expect(session("p1").lastScannedAt).toBe(0); + }); +}); diff --git a/packages/port-scanner/src/port-manager.ts b/packages/port-scanner/src/port-manager.ts index b86d0ba4dc5..36c69714f56 100644 --- a/packages/port-scanner/src/port-manager.ts +++ b/packages/port-scanner/src/port-manager.ts @@ -1,7 +1,7 @@ import { EventEmitter } from "node:events"; import { getListeningPortsForPids, - getProcessTree, + getProcessTreesForPids, type PortInfo, } from "./scanner.ts"; import type { DetectedPort } from "./types.ts"; @@ -9,6 +9,16 @@ import type { DetectedPort } from "./types.ts"; /** How often to poll for port changes (in ms) */ const SCAN_INTERVAL_MS = 2500; +/** A session with no PTY output for this long is considered idle (in ms) */ +export const IDLE_AFTER_MS = 60_000; + +/** + * How often idle sessions are still scanned (in ms). Ports can appear without + * terminal output (a silently daemonized server), so idle sessions decay to + * this cadence rather than being skipped outright. + */ +export const IDLE_SCAN_INTERVAL_MS = 30_000; + /** Delay before scanning after a port hint is detected (in ms) */ const HINT_SCAN_DELAY_MS = 500; @@ -91,6 +101,10 @@ interface SessionEntry { workspaceId: string; /** PTY process ID — null when the terminal isn't yet spawned (or has exited). */ pid: number | null; + /** Last time this session produced PTY output or was registered with a new pid. */ + lastActivityAt: number; + /** Last time this session was included in a scan. */ + lastScannedAt: number; } interface ScanState { @@ -122,6 +136,8 @@ export class PortManager extends EventEmitter { private isScanning = false; /** Set when a hint arrives during a scan; triggers one follow-up scan. */ private scanRequested = false; + /** Set when a force scan arrives mid-scan; the follow-up keeps the bypass. */ + private forceRequested = false; /** Aborts any in-flight scan children (lsof/netstat) on teardown. */ private scanAbort: AbortController | null = null; private readonly killFn: KillFn; @@ -141,7 +157,19 @@ export class PortManager extends EventEmitter { workspaceId: string, pid: number | null, ): void { - this.sessions.set(terminalId, { workspaceId, pid }); + const existing = this.sessions.get(terminalId); + if (existing && existing.pid === pid) { + // Re-upserts (e.g. the reaper's periodic sync of unattached daemon + // sessions) must not reset the idle clock. + existing.workspaceId = workspaceId; + } else { + this.sessions.set(terminalId, { + workspaceId, + pid, + lastActivityAt: Date.now(), + lastScannedAt: 0, + }); + } this.ensurePeriodicScanRunning(); } @@ -151,10 +179,16 @@ export class PortManager extends EventEmitter { unregisterSession(terminalId: string): void { this.sessions.delete(terminalId); this.removePortsForTerminal(terminalId); - this.stopPeriodicScanIfIdle(); + this.stopPeriodicScanIfNoSessions(); } - checkOutputForHint(data: string): void { + /** + * Called on every PTY output chunk: any output keeps the session on the + * fast scan cadence, and server-startup phrases trigger a prompt scan. + */ + checkOutputForHint(terminalId: string, data: string): void { + const session = this.sessions.get(terminalId); + if (session) session.lastActivityAt = Date.now(); if (this.hintScanTimeout || this.scanRequested) return; if (!containsPortHint(data)) return; this.scheduleHintScan(); @@ -191,7 +225,7 @@ export class PortManager extends EventEmitter { return this.scanAbort; } - private stopPeriodicScanIfIdle(): void { + private stopPeriodicScanIfNoSessions(): void { if (!this.hasAnySessions()) this.stopPeriodicScan(); } @@ -213,6 +247,7 @@ export class PortManager extends EventEmitter { } this.scanRequested = false; + this.forceRequested = false; } /** @@ -246,44 +281,48 @@ export class PortManager extends EventEmitter { }; } - private async collectSessionPids(scanState: ScanState): Promise { - const tasks: Promise[] = []; - for (const [terminalId, { workspaceId, pid }] of this.sessions) { - if (pid === null) continue; - tasks.push( - this.collectPidTree({ - terminalId, - workspaceId, - pid, - scanState, - }), - ); - } - await Promise.all(tasks); + /** + * Active sessions (recent PTY output) are scanned on every tick; idle ones + * decay to the IDLE_SCAN_INTERVAL_MS cadence. Skipped sessions keep their + * previously detected ports untouched until their next scan. + */ + private isSessionDue(entry: SessionEntry, now: number): boolean { + if (now - entry.lastActivityAt < IDLE_AFTER_MS) return true; + return now - entry.lastScannedAt >= IDLE_SCAN_INTERVAL_MS; } - private async collectPidTree({ - terminalId, - workspaceId, - pid, - scanState, - }: { - terminalId: string; - workspaceId: string; - pid: number; - scanState: ScanState; - }): Promise { - try { - const pids = await getProcessTree(pid); + private async collectSessionPids( + scanState: ScanState, + force: boolean, + ): Promise { + const now = Date.now(); + const dueSessions: { terminalId: string; pid: number }[] = []; + for (const [terminalId, entry] of this.sessions) { + if (entry.pid === null) continue; + if (!force && !this.isSessionDue(entry, now)) continue; + dueSessions.push({ terminalId, pid: entry.pid }); + } + if (dueSessions.length === 0) return; + + const trees = await getProcessTreesForPids( + dueSessions.map((session) => session.pid), + ); + for (const { terminalId, pid } of dueSessions) { + const entry = this.sessions.get(terminalId); + // The session may have been replaced (new pid) or unregistered while + // the table read was in flight; its tree is stale — don't apply it. + if (!entry || entry.pid !== pid) continue; + entry.lastScannedAt = now; + + const pids = trees.get(pid) ?? []; if (pids.length === 0) { + // Root pid absent from the process table — the session exited. scanState.emptyTreeTerminals.add(terminalId); - return; + continue; } - + const { workspaceId } = entry; scanState.terminalPortMap.set(terminalId, { workspaceId, pids }); this.addTerminalPids({ terminalId, workspaceId, pids, scanState }); - } catch { - // Session may have exited } } @@ -363,10 +402,11 @@ export class PortManager extends EventEmitter { } } - private async scanAllSessions(): Promise { + private async scanAllSessions(force = false): Promise { if (this.isScanning) { // A hint or tick fired mid-scan; queue exactly one follow-up. this.scanRequested = true; + if (force) this.forceRequested = true; return; } if (!this.hasAnySessions()) return; @@ -374,7 +414,7 @@ export class PortManager extends EventEmitter { try { const scanState = this.createScanState(); - await this.collectSessionPids(scanState); + await this.collectSessionPids(scanState, force); const portsByTerminal = await this.buildPortsByTerminal({ allPids: scanState.allPids, @@ -396,7 +436,9 @@ export class PortManager extends EventEmitter { if (this.scanRequested && this.hasAnySessions()) { this.scanRequested = false; - await this.scanAllSessions(); + const followUpForce = this.forceRequested; + this.forceRequested = false; + await this.scanAllSessions(followUpForce); } } @@ -499,7 +541,7 @@ export class PortManager extends EventEmitter { } async forceScan(): Promise { - await this.scanAllSessions(); + await this.scanAllSessions(true); } /** diff --git a/packages/port-scanner/src/scanner.test.ts b/packages/port-scanner/src/scanner.test.ts index c8d9eb59204..a1da041fb50 100644 --- a/packages/port-scanner/src/scanner.test.ts +++ b/packages/port-scanner/src/scanner.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "bun:test"; +import { getListeningPortsForPids, getProcessTreesForPids } from "./scanner.ts"; /** * Tests for lsof output parsing logic. @@ -85,6 +86,57 @@ function parseLsofOutput( return ports; } +describe("getProcessTreesForPids (real process table)", () => { + it("returns an empty map for no roots", async () => { + expect((await getProcessTreesForPids([])).size).toBe(0); + }); + + it("includes the root pid and its descendants from one table read", async () => { + // Not `sleep` — this package supports win32, where that binary is absent. + const child = Bun.spawn([ + process.execPath, + "-e", + "setTimeout(() => {}, 5000)", + ]); + try { + const trees = await getProcessTreesForPids([process.pid]); + const tree = trees.get(process.pid); + expect(tree).toContain(process.pid); + expect(tree).toContain(child.pid); + } finally { + child.kill(); + } + }); + + it("omits roots that are not running", async () => { + // PID_MAX on macOS is 99998 and on Linux defaults to 4194304, so this + // pid can never exist. + const trees = await getProcessTreesForPids([process.pid, 99_999_999]); + expect(trees.has(99_999_999)).toBe(false); + expect(trees.has(process.pid)).toBe(true); + }); +}); + +describe("getListeningPortsForPids (real sockets)", () => { + it("finds a genuinely listening port for our own pid", async () => { + const server = Bun.serve({ port: 0, fetch: () => new Response("ok") }); + try { + const listeningPort = server.port; + if (listeningPort === undefined) throw new Error("server has no port"); + const ports = await getListeningPortsForPids([process.pid]); + expect(ports.map((info) => info.port)).toContain(listeningPort); + expect(ports.every((info) => info.pid === process.pid)).toBe(true); + } finally { + server.stop(true); + } + }); + + it("returns nothing for a pid that is not running", async () => { + const ports = await getListeningPortsForPids([99_999_999]); + expect(ports).toHaveLength(0); + }); +}); + describe("port-scanner", () => { describe("parseLsofOutput", () => { it("should parse standard lsof output with (LISTEN) suffix", () => { diff --git a/packages/port-scanner/src/scanner.ts b/packages/port-scanner/src/scanner.ts index 75ab20681e5..83e8da659f2 100644 --- a/packages/port-scanner/src/scanner.ts +++ b/packages/port-scanner/src/scanner.ts @@ -57,15 +57,49 @@ export interface PortInfo { } /** - * Get all child PIDs of a process (including the process itself) + * Get the process tree (root + descendants) for each of the given root PIDs + * using a single system-wide process-table read. pidtree spawns a full + * `ps`/`wmic` per invocation, so calling it once per session made scan cost + * scale linearly with session count. + * + * Roots that are no longer running are absent from the returned map. Throws + * when the process table itself can't be read, so callers can keep previous + * state instead of treating every session as exited. */ -export async function getProcessTree(pid: number): Promise { - try { - return await pidtree(pid, { root: true }); - } catch { - // Process may have exited - return []; +export async function getProcessTreesForPids( + rootPids: number[], +): Promise> { + const trees = new Map(); + if (rootPids.length === 0) return trees; + + const table = await pidtree(-1, { advanced: true }); + + const childrenByPpid = new Map(); + const alivePids = new Set(); + for (const { pid, ppid } of table) { + alivePids.add(pid); + const siblings = childrenByPpid.get(ppid); + if (siblings) siblings.push(pid); + else childrenByPpid.set(ppid, [pid]); } + + for (const rootPid of rootPids) { + if (!alivePids.has(rootPid)) continue; + const pids: number[] = []; + const seen = new Set(); + const stack = [rootPid]; + while (stack.length > 0) { + const pid = stack.pop(); + if (pid === undefined || seen.has(pid)) continue; + seen.add(pid); + pids.push(pid); + const children = childrenByPpid.get(pid); + if (children) stack.push(...children); + } + trees.set(rootPid, pids); + } + + return trees; } /** @@ -103,16 +137,16 @@ async function getListeningPortsLsof( try { const pidArg = pids.join(","); const pidSet = new Set(pids); + // -a: AND the selectors — without it lsof ORs -p with -iTCP and + // walks every process on the machine, only to be filtered below // -p: filter by PIDs // -iTCP: only TCP connections // -sTCP:LISTEN: only listening sockets // -P: don't convert port numbers to names // -n: don't resolve hostnames - // Note: lsof may ignore -p filter if PIDs don't exist or have no matches, - // so we must validate PIDs in the output against our requested set const output = await runTolerant( "lsof", - ["-p", pidArg, "-iTCP", "-sTCP:LISTEN", "-P", "-n"], + ["-a", "-p", pidArg, "-iTCP", "-sTCP:LISTEN", "-P", "-n"], { maxBuffer: 10 * 1024 * 1024, timeout: EXEC_TIMEOUT_MS, signal }, ); @@ -141,8 +175,8 @@ async function getListeningPortsLsof( const pid = Number.parseInt(pidStr, 10); - // CRITICAL: Verify the PID is in our requested set - // lsof ignores -p filter when PIDs don't exist, returning all TCP listeners + // Defense in depth: -a should guarantee only requested PIDs appear, + // but a stray line must never attribute another process's port to a session if (!pidSet.has(pid)) continue; // Parse address:port from NAME column