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]>
This commit is contained in:
1 parent
0236cc845e
commit
da81a167ea
9 files changed
+193
-56
No files matched your search
@@ -1,20 +1,24 @@
|
||||
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
|
||||
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
|
||||
import { WebPortInspector } from "../Services/WebPortInspector";
|
||||
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.
|
||||
@@ -24,12 +28,18 @@ const closeServer = (server: Server) =>
|
||||
|
||||
const listenServer = (server: Server) =>
|
||||
Effect.callback<number, Error>((resume) => {
|
||||
server.listen(0, "127.0.0.1", (error?: Error) => {
|
||||
if (error) {
|
||||
resume(Effect.fail(error));
|
||||
return;
|
||||
}
|
||||
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.")));
|
||||
@@ -39,7 +49,10 @@ const listenServer = (server: Server) =>
|
||||
resume(Effect.succeed(address.port));
|
||||
});
|
||||
|
||||
return closeServer(server);
|
||||
return Effect.gen(function* () {
|
||||
cleanup();
|
||||
yield* closeServer(server);
|
||||
});
|
||||
});
|
||||
|
||||
const startServer = (
|
||||
@@ -111,3 +124,30 @@ it.layer(WebPortInspectorLive.pipe(Layer.provide(FetchHttpClient.layer)))(
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
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),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
|
||||
import { Effect, Layer, Option, Stream } from "effect";
|
||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import type { WebPortInspectorShape } from "../Services/WebPortInspector";
|
||||
@@ -126,14 +126,15 @@ const makeWebPortInspector = Effect.gen(function* () {
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WebPortInspectionError({
|
||||
port,
|
||||
host,
|
||||
detail: "Failed to execute HTTP probe request.",
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(WebPortInspectionError)(error)
|
||||
? error
|
||||
: new WebPortInspectionError({
|
||||
port,
|
||||
host,
|
||||
detail: "Failed to execute HTTP probe request.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -26,23 +26,43 @@ export const collectWindowsChildPids = Effect.fn("process.collectWindowsChildPid
|
||||
terminalPid: number,
|
||||
runCommand: WindowsRunCommand,
|
||||
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
|
||||
const command = [
|
||||
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -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) {
|
||||
return [];
|
||||
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 parsePidList(result.stdout);
|
||||
return childPids;
|
||||
});
|
||||
|
||||
export const checkWindowsListeningPorts = Effect.fn("process.checkWindowsListeningPorts")(
|
||||
|
||||
@@ -602,8 +602,14 @@ 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -61,7 +61,11 @@ 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 { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import {
|
||||
normalizeRunningPorts,
|
||||
selectThreadTerminalState,
|
||||
useTerminalStateStore,
|
||||
} from "../terminalStateStore";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import {
|
||||
resolveShortcutCommand,
|
||||
@@ -204,13 +208,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[]>,
|
||||
|
||||
@@ -33,7 +33,11 @@ import {
|
||||
type ThreadTerminalGroup,
|
||||
} from "../types";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import { selectTerminalEventEntries, useTerminalStateStore } from "../terminalStateStore";
|
||||
import {
|
||||
normalizeRunningPorts,
|
||||
selectTerminalEventEntries,
|
||||
useTerminalStateStore,
|
||||
} from "../terminalStateStore";
|
||||
|
||||
const MIN_DRAWER_HEIGHT = 180;
|
||||
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
|
||||
@@ -78,14 +82,6 @@ export function selectPendingTerminalEventEntries(
|
||||
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(
|
||||
@@ -99,7 +95,6 @@ function terminalRuntimeStatus(
|
||||
|
||||
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"
|
||||
@@ -110,7 +105,6 @@ function terminalRuntimeStatus(
|
||||
return {
|
||||
label,
|
||||
primaryWebPort,
|
||||
extraWebPortCount,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -62,7 +62,7 @@ function normalizeRunningTerminalIds(
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
function normalizeRunningPorts(ports: readonly number[] | undefined): number[] {
|
||||
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 <= 65_535)
|
||||
@@ -555,7 +555,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(
|
||||
|
||||
Reference in new issue
Block a user