@devries-cameron20 / t3code Mirror · read-only / commits / a27ec88bfa
Fork 0

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 22, 14:30 UTC

feat(server,web): see and stop the dev servers a thread started (#22542)

Co-authored-by: Guillermo <guillermolopezg00@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 27, 2026 at 15:14 UTC a27ec88bfaa85987b889c95166815f0227fec446
24 files changed +971 -43
apps/server/src/auth/RpcAuthorization.test.ts
+1
@@ -59,6 +59,7 @@ describe("RPC authorization scopes", () => {
59 WS_METHODS.terminalClear,
60 WS_METHODS.terminalRestart,
61 WS_METHODS.terminalClose,
62 + WS_METHODS.previewStopLocalServer,
63 ]) {
64 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalOperateScope);
65 }
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -196,6 +196,7 @@ export const RPC_REQUIRED_SCOPES = {
196 [WS_METHODS.previewClearProfile]: AuthPreviewOperateScope,
197 [WS_METHODS.previewReportProfiles]: AuthPreviewOperateScope,
198 [WS_METHODS.previewReportStatus]: AuthPreviewOperateScope,
199 + [WS_METHODS.previewStopLocalServer]: AuthTerminalOperateScope,
200 [WS_METHODS.subscribePreviewEvents]: AuthOrchestrationReadScope,
201 [WS_METHODS.subscribeDiscoveredLocalServers]: AuthOrchestrationReadScope,
202 [WS_METHODS.deviceConfigure]: AuthSettingsWriteScope,
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -255,6 +255,7 @@ export const make = Effect.gen(function* () {
255 threadPullRequestLinking: true,
256 serverResolvedCommandContext: true,
257 threadStop: true,
258 + ...(hostPlatform === "win32" ? {} : { localServerStop: true }),
259 environmentIcon: true,
260 projectCloneTracking: true,
261 ignoredFileListing: true,
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -204,6 +204,7 @@ const RPC_AGGREGATES = {
204 [WS_METHODS.previewReportStatus]: "preview",
205 [WS_METHODS.subscribePreviewEvents]: "preview",
206 [WS_METHODS.subscribeDiscoveredLocalServers]: "preview",
207 + [WS_METHODS.previewStopLocalServer]: "preview",
208 [WS_METHODS.deviceConfigure]: "device",
209 [WS_METHODS.deviceTestHost]: "device",
210 [WS_METHODS.deviceEasAccount]: "device",
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+2 -1
@@ -74,6 +74,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
74 import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
75 import { SpawnExecutableResolution } from "@t3tools/shared/shell";
76
77 +import * as PortScanner from "../../preview/PortScanner.ts";
78 import { attachmentRelativePath } from "../../attachmentStore.ts";
79 import { WorkflowAgentTranscriptReadObserver } from "../workflowAgentTranscript.ts";
80 import * as ServerConfig from "../../config.ts";
@@ -2325,7 +2326,7 @@ describe("ClaudeAdapterV2 MCP credential channel", () => {
2326 },
2327 });
2328 }).pipe(
2328 - Effect.provide(ClaudeAdapterV2.layerQueryRunner),
2329 + Effect.provide(ClaudeAdapterV2.layerQueryRunner.pipe(Layer.provide(PortScanner.layerTest))),
2330 Effect.provideService(ProviderEventLoggers.ProviderEventLoggers, {
2331 ...ProviderEventLoggers.NoOpProviderEventLoggers,
2332 native,
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+17 -1
@@ -138,6 +138,7 @@ import {
138 type CompiledClaudeModelSelection,
139 } from "../../claudeModelOptions.ts";
140 import * as ServerConfig from "../../config.ts";
141 +import * as PortScanner from "../../preview/PortScanner.ts";
142 import * as ServerSettings from "../../serverSettings.ts";
143 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
144 import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
@@ -917,6 +918,7 @@ export const layerQueryRunner: Layer.Layer<
918 | ChildProcessSpawner.ChildProcessSpawner
919 | Crypto.Crypto
920 | Path.Path
921 + | PortScanner.PortDiscovery
922 | ProviderEventLoggers.ProviderEventLoggers
923 > = Layer.effect(
924 ClaudeAgentSdkQueryRunner,
@@ -928,6 +930,8 @@ export const layerQueryRunner: Layer.Layer<
930 const agentScope = yield* AgentScope;
931 const platform = yield* HostProcess.Platform;
932 const runFork = Effect.runForkWith(yield* Effect.context<never>());
933 + const hostEnvironment = yield* HostProcess.Environment;
934 + const portDiscovery = yield* PortScanner.PortDiscovery;
935
936 return ClaudeAgentSdkQueryRunner.of({
937 allocateSessionId: crypto
@@ -951,7 +955,15 @@ export const layerQueryRunner: Layer.Layer<
955 Stream.toAsyncIterable,
956 );
957 // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments.
954 - const { mcpServers, ...queryOptions } = input.options;
958 + const { mcpServers, ...sdkOptions } = input.options;
959 + // Jobs the agent starts inherit the thread, so port discovery can attribute their servers.
960 + const queryOptions = {
961 + ...sdkOptions,
962 + env: {
963 + ...(sdkOptions.env ?? hostEnvironment),
964 + [PortScanner.AGENT_THREAD_ENV]: input.threadId,
965 + },
966 + };
967 // The SDK can prepend a scope wrapper to native binaries; script entries run through node.
968 const binaryPath = queryOptions.pathToClaudeCodeExecutable;
969 const launch =
@@ -998,6 +1010,10 @@ export const layerQueryRunner: Layer.Layer<
1010 const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => {
1011 const child = spawnProcess(spawnOptions);
1012 spawnedProcess = child;
1013 + // A spawn that fails emits only "error".
1014 + const releaseAgent = portDiscovery.trackAgent();
1015 + child.once("exit", releaseAgent);
1016 + child.on("error", releaseAgent);
1017 processExited = child.exitCode !== null || child.signalCode != null;
1018 processExit = new Promise<void>((resolve) => {
1019 if (processExited) resolve();
apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+53
@@ -24,6 +24,7 @@ import { AgentScope } from "@t3tools/shared/AgentScope";
24 import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
25 import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
26 import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
27 +import * as PortScanner from "../../preview/PortScanner.ts";
28 import {
29 ClaudeAgentSdkQueryRunner,
30 type ClaudeAgentSdkQueryOpenInput,
@@ -66,6 +67,7 @@ const writeClaudeSession = Effect.fnUntraced(function* (configDir: string) {
67 });
68
69 const forkRunnerLayer = layerQueryRunner.pipe(
70 + Layer.provide(PortScanner.layerTest),
71 Layer.provide(Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined })),
72 );
73
@@ -110,6 +112,7 @@ it.effect("forks a session stored under the instance's own CLAUDE_CONFIG_DIR", (
112 ).pipe(Effect.provide(NodeServices.layer)),
113 );
114 const realQueryRunner = layerQueryRunner.pipe(
115 + Layer.provide(PortScanner.layerTest),
116 Layer.provide(
117 Layer.succeed(ProviderEventLoggers, {
118 native: undefined,
@@ -487,4 +490,54 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
490 yield* Effect.promise(() => turnStopped);
491 }),
492 );
493 +
494 + it.effect("marks the CLI's jobs with its thread and counts it as an agent until it exits", () => {
495 + let runningAgents = 0;
496 + let releaseAgent!: () => void;
497 + const agentReleased = new Promise<void>((resolve) => (releaseAgent = resolve));
498 + const runner = layerQueryRunner.pipe(
499 + Layer.provide(
500 + Layer.mock(PortScanner.PortDiscovery)({
501 + trackAgent: () => {
502 + runningAgents += 1;
503 + return () => {
504 + runningAgents -= 1;
505 + releaseAgent();
506 + };
507 + },
508 + }),
509 + ),
510 + Layer.provide(
511 + Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined }),
512 + ),
513 + Layer.provide(NodeServices.layer),
514 + );
515 + return Effect.gen(function* () {
516 + const cli = fakeClaudeCli(
517 + [
518 + 'dir=$(dirname "$0")',
519 + `printf '%s' "$${PortScanner.AGENT_THREAD_ENV}" > "$dir/thread"`,
520 + "cat > /dev/null",
521 + ].join("\n"),
522 + );
523 + const dir = NodePath.dirname(cli);
524 + NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "thread")]);
525 + yield* Effect.addFinalizer(() =>
526 + Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })),
527 + );
528 + const threadRead = new Promise<string>((resolve) => {
529 + let thread = "";
530 + NodeFS.createReadStream(NodePath.join(dir, "thread"), "utf8")
531 + .on("data", (chunk) => (thread += chunk))
532 + .once("end", () => resolve(thread));
533 + });
534 +
535 + const session = yield* openFakeCli(cli);
536 + assert.equal(yield* Effect.promise(() => threadRead), "thread-fake-cli");
537 + assert.equal(runningAgents, 1);
538 + yield* session.close;
539 + yield* Effect.promise(() => agentReleased);
540 + assert.equal(runningAgents, 0);
541 + }).pipe(Effect.provide(runner));
542 + });
543 });
apps/server/src/preview/PortScanner.test.ts
+313 -1
@@ -1,9 +1,14 @@
1 +// @effect-diagnostics nodeBuiltinImport:off -- the stop test drives real server processes.
2 +import * as NodeChildProcess from "node:child_process";
3 +
4 import { it as effectIt } from "@effect/vitest";
5 +import * as NodeServices from "@effect/platform-node/NodeServices";
6 import {
7 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
8 PREVIEW_URL_MAX_LENGTH,
9 type DiscoveredLocalServer,
10 } from "@t3tools/contracts";
11 +import * as ProcessGroup from "@t3tools/provider-core/server/processGroup";
12 import * as HostProcess from "@t3tools/shared/HostProcess";
13 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14 import * as Duration from "effect/Duration";
@@ -14,11 +19,14 @@ import * as Layer from "effect/Layer";
19 import * as PlatformError from "effect/PlatformError";
20 import * as Scope from "effect/Scope";
21 import * as TestClock from "effect/testing/TestClock";
17 -import { expect } from "vite-plus/test";
22 +import { expect, vi } from "vite-plus/test";
23 import { FetchHttpClient } from "effect/http";
24
25 import * as ProcessRunner from "../processRunner.ts";
26 import * as PortScanner from "./PortScanner.ts";
27 +
28 +vi.mock("@t3tools/provider-core/server/processGroup", { spy: true });
29 +
30 const processProbeFailure: ProcessRunner.ProcessRunner["Service"]["run"] = (input) =>
31 Effect.fail(
32 new ProcessRunner.ProcessSpawnError({
@@ -496,3 +504,307 @@ effectIt.effect("ignores a partial Windows netstat snapshot when one query exits
504 expect(yield* scanner.scan()).toEqual([]);
505 }).pipe(Effect.provide(layer));
506 });
507 +
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 +
519 +effectIt.effect("rechecks the socket owner before stopping a Linux server without lsof", () => {
520 + let holder = "4242";
521 + const missing = FileSystem.makeNoop({});
522 + const layer = layerProbeFailure(
523 + (input) =>
524 + input.command === "lsof"
525 + ? processProbeFailure(input)
526 + : Effect.succeed(processOutput("4242 1 4300\n5000 1 5300\n")),
527 + () => Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } })),
528 + FileSystem.layerNoop({
529 + readFileString: (path) => {
530 + if (path === "/proc/net/tcp") {
531 + return Effect.succeed(PROC_NET_TCP.split("\n").slice(0, 2).join("\n"));
532 + }
533 + if (/^\/proc\/(4242|5000)\/comm$/.test(path)) return Effect.succeed("node\n");
534 + if (/^\/proc\/(4242|5000)\/environ$/.test(path)) {
535 + return Effect.succeed(`${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`);
536 + }
537 + return missing.readFileString(path);
538 + },
539 + readDirectory: (path) => {
540 + if (path === "/proc") return Effect.succeed(["4242", "5000"]);
541 + if (/^\/proc\/(4242|5000)\/fd$/.test(path)) {
542 + return Effect.succeed(path === `/proc/${holder}/fd` ? ["3"] : []);
543 + }
544 + return missing.readDirectory(path);
545 + },
546 + readLink: (path) =>
547 + path === `/proc/${holder}/fd/3` ? Effect.succeed("socket:[5001]") : missing.readLink(path),
548 + }),
549 + );
550 +
551 + return Effect.gen(function* () {
552 + const signal = vi.spyOn(ProcessGroup, "signalProcessGroup").mockImplementation(() => {
553 + throw Object.assign(new Error("No such process"), { code: "ESRCH" });
554 + });
555 + yield* Effect.addFinalizer(() => Effect.sync(() => signal.mockRestore()));
556 + const scanner = yield* PortScanner.PortDiscovery;
557 + expect(yield* scanner.scan()).toMatchObject([{ pid: 4242, port: 8765 }]);
558 +
559 + // The socket outlives its original holder. Its old pid now belongs to another agent job.
560 + holder = "5000";
561 + const result = yield* scanner
562 + .stopServer({ pid: 4242, port: 8765 })
563 + .pipe(Effect.match({ onFailure: (error) => error.reason, onSuccess: () => null }));
564 + expect(signal).not.toHaveBeenCalled();
565 + expect(result).toBe("not-found");
566 + expect(yield* scanner.scan()).toMatchObject([{ pid: 5000, port: 8765 }]);
567 + yield* scanner.stopServer({ pid: 5000, port: 8765 });
568 + expect(signal).toHaveBeenCalledExactlyOnceWith(5300, "SIGTERM");
569 + }).pipe(Effect.provide(layer));
570 +});
571 +
572 +effectIt.effect.each(["linux", "darwin"] as const)(
573 + "attributes listeners to the agent thread in their environment on %s, after the agent exits",
574 + (platform) => {
575 + const agentPort = 43_124;
576 + const otherPort = 43_125;
577 + const agentListener = `p4242\ncnode\nn127.0.0.1:${agentPort}\n`;
578 + const otherListener = `p5000\ncpostgres\nn127.0.0.1:${otherPort}\n`;
579 + let lsofStdout = otherListener;
580 + let lsofFails = false;
581 + let environmentFails = false;
582 + let lsofCalls = 0;
583 + let environmentReads = 0;
584 + const requests: string[] = [];
585 + const missing = FileSystem.makeNoop({});
586 + const procEnviron: Record<string, string> = {
587 + "/proc/4242/environ": `PATH=/usr/bin\0${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`,
588 + "/proc/5000/environ": "PATH=/usr/bin\0",
589 + };
590 + const layer = PortScanner.layer.pipe(
591 + Layer.provide(
592 + Layer.mergeAll(
593 + FileSystem.layerNoop({
594 + readFileString: (path) => {
595 + const content = procEnviron[path];
596 + if (content === undefined) return missing.readFileString(path);
597 + environmentReads += 1;
598 + return Effect.succeed(content);
599 + },
600 + }),
601 + Layer.succeed(ProcessRunner.ProcessRunner, {
602 + run: (input) => {
603 + if (input.command === "lsof") {
604 + lsofCalls += 1;
605 + return lsofFails
606 + ? Effect.fail(
607 + new ProcessRunner.ProcessTimeoutError({
608 + command: input.command,
609 + argumentCount: input.args.length,
610 + cwd: input.cwd,
611 + timeoutMs: 5_000,
612 + }),
613 + )
614 + : Effect.succeed(processOutput(lsofStdout));
615 + }
616 + // A direct child of this process, so stop refuses it without signaling anything.
617 + if (input.args[0] === "-A") {
618 + return Effect.succeed(processOutput(`4242 ${process.pid} 4242\n`));
619 + }
620 + if (environmentFails) {
621 + return Effect.fail(
622 + new ProcessRunner.ProcessTimeoutError({
623 + command: input.command,
624 + argumentCount: input.args.length,
625 + timeoutMs: 5_000,
626 + }),
627 + );
628 + }
629 + environmentReads += 1;
630 + return Effect.succeed(
631 + processOutput(
632 + ` 4242 node server.js PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-agent HOME=/Users/dev\n` +
633 + " 5000 postgres -D /data PATH=/usr/bin\n",
634 + ),
635 + );
636 + },
637 + }),
638 + Layer.succeed(HostProcess.Platform, platform),
639 + FetchHttpClient.layer.pipe(
640 + Layer.provide(
641 + Layer.succeed(FetchHttpClient.Fetch, (input) => {
642 + requests.push(String(input));
643 + return Promise.resolve(
644 + new Response("app", { headers: { "content-type": "text/html" } }),
645 + );
646 + }),
647 + ),
648 + ),
649 + ),
650 + ),
651 + );
652 +
653 + return Effect.gen(function* () {
654 + const scanner = yield* PortScanner.PortDiscovery;
655 + // Startup reads listeners once. With none marked, later scans stay idle.
656 + expect(yield* scanner.scan()).toEqual([]);
657 + expect(yield* scanner.scan()).toEqual([]);
658 + expect(lsofCalls).toBe(1);
659 +
660 + // The agent exits before any client looks, and the first read fails; its server is still
661 + // found.
662 + lsofStdout = `${agentListener}${otherListener}`;
663 + scanner.trackAgent()();
664 + lsofFails = true;
665 + expect(yield* scanner.scan()).toEqual([]);
666 + lsofFails = false;
667 + if (platform === "darwin") {
668 + environmentFails = true;
669 + expect(yield* scanner.scan()).toEqual([]);
670 + environmentFails = false;
671 + }
672 + expect(yield* scanner.scan()).toMatchObject([
673 + { port: agentPort, pid: 4242, terminal: null, agent: { threadId: "thread-agent" } },
674 + ]);
675 + expect(requests).toEqual([`http://localhost:${agentPort}/`]);
676 +
677 + expect(yield* scanner.scan()).toHaveLength(1);
678 + expect(environmentReads).toBe(2);
679 +
680 + // Stop reads its target's environment again rather than trust the cache, and still finds it.
681 + const stop = yield* Effect.flip(scanner.stopServer({ pid: 4242, port: agentPort }));
682 + expect(stop.reason).toBe("shared-group");
683 + expect(environmentReads).toBe(3);
684 +
685 + lsofStdout = otherListener;
686 + expect(yield* scanner.scan()).toEqual([]);
687 + const lsofCallsAfterExit = lsofCalls;
688 + expect(yield* scanner.scan()).toEqual([]);
689 + expect(lsofCalls).toBe(lsofCallsAfterExit);
690 + }).pipe(Effect.provide(layer));
691 + },
692 +);
693 +
694 +effectIt.effect("stops only a job's own process group", () =>
695 + Effect.sync(() => {
696 + const serverPid = 100;
697 + const rows = [
698 + { pid: 10, ppid: 1, pgid: 10 }, // `vp run dev`, whose job holds this server
699 + { pid: 20, ppid: 10, pgid: 10 }, // the web dev server in the same job
700 + { pid: serverPid, ppid: 10, pgid: 10 },
701 + { pid: 200, ppid: serverPid, pgid: 200 }, // agent CLI
702 + { pid: 210, ppid: 200, pgid: 200 }, // a server it spawned without a group of its own
703 + { pid: 300, ppid: 200, pgid: 300 }, // agent tool shell
704 + { pid: 400, ppid: 300, pgid: 400 }, // `npm run dev &`
705 + { pid: 401, ppid: 400, pgid: 400 },
706 + { pid: 500, ppid: serverPid, pgid: 500 }, // terminal shell
707 + { pid: 600, ppid: 500, pgid: 600 }, // terminal job
708 + ];
709 + const table = new Map(rows.map((row) => [row.pid, row]));
710 + expect(PortScanner.stoppableProcessGroup(table, 401, serverPid)).toBe(400);
711 + expect(PortScanner.stoppableProcessGroup(table, 600, serverPid)).toBe(600);
712 + for (const pid of [20, 210, 500, 999]) {
713 + expect(PortScanner.stoppableProcessGroup(table, pid, serverPid)).toBeNull();
714 + }
715 + }),
716 +);
717 +
718 +const AGENT_SERVER_SCRIPT = `
719 +const server = require("node:http").createServer((_, response) => {
720 + response.writeHead(200, { "content-type": "text/html" });
721 + response.end("<html></html>");
722 +});
723 +server.listen(0, "127.0.0.1", () => {
724 + process.stdout.write(process.pid + " " + server.address().port + "\\n");
725 +});
726 +`;
727 +
728 +/**
729 + * A real HTML server with an agent's environment, started the way an agent's tool shell starts a
730 + * job: under a detached shell with job control, in a group of its own. Release kills only the pids
731 + * it started.
732 + */
733 +const agentServer = () =>
734 + Effect.acquireRelease(
735 + Effect.callback<{
736 + readonly child: NodeChildProcess.ChildProcess;
737 + readonly pid: number;
738 + readonly port: number;
739 + readonly exited: Promise<void>;
740 + }>((resume) => {
741 + const env = { ...process.env, [PortScanner.AGENT_THREAD_ENV]: "thread-live" };
742 + // dash ignores `set -m` without a terminal; bash, like agent tool shells, honors it.
743 + const child = NodeChildProcess.spawn(
744 + "bash",
745 + ["-c", 'set -m; "$0" -e "$1" & wait', process.execPath, AGENT_SERVER_SCRIPT],
746 + { detached: true, env, stdio: ["ignore", "pipe", "ignore"] },
747 + );
748 + const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));
749 + child.once("error", (error) => resume(Effect.die(error)));
750 + child.stdout?.once("data", (chunk) => {
751 + const [pid, port] = String(chunk).trim().split(" ").map(Number);
752 + resume(Effect.succeed({ child, pid: pid!, port: port!, exited }));
753 + });
754 + }),
755 + ({ child, pid }) =>
756 + Effect.sync(() => {
757 + for (const target of [pid, child.pid]) {
758 + try {
759 + if (target !== undefined) process.kill(target, "SIGKILL");
760 + } catch {}
761 + }
762 + }),
763 + );
764 +
765 +const isRunning = (pid: number): boolean => {
766 + try {
767 + process.kill(pid, 0);
768 + return true;
769 + } catch {
770 + return false;
771 + }
772 +};
773 +
774 +effectIt.live.skipIf(HostProcess.Platform.defaultValue() === "win32")(
775 + "stops an agent's server through its job's group, and only a listed server",
776 + () =>
777 + Effect.gen(function* () {
778 + const scanner = yield* PortScanner.PortDiscovery;
779 + yield* Effect.acquireRelease(Effect.sync(scanner.trackAgent), (release) =>
780 + Effect.sync(release),
781 + );
782 + const job = yield* agentServer();
783 +
784 + expect(yield* scanner.scan()).toEqual(
785 + expect.arrayContaining([
786 + expect.objectContaining({
787 + pid: job.pid,
788 + port: job.port,
789 + agent: { threadId: "thread-live" },
790 + }),
791 + ]),
792 + );
793 +
794 + const unlisted = yield* Effect.flip(scanner.stopServer({ pid: process.pid, port: job.port }));
795 + expect(unlisted.reason).toBe("not-found");
796 +
797 + yield* scanner.stopServer({ pid: job.pid, port: job.port });
798 + // The shell waits on its job, so it exits once the job has.
799 + yield* Effect.promise(() => job.exited);
800 + expect(isRunning(job.pid)).toBe(false);
801 + }).pipe(
802 + Effect.scoped,
803 + Effect.provide(
804 + PortScanner.layer.pipe(
805 + Layer.provide(ProcessRunner.layer),
806 + Layer.provide(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer)),
807 + ),
808 + ),
809 + ),
810 +);
apps/server/src/preview/PortScanner.ts
+340 -31
@@ -1,9 +1,12 @@
1 import {
2 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
3 PREVIEW_URL_MAX_LENGTH,
4 + PreviewStopLocalServerError,
5 ThreadId,
6 type DiscoveredLocalServer,
7 + type PreviewStopLocalServerInput,
8 } from "@t3tools/contracts";
9 +import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
10 import * as HostProcess from "@t3tools/shared/HostProcess";
11 import { isLoopbackHost, LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
12 import * as Cause from "effect/Cause";
@@ -46,9 +49,25 @@ export class PortDiscovery extends Context.Service<
49 readonly threadId: string;
50 readonly terminalId: string;
51 }) => Effect.Effect<void>;
52 + /**
53 + * Counts a running agent until the returned function is called. While one runs, any
54 + * listener may be a server it started. Synchronous because provider spawn callbacks run
55 + * outside Effect.
56 + */
57 + readonly trackAgent: () => () => void;
58 + /** Stops a listed server's process group, never this server, an agent CLI, or a shell. */
59 + readonly stopServer: (
60 + input: PreviewStopLocalServerInput,
61 + ) => Effect.Effect<void, PreviewStopLocalServerError>;
62 }
63 >()("t3/preview/PortScanner/PortDiscovery") {}
64
65 +/**
66 + * Agents launch with this set to their thread, and every job they start inherits it, so a
67 + * server stays attributed after its launching shell exits or the agent settles.
68 + */
69 +export const AGENT_THREAD_ENV = "T3CODE_THREAD_ID";
70 +
71 const POLL_INTERVAL = Duration.seconds(3);
72 const LSOF_TIMEOUT_MS = 5_000;
73 const PROC_FD_WALK_LIMIT = 50_000;
@@ -63,6 +82,10 @@ const WINDOWS_PROCESS_NAME_TTL_MS = Duration.toMillis(Duration.seconds(60));
82 const WINDOWS_PROCESS_NAME_CONCURRENCY = 4;
83 const WEB_PROBE_CONCURRENCY = 16;
84 const NAVIGATION_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
85 +const PS_TIMEOUT_MS = 5_000;
86 +const PS_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
87 +const STOP_GRACE_MS = 3_000;
88 +const STOP_POLL_INTERVAL = Duration.millis(250);
89
90 type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
91
@@ -88,6 +111,19 @@ interface TerminalProcessOwner {
111 readonly terminalId: string;
112 }
113
114 +type ServerOwner = Pick<DiscoveredLocalServer, "terminal" | "agent">;
115 +
116 +const UNOWNED: ServerOwner = { terminal: null, agent: null };
117 +
118 +const isOwned = (server: DiscoveredLocalServer): boolean =>
119 + server.terminal !== null || (server.agent ?? null) !== null;
120 +
121 +interface ProcessTableRow {
122 + readonly pid: number;
123 + readonly ppid: number;
124 + readonly pgid: number;
125 +}
126 +
127 interface WebProbeCacheEntry {
128 readonly pid: number | null;
129 readonly isWeb: boolean;
@@ -170,7 +206,7 @@ const projectWebProbeSnapshot = (
206
207 const parseLsofOutput = (
208 raw: string,
173 - terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
209 + owners: ReadonlyMap<number, ServerOwner> = new Map(),
210 ): ReadonlyArray<DiscoveredLocalServer> => {
211 const seen = new Map<string, DiscoveredLocalServer>();
212 let pid: number | null = null;
@@ -195,10 +231,10 @@ const parseLsofOutput = (
231 if (portMatch == null) continue;
232 const url = `http://localhost:${portMatch}`;
233 const key = `localhost:${portMatch}`;
198 - const terminal = pid === null ? null : (terminalByProcessId.get(pid) ?? null);
234 + const owner = pid === null ? undefined : owners.get(pid);
235 const existing = seen.get(key);
236 if (existing) {
201 - if (terminal === null) seen.set(key, { ...existing, terminal: null });
237 + if (owner === undefined) seen.set(key, { ...existing, ...UNOWNED });
238 continue;
239 }
240 seen.set(key, {
@@ -207,7 +243,7 @@ const parseLsofOutput = (
243 url,
244 processName,
245 pid,
210 - terminal,
246 + ...(owner ?? UNOWNED),
247 });
248 }
249 }
@@ -288,18 +324,17 @@ const parseTasklistProcessName = (raw: string, pid: number): string | null => {
324
325 const parseWindowsListenerOutput = (
326 raw: string,
291 - terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
327 + owners: ReadonlyMap<number, ServerOwner> = new Map(),
328 ): ReadonlyArray<DiscoveredLocalServer> => {
329 const seen = new Map<number, DiscoveredLocalServer>();
330 for (const line of raw.split(/\r?\n/g)) {
331 const parsed = parseWindowsListenerLine(line);
332 if (!parsed) continue;
333 const { port, pid: normalizedPid, processName } = parsed;
298 - const terminal =
299 - normalizedPid === null ? null : (terminalByProcessId.get(normalizedPid) ?? null);
334 + const owner = normalizedPid === null ? undefined : owners.get(normalizedPid);
335 const existing = seen.get(port);
336 if (existing) {
302 - if (terminal === null) seen.set(port, { ...existing, terminal: null });
337 + if (owner === undefined) seen.set(port, { ...existing, ...UNOWNED });
338 continue;
339 }
340 seen.set(port, {
@@ -308,7 +343,7 @@ const parseWindowsListenerOutput = (
343 url: `http://localhost:${port}`,
344 processName,
345 pid: normalizedPid,
311 - terminal,
346 + ...(owner ?? UNOWNED),
347 });
348 }
349 return [...seen.values()].toSorted((left, right) => left.port - right.port);
@@ -343,6 +378,90 @@ const parseProcNetTcp = (
378 return listeners;
379 };
380
381 +/** Processes holding a loopback or wildcard listener in `lsof -F pcn` output. */
382 +const lsofProcessIds = (raw: string): ReadonlyArray<number> => {
383 + const pids = new Set<number>();
384 + let pid: number | null = null;
385 + for (const line of raw.split("\n")) {
386 + if (line.startsWith("p")) {
387 + const parsed = Number.parseInt(line.slice(1), 10);
388 + pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;
389 + } else if (
390 + line.startsWith("n") &&
391 + pid !== null &&
392 + parsePortFromLsofName(line.slice(1)) !== null
393 + ) {
394 + pids.add(pid);
395 + }
396 + }
397 + return [...pids];
398 +};
399 +
400 +const AGENT_THREAD_ASSIGNMENT = new RegExp(`(?:^|\\s)${AGENT_THREAD_ENV}=(\\S+)`);
401 +
402 +/** Reads `/proc/<pid>/environ`, whose entries are NUL-separated. */
403 +const parseProcEnvironThread = (raw: string): ThreadId | null => {
404 + const prefix = `${AGENT_THREAD_ENV}=`;
405 + const value = raw
406 + .split("\0")
407 + .find((entry) => entry.startsWith(prefix))
408 + ?.slice(prefix.length)
409 + .trim();
410 + return value ? ThreadId.make(value) : null;
411 +};
412 +
413 +/**
414 + * Reads macOS `ps -E -o pid=,command=`, which appends each process's launch environment to its
415 + * argv with spaces, so an argument that spells the assignment out also matches.
416 + */
417 +const parsePsEnvironmentThreads = (raw: string): ReadonlyMap<number, ThreadId | null> => {
418 + const threads = new Map<number, ThreadId | null>();
419 + for (const line of raw.split("\n")) {
420 + const match = /^\s*(\d+)\s(.*)$/.exec(line);
421 + if (!match) continue;
422 + const value = AGENT_THREAD_ASSIGNMENT.exec(match[2]!)?.[1];
423 + threads.set(Number(match[1]), value ? ThreadId.make(value) : null);
424 + }
425 + return threads;
426 +};
427 +
428 +const parseProcessTable = (raw: string): ReadonlyMap<number, ProcessTableRow> => {
429 + const rows = new Map<number, ProcessTableRow>();
430 + for (const line of raw.split("\n")) {
431 + const [pid, ppid, pgid] = line.trim().split(/\s+/).map(Number);
432 + if (Number.isInteger(pid) && Number.isInteger(ppid) && Number.isInteger(pgid)) {
433 + rows.set(pid!, { pid: pid!, ppid: ppid!, pgid: pgid! });
434 + }
435 + }
436 + return rows;
437 +};
438 +
439 +/**
440 + * The process group stopping `pid` signals. Shells with job control and agent tool shells give
441 + * every job its own group, so the group is the job. Null when the group also holds this server,
442 + * a direct child of it (agent CLIs and terminal shells), or one of its ancestors.
443 + */
444 +export const stoppableProcessGroup = (
445 + table: ReadonlyMap<number, ProcessTableRow>,
446 + pid: number,
447 + serverPid: number,
448 +): number | null => {
449 + const group = table.get(pid)?.pgid;
450 + if (group === undefined || group <= 1) return null;
451 + const guarded = new Set([serverPid]);
452 + for (
453 + let parent = table.get(serverPid)?.ppid;
454 + parent !== undefined && parent > 1 && !guarded.has(parent);
455 + parent = table.get(parent)?.ppid
456 + ) {
457 + guarded.add(parent);
458 + }
459 + for (const row of table.values()) {
460 + if (row.pgid === group && (guarded.has(row.pid) || row.ppid === serverPid)) return null;
461 + }
462 + return group;
463 +};
464 +
465 const serversEqual = (
466 left: ReadonlyArray<DiscoveredLocalServer>,
467 right: ReadonlyArray<DiscoveredLocalServer>,
@@ -359,7 +478,8 @@ const serversEqual = (
478 a.processName !== b.processName ||
479 a.pid !== b.pid ||
480 a.terminal?.threadId !== b.terminal?.threadId ||
362 - a.terminal?.terminalId !== b.terminal?.terminalId
481 + a.terminal?.terminalId !== b.terminal?.terminalId ||
482 + a.agent?.threadId !== b.agent?.threadId
483 ) {
484 return false;
485 }
@@ -367,6 +487,9 @@ const serversEqual = (
487 return true;
488 };
489
490 +const isNoSuchProcess = (cause: unknown): boolean =>
491 + typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ESRCH";
492 +
493 const isCommandNotFound = (error: ProcessRunner.ProcessSpawnError): boolean =>
494 PlatformError.isPlatformError(error.cause) && error.cause.reason._tag === "NotFound";
495
@@ -391,6 +514,72 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
514 ReadonlyMap<string, { readonly pid: number; readonly processName: string | null }>
515 >(new Map());
516 const socketOwnerMissesRef = yield* Ref.make<ReadonlyMap<string, number>>(new Map());
517 + // Each current listener pid's agent thread, or null without one. A process keeps its launch
518 + // environment, so a pid is read once while it listens. Cleared while no client retains the
519 + // scanner, since unscanned pids can be reused.
520 + const agentThreadsRef = yield* Ref.make<ReadonlyMap<number, ThreadId | null>>(new Map());
521 + let runningAgents = 0;
522 + // An agent that exited, or a cache cleared with a marked listener, owes one listener read: the
523 + // servers it left may still run. So does startup, for agents that ran before a restart.
524 + let agentScanPending = true;
525 +
526 + const readAgentThreads = Effect.fn("PortDiscovery.readAgentThreads")(function* (
527 + pids: ReadonlyArray<number>,
528 + ) {
529 + const cached = yield* Ref.get(agentThreadsRef);
530 + const unread = pids.filter((pid) => !cached.has(pid));
531 + const read: ReadonlyMap<number, ThreadId | null> =
532 + unread.length === 0
533 + ? new Map()
534 + : hostPlatform === "linux"
535 + ? new Map(
536 + yield* Effect.forEach(
537 + unread,
538 + (pid) =>
539 + fileSystem.readFileString(`/proc/${pid}/environ`).pipe(
540 + Effect.map(parseProcEnvironThread),
541 + Effect.orElseSucceed(() => null),
542 + Effect.map((threadId) => [pid, threadId] as const),
543 + ),
544 + { concurrency: 16 },
545 + ),
546 + )
547 + : yield* processRunner
548 + .run({
549 + command: "ps",
550 + args: ["-E", "-ww", "-o", "pid=,command=", "-p", unread.join(",")],
551 + timeout: Duration.millis(PS_TIMEOUT_MS),
552 + maxOutputBytes: PS_MAX_OUTPUT_BYTES,
553 + })
554 + .pipe(
555 + Effect.map((result) => parsePsEnvironmentThreads(result.stdout)),
556 + Effect.orElseSucceed(() => {
557 + agentScanPending = true;
558 + return new Map();
559 + }),
560 + );
561 + const next = new Map<number, ThreadId | null>();
562 + for (const pid of pids) {
563 + const threadId = cached.has(pid) ? cached.get(pid) : read.get(pid);
564 + if (threadId !== undefined) next.set(pid, threadId);
565 + }
566 + yield* Ref.set(agentThreadsRef, next);
567 + return next;
568 + });
569 +
570 + const withAgentOwners = Effect.fn("PortDiscovery.withAgentOwners")(function* (
571 + terminalOwners: ReadonlyMap<number, ServerOwner>,
572 + pids: ReadonlyArray<number>,
573 + ) {
574 + // Runs only once a listener snapshot exists, so a failed read leaves the scan pending.
575 + agentScanPending = false;
576 + const threads = yield* readAgentThreads(pids.filter((pid) => !terminalOwners.has(pid)));
577 + const owners = new Map(terminalOwners);
578 + for (const [pid, threadId] of threads) {
579 + if (threadId !== null) owners.set(pid, { terminal: null, agent: { threadId } });
580 + }
581 + return owners;
582 + });
583
584 const findSocketOwners = Effect.fn("PortDiscovery.findSocketOwners")(function* (
585 inodes: ReadonlySet<string>,
@@ -428,7 +617,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
617 });
618
619 const scanProcListeners = Effect.fn("PortDiscovery.scanProcListeners")(function* (
431 - terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner>,
620 + resolveOwners: (pids: ReadonlyArray<number>) => Effect.Effect<ReadonlyMap<number, ServerOwner>>,
621 ) {
622 if (hostPlatform !== "linux") return null;
623 const tables = yield* Effect.forEach(["/proc/net/tcp", "/proc/net/tcp6"], (path) =>
@@ -455,22 +644,25 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
644 }
645 yield* Ref.set(socketOwnersRef, owners);
646 yield* Ref.set(socketOwnerMissesRef, misses);
647 + const serverOwners = yield* resolveOwners([
648 + ...new Set([...owners.values()].map(({ pid }) => pid)),
649 + ]);
650 const seen = new Map<number, DiscoveredLocalServer>();
651 for (const { port, inode } of listeners) {
460 - const owner = owners.get(inode) ?? null;
461 - const terminal = owner === null ? null : (terminalByProcessId.get(owner.pid) ?? null);
652 + const socketOwner = owners.get(inode) ?? null;
653 + const owner = socketOwner === null ? undefined : serverOwners.get(socketOwner.pid);
654 const existing = seen.get(port);
463 - if (existing && (existing.pid !== null || owner === null)) {
464 - if (terminal === null) seen.set(port, { ...existing, terminal: null });
655 + if (existing && (existing.pid !== null || socketOwner === null)) {
656 + if (owner === undefined) seen.set(port, { ...existing, ...UNOWNED });
657 continue;
658 }
659 seen.set(port, {
660 host: "localhost",
661 port,
662 url: `http://localhost:${port}`,
471 - processName: owner?.processName ?? null,
472 - pid: owner?.pid ?? null,
473 - terminal: existing ? null : terminal,
663 + processName: socketOwner?.processName ?? null,
664 + pid: socketOwner?.pid ?? null,
665 + ...(existing ? UNOWNED : (owner ?? UNOWNED)),
666 });
667 }
668 return [...seen.values()].toSorted((left, right) => left.port - right.port);
@@ -530,7 +722,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
722
723 for (const server of servers) {
724 // Never probe an unidentified listener with HTTP or TLS; binary RPC servers can crash on it.
533 - if (server.terminal === null) continue;
725 + if (!isOwned(server)) continue;
726 groups.push({
727 server,
728 urls: [`http://${server.host}:${server.port}`, `https://${server.host}:${server.port}`],
@@ -682,15 +874,24 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
874 configuredUrls: ReadonlyArray<string>,
875 ) {
876 const state = yield* Ref.get(stateRef);
685 - const terminalByProcessId = new Map<number, TerminalProcessOwner>();
877 + const terminalOwners = new Map<number, ServerOwner>();
878 for (const registration of state.terminalProcesses.values()) {
879 for (const processId of registration.processIds) {
688 - terminalByProcessId.set(processId, registration.owner);
880 + terminalOwners.set(processId, { terminal: registration.owner, agent: null });
881 }
882 }
691 - if (terminalByProcessId.size === 0 && configuredUrls.length === 0) {
883 + // A server an agent started can outlive the agent, so listeners are read while the last scan
884 + // still found one.
885 + const agentsPossible =
886 + hostPlatform !== "win32" &&
887 + (runningAgents > 0 ||
888 + agentScanPending ||
889 + [...(yield* Ref.get(agentThreadsRef)).values()].some((threadId) => threadId !== null));
890 + if (terminalOwners.size === 0 && configuredUrls.length === 0 && !agentsPossible) {
891 return { discovered: [], configured: new Map() } satisfies WebProbeSnapshot;
892 }
893 + const resolveOwners = (pids: ReadonlyArray<number>) =>
894 + agentsPossible ? withAgentOwners(terminalOwners, pids) : Effect.succeed(terminalOwners);
895 if (hostPlatform === "win32") {
896 const recoverWindowsProbeFailure = recoverProcessProbeFailure("windows-listeners");
897 const runNetstat = (protocol: "tcp" | "tcpv6") =>
@@ -707,7 +908,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
908 Effect.map(([tcp4, tcp6]) =>
909 exitedWithError(tcp4) || exitedWithError(tcp6)
910 ? null
710 - : parseWindowsListenerOutput(`${tcp4.stdout}\n${tcp6.stdout}`, terminalByProcessId),
911 + : parseWindowsListenerOutput(`${tcp4.stdout}\n${tcp6.stdout}`, terminalOwners),
912 ),
913 Effect.catchTags({
914 ProcessSpawnError: recoverWindowsProbeFailure,
@@ -723,7 +924,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
924 }
925 const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof");
926 if (yield* Ref.get(lsofMissingRef)) {
726 - const fromProc = yield* scanProcListeners(terminalByProcessId);
927 + const fromProc = yield* scanProcListeners(resolveOwners);
928 return yield* probeWebServers(fromProc ?? [], configuredUrls);
929 }
930 const lsofResult = yield* processRunner
@@ -735,7 +936,11 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
936 maxOutputBytes: 1024 * 1024,
937 })
938 .pipe(
738 - Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),
939 + Effect.flatMap((result) =>
940 + resolveOwners(lsofProcessIds(result.stdout)).pipe(
941 + Effect.map((owners) => parseLsofOutput(result.stdout, owners)),
942 + ),
943 + ),
944 Effect.catchTags({
945 ProcessSpawnError: (error) =>
946 (isCommandNotFound(error) ? Ref.set(lsofMissingRef, true) : Effect.void).pipe(
@@ -748,7 +953,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
953 }),
954 );
955 if (lsofResult !== null) return yield* probeWebServers(lsofResult, configuredUrls);
751 - const fromProc = yield* scanProcListeners(terminalByProcessId);
956 + const fromProc = yield* scanProcListeners(resolveOwners);
957 return yield* probeWebServers(fromProc ?? [], configuredUrls);
958 });
959
@@ -809,11 +1014,19 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
1014 }
1015 });
1016
812 - const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(acquireRetention(), () =>
813 - Ref.update(stateRef, (state) => ({
814 - ...state,
815 - retainCount: Math.max(0, state.retainCount - 1),
816 - })),
1017 + const releaseRetention = Effect.gen(function* () {
1018 + const idle = yield* Ref.modify(stateRef, (state) => {
1019 + const retainCount = Math.max(0, state.retainCount - 1);
1020 + return [retainCount === 0, { ...state, retainCount }];
1021 + });
1022 + if (!idle) return;
1023 + const threads = yield* Ref.getAndSet(agentThreadsRef, new Map());
1024 + if ([...threads.values()].some((threadId) => threadId !== null)) agentScanPending = true;
1025 + });
1026 +
1027 + const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(
1028 + acquireRetention(),
1029 + () => releaseRetention,
1030 );
1031
1032 const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
@@ -867,13 +1080,109 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
1080 });
1081 });
1082
1083 + const trackAgent: PortDiscovery["Service"]["trackAgent"] = () => {
1084 + runningAgents += 1;
1085 + let released = false;
1086 + return () => {
1087 + if (released) return;
1088 + released = true;
1089 + runningAgents -= 1;
1090 + agentScanPending = true;
1091 + };
1092 + };
1093 +
1094 + // Fails when `ps` does, so an empty table never reads as every process having exited.
1095 + const readProcessTable = Effect.suspend(() =>
1096 + processRunner.run({
1097 + command: "ps",
1098 + args: ["-A", "-o", "pid=,ppid=,pgid="],
1099 + timeout: Duration.millis(PS_TIMEOUT_MS),
1100 + maxOutputBytes: PS_MAX_OUTPUT_BYTES,
1101 + }),
1102 + ).pipe(
1103 + Effect.mapError((cause) => new PreviewStopLocalServerError({ reason: "signal-failed", cause })),
1104 + Effect.filterOrFail(
1105 + (result) => !exitedWithError(result),
1106 + () => new PreviewStopLocalServerError({ reason: "signal-failed" }),
1107 + ),
1108 + Effect.map((result) => parseProcessTable(result.stdout)),
1109 + );
1110 +
1111 + const signalUntilStopped = Effect.fn("PortDiscovery.signalUntilStopped")(function* (
1112 + input: PreviewStopLocalServerInput,
1113 + ) {
1114 + if (hostPlatform === "win32") {
1115 + return yield* new PreviewStopLocalServerError({ reason: "unsupported" });
1116 + }
1117 + // A socket can outlive its cached owner. Wait for any in-flight scan before invalidating
1118 + // that owner, so the /proc fallback confirms who holds it before a signal is sent.
1119 + yield* scanSemaphore.withPermits(1)(
1120 + Ref.update(
1121 + socketOwnersRef,
1122 + (owners) => new Map([...owners].filter(([, owner]) => owner.pid !== input.pid)),
1123 + ),
1124 + );
1125 + // The pid comes from a client, so only a server this scan attributes to a thread is signaled,
1126 + // from its environment as read now.
1127 + yield* Ref.update(agentThreadsRef, (threads) => {
1128 + const next = new Map(threads);
1129 + next.delete(input.pid);
1130 + return next;
1131 + });
1132 + agentScanPending = true;
1133 + const listed = (yield* scanOnce()).some(
1134 + (server) => server.pid === input.pid && server.port === input.port && isOwned(server),
1135 + );
1136 + if (!listed) return yield* new PreviewStopLocalServerError({ reason: "not-found" });
1137 + const table = yield* readProcessTable;
1138 + // It exited after the scan, so there is nothing left to stop.
1139 + if (!table.has(input.pid)) return;
1140 + const group = stoppableProcessGroup(table, input.pid, process.pid);
1141 + if (group === null) return yield* new PreviewStopLocalServerError({ reason: "shared-group" });
1142 + // False when the whole group already exited.
1143 + const signalGroup = (signal: "SIGTERM" | "SIGKILL") =>
1144 + Effect.suspend(() => {
1145 + try {
1146 + signalProcessGroup(group, signal);
1147 + return Effect.succeed(true);
1148 + } catch (cause) {
1149 + return isNoSuchProcess(cause)
1150 + ? Effect.succeed(false)
1151 + : Effect.fail(new PreviewStopLocalServerError({ reason: "signal-failed", cause }));
1152 + }
1153 + });
1154 + if (!(yield* signalGroup("SIGTERM"))) return;
1155 + // While one of the group's original members is still in it, the group has not been reused,
1156 + // so SIGKILL goes only to the job that ignored SIGTERM.
1157 + const members = [...table.values()].filter((row) => row.pgid === group).map((row) => row.pid);
1158 + const jobRunning = readProcessTable.pipe(
1159 + Effect.map((current) => members.some((pid) => current.get(pid)?.pgid === group)),
1160 + Effect.orElseSucceed(() => false),
1161 + );
1162 + const deadline = (yield* Clock.currentTimeMillis) + STOP_GRACE_MS;
1163 + while ((yield* Clock.currentTimeMillis) < deadline) {
1164 + yield* Effect.sleep(STOP_POLL_INTERVAL);
1165 + if (!(yield* jobRunning)) return;
1166 + }
1167 + yield* signalGroup("SIGKILL");
1168 + });
1169 +
1170 + const stopServer: PortDiscovery["Service"]["stopServer"] = (input) =>
1171 + // Subscribers see the server leave now rather than on the next poll.
1172 + signalUntilStopped(input).pipe(Effect.andThen(pollIfRetained));
1173 +
1174 return PortDiscovery.of({
1175 scan: scanOnce,
1176 subscribe,
1177 retain,
1178 registerTerminalProcesses,
1179 unregisterTerminal,
1180 + trackAgent,
1181 + stopServer,
1182 });
1183 }).pipe(Effect.withSpan("PortDiscovery.make"));
1184
1185 export const layer = Layer.effect(PortDiscovery, make);
1186 +
1187 +/** A scanner that tracks nothing, for tests that build provider runners without a host. */
1188 +export const layerTest = Layer.mock(PortDiscovery)({ trackAgent: () => () => undefined });
apps/server/src/provider/ProviderInstanceRegistry.test.ts
+2
@@ -36,6 +36,7 @@ import * as ResetCreditCoordinator from "./resetCreditCoordinator.ts";
36 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
37 import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistry.ts";
38 import * as ProviderOrchestrationAdapterInfrastructure from "./ProviderOrchestrationAdapterInfrastructure.ts";
39 +import * as PortScanner from "../preview/PortScanner.ts";
40 import * as ProviderHostLive from "./ProviderHostLive.ts";
41
42 vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
@@ -191,6 +192,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
192 );
193 const layerBase = ProviderHostLive.layer.pipe(Layer.provideMerge(layerBaseDeps));
194 const layerTest = ProviderOrchestrationAdapterInfrastructure.layer.pipe(
195 + Layer.provide(PortScanner.layerTest),
196 Layer.provideMerge(layerBase),
197 );
198
apps/server/src/provider/ProviderInstanceRegistryHydration.ts
+4 -1
@@ -21,6 +21,7 @@ import * as ProviderHostLive from "./ProviderHostLive.ts";
21 import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
22 import type * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
23 import type * as ServerConfig from "../config.ts";
24 +import type * as PortScanner from "../preview/PortScanner.ts";
25
26 type ProviderInstanceRegistryHydrationEnv =
27 | Exclude<
@@ -31,7 +32,9 @@ type ProviderInstanceRegistryHydrationEnv =
32 >
33 | Settings.ServerSettingsService
34 | BackgroundPolicy.BackgroundPolicy
34 - | ServerConfig.ServerConfig;
35 + | ServerConfig.ServerConfig
36 + // The Claude runner counts its CLIs as running agents for port discovery.
37 + | PortScanner.PortDiscovery;
38
39 export const deriveProviderInstanceConfigMap = (
40 settings: ServerSettings,
apps/server/src/provider/ProviderRegistry.test.ts
+10 -5
@@ -51,6 +51,7 @@ import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRunt
51 import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger";
52 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
53 import * as ProviderInstanceRegistryHydration from "./ProviderInstanceRegistryHydration.ts";
54 +import * as PortScanner from "../preview/PortScanner.ts";
55 import * as ServerConfig from "../config.ts";
56 import * as ServerSettingsModule from "../serverSettings.ts";
57 import {
@@ -1961,7 +1962,9 @@ it.layer(
1962 const scope = yield* Scope.make();
1963 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
1964 const layerProviderRegistry = ProviderRegistry.layer.pipe(
1964 - Layer.provideMerge(ProviderInstanceRegistryHydration.layer),
1965 + Layer.provideMerge(
1966 + ProviderInstanceRegistryHydration.layer.pipe(Layer.provide(PortScanner.layerTest)),
1967 + ),
1968 Layer.provideMerge(AntigravityInstallation.AntigravityInstallation.layer),
1969 Layer.provideMerge(
1970 Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
@@ -2077,7 +2080,9 @@ it.layer(
2080 const scope = yield* Scope.make();
2081 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
2082 const layerProviderRegistry = ProviderRegistry.layer.pipe(
2080 - Layer.provideMerge(ProviderInstanceRegistryHydration.layer),
2083 + Layer.provideMerge(
2084 + ProviderInstanceRegistryHydration.layer.pipe(Layer.provide(PortScanner.layerTest)),
2085 + ),
2086 Layer.provideMerge(AntigravityInstallation.AntigravityInstallation.layer),
2087 Layer.provideMerge(
2088 Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
@@ -2210,9 +2215,9 @@ it.layer(
2215 ),
2216 );
2217 readSeed = false;
2213 - const services = yield* Layer.build(ProviderInstanceRegistryHydration.layer).pipe(
2214 - Effect.provide(dependencies),
2215 - );
2218 + const services = yield* Layer.build(
2219 + ProviderInstanceRegistryHydration.layer.pipe(Layer.provide(PortScanner.layerTest)),
2220 + ).pipe(Effect.provide(dependencies));
2221 failCurrentRead = input.failCurrentRead ?? false;
2222 yield* PubSub.publish(changes, undefined);
2223 yield* Deferred.succeed(consume, undefined);
apps/server/src/server.ts
+3
@@ -634,6 +634,9 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
634 ),
635 Layer.provideMerge(ProviderRegistry.layer),
636 Layer.provideMerge(ProviderInstanceRegistryHydration.layer),
637 + // Provider hydration builds the Claude runner, which reports agents to the same scanner the
638 + // terminal and preview layers share.
639 + Layer.provideMerge(layerPortScanner),
640 Layer.provideMerge(
641 Layer.mergeAll(
642 AntigravityInstallation.AntigravityInstallation.layer,
apps/server/src/ws.test.ts
+1 -1
@@ -423,7 +423,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
423 Layer.mock(PairingGrantStore.PairingGrantStore)({}),
424 Layer.mock(PeerLinks.PeerLinks)({}),
425 Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
426 - Layer.mock(PortScanner.PortDiscovery)({}),
426 + Layer.mock(PortScanner.PortDiscovery)({ trackAgent: () => () => undefined }),
427 Layer.mock(PreviewManager.PreviewManager)({}),
428 Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({}),
429 Layer.mock(ProcessResourceMonitor.ProcessResourceMonitor)({}),
apps/server/src/ws.ts
+1
@@ -3101,6 +3101,7 @@ export const layerWsRpc = (
3101 [WS_METHODS.deviceDetail]: (input) => deviceService.detail(input),
3102 [WS_METHODS.deviceAction]: (input) => deviceService.action(input),
3103 [WS_METHODS.subscribeDeviceState]: (_input) => DeviceService.stateStream(deviceService),
3104 + [WS_METHODS.previewStopLocalServer]: (input) => portDiscovery.stopServer(input),
3105 [WS_METHODS.subscribeDiscoveredLocalServers]: (input) =>
3106 Stream.callback<DiscoveredLocalServerList>((queue) =>
3107 Effect.gen(function* () {
apps/web/src/components/chat/ThreadDetailsPanel.tsx
+5
@@ -22,6 +22,7 @@ import { OpenInPicker } from "./OpenInPicker";
22 import { ThreadDetailsSection } from "./ThreadDetailsSection";
23 import { ThreadAutomationsPanel } from "./ThreadAutomationsPanel";
24 import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl";
25 +import { ThreadServersPanel } from "./ThreadServersPanel";
26
27 const GitActionsControl = memo(BaseGitActionsControl);
28
@@ -181,6 +182,10 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) {
182 </ThreadDetailsSection>
183 ) : null}
184
185 + {density === "full" && !props.draftId ? (
186 + <ThreadServersPanel environmentId={props.environmentId} threadId={props.threadId} />
187 + ) : null}
188 +
189 {density === "full" && !props.draftId ? (
190 <ThreadAutomationsPanel environmentId={props.environmentId} threadId={props.threadId} />
191 ) : null}
apps/web/src/components/chat/ThreadServersPanel.tsx new
+155
@@ -0,0 +1,155 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3 +import {
4 + AuthPreviewOperateScope,
5 + type DiscoveredLocalServer,
6 + type EnvironmentId,
7 + type ThreadId,
8 +} from "@t3tools/contracts";
9 +import {
10 + isAtomCommandInterrupted,
11 + squashAtomCommandFailure,
12 +} from "@t3tools/client-runtime/state/runtime";
13 +import { GlobeIcon, LoaderCircleIcon, SquareIcon } from "lucide-react";
14 +import { useState } from "react";
15 +
16 +import { cn } from "../../lib/utils";
17 +import { useThreadDiscoveredPorts } from "../../portDiscoveryState";
18 +import { useEnvironment } from "../../state/environments";
19 +import { previewEnvironment } from "../../state/preview";
20 +import { useEnvironmentScope } from "../../state/session";
21 +import { useAtomCommand } from "../../state/use-atom-command";
22 +import { openDiscoveredPort } from "../preview/openDiscoveredPort";
23 +import { stackedThreadToast, toastManager } from "../ui/toast";
24 +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
25 +import { ThreadDetailsControl } from "./ThreadDetailsControl";
26 +import { ThreadDetailsSection } from "./ThreadDetailsSection";
27 +import { THREAD_DETAILS_PANEL_ICON_CLASS } from "./threadDetailsPanelStyles";
28 +
29 +const serverKey = (server: DiscoveredLocalServer) => `${server.pid}:${server.port}`;
30 +
31 +/** Web servers the thread's terminals and agent started. Hidden while none run. */
32 +export function ThreadServersPanel(props: {
33 + readonly environmentId: EnvironmentId;
34 + readonly threadId: ThreadId;
35 +}) {
36 + const servers = useThreadDiscoveredPorts(props);
37 + const canOpen = useEnvironmentScope(props.environmentId, AuthPreviewOperateScope);
38 + const canStop = useAtomValue(
39 + previewEnvironment.stopLocalServer.permissionAtom(props.environmentId),
40 + );
41 + const supportsStop =
42 + useEnvironment(props.environmentId)?.serverConfig?.environment.capabilities.localServerStop ===
43 + true;
44 + const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
45 + const stopServer = useAtomCommand(previewEnvironment.stopLocalServer, {
46 + label: "thread server stop",
47 + });
48 + const [stoppingKey, setStoppingKey] = useState<string | null>(null);
49 +
50 + if (servers.length === 0) return null;
51 + const threadRef = scopeThreadRef(props.environmentId, props.threadId);
52 +
53 + const reportFailure = (title: string, error: unknown) => {
54 + toastManager.add(
55 + stackedThreadToast({
56 + type: "error",
57 + title,
58 + description: error instanceof Error ? error.message : String(error),
59 + }),
60 + );
61 + };
62 +
63 + const open = async (server: DiscoveredLocalServer) => {
64 + const result = await openDiscoveredPort({ threadRef, port: server, openPreview });
65 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
66 + reportFailure("Unable to open preview", squashAtomCommandFailure(result));
67 + }
68 + };
69 +
70 + const stop = async (server: DiscoveredLocalServer) => {
71 + if (server.pid === null || stoppingKey !== null) return;
72 + setStoppingKey(serverKey(server));
73 + const result = await stopServer({
74 + environmentId: props.environmentId,
75 + input: { pid: server.pid, port: server.port },
76 + });
77 + setStoppingKey(null);
78 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
79 + reportFailure("Could not stop server", squashAtomCommandFailure(result));
80 + }
81 + };
82 +
83 + return (
84 + <ThreadDetailsSection headingId="thread-details-servers-heading" title="Servers">
85 + <ul className="m-0 list-none p-0">
86 + {servers.map((server) => {
87 + const key = serverKey(server);
88 + const stoppable = canStop && supportsStop && server.pid !== null;
89 + return (
90 + <li key={key} className="group relative flex h-8 items-center rounded-lg">
91 + <Tooltip>
92 + <TooltipTrigger
93 + delay={200}
94 + render={
95 + <ThreadDetailsControl
96 + size="sm"
97 + variant="ghost"
98 + part="row"
99 + disabled={!canOpen}
100 + onClick={() => void open(server)}
101 + />
102 + }
103 + >
104 + <GlobeIcon aria-hidden className={THREAD_DETAILS_PANEL_ICON_CLASS} />
105 + <span className="shrink-0 text-sm font-medium leading-4 text-foreground/85">
106 + localhost:{server.port}
107 + </span>
108 + {/* The stop button covers this while it shows. */}
109 + <span
110 + className={cn(
111 + "ms-auto min-w-0 truncate text-2xs font-normal text-muted-foreground",
112 + stoppable &&
113 + "group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0 [@media(hover:none)]:opacity-0",
114 + )}
115 + >
116 + {[server.terminal === null ? "Agent" : "Terminal", server.processName]
117 + .filter(Boolean)
118 + .join(" · ")}
119 + </span>
120 + </TooltipTrigger>
121 + <TooltipPopup side="left">Open in the browser panel</TooltipPopup>
122 + </Tooltip>
123 + {stoppable ? (
124 + <div className="pointer-events-none absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 pointer-coarse:pointer-events-auto pointer-coarse:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100">
125 + <Tooltip>
126 + <TooltipTrigger
127 + render={
128 + <ThreadDetailsControl
129 + size="icon-xs"
130 + variant="ghost"
131 + part="icon"
132 + tone="destructive"
133 + aria-label={`Stop localhost:${server.port}`}
134 + disabled={stoppingKey !== null}
135 + onClick={() => void stop(server)}
136 + />
137 + }
138 + >
139 + {stoppingKey === key ? (
140 + <LoaderCircleIcon aria-hidden className="size-3 animate-spin" />
141 + ) : (
142 + <SquareIcon aria-hidden className="size-3 fill-current" />
143 + )}
144 + </TooltipTrigger>
145 + <TooltipPopup side="left">Stop server</TooltipPopup>
146 + </Tooltip>
147 + </div>
148 + ) : null}
149 + </li>
150 + );
151 + })}
152 + </ul>
153 + </ThreadDetailsSection>
154 + );
155 +}
apps/web/src/portDiscoveryState.ts
+4 -1
@@ -72,6 +72,9 @@ export function useThreadDiscoveredPorts(input: {
72 }): ReadonlyArray<DiscoveredLocalServer> {
73 const ports = useDiscoveredPorts(input.environmentId);
74 return input.threadId
75 - ? ports.filter((port) => port.terminal?.threadId === input.threadId)
75 + ? ports.filter(
76 + (port) =>
77 + port.terminal?.threadId === input.threadId || port.agent?.threadId === input.threadId,
78 + )
79 : EMPTY_PORTS;
80 }
docs/user/thread-sidebar.md
+7
@@ -251,6 +251,13 @@ Expand a tool call in the conversation to see its full command and output.
251 Summaries shorten shell wrappers and can still describe the latest call after it
252 finishes; the call's own result shows its status.
253
254 +On web and desktop, the thread details card lists the web servers that the
255 +thread's terminals or its Claude agent started, with their ports. A server the
256 +agent started stays listed after the agent's turn ends.
257 +Select a server to open it in the browser panel. **Stop** ends the server's job
258 +and keeps the agent, the terminal, and T3 Code running. Stop needs terminal
259 +access to the environment and is not available on Windows.
260 +
261 ## Snooze until later
262
263 Choose **Snooze → Custom…** from a thread's menu to pick a date and time in your
packages/client-runtime/src/state/preview.ts
+4
@@ -84,6 +84,10 @@ export function createPreviewEnvironmentAtoms<R, E>(
84 tag: WS_METHODS.previewReportProfiles,
85 concurrency: { mode: "latest", key: ({ environmentId }) => environmentId },
86 }),
87 + stopLocalServer: createEnvironmentRpcCommand(runtime, {
88 + label: "environment-data:preview:stop-local-server",
89 + tag: WS_METHODS.previewStopLocalServer,
90 + }),
91 reportStatus: createEnvironmentRpcCommand(runtime, {
92 label: "environment-data:preview:report-status",
93 tag: WS_METHODS.previewReportStatus,
packages/contracts/src/clientRpcPermissions.ts
+3
@@ -7,6 +7,7 @@ import {
7 AuthPreviewOperateScope,
8 AuthSettingsWriteScope,
9 AuthSourceControlWriteScope,
10 + AuthTerminalOperateScope,
11 type AuthEnvironmentScope,
12 } from "./auth.ts";
13 import { ORCHESTRATION_V2_WS_METHODS } from "./orchestrationV2.ts";
@@ -15,6 +16,8 @@ import { WS_METHODS } from "./rpc.ts";
16 /** Incremental client enforcement; the server still authorizes every request. */
17 export const CLIENT_GUARDED_RPC_SCOPES = {
18 [WS_METHODS.previewClose]: AuthPreviewOperateScope,
19 + // Stopping a server signals its processes, as closing a terminal does.
20 + [WS_METHODS.previewStopLocalServer]: AuthTerminalOperateScope,
21 [WS_METHODS.serverRunStorageCleanup]: AuthSettingsWriteScope,
22 [WS_METHODS.serverCheckOtlpEndpoint]: AuthSettingsWriteScope,
23 [WS_METHODS.pullRequestsRunAction]: AuthSourceControlWriteScope,
packages/contracts/src/environment.ts
+2
@@ -115,6 +115,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
115 threadPullRequestLinking: Schema.optionalKey(Schema.Boolean),
116 serverResolvedCommandContext: Schema.optionalKey(Schema.Boolean),
117 threadStop: Schema.optionalKey(Schema.Boolean),
118 + /** Absent on older servers and on Windows hosts, which cannot stop a discovered server. */
119 + localServerStop: Schema.optionalKey(Schema.Boolean),
120 threadPullRequests: Schema.optionalKey(Schema.Boolean),
121 threadPullRequestWatch: Schema.optionalKey(Schema.Boolean),
122 pullRequestStackActions: Schema.optionalKey(Schema.Boolean),
packages/contracts/src/preview.ts
+32 -1
@@ -312,9 +312,11 @@ export const PreviewEvent = Schema.Union([
312 ]);
313 export type PreviewEvent = typeof PreviewEvent.Type;
314
315 +const LocalServerPort = Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThan(65536));
316 +
317 export const DiscoveredLocalServer = Schema.Struct({
318 host: TrimmedNonEmptyString,
317 - port: Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThan(65536)),
319 + port: LocalServerPort,
320 url: Url,
321 processName: Schema.NullOr(TrimmedNonEmptyString),
322 pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
@@ -324,9 +326,38 @@ export const DiscoveredLocalServer = Schema.Struct({
326 terminalId: TrimmedNonEmptyString,
327 }),
328 ),
329 + /** Started by the thread's agent. Older servers omit it. */
330 + agent: Schema.optionalKey(Schema.NullOr(Schema.Struct({ threadId: ThreadId }))),
331 });
332 export type DiscoveredLocalServer = typeof DiscoveredLocalServer.Type;
333
334 +export const PreviewStopLocalServerInput = Schema.Struct({
335 + pid: PositiveInt,
336 + port: LocalServerPort,
337 +});
338 +export type PreviewStopLocalServerInput = typeof PreviewStopLocalServerInput.Type;
339 +
340 +export class PreviewStopLocalServerError extends Schema.TaggedError<PreviewStopLocalServerError>()(
341 + "PreviewStopLocalServerError",
342 + {
343 + reason: Schema.Literals(["not-found", "shared-group", "unsupported", "signal-failed"]),
344 + cause: Schema.optional(Schema.Defect()),
345 + },
346 +) {
347 + override get message() {
348 + switch (this.reason) {
349 + case "not-found":
350 + return "This server is no longer running.";
351 + case "shared-group":
352 + return "This server shares a process group with T3 Code, an agent, or a terminal shell, so it can't be stopped on its own.";
353 + case "unsupported":
354 + return "Stopping servers is not supported on this environment's platform.";
355 + case "signal-failed":
356 + return "The server's processes could not be signaled.";
357 + }
358 + }
359 +}
360 +
361 export const DiscoveredLocalServerList = Schema.Struct({
362 servers: Schema.Array(DiscoveredLocalServer),
363 scannedAt: Schema.String,
packages/contracts/src/rpc.ts
+9
@@ -282,6 +282,8 @@ import {
282 PreviewClearProfileInput,
283 PreviewReportProfilesInput,
284 PreviewNavigateInput,
285 + PreviewStopLocalServerError,
286 + PreviewStopLocalServerInput,
287 PreviewOpenInput,
288 PreviewRefreshInput,
289 PreviewReportStatusInput,
@@ -473,6 +475,7 @@ export const WS_METHODS = {
475 previewClearProfile: "preview.clearProfile",
476 previewReportProfiles: "preview.reportProfiles",
477 previewReportStatus: "preview.reportStatus",
478 + previewStopLocalServer: "preview.stopLocalServer",
479
480 deviceConfigure: "device.configure",
481 deviceList: "device.list",
@@ -1600,6 +1603,11 @@ const WsSubscribePreviewEventsRpc = Rpc.make(WS_METHODS.subscribePreviewEvents,
1603 stream: true,
1604 });
1605
1606 +const WsPreviewStopLocalServerRpc = Rpc.make(WS_METHODS.previewStopLocalServer, {
1607 + payload: PreviewStopLocalServerInput,
1608 + error: Schema.Union([PreviewStopLocalServerError, EnvironmentAuthorizationError]),
1609 +});
1610 +
1611 const WsSubscribeDiscoveredLocalServersRpc = Rpc.make(WS_METHODS.subscribeDiscoveredLocalServers, {
1612 payload: Schema.Struct({
1613 configuredUrls: Schema.optional(ConfiguredLocalServerUrls),
@@ -2124,6 +2132,7 @@ export const WsRpcGroup = RpcGroup.make(
2132 WsPreviewReportProfilesRpc,
2133 WsPreviewReportStatusRpc,
2134 WsSubscribePreviewEventsRpc,
2135 + WsPreviewStopLocalServerRpc,
2136 WsSubscribeDiscoveredLocalServersRpc,
2137 WsDeviceConfigureRpc,
2138 WsDeviceListRpc,