@devries-cameron20 / t3code-1 / commits / bf8e132439
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): preview discovery stops sending HTTP and TLS to agent-started ports (#27893)

Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 30, 2026 at 23:22 UTC bf8e1324391a570fbca298cfd0c97d39381666a3
6 files changed +209 -136
apps/server/src/preview/PortScanner.test.ts
+153 -57
@@ -62,6 +62,17 @@ const layerProbeFailure = (
62
63 const LSOF_TEST_PORT = 43_123;
64
65 +const processOutput = (stdout: string): ProcessRunner.ProcessRunOutput => ({
66 + stdout,
67 + stderr: "",
68 + code: ChildProcessSpawner.ExitCode(0),
69 + timedOut: false,
70 + stdoutTruncated: false,
71 + stderrTruncated: false,
72 + stdoutInvalidUtf8: false,
73 + stderrInvalidUtf8: false,
74 +});
75 +
76 const ownedScanner = (processIds: ReadonlyArray<number> = [1234]) =>
77 Effect.tap(PortScanner.PortDiscovery, (scanner) =>
78 scanner.registerTerminalProcesses({
@@ -174,10 +185,11 @@ effectIt.effect("preserves explicit loopback hosts and bounds wildcard rewrites"
185 effectIt.effect("projects configured paths independently for simultaneous subscribers", () => {
186 const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
187 const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
188 + let ready = true;
189 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
190 const url = String(input);
191 return Promise.resolve(
180 - url === docsUrl || url === adminUrl
192 + ready && (url === docsUrl || url === adminUrl)
193 ? new Response("app", { headers: { "content-type": "text/html" } })
194 : new Response("not found", { status: 404 }),
195 );
@@ -185,7 +197,7 @@ effectIt.effect("projects configured paths independently for simultaneous subscr
197 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
198
199 return Effect.gen(function* () {
188 - const scanner = yield* PortScanner.PortDiscovery;
200 + const scanner = yield* ownedScanner();
201 const docsSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
202 const adminSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
203 yield* scanner.subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, (servers) =>
@@ -198,6 +210,11 @@ effectIt.effect("projects configured paths independently for simultaneous subscr
210
211 expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl);
212 expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl);
213 +
214 + ready = false;
215 + yield* TestClock.adjust(Duration.seconds(15));
216 + expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl);
217 + expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl);
218 }).pipe(Effect.scoped, Effect.provide(layer));
219 });
220
@@ -289,28 +306,45 @@ effectIt.effect("uses the current configured fragment when readiness comes from
306 }).pipe(Effect.provide(layer));
307 });
308
292 -effectIt.effect("falls back to HTTPS and does not follow redirects while probing", () => {
293 - const redirects: Array<string | undefined> = [];
294 - const fetchFn = (async (
295 - input: Parameters<typeof globalThis.fetch>[0],
296 - init?: Parameters<typeof globalThis.fetch>[1],
297 - ) => {
298 - redirects.push(init?.redirect);
299 - if (String(input).startsWith("http:")) throw new TypeError("TLS listener");
300 - return new Response(null, { status: 302, headers: { location: "https://example.com" } });
301 - }) as typeof globalThis.fetch;
302 - const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
309 +effectIt.effect(
310 + "probes only a configured HTTPS URL, keeps it for an owned listener when the check fails, and does not follow redirects",
311 + () => {
312 + const configuredUrl = `https://localhost:${LSOF_TEST_PORT}/app`;
313 + const requests: Array<readonly [string, string | undefined]> = [];
314 + let respond = async () =>
315 + new Response(null, { status: 302, headers: { location: "https://example.com" } });
316 + const fetchFn = (async (
317 + input: Parameters<typeof globalThis.fetch>[0],
318 + init?: Parameters<typeof globalThis.fetch>[1],
319 + ) => {
320 + requests.push([String(input), init?.redirect]);
321 + return respond();
322 + }) as typeof globalThis.fetch;
323 + const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
324
304 - return Effect.gen(function* () {
305 - const scanner = yield* ownedScanner();
306 - const servers = yield* scanner.scan();
307 - expect(servers).toHaveLength(1);
308 - expect(servers[0]?.url).toBe(`https://localhost:${LSOF_TEST_PORT}`);
309 - expect(redirects).toEqual(["manual", "manual"]);
310 - }).pipe(Effect.provide(layer));
311 -});
325 + return Effect.gen(function* () {
326 + const scanner = yield* ownedScanner();
327 + expect(yield* scanner.scan([configuredUrl])).toMatchObject([
328 + { pid: 1234, url: configuredUrl },
329 + ]);
330 +
331 + respond = async () => new Response("unavailable", { status: 503 });
332 + yield* TestClock.adjust(Duration.seconds(15));
333 + expect(yield* scanner.scan([configuredUrl])).toMatchObject([
334 + { pid: 1234, url: configuredUrl },
335 + ]);
336
313 -effectIt.effect("probes a port only while T3 terminals own every listener on it", () => {
337 + respond = () => Promise.reject(new TypeError("fetch failed"));
338 + yield* TestClock.adjust(Duration.seconds(15));
339 + expect(yield* scanner.scan([configuredUrl])).toMatchObject([
340 + { pid: 1234, url: configuredUrl },
341 + ]);
342 + expect(requests).toEqual(Array.from({ length: 3 }, () => [configuredUrl, "manual"]));
343 + }).pipe(Effect.provide(layer));
344 + },
345 +);
346 +
347 +effectIt.effect("discovers owned listeners without sending HTTP or TLS probes", () => {
348 const owned = `p1234\ncnode\nn[::1]:${LSOF_TEST_PORT}\n`;
349 const unowned = `p5678\ncrpc\nn127.0.0.1:${LSOF_TEST_PORT}\n`;
350 let stdout = unowned;
@@ -330,19 +364,19 @@ effectIt.effect("probes a port only while T3 terminals own every listener on it"
364
365 stdout = owned;
366 expect(yield* scanner.scan()).toHaveLength(1);
333 - expect(requests).toEqual([`http://localhost:${LSOF_TEST_PORT}/`]);
367 + expect(requests).toEqual([]);
368
369 yield* scanner.unregisterTerminal({
370 threadId: "scanner-thread",
371 terminalId: "scanner-terminal",
372 });
373 expect(yield* scanner.scan()).toHaveLength(0);
340 - expect(requests).toHaveLength(1);
374 + expect(requests).toEqual([]);
375 }).pipe(Effect.provide(layer));
376 });
377
378 effectIt.effect(
345 - "excludes HTTP errors, non-navigation responses, and successful non-documents",
379 + "excludes configured URLs answering with HTTP errors, non-navigation responses, or non-documents",
380 () => {
381 let pid = 1;
382 let makeResponse = () =>
@@ -350,33 +384,35 @@ effectIt.effect(
384 const fetchFn = ((_input: Parameters<typeof globalThis.fetch>[0]) =>
385 Promise.resolve(makeResponse())) as typeof globalThis.fetch;
386 const layer = layerLsofScanner({ pid: () => pid, fetch: fetchFn });
387 + const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/`;
388
389 return Effect.gen(function* () {
355 - const scanner = yield* ownedScanner([1, 2, 3, 4, 5, 6, 7]);
356 - expect(yield* scanner.scan()).toHaveLength(0);
390 + const scanner = yield* PortScanner.PortDiscovery;
391 + const scan = () => scanner.scan([configuredUrl]);
392 + expect(yield* scan()).toHaveLength(0);
393
394 pid += 1;
395 makeResponse = () =>
396 new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
361 - expect(yield* scanner.scan()).toHaveLength(0);
397 + expect(yield* scan()).toHaveLength(0);
398
399 pid += 1;
400 makeResponse = () =>
401 new Response("ready", { status: 200, headers: { "content-type": "text/plain" } });
366 - expect(yield* scanner.scan()).toHaveLength(0);
402 + expect(yield* scan()).toHaveLength(0);
403
404 pid += 1;
405 makeResponse = () => new Response(null, { status: 304, headers: { location: "/cached" } });
370 - expect(yield* scanner.scan()).toHaveLength(0);
406 + expect(yield* scan()).toHaveLength(0);
407
408 pid += 1;
409 makeResponse = () =>
410 new Response(null, { status: 204, headers: { "content-type": "text/html" } });
375 - expect(yield* scanner.scan()).toHaveLength(0);
411 + expect(yield* scan()).toHaveLength(0);
412
413 pid += 1;
414 makeResponse = () => new Response(null, { status: 302 });
379 - expect(yield* scanner.scan()).toHaveLength(0);
415 + expect(yield* scan()).toHaveLength(0);
416
417 pid += 1;
418 makeResponse = () =>
@@ -384,7 +420,7 @@ effectIt.effect(
420 status: 200,
421 headers: { "content-type": "application/xhtml+xml; charset=utf-8" },
422 });
387 - expect(yield* scanner.scan()).toHaveLength(1);
423 + expect(yield* scan()).toHaveLength(1);
424 }).pipe(Effect.provide(layer));
425 },
426 );
@@ -433,10 +469,11 @@ effectIt.effect(
469 return target === undefined ? missing.readLink(path) : Effect.succeed(target);
470 },
471 });
436 - const fetchFn = (() =>
437 - Promise.resolve(
438 - new Response("hello", { headers: { "content-type": "text/html" } }),
439 - )) as typeof globalThis.fetch;
472 + const requests: string[] = [];
473 + const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
474 + requests.push(String(input));
475 + return Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }));
476 + }) as typeof globalThis.fetch;
477 const layer = layerProbeFailure(
478 (input) => {
479 lsofSpawns += 1;
@@ -449,37 +486,45 @@ effectIt.effect(
486 return Effect.gen(function* () {
487 const scanner = yield* ownedScanner([4242]);
488 const first = yield* scanner.scan();
452 - expect(first.map(({ port, pid, processName }) => ({ port, pid, processName }))).toEqual([
453 - { port: 8765, pid: 4242, processName: "python3" },
454 - ]);
489 + expect(
490 + first.map(({ port, pid, processName, url }) => ({ port, pid, processName, url })),
491 + ).toEqual([{ port: 8765, pid: 4242, processName: "python3", url: "http://localhost:8765" }]);
492 yield* scanner.scan();
493 expect(lsofSpawns).toBe(1);
494 expect(fdWalks).toEqual(["77", "4242", "77", "4242"]);
495 yield* scanner.scan();
496 yield* scanner.scan();
497 expect(fdWalks).toEqual(["77", "4242", "77", "4242", "77", "4242"]);
498 + expect(requests).toEqual([]);
499 }).pipe(Effect.provide(layer));
500 },
501 );
502
503 effectIt.effect("ignores a partial Windows netstat snapshot when one query exits nonzero", () => {
466 - const fetchFn = (() =>
467 - Promise.resolve(
468 - new Response("hello", { headers: { "content-type": "text/html" } }),
469 - )) as typeof globalThis.fetch;
504 + let ipv6Fails = true;
505 + const requests: string[] = [];
506 + const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
507 + requests.push(String(input));
508 + return Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }));
509 + }) as typeof globalThis.fetch;
510 const layer = PortScanner.layer.pipe(
511 Layer.provide(
512 Layer.mergeAll(
513 layerNoProc,
514 Layer.succeed(ProcessRunner.ProcessRunner, {
515 run: (input) => {
516 + if (input.command === "tasklist.exe") {
517 + return Effect.succeed(
518 + processOutput('"node.exe","1234","Console","1","50,000 K"\r\n'),
519 + );
520 + }
521 const isIpv6 = input.args.includes("tcpv6");
522 return Effect.succeed({
523 stdout: isIpv6
524 ? ""
525 : " TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 1234\r\n",
526 stderr: "",
482 - code: isIpv6 ? ChildProcessSpawner.ExitCode(1) : null,
527 + code: isIpv6 && ipv6Fails ? ChildProcessSpawner.ExitCode(1) : null,
528 timedOut: false,
529 stdoutTruncated: false,
530 stderrTruncated: false,
@@ -502,20 +547,14 @@ effectIt.effect("ignores a partial Windows netstat snapshot when one query exits
547 processIds: [1234],
548 });
549 expect(yield* scanner.scan()).toEqual([]);
550 + ipv6Fails = false;
551 + expect(yield* scanner.scan()).toMatchObject([
552 + { port: 5173, pid: 1234, processName: "node", url: "http://localhost:5173" },
553 + ]);
554 + expect(requests).toEqual([]);
555 }).pipe(Effect.provide(layer));
556 });
557
508 -const processOutput = (stdout: string): ProcessRunner.ProcessRunOutput => ({
509 - stdout,
510 - stderr: "",
511 - code: ChildProcessSpawner.ExitCode(0),
512 - timedOut: false,
513 - stdoutTruncated: false,
514 - stderrTruncated: false,
515 - stdoutInvalidUtf8: false,
516 - stderrInvalidUtf8: false,
517 -});
518 -
558 effectIt.effect("rechecks the socket owner before stopping a Linux server without lsof", () => {
559 let holder = "4242";
560 const missing = FileSystem.makeNoop({});
@@ -569,6 +608,63 @@ effectIt.effect("rechecks the socket owner before stopping a Linux server withou
608 }).pipe(Effect.provide(layer));
609 });
610
611 +effectIt.effect.each(["linux", "darwin", "win32"] as const)(
612 + "reads no listeners on %s while T3CODE_PORT_DISCOVERY=0, and still probes configured URLs",
613 + (platform) => {
614 + const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
615 + const commands: string[] = [];
616 + const fileReads: string[] = [];
617 + const requests: string[] = [];
618 + const missing = FileSystem.makeNoop({});
619 + const layer = PortScanner.layer.pipe(
620 + Layer.provide(
621 + Layer.mergeAll(
622 + FileSystem.layerNoop({
623 + readFileString: (path) => {
624 + fileReads.push(path);
625 + return missing.readFileString(path);
626 + },
627 + readDirectory: (path) => {
628 + fileReads.push(path);
629 + return missing.readDirectory(path);
630 + },
631 + }),
632 + Layer.succeed(ProcessRunner.ProcessRunner, {
633 + run: (input) => {
634 + commands.push(input.command);
635 + return Effect.succeed(processOutput(`p1234\ncnode\nn*:${LSOF_TEST_PORT}\n`));
636 + },
637 + }),
638 + Layer.succeed(HostProcess.Platform, platform),
639 + Layer.succeed(HostProcess.Environment, { T3CODE_PORT_DISCOVERY: "0" }),
640 + FetchHttpClient.layer.pipe(
641 + Layer.provide(
642 + Layer.succeed(FetchHttpClient.Fetch, (input) => {
643 + requests.push(String(input));
644 + return Promise.resolve(
645 + new Response("docs", { headers: { "content-type": "text/html" } }),
646 + );
647 + }),
648 + ),
649 + ),
650 + ),
651 + ),
652 + );
653 +
654 + return Effect.gen(function* () {
655 + const scanner = yield* ownedScanner();
656 + scanner.trackAgent();
657 + expect(yield* scanner.scan()).toEqual([]);
658 + expect(yield* scanner.scan([configuredUrl])).toMatchObject([
659 + { port: LSOF_TEST_PORT, pid: null, terminal: null, url: configuredUrl },
660 + ]);
661 + expect(requests).toEqual([configuredUrl]);
662 + expect(commands).toEqual([]);
663 + expect(fileReads).toEqual([]);
664 + }).pipe(Effect.provide(layer));
665 + },
666 +);
667 +
668 effectIt.effect.each(["linux", "darwin"] as const)(
669 "attributes listeners to the agent thread in their environment on %s, after the agent exits",
670 (platform) => {
@@ -672,7 +768,7 @@ effectIt.effect.each(["linux", "darwin"] as const)(
768 expect(yield* scanner.scan()).toMatchObject([
769 { port: agentPort, pid: 4242, terminal: null, agent: { threadId: "thread-agent" } },
770 ]);
675 - expect(requests).toEqual([`http://localhost:${agentPort}/`]);
771 + expect(requests).toEqual([]);
772
773 expect(yield* scanner.scan()).toHaveLength(1);
774 expect(environmentReads).toBe(2);
apps/server/src/preview/PortScanner.ts
+37 -74
@@ -68,6 +68,9 @@ export class PortDiscovery extends Context.Service<
68 */
69 export const AGENT_THREAD_ENV = "T3CODE_THREAD_ID";
70
71 +/** `0` turns off listener discovery; configured preview URLs are still probed. */
72 +const PORT_DISCOVERY_ENV = "T3CODE_PORT_DISCOVERY";
73 +
74 const POLL_INTERVAL = Duration.seconds(3);
75 const LSOF_TIMEOUT_MS = 5_000;
76 const PROC_FD_WALK_LIMIT = 50_000;
@@ -132,8 +135,8 @@ interface WebProbeCacheEntry {
135
136 interface WebProbeGroup {
137 readonly server: DiscoveredLocalServer;
135 - readonly urls: ReadonlyArray<string>;
136 - readonly configuredKey: string | null;
138 + readonly url: string;
139 + readonly configuredKey: string;
140 }
141
142 interface WebProbeSnapshot {
@@ -189,17 +192,22 @@ const projectWebProbeSnapshot = (
192 configuredUrls: ReadonlyArray<string>,
193 ): ReadonlyArray<DiscoveredLocalServer> => {
194 const visibleByServer = new Map<string, DiscoveredLocalServer>();
195 + const firstConfiguredByServer = new Map<string, string>();
196 for (const raw of normalizeConfiguredUrls(configuredUrls)) {
197 const url = new URL(raw);
198 const port = urlPort(url);
199 const serverKey = localServerKey(url.hostname, port);
200 + if (!firstConfiguredByServer.has(serverKey)) firstConfiguredByServer.set(serverKey, raw);
201 if (visibleByServer.has(serverKey)) continue;
202 const configured = snapshot.configured.get(webProbeCacheKey(raw));
203 if (configured) visibleByServer.set(serverKey, { ...configured, url: raw });
204 }
205 + // An owned listener whose configured check failed still opens at this caller's configured URL.
206 for (const server of snapshot.discovered) {
207 const key = localServerKey(server.host, server.port);
202 - if (!visibleByServer.has(key)) visibleByServer.set(key, server);
208 + if (visibleByServer.has(key)) continue;
209 + const configuredUrl = firstConfiguredByServer.get(key);
210 + visibleByServer.set(key, configuredUrl ? { ...server, url: configuredUrl } : server);
211 }
212 return [...visibleByServer.values()].toSorted((left, right) => left.port - right.port);
213 };
@@ -498,6 +506,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
506 const processRunner = yield* ProcessRunner.ProcessRunner;
507 const fileSystem = yield* FileSystem.FileSystem;
508 const hostPlatform = yield* HostProcess.Platform;
509 + const listenerDiscovery = (yield* HostProcess.Environment)[PORT_DISCOVERY_ENV] !== "0";
510 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
511 const stateRef = yield* Ref.make<ScannerState>({
512 listeners: new Map(),
@@ -715,24 +724,17 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
724 pid: null,
725 terminal: null,
726 },
718 - urls: [raw],
727 + url: raw,
728 configuredKey: resourceKey,
729 });
730 }
731
723 - for (const server of servers) {
724 - // Never probe an unidentified listener with HTTP or TLS; binary RPC servers can crash on it.
725 - if (!isOwned(server)) continue;
726 - groups.push({
727 - server,
728 - urls: [`http://${server.host}:${server.port}`, `https://${server.host}:${server.port}`],
729 - configuredKey: null,
730 - });
731 - }
732 -
732 return groups;
733 };
734
735 + // Only configured URLs are requested. Owned listeners are listed as plain HTTP without a
736 + // request: owning a process says nothing about its protocol, and HTTP or TLS bytes break
737 + // binary ones such as Unity's test runner or Steam's IPC.
738 const probeWebServers = Effect.fn("PortDiscovery.probeWebServers")(function* (
739 servers: ReadonlyArray<DiscoveredLocalServer>,
740 configuredUrls: ReadonlyArray<string>,
@@ -740,77 +742,37 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
742 const nowMillis = yield* Clock.currentTimeMillis;
743 const cached = yield* Ref.get(webProbeCacheRef);
744 const groups = makeWebProbeGroups(servers, configuredUrls);
743 - const batchProbes = new Map<
744 - string,
745 - Effect.Effect<{ readonly probe: WebProbeCacheEntry; readonly fresh: boolean }>
746 - >();
747 - const batchProbeSemaphore = yield* Semaphore.make(1);
748 - const getProbe = (url: string, pid: number | null) => {
749 - const key = webProbeCacheKey(url);
750 - const identity = `${key}\u0000${pid ?? ""}`;
751 - return batchProbeSemaphore
752 - .withPermits(1)(
753 - Effect.gen(function* () {
754 - const existing = batchProbes.get(identity);
755 - if (existing) return [existing] as const;
756 - const cachedProbe = cached.get(key);
757 - const cachedIsCurrent =
758 - cachedProbe?.pid === pid && cachedProbe.expiresAtMillis > nowMillis;
759 - const memoized = yield* Effect.cached(
760 - cachedIsCurrent
761 - ? Effect.succeed({ probe: cachedProbe, fresh: false })
762 - : probeWebUrl(url).pipe(
763 - Effect.map((result) => ({
764 - probe: { pid, isWeb: result !== null, expiresAtMillis: 0 },
765 - fresh: true,
766 - })),
767 - ),
768 - );
769 - batchProbes.set(identity, memoized);
770 - return [memoized] as const;
771 - }),
772 - )
773 - .pipe(Effect.flatMap(([probe]) => probe));
774 - };
745 const probed = yield* Effect.forEach(
746 groups,
777 - (group) =>
778 - Effect.gen(function* () {
779 - const probes: Array<readonly [string, WebProbeCacheEntry, boolean]> = [];
780 - let visibleUrl: string | null = null;
781 - for (const url of group.urls) {
782 - const key = webProbeCacheKey(url);
783 - const { probe, fresh } = yield* getProbe(url, group.server.pid);
784 - probes.push([key, probe, fresh]);
785 - if (probe.isWeb) {
786 - visibleUrl = url;
787 - break;
788 - }
789 - }
790 - return { group, probes, visibleUrl };
791 - }),
747 + (group) => {
748 + const { pid } = group.server;
749 + const cachedProbe = cached.get(group.configuredKey);
750 + return cachedProbe?.pid === pid && cachedProbe.expiresAtMillis > nowMillis
751 + ? Effect.succeed({ group, probe: cachedProbe, fresh: false })
752 + : probeWebUrl(group.url).pipe(
753 + Effect.map((result) => ({
754 + group,
755 + probe: { pid, isWeb: result !== null, expiresAtMillis: 0 },
756 + fresh: true,
757 + })),
758 + );
759 + },
760 { concurrency: WEB_PROBE_CONCURRENCY },
761 );
762 const completedAtMillis = yield* Clock.currentTimeMillis;
763 const nextCache = new Map(
764 [...cached].filter(([, probe]) => probe.expiresAtMillis > completedAtMillis),
765 );
798 - const discovered: DiscoveredLocalServer[] = [];
766 const configured = new Map<string, DiscoveredLocalServer>();
800 - for (const { group, probes, visibleUrl } of probed) {
801 - for (const [key, probe, fresh] of probes) {
802 - nextCache.set(
803 - key,
804 - fresh ? { ...probe, expiresAtMillis: completedAtMillis + WEB_PROBE_CACHE_TTL_MS } : probe,
805 - );
806 - }
807 - if (visibleUrl === null) continue;
808 - const server = { ...group.server, url: visibleUrl };
809 - if (group.configuredKey === null) discovered.push(server);
810 - else configured.set(group.configuredKey, server);
767 + for (const { group, probe, fresh } of probed) {
768 + nextCache.set(
769 + group.configuredKey,
770 + fresh ? { ...probe, expiresAtMillis: completedAtMillis + WEB_PROBE_CACHE_TTL_MS } : probe,
771 + );
772 + if (probe.isWeb) configured.set(group.configuredKey, { ...group.server, url: group.url });
773 }
774 yield* Ref.set(webProbeCacheRef, nextCache);
813 - return { discovered, configured } satisfies WebProbeSnapshot;
775 + return { discovered: servers.filter(isOwned), configured } satisfies WebProbeSnapshot;
776 });
777
778 // tasklist costs 200-300ms per PID; query visible servers with bounded concurrency and cache names.
@@ -873,6 +835,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
835 const scanUnlocked = Effect.fn("PortDiscovery.scanUnlocked")(function* (
836 configuredUrls: ReadonlyArray<string>,
837 ) {
838 + if (!listenerDiscovery) return yield* probeWebServers([], configuredUrls);
839 const state = yield* Ref.get(stateRef);
840 const terminalOwners = new Map<number, ServerOwner>();
841 for (const registration of state.terminalProcesses.values()) {
apps/web/src/components/chat/ThreadServersPanel.tsx
+1 -1
@@ -30,7 +30,7 @@ import { THREAD_DETAILS_PANEL_ICON_CLASS } from "./threadDetailsPanelStyles";
30
31 const serverKey = (server: DiscoveredLocalServer) => `${server.pid}:${server.port}`;
32
33 -/** Web servers the thread's terminals and agent started. Hidden while none run. */
33 +/** Local servers the thread's terminals and agent started. Hidden while none run. */
34 export function ThreadServersPanel(props: {
35 readonly environmentId: EnvironmentId;
36 readonly threadId: ThreadId;
apps/web/src/components/preview/PreviewEmptyState.tsx
+1 -1
@@ -40,7 +40,7 @@ export function PreviewEmptyState({
40 </EmptyMedia>
41 <EmptyTitle>No preview yet</EmptyTitle>
42 <EmptyDescription>
43 - Type a URL above, or run a dev script. Browser-ready localhost servers will show up here
43 + Type a URL above, or run a dev script. Local servers this thread starts will show up here
44 automatically.
45 </EmptyDescription>
46 </Empty>
docs/user/remote-access.md
+13
@@ -243,6 +243,19 @@ On a phone, tap the floating preview's corner dot to show its controls, then
243 **Pop into separate window** to keep watching in picture-in-picture over other
244 apps.
245
246 +### Local servers
247 +
248 +The browser lists ports held by processes your terminals and agents started.
249 +T3 Code reads which process holds each port and never connects to it, so a
250 +listed port opens as `http://localhost:<port>` and might not be a web page. For
251 +an HTTPS server or a specific path, set the **Preview URL** on the project
252 +script that starts it; T3 Code checks that address and opens it as written.
253 +
254 +To stop listing ports, set `T3CODE_PORT_DISCOVERY=0` in the environment that
255 +starts the T3 Code server, such as
256 +[`service.env`](./background-service.md#configure-the-service-environment) for
257 +the background service, and restart it. Script preview URLs still appear.
258 +
259 ### Browser host setup
260
261 macOS, Windows, and Linux desktops run the browser as is. Some Linux hosts need
docs/user/thread-sidebar.md
+4 -3
@@ -270,9 +270,10 @@ Expand a tool call in the conversation to see its full command and output.
270 Summaries shorten shell wrappers and can still describe the latest call after it
271 finishes; the call's own result shows its status.
272
273 -On web and desktop, the thread details card lists the web servers that the
274 -thread's terminals or its Claude agent started, with their ports. A server the
275 -agent started stays listed after the agent's turn ends.
273 +On web and desktop, the thread details card lists the local servers that the
274 +thread's terminals or its Claude agent started, with their ports. Not every one
275 +serves a web page. A server the agent started stays listed after the agent's
276 +turn ends.
277 Select a server to open it in the browser panel. **Stop** ends the server's job
278 and keeps the agent, the terminal, and T3 Code running. Stop needs terminal
279 access to the environment and is not available on Windows.