Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PortScanner.ts

1,343 lines51.5 KB

1import {
2 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
3 PREVIEW_URL_MAX_LENGTH,
4 PreviewStopLocalServerError,
5 ThreadId,
6 type DiscoveredLocalServer,
7 type PreviewStopLocalServerInput,
8} from "@t3tools/contracts";
9import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import { windowsSystem32Path } from "@t3tools/shared/windowsSystem";
12import { isLoopbackHost, LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
13import * as Cause from "effect/Cause";
14import * as Clock from "effect/Clock";
15import * as Context from "effect/Context";
16import * as Duration from "effect/Duration";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as PlatformError from "effect/PlatformError";
22import * as Ref from "effect/Ref";
23import * as Schedule from "effect/Schedule";
24import * as Scope from "effect/Scope";
25import * as Semaphore from "effect/Semaphore";
26import { FetchHttpClient, HttpClient } from "effect/http";
27​
28import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
29import * as ProcessLauncher from "../process/ProcessLauncher.ts";
30import * as WindowsTcpListeners from "../process/windowsTcpListeners.ts";
31import * as ProcessRunner from "../processRunner.ts";
32​
33export class PortDiscovery extends Context.Service<
34 PortDiscovery,
35 {
36 readonly scan: (
37 configuredUrls?: ReadonlyArray<string>,
38 ) => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
39 readonly subscribe: (
40 input: {
41 readonly configuredUrls: ReadonlyArray<string>;
42 readonly initialSnapshot: ReadonlyArray<DiscoveredLocalServer>;
43 },
44 listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
45 ) => Effect.Effect<void, never, Scope.Scope>;
46 readonly retain: Effect.Effect<void, never, Scope.Scope>;
47 readonly registerTerminalProcesses: (input: {
48 readonly threadId: string;
49 readonly terminalId: string;
50 readonly processIds: ReadonlyArray<number>;
51 }) => Effect.Effect<void>;
52 readonly unregisterTerminal: (input: {
53 readonly threadId: string;
54 readonly terminalId: string;
55 }) => Effect.Effect<void>;
56 /**
57 * Counts a running agent until the returned function is called. While one runs, any
58 * listener may be a server it started. Synchronous because provider spawn callbacks run
59 * outside Effect.
60 */
61 readonly trackAgent: () => () => void;
62 /**
63 * Tells an agent CLI's adapter which of its commands a user stop is about to signal, so the
64 * exit is not reported to the agent as the command finishing by itself.
65 */
66 readonly watchAgentCommandStops: (
67 watcher: AgentCommandStopWatcher,
68 ) => Effect.Effect<void, never, Scope.Scope>;
69 /** Stops a listed server's process group, never this server, an agent CLI, or a shell. */
70 readonly stopServer: (
71 input: PreviewStopLocalServerInput,
72 ) => Effect.Effect<void, PreviewStopLocalServerError>;
73 }
74>()("t3/preview/PortScanner/PortDiscovery") {}
75​
76/**
77 * Agents launch with this set to their thread, and every job they start inherits it, so a
78 * server stays attributed after its launching shell exits or the agent settles.
79 */
80export const AGENT_THREAD_ENV = "T3CODE_THREAD_ID";
81​
82export interface AgentCommandStopWatcher {
83 /** The variable the CLI sets on each command it starts, naming that command. */
84 readonly variable: string;
85 readonly onStop: (command: string) => Effect.Effect<void>;
86 /** The signal never reached the command, so it is still running or ended by itself. */
87 readonly onStopAbandoned: (command: string) => Effect.Effect<void>;
89​
90/** `0` turns off listener discovery; configured preview URLs are still probed. */
91const PORT_DISCOVERY_ENV = "T3CODE_PORT_DISCOVERY";
92​
93const POLL_INTERVAL = Duration.seconds(3);
94const LSOF_TIMEOUT_MS = 5_000;
95const PROC_FD_WALK_LIMIT = 50_000;
96const SOCKET_OWNER_ATTEMPTS = 3;
97const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
98const WEB_PROBE_TIMEOUT = Duration.seconds(1);
99const WEB_PROBE_CACHE_TTL_MS = Duration.toMillis(Duration.seconds(15));
100/** Bounds how long a cached Windows image name can outlive its process if Windows reuses the PID. */
101const WINDOWS_PROCESS_NAME_TTL_MS = Duration.toMillis(Duration.seconds(60));
102const WINDOWS_PROCESS_NAME_CONCURRENCY = 4;
103const WEB_PROBE_CONCURRENCY = 16;
104const NAVIGATION_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
105const PS_TIMEOUT_MS = 5_000;
106const PS_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
107const STOP_GRACE_MS = 3_000;
108const STOP_POLL_INTERVAL = Duration.millis(250);
109​
110type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
111​
112interface ListenerSubscription {
113 readonly configuredUrls: ReadonlyArray<string>;
114 readonly lastSnapshot: ReadonlyArray<DiscoveredLocalServer>;
116​
117interface ScannerState {
118 readonly listeners: ReadonlyMap<Listener, ListenerSubscription>;
119 readonly terminalProcesses: ReadonlyMap<
120 string,
121 {
122 readonly owner: TerminalProcessOwner;
123 readonly processIds: ReadonlySet<number>;
124 }
125 >;
126 readonly retainCount: number;
128​
129interface TerminalProcessOwner {
130 readonly threadId: ThreadId;
131 readonly terminalId: string;
133​
134type ServerOwner = Pick<DiscoveredLocalServer, "terminal" | "agent">;
135​
136const UNOWNED: ServerOwner = { terminal: null, agent: null };
137​
138const isOwned = (server: DiscoveredLocalServer): boolean =>
139 server.terminal !== null || (server.agent ?? null) !== null;
140​
141interface ProcessTableRow {
142 readonly pid: number;
143 readonly ppid: number;
144 readonly pgid: number;
146​
147interface WebProbeCacheEntry {
148 readonly pid: number | null;
149 readonly isWeb: boolean;
150 readonly expiresAtMillis: number;
152​
153interface WebProbeGroup {
154 readonly server: DiscoveredLocalServer;
155 readonly url: string;
156 readonly configuredKey: string;
158​
159interface WebProbeSnapshot {
160 readonly discovered: ReadonlyArray<DiscoveredLocalServer>;
161 readonly configured: ReadonlyMap<string, DiscoveredLocalServer>;
163​
164const terminalOwnerKey = (owner: {
165 readonly threadId: string;
166 readonly terminalId: string;
167}): string => `${owner.threadId}\u0000${owner.terminalId}`;
168​
169const parseConfiguredUrl = (raw: string): URL | null => {
170 try {
171 const url = new URL(raw);
172 if (url.protocol !== "http:" && url.protocol !== "https:") return null;
173 if (!isLoopbackHost(url.hostname)) return null;
174 return url;
175 } catch {
176 return null;
177 }
178};
179​
180const localServerKey = (host: string, port: number): string =>
181 `${isLoopbackHost(host) ? "loopback" : host.toLowerCase()}:${port}`;
182​
183const urlPort = (url: URL): number =>
184 url.port.length > 0 ? Number.parseInt(url.port, 10) : url.protocol === "http:" ? 80 : 443;
185​
186const webProbeCacheKey = (raw: string): string => {
187 const url = new URL(raw);
188 url.hash = "";
189 return url.href;
190};
191​
192const normalizeConfiguredUrls = (urls: ReadonlyArray<string>): ReadonlyArray<string> => [
193 ...new Set(
194 urls
195 .slice(0, CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS)
196 .filter((raw) => raw.length <= PREVIEW_URL_MAX_LENGTH)
197 .map(parseConfiguredUrl)
198 .filter((url): url is URL => url !== null && url.href.length <= PREVIEW_URL_MAX_LENGTH)
199 .map((url) => {
200 if (url.hostname === "0.0.0.0") url.hostname = "localhost";
201 return url.href;
202 })
203 .filter((url) => url.length <= PREVIEW_URL_MAX_LENGTH),
204 ),
205];
206​
207const projectWebProbeSnapshot = (
208 snapshot: WebProbeSnapshot,
209 configuredUrls: ReadonlyArray<string>,
210): ReadonlyArray<DiscoveredLocalServer> => {
211 const visibleByServer = new Map<string, DiscoveredLocalServer>();
212 const firstConfiguredByServer = new Map<string, string>();
213 for (const raw of normalizeConfiguredUrls(configuredUrls)) {
214 const url = new URL(raw);
215 const port = urlPort(url);
216 const serverKey = localServerKey(url.hostname, port);
217 if (!firstConfiguredByServer.has(serverKey)) firstConfiguredByServer.set(serverKey, raw);
218 if (visibleByServer.has(serverKey)) continue;
219 const configured = snapshot.configured.get(webProbeCacheKey(raw));
220 if (configured) visibleByServer.set(serverKey, { ...configured, url: raw });
221 }
222 // An owned listener whose configured check failed still opens at this caller's configured URL.
223 for (const server of snapshot.discovered) {
224 const key = localServerKey(server.host, server.port);
225 if (visibleByServer.has(key)) continue;
226 const configuredUrl = firstConfiguredByServer.get(key);
227 visibleByServer.set(key, configuredUrl ? { ...server, url: configuredUrl } : server);
228 }
229 return [...visibleByServer.values()].toSorted((left, right) => left.port - right.port);
230};
231​
232const parseLsofOutput = (
233 raw: string,
234 owners: ReadonlyMap<number, ServerOwner> = new Map(),
235): ReadonlyArray<DiscoveredLocalServer> => {
236 const seen = new Map<string, DiscoveredLocalServer>();
237 let pid: number | null = null;
238 let processName: string | null = null;
239​
240 for (const line of raw.split("\n")) {
241 if (line.length === 0) continue;
242 const tag = line.charAt(0);
243 const value = line.slice(1);
244 if (tag === "p") {
245 const parsed = Number.parseInt(value, 10);
246 pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;
247 processName = null;
248 continue;
249 }
250 if (tag === "c") {
251 processName = value.trim() || null;
252 continue;
253 }
254 if (tag === "n") {
255 const portMatch = parsePortFromLsofName(value);
256 if (portMatch == null) continue;
257 const url = `http://localhost:${portMatch}`;
258 const key = `localhost:${portMatch}`;
259 const owner = pid === null ? undefined : owners.get(pid);
260 const existing = seen.get(key);
261 if (existing) {
262 if (owner === undefined) seen.set(key, { ...existing, ...UNOWNED });
263 continue;
264 }
265 seen.set(key, {
266 host: "localhost",
267 port: portMatch,
268 url,
269 processName,
270 pid,
271 ...(owner ?? UNOWNED),
272 });
273 }
274 }
275​
276 return Array.from(seen.values()).toSorted((a, b) => a.port - b.port);
277};
278​
279const parsePortFromLsofName = (name: string): number | null => {
280 const trimmed = name.split(" ", 1)[0]?.trim() ?? "";
281 if (trimmed.length === 0) return null;
282 const lastColon = trimmed.lastIndexOf(":");
283 if (lastColon < 0) return null;
284 const hostPart = trimmed.slice(0, lastColon);
285 const portPart = trimmed.slice(lastColon + 1);
286 if (!LSOF_LOCAL_HOST_TOKENS.has(hostPart)) return null;
287 const port = Number.parseInt(portPart, 10);
288 if (!Number.isFinite(port) || port <= 0 || port >= 65536) return null;
289 return port;
290};
291​
292const exitedWithError = (result: ProcessRunner.ProcessRunOutput): boolean =>
293 result.code !== null && result.code !== 0;
294​
295const parseTasklistProcessName = (raw: string, pid: number): string | null => {
296 for (const line of raw.split(/\r?\n/g)) {
297 const match = /^"([^"]*)","(\d+)"/.exec(line.trim());
298 if (match && Number(match[2]) === pid) return match[1]!.replace(/\.exe$/i, "") || null;
299 }
300 return null;
301};
302​
303const discoveredWindowsListeners = (
304 listeners: ReadonlyArray<WindowsTcpListeners.WindowsTcpListener>,
305 owners: ReadonlyMap<number, ServerOwner>,
306): ReadonlyArray<DiscoveredLocalServer> => {
307 const seen = new Map<number, DiscoveredLocalServer>();
308 for (const { port, pid } of listeners) {
309 const owner = pid === null ? undefined : owners.get(pid);
310 const existing = seen.get(port);
311 if (existing) {
312 if (owner === undefined) seen.set(port, { ...existing, ...UNOWNED });
313 continue;
314 }
315 seen.set(port, {
316 host: "localhost",
317 port,
318 url: `http://localhost:${port}`,
319 processName: null,
320 pid,
321 ...(owner ?? UNOWNED),
322 });
323 }
324 return [...seen.values()].toSorted((left, right) => left.port - right.port);
325};
326​
327const PROC_TCP_LISTEN = "0A";
328​
329/** Each 32-bit word of the hex address is little-endian. */
330const procLocalAddress = (hex: string): boolean => {
331 if (hex.length === 8) {
332 return hex === "00000000" || hex === "0100007F";
333 }
334 if (hex.length !== 32) return false;
335 if (hex === "0".repeat(32) || hex === `${"0".repeat(24)}01000000`) return true;
336 return hex.startsWith(`${"0".repeat(16)}FFFF0000`) && procLocalAddress(hex.slice(24));
337};
338​
339const parseProcNetTcp = (
340 raw: string,
341): ReadonlyArray<{ readonly port: number; readonly inode: string }> => {
342 const listeners: Array<{ port: number; inode: string }> = [];
343 for (const line of raw.split("\n").slice(1)) {
344 const fields = line.trim().split(/\s+/);
345 const [address, portHex] = fields[1]?.split(":") ?? [];
346 if (fields[3] !== PROC_TCP_LISTEN || !address || !portHex) continue;
347 if (!procLocalAddress(address.toUpperCase())) continue;
348 const port = Number.parseInt(portHex, 16);
349 const inode = fields[9];
350 if (!Number.isInteger(port) || port <= 0 || port >= 65536 || !inode) continue;
351 listeners.push({ port, inode });
352 }
353 return listeners;
354};
355​
356/** Processes holding a loopback or wildcard listener in `lsof -F pcn` output. */
357const lsofProcessIds = (raw: string): ReadonlyArray<number> => {
358 const pids = new Set<number>();
359 let pid: number | null = null;
360 for (const line of raw.split("\n")) {
361 if (line.startsWith("p")) {
362 const parsed = Number.parseInt(line.slice(1), 10);
363 pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;
364 } else if (
365 line.startsWith("n") &&
366 pid !== null &&
367 parsePortFromLsofName(line.slice(1)) !== null
368 ) {
369 pids.add(pid);
370 }
371 }
372 return [...pids];
373};
374​
375const AGENT_THREAD_ASSIGNMENT = new RegExp(`(?:^|\\s)${AGENT_THREAD_ENV}=(\\S+)`);
376​
377/** A browser an agent's tool drives listens only for DevTools, which is not a page to preview. */
378const DEVTOOLS_PORT_ARGUMENT = /(?:^|[\s\0])--remote-debugging-port=/;
379​
380/** Reads `/proc/<pid>/environ`, whose entries are NUL-separated. */
381const parseProcEnvironThread = (raw: string): ThreadId | null => {
382 const prefix = `${AGENT_THREAD_ENV}=`;
383 const value = raw
384 .split("\0")
385 .find((entry) => entry.startsWith(prefix))
386 ?.slice(prefix.length)
387 .trim();
388 return value ? ThreadId.make(value) : null;
389};
390​
391/**
392 * A listener with an agent thread in its environment. An agent CLI is spawned directly by this
393 * server or its Linux process launcher and has that environment too, but its own ports are not
394 * servers it started.
395 */
396interface AgentListener {
397 readonly threadId: ThreadId;
398 readonly isAgentCli: boolean;
400​
401const isServerSpawnedChild = (
402 parentPid: number | null,
403 serverPid: number,
404 launcherPid?: number,
405): boolean =>
406 parentPid !== null &&
407 (parentPid === serverPid || (launcherPid !== undefined && parentPid === launcherPid));
408​
409/** Reads the parent pid from `/proc/<pid>/stat`, whose command field can hold spaces. */
410const parseProcStatParent = (raw: string): number | null => {
411 const parent = Number(
412 raw
413 .slice(raw.lastIndexOf(")") + 1)
414 .trim()
415 .split(" ")[1],
416 );
417 return Number.isInteger(parent) ? parent : null;
418};
419​
420/**
421 * Reads macOS `ps -E -o pid=,ppid=,command=`, which appends each process's launch environment
422 * to its argv with spaces, so an argument that spells the assignment out also matches.
423 */
424const parsePsEnvironmentThreads = (
425 raw: string,
426 serverPid: number,
427 launcherPid?: number,
428): ReadonlyMap<number, AgentListener | null> => {
429 const threads = new Map<number, AgentListener | null>();
430 for (const line of raw.split("\n")) {
431 const match = /^\s*(\d+)\s+(\d+)\s(.*)$/.exec(line);
432 if (!match) continue;
433 const value = AGENT_THREAD_ASSIGNMENT.exec(match[3]!)?.[1];
434 threads.set(
435 Number(match[1]),
436 value && !DEVTOOLS_PORT_ARGUMENT.test(match[3]!)
437 ? {
438 threadId: ThreadId.make(value),
439 isAgentCli: isServerSpawnedChild(Number(match[2]), serverPid, launcherPid),
440 }
441 : null,
442 );
443 }
444 return threads;
445};
446​
447const parsePsCommandLines = (raw: string): ReadonlyMap<number, string> => {
448 const lines = new Map<number, string>();
449 for (const line of raw.split("\n")) {
450 const match = /^\s*(\d+)\s(.*)$/.exec(line);
451 if (match) lines.set(Number(match[1]), match[2]!);
452 }
453 return lines;
454};
455​
456/** Splits `/proc/<pid>/environ` on NUL, or the environment macOS `ps -E` appends on spaces. */
457const parseEnvironmentVariables = (
458 raw: string,
459 separator: "\0" | RegExp,
460 names: ReadonlyArray<string>,
461): ReadonlyMap<string, string> => {
462 const variables = new Map<string, string>();
463 for (const entry of raw.split(separator)) {
464 const name = names.find((candidate) => entry.startsWith(`${candidate}=`));
465 if (name !== undefined && !variables.has(name)) {
466 variables.set(name, entry.slice(name.length + 1));
467 }
468 }
469 return variables;
470};
471​
472/**
473 * The agent commands that signaling a group stops, by the variable naming each. A CLI starts a
474 * command as a group leader and names it in the command's environment, which the CLI itself does
475 * not carry. A job the command moved to its own group inherits the name from its parent, and
476 * stopping that job does not end the command.
477 */
478export const agentCommandsInGroup = (
479 variables: ReadonlyMap<number, ReadonlyMap<string, string>>,
480 leader: ProcessTableRow,
481): ReadonlyMap<string, string> => {
482 const commands = new Map<string, string>();
483 const parent = variables.get(leader.ppid);
484 // An unreadable parent cannot rule out an inherited name.
485 if (parent === undefined) return commands;
486 for (const [name, command] of variables.get(leader.pid) ?? []) {
487 if (command !== "" && parent.get(name) !== command) commands.set(name, command);
488 }
489 return commands;
490};
491​
492const parseProcessTable = (raw: string): ReadonlyMap<number, ProcessTableRow> => {
493 const rows = new Map<number, ProcessTableRow>();
494 for (const line of raw.split("\n")) {
495 const [pid, ppid, pgid] = line.trim().split(/\s+/).map(Number);
496 if (Number.isInteger(pid) && Number.isInteger(ppid) && Number.isInteger(pgid)) {
497 rows.set(pid!, { pid: pid!, ppid: ppid!, pgid: pgid! });
498 }
499 }
500 return rows;
501};
502​
503/**
504 * The process group stopping `pid` signals. Shells with job control and agent tool shells give
505 * every job its own group, so the group is the job. Null when the group also holds this server,
506 * a direct child of it or its process launcher (agent CLIs and terminal shells), or one of its
507 * ancestors.
508 */
509export const stoppableProcessGroup = (
510 table: ReadonlyMap<number, ProcessTableRow>,
511 pid: number,
512 serverPid: number,
513 launcherPid?: number,
514): number | null => {
515 const group = table.get(pid)?.pgid;
516 if (group === undefined || group <= 1) return null;
517 const guarded = new Set([serverPid]);
518 if (launcherPid !== undefined) guarded.add(launcherPid);
519 for (
520 let parent = table.get(serverPid)?.ppid;
521 parent !== undefined && parent > 1 && !guarded.has(parent);
522 parent = table.get(parent)?.ppid
523 ) {
524 guarded.add(parent);
525 }
526 for (const row of table.values()) {
527 if (
528 row.pgid === group &&
529 (guarded.has(row.pid) || isServerSpawnedChild(row.ppid, serverPid, launcherPid))
530 ) {
531 return null;
532 }
533 }
534 return group;
535};
536​
537const serversEqual = (
538 left: ReadonlyArray<DiscoveredLocalServer>,
539 right: ReadonlyArray<DiscoveredLocalServer>,
540): boolean => {
541 if (left.length !== right.length) return false;
542 for (let i = 0; i < left.length; i += 1) {
543 const a = left[i];
544 const b = right[i];
545 if (!a || !b) return false;
546 if (
547 a.host !== b.host ||
548 a.port !== b.port ||
549 a.url !== b.url ||
550 a.processName !== b.processName ||
551 a.pid !== b.pid ||
552 a.terminal?.threadId !== b.terminal?.threadId ||
553 a.terminal?.terminalId !== b.terminal?.terminalId ||
554 a.agent?.threadId !== b.agent?.threadId
555 ) {
556 return false;
557 }
558 }
559 return true;
560};
561​
562const isNoSuchProcess = (cause: unknown): boolean =>
563 typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ESRCH";
564​
565const isCommandNotFound = (error: ProcessRunner.ProcessSpawnError): boolean =>
566 PlatformError.isPlatformError(error.cause) && error.cause.reason._tag === "NotFound";
567​
568/** @public */
569export const make = Effect.gen(function* PortDiscoveryMake() {
570 const processRunner = yield* ProcessRunner.ProcessRunner;
571 const fileSystem = yield* FileSystem.FileSystem;
572 const hostPlatform = yield* HostProcess.Platform;
573 const listenerDiscovery = (yield* HostProcess.Environment)[PORT_DISCOVERY_ENV] !== "0";
574 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
575 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
576 const processLauncher = yield* ProcessLauncher.ProcessLauncher;
577 const stateRef = yield* Ref.make<ScannerState>({
578 listeners: new Map(),
579 terminalProcesses: new Map(),
580 retainCount: 0,
581 });
582 const webProbeCacheRef = yield* Ref.make<ReadonlyMap<string, WebProbeCacheEntry>>(new Map());
583 const scanSemaphore = yield* Semaphore.make(1);
584 const lsofMissingRef = yield* Ref.make(false);
585 const windowsProcessNamesRef = yield* Ref.make<
586 ReadonlyMap<number, { readonly name: string | null; readonly expiresAtMillis: number }>
587 >(new Map());
588 const socketOwnersRef = yield* Ref.make<
589 ReadonlyMap<string, { readonly pid: number; readonly processName: string | null }>
590 >(new Map());
591 const socketOwnerMissesRef = yield* Ref.make<ReadonlyMap<string, number>>(new Map());
592 // Each current listener pid's agent thread, or null without one. A process keeps its launch
593 // environment, so a pid is read once while it listens. Cleared while no client retains the
594 // scanner, since unscanned pids can be reused.
595 const agentThreadsRef = yield* Ref.make<ReadonlyMap<number, AgentListener | null>>(new Map());
596 const agentCommandStopWatchers = new Set<AgentCommandStopWatcher>();
597 let runningAgents = 0;
598 // An agent that exited, or a cache cleared with a marked listener, owes one listener read: the
599 // servers it left may still run. So does startup, for agents that ran before a restart.
600 let agentScanPending = true;
601​
602 const readAgentThreads = Effect.fn("PortDiscovery.readAgentThreads")(function* (
603 pids: ReadonlyArray<number>,
604 ) {
605 const cached = yield* Ref.get(agentThreadsRef);
606 const unread = pids.filter((pid) => !cached.has(pid));
607 const launcherPid = unread.length === 0 ? undefined : yield* processLauncher.currentPid;
608 const readProcListener = Effect.fnUntraced(function* (pid: number) {
609 const threadId = yield* fileSystem.readFileString(`/proc/${pid}/environ`).pipe(
610 Effect.map(parseProcEnvironThread),
611 Effect.orElseSucceed(() => null),
612 );
613 if (threadId === null) return [pid, null] as const;
614 const isDevTools = yield* fileSystem.readFileString(`/proc/${pid}/cmdline`).pipe(
615 Effect.map((cmdline) => DEVTOOLS_PORT_ARGUMENT.test(cmdline)),
616 Effect.orElseSucceed(() => false),
617 );
618 if (isDevTools) return [pid, null] as const;
619 const parent = yield* fileSystem.readFileString(`/proc/${pid}/stat`).pipe(
620 Effect.map(parseProcStatParent),
621 Effect.orElseSucceed(() => null),
622 );
623 return [
624 pid,
625 { threadId, isAgentCli: isServerSpawnedChild(parent, process.pid, launcherPid) },
626 ] as const;
627 });
628 const read: ReadonlyMap<number, AgentListener | null> =
629 unread.length === 0
630 ? new Map()
631 : hostPlatform === "linux"
632 ? new Map(yield* Effect.forEach(unread, readProcListener, { concurrency: 16 }))
633 : yield* processRunner
634 .run({
635 command: "ps",
636 args: ["-E", "-ww", "-o", "pid=,ppid=,command=", "-p", unread.join(",")],
637 timeout: Duration.millis(PS_TIMEOUT_MS),
638 maxOutputBytes: PS_MAX_OUTPUT_BYTES,
639 })
640 .pipe(
641 Effect.map((result) =>
642 parsePsEnvironmentThreads(result.stdout, process.pid, launcherPid),
643 ),
644 Effect.orElseSucceed(() => {
645 agentScanPending = true;
646 return new Map();
647 }),
648 );
649 const next = new Map<number, AgentListener | null>();
650 for (const pid of pids) {
651 const listener = cached.has(pid) ? cached.get(pid) : read.get(pid);
652 if (listener !== undefined) next.set(pid, listener);
653 }
654 yield* Ref.set(agentThreadsRef, next);
655 return next;
656 });
657​
658 const withAgentOwners = Effect.fn("PortDiscovery.withAgentOwners")(function* (
659 terminalOwners: ReadonlyMap<number, ServerOwner>,
660 pids: ReadonlyArray<number>,
661 ) {
662 // Runs only once a listener snapshot exists, so a failed read leaves the scan pending.
663 agentScanPending = false;
664 const threads = yield* readAgentThreads(pids.filter((pid) => !terminalOwners.has(pid)));
665 const owners = new Map(terminalOwners);
666 for (const [pid, listener] of threads) {
667 if (listener !== null && !listener.isAgentCli) {
668 owners.set(pid, { terminal: null, agent: { threadId: listener.threadId } });
669 }
670 }
671 return owners;
672 });
673​
674 const findSocketOwners = Effect.fn("PortDiscovery.findSocketOwners")(function* (
675 inodes: ReadonlySet<string>,
676 ) {
677 const owners = new Map<string, { pid: number; processName: string | null }>();
678 const entries = yield* fileSystem.readDirectory("/proc").pipe(Effect.option);
679 if (Option.isNone(entries)) return null;
680 const pids = entries.value.filter((entry) => /^\d+$/.test(entry));
681 let budget = PROC_FD_WALK_LIMIT;
682 for (const pidText of pids) {
683 if (owners.size === inodes.size || budget <= 0) break;
684 const fds = yield* fileSystem
685 .readDirectory(`/proc/${pidText}/fd`)
686 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
687 const walked = fds.slice(0, budget);
688 budget -= walked.length;
689 const links = yield* Effect.forEach(
690 walked,
691 (fd) =>
692 fileSystem.readLink(`/proc/${pidText}/fd/${fd}`).pipe(Effect.orElseSucceed(() => "")),
693 { concurrency: 16 },
694 );
695 const held = links.flatMap((link) => /^socket:\[(\d+)\]$/.exec(link)?.[1] ?? []);
696 const matched = held.filter((inode) => inodes.has(inode) && !owners.has(inode));
697 if (matched.length === 0) continue;
698 const processName = yield* fileSystem.readFileString(`/proc/${pidText}/comm`).pipe(
699 Effect.map((name) => name.trim() || null),
700 Effect.orElseSucceed(() => null),
701 );
702 for (const inode of matched) owners.set(inode, { pid: Number(pidText), processName });
703 }
704 const lsofMissing = yield* Ref.get(lsofMissingRef);
705 return budget <= 0 && owners.size < inodes.size && !lsofMissing ? null : owners;
706 });
707​
708 const scanProcListeners = Effect.fn("PortDiscovery.scanProcListeners")(function* (
709 resolveOwners: (pids: ReadonlyArray<number>) => Effect.Effect<ReadonlyMap<number, ServerOwner>>,
710 ) {
711 if (hostPlatform !== "linux") return null;
712 const tables = yield* Effect.forEach(["/proc/net/tcp", "/proc/net/tcp6"], (path) =>
713 fileSystem.readFileString(path).pipe(
714 // Kernels without IPv6 omit tcp6; a denied table can hide listeners on a shared port.
715 Effect.catchIf(
716 (error) => error.reason._tag === "NotFound",
717 () => Effect.succeed(null),
718 ),
719 Effect.option,
720 ),
721 );
722 if (tables.some(Option.isNone)) return null;
723 const readable = tables.flatMap((table) =>
724 Option.isSome(table) && table.value !== null ? [table.value] : [],
725 );
726 if (
727 readable.length === 0 ||
728 readable.some(
729 (table) => !/^\s*sl\s+local_address\s+(?:rem|remote)_address\s+st\s/.test(table),
730 )
731 )
732 return null;
733 const listeners = readable.flatMap(parseProcNetTcp);
734 const known = yield* Ref.get(socketOwnersRef);
735 const knownMisses = yield* Ref.get(socketOwnerMissesRef);
736 const inodes = new Set(listeners.map((listener) => listener.inode));
737 // Walk fds only for unowned sockets; stop after repeated misses for inaccessible or exited processes.
738 const unseen = new Set(
739 [...inodes].filter(
740 (inode) => !known.has(inode) && (knownMisses.get(inode) ?? 0) < SOCKET_OWNER_ATTEMPTS,
741 ),
742 );
743 const found = unseen.size === 0 ? new Map() : yield* findSocketOwners(unseen);
744 if (found === null) return null;
745 const owners = new Map([...known, ...found].filter(([inode]) => inodes.has(inode)));
746 const misses = new Map([...knownMisses].filter(([inode]) => inodes.has(inode)));
747 for (const inode of unseen) {
748 if (!found.has(inode)) misses.set(inode, (misses.get(inode) ?? 0) + 1);
749 }
750 yield* Ref.set(socketOwnersRef, owners);
751 yield* Ref.set(socketOwnerMissesRef, misses);
752 const serverOwners = yield* resolveOwners([
753 ...new Set([...owners.values()].map(({ pid }) => pid)),
754 ]);
755 const seen = new Map<number, DiscoveredLocalServer>();
756 for (const { port, inode } of listeners) {
757 const socketOwner = owners.get(inode) ?? null;
758 const owner = socketOwner === null ? undefined : serverOwners.get(socketOwner.pid);
759 const existing = seen.get(port);
760 if (existing && (existing.pid !== null || socketOwner === null)) {
761 if (owner === undefined) seen.set(port, { ...existing, ...UNOWNED });
762 continue;
763 }
764 seen.set(port, {
765 host: "localhost",
766 port,
767 url: `http://localhost:${port}`,
768 processName: socketOwner?.processName ?? null,
769 pid: socketOwner?.pid ?? null,
770 ...(existing ? UNOWNED : (owner ?? UNOWNED)),
771 });
772 }
773 return [...seen.values()].toSorted((left, right) => left.port - right.port);
774 });
775​
776 const probeWebUrl = Effect.fn("PortDiscovery.probeWebUrl")((url: string) =>
777 httpClient.get(url).pipe(
778 Effect.map((response) => {
779 const location = response.headers.location?.trim();
780 if (NAVIGATION_REDIRECT_STATUSES.has(response.status) && location) return url;
781 if (response.status < 200 || response.status >= 300) return null;
782 if (response.status === 204 || response.status === 205) return null;
783 const contentType = response.headers["content-type"]
784 ?.split(";", 1)[0]
785 ?.trim()
786 .toLowerCase();
787 return contentType === "text/html" || contentType === "application/xhtml+xml" ? url : null;
788 }),
789 Effect.scoped,
790 Effect.timeoutOption(WEB_PROBE_TIMEOUT),
791 Effect.map(Option.getOrNull),
792 Effect.orElseSucceed(() => null),
793 Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
794 ),
795 );
796​
797 const makeWebProbeGroups = (
798 servers: ReadonlyArray<DiscoveredLocalServer>,
799 configuredUrls: ReadonlyArray<string>,
800 ): ReadonlyArray<WebProbeGroup> => {
801 const serversByKey = new Map(
802 servers.map((server) => [localServerKey(server.host, server.port), server] as const),
803 );
804 const groups: WebProbeGroup[] = [];
805 const configuredResources = new Set<string>();
806​
807 for (const raw of configuredUrls) {
808 const url = new URL(raw);
809 const port = urlPort(url);
810 const key = localServerKey(url.hostname, port);
811 const resourceKey = webProbeCacheKey(raw);
812 if (configuredResources.has(resourceKey)) continue;
813 configuredResources.add(resourceKey);
814 groups.push({
815 server: serversByKey.get(key) ?? {
816 host: url.hostname,
817 port,
818 url: raw,
819 processName: null,
820 pid: null,
821 terminal: null,
822 },
823 url: raw,
824 configuredKey: resourceKey,
825 });
826 }
827​
828 return groups;
829 };
830​
831 // Only configured URLs are requested. Owned listeners are listed as plain HTTP without a
832 // request: owning a process says nothing about its protocol, and HTTP or TLS bytes break
833 // binary ones such as Unity's test runner or Steam's IPC.
834 // Idle polls omit this span; requested scans and uncached probes retain their own spans.
835 const probeWebServers = Effect.fnUntraced(function* (
836 servers: ReadonlyArray<DiscoveredLocalServer>,
837 configuredUrls: ReadonlyArray<string>,
838 ) {
839 const nowMillis = yield* Clock.currentTimeMillis;
840 const cached = yield* Ref.get(webProbeCacheRef);
841 const groups = makeWebProbeGroups(servers, configuredUrls);
842 const probed = yield* Effect.forEach(
843 groups,
844 (group) => {
845 const { pid } = group.server;
846 const cachedProbe = cached.get(group.configuredKey);
847 return cachedProbe?.pid === pid && cachedProbe.expiresAtMillis > nowMillis
848 ? Effect.succeed({ group, probe: cachedProbe, fresh: false })
849 : probeWebUrl(group.url).pipe(
850 Effect.map((result) => ({
851 group,
852 probe: { pid, isWeb: result !== null, expiresAtMillis: 0 },
853 fresh: true,
854 })),
855 );
856 },
857 { concurrency: WEB_PROBE_CONCURRENCY },
858 );
859 const completedAtMillis = yield* Clock.currentTimeMillis;
860 const nextCache = new Map(
861 [...cached].filter(([, probe]) => probe.expiresAtMillis > completedAtMillis),
862 );
863 const configured = new Map<string, DiscoveredLocalServer>();
864 for (const { group, probe, fresh } of probed) {
865 nextCache.set(
866 group.configuredKey,
867 fresh ? { ...probe, expiresAtMillis: completedAtMillis + WEB_PROBE_CACHE_TTL_MS } : probe,
868 );
869 if (probe.isWeb) configured.set(group.configuredKey, { ...group.server, url: group.url });
870 }
871 yield* Ref.set(webProbeCacheRef, nextCache);
872 return { discovered: servers.filter(isOwned), configured } satisfies WebProbeSnapshot;
873 });
874​
875 // tasklist costs 200-300ms per PID; query visible servers with bounded concurrency and cache names.
876 const withWindowsProcessNames = Effect.fn("PortDiscovery.withWindowsProcessNames")(function* (
877 snapshot: WebProbeSnapshot,
878 ) {
879 const servers = [...snapshot.discovered, ...snapshot.configured.values()];
880 const pids = new Set(servers.flatMap((server) => (server.pid === null ? [] : [server.pid])));
881 const nowMillis = yield* Clock.currentTimeMillis;
882 const cached = [...(yield* Ref.get(windowsProcessNamesRef))].filter(
883 ([pid, entry]) => pids.has(pid) && entry.expiresAtMillis > nowMillis,
884 );
885 const cachedPids = new Set(cached.map(([pid]) => pid));
886 const expiresAtMillis = nowMillis + WINDOWS_PROCESS_NAME_TTL_MS;
887 const tasklist = windowsSystem32Path(yield* HostProcess.Environment, "tasklist.exe");
888 const fetched = yield* Effect.forEach(
889 [...pids].filter((pid) => !cachedPids.has(pid)),
890 (pid) =>
891 processRunner
892 .run({
893 command: tasklist,
894 args: ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`],
895 timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
896 maxOutputBytes: 64 * 1024,
897 })
898 .pipe(
899 Effect.map((result) =>
900 exitedWithError(result)
901 ? []
902 : [
903 [
904 pid,
905 { name: parseTasklistProcessName(result.stdout, pid), expiresAtMillis },
906 ] as const,
907 ],
908 ),
909 Effect.orElseSucceed(() => []),
910 ),
911 { concurrency: WINDOWS_PROCESS_NAME_CONCURRENCY },
912 );
913 const names = new Map([...cached, ...fetched.flat()]);
914 yield* Ref.set(windowsProcessNamesRef, names);
915 const withName = (server: DiscoveredLocalServer): DiscoveredLocalServer =>
916 server.pid === null || server.processName !== null
917 ? server
918 : { ...server, processName: names.get(server.pid)?.name ?? null };
919 return {
920 discovered: snapshot.discovered.map(withName),
921 configured: new Map([...snapshot.configured].map(([key, server]) => [key, withName(server)])),
922 } satisfies WebProbeSnapshot;
923 });
924​
925 const recoverProcessProbeFailure =
926 (probe: "lsof" | "windows-listeners") => (error: ProcessRunner.ProcessRunError) =>
927 Effect.logDebug("preview port process probe failed; probing configured URLs only", {
928 cause: error,
929 probe,
930 platform: hostPlatform,
931 }).pipe(Effect.as(null));
932​
933 // Routine polling helpers share operation/probe spans instead of tracing every tick.
934 const scanUnlocked = Effect.fnUntraced(function* (configuredUrls: ReadonlyArray<string>) {
935 if (!listenerDiscovery) return yield* probeWebServers([], configuredUrls);
936 const state = yield* Ref.get(stateRef);
937 const terminalOwners = new Map<number, ServerOwner>();
938 for (const registration of state.terminalProcesses.values()) {
939 for (const processId of registration.processIds) {
940 terminalOwners.set(processId, { terminal: registration.owner, agent: null });
941 }
942 }
943 // A server an agent started can outlive the agent, so listeners are read while the last scan
944 // still found one.
945 const agentsPossible =
946 hostPlatform !== "win32" &&
947 (runningAgents > 0 ||
948 agentScanPending ||
949 [...(yield* Ref.get(agentThreadsRef)).values()].some((threadId) => threadId !== null));
950 if (terminalOwners.size === 0 && configuredUrls.length === 0 && !agentsPossible) {
951 return { discovered: [], configured: new Map() } satisfies WebProbeSnapshot;
952 }
953 const resolveOwners = (pids: ReadonlyArray<number>) =>
954 agentsPossible ? withAgentOwners(terminalOwners, pids) : Effect.succeed(terminalOwners);
955 if (hostPlatform === "win32") {
956 const recoverWindowsProbeFailure = recoverProcessProbeFailure("windows-listeners");
957 const listeners = yield* WindowsTcpListeners.queryWindowsTcpListeners(
958 processRunner,
959 "netstat.exe",
960 ).pipe(
961 Effect.map((snapshot) =>
962 snapshot === null ? null : discoveredWindowsListeners(snapshot, terminalOwners),
963 ),
964 Effect.catchTags({
965 ProcessSpawnError: recoverWindowsProbeFailure,
966 ProcessStdinError: recoverWindowsProbeFailure,
967 ProcessOutputLimitError: recoverWindowsProbeFailure,
968 ProcessReadError: recoverWindowsProbeFailure,
969 ProcessTimeoutError: recoverWindowsProbeFailure,
970 }),
971 );
972 return yield* withWindowsProcessNames(
973 yield* probeWebServers(listeners ?? [], configuredUrls),
974 );
975 }
976 const fromProc = yield* scanProcListeners(resolveOwners);
977 if (fromProc !== null) return yield* probeWebServers(fromProc, configuredUrls);
978 const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof");
979 if (yield* Ref.get(lsofMissingRef)) return yield* probeWebServers([], configuredUrls);
980 const lsofResult = yield* processRunner
981 .run({
982 command: "lsof",
983 args: ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"],
984 timeout: Duration.millis(LSOF_TIMEOUT_MS),
985 // Partial output could hide another app's listener on an owned port.
986 maxOutputBytes: 1024 * 1024,
987 })
988 .pipe(
989 Effect.flatMap((result) =>
990 resolveOwners(lsofProcessIds(result.stdout)).pipe(
991 Effect.map((owners) => parseLsofOutput(result.stdout, owners)),
992 ),
993 ),
994 Effect.catchTags({
995 ProcessSpawnError: (error) =>
996 (isCommandNotFound(error) ? Ref.set(lsofMissingRef, true) : Effect.void).pipe(
997 Effect.andThen(recoverLsofProbeFailure(error)),
998 ),
999 ProcessStdinError: recoverLsofProbeFailure,
1000 ProcessOutputLimitError: recoverLsofProbeFailure,
1001 ProcessReadError: recoverLsofProbeFailure,
1002 ProcessTimeoutError: recoverLsofProbeFailure,
1003 }),
1004 );
1005 if (lsofResult !== null) return yield* probeWebServers(lsofResult, configuredUrls);
1006 // A missing lsof makes a bounded, partial /proc owner walk the only available discovery.
1007 const withoutLsof = (yield* Ref.get(lsofMissingRef))
1008 ? yield* scanProcListeners(resolveOwners)
1009 : null;
1010 return yield* probeWebServers(withoutLsof ?? [], configuredUrls);
1011 });
1012​
1013 const scanSnapshot = (configuredUrls: ReadonlyArray<string>) =>
1014 scanSemaphore.withPermits(1)(scanUnlocked(configuredUrls));
1015​
1016 const scanOnce: PortDiscovery["Service"]["scan"] = (configuredUrls = []) => {
1017 const normalized = normalizeConfiguredUrls(configuredUrls);
1018 return scanSnapshot(normalized).pipe(
1019 Effect.map((snapshot) => projectWebProbeSnapshot(snapshot, normalized)),
1020 Effect.withSpan("PortDiscovery.scan"),
1021 );
1022 };
1023​
1024 const pollTick = Effect.fnUntraced(
1025 function* () {
1026 const configuredUrls = [
1027 ...new Set(
1028 [...(yield* Ref.get(stateRef)).listeners.values()].flatMap(
1029 (subscription) => subscription.configuredUrls,
1030 ),
1031 ),
1032 ];
1033 const snapshot = yield* scanSnapshot(configuredUrls);
1034 const notifications = yield* Ref.modify(stateRef, (state) => {
1035 const listeners = new Map(state.listeners);
1036 const changed: Array<readonly [Listener, ReadonlyArray<DiscoveredLocalServer>]> = [];
1037 for (const [listener, subscription] of listeners) {
1038 const next = projectWebProbeSnapshot(snapshot, subscription.configuredUrls);
1039 if (serversEqual(subscription.lastSnapshot, next)) continue;
1040 listeners.set(listener, { ...subscription, lastSnapshot: next });
1041 changed.push([listener, next]);
1043 return [changed, { ...state, listeners }];
1044 });
1045 yield* Effect.forEach(notifications, ([listener, servers]) => listener(servers), {
1046 discard: true,
1047 });
1048 },
1049 Effect.catchCause((cause: Cause.Cause<never>) =>
1050 Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
1051 ),
1052 );
1053​
1054 const pollIfRetained = Ref.get(stateRef).pipe(
1055 Effect.flatMap((state) => (state.retainCount > 0 ? pollTick() : Effect.void)),
1056 );
1057 const scheduledPoll = backgroundPolicy.shouldRunOpportunisticWork.pipe(
1058 Effect.flatMap((foreground) => (foreground ? pollIfRetained : Effect.void)),
1059 );
1060 yield* Effect.forkScoped(scheduledPoll.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
1061​
1062 const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {
1063 const wasIdle = yield* Ref.modify(stateRef, (state) => [
1064 state.retainCount === 0,
1065 { ...state, retainCount: state.retainCount + 1 },
1066 ]);
1067 if (wasIdle) {
1068 yield* pollTick();
1070 });
1071​
1072 const releaseRetention = Effect.gen(function* () {
1073 const idle = yield* Ref.modify(stateRef, (state) => {
1074 const retainCount = Math.max(0, state.retainCount - 1);
1075 return [retainCount === 0, { ...state, retainCount }];
1076 });
1077 if (!idle) return;
1078 yield* scanSemaphore.withPermits(1)(
1079 Effect.gen(function* () {
1080 yield* Ref.set(socketOwnersRef, new Map());
1081 yield* Ref.set(socketOwnerMissesRef, new Map());
1082 const threads = yield* Ref.getAndSet(agentThreadsRef, new Map());
1083 if ([...threads.values()].some((threadId) => threadId !== null)) agentScanPending = true;
1084 }),
1085 );
1086 });
1087​
1088 const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(
1089 acquireRetention(),
1090 () => releaseRetention,
1091 );
1092​
1093 const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
1094 (input, listener) =>
1095 Effect.acquireRelease(
1096 Ref.update(stateRef, (state) => {
1097 const listeners = new Map(state.listeners);
1098 listeners.set(listener, {
1099 configuredUrls: normalizeConfiguredUrls(input.configuredUrls),
1100 lastSnapshot: input.initialSnapshot,
1101 });
1102 return { ...state, listeners };
1103 }),
1104 () =>
1105 Ref.update(stateRef, (state) => {
1106 const listeners = new Map(state.listeners);
1107 listeners.delete(listener);
1108 return { ...state, listeners };
1109 }),
1110 ),
1111 );
1112​
1113 const registerTerminalProcesses: PortDiscovery["Service"]["registerTerminalProcesses"] =
1114 Effect.fn("PortDiscovery.registerTerminalProcesses")(function* (input) {
1115 const owner = {
1116 threadId: ThreadId.make(input.threadId),
1117 terminalId: input.terminalId,
1118 };
1119 const processIds = new Set(
1120 input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
1121 );
1122 yield* Ref.update(stateRef, (state) => {
1123 const terminalProcesses = new Map(state.terminalProcesses);
1124 const key = terminalOwnerKey(owner);
1125 if (processIds.size === 0) {
1126 terminalProcesses.delete(key);
1127 } else {
1128 terminalProcesses.set(key, { owner, processIds });
1130 return { ...state, terminalProcesses };
1131 });
1132 });
1133​
1134 const unregisterTerminal: PortDiscovery["Service"]["unregisterTerminal"] = Effect.fn(
1135 "PortDiscovery.unregisterTerminal",
1136 )(function* (input) {
1137 yield* Ref.update(stateRef, (state) => {
1138 const terminalProcesses = new Map(state.terminalProcesses);
1139 terminalProcesses.delete(terminalOwnerKey(input));
1140 return { ...state, terminalProcesses };
1141 });
1142 });
1143​
1144 const trackAgent: PortDiscovery["Service"]["trackAgent"] = () => {
1145 runningAgents += 1;
1146 let released = false;
1147 return () => {
1148 if (released) return;
1149 released = true;
1150 runningAgents -= 1;
1151 agentScanPending = true;
1152 };
1153 };
1154​
1155 const watchAgentCommandStops: PortDiscovery["Service"]["watchAgentCommandStops"] = (watcher) =>
1156 Effect.acquireRelease(
1157 Effect.sync(() => {
1158 agentCommandStopWatchers.add(watcher);
1159 }),
1160 () => Effect.sync(() => agentCommandStopWatchers.delete(watcher)),
1161 );
1162​
1163 /** Each process's launch values for `names`; a process that cannot be read is left out. */
1164 const readEnvironmentVariables = Effect.fn("PortDiscovery.readEnvironmentVariables")(function* (
1165 pids: ReadonlyArray<number>,
1166 names: ReadonlyArray<string>,
1167 ) {
1168 if (hostPlatform === "linux") {
1169 const read = yield* Effect.forEach(pids, (pid) =>
1170 fileSystem.readFileString(`/proc/${pid}/environ`).pipe(
1171 Effect.map((raw) => [pid, parseEnvironmentVariables(raw, "\0", names)] as const),
1172 Effect.option,
1173 ),
1174 );
1175 return new Map(read.flatMap(Option.toArray));
1177 const readCommandLines = (withEnvironment: boolean) =>
1178 processRunner
1179 .run({
1180 command: "ps",
1181 args: [
1182 ...(withEnvironment ? ["-E"] : []),
1183 "-ww",
1184 "-o",
1185 "pid=,command=",
1186 "-p",
1187 pids.join(","),
1188 ],
1189 timeout: Duration.millis(PS_TIMEOUT_MS),
1190 maxOutputBytes: PS_MAX_OUTPUT_BYTES,
1191 })
1192 .pipe(
1193 Effect.map((result) => parsePsCommandLines(result.stdout)),
1194 Effect.orElseSucceed(() => new Map<number, string>()),
1195 );
1196 // `ps -E` prints the environment after the arguments, so the arguments alone are read
1197 // separately and only what follows them counts as environment.
1198 const [withEnvironment, argumentsOnly] = yield* Effect.all(
1199 [readCommandLines(true), readCommandLines(false)],
1200 { concurrency: 2 },
1201 );
1202 const variables = new Map<number, ReadonlyMap<string, string>>();
1203 for (const [pid, line] of withEnvironment) {
1204 const commandLine = argumentsOnly.get(pid);
1205 if (commandLine !== undefined && line.startsWith(commandLine)) {
1206 variables.set(pid, parseEnvironmentVariables(line.slice(commandLine.length), /\s+/, names));
1209 return variables;
1210 });
1211​
1212 const agentCommandStops = Effect.fn("PortDiscovery.agentCommandStops")(function* (
1213 leader: ProcessTableRow | undefined,
1214 ) {
1215 const watchers = [...agentCommandStopWatchers];
1216 if (leader === undefined || watchers.length === 0) return [];
1217 const names = [...new Set(watchers.map((watcher) => watcher.variable))];
1218 const commands = agentCommandsInGroup(
1219 yield* readEnvironmentVariables([leader.pid, leader.ppid], names),
1220 leader,
1221 );
1222 return watchers.flatMap((watcher) => {
1223 const command = commands.get(watcher.variable);
1224 return command === undefined ? [] : [{ watcher, command }];
1225 });
1226 });
1227​
1228 // Fails when `ps` does, so an empty table never reads as every process having exited.
1229 const readProcessTable = Effect.suspend(() =>
1230 processRunner.run({
1231 command: "ps",
1232 args: ["-A", "-o", "pid=,ppid=,pgid="],
1233 timeout: Duration.millis(PS_TIMEOUT_MS),
1234 maxOutputBytes: PS_MAX_OUTPUT_BYTES,
1235 }),
1236 ).pipe(
1237 Effect.mapError((cause) => new PreviewStopLocalServerError({ reason: "signal-failed", cause })),
1238 Effect.filterOrFail(
1239 (result) => !exitedWithError(result),
1240 () => new PreviewStopLocalServerError({ reason: "signal-failed" }),
1241 ),
1242 Effect.map((result) => parseProcessTable(result.stdout)),
1243 );
1244​
1245 const signalUntilStopped = Effect.fn("PortDiscovery.signalUntilStopped")(function* (
1246 input: PreviewStopLocalServerInput,
1247 ) {
1248 if (hostPlatform === "win32") {
1249 return yield* new PreviewStopLocalServerError({ reason: "unsupported" });
1251 // A socket can outlive its cached owner. Wait for any in-flight scan before invalidating
1252 // that owner, so the /proc fallback confirms who holds it before a signal is sent.
1253 yield* scanSemaphore.withPermits(1)(
1254 Ref.update(
1255 socketOwnersRef,
1256 (owners) => new Map([...owners].filter(([, owner]) => owner.pid !== input.pid)),
1257 ),
1258 );
1259 // The pid comes from a client, so only a server this scan attributes to a thread is signaled,
1260 // from its environment as read now.
1261 yield* Ref.update(agentThreadsRef, (threads) => {
1262 const next = new Map(threads);
1263 next.delete(input.pid);
1264 return next;
1265 });
1266 agentScanPending = true;
1267 const listed = (yield* scanOnce()).some(
1268 (server) => server.pid === input.pid && server.port === input.port && isOwned(server),
1269 );
1270 if (!listed) return yield* new PreviewStopLocalServerError({ reason: "not-found" });
1271 const table = yield* readProcessTable;
1272 // It exited after the scan, so there is nothing left to stop.
1273 if (!table.has(input.pid)) return;
1274 const group = stoppableProcessGroup(
1275 table,
1276 input.pid,
1277 process.pid,
1278 yield* processLauncher.currentPid,
1279 );
1280 if (group === null) return yield* new PreviewStopLocalServerError({ reason: "shared-group" });
1281 // False when the whole group already exited.
1282 const signalGroup = (signal: "SIGTERM" | "SIGKILL") =>
1283 Effect.suspend(() => {
1284 try {
1285 signalProcessGroup(group, signal);
1286 return Effect.succeed(true);
1287 } catch (cause) {
1288 return isNoSuchProcess(cause)
1289 ? Effect.succeed(false)
1290 : Effect.fail(new PreviewStopLocalServerError({ reason: "signal-failed", cause }));
1292 });
1293 // Told before the signal, since the CLI can report the exit before a later step runs.
1294 const commandStops = yield* agentCommandStops(table.get(group));
1295 yield* Effect.forEach(commandStops, ({ watcher, command }) => watcher.onStop(command), {
1296 discard: true,
1297 });
1298 const abandonCommandStops = Effect.forEach(
1299 commandStops,
1300 ({ watcher, command }) => watcher.onStopAbandoned(command),
1301 { discard: true },
1302 );
1303 if (!(yield* signalGroup("SIGTERM").pipe(Effect.tapError(() => abandonCommandStops)))) {
1304 return yield* abandonCommandStops;
1306 // While one of the group's original members is still in it, the group has not been reused,
1307 // so SIGKILL goes only to the job that ignored SIGTERM.
1308 const members = [...table.values()].filter((row) => row.pgid === group).map((row) => row.pid);
1309 const jobRunning = readProcessTable.pipe(
1310 Effect.map((current) => members.some((pid) => current.get(pid)?.pgid === group)),
1311 Effect.orElseSucceed(() => false),
1312 );
1313 const deadline = (yield* Clock.currentTimeMillis) + STOP_GRACE_MS;
1314 while ((yield* Clock.currentTimeMillis) < deadline) {
1315 yield* Effect.sleep(STOP_POLL_INTERVAL);
1316 if (!(yield* jobRunning)) return;
1318 yield* signalGroup("SIGKILL");
1319 });
1320​
1321 const stopServer: PortDiscovery["Service"]["stopServer"] = (input) =>
1322 // Subscribers see the server leave now rather than on the next poll.
1323 signalUntilStopped(input).pipe(Effect.andThen(pollIfRetained));
1324​
1325 return PortDiscovery.of({
1326 scan: scanOnce,
1327 subscribe,
1328 retain,
1329 registerTerminalProcesses,
1330 unregisterTerminal,
1331 trackAgent,
1332 watchAgentCommandStops,
1333 stopServer,
1334 });
1335}).pipe(Effect.withSpan("PortDiscovery.make"));
1336​
1337export const layer = Layer.effect(PortDiscovery, make);
1338​
1339/** A scanner that tracks nothing, for tests that build provider runners without a host. */
1340export const layerTest = Layer.mock(PortDiscovery)({
1341 trackAgent: () => () => undefined,
1342 watchAgentCommandStops: () => Effect.void,
1343});