diff --git a/apps/server/src/process/Layers/TerminalProcessInspector.ts b/apps/server/src/process/Layers/TerminalProcessInspector.ts index bbb1b5e556..b2533b94ff 100644 --- a/apps/server/src/process/Layers/TerminalProcessInspector.ts +++ b/apps/server/src/process/Layers/TerminalProcessInspector.ts @@ -212,6 +212,7 @@ const makeTerminalProcessInspector = Effect.gen(function* () { const runningPorts = yield* checkPosixListeningPorts(processFamilyPids, { terminalPid, runCommand: runInspectorCommand, + platform: process.platform, }); return { hasRunningSubprocess: subprocessPids.length > 0 || runningPorts.length > 0, diff --git a/apps/server/src/process/Services/TerminalProcessInspector.ts b/apps/server/src/process/Services/TerminalProcessInspector.ts index 69bd89d608..9d96d40c08 100644 --- a/apps/server/src/process/Services/TerminalProcessInspector.ts +++ b/apps/server/src/process/Services/TerminalProcessInspector.ts @@ -1,6 +1,19 @@ import { ServiceMap, Schema } from "effect"; import type { Effect } from "effect"; +function describeTerminalInspectorCause(cause: unknown): string | null { + if (cause instanceof Error && cause.message.length > 0) { + return cause.message; + } + if (typeof cause === "string" && cause.length > 0) { + return cause; + } + if (cause === undefined || cause === null) { + return null; + } + return String(cause); +} + export class TerminalProcessInspectionError extends Schema.TaggedErrorClass()( "TerminalProcessInspectionError", { @@ -12,7 +25,10 @@ export class TerminalProcessInspectionError extends Schema.TaggedErrorClass { + it.effect("falls back to ss when lsof exits with code 1", () => + Effect.gen(function* () { + const commands: string[] = []; + + const ports = yield* checkPosixListeningPorts([123], { + terminalPid: 123, + platform: "linux", + runCommand: (input) => { + commands.push(input.command); + if (input.command === "lsof") { + return Effect.succeed({ + stdout: "", + stderr: "", + exitCode: 1, + }); + } + + return Effect.succeed({ + stdout: + "State Recv-Q Send-Q Local Address:Port Peer Address:Port Process\n" + + 'LISTEN 0 511 127.0.0.1:3773 0.0.0.0:* users:(("node",pid=123,fd=18))\n', + stderr: "", + exitCode: 0, + }); + }, + }); + + assert.deepStrictEqual(ports, [3773]); + assert.deepStrictEqual(commands, ["lsof", "ss"]); + }), + ); + + it.effect("does not try ss on darwin when lsof reports no listening ports", () => + Effect.gen(function* () { + const commands: string[] = []; + + const ports = yield* checkPosixListeningPorts([123], { + terminalPid: 123, + platform: "darwin", + runCommand: (input) => { + commands.push(input.command); + return Effect.succeed({ + stdout: "", + stderr: "", + exitCode: 1, + }); + }, + }); + + assert.deepStrictEqual(ports, []); + assert.deepStrictEqual(commands, ["lsof"]); + }), + ); +}); diff --git a/apps/server/src/process/posix.ts b/apps/server/src/process/posix.ts index f35f59b783..8a3f4a3e17 100644 --- a/apps/server/src/process/posix.ts +++ b/apps/server/src/process/posix.ts @@ -76,12 +76,14 @@ export const checkPosixListeningPorts = Effect.fn("process.checkPosixListeningPo input: { terminalPid: number; runCommand: PosixRunCommand; + platform?: NodeJS.Platform; }, ): Effect.fn.Return { if (processIds.length === 0) return []; const ports = new Set(); const pidFilter = new Set(processIds); + const platform = input.platform ?? process.platform; const lsofResult = yield* input .runCommand({ @@ -95,9 +97,6 @@ export const checkPosixListeningPorts = Effect.fn("process.checkPosixListeningPo .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\)$/); @@ -109,6 +108,9 @@ export const checkPosixListeningPorts = Effect.fn("process.checkPosixListeningPo } return [...ports].toSorted((left, right) => left - right); } + if (lsofResult.value.exitCode === 1 && platform === "darwin") { + return []; + } } const ssResult = yield* input.runCommand({ diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index e00b1561dc..270377d9e7 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -29,8 +29,15 @@ 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 { + TerminalProcessInspectionError, + TerminalProcessInspector, +} from "../../process/Services/TerminalProcessInspector"; +import { + WebPortInspector, + WebPortInspectionError, + type TerminalWebPortInspector, +} from "../../process/Services/WebPortInspector"; import type { TerminalManagerShape } from "../Services/Manager"; import { type PtyAdapterShape, @@ -39,7 +46,11 @@ import { type PtySpawnInput, PtySpawnError, } from "../Services/PTY"; -import { makeTerminalManagerWithOptions } from "./Manager"; +import { + describeSubprocessInspectorError, + makeTerminalManagerWithOptions, + nextSubprocessActivityErrorLogState, +} from "./Manager"; class FakePtyProcess implements PtyProcess { readonly writes: string[] = []; @@ -198,7 +209,8 @@ interface CreateManagerOptions { subprocessInspector?: ( terminalPid: number, ) => Effect.Effect<{ hasRunningSubprocess: boolean; runningPorts: number[] }>; - webPortInspector?: (port: number) => Effect.Effect; + webPortInspector?: TerminalWebPortInspector; + webPortProbeCacheTtlMs?: number; subprocessPollIntervalMs?: number; processKillGraceMs?: number; maxRetainedInactiveSessions?: number; @@ -238,6 +250,9 @@ const createManager = ( ...(options.webPortInspector !== undefined ? { webPortInspector: options.webPortInspector } : {}), + ...(options.webPortProbeCacheTtlMs !== undefined + ? { webPortProbeCacheTtlMs: options.webPortProbeCacheTtlMs } + : {}), ...(options.subprocessPollIntervalMs !== undefined ? { subprocessPollIntervalMs: options.subprocessPollIntervalMs } : {}), @@ -267,6 +282,61 @@ const createManager = ( const nodeChildProcessLayer = NodeChildProcessSpawner.layer.pipe(Layer.provide(NodeServices.layer)); +it.effect("formats subprocess inspector errors with command and underlying cause details", () => + Effect.sync(() => { + const error = new TerminalProcessInspectionError({ + operation: "TerminalProcessInspector.checkPosixListeningPorts.ss", + terminalPid: 77_411, + command: "ss -ltnp", + detail: "Failed to spawn inspector command.", + cause: new Error("spawn ss ENOENT"), + }); + + const description = describeSubprocessInspectorError(error); + + assert.equal(description.operation, "TerminalProcessInspector.checkPosixListeningPorts.ss"); + assert.equal(description.command, "ss -ltnp"); + assert.equal(description.detail, "Failed to spawn inspector command."); + assert.equal(description.cause, "spawn ss ENOENT"); + assert.include(description.error, "ss -ltnp"); + assert.include(description.error, "spawn ss ENOENT"); + }), +); + +it.effect( + "suppresses repeated identical subprocess inspector warnings inside the throttle window", + () => + Effect.sync(() => { + const first = nextSubprocessActivityErrorLogState({ + previous: undefined, + fingerprint: "same-error", + now: 1_000, + throttleMs: 30_000, + }); + assert.equal(first.shouldLog, true); + assert.equal(first.suppressedRepeats, 0); + + const second = nextSubprocessActivityErrorLogState({ + previous: first.next, + fingerprint: "same-error", + now: 2_000, + throttleMs: 30_000, + }); + assert.equal(second.shouldLog, false); + assert.equal(second.next.suppressedRepeats, 1); + + const third = nextSubprocessActivityErrorLogState({ + previous: second.next, + fingerprint: "same-error", + now: 32_000, + throttleMs: 30_000, + }); + assert.equal(third.shouldLog, true); + assert.equal(third.suppressedRepeats, 1); + assert.equal(third.next.suppressedRepeats, 0); + }), +); + it.layer( Layer.mergeAll( NodeServices.layer, @@ -626,6 +696,61 @@ it.layer( }), ); + it.effect("keeps a confirmed web port during transient probe failures after cache expiry", () => + Effect.gen(function* () { + let activity = { + hasRunningSubprocess: true, + runningPorts: [3000], + }; + let probeCalls = 0; + const { manager, getEvents } = yield* createManager(5, { + subprocessInspector: () => Effect.succeed(activity), + webPortInspector: () => { + probeCalls += 1; + return probeCalls === 1 + ? Effect.succeed(true) + : Effect.fail( + new WebPortInspectionError({ + port: 3000, + host: "127.0.0.1", + detail: "transient web probe failure", + }), + ); + }, + webPortProbeCacheTtlMs: 25, + subprocessPollIntervalMs: 20, + }); + + yield* manager.open(openInput()); + yield* waitFor( + Effect.map(getEvents, (events) => + events.some( + (event) => + event.type === "activity" && + event.hasRunningSubprocess === true && + event.runningPorts.join(",") === "3000", + ), + ), + "1200 millis", + ); + + yield* waitFor( + Effect.sync(() => probeCalls >= 2), + "1200 millis", + ); + const events = yield* getEvents; + expect( + events.some( + (event) => + event.type === "activity" && + event.hasRunningSubprocess === true && + event.runningPorts.length === 0, + ), + ).toBe(false); + activity = { hasRunningSubprocess: false, runningPorts: [] }; + }), + ); + it.effect("does not invoke subprocess polling until a terminal session is running", () => Effect.gen(function* () { let checks = 0; diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index 1fa751bdfb..53c4375661 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -17,6 +17,7 @@ import { FileSystem, Layer, Option, + Schema, Scope, Semaphore, SynchronizedRef, @@ -31,6 +32,7 @@ import { import { arePortListsEqual, normalizeRunningPorts } from "../../process/utils"; import { TerminalProcessInspector, + TerminalProcessInspectionError, type TerminalSubprocessActivity, type TerminalSubprocessInspector, } from "../../process/Services/TerminalProcessInspector"; @@ -58,6 +60,7 @@ import { const DEFAULT_HISTORY_LINE_LIMIT = 5_000; const DEFAULT_PERSIST_DEBOUNCE_MS = 40; const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000; +const DEFAULT_SUBPROCESS_ACTIVITY_ERROR_LOG_THROTTLE_MS = 30_000; const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000; const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128; const DEFAULT_OPEN_COLS = 120; @@ -70,6 +73,96 @@ class TerminalProcessSignalError extends Data.TaggedError("TerminalProcessSignal readonly signal: "SIGTERM" | "SIGKILL"; }> {} +interface SubprocessActivityErrorLogState { + fingerprint: string; + lastLoggedAt: number; + suppressedRepeats: number; +} + +export function describeSubprocessInspectorError(error: unknown): { + fingerprint: string; + error: string; + operation?: string; + command?: string; + detail?: string; + cause?: string; +} { + if (Schema.is(TerminalProcessInspectionError)(error)) { + const cause = + error.cause instanceof Error + ? error.cause.message + : typeof error.cause === "string" + ? error.cause + : error.cause === undefined || error.cause === null + ? undefined + : String(error.cause); + return { + fingerprint: JSON.stringify([ + error.operation, + error.terminalPid, + error.command, + error.detail, + cause ?? "", + ]), + error: error.message, + operation: error.operation, + command: error.command, + detail: error.detail, + ...(cause ? { cause } : {}), + }; + } + + const message = error instanceof Error ? error.message : String(error); + return { + fingerprint: message, + error: message, + }; +} + +export function nextSubprocessActivityErrorLogState(input: { + previous: SubprocessActivityErrorLogState | undefined; + fingerprint: string; + now: number; + throttleMs: number; +}): { + shouldLog: boolean; + suppressedRepeats: number; + next: SubprocessActivityErrorLogState; +} { + if (!input.previous || input.previous.fingerprint !== input.fingerprint) { + return { + shouldLog: true, + suppressedRepeats: 0, + next: { + fingerprint: input.fingerprint, + lastLoggedAt: input.now, + suppressedRepeats: 0, + }, + }; + } + + if (input.now - input.previous.lastLoggedAt >= input.throttleMs) { + return { + shouldLog: true, + suppressedRepeats: input.previous.suppressedRepeats, + next: { + fingerprint: input.fingerprint, + lastLoggedAt: input.now, + suppressedRepeats: 0, + }, + }; + } + + return { + shouldLog: false, + suppressedRepeats: input.previous.suppressedRepeats + 1, + next: { + ...input.previous, + suppressedRepeats: input.previous.suppressedRepeats + 1, + }, + }; +} + interface ShellCandidate { shell: string; args?: string[]; @@ -579,7 +672,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS; const maxRetainedInactiveSessions = options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS; - const webPortProbeCache = new Map(); + const webPortProbeCache = new Map(); + const subprocessActivityErrorLogState = new Map(); yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie); @@ -602,23 +696,39 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith const inspectWebPortCached = (port: number) => Effect.gen(function* () { const now = Date.now(); + const cached = webPortProbeCache.get(port); for (const [cachedPort, entry] of webPortProbeCache) { - if (now - entry.checkedAt > webPortProbeCacheTtlMs) { + if (cachedPort !== port && now - entry.checkedAt > webPortProbeCacheTtlMs) { webPortProbeCache.delete(cachedPort); } } - const cached = webPortProbeCache.get(port); - if (cached) { - return cached.isWeb; + if (cached && now - cached.checkedAt <= webPortProbeCacheTtlMs) { + return true; } - const isWeb = yield* webPortInspector(port).pipe(Effect.catch(() => Effect.succeed(false))); - webPortProbeCache.set(port, { - isWeb, - checkedAt: Date.now(), - }); - return isWeb; + const probeResult = yield* webPortInspector(port).pipe(Effect.exit); + if (probeResult._tag === "Success") { + if (probeResult.value) { + webPortProbeCache.set(port, { + isWeb: true, + checkedAt: Date.now(), + }); + return true; + } + webPortProbeCache.delete(port); + return false; + } + + if (cached) { + webPortProbeCache.set(port, { + isWeb: true, + checkedAt: Date.now(), + }); + return true; + } + + return false; }); const detectWebPorts = (runningPorts: number[]) => @@ -1404,6 +1514,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith (session): session is TerminalSessionState & { pid: number } => session.status === "running" && Number.isInteger(session.pid), ); + const activeRunningSessionKeys = new Set( + runningSessions.map((session) => toSessionKey(session.threadId, session.terminalId)), + ); + for (const sessionKey of subprocessActivityErrorLogState.keys()) { + if (!activeRunningSessionKeys.has(sessionKey)) { + subprocessActivityErrorLogState.delete(sessionKey); + } + } if (runningSessions.length === 0) { return; @@ -1413,16 +1531,36 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith session: TerminalSessionState & { pid: number }, ) { const terminalPid = session.pid; + const sessionKey = toSessionKey(session.threadId, session.terminalId); const activity = yield* subprocessInspector(terminalPid).pipe( + Effect.tap(() => Effect.sync(() => subprocessActivityErrorLogState.delete(sessionKey))), Effect.map(Option.some), - Effect.catch((error) => - Effect.logWarning("failed to check terminal subprocess activity", { + Effect.catch((error) => { + const description = describeSubprocessInspectorError(error); + const logDecision = nextSubprocessActivityErrorLogState({ + previous: subprocessActivityErrorLogState.get(sessionKey), + fingerprint: description.fingerprint, + now: Date.now(), + throttleMs: DEFAULT_SUBPROCESS_ACTIVITY_ERROR_LOG_THROTTLE_MS, + }); + subprocessActivityErrorLogState.set(sessionKey, logDecision.next); + if (!logDecision.shouldLog) { + return Effect.succeed(Option.none()); + } + return Effect.logWarning("failed to check terminal subprocess activity", { threadId: session.threadId, terminalId: session.terminalId, terminalPid, - error: error instanceof Error ? error.message : String(error), - }).pipe(Effect.as(Option.none())), - ), + error: description.error, + ...(description.operation ? { operation: description.operation } : {}), + ...(description.command ? { command: description.command } : {}), + ...(description.detail ? { detail: description.detail } : {}), + ...(description.cause ? { cause: description.cause } : {}), + ...(logDecision.suppressedRepeats > 0 + ? { suppressedRepeats: logDecision.suppressedRepeats } + : {}), + }).pipe(Effect.as(Option.none())); + }), ); if (Option.isNone(activity)) { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 280d87bedb..a6186f6bf8 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -448,26 +448,40 @@ function SidebarThreadRow(props: SidebarThreadRowProps) {
{terminalStatus && (terminalStatus.primaryWebPort === null ? ( - - - + + + + + } + /> + {terminalStatus.label} + ) : ( - + + { + props.openWebPort(event, terminalStatus.primaryWebPort!); + }} + > + + + } + /> + {terminalStatus.label} + ))}
{isConfirmingArchive ? ( diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index a0df8a725f..b8d81a8869 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -1281,26 +1281,56 @@ export default function ThreadTerminalDrawer({ {runtimeStatus && (runtimeStatus.primaryWebPort === null ? ( - - - + + + + + } + /> + + {runtimeStatus.label} + + ) : ( - + + + openWebPort(event, runtimeStatus.primaryWebPort!) + } + aria-label={runtimeStatus.label} + > + + + } + /> + + {runtimeStatus.label} + + ))} {normalizedTerminalIds.length > 1 && (