Open History to see the last commit
1/**
2 * In-process PortScanner implementation.
3 *
4 * macOS/Linux: parses `lsof -iTCP -sTCP:LISTEN -P -n -F pcn` (-F output is a
5 * stable line-prefixed field format; this is the only `lsof` flag set we rely
6 * on).
7 *
8 * Linux without lsof: reads listening sockets from `/proc/net/tcp{,6}` and
9 * finds their processes through `/proc/<pid>/fd`.
10 *
11 * Only listeners owned by T3 terminal processes and explicitly configured
12 * URLs receive probes. Without listener ownership, only configured URLs do.
13 *
14 * Listening ports are published only after a bounded HTTP(S) probe finds a
15 * successful HTML document or a redirect to one.
16 * Positive and negative results are cached briefly by candidate URL and listener identity,
17 * limiting repeated requests without leaving stale classifications around.
18 *
19 * Polling is reference-counted via scoped `retain`. A single layer-scoped fiber
20 * polls forever, but each tick is a no-op when the retain count is zero.
21 */
22import {
23 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
24 PREVIEW_URL_MAX_LENGTH,
25 ThreadId,
26 type DiscoveredLocalServer,
27} from "@t3tools/contracts";
28import * as HostProcess from "@t3tools/shared/HostProcess";
29import { isLoopbackHost, LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
30import * as Cause from "effect/Cause";
31import * as Clock from "effect/Clock";
32import * as Context from "effect/Context";
33import * as Duration from "effect/Duration";
34import * as Effect from "effect/Effect";
35import * as FileSystem from "effect/FileSystem";
36import * as Layer from "effect/Layer";
37import * as Option from "effect/Option";
38import * as PlatformError from "effect/PlatformError";
39import * as Ref from "effect/Ref";
40import * as Schedule from "effect/Schedule";
41import * as Scope from "effect/Scope";
42import * as Semaphore from "effect/Semaphore";
43import { FetchHttpClient, HttpClient } from "effect/http";
44
45import * as ProcessRunner from "../processRunner.ts";
46
47export class PortDiscovery extends Context.Service<
48 PortDiscovery,
49 {
50 readonly scan: (
51 configuredUrls?: ReadonlyArray<string>,
52 ) => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
53 readonly subscribe: (
54 input: {
55 readonly configuredUrls: ReadonlyArray<string>;
56 readonly initialSnapshot: ReadonlyArray<DiscoveredLocalServer>;
57 },
58 listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
59 ) => Effect.Effect<void, never, Scope.Scope>;
60 readonly retain: Effect.Effect<void, never, Scope.Scope>;
61 readonly registerTerminalProcesses: (input: {
62 readonly threadId: string;
63 readonly terminalId: string;
64 readonly processIds: ReadonlyArray<number>;
65 }) => Effect.Effect<void>;
66 readonly unregisterTerminal: (input: {
67 readonly threadId: string;
68 readonly terminalId: string;
69 }) => Effect.Effect<void>;
70 }
71>()("t3/preview/PortScanner/PortDiscovery") {}
72
73const POLL_INTERVAL = Duration.seconds(3);
74const LSOF_TIMEOUT_MS = 5_000;
75/** File descriptors one `/proc` walk may read before it stops looking for socket owners. */
76const PROC_FD_WALK_LIMIT = 50_000;
77/** Scans that retry the fd walk for a listening socket whose owner was not found. */
78const SOCKET_OWNER_ATTEMPTS = 3;
79const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
80/** `netstat -ano` lists every connection, not just listeners; ~80 bytes per row, sized for ~200k rows. */
81const WINDOWS_NETSTAT_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
82const WEB_PROBE_TIMEOUT = Duration.seconds(1);
83const WEB_PROBE_CACHE_TTL_MS = Duration.toMillis(Duration.seconds(15));
84/** Bounds how long a cached Windows image name can outlive its process if Windows reuses the PID. */
85const WINDOWS_PROCESS_NAME_TTL_MS = Duration.toMillis(Duration.seconds(60));
86const WINDOWS_PROCESS_NAME_CONCURRENCY = 4;
87const WEB_PROBE_CONCURRENCY = 16;
88const NAVIGATION_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
89
90type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
91
92interface ListenerSubscription {
93 readonly configuredUrls: ReadonlyArray<string>;
94 readonly lastSnapshot: ReadonlyArray<DiscoveredLocalServer>;
95}
96
97interface ScannerState {
98 readonly listeners: ReadonlyMap<Listener, ListenerSubscription>;
99 readonly terminalProcesses: ReadonlyMap<
100 string,
101 {
102 readonly owner: TerminalProcessOwner;
103 readonly processIds: ReadonlySet<number>;
104 }
105 >;
106 readonly retainCount: number;
107}
108
109interface TerminalProcessOwner {
110 readonly threadId: ThreadId;
111 readonly terminalId: string;
112}
113
114interface WebProbeCacheEntry {
115 readonly pid: number | null;
116 readonly isWeb: boolean;
117 readonly expiresAtMillis: number;
118}
119
120interface WebProbeGroup {
121 readonly server: DiscoveredLocalServer;
122 readonly urls: ReadonlyArray<string>;
123 readonly configuredKey: string | null;
124}
125
126interface WebProbeSnapshot {
127 readonly discovered: ReadonlyArray<DiscoveredLocalServer>;
128 readonly configured: ReadonlyMap<string, DiscoveredLocalServer>;
129}
130
131const terminalOwnerKey = (owner: {
132 readonly threadId: string;
133 readonly terminalId: string;
134}): string => `${owner.threadId}\u0000${owner.terminalId}`;
135
136const parseConfiguredUrl = (raw: string): URL | null => {
137 try {
138 const url = new URL(raw);
139 if (url.protocol !== "http:" && url.protocol !== "https:") return null;
140 if (!isLoopbackHost(url.hostname)) return null;
141 return url;
142 } catch {
143 return null;
144 }
145};
146
147const localServerKey = (host: string, port: number): string =>
148 `${isLoopbackHost(host) ? "loopback" : host.toLowerCase()}:${port}`;
149
150const urlPort = (url: URL): number =>
151 url.port.length > 0 ? Number.parseInt(url.port, 10) : url.protocol === "http:" ? 80 : 443;
152
153const webProbeCacheKey = (raw: string): string => {
154 const url = new URL(raw);
155 url.hash = "";
156 return url.href;
157};
158
159const normalizeConfiguredUrls = (urls: ReadonlyArray<string>): ReadonlyArray<string> => [
160 ...new Set(
161 urls
162 .slice(0, CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS)
163 .filter((raw) => raw.length <= PREVIEW_URL_MAX_LENGTH)
164 .map(parseConfiguredUrl)
165 .filter((url): url is URL => url !== null && url.href.length <= PREVIEW_URL_MAX_LENGTH)
166 .map((url) => {
167 if (url.hostname === "0.0.0.0") url.hostname = "localhost";
168 return url.href;
169 })
170 .filter((url) => url.length <= PREVIEW_URL_MAX_LENGTH),
171 ),
172];
173
174const projectWebProbeSnapshot = (
175 snapshot: WebProbeSnapshot,
176 configuredUrls: ReadonlyArray<string>,
177): ReadonlyArray<DiscoveredLocalServer> => {
178 const visibleByServer = new Map<string, DiscoveredLocalServer>();
179 for (const raw of normalizeConfiguredUrls(configuredUrls)) {
180 const url = new URL(raw);
181 const port = urlPort(url);
182 const serverKey = localServerKey(url.hostname, port);
183 if (visibleByServer.has(serverKey)) continue;
184 const configured = snapshot.configured.get(webProbeCacheKey(raw));
185 if (configured) visibleByServer.set(serverKey, { ...configured, url: raw });
186 }
187 for (const server of snapshot.discovered) {
188 const key = localServerKey(server.host, server.port);
189 if (!visibleByServer.has(key)) visibleByServer.set(key, server);
190 }
191 return [...visibleByServer.values()].toSorted((left, right) => left.port - right.port);
192};
193
194const parseLsofOutput = (
195 raw: string,
196 terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
197): ReadonlyArray<DiscoveredLocalServer> => {
198 const seen = new Map<string, DiscoveredLocalServer>();
199 let pid: number | null = null;
200 let processName: string | null = null;
201
202 for (const line of raw.split("\n")) {
203 if (line.length === 0) continue;
204 const tag = line.charAt(0);
205 const value = line.slice(1);
206 if (tag === "p") {
207 const parsed = Number.parseInt(value, 10);
208 pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;
209 processName = null;
210 continue;
211 }
212 if (tag === "c") {
213 processName = value.trim() || null;
214 continue;
215 }
216 if (tag === "n") {
217 const portMatch = parsePortFromLsofName(value);
218 if (portMatch == null) continue;
219 const url = `http://localhost:${portMatch}`;
220 const key = `localhost:${portMatch}`;
221 const terminal = pid === null ? null : (terminalByProcessId.get(pid) ?? null);
222 const existing = seen.get(key);
223 // A port receives probes only when T3 terminals own all of its listeners.
224 if (existing) {
225 if (terminal === null) seen.set(key, { ...existing, terminal: null });
226 continue;
227 }
228 seen.set(key, {
229 host: "localhost",
230 port: portMatch,
231 url,
232 processName,
233 pid,
234 terminal,
235 });
236 }
237 }
238
239 return Array.from(seen.values()).toSorted((a, b) => a.port - b.port);
240};
241
242const parsePortFromLsofName = (name: string): number | null => {
243 // Examples: "*:5173", "127.0.0.1:5173", "[::1]:5173", "localhost:5173",
244 // "192.168.1.10:5173 (LISTEN)" — we only care if the host part is local.
245 const trimmed = name.split(" ", 1)[0]?.trim() ?? "";
246 if (trimmed.length === 0) return null;
247 const lastColon = trimmed.lastIndexOf(":");
248 if (lastColon < 0) return null;
249 const hostPart = trimmed.slice(0, lastColon);
250 const portPart = trimmed.slice(lastColon + 1);
251 if (!LSOF_LOCAL_HOST_TOKENS.has(hostPart)) return null;
252 const port = Number.parseInt(portPart, 10);
253 if (!Number.isFinite(port) || port <= 0 || port >= 65536) return null;
254 return port;
255};
256
257const parseWindowsListenerLine = (
258 line: string,
259): {
260 readonly host: string;
261 readonly port: number;
262 readonly pid: number | null;
263 readonly processName: string | null;
264} | null => {
265 const trimmed = line.trim();
266 if (trimmed.length === 0) return null;
267
268 if (trimmed.includes("|")) {
269 const [hostRaw, portRaw, pidRaw, processNameRaw] = trimmed.split("|", 4);
270 const host = hostRaw?.trim() ?? "";
271 if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") return null;
272 const port = Number(portRaw);
273 const pid = Number(pidRaw);
274 if (!Number.isInteger(port) || port <= 0 || port >= 65536) return null;
275 return {
276 host,
277 port,
278 pid: Number.isInteger(pid) && pid > 0 ? pid : null,
279 processName: processNameRaw?.trim() || null,
280 };
281 }
282
283 // `netstat.exe -ano -p tcp` / `tcpv6`:
284 // TCP 127.0.0.1:3773 0.0.0.0:0 LISTENING 34280
285 // TCP [::1]:35783 [::]:0 LISTENING 22876
286 // Foreign port `:0` identifies a listening TCP socket regardless of Windows locale.
287 const fields = trimmed.split(/\s+/);
288 if (fields.length < 4 || fields[0]?.toUpperCase() !== "TCP") return null;
289 const localEndpoint = fields[1] ?? "";
290 const foreignEndpoint = fields[2] ?? "";
291 if (!foreignEndpoint.endsWith(":0")) return null;
292 const lastColon = localEndpoint.lastIndexOf(":");
293 if (lastColon <= 0) return null;
294 const host = localEndpoint.slice(0, lastColon);
295 if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") return null;
296 const port = Number(localEndpoint.slice(lastColon + 1));
297 if (!Number.isInteger(port) || port <= 0 || port >= 65536) return null;
298 const pid = Number(fields.at(-1));
299 return {
300 host,
301 port,
302 pid: Number.isInteger(pid) && pid > 0 ? pid : null,
303 processName: null,
304 };
305};
306
307/** `ProcessRunner` reports a nonzero exit as a result, not a failure. */
308const exitedWithError = (result: ProcessRunner.ProcessRunOutput): boolean =>
309 result.code !== null && result.code !== 0;
310
311/** Reads the image name from `tasklist.exe /FO CSV /NH /FI "PID eq <pid>"` output. */
312const parseTasklistProcessName = (raw: string, pid: number): string | null => {
313 for (const line of raw.split(/\r?\n/g)) {
314 const match = /^"([^"]*)","(\d+)"/.exec(line.trim());
315 if (match && Number(match[2]) === pid) return match[1]!.replace(/\.exe$/i, "") || null;
316 }
317 return null;
318};
319
320const parseWindowsListenerOutput = (
321 raw: string,
322 terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
323): ReadonlyArray<DiscoveredLocalServer> => {
324 const seen = new Map<number, DiscoveredLocalServer>();
325 for (const line of raw.split(/\r?\n/g)) {
326 const parsed = parseWindowsListenerLine(line);
327 if (!parsed) continue;
328 const { port, pid: normalizedPid, processName } = parsed;
329 const terminal =
330 normalizedPid === null ? null : (terminalByProcessId.get(normalizedPid) ?? null);
331 const existing = seen.get(port);
332 if (existing) {
333 if (terminal === null) seen.set(port, { ...existing, terminal: null });
334 continue;
335 }
336 seen.set(port, {
337 host: "localhost",
338 port,
339 url: `http://localhost:${port}`,
340 processName,
341 pid: normalizedPid,
342 terminal,
343 });
344 }
345 return [...seen.values()].toSorted((left, right) => left.port - right.port);
346};
347
348/** `/proc/net/tcp` state for a listening socket. */
349const PROC_TCP_LISTEN = "0A";
350
351/**
352 * Whether a `/proc/net/tcp{,6}` address is one the preview can reach on
353 * loopback: the wildcard or a loopback address, as `lsof` parsing accepts.
354 * Each 32-bit word of the hex address is little-endian.
355 */
356const procLocalAddress = (hex: string): boolean => {
357 if (hex.length === 8) {
358 return hex === "00000000" || hex.endsWith("7F");
359 }
360 if (hex.length !== 32) return false;
361 if (hex === "0".repeat(32) || hex === `${"0".repeat(24)}01000000`) return true;
362 // IPv4-mapped (::ffff:a.b.c.d): wildcard or 127.0.0.0/8.
363 return hex.startsWith(`${"0".repeat(16)}FFFF0000`) && procLocalAddress(hex.slice(24));
364};
365
366/** Listening loopback ports in `/proc/net/tcp{,6}` content, with their socket inodes. */
367const parseProcNetTcp = (
368 raw: string,
369): ReadonlyArray<{ readonly port: number; readonly inode: string }> => {
370 const listeners: Array<{ port: number; inode: string }> = [];
371 for (const line of raw.split("\n").slice(1)) {
372 const fields = line.trim().split(/\s+/);
373 const [address, portHex] = fields[1]?.split(":") ?? [];
374 if (fields[3] !== PROC_TCP_LISTEN || !address || !portHex) continue;
375 if (!procLocalAddress(address.toUpperCase())) continue;
376 const port = Number.parseInt(portHex, 16);
377 const inode = fields[9];
378 if (!Number.isInteger(port) || port <= 0 || port >= 65536 || !inode) continue;
379 listeners.push({ port, inode });
380 }
381 return listeners;
382};
383
384const serversEqual = (
385 left: ReadonlyArray<DiscoveredLocalServer>,
386 right: ReadonlyArray<DiscoveredLocalServer>,
387): boolean => {
388 if (left.length !== right.length) return false;
389 for (let i = 0; i < left.length; i += 1) {
390 const a = left[i];
391 const b = right[i];
392 if (!a || !b) return false;
393 if (
394 a.host !== b.host ||
395 a.port !== b.port ||
396 a.url !== b.url ||
397 a.processName !== b.processName ||
398 a.pid !== b.pid ||
399 a.terminal?.threadId !== b.terminal?.threadId ||
400 a.terminal?.terminalId !== b.terminal?.terminalId
401 ) {
402 return false;
403 }
404 }
405 return true;
406};
407
408const isCommandNotFound = (error: ProcessRunner.ProcessSpawnError): boolean =>
409 PlatformError.isPlatformError(error.cause) && error.cause.reason._tag === "NotFound";
410
411/** @public Service construction is part of the canonical Effect module API. */
412export const make = Effect.gen(function* PortDiscoveryMake() {
413 const processRunner = yield* ProcessRunner.ProcessRunner;
414 const fileSystem = yield* FileSystem.FileSystem;
415 const hostPlatform = yield* HostProcess.Platform;
416 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
417 const stateRef = yield* Ref.make<ScannerState>({
418 listeners: new Map(),
419 terminalProcesses: new Map(),
420 retainCount: 0,
421 });
422 const webProbeCacheRef = yield* Ref.make<ReadonlyMap<string, WebProbeCacheEntry>>(new Map());
423 const scanSemaphore = yield* Semaphore.make(1);
424 const lsofMissingRef = yield* Ref.make(false);
425 /** Windows image names by PID; netstat reports only PIDs. */
426 const windowsProcessNamesRef = yield* Ref.make<
427 ReadonlyMap<number, { readonly name: string | null; readonly expiresAtMillis: number }>
428 >(new Map());
429 /** Confirmed owners of listening socket inodes. */
430 const socketOwnersRef = yield* Ref.make<
431 ReadonlyMap<string, { readonly pid: number; readonly processName: string | null }>
432 >(new Map());
433 /** Fd walks that found no owner, per socket inode; retried up to `SOCKET_OWNER_ATTEMPTS`. */
434 const socketOwnerMissesRef = yield* Ref.make<ReadonlyMap<string, number>>(new Map());
435
436 /** Maps socket inodes to the processes holding them, by `/proc/<pid>/fd`. */
437 const findSocketOwners = Effect.fn("PortDiscovery.findSocketOwners")(function* (
438 inodes: ReadonlySet<string>,
439 ) {
440 const owners = new Map<string, { pid: number; processName: string | null }>();
441 const pids = (yield* fileSystem
442 .readDirectory("/proc")
443 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))).filter((entry) =>
444 /^\d+$/.test(entry),
445 );
446 let budget = PROC_FD_WALK_LIMIT;
447 for (const pidText of pids) {
448 if (owners.size === inodes.size || budget <= 0) break;
449 // Other users' fds are unreadable; their ports still list, without a pid.
450 const fds = yield* fileSystem
451 .readDirectory(`/proc/${pidText}/fd`)
452 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
453 const walked = fds.slice(0, budget);
454 budget -= walked.length;
455 const links = yield* Effect.forEach(
456 walked,
457 (fd) =>
458 fileSystem.readLink(`/proc/${pidText}/fd/${fd}`).pipe(Effect.orElseSucceed(() => "")),
459 { concurrency: 16 },
460 );
461 const held = links.flatMap((link) => /^socket:\[(\d+)\]$/.exec(link)?.[1] ?? []);
462 const matched = held.filter((inode) => inodes.has(inode) && !owners.has(inode));
463 if (matched.length === 0) continue;
464 const processName = yield* fileSystem.readFileString(`/proc/${pidText}/comm`).pipe(
465 Effect.map((name) => name.trim() || null),
466 Effect.orElseSucceed(() => null),
467 );
468 for (const inode of matched) owners.set(inode, { pid: Number(pidText), processName });
469 }
470 return owners;
471 });
472
473 /**
474 * Linux listeners from `/proc/net/tcp{,6}`, for hosts without `lsof`. Null
475 * when neither file is readable, so only configured URLs are probed.
476 */
477 const scanProcListeners = Effect.fn("PortDiscovery.scanProcListeners")(function* (
478 terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner>,
479 ) {
480 if (hostPlatform !== "linux") return null;
481 const tables = yield* Effect.forEach(["/proc/net/tcp", "/proc/net/tcp6"], (path) =>
482 fileSystem.readFileString(path).pipe(Effect.option),
483 );
484 if (tables.every(Option.isNone)) return null;
485 const listeners = tables.flatMap((table) =>
486 Option.isSome(table) ? parseProcNetTcp(table.value) : [],
487 );
488 const known = yield* Ref.get(socketOwnersRef);
489 const knownMisses = yield* Ref.get(socketOwnerMissesRef);
490 const inodes = new Set(listeners.map((listener) => listener.inode));
491 // Listeners rarely change, so the fd walk runs only for sockets without a
492 // confirmed owner, and gives up on one after a few walks miss it (another
493 // user's process, or one that exited mid-walk).
494 const unseen = new Set(
495 [...inodes].filter(
496 (inode) => !known.has(inode) && (knownMisses.get(inode) ?? 0) < SOCKET_OWNER_ATTEMPTS,
497 ),
498 );
499 const found = unseen.size === 0 ? new Map() : yield* findSocketOwners(unseen);
500 const owners = new Map([...known, ...found].filter(([inode]) => inodes.has(inode)));
501 const misses = new Map([...knownMisses].filter(([inode]) => inodes.has(inode)));
502 for (const inode of unseen) {
503 if (!found.has(inode)) misses.set(inode, (misses.get(inode) ?? 0) + 1);
504 }
505 yield* Ref.set(socketOwnersRef, owners);
506 yield* Ref.set(socketOwnerMissesRef, misses);
507 const seen = new Map<number, DiscoveredLocalServer>();
508 for (const { port, inode } of listeners) {
509 const owner = owners.get(inode) ?? null;
510 const terminal = owner === null ? null : (terminalByProcessId.get(owner.pid) ?? null);
511 const existing = seen.get(port);
512 if (existing && (existing.pid !== null || owner === null)) {
513 if (terminal === null) seen.set(port, { ...existing, terminal: null });
514 continue;
515 }
516 seen.set(port, {
517 host: "localhost",
518 port,
519 url: `http://localhost:${port}`,
520 processName: owner?.processName ?? null,
521 pid: owner?.pid ?? null,
522 // A replaced listener had no known owner, so the port stays unowned.
523 terminal: existing ? null : terminal,
524 });
525 }
526 return [...seen.values()].toSorted((left, right) => left.port - right.port);
527 });
528
529 const probeWebUrl = Effect.fn("PortDiscovery.probeWebUrl")((url: string) =>
530 httpClient.get(url).pipe(
531 Effect.map((response) => {
532 const location = response.headers.location?.trim();
533 if (NAVIGATION_REDIRECT_STATUSES.has(response.status) && location) return url;
534 if (response.status < 200 || response.status >= 300) return null;
535 if (response.status === 204 || response.status === 205) return null;
536 const contentType = response.headers["content-type"]
537 ?.split(";", 1)[0]
538 ?.trim()
539 .toLowerCase();
540 return contentType === "text/html" || contentType === "application/xhtml+xml" ? url : null;
541 }),
542 Effect.scoped,
543 Effect.timeoutOption(WEB_PROBE_TIMEOUT),
544 Effect.map(Option.getOrNull),
545 Effect.orElseSucceed(() => null),
546 Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
547 ),
548 );
549
550 const makeWebProbeGroups = (
551 servers: ReadonlyArray<DiscoveredLocalServer>,
552 configuredUrls: ReadonlyArray<string>,
553 ): ReadonlyArray<WebProbeGroup> => {
554 const serversByKey = new Map(
555 servers.map((server) => [localServerKey(server.host, server.port), server] as const),
556 );
557 const groups: WebProbeGroup[] = [];
558 const configuredResources = new Set<string>();
559
560 for (const raw of configuredUrls) {
561 const url = new URL(raw);
562 const port = urlPort(url);
563 const key = localServerKey(url.hostname, port);
564 const resourceKey = webProbeCacheKey(raw);
565 if (configuredResources.has(resourceKey)) continue;
566 configuredResources.add(resourceKey);
567 groups.push({
568 server: serversByKey.get(key) ?? {
569 host: url.hostname,
570 port,
571 url: raw,
572 processName: null,
573 pid: null,
574 terminal: null,
575 },
576 urls: [raw],
577 configuredKey: resourceKey,
578 });
579 }
580
581 for (const server of servers) {
582 // A listener alone does not identify its protocol. Sending HTTP or TLS to
583 // another app's binary RPC listener can crash it before classification.
584 if (server.terminal === null) continue;
585 groups.push({
586 server,
587 urls: [`http://${server.host}:${server.port}`, `https://${server.host}:${server.port}`],
588 configuredKey: null,
589 });
590 }
591
592 return groups;
593 };
594
595 const probeWebServers = Effect.fn("PortDiscovery.probeWebServers")(function* (
596 servers: ReadonlyArray<DiscoveredLocalServer>,
597 configuredUrls: ReadonlyArray<string>,
598 ) {
599 const nowMillis = yield* Clock.currentTimeMillis;
600 const cached = yield* Ref.get(webProbeCacheRef);
601 const groups = makeWebProbeGroups(servers, configuredUrls);
602 const batchProbes = new Map<
603 string,
604 Effect.Effect<{ readonly probe: WebProbeCacheEntry; readonly fresh: boolean }>
605 >();
606 const batchProbeSemaphore = yield* Semaphore.make(1);
607 const getProbe = (url: string, pid: number | null) => {
608 const key = webProbeCacheKey(url);
609 const identity = `${key}\u0000${pid ?? ""}`;
610 return batchProbeSemaphore
611 .withPermits(1)(
612 Effect.gen(function* () {
613 const existing = batchProbes.get(identity);
614 if (existing) return [existing] as const;
615 const cachedProbe = cached.get(key);
616 const cachedIsCurrent =
617 cachedProbe?.pid === pid && cachedProbe.expiresAtMillis > nowMillis;
618 const memoized = yield* Effect.cached(
619 cachedIsCurrent
620 ? Effect.succeed({ probe: cachedProbe, fresh: false })
621 : probeWebUrl(url).pipe(
622 Effect.map((result) => ({
623 probe: { pid, isWeb: result !== null, expiresAtMillis: 0 },
624 fresh: true,
625 })),
626 ),
627 );
628 batchProbes.set(identity, memoized);
629 return [memoized] as const;
630 }),
631 )
632 .pipe(Effect.flatMap(([probe]) => probe));
633 };
634 const probed = yield* Effect.forEach(
635 groups,
636 (group) =>
637 Effect.gen(function* () {
638 const probes: Array<readonly [string, WebProbeCacheEntry, boolean]> = [];
639 let visibleUrl: string | null = null;
640 for (const url of group.urls) {
641 const key = webProbeCacheKey(url);
642 const { probe, fresh } = yield* getProbe(url, group.server.pid);
643 probes.push([key, probe, fresh]);
644 if (probe.isWeb) {
645 visibleUrl = url;
646 break;
647 }
648 }
649 return { group, probes, visibleUrl };
650 }),
651 { concurrency: WEB_PROBE_CONCURRENCY },
652 );
653 const completedAtMillis = yield* Clock.currentTimeMillis;
654 const nextCache = new Map(
655 [...cached].filter(([, probe]) => probe.expiresAtMillis > completedAtMillis),
656 );
657 const discovered: DiscoveredLocalServer[] = [];
658 const configured = new Map<string, DiscoveredLocalServer>();
659 for (const { group, probes, visibleUrl } of probed) {
660 for (const [key, probe, fresh] of probes) {
661 nextCache.set(
662 key,
663 fresh ? { ...probe, expiresAtMillis: completedAtMillis + WEB_PROBE_CACHE_TTL_MS } : probe,
664 );
665 }
666 if (visibleUrl === null) continue;
667 const server = { ...group.server, url: visibleUrl };
668 if (group.configuredKey === null) discovered.push(server);
669 else configured.set(group.configuredKey, server);
670 }
671 yield* Ref.set(webProbeCacheRef, nextCache);
672 return { discovered, configured } satisfies WebProbeSnapshot;
673 });
674
675 // `tasklist` costs ~200-300ms per PID, so look up only visible servers, a few at a time, and
676 // reuse each name until its TTL expires.
677 const withWindowsProcessNames = Effect.fn("PortDiscovery.withWindowsProcessNames")(function* (
678 snapshot: WebProbeSnapshot,
679 ) {
680 const servers = [...snapshot.discovered, ...snapshot.configured.values()];
681 const pids = new Set(servers.flatMap((server) => (server.pid === null ? [] : [server.pid])));
682 const nowMillis = yield* Clock.currentTimeMillis;
683 const cached = [...(yield* Ref.get(windowsProcessNamesRef))].filter(
684 ([pid, entry]) => pids.has(pid) && entry.expiresAtMillis > nowMillis,
685 );
686 const cachedPids = new Set(cached.map(([pid]) => pid));
687 const expiresAtMillis = nowMillis + WINDOWS_PROCESS_NAME_TTL_MS;
688 const fetched = yield* Effect.forEach(
689 [...pids].filter((pid) => !cachedPids.has(pid)),
690 (pid) =>
691 processRunner
692 .run({
693 command: "tasklist.exe",
694 args: ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`],
695 timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
696 maxOutputBytes: 64 * 1024,
697 })
698 .pipe(
699 // Only a completed lookup is cached; failures retry on the next scan.
700 Effect.map((result) =>
701 exitedWithError(result)
702 ? []
703 : [
704 [
705 pid,
706 { name: parseTasklistProcessName(result.stdout, pid), expiresAtMillis },
707 ] as const,
708 ],
709 ),
710 Effect.orElseSucceed(() => []),
711 ),
712 { concurrency: WINDOWS_PROCESS_NAME_CONCURRENCY },
713 );
714 const names = new Map([...cached, ...fetched.flat()]);
715 yield* Ref.set(windowsProcessNamesRef, names);
716 const withName = (server: DiscoveredLocalServer): DiscoveredLocalServer =>
717 server.pid === null || server.processName !== null
718 ? server
719 : { ...server, processName: names.get(server.pid)?.name ?? null };
720 return {
721 discovered: snapshot.discovered.map(withName),
722 configured: new Map([...snapshot.configured].map(([key, server]) => [key, withName(server)])),
723 } satisfies WebProbeSnapshot;
724 });
725
726 const recoverProcessProbeFailure =
727 (probe: "lsof" | "windows-listeners") => (error: ProcessRunner.ProcessRunError) =>
728 Effect.logDebug("preview port process probe failed; probing configured URLs only", {
729 cause: error,
730 probe,
731 platform: hostPlatform,
732 }).pipe(Effect.as(null));
733
734 const scanUnlocked = Effect.fn("PortDiscovery.scanUnlocked")(function* (
735 configuredUrls: ReadonlyArray<string>,
736 ) {
737 const state = yield* Ref.get(stateRef);
738 const terminalByProcessId = new Map<number, TerminalProcessOwner>();
739 for (const registration of state.terminalProcesses.values()) {
740 for (const processId of registration.processIds) {
741 terminalByProcessId.set(processId, registration.owner);
742 }
743 }
744 if (hostPlatform === "win32") {
745 if (terminalByProcessId.size === 0 && configuredUrls.length === 0) {
746 return { discovered: [], configured: new Map() } satisfies WebProbeSnapshot;
747 }
748 const recoverWindowsProbeFailure = recoverProcessProbeFailure("windows-listeners");
749 const runNetstat = (protocol: "tcp" | "tcpv6") =>
750 processRunner.run({
751 command: "netstat.exe",
752 args: ["-ano", "-p", protocol],
753 timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
754 maxOutputBytes: WINDOWS_NETSTAT_MAX_OUTPUT_BYTES,
755 });
756 const listeners = yield* Effect.all([runNetstat("tcp"), runNetstat("tcpv6")], {
757 concurrency: 2,
758 }).pipe(
759 // One failed query leaves a partial snapshot that could hide another process sharing a
760 // port across IPv4/IPv6, so fall back to configured URLs instead.
761 Effect.map(([tcp4, tcp6]) =>
762 exitedWithError(tcp4) || exitedWithError(tcp6)
763 ? null
764 : parseWindowsListenerOutput(`${tcp4.stdout}\n${tcp6.stdout}`, terminalByProcessId),
765 ),
766 Effect.catchTags({
767 ProcessSpawnError: recoverWindowsProbeFailure,
768 ProcessStdinError: recoverWindowsProbeFailure,
769 ProcessOutputLimitError: recoverWindowsProbeFailure,
770 ProcessReadError: recoverWindowsProbeFailure,
771 ProcessTimeoutError: recoverWindowsProbeFailure,
772 }),
773 );
774 return yield* withWindowsProcessNames(
775 yield* probeWebServers(listeners ?? [], configuredUrls),
776 );
777 }
778 const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof");
779 if (yield* Ref.get(lsofMissingRef)) {
780 const fromProc = yield* scanProcListeners(terminalByProcessId);
781 return yield* probeWebServers(fromProc ?? [], configuredUrls);
782 }
783 const lsofResult = yield* processRunner
784 .run({
785 command: "lsof",
786 args: ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"],
787 timeout: Duration.millis(LSOF_TIMEOUT_MS),
788 // Partial output could hide another app's listener on an owned port.
789 maxOutputBytes: 1024 * 1024,
790 })
791 .pipe(
792 Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),
793 Effect.catchTags({
794 // A missing lsof stays missing; later scans skip straight to the fallback.
795 ProcessSpawnError: (error) =>
796 (isCommandNotFound(error) ? Ref.set(lsofMissingRef, true) : Effect.void).pipe(
797 Effect.andThen(recoverLsofProbeFailure(error)),
798 ),
799 ProcessStdinError: recoverLsofProbeFailure,
800 ProcessOutputLimitError: recoverLsofProbeFailure,
801 ProcessReadError: recoverLsofProbeFailure,
802 ProcessTimeoutError: recoverLsofProbeFailure,
803 }),
804 );
805 if (lsofResult !== null) return yield* probeWebServers(lsofResult, configuredUrls);
806 const fromProc = yield* scanProcListeners(terminalByProcessId);
807 return yield* probeWebServers(fromProc ?? [], configuredUrls);
808 });
809
810 const scanSnapshot = Effect.fn("PortDiscovery.scanSnapshot")(
811 (configuredUrls: ReadonlyArray<string>) =>
812 scanSemaphore.withPermits(1)(scanUnlocked(configuredUrls)),
813 );
814
815 const scanOnce: PortDiscovery["Service"]["scan"] = (configuredUrls = []) => {
816 const normalized = normalizeConfiguredUrls(configuredUrls);
817 return scanSnapshot(normalized).pipe(
818 Effect.map((snapshot) => projectWebProbeSnapshot(snapshot, normalized)),
819 );
820 };
821
822 const pollTick = Effect.fn("PortDiscovery.pollTick")(
823 function* () {
824 const configuredUrls = [
825 ...new Set(
826 [...(yield* Ref.get(stateRef)).listeners.values()].flatMap(
827 (subscription) => subscription.configuredUrls,
828 ),
829 ),
830 ];
831 const snapshot = yield* scanSnapshot(configuredUrls);
832 const notifications = yield* Ref.modify(stateRef, (state) => {
833 const listeners = new Map(state.listeners);
834 const changed: Array<readonly [Listener, ReadonlyArray<DiscoveredLocalServer>]> = [];
835 for (const [listener, subscription] of listeners) {
836 const next = projectWebProbeSnapshot(snapshot, subscription.configuredUrls);
837 if (serversEqual(subscription.lastSnapshot, next)) continue;
838 listeners.set(listener, { ...subscription, lastSnapshot: next });
839 changed.push([listener, next]);
840 }
841 return [changed, { ...state, listeners }];
842 });
843 yield* Effect.forEach(notifications, ([listener, servers]) => listener(servers), {
844 discard: true,
845 });
846 },
847 Effect.catchCause((cause: Cause.Cause<never>) =>
848 Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
849 ),
850 );
851
852 // Single layer-scoped polling fiber. Ticks skip the scan and its span when no
853 // client is currently retained, so the cost is one Ref.get every POLL_INTERVAL.
854 const pollIfRetained = Ref.get(stateRef).pipe(
855 Effect.flatMap((state) => (state.retainCount > 0 ? pollTick() : Effect.void)),
856 );
857 yield* Effect.forkScoped(pollIfRetained.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
858
859 const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {
860 const wasIdle = yield* Ref.modify(stateRef, (state) => [
861 state.retainCount === 0,
862 { ...state, retainCount: state.retainCount + 1 },
863 ]);
864 if (wasIdle) {
865 // Run an immediate scan + broadcast so the new retainer doesn't have
866 // to wait up to POLL_INTERVAL for the first emission.
867 yield* pollTick();
868 }
869 });
870
871 const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(acquireRetention(), () =>
872 Ref.update(stateRef, (state) => ({
873 ...state,
874 retainCount: Math.max(0, state.retainCount - 1),
875 })),
876 );
877
878 const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
879 (input, listener) =>
880 Effect.acquireRelease(
881 Ref.update(stateRef, (state) => {
882 const listeners = new Map(state.listeners);
883 listeners.set(listener, {
884 configuredUrls: normalizeConfiguredUrls(input.configuredUrls),
885 lastSnapshot: input.initialSnapshot,
886 });
887 return { ...state, listeners };
888 }),
889 () =>
890 Ref.update(stateRef, (state) => {
891 const listeners = new Map(state.listeners);
892 listeners.delete(listener);
893 return { ...state, listeners };
894 }),
895 ),
896 );
897
898 const registerTerminalProcesses: PortDiscovery["Service"]["registerTerminalProcesses"] =
899 Effect.fn("PortDiscovery.registerTerminalProcesses")(function* (input) {
900 const owner = {
901 threadId: ThreadId.make(input.threadId),
902 terminalId: input.terminalId,
903 };
904 const processIds = new Set(
905 input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
906 );
907 yield* Ref.update(stateRef, (state) => {
908 const terminalProcesses = new Map(state.terminalProcesses);
909 const key = terminalOwnerKey(owner);
910 if (processIds.size === 0) {
911 terminalProcesses.delete(key);
912 } else {
913 terminalProcesses.set(key, { owner, processIds });
914 }
915 return { ...state, terminalProcesses };
916 });
917 });
918
919 const unregisterTerminal: PortDiscovery["Service"]["unregisterTerminal"] = Effect.fn(
920 "PortDiscovery.unregisterTerminal",
921 )(function* (input) {
922 yield* Ref.update(stateRef, (state) => {
923 const terminalProcesses = new Map(state.terminalProcesses);
924 terminalProcesses.delete(terminalOwnerKey(input));
925 return { ...state, terminalProcesses };
926 });
927 });
928
929 return PortDiscovery.of({
930 scan: scanOnce,
931 subscribe,
932 retain,
933 registerTerminalProcesses,
934 unregisterTerminal,
935 });
936}).pipe(Effect.withSpan("PortDiscovery.make"));
937
938export const layer = Layer.effect(PortDiscovery, make);