Compare commits

...
Author SHA1 Message Date
Cursor Agent 755bf3aa0d Fix Windows process tree traversal, remove dead code, deduplicate normalizeRunningPorts
- win32.ts: Replace direct-child-only query with full BFS traversal
  (collectWindowsProcessFamilyPids) to match POSIX behavior for
  detecting grandchild processes and their listening ports
- index.ts: Remove unused subprocessCheckerToInspector export and
  clean up unused type imports
- Deduplicate normalizeRunningPorts by exporting from terminalStateStore
  and importing in Sidebar.tsx and ThreadTerminalDrawer.tsx
2026-04-04 20:40:03 +00:00
Julius Marmingeandcodex 05a7018f03 Merge origin/main into codething/50e6e9da
Co-authored-by: codex <[email protected]>
2026-04-04 13:28:00 -07:00
Julius Marmingeandcodex d377e566f8 Merge origin/main into codething/50e6e9da
Co-authored-by: codex <[email protected]>
2026-02-16 01:01:24 -08:00
Julius Marminge 38644b0d81 Detect root-process ports and harden web port probing
- Include terminal root PID in port scans so listener-only sessions are marked active
- Improve web port detection for slow/large HTML responses and redirects
- Add integration-style tests for terminal subprocess and web port inspectors
2026-02-15 19:46:11 -08:00
Julius Marminge c11027be4d Show terminal runtime status and web port actions in thread UI
- Pass running terminal IDs/ports from `ChatView` into `ThreadTerminalDrawer`
- Add runtime badges/icons for running terminals and localhost web ports
- Make sidebar thread rows keyboard-activatable and add web-port quick open button
2026-02-15 18:25:22 -08:00
Julius Marminge b3e967e2cf adapters 2026-02-15 16:48:08 -08:00
Julius Marminge 3d082fc73b Detect real web ports and add one-click localhost shortcut
- Probe terminal subprocess ports and keep only likely web servers
- Cache/dedupe port probes and ignore root-path 404 responses
- Show a globe status icon in Sidebar that opens `http://localhost:<port>`
2026-02-15 16:47:19 -08:00
Julius Marminge 94a83ab48e Require all lsof filters when checking listening ports
- Add `-a` to the `lsof` command in terminal port detection
- Prevent mismatched results by combining TCP listen and PID filters correctly
2026-02-15 16:46:51 -08:00
Julius Marminge f2ec777443 Track running terminal ports across terminal activity events
- add `runningPorts` to terminal activity contract and validation
- detect/listen ports in server subprocess inspection and emit activity updates on port changes
- persist terminal-to-port state in web store and show active ports in sidebar indicator
- update server/web/contracts tests for port-aware activity behavior
2026-02-15 16:46:51 -08:00
21 changed files with 1092 additions and 168 deletions

No files matched your search

@@ -189,6 +189,10 @@ function multiTerminalHistoryLogPath(
interface CreateManagerOptions {
shellResolver?: () => string;
subprocessChecker?: (terminalPid: number) => Effect.Effect<boolean>;
subprocessInspector?: (
terminalPid: number,
) => Effect.Effect<{ hasRunningSubprocess: boolean; runningPorts: number[] }>;
webPortInspector?: (port: number) => Effect.Effect<boolean>;
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
maxRetainedInactiveSessions?: number;
@@ -225,6 +229,12 @@ const createManager = (
...(options.subprocessChecker !== undefined
? { subprocessChecker: options.subprocessChecker }
: {}),
...(options.subprocessInspector !== undefined
? { subprocessInspector: options.subprocessInspector }
: {}),
...(options.webPortInspector !== undefined
? { webPortInspector: options.webPortInspector }
: {}),
...(options.subprocessPollIntervalMs !== undefined
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
: {}),
@@ -548,29 +558,56 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
}),
);
it.effect("emits subprocess activity events when child-process state changes", () =>
it.effect("emits subprocess activity events when child-process state or web ports change", () =>
Effect.gen(function* () {
let hasRunningSubprocess = false;
let activity = {
hasRunningSubprocess: false,
runningPorts: [] as number[],
};
const { manager, getEvents } = yield* createManager(5, {
subprocessChecker: () => Effect.succeed(hasRunningSubprocess),
subprocessInspector: () => Effect.succeed(activity),
webPortInspector: (port) => Effect.succeed(port === 3000),
subprocessPollIntervalMs: 20,
});
yield* manager.open(openInput());
expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false);
hasRunningSubprocess = true;
activity = { hasRunningSubprocess: true, runningPorts: [3000] };
yield* waitFor(
Effect.map(getEvents, (events) =>
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true),
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === true &&
event.runningPorts.join(",") === "3000",
),
),
"1200 millis",
);
hasRunningSubprocess = false;
activity = { hasRunningSubprocess: true, runningPorts: [5173] };
yield* waitFor(
Effect.map(getEvents, (events) =>
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false),
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === true &&
event.runningPorts.length === 0,
),
),
"1200 millis",
);
activity = { hasRunningSubprocess: false, runningPorts: [5173] };
yield* waitFor(
Effect.map(getEvents, (events) =>
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === false &&
event.runningPorts.length === 0,
),
),
"1200 millis",
);
+106 -110
View File
@@ -28,7 +28,12 @@ import {
terminalRestartsTotal,
terminalSessionsTotal,
} from "../../observability/Metrics";
import { runProcess } from "../../processRunner";
import {
arePortListsEqual,
defaultSubprocessInspector,
normalizeRunningPorts,
} from "../../terminalProcessInspector";
import { DEFAULT_WEB_PORT_PROBE_TTL_MS, defaultWebPortInspector } from "../../webPortInspector";
import {
TerminalCwdError,
TerminalHistoryError,
@@ -57,6 +62,14 @@ const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECT
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;
@@ -107,6 +120,7 @@ interface TerminalSessionState {
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
runningSubprocessPorts: number[];
runtimeEnv: Record<string, string> | null;
}
@@ -299,108 +313,6 @@ function isRetryableShellSpawnError(error: PtySpawnError): boolean {
);
}
function checkWindowsSubprocessActivity(
terminalPid: number,
): Effect.Effect<boolean, TerminalSubprocessCheckError> {
const command = [
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
"if ($children) { exit 0 }",
"exit 1",
].join("; ");
return Effect.tryPromise({
try: () =>
runProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
timeoutMs: 1_500,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to check Windows terminal subprocess activity.",
cause,
terminalPid,
command: "powershell",
}),
}).pipe(Effect.map((result) => result.code === 0));
}
const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessActivity")(function* (
terminalPid: number,
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
const runPgrep = Effect.tryPromise({
try: () =>
runProcess("pgrep", ["-P", String(terminalPid)], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with pgrep.",
cause,
terminalPid,
command: "pgrep",
}),
});
const runPs = Effect.tryPromise({
try: () =>
runProcess("ps", ["-eo", "pid=,ppid="], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 262_144,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with ps.",
cause,
terminalPid,
command: "ps",
}),
});
const pgrepResult = yield* Effect.exit(runPgrep);
if (pgrepResult._tag === "Success") {
if (pgrepResult.value.code === 0) {
return pgrepResult.value.stdout.trim().length > 0;
}
if (pgrepResult.value.code === 1) {
return false;
}
}
const psResult = yield* Effect.exit(runPs);
if (psResult._tag === "Failure" || psResult.value.code !== 0) {
return false;
}
for (const line of psResult.value.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;
if (ppid === terminalPid) {
return true;
}
}
return false;
});
const defaultSubprocessChecker = Effect.fn("terminal.defaultSubprocessChecker")(function* (
terminalPid: number,
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return false;
}
if (process.platform === "win32") {
return yield* checkWindowsSubprocessActivity(terminalPid);
}
return yield* checkPosixSubprocessActivity(terminalPid);
});
function capHistory(history: string, maxLines: number): string {
if (history.length === 0) return history;
const hasTrailingNewline = history.endsWith("\n");
@@ -647,6 +559,9 @@ interface TerminalManagerOptions {
ptyAdapter: PtyAdapterShape;
shellResolver?: () => string;
subprocessChecker?: TerminalSubprocessChecker;
subprocessInspector?: TerminalSubprocessInspector;
webPortInspector?: TerminalWebPortInspector;
webPortProbeCacheTtlMs?: number;
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
maxRetainedInactiveSessions?: number;
@@ -670,12 +585,39 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
const logsDir = options.logsDir;
const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
const shellResolver = options.shellResolver ?? defaultShellResolver;
const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
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,
}));
const webPortProbeCacheTtlMs = options.webPortProbeCacheTtlMs ?? DEFAULT_WEB_PORT_PROBE_TTL_MS;
const subprocessPollIntervalMs =
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
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 }>();
yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie);
@@ -695,6 +637,44 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
}
});
const inspectWebPortCached = (port: number) =>
Effect.gen(function* () {
const now = Date.now();
const cached = webPortProbeCache.get(port);
if (cached && now - cached.checkedAt <= webPortProbeCacheTtlMs) {
return cached.isWeb;
}
const isWeb = yield* webPortInspector(port).pipe(Effect.catch(() => Effect.succeed(false)));
webPortProbeCache.set(port, {
isWeb,
checkedAt: Date.now(),
});
return isWeb;
});
const detectWebPorts = (runningPorts: number[]) =>
Effect.gen(function* () {
if (runningPorts.length === 0) {
return [] as number[];
}
const checks = yield* Effect.forEach(
runningPorts,
(port) =>
Effect.map(inspectWebPortCached(port), (isWeb) => ({
port,
isWeb,
})),
{ concurrency: "unbounded" },
);
return checks
.filter((entry) => entry.isWeb)
.map((entry) => entry.port)
.toSorted((left, right) => left - right);
});
const historyPath = (threadId: string, terminalId: string) => {
const threadPart = toSafeThreadId(threadId);
if (terminalId === DEFAULT_TERMINAL_ID) {
@@ -1158,6 +1138,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.process = null;
session.pid = null;
session.hasRunningSubprocess = false;
session.runningSubprocessPorts = [];
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.pendingProcessEvents = [];
@@ -1225,6 +1206,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.process = null;
session.pid = null;
session.hasRunningSubprocess = false;
session.runningSubprocessPorts = [];
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.pendingProcessEvents = [];
@@ -1318,6 +1300,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.exitCode = null;
session.exitSignal = null;
session.hasRunningSubprocess = false;
session.runningSubprocessPorts = [];
session.pendingProcessEvents = [];
session.pendingProcessEventIndex = 0;
session.processEventDrainRunning = false;
@@ -1391,6 +1374,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.unsubscribeData = null;
session.unsubscribeExit = null;
session.hasRunningSubprocess = false;
session.runningSubprocessPorts = [];
session.pendingProcessEvents = [];
session.pendingProcessEventIndex = 0;
session.processEventDrainRunning = false;
@@ -1461,7 +1445,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session: TerminalSessionState & { pid: number },
) {
const terminalPid = session.pid;
const hasRunningSubprocess = yield* subprocessChecker(terminalPid).pipe(
const activity = yield* subprocessInspector(terminalPid).pipe(
Effect.map(Option.some),
Effect.catch((error) =>
Effect.logWarning("failed to check terminal subprocess activity", {
@@ -1469,14 +1453,21 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
terminalId: session.terminalId,
terminalPid,
error: error instanceof Error ? error.message : String(error),
}).pipe(Effect.as(Option.none<boolean>())),
}).pipe(Effect.as(Option.none<TerminalSubprocessActivity>())),
),
);
if (Option.isNone(hasRunningSubprocess)) {
if (Option.isNone(activity)) {
return;
}
const hasRunningSubprocess = activity.value.hasRunningSubprocess === true;
const runningPorts = hasRunningSubprocess
? normalizeRunningPorts(
yield* detectWebPorts(normalizeRunningPorts(activity.value.runningPorts)),
)
: [];
const event = yield* modifyManagerState((state) => {
const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
@@ -1485,12 +1476,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
Option.isNone(liveSession) ||
liveSession.value.status !== "running" ||
liveSession.value.pid !== terminalPid ||
liveSession.value.hasRunningSubprocess === hasRunningSubprocess.value
(liveSession.value.hasRunningSubprocess === hasRunningSubprocess &&
arePortListsEqual(liveSession.value.runningSubprocessPorts, runningPorts))
) {
return [Option.none(), state] as const;
}
liveSession.value.hasRunningSubprocess = hasRunningSubprocess.value;
liveSession.value.hasRunningSubprocess = hasRunningSubprocess;
liveSession.value.runningSubprocessPorts = runningPorts;
liveSession.value.updatedAt = new Date().toISOString();
return [
@@ -1499,7 +1492,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: liveSession.value.threadId,
terminalId: liveSession.value.terminalId,
createdAt: new Date().toISOString(),
hasRunningSubprocess: hasRunningSubprocess.value,
hasRunningSubprocess,
runningPorts,
}),
state,
] as const;
@@ -1598,6 +1592,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
runningSubprocessPorts: [],
runtimeEnv: normalizedRuntimeEnv(input.env),
};
@@ -1777,6 +1772,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
runningSubprocessPorts: [],
runtimeEnv: normalizedRuntimeEnv(input.env),
};
const createdSession = session;
@@ -51,6 +51,7 @@ export interface TerminalSessionState {
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
runningSubprocessPorts: number[];
runtimeEnv: Record<string, string> | null;
}
@@ -0,0 +1,141 @@
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([]);
});
});
@@ -0,0 +1,46 @@
import { collectPosixProcessFamilyPids, checkPosixListeningPorts } from "./posix";
import { type TerminalSubprocessActivity } from "./types";
import { checkWindowsListeningPorts, collectWindowsProcessFamilyPids } 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 processFamilyPids = await collectWindowsProcessFamilyPids(terminalPid);
if (processFamilyPids.length === 0) {
return { hasRunningSubprocess: false, runningPorts: [] };
}
const subprocessPids = processFamilyPids.filter((pid) => pid !== terminalPid);
const runningPorts = await checkWindowsListeningPorts(processFamilyPids);
return {
hasRunningSubprocess: subprocessPids.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,
};
}
@@ -0,0 +1,119 @@
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 [];
}
}
@@ -0,0 +1,12 @@
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>;
@@ -0,0 +1,52 @@
export const MAX_PORT_NUMBER = 65_535;
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 function parsePidList(stdout: string): number[] {
const pids: number[] = [];
for (const line of stdout.split(/\r?\n/g)) {
const pid = Number(line.trim());
if (!Number.isInteger(pid) || pid <= 0) {
continue;
}
pids.push(pid);
}
return [...new Set(pids)];
}
export function parsePortList(stdout: string): number[] {
const ports: number[] = [];
for (const line of stdout.split(/\r?\n/g)) {
const port = Number(line.trim());
if (!Number.isInteger(port)) {
continue;
}
ports.push(port);
}
return normalizeRunningPorts(ports);
}
export function portFromAddress(address: string): number | null {
const match = address.match(/:(\d+)$/);
if (!match?.[1]) return null;
const port = Number(match[1]);
if (!Number.isInteger(port) || port <= 0 || port > MAX_PORT_NUMBER) {
return null;
}
return port;
}
export function arePortListsEqual(left: number[], right: number[]): boolean {
if (left.length !== right.length) return false;
for (let index = 0; index < left.length; index += 1) {
if (left[index] !== right[index]) {
return false;
}
}
return true;
}
@@ -0,0 +1,87 @@
import { runProcess } from "../processRunner";
import { parsePortList } from "./utils";
export async function collectWindowsProcessFamilyPids(terminalPid: number): Promise<number[]> {
const command = [
"$procs = Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId -ErrorAction SilentlyContinue",
"if (-not $procs) { exit 0 }",
'$procs | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }',
].join("; ");
try {
const result = await runProcess(
"powershell.exe",
["-NoProfile", "-NonInteractive", "-Command", command],
{
timeoutMs: 2_000,
allowNonZeroExit: true,
maxBufferBytes: 262_144,
outputMode: "truncate",
},
);
if (result.code !== 0) {
return [];
}
const childrenByParentPid = new Map<number, number[]>();
for (const line of result.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 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 [];
}
}
+81
View File
@@ -0,0 +1,81 @@
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);
});
});
+132
View File
@@ -0,0 +1,132 @@
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);
}
@@ -1406,6 +1406,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: [],
runningTerminalPorts: {},
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
+2
View File
@@ -558,6 +558,8 @@ function PersistentThreadTerminalDrawer({
activeTerminalId={terminalState.activeTerminalId}
terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={terminalState.activeTerminalGroupId}
runningTerminalIds={terminalState.runningTerminalIds}
runningTerminalPorts={terminalState.runningTerminalPorts}
focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
+70 -19
View File
@@ -4,6 +4,7 @@ import {
ChevronRightIcon,
FolderIcon,
GitPullRequestIcon,
GlobeIcon,
PlusIcon,
SettingsIcon,
SquarePenIcon,
@@ -60,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,
@@ -150,9 +155,10 @@ type SidebarProjectSnapshot = Project & {
expanded: boolean;
};
interface TerminalStatusIndicator {
label: "Terminal process running";
label: string;
colorClass: string;
pulse: boolean;
primaryWebPort: number | null;
}
interface PrStatusIndicator {
@@ -202,16 +208,32 @@ function ThreadStatusLabel({
);
}
function terminalStatusFromRunningIds(
function terminalStatusFromTerminalState(
runningTerminalIds: string[],
runningTerminalPorts: Record<string, number[]>,
): TerminalStatusIndicator | null {
if (runningTerminalIds.length === 0) {
return null;
}
const runningPorts = normalizeRunningPorts(
runningTerminalIds.flatMap((terminalId) => runningTerminalPorts[terminalId] ?? []),
);
const primaryWebPort = runningPorts[0] ?? null;
return {
label: "Terminal process running",
colorClass: "text-teal-600 dark:text-teal-300/90",
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(", ")})`,
colorClass:
primaryWebPort === null
? "text-teal-600 dark:text-teal-300/90"
: "text-sky-600 dark:text-sky-300/90",
pulse: true,
primaryWebPort,
};
}
@@ -276,6 +298,7 @@ interface SidebarThreadRowProps {
commitRename: (threadId: ThreadId, newTitle: string, originalTitle: string) => Promise<void>;
cancelRename: () => void;
attemptArchiveThread: (threadId: ThreadId) => Promise<void>;
openWebPort: (event: MouseEvent<HTMLElement>, port: number) => void;
openPrLink: (event: MouseEvent<HTMLElement>, prUrl: string) => void;
pr: ThreadPr | null;
}
@@ -283,9 +306,8 @@ interface SidebarThreadRowProps {
function SidebarThreadRow(props: SidebarThreadRowProps) {
const thread = useSidebarThreadSummaryById(props.threadId);
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[props.threadId]);
const runningTerminalIds = useTerminalStateStore(
(state) =>
selectThreadTerminalState(state.terminalStateByThreadId, props.threadId).runningTerminalIds,
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadId, props.threadId),
);
if (!thread) {
@@ -304,7 +326,10 @@ function SidebarThreadRow(props: SidebarThreadRowProps) {
},
});
const prStatus = prStatusIndicator(props.pr);
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
const terminalStatus = terminalStatusFromTerminalState(
terminalState.runningTerminalIds,
terminalState.runningTerminalPorts,
);
const isConfirmingArchive = props.confirmingArchiveThreadId === thread.id && !isThreadRunning;
const threadMetaClassName = isConfirmingArchive
? "pointer-events-none opacity-0"
@@ -421,16 +446,29 @@ function SidebarThreadRow(props: SidebarThreadRowProps) {
)}
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<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>
)}
{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>
) : (
<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>
))}
<div className="flex min-w-12 justify-end">
{isConfirmingArchive ? (
<button
@@ -832,6 +870,18 @@ export default function Sidebar() {
});
}, []);
const openWebPort = useCallback((event: MouseEvent<HTMLElement>, port: number) => {
event.preventDefault();
event.stopPropagation();
const api = readNativeApi();
if (!api) {
return;
}
void api.shell.openExternal(`http://localhost:${port}`).catch(() => undefined);
}, []);
const attemptArchiveThread = useCallback(
async (threadId: ThreadId) => {
try {
@@ -1740,6 +1790,7 @@ export default function Sidebar() {
commitRename={commitRename}
cancelRename={cancelRename}
attemptArchiveThread={attemptArchiveThread}
openWebPort={openWebPort}
openPrLink={openPrLink}
pr={prByThreadId.get(threadId) ?? null}
/>
@@ -1,5 +1,5 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import { Globe, Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import {
type TerminalEvent,
type TerminalSessionSnapshot,
@@ -7,6 +7,7 @@ import {
} from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
type ReactNode,
useCallback,
@@ -32,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;
@@ -74,6 +79,38 @@ export function selectPendingTerminalEventEntries(
return entries.filter((entry) => entry.id > lastAppliedTerminalEventId);
}
interface TerminalRuntimeStatus {
label: string;
primaryWebPort: number | null;
extraWebPortCount: number;
}
function terminalRuntimeStatus(
terminalId: string,
runningTerminalIds: Set<string>,
runningTerminalPorts: Record<string, number[]>,
): TerminalRuntimeStatus | 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,
};
}
function terminalThemeFromApp(): ITheme {
const isDark = document.documentElement.classList.contains("dark");
const bodyStyles = getComputedStyle(document.body);
@@ -731,6 +768,8 @@ interface ThreadTerminalDrawerProps {
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
runningTerminalIds: string[];
runningTerminalPorts: Record<string, number[]>;
focusRequestId: number;
onSplitTerminal: () => void;
onNewTerminal: () => void;
@@ -783,6 +822,8 @@ export default function ThreadTerminalDrawer({
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
runningTerminalIds,
runningTerminalPorts,
focusRequestId,
onSplitTerminal,
onNewTerminal,
@@ -906,6 +947,10 @@ export default function ThreadTerminalDrawer({
),
[normalizedTerminalIds],
);
const runningTerminalIdSet = useMemo(
() => new Set(runningTerminalIds.map((terminalId) => terminalId.trim())),
[runningTerminalIds],
);
const splitTerminalActionLabel = hasReachedSplitLimit
? `Split Terminal (max ${MAX_TERMINALS_PER_GROUP} per group)`
: splitShortcutLabel
@@ -1027,6 +1072,14 @@ export default function ThreadTerminalDrawer({
};
}, [syncHeight]);
const openWebPort = useCallback((event: ReactMouseEvent<HTMLButtonElement>, port: number) => {
event.preventDefault();
event.stopPropagation();
const api = readNativeApi();
if (!api) return;
void api.shell.openExternal(`http://localhost:${port}`).catch(() => undefined);
}, []);
return (
<aside
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
@@ -1199,6 +1252,11 @@ export default function ThreadTerminalDrawer({
>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
const runtimeStatus = terminalRuntimeStatus(
terminalId,
runningTerminalIdSet,
runningTerminalPorts,
);
const closeTerminalLabel = `Close ${
terminalLabelById.get(terminalId) ?? "terminal"
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
@@ -1224,6 +1282,29 @@ export default function ThreadTerminalDrawer({
{terminalLabelById.get(terminalId) ?? "Terminal"}
</span>
</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>
) : (
<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>
))}
{normalizedTerminalIds.length > 1 && (
<Popover>
<PopoverTrigger
+4 -8
View File
@@ -30,22 +30,25 @@ describe("terminalRunningSubprocessFromEvent", () => {
...eventBase(),
type: "activity",
hasRunningSubprocess: true,
runningPorts: [3000],
});
const idle = terminalRunningSubprocessFromEvent({
...eventBase(),
type: "activity",
hasRunningSubprocess: false,
runningPorts: [],
});
expect(active).toBe(true);
expect(idle).toBe(false);
});
it("clears running state when a terminal session starts/restarts/exits", () => {
it("clears running state when a terminal session starts/restarts/exits/errors", () => {
const events: TerminalEvent[] = [
{ ...eventBase(), type: "started", snapshot },
{ ...eventBase(), type: "restarted", snapshot },
{ ...eventBase(), type: "exited", exitCode: 0, exitSignal: null },
{ ...eventBase(), type: "error", message: "oops" },
];
for (const event of events) {
@@ -61,12 +64,5 @@ describe("terminalRunningSubprocessFromEvent", () => {
data: "hello",
}),
).toBeNull();
expect(
terminalRunningSubprocessFromEvent({
...eventBase(),
type: "error",
message: "oops",
}),
).toBeNull();
});
});
+1
View File
@@ -7,6 +7,7 @@ export function terminalRunningSubprocessFromEvent(event: TerminalEvent): boolea
case "started":
case "restarted":
case "exited":
case "error":
return false;
default:
return null;
+30 -15
View File
@@ -23,7 +23,13 @@ function makeTerminalEvent(
case "output":
return { ...base, type, data: "hello\n", ...overrides } as TerminalEvent;
case "activity":
return { ...base, type, hasRunningSubprocess: true, ...overrides } as TerminalEvent;
return {
...base,
type,
hasRunningSubprocess: true,
runningPorts: [],
...overrides,
} as TerminalEvent;
case "error":
return { ...base, type, message: "boom", ...overrides } as TerminalEvent;
case "cleared":
@@ -73,6 +79,7 @@ describe("terminalStateStore actions", () => {
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: [],
runningTerminalPorts: {},
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
@@ -181,17 +188,21 @@ describe("terminalStateStore actions", () => {
it("tracks and clears terminal subprocess activity", () => {
const store = useTerminalStateStore.getState();
store.splitTerminal(THREAD_ID, "terminal-2");
store.setTerminalActivity(THREAD_ID, "terminal-2", true);
expect(
selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)
.runningTerminalIds,
).toEqual(["terminal-2"]);
store.setTerminalActivity(THREAD_ID, "terminal-2", true, [5173, 3000, 5173]);
let terminalState = selectThreadTerminalState(
useTerminalStateStore.getState().terminalStateByThreadId,
THREAD_ID,
);
expect(terminalState.runningTerminalIds).toEqual(["terminal-2"]);
expect(terminalState.runningTerminalPorts).toEqual({ "terminal-2": [3000, 5173] });
store.setTerminalActivity(THREAD_ID, "terminal-2", false);
expect(
selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)
.runningTerminalIds,
).toEqual([]);
terminalState = selectThreadTerminalState(
useTerminalStateStore.getState().terminalStateByThreadId,
THREAD_ID,
);
expect(terminalState.runningTerminalIds).toEqual([]);
expect(terminalState.runningTerminalPorts).toEqual({});
});
it("resets to default and clears persisted entry when closing the last terminal", () => {
@@ -287,12 +298,15 @@ describe("terminalStateStore actions", () => {
makeTerminalEvent("activity", {
terminalId: "terminal-2",
hasRunningSubprocess: true,
runningPorts: [5173, 3000],
}),
);
expect(
selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)
.runningTerminalIds,
).toEqual(["terminal-2"]);
let terminalState = selectThreadTerminalState(
useTerminalStateStore.getState().terminalStateByThreadId,
THREAD_ID,
);
expect(terminalState.runningTerminalIds).toEqual(["terminal-2"]);
expect(terminalState.runningTerminalPorts).toEqual({ "terminal-2": [3000, 5173] });
store.applyTerminalEvent(
makeTerminalEvent("exited", {
@@ -302,7 +316,7 @@ describe("terminalStateStore actions", () => {
}),
);
const terminalState = selectThreadTerminalState(
terminalState = selectThreadTerminalState(
useTerminalStateStore.getState().terminalStateByThreadId,
THREAD_ID,
);
@@ -313,6 +327,7 @@ describe("terminalStateStore actions", () => {
);
expect(terminalState.runningTerminalIds).toEqual([]);
expect(terminalState.runningTerminalPorts).toEqual({});
expect(entries.map((entry) => entry.event.type)).toEqual(["activity", "exited"]);
});
+77 -6
View File
@@ -22,6 +22,7 @@ interface ThreadTerminalState {
terminalHeight: number;
terminalIds: string[];
runningTerminalIds: string[];
runningTerminalPorts: Record<string, number[]>;
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
@@ -61,6 +62,30 @@ function normalizeRunningTerminalIds(
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
}
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)
.toSorted((left, right) => left - right);
}
function normalizeRunningTerminalPorts(
runningTerminalPorts: Record<string, number[]> | undefined,
terminalIds: string[],
): Record<string, number[]> {
if (!runningTerminalPorts) return {};
const validTerminalIdSet = new Set(terminalIds);
const normalizedEntries: Array<[string, number[]]> = [];
for (const [rawTerminalId, ports] of Object.entries(runningTerminalPorts)) {
const terminalId = rawTerminalId.trim();
if (terminalId.length === 0 || !validTerminalIdSet.has(terminalId)) {
continue;
}
normalizedEntries.push([terminalId, normalizeRunningPorts(ports)]);
}
return Object.fromEntries(normalizedEntries);
}
function fallbackGroupId(terminalId: string): string {
return `group-${terminalId}`;
}
@@ -136,7 +161,7 @@ function normalizeTerminalGroups(
return nextGroups;
}
function arraysEqual(a: string[], b: string[]): boolean {
function arraysEqual<T>(a: readonly T[], b: readonly T[]): boolean {
if (a.length !== b.length) return false;
for (let index = 0; index < a.length; index += 1) {
if (a[index] !== b[index]) return false;
@@ -156,6 +181,22 @@ function terminalGroupsEqual(left: ThreadTerminalGroup[], right: ThreadTerminalG
return true;
}
function runningTerminalPortsEqual(
left: Record<string, number[]>,
right: Record<string, number[]>,
): boolean {
const leftEntries = Object.entries(left);
const rightEntries = Object.entries(right);
if (leftEntries.length !== rightEntries.length) return false;
for (const [terminalId, leftPorts] of leftEntries) {
const rightPorts = right[terminalId];
if (!rightPorts || !arraysEqual(leftPorts, rightPorts)) {
return false;
}
}
return true;
}
function threadTerminalStateEqual(left: ThreadTerminalState, right: ThreadTerminalState): boolean {
return (
left.terminalOpen === right.terminalOpen &&
@@ -164,6 +205,7 @@ function threadTerminalStateEqual(left: ThreadTerminalState, right: ThreadTermin
left.activeTerminalGroupId === right.activeTerminalGroupId &&
arraysEqual(left.terminalIds, right.terminalIds) &&
arraysEqual(left.runningTerminalIds, right.runningTerminalIds) &&
runningTerminalPortsEqual(left.runningTerminalPorts, right.runningTerminalPorts) &&
terminalGroupsEqual(left.terminalGroups, right.terminalGroups)
);
}
@@ -173,6 +215,7 @@ const DEFAULT_THREAD_TERMINAL_STATE: ThreadTerminalState = Object.freeze({
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
runningTerminalPorts: {},
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
@@ -188,6 +231,7 @@ function createDefaultThreadTerminalState(): ThreadTerminalState {
...DEFAULT_THREAD_TERMINAL_STATE,
terminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.terminalIds],
runningTerminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.runningTerminalIds],
runningTerminalPorts: { ...DEFAULT_THREAD_TERMINAL_STATE.runningTerminalPorts },
terminalGroups: copyTerminalGroups(DEFAULT_THREAD_TERMINAL_STATE.terminalGroups),
};
}
@@ -200,6 +244,10 @@ function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTermina
const terminalIds = normalizeTerminalIds(state.terminalIds);
const nextTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
const runningTerminalIds = normalizeRunningTerminalIds(state.runningTerminalIds, nextTerminalIds);
const runningTerminalPorts = normalizeRunningTerminalPorts(
state.runningTerminalPorts,
nextTerminalIds,
);
const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
? state.activeTerminalId
: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
@@ -220,6 +268,7 @@ function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTermina
: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: nextTerminalIds,
runningTerminalIds,
runningTerminalPorts,
activeTerminalId,
terminalGroups,
activeTerminalGroupId:
@@ -455,6 +504,9 @@ function closeThreadTerminal(state: ThreadTerminalState, terminalId: string): Th
terminalHeight: normalized.terminalHeight,
terminalIds: remainingTerminalIds,
runningTerminalIds: normalized.runningTerminalIds.filter((id) => id !== terminalId),
runningTerminalPorts: Object.fromEntries(
Object.entries(normalized.runningTerminalPorts).filter(([key]) => key !== terminalId),
),
activeTerminalId: nextActiveTerminalId,
terminalGroups,
activeTerminalGroupId: nextActiveTerminalGroupId,
@@ -465,22 +517,35 @@ function setThreadTerminalActivity(
state: ThreadTerminalState,
terminalId: string,
hasRunningSubprocess: boolean,
runningPorts: readonly number[] = [],
): ThreadTerminalState {
const normalized = normalizeThreadTerminalState(state);
if (!normalized.terminalIds.includes(terminalId)) {
return normalized;
}
const alreadyRunning = normalized.runningTerminalIds.includes(terminalId);
if (hasRunningSubprocess === alreadyRunning) {
const nextRunningPorts = normalizeRunningPorts(runningPorts);
const currentRunningPorts = normalized.runningTerminalPorts[terminalId] ?? [];
if (
hasRunningSubprocess === alreadyRunning &&
arraysEqual(currentRunningPorts, nextRunningPorts)
) {
return normalized;
}
const runningTerminalIds = new Set(normalized.runningTerminalIds);
const runningTerminalPorts = { ...normalized.runningTerminalPorts };
if (hasRunningSubprocess) {
runningTerminalIds.add(terminalId);
runningTerminalPorts[terminalId] = nextRunningPorts;
} else {
runningTerminalIds.delete(terminalId);
delete runningTerminalPorts[terminalId];
}
return { ...normalized, runningTerminalIds: [...runningTerminalIds] };
return {
...normalized,
runningTerminalIds: [...runningTerminalIds],
runningTerminalPorts,
};
}
export function selectThreadTerminalState(
@@ -558,6 +623,7 @@ interface TerminalStateStoreState {
threadId: ThreadId,
terminalId: string,
hasRunningSubprocess: boolean,
runningPorts?: readonly number[],
) => void;
recordTerminalEvent: (event: TerminalEvent) => void;
applyTerminalEvent: (event: TerminalEvent) => void;
@@ -641,9 +707,9 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
const { [threadId]: _removed, ...rest } = state.terminalLaunchContextByThreadId;
return { terminalLaunchContextByThreadId: rest };
}),
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess, runningPorts) =>
updateTerminal(threadId, (state) =>
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess),
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess, runningPorts),
),
recordTerminalEvent: (event) =>
set((state) =>
@@ -685,7 +751,12 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
nextTerminalStateByThreadId,
threadId,
(current) =>
setThreadTerminalActivity(current, event.terminalId, hasRunningSubprocess),
setThreadTerminalActivity(
current,
event.terminalId,
hasRunningSubprocess,
event.type === "activity" ? event.runningPorts : [],
),
);
}
+1
View File
@@ -205,6 +205,7 @@ describe("TerminalEvent", () => {
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(),
hasRunningSubprocess: true,
runningPorts: [3000],
}),
).toBe(true);
});
+2 -1
View File
@@ -10,6 +10,7 @@ const TerminalColsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(20)).c
const TerminalRowsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(5)).check(
Schema.isLessThanOrEqualTo(200),
);
const TerminalPortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65_535 }));
const TerminalIdSchema = TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(128));
const TerminalEnvKeySchema = Schema.String.check(
Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/),
@@ -140,8 +141,8 @@ const TerminalActivityEvent = Schema.Struct({
...TerminalEventBaseSchema.fields,
type: Schema.Literal("activity"),
hasRunningSubprocess: Schema.Boolean,
runningPorts: Schema.Array(TerminalPortSchema),
});
export const TerminalEvent = Schema.Union([
TerminalStartedEvent,
TerminalOutputEvent,