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
This commit is contained in:
1 parent
748ea2ae20
commit
f2ec777443
12 files changed
+386
-52
No files matched your search
@@ -144,6 +144,9 @@ describe("TerminalManager", () => {
|
||||
options: {
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
|
||||
subprocessInspector?: (
|
||||
terminalPid: number,
|
||||
) => Promise<{ hasRunningSubprocess: boolean; runningPorts: number[] }>;
|
||||
subprocessPollIntervalMs?: number;
|
||||
} = {},
|
||||
) {
|
||||
@@ -156,6 +159,7 @@ describe("TerminalManager", () => {
|
||||
historyLineLimit,
|
||||
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
||||
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
|
||||
...(options.subprocessInspector ? { subprocessInspector: options.subprocessInspector } : {}),
|
||||
...(options.subprocessPollIntervalMs
|
||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||
: {}),
|
||||
@@ -289,9 +293,12 @@ describe("TerminalManager", () => {
|
||||
});
|
||||
|
||||
it("emits subprocess activity events when child-process state changes", async () => {
|
||||
let hasRunningSubprocess = false;
|
||||
let activity = {
|
||||
hasRunningSubprocess: false,
|
||||
runningPorts: [] as number[],
|
||||
};
|
||||
const { manager } = makeManager(5, {
|
||||
subprocessChecker: async () => hasRunningSubprocess,
|
||||
subprocessInspector: async () => activity,
|
||||
subprocessPollIntervalMs: 20,
|
||||
});
|
||||
const events: TerminalEvent[] = [];
|
||||
@@ -303,17 +310,39 @@ describe("TerminalManager", () => {
|
||||
await waitFor(() => events.some((event) => event.type === "started"));
|
||||
expect(events.some((event) => event.type === "activity")).toBe(false);
|
||||
|
||||
hasRunningSubprocess = true;
|
||||
activity = { hasRunningSubprocess: true, runningPorts: [3000] };
|
||||
await waitFor(
|
||||
() =>
|
||||
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true),
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "activity" &&
|
||||
event.hasRunningSubprocess === true &&
|
||||
event.runningPorts.join(",") === "3000",
|
||||
),
|
||||
1_200,
|
||||
);
|
||||
|
||||
hasRunningSubprocess = false;
|
||||
activity = { hasRunningSubprocess: true, runningPorts: [5173, 3000] };
|
||||
await waitFor(
|
||||
() =>
|
||||
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false),
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "activity" &&
|
||||
event.hasRunningSubprocess === true &&
|
||||
event.runningPorts.join(",") === "3000,5173",
|
||||
),
|
||||
1_200,
|
||||
);
|
||||
|
||||
activity = { hasRunningSubprocess: false, runningPorts: [5173] };
|
||||
await waitFor(
|
||||
() =>
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "activity" &&
|
||||
event.hasRunningSubprocess === false &&
|
||||
event.runningPorts.length === 0,
|
||||
),
|
||||
1_200,
|
||||
);
|
||||
|
||||
|
||||
@@ -27,8 +27,16 @@ const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
|
||||
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
|
||||
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
|
||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
||||
const MAX_PORT_NUMBER = 65_535;
|
||||
|
||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||
interface TerminalSubprocessActivity {
|
||||
hasRunningSubprocess: boolean;
|
||||
runningPorts: number[];
|
||||
}
|
||||
type TerminalSubprocessInspector = (
|
||||
terminalPid: number,
|
||||
) => Promise<TerminalSubprocessActivity>;
|
||||
|
||||
export interface TerminalManagerEvents {
|
||||
event: [event: TerminalEvent];
|
||||
@@ -40,6 +48,7 @@ export interface TerminalManagerOptions {
|
||||
ptyAdapter?: PtyAdapter;
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: TerminalSubprocessChecker;
|
||||
subprocessInspector?: TerminalSubprocessInspector;
|
||||
subprocessPollIntervalMs?: number;
|
||||
}
|
||||
|
||||
@@ -59,6 +68,7 @@ interface TerminalSessionState {
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
runningSubprocessPorts: number[];
|
||||
}
|
||||
|
||||
function defaultShellResolver(): string {
|
||||
@@ -125,11 +135,62 @@ function isRetryableShellSpawnError(error: unknown): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
async function checkWindowsSubprocessActivity(terminalPid: number): Promise<boolean> {
|
||||
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);
|
||||
}
|
||||
|
||||
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)];
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
async function collectWindowsChildPids(terminalPid: number): Promise<number[]> {
|
||||
const command = [
|
||||
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
|
||||
"if ($children) { exit 0 }",
|
||||
"exit 1",
|
||||
"if (-not $children) { exit 0 }",
|
||||
"$children | Select-Object -ExpandProperty ProcessId",
|
||||
].join("; ");
|
||||
try {
|
||||
const result = await runProcess(
|
||||
@@ -142,30 +203,47 @@ async function checkWindowsSubprocessActivity(terminalPid: number): Promise<bool
|
||||
outputMode: "truncate",
|
||||
},
|
||||
);
|
||||
return result.code === 0;
|
||||
if (result.code !== 0) {
|
||||
return [];
|
||||
}
|
||||
return parsePidList(result.stdout);
|
||||
} catch {
|
||||
return false;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolean> {
|
||||
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 pgrepResult = await runProcess("pgrep", ["-P", String(terminalPid)], {
|
||||
timeoutMs: 1_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
if (pgrepResult.code === 0) {
|
||||
return pgrepResult.stdout.trim().length > 0;
|
||||
}
|
||||
if (pgrepResult.code === 1) {
|
||||
return false;
|
||||
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 {
|
||||
// Fall back to ps when pgrep is unavailable.
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function collectPosixProcessFamilyPids(terminalPid: number): Promise<number[]> {
|
||||
try {
|
||||
const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], {
|
||||
timeoutMs: 1_000,
|
||||
@@ -174,32 +252,134 @@ async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolea
|
||||
outputMode: "truncate",
|
||||
});
|
||||
if (psResult.code !== 0) {
|
||||
return false;
|
||||
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;
|
||||
if (ppid === terminalPid) {
|
||||
return true;
|
||||
const children = childrenByParentPid.get(ppid);
|
||||
if (children) {
|
||||
children.push(pid);
|
||||
} else {
|
||||
childrenByParentPid.set(ppid, [pid]);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
|
||||
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 false;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
|
||||
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", "-iTCP", "-sTCP:LISTEN", "-p", processIds.join(",")],
|
||||
{
|
||||
timeoutMs: 1_500,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
);
|
||||
if (result.code === 0) {
|
||||
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 [];
|
||||
}
|
||||
}
|
||||
|
||||
async function defaultSubprocessInspector(
|
||||
terminalPid: number,
|
||||
): Promise<TerminalSubprocessActivity> {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
return { hasRunningSubprocess: false, runningPorts: [] };
|
||||
}
|
||||
|
||||
if (process.platform === "win32") {
|
||||
return checkWindowsSubprocessActivity(terminalPid);
|
||||
const childPids = await collectWindowsChildPids(terminalPid);
|
||||
if (childPids.length === 0) {
|
||||
return { hasRunningSubprocess: false, runningPorts: [] };
|
||||
}
|
||||
const runningPorts = await checkWindowsListeningPorts(childPids);
|
||||
return { hasRunningSubprocess: true, runningPorts };
|
||||
}
|
||||
return checkPosixSubprocessActivity(terminalPid);
|
||||
|
||||
const processFamilyPids = await collectPosixProcessFamilyPids(terminalPid);
|
||||
const subprocessPids = processFamilyPids.filter((pid) => pid !== terminalPid);
|
||||
if (subprocessPids.length === 0) {
|
||||
return { hasRunningSubprocess: false, runningPorts: [] };
|
||||
}
|
||||
|
||||
const runningPorts = await checkPosixListeningPorts(subprocessPids);
|
||||
return { hasRunningSubprocess: true, runningPorts };
|
||||
}
|
||||
|
||||
function capHistory(history: string, maxLines: number): string {
|
||||
@@ -262,7 +442,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
private readonly pendingPersistHistory = new Map<string, string>();
|
||||
private readonly threadLocks = new Map<string, Promise<void>>();
|
||||
private readonly persistDebounceMs: number;
|
||||
private readonly subprocessChecker: TerminalSubprocessChecker;
|
||||
private readonly subprocessInspector: TerminalSubprocessInspector;
|
||||
private readonly subprocessPollIntervalMs: number;
|
||||
private subprocessPollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private subprocessPollInFlight = false;
|
||||
@@ -275,7 +455,14 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.ptyAdapter = options.ptyAdapter ?? new NodePtyAdapter();
|
||||
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
||||
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
||||
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
||||
this.subprocessInspector =
|
||||
options.subprocessInspector ??
|
||||
(options.subprocessChecker
|
||||
? async (terminalPid: number) => ({
|
||||
hasRunningSubprocess: await options.subprocessChecker!(terminalPid),
|
||||
runningPorts: [],
|
||||
})
|
||||
: defaultSubprocessInspector);
|
||||
this.subprocessPollIntervalMs =
|
||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||
fs.mkdirSync(this.logsDir, { recursive: true });
|
||||
@@ -307,6 +494,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
runningSubprocessPorts: [],
|
||||
};
|
||||
this.sessions.set(sessionKey, session);
|
||||
this.startSession(session, input, "started");
|
||||
@@ -404,6 +592,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
runningSubprocessPorts: [],
|
||||
};
|
||||
this.sessions.set(sessionKey, session);
|
||||
} else {
|
||||
@@ -474,6 +663,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.exitCode = null;
|
||||
session.exitSignal = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.runningSubprocessPorts = [];
|
||||
session.updatedAt = new Date().toISOString();
|
||||
|
||||
let ptyProcess: PtyProcess | null = null;
|
||||
@@ -540,6 +730,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.pid = null;
|
||||
session.process = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.runningSubprocessPorts = [];
|
||||
session.updatedAt = new Date().toISOString();
|
||||
this.updateSubprocessPollingState();
|
||||
const message = error instanceof Error ? error.message : "Terminal start failed";
|
||||
@@ -577,6 +768,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.process = null;
|
||||
session.pid = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.runningSubprocessPorts = [];
|
||||
session.status = "exited";
|
||||
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
|
||||
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
|
||||
@@ -599,6 +791,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.process = null;
|
||||
session.pid = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.runningSubprocessPorts = [];
|
||||
session.status = "exited";
|
||||
session.updatedAt = new Date().toISOString();
|
||||
try {
|
||||
@@ -817,9 +1010,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
await Promise.all(
|
||||
runningSessions.map(async (session) => {
|
||||
const terminalPid = session.pid;
|
||||
let hasRunningSubprocess = false;
|
||||
let activity: TerminalSubprocessActivity = {
|
||||
hasRunningSubprocess: false,
|
||||
runningPorts: [],
|
||||
};
|
||||
try {
|
||||
hasRunningSubprocess = await this.subprocessChecker(terminalPid);
|
||||
activity = await this.subprocessInspector(terminalPid);
|
||||
} catch (error) {
|
||||
this.logger.warn("failed to check terminal subprocess activity", {
|
||||
threadId: session.threadId,
|
||||
@@ -834,11 +1030,19 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) {
|
||||
return;
|
||||
}
|
||||
if (liveSession.hasRunningSubprocess === hasRunningSubprocess) {
|
||||
const hasRunningSubprocess = activity.hasRunningSubprocess === true;
|
||||
const runningPorts = hasRunningSubprocess
|
||||
? normalizeRunningPorts(activity.runningPorts)
|
||||
: [];
|
||||
if (
|
||||
liveSession.hasRunningSubprocess === hasRunningSubprocess &&
|
||||
arePortListsEqual(liveSession.runningSubprocessPorts, runningPorts)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
liveSession.hasRunningSubprocess = hasRunningSubprocess;
|
||||
liveSession.runningSubprocessPorts = runningPorts;
|
||||
liveSession.updatedAt = new Date().toISOString();
|
||||
this.emitEvent({
|
||||
type: "activity",
|
||||
@@ -846,6 +1050,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
terminalId: liveSession.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
hasRunningSubprocess,
|
||||
runningPorts,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -99,6 +99,7 @@ function AutoProjectBootstrap() {
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
runningTerminalPorts: {},
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
|
||||
@@ -48,9 +48,10 @@ interface ThreadStatusPill {
|
||||
}
|
||||
|
||||
interface TerminalStatusIndicator {
|
||||
label: "Terminal process running";
|
||||
label: string;
|
||||
colorClass: string;
|
||||
pulse: boolean;
|
||||
portsLabel: string | null;
|
||||
}
|
||||
|
||||
function hasUnseenCompletion(thread: Thread): boolean {
|
||||
@@ -108,10 +109,27 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
||||
if (thread.runningTerminalIds.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const runningPorts = [...new Set(
|
||||
thread.runningTerminalIds.flatMap(
|
||||
(terminalId) => thread.runningTerminalPorts[terminalId] ?? [],
|
||||
),
|
||||
)]
|
||||
.filter((port) => Number.isInteger(port) && port > 0 && port <= 65_535)
|
||||
.toSorted((left, right) => left - right);
|
||||
|
||||
const label =
|
||||
runningPorts.length === 1
|
||||
? `Terminal process running on port ${runningPorts[0]}`
|
||||
: runningPorts.length > 1
|
||||
? `Terminal process running on ports ${runningPorts.join(", ")}`
|
||||
: "Terminal process running";
|
||||
|
||||
return {
|
||||
label: "Terminal process running",
|
||||
label,
|
||||
colorClass: "text-teal-600 dark:text-teal-300/90",
|
||||
pulse: true,
|
||||
portsLabel: runningPorts.length > 0 ? runningPorts.join(", ") : null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -153,6 +171,7 @@ export default function Sidebar() {
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
runningTerminalPorts: {},
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
@@ -526,15 +545,26 @@ export default function Sidebar() {
|
||||
</div>
|
||||
<div className="ml-2 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 className="inline-flex items-center gap-1">
|
||||
<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.portsLabel && (
|
||||
<span
|
||||
className={`max-w-20 truncate text-[10px] ${terminalStatus.colorClass}`}
|
||||
aria-label={`Ports ${terminalStatus.portsLabel}`}
|
||||
title={`Ports ${terminalStatus.portsLabel}`}
|
||||
>
|
||||
{terminalStatus.portsLabel}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-[10px] text-muted-foreground/40">
|
||||
|
||||
@@ -271,6 +271,7 @@ describe("toPersistedState", () => {
|
||||
terminalHeight: 320,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
runningTerminalIds: [],
|
||||
runningTerminalPorts: {},
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
|
||||
@@ -247,6 +247,7 @@ function hydrateThread(
|
||||
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: safeTerminalIds,
|
||||
runningTerminalIds: [],
|
||||
runningTerminalPorts: {},
|
||||
activeTerminalId,
|
||||
terminalGroups: normalizedGroups,
|
||||
activeTerminalGroupId,
|
||||
|
||||
@@ -42,6 +42,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
runningTerminalPorts: {},
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
@@ -111,6 +112,7 @@ function makeTerminalActivityEvent(
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:02.000Z",
|
||||
hasRunningSubprocess: true,
|
||||
runningPorts: [3000],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -303,6 +305,7 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.terminalOpen).toBe(false);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
expect(next.threads[0]?.runningTerminalPorts).toEqual({});
|
||||
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
@@ -325,14 +328,26 @@ describe("store reducer thread continuity", () => {
|
||||
event: makeTerminalActivityEvent(),
|
||||
});
|
||||
expect(active.threads[0]?.runningTerminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(active.threads[0]?.runningTerminalPorts).toEqual({
|
||||
[DEFAULT_THREAD_TERMINAL_ID]: [3000],
|
||||
});
|
||||
|
||||
const idle = reducer(active, {
|
||||
const activeWithPortChange = reducer(active, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: makeTerminalActivityEvent({ runningPorts: [5173, 3000] }),
|
||||
});
|
||||
expect(activeWithPortChange.threads[0]?.runningTerminalPorts).toEqual({
|
||||
[DEFAULT_THREAD_TERMINAL_ID]: [3000, 5173],
|
||||
});
|
||||
|
||||
const idle = reducer(activeWithPortChange, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: makeTerminalActivityEvent({ hasRunningSubprocess: false }),
|
||||
});
|
||||
expect(idle.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
expect(idle.threads[0]?.runningTerminalPorts).toEqual({});
|
||||
|
||||
const exited = reducer(active, {
|
||||
const exited = reducer(activeWithPortChange, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: {
|
||||
type: "exited",
|
||||
@@ -344,6 +359,7 @@ describe("store reducer thread continuity", () => {
|
||||
},
|
||||
});
|
||||
expect(exited.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
expect(exited.threads[0]?.runningTerminalPorts).toEqual({});
|
||||
});
|
||||
|
||||
it("keeps running status when another terminal in the thread is still running", () => {
|
||||
@@ -351,6 +367,10 @@ describe("store reducer thread continuity", () => {
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
runningTerminalPorts: {
|
||||
[DEFAULT_THREAD_TERMINAL_ID]: [3000],
|
||||
"term-2": [5173],
|
||||
},
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{
|
||||
@@ -375,6 +395,7 @@ describe("store reducer thread continuity", () => {
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual(["term-2"]);
|
||||
expect(next.threads[0]?.runningTerminalPorts).toEqual({ "term-2": [5173] });
|
||||
});
|
||||
|
||||
it("backfills codexThreadId from routed provider events", () => {
|
||||
|
||||
+43
-1
@@ -157,6 +157,29 @@ function normalizeRunningTerminalIds(
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
function normalizeRunningPorts(ports: number[]): number[] {
|
||||
if (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[]>,
|
||||
terminalIds: string[],
|
||||
): Record<string, number[]> {
|
||||
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 normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
@@ -257,6 +280,10 @@ function normalizeThreadTerminals(thread: Thread): Thread {
|
||||
...thread,
|
||||
terminalIds,
|
||||
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
|
||||
runningTerminalPorts: normalizeRunningTerminalPorts(
|
||||
thread.runningTerminalPorts,
|
||||
terminalIds,
|
||||
),
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId,
|
||||
@@ -276,6 +303,7 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
terminalOpen: false,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
runningTerminalPorts: {},
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
@@ -317,6 +345,9 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
...thread,
|
||||
terminalIds: remainingTerminalIds,
|
||||
runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
|
||||
runningTerminalPorts: Object.fromEntries(
|
||||
Object.entries(thread.runningTerminalPorts).filter(([key]) => key !== terminalId),
|
||||
),
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups: nextTerminalGroups,
|
||||
});
|
||||
@@ -683,21 +714,32 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
threads: updateThread(state.threads, action.event.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const runningTerminalIdSet = new Set(normalizedThread.runningTerminalIds);
|
||||
if (action.event.type === "started" || action.event.type === "restarted") {
|
||||
const runningTerminalPorts = { ...normalizedThread.runningTerminalPorts };
|
||||
if (
|
||||
action.event.type === "started" ||
|
||||
action.event.type === "restarted"
|
||||
) {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
delete runningTerminalPorts[action.event.terminalId];
|
||||
} else if (action.event.type === "activity") {
|
||||
if (action.event.hasRunningSubprocess) {
|
||||
runningTerminalIdSet.add(action.event.terminalId);
|
||||
runningTerminalPorts[action.event.terminalId] = normalizeRunningPorts(
|
||||
action.event.runningPorts,
|
||||
);
|
||||
} else {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
delete runningTerminalPorts[action.event.terminalId];
|
||||
}
|
||||
} else if (action.event.type === "exited" || action.event.type === "error") {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
delete runningTerminalPorts[action.event.terminalId];
|
||||
}
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
runningTerminalIds: [...runningTerminalIdSet],
|
||||
runningTerminalPorts,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -49,6 +49,7 @@ export interface Thread {
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
runningTerminalPorts: Record<string, number[]>;
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
|
||||
@@ -14,6 +14,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
runningTerminalPorts: {},
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
|
||||
@@ -147,6 +147,7 @@ describe("terminalEventSchema", () => {
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
hasRunningSubprocess: true,
|
||||
runningPorts: [3000],
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
@@ -89,6 +89,7 @@ export const terminalRestartedEventSchema = terminalEventBaseSchema.extend({
|
||||
export const terminalActivityEventSchema = terminalEventBaseSchema.extend({
|
||||
type: z.literal("activity"),
|
||||
hasRunningSubprocess: z.boolean(),
|
||||
runningPorts: z.array(z.number().int().min(1).max(65_535)).default([]),
|
||||
});
|
||||
|
||||
export const terminalEventSchema = z.discriminatedUnion("type", [
|
||||
|
||||
Reference in new issue
Block a user