Compare commits

...
Author SHA1 Message Date
Cursor Agent b1ad5fac52 Fix duplicated port logic and negative web port probe caching
- Extract normalizeRunningPorts and portStatusLabel into @t3tools/shared/port
- Update server (process/utils.ts) and web (terminalStateStore.ts) to import
  from the shared package instead of maintaining duplicate implementations
- Update Sidebar.tsx and ThreadTerminalDrawer.tsx to use shared portStatusLabel
  for constructing terminal port status labels
- Fix inspectWebPortCached in Manager.ts to only cache successful probe results,
  avoiding caching transient failures for the full TTL
2026-04-05 00:28:39 +00:00
Julius Marminge da81a167ea Normalize terminal state and harden process probing
- Share port normalization across terminal selectors
- Preserve typed web probe errors and walk Windows child trees
- Co-authored-by: codex <[email protected]>
2026-04-04 17:14:48 -07:00
Julius Marminge 0236cc845e Move process inspector types beside their services
- Co-locate inspection errors and types with the service modules
- Remove legacy subprocessChecker plumbing from the terminal manager
2026-04-04 16:54:06 -07:00
Julius Marminge 6aac79caff Use Effect HTTP client for web port probing
- add layer-level coverage for slow, large, and 404 responses
- move inspector tests beside the layer and wire FetchHttpClient in terminal tests
2026-04-04 16:43:57 -07:00
Julius Marminge bc30ac51f5 Consolidate terminal inspectors under process
- Rename terminalProcessInspector modules to process
- Fold web port inspector exports into the new package
- Update server and terminal manager imports
2026-04-04 16:20:35 -07:00
Julius Marminge 75ae12f6f7 Extract terminal inspectors into Effect services
- Add Effect layers for process and port probing
- Wire inspectors into server startup and tests
- Co-authored-by: codex <[email protected]>
2026-04-04 16:09:57 -07:00
Julius Marmingeandcodex 05a7018f03 Merge origin/main into codething/50e6e9da
Co-authored-by: codex <[email protected]>
2026-04-04 13:28:00 -07:00
Julius Marmingeandcodex d377e566f8 Merge origin/main into codething/50e6e9da
Co-authored-by: codex <[email protected]>
2026-02-16 01:01:24 -08:00
Julius Marminge 38644b0d81 Detect root-process ports and harden web port probing
- Include terminal root PID in port scans so listener-only sessions are marked active
- Improve web port detection for slow/large HTML responses and redirects
- Add integration-style tests for terminal subprocess and web port inspectors
2026-02-15 19:46:11 -08:00
Julius Marminge c11027be4d Show terminal runtime status and web port actions in thread UI
- Pass running terminal IDs/ports from `ChatView` into `ThreadTerminalDrawer`
- Add runtime badges/icons for running terminals and localhost web ports
- Make sidebar thread rows keyboard-activatable and add web-port quick open button
2026-02-15 18:25:22 -08:00
Julius Marminge b3e967e2cf adapters 2026-02-15 16:48:08 -08:00
Julius Marminge 3d082fc73b Detect real web ports and add one-click localhost shortcut
- Probe terminal subprocess ports and keep only likely web servers
- Cache/dedupe port probes and ignore root-path 404 responses
- Show a globe status icon in Sidebar that opens `http://localhost:<port>`
2026-02-15 16:47:19 -08:00
Julius Marminge 94a83ab48e Require all lsof filters when checking listening ports
- Add `-a` to the `lsof` command in terminal port detection
- Prevent mismatched results by combining TCP listen and PID filters correctly
2026-02-15 16:46:51 -08:00
Julius Marminge f2ec777443 Track running terminal ports across terminal activity events
- add `runningPorts` to terminal activity contract and validation
- detect/listen ports in server subprocess inspection and emit activity updates on port changes
- persist terminal-to-port state in web store and show active ports in sidebar indicator
- update server/web/contracts tests for port-aware activity behavior
2026-02-15 16:46:51 -08:00
26 changed files with 1589 additions and 187 deletions

No files matched your search

@@ -0,0 +1,162 @@
import { spawn, type ChildProcess, type ChildProcessByStdio } from "node:child_process";
import type { Readable } from "node:stream";
import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcessSpawner";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { TerminalProcessInspector } from "../Services/TerminalProcessInspector";
import { TerminalProcessInspectorLive } from "./TerminalProcessInspector";
type ListenerProcess = ChildProcessByStdio<null, Readable, Readable>;
interface StartedProcess {
readonly process: ListenerProcess;
readonly port: number;
}
const stopProcess = (child: ChildProcess) =>
Effect.callback<void>((resume) => {
if (child.exitCode !== null || child.signalCode !== null) {
resume(Effect.void);
return;
}
child.kill("SIGTERM");
const timeout = setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) {
child.kill("SIGKILL");
}
}, 1_000);
child.once("exit", () => {
clearTimeout(timeout);
resume(Effect.void);
});
});
const waitForPort = (child: ListenerProcess) =>
Effect.callback<number, Error>((resume) => {
const timeout = setTimeout(() => {
cleanup();
resume(Effect.fail(new Error("Timed out waiting for listener port")));
}, 3_000);
let stdout = "";
let stderr = "";
const cleanup = () => {
clearTimeout(timeout);
child.stdout.off("data", onStdout);
child.stderr.off("data", onStderr);
child.off("exit", onExit);
};
const onStdout = (chunk: Buffer) => {
stdout += chunk.toString("utf8");
const match = stdout.match(/PORT:(\d+)/);
if (!match?.[1]) return;
const port = Number(match[1]);
if (!Number.isInteger(port) || port <= 0) return;
cleanup();
resume(Effect.succeed(port));
};
const onStderr = (chunk: Buffer) => {
stderr += chunk.toString("utf8");
};
const onExit = (code: number | null) => {
cleanup();
resume(
Effect.fail(
new Error(
`Listener process exited before reporting port (code=${String(code)}): ${stderr.trim()}`,
),
),
);
};
child.stdout.on("data", onStdout);
child.stderr.on("data", onStderr);
child.on("exit", onExit);
return Effect.sync(cleanup);
});
const startListenerProcess = Effect.gen(function* () {
const script = [
"const { createServer } = require('node:http');",
"const server = createServer((_req, res) => {",
" res.statusCode = 200;",
" res.end('ok');",
"});",
"server.listen(0, '127.0.0.1', () => {",
" const address = server.address();",
" if (typeof address !== 'object' || !address) process.exit(1);",
" console.log(`PORT:${address.port}`);",
"});",
"const shutdown = () => server.close(() => process.exit(0));",
"process.on('SIGTERM', shutdown);",
"process.on('SIGINT', shutdown);",
"setInterval(() => {}, 10_000);",
].join("");
const process = spawn("node", ["-e", script], {
stdio: ["ignore", "pipe", "pipe"],
});
const port = yield* waitForPort(process);
return { process, port } satisfies StartedProcess;
});
const nodeChildProcessLayer = NodeChildProcessSpawner.layer.pipe(Layer.provide(NodeServices.layer));
const testLayer = TerminalProcessInspectorLive.pipe(Layer.provide(nodeChildProcessLayer));
it.layer(testLayer)("TerminalProcessInspectorLive", (it) => {
it.effect("detects listening ports when the terminal root pid is the listener", () =>
Effect.acquireUseRelease(
startListenerProcess,
({ process, port }) =>
Effect.gen(function* () {
const listenerPid = process.pid;
if (!listenerPid) {
return yield* Effect.fail(new Error("Listener process pid missing"));
}
const inspector = yield* TerminalProcessInspector;
const activity = yield* inspector.inspect(listenerPid);
assert.equal(activity.hasRunningSubprocess, true);
assert.deepStrictEqual(activity.runningPorts.includes(port), true);
}),
({ process }) => stopProcess(process),
),
);
it.effect("returns idle activity when root process has no children and no listening ports", () =>
Effect.acquireUseRelease(
Effect.sync(() =>
spawn("node", ["-e", "setInterval(() => {}, 10_000)"], {
stdio: ["ignore", "ignore", "ignore"],
}),
),
(process) =>
Effect.gen(function* () {
const idlePid = process.pid;
if (!idlePid) {
return yield* Effect.fail(new Error("Idle process pid missing"));
}
const inspector = yield* TerminalProcessInspector;
const activity = yield* inspector.inspect(idlePid);
assert.equal(activity.hasRunningSubprocess, false);
assert.deepStrictEqual(activity.runningPorts, []);
}),
stopProcess,
),
);
});
@@ -0,0 +1,231 @@
import { Buffer } from "node:buffer";
import { Effect, Layer, Option, PlatformError, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { collectPosixProcessFamilyPids, checkPosixListeningPorts } from "../posix";
import type {
TerminalProcessInspectorShape,
TerminalSubprocessActivity,
} from "../Services/TerminalProcessInspector";
import {
TerminalProcessInspector,
TerminalProcessInspectionError,
} from "../Services/TerminalProcessInspector";
import { checkWindowsListeningPorts, collectWindowsChildPids } from "../win32";
const DEFAULT_COMMAND_KILL_GRACE_MS = 1_000;
interface InspectorCommandResult {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: number;
}
interface CollectOutputResult {
readonly text: string;
readonly truncated: boolean;
}
interface RunInspectorCommandInput {
readonly operation: string;
readonly terminalPid: number;
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs: number;
readonly maxOutputBytes: number;
}
function commandLabel(command: string, args: ReadonlyArray<string>): string {
return [command, ...args].join(" ");
}
const collectOutput = Effect.fn("process.collectOutput")(function* (
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
maxOutputBytes: number,
): Effect.fn.Return<CollectOutputResult, PlatformError.PlatformError> {
return yield* stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => ({
text: "",
bytes: 0,
truncated: false,
}),
(state, chunk) => {
if (state.bytes >= maxOutputBytes) {
return {
...state,
truncated: true,
};
}
const chunkBytes = Buffer.byteLength(chunk);
const remainingBytes = maxOutputBytes - state.bytes;
if (chunkBytes <= remainingBytes) {
return {
text: `${state.text}${chunk}`,
bytes: state.bytes + chunkBytes,
truncated: state.truncated,
};
}
const truncatedChunk = Buffer.from(chunk).subarray(0, remainingBytes).toString("utf8");
return {
text: `${state.text}${truncatedChunk}`,
bytes: state.bytes + remainingBytes,
truncated: true,
};
},
),
Effect.map(({ text, truncated }) => ({ text, truncated })),
);
});
const makeTerminalProcessInspector = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runInspectorCommand = Effect.fn("process.runInspectorCommand")(function* (
input: RunInspectorCommandInput,
) {
const command = ChildProcess.make(input.command, [...input.args], {
killSignal: "SIGTERM",
forceKillAfter: DEFAULT_COMMAND_KILL_GRACE_MS,
});
return yield* Effect.gen(function* () {
const child = yield* spawner.spawn(command).pipe(
Effect.mapError(
(cause) =>
new TerminalProcessInspectionError({
operation: input.operation,
terminalPid: input.terminalPid,
command: commandLabel(input.command, input.args),
detail: "Failed to spawn inspector command.",
cause,
}),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectOutput(child.stdout, input.maxOutputBytes).pipe(
Effect.mapError(
(cause) =>
new TerminalProcessInspectionError({
operation: input.operation,
terminalPid: input.terminalPid,
command: commandLabel(input.command, input.args),
detail: "Failed to read stdout from inspector command.",
cause,
}),
),
),
collectOutput(child.stderr, input.maxOutputBytes).pipe(
Effect.mapError(
(cause) =>
new TerminalProcessInspectionError({
operation: input.operation,
terminalPid: input.terminalPid,
command: commandLabel(input.command, input.args),
detail: "Failed to read stderr from inspector command.",
cause,
}),
),
),
child.exitCode.pipe(
Effect.map(Number),
Effect.mapError(
(cause) =>
new TerminalProcessInspectionError({
operation: input.operation,
terminalPid: input.terminalPid,
command: commandLabel(input.command, input.args),
detail: "Failed to read inspector command exit code.",
cause,
}),
),
),
],
{ concurrency: "unbounded" },
);
return {
stdout: stdout.text,
stderr: stderr.text,
exitCode,
} satisfies InspectorCommandResult;
}).pipe(
Effect.scoped,
Effect.timeoutOption(input.timeoutMs),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TerminalProcessInspectionError({
operation: input.operation,
terminalPid: input.terminalPid,
command: commandLabel(input.command, input.args),
detail: "Inspector command timed out.",
}),
),
onSome: Effect.succeed,
}),
),
);
});
const inspect: TerminalProcessInspectorShape["inspect"] = Effect.fn("process.inspect")(
function* (terminalPid) {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return {
hasRunningSubprocess: false,
runningPorts: [],
} satisfies TerminalSubprocessActivity;
}
if (process.platform === "win32") {
const childPids = yield* collectWindowsChildPids(terminalPid, runInspectorCommand);
const processPidsForPortScan = [terminalPid, ...childPids];
const runningPorts = yield* checkWindowsListeningPorts(processPidsForPortScan, {
terminalPid,
runCommand: runInspectorCommand,
});
return {
hasRunningSubprocess: childPids.length > 0 || runningPorts.length > 0,
runningPorts,
} satisfies TerminalSubprocessActivity;
}
const processFamilyPids = yield* collectPosixProcessFamilyPids(
terminalPid,
runInspectorCommand,
);
if (processFamilyPids.length === 0) {
return {
hasRunningSubprocess: false,
runningPorts: [],
} satisfies TerminalSubprocessActivity;
}
const subprocessPids = processFamilyPids.filter((pid) => pid !== terminalPid);
const runningPorts = yield* checkPosixListeningPorts(processFamilyPids, {
terminalPid,
runCommand: runInspectorCommand,
});
return {
hasRunningSubprocess: subprocessPids.length > 0 || runningPorts.length > 0,
runningPorts,
} satisfies TerminalSubprocessActivity;
},
);
return {
inspect,
} satisfies TerminalProcessInspectorShape;
});
export const TerminalProcessInspectorLive = Layer.effect(
TerminalProcessInspector,
makeTerminalProcessInspector,
);
@@ -0,0 +1,153 @@
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Schema } from "effect";
import { WebPortInspectionError, WebPortInspector } from "../Services/WebPortInspector";
import { WebPortInspectorLive } from "./WebPortInspector";
const closeServer = (server: Server) =>
Effect.callback<void>((resume) => {
server.closeAllConnections?.();
server.closeIdleConnections?.();
server.close(() => {
resume(Effect.void);
});
return Effect.sync(() => {
try {
server.closeAllConnections?.();
server.closeIdleConnections?.();
server.close();
} catch {
// Ignore cleanup failures in tests.
}
});
});
const listenServer = (server: Server) =>
Effect.callback<number, Error>((resume) => {
const onError = (error: Error) => {
cleanup();
resume(Effect.fail(error));
};
const cleanup = () => {
server.off("error", onError);
};
server.once("error", onError);
server.listen(0, "127.0.0.1", () => {
cleanup();
const address = server.address();
if (!address || typeof address !== "object") {
resume(Effect.fail(new Error("Server did not provide a valid listening address.")));
return;
}
resume(Effect.succeed(address.port));
});
return Effect.gen(function* () {
cleanup();
yield* closeServer(server);
});
});
const startServer = (
handler: (request: IncomingMessage, response: ServerResponse) => void,
): Effect.Effect<{ server: Server; port: number }, Error> =>
Effect.gen(function* () {
const server = createServer(handler);
const port = yield* listenServer(server);
return { server, port };
});
it.layer(WebPortInspectorLive.pipe(Layer.provide(FetchHttpClient.layer)))(
"WebPortInspectorLive",
(it) => {
it.effect("treats slow HTML responses as web ports", () =>
Effect.acquireUseRelease(
startServer((_request, response) => {
setTimeout(() => {
response.statusCode = 200;
response.setHeader("content-type", "text/html; charset=utf-8");
response.end(
"<!DOCTYPE html><html><head><title>ok</title></head><body>hello</body></html>",
);
}, 800);
}),
({ port }) =>
Effect.gen(function* () {
const inspector = yield* WebPortInspector;
const isWeb = yield* inspector.inspect(port);
assert.equal(isWeb, true);
}),
({ server }) => closeServer(server),
),
);
it.effect("treats HTML responses with large bodies as web ports", () =>
Effect.acquireUseRelease(
startServer((_request, response) => {
response.statusCode = 200;
response.setHeader("content-type", "text/html; charset=utf-8");
response.end(
`<!DOCTYPE html><html><head><title>x</title></head><body>${"x".repeat(20_000)}</body></html>`,
);
}),
({ port }) =>
Effect.gen(function* () {
const inspector = yield* WebPortInspector;
const isWeb = yield* inspector.inspect(port);
assert.equal(isWeb, true);
}),
({ server }) => closeServer(server),
),
);
it.effect("ignores HTTP 404 responses", () =>
Effect.acquireUseRelease(
startServer((_request, response) => {
response.statusCode = 404;
response.end();
}),
({ port }) =>
Effect.gen(function* () {
const inspector = yield* WebPortInspector;
const isWeb = yield* inspector.inspect(port);
assert.equal(isWeb, false);
}),
({ server }) => closeServer(server),
),
);
},
);
it.effect("WebPortInspectorLive preserves typed timeout errors", () =>
Effect.gen(function* () {
const inspector = yield* WebPortInspector;
const error = yield* inspector.inspect(3000).pipe(Effect.flip);
assert.equal(Schema.is(WebPortInspectionError)(error), true);
assert.equal(error.detail, "HTTP probe timed out.");
}).pipe(
Effect.provide(
WebPortInspectorLive.pipe(
Layer.provide(
Layer.succeed(HttpClient.HttpClient, {
execute: () =>
Effect.fail(
new WebPortInspectionError({
port: 3000,
host: "127.0.0.1",
detail: "HTTP probe timed out.",
}),
),
} as never),
),
),
),
),
);
@@ -0,0 +1,179 @@
import { Buffer } from "node:buffer";
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
import type { WebPortInspectorShape } from "../Services/WebPortInspector";
import { WebPortInspector, WebPortInspectionError } from "../Services/WebPortInspector";
const DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS = 2_000;
const WEB_PORT_PROBE_MAX_BODY_BYTES = 8_192;
interface WebProbeResult {
readonly status: number;
readonly contentType: string;
readonly body: string;
readonly location: string;
}
function normalizeHeaderValue(value: string | string[] | undefined): string {
if (typeof value === "string") return value;
if (Array.isArray(value)) return value[0] ?? "";
return "";
}
function isLikelyWebProbe(result: WebProbeResult | null): boolean {
if (!result) return false;
if (result.status === 404) return false;
if (result.status >= 300 && result.status < 400 && result.location.length > 0) {
return true;
}
const contentType = result.contentType.toLowerCase();
if (contentType.includes("text/html") || contentType.includes("application/xhtml+xml")) {
return true;
}
const body = result.body.toLowerCase();
return body.includes("<!doctype") || body.includes("<html") || body.includes("<head");
}
const collectBodyPreview = <E>(
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, never> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => ({
text: "",
bytes: 0,
}),
(state, chunk) => {
if (state.bytes >= WEB_PORT_PROBE_MAX_BODY_BYTES) {
return state;
}
const chunkBytes = Buffer.byteLength(chunk);
const remainingBytes = WEB_PORT_PROBE_MAX_BODY_BYTES - state.bytes;
if (chunkBytes <= remainingBytes) {
return {
text: `${state.text}${chunk}`,
bytes: state.bytes + chunkBytes,
};
}
return {
text: `${state.text}${Buffer.from(chunk).subarray(0, remainingBytes).toString("utf8")}`,
bytes: state.bytes + remainingBytes,
};
},
),
Effect.map((preview) => preview.text),
Effect.orElseSucceed(() => ""),
);
const makeWebPortInspector = Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
const probeWebPortOnHost = Effect.fn("process.probeWebPortOnHost")(function* (
port: number,
host: string,
): Effect.fn.Return<WebProbeResult | null, WebPortInspectionError> {
const request = HttpClientRequest.get(`http://${host}:${port}/`).pipe(
HttpClientRequest.setHeaders({
accept: "text/html,application/xhtml+xml;q=1,*/*;q=0.1",
}),
);
return yield* httpClient.execute(request).pipe(
Effect.flatMap((response) =>
Effect.gen(function* () {
const status = response.status;
const contentType = normalizeHeaderValue(response.headers["content-type"]);
const location = normalizeHeaderValue(response.headers.location);
if (
(status >= 300 && status < 400 && location.length > 0) ||
contentType.toLowerCase().includes("text/html") ||
contentType.toLowerCase().includes("application/xhtml+xml")
) {
return {
status,
contentType,
location,
body: "",
} satisfies WebProbeResult;
}
const body = yield* collectBodyPreview(response.stream);
return {
status,
contentType,
location,
body,
} satisfies WebProbeResult;
}),
),
Effect.timeoutOption(DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new WebPortInspectionError({
port,
host,
detail: "HTTP probe timed out.",
}),
),
onSome: Effect.succeed,
}),
),
Effect.mapError((error) =>
Schema.is(WebPortInspectionError)(error)
? error
: new WebPortInspectionError({
port,
host,
detail: "Failed to execute HTTP probe request.",
cause: error,
}),
),
);
});
const inspect: WebPortInspectorShape["inspect"] = Effect.fn("process.inspectWebPort")(
function* (port) {
if (!Number.isInteger(port) || port <= 0 || port > 65_535) {
return yield* new WebPortInspectionError({
port,
host: "127.0.0.1",
detail: "Port must be an integer between 1 and 65535.",
});
}
const ipv4Result = yield* probeWebPortOnHost(port, "127.0.0.1").pipe(Effect.exit);
if (ipv4Result._tag === "Success" && isLikelyWebProbe(ipv4Result.value)) {
return true;
}
const ipv6Result = yield* probeWebPortOnHost(port, "::1").pipe(Effect.exit);
if (ipv6Result._tag === "Success" && isLikelyWebProbe(ipv6Result.value)) {
return true;
}
if (ipv4Result._tag === "Success" || ipv6Result._tag === "Success") {
return false;
}
if (ipv6Result._tag === "Failure") {
return yield* Effect.failCause(ipv6Result.cause);
}
return yield* Effect.failCause(ipv4Result.cause);
},
);
return {
inspect,
} satisfies WebPortInspectorShape;
});
export const WebPortInspectorLive = Layer.effect(WebPortInspector, makeWebPortInspector);
@@ -0,0 +1,37 @@
import { ServiceMap, Schema } from "effect";
import type { Effect } from "effect";
export class TerminalProcessInspectionError extends Schema.TaggedErrorClass<TerminalProcessInspectionError>()(
"TerminalProcessInspectionError",
{
operation: Schema.String,
terminalPid: Schema.Int,
command: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `${this.operation} failed for terminal pid ${this.terminalPid}: ${this.detail}`;
}
}
export interface TerminalSubprocessActivity {
hasRunningSubprocess: boolean;
runningPorts: number[];
}
export type TerminalSubprocessInspector = (
terminalPid: number,
) => Effect.Effect<TerminalSubprocessActivity, TerminalProcessInspectionError>;
export interface TerminalProcessInspectorShape {
readonly inspect: (
terminalPid: number,
) => Effect.Effect<TerminalSubprocessActivity, TerminalProcessInspectionError>;
}
export class TerminalProcessInspector extends ServiceMap.Service<
TerminalProcessInspector,
TerminalProcessInspectorShape
>()("t3/process/Services/TerminalProcessInspector") {}
@@ -0,0 +1,30 @@
import { ServiceMap, Schema } from "effect";
import type { Effect } from "effect";
export const DEFAULT_WEB_PORT_PROBE_TTL_MS = 10_000;
export type TerminalWebPortInspector = (
port: number,
) => Effect.Effect<boolean, WebPortInspectionError>;
export class WebPortInspectionError extends Schema.TaggedErrorClass<WebPortInspectionError>()(
"WebPortInspectionError",
{
port: Schema.Int,
host: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Web port probe failed for ${this.host}:${this.port}: ${this.detail}`;
}
}
export interface WebPortInspectorShape {
readonly inspect: (port: number) => Effect.Effect<boolean, WebPortInspectionError>;
}
export class WebPortInspector extends ServiceMap.Service<WebPortInspector, WebPortInspectorShape>()(
"t3/process/Services/WebPortInspector",
) {}
+145
View File
@@ -0,0 +1,145 @@
import { Effect } from "effect";
import type { TerminalProcessInspectionError } from "./Services/TerminalProcessInspector";
import { MAX_PORT_NUMBER, portFromAddress } from "./utils";
interface InspectorCommandResult {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: number;
}
interface PosixRunCommand {
(
input: Readonly<{
operation: string;
terminalPid: number;
command: string;
args: ReadonlyArray<string>;
timeoutMs: number;
maxOutputBytes: number;
}>,
): Effect.Effect<InspectorCommandResult, TerminalProcessInspectionError>;
}
export const collectPosixProcessFamilyPids = Effect.fn("process.collectPosixProcessFamilyPids")(
function* (
terminalPid: number,
runCommand: PosixRunCommand,
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
const psResult = yield* runCommand({
operation: "TerminalProcessInspector.collectPosixProcessFamilyPids",
terminalPid,
command: "ps",
args: ["-eo", "pid=,ppid="],
timeoutMs: 1_000,
maxOutputBytes: 262_144,
});
if (psResult.exitCode !== 0) {
return [];
}
const childrenByParentPid = new Map<number, number[]>();
for (const line of psResult.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
const children = childrenByParentPid.get(ppid);
if (children) {
children.push(pid);
} else {
childrenByParentPid.set(ppid, [pid]);
}
}
const processFamily = new Set<number>([terminalPid]);
const pendingParents = [terminalPid];
while (pendingParents.length > 0) {
const parentPid = pendingParents.shift();
if (!parentPid) continue;
const childPids = childrenByParentPid.get(parentPid);
if (!childPids || childPids.length === 0) continue;
for (const childPid of childPids) {
if (processFamily.has(childPid)) continue;
processFamily.add(childPid);
pendingParents.push(childPid);
}
}
return [...processFamily];
},
);
export const checkPosixListeningPorts = Effect.fn("process.checkPosixListeningPorts")(function* (
processIds: number[],
input: {
terminalPid: number;
runCommand: PosixRunCommand;
},
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
if (processIds.length === 0) return [];
const ports = new Set<number>();
const pidFilter = new Set(processIds);
const lsofResult = yield* input
.runCommand({
operation: "TerminalProcessInspector.checkPosixListeningPorts.lsof",
terminalPid: input.terminalPid,
command: "lsof",
args: ["-nP", "-a", "-iTCP", "-sTCP:LISTEN", "-p", processIds.join(",")],
timeoutMs: 1_500,
maxOutputBytes: 262_144,
})
.pipe(Effect.exit);
if (lsofResult._tag === "Success") {
if (lsofResult.value.exitCode === 1) {
return [];
}
if (lsofResult.value.exitCode === 0) {
for (const line of lsofResult.value.stdout.split(/\r?\n/g)) {
const match = line.match(/:(\d+)\s+\(LISTEN\)$/);
if (!match?.[1]) continue;
const port = Number(match[1]);
if (Number.isInteger(port) && port > 0 && port <= MAX_PORT_NUMBER) {
ports.add(port);
}
}
return [...ports].toSorted((left, right) => left - right);
}
}
const ssResult = yield* input.runCommand({
operation: "TerminalProcessInspector.checkPosixListeningPorts.ss",
terminalPid: input.terminalPid,
command: "ss",
args: ["-ltnp"],
timeoutMs: 1_500,
maxOutputBytes: 524_288,
});
if (ssResult.exitCode !== 0) {
return [];
}
for (const line of ssResult.stdout.split(/\r?\n/g)) {
if (!line.includes("pid=")) continue;
const localAddress = line.trim().split(/\s+/g)[3];
if (!localAddress) continue;
const port = portFromAddress(localAddress);
if (port === null) continue;
const pidMatches = [...line.matchAll(/pid=(\d+)/g)];
if (pidMatches.length === 0) continue;
if (
pidMatches.some((match) => {
const pid = Number(match[1]);
return Number.isInteger(pid) && pidFilter.has(pid);
})
) {
ports.add(port);
}
}
return [...ports].toSorted((left, right) => left - right);
});
+47
View File
@@ -0,0 +1,47 @@
import { MAX_PORT_NUMBER, normalizeRunningPorts } from "@t3tools/shared/port";
export { MAX_PORT_NUMBER, normalizeRunningPorts };
export function parsePidList(stdout: string): number[] {
const pids: number[] = [];
for (const line of stdout.split(/\r?\n/g)) {
const pid = Number(line.trim());
if (!Number.isInteger(pid) || pid <= 0) {
continue;
}
pids.push(pid);
}
return [...new Set(pids)];
}
export function parsePortList(stdout: string): number[] {
const ports: number[] = [];
for (const line of stdout.split(/\r?\n/g)) {
const port = Number(line.trim());
if (!Number.isInteger(port)) {
continue;
}
ports.push(port);
}
return normalizeRunningPorts(ports);
}
export function portFromAddress(address: string): number | null {
const match = address.match(/:(\d+)$/);
if (!match?.[1]) return null;
const port = Number(match[1]);
if (!Number.isInteger(port) || port <= 0 || port > MAX_PORT_NUMBER) {
return null;
}
return port;
}
export function arePortListsEqual(left: number[], right: number[]): boolean {
if (left.length !== right.length) return false;
for (let index = 0; index < left.length; index += 1) {
if (left[index] !== right[index]) {
return false;
}
}
return true;
}
+57
View File
@@ -0,0 +1,57 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import { collectWindowsChildPids } from "./win32";
function parentPidFromCommand(command: string | undefined): number {
return Number(/ParentProcessId = (\d+)/.exec(command ?? "")?.[1] ?? "0");
}
describe("process.collectWindowsChildPids", () => {
it.effect("walks the full descendant tree breadth-first", () =>
Effect.gen(function* () {
const commands: string[] = [];
const childMap = new Map<number, string>([
[100, "200\n300\n"],
[200, "400\n"],
[300, ""],
[400, ""],
]);
const childPids = yield* collectWindowsChildPids(100, (input) => {
const command = input.args[3] ?? "";
commands.push(command);
return Effect.succeed({
stdout: childMap.get(parentPidFromCommand(command)) ?? "",
stderr: "",
exitCode: 0,
});
});
assert.deepStrictEqual(childPids, [200, 300, 400]);
assert.equal(commands.length, 4);
}),
);
it.effect("deduplicates repeated descendants to avoid traversal loops", () =>
Effect.gen(function* () {
const childMap = new Map<number, string>([
[100, "200\n300\n"],
[200, "300\n400\n"],
[300, "200\n"],
[400, ""],
]);
const childPids = yield* collectWindowsChildPids(100, (input) => {
const parentPid = parentPidFromCommand(input.args[3]);
return Effect.succeed({
stdout: childMap.get(parentPid) ?? "",
stderr: "",
exitCode: 0,
});
});
assert.deepStrictEqual(childPids, [200, 300, 400]);
}),
);
});
+98
View File
@@ -0,0 +1,98 @@
import { Effect } from "effect";
import type { TerminalProcessInspectionError } from "./Services/TerminalProcessInspector";
import { parsePidList, parsePortList } from "./utils";
interface InspectorCommandResult {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: number;
}
interface WindowsRunCommand {
(
input: Readonly<{
operation: string;
terminalPid: number;
command: string;
args: ReadonlyArray<string>;
timeoutMs: number;
maxOutputBytes: number;
}>,
): Effect.Effect<InspectorCommandResult, TerminalProcessInspectionError>;
}
export const collectWindowsChildPids = Effect.fn("process.collectWindowsChildPids")(function* (
terminalPid: number,
runCommand: WindowsRunCommand,
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
const seenPids = new Set<number>([terminalPid]);
const childPids: number[] = [];
const pendingParentPids = [terminalPid];
while (pendingParentPids.length > 0) {
const parentPid = pendingParentPids.shift();
if (parentPid === undefined) {
break;
}
const command = [
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${parentPid}" -ErrorAction SilentlyContinue`,
"if (-not $children) { exit 0 }",
"$children | Select-Object -ExpandProperty ProcessId",
].join("; ");
const result = yield* runCommand({
operation: "TerminalProcessInspector.collectWindowsChildPids",
terminalPid,
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeoutMs: 1_500,
maxOutputBytes: 32_768,
});
if (result.exitCode !== 0) {
continue;
}
for (const childPid of parsePidList(result.stdout)) {
if (seenPids.has(childPid)) {
continue;
}
seenPids.add(childPid);
childPids.push(childPid);
pendingParentPids.push(childPid);
}
}
return childPids;
});
export const checkWindowsListeningPorts = Effect.fn("process.checkWindowsListeningPorts")(
function* (
processIds: number[],
input: {
terminalPid: number;
runCommand: WindowsRunCommand;
},
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
if (processIds.length === 0) return [];
const processFilter = processIds.map((pid) => `$_.OwningProcess -eq ${pid}`).join(" -or ");
const command = [
"$connections = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue",
`$matching = $connections | Where-Object { ${processFilter} }`,
"if (-not $matching) { exit 0 }",
"$matching | Select-Object -ExpandProperty LocalPort -Unique",
].join("; ");
const result = yield* input.runCommand({
operation: "TerminalProcessInspector.checkWindowsListeningPorts",
terminalPid: input.terminalPid,
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeoutMs: 1_500,
maxOutputBytes: 65_536,
});
if (result.exitCode !== 0) {
return [];
}
return parsePortList(result.stdout);
},
);
+7 -1
View File
@@ -43,6 +43,8 @@ import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem"
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner";
import { ObservabilityLive } from "./observability/Layers/Observability";
import { TerminalProcessInspectorLive } from "./process/Layers/TerminalProcessInspector";
import { WebPortInspectorLive } from "./process/Layers/WebPortInspector";
const PtyAdapterLive = Layer.unwrap(
Effect.gen(function* () {
@@ -168,7 +170,11 @@ const GitLayerLive = Layer.empty.pipe(
Layer.provideMerge(GitCoreLive),
);
const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive));
const TerminalLayerLive = TerminalManagerLive.pipe(
Layer.provideMerge(WebPortInspectorLive),
Layer.provideMerge(TerminalProcessInspectorLive),
Layer.provide(PtyAdapterLive),
);
const WorkspaceLayerLive = Layer.mergeAll(
WorkspacePathsLive,
+66 -14
View File
@@ -1,7 +1,9 @@
import path from "node:path";
import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcessSpawner";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { FetchHttpClient } from "effect/unstable/http";
import {
DEFAULT_TERMINAL_ID,
type TerminalEvent,
@@ -15,6 +17,7 @@ import {
Exit,
Fiber,
FileSystem,
Layer,
Option,
PlatformError,
Ref,
@@ -24,6 +27,10 @@ import {
import { TestClock } from "effect/testing";
import { expect } from "vitest";
import { TerminalProcessInspectorLive } from "../../process/Layers/TerminalProcessInspector";
import { WebPortInspectorLive } from "../../process/Layers/WebPortInspector";
import { TerminalProcessInspector } from "../../process/Services/TerminalProcessInspector";
import { WebPortInspector } from "../../process/Services/WebPortInspector";
import type { TerminalManagerShape } from "../Services/Manager";
import {
type PtyAdapterShape,
@@ -188,7 +195,10 @@ function multiTerminalHistoryLogPath(
interface CreateManagerOptions {
shellResolver?: () => string;
subprocessChecker?: (terminalPid: number) => Effect.Effect<boolean>;
subprocessInspector?: (
terminalPid: number,
) => Effect.Effect<{ hasRunningSubprocess: boolean; runningPorts: number[] }>;
webPortInspector?: (port: number) => Effect.Effect<boolean>;
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
maxRetainedInactiveSessions?: number;
@@ -209,7 +219,7 @@ const createManager = (
): Effect.Effect<
ManagerFixture,
PlatformError.PlatformError,
FileSystem.FileSystem | Scope.Scope
FileSystem.FileSystem | Scope.Scope | TerminalProcessInspector | WebPortInspector
> =>
Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>
Effect.gen(function* () {
@@ -222,8 +232,11 @@ const createManager = (
historyLineLimit,
ptyAdapter,
...(options.shellResolver !== undefined ? { shellResolver: options.shellResolver } : {}),
...(options.subprocessChecker !== undefined
? { subprocessChecker: options.subprocessChecker }
...(options.subprocessInspector !== undefined
? { subprocessInspector: options.subprocessInspector }
: {}),
...(options.webPortInspector !== undefined
? { webPortInspector: options.webPortInspector }
: {}),
...(options.subprocessPollIntervalMs !== undefined
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
@@ -252,7 +265,16 @@ const createManager = (
}),
);
it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (it) => {
const nodeChildProcessLayer = NodeChildProcessSpawner.layer.pipe(Layer.provide(NodeServices.layer));
it.layer(
Layer.mergeAll(
NodeServices.layer,
WebPortInspectorLive.pipe(Layer.provide(FetchHttpClient.layer)),
TerminalProcessInspectorLive.pipe(Layer.provide(nodeChildProcessLayer)),
),
{ excludeTestServices: true },
)("TerminalManager", (it) => {
it.effect("spawns lazily and reuses running terminal per thread", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
@@ -548,29 +570,56 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
}),
);
it.effect("emits subprocess activity events when child-process state changes", () =>
it.effect("emits subprocess activity events when child-process state or web ports change", () =>
Effect.gen(function* () {
let hasRunningSubprocess = false;
let activity = {
hasRunningSubprocess: false,
runningPorts: [] as number[],
};
const { manager, getEvents } = yield* createManager(5, {
subprocessChecker: () => Effect.succeed(hasRunningSubprocess),
subprocessInspector: () => Effect.succeed(activity),
webPortInspector: (port) => Effect.succeed(port === 3000),
subprocessPollIntervalMs: 20,
});
yield* manager.open(openInput());
expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false);
hasRunningSubprocess = true;
activity = { hasRunningSubprocess: true, runningPorts: [3000] };
yield* waitFor(
Effect.map(getEvents, (events) =>
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true),
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === true &&
event.runningPorts.join(",") === "3000",
),
),
"1200 millis",
);
hasRunningSubprocess = false;
activity = { hasRunningSubprocess: true, runningPorts: [5173] };
yield* waitFor(
Effect.map(getEvents, (events) =>
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false),
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === true &&
event.runningPorts.length === 0,
),
),
"1200 millis",
);
activity = { hasRunningSubprocess: false, runningPorts: [5173] };
yield* waitFor(
Effect.map(getEvents, (events) =>
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === false &&
event.runningPorts.length === 0,
),
),
"1200 millis",
);
@@ -581,9 +630,12 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
Effect.gen(function* () {
let checks = 0;
const { manager } = yield* createManager(5, {
subprocessChecker: () => {
subprocessInspector: () => {
checks += 1;
return Effect.succeed(false);
return Effect.succeed({
hasRunningSubprocess: false,
runningPorts: [],
});
},
subprocessPollIntervalMs: 20,
});
+91 -122
View File
@@ -28,7 +28,17 @@ import {
terminalRestartsTotal,
terminalSessionsTotal,
} from "../../observability/Metrics";
import { runProcess } from "../../processRunner";
import { arePortListsEqual, normalizeRunningPorts } from "../../process/utils";
import {
TerminalProcessInspector,
type TerminalSubprocessActivity,
type TerminalSubprocessInspector,
} from "../../process/Services/TerminalProcessInspector";
import {
DEFAULT_WEB_PORT_PROBE_TTL_MS,
WebPortInspector,
type TerminalWebPortInspector,
} from "../../process/Services/WebPortInspector";
import {
TerminalCwdError,
TerminalHistoryError,
@@ -54,17 +64,6 @@ const DEFAULT_OPEN_COLS = 120;
const DEFAULT_OPEN_ROWS = 30;
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
type TerminalSubprocessChecker = (
terminalPid: number,
) => Effect.Effect<boolean, TerminalSubprocessCheckError>;
class TerminalSubprocessCheckError extends Data.TaggedError("TerminalSubprocessCheckError")<{
readonly message: string;
readonly cause?: unknown;
readonly terminalPid: number;
readonly command: "powershell" | "pgrep" | "ps";
}> {}
class TerminalProcessSignalError extends Data.TaggedError("TerminalProcessSignalError")<{
readonly message: string;
readonly cause?: unknown;
@@ -107,6 +106,7 @@ interface TerminalSessionState {
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
runningSubprocessPorts: number[];
runtimeEnv: Record<string, string> | null;
}
@@ -299,108 +299,6 @@ function isRetryableShellSpawnError(error: PtySpawnError): boolean {
);
}
function checkWindowsSubprocessActivity(
terminalPid: number,
): Effect.Effect<boolean, TerminalSubprocessCheckError> {
const command = [
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
"if ($children) { exit 0 }",
"exit 1",
].join("; ");
return Effect.tryPromise({
try: () =>
runProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
timeoutMs: 1_500,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to check Windows terminal subprocess activity.",
cause,
terminalPid,
command: "powershell",
}),
}).pipe(Effect.map((result) => result.code === 0));
}
const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessActivity")(function* (
terminalPid: number,
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
const runPgrep = Effect.tryPromise({
try: () =>
runProcess("pgrep", ["-P", String(terminalPid)], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with pgrep.",
cause,
terminalPid,
command: "pgrep",
}),
});
const runPs = Effect.tryPromise({
try: () =>
runProcess("ps", ["-eo", "pid=,ppid="], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 262_144,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with ps.",
cause,
terminalPid,
command: "ps",
}),
});
const pgrepResult = yield* Effect.exit(runPgrep);
if (pgrepResult._tag === "Success") {
if (pgrepResult.value.code === 0) {
return pgrepResult.value.stdout.trim().length > 0;
}
if (pgrepResult.value.code === 1) {
return false;
}
}
const psResult = yield* Effect.exit(runPs);
if (psResult._tag === "Failure" || psResult.value.code !== 0) {
return false;
}
for (const line of psResult.value.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
if (ppid === terminalPid) {
return true;
}
}
return false;
});
const defaultSubprocessChecker = Effect.fn("terminal.defaultSubprocessChecker")(function* (
terminalPid: number,
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return false;
}
if (process.platform === "win32") {
return yield* checkWindowsSubprocessActivity(terminalPid);
}
return yield* checkPosixSubprocessActivity(terminalPid);
});
function capHistory(history: string, maxLines: number): string {
if (history.length === 0) return history;
const hasTrailingNewline = history.endsWith("\n");
@@ -646,7 +544,9 @@ interface TerminalManagerOptions {
historyLineLimit?: number;
ptyAdapter: PtyAdapterShape;
shellResolver?: () => string;
subprocessChecker?: TerminalSubprocessChecker;
subprocessInspector?: TerminalSubprocessInspector;
webPortInspector?: TerminalWebPortInspector;
webPortProbeCacheTtlMs?: number;
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
maxRetainedInactiveSessions?: number;
@@ -670,12 +570,16 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
const logsDir = options.logsDir;
const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
const shellResolver = options.shellResolver ?? defaultShellResolver;
const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
const subprocessInspector =
options.subprocessInspector ?? (yield* TerminalProcessInspector).inspect;
const webPortInspector = options.webPortInspector ?? (yield* WebPortInspector).inspect;
const webPortProbeCacheTtlMs = options.webPortProbeCacheTtlMs ?? DEFAULT_WEB_PORT_PROBE_TTL_MS;
const subprocessPollIntervalMs =
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
const maxRetainedInactiveSessions =
options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS;
const webPortProbeCache = new Map<number, { isWeb: boolean; checkedAt: number }>();
yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie);
@@ -695,6 +599,55 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
}
});
const inspectWebPortCached = (port: number) =>
Effect.gen(function* () {
const now = Date.now();
for (const [cachedPort, entry] of webPortProbeCache) {
if (now - entry.checkedAt > webPortProbeCacheTtlMs) {
webPortProbeCache.delete(cachedPort);
}
}
const cached = webPortProbeCache.get(port);
if (cached) {
return cached.isWeb;
}
const isWeb = yield* webPortInspector(port).pipe(
Effect.map((result) => ({ result, probeSucceeded: true }) as const),
Effect.catch(() => Effect.succeed({ result: false, probeSucceeded: false } as const)),
);
if (isWeb.probeSucceeded) {
webPortProbeCache.set(port, {
isWeb: isWeb.result,
checkedAt: Date.now(),
});
}
return isWeb.result;
});
const detectWebPorts = (runningPorts: number[]) =>
Effect.gen(function* () {
if (runningPorts.length === 0) {
return [] as number[];
}
const checks = yield* Effect.forEach(
runningPorts,
(port) =>
Effect.map(inspectWebPortCached(port), (isWeb) => ({
port,
isWeb,
})),
{ concurrency: "unbounded" },
);
return checks
.filter((entry) => entry.isWeb)
.map((entry) => entry.port)
.toSorted((left, right) => left - right);
});
const historyPath = (threadId: string, terminalId: string) => {
const threadPart = toSafeThreadId(threadId);
if (terminalId === DEFAULT_TERMINAL_ID) {
@@ -1158,6 +1111,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.process = null;
session.pid = null;
session.hasRunningSubprocess = false;
session.runningSubprocessPorts = [];
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.pendingProcessEvents = [];
@@ -1225,6 +1179,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.process = null;
session.pid = null;
session.hasRunningSubprocess = false;
session.runningSubprocessPorts = [];
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.pendingProcessEvents = [];
@@ -1318,6 +1273,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.exitCode = null;
session.exitSignal = null;
session.hasRunningSubprocess = false;
session.runningSubprocessPorts = [];
session.pendingProcessEvents = [];
session.pendingProcessEventIndex = 0;
session.processEventDrainRunning = false;
@@ -1391,6 +1347,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.unsubscribeData = null;
session.unsubscribeExit = null;
session.hasRunningSubprocess = false;
session.runningSubprocessPorts = [];
session.pendingProcessEvents = [];
session.pendingProcessEventIndex = 0;
session.processEventDrainRunning = false;
@@ -1461,7 +1418,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session: TerminalSessionState & { pid: number },
) {
const terminalPid = session.pid;
const hasRunningSubprocess = yield* subprocessChecker(terminalPid).pipe(
const activity = yield* subprocessInspector(terminalPid).pipe(
Effect.map(Option.some),
Effect.catch((error) =>
Effect.logWarning("failed to check terminal subprocess activity", {
@@ -1469,14 +1426,21 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
terminalId: session.terminalId,
terminalPid,
error: error instanceof Error ? error.message : String(error),
}).pipe(Effect.as(Option.none<boolean>())),
}).pipe(Effect.as(Option.none<TerminalSubprocessActivity>())),
),
);
if (Option.isNone(hasRunningSubprocess)) {
if (Option.isNone(activity)) {
return;
}
const hasRunningSubprocess = activity.value.hasRunningSubprocess === true;
const runningPorts = hasRunningSubprocess
? normalizeRunningPorts(
yield* detectWebPorts(normalizeRunningPorts(activity.value.runningPorts)),
)
: [];
const event = yield* modifyManagerState((state) => {
const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
@@ -1485,12 +1449,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
Option.isNone(liveSession) ||
liveSession.value.status !== "running" ||
liveSession.value.pid !== terminalPid ||
liveSession.value.hasRunningSubprocess === hasRunningSubprocess.value
(liveSession.value.hasRunningSubprocess === hasRunningSubprocess &&
arePortListsEqual(liveSession.value.runningSubprocessPorts, runningPorts))
) {
return [Option.none(), state] as const;
}
liveSession.value.hasRunningSubprocess = hasRunningSubprocess.value;
liveSession.value.hasRunningSubprocess = hasRunningSubprocess;
liveSession.value.runningSubprocessPorts = runningPorts;
liveSession.value.updatedAt = new Date().toISOString();
return [
@@ -1499,7 +1465,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: liveSession.value.threadId,
terminalId: liveSession.value.terminalId,
createdAt: new Date().toISOString(),
hasRunningSubprocess: hasRunningSubprocess.value,
hasRunningSubprocess,
runningPorts,
}),
state,
] as const;
@@ -1598,6 +1565,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
runningSubprocessPorts: [],
runtimeEnv: normalizedRuntimeEnv(input.env),
};
@@ -1777,6 +1745,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
runningSubprocessPorts: [],
runtimeEnv: normalizedRuntimeEnv(input.env),
};
const createdSession = session;
@@ -51,6 +51,7 @@ export interface TerminalSessionState {
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
runningSubprocessPorts: number[];
runtimeEnv: Record<string, string> | null;
}
@@ -1406,6 +1406,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: [],
runningTerminalPorts: {},
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
+2
View File
@@ -558,6 +558,8 @@ function PersistentThreadTerminalDrawer({
activeTerminalId={terminalState.activeTerminalId}
terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={terminalState.activeTerminalGroupId}
runningTerminalIds={terminalState.runningTerminalIds}
runningTerminalPorts={terminalState.runningTerminalPorts}
focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
+61 -18
View File
@@ -4,6 +4,7 @@ import {
ChevronRightIcon,
FolderIcon,
GitPullRequestIcon,
GlobeIcon,
PlusIcon,
SettingsIcon,
SquarePenIcon,
@@ -60,6 +61,7 @@ import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
import { isTerminalFocused } from "../lib/terminalFocus";
import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils";
import { useStore } from "../store";
import { normalizeRunningPorts, portStatusLabel } from "@t3tools/shared/port";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { useUiStateStore } from "../uiStateStore";
import {
@@ -150,9 +152,10 @@ type SidebarProjectSnapshot = Project & {
expanded: boolean;
};
interface TerminalStatusIndicator {
label: "Terminal process running";
label: string;
colorClass: string;
pulse: boolean;
primaryWebPort: number | null;
}
interface PrStatusIndicator {
@@ -202,16 +205,27 @@ function ThreadStatusLabel({
);
}
function terminalStatusFromRunningIds(
function terminalStatusFromTerminalState(
runningTerminalIds: string[],
runningTerminalPorts: Record<string, number[]>,
): TerminalStatusIndicator | null {
if (runningTerminalIds.length === 0) {
return null;
}
const runningPorts = normalizeRunningPorts(
runningTerminalIds.flatMap((terminalId) => runningTerminalPorts[terminalId] ?? []),
);
const { label, primaryWebPort } = portStatusLabel(runningPorts);
return {
label: "Terminal process running",
colorClass: "text-teal-600 dark:text-teal-300/90",
label,
colorClass:
primaryWebPort === null
? "text-teal-600 dark:text-teal-300/90"
: "text-sky-600 dark:text-sky-300/90",
pulse: true,
primaryWebPort,
};
}
@@ -276,6 +290,7 @@ interface SidebarThreadRowProps {
commitRename: (threadId: ThreadId, newTitle: string, originalTitle: string) => Promise<void>;
cancelRename: () => void;
attemptArchiveThread: (threadId: ThreadId) => Promise<void>;
openWebPort: (event: MouseEvent<HTMLElement>, port: number) => void;
openPrLink: (event: MouseEvent<HTMLElement>, prUrl: string) => void;
pr: ThreadPr | null;
}
@@ -283,9 +298,8 @@ interface SidebarThreadRowProps {
function SidebarThreadRow(props: SidebarThreadRowProps) {
const thread = useSidebarThreadSummaryById(props.threadId);
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[props.threadId]);
const runningTerminalIds = useTerminalStateStore(
(state) =>
selectThreadTerminalState(state.terminalStateByThreadId, props.threadId).runningTerminalIds,
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadId, props.threadId),
);
if (!thread) {
@@ -304,7 +318,10 @@ function SidebarThreadRow(props: SidebarThreadRowProps) {
},
});
const prStatus = prStatusIndicator(props.pr);
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
const terminalStatus = terminalStatusFromTerminalState(
terminalState.runningTerminalIds,
terminalState.runningTerminalPorts,
);
const isConfirmingArchive = props.confirmingArchiveThreadId === thread.id && !isThreadRunning;
const threadMetaClassName = isConfirmingArchive
? "pointer-events-none opacity-0"
@@ -421,16 +438,29 @@ function SidebarThreadRow(props: SidebarThreadRowProps) {
)}
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
</span>
)}
{terminalStatus &&
(terminalStatus.primaryWebPort === null ? (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
</span>
) : (
<button
type="button"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center rounded-sm ${terminalStatus.colorClass} outline-hidden transition-colors hover:bg-accent hover:text-sky-700 focus-visible:ring-1 focus-visible:ring-ring dark:hover:text-sky-200`}
onClick={(event) => {
props.openWebPort(event, terminalStatus.primaryWebPort!);
}}
>
<GlobeIcon className="size-3" />
</button>
))}
<div className="flex min-w-12 justify-end">
{isConfirmingArchive ? (
<button
@@ -832,6 +862,18 @@ export default function Sidebar() {
});
}, []);
const openWebPort = useCallback((event: MouseEvent<HTMLElement>, port: number) => {
event.preventDefault();
event.stopPropagation();
const api = readNativeApi();
if (!api) {
return;
}
void api.shell.openExternal(`http://localhost:${port}`).catch(() => undefined);
}, []);
const attemptArchiveThread = useCallback(
async (threadId: ThreadId) => {
try {
@@ -1740,6 +1782,7 @@ export default function Sidebar() {
commitRename={commitRename}
cancelRename={cancelRename}
attemptArchiveThread={attemptArchiveThread}
openWebPort={openWebPort}
openPrLink={openPrLink}
pr={prByThreadId.get(threadId) ?? null}
/>
@@ -1,5 +1,5 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import { Globe, Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import {
type TerminalEvent,
type TerminalSessionSnapshot,
@@ -7,6 +7,7 @@ import {
} from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
type ReactNode,
useCallback,
@@ -32,6 +33,7 @@ import {
type ThreadTerminalGroup,
} from "../types";
import { readNativeApi } from "~/nativeApi";
import { normalizeRunningPorts, portStatusLabel, type PortStatusLabel } from "@t3tools/shared/port";
import { selectTerminalEventEntries, useTerminalStateStore } from "../terminalStateStore";
const MIN_DRAWER_HEIGHT = 180;
@@ -74,6 +76,19 @@ export function selectPendingTerminalEventEntries(
return entries.filter((entry) => entry.id > lastAppliedTerminalEventId);
}
function terminalRuntimeStatus(
terminalId: string,
runningTerminalIds: Set<string>,
runningTerminalPorts: Record<string, number[]>,
): PortStatusLabel | null {
if (!runningTerminalIds.has(terminalId)) {
return null;
}
const runningPorts = normalizeRunningPorts(runningTerminalPorts[terminalId]);
return portStatusLabel(runningPorts);
}
function terminalThemeFromApp(): ITheme {
const isDark = document.documentElement.classList.contains("dark");
const bodyStyles = getComputedStyle(document.body);
@@ -731,6 +746,8 @@ interface ThreadTerminalDrawerProps {
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
runningTerminalIds: string[];
runningTerminalPorts: Record<string, number[]>;
focusRequestId: number;
onSplitTerminal: () => void;
onNewTerminal: () => void;
@@ -783,6 +800,8 @@ export default function ThreadTerminalDrawer({
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
runningTerminalIds,
runningTerminalPorts,
focusRequestId,
onSplitTerminal,
onNewTerminal,
@@ -906,6 +925,10 @@ export default function ThreadTerminalDrawer({
),
[normalizedTerminalIds],
);
const runningTerminalIdSet = useMemo(
() => new Set(runningTerminalIds.map((terminalId) => terminalId.trim())),
[runningTerminalIds],
);
const splitTerminalActionLabel = hasReachedSplitLimit
? `Split Terminal (max ${MAX_TERMINALS_PER_GROUP} per group)`
: splitShortcutLabel
@@ -1027,6 +1050,14 @@ export default function ThreadTerminalDrawer({
};
}, [syncHeight]);
const openWebPort = useCallback((event: ReactMouseEvent<HTMLButtonElement>, port: number) => {
event.preventDefault();
event.stopPropagation();
const api = readNativeApi();
if (!api) return;
void api.shell.openExternal(`http://localhost:${port}`).catch(() => undefined);
}, []);
return (
<aside
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
@@ -1199,6 +1230,11 @@ export default function ThreadTerminalDrawer({
>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
const runtimeStatus = terminalRuntimeStatus(
terminalId,
runningTerminalIdSet,
runningTerminalPorts,
);
const closeTerminalLabel = `Close ${
terminalLabelById.get(terminalId) ?? "terminal"
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
@@ -1224,6 +1260,29 @@ export default function ThreadTerminalDrawer({
{terminalLabelById.get(terminalId) ?? "Terminal"}
</span>
</button>
{runtimeStatus &&
(runtimeStatus.primaryWebPort === null ? (
<span
role="img"
aria-label={runtimeStatus.label}
title={runtimeStatus.label}
className="inline-flex items-center justify-center text-teal-600 dark:text-teal-300/90"
>
<TerminalSquare className="size-2.5 animate-pulse" />
</span>
) : (
<button
type="button"
className="inline-flex items-center justify-center rounded p-0.5 text-sky-600 transition-colors hover:bg-accent hover:text-sky-700 dark:text-sky-300/90 dark:hover:text-sky-200"
onClick={(event) =>
openWebPort(event, runtimeStatus.primaryWebPort!)
}
aria-label={runtimeStatus.label}
title={runtimeStatus.label}
>
<Globe className="size-2.5 shrink-0" />
</button>
))}
{normalizedTerminalIds.length > 1 && (
<Popover>
<PopoverTrigger
+4 -8
View File
@@ -30,22 +30,25 @@ describe("terminalRunningSubprocessFromEvent", () => {
...eventBase(),
type: "activity",
hasRunningSubprocess: true,
runningPorts: [3000],
});
const idle = terminalRunningSubprocessFromEvent({
...eventBase(),
type: "activity",
hasRunningSubprocess: false,
runningPorts: [],
});
expect(active).toBe(true);
expect(idle).toBe(false);
});
it("clears running state when a terminal session starts/restarts/exits", () => {
it("clears running state when a terminal session starts/restarts/exits/errors", () => {
const events: TerminalEvent[] = [
{ ...eventBase(), type: "started", snapshot },
{ ...eventBase(), type: "restarted", snapshot },
{ ...eventBase(), type: "exited", exitCode: 0, exitSignal: null },
{ ...eventBase(), type: "error", message: "oops" },
];
for (const event of events) {
@@ -61,12 +64,5 @@ describe("terminalRunningSubprocessFromEvent", () => {
data: "hello",
}),
).toBeNull();
expect(
terminalRunningSubprocessFromEvent({
...eventBase(),
type: "error",
message: "oops",
}),
).toBeNull();
});
});
+1
View File
@@ -7,6 +7,7 @@ export function terminalRunningSubprocessFromEvent(event: TerminalEvent): boolea
case "started":
case "restarted":
case "exited":
case "error":
return false;
default:
return null;
+51 -15
View File
@@ -23,7 +23,13 @@ function makeTerminalEvent(
case "output":
return { ...base, type, data: "hello\n", ...overrides } as TerminalEvent;
case "activity":
return { ...base, type, hasRunningSubprocess: true, ...overrides } as TerminalEvent;
return {
...base,
type,
hasRunningSubprocess: true,
runningPorts: [],
...overrides,
} as TerminalEvent;
case "error":
return { ...base, type, message: "boom", ...overrides } as TerminalEvent;
case "cleared":
@@ -73,12 +79,34 @@ describe("terminalStateStore actions", () => {
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: [],
runningTerminalPorts: {},
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
});
});
it("normalizes legacy persisted thread terminal state at selector boundaries", () => {
const terminalState = selectThreadTerminalState(
{
[THREAD_ID]: {
terminalOpen: true,
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: ["default", "default"],
runningTerminalPorts: { default: [5173, 3000, 5173, 0] },
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
},
},
THREAD_ID,
);
expect(terminalState.runningTerminalIds).toEqual(["default"]);
expect(terminalState.runningTerminalPorts).toEqual({ default: [3000, 5173] });
});
it("opens and splits terminals into the active group", () => {
const store = useTerminalStateStore.getState();
store.setTerminalOpen(THREAD_ID, true);
@@ -181,17 +209,21 @@ describe("terminalStateStore actions", () => {
it("tracks and clears terminal subprocess activity", () => {
const store = useTerminalStateStore.getState();
store.splitTerminal(THREAD_ID, "terminal-2");
store.setTerminalActivity(THREAD_ID, "terminal-2", true);
expect(
selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)
.runningTerminalIds,
).toEqual(["terminal-2"]);
store.setTerminalActivity(THREAD_ID, "terminal-2", true, [5173, 3000, 5173]);
let terminalState = selectThreadTerminalState(
useTerminalStateStore.getState().terminalStateByThreadId,
THREAD_ID,
);
expect(terminalState.runningTerminalIds).toEqual(["terminal-2"]);
expect(terminalState.runningTerminalPorts).toEqual({ "terminal-2": [3000, 5173] });
store.setTerminalActivity(THREAD_ID, "terminal-2", false);
expect(
selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)
.runningTerminalIds,
).toEqual([]);
terminalState = selectThreadTerminalState(
useTerminalStateStore.getState().terminalStateByThreadId,
THREAD_ID,
);
expect(terminalState.runningTerminalIds).toEqual([]);
expect(terminalState.runningTerminalPorts).toEqual({});
});
it("resets to default and clears persisted entry when closing the last terminal", () => {
@@ -287,12 +319,15 @@ describe("terminalStateStore actions", () => {
makeTerminalEvent("activity", {
terminalId: "terminal-2",
hasRunningSubprocess: true,
runningPorts: [5173, 3000],
}),
);
expect(
selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)
.runningTerminalIds,
).toEqual(["terminal-2"]);
let terminalState = selectThreadTerminalState(
useTerminalStateStore.getState().terminalStateByThreadId,
THREAD_ID,
);
expect(terminalState.runningTerminalIds).toEqual(["terminal-2"]);
expect(terminalState.runningTerminalPorts).toEqual({ "terminal-2": [3000, 5173] });
store.applyTerminalEvent(
makeTerminalEvent("exited", {
@@ -302,7 +337,7 @@ describe("terminalStateStore actions", () => {
}),
);
const terminalState = selectThreadTerminalState(
terminalState = selectThreadTerminalState(
useTerminalStateStore.getState().terminalStateByThreadId,
THREAD_ID,
);
@@ -313,6 +348,7 @@ describe("terminalStateStore actions", () => {
);
expect(terminalState.runningTerminalIds).toEqual([]);
expect(terminalState.runningTerminalPorts).toEqual({});
expect(entries.map((entry) => entry.event.type)).toEqual(["activity", "exited"]);
});
+74 -7
View File
@@ -6,6 +6,8 @@
*/
import { ThreadId, type TerminalEvent } from "@t3tools/contracts";
import { normalizeRunningPorts } from "@t3tools/shared/port";
export { normalizeRunningPorts } from "@t3tools/shared/port";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { resolveStorage } from "./lib/storage";
@@ -22,6 +24,7 @@ interface ThreadTerminalState {
terminalHeight: number;
terminalIds: string[];
runningTerminalIds: string[];
runningTerminalPorts: Record<string, number[]>;
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
@@ -61,6 +64,23 @@ function normalizeRunningTerminalIds(
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
}
function normalizeRunningTerminalPorts(
runningTerminalPorts: Record<string, number[]> | undefined,
terminalIds: string[],
): Record<string, number[]> {
if (!runningTerminalPorts) return {};
const validTerminalIdSet = new Set(terminalIds);
const normalizedEntries: Array<[string, number[]]> = [];
for (const [rawTerminalId, ports] of Object.entries(runningTerminalPorts)) {
const terminalId = rawTerminalId.trim();
if (terminalId.length === 0 || !validTerminalIdSet.has(terminalId)) {
continue;
}
normalizedEntries.push([terminalId, normalizeRunningPorts(ports)]);
}
return Object.fromEntries(normalizedEntries);
}
function fallbackGroupId(terminalId: string): string {
return `group-${terminalId}`;
}
@@ -136,7 +156,7 @@ function normalizeTerminalGroups(
return nextGroups;
}
function arraysEqual(a: string[], b: string[]): boolean {
function arraysEqual<T>(a: readonly T[], b: readonly T[]): boolean {
if (a.length !== b.length) return false;
for (let index = 0; index < a.length; index += 1) {
if (a[index] !== b[index]) return false;
@@ -156,6 +176,22 @@ function terminalGroupsEqual(left: ThreadTerminalGroup[], right: ThreadTerminalG
return true;
}
function runningTerminalPortsEqual(
left: Record<string, number[]>,
right: Record<string, number[]>,
): boolean {
const leftEntries = Object.entries(left);
const rightEntries = Object.entries(right);
if (leftEntries.length !== rightEntries.length) return false;
for (const [terminalId, leftPorts] of leftEntries) {
const rightPorts = right[terminalId];
if (!rightPorts || !arraysEqual(leftPorts, rightPorts)) {
return false;
}
}
return true;
}
function threadTerminalStateEqual(left: ThreadTerminalState, right: ThreadTerminalState): boolean {
return (
left.terminalOpen === right.terminalOpen &&
@@ -164,6 +200,7 @@ function threadTerminalStateEqual(left: ThreadTerminalState, right: ThreadTermin
left.activeTerminalGroupId === right.activeTerminalGroupId &&
arraysEqual(left.terminalIds, right.terminalIds) &&
arraysEqual(left.runningTerminalIds, right.runningTerminalIds) &&
runningTerminalPortsEqual(left.runningTerminalPorts, right.runningTerminalPorts) &&
terminalGroupsEqual(left.terminalGroups, right.terminalGroups)
);
}
@@ -173,6 +210,7 @@ const DEFAULT_THREAD_TERMINAL_STATE: ThreadTerminalState = Object.freeze({
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
runningTerminalPorts: {},
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
@@ -188,6 +226,7 @@ function createDefaultThreadTerminalState(): ThreadTerminalState {
...DEFAULT_THREAD_TERMINAL_STATE,
terminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.terminalIds],
runningTerminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.runningTerminalIds],
runningTerminalPorts: { ...DEFAULT_THREAD_TERMINAL_STATE.runningTerminalPorts },
terminalGroups: copyTerminalGroups(DEFAULT_THREAD_TERMINAL_STATE.terminalGroups),
};
}
@@ -200,6 +239,10 @@ function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTermina
const terminalIds = normalizeTerminalIds(state.terminalIds);
const nextTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
const runningTerminalIds = normalizeRunningTerminalIds(state.runningTerminalIds, nextTerminalIds);
const runningTerminalPorts = normalizeRunningTerminalPorts(
state.runningTerminalPorts,
nextTerminalIds,
);
const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
? state.activeTerminalId
: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
@@ -220,6 +263,7 @@ function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTermina
: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: nextTerminalIds,
runningTerminalIds,
runningTerminalPorts,
activeTerminalId,
terminalGroups,
activeTerminalGroupId:
@@ -455,6 +499,9 @@ function closeThreadTerminal(state: ThreadTerminalState, terminalId: string): Th
terminalHeight: normalized.terminalHeight,
terminalIds: remainingTerminalIds,
runningTerminalIds: normalized.runningTerminalIds.filter((id) => id !== terminalId),
runningTerminalPorts: Object.fromEntries(
Object.entries(normalized.runningTerminalPorts).filter(([key]) => key !== terminalId),
),
activeTerminalId: nextActiveTerminalId,
terminalGroups,
activeTerminalGroupId: nextActiveTerminalGroupId,
@@ -465,22 +512,35 @@ function setThreadTerminalActivity(
state: ThreadTerminalState,
terminalId: string,
hasRunningSubprocess: boolean,
runningPorts: readonly number[] = [],
): ThreadTerminalState {
const normalized = normalizeThreadTerminalState(state);
if (!normalized.terminalIds.includes(terminalId)) {
return normalized;
}
const alreadyRunning = normalized.runningTerminalIds.includes(terminalId);
if (hasRunningSubprocess === alreadyRunning) {
const nextRunningPorts = normalizeRunningPorts(runningPorts);
const currentRunningPorts = normalized.runningTerminalPorts[terminalId] ?? [];
if (
hasRunningSubprocess === alreadyRunning &&
arraysEqual(currentRunningPorts, nextRunningPorts)
) {
return normalized;
}
const runningTerminalIds = new Set(normalized.runningTerminalIds);
const runningTerminalPorts = { ...normalized.runningTerminalPorts };
if (hasRunningSubprocess) {
runningTerminalIds.add(terminalId);
runningTerminalPorts[terminalId] = nextRunningPorts;
} else {
runningTerminalIds.delete(terminalId);
delete runningTerminalPorts[terminalId];
}
return { ...normalized, runningTerminalIds: [...runningTerminalIds] };
return {
...normalized,
runningTerminalIds: [...runningTerminalIds],
runningTerminalPorts,
};
}
export function selectThreadTerminalState(
@@ -490,7 +550,8 @@ export function selectThreadTerminalState(
if (threadId.length === 0) {
return getDefaultThreadTerminalState();
}
return terminalStateByThreadId[threadId] ?? getDefaultThreadTerminalState();
const state = terminalStateByThreadId[threadId];
return state ? normalizeThreadTerminalState(state) : getDefaultThreadTerminalState();
}
function updateTerminalStateByThreadId(
@@ -558,6 +619,7 @@ interface TerminalStateStoreState {
threadId: ThreadId,
terminalId: string,
hasRunningSubprocess: boolean,
runningPorts?: readonly number[],
) => void;
recordTerminalEvent: (event: TerminalEvent) => void;
applyTerminalEvent: (event: TerminalEvent) => void;
@@ -641,9 +703,9 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
const { [threadId]: _removed, ...rest } = state.terminalLaunchContextByThreadId;
return { terminalLaunchContextByThreadId: rest };
}),
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess, runningPorts) =>
updateTerminal(threadId, (state) =>
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess),
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess, runningPorts),
),
recordTerminalEvent: (event) =>
set((state) =>
@@ -685,7 +747,12 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
nextTerminalStateByThreadId,
threadId,
(current) =>
setThreadTerminalActivity(current, event.terminalId, hasRunningSubprocess),
setThreadTerminalActivity(
current,
event.terminalId,
hasRunningSubprocess,
event.type === "activity" ? event.runningPorts : [],
),
);
}
+1
View File
@@ -205,6 +205,7 @@ describe("TerminalEvent", () => {
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(),
hasRunningSubprocess: true,
runningPorts: [3000],
}),
).toBe(true);
});
+2 -1
View File
@@ -10,6 +10,7 @@ const TerminalColsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(20)).c
const TerminalRowsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(5)).check(
Schema.isLessThanOrEqualTo(200),
);
const TerminalPortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65_535 }));
const TerminalIdSchema = TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(128));
const TerminalEnvKeySchema = Schema.String.check(
Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/),
@@ -140,8 +141,8 @@ const TerminalActivityEvent = Schema.Struct({
...TerminalEventBaseSchema.fields,
type: Schema.Literal("activity"),
hasRunningSubprocess: Schema.Boolean,
runningPorts: Schema.Array(TerminalPortSchema),
});
export const TerminalEvent = Schema.Union([
TerminalStartedEvent,
TerminalOutputEvent,
+4
View File
@@ -51,6 +51,10 @@
"./projectScripts": {
"types": "./src/projectScripts.ts",
"import": "./src/projectScripts.ts"
},
"./port": {
"types": "./src/port.ts",
"import": "./src/port.ts"
}
},
"scripts": {
+24
View File
@@ -0,0 +1,24 @@
export const MAX_PORT_NUMBER = 65_535;
export function normalizeRunningPorts(ports: readonly number[] | undefined): number[] {
if (!ports || ports.length === 0) return [];
return [...new Set(ports)]
.filter((port) => Number.isInteger(port) && port > 0 && port <= MAX_PORT_NUMBER)
.toSorted((left, right) => left - right);
}
export interface PortStatusLabel {
label: string;
primaryWebPort: number | null;
}
export function portStatusLabel(runningPorts: readonly number[]): PortStatusLabel {
const primaryWebPort = runningPorts[0] ?? null;
const label =
runningPorts.length === 0
? "Terminal process running"
: runningPorts.length === 1
? `Open web server: http://localhost:${primaryWebPort}`
: `Open web server: http://localhost:${primaryWebPort} (detected web ports: ${runningPorts.join(", ")})`;
return { label, primaryWebPort };
}