Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(ports): dev-server port discovery + same-port forwarding for SSH projects
review4e6e86072067
diff --git a/CLAUDE.md b/CLAUDE.mdindex a81a8d718..50535562e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -5172,6 +5172,98 @@ disappearing" rather than as an occasional cull. The `vm_stat` reader is what maagain; the grace window was never the thing that was wrong.+## Dev-server ports (the Ports chip + same-port SSH forwarding)++An agent starts a dev server inside a node's session; on an SSH project it listens on the HOST's+`127.0.0.1:<port>`, and before this the person had to build a tunnel by hand before a browser node+could show it. A terminal node's header (and its kanban card modal — one component, `PortsChip`)+now shows the TCP ports that node's session listens on; a row opens `http://localhost:<port>` in a+browser node beside it, and on an SSH project it first forwards the SAME port number over the+project's existing ControlMaster, so the URL the tool itself printed just works here. Pieces:+`core/dev-ports.ts` (probe + parsers), `core/remote-ssh/port-forward.ts` (lifecycle),+`core/dev-ports-service.ts` (routing), `renderer/components/PortsChip.tsx`,+`renderer/state/devPorts.ts` + `canvas/useDevPortScanner.ts` (cadence), `lib/devPorts.ts` (pure).++- **Discovery is by OWNERSHIP, never by probing.** A port is attributed to a node only when its+ listening socket belongs to a process inside that node's tmux pane tree (every pane of `nt-<id>`,+ the same tree session memory rolls up — `indexProcesses` is shared). Nothing is ever connected to,+ and another user's or another program's port is never reported. The owning pid comes from+ `ss -ltnp` (Linux), else `lsof -nP -iTCP -sTCP:LISTEN -Fpcn` (macOS, Linux without iproute2 — its+ exit 1 with no output is an ANSWER, "nothing listening"), else `/proc/net/tcp{,6}` joined to+ `ls -l /proc/*/fd` by socket inode (one `ls`, never a `readlink` per descriptor). No tool at all is+ its own failure (`no-listener-tool`), never "no ports".+- **One generated script, run on BOTH machines.** `devPortsProbeCommand` is POSIX sh; a local project+ runs it through `/bin/sh -c`, an SSH project over the master — one round trip carrying the panes of+ both nodeterm sockets (fenced per socket with the SAME `fencedListPanesCommand`/`parseFencedPanes`+ session memory uses, so "no server running" is an answer and a broken tmux on every socket is+ `unreachable`), `ps -eo pid=,ppid=,comm=`, and the listener section. One script, one parser: a+ separately written local leg is the drift the session-memory ledger records three times. PATH is+ APPENDED with the tmux dirs and `/usr/sbin:/sbin` (where `ss`/`lsof` live on some distros and a+ non-login exec channel's PATH lacks them). Every marker is quoted (`echo ##X` prints an empty line+ under POSIX sh). Tested under a real `/bin/sh` against a fake host tree, one case per branch, AND+ end to end on Linux: a real tmux session (private socket, sandboxed TMUX_TMPDIR) running a real+ listener two processes below its pane, read back through real `ps` + `ss`+ (`dev-ports.realsh.test.ts`).+- **Ports in the ephemeral range (≥ 32768) are listed but not counted.** A headless browser's+ debugging endpoint or an MCP helper asks for "any port" and lands there; a dev server a person+ means to open almost never does. The chip counts only the rest and is absent when there are none;+ the others sit one level down in the menu ("Other ports").+- **Cadence** (`lib/devPorts.ts`): a scan when the project comes on screen and on window focus; a+ debounced trailing scan 4 s after the project's agents report activity (`onHookEvent` — a dev+ server is usually an agent's tool call); a slow poll (30 s local, 60 s SSH) ONLY while the window is+ focused and visible — a server started by hand in a plain terminal fires no hook; and on demand when+ the chip's menu opens. Automatic scans keep a 10 s gap; concurrent ones coalesce in core. An SSH+ project is scanned only while connected. One scan costs one `ps` plus one `ss` (a few lines) — an+ exec over the master on a host, never a login.+- **Forwarding rules — each a refusal, never a guess** (`PortForwardRegistry`):+ - The renderer names a node and a port, never an address. Core re-scans at click time and forwards+ only a port that scan attributes to THAT node; the host-side target FOLLOWS THE BIND+ (`forwardTarget`: any IPv4 wildcard/loopback → `127.0.0.1`, else `::1`, else the one specific+ address), because a server bound only to `::1` refuses `127.0.0.1`. The target is re-validated as+ an IP literal — it came off another machine's command output and lands in an ssh argument.+ - The local side binds `127.0.0.1` ONLY (`localForwardArgs`), never `*`: an unfinished app must not+ be published to the network the laptop is on.+ - **A taken local port is refused with the reason, never silently moved.** "Taken" means anything+ answers on `127.0.0.1:P` OR `[::1]:P`, or 127.0.0.1 cannot be bound: a local app bound only to+ `::1` leaves 127.0.0.1 free, the forward would succeed, and the browser's `localhost` (IPv6 first)+ would show the LOCAL app under the host's name. A different local port is only ever the person's+ explicit choice (a confirm naming a suggested free port, and saying the tool's printed links will+ not reach it).+ - A privileged port (< 1024, either side) is never forwarded until the person confirms it.+ - Lifecycle: cancelled (`-O cancel` with the exact spec) when the node's session ends+ (`PtyManager.onSessionEnded` — delete and recycle) or when a SUCCESSFUL scan no longer lists the+ host port; dropped without ssh when the project leaves `connected` (the master takes its+ listeners with it). A failed scan cancels nothing — a failed read is never evidence. A master+ rebuilt behind our back by `ControlMaster=auto` (issue #735's mechanism) carries no `-L`, so every+ successful scan re-checks that the local listener is still held and forgets one that is not — the+ menu then offers to forward again instead of claiming a dead forward.+ - Main wires both lifecycle hooks; `main/dev-ports-wiring.test.ts` pins them at source level,+ because a dropped listener compiles and leaves forwards open after their node closed.+- **MEASURED against a real OpenSSH 9.6p1 sshd + mux master (2026-09-30, lab on loopback):**+ `-O forward -L 127.0.0.1:P:[::1]:P` exits 0 and `http://localhost:P` answers 200 through it (the+ bracketed IPv6 target works); the IDENTICAL forward again exits 0 (the master dedups it); a local+ port already bound by another process exits **255** with `mux_client_forward: forwarding request+ failed: Port forwarding failed` — synchronous, so a refusal is known at click time; `-O cancel`+ closes the listener (curl then gets connection refused) and exits **0 even when nothing was+ forwarded** (it only prints an error), which is why its exit code is ignored; `-O exit` takes every+ forward with it.+- **Surfaces.** Desktop: full (local projects: discovery + open, no forward — the port is already on+ this machine; SSH projects: discovery on the host + same-port forward). Windows: the local probe+ answers `unsupported` (no `/bin/sh`, no tmux) and the chip is not drawn; an SSH project from a+ Windows desktop still works (the probe runs on the host). **Server Edition: not served, on+ purpose** — the browser node is an Electron `<webview>` a browser tab does not have, and a page the+ viewer opened would load on the VIEWER's machine, where the server's port is not. Its bridge stub+ answers `unsupported`; nothing registers the service in `src/server`. Relay tabs: the same stub+ (their sessions live on the host). Kanban: the card modal draws the chip when the card's project is+ the one on the canvas; opening a port hands over to the canvas, where the browser node appears+ beside the node. **Mobile: follow-up** — the phone would need the port list over the relay and a+ forward of its own (it has no local browser node); noted for nodeterm-ios. All three channels are+ in `HOST_ONLY_CHANNELS` (a forward binds a port on the host machine's loopback).+- **Known limits, stated:** a server that DAEMONIZES (double-fork, reparented to init) leaves the+ pane tree and is not found; `ss` without `-p` information for our own processes (hidepid, a+ container) finds listeners but no owner, so nothing is attributed; the Mac leg (lsof, the local+ bind/connect probes under BSD socket rules) has not been run on a Mac — device checklist in the PR.+## Node colors (one palette, two sections)`src/shared/node-colors.ts` is the palette AND the control boundary — the picker's list and thediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex aab67070c..d03ca239e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -200,6 +200,14 @@ anything else. Board-level fields survive every transform — `pullLinks` is onefrom a background header: only the active SSH project is git-routable. SSH headers observeSource refreshes instead.+- **A port is a node's only if its listener is in that node's process tree.** Dev-server+ discovery (`core/dev-ports.ts`) attributes ports by socket ownership and never connects to+ anything. A new consumer reads the scan, it does not add a probe. A forward+ (`core/remote-ssh/port-forward.ts`) binds `127.0.0.1` only, keeps the same port number or+ refuses with the reason — a different local port is only ever the person's explicit choice — and+ never forwards a port below 1024 unasked. The renderer passes a node and a port, never an address:+ core re-scans and decides the host-side target. See CLAUDE.md → Dev-server ports.+- **A GitHub issue reaches a pane only as a validated reference.** Issue titles and bodies arewritten by strangers on public repositories, and a launch line is typed into a shell. Anythingthat starts or instructs an agent about an issue goes through `@shared/github-issue-ref`:diff --git a/src/core/dev-ports-service.test.ts b/src/core/dev-ports-service.test.tsnew file mode 100644index 000000000..bb163bf3f--- /dev/null+++ b/src/core/dev-ports-service.test.ts@@ -0,0 +1,120 @@+// Routing only: which machine answers a scan, and that a forward is only ever offered for an SSH+// project with a registry behind it. The probe and the registry have their own suites.+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { IPC } from '../shared/ipc'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'+import { startDevPortsService } from './dev-ports-service'+import type { DevPortForwardResult, DevPortsReport } from '../shared/dev-ports'++let platform: FakePlatform+const scan = (q: unknown): Promise<DevPortsReport> => platform.handlers[IPC.devPortsScan](q) as Promise<DevPortsReport>+const fwd = (q: unknown): Promise<DevPortForwardResult> =>+ platform.handlers[IPC.devPortsForward](q) as Promise<DevPortForwardResult>++const REPLY = [+ '##PANES',+ '##SOCK node-terminal',+ 'no server running on /tmp/x',+ '##SOCKRC 1',+ '##SOCK nodeterm-rmt',+ 'nt-web|100|zsh',+ '##SOCKRC 0',+ '##PROCS',+ '100 1 zsh',+ '102 100 node',+ '##LISTEN',+ '##VIA ss',+ 'LISTEN 0 511 127.0.0.1:5173 0.0.0.0:* users:(("node",pid=102,fd=26))',+ '##LISTENRC 0',+ '##END'+].join('\n')++beforeEach(() => {+ resetPlatformForTests()+ platform = fakePlatform()+ initPlatform(platform)+})+afterEach(() => resetPlatformForTests())++describe('startDevPortsService', () => {+ it('a local project is scanned on this machine', async () => {+ const local = vi.fn(async (): Promise<DevPortsReport> => ({ ok: true, nodes: {} }))+ const run = vi.fn()+ startDevPortsService({ local, remote: { isRemoteProject: () => false, run } })+ await scan({ projectId: 'p' })+ expect(local).toHaveBeenCalledTimes(1)+ expect(run).not.toHaveBeenCalled()+ })++ it('an SSH project is scanned on its host — by identity OR by the renderer\'s claim — never locally', async () => {+ const local = vi.fn(async (): Promise<DevPortsReport> => ({ ok: true, nodes: { x: [] } }))+ const run = vi.fn(async () => REPLY)+ startDevPortsService({ local, remote: { isRemoteProject: (id) => id === 'ssh', run } })+ expect((await scan({ projectId: 'ssh' })).nodes.web[0].port).toBe(5173)+ expect((await scan({ projectId: 'other', remote: true })).ok).toBe(true)+ expect(local).not.toHaveBeenCalled()+ })++ it('a dead master is unreachable, and with no runner a remote scope is refused, never local', async () => {+ const local = vi.fn(async (): Promise<DevPortsReport> => ({ ok: true, nodes: {} }))+ startDevPortsService({ local, remote: { isRemoteProject: () => true, run: async () => null } })+ expect((await scan({ projectId: 'ssh' })).reason).toBe('unreachable')+ resetPlatformForTests()+ platform = fakePlatform()+ initPlatform(platform)+ startDevPortsService({ local, remote: { isRemoteProject: () => true } })+ expect((await scan({ projectId: 'ssh' })).reason).toBe('unsupported')+ expect(local).not.toHaveBeenCalled()+ })++ it('coalesces concurrent remote scans of one project', async () => {+ let calls = 0+ const run = vi.fn(async () => {+ calls+++ await new Promise((r) => setTimeout(r, 5))+ return REPLY+ })+ startDevPortsService({ remote: { isRemoteProject: () => true, run } })+ await Promise.all([scan({ projectId: 'ssh' }), scan({ projectId: 'ssh' })])+ expect(calls).toBe(1)+ })++ it('forwarding is refused for a local project, and when no registry is wired', async () => {+ startDevPortsService({+ remote: {+ isRemoteProject: (id) => id === 'ssh',+ run: async () => REPLY,+ forward: { refForProject: () => ({ conn: { host: 'h', user: 'u' }, controlPath: '/c' }), run: async () => ({ code: 0, stdout: '' }) }+ }+ })+ expect(await fwd({ projectId: 'local', nodeId: 'web', port: 5173 })).toMatchObject({ ok: false, reason: 'unsupported' })+ resetPlatformForTests()+ platform = fakePlatform()+ initPlatform(platform)+ startDevPortsService({ remote: { isRemoteProject: () => true, run: async () => REPLY } })+ expect(await fwd({ projectId: 'ssh', nodeId: 'web', port: 5173 })).toMatchObject({ ok: false, reason: 'unsupported' })+ })++ it('an SSH scan reports the forwards the registry holds, and reconciles them', async () => {+ const sshRun = vi.fn(async (_args: string[]) => ({ code: 0, stdout: "" }))+ const held = new Set<number>()+ startDevPortsService({+ remote: {+ isRemoteProject: () => true,+ run: async () => REPLY,+ forward: {+ refForProject: () => ({ conn: { host: 'h', user: 'u' }, controlPath: '/c' }),+ run: async (args) => {+ held.add(5173)+ return sshRun(args)+ },+ localPortBusy: async () => false,+ localPortHeld: async (p) => held.has(p)+ }+ }+ })+ expect(await fwd({ projectId: 'ssh', nodeId: 'web', port: 5173 })).toMatchObject({ ok: true, localPort: 5173 })+ expect((await scan({ projectId: 'ssh' })).forwards).toEqual([{ nodeId: 'web', remotePort: 5173, localPort: 5173 }])+ })+})diff --git a/src/core/dev-ports-service.ts b/src/core/dev-ports-service.tsnew file mode 100644index 000000000..ba54ce2c3--- /dev/null+++ b/src/core/dev-ports-service.ts@@ -0,0 +1,115 @@+// RPC surface for dev-server ports. The shape follows session-memory-service.ts: core owns the+// probe and the parsing, the shell injects the ControlMaster, and the ONE decision made here is+// which machine answers.+//+// Registered by the DESKTOP only. The Server Edition deliberately does not serve it: the browser+// node is an Electron `<webview>`, which a browser tab does not have, and a page the viewer opened+// would load on the VIEWER's machine, where the server's port is not. Its bridge answers+// `unsupported` and the chip is not drawn (docs in CLAUDE.md → Dev-server ports).++import { IPC } from '../shared/ipc'+import { platform } from './platform'+import type {+ DevPortForwardRequest,+ DevPortForwardResult,+ DevPortsQuery,+ DevPortsReport+} from '../shared/dev-ports'+import { collectLocalDevPorts, fetchRemoteDevPorts, type RemoteDevPortsRunner } from './dev-ports'+import {+ defaultLocalPortBusy,+ defaultLocalPortHeld,+ PortForwardRegistry,+ type PortForwardDeps+} from './remote-ssh/port-forward'++export interface DevPortsServiceOptions {+ /** This machine's scan. Injectable for tests. */+ local?: () => Promise<DevPortsReport>+ remote?: {+ /** Identity, not liveness — see `sshScopePredicate` (session-memory-service.ts). */+ isRemoteProject: (projectId: string) => boolean+ run?: RemoteDevPortsRunner+ /** Present ⇒ same-port forwarding is offered for SSH projects. */+ forward?: Pick<PortForwardDeps, 'refForProject' | 'run'> &+ Partial<Pick<PortForwardDeps, 'localPortBusy' | 'localPortHeld'>>+ }+}++const unsupported = (): DevPortsReport => ({ ok: false, reason: 'unsupported', nodes: {} })++export function startDevPortsService(opts: DevPortsServiceOptions = {}): {+ registry: PortForwardRegistry | null+ dispose(): void+} {+ const isRemote = (q: DevPortsQuery): boolean =>+ q.remote === true || (!!q.projectId && !!opts.remote?.isRemoteProject(q.projectId))++ // One in-flight remote scan per project — the renderer's timer, a click's re-scan and a hook+ // event can land together, and each is an exec on somebody else's machine. Never a cache.+ const inFlight = new Map<string, Promise<DevPortsReport>>()+ const scanRemote = (projectId: string): Promise<DevPortsReport> => {+ const run = opts.remote?.run+ if (!run) return Promise.resolve(unsupported())+ const pending = inFlight.get(projectId)+ if (pending) return pending+ const p = fetchRemoteDevPorts(projectId, run).finally(() => inFlight.delete(projectId))+ inFlight.set(projectId, p)+ return p+ }++ const fwd = opts.remote?.forward+ const registry = fwd+ ? new PortForwardRegistry({+ refForProject: fwd.refForProject,+ run: fwd.run,+ scan: scanRemote,+ localPortBusy: fwd.localPortBusy ?? defaultLocalPortBusy,+ localPortHeld: fwd.localPortHeld ?? defaultLocalPortHeld+ })+ : null++ platform().handle(IPC.devPortsScan, async (q: DevPortsQuery = {}): Promise<DevPortsReport> => {+ const query = q && typeof q === 'object' ? q : {}+ if (isRemote(query)) {+ // Never fall back to this machine: its ports would be published under the host's name.+ if (!query.projectId || typeof query.projectId !== 'string') return unsupported()+ const report = await scanRemote(query.projectId)+ if (!registry) return report+ await registry.reconcile(query.projectId, report)+ return { ...report, forwards: registry.list(query.projectId) }+ }+ return (opts.local ?? (() => collectLocalDevPorts()))()+ })++ platform().handle(+ IPC.devPortsForward,+ async (req: DevPortForwardRequest): Promise<DevPortForwardResult> => {+ if (!registry || !req || typeof req !== 'object' || typeof req.projectId !== 'string') {+ return { ok: false, reason: 'unsupported', message: 'Port forwarding is not available here.' }+ }+ // Forwarding only exists for a project that is somebody else's machine. A local project's+ // port is already on this machine — there is nothing to forward.+ if (!opts.remote?.isRemoteProject(req.projectId)) {+ return { ok: false, reason: 'unsupported', message: 'Only an SSH project needs its ports forwarded.' }+ }+ return registry.forward({+ projectId: req.projectId,+ nodeId: String(req.nodeId ?? ''),+ port: Number(req.port),+ ...(req.localPort !== undefined ? { localPort: Number(req.localPort) } : {}),+ ...(req.allowPrivileged === true ? { allowPrivileged: true } : {})+ })+ }+ )++ platform().handle(+ IPC.devPortsUnforward,+ async (req: { projectId: string; localPort: number }): Promise<boolean> => {+ if (!registry || !req || typeof req.projectId !== 'string') return false+ return registry.unforward(req.projectId, Number(req.localPort))+ }+ )++ return { registry, dispose: (): void => {} }+}diff --git a/src/core/dev-ports.realsh.test.ts b/src/core/dev-ports.realsh.test.tsnew file mode 100644index 000000000..06e1ca425--- /dev/null+++ b/src/core/dev-ports.realsh.test.ts@@ -0,0 +1,149 @@+// The dev-ports probe is generated shell no compiler checks, so it is executed here for real:+// 1. under /bin/sh against a FAKE host tree (stub tmux / ps / ss / lsof and a fake /proc), one+// case per listener-tool branch — the branch a real host takes depends on what it has installed;+// 2. end to end on this machine: a real tmux session (in the suite's private TMUX_TMPDIR, on a+// socket name nothing else uses) running a real TCP listener two processes below its pane,+// read back through real `ps` and real `ss`/`lsof`.+import { afterAll, describe, expect, it } from 'vitest'+import { execFile, execFileSync } from 'child_process'+import { promisify } from 'util'+import fs from 'fs'+import path from 'path'+import { devPortsProbeCommand, parseDevPortsProbe } from './dev-ports'+import { testTmpDir } from './test-tmp'++const run = promisify(execFile)+const SOCKS = ['node-terminal', 'nodeterm-rmt']++function fakeHost(bins: Record<string, string>): string {+ const dir = testTmpDir('devports-bin-')+ for (const [name, body] of Object.entries(bins)) {+ fs.writeFileSync(path.join(dir, name), `#!/bin/sh\n${body}\n`, { mode: 0o755 })+ }+ return dir+}+const TMUX = `case "$2" in+ node-terminal) printf 'nt-web|100|zsh\\nnt-idle|300|zsh\\n'; exit 0;;+ *) echo "no server running on /tmp/tmux-1000/$2" >&2; exit 1;;+esac`+const PS = `printf ' 1 0 init\\n 100 1 zsh\\n 101 100 npm\\n 102 101 node\\n 300 1 zsh\\n 500 1 postgres\\n'`++async function probe(binDir: string, procRoot = '/nonexistent-proc'): Promise<string> {+ // PATH is ONLY the fake dir: the script appends its own dirs, none of which hold ss/lsof here.+ const { stdout } = await run('/bin/sh', ['-c', devPortsProbeCommand({ sockets: SOCKS, procRoot })], {+ env: { PATH: binDir, HOME: '/nonexistent' }+ })+ return stdout+}++const realSsOnAppendedPath = ['/usr/sbin/ss', '/sbin/ss', '/usr/local/bin/ss', '/opt/homebrew/bin/ss'].some((p) =>+ fs.existsSync(p)+)+const realLsofOnAppendedPath = ['/usr/sbin/lsof', '/sbin/lsof', '/usr/local/bin/lsof', '/opt/homebrew/bin/lsof'].some(+ (p) => fs.existsSync(p)+)++describe('dev-ports probe under a real /bin/sh, fake host', () => {+ it('ss branch: the vite two levels below the pane is the node\'s; postgres is nobody\'s', async () => {+ const bin = fakeHost({+ tmux: TMUX,+ ps: PS,+ ss: `cat <<'EOF'+State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess+LISTEN 0 511 127.0.0.1:5173 0.0.0.0:* users:(("node",pid=102,fd=26))+LISTEN 0 511 [::1]:5173 [::]:* users:(("node",pid=102,fd=27))+LISTEN 0 244 0.0.0.0:5432 0.0.0.0:* users:(("postgres",pid=500,fd=7))+EOF`,+ cat: 'exec /bin/cat "$@"'+ })+ const r = parseDevPortsProbe(await probe(bin), SOCKS)+ expect(r).toEqual({+ ok: true,+ nodes: { web: [{ port: 5173, addresses: ['127.0.0.1', '::1'], command: 'node', ephemeral: false }] }+ })+ })++ it.skipIf(realSsOnAppendedPath)('lsof branch (macOS, or Linux without ss); lsof exit 1 = nothing listening', async () => {+ const bin = fakeHost({ tmux: TMUX, ps: PS, lsof: `printf 'p102\\ncnode\\nf21\\nn*:3000\\n'` })+ const r = parseDevPortsProbe(await probe(bin), SOCKS)+ expect(r.nodes).toEqual({ web: [{ port: 3000, addresses: ['*'], command: 'node', ephemeral: false }] })+ const none = fakeHost({ tmux: TMUX, ps: PS, lsof: 'exit 1' })+ expect(parseDevPortsProbe(await probe(none), SOCKS)).toEqual({ ok: true, nodes: {} })+ })++ it.skipIf(realSsOnAppendedPath || realLsofOnAppendedPath)('/proc branch joins the socket inode to the pid', async () => {+ const proc = testTmpDir('devports-proc-')+ fs.mkdirSync(path.join(proc, 'net'))+ fs.writeFileSync(+ path.join(proc, 'net/tcp'),+ ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n' ++ ' 0: 0100007F:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 4242 1\n'+ )+ for (const pid of ['102', '500']) fs.mkdirSync(path.join(proc, pid, 'fd'), { recursive: true })+ fs.symlinkSync('socket:[4242]', path.join(proc, '102/fd/26'))+ fs.symlinkSync('/dev/null', path.join(proc, '500/fd/0'))+ const bin = fakeHost({ tmux: TMUX, ps: PS, cat: 'exec /bin/cat "$@"', ls: 'exec /bin/ls "$@"' })+ const r = parseDevPortsProbe(await probe(bin, proc), SOCKS)+ expect(r).toEqual({ ok: true, nodes: { web: [{ port: 8080, addresses: ['127.0.0.1'], command: 'node', ephemeral: false }] } })+ })++ it.skipIf(realSsOnAppendedPath || realLsofOnAppendedPath)('no tool at all says so — never "no ports"', async () => {+ const bin = fakeHost({ tmux: TMUX, ps: PS })+ expect(parseDevPortsProbe(await probe(bin), SOCKS)).toEqual({ ok: false, reason: 'no-listener-tool', nodes: {} })+ })++ it('a broken tmux on every socket is unreachable, not empty', async () => {+ const bin = fakeHost({ tmux: 'echo "tmux: cannot open shared object file" >&2; exit 127', ps: PS, ss: 'exit 0' })+ expect(parseDevPortsProbe(await probe(bin), SOCKS).reason).toBe('unreachable')+ })+})++// ---- real end to end -------------------------------------------------------------------------++const hasTool = (t: string): boolean => {+ try {+ execFileSync('/bin/sh', ['-c', `command -v ${t}`], { stdio: 'ignore' })+ return true+ } catch {+ return false+ }+}+const canRunReal = process.platform !== 'win32' && hasTool('tmux') && (hasTool('ss') || hasTool('lsof'))+const SOCKET = `ntports-${process.pid}-${Math.random().toString(36).slice(2, 8)}`++describe.skipIf(!canRunReal)('dev-ports probe end to end (real tmux, real listener)', () => {+ afterAll(() => {+ // Our own socket only — never a kill-server on a shared name.+ try {+ execFileSync('tmux', ['-L', SOCKET, 'kill-server'], { stdio: 'ignore' })+ } catch {+ /* already gone */+ }+ })++ it('finds a listener two processes below the pane and attributes it to the node', async () => {+ const dir = testTmpDir('devports-real-')+ const portFile = path.join(dir, 'port')+ const server = path.join(dir, 'server.js')+ fs.writeFileSync(+ server,+ `const s=require('net').createServer();s.listen(0,'127.0.0.1',()=>require('fs').writeFileSync(${JSON.stringify(portFile)},String(s.address().port)))`+ )+ // sh → sh → node: the listener is a grandchild of the pane's process.+ execFileSync('tmux', [+ '-L', SOCKET, '-f', '/dev/null', 'new-session', '-d', '-s', 'nt-realnode',+ `sh -c 'sh -c "exec ${process.execPath} ${server}"; sleep 60'`+ ])+ let port = ''+ for (let i = 0; i < 100 && !port; i++) {+ await new Promise((r) => setTimeout(r, 50))+ port = fs.existsSync(portFile) ? fs.readFileSync(portFile, 'utf8') : ''+ }+ expect(port).not.toBe('')+ const { stdout } = await run('/bin/sh', ['-c', devPortsProbeCommand({ sockets: [SOCKET] })])+ const r = parseDevPortsProbe(stdout, [SOCKET])+ expect(r.ok).toBe(true)+ expect(r.nodes.realnode?.map((p) => p.port)).toEqual([Number(port)])+ expect(r.nodes.realnode?.[0].addresses).toEqual(['127.0.0.1'])+ }, 20_000)+})diff --git a/src/core/dev-ports.test.ts b/src/core/dev-ports.test.tsnew file mode 100644index 000000000..5a30bae23--- /dev/null+++ b/src/core/dev-ports.test.ts@@ -0,0 +1,230 @@+import { describe, expect, it } from 'vitest'+import {+ assembleDevPorts,+ collectLocalDevPorts,+ decodeProcAddress,+ devPortsProbeCommand,+ fetchRemoteDevPorts,+ forwardTarget,+ parseDevPortsProbe,+ parseLsofListeners,+ parseProcFdSockets,+ parseProcNetTcp,+ parseProcRows,+ parseSsListeners,+ splitHostPort+} from './dev-ports'++// Captured from a real Ubuntu 24.04 host (iproute2 6.1) — note the glued `PortProcess` header.+const SS_REAL = `State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess+LISTEN 0 511 127.0.0.1:5173 0.0.0.0:* users:(("node",pid=210,fd=26))+LISTEN 0 511 [::1]:5173 [::]:* users:(("node",pid=210,fd=27))+LISTEN 0 4096 0.0.0.0:6543 0.0.0.0:* users:(("docker-proxy",pid=7799,fd=8))+LISTEN 0 128 *:3000 *:* users:(("ruby",pid=300,fd=9),("ruby",pid=301,fd=9))+LISTEN 0 128 [::]:8080 [::]:*+LISTEN 0 128 127.0.0.53%lo:53 0.0.0.0:*`++describe('splitHostPort', () => {+ it('reads every spelling ss and lsof print', () => {+ expect(splitHostPort('127.0.0.1:5173')).toEqual({ address: '127.0.0.1', port: 5173 })+ expect(splitHostPort('[::1]:5173')).toEqual({ address: '::1', port: 5173 })+ expect(splitHostPort('[::]:80')).toEqual({ address: '::', port: 80 })+ expect(splitHostPort(':::8080')).toEqual({ address: '::', port: 8080 })+ expect(splitHostPort('*:3000')).toEqual({ address: '*', port: 3000 })+ expect(splitHostPort('127.0.0.53%lo:53')).toEqual({ address: '127.0.0.53', port: 53 })+ })+ it('refuses a peer column and out-of-range ports', () => {+ expect(splitHostPort('0.0.0.0:*')).toBeNull()+ expect(splitHostPort('1.2.3.4:0')).toBeNull()+ expect(splitHostPort('1.2.3.4:70000')).toBeNull()+ expect(splitHostPort('LISTEN')).toBeNull()+ })+})++describe('parseSsListeners', () => {+ it('takes the local address, every owning pid and the command', () => {+ const l = parseSsListeners(SS_REAL)+ expect(l[0]).toEqual({ pids: [210], address: '127.0.0.1', port: 5173, command: 'node' })+ expect(l[1]).toEqual({ pids: [210], address: '::1', port: 5173, command: 'node' })+ expect(l[3]).toEqual({ pids: [300, 301], address: '*', port: 3000, command: 'ruby' })+ // Another user's socket carries no process column: listed, but owned by nobody we know.+ expect(l[4]).toEqual({ pids: [], address: '::', port: 8080, command: '' })+ expect(l).toHaveLength(6)+ })+})++describe('parseLsofListeners', () => {+ it('groups n-fields under the preceding p/c', () => {+ const out = parseLsofListeners('p210\ncnode\nf26\nn127.0.0.1:5173\nf27\nn[::1]:5173\np300\ncruby\nn*:3000\n')+ expect(out).toEqual([+ { pids: [210], address: '127.0.0.1', port: 5173, command: 'node' },+ { pids: [210], address: '::1', port: 5173, command: 'node' },+ { pids: [300], address: '*', port: 3000, command: 'ruby' }+ ])+ })+})++describe('/proc parsing', () => {+ it('decodes little-endian IPv4 and IPv6 words', () => {+ expect(decodeProcAddress('0100007F')).toBe('127.0.0.1')+ expect(decodeProcAddress('00000000')).toBe('0.0.0.0')+ expect(decodeProcAddress('00000000000000000000000001000000')).toBe('::1')+ expect(decodeProcAddress('00000000000000000000000000000000')).toBe('::')+ expect(decodeProcAddress('0000000000000000FFFF00000100007F')).toBe('127.0.0.1')+ expect(decodeProcAddress('zz')).toBeNull()+ })+ it('keeps only LISTEN rows, keyed by inode', () => {+ const tcp = ` sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode+ 0: 0100007F:1435 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 4242 1+ 1: 0100007F:1435 0100007F:C001 01 00000000:00000000 00:00000000 00000000 1000 0 9999 1+ 0: 00000000000000000000000001000000:1F90 00000000000000000000000000000000:0000 0A 0 0 0 1000 0 777 1`+ const m = parseProcNetTcp(tcp)+ expect([...m.entries()]).toEqual([+ ['4242', { address: '127.0.0.1', port: 5173 }],+ ['777', { address: '::1', port: 8080 }]+ ])+ })+ it('maps socket inodes to pids from ls -l over several fd dirs', () => {+ const ls = `/proc/210/fd:+total 0+lrwx------ 1 u u 64 Sep 30 12:00 0 -> /dev/pts/1+lrwx------ 1 u u 64 Sep 30 12:00 26 -> socket:[4242]++/proc/211/fd:+lrwx------ 1 u u 64 Sep 30 12:00 3 -> socket:[4242]+lrwx------ 1 u u 64 Sep 30 12:00 4 -> socket:[777]`+ const m = parseProcFdSockets(ls)+ expect(m.get('4242')).toEqual([210, 211])+ expect(m.get('777')).toEqual([211])+ })+ it('parses ps rows and keeps the command basename', () => {+ expect(parseProcRows(' 1 0 /sbin/launchd\n 42 1 node\n x\n')).toEqual([+ { pid: 1, ppid: 0, command: 'launchd' },+ { pid: 42, ppid: 1, command: 'node' }+ ])+ })+})++describe('assembleDevPorts — ownership by process tree', () => {+ const panes = [+ { session: 'nt-a', panePid: 100, command: 'zsh' },+ { session: 'nt-b', panePid: 200, command: 'zsh' },+ { session: 'someone-else', panePid: 900, command: 'bash' }+ ]+ const procs = [+ { pid: 1, ppid: 0, command: 'init' },+ { pid: 100, ppid: 1, command: 'zsh' },+ { pid: 101, ppid: 100, command: 'npm' },+ { pid: 102, ppid: 101, command: 'node' }, // vite, two levels below the pane+ { pid: 200, ppid: 1, command: 'zsh' },+ { pid: 900, ppid: 1, command: 'bash' },+ { pid: 901, ppid: 900, command: 'python3' },+ { pid: 500, ppid: 1, command: 'postgres' }+ ]+ it('attributes a descendant listener to its node, merges families, sorts', () => {+ const out = assembleDevPorts(panes, procs, [+ { pids: [102], address: '::1', port: 5173, command: '' },+ { pids: [102], address: '127.0.0.1', port: 5173, command: 'node' },+ { pids: [102], address: '127.0.0.1', port: 4000, command: 'node' },+ { pids: [102], address: '127.0.0.1', port: 40001, command: 'node' }+ ])+ expect(out).toEqual({+ a: [+ { port: 4000, addresses: ['127.0.0.1'], command: 'node', ephemeral: false },+ { port: 5173, addresses: ['::1', '127.0.0.1'], command: 'node', ephemeral: false },+ { port: 40001, addresses: ['127.0.0.1'], command: 'node', ephemeral: true }+ ]+ })+ })+ it('never reports a port owned outside every nt- pane tree', () => {+ const out = assembleDevPorts(panes, procs, [+ { pids: [500], address: '0.0.0.0', port: 5432, command: 'postgres' },+ { pids: [901], address: '0.0.0.0', port: 8000, command: 'python3' },+ { pids: [], address: '::', port: 8080, command: '' }+ ])+ expect(out).toEqual({})+ })+ it('takes the command from ps when the listener tool did not name it', () => {+ const out = assembleDevPorts(panes, procs, [{ pids: [102], address: '127.0.0.1', port: 3000, command: '' }])+ expect(out.a[0].command).toBe('node')+ })+ it('survives a cyclic ppid chain', () => {+ const cyclic = [+ { pid: 100, ppid: 101, command: 'zsh' },+ { pid: 101, ppid: 100, command: 'node' }+ ]+ const out = assembleDevPorts([{ session: 'nt-a', panePid: 100, command: 'zsh' }], cyclic, [+ { pids: [101], address: '127.0.0.1', port: 3000, command: 'node' }+ ])+ expect(out.a.map((p) => p.port)).toEqual([3000])+ })+})++const probeOut = (listen: string, panes = "##SOCK node-terminal\nnt-a|100|zsh\n##SOCKRC 0\n##SOCK nodeterm-rmt\nno server running on /tmp/x\n##SOCKRC 1"): string =>+ ['##PANES', panes, '##PROCS', ' 100 1 zsh', ' 102 100 node', '##LISTEN', listen, '##END', ''].join('\n')++describe('parseDevPortsProbe', () => {+ it('reads an ss answer', () => {+ const r = parseDevPortsProbe(probeOut('##VIA ss\n' + SS_REAL.replace(/pid=210/g, 'pid=102') + '\n##LISTENRC 0'))+ expect(r.ok).toBe(true)+ expect(r.nodes.a.map((p) => p.port)).toEqual([5173])+ })+ it('reads an lsof answer, and lsof exit 1 with no output is "no listeners"', () => {+ expect(parseDevPortsProbe(probeOut('##VIA lsof\np102\ncnode\nn*:3000\n##LISTENRC 0')).nodes.a[0].port).toBe(3000)+ expect(parseDevPortsProbe(probeOut('##VIA lsof\n##LISTENRC 1'))).toEqual({ ok: true, nodes: {} })+ })+ it('reads the /proc answer', () => {+ const r = parseDevPortsProbe(+ probeOut(+ '##VIA proc\n 0: 0100007F:1435 00000000:0000 0A 0 0 0 1000 0 4242 1\n##FD\n/proc/102/fd:\nl 1 -> socket:[4242]\n/proc/1/fd:\n##LISTENRC 0'+ )+ )+ expect(r).toEqual({ ok: true, nodes: { a: [{ port: 5173, addresses: ['127.0.0.1'], command: 'node', ephemeral: false }] } })+ })+ it('never turns a failure into "no ports"', () => {+ expect(parseDevPortsProbe('').ok).toBe(false)+ // cut short: no ##END+ expect(parseDevPortsProbe(probeOut('##VIA ss\n##LISTENRC 0').replace('##END', '')).reason).toBe('unreachable')+ // no socket answered (broken tmux client on both)+ const broken = '##SOCK node-terminal\ntmux: error while loading shared libraries\n##SOCKRC 127\n##SOCK nodeterm-rmt\ntmux: error\n##SOCKRC 127'+ expect(parseDevPortsProbe(probeOut('##VIA ss\n##LISTENRC 0', broken)).reason).toBe('unreachable')+ // ss failed+ expect(parseDevPortsProbe(probeOut('##VIA ss\n##LISTENRC 1')).reason).toBe('unreachable')+ // lsof failed WITH output+ expect(parseDevPortsProbe(probeOut('##VIA lsof\nlsof: WARNING\n##LISTENRC 1')).reason).toBe('unreachable')+ // no tool+ expect(parseDevPortsProbe(probeOut('##VIA none'))).toEqual({ ok: false, reason: 'no-listener-tool', nodes: {} })+ // an rc file echoing a marker ahead of ours+ expect(parseDevPortsProbe('##END\n' + probeOut('##VIA ss\n##LISTENRC 0').replace(/##END\n$/, '')).ok).toBe(false)+ })+})++describe('forwardTarget', () => {+ it('follows the bind', () => {+ expect(forwardTarget(['::1', '127.0.0.1'])).toBe('127.0.0.1')+ expect(forwardTarget(['*'])).toBe('127.0.0.1')+ expect(forwardTarget(['0.0.0.0'])).toBe('127.0.0.1')+ expect(forwardTarget(['::1'])).toBe('::1')+ expect(forwardTarget(['::'])).toBe('::1')+ expect(forwardTarget(['10.0.0.5'])).toBe('10.0.0.5')+ expect(forwardTarget(['fe80::1'])).toBe('fe80::1')+ })+ it('refuses anything that is not an IP literal', () => {+ expect(forwardTarget(['localhost'])).toBeNull()+ expect(forwardTarget(['-oProxyCommand=x'])).toBeNull()+ expect(forwardTarget([])).toBeNull()+ })+})++describe('runners', () => {+ it('local: Windows is unsupported, a throwing exec is unreachable', async () => {+ expect(await collectLocalDevPorts(async () => '', 'win32')).toEqual({ ok: false, reason: 'unsupported', nodes: {} })+ expect((await collectLocalDevPorts(async () => { throw new Error('x') }, 'linux')).reason).toBe('unreachable')+ })+ it('remote: a null (dead master) is unreachable, never empty', async () => {+ expect(await fetchRemoteDevPorts('p', async () => null)).toEqual({ ok: false, reason: 'unreachable', nodes: {} })+ let seen = ''+ await fetchRemoteDevPorts('p', async (_id, cmd) => ((seen = cmd), null))+ expect(seen).toBe(devPortsProbeCommand())+ })+})diff --git a/src/core/dev-ports.ts b/src/core/dev-ports.tsnew file mode 100644index 000000000..d654c7607--- /dev/null+++ b/src/core/dev-ports.ts@@ -0,0 +1,401 @@+// Dev-server port discovery: which TCP ports each node's session is LISTENING on.+//+// Ownership, never probing. A port is attributed to a node only when its listening socket belongs+// to a process inside that node's tmux pane tree (the same tree session memory rolls up). Nothing+// is ever connected to, and another user's or another program's port is never reported.+//+// ONE generated POSIX sh script answers the whole question in one round trip — the panes of every+// nodeterm tmux socket, the process table, and the listening sockets with their owning pids — and+// the SAME script runs for a local project (`/bin/sh -c`) and over an SSH project's ControlMaster.+// One script, one parser: a local leg written separately would drift from the remote one, which is+// what this repo's session-memory ledger records happening three times.+//+// Which listener tool answers, in order:+// - `ss -ltnp` (Linux, iproute2): only listeners, with `users:(("node",pid=123,fd=21))` for+// sockets of processes we own — a few lines of output.+// - `lsof -nP -iTCP -sTCP:LISTEN -Fpcn` (macOS, and Linux hosts without ss). lsof exits 1 when+// nothing matched, which is an ANSWER here, not a failure.+// - `/proc/net/tcp{,6}` + `ls -l /proc/<pid>/fd` (a Linux host with neither): the socket inode+// joins the two. One `ls` process, not one `readlink` per descriptor.++import { execFile } from 'child_process'+import { promisify } from 'util'+import { DEV_PORT_EPHEMERAL_MIN, type DevPort, type DevPortsReport } from '../shared/dev-ports'+import { REMOTE_TMUX_PATH_DIRS } from '../shared/ssh'+import { indexProcesses, type PaneRef } from './session-memory'+import { fencedListPanesCommand, parseFencedPanes } from './session-memory-remote'+import { TMUX_SOCKET } from './tmux-naming'+import { RMT_TMUX_SOCKET } from './remote-ssh/control-master'++const runAsync = promisify(execFile)++const PANES = '##PANES'+const PROCS = '##PROCS'+const LISTEN = '##LISTEN'+const FD = '##FD'+const END = '##END'++/** The sockets nodeterm's sessions live on — a local project's (`node-terminal`) and an SSH+ * project's on its host (`nodeterm-rmt`). Both are listed on either machine, like session memory,+ * because a host can run a nodeterm of its own. */+export const DEV_PORT_SOCKETS: readonly string[] = [TMUX_SOCKET, RMT_TMUX_SOCKET]++export interface DevPortsProbeOptions {+ /** tmux sockets to list. Tests pass a private one; production uses DEV_PORT_SOCKETS. */+ sockets?: readonly string[]+ /** Root of the proc filesystem for the last-resort branch. Tests point it at a fake tree. */+ procRoot?: string+}++/**+ * The generated script. Load-bearing details:+ * - Every marker is QUOTED: an unquoted `#` at the start of a word begins a comment in POSIX sh,+ * so `echo ##PANES` prints an empty line (measured under dash in session-memory-remote.ts).+ * - `##END` is printed last and unconditionally; a missing one means the stream was cut short.+ * - PATH is APPENDED with the tmux dirs (Homebrew — issue #449) and `/usr/sbin:/sbin`, where `ss`+ * and `lsof` live on some distributions and macOS, and which an ssh exec channel's non-login+ * PATH often lacks. Append, never prepend: the host's own binaries win.+ * - `ps -eo pid=,ppid=,comm=` is POSIX (`=` suppresses the header) and works on macOS.+ */+export function devPortsProbeCommand(opts: DevPortsProbeOptions = {}): string {+ const sockets = opts.sockets ?? DEV_PORT_SOCKETS+ const proc = opts.procRoot ?? '/proc'+ return [+ `PATH="$PATH:${REMOTE_TMUX_PATH_DIRS}:/usr/sbin:/sbin"`,+ `echo '${PANES}'`,+ ...sockets.map(fencedListPanesCommand),+ `echo '${PROCS}'`,+ `ps -eo pid=,ppid=,comm= 2>/dev/null`,+ `echo '${LISTEN}'`,+ `if command -v ss >/dev/null 2>&1; then`,+ ` echo '##VIA ss'`,+ ` ss -ltnp 2>/dev/null`,+ ` echo "##LISTENRC $?"`,+ `elif command -v lsof >/dev/null 2>&1; then`,+ ` echo '##VIA lsof'`,+ ` lsof -nP -iTCP -sTCP:LISTEN -Fpcn 2>/dev/null`,+ ` echo "##LISTENRC $?"`,+ `elif [ -r '${proc}/net/tcp' ]; then`,+ ` echo '##VIA proc'`,+ ` cat '${proc}/net/tcp' '${proc}/net/tcp6' 2>/dev/null`,+ ` echo '${FD}'`,+ ` ls -l '${proc}'/[0-9]*/fd 2>/dev/null`,+ ` echo '##LISTENRC 0'`,+ `else`,+ ` echo '##VIA none'`,+ `fi`,+ `echo '${END}'`+ ].join('\n')+}++/** One listening socket and the pid(s) that hold it. */+export interface Listener {+ pids: number[]+ address: string+ port: number+ command: string+}++export interface ProcRow {+ pid: number+ ppid: number+ command: string+}++/** `ps -eo pid=,ppid=,comm=`. `comm` is a full path on macOS; only its basename is kept. */+export function parseProcRows(text: string): ProcRow[] {+ const out: ProcRow[] = []+ for (const line of text.split('\n')) {+ const m = /^\s*(\d+)\s+(\d+)\s*(.*)$/.exec(line)+ if (!m) continue+ const command = m[3].trim()+ out.push({ pid: Number(m[1]), ppid: Number(m[2]), command: command.split('/').pop() ?? command })+ }+ return out+}++/**+ * Split `host:port` as ss and lsof print it: `127.0.0.1:5173`, `*:3000`, `[::1]:5173`, `[::]:80`,+ * the old ss spelling `:::8080`, and a scoped `127.0.0.53%lo:53`. Returns null for anything whose+ * port is not a plain number (a peer column's `*`).+ */+export function splitHostPort(token: string): { address: string; port: number } | null {+ const i = token.lastIndexOf(':')+ if (i < 0) return null+ const portText = token.slice(i + 1)+ if (!/^\d{1,5}$/.test(portText)) return null+ const port = Number(portText)+ if (port < 1 || port > 65535) return null+ let address = token.slice(0, i)+ if (address.startsWith('[') && address.endsWith(']')) address = address.slice(1, -1)+ const pct = address.indexOf('%')+ if (pct >= 0) address = address.slice(0, pct)+ if (address === '::' || address === '') address = '::'+ return { address, port }+}++/** `ss -ltnp`. The local address is the first `addr:port` token with a numeric port — the peer+ * column (`0.0.0.0:*`) never has one, which also makes this indifferent to whether the installed+ * ss prints a State column. */+export function parseSsListeners(text: string): Listener[] {+ const out: Listener[] = []+ for (const line of text.split('\n')) {+ let hp: { address: string; port: number } | null = null+ for (const tok of line.trim().split(/\s+/)) {+ hp = splitHostPort(tok)+ if (hp) break+ }+ if (!hp) continue+ const pids = [...line.matchAll(/pid=(\d+)/g)].map((m) => Number(m[1]))+ const command = /\(\("([^"]*)",pid=/.exec(line)?.[1] ?? ''+ out.push({ pids, ...hp, command })+ }+ return out+}++/** `lsof -Fpcn`: `p<pid>` opens a process, `c<cmd>` names it, each `n<addr:port>` is one socket. */+export function parseLsofListeners(text: string): Listener[] {+ const out: Listener[] = []+ let pid = 0+ let command = ''+ for (const line of text.split('\n')) {+ const tag = line[0]+ const val = line.slice(1).trim()+ if (tag === 'p') {+ pid = Number(val) || 0+ command = ''+ } else if (tag === 'c') {+ command = val+ } else if (tag === 'n' && pid > 0) {+ // An established connection prints `a->b`; LISTEN never does, but be explicit.+ if (val.includes('->')) continue+ const hp = splitHostPort(val)+ if (hp) out.push({ pids: [pid], ...hp, command })+ }+ }+ return out+}++/** Decode a `/proc/net/tcp{,6}` address word: each 32-bit group is in host (little-endian) order. */+export function decodeProcAddress(hex: string): string | null {+ const le = (h: string): number[] => [h.slice(6, 8), h.slice(4, 6), h.slice(2, 4), h.slice(0, 2)].map((b) => parseInt(b, 16))+ if (/^[0-9A-Fa-f]{8}$/.test(hex)) return le(hex).join('.')+ if (!/^[0-9A-Fa-f]{32}$/.test(hex)) return null+ const bytes: number[] = []+ for (let g = 0; g < 4; g++) bytes.push(...le(hex.slice(g * 8, g * 8 + 8)))+ // IPv4-mapped (::ffff:a.b.c.d) is reported as its IPv4 address.+ if (bytes.slice(0, 10).every((b) => b === 0) && bytes[10] === 0xff && bytes[11] === 0xff) {+ return bytes.slice(12).join('.')+ }+ const words: string[] = []+ for (let i = 0; i < 16; i += 2) words.push(((bytes[i] << 8) | bytes[i + 1]).toString(16))+ return compressIpv6(words)+}++function compressIpv6(words: string[]): string {+ // Longest run (≥ 2) of zero words becomes `::`.+ let best = -1+ let bestLen = 0+ for (let i = 0; i < words.length; ) {+ if (words[i] !== '0') {+ i+++ continue+ }+ let j = i+ while (j < words.length && words[j] === '0') j+++ if (j - i > bestLen && j - i >= 2) {+ best = i+ bestLen = j - i+ }+ i = j+ }+ if (best < 0) return words.join(':')+ return `${words.slice(0, best).join(':')}::${words.slice(best + bestLen).join(':')}`+}++/** LISTEN rows (`st == 0A`) of `/proc/net/tcp` + `tcp6`, keyed by socket inode. */+export function parseProcNetTcp(text: string): Map<string, { address: string; port: number }> {+ const out = new Map<string, { address: string; port: number }>()+ for (const line of text.split('\n')) {+ const f = line.trim().split(/\s+/)+ if (f.length < 10 || f[3] !== '0A') continue+ const [addrHex, portHex] = f[1].split(':')+ const address = decodeProcAddress(addrHex ?? '')+ const port = parseInt(portHex ?? '', 16)+ const inode = f[9]+ if (address === null || !Number.isInteger(port) || port < 1 || !/^\d+$/.test(inode) || inode === '0') continue+ out.set(inode, { address, port })+ }+ return out+}++/** `ls -l <proc>/[0-9]*\/fd`: directory headers name the pid, `-> socket:[N]` names the inode. */+export function parseProcFdSockets(text: string): Map<string, number[]> {+ const out = new Map<string, number[]>()+ let pid = 0+ for (const line of text.split('\n')) {+ const head = /\/(\d+)\/fd:\s*$/.exec(line)+ if (head) {+ pid = Number(head[1])+ continue+ }+ const sock = /->\s*socket:\[(\d+)\]/.exec(line)+ if (!sock || pid <= 0) continue+ const list = out.get(sock[1])+ if (list) {+ if (!list.includes(pid)) list.push(pid)+ } else out.set(sock[1], [pid])+ }+ return out+}++/** `node id → ports`, from the three facts. Pure. */+export function assembleDevPorts(+ panes: readonly PaneRef[],+ procs: readonly ProcRow[],+ listeners: readonly Listener[]+): Record<string, DevPort[]> {+ const { kids } = indexProcesses(procs.map((p) => ({ pid: p.pid, ppid: p.ppid, rssKb: 0 })))+ const commandOf = new Map(procs.map((p) => [p.pid, p.command]))+ // pid → owning node. Every pane of a session counts (a session can carry a lead pane), and a+ // `seen` set guards the walk against a cyclic ppid chain captured mid-recycle.+ const owner = new Map<number, string>()+ for (const pane of panes) {+ if (!pane.session.startsWith('nt-')) continue+ const nodeId = pane.session.slice('nt-'.length)+ if (!nodeId) continue+ const stack = [pane.panePid]+ while (stack.length > 0) {+ const pid = stack.pop() as number+ if (owner.has(pid)) continue+ owner.set(pid, nodeId)+ for (const k of kids.get(pid) ?? []) stack.push(k)+ }+ }+ const byNode = new Map<string, Map<number, DevPort>>()+ for (const l of listeners) {+ const pid = l.pids.find((p) => owner.has(p))+ if (pid === undefined) continue+ const nodeId = owner.get(pid) as string+ let ports = byNode.get(nodeId)+ if (!ports) byNode.set(nodeId, (ports = new Map()))+ const existing = ports.get(l.port)+ if (existing) {+ if (!existing.addresses.includes(l.address)) existing.addresses.push(l.address)+ continue+ }+ ports.set(l.port, {+ port: l.port,+ addresses: [l.address],+ command: l.command || commandOf.get(pid) || '',+ ephemeral: l.port >= DEV_PORT_EPHEMERAL_MIN+ })+ }+ const out: Record<string, DevPort[]> = {}+ for (const [nodeId, ports] of byNode) out[nodeId] = [...ports.values()].sort((a, b) => a.port - b.port)+ return out+}++const fail = (reason: DevPortsReport['reason']): DevPortsReport => ({ ok: false, reason, nodes: {} })++/**+ * Parse the whole probe. Every failure reads as "could not look", never as "no ports":+ * - a missing or out-of-order marker (a cut stream, an rc file that echoes into the channel);+ * - an empty process table (a host always has processes, so `ps` never ran);+ * - no tmux socket answered (see `parseFencedPanes` — "no server running" IS an answer);+ * - a listener tool that failed (`ss` non-zero; `lsof` non-zero WITH output).+ */+export function parseDevPortsProbe(stdout: string, sockets: readonly string[] = DEV_PORT_SOCKETS): DevPortsReport {+ const lines = stdout.split('\n').map((l) => l.replace(/\r$/, ''))+ const iPanes = lines.indexOf(PANES)+ const iProcs = lines.indexOf(PROCS)+ const iListen = lines.indexOf(LISTEN)+ const iEnd = lines.lastIndexOf(END)+ if (iPanes < 0 || iProcs < 0 || iListen < 0 || iEnd < 0) return fail('unreachable')+ if (!(iPanes < iProcs && iProcs < iListen && iListen < iEnd)) return fail('unreachable')++ const { answered, panes } = parseFencedPanes(lines.slice(iPanes + 1, iProcs), sockets)+ if (answered === 0) return fail('unreachable')+ const procs = parseProcRows(lines.slice(iProcs + 1, iListen).join('\n'))+ if (procs.length === 0) return fail('unreachable')++ const listen = lines.slice(iListen + 1, iEnd)+ const via = /^##VIA (\w+)$/.exec(listen[0] ?? '')?.[1]+ if (via === 'none') return fail('no-listener-tool')+ const rcLine = listen.findIndex((l) => /^##LISTENRC \d+$/.test(l))+ if (!via || rcLine < 0) return fail('unreachable')+ const rc = Number(listen[rcLine].slice('##LISTENRC '.length))+ const body = listen.slice(1, rcLine).join('\n')++ let listeners: Listener[]+ if (via === 'ss') {+ if (rc !== 0) return fail('unreachable')+ listeners = parseSsListeners(body)+ } else if (via === 'lsof') {+ // lsof exits 1 when it matched nothing: with no output that is "no listeners", an answer.+ if (rc !== 0 && !(rc === 1 && body.trim() === '')) return fail('unreachable')+ listeners = parseLsofListeners(body)+ } else if (via === 'proc') {+ const fdAt = body.split('\n').indexOf(FD)+ const bodyLines = body.split('\n')+ if (fdAt < 0) return fail('unreachable')+ const sockets4 = parseProcNetTcp(bodyLines.slice(0, fdAt).join('\n'))+ const owners = parseProcFdSockets(bodyLines.slice(fdAt + 1).join('\n'))+ listeners = []+ for (const [inode, hp] of sockets4) listeners.push({ pids: owners.get(inode) ?? [], ...hp, command: '' })+ } else {+ return fail('unreachable')+ }++ // Both sockets print into one section; first pane of a (session, pid) is enough.+ return { ok: true, nodes: assembleDevPorts(panes, procs, listeners) }+}++/**+ * Which address the HOST side of a forward should connect to, from the addresses a port is bound+ * on. A server bound only to `::1` (common: `localhost` resolving to IPv6 first) refuses+ * `127.0.0.1`, so the target must follow the bind:+ * - any IPv4 wildcard/loopback (`0.0.0.0`, `*`, `127.x`) → `127.0.0.1`;+ * - else IPv6 loopback or wildcard → `::1`;+ * - else the one specific address it is bound on.+ * Returns null for anything that is not a plain IPv4/IPv6 literal — the value came off another+ * machine's command output and lands in an ssh argument.+ */+export function forwardTarget(addresses: readonly string[]): string | null {+ const v4 = /^\d{1,3}(\.\d{1,3}){3}$/+ const v6 = /^[0-9A-Fa-f:]+$/+ if (addresses.some((a) => a === '0.0.0.0' || a === '*' || /^127\./.test(a))) return '127.0.0.1'+ if (addresses.some((a) => a === '::1' || a === '::')) return '::1'+ const specific = addresses.find((a) => v4.test(a) || (v6.test(a) && a.includes(':')))+ return specific ?? null+}++/** Runs the probe on this machine. Windows has no `/bin/sh` and no tmux: honestly unsupported. */+export async function collectLocalDevPorts(+ exec: (command: string) => Promise<string> = async (command) => {+ const { stdout } = await runAsync('/bin/sh', ['-c', command], { timeout: 15_000, maxBuffer: 16 * 1024 * 1024 })+ return stdout+ },+ platformName: NodeJS.Platform = process.platform+): Promise<DevPortsReport> {+ if (platformName === 'win32') return fail('unsupported')+ try {+ return parseDevPortsProbe(await exec(devPortsProbeCommand()))+ } catch {+ return fail('unreachable')+ }+}++/** Runs a POSIX sh command on the project's host; resolves stdout, or null if it could not run. */+export type RemoteDevPortsRunner = (projectId: string, command: string) => Promise<string | null>++export async function fetchRemoteDevPorts(projectId: string, run: RemoteDevPortsRunner): Promise<DevPortsReport> {+ let stdout: string | null+ try {+ stdout = await run(projectId, devPortsProbeCommand())+ } catch {+ return fail('unreachable')+ }+ if (stdout === null) return fail('unreachable')+ return parseDevPortsProbe(stdout)+}diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex d1ca58041..6ff3956c2 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -770,6 +770,36 @@ export function hookForwardArgs(conn: SshConnection, controlPath: string, remoteexport function hookForwardCancelArgs(conn: SshConnection, controlPath: string, remoteSock: string, hookPort: number): string[] {return ['-O', 'cancel', '-R', fwdSpec(remoteSock, hookPort), '-o', `ControlPath=${controlPath}`, ...portArgs(conn), target(conn)]}+/**+ * A dev-server LOCAL forward over the existing master (`ssh -O forward -L`): this machine's+ * `127.0.0.1:<localPort>` → the host's `<target>:<remotePort>`. The local side binds loopback ONLY+ * — never `*` or a LAN address, which would publish someone's unfinished app to the network the+ * laptop is on. An IPv6 target is bracketed, which is how ssh's `-L` grammar takes it.+ * `toAddr` must already be a validated IP literal (core/dev-ports.ts `forwardTarget`).+ */+function localFwdSpec(localPort: number, toAddr: string, remotePort: number): string {+ const host = toAddr.includes(':') ? `[${toAddr}]` : toAddr+ return `127.0.0.1:${localPort}:${host}:${remotePort}`+}+export function localForwardArgs(+ conn: SshConnection,+ controlPath: string,+ localPort: number,+ toAddr: string,+ remotePort: number+): string[] {+ return ['-O', 'forward', '-L', localFwdSpec(localPort, toAddr, remotePort), '-o', `ControlPath=${controlPath}`, ...portArgs(conn), target(conn)]+}+/** The exact spec `localForwardArgs` opened — ssh matches a cancel against it verbatim. */+export function localForwardCancelArgs(+ conn: SshConnection,+ controlPath: string,+ localPort: number,+ toAddr: string,+ remotePort: number+): string[] {+ return ['-O', 'cancel', '-L', localFwdSpec(localPort, toAddr, remotePort), '-o', `ControlPath=${controlPath}`, ...portArgs(conn), target(conn)]+}/*** tmux `-e KEY=VALUE` pairs injecting the remote hook endpoint file + node id + protocol version,* plus the agent identity. The identity pair matters: the local path's `hookServer.buildPtyEnv`diff --git a/src/core/remote-ssh/port-forward.test.ts b/src/core/remote-ssh/port-forward.test.tsnew file mode 100644index 000000000..aa0a53748--- /dev/null+++ b/src/core/remote-ssh/port-forward.test.ts@@ -0,0 +1,220 @@+import { afterEach, describe, expect, it } from 'vitest'+import net from 'net'+import type { DevPortsReport } from '../../shared/dev-ports'+import type { SshConnection } from '../../shared/ssh'+import { localForwardArgs, localForwardCancelArgs } from './control-master'+import { canBind, canConnect, defaultLocalPortBusy, PortForwardRegistry, type PortForwardDeps } from './port-forward'++const conn: SshConnection = { host: 'box', user: 'me', port: 2222 }+const CP = '/tmp/cp.sock'++function report(nodes: DevPortsReport['nodes'], ok = true): DevPortsReport {+ return ok ? { ok: true, nodes } : { ok: false, reason: 'unreachable', nodes: {} }+}+const vite = (addresses = ['127.0.0.1']): DevPortsReport['nodes'] => ({+ web: [{ port: 5173, addresses, command: 'node', ephemeral: false }]+})++function harness(over: Partial<PortForwardDeps> & { scanResult?: DevPortsReport } = {}) {+ const calls: string[][] = []+ const busy = new Set<number>()+ const held = new Set<number>()+ let connected = true+ let scanResult = over.scanResult ?? report(vite())+ const deps: PortForwardDeps = {+ refForProject: (id) => (connected && id === 'p' ? { conn, controlPath: CP } : undefined),+ run: async (args) => {+ calls.push(args)+ const i = args.indexOf('-L')+ const local = Number(args[i + 1].split(':')[1])+ if (args[1] === 'forward') held.add(local)+ else held.delete(local)+ return { code: 0, stdout: '' }+ },+ scan: async () => scanResult,+ localPortBusy: async (p) => busy.has(p) || held.has(p),+ localPortHeld: async (p) => held.has(p),+ ...over+ }+ return {+ reg: new PortForwardRegistry(deps),+ calls,+ busy,+ held,+ setScan: (r: DevPortsReport) => (scanResult = r),+ disconnect: () => (connected = false)+ }+}++describe('argv', () => {+ it('binds 127.0.0.1 only, same spec for forward and cancel, brackets an IPv6 target', () => {+ expect(localForwardArgs(conn, CP, 5173, '127.0.0.1', 5173)).toEqual([+ '-O', 'forward', '-L', '127.0.0.1:5173:127.0.0.1:5173', '-o', `ControlPath=${CP}`, '-p', '2222', 'me@box'+ ])+ expect(localForwardCancelArgs(conn, CP, 5174, '::1', 5173)).toEqual([+ '-O', 'cancel', '-L', '127.0.0.1:5174:[::1]:5173', '-o', `ControlPath=${CP}`, '-p', '2222', 'me@box'+ ])+ })+})++describe('PortForwardRegistry.forward', () => {+ it('forwards the SAME port, targeting the address the server bound', async () => {+ const h = harness({ scanResult: report(vite(['::1'])) })+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })).toEqual({+ ok: true, localPort: 5173, url: 'http://localhost:5173', reused: false+ })+ expect(h.calls[0]).toContain('127.0.0.1:5173:[::1]:5173')+ expect(h.reg.list('p')).toEqual([{ nodeId: 'web', remotePort: 5173, localPort: 5173 }])+ })++ it('reuses a live forward instead of opening a second', async () => {+ const h = harness()+ await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })+ const again = await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })+ expect(again).toMatchObject({ ok: true, reused: true })+ expect(h.calls).toHaveLength(1)+ })++ it('coalesces a double click into one ssh call', async () => {+ const h = harness()+ const [a, b] = await Promise.all([+ h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 }),+ h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })+ ])+ expect(a).toEqual(b)+ expect(h.calls).toHaveLength(1)+ })++ it('refuses a port the node is not listening on — decided by a scan, not by the caller', async () => {+ const h = harness()+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 22 })).toMatchObject({ ok: false, reason: 'not-listening' })+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'other', port: 5173 })).toMatchObject({ ok: false, reason: 'not-listening' })+ expect(h.calls).toHaveLength(0)+ })++ it('a failed scan is not-connected, never a forward on stale facts', async () => {+ const h = harness({ scanResult: report({}, false) })+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })).toMatchObject({ ok: false, reason: 'not-connected' })+ expect(h.calls).toHaveLength(0)+ })++ it('refuses a busy local port with a suggestion, and never moves it on its own', async () => {+ const h = harness()+ h.busy.add(5173)+ h.busy.add(5174)+ const r = await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })+ expect(r).toMatchObject({ ok: false, reason: 'local-port-busy', suggestedLocalPort: 5175 })+ expect(h.calls).toHaveLength(0)+ // The explicit choice is honoured.+ const chosen = await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173, localPort: 5175 })+ expect(chosen).toMatchObject({ ok: true, localPort: 5175, url: 'http://localhost:5175' })+ expect(h.calls[0]).toContain('127.0.0.1:5175:127.0.0.1:5173')+ })++ it('never forwards a privileged port without the person confirming it', async () => {+ const h = harness({ scanResult: report({ web: [{ port: 80, addresses: ['0.0.0.0'], command: 'nginx', ephemeral: false }] }) })+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 80 })).toMatchObject({ ok: false, reason: 'privileged' })+ expect(h.calls).toHaveLength(0)+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 80, allowPrivileged: true })).toMatchObject({ ok: true })+ // A privileged LOCAL port is asked about too.+ const h2 = harness()+ expect(await h2.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173, localPort: 443 })).toMatchObject({ reason: 'privileged' })+ })++ it('reports an ssh failure honestly and records nothing', async () => {+ const h = harness({ run: async () => ({ code: 255, stdout: '' }) })+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })).toMatchObject({ ok: false, reason: 'forward-failed' })+ expect(h.reg.list('p')).toEqual([])+ })++ it('refuses garbage and a disconnected project', async () => {+ const h = harness()+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 0 })).toMatchObject({ reason: 'invalid-port' })+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173.5 })).toMatchObject({ reason: 'invalid-port' })+ h.disconnect()+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })).toMatchObject({ reason: 'not-connected' })+ })+})++describe('PortForwardRegistry lifecycle', () => {+ it('cancels when a successful scan no longer lists the host port; a FAILED scan cancels nothing', async () => {+ const h = harness()+ await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })+ await h.reg.reconcile('p', report({}, false))+ expect(h.reg.list('p')).toHaveLength(1)+ await h.reg.reconcile('p', report({}))+ expect(h.reg.list('p')).toEqual([])+ expect(h.calls[1].slice(0, 4)).toEqual(['-O', 'cancel', '-L', '127.0.0.1:5173:127.0.0.1:5173'])+ })++ it('forgets a forward whose local listener vanished (a master rebuilt without -L)', async () => {+ const h = harness()+ await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })+ h.held.clear()+ await h.reg.reconcile('p', report(vite()))+ expect(h.reg.list('p')).toEqual([])+ expect(h.calls).toHaveLength(1) // nothing to cancel+ // …and the next click forwards again rather than "reusing" a dead one.+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })).toMatchObject({ ok: true, reused: false })+ })++ it('cancels a node\'s forwards when its session ends', async () => {+ const h = harness()+ await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })+ await h.reg.nodeEnded('someone-else')+ expect(h.reg.list('p')).toHaveLength(1)+ await h.reg.nodeEnded('web')+ expect(h.reg.list('p')).toEqual([])+ expect(h.calls.at(-1)?.[1]).toBe('cancel')+ })++ it('drops (without ssh) when the project disconnects', async () => {+ const h = harness()+ await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })+ h.reg.projectDisconnected('p')+ expect(h.reg.list('p')).toEqual([])+ expect(h.calls).toHaveLength(1)+ })++ it('unforward cancels only the named project\'s forward', async () => {+ const h = harness()+ await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })+ expect(await h.reg.unforward('q', 5173)).toBe(false)+ expect(await h.reg.unforward('p', 5173)).toBe(true)+ expect(h.reg.list('p')).toEqual([])+ })+})++describe('local port probes (real sockets)', () => {+ const servers: net.Server[] = []+ afterEach(async () => {+ await Promise.all(servers.splice(0).map((s) => new Promise((r) => s.close(r))))+ })+ const listen = (host: string, port = 0): Promise<number> =>+ new Promise((resolve, reject) => {+ const s = net.createServer()+ servers.push(s)+ s.once('error', reject)+ s.listen({ host, port }, () => resolve((s.address() as net.AddressInfo).port))+ })++ it('a free port is free; a v4 listener makes it busy', async () => {+ const port = await listen('127.0.0.1')+ expect(await canConnect('127.0.0.1', port)).toBe(true)+ expect(await canBind('127.0.0.1', port)).toBe(false)+ expect(await defaultLocalPortBusy(port)).toBe(true)+ await new Promise((r) => servers.pop()!.close(r))+ expect(await defaultLocalPortBusy(port)).toBe(false)+ })++ it('a listener on ::1 ONLY still makes the port busy (localhost would reach it first)', async () => {+ let port: number+ try {+ port = await listen('::1')+ } catch {+ return // no IPv6 loopback on this machine: nothing to prove+ }+ expect(await canBind('127.0.0.1', port)).toBe(true) // the v4 bind alone would call it free…+ expect(await defaultLocalPortBusy(port)).toBe(true) // …the connect check does not.+ })+})diff --git a/src/core/remote-ssh/port-forward.ts b/src/core/remote-ssh/port-forward.tsnew file mode 100644index 000000000..05ecc087e--- /dev/null+++ b/src/core/remote-ssh/port-forward.ts@@ -0,0 +1,238 @@+// Same-port local forwards for an SSH project's dev servers, over the project's EXISTING+// ControlMaster (`ssh -O forward -L 127.0.0.1:P:<host-side addr>:P`). The point of the SAME number+// is that the URLs the tool prints — `http://localhost:5173` — just work on this machine.+//+// Rules, each a refusal rather than a guess:+// - Only a port discovery attributed to THIS node, in a scan taken at click time, is forwarded;+// the renderer names a node and a port, never a host-side address.+// - The local side binds 127.0.0.1 only.+// - A local port that is taken — by anything listening on 127.0.0.1 OR ::1, since a browser's+// `localhost` tries IPv6 first and would silently show the LOCAL app — is refused with the+// reason, never silently moved. A different local port is only ever the person's explicit+// choice (`localPort` in the request), with a free one suggested.+// - A privileged port (< 1024, on either side) is refused until the person confirmed it.+// - Lifecycle: a forward is cancelled when its node's session ends, when a successful scan no+// longer lists the host port, or dropped when the project disconnects (the master takes the+// listener with it). A failed scan cancels nothing — a failed read is never evidence.+// - A master rebuilt behind our back (`ControlMaster=auto`, issue #735's mechanism) carries no+// `-L`: every successful scan re-checks that the local listener is still held and forgets a+// forward whose listener is gone, so the menu offers to forward again instead of lying.++import net from 'net'+import type { SshConnection } from '../../shared/ssh'+import {+ devPortUrl,+ forwardRefusalText,+ isPrivilegedPort,+ isValidPort,+ type DevPortForward,+ type DevPortForwardRequest,+ type DevPortForwardResult,+ type DevPortsReport+} from '../../shared/dev-ports'+import { forwardTarget } from '../dev-ports'+import { localForwardArgs, localForwardCancelArgs } from './control-master'++export interface PortForwardDeps {+ refForProject(projectId: string): { conn: SshConnection; controlPath: string } | undefined+ run(args: string[]): Promise<{ code: number; stdout: string }>+ /** A fresh discovery of the project's host (coalesced by the caller). */+ scan(projectId: string): Promise<DevPortsReport>+ /** Is anything reachable on this machine's `localhost:<port>`, or is the loopback port unbindable? */+ localPortBusy(port: number): Promise<boolean>+ /** Is the loopback listener still there (i.e. can we NOT bind 127.0.0.1:<port>)? */+ localPortHeld(port: number): Promise<boolean>+}++interface Held extends DevPortForward {+ projectId: string+ target: string+ conn: SshConnection+ controlPath: string+}++/** How far past the requested port the suggestion looks for a free one. */+const SUGGEST_SPAN = 100++export class PortForwardRegistry {+ private readonly held = new Map<number, Held>() // keyed by LOCAL port — unique on this machine+ private readonly inFlight = new Map<string, Promise<DevPortForwardResult>>()++ constructor(private readonly d: PortForwardDeps) {}++ list(projectId: string): DevPortForward[] {+ return [...this.held.values()]+ .filter((h) => h.projectId === projectId)+ .map(({ nodeId, remotePort, localPort }) => ({ nodeId, remotePort, localPort }))+ .sort((a, b) => a.remotePort - b.remotePort)+ }++ /** Coalesces a double click on the same row into one attempt. */+ forward(req: DevPortForwardRequest): Promise<DevPortForwardResult> {+ const key = `${req.projectId}\u0000${req.nodeId}\u0000${req.port}\u0000${req.localPort ?? ''}`+ const pending = this.inFlight.get(key)+ if (pending) return pending+ const p = this.forwardOnce(req).finally(() => this.inFlight.delete(key))+ this.inFlight.set(key, p)+ return p+ }++ private refuse(+ reason: Parameters<typeof forwardRefusalText>[0],+ port: number,+ localPort?: number,+ suggestedLocalPort?: number+ ): DevPortForwardResult {+ return {+ ok: false,+ reason,+ message: forwardRefusalText(reason, port, localPort),+ ...(suggestedLocalPort !== undefined ? { suggestedLocalPort } : {})+ }+ }++ private async forwardOnce(req: DevPortForwardRequest): Promise<DevPortForwardResult> {+ const remotePort = req.port+ const localPort = req.localPort ?? remotePort+ if (!isValidPort(remotePort) || !isValidPort(localPort) || typeof req.nodeId !== 'string' || !req.nodeId) {+ return this.refuse('invalid-port', Number(remotePort))+ }+ if (!this.d.refForProject(req.projectId)) return this.refuse('not-connected', remotePort)++ // The host side is decided HERE, from a scan taken now — never from the renderer.+ const report = await this.d.scan(req.projectId)+ if (!report.ok) return this.refuse('not-connected', remotePort)+ const found = report.nodes[req.nodeId]?.find((p) => p.port === remotePort)+ if (!found) return this.refuse('not-listening', remotePort)+ const target = forwardTarget(found.addresses)+ if (!target) return this.refuse('forward-failed', remotePort)++ // Already forwarded for this project's port: hand back the live one, forget a dead one.+ for (const h of this.held.values()) {+ if (h.projectId !== req.projectId || h.remotePort !== remotePort) continue+ if (req.localPort !== undefined && h.localPort !== req.localPort) continue+ if (await this.d.localPortHeld(h.localPort)) {+ return { ok: true, localPort: h.localPort, url: devPortUrl(h.localPort), reused: true }+ }+ this.held.delete(h.localPort)+ }++ if ((isPrivilegedPort(remotePort) || isPrivilegedPort(localPort)) && req.allowPrivileged !== true) {+ return this.refuse('privileged', remotePort, localPort)+ }++ const ours = this.held.get(localPort)+ if (ours || (await this.d.localPortBusy(localPort))) {+ return this.refuse('local-port-busy', remotePort, localPort, await this.suggest(localPort))+ }++ // Re-read the ref: the scan was a round trip, and the master may have gone meanwhile.+ const ref = this.d.refForProject(req.projectId)+ if (!ref) return this.refuse('not-connected', remotePort)+ let code: number+ try {+ ;({ code } = await this.d.run(localForwardArgs(ref.conn, ref.controlPath, localPort, target, remotePort)))+ } catch {+ code = -1+ }+ if (code !== 0) return this.refuse('forward-failed', remotePort, localPort)+ this.held.set(localPort, {+ projectId: req.projectId,+ nodeId: req.nodeId,+ remotePort,+ localPort,+ target,+ conn: ref.conn,+ controlPath: ref.controlPath+ })+ return { ok: true, localPort, url: devPortUrl(localPort), reused: false }+ }++ /** The first free, non-privileged, not-ours local port after `from` — a suggestion only. */+ private async suggest(from: number): Promise<number | undefined> {+ for (let p = Math.max(from + 1, 1024); p <= Math.min(from + SUGGEST_SPAN, 65535); p++) {+ if (this.held.has(p)) continue+ if (!(await this.d.localPortBusy(p))) return p+ }+ return undefined+ }++ private async cancel(h: Held): Promise<void> {+ this.held.delete(h.localPort)+ try {+ await this.d.run(localForwardCancelArgs(h.conn, h.controlPath, h.localPort, h.target, h.remotePort))+ } catch {+ // Best effort: the master may already be gone, taking the listener with it.+ }+ }++ async unforward(projectId: string, localPort: number): Promise<boolean> {+ const h = this.held.get(localPort)+ if (!h || h.projectId !== projectId) return false+ await this.cancel(h)+ return true+ }++ /** After a SUCCESSFUL scan of the project: cancel forwards whose host port stopped listening,+ * forget forwards whose local listener vanished (a rebuilt master). A failed scan changes nothing. */+ async reconcile(projectId: string, report: DevPortsReport): Promise<void> {+ if (!report.ok) return+ const listening = new Set<number>()+ for (const ports of Object.values(report.nodes)) for (const p of ports) listening.add(p.port)+ for (const h of [...this.held.values()]) {+ if (h.projectId !== projectId) continue+ if (!listening.has(h.remotePort)) await this.cancel(h)+ else if (!(await this.d.localPortHeld(h.localPort))) this.held.delete(h.localPort)+ }+ }++ /** The node's session ended (delete, recycle): its dev server went with it. */+ async nodeEnded(nodeId: string): Promise<void> {+ for (const h of [...this.held.values()]) if (h.nodeId === nodeId) await this.cancel(h)+ }++ /** The project's master is gone; its listeners died with it — nothing to cancel over ssh. */+ projectDisconnected(projectId: string): void {+ for (const h of [...this.held.values()]) if (h.projectId === projectId) this.held.delete(h.localPort)+ }+}++/** Can a TCP connection to `host:port` on this machine be opened within `timeoutMs`? */+export function canConnect(host: string, port: number, timeoutMs = 400): Promise<boolean> {+ return new Promise((resolve) => {+ const sock = net.connect({ host, port })+ const done = (v: boolean): void => {+ sock.removeAllListeners()+ sock.destroy()+ resolve(v)+ }+ sock.setTimeout(timeoutMs, () => done(false))+ sock.once('connect', () => done(true))+ sock.once('error', () => done(false))+ })+}++/** Could this process bind `host:port` right now? (Released immediately.) */+export function canBind(host: string, port: number): Promise<boolean> {+ return new Promise((resolve) => {+ const srv = net.createServer()+ srv.once('error', () => resolve(false))+ srv.listen({ host, port, exclusive: true }, () => srv.close(() => resolve(true)))+ })+}++/**+ * Busy = something answers on `localhost:<port>` over either family, or 127.0.0.1 cannot be bound.+ * The ::1 connect check is the one that matters for correctness: a local app bound only to ::1+ * leaves 127.0.0.1 free, the forward would succeed, and the browser node's `localhost` (IPv6+ * first) would show the local app instead of the host's.+ */+export async function defaultLocalPortBusy(port: number): Promise<boolean> {+ const [v4, v6] = await Promise.all([canConnect('127.0.0.1', port), canConnect('::1', port)])+ if (v4 || v6) return true+ return !(await canBind('127.0.0.1', port))+}++export async function defaultLocalPortHeld(port: number): Promise<boolean> {+ return !(await canBind('127.0.0.1', port))+}diff --git a/src/core/session-memory-remote.ts b/src/core/session-memory-remote.tsindex 6fe424963..9a13d4341 100644--- a/src/core/session-memory-remote.ts+++ b/src/core/session-memory-remote.ts@@ -56,12 +56,7 @@ const SWEEP_SOCKETS: readonly string[] = [TMUX_SOCKET, RMT_TMUX_SOCKET]* /proc reads over a link we do not control, and its output is what we already parse.*/export function remoteSessionMemoryCommand(): string {- const listPanes = (socket: string): string =>- [- `echo '${SOCK} ${socket}'`,- `tmux -L ${socket} list-panes -a -F '${PANE_FMT}' 2>&1`,- `echo "${SOCKRC} $?"`- ].join('\n')+ const listPanes = fencedListPanesCommandreturn [// tmux may live off the exec channel's PATH (Homebrew on macOS — issue #449, same append as// remoteTmuxPathPrologue). Without this every socket answers 127 and the sweep reports@@ -107,7 +102,26 @@ function parseMem(lines: string[]): MemInfo | null {* happens to start with the marker text.*/function parsePanesSection(lines: readonly string[]): { answered: number; panes: PaneRef[] } {- const headers = new Map(SWEEP_SOCKETS.map((s) => [`${SOCK} ${s}`, s]))+ return parseFencedPanes(lines, SWEEP_SOCKETS)+}++/** One socket's fenced `list-panes` block for a generated script. Shared with the dev-ports probe+ * (core/dev-ports.ts), so the two remote sweeps fence a socket — and classify its failure — the+ * same way. */+export function fencedListPanesCommand(socket: string): string {+ return [+ `echo '${SOCK} ${socket}'`,+ `tmux -L ${socket} list-panes -a -F '${PANE_FMT}' 2>&1`,+ `echo "${SOCKRC} $?"`+ ].join('\n')+}++/** `parsePanesSection` over an explicit socket list — see that function for the rules. */+export function parseFencedPanes(+ lines: readonly string[],+ sockets: readonly string[]+): { answered: number; panes: PaneRef[] } {+ const headers = new Map(sockets.map((s) => [`${SOCK} ${s}`, s]))let answered = 0const panes: PaneRef[] = []let buf: string[] | null = nulldiff --git a/src/main/dev-ports-wiring.test.ts b/src/main/dev-ports-wiring.test.tsnew file mode 100644index 000000000..e52320c14--- /dev/null+++ b/src/main/dev-ports-wiring.test.ts@@ -0,0 +1,28 @@+// Nothing type-checks that main actually wires the forward lifecycle: a dropped listener compiles,+// passes every unit test, and leaves forwards open after their node closed. Pinned at source level,+// the same remedy hook-verified-parity.test.ts uses for the same class of hole.+import { describe, it, expect } from 'vitest'+import fs from 'fs'+import path from 'path'++const read = (p: string): string => fs.readFileSync(path.join(__dirname, '..', p), 'utf8').replace(/\r\n/g, '\n')++describe('dev-ports wiring', () => {+ const main = read('main/index.ts')+ it('the desktop registers the service with a forward leg over the project master', () => {+ expect(main).toMatch(/startDevPortsService\(\{[\s\S]{0,1500}forward: \{[\s\S]{0,300}refForProject/)+ })+ it('a node\'s session ending cancels its forwards; a disconnect forgets the project\'s', () => {+ expect(main).toMatch(/ptyManager\.onSessionEnded\(\(nodeId\) => void devPorts\.registry\?\.nodeEnded\(nodeId\)\)/)+ expect(main).toMatch(/onSshProjectStatus\([\s\S]{0,200}projectDisconnected\(e\.projectId\)/)+ })+ it('the Server Edition does not register it (its bridge answers unsupported)', () => {+ expect(read('server/index.ts')).not.toMatch(/startDevPortsService/)+ expect(read('renderer/bridge/ws-bridge.ts')).not.toMatch(/devPortsScan/)+ })+ it('the canvas node header and the card modal both draw the chip; Canvas runs the scanner', () => {+ expect(read('renderer/nodes/TerminalNode.tsx')).toMatch(/<PortsChip/)+ expect(read('renderer/components/kanban/CardModal.tsx')).toMatch(/<PortsChip/)+ expect(read('renderer/canvas/Canvas.tsx')).toMatch(/useDevPortScanner\(/)+ })+})diff --git a/src/main/index.ts b/src/main/index.tsindex de78adbea..d2057beda 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -231,6 +231,7 @@ import { createSessionReaper } from '../core/session-budget'import { initKeepAwake } from './keep-awake'import type { KeepAwakeTracker } from '../core/keep-awake'import { startSessionMemoryService, sshScopePredicate } from '../core/session-memory-service'+import { startDevPortsService } from '../core/dev-ports-service'import { createMemoryPressureMonitor } from '../core/memory-pressure'import { createPtyPressureMonitor } from '../core/pty-pressure'import { registerPtmxLimitHandler } from './ptmx-limit'@@ -368,7 +369,7 @@ import { isJoinCode } from '../core/relay/join-code'import { connectHostedTeam, removeHostedBookmark } from './remote/hosted-join'import { BookmarkStore, publicBookmark } from './remote/relay-bookmarks'import { loadOrCreatePeerKeyPair } from './remote/peer-identity'-import { initSshProject } from './remote-ssh/ssh-project'+import { initSshProject, onSshProjectStatus } from './remote-ssh/ssh-project'import { resyncProjectAgents, RESYNC_TRANSCRIPT_TAIL_BYTES } from './remote-ssh/agent-resync'import { setGitRemoteResolver, type GitRemoteRef } from '../core/remote-ssh/remote-git'import { SshFs, sshAppendArgs, sshTailArgs, sshSizeArgs, sshWriteArgs } from './ssh-fs'@@ -3151,6 +3152,40 @@ app.whenReady().then(async () => {}}})+ // Dev-server ports (CLAUDE.md → Dev-server ports). Same identity predicate and the same+ // exit-code-gated runner shape as session memory above; forwarding rides the project's master.+ const devPorts = startDevPortsService({+ remote: {+ isRemoteProject: sshScopePredicate({+ sshProjectIds: () => workspaceStore.sshProjectIds(),+ connectedProjectIds: () =>+ (sshProjectManager?.connectedHosts() ?? []).map((h) => h.projectId)+ }),+ run: async (projectId, command) => {+ const mgr = sshProjectManager+ const ref = mgr?.refForProject(projectId)+ if (!mgr || !ref) return null+ try {+ // The script always ends with an unconditional echo: a non-zero code is ssh itself failing.+ const { code, stdout } = await mgr.sshRun(childArgs(ref.conn, ref.controlPath, command))+ return code === 0 ? stdout : null+ } catch {+ return null+ }+ },+ forward: {+ refForProject: (projectId) => sshProjectManager?.refForProject(projectId),+ run: (args) =>+ sshProjectManager ? sshProjectManager.sshRun(args) : Promise.resolve({ code: -1, stdout: '' })+ }+ }+ })+ // A node's session ending (delete, recycle) takes its dev server with it — cancel its forwards.+ ptyManager.onSessionEnded((nodeId) => void devPorts.registry?.nodeEnded(nodeId))+ // A master that went away took its listeners with it; forget them so the menu offers again.+ onSshProjectStatus((e) => {+ if (e.status !== 'connected' && e.status !== 'connecting') devPorts.registry?.projectDisconnected(e.projectId)+ })const ackSweeper = createAckSweeper({handlers: { ackDone, onUnreadClear: (id) => sendToMain(IPC.agentUnreadClear, id) }})diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 34167f7dd..9e6811540 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -2721,6 +2721,14 @@ export function resolvePassphrasePrompt(requestId: string, value: string | null)* not hand a host two budgets. */const sshChildGate = new SshChildGate()+/** In-process listeners for every project status event (beside the renderer push). Used by the+ * dev-port forward registry to forget a disconnected project's forwards. */+const sshStatusListeners = new Set<(e: SshProjectStatusEvent) => void>()+export function onSshProjectStatus(listener: (e: SshProjectStatusEvent) => void): () => void {+ sshStatusListeners.add(listener)+ return () => sshStatusListeners.delete(listener)+}+export function initSshProject(onConnected?: (projectId: string) => void,askpassScriptPath?: string,@@ -2872,6 +2880,13 @@ export function initSshProject(nodeIdsForProject: (projectId) => nodeIdsForCanvas(projectId),nodeTokenMinter: () => remoteNodeTokenMinter(),onStatus: (e) => {+ for (const listener of [...sshStatusListeners]) {+ try {+ listener(e)+ } catch {+ // an in-process listener must never break the status push to the UI+ }+ }// sendToMain resolves the window AT SEND TIME (see main-window.ts): the `win` captured here// is destroyed and recreated by a macOS close/reopen, and sending to the stale reference is// silently dropped. The try/catch is the other half: webContents.send THROWS when the renderdiff --git a/src/preload/index.ts b/src/preload/index.tsindex c37047a4e..851f88cfb 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -23,6 +23,7 @@ import type {} from '../shared/types'import type { ClientId, PeerDiff, PeerIdentity, PeerState } from '../shared/presence'import type { ProjectConsentRequest, ProjectSetupEvent } from '../shared/project-settings'+import type { DevPortForwardRequest, DevPortsQuery } from '../shared/dev-ports'// Fan a single ipcRenderer listener per channel out to many renderer subscribers. Without// this, every node that subscribes (e.g. Cmd+M markdown toggle on each terminal/editor) adds@@ -501,6 +502,13 @@ const api: NodeTerminalApi = {read: (q?: SessionMemoryQuery) => ipcRenderer.invoke(IPC.sessionMemory, q),host: (q?: SessionMemoryQuery) => ipcRenderer.invoke(IPC.sessionMemoryHost, q)},+ // Forwarded verbatim for the same reason as sessionMemory: `remote` is OR-ed with the core's own+ // claim, and a forward request carries only node + port — the host-side address is decided in core.+ devPorts: {+ scan: (q?: DevPortsQuery) => ipcRenderer.invoke(IPC.devPortsScan, q),+ forward: (req: DevPortForwardRequest) => ipcRenderer.invoke(IPC.devPortsForward, req),+ unforward: (req: { projectId: string; localPort: number }) => ipcRenderer.invoke(IPC.devPortsUnforward, req)+ },wallpaper: {listStills: () => ipcRenderer.invoke(IPC.wallpaperListStills),load: (w) => ipcRenderer.invoke(IPC.wallpaperLoad, w),diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 2befe0138..ab7521c55 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -276,6 +276,17 @@ export function buildStubApi(): Omit<cookieProviders: () => Promise.resolve({}),onUpdate: noopUnsub},+ devPorts: {+ // Deliberately NOT superseded by a WS namespace: the Server Edition does not serve dev ports+ // (its browser tab has no <webview> browser node, and a page the viewer opened would load on+ // the viewer's machine, where the server's port is not). A relay tab shares this surface for+ // the other reason — its sessions live on the host. `unsupported` is the honest answer on+ // both, and the chip is not drawn.+ scan: () => Promise.resolve({ ok: false, reason: 'unsupported', nodes: {} }),+ forward: () =>+ Promise.resolve({ ok: false, reason: 'unsupported', message: 'Port forwarding is not available here.' }),+ unforward: () => Promise.resolve(false)+ },sessionMemory: {// Superseded by the real WS-backed namespace in ws-bridge (the core session-memory service// runs in the server shell too), so nothing reaches these in a live browser session. Keptdiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex a082383c3..d6b12ae24 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1,4 +1,5 @@import { reportTextDelivery } from '../lib/textDelivery'+import { useDevPortScanner } from './useDevPortScanner'import { TEXT_NOT_SUBMITTED } from '@shared/text-delivery'import { VisibleMiniMap } from './VisibleMiniMap'import { MinimapDock } from './MinimapDock'@@ -1915,6 +1916,13 @@ export function Canvas() {// tab switch. Reading presence imperatively via `.store.getState()`/`.subscribe` (never a reactive// `usePresence(sel)` hook) is the PERF CONTRACT: a peer's 20 Hz cursor never re-renders Canvas.const activeSession = sessionForProject(activeProjectId || '')+ // Dev-server ports of the project on screen (CLAUDE.md → Dev-server ports): a primitive of its+ // terminal ids, so a drag or an edit does not re-run the scanner's effects.+ const devPortTerminalSig = useMemo(+ () => nodes.filter((n) => n.type === 'terminal').map((n) => n.id).join(','),+ [nodes]+ )+ useDevPortScanner(activeProjectId || '', devPortTerminalSig)const activePresence = presenceForProject(activeProjectId || '')// The active tab's hosted team, when it is one (undefined for every other tab). A role below Editor// makes the canvas read-only in the UI; the host enforces the role either way.diff --git a/src/renderer/canvas/useDevPortScanner.ts b/src/renderer/canvas/useDevPortScanner.tsnew file mode 100644index 000000000..5c302f090--- /dev/null+++ b/src/renderer/canvas/useDevPortScanner.ts@@ -0,0 +1,52 @@+// Drives the dev-port scans for the project on screen (CLAUDE.md → Dev-server ports). The cadence+// rules live in lib/devPorts.ts; this is only the wiring: mount, window focus, a debounced trailing+// scan after the project's agents report activity, and a slow poll while the window is focused.+import { useEffect } from 'react'+import { DEV_PORTS_HOOK_DEBOUNCE_MS, pollIntervalMs } from '../lib/devPorts'+import { devPortsAvailable, scanDevPorts } from '../state/devPorts'+import { useAgentStatus } from '../state/agentStatus'+import { useProjects } from '../state/projects'+import { useSshConn } from '../state/sshConn'++/**+ * @param terminalIdsSig the project's terminal node ids joined with `,` — a primitive, so a canvas+ * edit that does not add or remove a terminal does not re-run the effects.+ */+export function useDevPortScanner(projectId: string, terminalIdsSig: string): void {+ const remote = useProjects((s) => !!s.getProject(projectId)?.ssh)+ const connected = useSshConn((s) => !!s.byProject[projectId])+ const eligible = !!terminalIdsSig && devPortsAvailable(projectId) && (!remote || connected)++ useEffect(() => {+ if (!eligible) return+ const watching = (): boolean => document.visibilityState === 'visible' && document.hasFocus()+ void scanDevPorts(projectId, remote, 'mount')+ const timer = setInterval(() => {+ if (watching()) void scanDevPorts(projectId, remote, 'poll')+ }, pollIntervalMs(remote))+ const onFocus = (): void => void scanDevPorts(projectId, remote, 'focus')+ window.addEventListener('focus', onFocus)+ return () => {+ clearInterval(timer)+ window.removeEventListener('focus', onFocus)+ }+ }, [eligible, projectId, remote])++ useEffect(() => {+ if (!eligible) return+ let debounce: ReturnType<typeof setTimeout> | null = null+ const onEvent = (): void => {+ if (debounce) clearTimeout(debounce)+ debounce = setTimeout(() => {+ debounce = null+ void scanDevPorts(projectId, remote, 'hook')+ }, DEV_PORTS_HOOK_DEBOUNCE_MS)+ }+ const subscribe = useAgentStatus.getState().onHookEvent+ const offs = terminalIdsSig.split(',').filter(Boolean).map((id) => subscribe(id, onEvent))+ return () => {+ if (debounce) clearTimeout(debounce)+ for (const off of offs) off()+ }+ }, [eligible, projectId, remote, terminalIdsSig])+}diff --git a/src/renderer/components/PortsChip.test.tsx b/src/renderer/components/PortsChip.test.tsxnew file mode 100644index 000000000..655b3cab0--- /dev/null+++ b/src/renderer/components/PortsChip.test.tsx@@ -0,0 +1,119 @@+// @vitest-environment jsdom+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { createRoot, type Root } from 'react-dom/client'+import { act } from 'react'+import type { DevPortForwardRequest, DevPortForwardResult, DevPortsReport } from '@shared/dev-ports'++class NoopResizeObserver {+ observe(): void {}+ disconnect(): void {}+}+;(globalThis as { ResizeObserver?: unknown }).ResizeObserver ??= NoopResizeObserver++const forward = vi.fn<(req: DevPortForwardRequest) => Promise<DevPortForwardResult>>()+const scan = vi.fn<() => Promise<DevPortsReport>>(async () => ({ ok: true, nodes: {} }))+vi.mock('../session/session', () => ({+ sessionForProject: () => ({ source: 'local', api: { devPorts: { forward, scan, unforward: vi.fn(async () => true) } } })+}))++const { PortsChip } = await import('./PortsChip')+const { useDevPorts, resetDevPortScans } = await import('../state/devPorts')++const vite = { port: 5173, addresses: ['127.0.0.1'], command: 'node', ephemeral: false }+const chrome = { port: 41234, addresses: ['127.0.0.1'], command: 'chrome', ephemeral: true }++let host: HTMLElement+let root: Root+const opened: string[] = []+function render(remote: boolean): void {+ act(() =>+ root.render(<PortsChip nodeId="web" projectId="p" remote={remote} onOpenUrl={(u) => opened.push(u)} />)+ )+}+const chip = (): HTMLButtonElement | null => host.querySelector('.ports-chip')+const menuItem = (text: string): HTMLElement =>+ [...document.body.querySelectorAll<HTMLElement>('.ctx-item')].find((e) => e.textContent?.includes(text)) as HTMLElement+const flush = async (): Promise<void> => {+ await act(async () => {+ await Promise.resolve()+ await Promise.resolve()+ })+}++beforeEach(() => {+ resetDevPortScans()+ opened.length = 0+ forward.mockReset()+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(() => {+ act(() => root.unmount())+ document.body.innerHTML = ''+})++describe('PortsChip', () => {+ it('draws nothing for a node with no ports, or only ephemeral ones', () => {+ render(false)+ expect(chip()).toBeNull()+ act(() => useDevPorts.getState().apply('p', { ok: true, nodes: { web: [chrome] } }))+ expect(chip()).toBeNull()+ })++ it('local project: opens http://localhost:<port> without forwarding anything', async () => {+ act(() => useDevPorts.getState().apply('p', { ok: true, nodes: { web: [vite, chrome] } }))+ render(false)+ expect(chip()?.textContent).toBe(':5173')+ act(() => chip()!.click())+ act(() => menuItem('Open :5173').click())+ expect(opened).toEqual(['http://localhost:5173'])+ expect(forward).not.toHaveBeenCalled()+ })++ it('SSH project: forwards the same port first, then opens the URL it answered', async () => {+ act(() => useDevPorts.getState().apply('p', { ok: true, nodes: { web: [vite] } }))+ forward.mockResolvedValueOnce({ ok: true, localPort: 5173, url: 'http://localhost:5173', reused: false })+ render(true)+ act(() => chip()!.click())+ act(() => menuItem('Open :5173').click())+ await flush()+ expect(forward).toHaveBeenCalledWith({ projectId: 'p', nodeId: 'web', port: 5173 })+ expect(opened).toEqual(['http://localhost:5173'])+ expect(useDevPorts.getState().byProject.p.forwards).toEqual([{ nodeId: 'web', remotePort: 5173, localPort: 5173 }])+ })++ it('a busy local port is ASKED about; only the confirmed choice is forwarded', async () => {+ act(() => useDevPorts.getState().apply('p', { ok: true, nodes: { web: [vite] } }))+ forward+ .mockResolvedValueOnce({ ok: false, reason: 'local-port-busy', message: 'busy', suggestedLocalPort: 5174 })+ .mockResolvedValueOnce({ ok: true, localPort: 5174, url: 'http://localhost:5174', reused: false })+ render(true)+ act(() => chip()!.click())+ act(() => menuItem('Open :5173').click())+ await flush()+ expect(opened).toEqual([])+ const confirm = [...document.body.querySelectorAll('button')].find((b) => b.textContent === 'Use port 5174')+ expect(confirm).toBeTruthy()+ act(() => confirm!.click())+ await flush()+ expect(forward).toHaveBeenLastCalledWith({ projectId: 'p', nodeId: 'web', port: 5173, localPort: 5174 })+ expect(opened).toEqual(['http://localhost:5174'])+ })++ it('a privileged port is asked about before it is forwarded', async () => {+ const http = { port: 80, addresses: ['0.0.0.0'], command: 'nginx', ephemeral: false }+ act(() => useDevPorts.getState().apply('p', { ok: true, nodes: { web: [http] } }))+ forward+ .mockResolvedValueOnce({ ok: false, reason: 'privileged', message: 'Port 80 is a privileged port (below 1024).' })+ .mockResolvedValueOnce({ ok: true, localPort: 80, url: 'http://localhost:80', reused: false })+ render(true)+ act(() => chip()!.click())+ act(() => menuItem('Open :80').click())+ await flush()+ const confirm = [...document.body.querySelectorAll('button')].find((b) => b.textContent === 'Forward anyway')+ act(() => confirm!.click())+ await flush()+ expect(forward).toHaveBeenLastCalledWith({ projectId: 'p', nodeId: 'web', port: 80, allowPrivileged: true })+ })+})diff --git a/src/renderer/components/PortsChip.tsx b/src/renderer/components/PortsChip.tsxnew file mode 100644index 000000000..976cdb180--- /dev/null+++ b/src/renderer/components/PortsChip.tsx@@ -0,0 +1,195 @@+import { memo, useCallback, useState } from 'react'+import {+ devPortUrl,+ forwardRefusalText,+ type DevPortForwardRequest,+ type DevPortForwardResult+} from '@shared/dev-ports'+import { devPortsSig, parseDevPortsSig, portRowLabel, portsChipLabel, type PortRow } from '../lib/devPorts'+import { scanDevPorts, useDevPorts } from '../state/devPorts'+import { sessionForProject } from '../session/session'+import { ContextMenu, type MenuItem } from './ContextMenu'+import { ConfirmDialog } from './ConfirmDialog'++function toast(message: string): void {+ window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message } }))+}++interface Pending {+ message: string+ confirmLabel: string+ retry: Partial<DevPortForwardRequest>+ port: number+}++/**+ * The dev-server ports a node's session is listening on (CLAUDE.md → Dev-server ports), drawn by+ * the canvas node header AND the kanban card modal — one component, so the two views of one+ * session cannot disagree. Absent when the session listens on no (non-ephemeral) port.+ *+ * A row opens the port in a browser node. On an SSH project it first forwards the SAME port over+ * the project's master, so `http://localhost:<port>` — the URL the tool itself printed — reaches the+ * host. A local port that is taken, or a privileged one, is never forwarded silently: the person+ * is asked, and a different local port is only ever their explicit choice.+ */+export const PortsChip = memo(function PortsChip({+ nodeId,+ projectId,+ remote,+ onOpenUrl,+ menuZIndex = 70+}: {+ nodeId: string+ projectId: string+ /** The project is an SSH project: its ports are on the host and must be forwarded. */+ remote: boolean+ onOpenUrl: (url: string) => void+ menuZIndex?: number+}): React.JSX.Element | null {+ const sig = useDevPorts((s) => {+ const p = s.byProject[projectId]+ return devPortsSig(p?.nodes[nodeId], p?.forwards.filter((f) => f.nodeId === nodeId))+ })+ const [menu, setMenu] = useState<{ x: number; y: number } | null>(null)+ const [pending, setPending] = useState<Pending | null>(null)++ const forward = useCallback(+ async (req: DevPortForwardRequest): Promise<void> => {+ let result: DevPortForwardResult+ try {+ result = await sessionForProject(projectId).api.devPorts.forward(req)+ } catch {+ result = { ok: false, reason: 'forward-failed', message: forwardRefusalText('forward-failed', req.port) }+ }+ if (result.ok) {+ useDevPorts.getState().noteForward(projectId, { nodeId, remotePort: req.port, localPort: result.localPort })+ onOpenUrl(result.url)+ return+ }+ if (result.reason === 'privileged') {+ setPending({+ port: req.port,+ message: `${result.message} Forward it to this computer anyway? Binding a port below 1024 may need administrator rights here.`,+ confirmLabel: 'Forward anyway',+ retry: { ...req, allowPrivileged: true }+ })+ return+ }+ if (result.reason === 'local-port-busy' && result.suggestedLocalPort !== undefined) {+ const alt = result.suggestedLocalPort+ setPending({+ port: req.port,+ message:+ `${result.message} Forward it to local port ${alt} instead? ` ++ `Links the tool prints (http://localhost:${req.port}) will not reach it — use the browser node this opens.`,+ confirmLabel: `Use port ${alt}`,+ retry: { ...req, localPort: alt }+ })+ return+ }+ if (result.reason === 'not-listening') void scanDevPorts(projectId, remote, 'user')+ toast(result.message)+ },+ [nodeId, onOpenUrl, projectId, remote]+ )++ const open = useCallback(+ (row: PortRow): void => {+ if (!remote) {+ onOpenUrl(devPortUrl(row.port))+ return+ }+ void forward({ projectId, nodeId, port: row.port })+ },+ [forward, nodeId, onOpenUrl, projectId, remote]+ )++ const rows = parseDevPortsSig(sig)+ const label = portsChipLabel(rows.map((r) => ({ port: r.port, ephemeral: r.ephemeral, addresses: [], command: r.command })))+ if (!label && !pending) return null++ const rowItems = (row: PortRow): MenuItem[] => {+ const items: MenuItem[] = [+ {+ label: `Open ${portRowLabel(row)}`,+ hint: remote+ ? row.forwardedTo !== undefined+ ? `Forwarded to localhost:${row.forwardedTo} on this computer — open it in a browser node`+ : `Forward port ${row.port} from the server to the same port here, then open it in a browser node`+ : `Open http://localhost:${row.port} in a browser node`,+ onClick: () => open(row)+ }+ ]+ if (remote && row.forwardedTo !== undefined) {+ const localPort = row.forwardedTo+ items.push({+ label: `Stop forwarding :${row.port}`,+ hint: `Close localhost:${localPort} on this computer`,+ onClick: () => {+ void sessionForProject(projectId)+ .api.devPorts.unforward({ projectId, localPort })+ .then(() => useDevPorts.getState().dropForward(projectId, localPort))+ }+ })+ }+ return items+ }+ const primary = rows.filter((r) => !r.ephemeral)+ const other = rows.filter((r) => r.ephemeral)+ const items: MenuItem[] = [+ { type: 'label', label: remote ? 'Listening on the server' : 'Listening in this session' },+ ...primary.flatMap(rowItems)+ ]+ if (other.length > 0) {+ items.push({+ type: 'submenu',+ label: `Other ports (${other.length})`,+ children: other.flatMap(rowItems)+ })+ }++ const stop = (e: React.SyntheticEvent): void => e.stopPropagation()+ return (+ // Inside a draggable header and a clickable card: every event stops here (TeamProgressChip).+ <span+ className="ports-chip-wrap"+ onClick={stop}+ onDoubleClick={stop}+ onMouseDown={stop}+ onPointerDown={stop}+ onContextMenu={stop}+ onKeyDown={stop}+ >+ {label && (+ <button+ type="button"+ className="ports-chip nodrag"+ title={remote ? 'Dev servers listening on the server — click to forward and open' : 'Dev servers listening in this session — click to open'}+ aria-label={`Listening ports: ${label}`}+ aria-haspopup="menu"+ aria-expanded={!!menu}+ onClick={(e) => {+ const r = e.currentTarget.getBoundingClientRect()+ if (!menu) void scanDevPorts(projectId, remote, 'user')+ setMenu((cur) => (cur ? null : { x: r.left, y: r.bottom + 4 }))+ }}+ >+ {label}+ </button>+ )}+ {menu && <ContextMenu x={menu.x} y={menu.y} zIndex={menuZIndex} scroll items={items} onClose={() => setMenu(null)} />}+ {pending && (+ <ConfirmDialog+ message={pending.message}+ confirmLabel={pending.confirmLabel}+ onCancel={() => setPending(null)}+ onConfirm={() => {+ const retry = pending.retry+ setPending(null)+ void forward({ projectId, nodeId, port: pending.port, ...retry })+ }}+ />+ )}+ </span>+ )+})diff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsxindex 517433c3e..2dee7f581 100644--- a/src/renderer/components/kanban/CardModal.tsx+++ b/src/renderer/components/kanban/CardModal.tsx@@ -21,6 +21,8 @@ import { isRemoteSessionNode } from '@shared/worktree'import { AccountChip, useAccountChip } from '../AccountChip'import { IssueRefChip } from '../IssueRefChip'import { TeamProgressChip } from '../TeamProgressChip'+import { PortsChip } from '../PortsChip'+import { useProjects } from '../../state/projects'import type { TeamStation } from '../../lib/teamProgress'import { sessionNameRepeatsTitle } from '../../lib/cardRedundancy'import type { IssueRef } from '@shared/github-issue-ref'@@ -73,6 +75,9 @@ interface CardModalProps {board: ProjectKanbanonChangeBoard: (next: ProjectKanban) => voidonClose: () => void+ /** The card's project, when its node is on the LIVE canvas (the active project): the Ports chip+ * is drawn only then, because "Open in browser node" places the page beside the node there. */+ portsProjectId?: string/** Secondary action: close the modal, switch to canvas, focus the node. */onOpenCanvas: () => void/** Rename funnel (same as the sidebar's). */@@ -100,7 +105,7 @@ interface CardModalProps {* canvas under it) stay mounted. Terminal cards carry the node header's actions too:* search / dictate / AI-name / the ⌘M view — ChatPanel or the output markdown, the same face the* canvas node shows (the node itself is hidden under the board). */-export function CardModal({ session, columnTitle, board, onChangeBoard, onClose, onOpenCanvas, onRename, onEditSticky, onBrowserNav, onSetIcon, onOpenIssue, mentionables, team, onTravel }: CardModalProps) {+export function CardModal({ session, columnTitle, board, onChangeBoard, onClose, portsProjectId, onOpenCanvas, onRename, onEditSticky, onBrowserNav, onSetIcon, onOpenIssue, mentionables, team, onTravel }: CardModalProps) {const { api } = useSession()const idRef = useRef<string>()if (!idRef.current) idRef.current = nextDialogId()@@ -124,6 +129,7 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,// and the canvas node header use). The card carries it on its detail line; the modal, which// hides the node, carries it here so the session's name is never two views away.const sessionName = useAgentStatus((st) => st.byId[session.id]?.session)+ const portsRemote = useProjects((s) => !!(portsProjectId && s.getProject(portsProjectId)?.ssh))const accountChip = useAccountChip(session.spawn.accountId, observedAccount)const [naming, setNaming] = useState(false)// Comments & activity panel: OPEN by default in the modal; the header 💬 collapses it. The@@ -373,6 +379,19 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,<span className="kanban-modal__column">{columnTitle ?? 'Ungrouped'}</span>{isTerminal && onOpenIssue && <IssueRefChip issueRef={session.issueRef} onOpen={onOpenIssue} />}{isTerminal && team && team.length > 0 && onTravel && <TeamProgressChip stations={team} onTravel={onTravel} />}+ {/* The same Ports chip as the canvas node header. Opening a port places the browser node+ beside this node ON THE CANVAS, so the modal hands over to the canvas to show it. */}+ {isTerminal && portsProjectId && (+ <PortsChip+ nodeId={session.id}+ projectId={portsProjectId}+ remote={portsRemote}+ onOpenUrl={(url) => {+ window.dispatchEvent(new CustomEvent('nodeterm:open-url-node', { detail: { url, sourceNodeId: session.id } }))+ onOpenCanvas()+ }}+ />+ )}{isTerminal && sessionName && !sessionNameRepeatsTitle(sessionName, session.title) && (<span className="kanban-card__session kanban-modal__session" title={sessionName}>{sessionName}diff --git a/src/renderer/components/kanban/GlobalKanbanView.tsx b/src/renderer/components/kanban/GlobalKanbanView.tsxindex b6a383fb3..7a3ae6110 100644--- a/src/renderer/components/kanban/GlobalKanbanView.tsx+++ b/src/renderer/components/kanban/GlobalKanbanView.tsx@@ -88,6 +88,7 @@ const Swimlane = memo(function Swimlane({const [cardMenu, setCardMenu] = useState<{ x: number; y: number; nodeId: string } | null>(null)const [labelFilter, setLabelFilter] = useState<string[]>([])const [collapsed, setCollapsed] = useState(false)+ const activePortsProjectId = useProjects((s) => s.activeProjectId)const customAgents = useSettings((s) => s.settings.customAgents)const disabledAgents = useSettings((s) => s.settings.disabledAgents)@@ -304,6 +305,7 @@ const Swimlane = memo(function Swimlane({board={board}onChangeBoard={commit}onClose={() => setModalNodeId(null)}+ portsProjectId={projectId === activePortsProjectId ? projectId : undefined}onOpenCanvas={() => { setModalNodeId(null); onOpenNode(modalNodeId, projectId) }}onRename={(t) => onRenameNode(modalNodeId, t)}onEditSticky={(t) => onEditSticky(projectId, modalNodeId, t)}diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsxindex 69d9b4a46..f0998200e 100644--- a/src/renderer/components/kanban/KanbanView.tsx+++ b/src/renderer/components/kanban/KanbanView.tsx@@ -1245,6 +1245,7 @@ export const KanbanView = memo(function KanbanView({board={board}onChangeBoard={commit}onClose={() => setModalNodeId(null)}+ portsProjectId={projectId}onOpenCanvas={() => {setModalNodeId(null)onOpenNode(modalNodeId)diff --git a/src/renderer/lib/devPorts.test.ts b/src/renderer/lib/devPorts.test.tsnew file mode 100644index 000000000..544efb063--- /dev/null+++ b/src/renderer/lib/devPorts.test.ts@@ -0,0 +1,46 @@+import { describe, it, expect } from 'vitest'+import {+ DEV_PORTS_MIN_GAP_MS,+ devPortsSig,+ parseDevPortsSig,+ pollIntervalMs,+ portRowLabel,+ portsChipLabel,+ shouldScan+} from './devPorts'++const p = (port: number, ephemeral = false, command = 'node') => ({ port, addresses: ['127.0.0.1'], command, ephemeral })++describe('cadence', () => {+ it('an explicit refresh always runs; automatic scans keep their distance', () => {+ expect(shouldScan('user', 1000, 999)).toBe(true)+ expect(shouldScan('poll', 1000, undefined)).toBe(true)+ expect(shouldScan('hook', 1000 + DEV_PORTS_MIN_GAP_MS - 1, 1000)).toBe(false)+ expect(shouldScan('focus', 1000 + DEV_PORTS_MIN_GAP_MS, 1000)).toBe(true)+ })+ it('an SSH host is polled more slowly than this machine', () => {+ expect(pollIntervalMs(true)).toBeGreaterThan(pollIntervalMs(false))+ })+})++describe('chip + rows', () => {+ it('counts only non-ephemeral ports', () => {+ expect(portsChipLabel([])).toBeNull()+ expect(portsChipLabel([p(41000, true)])).toBeNull()+ expect(portsChipLabel([p(5173), p(41000, true)])).toBe(':5173')+ expect(portsChipLabel([p(3000), p(5173)])).toBe('2 ports')+ })+ it('the signature round-trips and carries the forward', () => {+ const sig = devPortsSig([p(5173), p(41000, true, 'we|ird:cmd')], [{ nodeId: 'n', remotePort: 5173, localPort: 5174 }])+ expect(parseDevPortsSig(sig)).toEqual([+ { port: 5173, ephemeral: false, command: 'node', forwardedTo: 5174 },+ { port: 41000, ephemeral: true, command: 'we|ird:cmd' }+ ])+ expect(devPortsSig(undefined, undefined)).toBe('')+ })+ it('names a re-mapped forward, and only then', () => {+ expect(portRowLabel({ port: 5173, ephemeral: false, command: 'node' })).toBe(':5173 · node')+ expect(portRowLabel({ port: 5173, ephemeral: false, command: 'node', forwardedTo: 5173 })).toBe(':5173 · node')+ expect(portRowLabel({ port: 5173, ephemeral: false, command: '', forwardedTo: 5174 })).toBe(':5173 → localhost:5174')+ })+})diff --git a/src/renderer/lib/devPorts.ts b/src/renderer/lib/devPorts.tsnew file mode 100644index 000000000..d023e2fe0--- /dev/null+++ b/src/renderer/lib/devPorts.ts@@ -0,0 +1,85 @@+// Pure decisions for the dev-server Ports chip and its scanner (CLAUDE.md → Dev-server ports).+import type { DevPort, DevPortForward } from '@shared/dev-ports'++/**+ * Cadence. A scan is one `ps` + one `ss`/`lsof` on the machine the project runs on — cheap locally,+ * an exec over the ControlMaster on an SSH host — so it runs only while someone can see the result:+ * - when the project comes on screen and when the window regains focus;+ * - a few seconds after the project's agents report activity (a dev server is usually started by+ * an agent's tool call, and a hook event is the cheapest "something changed" there is);+ * - on a slow timer ONLY while the window is focused and the project is on screen — a server+ * started by hand in a plain terminal fires no hook at all;+ * - on demand, when the person opens the chip's menu.+ * Never while the window is in the background: nobody is looking at a chip then.+ */+export const DEV_PORTS_POLL_LOCAL_MS = 30_000+export const DEV_PORTS_POLL_SSH_MS = 60_000+export const DEV_PORTS_HOOK_DEBOUNCE_MS = 4_000+/** No automatic scan closer than this to the previous one; an explicit refresh ignores it. */+export const DEV_PORTS_MIN_GAP_MS = 10_000++export type ScanReason = 'mount' | 'focus' | 'hook' | 'poll' | 'user'++export function shouldScan(reason: ScanReason, now: number, lastStartedAt: number | undefined): boolean {+ if (reason === 'user') return true+ if (lastStartedAt === undefined) return true+ return now - lastStartedAt >= DEV_PORTS_MIN_GAP_MS+}++export function pollIntervalMs(remote: boolean): number {+ return remote ? DEV_PORTS_POLL_SSH_MS : DEV_PORTS_POLL_LOCAL_MS+}++/** The ports the chip counts: not the ephemeral range (see DEV_PORT_EPHEMERAL_MIN). */+export function primaryPorts(ports: readonly DevPort[]): DevPort[] {+ return ports.filter((p) => !p.ephemeral)+}++/** `:5173` for one port, `3 ports` for several, null for none (no chip). */+export function portsChipLabel(ports: readonly DevPort[]): string | null {+ const primary = primaryPorts(ports)+ if (primary.length === 0) return null+ if (primary.length === 1) return `:${primary[0].port}`+ return `${primary.length} ports`+}++/**+ * A primitive signature of one node's ports and forwards, for a zustand selector: the store's+ * report object is replaced on every scan, and a node header must not re-render for a scan that+ * changed nothing about it.+ */+export function devPortsSig(ports: readonly DevPort[] | undefined, forwards: readonly DevPortForward[] | undefined): string {+ if (!ports || ports.length === 0) return ''+ const fwd = new Map((forwards ?? []).map((f) => [f.remotePort, f.localPort]))+ return ports+ .map((p) => [p.port, p.ephemeral ? 'e' : 'p', encodeURIComponent(p.command), fwd.get(p.port) ?? ''].join(':'))+ .join('|')+}++export interface PortRow {+ port: number+ ephemeral: boolean+ command: string+ /** SSH only: the local port it is forwarded to, when it is. */+ forwardedTo?: number+}++export function parseDevPortsSig(sig: string): PortRow[] {+ if (!sig) return []+ return sig.split('|').map((part) => {+ const [port, kind, cmd, fwd] = part.split(':')+ return {+ port: Number(port),+ ephemeral: kind === 'e',+ command: decodeURIComponent(cmd ?? ''),+ ...(fwd ? { forwardedTo: Number(fwd) } : {})+ }+ })+}++/** The menu row's text: `:5173 · node`, plus where an SSH forward lands when it is not the same. */+export function portRowLabel(row: PortRow): string {+ const base = row.command ? `:${row.port} · ${row.command}` : `:${row.port}`+ if (row.forwardedTo !== undefined && row.forwardedTo !== row.port) return `${base} → localhost:${row.forwardedTo}`+ return base+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 93b63a57f..40380c45d 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -260,6 +260,7 @@ import { NodeColorSwatches } from '../components/NodeColorSwatches'import { AccountChip, useAccountChip } from '../components/AccountChip'import { IssueRefChip } from '../components/IssueRefChip'import { TeamProgressChip } from '../components/TeamProgressChip'+import { PortsChip } from '../components/PortsChip'import { useTeamStations } from '../state/teamStations'import { sessionNameRepeatsTitle } from '../lib/cardRedundancy'import { effectiveAccountId } from '../lib/accountChip'@@ -1770,6 +1771,7 @@ export function TerminalNode({// node (`isRemoteSessionNode` — an SSH-project terminal carries `data.ssh`/`data.sshRemoteTmux`).// The affordance is absent, not merely refused on click.const sshProject = useProjects((s) => !!s.projects.find((p) => p.id === s.activeProjectId)?.ssh)+ const portsProjectId = useProjects((s) => s.activeProjectId)// The project's SSH endpoint, as two primitives: the project object is rebuilt on every node// serialization, so selecting `ssh.server` itself would re-render this node on each canvas edit.const projectSshHost = useProjects((s) => s.getProject(s.activeProjectId)?.ssh?.server.host)@@ -5918,6 +5920,18 @@ export function TerminalNode({)}}/>+ {/* Dev servers this session listens on (CLAUDE.md → Dev-server ports). On an SSH project a+ row forwards the SAME port over the project's master before opening it. The card modal+ draws the same component. */}+ <PortsChip+ nodeId={id}+ projectId={portsProjectId}+ remote={sshProject}+ onOpenUrl={(url) =>+ window.dispatchEvent(new CustomEvent('nodeterm:open-url-node', { detail: { url, sourceNodeId: id } }))+ }+ menuZIndex={60}+ />{/* The stations this session opened, and how far along they are — the same ring its boardcard and card modal draw (lib/teamProgress). A row travels to that station. */}{team && <TeamProgressChip stations={team} onTravel={travelToStation} menuZIndex={60} />}diff --git a/src/renderer/state/devPorts.test.ts b/src/renderer/state/devPorts.test.tsnew file mode 100644index 000000000..cafdb4ed5--- /dev/null+++ b/src/renderer/state/devPorts.test.ts@@ -0,0 +1,49 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import type { DevPortsReport } from '@shared/dev-ports'++const scan = vi.fn<(q: unknown) => Promise<DevPortsReport>>()+let source = 'local'+vi.mock('../session/session', () => ({ sessionForProject: () => ({ source, api: { devPorts: { scan } } }) }))+vi.mock('../bridge/runtime', () => ({ isBrowserRuntime: () => false }))++const { useDevPorts, scanDevPorts, resetDevPortScans } = await import('./devPorts')+const vite = { port: 5173, addresses: ['127.0.0.1'], command: 'node', ephemeral: false }++beforeEach(() => {+ resetDevPortScans()+ scan.mockReset()+ source = 'local'+})++describe('devPorts store', () => {+ it('a failed scan keeps the last good ports but is marked not-ok', () => {+ const s = useDevPorts.getState()+ s.apply('p', { ok: true, nodes: { web: [vite] } })+ s.apply('p', { ok: false, reason: 'unreachable', nodes: {} })+ expect(useDevPorts.getState().byProject.p).toEqual({ ok: false, nodes: { web: [vite] }, forwards: [] })+ })++ it('an automatic scan inside the gap is skipped; an explicit one is not', async () => {+ scan.mockResolvedValue({ ok: true, nodes: {} })+ await scanDevPorts('p', false, 'mount')+ await scanDevPorts('p', false, 'poll')+ expect(scan).toHaveBeenCalledTimes(1)+ await scanDevPorts('p', false, 'user')+ expect(scan).toHaveBeenCalledTimes(2)+ expect(scan).toHaveBeenLastCalledWith({ projectId: 'p', remote: false })+ })++ it('an unsupported core is not asked again this run, and leaves nothing behind', async () => {+ scan.mockResolvedValue({ ok: false, reason: 'unsupported', nodes: {} })+ await scanDevPorts('p', false, 'user')+ await scanDevPorts('p', false, 'user')+ expect(scan).toHaveBeenCalledTimes(1)+ expect(useDevPorts.getState().byProject.p).toBeUndefined()+ })++ it('a relay tab never scans (its sessions live on the host)', async () => {+ source = 'relay'+ await scanDevPorts('p', false, 'user')+ expect(scan).not.toHaveBeenCalled()+ })+})diff --git a/src/renderer/state/devPorts.ts b/src/renderer/state/devPorts.tsnew file mode 100644index 000000000..b168d8262--- /dev/null+++ b/src/renderer/state/devPorts.ts@@ -0,0 +1,95 @@+// Transient per-project record of the last dev-port scan (CLAUDE.md → Dev-server ports). Never+// persisted: a listening port is a fact about a process that may be gone by the next launch.+import { create } from 'zustand'+import type { DevPortForward, DevPortsReport } from '@shared/dev-ports'+import { shouldScan, type ScanReason } from '../lib/devPorts'+import { sessionForProject } from '../session/session'+import { isBrowserRuntime } from '../bridge/runtime'++export interface ProjectPorts {+ ok: boolean+ nodes: DevPortsReport['nodes']+ forwards: DevPortForward[]+}++interface DevPortsState {+ byProject: Record<string, ProjectPorts>+ apply(projectId: string, report: DevPortsReport): void+ noteForward(projectId: string, fwd: DevPortForward): void+ dropForward(projectId: string, localPort: number): void+}++const EMPTY: DevPortForward[] = []++export const useDevPorts = create<DevPortsState>((set) => ({+ byProject: {},+ apply: (projectId, report) =>+ set((s) => {+ const prev = s.byProject[projectId]+ // A FAILED scan keeps the last good nodes: a dead master for a moment is not "the servers+ // stopped". It is still recorded as not-ok so nothing new is offered on its strength.+ const next: ProjectPorts = report.ok+ ? { ok: true, nodes: report.nodes, forwards: report.forwards ?? EMPTY }+ : { ok: false, nodes: prev?.nodes ?? {}, forwards: prev?.forwards ?? EMPTY }+ return { byProject: { ...s.byProject, [projectId]: next } }+ }),+ noteForward: (projectId, fwd) =>+ set((s) => {+ const prev = s.byProject[projectId] ?? { ok: true, nodes: {}, forwards: EMPTY }+ const forwards = [...prev.forwards.filter((f) => f.localPort !== fwd.localPort), fwd]+ return { byProject: { ...s.byProject, [projectId]: { ...prev, forwards } } }+ }),+ dropForward: (projectId, localPort) =>+ set((s) => {+ const prev = s.byProject[projectId]+ if (!prev) return s+ const forwards = prev.forwards.filter((f) => f.localPort !== localPort)+ return { byProject: { ...s.byProject, [projectId]: { ...prev, forwards } } }+ })+}))++/** Can this project's ports be shown at all from this window? Desktop, local session only. */+export function devPortsAvailable(projectId: string): boolean {+ if (!projectId || isBrowserRuntime()) return false+ return sessionForProject(projectId).source === 'local'+}++const lastStarted = new Map<string, number>()+const inFlight = new Map<string, Promise<void>>()+/** Projects whose core answered `unsupported` (a Windows core): not asked again this run. */+const unsupported = new Set<string>()++/** Scan one project, subject to the cadence rules (`shouldScan`). Never rejects. */+export function scanDevPorts(projectId: string, remote: boolean, reason: ScanReason): Promise<void> {+ if (!devPortsAvailable(projectId) || unsupported.has(projectId)) return Promise.resolve()+ const pending = inFlight.get(projectId)+ if (pending) return pending+ const now = Date.now()+ if (!shouldScan(reason, now, lastStarted.get(projectId))) return Promise.resolve()+ lastStarted.set(projectId, now)+ const api = sessionForProject(projectId).api+ const p = api.devPorts+ .scan({ projectId, remote })+ .then((report) => {+ // `unsupported` is a property of the surface, not news: leave nothing behind for it.+ if (report.reason === 'unsupported') {+ unsupported.add(projectId)+ return+ }+ useDevPorts.getState().apply(projectId, report)+ })+ .catch(() => {+ useDevPorts.getState().apply(projectId, { ok: false, reason: 'unreachable', nodes: {} })+ })+ .finally(() => inFlight.delete(projectId))+ inFlight.set(projectId, p)+ return p+}++/** Test seam. */+export function resetDevPortScans(): void {+ lastStarted.clear()+ inFlight.clear()+ unsupported.clear()+ useDevPorts.setState({ byProject: {} })+}diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 3a38df8ad..3d109e9c6 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -11201,6 +11201,31 @@ button.pull-checks__name {color: var(--text);background: rgba(var(--tint-rgb), 0.08);}+/* Dev-server ports a node's session listens on (components/PortsChip) — canvas node header and+ the card modal header alike. Same quiet outline as `#N`; the port is monospace so `:5173` reads+ as an address, not a count. */+.ports-chip-wrap {+ display: inline-flex;+ flex: 0 0 auto;+}+.ports-chip {+ margin-left: 6px;+ padding: 0 6px;+ flex: 0 0 auto;+ border: 1px solid rgba(var(--tint-rgb), 0.16);+ border-radius: 6px;+ background: transparent;+ color: var(--muted);+ font: inherit;+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);+ font-size: 11px;+ line-height: 1.5;+ cursor: pointer;+}+.ports-chip:hover {+ color: var(--text);+ background: rgba(var(--tint-rgb), 0.08);+}/* Team progress — "N of M done" over the stations a session opened (lib/teamProgress). Onecomponent on the board card, the card modal header and the canvas node header. The arc is thedone fraction; the dot says the strongest thing a station is asking for. */diff --git a/src/shared/dev-ports.ts b/src/shared/dev-ports.tsnew file mode 100644index 000000000..7eca0c4ec--- /dev/null+++ b/src/shared/dev-ports.ts@@ -0,0 +1,122 @@+// Dev-server ports: which TCP ports a node's session is LISTENING on, and (on an SSH project) the+// same-port local forward that makes `http://localhost:<port>` on this machine reach the host.+//+// Discovery is by OWNERSHIP, never by probing: a port is reported for a node only when its+// listening socket belongs to a process in that node's tmux pane tree. Nobody else's ports are+// ever looked at, and nothing is ever connected to on the host.++/** Ports at or above this are the OS's ephemeral range (Linux starts at 32768, macOS at 49152).+ * A listener there is almost always something that asked for "any port" — a headless browser's+ * debugging endpoint, an MCP helper — rather than a dev server a person means to open, so the+ * chip does not count them. They are still listed, one level down. */+export const DEV_PORT_EPHEMERAL_MIN = 32768++export interface DevPort {+ port: number+ /** Every address the port is bound on (`127.0.0.1`, `::1`, `0.0.0.0`, `::`, or a specific one). */+ addresses: string[]+ /** The listening process's command name (basename), for the menu row. May be ''. */+ command: string+ ephemeral: boolean+}++/** A live same-port (or explicitly re-mapped) forward this app holds for an SSH project. */+export interface DevPortForward {+ nodeId: string+ remotePort: number+ localPort: number+}++export type DevPortsFailure =+ /** This machine cannot run the probe (Windows) or the surface cannot reach the core (relay tab,+ * browser). */+ | 'unsupported'+ /** The probe could not run or its answer was cut short — a dead ControlMaster, a broken tmux.+ * Never "there are no ports". */+ | 'unreachable'+ /** The host has neither `ss`, `lsof`, nor a readable `/proc/net/tcp`. */+ | 'no-listener-tool'++export interface DevPortsReport {+ ok: boolean+ reason?: DevPortsFailure+ /** node id → its listening ports, ascending. Only nodes with at least one port appear. */+ nodes: Record<string, DevPort[]>+ /** SSH scope only: the forwards this app currently holds for the project. */+ forwards?: DevPortForward[]+}++export interface DevPortsQuery {+ projectId?: string+ /** The renderer's own claim that the scope is an SSH project (OR-ed with the shell's). */+ remote?: boolean+}++export interface DevPortForwardRequest {+ projectId: string+ nodeId: string+ /** The port the node listens on, on the host. */+ port: number+ /** Only when the person explicitly chose a different local port after a `local-port-busy`. */+ localPort?: number+ /** Only after the person confirmed a privileged (< 1024) port. */+ allowPrivileged?: boolean+}++export type DevPortForwardRefusal =+ | 'unsupported'+ | 'invalid-port'+ | 'not-connected'+ | 'not-listening'+ | 'privileged'+ | 'local-port-busy'+ | 'forward-failed'++export type DevPortForwardResult =+ | { ok: true; localPort: number; url: string; reused: boolean }+ | { ok: false; reason: DevPortForwardRefusal; message: string; suggestedLocalPort?: number }++export interface DevPortsApi {+ scan(q?: DevPortsQuery): Promise<DevPortsReport>+ forward(req: DevPortForwardRequest): Promise<DevPortForwardResult>+ unforward(req: { projectId: string; localPort: number }): Promise<boolean>+}++export function isValidPort(n: unknown): n is number {+ return typeof n === 'number' && Number.isInteger(n) && n >= 1 && n <= 65535+}++/** Privileged ports: binding them locally needs root on Linux, and a same-port forward of one is+ * never made without the person saying so. */+export function isPrivilegedPort(port: number): boolean {+ return port < 1024+}++/** What the browser node opens. `localhost`, not `127.0.0.1`: it is what dev tools print, so the+ * page's own links and cookies (scoped by host) match the URL the terminal shows. */+export function devPortUrl(localPort: number): string {+ return `http://localhost:${localPort}`+}++export function forwardRefusalText(+ reason: DevPortForwardRefusal,+ port: number,+ localPort: number = port+): string {+ switch (reason) {+ case 'unsupported':+ return 'Port forwarding is not available here.'+ case 'invalid-port':+ return `${port} is not a valid port.`+ case 'not-connected':+ return 'This project is not connected to its server right now.'+ case 'not-listening':+ return `Nothing in this session is listening on port ${port} any more.`+ case 'privileged':+ return `Port ${port} is a privileged port (below 1024).`+ case 'local-port-busy':+ return `Port ${localPort} is already in use on this computer, so it cannot be forwarded to the same number.`+ case 'forward-failed':+ return `The SSH connection refused to forward port ${port}.`+ }+}diff --git a/src/shared/host-control.ts b/src/shared/host-control.tsindex 08661f079..cf5289086 100644--- a/src/shared/host-control.ts+++ b/src/shared/host-control.ts@@ -95,7 +95,12 @@ export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([IPC.agentDiscoverModels,IPC.agentGatewayCredentialStatus,IPC.agentGatewayCredentialSave,- IPC.agentGatewayCredentialClear+ IPC.agentGatewayCredentialClear,+ // Dev-server ports: a scan lists the host's listening ports, and a forward binds a port on the+ // HOST machine's loopback over one of its SSH masters. Neither is a peer's to ask for.+ IPC.devPortsScan,+ IPC.devPortsForward,+ IPC.devPortsUnforward])/** What a refused peer is told. One wording, so the two shells answer identically. */diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 6c5293abe..549138bf6 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -330,6 +330,12 @@ export const IPC = {/** The scoped machine's RAM (available/total) — the cheap read behind the system-resource* pill. Safe to poll locally; NOT polled for an SSH scope. */sessionMemoryHost: 'session-memory:host',+ /** Dev-server ports (core/dev-ports-service.ts): which TCP ports each node's session listens on+ * (ownership by process tree, one round trip per host), and the same-port SSH forward that makes+ * `http://localhost:<port>` reach an SSH project's host. Desktop only; host-only for relay peers. */+ devPortsScan: 'dev-ports:scan',+ devPortsForward: 'dev-ports:forward',+ devPortsUnforward: 'dev-ports:unforward',// Canvas wallpaper (core/wallpaper.ts): macOS stills, cached image reads, image import.wallpaperListStills: 'wallpaper:list-stills',wallpaperLoad: 'wallpaper:load',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 2e32a6b2e..e1a6a3c40 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -4035,6 +4035,7 @@ export interface NodeTerminalApi {githubControl: import('./github-issues').GitHubControlApiusage: UsageApisessionMemory: SessionMemoryApi+ devPorts: import('./dev-ports').DevPortsApiwallpaper: import('./wallpaper').WallpaperApitriggers: TriggersApicontext: ContextApi