From 5ca68283715d74e5916a2f3b6dcd55b2702e2748 Mon Sep 17 00:00:00 2001 From: Jonathan Avila Date: Fri, 22 May 2026 03:52:51 -0400 Subject: [PATCH] feat: surface dev-server URLs in the ports panel (#2534) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Surface dev-server URLs in workspace ports panel Why: the OS scanner only sees `127.0.0.1:3001`, so clicking a Vite port in the panel opens the wrong host/protocol when the dev server binds with a custom hostname or HTTPS (e.g. `https://local.getmontecarlo.com:3001/`). We now watch PTY output for advertised origins and prefer them at display, copy, and open time. Falls back to the OS-derived address. The watcher taps the central `runtime.onPtyData` path so it sees local, daemon-backed, and SSH PTYs uniformly. URL candidates are validated with `new URL()`, sanitized to origin only (no path/query/fragment/userinfo), and gated by listener-PID validation so stale entries get evicted when a different process reuses the port. SSH `DetectedPort` enrichment is out of scope here — that panel uses separate data shapes and port-forwarding may rewrite the local port, making naive URL reuse incorrect. Tracked as a follow-up. Co-Authored-By: Claude Opus 4.7 (1M context) * Extend advertised-URL enrichment to SSH ports Why: the first cut only enriched the local workspace ports panel. SSH worktrees use a separate panel with `DetectedPort` and `PortForwardEntry` shapes scanned by the remote relay, so the same dev-server banners that flow through Orca's SSH PTYs were captured by the watcher but never surfaced. The renderer-side SSH scanner doesn't know which worktreeId the watcher keyed an entry under, so a small helper walks the store to find every worktree attached to a given connection and asks the watcher for the best match per port (custom DNS host > loopback > LAN IP, https and recency as tie-breakers). Enrichment runs at every broadcast and list site in src/main/ipc/ssh.ts. For a forwarded SSH port, the open action now uses `advertisedProtocol://customHost:localPort`. We deliberately reuse the local forward port — the remote port number is not reachable from the local machine — and we only reuse the host when it's a custom DNS name (IP literals and the remote's `localhost` get ignored, falling back to 127.0.0.1 like before). Loopback advertisements from the remote box are a no-op because they don't translate to the local browser. Co-Authored-By: Claude Opus 4.7 (1M context) * Address Codex review of advertised-URL enrichment Four findings from the post-implementation review: - Watcher rejects wildcard advertised hosts (`0.0.0.0`, `::`, `*`). The OS scanner already normalizes wildcards to localhost for the connect host; if a dev server prints `http://0.0.0.0:3000/` verbatim we keep that sensible default instead of letting the watcher overwrite it with a host the browser can't open. - Pre-bind pending buffer is now capped at 32 distinct PTY IDs with LRU eviction. Spawn-failure paths could otherwise leave never-bound entries forever — per-PTY 16 KiB bound was the only guard. - `clearProviderPtyState` now calls `advertisedUrlWatcher.unbindPty`. SSH reattach failures, `clearPtyOwnershipForConnection`, and daemon spawn-failure cleanup bypass `runtime.onPtyExit`; routing through the central provider teardown plugs those holes (and is idempotent with the existing `onPtyExit` hook for natural exits). - `lookupBest` accepts an optional current listener PID and runs the same pin-then-evict logic as `lookup`. `enrichSshDetectedPorts` threads `DetectedPort.pid` through so a stale advertised URL gets evicted on remote port reuse. Forward enrichment stays best-effort (forwards are persisted config, not observed listeners — detected enrichment is the eviction path). Co-Authored-By: Claude Opus 4.7 (1M context) * fix: refresh SSH ports when advertised URLs change Co-authored-by: Orca * fix: show advertised URLs in port rows Co-authored-by: Orca * fix: address advertised URL review issues Co-authored-by: Orca * fix: tighten advertised URL cache handling Co-authored-by: Orca * fix: align advertised URL edge cases Co-authored-by: Orca * fix: handle advertised URL cache invalidation Co-authored-by: Orca * fix: show status port action tooltips Co-authored-by: Orca * fix: keep port action tooltips above popover Co-authored-by: Orca * fix: clear port action focus after click Co-authored-by: Orca --------- Co-authored-by: Claude Opus 4.7 (1M context) Co-authored-by: Jinwoo-H Co-authored-by: Orca --- src/main/ipc/pty.ts | 6 + src/main/ipc/ssh.ts | 89 ++- ...ertised-url-watcher-pid-validation.test.ts | 137 ++++ src/main/ports/advertised-url-watcher.test.ts | 298 ++++++++ src/main/ports/advertised-url-watcher.ts | 653 ++++++++++++++++++ .../ports/local-workspace-port-scanner.ts | 48 +- .../ssh-advertised-url-enrichment.test.ts | 313 +++++++++ .../ports/ssh-advertised-url-enrichment.ts | 140 ++++ src/main/runtime/orca-runtime.test.ts | 13 + src/main/runtime/orca-runtime.ts | 12 + src/preload/api-types.ts | 6 +- src/preload/index.ts | 8 +- .../right-sidebar/PortsPanel.test.tsx | 48 +- .../components/right-sidebar/PortsPanel.tsx | 67 +- .../sidebar/WorktreeCardPorts.test.tsx | 51 ++ .../components/sidebar/WorktreeCardPorts.tsx | 33 +- .../status-bar/PortsStatusSegment.tsx | 40 +- .../src/lib/workspace-port-actions.ts | 19 +- src/renderer/src/lib/workspace-port-urls.ts | 118 ++++ src/renderer/src/store/slices/ssh.ts | 10 +- src/shared/ssh-types.ts | 14 + src/shared/workspace-ports.ts | 6 + 22 files changed, 2042 insertions(+), 87 deletions(-) create mode 100644 src/main/ports/advertised-url-watcher-pid-validation.test.ts create mode 100644 src/main/ports/advertised-url-watcher.test.ts create mode 100644 src/main/ports/advertised-url-watcher.ts create mode 100644 src/main/ports/ssh-advertised-url-enrichment.test.ts create mode 100644 src/main/ports/ssh-advertised-url-enrichment.ts create mode 100644 src/renderer/src/components/sidebar/WorktreeCardPorts.test.tsx create mode 100644 src/renderer/src/lib/workspace-port-urls.ts diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index e4dc7c00d..30a884420 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -29,6 +29,7 @@ import { } from '../claude-accounts/live-pty-gate' import { applyTerminalAttributionEnv } from '../attribution/terminal-attribution' import { registerPty, unregisterPty } from '../memory/pty-registry' +import { advertisedUrlWatcher } from '../ports/advertised-url-watcher' import { track } from '../telemetry/client' import { classifyError } from '../telemetry/classify-error' import { getCohortAtEmit } from '../telemetry/cohort-classifier' @@ -484,6 +485,11 @@ export function clearProviderPtyState(id: string): void { // trying to resolve its (now-dead) pid on every snapshot. Safe no-op for // PTYs that were never registered (SSH-owned). unregisterPty(id) + // Why: cover lifecycle paths that bypass runtime.onPtyExit — SSH reattach + // failures, SSH connection shutdown (clearPtyOwnershipForConnection), and + // daemon spawn-failure cleanup all funnel through here. Without this the + // watcher's per-PTY buffer and worktree binding outlive the PTY. + advertisedUrlWatcher.unbindPty(id) clearMigrationUnsupportedPty(id) agentHookServer.clearPaneKeyAliasesForPty(id, { shouldClearStablePaneKey: (stablePaneKey) => { diff --git a/src/main/ipc/ssh.ts b/src/main/ipc/ssh.ts index 63113f5e5..4e2f03037 100644 --- a/src/main/ipc/ssh.ts +++ b/src/main/ipc/ssh.ts @@ -9,6 +9,7 @@ import { SshRelaySession } from '../ssh/ssh-relay-session' import { SshPortForwardManager } from '../ssh/ssh-port-forward' import { type DetectedPort, + type EnrichedDetectedPort, type SavedPortForward, type SshTarget, type SshConnectionStatus, @@ -20,6 +21,13 @@ import { forceStopRelayForTarget } from '../ssh/ssh-relay-reset' import { isSshPtyNotFoundError } from '../providers/ssh-pty-provider' import { toAppSshPtyId, toRelaySshPtyId } from '../providers/ssh-pty-id' import { registerSshBrowseHandler } from './ssh-browse' +import { + getConnectionIdsForWorktree, + enrichSshDetectedPorts, + enrichSshForwardEntries, + getWorktreeIdsForConnection +} from '../ports/ssh-advertised-url-enrichment' +import { advertisedUrlWatcher } from '../ports/advertised-url-watcher' import { requestCredential, registerCredentialHandler } from './ssh-passphrase' import { clearProviderPtyState, @@ -34,6 +42,8 @@ let connectionManager: SshConnectionManager | null = null let portForwardManager: SshPortForwardManager | null = null let registeredConnectSshTarget: ((targetId: string) => Promise) | null = null let registeredGetSshState: ((targetId: string) => SshConnectionState | undefined) | null = null +let persistedStore: Store | null = null +let advertisedUrlWatcherUnsubscribe: (() => void) | null = null export async function connectRegisteredSshTarget(targetId: string): Promise { if (!registeredConnectSshTarget) { @@ -142,20 +152,50 @@ function broadcastPortForwards(getMainWindow: () => BrowserWindow | null, target if (!win || win.isDestroyed()) { return } - const forwards = portForwardManager!.listForwards(targetId) - win.webContents.send('ssh:port-forwards-changed', { targetId, forwards }) + win.webContents.send('ssh:port-forwards-changed', { + targetId, + forwards: listForwardsEnriched(targetId) + }) } function broadcastDetectedPorts( getMainWindow: () => BrowserWindow | null, targetId: string, - ports: DetectedPort[] + ports: DetectedPort[], + options?: Parameters[3] ): void { const win = getMainWindow() if (!win || win.isDestroyed()) { return } - win.webContents.send('ssh:detected-ports-changed', { targetId, ports }) + win.webContents.send('ssh:detected-ports-changed', { + targetId, + ports: enrichDetected(targetId, ports, options) + }) +} + +function listForwardsEnriched(targetId: string): ReturnType { + const raw = portForwardManager!.listForwards(targetId) + if (!persistedStore) { + return raw + } + return enrichSshForwardEntries(raw, getWorktreeIdsForConnection(persistedStore, targetId)) +} + +function enrichDetected( + targetId: string, + ports: DetectedPort[], + options?: Parameters[3] +): EnrichedDetectedPort[] { + if (!persistedStore) { + return ports + } + return enrichSshDetectedPorts( + ports, + getWorktreeIdsForConnection(persistedStore, targetId), + undefined, + options + ) } // Why: after user-initiated add/remove/update the runtime manager is the @@ -241,6 +281,33 @@ async function restorePortForwards( broadcastPortForwards(getMainWindow, targetId) } +function registerAdvertisedUrlRefresh(getMainWindow: () => BrowserWindow | null): void { + advertisedUrlWatcherUnsubscribe?.() + // Why: SSH port scans only emit when raw host/port/PID data changes. A + // terminal can print the advertised URL after the raw port row is already + // visible, so the watcher must also trigger a renderer refresh. + advertisedUrlWatcherUnsubscribe = advertisedUrlWatcher.onDidChange(({ worktreeId }) => { + if (!persistedStore) { + return + } + for (const targetId of getConnectionIdsForWorktree(persistedStore, worktreeId)) { + const session = activeSessions.get(targetId) + if (!session) { + continue + } + const scanner = session.getPortScanner() + if (scanner) { + // Why: watcher changes can arrive before the next SSH scan refreshes + // listener PIDs; cached scanner rows must not pin a fresh URL stale. + broadcastDetectedPorts(getMainWindow, targetId, scanner.getDetectedPorts(targetId), { + validatePid: false + }) + } + broadcastPortForwards(getMainWindow, targetId) + } + }) +} + export function registerSshHandlers( store: Store, getMainWindow: () => BrowserWindow | null, @@ -272,6 +339,8 @@ export function registerSshHandlers( } sshStore = new SshConnectionStore(store) + persistedStore = store + registerAdvertisedUrlRefresh(getMainWindow) registerCredentialHandler(getMainWindow) @@ -951,12 +1020,20 @@ export function registerSshHandlers( }) ipcMain.handle('ssh:listPortForwards', (_event, args?: { targetId?: string }) => { - return portForwardManager!.listForwards(args?.targetId) + const all = portForwardManager!.listForwards(args?.targetId) + if (!persistedStore || !args?.targetId) { + // Why: the cross-target list is rare and we cannot map every entry to + // worktrees in a single call; serve the raw list. Per-target callers + // get full enrichment. + return all + } + return enrichSshForwardEntries(all, getWorktreeIdsForConnection(persistedStore, args.targetId)) }) ipcMain.handle('ssh:listDetectedPorts', (_event, args: { targetId: string }) => { const session = activeSessions.get(args.targetId) - return session?.getPortScanner()?.getDetectedPorts(args.targetId) ?? [] + const ports = session?.getPortScanner()?.getDetectedPorts(args.targetId) ?? [] + return enrichDetected(args.targetId, ports) }) return { connectionManager, sshStore } diff --git a/src/main/ports/advertised-url-watcher-pid-validation.test.ts b/src/main/ports/advertised-url-watcher-pid-validation.test.ts new file mode 100644 index 000000000..abed89fba --- /dev/null +++ b/src/main/ports/advertised-url-watcher-pid-validation.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it } from 'vitest' +import { AdvertisedUrlWatcher } from './advertised-url-watcher' + +const WORKTREE = 'repo::/repo' +const PTY = 'pty-1' + +function bindFresh(now = 1_000): AdvertisedUrlWatcher { + const watcher = new AdvertisedUrlWatcher({ now: () => now }) + watcher.bindPty(PTY, WORKTREE) + return watcher +} + +describe('AdvertisedUrlWatcher.lookupBest PID validation', () => { + it('pins the listener PID on first lookupBest match', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'A: https://a.example.com:3001/\n') + const first = watcher.lookupBest([WORKTREE], 3001, 4242) + expect(first?.validatedListenerPid).toBe(4242) + const second = watcher.lookupBest([WORKTREE], 3001, 4242) + expect(second?.host).toBe('a.example.com') + }) + + it('evicts stale candidates after scanner-observed listener PID changes', () => { + const watcher = bindFresh() + watcher.bindPty('pty-2', 'repo::/wt2') + const events: { worktreeId: string; port: number }[] = [] + watcher.onDidChange((event) => events.push(event)) + watcher.ingest(PTY, 'A: http://localhost:3001/\n') + watcher.ingest('pty-2', 'B: https://custom.example.com:3001/\n') + watcher.reconcileScan([WORKTREE, 'repo::/wt2'], [{ port: 3001, pid: 4242 }]) + expect(watcher.lookupBest([WORKTREE, 'repo::/wt2'], 3001, 4242)?.host).toBe( + 'custom.example.com' + ) + expect(watcher.lookup(WORKTREE, 3001)?.validatedListenerPid).toBeUndefined() + // Remote port reused by a different process: the pinned winner and the + // unvalidated non-winner both get evicted by scanner reconciliation. + watcher.reconcileScan([WORKTREE, 'repo::/wt2'], [{ port: 3001, pid: 9999 }]) + expect(watcher.lookupBest([WORKTREE, 'repo::/wt2'], 3001, 9999)).toBeUndefined() + expect(watcher.lookupBest([WORKTREE, 'repo::/wt2'], 3001)).toBeUndefined() + expect(events).toContainEqual({ worktreeId: WORKTREE, port: 3001 }) + expect(events).toContainEqual({ worktreeId: 'repo::/wt2', port: 3001 }) + }) + + it('pins only the selected lookupBest winner when candidates share a port', () => { + const watcher = bindFresh() + watcher.bindPty('pty-2', 'repo::/wt2') + watcher.ingest(PTY, 'A: http://localhost:3001/\n') + watcher.ingest('pty-2', 'B: https://custom.example.com:3001/\n') + + const best = watcher.lookupBest([WORKTREE, 'repo::/wt2'], 3001, 4242) + + expect(best?.host).toBe('custom.example.com') + expect(watcher.lookup('repo::/wt2', 3001)?.validatedListenerPid).toBe(4242) + expect(watcher.lookup(WORKTREE, 3001)?.validatedListenerPid).toBeUndefined() + }) + + it('falls through to a still-valid candidate when one entry was reassigned', () => { + const watcher = bindFresh() + watcher.bindPty('pty-2', 'repo::/wt2') + watcher.ingest(PTY, 'A: https://a.example.com:3001/\n') + watcher.ingest('pty-2', 'B: https://b.example.com:3001/\n') + // Pin only the WORKTREE entry to PID 100. + expect(watcher.lookup(WORKTREE, 3001, 100)?.host).toBe('a.example.com') + // Now query with PID 200 across both worktrees: the WORKTREE entry + // gets evicted (mismatch), and the repo::/wt2 entry - which had no + // pinned PID yet - gets pinned to 200 and wins. + expect(watcher.lookupBest([WORKTREE, 'repo::/wt2'], 3001, 200)?.host).toBe('b.example.com') + }) +}) + +describe('AdvertisedUrlWatcher.lookup PID validation', () => { + it('records the listener PID on first lookup that supplies one', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'A: https://a.example.com:3001/\n') + const first = watcher.lookup(WORKTREE, 3001, 4242) + expect(first?.validatedListenerPid).toBe(4242) + // Same PID on a later lookup keeps the entry. + const second = watcher.lookup(WORKTREE, 3001, 4242) + expect(second?.host).toBe('a.example.com') + }) + + it('evicts the entry when the listener PID changes', () => { + const watcher = bindFresh() + const events: { worktreeId: string; port: number }[] = [] + watcher.onDidChange((event) => events.push(event)) + watcher.ingest(PTY, 'A: https://a.example.com:3001/\n') + expect(watcher.lookup(WORKTREE, 3001, 4242)?.validatedListenerPid).toBe(4242) + // Different PID means the port was reused by another process. + expect(watcher.lookup(WORKTREE, 3001, 9999)).toBeUndefined() + // Entry is gone. + expect(watcher.lookup(WORKTREE, 3001, 4242)).toBeUndefined() + expect(events).toContainEqual({ worktreeId: WORKTREE, port: 3001 }) + }) + + it('skips validation when no PID is provided', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'A: https://a.example.com:3001/\n') + watcher.lookup(WORKTREE, 3001, 4242) // pins PID + // Looking up without a PID does not evict. + expect(watcher.lookup(WORKTREE, 3001)?.host).toBe('a.example.com') + }) + + it('replacing a cached URL resets validatedListenerPid', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'A: http://localhost:3001/\n') + watcher.lookup(WORKTREE, 3001, 100) // pins PID to old listener + // A higher-score URL replaces; the new entry starts unvalidated. + watcher.ingest(PTY, 'B: https://custom.example.com:3001/\n') + const refreshed = watcher.lookup(WORKTREE, 3001) + expect(refreshed?.host).toBe('custom.example.com') + expect(refreshed?.validatedListenerPid).toBeUndefined() + }) + + it('evicts an unvalidated URL when scanner sees its port absent before reuse', () => { + const watcher = bindFresh() + const events: { worktreeId: string; port: number }[] = [] + watcher.onDidChange((event) => events.push(event)) + + watcher.reconcileScan([WORKTREE], [{ port: 3001, pid: 100 }]) + watcher.ingest(PTY, 'A: https://a.example.com:3001/\n') + watcher.reconcileScan([WORKTREE], []) + watcher.reconcileScan([WORKTREE], [{ port: 3001, pid: 200 }]) + + expect(watcher.lookup(WORKTREE, 3001, 200)).toBeUndefined() + expect(events).toContainEqual({ worktreeId: WORKTREE, port: 3001 }) + }) + + it('evicts an unvalidated URL when scanner observes a different PID first', () => { + const watcher = bindFresh() + + watcher.reconcileScan([WORKTREE], [{ port: 3001, pid: 100 }]) + watcher.ingest(PTY, 'A: https://a.example.com:3001/\n') + watcher.reconcileScan([WORKTREE], [{ port: 3001, pid: 200 }]) + + expect(watcher.lookup(WORKTREE, 3001, 200)).toBeUndefined() + }) +}) diff --git a/src/main/ports/advertised-url-watcher.test.ts b/src/main/ports/advertised-url-watcher.test.ts new file mode 100644 index 000000000..8ec67d0b2 --- /dev/null +++ b/src/main/ports/advertised-url-watcher.test.ts @@ -0,0 +1,298 @@ +import { describe, expect, it } from 'vitest' +import { + AdvertisedUrlWatcher, + classifyHost, + extractUrlCandidates, + stripTerminalControls +} from './advertised-url-watcher' + +const WORKTREE = 'repo::/repo' +const PTY = 'pty-1' + +function bindFresh(now = 1_000): AdvertisedUrlWatcher { + const watcher = new AdvertisedUrlWatcher({ now: () => now }) + watcher.bindPty(PTY, WORKTREE) + return watcher +} + +describe('stripTerminalControls', () => { + it('strips CSI color codes and CRLF', () => { + expect(stripTerminalControls('\x1b[32mhello\x1b[0m\r\n')).toBe('hello\n') + }) + + it('strips OSC sequences terminated by BEL or ST', () => { + expect(stripTerminalControls('\x1b]0;title\x07rest')).toBe('rest') + expect(stripTerminalControls('\x1b]8;;https://example.com\x1b\\link\x1b]8;;\x1b\\')).toBe( + 'link' + ) + }) + + it('drops non-printable bytes but keeps whitespace and printable ASCII', () => { + expect(stripTerminalControls('a\x00b\x08c\td')).toBe('abc\td') + }) +}) + +describe('extractUrlCandidates', () => { + it('finds plain URLs', () => { + const urls = extractUrlCandidates('Server: https://example.com:3001/ ready') + expect(urls.map((u) => u.href)).toEqual(['https://example.com:3001/']) + }) + + it('trims trailing punctuation', () => { + const urls = extractUrlCandidates('open https://example.com:3001/. now.') + expect(urls).toHaveLength(1) + expect(urls[0].port).toBe('3001') + }) + + it('parses IPv6 with brackets', () => { + const urls = extractUrlCandidates('Local: http://[::1]:5173/') + expect(urls).toHaveLength(1) + // Node returns IPv6 hostnames with brackets retained. + expect(urls[0].hostname.replace(/^\[|\]$/g, '')).toBe('::1') + expect(urls[0].port).toBe('5173') + }) + + it('ignores non-http(s) schemes and bare hostnames', () => { + expect(extractUrlCandidates('ftp://example.com')).toHaveLength(0) + expect(extractUrlCandidates('example.com:3001')).toHaveLength(0) + }) + + it('handles multiple URLs in one line', () => { + const urls = extractUrlCandidates( + 'Local: http://localhost:3001/ Network: https://custom:3001/' + ) + expect(urls.map((u) => u.hostname).sort()).toEqual(['custom', 'localhost']) + }) +}) + +describe('classifyHost', () => { + it('classifies loopback hosts', () => { + expect(classifyHost('localhost')).toBe('loopback') + expect(classifyHost('127.0.0.1')).toBe('loopback') + expect(classifyHost('::1')).toBe('loopback') + }) + + it('classifies private IPv4 ranges', () => { + expect(classifyHost('10.0.0.1')).toBe('private-ip') + expect(classifyHost('172.16.5.5')).toBe('private-ip') + expect(classifyHost('192.168.1.50')).toBe('private-ip') + expect(classifyHost('169.254.1.1')).toBe('private-ip') + }) + + it('classifies public IPv4', () => { + expect(classifyHost('8.8.8.8')).toBe('public-ip') + expect(classifyHost('172.15.0.1')).toBe('public-ip') // just outside private range + }) + + it('classifies private IPv6 ranges', () => { + expect(classifyHost('fc00::1')).toBe('private-ip') + expect(classifyHost('fd12::1')).toBe('private-ip') + expect(classifyHost('fe80::1')).toBe('private-ip') + expect(classifyHost('fe90::1')).toBe('private-ip') + expect(classifyHost('fea0::1')).toBe('private-ip') + expect(classifyHost('[febf::1]')).toBe('private-ip') + }) + + it('classifies IPv6 addresses outside private ranges as public', () => { + expect(classifyHost('2001:db8::1')).toBe('public-ip') + expect(classifyHost('fe7f::1')).toBe('public-ip') + expect(classifyHost('fec0::1')).toBe('public-ip') + }) + + it('classifies DNS hostnames as custom', () => { + expect(classifyHost('local.getmontecarlo.com')).toBe('custom') + expect(classifyHost('app.example.dev')).toBe('custom') + }) +}) + +describe('AdvertisedUrlWatcher.ingest', () => { + it('captures a complete URL printed in one chunk', () => { + const watcher = bindFresh() + watcher.ingest(PTY, ' Network: https://local.getmontecarlo.com:3001/\n') + const found = watcher.lookup(WORKTREE, 3001) + expect(found?.origin).toBe('https://local.getmontecarlo.com:3001') + expect(found?.hostKind).toBe('custom') + expect(found?.protocol).toBe('https') + }) + + it('reassembles a URL split across two chunks', () => { + const watcher = bindFresh() + watcher.ingest(PTY, ' Network: https://local.getmontecarlo') + expect(watcher.lookup(WORKTREE, 3001)).toBeUndefined() + watcher.ingest(PTY, '.com:3001/\n') + expect(watcher.lookup(WORKTREE, 3001)?.origin).toBe('https://local.getmontecarlo.com:3001') + }) + + it('reassembles an ANSI escape split across two chunks', () => { + const watcher = bindFresh() + watcher.ingest(PTY, '\x1b[32mhttps://example.com:3001/\x1b') + // Partial ESC at end keeps everything buffered; nothing emitted yet. + expect(watcher.lookup(WORKTREE, 3001)).toBeUndefined() + watcher.ingest(PTY, '[0m\n') + expect(watcher.lookup(WORKTREE, 3001)?.origin).toBe('https://example.com:3001') + }) + + it('sanitizes to origin (drops path, query, fragment, userinfo)', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'go to https://user:pass@example.com:3001/callback?token=secret#x\n') + expect(watcher.lookup(WORKTREE, 3001)?.origin).toBe('https://example.com:3001') + }) + + it('omits default port from origin', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'Listening on https://example.com/ now\n') + expect(watcher.lookup(WORKTREE, 443)?.origin).toBe('https://example.com') + }) + + it('re-brackets IPv6 hosts in the origin', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'Local: http://[::1]:5173/\n') + expect(watcher.lookup(WORKTREE, 5173)?.origin).toBe('http://[::1]:5173') + }) + + it('prefers a custom DNS host over loopback for the same port', () => { + const watcher = bindFresh() + watcher.ingest(PTY, ' Local: http://localhost:3001/\n') + watcher.ingest(PTY, ' Network: https://custom.example.com:3001/\n') + expect(watcher.lookup(WORKTREE, 3001)?.host).toBe('custom.example.com') + }) + + it('does not let a later loopback URL overwrite a custom DNS host', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'Network: https://custom.example.com:3001/\n') + watcher.ingest(PTY, 'Local: http://localhost:3001/\n') + expect(watcher.lookup(WORKTREE, 3001)?.host).toBe('custom.example.com') + }) + + it('prefers https over http when scores match and a newer https is seen', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'A: http://app.example.com:3001/\n') + watcher.ingest(PTY, 'B: https://app.example.com:3001/\n') + expect(watcher.lookup(WORKTREE, 3001)?.protocol).toBe('https') + }) + + it('prefers loopback over a private LAN IP', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'Network: http://192.168.1.50:3001/\n') + watcher.ingest(PTY, 'Local: http://localhost:3001/\n') + expect(watcher.lookup(WORKTREE, 3001)?.hostKind).toBe('loopback') + }) + + it('buffers data that arrives before bindPty and replays on bind', () => { + const watcher = new AdvertisedUrlWatcher({ now: () => 1_000 }) + watcher.ingest('pty-X', 'early https://app.example.com:3001/\n') + expect(watcher.lookup(WORKTREE, 3001)).toBeUndefined() + watcher.bindPty('pty-X', WORKTREE) + expect(watcher.lookup(WORKTREE, 3001)?.host).toBe('app.example.com') + }) + + it('unbindPty drops buffered state for the PTY', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'cached https://cached.example.com:3002/\n') + watcher.ingest(PTY, 'partial https://example.com:3001') // no newline → buffered + const events: { worktreeId: string; port: number }[] = [] + watcher.onDidChange((event) => events.push(event)) + watcher.unbindPty(PTY) + // After unbind, the buffer is gone, so a completing chunk on a fresh + // binding would have to repeat the URL. + watcher.bindPty(PTY, WORKTREE) + watcher.ingest(PTY, '/now\n') + expect(watcher.lookup(WORKTREE, 3001)).toBeUndefined() + expect(watcher.lookupBest([WORKTREE], 3002)).toBeUndefined() + expect(events).toContainEqual({ worktreeId: WORKTREE, port: 3002 }) + }) + + it('different worktrees on the same port are tracked independently', () => { + const watcher = bindFresh() + watcher.bindPty('pty-2', 'repo::/other') + watcher.ingest(PTY, 'A: https://a.example.com:3001/\n') + watcher.ingest('pty-2', 'B: https://b.example.com:3001/\n') + expect(watcher.lookup(WORKTREE, 3001)?.host).toBe('a.example.com') + expect(watcher.lookup('repo::/other', 3001)?.host).toBe('b.example.com') + }) + + it('LRU-evicts the oldest entry when the cache cap is exceeded', () => { + const watcher = new AdvertisedUrlWatcher({ now: () => 1_000, maxCacheEntries: 2 }) + watcher.bindPty(PTY, WORKTREE) + watcher.ingest(PTY, 'A: https://a.example.com:3001/\n', 100) + watcher.ingest(PTY, 'B: https://b.example.com:3002/\n', 200) + const events: { worktreeId: string; port: number }[] = [] + watcher.onDidChange((event) => events.push(event)) + watcher.ingest(PTY, 'C: https://c.example.com:3003/\n', 300) + expect(watcher.lookup(WORKTREE, 3001)).toBeUndefined() + expect(watcher.lookup(WORKTREE, 3002)?.host).toBe('b.example.com') + expect(watcher.lookup(WORKTREE, 3003)?.host).toBe('c.example.com') + expect(events).toEqual([ + { worktreeId: WORKTREE, port: 3001 }, + { worktreeId: WORKTREE, port: 3003 } + ]) + }) + + it('invalidate drops one cache entry', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'A: https://a.example.com:3001/\n') + watcher.invalidate(WORKTREE, 3001) + expect(watcher.lookup(WORKTREE, 3001)).toBeUndefined() + }) + + it('rejects wildcard advertised hosts so they cannot override connectHost', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'Listening on http://0.0.0.0:3000/\n') + watcher.ingest(PTY, 'Listening on http://[::]:3000/\n') + expect(watcher.lookup(WORKTREE, 3000)).toBeUndefined() + }) + + it('notifies listeners when the visible advertised URL changes', () => { + const watcher = bindFresh() + const events: { worktreeId: string; port: number }[] = [] + const unsubscribe = watcher.onDidChange((event) => events.push(event)) + + watcher.ingest(PTY, 'Local: http://localhost:3001/\n') + watcher.ingest(PTY, 'Network: https://custom.example.com:3001/\n') + watcher.ingest(PTY, 'Local: http://localhost:3001/\n') + unsubscribe() + watcher.ingest(PTY, 'Network: https://other.example.com:3001/\n') + + expect(events).toEqual([ + { worktreeId: WORKTREE, port: 3001 }, + { worktreeId: WORKTREE, port: 3001 } + ]) + }) + + it('caps the pre-bind pending buffer at 32 distinct PTY IDs', () => { + const watcher = new AdvertisedUrlWatcher({ now: () => 1_000 }) + // 33 distinct unbound IDs; the first should be evicted before bind. + for (let i = 0; i < 33; i++) { + watcher.ingest(`pty-${i}`, `https://h${i}.example.com:300${i % 10}/\n`) + } + // Bind the first ID now; if it was evicted (LRU), no URL should appear. + watcher.bindPty('pty-0', WORKTREE) + expect(watcher.lookup(WORKTREE, 3000)).toBeUndefined() + // Bind the most-recent ID; its pending data must still be there. + watcher.bindPty('pty-32', WORKTREE) + expect(watcher.lookup(WORKTREE, 3002)?.host).toBe('h32.example.com') + }) +}) + +describe('AdvertisedUrlWatcher.lookupBest', () => { + it('returns undefined when no worktree has the port cached', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'A: https://a.example.com:3001/\n') + expect(watcher.lookupBest(['repo::/other'], 3001)).toBeUndefined() + }) + + it('returns the only entry when one worktree has it', () => { + const watcher = bindFresh() + watcher.ingest(PTY, 'A: https://a.example.com:3001/\n') + expect(watcher.lookupBest([WORKTREE], 3001)?.host).toBe('a.example.com') + }) + + it('picks the best entry across worktrees by hostKind', () => { + const watcher = bindFresh() + watcher.bindPty('pty-2', 'repo::/wt2') + watcher.ingest(PTY, 'A: http://localhost:3001/\n') + watcher.ingest('pty-2', 'B: https://custom.example.com:3001/\n') + const best = watcher.lookupBest([WORKTREE, 'repo::/wt2'], 3001) + expect(best?.host).toBe('custom.example.com') + }) +}) diff --git a/src/main/ports/advertised-url-watcher.ts b/src/main/ports/advertised-url-watcher.ts new file mode 100644 index 000000000..ef2769677 --- /dev/null +++ b/src/main/ports/advertised-url-watcher.ts @@ -0,0 +1,653 @@ +/* eslint-disable no-control-regex, max-lines -- Why: ANSI/OSC stripping must match raw + * control sequences in PTY output, same as src/main/runtime/orca-runtime.ts; + * URL parsing, host classification, cache lifecycle, and cross-worktree lookup + * are tightly coupled and kept in one file to keep the rules in lockstep. */ +// Watches PTY output for HTTP(S) URLs that dev servers (Vite, Next, etc.) +// print on startup. Maintains a per-{worktreeId, port} cache so the workspace +// ports panel can show the tool-advertised origin instead of the kernel bind +// (e.g. `https://local.getmontecarlo.com:3001/` rather than `127.0.0.1:3001`). +// +// Why a separate stateful buffer per PTY: ANSI escape sequences and URLs can +// both straddle PTY write boundaries, so we cannot strip ANSI and scan one +// chunk at a time. We accumulate raw bytes, finalize only at newline-anchored +// boundaries, then run a stateless strip-and-scan on the finalized prefix. + +const PER_PTY_BUFFER_LIMIT = 4096 +const PENDING_PRE_BIND_LIMIT = 16 * 1024 +/** Cap on distinct never-bound PTY IDs. Spawn-failure paths can leave a + * pending entry that never gets bindPty'd — without an upper bound, a + * long-running app would slowly leak one entry per failure. */ +const MAX_PENDING_ENTRIES = 32 +const MAX_CACHE_ENTRIES = 256 +const URL_CANDIDATE_LIMIT = 2048 + +// ANSI/OSC strippers mirror normalizeTerminalChunk in +// src/main/runtime/orca-runtime.ts so the two stay in lockstep. +const OSC_PATTERN = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g +const CSI_PATTERN = /\x1b\[[0-?]*[ -/]*[@-~]/g +const SINGLE_ESC_PATTERN = /\x1b[@-_]/g +const CONTROL_PATTERN = /[\x00-\x08\x0b-\x1f\x7f]/g + +// Why: this is a permissive candidate matcher. Real validation happens via +// `new URL()` below. Stopping at characters that cannot appear in a URL +// (whitespace, quotes, angle brackets, backtick) avoids absorbing terminal +// punctuation. Trailing punctuation like `.,;)` is trimmed before parsing +// because URLs are commonly followed by sentence punctuation in human text. +const URL_CANDIDATE_PATTERN = /\bhttps?:\/\/[^\s<>"'`]+/gi + +export type HostKind = 'custom' | 'loopback' | 'private-ip' | 'public-ip' + +export type AdvertisedUrl = { + origin: string + host: string + hostKind: HostKind + protocol: 'http' | 'https' + port: number + ptyId: string + lastSeenAt: number + /** PID of the listening process that this advertised URL was validated + * against on a previous scan. Set by lookup APIs when a current PID is + * supplied; a later mismatch evicts the entry. Captured on first scan + * rather than at capture time because the PTY shell PID is not the + * listener PID. */ + validatedListenerPid?: number +} + +export type AdvertisedUrlChangeEvent = { + worktreeId: string + port: number +} + +export type AdvertisedUrlListenerObservation = { + port: number + pid?: number +} + +type CacheKey = string +type ListenerScanState = { kind: 'absent' } | { kind: 'present'; pid?: number } + +function cacheKey(worktreeId: string, port: number): CacheKey { + return `${worktreeId}::${port}` +} + +function worktreeIdFromCacheKey(key: CacheKey, port: number): string { + const suffix = `::${port}` + return key.endsWith(suffix) ? key.slice(0, -suffix.length) : key +} + +class PtyBuffer { + private raw = '' + + /** Append a chunk and return the cleaned, finalized text (everything up to + * and including the last newline). Whatever follows the last newline stays + * buffered so that a URL or ANSI sequence split across chunks survives. */ + ingest(chunk: string): string { + this.raw += chunk + if (this.raw.length > PER_PTY_BUFFER_LIMIT) { + this.raw = this.raw.slice(-PER_PTY_BUFFER_LIMIT) + } + const lastNewline = lastLineBreak(this.raw) + if (lastNewline === -1) { + return '' + } + const finalized = this.raw.slice(0, lastNewline + 1) + this.raw = this.raw.slice(lastNewline + 1) + return stripTerminalControls(finalized) + } +} + +function lastLineBreak(text: string): number { + // Both \n and \r are accepted; \r\n is handled by stripping \r in + // stripTerminalControls — but we still want either one as a finalize point. + for (let i = text.length - 1; i >= 0; i--) { + const ch = text.charCodeAt(i) + if (ch === 0x0a || ch === 0x0d) { + return i + } + } + return -1 +} + +export function stripTerminalControls(text: string): string { + return text + .replace(/\r\n/g, '\n') + .replace(/\r/g, '\n') + .replace(OSC_PATTERN, '') + .replace(CSI_PATTERN, '') + .replace(SINGLE_ESC_PATTERN, '') + .replace(CONTROL_PATTERN, '') +} + +export function extractUrlCandidates(cleaned: string): URL[] { + const results: URL[] = [] + for (const match of cleaned.matchAll(URL_CANDIDATE_PATTERN)) { + let candidate = match[0] + if (candidate.length > URL_CANDIDATE_LIMIT) { + continue + } + // Strip common trailing punctuation that cannot end a real URL. + while (candidate.length > 0 && /[.,;:!?)\]}>'"`]/.test(candidate.slice(-1))) { + candidate = candidate.slice(0, -1) + } + const url = parseUrl(candidate) + if (url) { + results.push(url) + } + } + return results +} + +function parseUrl(candidate: string): URL | null { + try { + const url = new URL(candidate) + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + return null + } + if (!url.hostname) { + return null + } + return url + } catch { + return null + } +} + +export function classifyHost(hostname: string): HostKind { + // Why: Node's URL.hostname returns IPv6 literals with brackets ("[::1]"), + // while the public API for this function should accept either form. + const lower = hostname.toLowerCase().replace(/^\[|\]$/g, '') + if (lower === 'localhost' || lower === '127.0.0.1' || lower === '::1') { + return 'loopback' + } + if (isIpv4(lower)) { + if (isPrivateIpv4(lower)) { + return 'private-ip' + } + return 'public-ip' + } + if (isIpv6(lower)) { + if (isPrivateIpv6(lower)) { + return 'private-ip' + } + return 'public-ip' + } + // Anything else is a DNS name — that's what we prefer for dev servers. + return 'custom' +} + +function isIpv4(value: string): boolean { + const parts = value.split('.') + if (parts.length !== 4) { + return false + } + return parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255) +} + +function isPrivateIpv4(value: string): boolean { + const [a, b] = value.split('.').map((n) => Number(n)) + // 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16 (link-local) + if (a === 10) { + return true + } + if (a === 172 && b >= 16 && b <= 31) { + return true + } + if (a === 192 && b === 168) { + return true + } + if (a === 169 && b === 254) { + return true + } + return false +} + +function isUnspecifiedHost(hostname: string): boolean { + const stripped = hostname.toLowerCase().replace(/^\[|\]$/g, '') + return stripped === '0.0.0.0' || stripped === '::' || stripped === '*' +} + +function isIpv6(value: string): boolean { + // url.hostname for IPv6 returns lowercase without brackets — quick sniff. + return value.includes(':') && /^[0-9a-f:]+$/.test(value) +} + +function isPrivateIpv6(value: string): boolean { + // fc00::/7 (ULA) and fe80::/10 (link-local) + if (value.startsWith('fc') || value.startsWith('fd')) { + return true + } + const firstHextet = Number.parseInt(value.split(':', 1)[0], 16) + return Number.isFinite(firstHextet) && (firstHextet & 0xffc0) === 0xfe80 +} + +function hostKindScore(kind: HostKind): number { + // Codex's preference: custom DNS > loopback > private IP > public IP. + // A custom-configured host (e.g. `local.getmontecarlo.com`) is almost always + // the one the user wants opened, and loopback beats LAN for cert/cookie + // reasons on a single-machine setup. + switch (kind) { + case 'custom': + return 3 + case 'loopback': + return 2 + case 'private-ip': + return 1 + case 'public-ip': + return 0 + } +} + +function shouldReplace(existing: AdvertisedUrl, candidate: AdvertisedUrl): boolean { + const oldScore = hostKindScore(existing.hostKind) + const newScore = hostKindScore(candidate.hostKind) + if (newScore !== oldScore) { + return newScore > oldScore + } + if (existing.protocol !== candidate.protocol) { + return candidate.protocol === 'https' + } + return candidate.lastSeenAt >= existing.lastSeenAt +} + +export type AdvertisedUrlWatcherOptions = { + /** Override the clock; useful for tests. */ + now?: () => number + /** Override the max cache entries (default 256). */ + maxCacheEntries?: number +} + +export class AdvertisedUrlWatcher { + private readonly buffers = new Map() + private readonly ptyToWorktree = new Map() + private readonly pending = new Map() + private readonly cache = new Map() + private readonly scanSnapshots = new Map>() + private readonly validationBaselines = new Map() + private readonly listeners = new Set<(event: AdvertisedUrlChangeEvent) => void>() + private readonly now: () => number + private readonly maxCacheEntries: number + + constructor(options: AdvertisedUrlWatcherOptions = {}) { + this.now = options.now ?? Date.now + this.maxCacheEntries = options.maxCacheEntries ?? MAX_CACHE_ENTRIES + } + + onDidChange(listener: (event: AdvertisedUrlChangeEvent) => void): () => void { + this.listeners.add(listener) + return () => { + this.listeners.delete(listener) + } + } + + bindPty(ptyId: string, worktreeId: string): void { + this.ptyToWorktree.set(ptyId, worktreeId) + const pending = this.pending.get(ptyId) + if (pending !== undefined) { + this.pending.delete(ptyId) + this.ingest(ptyId, pending) + } + } + + unbindPty(ptyId: string): void { + this.ptyToWorktree.delete(ptyId) + this.buffers.delete(ptyId) + this.pending.delete(ptyId) + const removedEvents: AdvertisedUrlChangeEvent[] = [] + for (const [key, entry] of this.cache) { + if (entry.ptyId !== ptyId) { + continue + } + // Why: SSH forward enrichment has no listener PID to validate against, + // so PTY teardown is the only reliable expiry signal for that cache row. + this.cache.delete(key) + this.validationBaselines.delete(key) + const worktreeId = worktreeIdFromCacheKey(key, entry.port) + removedEvents.push({ worktreeId, port: entry.port }) + } + for (const event of removedEvents) { + this.emitChange(event) + } + } + + ingest(ptyId: string, chunk: string, now?: number): void { + if (!chunk) { + return + } + const worktreeId = this.ptyToWorktree.get(ptyId) + if (!worktreeId) { + // Why: data can arrive on daemon-backed PTYs before the spawn handler + // resolves and we learn the worktreeId (see comment at + // src/main/ipc/pty.ts:1318-1323). Buffer until bindPty replays. + const prior = this.pending.get(ptyId) ?? '' + const merged = (prior + chunk).slice(-PENDING_PRE_BIND_LIMIT) + // Why: drop+reinsert touches insertion order so this acts as an LRU + // (Map iterates in insertion order). Combined with the eviction below, + // we keep at most MAX_PENDING_ENTRIES distinct unbound PTYs. + this.pending.delete(ptyId) + this.pending.set(ptyId, merged) + while (this.pending.size > MAX_PENDING_ENTRIES) { + const oldest = this.pending.keys().next().value + if (oldest === undefined) { + break + } + this.pending.delete(oldest) + } + return + } + let buffer = this.buffers.get(ptyId) + if (!buffer) { + buffer = new PtyBuffer() + this.buffers.set(ptyId, buffer) + } + const finalized = buffer.ingest(chunk) + if (!finalized) { + return + } + const timestamp = now ?? this.now() + for (const url of extractUrlCandidates(finalized)) { + this.consider(url, ptyId, worktreeId, timestamp) + } + } + + private consider(url: URL, ptyId: string, worktreeId: string, timestamp: number): void { + const protocol = url.protocol === 'https:' ? 'https' : 'http' + const port = url.port ? Number(url.port) : protocol === 'https' ? 443 : 80 + if (!Number.isFinite(port) || port <= 0 || port > 65535) { + return + } + const hostname = url.hostname + // Why: dev servers sometimes print their bind address verbatim + // (`http://0.0.0.0:3000/`). Those wildcard hosts cannot be opened in a + // browser — the OS scanner already normalizes wildcards to `localhost` + // for the connect host, so refuse the advertised value rather than let + // it overwrite that sensible default. + if (isUnspecifiedHost(hostname)) { + return + } + const hostKind = classifyHost(hostname) + // Why: store origin only — no path, query, fragment, or userinfo. A + // terminal line containing an OAuth callback or token must not get + // surfaced in the port panel. + const origin = `${protocol}://${formatHostForOrigin(url)}${ + isDefaultPort(protocol, port) ? '' : `:${port}` + }` + const candidate: AdvertisedUrl = { + origin, + host: hostname, + hostKind, + protocol, + port, + ptyId, + lastSeenAt: timestamp + } + const key = cacheKey(worktreeId, port) + const existing = this.cache.get(key) + if (!existing || shouldReplace(existing, candidate)) { + this.cache.set(key, candidate) + const baseline = this.currentScanStateFor(worktreeId, port) + if (baseline) { + this.validationBaselines.set(key, baseline) + } else { + this.validationBaselines.delete(key) + } + const changedEvents = this.enforceCacheLimit() + if (!existing || existing.origin !== candidate.origin) { + changedEvents.push({ worktreeId, port }) + } + for (const event of dedupeChangeEvents(changedEvents)) { + this.emitChange(event) + } + } else { + // Refresh recency on the existing entry so it isn't evicted by LRU. + existing.lastSeenAt = timestamp + } + } + + private emitChange(event: AdvertisedUrlChangeEvent): void { + for (const listener of this.listeners) { + try { + listener(event) + } catch (error) { + console.warn('[advertised-url-watcher] listener failed', error) + } + } + } + + private enforceCacheLimit(): AdvertisedUrlChangeEvent[] { + if (this.cache.size <= this.maxCacheEntries) { + return [] + } + // Drop oldest by lastSeenAt until we are back at the cap. + const entries = Array.from(this.cache.entries()).sort( + (a, b) => a[1].lastSeenAt - b[1].lastSeenAt + ) + const overflow = this.cache.size - this.maxCacheEntries + const removedEvents: AdvertisedUrlChangeEvent[] = [] + for (let i = 0; i < overflow; i++) { + const [key, entry] = entries[i] + this.cache.delete(key) + this.validationBaselines.delete(key) + removedEvents.push({ worktreeId: worktreeIdFromCacheKey(key, entry.port), port: entry.port }) + } + return removedEvents + } + + lookup(worktreeId: string, port: number, currentListenerPid?: number): AdvertisedUrl | undefined { + const key = cacheKey(worktreeId, port) + const entry = this.cache.get(key) + if (!entry) { + return undefined + } + if (currentListenerPid !== undefined) { + if (entry.validatedListenerPid === undefined) { + entry.validatedListenerPid = currentListenerPid + } else if (entry.validatedListenerPid !== currentListenerPid) { + // Why: the process that printed this URL is gone and a different + // process is now listening on the port. Drop the cached URL — the + // new listener may be unrelated to the captured banner. + this.cache.delete(key) + this.validationBaselines.delete(key) + this.emitChange({ worktreeId, port }) + return undefined + } + } + return entry + } + + /** Drop a single cached entry. */ + invalidate(worktreeId: string, port: number): void { + const key = cacheKey(worktreeId, port) + this.validationBaselines.delete(key) + if (this.cache.delete(key)) { + this.emitChange({ worktreeId, port }) + } + } + + /** Reconcile the URL cache with a scanner snapshot for a worktree scope. + * Unvalidated URLs are tied to the listener state observed around capture, + * so a later absent port or changed PID cannot be lazily blessed. */ + reconcileScan( + worktreeIds: readonly string[], + observations: readonly AdvertisedUrlListenerObservation[] + ): void { + const observedByPort = observedListenersByPort(observations) + const worktreeSet = new Set(worktreeIds) + const removedEvents: AdvertisedUrlChangeEvent[] = [] + + for (const [key, entry] of this.cache) { + const worktreeId = worktreeIdFromCacheKey(key, entry.port) + if (!worktreeSet.has(worktreeId)) { + continue + } + const current = observedByPort.has(entry.port) + ? ({ kind: 'present', pid: observedByPort.get(entry.port) } as const) + : ({ kind: 'absent' } as const) + + if (this.shouldEvictAfterScan(key, entry, current)) { + this.cache.delete(key) + this.validationBaselines.delete(key) + removedEvents.push({ worktreeId, port: entry.port }) + } else if (entry.validatedListenerPid === undefined) { + this.validationBaselines.set(key, current) + } + } + + for (const worktreeId of worktreeSet) { + this.scanSnapshots.set(worktreeId, new Map(observedByPort)) + } + for (const event of removedEvents) { + this.emitChange(event) + } + } + + private shouldEvictAfterScan( + key: CacheKey, + entry: AdvertisedUrl, + current: ListenerScanState + ): boolean { + if (current.kind === 'absent') { + return true + } + if ( + entry.validatedListenerPid !== undefined && + current.pid !== undefined && + entry.validatedListenerPid !== current.pid + ) { + return true + } + const baseline = this.validationBaselines.get(key) + return ( + entry.validatedListenerPid === undefined && + baseline !== undefined && + scanStateChanged(baseline, current) + ) + } + + /** Find the best advertised URL for `port` across multiple worktrees. SSH + * connections host several worktrees but the remote-side port scanner + * returns ports for the whole connection, so we need to scan all the + * worktrees attached to that connection. Returns the highest-scoring + * entry by hostKind (custom DNS > loopback > private IP > public IP), + * with HTTPS and recency as tie-breakers — same rule as `shouldReplace` + * uses on insert. + * + * When `currentListenerPid` is supplied each candidate entry is run + * through PID filtering first. Already-pinned mismatches are evicted, + * then only the returned winner is pinned to the current listener. */ + lookupBest( + worktreeIds: readonly string[], + port: number, + currentListenerPid?: number + ): AdvertisedUrl | undefined { + let best: { worktreeId: string; entry: AdvertisedUrl } | undefined + for (const worktreeId of worktreeIds) { + const key = cacheKey(worktreeId, port) + const candidate = this.cache.get(key) + if (!candidate) { + continue + } + if (currentListenerPid !== undefined) { + if ( + candidate.validatedListenerPid !== undefined && + candidate.validatedListenerPid !== currentListenerPid + ) { + this.cache.delete(key) + this.validationBaselines.delete(key) + this.emitChange({ worktreeId, port }) + continue + } + } + if (!best || shouldReplace(best.entry, candidate)) { + best = { worktreeId, entry: candidate } + } + } + if (best && currentListenerPid !== undefined && best.entry.validatedListenerPid === undefined) { + best.entry.validatedListenerPid = currentListenerPid + this.validationBaselines.delete(cacheKey(best.worktreeId, port)) + } + return best?.entry + } + + clear(): void { + this.buffers.clear() + this.ptyToWorktree.clear() + this.pending.clear() + this.cache.clear() + this.scanSnapshots.clear() + this.validationBaselines.clear() + } + + private currentScanStateFor(worktreeId: string, port: number): ListenerScanState | undefined { + const snapshot = this.scanSnapshots.get(worktreeId) + if (!snapshot) { + return undefined + } + return snapshot.has(port) ? { kind: 'present', pid: snapshot.get(port) } : { kind: 'absent' } + } +} + +function isDefaultPort(protocol: 'http' | 'https', port: number): boolean { + return (protocol === 'http' && port === 80) || (protocol === 'https' && port === 443) +} + +/** Process-wide singleton. The runtime feeds it from `onPtyData`; the scanner + * enrichment reads it. Tests should instantiate their own + * `AdvertisedUrlWatcher` rather than relying on this. */ +export const advertisedUrlWatcher = new AdvertisedUrlWatcher() + +function formatHostForOrigin(url: URL): string { + // Why: Node returns IPv6 hostnames pre-bracketed ("[::1]"). Some other JS + // runtimes strip the brackets. Accept both: re-bracket if a bare IPv6 + // literal slips through. + const h = url.hostname + if (h.startsWith('[') && h.endsWith(']')) { + return h + } + if (h.includes(':')) { + return `[${h}]` + } + return h +} + +function observedListenersByPort( + observations: readonly AdvertisedUrlListenerObservation[] +): Map { + const observed = new Map() + for (const observation of observations) { + const existing = observed.get(observation.port) + if (!observed.has(observation.port)) { + observed.set(observation.port, observation.pid) + } else if (existing !== observation.pid) { + // Multiple host-specific listeners on one port make PID attribution + // ambiguous for our port-keyed URL cache; preserve presence only. + observed.set(observation.port, undefined) + } + } + return observed +} + +function scanStateChanged(previous: ListenerScanState, current: ListenerScanState): boolean { + if (previous.kind !== current.kind) { + return true + } + if (previous.kind === 'absent' || current.kind === 'absent') { + return false + } + return previous.pid !== undefined && current.pid !== undefined && previous.pid !== current.pid +} + +function dedupeChangeEvents( + events: readonly AdvertisedUrlChangeEvent[] +): AdvertisedUrlChangeEvent[] { + const seen = new Set() + const deduped: AdvertisedUrlChangeEvent[] = [] + for (const event of events) { + const key = cacheKey(event.worktreeId, event.port) + if (seen.has(key)) { + continue + } + seen.add(key) + deduped.push(event) + } + return deduped +} diff --git a/src/main/ports/local-workspace-port-scanner.ts b/src/main/ports/local-workspace-port-scanner.ts index 6c30c0521..8691b31af 100644 --- a/src/main/ports/local-workspace-port-scanner.ts +++ b/src/main/ports/local-workspace-port-scanner.ts @@ -10,6 +10,7 @@ import type { WorkspacePortProbe, WorkspacePortScanResult } from '../../shared/workspace-ports' +import { advertisedUrlWatcher, type AdvertisedUrlWatcher } from './advertised-url-watcher' const execFileAsync = promisify(execFile) @@ -34,12 +35,14 @@ type ProcessMetadata = { } export async function scanWorkspacePorts( - worktrees: WorkspacePortProbe[] + worktrees: WorkspacePortProbe[], + urlWatcher: Pick = advertisedUrlWatcher ): Promise { try { const rawPorts = await scanPlatformListeningPorts() + reconcileAdvertisedUrls(rawPorts, worktrees, urlWatcher) const ports = rawPorts - .map((port) => enrichPort(port, worktrees)) + .map((port) => enrichPort(port, worktrees, urlWatcher)) .sort(compareWorkspacePorts) .slice(0, MAX_PORTS) return { platform: process.platform, scannedAt: Date.now(), ports } @@ -353,7 +356,11 @@ async function readTextIfAvailable(filePath: string): Promise +): WorkspacePort { const owner = attributePortToWorkspace(port, worktrees) const base = { id: `${port.host}:${port.port}:${port.pid ?? 'unknown'}`, @@ -366,7 +373,17 @@ function enrichPort(port: RawListeningPort, worktrees: WorkspacePortProbe[]): Wo } if (owner) { - return { ...base, kind: 'workspace', owner } + // Why: only enrich workspace-attributed ports. Container and external + // ports may have URLs printed in unrelated terminals — the worktree + // scoping is the primary false-positive filter. + const advertised = urlWatcher.lookup(owner.worktreeId, port.port, port.pid) + return { + ...base, + protocol: advertised?.protocol ?? base.protocol, + kind: 'workspace', + owner, + ...(advertised ? { advertisedUrl: advertised.origin } : {}) + } } if (isContainerProcess(port)) { return { ...base, kind: 'container' } @@ -374,6 +391,29 @@ function enrichPort(port: RawListeningPort, worktrees: WorkspacePortProbe[]): Wo return { ...base, kind: 'external' } } +function reconcileAdvertisedUrls( + ports: RawListeningPort[], + worktrees: WorkspacePortProbe[], + urlWatcher: Pick +): void { + const observationsByWorktree = new Map() + for (const worktree of worktrees) { + observationsByWorktree.set(worktree.id, []) + } + for (const port of ports) { + const owner = attributePortToWorkspace(port, worktrees) + if (!owner) { + continue + } + observationsByWorktree.get(owner.worktreeId)?.push({ port: port.port, pid: port.pid }) + } + for (const [worktreeId, observations] of observationsByWorktree) { + // Why: the scanner sees port disappearance and PID changes before a lazy + // lookup would otherwise pin a stale banner to a new listener. + urlWatcher.reconcileScan([worktreeId], observations) + } +} + function compareWorkspacePorts(a: WorkspacePort, b: WorkspacePort): number { const aRank = a.kind === 'workspace' ? 0 : a.kind === 'container' ? 1 : 2 const bRank = b.kind === 'workspace' ? 0 : b.kind === 'container' ? 1 : 2 diff --git a/src/main/ports/ssh-advertised-url-enrichment.test.ts b/src/main/ports/ssh-advertised-url-enrichment.test.ts new file mode 100644 index 000000000..db567c9fd --- /dev/null +++ b/src/main/ports/ssh-advertised-url-enrichment.test.ts @@ -0,0 +1,313 @@ +import { describe, expect, it } from 'vitest' +import type { DetectedPort, PortForwardEntry } from '../../shared/ssh-types' +import { + enrichSshDetectedPorts, + enrichSshForwardEntries, + getConnectionIdsForWorktree, + getWorktreeIdsForConnection +} from './ssh-advertised-url-enrichment' +import { AdvertisedUrlWatcher, type AdvertisedUrl } from './advertised-url-watcher' + +function watcherWith( + entries: Record> +): Pick { + return { + reconcileScan: () => {}, + lookupBest(worktreeIds, port): AdvertisedUrl | undefined { + // Why: tests pin URLs to worktreeId+port via the entries map; whichever + // worktree appears first in the request wins to keep assertions explicit. + for (const wt of worktreeIds) { + const hit = entries[`${wt}::${port}`] + if (hit) { + return { + origin: hit.origin ?? 'http://x:1', + host: hit.host ?? 'x', + hostKind: hit.hostKind ?? 'custom', + protocol: hit.protocol ?? 'http', + port, + ptyId: 'pty', + lastSeenAt: 0 + } + } + } + return undefined + } + } +} + +describe('getConnectionIdsForWorktree', () => { + it('maps a watcher worktreeId back to its SSH connection', () => { + const store = { + getRepos: () => [{ id: 'local-repo' }, { id: 'remote-repo', connectionId: 'ssh-1' }] + } as Parameters[0] + + expect(getConnectionIdsForWorktree(store, 'remote-repo::/repo')).toEqual(['ssh-1']) + expect(getConnectionIdsForWorktree(store, 'local-repo::/repo')).toEqual([]) + expect(getConnectionIdsForWorktree(store, 'invalid')).toEqual([]) + }) +}) + +describe('getWorktreeIdsForConnection', () => { + it('maps an SSH connection to every attached worktree', () => { + const store = { + getRepos: () => [ + { id: 'local-repo' }, + { id: 'remote-repo', connectionId: 'ssh-1' }, + { id: 'other-remote', connectionId: 'ssh-2' } + ], + getAllWorktreeMeta: () => ({ + 'remote-repo::/repo': { displayName: 'repo' }, + 'remote-repo::/repo/feature': { displayName: 'feature' }, + 'other-remote::/repo': { displayName: 'other' }, + 'local-repo::/repo': { displayName: 'local' }, + invalid: { displayName: 'invalid' } + }) + } as unknown as Parameters[0] + + expect(getWorktreeIdsForConnection(store, 'ssh-1').sort()).toEqual([ + 'remote-repo::/repo', + 'remote-repo::/repo/feature' + ]) + }) +}) + +describe('enrichSshForwardEntries', () => { + it('returns input untouched when there are no worktrees', () => { + const entries: PortForwardEntry[] = [ + { id: 'a', connectionId: 'conn', localPort: 53001, remoteHost: 'h', remotePort: 3001 } + ] + expect(enrichSshForwardEntries(entries, [], watcherWith({}))).toEqual(entries) + }) + + it('attaches advertisedUrl + protocol for entries whose remotePort matches', () => { + const watcher = watcherWith({ + 'wt::3001': { + origin: 'https://custom.example.com:3001', + host: 'custom.example.com', + protocol: 'https' + } + }) + const entries: PortForwardEntry[] = [ + { id: 'a', connectionId: 'conn', localPort: 53001, remoteHost: 'h', remotePort: 3001 }, + { id: 'b', connectionId: 'conn', localPort: 53002, remoteHost: 'h', remotePort: 3002 } + ] + const enriched = enrichSshForwardEntries(entries, ['wt'], watcher) + expect(enriched[0].advertisedUrl).toBe('https://custom.example.com:3001') + expect(enriched[0].advertisedProtocol).toBe('https') + expect(enriched[1].advertisedUrl).toBeUndefined() + }) + + it('does not mutate the input array entries', () => { + const watcher = watcherWith({ 'wt::3001': { origin: 'http://x:3001', protocol: 'http' } }) + const entries: PortForwardEntry[] = [ + { id: 'a', connectionId: 'conn', localPort: 53001, remoteHost: 'h', remotePort: 3001 } + ] + enrichSshForwardEntries(entries, ['wt'], watcher) + expect(entries[0].advertisedUrl).toBeUndefined() + }) +}) + +describe('enrichSshDetectedPorts', () => { + it('reconciles an empty scan before returning unchanged ports', () => { + const calls: unknown[][] = [] + const watcher = { + reconcileScan(...args: Parameters): void { + calls.push(['reconcile', ...args]) + }, + lookupBest(...args: Parameters): AdvertisedUrl { + calls.push(['lookupBest', ...args]) + return { + origin: 'https://local.example.com:3001', + host: 'local.example.com', + hostKind: 'custom', + protocol: 'https', + port: 3001, + ptyId: 'pty', + lastSeenAt: 0 + } + } + } + + expect(enrichSshDetectedPorts([], ['wt'], watcher)).toEqual([]) + expect(calls).toEqual([['reconcile', ['wt'], []]]) + }) + + it('attaches advertisedUrl when a worktree has a cached match', () => { + const watcher = watcherWith({ + 'wt::3001': { + origin: 'https://local.example.com:3001', + host: 'local.example.com', + protocol: 'https' + } + }) + const ports: DetectedPort[] = [ + { port: 3001, host: '127.0.0.1', processName: 'node' }, + { port: 3002, host: '0.0.0.0' } + ] + const enriched = enrichSshDetectedPorts(ports, ['wt'], watcher) + expect(enriched[0].advertisedUrl).toBe('https://local.example.com:3001') + expect(enriched[0].advertisedProtocol).toBe('https') + expect(enriched[1].advertisedUrl).toBeUndefined() + }) + + it('passes detected listener PID through to watcher lookup', () => { + const calls: unknown[][] = [] + const watcher = { + reconcileScan(...args: Parameters): void { + calls.push(['reconcile', ...args]) + }, + lookupBest(...args: Parameters): AdvertisedUrl { + calls.push(['lookupBest', ...args]) + return { + origin: 'https://local.example.com:3001', + host: 'local.example.com', + hostKind: 'custom', + protocol: 'https', + port: 3001, + ptyId: 'pty', + lastSeenAt: 0 + } + } + } + + enrichSshDetectedPorts( + [{ port: 3001, host: '127.0.0.1', pid: 4242, processName: 'node' }], + ['wt'], + watcher + ) + + expect(calls).toEqual([ + ['reconcile', ['wt'], [{ port: 3001, pid: 4242 }]], + ['lookupBest', ['wt'], 3001, 4242] + ]) + }) + + it('skips advertised enrichment when one port maps to multiple listener PIDs', () => { + const calls: unknown[][] = [] + const watcher = { + reconcileScan(...args: Parameters): void { + calls.push(['reconcile', ...args]) + }, + lookupBest(...args: Parameters): AdvertisedUrl { + calls.push(['lookupBest', ...args]) + return { + origin: 'https://local.example.com:3001', + host: 'local.example.com', + hostKind: 'custom', + protocol: 'https', + port: 3001, + ptyId: 'pty', + lastSeenAt: 0 + } + } + } + + const enriched = enrichSshDetectedPorts( + [ + { port: 3001, host: '127.0.0.1', pid: 1111, processName: 'node' }, + { port: 3001, host: '127.0.0.2', pid: 2222, processName: 'node' } + ], + ['wt'], + watcher + ) + + expect(enriched.every((port) => port.advertisedUrl === undefined)).toBe(true) + expect(calls).toEqual([ + [ + 'reconcile', + ['wt'], + [ + { port: 3001, pid: 1111 }, + { port: 3001, pid: 2222 } + ] + ] + ]) + }) + + it('still enriches duplicate host rows when the port has one unique PID', () => { + const calls: unknown[][] = [] + const watcher = { + reconcileScan(...args: Parameters): void { + calls.push(['reconcile', ...args]) + }, + lookupBest(...args: Parameters): AdvertisedUrl { + calls.push(['lookupBest', ...args]) + return { + origin: 'https://local.example.com:3001', + host: 'local.example.com', + hostKind: 'custom', + protocol: 'https', + port: 3001, + ptyId: 'pty', + lastSeenAt: 0 + } + } + } + + const enriched = enrichSshDetectedPorts( + [ + { port: 3001, host: '127.0.0.1', pid: 4242, processName: 'node' }, + { port: 3001, host: '::1', pid: 4242, processName: 'node' } + ], + ['wt'], + watcher + ) + + expect(enriched.every((port) => port.advertisedUrl === 'https://local.example.com:3001')).toBe( + true + ) + expect(calls).toEqual([ + [ + 'reconcile', + ['wt'], + [ + { port: 3001, pid: 4242 }, + { port: 3001, pid: 4242 } + ] + ], + ['lookupBest', ['wt'], 3001, 4242], + ['lookupBest', ['wt'], 3001, 4242] + ]) + }) + + it('can enrich cached scanner rows without validating their PID', () => { + const calls: unknown[][] = [] + const watcher = { + reconcileScan(...args: Parameters): void { + calls.push(['reconcile', ...args]) + }, + lookupBest(...args: Parameters): AdvertisedUrl { + calls.push(['lookupBest', ...args]) + return { + origin: 'https://local.example.com:3001', + host: 'local.example.com', + hostKind: 'custom', + protocol: 'https', + port: 3001, + ptyId: 'pty', + lastSeenAt: 0 + } + } + } + + const enriched = enrichSshDetectedPorts( + [{ port: 3001, host: '127.0.0.1', pid: 4242, processName: 'node' }], + ['wt'], + watcher, + { validatePid: false } + ) + + expect(calls).toEqual([['lookupBest', ['wt'], 3001, undefined]]) + expect(enriched[0].pid).toBe(4242) + expect(enriched[0].advertisedUrl).toBe('https://local.example.com:3001') + }) + + it('does not reconcile cached scanner rows during watcher-triggered refreshes', () => { + const watcher = new AdvertisedUrlWatcher() + watcher.bindPty('pty-1', 'wt') + watcher.ingest('pty-1', 'ready at https://local.example.com:3001/\n') + + expect(enrichSshDetectedPorts([], ['wt'], watcher, { validatePid: false })).toEqual([]) + expect(watcher.lookupBest(['wt'], 3001)?.origin).toBe('https://local.example.com:3001') + }) +}) diff --git a/src/main/ports/ssh-advertised-url-enrichment.ts b/src/main/ports/ssh-advertised-url-enrichment.ts new file mode 100644 index 000000000..c7c264d3e --- /dev/null +++ b/src/main/ports/ssh-advertised-url-enrichment.ts @@ -0,0 +1,140 @@ +// Maps the local AdvertisedUrlWatcher cache onto SSH port shapes. +// +// SSH PTY data already flows through `runtime.onPtyData`, so the watcher +// captures URLs from remote dev servers running inside SSH-hosted terminals. +// What the SSH side lacks is the link between a connection's port scan and +// the worktreeIds the watcher keyed those URLs under. + +import type { DetectedPort, EnrichedDetectedPort, PortForwardEntry } from '../../shared/ssh-types' +import type { Store } from '../persistence' +import { splitWorktreeId } from '../../shared/worktree-id' +import { + advertisedUrlWatcher, + type AdvertisedUrl, + type AdvertisedUrlWatcher +} from './advertised-url-watcher' + +/** Collect every worktreeId attached to a given SSH connection. The watcher + * is keyed per worktree, but SSH port scans are per connection, so callers + * need the union to find the best advertised URL across the connection. */ +export function getWorktreeIdsForConnection( + store: Pick, + connectionId: string +): string[] { + const matchingRepoIds = new Set( + store + .getRepos() + .filter((repo) => repo.connectionId === connectionId) + .map((repo) => repo.id) + ) + if (matchingRepoIds.size === 0) { + return [] + } + return Object.keys(store.getAllWorktreeMeta()).filter((worktreeId) => { + const parsed = splitWorktreeId(worktreeId) + return parsed ? matchingRepoIds.has(parsed.repoId) : false + }) +} + +export function getConnectionIdsForWorktree( + store: Pick, + worktreeId: string +): string[] { + const parsed = splitWorktreeId(worktreeId) + if (!parsed) { + return [] + } + const connectionId = store.getRepos().find((repo) => repo.id === parsed.repoId)?.connectionId + return connectionId ? [connectionId] : [] +} + +type EnrichmentTarget = { advertisedUrl?: string; advertisedProtocol?: 'http' | 'https' } +type SshDetectedPortEnrichmentOptions = { + validatePid?: boolean +} +type PortPidState = { kind: 'single'; pid?: number } | { kind: 'ambiguous' } + +function applyAdvertisedUrl( + target: T, + found: AdvertisedUrl +): T & EnrichmentTarget { + // Spread to keep callers' inputs immutable — important for the broadcast + // path which sends the same array to multiple subscribers. + return { ...target, advertisedUrl: found.origin, advertisedProtocol: found.protocol } +} + +export function enrichSshDetectedPorts( + ports: readonly DetectedPort[], + worktreeIds: readonly string[], + watcher: Pick = advertisedUrlWatcher, + options: SshDetectedPortEnrichmentOptions = {} +): EnrichedDetectedPort[] { + if (worktreeIds.length === 0) { + return [...ports] + } + if (options.validatePid !== false) { + // Why: SSH scans are connection-scoped while URLs are worktree-scoped; use + // the scan snapshot to invalidate stale same-port candidates before lookup. + watcher.reconcileScan( + worktreeIds, + ports.map((port) => ({ port: port.port, pid: port.pid })) + ) + } + if (ports.length === 0) { + return [...ports] + } + const pidStateByPort = options.validatePid === false ? undefined : getPidStateByPort(ports) + return ports.map((port) => { + const pidState = pidStateByPort?.get(port.port) + if (pidState?.kind === 'ambiguous') { + return port + } + // Why: pass the remote listener PID so the watcher can evict stale URLs + // when the port has been reused by a different process. The relay-side + // scanner reads /proc/net/tcp and includes the PID when available. + const found = watcher.lookupBest( + worktreeIds, + port.port, + options.validatePid === false ? undefined : pidState?.pid + ) + return found ? applyAdvertisedUrl(port, found) : port + }) +} + +function getPidStateByPort(ports: readonly DetectedPort[]): Map { + const states = new Map() + for (const port of ports) { + const existing = states.get(port.port) + if (!existing) { + states.set(port.port, { kind: 'single', pid: port.pid }) + continue + } + if (existing.kind === 'ambiguous') { + continue + } + if (existing.pid !== port.pid || existing.pid === undefined) { + // Why: SSH scans can report several host-specific listeners for one + // numeric port, but advertised URLs are cached only by port. + states.set(port.port, { kind: 'ambiguous' }) + } + } + return states +} + +export function enrichSshForwardEntries( + entries: readonly PortForwardEntry[], + worktreeIds: readonly string[], + watcher: Pick = advertisedUrlWatcher +): PortForwardEntry[] { + if (worktreeIds.length === 0 || entries.length === 0) { + return [...entries] + } + // Why: forward entries are user-configured (persisted by remotePort), not + // observed listeners — we cannot validate against a current listener PID + // here. Detected-port enrichment is the eviction path; whatever survives + // there is safe to surface for the matching forward. + return entries.map((entry) => { + const found = watcher.lookupBest(worktreeIds, entry.remotePort) + return found ? applyAdvertisedUrl(entry, found) : entry + }) +} diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 2abadb473..c67d1372d 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -30,6 +30,7 @@ import { } from '../providers/ssh-filesystem-dispatch' import { registerSshGitProvider, unregisterSshGitProvider } from '../providers/ssh-git-dispatch' import { DEFAULT_REPO_BADGE_COLOR } from '../../shared/constants' +import { advertisedUrlWatcher } from '../ports/advertised-url-watcher' const { MOCK_GIT_WORKTREES, @@ -254,6 +255,7 @@ vi.mock('../git/repo', async (importOriginal) => { }) afterEach(() => { + advertisedUrlWatcher.clear() vi.mocked(listWorktrees).mockResolvedValue(MOCK_GIT_WORKTREES) vi.mocked(addWorktree).mockReset() vi.mocked(assertWorktreeCleanForRemoval).mockReset() @@ -3435,6 +3437,17 @@ describe('OrcaRuntimeService', () => { expect(read.tail).toEqual(['ready']) }) + it('binds advertised URLs for renderer-restored PTYs that skip registerPty', () => { + const runtime = new OrcaRuntimeService(store) + + syncSinglePty(runtime, 'pty-restored') + runtime.onPtyData('pty-restored', 'Network: https://restored.example.com:3001/\n', 100) + + expect(advertisedUrlWatcher.lookup(TEST_WORKTREE_ID, 3001)?.origin).toBe( + 'https://restored.example.com:3001' + ) + }) + it('keeps preallocated terminal handles valid across renderer reloads', async () => { const runtime = new OrcaRuntimeService(store) const handle = runtime.preAllocateHandleForPty('pty-1') diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 53ed75e25..a06078aad 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -80,6 +80,7 @@ import { killWorkspacePort, scanWorkspacePortProbes } from '../ports/workspace-port-ownership' +import { advertisedUrlWatcher } from '../ports/advertised-url-watcher' import type { RuntimeGraphStatus, RuntimeRepoSearchRefs, @@ -1994,6 +1995,10 @@ export class OrcaRuntimeService { // Agent detection runs on raw data before leaf processing, since the // tail buffer logic normalizes away the OSC sequences we need. this.agentDetector?.onData(ptyId, data, at) + // Why: watch terminal output for advertised dev-server URLs (e.g. Vite's + // `Network: https://local.example.com:3001/`) so the workspace ports + // panel can surface them in place of the kernel bind address. + advertisedUrlWatcher.ingest(ptyId, data, at) // Ordering invariant (DO NOT REORDER): maybeHydrateHeadlessFromRenderer // MUST run before trackHeadlessTerminalData so the eager-state pattern // (set headlessTerminals + writeChain head = seedPromise) is in place @@ -3094,6 +3099,7 @@ export class OrcaRuntimeService { } onPtyExit(ptyId: string, exitCode: number): void { + advertisedUrlWatcher.unbindPty(ptyId) // Clean up new mobile state for this PTY this.mobileSubscribers.delete(ptyId) this.mobileDisplayModes.delete(ptyId) @@ -9468,6 +9474,9 @@ export class OrcaRuntimeService { preview: state.preview ?? '' } this.ptysById.set(ptyId, pty) + // Why: restored/controller-discovered PTYs learn their worktree here + // without registerPty(), so URL enrichment must bind at this source. + advertisedUrlWatcher.bindPty(ptyId, worktreeId) return pty } @@ -9487,6 +9496,9 @@ export class OrcaRuntimeService { if (state.preview !== undefined && state.preview.length > 0) { pty.preview = state.preview } + // Why: recordPtyWorktree is the common lifecycle point for every path that + // resolves a PTY's worktree, including renderer restore and controller list. + advertisedUrlWatcher.bindPty(ptyId, worktreeId) return pty } diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 2ad524611..3ccf49a6a 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -240,7 +240,7 @@ import type { SshConnectionState, SshTarget, PortForwardEntry, - DetectedPort + EnrichedDetectedPort } from '../shared/ssh-types' import type { CodexUsageBreakdownKind, @@ -1989,12 +1989,12 @@ export type PreloadApi = { }) => Promise removePortForward: (args: { id: string }) => Promise listPortForwards: (args?: { targetId?: string }) => Promise - listDetectedPorts: (args: { targetId: string }) => Promise + listDetectedPorts: (args: { targetId: string }) => Promise onPortForwardsChanged: ( callback: (data: { targetId: string; forwards: PortForwardEntry[] }) => void ) => () => void onDetectedPortsChanged: ( - callback: (data: { targetId: string; ports: DetectedPort[] }) => void + callback: (data: { targetId: string; ports: EnrichedDetectedPort[] }) => void ) => () => void browseDir: (args: { targetId: string; dirPath: string }) => Promise<{ entries: { name: string; isDirectory: boolean }[] diff --git a/src/preload/index.ts b/src/preload/index.ts index df77c64a4..419052bcc 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -102,7 +102,7 @@ import type { SshConnectionState, SshTarget, PortForwardEntry, - DetectedPort + EnrichedDetectedPort } from '../shared/ssh-types' import type { AgentStatusIpcPayload, @@ -3017,7 +3017,7 @@ const api = { listPortForwards: (args?: { targetId?: string }): Promise => ipcRenderer.invoke('ssh:listPortForwards', args), - listDetectedPorts: (args: { targetId: string }): Promise => + listDetectedPorts: (args: { targetId: string }): Promise => ipcRenderer.invoke('ssh:listDetectedPorts', args), onPortForwardsChanged: ( @@ -3032,11 +3032,11 @@ const api = { }, onDetectedPortsChanged: ( - callback: (data: { targetId: string; ports: DetectedPort[] }) => void + callback: (data: { targetId: string; ports: EnrichedDetectedPort[] }) => void ): (() => void) => { const handler = ( _event: Electron.IpcRendererEvent, - data: { targetId: string; ports: DetectedPort[] } + data: { targetId: string; ports: EnrichedDetectedPort[] } ) => callback(data) ipcRenderer.on('ssh:detected-ports-changed', handler) return () => ipcRenderer.removeListener('ssh:detected-ports-changed', handler) diff --git a/src/renderer/src/components/right-sidebar/PortsPanel.test.tsx b/src/renderer/src/components/right-sidebar/PortsPanel.test.tsx index fc7a1d018..b8838f200 100644 --- a/src/renderer/src/components/right-sidebar/PortsPanel.test.tsx +++ b/src/renderer/src/components/right-sidebar/PortsPanel.test.tsx @@ -3,8 +3,15 @@ import { MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, RUNTIME_PROTOCOL_VERSION } from '../../../../shared/protocol-version' +import type { PortForwardEntry } from '../../../../shared/ssh-types' import type { WorkspacePort, WorkspacePortScanResult } from '../../../../shared/workspace-ports' import { clearRuntimeCompatibilityCacheForTests } from '@/runtime/runtime-rpc-client' +import { + addressForPort, + addressForPortForwardEntry, + browserUrlForPort, + browserUrlForPortForwardEntry +} from '@/lib/workspace-port-urls' const { activateAndRevealWorktreeMock } = vi.hoisted(() => ({ activateAndRevealWorktreeMock: vi.fn() @@ -14,13 +21,12 @@ vi.mock('@/lib/worktree-activation', () => ({ activateAndRevealWorktree: activateAndRevealWorktreeMock })) +import { getLocalWorkspacePortSections } from './PortsPanel' import { - browserUrlForPort, - getLocalWorkspacePortSections, killWorkspacePortForTarget, openWorkspacePortInBrowser, scanWorkspacePortsForTarget -} from './PortsPanel' +} from '@/lib/workspace-port-actions' const workspacePort: WorkspacePort = { id: '127.0.0.1:63468:1234', @@ -253,4 +259,40 @@ describe('PortsPanel runtime routing', () => { it('defaults unknown protocols to http for built-in browser opens', () => { expect(browserUrlForPort(workspacePort)).toBe('http://127.0.0.1:63468') }) + + it('prefers advertisedUrl over the OS-derived host:port', () => { + const advertised: WorkspacePort = { + ...workspacePort, + advertisedUrl: 'https://local.getmontecarlo.com:63468' + } + expect(browserUrlForPort(advertised)).toBe('https://local.getmontecarlo.com:63468') + expect(addressForPort(advertised)).toBe('local.getmontecarlo.com:63468') + }) + + it('formats SSH forwarded advertised URLs with a single protocol fallback order', () => { + const forward: PortForwardEntry = { + id: 'forward-1', + connectionId: 'connection-1', + localPort: 63468, + remoteHost: 'localhost', + remotePort: 3001, + advertisedUrl: 'https://local.getmontecarlo.com:3001' + } + + expect(browserUrlForPortForwardEntry(forward)).toBe('https://local.getmontecarlo.com:63468') + expect(addressForPortForwardEntry(forward)).toBe('local.getmontecarlo.com:63468') + expect(browserUrlForPortForwardEntry({ ...forward, advertisedProtocol: 'http' })).toBe( + 'http://local.getmontecarlo.com:63468' + ) + expect( + browserUrlForPortForwardEntry({ + ...forward, + advertisedUrl: undefined, + remotePort: 8443 + }) + ).toBe('https://127.0.0.1:63468') + expect(addressForPortForwardEntry({ ...forward, advertisedUrl: undefined })).toBe( + '127.0.0.1:63468' + ) + }) }) diff --git a/src/renderer/src/components/right-sidebar/PortsPanel.tsx b/src/renderer/src/components/right-sidebar/PortsPanel.tsx index 6b356b978..2681780d7 100644 --- a/src/renderer/src/components/right-sidebar/PortsPanel.tsx +++ b/src/renderer/src/components/right-sidebar/PortsPanel.tsx @@ -20,12 +20,18 @@ import { useActiveWorktree, useRepoById } from '@/store/selectors' import { cn } from '@/lib/utils' import { getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' import { - addressForPort, killWorkspacePortForTarget, openWorkspacePortInBrowser, scanWorkspacePortsForTarget, workspacePortRuntimeTargetKey } from '@/lib/workspace-port-actions' +import { + addressForPort, + addressForPortForwardEntry, + advertisedBrowserUrlForDetectedPort, + advertisedBrowserUrlForForwardedRow, + browserUrlForPortForwardEntry +} from '@/lib/workspace-port-urls' import { Dialog, DialogContent, @@ -43,11 +49,10 @@ import { ContextMenuSeparator, ContextMenuTrigger } from '@/components/ui/context-menu' -import type { PortForwardEntry, DetectedPort } from '../../../../shared/ssh-types' +import type { PortForwardEntry, EnrichedDetectedPort } from '../../../../shared/ssh-types' import type { WorkspacePort } from '../../../../shared/workspace-ports' export { - browserUrlForPort, killWorkspacePortForTarget, openWorkspacePortInBrowser, scanWorkspacePortsForTarget @@ -116,8 +121,6 @@ function safeLocalPort(remotePort: number): number { return remotePort } -const HTTPS_PORTS = new Set([443, 8443]) - // Why: forwarded SSH ports and detected remote ports may report the same loopback // endpoint using different textual hosts. Normalize for deduping only. const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0', '::']) @@ -443,6 +446,7 @@ function LocalPortRow({ ) const processLabel = port.processName ?? (port.pid ? `PID ${port.pid}` : 'Unknown process') + const address = addressForPort(port) const ownerLabel = port.kind === 'workspace' ? port.owner.displayName @@ -472,6 +476,9 @@ function LocalPortRow({ {processLabel}
+ {address} +
+
{ownerLabel} {confidenceLabel && ( {confidenceLabel} @@ -507,13 +514,13 @@ function LocalPortRow({ size="icon-xs" className="text-muted-foreground hover:text-foreground" onClick={handleCopyButtonClick} - aria-label="Copy Address" + aria-label={`Copy ${address}`} > - Copy Address + Copy {address} {canStopProcess && ( @@ -672,7 +679,7 @@ function SshPortsPanel(): React.JSX.Element { const [detectedCollapsed, setDetectedCollapsed] = useState(false) const [dialogState, setDialogState] = useState({ mode: 'closed' }) - const handleForwardDetected = useCallback((port: DetectedPort & { targetId: string }) => { + const handleForwardDetected = useCallback((port: EnrichedDetectedPort & { targetId: string }) => { setDialogState({ mode: 'add', defaults: { @@ -694,10 +701,7 @@ function SshPortsPanel(): React.JSX.Element { toast.error('No workspace selected for the browser.') return } - // Why: the protocol hint comes from the remote port (the actual service), - // not the local port which may be an arbitrary remap. - const protocol = HTTPS_PORTS.has(entry.remotePort) ? 'https' : 'http' - createBrowserTab(activeWorktree.id, `${protocol}://127.0.0.1:${entry.localPort}`, { + createBrowserTab(activeWorktree.id, browserUrlForPortForwardEntry(entry), { activate: true }) }, @@ -841,6 +845,7 @@ function ForwardedPortRow({ onOpenInBrowser: () => void }): React.JSX.Element { const [removing, setRemoving] = useState(false) + const forwardedAddress = addressForPortForwardEntry(entry) const handleRemove = useCallback(async () => { setRemoving(true) @@ -853,11 +858,8 @@ function ForwardedPortRow({ }, [entry.id]) const handleCopy = useCallback(() => { - // Why: use 127.0.0.1 instead of localhost because the local TCP listener - // binds to 127.0.0.1 specifically. On systems that resolve localhost to - // ::1 first, "localhost:" would fail even though the forward is up. - void window.api.ui.writeClipboardText(`127.0.0.1:${entry.localPort}`) - }, [entry.localPort]) + void window.api.ui.writeClipboardText(forwardedAddress) + }, [forwardedAddress]) const handleOpenBrowser = useCallback(() => { onOpenInBrowser() @@ -903,6 +905,8 @@ function ForwardedPortRow({ [handleRemove] ) + const advertisedBrowserUrl = advertisedBrowserUrlForForwardedRow(entry) + return (
@@ -919,13 +923,22 @@ function ForwardedPortRow({ :{entry.localPort} → :{entry.remotePort}
+ {advertisedBrowserUrl && ( +
+ opens {advertisedBrowserUrl} +
+ )}
@@ -933,7 +946,7 @@ function ForwardedPortRow({ type="button" className="p-1 rounded hover:bg-accent transition-colors text-muted-foreground hover:text-foreground" onClick={handleCopyButtonClick} - title="Copy Address" + title={`Copy ${forwardedAddress}`} > @@ -966,15 +979,23 @@ function DetectedPortRow({ port, onForward }: { - port: DetectedPort & { targetId: string } + port: EnrichedDetectedPort & { targetId: string } onForward: () => void }): React.JSX.Element { + const advertisedBrowserUrl = advertisedBrowserUrlForDetectedPort(port) return (
- :{port.port} - {port.processName && ( - {port.processName} +
+ :{port.port} + {port.processName && ( + {port.processName} + )} +
+ {advertisedBrowserUrl && ( +
+ advertised as {advertisedBrowserUrl} +
)}
@@ -82,6 +89,7 @@ function WorktreePortRow({ port }: { port: WorkspacePort }): React.JSX.Element { const setWorkspacePortScanRefreshing = useAppStore((s) => s.setWorkspacePortScanRefreshing) const runtimeTarget = useMemo(() => getActiveRuntimeTarget(settings), [settings]) const processLabel = port.processName ?? (port.pid ? `PID ${port.pid}` : 'Unknown process') + const address = addressForPort(port) const canStop = canStopWorkspacePort(port) const handleOpen = useCallback( @@ -104,8 +112,9 @@ function WorktreePortRow({ port }: { port: WorkspacePort }): React.JSX.Element { const handleCopy = useCallback( (event: React.MouseEvent) => { event.stopPropagation() - void window.api.ui.writeClipboardText(addressForPort(port)) - toast.success(`Copied ${port.port}`) + const address = addressForPort(port) + void window.api.ui.writeClipboardText(address) + toast.success(`Copied ${address}`) }, [port] ) @@ -151,19 +160,27 @@ function WorktreePortRow({ port }: { port: WorkspacePort }): React.JSX.Element {
- - {processLabel} + + {processLabel} + - + + {address} + - {processLabel} + + {processLabel} + - + {address} +
- + diff --git a/src/renderer/src/components/status-bar/PortsStatusSegment.tsx b/src/renderer/src/components/status-bar/PortsStatusSegment.tsx index b76e98608..a1453d207 100644 --- a/src/renderer/src/components/status-bar/PortsStatusSegment.tsx +++ b/src/renderer/src/components/status-bar/PortsStatusSegment.tsx @@ -47,22 +47,33 @@ function PortAction({ disabled?: boolean children: React.ReactNode }): React.JSX.Element { + const handleClick = (event: React.MouseEvent): void => { + onClick(event) + if (event.detail > 0) { + event.currentTarget.blur() + } + } + + const button = ( + + ) + return ( - + {disabled ? {button} : button} - + {label} @@ -109,8 +120,9 @@ function PortRow({ const handleCopy = useCallback( (event: React.MouseEvent) => { event.stopPropagation() - void window.api.ui.writeClipboardText(addressForPort(port)) - toast.success(`Copied ${port.port}`) + const address = addressForPort(port) + void window.api.ui.writeClipboardText(address) + toast.success(`Copied ${address}`) }, [port] ) diff --git a/src/renderer/src/lib/workspace-port-actions.ts b/src/renderer/src/lib/workspace-port-actions.ts index f23547b14..6ebdc3f56 100644 --- a/src/renderer/src/lib/workspace-port-actions.ts +++ b/src/renderer/src/lib/workspace-port-actions.ts @@ -10,24 +10,9 @@ import type { WorkspacePortKillResult, WorkspacePortScanResult } from '../../../shared/workspace-ports' +import { browserUrlForPort } from './workspace-port-urls' -// Why: the scanner reports numeric addresses (127.0.0.1, 0.0.0.0, ::1, ::) -// while UI actions should use an address a browser can reliably open. -function hostForLocalAction(host: string): string { - if (!host) { - return 'localhost' - } - return host.includes(':') ? `[${host}]` : host -} - -export function addressForPort(port: WorkspacePort): string { - return `${hostForLocalAction(port.connectHost)}:${port.port}` -} - -export function browserUrlForPort(port: WorkspacePort): string { - const protocol = port.protocol === 'https' ? 'https' : 'http' - return `${protocol}://${addressForPort(port)}` -} +export { addressForPort } from './workspace-port-urls' export function canStopWorkspacePort( port: WorkspacePort diff --git a/src/renderer/src/lib/workspace-port-urls.ts b/src/renderer/src/lib/workspace-port-urls.ts new file mode 100644 index 000000000..a945ecdad --- /dev/null +++ b/src/renderer/src/lib/workspace-port-urls.ts @@ -0,0 +1,118 @@ +import type { PortForwardEntry, EnrichedDetectedPort } from '../../../shared/ssh-types' +import type { WorkspacePort } from '../../../shared/workspace-ports' + +const HTTPS_PORTS = new Set([443, 8443]) +const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0', '::']) + +// Why: the scanner reports numeric addresses (127.0.0.1, 0.0.0.0, ::1, ::) +// while UI actions should use an address a browser can reliably open. +function hostForLocalAction(host: string): string { + if (!host) { + return 'localhost' + } + return host.includes(':') ? `[${host}]` : host +} + +export function addressForPort(port: WorkspacePort): string { + // Why: when a dev server printed its own URL to the terminal, that origin + // (e.g. `local.getmontecarlo.com:3001`) is what the user actually wants in + // the clipboard, not the kernel bind `127.0.0.1:3001`. + if (port.kind === 'workspace' && port.advertisedUrl) { + try { + const url = new URL(port.advertisedUrl) + return url.host || `${hostForLocalAction(port.connectHost)}:${port.port}` + } catch { + // Fall through to OS-derived address. + } + } + return `${hostForLocalAction(port.connectHost)}:${port.port}` +} + +export function browserUrlForPort(port: WorkspacePort): string { + if (port.kind === 'workspace' && port.advertisedUrl) { + return port.advertisedUrl + } + const protocol = port.protocol === 'https' ? 'https' : 'http' + return `${protocol}://${hostForLocalAction(port.connectHost)}:${port.port}` +} + +/** Extract a custom DNS hostname from an advertised URL for reuse with a + * local SSH forward port. Returns null for loopback and IP literals; those + * printed-from-remote values don't help the local browser, and callers + * should fall back to 127.0.0.1 + local port. A DNS hostname only resolves + * locally if the user has /etc/hosts (or equivalent) mapping; we trust that + * rather than probing DNS here. */ +function customHostFromAdvertised(advertisedUrl: string | undefined): string | null { + if (!advertisedUrl) { + return null + } + try { + const url = new URL(advertisedUrl) + const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, '') + if (LOOPBACK_HOSTS.has(hostname)) { + return null + } + // IPv4 or IPv6 literals are not portable to the local box. + if (/^[0-9.]+$/.test(hostname) || hostname.includes(':')) { + return null + } + return url.hostname + } catch { + return null + } +} + +type AdvertisedPortUrlFields = { + advertisedProtocol?: 'http' | 'https' + advertisedUrl?: string + remotePort: number +} + +function advertisedProtocolForPort(port: AdvertisedPortUrlFields): 'http' | 'https' { + if (port.advertisedProtocol) { + return port.advertisedProtocol + } + if (port.advertisedUrl) { + try { + const protocol = new URL(port.advertisedUrl).protocol.replace(/:$/, '') + if (protocol === 'http' || protocol === 'https') { + return protocol + } + } catch { + // Fall through to the same port heuristic used for entries without an advertised URL. + } + } + return HTTPS_PORTS.has(port.remotePort) ? 'https' : 'http' +} + +export function browserUrlForPortForwardEntry(entry: PortForwardEntry): string { + // Why: older enriched entries may have advertisedUrl without advertisedProtocol; + // derive the URL once so the open action and labels do not drift. + const protocol = advertisedProtocolForPort(entry) + const host = customHostFromAdvertised(entry.advertisedUrl) ?? '127.0.0.1' + return `${protocol}://${host}:${entry.localPort}` +} + +export function addressForPortForwardEntry(entry: PortForwardEntry): string { + return new URL(browserUrlForPortForwardEntry(entry)).host +} + +export function advertisedBrowserUrlForForwardedRow(entry: PortForwardEntry): string | null { + if (!customHostFromAdvertised(entry.advertisedUrl)) { + return null + } + return browserUrlForPortForwardEntry(entry) +} + +export function advertisedBrowserUrlForDetectedPort(port: EnrichedDetectedPort): string | null { + const host = customHostFromAdvertised(port.advertisedUrl) + if (!host) { + return null + } + const protocol = advertisedProtocolForPort({ + advertisedProtocol: port.advertisedProtocol, + advertisedUrl: port.advertisedUrl, + remotePort: port.port + }) + return `${protocol}://${host}:${port.port}` +} diff --git a/src/renderer/src/store/slices/ssh.ts b/src/renderer/src/store/slices/ssh.ts index 1206bb280..0b28d74f9 100644 --- a/src/renderer/src/store/slices/ssh.ts +++ b/src/renderer/src/store/slices/ssh.ts @@ -3,7 +3,7 @@ import type { AppState } from '../types' import type { SshConnectionState, PortForwardEntry, - DetectedPort, + EnrichedDetectedPort, SshTarget } from '../../../../shared/ssh-types' @@ -40,9 +40,9 @@ export type SshSlice = { * objects. Spreading a Record produces a new reference that Zustand can diff * by identity, whereas Map mutations are easy to get wrong. */ portForwardsByConnection: Record - /** Detected listening ports on the remote, keyed by connection ID. - * Updated by polling the relay's ports.detect RPC. */ - detectedPortsByConnection: Record + /** Detected remote listening ports after main-process enrichment, keyed by + * connection ID. Updated from SSH IPC snapshots and push events. */ + detectedPortsByConnection: Record setSshConnectionState: (targetId: string, state: SshConnectionState) => void setSshTargetLabels: (labels: Map) => void setSshTargetsMetadata: (targets: Pick[]) => void @@ -53,7 +53,7 @@ export type SshSlice = { removeSshCredentialRequest: (requestId: string) => void setPortForwards: (targetId: string, forwards: PortForwardEntry[]) => void clearPortForwards: (targetId: string) => void - setDetectedPorts: (targetId: string, ports: DetectedPort[]) => void + setDetectedPorts: (targetId: string, ports: EnrichedDetectedPort[]) => void } export const createSshSlice: StateCreator = (set) => ({ diff --git a/src/shared/ssh-types.ts b/src/shared/ssh-types.ts index 75640aacb..58c8b02d9 100644 --- a/src/shared/ssh-types.ts +++ b/src/shared/ssh-types.ts @@ -80,6 +80,13 @@ export type PortForwardEntry = { remoteHost: string remotePort: number label?: string + /** Origin captured from terminal output for this remote port (e.g. a Vite + * banner printed inside an SSH-hosted PTY). The renderer rewrites the port + * to the local forward and trusts the user has DNS for the custom host. */ + advertisedUrl?: string + /** Protocol parsed from the advertised URL — used to upgrade HTTP guesses + * to HTTPS even when the advertised host can't be reused locally. */ + advertisedProtocol?: 'http' | 'https' } /** A listening port detected on the remote host via /proc/net/tcp scanning. @@ -91,3 +98,10 @@ export type DetectedPort = { pid?: number processName?: string } + +/** A detected SSH port after the main process has mapped terminal-advertised + * URLs onto the raw relay scan row for IPC/UI consumption. */ +export type EnrichedDetectedPort = DetectedPort & { + advertisedUrl?: string + advertisedProtocol?: 'http' | 'https' +} diff --git a/src/shared/workspace-ports.ts b/src/shared/workspace-ports.ts index 2b9ff8a94..9e2a22eed 100644 --- a/src/shared/workspace-ports.ts +++ b/src/shared/workspace-ports.ts @@ -31,6 +31,12 @@ export type WorkspacePort = | (WorkspacePortBase & { kind: 'workspace' owner: WorkspacePortOwner + /** Origin captured from terminal output (e.g. Vite's `Network: https://...:3001/`). + * Only set when a workspace-attributed PTY printed a URL whose port matches + * this listener. Origin only — never includes path, query, fragment, or + * userinfo. Prefer this over `protocol://connectHost:port` for the open and + * copy-link actions. */ + advertisedUrl?: string }) | (WorkspacePortBase & { kind: 'container'