The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 13:00 UTC
perf(server): replace Windows PowerShell port polling with netstat (#18524)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Max Weinbach committed
Oct 15, 2026 at 13:39 UTC
cde9caecbd731a295e998460f42ea1f06be0b6ac
2 files changed
+291
-28
apps/server/src/preview/PortScanner.test.ts
+134
@@ -8,6 +8,7 @@ import {
8
} from "@t3tools/contracts";
9
import * as HostProcess from "@t3tools/shared/HostProcess";
10
import * as Cause from "effect/Cause";
11
+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12
import * as Clock from "effect/Clock";
13
import * as Duration from "effect/Duration";
14
import * as Effect from "effect/Effect";
@@ -789,3 +790,136 @@ effectIt.effect("does not swallow process probe interruption", () =>
790
}
791
}),
792
);
793
+
794
+effectIt.effect(
795
+ "parses Windows netstat listeners, names them via tasklist with retry, and skips spawns when idle",
796
+ () => {
797
+ const spawnedArgs: Array<ReadonlyArray<string>> = [];
798
+ let tasklistCalls = 0;
799
+ const fetchFn = (() =>
800
+ Promise.resolve(
801
+ new Response("hello", { headers: { "content-type": "text/html" } }),
802
+ )) as typeof globalThis.fetch;
803
+ const layer = PortScanner.layer.pipe(
804
+ Layer.provide(
805
+ Layer.mergeAll(
806
+ layerNoProc,
807
+ Layer.succeed(ProcessRunner.ProcessRunner, {
808
+ run: (input) => {
809
+ spawnedArgs.push(input.args);
810
+ const isIpv6 = input.args.includes("tcpv6");
811
+ const isTasklist = input.command === "tasklist.exe";
812
+ // The first lookup fails, so it must not be cached as "no name".
813
+ const failTasklist = isTasklist && tasklistCalls++ === 0;
814
+ return Effect.succeed({
815
+ stdout: isTasklist
816
+ ? '"node.exe","1234","Console","1","93,164 K"\r\n'
817
+ : isIpv6
818
+ ? " TCP [::1]:43123 [::]:0 ABHÖREN 1234\r\n TCP [::1]:43123 [::1]:52000 HERGESTELLT 1234\r\n"
819
+ : " TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 1234\r\n TCP 127.0.0.1:5173 127.0.0.1:60123 ESTABLISHED 9999\r\n",
820
+ stderr: "",
821
+ code: failTasklist ? ChildProcessSpawner.ExitCode(1) : null,
822
+ timedOut: false,
823
+ stdoutTruncated: false,
824
+ stderrTruncated: false,
825
+ stdoutInvalidUtf8: false,
826
+ stderrInvalidUtf8: false,
827
+ });
828
+ },
829
+ }),
830
+ Layer.succeed(HostProcess.Platform, "win32"),
831
+ FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))),
832
+ ),
833
+ ),
834
+ );
835
+
836
+ return Effect.gen(function* () {
837
+ const scanner = yield* PortScanner.PortDiscovery;
838
+ expect(yield* scanner.scan()).toEqual([]);
839
+ expect(spawnedArgs).toHaveLength(0);
840
+
841
+ yield* scanner.registerTerminalProcesses({
842
+ threadId: "scanner-thread",
843
+ terminalId: "scanner-terminal",
844
+ processIds: [1234],
845
+ });
846
+ const summarize = (
847
+ servers: ReadonlyArray<{
848
+ readonly port: number;
849
+ readonly pid: number | null;
850
+ readonly processName: string | null;
851
+ }>,
852
+ ) =>
853
+ servers.map((entry) => ({
854
+ port: entry.port,
855
+ pid: entry.pid,
856
+ processName: entry.processName,
857
+ }));
858
+ expect(summarize(yield* scanner.scan())).toEqual([
859
+ { port: 5173, pid: 1234, processName: null },
860
+ { port: 43123, pid: 1234, processName: null },
861
+ ]);
862
+ expect(spawnedArgs).toEqual([
863
+ ["-ano", "-p", "tcp"],
864
+ ["-ano", "-p", "tcpv6"],
865
+ ["/FO", "CSV", "/NH", "/FI", "PID eq 1234"],
866
+ ]);
867
+
868
+ // The failed lookup retries; the result is then cached, so later polls spawn only netstat.
869
+ expect(summarize(yield* scanner.scan())).toEqual([
870
+ { port: 5173, pid: 1234, processName: "node" },
871
+ { port: 43123, pid: 1234, processName: "node" },
872
+ ]);
873
+ yield* scanner.scan();
874
+ expect(tasklistCalls).toBe(2);
875
+
876
+ // Cached names expire, since Windows may hand the PID to another process.
877
+ yield* TestClock.adjust(Duration.seconds(61));
878
+ yield* scanner.scan();
879
+ expect(tasklistCalls).toBe(3);
880
+ }).pipe(Effect.provide(layer));
881
+ },
882
+);
883
+
884
+effectIt.effect("ignores a partial Windows netstat snapshot when one query exits nonzero", () => {
885
+ const fetchFn = (() =>
886
+ Promise.resolve(
887
+ new Response("hello", { headers: { "content-type": "text/html" } }),
888
+ )) as typeof globalThis.fetch;
889
+ const layer = PortScanner.layer.pipe(
890
+ Layer.provide(
891
+ Layer.mergeAll(
892
+ layerNoProc,
893
+ Layer.succeed(ProcessRunner.ProcessRunner, {
894
+ run: (input) => {
895
+ const isIpv6 = input.args.includes("tcpv6");
896
+ return Effect.succeed({
897
+ stdout: isIpv6
898
+ ? ""
899
+ : " TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 1234\r\n",
900
+ stderr: "",
901
+ code: isIpv6 ? ChildProcessSpawner.ExitCode(1) : null,
902
+ timedOut: false,
903
+ stdoutTruncated: false,
904
+ stderrTruncated: false,
905
+ stdoutInvalidUtf8: false,
906
+ stderrInvalidUtf8: false,
907
+ });
908
+ },
909
+ }),
910
+ Layer.succeed(HostProcess.Platform, "win32"),
911
+ FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))),
912
+ ),
913
+ ),
914
+ );
915
+
916
+ return Effect.gen(function* () {
917
+ const scanner = yield* PortScanner.PortDiscovery;
918
+ yield* scanner.registerTerminalProcesses({
919
+ threadId: "scanner-thread",
920
+ terminalId: "scanner-terminal",
921
+ processIds: [1234],
922
+ });
923
+ expect(yield* scanner.scan()).toEqual([]);
924
+ }).pipe(Effect.provide(layer));
925
+});
apps/server/src/preview/PortScanner.ts
+157
-28
@@ -77,8 +77,13 @@ const PROC_FD_WALK_LIMIT = 50_000;
77
/** Scans that retry the fd walk for a listening socket whose owner was not found. */
78
const SOCKET_OWNER_ATTEMPTS = 3;
79
const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
80
+/** `netstat -ano` lists every connection, not just listeners; ~80 bytes per row, sized for ~200k rows. */
81
+const WINDOWS_NETSTAT_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
82
const WEB_PROBE_TIMEOUT = Duration.seconds(1);
83
const 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. */
85
+const WINDOWS_PROCESS_NAME_TTL_MS = Duration.toMillis(Duration.seconds(60));
86
+const WINDOWS_PROCESS_NAME_CONCURRENCY = 4;
87
const WEB_PROBE_CONCURRENCY = 16;
88
const NAVIGATION_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
89
@@ -249,19 +254,78 @@ const parsePortFromLsofName = (name: string): number | null => {
254
return port;
255
};
256
257
+const 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. */
308
+const 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. */
312
+const 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
+
320
const 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)) {
258
- const [hostRaw, portRaw, pidRaw, processNameRaw] = line.trim().split("|", 4);
259
- const host = hostRaw?.trim() ?? "";
260
- if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") continue;
261
- const port = Number(portRaw);
262
- const pid = Number(pidRaw);
263
- if (!Number.isInteger(port) || port <= 0 || port >= 65536) continue;
264
- const normalizedPid = Number.isInteger(pid) && pid > 0 ? pid : null;
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);
@@ -273,7 +337,7 @@ const parseWindowsListenerOutput = (
337
host: "localhost",
338
port,
339
url: `http://localhost:${port}`,
276
- processName: processNameRaw?.trim() || null,
340
+ processName,
341
pid: normalizedPid,
342
terminal,
343
});
@@ -358,6 +422,10 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
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 }>
@@ -604,6 +672,57 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
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", {
@@ -623,28 +742,38 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
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");
627
- const command =
628
- 'Get-NetTCPConnection -State Listen -ErrorAction Stop | ForEach-Object { $processName = (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName; Write-Output "$($_.LocalAddress)|$($_.LocalPort)|$($_.OwningProcess)|$processName" }';
629
- const listeners = yield* processRunner
630
- .run({
631
- command: "powershell.exe",
632
- args: ["-NoProfile", "-NonInteractive", "-Command", command],
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),
634
- maxOutputBytes: 1024 * 1024,
635
- })
636
- .pipe(
637
- Effect.map((result) => parseWindowsListenerOutput(result.stdout, terminalByProcessId)),
638
- Effect.catchTags({
639
- ProcessSpawnError: recoverWindowsProbeFailure,
640
- ProcessStdinError: recoverWindowsProbeFailure,
641
- ProcessOutputLimitError: recoverWindowsProbeFailure,
642
- ProcessReadError: recoverWindowsProbeFailure,
643
- ProcessTimeoutError: recoverWindowsProbeFailure,
644
- }),
645
- );
646
- if (listeners !== null) return yield* probeWebServers(listeners, configuredUrls);
647
- return yield* probeWebServers([], configuredUrls);
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)) {