diff --git a/apps/server/src/terminalManager.test.ts b/apps/server/src/terminalManager.test.ts index 3f092946f0..7266c8cf3b 100644 --- a/apps/server/src/terminalManager.test.ts +++ b/apps/server/src/terminalManager.test.ts @@ -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; 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((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((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()); diff --git a/apps/server/src/terminalManager.ts b/apps/server/src/terminalManager.ts index 2ffbedfcba..f4ee6b904a 100644 --- a/apps/server/src/terminalManager.ts +++ b/apps/server/src/terminalManager.ts @@ -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; +type TerminalWebPortInspector = (port: number) => Promise; 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(" { + return new Promise((resolve) => { + let timer: ReturnType | 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 { + 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 { private readonly threadLocks = new Map>(); 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>(); private readonly subprocessPollIntervalMs: number; private subprocessPollTimer: ReturnType | null = null; private subprocessPollInFlight = false; @@ -463,6 +586,9 @@ export class TerminalManager extends EventEmitter { 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 { 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 { this.subprocessPollTimer = null; } + private async inspectWebPortCached(port: number): Promise { + 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 { + 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 { if (this.subprocessPollInFlight) return; @@ -1032,7 +1202,9 @@ export class TerminalManager extends EventEmitter { } const hasRunningSubprocess = activity.hasRunningSubprocess === true; const runningPorts = hasRunningSubprocess - ? normalizeRunningPorts(activity.runningPorts) + ? normalizeRunningPorts( + await this.detectWebPorts(normalizeRunningPorts(activity.runningPorts)), + ) : []; if ( liveSession.hasRunningSubprocess === hasRunningSubprocess && diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index a285d386b6..aed7909a84 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -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, 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() {
{terminalStatus && ( - - - - - {terminalStatus.portsLabel && ( + + {terminalStatus.primaryWebPort !== null ? ( + 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} + + + ) : ( + + )}