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

PortScanner.test.ts

1,318 lines52.1 KB

1// @effect-diagnostics nodeBuiltinImport:off -- the stop test drives real server processes.
2import * as NodeChildProcess from "node:child_process";
3​
4import { it as effectIt } from "@effect/vitest";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import {
7 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
8 PREVIEW_URL_MAX_LENGTH,
9 type DiscoveredLocalServer,
10} from "@t3tools/contracts";
11import * as ProcessGroup from "@t3tools/provider-core/server/processGroup";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as PlatformError from "effect/PlatformError";
20import * as Scope from "effect/Scope";
21import * as TestClock from "effect/testing/TestClock";
22import { expect, vi } from "vite-plus/test";
23import { FetchHttpClient } from "effect/http";
24​
25import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
26import * as ProcessLauncher from "../process/ProcessLauncher.ts";
27import * as ProcessRunner from "../processRunner.ts";
28import * as PortScanner from "./PortScanner.ts";
29​
30vi.mock("@t3tools/provider-core/server/processGroup", { spy: true });
31​
32const processProbeFailure: ProcessRunner.ProcessRunner["Service"]["run"] = (input) =>
33 Effect.fail(
34 new ProcessRunner.ProcessSpawnError({
35 command: input.command,
36 argumentCount: input.args.length,
37 cwd: input.cwd,
38 cause: PlatformError.systemError({
39 _tag: "NotFound",
40 module: "ChildProcess",
41 method: "spawn",
42 description: "PowerShell is not installed in the test environment",
43 }),
44 }),
45 );
46​
47const layerNoProc = FileSystem.layerNoop({});
48​
49const layerForeground = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
50 shouldRunOpportunisticWork: Effect.succeed(true),
51});
52​
53const layerScanner = PortScanner.layer.pipe(Layer.provide(layerForeground));
54​
55const layerProbeFailure = (
56 run: ProcessRunner.ProcessRunner["Service"]["run"],
57 fetch: typeof globalThis.fetch = globalThis.fetch,
58 fileSystem: Layer.Layer<FileSystem.FileSystem> = layerNoProc,
59) =>
60 layerScanner.pipe(
61 Layer.provide(
62 Layer.mergeAll(
63 fileSystem,
64 Layer.succeed(ProcessRunner.ProcessRunner, { run }),
65 Layer.succeed(HostProcess.Platform, "linux"),
66 FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetch))),
67 ),
68 ),
69 );
70​
71const LSOF_TEST_PORT = 43_123;
72​
73const processOutput = (stdout: string): ProcessRunner.ProcessRunOutput => ({
74 stdout,
75 stderr: "",
76 code: ChildProcessSpawner.ExitCode(0),
77 timedOut: false,
78 stdoutTruncated: false,
79 stderrTruncated: false,
80 stdoutInvalidUtf8: false,
81 stderrInvalidUtf8: false,
82});
83​
84const ownedScanner = (processIds: ReadonlyArray<number> = [1234]) =>
85 Effect.tap(PortScanner.PortDiscovery, (scanner) =>
86 scanner.registerTerminalProcesses({
87 threadId: "scanner-thread",
88 terminalId: "scanner-terminal",
89 processIds,
90 }),
91 );
92​
93const layerLsofScanner = (input: {
94 readonly pid: () => number;
95 readonly fetch: typeof globalThis.fetch;
96 readonly stdout?: () => string;
97 readonly backgroundPolicy?: Layer.Layer<BackgroundPolicy.BackgroundPolicy>;
98}) =>
99 PortScanner.layer.pipe(
100 Layer.provide(
101 Layer.mergeAll(
102 input.backgroundPolicy ?? layerForeground,
103 layerNoProc,
104 Layer.succeed(ProcessRunner.ProcessRunner, {
105 run: () =>
106 Effect.succeed({
107 stdout: input.stdout?.() ?? `p${input.pid()}\ncnode\nn*:${LSOF_TEST_PORT}\n`,
108 stderr: "",
109 code: null,
110 timedOut: false,
111 stdoutTruncated: false,
112 stderrTruncated: false,
113 stdoutInvalidUtf8: false,
114 stderrInvalidUtf8: false,
115 }),
116 }),
117 Layer.succeed(HostProcess.Platform, "linux"),
118 FetchHttpClient.layer.pipe(
119 Layer.provide(Layer.succeed(FetchHttpClient.Fetch, input.fetch)),
120 ),
121 ),
122 ),
123 );
124​
125effectIt.effect("keeps a full configured URL when the discovered server root fails", () => {
126 const requests: string[] = [];
127 const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
128 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
129 const url = String(input);
130 requests.push(url);
131 return Promise.resolve(
132 url === configuredUrl
133 ? new Response("docs", { headers: { "content-type": "text/html" } })
134 : new Response("not found", {
135 status: 404,
136 headers: { "content-type": "text/html" },
137 }),
138 );
139 }) as typeof globalThis.fetch;
140 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
141​
142 return Effect.gen(function* () {
143 const scanner = yield* PortScanner.PortDiscovery;
144 const servers = yield* scanner.scan([configuredUrl]);
145 expect(servers).toHaveLength(1);
146 expect(servers[0]?.url).toBe(configuredUrl);
147 expect(requests).toContain(configuredUrl);
148 }).pipe(Effect.provide(layer));
149});
150​
151effectIt.effect("probes configured custom ports through a canonical loopback host", () => {
152 const customPort = 43_124;
153 const configuredUrl = `http://0.0.0.0:${customPort}/docs`;
154 const expectedUrl = `http://localhost:${customPort}/docs`;
155 const requests: string[] = [];
156 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
157 requests.push(String(input));
158 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
159 }) as typeof globalThis.fetch;
160 const layer = layerProbeFailure(processProbeFailure, fetchFn);
161​
162 return Effect.gen(function* () {
163 const scanner = yield* PortScanner.PortDiscovery;
164 const servers = yield* scanner.scan([configuredUrl]);
165 expect(servers).toHaveLength(1);
166 expect(servers[0]?.host).toBe("localhost");
167 expect(servers[0]?.port).toBe(customPort);
168 expect(servers[0]?.url).toBe(expectedUrl);
169 expect(requests).toEqual([expectedUrl]);
170 }).pipe(Effect.provide(layer));
171});
172​
173effectIt.effect("preserves explicit loopback hosts and bounds wildcard rewrites", () => {
174 const ipv4Url = "https://127.0.0.1:43125/docs";
175 const ipv6Url = "http://[::1]:43126/docs";
176 const wildcardPrefix = "http://0.0.0.0/";
177 const maximumWildcardUrl = `${wildcardPrefix}${"a".repeat(
178 PREVIEW_URL_MAX_LENGTH - wildcardPrefix.length,
179 )}`;
180 const requests: string[] = [];
181 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
182 requests.push(String(input));
183 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
184 }) as typeof globalThis.fetch;
185 const layer = layerProbeFailure(processProbeFailure, fetchFn);
186​
187 return Effect.gen(function* () {
188 const scanner = yield* PortScanner.PortDiscovery;
189 const servers = yield* scanner.scan([ipv4Url, ipv6Url, maximumWildcardUrl]);
190 expect(servers.map((server) => server.url)).toEqual([ipv4Url, ipv6Url]);
191 expect(requests).toEqual([ipv4Url, ipv6Url]);
192 }).pipe(Effect.provide(layer));
193});
194​
195effectIt.effect("projects configured paths independently for simultaneous subscribers", () => {
196 const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
197 const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
198 let ready = true;
199 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
200 const url = String(input);
201 return Promise.resolve(
202 ready && (url === docsUrl || url === adminUrl)
203 ? new Response("app", { headers: { "content-type": "text/html" } })
204 : new Response("not found", { status: 404 }),
205 );
206 }) as typeof globalThis.fetch;
207 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
208​
209 return Effect.gen(function* () {
210 const scanner = yield* ownedScanner();
211 const docsSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
212 const adminSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
213 yield* scanner.subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, (servers) =>
214 Effect.sync(() => docsSnapshots.push(servers)),
215 );
216 yield* scanner.subscribe({ configuredUrls: [adminUrl], initialSnapshot: [] }, (servers) =>
217 Effect.sync(() => adminSnapshots.push(servers)),
218 );
219 yield* scanner.retain;
220​
221 expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl);
222 expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl);
223​
224 ready = false;
225 yield* TestClock.adjust(Duration.seconds(15));
226 expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl);
227 expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl);
228 }).pipe(Effect.scoped, Effect.provide(layer));
229});
230​
231effectIt.effect(
232 "keeps each subscriber's candidates when their combined union exceeds the per-client cap",
233 () => {
234 const firstSubscriberUrls = Array.from(
235 { length: CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS },
236 (_, index) => `http://localhost:${LSOF_TEST_PORT}/app-${index}`,
237 );
238 const secondSubscriberUrl = `http://localhost:${LSOF_TEST_PORT}/app-${CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS}`;
239 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) =>
240 Promise.resolve(
241 String(input) === secondSubscriberUrl
242 ? new Response("app", { headers: { "content-type": "text/html" } })
243 : new Response("not found", { status: 404 }),
244 )) as typeof globalThis.fetch;
245 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
246​
247 return Effect.gen(function* () {
248 const scanner = yield* PortScanner.PortDiscovery;
249 const secondSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
250 yield* scanner.subscribe(
251 { configuredUrls: firstSubscriberUrls, initialSnapshot: [] },
252 () => Effect.void,
253 );
254 yield* scanner.subscribe(
255 { configuredUrls: [secondSubscriberUrl], initialSnapshot: [] },
256 (servers) => Effect.sync(() => secondSnapshots.push(servers)),
257 );
258 yield* scanner.retain;
259​
260 expect(secondSnapshots.at(-1)?.[0]?.url).toBe(secondSubscriberUrl);
261 }).pipe(Effect.scoped, Effect.provide(layer));
262 },
263);
264​
265effectIt.effect("stops probing a subscriber's configured paths after its scope closes", () => {
266 const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
267 const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
268 const requests: string[] = [];
269 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
270 const url = String(input);
271 requests.push(url);
272 return Promise.resolve(
273 url === docsUrl || url === adminUrl
274 ? new Response("app", { headers: { "content-type": "text/html" } })
275 : new Response("not found", { status: 404 }),
276 );
277 }) as typeof globalThis.fetch;
278 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
279​
280 return Effect.gen(function* () {
281 const scanner = yield* PortScanner.PortDiscovery;
282 const docsScope = yield* Scope.make();
283 yield* scanner
284 .subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, () => Effect.void)
285 .pipe(Effect.provideService(Scope.Scope, docsScope));
286 yield* scanner.subscribe(
287 { configuredUrls: [adminUrl], initialSnapshot: [] },
288 () => Effect.void,
289 );
290 yield* scanner.retain;
291 yield* Scope.close(docsScope, Exit.void);
292​
293 requests.length = 0;
294 yield* TestClock.adjust(Duration.seconds(15));
295 expect(requests).toContain(adminUrl);
296 expect(requests).not.toContain(docsUrl);
297 }).pipe(Effect.scoped, Effect.provide(layer));
298});
299​
300effectIt.effect("skips scheduled scans while no client is in the foreground", () => {
301 let lsofRuns = 0;
302 let foreground = true;
303 const layer = layerLsofScanner({
304 pid: () => 1234,
305 fetch: (() => Promise.resolve(new Response("not found", { status: 404 }))) as typeof fetch,
306 stdout: () => {
307 lsofRuns += 1;
308 return `p1234\ncnode\nn*:${LSOF_TEST_PORT}\n`;
309 },
310 backgroundPolicy: Layer.mock(BackgroundPolicy.BackgroundPolicy)({
311 shouldRunOpportunisticWork: Effect.sync(() => foreground),
312 }),
313 });
314​
315 return Effect.gen(function* () {
316 const scanner = yield* PortScanner.PortDiscovery;
317 yield* scanner.subscribe(
318 { configuredUrls: [`http://localhost:${LSOF_TEST_PORT}/`], initialSnapshot: [] },
319 () => Effect.void,
320 );
321 yield* scanner.retain;
322 const afterInitialScan = lsofRuns;
323 expect(afterInitialScan).toBeGreaterThan(0);
324​
325 foreground = false;
326 yield* TestClock.adjust(Duration.seconds(15));
327 expect(lsofRuns).toBe(afterInitialScan);
328​
329 foreground = true;
330 yield* TestClock.adjust(Duration.seconds(3));
331 expect(lsofRuns).toBeGreaterThan(afterInitialScan);
332 }).pipe(Effect.scoped, Effect.provide(layer));
333});
334​
335effectIt.effect("uses the current configured fragment when readiness comes from cache", () => {
336 const requests: string[] = [];
337 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
338 requests.push(String(input));
339 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
340 }) as typeof globalThis.fetch;
341 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
342 const oldUrl = `http://localhost:${LSOF_TEST_PORT}/docs#old`;
343 const newUrl = `http://localhost:${LSOF_TEST_PORT}/docs#new`;
344​
345 return Effect.gen(function* () {
346 const scanner = yield* PortScanner.PortDiscovery;
347 expect((yield* scanner.scan([oldUrl]))[0]?.url).toBe(oldUrl);
348 const requestCount = requests.length;
349 expect((yield* scanner.scan([newUrl]))[0]?.url).toBe(newUrl);
350 expect(requests).toHaveLength(requestCount);
351 }).pipe(Effect.provide(layer));
352});
353​
354effectIt.effect(
355 "probes only a configured HTTPS URL, keeps it for an owned listener when the check fails, and does not follow redirects",
356 () => {
357 const configuredUrl = `https://localhost:${LSOF_TEST_PORT}/app`;
358 const requests: Array<readonly [string, string | undefined]> = [];
359 let respond = async () =>
360 new Response(null, { status: 302, headers: { location: "https://example.com" } });
361 const fetchFn = (async (
362 input: Parameters<typeof globalThis.fetch>[0],
363 init?: Parameters<typeof globalThis.fetch>[1],
364 ) => {
365 requests.push([String(input), init?.redirect]);
366 return respond();
367 }) as typeof globalThis.fetch;
368 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
369​
370 return Effect.gen(function* () {
371 const scanner = yield* ownedScanner();
372 expect(yield* scanner.scan([configuredUrl])).toMatchObject([
373 { pid: 1234, url: configuredUrl },
374 ]);
375​
376 respond = async () => new Response("unavailable", { status: 503 });
377 yield* TestClock.adjust(Duration.seconds(15));
378 expect(yield* scanner.scan([configuredUrl])).toMatchObject([
379 { pid: 1234, url: configuredUrl },
380 ]);
381​
382 respond = () => Promise.reject(new TypeError("fetch failed"));
383 yield* TestClock.adjust(Duration.seconds(15));
384 expect(yield* scanner.scan([configuredUrl])).toMatchObject([
385 { pid: 1234, url: configuredUrl },
386 ]);
387 expect(requests).toEqual(Array.from({ length: 3 }, () => [configuredUrl, "manual"]));
388 }).pipe(Effect.provide(layer));
389 },
390);
391​
392effectIt.effect("discovers owned listeners without sending HTTP or TLS probes", () => {
393 const owned = `p1234\ncnode\nn[::1]:${LSOF_TEST_PORT}\n`;
394 const unowned = `p5678\ncrpc\nn127.0.0.1:${LSOF_TEST_PORT}\n`;
395 let stdout = unowned;
396 const requests: string[] = [];
397 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
398 requests.push(String(input));
399 return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
400 }) as typeof globalThis.fetch;
401 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn, stdout: () => stdout });
402​
403 return Effect.gen(function* () {
404 const scanner = yield* ownedScanner();
405 expect(yield* scanner.scan()).toHaveLength(0);
406 stdout = `${owned}${unowned}`;
407 expect(yield* scanner.scan()).toHaveLength(0);
408 expect(requests).toEqual([]);
409​
410 stdout = owned;
411 expect(yield* scanner.scan()).toHaveLength(1);
412 expect(requests).toEqual([]);
413​
414 yield* scanner.unregisterTerminal({
415 threadId: "scanner-thread",
416 terminalId: "scanner-terminal",
417 });
418 expect(yield* scanner.scan()).toHaveLength(0);
419 expect(requests).toEqual([]);
420 }).pipe(Effect.provide(layer));
421});
422​
423effectIt.effect(
424 "excludes configured URLs answering with HTTP errors, non-navigation responses, or non-documents",
425 () => {
426 let pid = 1;
427 let makeResponse = () =>
428 new Response("not found", { status: 404, headers: { "content-type": "text/html" } });
429 const fetchFn = ((_input: Parameters<typeof globalThis.fetch>[0]) =>
430 Promise.resolve(makeResponse())) as typeof globalThis.fetch;
431 const layer = layerLsofScanner({ pid: () => pid, fetch: fetchFn });
432 const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/`;
433​
434 return Effect.gen(function* () {
435 const scanner = yield* PortScanner.PortDiscovery;
436 const scan = () => scanner.scan([configuredUrl]);
437 expect(yield* scan()).toHaveLength(0);
438​
439 pid += 1;
440 makeResponse = () =>
441 new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
442 expect(yield* scan()).toHaveLength(0);
443​
444 pid += 1;
445 makeResponse = () =>
446 new Response("ready", { status: 200, headers: { "content-type": "text/plain" } });
447 expect(yield* scan()).toHaveLength(0);
448​
449 pid += 1;
450 makeResponse = () => new Response(null, { status: 304, headers: { location: "/cached" } });
451 expect(yield* scan()).toHaveLength(0);
452​
453 pid += 1;
454 makeResponse = () =>
455 new Response(null, { status: 204, headers: { "content-type": "text/html" } });
456 expect(yield* scan()).toHaveLength(0);
457​
458 pid += 1;
459 makeResponse = () => new Response(null, { status: 302 });
460 expect(yield* scan()).toHaveLength(0);
461​
462 pid += 1;
463 makeResponse = () =>
464 new Response("<html />", {
465 status: 200,
466 headers: { "content-type": "application/xhtml+xml; charset=utf-8" },
467 });
468 expect(yield* scan()).toHaveLength(1);
469 }).pipe(Effect.provide(layer));
470 },
471);
472​
473const PROC_NET_TCP = ` sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
474 0: 0100007F:223D 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5001 1 0000000000000000 100 0 0 10 0
475 1: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 5002 1 0000000000000000 100 0 0 10 0
476 2: 0100007F:223D 0100007F:C350 01 00000000:00000000 00:00000000 00000000 1000 0 5003 1 0000000000000000 20 4 30 10 -1
477 3: 0A00000F:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5005 1 0000000000000000 100 0 0 10 0
478`;
479const PROC_NET_TCP6 = ` sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
480 0: 00000000000000000000000000000000:0BB9 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5004 1 0000000000000000 100 0 0 10 0
481`;
482​
483effectIt.effect(
484 "prefers Linux /proc over installed lsof, and bounds repeated socket owner lookups",
485 () => {
486 let lsofSpawns = 0;
487 const fdWalks: string[] = [];
488 const procFiles: Record<string, string> = {
489 "/proc/net/tcp":
490 PROC_NET_TCP +
491 PROC_NET_TCP.split("\n")[1]!
492 .replace("0100007F:223D", "0101007F:1388")
493 .replace("5001", "5007"),
494 "/proc/net/tcp6": PROC_NET_TCP6,
495 "/proc/4242/comm": "python3\n",
496 };
497 const procFds: Record<string, Record<string, string>> = {
498 "4242": {
499 "0": "/dev/null",
500 "3": "socket:[5001]",
501 "4": "socket:[5004]",
502 "5": "socket:[5007]",
503 },
504 "77": { "5": "socket:[9999]" },
505 };
506 const missing = FileSystem.makeNoop({});
507 const fileSystem = FileSystem.layerNoop({
508 readFileString: (path) => {
509 const content = procFiles[path];
510 return content === undefined ? missing.readFileString(path) : Effect.succeed(content);
511 },
512 readDirectory: (path) => {
513 if (path === "/proc") return Effect.succeed(["self", "77", "4242"]);
514 const pid = /^\/proc\/(\d+)\/fd$/.exec(path)?.[1];
515 const fds = pid === undefined ? undefined : procFds[pid];
516 if (pid === undefined || fds === undefined) return missing.readDirectory(path);
517 fdWalks.push(pid);
518 return Effect.succeed(Object.keys(fds));
519 },
520 readLink: (path) => {
521 const [, pid, fd] = /^\/proc\/(\d+)\/fd\/(\d+)$/.exec(path) ?? [];
522 const target = pid && fd ? procFds[pid]?.[fd] : undefined;
523 return target === undefined ? missing.readLink(path) : Effect.succeed(target);
524 },
525 });
526 const requests: string[] = [];
527 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
528 requests.push(String(input));
529 return Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }));
530 }) as typeof globalThis.fetch;
531 const layer = layerProbeFailure(
532 () => {
533 lsofSpawns += 1;
534 return Effect.succeed(processOutput("p4242\ncpython3\nn*:3001\nn*:8765\n"));
535 },
536 fetchFn,
537 fileSystem,
538 );
539​
540 return Effect.gen(function* () {
541 const scanner = yield* ownedScanner([4242]);
542 const first = yield* scanner.scan();
543 expect(
544 first.map(({ port, pid, processName, url }) => ({ port, pid, processName, url })),
545 ).toEqual([
546 { port: 3001, pid: 4242, processName: "python3", url: "http://localhost:3001" },
547 { port: 8765, pid: 4242, processName: "python3", url: "http://localhost:8765" },
548 ]);
549 yield* scanner.scan();
550 expect(lsofSpawns).toBe(0);
551 expect(fdWalks).toEqual(["77", "4242", "77", "4242"]);
552 yield* scanner.scan();
553 yield* scanner.scan();
554 expect(fdWalks).toEqual(["77", "4242", "77", "4242", "77", "4242"]);
555 procFds["77"]!["6"] = "socket:[5006]";
556 procFiles["/proc/net/tcp6"] =
557 PROC_NET_TCP6 + PROC_NET_TCP.split("\n")[1]!.replace("5001", "5006");
558 expect((yield* scanner.scan()).map(({ port }) => port)).toEqual([3001]);
559 const walksAfterCollision = fdWalks.length;
560 procFiles["/proc/net/tcp"] = PROC_NET_TCP.split("\n")[0]!;
561 procFiles["/proc/net/tcp6"] = PROC_NET_TCP6.split("\n")[0]!;
562 expect(yield* scanner.scan()).toEqual([]);
563 expect(lsofSpawns).toBe(0);
564 expect(fdWalks).toHaveLength(walksAfterCollision);
565 expect(requests).toEqual([]);
566​
567 procFiles["/proc/net/tcp"] = PROC_NET_TCP;
568 procFiles["/proc/net/tcp6"] = PROC_NET_TCP6;
569 expect((yield* scanner.scan()).map(({ pid }) => pid)).toEqual([4242, 4242]);
570 yield* scanner.retain.pipe(Effect.scoped);
571 procFds["77"] = procFds["4242"]!;
572 delete procFds["4242"];
573 procFiles["/proc/77/comm"] = "python3\n";
574 yield* scanner.registerTerminalProcesses({
575 threadId: "scanner-thread",
576 terminalId: "scanner-terminal",
577 processIds: [77],
578 });
579 expect((yield* scanner.scan()).map(({ port, pid }) => ({ port, pid }))).toEqual([
580 { port: 3001, pid: 77 },
581 { port: 8765, pid: 77 },
582 ]);
583 }).pipe(Effect.provide(layer));
584 },
585);
586​
587effectIt.effect.each([
588 { mode: "missing", fallback: true },
589 { mode: "denied", fallback: true },
590 { mode: "invalid", fallback: true },
591 { mode: "fd-unavailable", fallback: true },
592 { mode: "fd-budget", fallback: true },
593 { mode: "fd-budget-no-lsof", fallback: true },
594 { mode: "ipv6-denied", fallback: true },
595 { mode: "ipv6-absent", fallback: false },
596 { mode: "empty", fallback: false },
597 { mode: "darwin", fallback: true },
598] as const)("uses lsof only if Linux /proc is unusable: $mode", ({ mode, fallback }) => {
599 let lsofSpawns = 0;
600 let procWalks = 0;
601 const missing = FileSystem.makeNoop({});
602 const layer = layerScanner.pipe(
603 Layer.provide(
604 Layer.mergeAll(
605 FileSystem.layerNoop({
606 readFileString: (path) => {
607 if (!path.startsWith("/proc/net/tcp") || mode === "missing") {
608 return missing.readFileString(path);
609 }
610 if (mode === "denied" || (mode === "ipv6-denied" && path.endsWith("tcp6"))) {
611 return Effect.fail(
612 PlatformError.systemError({
613 _tag: "PermissionDenied",
614 module: "FileSystem",
615 method: "readFileString",
616 }),
617 );
618 }
619 if (mode === "ipv6-absent" && path.endsWith("tcp6")) {
620 return missing.readFileString(path);
621 }
622 if (mode === "invalid") return Effect.succeed("unusable table");
623 return Effect.succeed(
624 mode === "fd-unavailable" || mode.startsWith("fd-budget")
625 ? PROC_NET_TCP
626 : PROC_NET_TCP.split("\n")[0]!,
627 );
628 },
629 readDirectory: (path) => {
630 if (!mode.startsWith("fd-budget")) return missing.readDirectory(path);
631 if (path === "/proc") procWalks += 1;
632 if (mode === "fd-budget-no-lsof") {
633 if (path === "/proc") return Effect.succeed(["1234", "9999"]);
634 if (path === "/proc/1234/fd") return Effect.succeed(["3"]);
635 }
636 return Effect.succeed(
637 path === "/proc"
638 ? ["1", "1234"]
639 : Array.from({ length: 50_000 }, (_, i) => String(i)),
640 );
641 },
642 readLink: (path) =>
643 mode === "fd-budget-no-lsof" && path === "/proc/1234/fd/3"
644 ? Effect.succeed("socket:[5001]")
645 : mode.startsWith("fd-budget")
646 ? Effect.succeed("/dev/null")
647 : missing.readLink(path),
648 }),
649 Layer.succeed(ProcessRunner.ProcessRunner, {
650 run: (input) => {
651 lsofSpawns += 1;
652 if (mode === "fd-budget-no-lsof") return processProbeFailure(input);
653 return Effect.succeed(processOutput(`p1234\ncnode\nn*:${LSOF_TEST_PORT}\n`));
654 },
655 }),
656 Layer.succeed(HostProcess.Platform, mode === "darwin" ? "darwin" : "linux"),
657 FetchHttpClient.layer,
658 ),
659 ),
660 );
661 return Effect.gen(function* () {
662 const scanner = yield* ownedScanner();
663 expect((yield* scanner.scan()).map(({ port }) => port)).toEqual(
664 mode === "fd-budget-no-lsof" ? [8765] : fallback ? [LSOF_TEST_PORT] : [],
665 );
666 if (mode === "fd-budget-no-lsof") {
667 for (let i = 0; i < 3; i += 1) {
668 expect((yield* scanner.scan()).map(({ port }) => port)).toEqual([8765]);
669 }
670 expect(procWalks).toBe(4);
671 }
672 expect(lsofSpawns).toBe(fallback ? 1 : 0);
673 }).pipe(Effect.provide(layer));
674});
675​
676effectIt.effect("ignores a partial Windows netstat snapshot when one query exits nonzero", () => {
677 let ipv6Fails = true;
678 const requests: string[] = [];
679 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
680 requests.push(String(input));
681 return Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }));
682 }) as typeof globalThis.fetch;
683 const layer = layerScanner.pipe(
684 Layer.provide(
685 Layer.mergeAll(
686 layerNoProc,
687 Layer.succeed(ProcessRunner.ProcessRunner, {
688 run: (input) => {
689 if (input.command === String.raw`C:\Windows\System32\tasklist.exe`) {
690 return Effect.succeed(
691 processOutput('"node.exe","1234","Console","1","50,000 K"\r\n'),
692 );
693 }
694 const isIpv6 = input.args.includes("tcpv6");
695 return Effect.succeed({
696 stdout: isIpv6
697 ? ""
698 : " TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 1234\r\n",
699 stderr: "",
700 code: isIpv6 && ipv6Fails ? ChildProcessSpawner.ExitCode(1) : null,
701 timedOut: false,
702 stdoutTruncated: false,
703 stderrTruncated: false,
704 stdoutInvalidUtf8: false,
705 stderrInvalidUtf8: false,
706 });
707 },
708 }),
709 Layer.succeed(HostProcess.Platform, "win32"),
710 Layer.succeed(HostProcess.Environment, {}),
711 FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))),
712 ),
713 ),
714 );
715​
716 return Effect.gen(function* () {
717 const scanner = yield* PortScanner.PortDiscovery;
718 yield* scanner.registerTerminalProcesses({
719 threadId: "scanner-thread",
720 terminalId: "scanner-terminal",
721 processIds: [1234],
722 });
723 expect(yield* scanner.scan()).toEqual([]);
724 ipv6Fails = false;
725 expect(yield* scanner.scan()).toMatchObject([
726 { port: 5173, pid: 1234, processName: "node", url: "http://localhost:5173" },
727 ]);
728 expect(requests).toEqual([]);
729 }).pipe(Effect.provide(layer));
730});
731​
732effectIt.effect("rechecks the socket owner before stopping a Linux server without lsof", () => {
733 let holder = "4242";
734 const missing = FileSystem.makeNoop({});
735 const layer = layerProbeFailure(
736 (input) =>
737 input.command === "lsof"
738 ? processProbeFailure(input)
739 : Effect.succeed(processOutput("4242 1 4300\n5000 1 5300\n")),
740 () => Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } })),
741 FileSystem.layerNoop({
742 readFileString: (path) => {
743 if (path === "/proc/net/tcp") {
744 return Effect.succeed(PROC_NET_TCP.split("\n").slice(0, 2).join("\n"));
745 }
746 if (/^\/proc\/(4242|5000)\/comm$/.test(path)) return Effect.succeed("node\n");
747 if (/^\/proc\/(4242|5000)\/environ$/.test(path)) {
748 return Effect.succeed(`${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`);
749 }
750 return missing.readFileString(path);
751 },
752 readDirectory: (path) => {
753 if (path === "/proc") return Effect.succeed(["4242", "5000"]);
754 if (/^\/proc\/(4242|5000)\/fd$/.test(path)) {
755 return Effect.succeed(path === `/proc/${holder}/fd` ? ["3"] : []);
756 }
757 return missing.readDirectory(path);
758 },
759 readLink: (path) =>
760 path === `/proc/${holder}/fd/3` ? Effect.succeed("socket:[5001]") : missing.readLink(path),
761 }),
762 );
763​
764 return Effect.gen(function* () {
765 const signal = vi.spyOn(ProcessGroup, "signalProcessGroup").mockImplementation(() => {
766 throw Object.assign(new Error("No such process"), { code: "ESRCH" });
767 });
768 yield* Effect.addFinalizer(() => Effect.sync(() => signal.mockRestore()));
769 const scanner = yield* PortScanner.PortDiscovery;
770 expect(yield* scanner.scan()).toMatchObject([{ pid: 4242, port: 8765 }]);
771​
772 // The socket outlives its original holder. Its old pid now belongs to another agent job.
773 holder = "5000";
774 const result = yield* scanner
775 .stopServer({ pid: 4242, port: 8765 })
776 .pipe(Effect.match({ onFailure: (error) => error.reason, onSuccess: () => null }));
777 expect(signal).not.toHaveBeenCalled();
778 expect(result).toBe("not-found");
779 expect(yield* scanner.scan()).toMatchObject([{ pid: 5000, port: 8765 }]);
780 yield* scanner.stopServer({ pid: 5000, port: 8765 });
781 expect(signal).toHaveBeenCalledExactlyOnceWith(5300, "SIGTERM");
782 }).pipe(Effect.provide(layer));
783});
784​
785effectIt.effect.each(["linux", "darwin", "win32"] as const)(
786 "reads no listeners on %s while T3CODE_PORT_DISCOVERY=0, and still probes configured URLs",
787 (platform) => {
788 const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
789 const commands: string[] = [];
790 const fileReads: string[] = [];
791 const requests: string[] = [];
792 const missing = FileSystem.makeNoop({});
793 const layer = layerScanner.pipe(
794 Layer.provide(
795 Layer.mergeAll(
796 FileSystem.layerNoop({
797 readFileString: (path) => {
798 fileReads.push(path);
799 return missing.readFileString(path);
800 },
801 readDirectory: (path) => {
802 fileReads.push(path);
803 return missing.readDirectory(path);
804 },
805 }),
806 Layer.succeed(ProcessRunner.ProcessRunner, {
807 run: (input) => {
808 commands.push(input.command);
809 return Effect.succeed(processOutput(`p1234\ncnode\nn*:${LSOF_TEST_PORT}\n`));
810 },
811 }),
812 Layer.succeed(HostProcess.Platform, platform),
813 Layer.succeed(HostProcess.Environment, { T3CODE_PORT_DISCOVERY: "0" }),
814 FetchHttpClient.layer.pipe(
815 Layer.provide(
816 Layer.succeed(FetchHttpClient.Fetch, (input) => {
817 requests.push(String(input));
818 return Promise.resolve(
819 new Response("docs", { headers: { "content-type": "text/html" } }),
820 );
821 }),
822 ),
823 ),
824 ),
825 ),
826 );
827​
828 return Effect.gen(function* () {
829 const scanner = yield* ownedScanner();
830 scanner.trackAgent();
831 expect(yield* scanner.scan()).toEqual([]);
832 expect(yield* scanner.scan([configuredUrl])).toMatchObject([
833 { port: LSOF_TEST_PORT, pid: null, terminal: null, url: configuredUrl },
834 ]);
835 expect(requests).toEqual([configuredUrl]);
836 expect(commands).toEqual([]);
837 expect(fileReads).toEqual([]);
838 }).pipe(Effect.provide(layer));
839 },
840);
841​
842effectIt.effect.each(["linux", "darwin"] as const)(
843 "skips the DevTools port of a browser an agent's tool launched on %s",
844 (platform) => {
845 const appPort = 43_126;
846 const devToolsPort = 43_127;
847 const agentEnvironment = `PATH=/usr/bin\0${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`;
848 const procFiles: Record<string, string> = {
849 "/proc/4242/environ": agentEnvironment,
850 "/proc/4242/cmdline": "node\0server.js\0",
851 "/proc/6000/environ": agentEnvironment,
852 "/proc/6000/cmdline": "/opt/google/chrome/chrome\0--remote-debugging-port=0\0about:blank\0",
853 };
854 const missing = FileSystem.makeNoop({});
855 const layer = layerScanner.pipe(
856 Layer.provide(
857 Layer.mergeAll(
858 FileSystem.layerNoop({
859 readFileString: (path) => {
860 const content = procFiles[path];
861 return content === undefined ? missing.readFileString(path) : Effect.succeed(content);
862 },
863 }),
864 Layer.succeed(ProcessRunner.ProcessRunner, {
865 run: (input) =>
866 Effect.succeed(
867 processOutput(
868 input.command === "lsof"
869 ? `p4242\ncnode\nn127.0.0.1:${appPort}\np6000\ncchrome\nn127.0.0.1:${devToolsPort}\n`
870 : ` 4242 1 node server.js PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-agent\n` +
871 ` 6000 1 /opt/google/chrome/chrome --remote-debugging-port=0 about:blank PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-agent\n`,
872 ),
873 ),
874 }),
875 Layer.succeed(HostProcess.Platform, platform),
876 FetchHttpClient.layer.pipe(
877 Layer.provide(Layer.succeed(FetchHttpClient.Fetch, () => Promise.reject(new Error()))),
878 ),
879 ),
880 ),
881 );
882​
883 return Effect.gen(function* () {
884 const scanner = yield* PortScanner.PortDiscovery;
885 expect(yield* scanner.scan()).toMatchObject([
886 { port: appPort, pid: 4242, agent: { threadId: "thread-agent" } },
887 ]);
888 }).pipe(Effect.provide(layer));
889 },
890);
891​
892effectIt.effect.each(["linux", "darwin"] as const)(
893 "attributes listeners to the agent thread in their environment on %s, after the agent exits",
894 (platform) => {
895 const agentPort = 43_124;
896 const otherPort = 43_125;
897 // The agent CLI has the thread in its environment too; its own port is not a server.
898 const agentListener =
899 `p4242\ncnode\nn127.0.0.1:${agentPort}\n` + `p4300\ncagy\nn127.0.0.1:43126\n`;
900 const otherListener = `p5000\ncpostgres\nn127.0.0.1:${otherPort}\n`;
901 let lsofStdout = otherListener;
902 let lsofFails = false;
903 let environmentFails = false;
904 let lsofCalls = 0;
905 let environmentReads = 0;
906 const requests: string[] = [];
907 const missing = FileSystem.makeNoop({});
908 const procEnviron: Record<string, string> = {
909 "/proc/4242/environ": `PATH=/usr/bin\0${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`,
910 "/proc/5000/environ": "PATH=/usr/bin\0",
911 };
912 const procAgent: Record<string, string> = {
913 "/proc/4242/stat": "4242 (node) S 4300 4300 4300 0",
914 "/proc/4300/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`,
915 "/proc/4300/stat": `4300 (agy acp) S ${process.pid} 4300 4300 0`,
916 };
917 const layer = layerScanner.pipe(
918 Layer.provide(
919 Layer.mergeAll(
920 FileSystem.layerNoop({
921 readFileString: (path) => {
922 const agent = procAgent[path];
923 if (agent !== undefined) return Effect.succeed(agent);
924 const content = procEnviron[path];
925 if (content === undefined) return missing.readFileString(path);
926 environmentReads += 1;
927 return Effect.succeed(content);
928 },
929 }),
930 Layer.succeed(ProcessRunner.ProcessRunner, {
931 run: (input) => {
932 if (input.command === "lsof") {
933 lsofCalls += 1;
934 return lsofFails
935 ? Effect.fail(
936 new ProcessRunner.ProcessTimeoutError({
937 command: input.command,
938 argumentCount: input.args.length,
939 cwd: input.cwd,
940 timeoutMs: 5_000,
941 }),
942 )
943 : Effect.succeed(processOutput(lsofStdout));
944 }
945 // In its agent CLI's process group, so stop refuses it without signaling anything.
946 if (input.args[0] === "-A") {
947 return Effect.succeed(processOutput(`4242 4300 4300\n4300 ${process.pid} 4300\n`));
948 }
949 if (environmentFails) {
950 return Effect.fail(
951 new ProcessRunner.ProcessTimeoutError({
952 command: input.command,
953 argumentCount: input.args.length,
954 timeoutMs: 5_000,
955 }),
956 );
957 }
958 environmentReads += 1;
959 return Effect.succeed(
960 processOutput(
961 ` 4242 4300 node server.js PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-agent HOME=/Users/dev\n` +
962 ` 4300 ${process.pid} agy acp ${PortScanner.AGENT_THREAD_ENV}=thread-agent\n` +
963 " 5000 1 postgres -D /data PATH=/usr/bin\n",
964 ),
965 );
966 },
967 }),
968 Layer.succeed(HostProcess.Platform, platform),
969 FetchHttpClient.layer.pipe(
970 Layer.provide(
971 Layer.succeed(FetchHttpClient.Fetch, (input) => {
972 requests.push(String(input));
973 return Promise.resolve(
974 new Response("app", { headers: { "content-type": "text/html" } }),
975 );
976 }),
977 ),
978 ),
979 ),
980 ),
981 );
982​
983 return Effect.gen(function* () {
984 const scanner = yield* PortScanner.PortDiscovery;
985 // Startup reads listeners once. With none marked, later scans stay idle.
986 expect(yield* scanner.scan()).toEqual([]);
987 expect(yield* scanner.scan()).toEqual([]);
988 expect(lsofCalls).toBe(1);
989​
990 // The agent exits before any client looks, and the first read fails; its server is still
991 // found.
992 lsofStdout = `${agentListener}${otherListener}`;
993 scanner.trackAgent()();
994 lsofFails = true;
995 expect(yield* scanner.scan()).toEqual([]);
996 lsofFails = false;
997 if (platform === "darwin") {
998 environmentFails = true;
999 expect(yield* scanner.scan()).toEqual([]);
1000 environmentFails = false;
1002 expect(yield* scanner.scan()).toMatchObject([
1003 { port: agentPort, pid: 4242, terminal: null, agent: { threadId: "thread-agent" } },
1004 ]);
1005 expect(requests).toEqual([]);
1006​
1007 expect(yield* scanner.scan()).toHaveLength(1);
1008 expect(environmentReads).toBe(2);
1009​
1010 // Stop reads its target's environment again rather than trust the cache, and still finds it.
1011 const stop = yield* Effect.flip(scanner.stopServer({ pid: 4242, port: agentPort }));
1012 expect(stop.reason).toBe("shared-group");
1013 expect(environmentReads).toBe(3);
1014​
1015 lsofStdout = otherListener;
1016 expect(yield* scanner.scan()).toEqual([]);
1017 const lsofCallsAfterExit = lsofCalls;
1018 expect(yield* scanner.scan()).toEqual([]);
1019 expect(lsofCalls).toBe(lsofCallsAfterExit);
1020 }).pipe(Effect.provide(layer));
1021 },
1023​
1024effectIt.effect("stops only a job's own process group", () =>
1025 Effect.sync(() => {
1026 const serverPid = 100;
1027 const launcherPid = 150;
1028 const rows = [
1029 { pid: 10, ppid: 1, pgid: 10 }, // `vp run dev`, whose job holds this server
1030 { pid: 20, ppid: 10, pgid: 10 }, // the web dev server in the same job
1031 { pid: serverPid, ppid: 10, pgid: 10 },
1032 { pid: launcherPid, ppid: serverPid, pgid: 10 }, // Linux ProcessLauncher worker
1033 { pid: 200, ppid: serverPid, pgid: 200 }, // direct agent CLI
1034 { pid: 210, ppid: 200, pgid: 200 }, // a server it spawned without a group of its own
1035 { pid: 250, ppid: launcherPid, pgid: 250 }, // launcher-spawned agent CLI (e.g. agy acp)
1036 { pid: 260, ppid: 250, pgid: 250 }, // a server in the launcher-spawned agent CLI's group
1037 { pid: 270, ppid: 250, pgid: 270 }, // a job started by the launcher-spawned agent CLI
1038 { pid: 300, ppid: 200, pgid: 300 }, // agent tool shell
1039 { pid: 400, ppid: 300, pgid: 400 }, // `npm run dev &`
1040 { pid: 401, ppid: 400, pgid: 400 },
1041 { pid: 500, ppid: serverPid, pgid: 500 }, // terminal shell
1042 { pid: 600, ppid: 500, pgid: 600 }, // terminal job
1043 ];
1044 const table = new Map(rows.map((row) => [row.pid, row]));
1045 expect(PortScanner.stoppableProcessGroup(table, 401, serverPid, launcherPid)).toBe(400);
1046 expect(PortScanner.stoppableProcessGroup(table, 600, serverPid, launcherPid)).toBe(600);
1047 expect(PortScanner.stoppableProcessGroup(table, 270, serverPid, launcherPid)).toBe(270);
1048 for (const pid of [20, 150, 210, 250, 260, 500, 999]) {
1049 expect(PortScanner.stoppableProcessGroup(table, pid, serverPid, launcherPid)).toBeNull();
1051 // The tool shell is the command; its `npm run dev &` job only inherited the name.
1052 const variables = new Map([
1053 [200, new Map<string, string>()],
1054 [300, new Map([["COMMAND", "a"]])],
1055 [400, new Map([["COMMAND", "a"]])],
1056 ]);
1057 expect([...PortScanner.agentCommandsInGroup(variables, table.get(300)!)]).toEqual([
1058 ["COMMAND", "a"],
1059 ]);
1060 expect(PortScanner.agentCommandsInGroup(variables, table.get(400)!).size).toBe(0);
1061 expect(PortScanner.agentCommandsInGroup(variables, table.get(600)!).size).toBe(0);
1062 }),
1064​
1065effectIt.effect(
1066 "excludes Linux agent CLIs spawned through ProcessLauncher (including after restarts) while keeping their dev servers",
1067 () => {
1068 let launcherPid = 9_000;
1069 const firstDevPort = 43_201;
1070 const secondDevPort = 43_202;
1071 let lsofStdout =
1072 `p4300\ncagy\nn127.0.0.1:43200\n` +
1073 `p4301\ncclaude\nn127.0.0.1:43199\n` +
1074 `p4242\ncnode\nn127.0.0.1:${firstDevPort}\n`;
1075 const procFiles: Record<string, string> = {
1076 "/proc/4300/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-agy\0`,
1077 "/proc/4300/stat": `4300 (agy) S ${launcherPid} 4300 4300 0`,
1078 "/proc/4301/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-claude\0`,
1079 "/proc/4301/stat": `4301 (claude) S ${process.pid} 4301 4301 0`,
1080 "/proc/4242/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-agy\0`,
1081 "/proc/4242/stat": "4242 (node) S 4300 4300 4300 0",
1082 };
1083 const missing = FileSystem.makeNoop({});
1084 const layer = layerScanner.pipe(
1085 Layer.provide(
1086 Layer.mergeAll(
1087 FileSystem.layerNoop({
1088 readFileString: (path) => {
1089 const content = procFiles[path];
1090 return content === undefined ? missing.readFileString(path) : Effect.succeed(content);
1091 },
1092 }),
1093 Layer.succeed(ProcessRunner.ProcessRunner, {
1094 run: (input) =>
1095 input.command === "lsof"
1096 ? Effect.succeed(processOutput(lsofStdout))
1097 : Effect.succeed(
1098 processOutput(
1099 `${launcherPid} ${process.pid} ${process.pid}\n` +
1100 `4300 ${launcherPid} 4300\n` +
1101 "4242 4300 4300\n",
1102 ),
1103 ),
1104 }),
1105 Layer.succeed(ProcessLauncher.ProcessLauncher, {
1106 currentPid: Effect.sync(() => launcherPid),
1107 }),
1108 Layer.succeed(HostProcess.Platform, "linux"),
1109 FetchHttpClient.layer.pipe(
1110 Layer.provide(Layer.succeed(FetchHttpClient.Fetch, () => Promise.reject(new Error()))),
1111 ),
1112 ),
1113 ),
1114 );
1115​
1116 return Effect.gen(function* () {
1117 const scanner = yield* PortScanner.PortDiscovery;
1118 expect(yield* scanner.scan()).toMatchObject([
1119 { port: firstDevPort, pid: 4242, agent: { threadId: "thread-agy" } },
1120 ]);
1121​
1122 // Refuses to stop a server sharing the ProcessLauncher-spawned agent CLI's process group.
1123 const stop = yield* Effect.flip(scanner.stopServer({ pid: 4242, port: firstDevPort }));
1124 expect(stop.reason).toBe("shared-group");
1125​
1126 // After ProcessLauncher restarts with a new helper PID, new agent CLIs are still excluded.
1127 launcherPid = 9_001;
1128 procFiles["/proc/4400/environ"] = `${PortScanner.AGENT_THREAD_ENV}=thread-agy-2\0`;
1129 procFiles["/proc/4400/stat"] = `4400 (agy) S ${launcherPid} 4400 4400 0`;
1130 procFiles["/proc/4401/environ"] = `${PortScanner.AGENT_THREAD_ENV}=thread-agy-2\0`;
1131 procFiles["/proc/4401/stat"] = "4401 (node) S 4400 4401 4401 0";
1132 lsofStdout = `p4400\ncagy\nn127.0.0.1:43210\np4401\ncnode\nn127.0.0.1:${secondDevPort}\n`;
1133​
1134 expect(yield* scanner.scan()).toMatchObject([
1135 { port: secondDevPort, pid: 4401, agent: { threadId: "thread-agy-2" } },
1136 ]);
1137 }).pipe(Effect.provide(layer));
1138 },
1140​
1141effectIt.effect.each([
1143 case: "its parent's arguments",
1144 leader: { command: "node server.js", env: "COMMAND=cmd-a" },
1145 parent: { command: "/bin/bash -c set -m; COMMAND=cmd-a node server.js & wait", env: "" },
1146 stops: ["cmd-a"],
1147 },
1149 case: "its own arguments",
1150 leader: { command: "node server.js COMMAND=cmd-a", env: "" },
1151 parent: { command: "/bin/bash -c node server.js & wait", env: "" },
1152 stops: [],
1153 },
1154])("on macOS, a stop names the command in the leader's environment, not $case", (scenario) => {
1155 const port = 43_127;
1156 // macOS `ps -E` prints the environment after the arguments; plain `ps` prints only the arguments.
1157 const command = (row: { command: string; env: string }, withEnvironment: boolean) =>
1158 withEnvironment
1159 ? `${row.command} PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-a ${row.env}`.trim()
1160 : row.command;
1161 const layer = layerScanner.pipe(
1162 Layer.provide(
1163 Layer.mergeAll(
1164 layerNoProc,
1165 Layer.succeed(ProcessRunner.ProcessRunner, {
1166 run: (input) => {
1167 if (input.command === "lsof") {
1168 return Effect.succeed(processOutput(`p4242\ncnode\nn127.0.0.1:${port}\n`));
1170 if (input.args[0] === "-A") {
1171 return Effect.succeed(
1172 processOutput(`4242 4300 4242\n4300 4200 4300\n4200 ${process.pid} 4200\n`),
1173 );
1175 const withEnvironment = input.args.includes("-E");
1176 const withParent = input.args.includes("pid=,ppid=,command=");
1177 return Effect.succeed(
1178 processOutput(
1179 ` 4242${withParent ? " 4300" : ""} ${command(scenario.leader, withEnvironment)}\n` +
1180 ` 4300${withParent ? " 4200" : ""} ${command(scenario.parent, withEnvironment)}\n`,
1181 ),
1182 );
1183 },
1184 }),
1185 Layer.succeed(HostProcess.Platform, "darwin"),
1186 FetchHttpClient.layer,
1187 ),
1188 ),
1189 );
1190​
1191 return Effect.gen(function* () {
1192 const signal = vi.spyOn(ProcessGroup, "signalProcessGroup").mockImplementation(() => {
1193 throw Object.assign(new Error("No such process"), { code: "ESRCH" });
1194 });
1195 yield* Effect.addFinalizer(() => Effect.sync(() => signal.mockRestore()));
1196 const scanner = yield* PortScanner.PortDiscovery;
1197 scanner.trackAgent();
1198 const stops: string[] = [];
1199 yield* scanner.watchAgentCommandStops({
1200 variable: "COMMAND",
1201 onStop: (stopped) => Effect.sync(() => stops.push(stopped)),
1202 onStopAbandoned: () => Effect.void,
1203 });
1204 expect(yield* scanner.scan()).toMatchObject([{ pid: 4242, agent: { threadId: "thread-a" } }]);
1205 yield* scanner.stopServer({ pid: 4242, port });
1206 expect(signal).toHaveBeenCalledExactlyOnceWith(4242, "SIGTERM");
1207 expect(stops).toEqual(scenario.stops);
1208 }).pipe(Effect.scoped, Effect.provide(layer));
1209});
1210​
1211const AGENT_SERVER_SCRIPT = `
1212const server = require("node:http").createServer((_, response) => {
1213 response.writeHead(200, { "content-type": "text/html" });
1214 response.end("<html></html>");
1215});
1216server.listen(0, "127.0.0.1", () => {
1217 process.stdout.write(process.pid + " " + server.address().port + "\\n");
1218});
1220​
1221const AGENT_COMMAND_ENV = "T3CODE_TEST_AGENT_COMMAND";
1222​
1223/**
1224 * A real HTML server with an agent's environment, started the way an agent's tool shell starts a
1225 * job: under a detached shell with job control, in a group of its own. Release kills only the pids
1226 * it started.
1227 */
1228const agentServer = () =>
1229 Effect.acquireRelease(
1230 Effect.callback<{
1231 readonly child: NodeChildProcess.ChildProcess;
1232 readonly pid: number;
1233 readonly port: number;
1234 readonly exited: Promise<void>;
1235 }>((resume) => {
1236 const env = { ...process.env, [PortScanner.AGENT_THREAD_ENV]: "thread-live" };
1237 // dash ignores `set -m` without a terminal; bash, like agent tool shells, honors it.
1238 const child = NodeChildProcess.spawn(
1239 "bash",
1241 "-c",
1242 `set -m; ${AGENT_COMMAND_ENV}=command-live "$0" -e "$1" & wait`,
1243 process.execPath,
1244 AGENT_SERVER_SCRIPT,
1245 ],
1246 { detached: true, env, stdio: ["ignore", "pipe", "ignore"] },
1247 );
1248 const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));
1249 child.once("error", (error) => resume(Effect.die(error)));
1250 child.stdout?.once("data", (chunk) => {
1251 const [pid, port] = String(chunk).trim().split(" ").map(Number);
1252 resume(Effect.succeed({ child, pid: pid!, port: port!, exited }));
1253 });
1254 }),
1255 ({ child, pid }) =>
1256 Effect.sync(() => {
1257 for (const target of [pid, child.pid]) {
1258 try {
1259 if (target !== undefined) process.kill(target, "SIGKILL");
1260 } catch {}
1262 }),
1263 );
1264​
1265const isRunning = (pid: number): boolean => {
1266 try {
1267 process.kill(pid, 0);
1268 return true;
1269 } catch {
1270 return false;
1273​
1274effectIt.live.skipIf(HostProcess.Platform.defaultValue() === "win32")(
1275 "stops an agent's server through its job's group, and only a listed server",
1276 () =>
1277 Effect.gen(function* () {
1278 const scanner = yield* PortScanner.PortDiscovery;
1279 yield* Effect.acquireRelease(Effect.sync(scanner.trackAgent), (release) =>
1280 Effect.sync(release),
1281 );
1282 const job = yield* agentServer();
1283 const stops: Array<readonly [string, boolean]> = [];
1284 yield* scanner.watchAgentCommandStops({
1285 variable: AGENT_COMMAND_ENV,
1286 onStop: (command) => Effect.sync(() => stops.push([command, isRunning(job.pid)])),
1287 onStopAbandoned: () => Effect.die("the signal reached the job"),
1288 });
1289​
1290 expect(yield* scanner.scan()).toEqual(
1291 expect.arrayContaining([
1292 expect.objectContaining({
1293 pid: job.pid,
1294 port: job.port,
1295 agent: { threadId: "thread-live" },
1296 }),
1297 ]),
1298 );
1299​
1300 const unlisted = yield* Effect.flip(scanner.stopServer({ pid: process.pid, port: job.port }));
1301 expect(unlisted.reason).toBe("not-found");
1302 expect(stops).toEqual([]);
1303​
1304 yield* scanner.stopServer({ pid: job.pid, port: job.port });
1305 expect(stops).toEqual([["command-live", true]]);
1306 // The shell waits on its job, so it exits once the job has.
1307 yield* Effect.promise(() => job.exited);
1308 expect(isRunning(job.pid)).toBe(false);
1309 }).pipe(
1310 Effect.scoped,
1311 Effect.provide(
1312 layerScanner.pipe(
1313 Layer.provide(ProcessRunner.layer),
1314 Layer.provide(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer)),
1315 ),
1316 ),
1317 ),