Refine terminal subprocess inspection and status tooltips

- Fallback from `lsof` to `ss` on Linux and keep confirmed web ports cached
- Include command and cause details in subprocess errors, with throttled repeat warnings
- Add hover tooltips to terminal status icons in the sidebar and drawer
This commit is contained in:
Julius Marminge committed 2026-04-05 09:05:24 -07:00
1 parent da81a167ea
commit 07252e5be8
8 files changed
+448 -62

No files matched your search

@@ -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,
@@ -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>()(
"TerminalProcessInspectionError",
{
@@ -12,7 +25,10 @@ export class TerminalProcessInspectionError extends Schema.TaggedErrorClass<Term
},
) {
override get message(): string {
return `${this.operation} failed for terminal pid ${this.terminalPid}: ${this.detail}`;
const cause = describeTerminalInspectorCause(this.cause);
return `${this.operation} failed for terminal pid ${this.terminalPid} (${this.command}): ${this.detail}${
cause ? ` Cause: ${cause}` : ""
}`;
}
}
+60
View File
@@ -0,0 +1,60 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import { checkPosixListeningPorts } from "./posix";
describe("process.checkPosixListeningPorts", () => {
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"]);
}),
);
});
+5 -3
View File
@@ -76,12 +76,14 @@ export const checkPosixListeningPorts = Effect.fn("process.checkPosixListeningPo
input: {
terminalPid: number;
runCommand: PosixRunCommand;
platform?: NodeJS.Platform;
},
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
if (processIds.length === 0) return [];
const ports = new Set<number>();
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({
+129 -4
View File
@@ -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<boolean>;
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;
+154 -16
View File
@@ -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<number, { isWeb: boolean; checkedAt: number }>();
const webPortProbeCache = new Map<number, { isWeb: true; checkedAt: number }>();
const subprocessActivityErrorLogState = new Map<string, SubprocessActivityErrorLogState>();
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<TerminalSubprocessActivity>());
}
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<TerminalSubprocessActivity>())),
),
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<TerminalSubprocessActivity>()));
}),
);
if (Option.isNone(activity)) {
+33 -19
View File
@@ -448,26 +448,40 @@ function SidebarThreadRow(props: SidebarThreadRowProps) {
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{terminalStatus &&
(terminalStatus.primaryWebPort === null ? (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
</span>
<Tooltip>
<TooltipTrigger
render={
<span
role="img"
aria-label={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon
className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
/>
</span>
}
/>
<TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
</Tooltip>
) : (
<button
type="button"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center rounded-sm ${terminalStatus.colorClass} outline-hidden transition-colors hover:bg-accent hover:text-sky-700 focus-visible:ring-1 focus-visible:ring-ring dark:hover:text-sky-200`}
onClick={(event) => {
props.openWebPort(event, terminalStatus.primaryWebPort!);
}}
>
<GlobeIcon className="size-3" />
</button>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={terminalStatus.label}
className={`inline-flex cursor-pointer items-center justify-center rounded-sm ${terminalStatus.colorClass} outline-hidden transition-colors hover:bg-accent hover:text-sky-700 focus-visible:ring-1 focus-visible:ring-ring dark:hover:text-sky-200`}
onClick={(event) => {
props.openWebPort(event, terminalStatus.primaryWebPort!);
}}
>
<GlobeIcon className="size-3" />
</button>
}
/>
<TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
</Tooltip>
))}
<div className="flex min-w-12 justify-end">
{isConfirmingArchive ? (
@@ -1281,26 +1281,56 @@ export default function ThreadTerminalDrawer({
</button>
{runtimeStatus &&
(runtimeStatus.primaryWebPort === null ? (
<span
role="img"
aria-label={runtimeStatus.label}
title={runtimeStatus.label}
className="inline-flex items-center justify-center text-teal-600 dark:text-teal-300/90"
>
<TerminalSquare className="size-2.5 animate-pulse" />
</span>
<Popover>
<PopoverTrigger
openOnHover
render={
<span
role="img"
aria-label={runtimeStatus.label}
className="inline-flex items-center justify-center text-teal-600 dark:text-teal-300/90"
>
<TerminalSquare className="size-2.5 animate-pulse" />
</span>
}
/>
<PopoverPopup
tooltipStyle
side="bottom"
sideOffset={6}
align="center"
className="pointer-events-none select-none"
>
{runtimeStatus.label}
</PopoverPopup>
</Popover>
) : (
<button
type="button"
className="inline-flex items-center justify-center rounded p-0.5 text-sky-600 transition-colors hover:bg-accent hover:text-sky-700 dark:text-sky-300/90 dark:hover:text-sky-200"
onClick={(event) =>
openWebPort(event, runtimeStatus.primaryWebPort!)
}
aria-label={runtimeStatus.label}
title={runtimeStatus.label}
>
<Globe className="size-2.5 shrink-0" />
</button>
<Popover>
<PopoverTrigger
openOnHover
render={
<button
type="button"
className="inline-flex cursor-pointer items-center justify-center rounded p-0.5 text-sky-600 transition-colors hover:bg-accent hover:text-sky-700 dark:text-sky-300/90 dark:hover:text-sky-200"
onClick={(event) =>
openWebPort(event, runtimeStatus.primaryWebPort!)
}
aria-label={runtimeStatus.label}
>
<Globe className="size-2.5 shrink-0" />
</button>
}
/>
<PopoverPopup
tooltipStyle
side="bottom"
sideOffset={6}
align="center"
className="pointer-events-none select-none"
>
{runtimeStatus.label}
</PopoverPopup>
</Popover>
))}
{normalizedTerminalIds.length > 1 && (
<Popover>