Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1ad5fac52 | ||
|
|
da81a167ea | ||
|
|
0236cc845e | ||
|
|
6aac79caff | ||
|
|
bc30ac51f5 | ||
|
|
75ae12f6f7 |
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",
|
||||
) {}
|
||||
@@ -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);
|
||||
});
|
||||
+2
-7
@@ -1,11 +1,6 @@
|
||||
export const MAX_PORT_NUMBER = 65_535;
|
||||
import { MAX_PORT_NUMBER, normalizeRunningPorts } from "@t3tools/shared/port";
|
||||
|
||||
export function normalizeRunningPorts(ports: number[]): number[] {
|
||||
if (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 { MAX_PORT_NUMBER, normalizeRunningPorts };
|
||||
|
||||
export function parsePidList(stdout: string): number[] {
|
||||
const pids: number[] = [];
|
||||
@@ -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]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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);
|
||||
},
|
||||
);
|
||||
@@ -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,
|
||||
|
||||
@@ -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,6 @@ function multiTerminalHistoryLogPath(
|
||||
|
||||
interface CreateManagerOptions {
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: (terminalPid: number) => Effect.Effect<boolean>;
|
||||
subprocessInspector?: (
|
||||
terminalPid: number,
|
||||
) => Effect.Effect<{ hasRunningSubprocess: boolean; runningPorts: number[] }>;
|
||||
@@ -213,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* () {
|
||||
@@ -226,9 +232,6 @@ const createManager = (
|
||||
historyLineLimit,
|
||||
ptyAdapter,
|
||||
...(options.shellResolver !== undefined ? { shellResolver: options.shellResolver } : {}),
|
||||
...(options.subprocessChecker !== undefined
|
||||
? { subprocessChecker: options.subprocessChecker }
|
||||
: {}),
|
||||
...(options.subprocessInspector !== undefined
|
||||
? { subprocessInspector: options.subprocessInspector }
|
||||
: {}),
|
||||
@@ -262,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();
|
||||
@@ -618,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,
|
||||
});
|
||||
|
||||
@@ -28,12 +28,17 @@ import {
|
||||
terminalRestartsTotal,
|
||||
terminalSessionsTotal,
|
||||
} from "../../observability/Metrics";
|
||||
import { arePortListsEqual, normalizeRunningPorts } from "../../process/utils";
|
||||
import {
|
||||
arePortListsEqual,
|
||||
defaultSubprocessInspector,
|
||||
normalizeRunningPorts,
|
||||
} from "../../terminalProcessInspector";
|
||||
import { DEFAULT_WEB_PORT_PROBE_TTL_MS, defaultWebPortInspector } from "../../webPortInspector";
|
||||
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,
|
||||
@@ -59,25 +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>;
|
||||
type TerminalSubprocessActivity = {
|
||||
hasRunningSubprocess: boolean;
|
||||
runningPorts: number[];
|
||||
};
|
||||
type TerminalSubprocessInspector = (
|
||||
terminalPid: number,
|
||||
) => Effect.Effect<TerminalSubprocessActivity, TerminalSubprocessCheckError>;
|
||||
type TerminalWebPortInspector = (port: number) => Effect.Effect<boolean>;
|
||||
|
||||
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;
|
||||
@@ -558,7 +544,6 @@ interface TerminalManagerOptions {
|
||||
historyLineLimit?: number;
|
||||
ptyAdapter: PtyAdapterShape;
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: TerminalSubprocessChecker;
|
||||
subprocessInspector?: TerminalSubprocessInspector;
|
||||
webPortInspector?: TerminalWebPortInspector;
|
||||
webPortProbeCacheTtlMs?: number;
|
||||
@@ -586,31 +571,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
|
||||
const shellResolver = options.shellResolver ?? defaultShellResolver;
|
||||
const subprocessInspector =
|
||||
options.subprocessInspector ??
|
||||
(options.subprocessChecker
|
||||
? (terminalPid: number) =>
|
||||
Effect.map(options.subprocessChecker!(terminalPid), (hasRunningSubprocess) => ({
|
||||
hasRunningSubprocess,
|
||||
runningPorts: [],
|
||||
}))
|
||||
: (terminalPid: number) =>
|
||||
Effect.tryPromise({
|
||||
try: () => defaultSubprocessInspector(terminalPid),
|
||||
catch: (cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to inspect terminal subprocess activity",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: process.platform === "win32" ? "powershell" : "ps",
|
||||
}),
|
||||
}));
|
||||
const webPortInspector =
|
||||
options.webPortInspector ??
|
||||
((port: number) =>
|
||||
Effect.tryPromise({
|
||||
try: () => defaultWebPortInspector(port),
|
||||
catch: () => false,
|
||||
}));
|
||||
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;
|
||||
@@ -640,17 +602,28 @@ 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 && now - cached.checkedAt <= webPortProbeCacheTtlMs) {
|
||||
if (cached) {
|
||||
return cached.isWeb;
|
||||
}
|
||||
|
||||
const isWeb = yield* webPortInspector(port).pipe(Effect.catch(() => Effect.succeed(false)));
|
||||
webPortProbeCache.set(port, {
|
||||
isWeb,
|
||||
checkedAt: Date.now(),
|
||||
});
|
||||
return 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[]) =>
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
import { spawn, type ChildProcess, type ChildProcessByStdio } from "node:child_process";
|
||||
import type { Readable } from "node:stream";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { defaultSubprocessInspector } from "./index";
|
||||
|
||||
type ListenerProcess = ChildProcessByStdio<null, Readable, Readable>;
|
||||
|
||||
interface StartedProcess {
|
||||
process: ListenerProcess;
|
||||
port: number;
|
||||
}
|
||||
|
||||
async function waitForPort(child: ListenerProcess): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(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();
|
||||
resolve(port);
|
||||
};
|
||||
|
||||
const onStderr = (chunk: Buffer) => {
|
||||
stderr += chunk.toString("utf8");
|
||||
};
|
||||
|
||||
const onExit = (code: number | null) => {
|
||||
cleanup();
|
||||
reject(
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
async function startListenerProcess(): Promise<StartedProcess> {
|
||||
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 = await waitForPort(process);
|
||||
return { process, port };
|
||||
}
|
||||
|
||||
async function stopProcess(child: ChildProcess): Promise<void> {
|
||||
if (child.exitCode !== null || child.signalCode !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
child.kill("SIGTERM");
|
||||
await new Promise<void>((resolve) => {
|
||||
const timeout = setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}, 1_000);
|
||||
child.once("exit", () => {
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
describe("defaultSubprocessInspector", () => {
|
||||
const spawned: ChildProcess[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(spawned.splice(0, spawned.length).map((child) => stopProcess(child)));
|
||||
});
|
||||
|
||||
it("detects listening ports when the terminal root PID is the listener", async () => {
|
||||
const listener = await startListenerProcess();
|
||||
spawned.push(listener.process);
|
||||
const listenerPid = listener.process.pid;
|
||||
if (!listenerPid) {
|
||||
throw new Error("Listener process pid missing");
|
||||
}
|
||||
|
||||
const activity = await defaultSubprocessInspector(listenerPid);
|
||||
|
||||
expect(activity.hasRunningSubprocess).toBe(true);
|
||||
expect(activity.runningPorts).toContain(listener.port);
|
||||
});
|
||||
|
||||
it("returns idle activity when root process has no children and no listening ports", async () => {
|
||||
const idle = spawn("node", ["-e", "setInterval(() => {}, 10_000)"], {
|
||||
stdio: ["ignore", "ignore", "ignore"],
|
||||
});
|
||||
spawned.push(idle);
|
||||
const idlePid = idle.pid;
|
||||
if (!idlePid) {
|
||||
throw new Error("Idle process pid missing");
|
||||
}
|
||||
|
||||
const activity = await defaultSubprocessInspector(idlePid);
|
||||
|
||||
expect(activity.hasRunningSubprocess).toBe(false);
|
||||
expect(activity.runningPorts).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
import { collectPosixProcessFamilyPids, checkPosixListeningPorts } from "./posix";
|
||||
import {
|
||||
type TerminalSubprocessActivity,
|
||||
type TerminalSubprocessChecker,
|
||||
type TerminalSubprocessInspector,
|
||||
type TerminalWebPortInspector,
|
||||
} from "./types";
|
||||
import { checkWindowsListeningPorts, collectWindowsChildPids } from "./win32";
|
||||
|
||||
export { arePortListsEqual, normalizeRunningPorts } from "./utils";
|
||||
|
||||
export type {
|
||||
TerminalSubprocessActivity,
|
||||
TerminalSubprocessChecker,
|
||||
TerminalSubprocessInspector,
|
||||
TerminalWebPortInspector,
|
||||
} from "./types";
|
||||
|
||||
export async function defaultSubprocessInspector(
|
||||
terminalPid: number,
|
||||
): Promise<TerminalSubprocessActivity> {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return { hasRunningSubprocess: false, runningPorts: [] };
|
||||
}
|
||||
|
||||
if (process.platform === "win32") {
|
||||
const childPids = await collectWindowsChildPids(terminalPid);
|
||||
const processPidsForPortScan = [terminalPid, ...childPids];
|
||||
const runningPorts = await checkWindowsListeningPorts(processPidsForPortScan);
|
||||
return {
|
||||
hasRunningSubprocess: childPids.length > 0 || runningPorts.length > 0,
|
||||
runningPorts,
|
||||
};
|
||||
}
|
||||
|
||||
const processFamilyPids = await collectPosixProcessFamilyPids(terminalPid);
|
||||
if (processFamilyPids.length === 0) {
|
||||
return { hasRunningSubprocess: false, runningPorts: [] };
|
||||
}
|
||||
|
||||
const subprocessPids = processFamilyPids.filter((pid) => pid !== terminalPid);
|
||||
const runningPorts = await checkPosixListeningPorts(processFamilyPids);
|
||||
return {
|
||||
hasRunningSubprocess: subprocessPids.length > 0 || runningPorts.length > 0,
|
||||
runningPorts,
|
||||
};
|
||||
}
|
||||
|
||||
export function subprocessCheckerToInspector(
|
||||
subprocessChecker: TerminalSubprocessChecker,
|
||||
): TerminalSubprocessInspector {
|
||||
return async (terminalPid: number) => ({
|
||||
hasRunningSubprocess: await subprocessChecker(terminalPid),
|
||||
runningPorts: [],
|
||||
});
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
import { runProcess } from "../processRunner";
|
||||
import { MAX_PORT_NUMBER, portFromAddress } from "./utils";
|
||||
|
||||
export async function collectPosixProcessFamilyPids(terminalPid: number): Promise<number[]> {
|
||||
try {
|
||||
const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], {
|
||||
timeoutMs: 1_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
if (psResult.code !== 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];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkPosixListeningPorts(processIds: number[]): Promise<number[]> {
|
||||
if (processIds.length === 0) return [];
|
||||
|
||||
const ports = new Set<number>();
|
||||
const pidFilter = new Set(processIds);
|
||||
|
||||
try {
|
||||
const result = await runProcess(
|
||||
"lsof",
|
||||
["-nP", "-a", "-iTCP", "-sTCP:LISTEN", "-p", processIds.join(",")],
|
||||
{
|
||||
timeoutMs: 1_500,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
);
|
||||
if (result.code !== 0) {
|
||||
// `lsof` returns 1 when there are no matching files/sockets.
|
||||
// This is a valid "no results" outcome; avoid falling back to `ss`.
|
||||
return [];
|
||||
}
|
||||
|
||||
for (const line of result.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);
|
||||
} catch {
|
||||
// Fall back to ss if lsof is unavailable.
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await runProcess("ss", ["-ltnp"], {
|
||||
timeoutMs: 1_500,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 524_288,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
for (const line of result.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);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
export type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||
|
||||
export type TerminalWebPortInspector = (port: number) => Promise<boolean>;
|
||||
|
||||
export interface TerminalSubprocessActivity {
|
||||
hasRunningSubprocess: boolean;
|
||||
runningPorts: number[];
|
||||
}
|
||||
|
||||
export type TerminalSubprocessInspector = (
|
||||
terminalPid: number,
|
||||
) => Promise<TerminalSubprocessActivity>;
|
||||
@@ -1,58 +0,0 @@
|
||||
import { runProcess } from "../processRunner";
|
||||
import { parsePidList, parsePortList } from "./utils";
|
||||
|
||||
export async function collectWindowsChildPids(terminalPid: number): Promise<number[]> {
|
||||
const command = [
|
||||
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
|
||||
"if (-not $children) { exit 0 }",
|
||||
"$children | Select-Object -ExpandProperty ProcessId",
|
||||
].join("; ");
|
||||
try {
|
||||
const result = await runProcess(
|
||||
"powershell.exe",
|
||||
["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
{
|
||||
timeoutMs: 1_500,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
);
|
||||
if (result.code !== 0) {
|
||||
return [];
|
||||
}
|
||||
return parsePidList(result.stdout);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkWindowsListeningPorts(processIds: number[]): Promise<number[]> {
|
||||
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("; ");
|
||||
try {
|
||||
const result = await runProcess(
|
||||
"powershell.exe",
|
||||
["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
{
|
||||
timeoutMs: 1_500,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 65_536,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
);
|
||||
if (result.code !== 0) {
|
||||
return [];
|
||||
}
|
||||
return parsePortList(result.stdout);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
import { createServer, type Server } from "node:http";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { defaultWebPortInspector } from "./webPortInspector";
|
||||
|
||||
async function listenServer(server: Server): Promise<number> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.listen(0, "127.0.0.1", (error?: Error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
const address = server.address();
|
||||
if (!address || typeof address !== "object") {
|
||||
throw new Error("Server did not provide a valid listening address.");
|
||||
}
|
||||
return address.port;
|
||||
}
|
||||
|
||||
async function closeServer(server: Server): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error?: Error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
describe("defaultWebPortInspector", () => {
|
||||
const servers: Server[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(servers.splice(0, servers.length).map((server) => closeServer(server)));
|
||||
});
|
||||
|
||||
it("treats slow HTML responses as web ports", async () => {
|
||||
const server = createServer((_req, res) => {
|
||||
setTimeout(() => {
|
||||
res.statusCode = 200;
|
||||
res.setHeader("content-type", "text/html; charset=utf-8");
|
||||
res.end("<!DOCTYPE html><html><head><title>ok</title></head><body>hello</body></html>");
|
||||
}, 800);
|
||||
});
|
||||
servers.push(server);
|
||||
const port = await listenServer(server);
|
||||
|
||||
await expect(defaultWebPortInspector(port)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("treats HTML responses with large bodies as web ports", async () => {
|
||||
const server = createServer((_req, res) => {
|
||||
res.statusCode = 200;
|
||||
res.setHeader("content-type", "text/html; charset=utf-8");
|
||||
res.end(
|
||||
`<!DOCTYPE html><html><head><title>x</title></head><body>${"x".repeat(20_000)}</body></html>`,
|
||||
);
|
||||
});
|
||||
servers.push(server);
|
||||
const port = await listenServer(server);
|
||||
|
||||
await expect(defaultWebPortInspector(port)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("ignores HTTP 404 responses", async () => {
|
||||
const server = createServer((_req, res) => {
|
||||
res.statusCode = 404;
|
||||
res.end();
|
||||
});
|
||||
servers.push(server);
|
||||
const port = await listenServer(server);
|
||||
|
||||
await expect(defaultWebPortInspector(port)).resolves.toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,132 +0,0 @@
|
||||
import { request as httpRequest } from "node:http";
|
||||
|
||||
export const DEFAULT_WEB_PORT_PROBE_TTL_MS = 10_000;
|
||||
const DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS = 2_000;
|
||||
const WEB_PORT_PROBE_MAX_BODY_BYTES = 8_192;
|
||||
|
||||
interface WebProbeResult {
|
||||
status: number;
|
||||
contentType: string;
|
||||
body: string;
|
||||
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");
|
||||
}
|
||||
|
||||
async function probeWebPortOnHost(port: number, host: string): Promise<WebProbeResult | null> {
|
||||
return new Promise((resolve) => {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let settled = false;
|
||||
const settle = (result: WebProbeResult | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
const req = httpRequest(
|
||||
{
|
||||
host,
|
||||
port,
|
||||
method: "GET",
|
||||
path: "/",
|
||||
timeout: DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS,
|
||||
},
|
||||
(res) => {
|
||||
const status = res.statusCode ?? 0;
|
||||
const contentType = normalizeHeaderValue(res.headers["content-type"]);
|
||||
const location = normalizeHeaderValue(res.headers.location);
|
||||
|
||||
const settleFromChunks = (chunks: string[]) => {
|
||||
settle({
|
||||
status,
|
||||
contentType,
|
||||
location,
|
||||
body: chunks.join(""),
|
||||
});
|
||||
};
|
||||
|
||||
// Resolve immediately for clear web responses based on status/headers.
|
||||
if (
|
||||
(status >= 300 && status < 400 && location.length > 0) ||
|
||||
contentType.toLowerCase().includes("text/html") ||
|
||||
contentType.toLowerCase().includes("application/xhtml+xml")
|
||||
) {
|
||||
settle({
|
||||
status,
|
||||
contentType,
|
||||
location,
|
||||
body: "",
|
||||
});
|
||||
req.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks: string[] = [];
|
||||
let received = 0;
|
||||
res.setEncoding("utf8");
|
||||
res.on("data", (chunk: string) => {
|
||||
if (received >= WEB_PORT_PROBE_MAX_BODY_BYTES) return;
|
||||
const remaining = WEB_PORT_PROBE_MAX_BODY_BYTES - received;
|
||||
const fragment = chunk.slice(0, remaining);
|
||||
received += fragment.length;
|
||||
chunks.push(fragment);
|
||||
if (received >= WEB_PORT_PROBE_MAX_BODY_BYTES) {
|
||||
settleFromChunks(chunks);
|
||||
res.destroy();
|
||||
}
|
||||
});
|
||||
res.on("end", () => {
|
||||
settleFromChunks(chunks);
|
||||
});
|
||||
res.on("error", () => {
|
||||
settle(null);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
req.on("timeout", () => {
|
||||
req.destroy();
|
||||
settle(null);
|
||||
});
|
||||
req.on("error", () => {
|
||||
settle(null);
|
||||
});
|
||||
|
||||
timer = setTimeout(() => {
|
||||
req.destroy();
|
||||
settle(null);
|
||||
}, DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS + 50);
|
||||
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
export async function defaultWebPortInspector(port: number): Promise<boolean> {
|
||||
const ipv4Result = await probeWebPortOnHost(port, "127.0.0.1");
|
||||
if (isLikelyWebProbe(ipv4Result)) {
|
||||
return true;
|
||||
}
|
||||
const ipv6Result = await probeWebPortOnHost(port, "::1");
|
||||
return isLikelyWebProbe(ipv6Result);
|
||||
}
|
||||
@@ -61,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 {
|
||||
@@ -204,13 +205,6 @@ function ThreadStatusLabel({
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeRunningPorts(rawPorts: number[] | undefined): number[] {
|
||||
if (!rawPorts) return [];
|
||||
return [...new Set(rawPorts)]
|
||||
.filter((port) => Number.isInteger(port) && port > 0 && port <= 65_535)
|
||||
.toSorted((left, right) => left - right);
|
||||
}
|
||||
|
||||
function terminalStatusFromTerminalState(
|
||||
runningTerminalIds: string[],
|
||||
runningTerminalPorts: Record<string, number[]>,
|
||||
@@ -222,15 +216,10 @@ function terminalStatusFromTerminalState(
|
||||
const runningPorts = normalizeRunningPorts(
|
||||
runningTerminalIds.flatMap((terminalId) => runningTerminalPorts[terminalId] ?? []),
|
||||
);
|
||||
const primaryWebPort = runningPorts[0] ?? null;
|
||||
const { label, primaryWebPort } = portStatusLabel(runningPorts);
|
||||
|
||||
return {
|
||||
label:
|
||||
primaryWebPort === null
|
||||
? "Terminal process running"
|
||||
: runningPorts.length === 1
|
||||
? `Open web server: http://localhost:${primaryWebPort}`
|
||||
: `Open web server: http://localhost:${primaryWebPort} (detected web ports: ${runningPorts.join(", ")})`,
|
||||
label,
|
||||
colorClass:
|
||||
primaryWebPort === null
|
||||
? "text-teal-600 dark:text-teal-300/90"
|
||||
|
||||
@@ -33,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;
|
||||
@@ -75,43 +76,17 @@ export function selectPendingTerminalEventEntries(
|
||||
return entries.filter((entry) => entry.id > lastAppliedTerminalEventId);
|
||||
}
|
||||
|
||||
interface TerminalRuntimeStatus {
|
||||
label: string;
|
||||
primaryWebPort: number | null;
|
||||
extraWebPortCount: number;
|
||||
}
|
||||
|
||||
function normalizeRunningPorts(rawPorts: number[] | undefined): number[] {
|
||||
if (!rawPorts) return [];
|
||||
return [...new Set(rawPorts)]
|
||||
.filter((port) => Number.isInteger(port) && port > 0 && port <= 65_535)
|
||||
.toSorted((left, right) => left - right);
|
||||
}
|
||||
|
||||
function terminalRuntimeStatus(
|
||||
terminalId: string,
|
||||
runningTerminalIds: Set<string>,
|
||||
runningTerminalPorts: Record<string, number[]>,
|
||||
): TerminalRuntimeStatus | null {
|
||||
): PortStatusLabel | null {
|
||||
if (!runningTerminalIds.has(terminalId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const runningPorts = normalizeRunningPorts(runningTerminalPorts[terminalId]);
|
||||
const primaryWebPort = runningPorts[0] ?? null;
|
||||
const extraWebPortCount = runningPorts.length > 1 ? runningPorts.length - 1 : 0;
|
||||
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,
|
||||
extraWebPortCount,
|
||||
};
|
||||
return portStatusLabel(runningPorts);
|
||||
}
|
||||
|
||||
function terminalThemeFromApp(): ITheme {
|
||||
|
||||
@@ -86,6 +86,27 @@ describe("terminalStateStore actions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
@@ -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";
|
||||
@@ -62,13 +64,6 @@ function normalizeRunningTerminalIds(
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
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 <= 65_535)
|
||||
.toSorted((left, right) => left - right);
|
||||
}
|
||||
|
||||
function normalizeRunningTerminalPorts(
|
||||
runningTerminalPorts: Record<string, number[]> | undefined,
|
||||
terminalIds: string[],
|
||||
@@ -555,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(
|
||||
|
||||
@@ -51,6 +51,10 @@
|
||||
"./projectScripts": {
|
||||
"types": "./src/projectScripts.ts",
|
||||
"import": "./src/projectScripts.ts"
|
||||
},
|
||||
"./port": {
|
||||
"types": "./src/port.ts",
|
||||
"import": "./src/port.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
Reference in new issue
Block a user