From da81a167eac8b111b129cc7ed989b0b7c8f62dde Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 4 Apr 2026 17:14:48 -0700 Subject: [PATCH] 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 --- .../process/Layers/WebPortInspector.test.ts | 58 ++++++++++++++++--- .../src/process/Layers/WebPortInspector.ts | 19 +++--- apps/server/src/process/win32.test.ts | 57 ++++++++++++++++++ apps/server/src/process/win32.ts | 52 ++++++++++++----- apps/server/src/terminal/Layers/Manager.ts | 8 ++- apps/web/src/components/Sidebar.tsx | 13 ++--- .../src/components/ThreadTerminalDrawer.tsx | 16 ++--- apps/web/src/terminalStateStore.test.ts | 21 +++++++ apps/web/src/terminalStateStore.ts | 5 +- 9 files changed, 193 insertions(+), 56 deletions(-) create mode 100644 apps/server/src/process/win32.test.ts diff --git a/apps/server/src/process/Layers/WebPortInspector.test.ts b/apps/server/src/process/Layers/WebPortInspector.test.ts index 31fe3e1d91..52e47efa5f 100644 --- a/apps/server/src/process/Layers/WebPortInspector.test.ts +++ b/apps/server/src/process/Layers/WebPortInspector.test.ts @@ -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((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((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), + ), + ), + ), + ), +); diff --git a/apps/server/src/process/Layers/WebPortInspector.ts b/apps/server/src/process/Layers/WebPortInspector.ts index 949b0b13d2..5e3c505604 100644 --- a/apps/server/src/process/Layers/WebPortInspector.ts +++ b/apps/server/src/process/Layers/WebPortInspector.ts @@ -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, + }), ), ); }); diff --git a/apps/server/src/process/win32.test.ts b/apps/server/src/process/win32.test.ts new file mode 100644 index 0000000000..e262a02c7a --- /dev/null +++ b/apps/server/src/process/win32.test.ts @@ -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([ + [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([ + [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]); + }), + ); +}); diff --git a/apps/server/src/process/win32.ts b/apps/server/src/process/win32.ts index e4d57a0aa3..4b70c86a6b 100644 --- a/apps/server/src/process/win32.ts +++ b/apps/server/src/process/win32.ts @@ -26,23 +26,43 @@ export const collectWindowsChildPids = Effect.fn("process.collectWindowsChildPid terminalPid: number, runCommand: WindowsRunCommand, ): Effect.fn.Return { - 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([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")( diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index 0be4aa37c7..1fa751bdfb 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -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; } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 8f7ddb19d0..280d87bedb 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -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, diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 71243fa1b3..a0df8a725f 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -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, }; } diff --git a/apps/web/src/terminalStateStore.test.ts b/apps/web/src/terminalStateStore.test.ts index d63adacd57..2438bb5669 100644 --- a/apps/web/src/terminalStateStore.test.ts +++ b/apps/web/src/terminalStateStore.test.ts @@ -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); diff --git a/apps/web/src/terminalStateStore.ts b/apps/web/src/terminalStateStore.ts index 545160074f..60ad5c5a1d 100644 --- a/apps/web/src/terminalStateStore.ts +++ b/apps/web/src/terminalStateStore.ts @@ -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(