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 * Windows listener failures, or neither source: checks a curated list of
12 * common dev ports through the shared Net service.
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 { HostProcessPlatform } from "@t3tools/shared/hostProcess";
29import * as Net from "@t3tools/shared/Net";
30import { isLoopbackHost, LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
31import * as Cause from "effect/Cause";
32import * as Clock from "effect/Clock";
33import * as Context from "effect/Context";
34import * as Duration from "effect/Duration";
35import * as Effect from "effect/Effect";
36import * as FileSystem from "effect/FileSystem";
37import * as Layer from "effect/Layer";
38import * as Option from "effect/Option";
39import * as PlatformError from "effect/PlatformError";
40import * as Ref from "effect/Ref";
41import * as Schedule from "effect/Schedule";
42import * as Scope from "effect/Scope";
43import * as Semaphore from "effect/Semaphore";
44import { FetchHttpClient, HttpClient } from "effect/http";
45
46import * as ProcessRunner from "../processRunner.ts";
47
48export class PortDiscovery extends Context.Service<
49 PortDiscovery,
50 {
51 readonly scan: (
52 configuredUrls?: ReadonlyArray<string>,
53 ) => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
54 readonly subscribe: (
55 input: {
56 readonly configuredUrls: ReadonlyArray<string>;
57 readonly initialSnapshot: ReadonlyArray<DiscoveredLocalServer>;
58 },
59 listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
60 ) => Effect.Effect<void, never, Scope.Scope>;
61 readonly retain: Effect.Effect<void, never, Scope.Scope>;
62 readonly registerTerminalProcesses: (input: {
63 readonly threadId: string;
64 readonly terminalId: string;
65 readonly processIds: ReadonlyArray<number>;
66 }) => Effect.Effect<void>;
67 readonly unregisterTerminal: (input: {
68 readonly threadId: string;
69 readonly terminalId: string;
70 }) => Effect.Effect<void>;
71 }
72>()("t3/preview/PortScanner/PortDiscovery") {}
73
74export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
75 3000, 3001, 3333, 4173, 4200, 4321, 5000, 5173, 5174, 5175, 5500, 8000, 8080, 8081, 8888, 9000,
76]);
77
78const POLL_INTERVAL = Duration.seconds(3);
79const LSOF_TIMEOUT_MS = 5_000;
80/** File descriptors one `/proc` walk may read before it stops looking for socket owners. */
81const PROC_FD_WALK_LIMIT = 50_000;
82/** Scans that retry the fd walk for a listening socket whose owner was not found. */
83const SOCKET_OWNER_ATTEMPTS = 3;
84const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
85const WEB_PROBE_TIMEOUT = Duration.seconds(1);
86const WEB_PROBE_CACHE_TTL_MS = Duration.toMillis(Duration.seconds(15));
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 if (seen.has(key)) continue;
222 seen.set(key, {
223 host: "localhost",
224 port: portMatch,
225 url,
226 processName,
227 pid,
228 terminal: pid === null ? null : (terminalByProcessId.get(pid) ?? null),
229 });
230 }
231 }
232
233 return Array.from(seen.values()).toSorted((a, b) => a.port - b.port);
234};
235
236const parsePortFromLsofName = (name: string): number | null => {
237 // Examples: "*:5173", "127.0.0.1:5173", "[::1]:5173", "localhost:5173",
238 // "192.168.1.10:5173 (LISTEN)" — we only care if the host part is local.
239 const trimmed = name.split(" ", 1)[0]?.trim() ?? "";
240 if (trimmed.length === 0) return null;
241 const lastColon = trimmed.lastIndexOf(":");
242 if (lastColon < 0) return null;
243 const hostPart = trimmed.slice(0, lastColon);
244 const portPart = trimmed.slice(lastColon + 1);
245 if (!LSOF_LOCAL_HOST_TOKENS.has(hostPart)) return null;
246 const port = Number.parseInt(portPart, 10);
247 if (!Number.isFinite(port) || port <= 0 || port >= 65536) return null;
248 return port;
249};
250
251const parseWindowsListenerOutput = (
252 raw: string,
253 terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
254): ReadonlyArray<DiscoveredLocalServer> => {
255 const seen = new Map<number, DiscoveredLocalServer>();
256 for (const line of raw.split(/\r?\n/g)) {
257 const [hostRaw, portRaw, pidRaw, processNameRaw] = line.trim().split("|", 4);
258 const host = hostRaw?.trim() ?? "";
259 if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") continue;
260 const port = Number(portRaw);
261 const pid = Number(pidRaw);
262 if (!Number.isInteger(port) || port <= 0 || port >= 65536) continue;
263 const normalizedPid = Number.isInteger(pid) && pid > 0 ? pid : null;
264 if (seen.has(port)) continue;
265 seen.set(port, {
266 host: "localhost",
267 port,
268 url: `http://localhost:${port}`,
269 processName: processNameRaw?.trim() || null,
270 pid: normalizedPid,
271 terminal: normalizedPid === null ? null : (terminalByProcessId.get(normalizedPid) ?? null),
272 });
273 }
274 return [...seen.values()].toSorted((left, right) => left.port - right.port);
275};
276
277/** `/proc/net/tcp` state for a listening socket. */
278const PROC_TCP_LISTEN = "0A";
279
280/**
281 * Whether a `/proc/net/tcp{,6}` address is one the preview can reach on
282 * loopback: the wildcard or a loopback address, as `lsof` parsing accepts.
283 * Each 32-bit word of the hex address is little-endian.
284 */
285const procLocalAddress = (hex: string): boolean => {
286 if (hex.length === 8) {
287 return hex === "00000000" || hex.endsWith("7F");
288 }
289 if (hex.length !== 32) return false;
290 if (hex === "0".repeat(32) || hex === `${"0".repeat(24)}01000000`) return true;
291 // IPv4-mapped (::ffff:a.b.c.d): wildcard or 127.0.0.0/8.
292 return hex.startsWith(`${"0".repeat(16)}FFFF0000`) && procLocalAddress(hex.slice(24));
293};
294
295/** Listening loopback ports in `/proc/net/tcp{,6}` content, with their socket inodes. */
296const parseProcNetTcp = (
297 raw: string,
298): ReadonlyArray<{ readonly port: number; readonly inode: string }> => {
299 const listeners: Array<{ port: number; inode: string }> = [];
300 for (const line of raw.split("\n").slice(1)) {
301 const fields = line.trim().split(/\s+/);
302 const [address, portHex] = fields[1]?.split(":") ?? [];
303 if (fields[3] !== PROC_TCP_LISTEN || !address || !portHex) continue;
304 if (!procLocalAddress(address.toUpperCase())) continue;
305 const port = Number.parseInt(portHex, 16);
306 const inode = fields[9];
307 if (!Number.isInteger(port) || port <= 0 || port >= 65536 || !inode) continue;
308 listeners.push({ port, inode });
309 }
310 return listeners;
311};
312
313const serversEqual = (
314 left: ReadonlyArray<DiscoveredLocalServer>,
315 right: ReadonlyArray<DiscoveredLocalServer>,
316): boolean => {
317 if (left.length !== right.length) return false;
318 for (let i = 0; i < left.length; i += 1) {
319 const a = left[i];
320 const b = right[i];
321 if (!a || !b) return false;
322 if (
323 a.host !== b.host ||
324 a.port !== b.port ||
325 a.url !== b.url ||
326 a.processName !== b.processName ||
327 a.pid !== b.pid ||
328 a.terminal?.threadId !== b.terminal?.threadId ||
329 a.terminal?.terminalId !== b.terminal?.terminalId
330 ) {
331 return false;
332 }
333 }
334 return true;
335};
336
337const isCommandNotFound = (error: ProcessRunner.ProcessSpawnError): boolean =>
338 PlatformError.isPlatformError(error.cause) && error.cause.reason._tag === "NotFound";
339
340/** @public Service construction is part of the canonical Effect module API. */
341export const make = Effect.gen(function* PortDiscoveryMake() {
342 const net = yield* Net.NetService;
343 const processRunner = yield* ProcessRunner.ProcessRunner;
344 const fileSystem = yield* FileSystem.FileSystem;
345 const hostPlatform = yield* HostProcessPlatform;
346 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
347 const stateRef = yield* Ref.make<ScannerState>({
348 listeners: new Map(),
349 terminalProcesses: new Map(),
350 retainCount: 0,
351 });
352 const webProbeCacheRef = yield* Ref.make<ReadonlyMap<string, WebProbeCacheEntry>>(new Map());
353 const scanSemaphore = yield* Semaphore.make(1);
354 const lsofMissingRef = yield* Ref.make(false);
355 /** Confirmed owners of listening socket inodes. */
356 const socketOwnersRef = yield* Ref.make<
357 ReadonlyMap<string, { readonly pid: number; readonly processName: string | null }>
358 >(new Map());
359 /** Fd walks that found no owner, per socket inode; retried up to `SOCKET_OWNER_ATTEMPTS`. */
360 const socketOwnerMissesRef = yield* Ref.make<ReadonlyMap<string, number>>(new Map());
361
362 /** Maps socket inodes to the processes holding them, by `/proc/<pid>/fd`. */
363 const findSocketOwners = Effect.fn("PortDiscovery.findSocketOwners")(function* (
364 inodes: ReadonlySet<string>,
365 ) {
366 const owners = new Map<string, { pid: number; processName: string | null }>();
367 const pids = (yield* fileSystem
368 .readDirectory("/proc")
369 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))).filter((entry) =>
370 /^\d+$/.test(entry),
371 );
372 let budget = PROC_FD_WALK_LIMIT;
373 for (const pidText of pids) {
374 if (owners.size === inodes.size || budget <= 0) break;
375 // Other users' fds are unreadable; their ports still list, without a pid.
376 const fds = yield* fileSystem
377 .readDirectory(`/proc/${pidText}/fd`)
378 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
379 const walked = fds.slice(0, budget);
380 budget -= walked.length;
381 const links = yield* Effect.forEach(
382 walked,
383 (fd) =>
384 fileSystem.readLink(`/proc/${pidText}/fd/${fd}`).pipe(Effect.orElseSucceed(() => "")),
385 { concurrency: 16 },
386 );
387 const held = links.flatMap((link) => /^socket:\[(\d+)\]$/.exec(link)?.[1] ?? []);
388 const matched = held.filter((inode) => inodes.has(inode) && !owners.has(inode));
389 if (matched.length === 0) continue;
390 const processName = yield* fileSystem.readFileString(`/proc/${pidText}/comm`).pipe(
391 Effect.map((name) => name.trim() || null),
392 Effect.orElseSucceed(() => null),
393 );
394 for (const inode of matched) owners.set(inode, { pid: Number(pidText), processName });
395 }
396 return owners;
397 });
398
399 /**
400 * Linux listeners from `/proc/net/tcp{,6}`, for hosts without `lsof`. Null
401 * when neither file is readable, so discovery falls back to common ports.
402 */
403 const scanProcListeners = Effect.fn("PortDiscovery.scanProcListeners")(function* (
404 terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner>,
405 ) {
406 if (hostPlatform !== "linux") return null;
407 const tables = yield* Effect.forEach(["/proc/net/tcp", "/proc/net/tcp6"], (path) =>
408 fileSystem.readFileString(path).pipe(Effect.option),
409 );
410 if (tables.every(Option.isNone)) return null;
411 const listeners = tables.flatMap((table) =>
412 Option.isSome(table) ? parseProcNetTcp(table.value) : [],
413 );
414 const known = yield* Ref.get(socketOwnersRef);
415 const knownMisses = yield* Ref.get(socketOwnerMissesRef);
416 const inodes = new Set(listeners.map((listener) => listener.inode));
417 // Listeners rarely change, so the fd walk runs only for sockets without a
418 // confirmed owner, and gives up on one after a few walks miss it (another
419 // user's process, or one that exited mid-walk).
420 const unseen = new Set(
421 [...inodes].filter(
422 (inode) => !known.has(inode) && (knownMisses.get(inode) ?? 0) < SOCKET_OWNER_ATTEMPTS,
423 ),
424 );
425 const found = unseen.size === 0 ? new Map() : yield* findSocketOwners(unseen);
426 const owners = new Map([...known, ...found].filter(([inode]) => inodes.has(inode)));
427 const misses = new Map([...knownMisses].filter(([inode]) => inodes.has(inode)));
428 for (const inode of unseen) {
429 if (!found.has(inode)) misses.set(inode, (misses.get(inode) ?? 0) + 1);
430 }
431 yield* Ref.set(socketOwnersRef, owners);
432 yield* Ref.set(socketOwnerMissesRef, misses);
433 const seen = new Map<number, DiscoveredLocalServer>();
434 for (const { port, inode } of listeners) {
435 const owner = owners.get(inode) ?? null;
436 const existing = seen.get(port);
437 if (existing && (existing.pid !== null || owner === null)) continue;
438 seen.set(port, {
439 host: "localhost",
440 port,
441 url: `http://localhost:${port}`,
442 processName: owner?.processName ?? null,
443 pid: owner?.pid ?? null,
444 terminal: owner === null ? null : (terminalByProcessId.get(owner.pid) ?? null),
445 });
446 }
447 return [...seen.values()].toSorted((left, right) => left.port - right.port);
448 });
449
450 const probeCommonPorts = Effect.fn("PortDiscovery.probeCommonPorts")(function* () {
451 const results = yield* Effect.forEach(
452 COMMON_DEV_PORTS,
453 (port) =>
454 net.isPortAvailableOnLoopback(port).pipe(
455 Effect.map((available) => ({
456 port,
457 listening: !available,
458 })),
459 ),
460 { concurrency: "unbounded" },
461 );
462 return results
463 .filter((result) => result.listening)
464 .map<DiscoveredLocalServer>((result) => ({
465 host: "localhost",
466 port: result.port,
467 url: `http://localhost:${result.port}`,
468 processName: null,
469 pid: null,
470 terminal: null,
471 }));
472 });
473
474 const probeWebUrl = Effect.fn("PortDiscovery.probeWebUrl")((url: string) =>
475 httpClient.get(url).pipe(
476 Effect.map((response) => {
477 const location = response.headers.location?.trim();
478 if (NAVIGATION_REDIRECT_STATUSES.has(response.status) && location) return url;
479 if (response.status < 200 || response.status >= 300) return null;
480 if (response.status === 204 || response.status === 205) return null;
481 const contentType = response.headers["content-type"]
482 ?.split(";", 1)[0]
483 ?.trim()
484 .toLowerCase();
485 return contentType === "text/html" || contentType === "application/xhtml+xml" ? url : null;
486 }),
487 Effect.scoped,
488 Effect.timeoutOption(WEB_PROBE_TIMEOUT),
489 Effect.map(Option.getOrNull),
490 Effect.orElseSucceed(() => null),
491 Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
492 ),
493 );
494
495 const makeWebProbeGroups = (
496 servers: ReadonlyArray<DiscoveredLocalServer>,
497 configuredUrls: ReadonlyArray<string>,
498 ): ReadonlyArray<WebProbeGroup> => {
499 const serversByKey = new Map(
500 servers.map((server) => [localServerKey(server.host, server.port), server] as const),
501 );
502 const groups: WebProbeGroup[] = [];
503 const configuredResources = new Set<string>();
504
505 for (const raw of configuredUrls) {
506 const url = new URL(raw);
507 const port = urlPort(url);
508 const key = localServerKey(url.hostname, port);
509 const resourceKey = webProbeCacheKey(raw);
510 if (configuredResources.has(resourceKey)) continue;
511 configuredResources.add(resourceKey);
512 groups.push({
513 server: serversByKey.get(key) ?? {
514 host: url.hostname,
515 port,
516 url: raw,
517 processName: null,
518 pid: null,
519 terminal: null,
520 },
521 urls: [raw],
522 configuredKey: resourceKey,
523 });
524 }
525
526 for (const server of servers) {
527 groups.push({
528 server,
529 urls: [`http://${server.host}:${server.port}`, `https://${server.host}:${server.port}`],
530 configuredKey: null,
531 });
532 }
533
534 return groups;
535 };
536
537 const probeWebServers = Effect.fn("PortDiscovery.probeWebServers")(function* (
538 servers: ReadonlyArray<DiscoveredLocalServer>,
539 configuredUrls: ReadonlyArray<string>,
540 ) {
541 const nowMillis = yield* Clock.currentTimeMillis;
542 const cached = yield* Ref.get(webProbeCacheRef);
543 const groups = makeWebProbeGroups(servers, configuredUrls);
544 const batchProbes = new Map<
545 string,
546 Effect.Effect<{ readonly probe: WebProbeCacheEntry; readonly fresh: boolean }>
547 >();
548 const batchProbeSemaphore = yield* Semaphore.make(1);
549 const getProbe = (url: string, pid: number | null) => {
550 const key = webProbeCacheKey(url);
551 const identity = `${key}\u0000${pid ?? ""}`;
552 return batchProbeSemaphore
553 .withPermits(1)(
554 Effect.gen(function* () {
555 const existing = batchProbes.get(identity);
556 if (existing) return [existing] as const;
557 const cachedProbe = cached.get(key);
558 const cachedIsCurrent =
559 cachedProbe?.pid === pid && cachedProbe.expiresAtMillis > nowMillis;
560 const memoized = yield* Effect.cached(
561 cachedIsCurrent
562 ? Effect.succeed({ probe: cachedProbe, fresh: false })
563 : probeWebUrl(url).pipe(
564 Effect.map((result) => ({
565 probe: { pid, isWeb: result !== null, expiresAtMillis: 0 },
566 fresh: true,
567 })),
568 ),
569 );
570 batchProbes.set(identity, memoized);
571 return [memoized] as const;
572 }),
573 )
574 .pipe(Effect.flatMap(([probe]) => probe));
575 };
576 const probed = yield* Effect.forEach(
577 groups,
578 (group) =>
579 Effect.gen(function* () {
580 const probes: Array<readonly [string, WebProbeCacheEntry, boolean]> = [];
581 let visibleUrl: string | null = null;
582 for (const url of group.urls) {
583 const key = webProbeCacheKey(url);
584 const { probe, fresh } = yield* getProbe(url, group.server.pid);
585 probes.push([key, probe, fresh]);
586 if (probe.isWeb) {
587 visibleUrl = url;
588 break;
589 }
590 }
591 return { group, probes, visibleUrl };
592 }),
593 { concurrency: WEB_PROBE_CONCURRENCY },
594 );
595 const completedAtMillis = yield* Clock.currentTimeMillis;
596 const nextCache = new Map(
597 [...cached].filter(([, probe]) => probe.expiresAtMillis > completedAtMillis),
598 );
599 const discovered: DiscoveredLocalServer[] = [];
600 const configured = new Map<string, DiscoveredLocalServer>();
601 for (const { group, probes, visibleUrl } of probed) {
602 for (const [key, probe, fresh] of probes) {
603 nextCache.set(
604 key,
605 fresh ? { ...probe, expiresAtMillis: completedAtMillis + WEB_PROBE_CACHE_TTL_MS } : probe,
606 );
607 }
608 if (visibleUrl === null) continue;
609 const server = { ...group.server, url: visibleUrl };
610 if (group.configuredKey === null) discovered.push(server);
611 else configured.set(group.configuredKey, server);
612 }
613 yield* Ref.set(webProbeCacheRef, nextCache);
614 return { discovered, configured } satisfies WebProbeSnapshot;
615 });
616
617 const recoverProcessProbeFailure =
618 (probe: "lsof" | "windows-listeners") => (error: ProcessRunner.ProcessRunError) =>
619 Effect.logDebug("preview port process probe failed; falling back to common-port probes", {
620 cause: error,
621 probe,
622 platform: hostPlatform,
623 }).pipe(Effect.as(null));
624
625 const scanUnlocked = Effect.fn("PortDiscovery.scanUnlocked")(function* (
626 configuredUrls: ReadonlyArray<string>,
627 ) {
628 const state = yield* Ref.get(stateRef);
629 const terminalByProcessId = new Map<number, TerminalProcessOwner>();
630 for (const registration of state.terminalProcesses.values()) {
631 for (const processId of registration.processIds) {
632 terminalByProcessId.set(processId, registration.owner);
633 }
634 }
635 if (hostPlatform === "win32") {
636 const recoverWindowsProbeFailure = recoverProcessProbeFailure("windows-listeners");
637 const command =
638 'Get-NetTCPConnection -State Listen -ErrorAction Stop | ForEach-Object { $processName = (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName; Write-Output "$($_.LocalAddress)|$($_.LocalPort)|$($_.OwningProcess)|$processName" }';
639 const listeners = yield* processRunner
640 .run({
641 command: "powershell.exe",
642 args: ["-NoProfile", "-NonInteractive", "-Command", command],
643 timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
644 maxOutputBytes: 1024 * 1024,
645 outputMode: "truncate",
646 })
647 .pipe(
648 Effect.map((result) => parseWindowsListenerOutput(result.stdout, terminalByProcessId)),
649 Effect.catchTags({
650 ProcessSpawnError: recoverWindowsProbeFailure,
651 ProcessStdinError: recoverWindowsProbeFailure,
652 ProcessOutputLimitError: recoverWindowsProbeFailure,
653 ProcessReadError: recoverWindowsProbeFailure,
654 ProcessTimeoutError: recoverWindowsProbeFailure,
655 }),
656 );
657 if (listeners !== null) return yield* probeWebServers(listeners, configuredUrls);
658 return yield* probeWebServers(yield* probeCommonPorts(), configuredUrls);
659 }
660 const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof");
661 if (yield* Ref.get(lsofMissingRef)) {
662 const fromProc = yield* scanProcListeners(terminalByProcessId);
663 return yield* probeWebServers(fromProc ?? (yield* probeCommonPorts()), configuredUrls);
664 }
665 const lsofResult = yield* processRunner
666 .run({
667 command: "lsof",
668 args: ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"],
669 timeout: Duration.millis(LSOF_TIMEOUT_MS),
670 maxOutputBytes: 1024 * 1024,
671 outputMode: "truncate",
672 })
673 .pipe(
674 Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),
675 Effect.catchTags({
676 // A missing lsof stays missing; later scans skip straight to the fallback.
677 ProcessSpawnError: (error) =>
678 (isCommandNotFound(error) ? Ref.set(lsofMissingRef, true) : Effect.void).pipe(
679 Effect.andThen(recoverLsofProbeFailure(error)),
680 ),
681 ProcessStdinError: recoverLsofProbeFailure,
682 ProcessOutputLimitError: recoverLsofProbeFailure,
683 ProcessReadError: recoverLsofProbeFailure,
684 ProcessTimeoutError: recoverLsofProbeFailure,
685 }),
686 );
687 if (lsofResult !== null) return yield* probeWebServers(lsofResult, configuredUrls);
688 const fromProc = yield* scanProcListeners(terminalByProcessId);
689 return yield* probeWebServers(fromProc ?? (yield* probeCommonPorts()), configuredUrls);
690 });
691
692 const scanSnapshot = Effect.fn("PortDiscovery.scanSnapshot")(
693 (configuredUrls: ReadonlyArray<string>) =>
694 scanSemaphore.withPermits(1)(scanUnlocked(configuredUrls)),
695 );
696
697 const scanOnce: PortDiscovery["Service"]["scan"] = (configuredUrls = []) => {
698 const normalized = normalizeConfiguredUrls(configuredUrls);
699 return scanSnapshot(normalized).pipe(
700 Effect.map((snapshot) => projectWebProbeSnapshot(snapshot, normalized)),
701 );
702 };
703
704 const pollTick = Effect.fn("PortDiscovery.pollTick")(
705 function* () {
706 const configuredUrls = [
707 ...new Set(
708 [...(yield* Ref.get(stateRef)).listeners.values()].flatMap(
709 (subscription) => subscription.configuredUrls,
710 ),
711 ),
712 ];
713 const snapshot = yield* scanSnapshot(configuredUrls);
714 const notifications = yield* Ref.modify(stateRef, (state) => {
715 const listeners = new Map(state.listeners);
716 const changed: Array<readonly [Listener, ReadonlyArray<DiscoveredLocalServer>]> = [];
717 for (const [listener, subscription] of listeners) {
718 const next = projectWebProbeSnapshot(snapshot, subscription.configuredUrls);
719 if (serversEqual(subscription.lastSnapshot, next)) continue;
720 listeners.set(listener, { ...subscription, lastSnapshot: next });
721 changed.push([listener, next]);
722 }
723 return [changed, { ...state, listeners }];
724 });
725 yield* Effect.forEach(notifications, ([listener, servers]) => listener(servers), {
726 discard: true,
727 });
728 },
729 Effect.catchCause((cause: Cause.Cause<never>) =>
730 Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
731 ),
732 );
733
734 // Single layer-scoped polling fiber. Ticks skip the scan and its span when no
735 // client is currently retained, so the cost is one Ref.get every POLL_INTERVAL.
736 const pollIfRetained = Ref.get(stateRef).pipe(
737 Effect.flatMap((state) => (state.retainCount > 0 ? pollTick() : Effect.void)),
738 );
739 yield* Effect.forkScoped(pollIfRetained.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
740
741 const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {
742 const wasIdle = yield* Ref.modify(stateRef, (state) => [
743 state.retainCount === 0,
744 { ...state, retainCount: state.retainCount + 1 },
745 ]);
746 if (wasIdle) {
747 // Run an immediate scan + broadcast so the new retainer doesn't have
748 // to wait up to POLL_INTERVAL for the first emission.
749 yield* pollTick();
750 }
751 });
752
753 const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(acquireRetention(), () =>
754 Ref.update(stateRef, (state) => ({
755 ...state,
756 retainCount: Math.max(0, state.retainCount - 1),
757 })),
758 );
759
760 const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
761 (input, listener) =>
762 Effect.acquireRelease(
763 Ref.update(stateRef, (state) => {
764 const listeners = new Map(state.listeners);
765 listeners.set(listener, {
766 configuredUrls: normalizeConfiguredUrls(input.configuredUrls),
767 lastSnapshot: input.initialSnapshot,
768 });
769 return { ...state, listeners };
770 }),
771 () =>
772 Ref.update(stateRef, (state) => {
773 const listeners = new Map(state.listeners);
774 listeners.delete(listener);
775 return { ...state, listeners };
776 }),
777 ),
778 );
779
780 const registerTerminalProcesses: PortDiscovery["Service"]["registerTerminalProcesses"] =
781 Effect.fn("PortDiscovery.registerTerminalProcesses")(function* (input) {
782 const owner = {
783 threadId: ThreadId.make(input.threadId),
784 terminalId: input.terminalId,
785 };
786 const processIds = new Set(
787 input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
788 );
789 yield* Ref.update(stateRef, (state) => {
790 const terminalProcesses = new Map(state.terminalProcesses);
791 const key = terminalOwnerKey(owner);
792 if (processIds.size === 0) {
793 terminalProcesses.delete(key);
794 } else {
795 terminalProcesses.set(key, { owner, processIds });
796 }
797 return { ...state, terminalProcesses };
798 });
799 });
800
801 const unregisterTerminal: PortDiscovery["Service"]["unregisterTerminal"] = Effect.fn(
802 "PortDiscovery.unregisterTerminal",
803 )(function* (input) {
804 yield* Ref.update(stateRef, (state) => {
805 const terminalProcesses = new Map(state.terminalProcesses);
806 terminalProcesses.delete(terminalOwnerKey(input));
807 return { ...state, terminalProcesses };
808 });
809 });
810
811 return PortDiscovery.of({
812 scan: scanOnce,
813 subscribe,
814 retain,
815 registerTerminalProcesses,
816 unregisterTerminal,
817 });
818}).pipe(Effect.withSpan("PortDiscovery.make"));
819
820export const layer = Layer.effect(PortDiscovery, make);