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>`
This commit is contained in:
Julius Marminge committed 2026-02-15 16:47:19 -08:00
1 parent 94a83ab48e
commit 3d082fc73b
3 files changed
+298 -29

No files matched your search

+67 -2
View File
@@ -1,4 +1,5 @@
import fs from "node:fs";
import { createServer } from "node:http";
import os from "node:os";
import path from "node:path";
@@ -147,6 +148,7 @@ describe("TerminalManager", () => {
subprocessInspector?: (
terminalPid: number,
) => Promise<{ hasRunningSubprocess: boolean; runningPorts: number[] }>;
webPortInspector?: (port: number) => Promise<boolean>;
subprocessPollIntervalMs?: number;
} = {},
) {
@@ -160,6 +162,7 @@ describe("TerminalManager", () => {
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
...(options.subprocessInspector ? { subprocessInspector: options.subprocessInspector } : {}),
...(options.webPortInspector ? { webPortInspector: options.webPortInspector } : {}),
...(options.subprocessPollIntervalMs
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
: {}),
@@ -299,6 +302,7 @@ describe("TerminalManager", () => {
};
const { manager } = makeManager(5, {
subprocessInspector: async () => activity,
webPortInspector: async (port) => port === 3000,
subprocessPollIntervalMs: 20,
});
const events: TerminalEvent[] = [];
@@ -322,14 +326,14 @@ describe("TerminalManager", () => {
1_200,
);
activity = { hasRunningSubprocess: true, runningPorts: [5173, 3000] };
activity = { hasRunningSubprocess: true, runningPorts: [5173] };
await waitFor(
() =>
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === true &&
event.runningPorts.join(",") === "3000,5173",
event.runningPorts.length === 0,
),
1_200,
);
@@ -349,6 +353,67 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("ignores ports that return HTTP 404 at root during web-port detection", async () => {
const notFoundServer = createServer((_req, res) => {
res.statusCode = 404;
res.end();
});
await new Promise<void>((resolve, reject) => {
notFoundServer.listen(0, "127.0.0.1", (error?: Error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
const address = notFoundServer.address();
const port = typeof address === "object" && address ? address.port : 0;
expect(port).toBeGreaterThan(0);
const events: TerminalEvent[] = [];
let activity = {
hasRunningSubprocess: false,
runningPorts: [] as number[],
};
const { manager } = makeManager(5, {
subprocessInspector: async () => activity,
subprocessPollIntervalMs: 20,
});
manager.on("event", (event) => {
events.push(event);
});
try {
await manager.open(openInput());
await waitFor(() => events.some((event) => event.type === "started"));
activity = { hasRunningSubprocess: true, runningPorts: [port] };
await waitFor(
() =>
events.some(
(event) =>
event.type === "activity" &&
event.hasRunningSubprocess === true &&
event.runningPorts.length === 0,
),
1_500,
);
} finally {
manager.dispose();
await new Promise<void>((resolve, reject) => {
notFoundServer.close((error?: Error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
});
it("caps persisted history to configured line limit", async () => {
const { manager, ptyAdapter } = makeManager(3);
await manager.open(openInput());
+173 -1
View File
@@ -1,5 +1,6 @@
import { EventEmitter } from "node:events";
import fs from "node:fs";
import { request as httpRequest } from "node:http";
import path from "node:path";
import {
@@ -27,9 +28,13 @@ 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 DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS = 500;
const DEFAULT_WEB_PORT_PROBE_TTL_MS = 10_000;
const WEB_PORT_PROBE_MAX_BODY_BYTES = 8_192;
const MAX_PORT_NUMBER = 65_535;
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
type TerminalWebPortInspector = (port: number) => Promise<boolean>;
interface TerminalSubprocessActivity {
hasRunningSubprocess: boolean;
runningPorts: number[];
@@ -49,6 +54,8 @@ export interface TerminalManagerOptions {
shellResolver?: () => string;
subprocessChecker?: TerminalSubprocessChecker;
subprocessInspector?: TerminalSubprocessInspector;
webPortInspector?: TerminalWebPortInspector;
webPortProbeCacheTtlMs?: number;
subprocessPollIntervalMs?: number;
}
@@ -382,6 +389,115 @@ async function defaultSubprocessInspector(
return { hasRunningSubprocess: true, runningPorts };
}
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 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) {
res.destroy();
}
});
res.on("end", () => {
settle({
status: res.statusCode ?? 0,
contentType: normalizeHeaderValue(res.headers["content-type"]),
location: normalizeHeaderValue(res.headers.location),
body: chunks.join(""),
});
});
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();
});
}
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);
}
function capHistory(history: string, maxLines: number): string {
if (history.length === 0) return history;
const hasTrailingNewline = history.endsWith("\n");
@@ -443,6 +559,13 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private readonly threadLocks = new Map<string, Promise<void>>();
private readonly persistDebounceMs: number;
private readonly subprocessInspector: TerminalSubprocessInspector;
private readonly webPortInspector: TerminalWebPortInspector;
private readonly webPortProbeCacheTtlMs: number;
private readonly webPortProbeCache = new Map<
number,
{ isWeb: boolean; checkedAt: number }
>();
private readonly webPortProbeInFlight = new Map<number, Promise<boolean>>();
private readonly subprocessPollIntervalMs: number;
private subprocessPollTimer: ReturnType<typeof setInterval> | null = null;
private subprocessPollInFlight = false;
@@ -463,6 +586,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
runningPorts: [],
})
: defaultSubprocessInspector);
this.webPortInspector = options.webPortInspector ?? defaultWebPortInspector;
this.webPortProbeCacheTtlMs =
options.webPortProbeCacheTtlMs ?? DEFAULT_WEB_PORT_PROBE_TTL_MS;
this.subprocessPollIntervalMs =
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
fs.mkdirSync(this.logsDir, { recursive: true });
@@ -647,6 +773,8 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.pendingPersistHistory.clear();
this.threadLocks.clear();
this.persistQueues.clear();
this.webPortProbeCache.clear();
this.webPortProbeInFlight.clear();
}
private startSession(
@@ -993,6 +1121,48 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.subprocessPollTimer = null;
}
private async inspectWebPortCached(port: number): Promise<boolean> {
const now = Date.now();
const cached = this.webPortProbeCache.get(port);
if (cached && now - cached.checkedAt <= this.webPortProbeCacheTtlMs) {
return cached.isWeb;
}
const inFlight = this.webPortProbeInFlight.get(port);
if (inFlight) {
return inFlight;
}
const probe = this.webPortInspector(port)
.then((isWeb) => {
this.webPortProbeCache.set(port, {
isWeb,
checkedAt: Date.now(),
});
return isWeb;
})
.catch(() => false)
.finally(() => {
this.webPortProbeInFlight.delete(port);
});
this.webPortProbeInFlight.set(port, probe);
return probe;
}
private async detectWebPorts(runningPorts: number[]): Promise<number[]> {
if (runningPorts.length === 0) return [];
const checks = await Promise.all(
runningPorts.map(async (port) => ({
port,
isWeb: await this.inspectWebPortCached(port),
})),
);
return checks
.filter((entry) => entry.isWeb)
.map((entry) => entry.port)
.toSorted((left, right) => left - right);
}
private async pollSubprocessActivity(): Promise<void> {
if (this.subprocessPollInFlight) return;
@@ -1032,7 +1202,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
}
const hasRunningSubprocess = activity.hasRunningSubprocess === true;
const runningPorts = hasRunningSubprocess
? normalizeRunningPorts(activity.runningPorts)
? normalizeRunningPorts(
await this.detectWebPorts(normalizeRunningPorts(activity.runningPorts)),
)
: [];
if (
liveSession.hasRunningSubprocess === hasRunningSubprocess &&
+58 -26
View File
@@ -1,5 +1,5 @@
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { GlobeIcon, MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
import { type MouseEvent, useCallback, useEffect, useMemo, useState } from "react";
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { isElectron } from "../env";
@@ -51,7 +51,7 @@ interface TerminalStatusIndicator {
label: string;
colorClass: string;
pulse: boolean;
portsLabel: string | null;
primaryWebPort: number | null;
}
function hasUnseenCompletion(thread: Thread): boolean {
@@ -119,17 +119,20 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
.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";
runningPorts.length === 0
? "Terminal process running"
: runningPorts.length === 1
? `Open web server: http://localhost:${runningPorts[0]}`
: `Open web server: http://localhost:${runningPorts[0]} (detected web ports: ${runningPorts.join(", ")})`;
return {
label,
colorClass: "text-teal-600 dark:text-teal-300/90",
colorClass:
runningPorts.length >= 1
? "text-sky-600 dark:text-sky-300/90"
: "text-teal-600 dark:text-teal-300/90",
pulse: true,
portsLabel: runningPorts.length > 0 ? runningPorts.join(", ") : null,
primaryWebPort: runningPorts[0] ?? null,
};
}
@@ -398,6 +401,16 @@ export default function Sidebar() {
[api, dispatch, state.projects, state.threads],
);
const openWebPort = useCallback(
(event: MouseEvent<HTMLElement>, port: number) => {
event.preventDefault();
event.stopPropagation();
if (!api) return;
void api.shell.openExternal(`http://localhost:${port}`).catch(() => undefined);
},
[api],
);
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
if (!isChatNewShortcut(event, keybindings)) return;
@@ -545,24 +558,43 @@ export default function Sidebar() {
</div>
<div className="ml-2 flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<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="inline-flex items-center">
{terminalStatus.primaryWebPort !== null ? (
<span
className={`max-w-20 truncate text-[10px] ${terminalStatus.colorClass}`}
aria-label={`Ports ${terminalStatus.portsLabel}`}
title={`Ports ${terminalStatus.portsLabel}`}
role="link"
tabIndex={0}
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
onClick={(event) =>
openWebPort(event, terminalStatus.primaryWebPort!)
}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
event.stopPropagation();
if (!api) return;
void api.shell
.openExternal(
`http://localhost:${terminalStatus.primaryWebPort!}`,
)
.catch(() => undefined);
}}
>
{terminalStatus.portsLabel}
<GlobeIcon
className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
/>
</span>
) : (
<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>
)}
</span>