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(windows): dev-server ports for local projects on the session host
review172c0a4d46d4
diff --git a/src/core/dev-ports-service.test.ts b/src/core/dev-ports-service.test.tsindex ae15e70d6..d81537c63 100644--- a/src/core/dev-ports-service.test.ts+++ b/src/core/dev-ports-service.test.ts@@ -118,3 +118,17 @@ describe('startDevPortsService', () => {expect((await scan({ projectId: 'ssh' })).forwards).toEqual([{ nodeId: 'web', remotePort: 5173, localPort: 5173 }])})})++describe('startDevPortsService — Windows local scan', () => {+ it('threads the session host and the platform into the local scan', async () => {+ const sessionHost = vi.fn(async () => ({ running: false, names: [], sessions: [] }))+ startDevPortsService({ tmuxBin: () => null, sessionHost, platformName: 'win32' })+ expect(await scan({ projectId: 'p' })).toEqual({ ok: true, nodes: {} })+ expect(sessionHost).toHaveBeenCalledTimes(1)+ })++ it('without a session host a Windows core stays unsupported', async () => {+ startDevPortsService({ tmuxBin: () => null, platformName: 'win32' })+ expect((await scan({ projectId: 'p' })).reason).toBe('unsupported')+ })+})diff --git a/src/core/dev-ports-service.ts b/src/core/dev-ports-service.tsindex b2dab3569..c5eb7fe7b 100644--- a/src/core/dev-ports-service.ts+++ b/src/core/dev-ports-service.ts@@ -16,6 +16,7 @@ import type {DevPortsReport} from '../shared/dev-ports'import { collectLocalDevPorts, fetchRemoteDevPorts, type RemoteDevPortsRunner } from './dev-ports'+import type { SessionHostListing } from './session-host-client'import {defaultLocalPortState,defaultLocalPortHeld,@@ -26,6 +27,10 @@ import {export interface DevPortsServiceOptions {/** The app's tmux binary for the LOCAL scan — the same resolver session memory is given. */tmuxBin: () => string | null+ /** Windows: the session host's listing — the pane tree there (`PtyManager.sessionHostListing()`). */+ sessionHost?: () => Promise<SessionHostListing | null> | undefined+ /** The platform the LOCAL scan runs on. Injectable for tests; defaults to this process's. */+ platformName?: NodeJS.Platform/** This machine's scan. Injectable for tests. */local?: () => Promise<DevPortsReport>remote?: {@@ -81,7 +86,15 @@ export function startDevPortsService(opts: DevPortsServiceOptions): {await registry.reconcile(query.projectId, report)return { ...report, forwards: registry.list(query.projectId) }}- return (opts.local ?? (() => collectLocalDevPorts({ tmuxBin: opts.tmuxBin })))()+ return (+ opts.local ??+ (() =>+ collectLocalDevPorts({+ tmuxBin: opts.tmuxBin,+ ...(opts.sessionHost ? { sessionHost: opts.sessionHost } : {}),+ ...(opts.platformName ? { platformName: opts.platformName } : {})+ }))+ )()})platform().handle(diff --git a/src/core/dev-ports-win32.test.ts b/src/core/dev-ports-win32.test.tsnew file mode 100644index 000000000..e2789c0d7--- /dev/null+++ b/src/core/dev-ports-win32.test.ts@@ -0,0 +1,183 @@+// The Windows leg of dev-server port discovery: the session host's panes + one PowerShell call,+// joined by the same `assembleDevPorts`. Runs on every CI host — the platform, the host listing and+// the PowerShell output are all injected.+import { describe, it, expect, vi } from 'vitest'+import {+ collectLocalDevPorts,+ collectWin32DevPorts,+ parseNetstatListeners,+ parseWin32DevPortsProbe,+ parseWin32ProcRows,+ parseWinNetTcpListeners,+ WIN32_DEV_PORTS_SCRIPT+} from './dev-ports'+import { powershellArgs, POWERSHELL_EXE } from './win32-powershell'+import type { SessionHostListing } from './session-host-client'++const PROCS_JSON = JSON.stringify([+ { ProcessId: 4000, ParentProcessId: 900, Name: 'pwsh.exe' },+ { ProcessId: 4100, ParentProcessId: 4000, Name: 'node.exe' },+ { ProcessId: 4200, ParentProcessId: 4100, Name: 'esbuild.exe' },+ { ProcessId: 7000, ParentProcessId: 1, Name: 'svchost.exe' }+])++const NETTCP_JSON = JSON.stringify([+ { LocalAddress: '127.0.0.1', LocalPort: 5173, OwningProcess: 4200 },+ { LocalAddress: '::1', LocalPort: 5173, OwningProcess: 4200 },+ { LocalAddress: '0.0.0.0', LocalPort: 135, OwningProcess: 7000 },+ { LocalAddress: '::', LocalPort: 50123, OwningProcess: 4100 }+])++const NETSTAT = [+ '',+ 'Active Connections',+ '',+ ' Proto Local Address Foreign Address State PID',+ ' TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 7000',+ ' TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 4200',+ ' TCP 127.0.0.1:5173 127.0.0.1:61000 ESTABLISHED 4200',+ ' TCP [::]:3000 [::]:0 ABHÖREN 4100',+ ' TCP [::1]:5173 [::]:0 LISTENING 4200',+ ' UDP 0.0.0.0:5353 *:* 1234'+].join('\r\n')++const probe = (via: 'nettcp' | 'netstat', body: string): string =>+ ['##PROCS', PROCS_JSON, '##LISTEN', `##VIA ${via}`, body, '##END', ''].join('\r\n')++const listing = (over: Partial<SessionHostListing> = {}): SessionHostListing => ({+ running: true,+ names: ['nt-web'],+ sessions: [{ name: 'nt-web', pid: 4000, subscribers: 1, lastOutputMs: 1, createdMs: 1, generation: 'gen-aaaaaaaa' }],+ ...over+})+const PANES = [{ session: 'nt-web', panePid: 4000, command: '' }]++describe('Windows parsers', () => {+ it('Win32_Process rows: basename without .exe; a single object is one row; bad JSON is null', () => {+ expect(parseWin32ProcRows(PROCS_JSON)?.map((p) => p.command)).toEqual(['pwsh', 'node', 'esbuild', 'svchost'])+ expect(parseWin32ProcRows('{"ProcessId":1,"ParentProcessId":0,"Name":"System"}')).toEqual([+ { pid: 1, ppid: 0, command: 'System' }+ ])+ expect(parseWin32ProcRows('nope')).toBeNull()+ })++ it('Get-NetTCPConnection: owner is the kernel pid field; IPv6 wildcard normalized', () => {+ expect(parseWinNetTcpListeners(NETTCP_JSON)).toEqual([+ { owners: [{ pid: 4200, command: '' }], address: '127.0.0.1', port: 5173 },+ { owners: [{ pid: 4200, command: '' }], address: '::1', port: 5173 },+ { owners: [{ pid: 7000, command: '' }], address: '0.0.0.0', port: 135 },+ { owners: [{ pid: 4100, command: '' }], address: '::', port: 50123 }+ ])+ expect(parseWinNetTcpListeners('{"LocalAddress":"::ffff:127.0.0.1","LocalPort":8080,"OwningProcess":5}')).toEqual([+ { owners: [{ pid: 5, command: '' }], address: '127.0.0.1', port: 8080 }+ ])+ expect(parseWinNetTcpListeners('')).toEqual([])+ expect(parseWinNetTcpListeners('{oops')).toBeNull()+ })++ it('netstat -ano: listeners by foreign port 0, whatever language the state column is in', () => {+ expect(parseNetstatListeners(NETSTAT)).toEqual([+ { owners: [{ pid: 7000, command: '' }], address: '0.0.0.0', port: 135 },+ { owners: [{ pid: 4200, command: '' }], address: '127.0.0.1', port: 5173 },+ { owners: [{ pid: 4100, command: '' }], address: '::', port: 3000 },+ { owners: [{ pid: 4200, command: '' }], address: '::1', port: 5173 }+ ])+ })+})++describe('parseWin32DevPortsProbe', () => {+ it('attributes a listener two processes below the pane, and nobody else\'s', () => {+ const r = parseWin32DevPortsProbe(probe('nettcp', NETTCP_JSON), PANES)+ expect(r.ok).toBe(true)+ expect(Object.keys(r.nodes)).toEqual(['web'])+ expect(r.nodes.web).toEqual([+ { port: 5173, addresses: ['127.0.0.1', '::1'], command: 'esbuild', ephemeral: false },+ { port: 50123, addresses: ['::'], command: 'node', ephemeral: true }+ ])+ })++ it('the netstat fallback feeds the same join', () => {+ const r = parseWin32DevPortsProbe(probe('netstat', NETSTAT), PANES)+ expect(r.nodes.web?.map((p) => p.port)).toEqual([3000, 5173])+ })++ it('every malformed stream is unreachable, never "no ports"', () => {+ const unreachable = { ok: false, reason: 'unreachable', nodes: {} }+ expect(parseWin32DevPortsProbe('', PANES)).toEqual(unreachable)+ expect(parseWin32DevPortsProbe(probe('nettcp', NETTCP_JSON).replace('##END', ''), PANES)).toEqual(unreachable)+ expect(parseWin32DevPortsProbe(probe('nettcp', '{bad'), PANES)).toEqual(unreachable)+ expect(parseWin32DevPortsProbe(probe('nettcp', NETTCP_JSON).replace(PROCS_JSON, ''), PANES)).toEqual(unreachable)+ expect(parseWin32DevPortsProbe(probe('nettcp', NETTCP_JSON).replace('##VIA nettcp', '##VIA what'), PANES)).toEqual(+ unreachable+ )+ })++ it('the script is fenced with the same markers and carries no double quote (one argv element)', () => {+ for (const marker of ["'##PROCS'", "'##LISTEN'", "'##VIA nettcp'", "'##VIA netstat'", "'##END'"]) {+ expect(WIN32_DEV_PORTS_SCRIPT).toContain(marker)+ }+ expect(WIN32_DEV_PORTS_SCRIPT).not.toContain('"')+ expect(WIN32_DEV_PORTS_SCRIPT).toContain('exit 1')+ })+})++describe('collectWin32DevPorts / collectLocalDevPorts(win32)', () => {+ it('runs ONE PowerShell call through the seam and joins the host pane', async () => {+ const calls: Array<{ bin: string; args: string[] }> = []+ const r = await collectLocalDevPorts({+ tmuxBin: () => null,+ platformName: 'win32',+ sessionHost: async () => listing(),+ execWin: async (bin, args) => {+ calls.push({ bin, args })+ return probe('nettcp', NETTCP_JSON)+ }+ })+ expect(calls).toEqual([{ bin: POWERSHELL_EXE, args: powershellArgs(WIN32_DEV_PORTS_SCRIPT) }])+ expect(r.ok).toBe(true)+ expect(r.nodes.web?.[0].port).toBe(5173)+ })++ it('no session host as the backend is unsupported, and runs nothing', async () => {+ const execWin = vi.fn(async () => '')+ const r = await collectLocalDevPorts({ tmuxBin: () => null, platformName: 'win32', sessionHost: () => undefined, execWin })+ expect(r).toEqual({ ok: false, reason: 'unsupported', nodes: {} })+ expect(execWin).not.toHaveBeenCalled()+ })++ it('a failed host read, or an older host without pids, is unreachable — never unsupported', async () => {+ const execWin = vi.fn(async () => probe('nettcp', NETTCP_JSON))+ expect((await collectWin32DevPorts(Promise.resolve(null), execWin)).reason).toBe('unreachable')+ expect((await collectWin32DevPorts(Promise.reject(new Error('pipe')), execWin)).reason).toBe('unreachable')+ expect((await collectWin32DevPorts(Promise.resolve(listing({ sessions: null })), execWin)).reason).toBe('unreachable')+ expect(execWin).not.toHaveBeenCalled()+ })++ it('a non-zero PowerShell exit (the exec rejects) is unreachable', async () => {+ const r = await collectWin32DevPorts(Promise.resolve(listing()), async () => {+ throw new Error('Command failed: exit 1')+ })+ expect(r).toEqual({ ok: false, reason: 'unreachable', nodes: {} })+ })++ it('no host running, or no nt- session, is an empty answer that spawns no PowerShell', async () => {+ const execWin = vi.fn(async () => '')+ expect(await collectWin32DevPorts(Promise.resolve({ running: false, names: [], sessions: [] }), execWin)).toEqual({+ ok: true,+ nodes: {}+ })+ expect(await collectWin32DevPorts(Promise.resolve(listing({ names: [], sessions: [] })), execWin)).toEqual({+ ok: true,+ nodes: {}+ })+ expect(execWin).not.toHaveBeenCalled()+ })++ it('a POSIX platform never takes the Windows leg', async () => {+ const sessionHost = vi.fn(async () => listing())+ const exec = vi.fn(async () => '')+ await collectLocalDevPorts({ tmuxBin: () => '/usr/bin/tmux', platformName: 'linux', sessionHost, exec })+ expect(sessionHost).not.toHaveBeenCalled()+ expect(exec).toHaveBeenCalledTimes(1)+ })+})diff --git a/src/core/dev-ports.test.ts b/src/core/dev-ports.test.tsindex b00408e59..ac0c0918a 100644--- a/src/core/dev-ports.test.ts+++ b/src/core/dev-ports.test.ts@@ -261,7 +261,7 @@ describe('forwardTarget', () => {})describe('runners', () => {- it('local: Windows is unsupported, a throwing exec is unreachable', async () => {+ it('local: Windows without the session host is unsupported, a throwing exec is unreachable', async () => {const tmuxBin = (): string => '/usr/bin/tmux'expect(await collectLocalDevPorts({ tmuxBin, exec: async () => '', platformName: 'win32' })).toEqual({ok: false,diff --git a/src/core/dev-ports.ts b/src/core/dev-ports.tsindex 099bb1be0..f5269c0e1 100644--- a/src/core/dev-ports.ts+++ b/src/core/dev-ports.ts@@ -27,6 +27,8 @@ 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'+import type { SessionHostListing } from './session-host-client'+import { cimRows, powershellArgs, POWERSHELL_EXE } from './win32-powershell'const runAsync = promisify(execFile)@@ -425,17 +427,176 @@ export function forwardTarget(addresses: readonly string[]): string | null {return specific ?? null}+// ── Windows: the session host's panes + one PowerShell call ─────────────────────────────────────+//+// Windows has no `/bin/sh` and no tmux, so the POSIX script cannot run there. The three facts are+// the same, from different sources: the panes come from the session host (each session's pty pid —+// its `sessionDetails` listing), and the process table and listening sockets from ONE PowerShell+// call — `Win32_Process` and `Get-NetTCPConnection` (owning pid is a field, no name to forge), or+// `netstat -ano` where the NetTCPIP module is missing. The pure parsers below feed the very same+// `assembleDevPorts`, so ownership is decided by one tree walk on every platform.++/**+ * The Windows probe. Fenced like the POSIX one (`##PROCS`/`##LISTEN`/`##VIA`/`##END`), and any+ * error inside it exits 1 — which the exec seam reports as a rejection, i.e. `unreachable`. One+ * line, single quotes only: the whole script is one argv element and contains no `"` for Windows'+ * argv quoting to mangle.+ *+ * `Where-Object State -eq Listen` over the UNFILTERED cmdlet, not `-State Listen`: the filtered+ * form throws "no matching objects" when nothing listens, which would read as a failed probe.+ */+export const WIN32_DEV_PORTS_SCRIPT = [+ "$ErrorActionPreference = 'Stop'",+ 'try {',+ `'${PROCS}';`,+ 'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name | ConvertTo-Json -Compress;',+ `'${LISTEN}';`,+ 'if (Get-Command Get-NetTCPConnection -ErrorAction SilentlyContinue) {',+ "'##VIA nettcp';",+ "Get-NetTCPConnection | Where-Object { $_.State -eq 'Listen' } | Select-Object LocalAddress,LocalPort,OwningProcess | ConvertTo-Json -Compress",+ '} else {',+ "'##VIA netstat';",+ 'netstat.exe -ano;',+ "if ($LASTEXITCODE -ne 0) { throw ('netstat exited ' + $LASTEXITCODE) }",+ '};',+ `'${END}'`,+ '} catch { [Console]::Error.WriteLine($_.ToString()); exit 1 }'+].join(' ')++/** `Win32_Process` rows (ConvertTo-Json) → ProcRow. `Name` keeps its basename without `.exe`, the+ * same shape `ps`'s comm gives the menu row. Null for unreadable JSON. */+export function parseWin32ProcRows(json: string): ProcRow[] | null {+ const rows = cimRows(json)+ if (rows === null) return null+ const out: ProcRow[] = []+ for (const r of rows) {+ const pid = Number(r.ProcessId)+ const ppid = Number(r.ParentProcessId)+ if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(ppid)) continue+ const name = typeof r.Name === 'string' ? r.Name : ''+ out.push({ pid, ppid, command: name.replace(/\.exe$/i, '') })+ }+ return out+}++/** One address+port as the shared normalizer reads it (brackets for IPv6, mapped IPv4 unwrapped). */+function winHostPort(address: string, port: number): { address: string; port: number } | null {+ return splitHostPort(address.includes(':') ? `[${address}]:${port}` : `${address}:${port}`)+}++/** `Get-NetTCPConnection` listeners (ConvertTo-Json). The owning pid is a kernel FIELD, not text a+ * process can rename itself into, so the owner carries no name to cross-check. Null for bad JSON. */+export function parseWinNetTcpListeners(json: string): Listener[] | null {+ const rows = cimRows(json)+ if (rows === null) return null+ const out: Listener[] = []+ for (const r of rows) {+ const pid = Number(r.OwningProcess)+ if (typeof r.LocalAddress !== 'string' || !Number.isSafeInteger(pid)) continue+ const hp = winHostPort(r.LocalAddress, Number(r.LocalPort))+ if (hp) out.push({ owners: [{ pid, command: '' }], ...hp })+ }+ return out+}++/**+ * `netstat -ano` → TCP listeners. The state column is LOCALIZED (`LISTENING`, `ABHÖREN`, …), so a+ * listener is recognised by what is language-neutral: a TCP row whose FOREIGN address has port 0+ * (`0.0.0.0:0`, `[::]:0`) — an established or waiting connection always has a real peer port.+ */+export function parseNetstatListeners(text: string): Listener[] {+ const out: Listener[] = []+ for (const line of text.split('\n')) {+ const m = /^\s*TCP\s+(\S+)\s+(\S+)\s+.*?(\d+)\s*$/i.exec(line.replace(/\r$/, ''))+ if (!m || !/:0$/.test(m[2])) continue+ const hp = splitHostPort(m[1])+ if (hp) out.push({ owners: [{ pid: Number(m[3]), command: '' }], ...hp })+ }+ return out+}++/** Parse the Windows probe for the given panes. Every failure is `unreachable`, never "no ports". */+export function parseWin32DevPortsProbe(stdout: string, panes: readonly PaneRef[]): DevPortsReport {+ const lines = stdout.split('\n').map((l) => l.replace(/\r$/, ''))+ const iProcs = lines.indexOf(PROCS)+ const iListen = lines.indexOf(LISTEN)+ const iEnd = lines.lastIndexOf(END)+ if (iProcs < 0 || iListen < 0 || iEnd < 0 || !(iProcs < iListen && iListen < iEnd)) return fail('unreachable')+ const procs = parseWin32ProcRows(lines.slice(iProcs + 1, iListen).join('\n'))+ if (!procs || procs.length === 0) return fail('unreachable')+ const listen = lines.slice(iListen + 1, iEnd)+ const via = /^##VIA (\w+)$/.exec(listen[0] ?? '')?.[1]+ const body = listen.slice(1).join('\n')+ let listeners: Listener[] | null+ if (via === 'nettcp') listeners = parseWinNetTcpListeners(body)+ else if (via === 'netstat') listeners = parseNetstatListeners(body)+ else return fail('unreachable')+ if (!listeners) return fail('unreachable')+ return { ok: true, nodes: assembleDevPorts(panes, procs, listeners) }+}++/**+ * The Windows local scan. The session host's listing decides everything before PowerShell runs:+ * - a failed read, or a host too old to name its sessions' pids → `unreachable` ("could not look");+ * - no host running, or no nt- session → ok with no ports (an answer), and NO PowerShell spawn;+ * - otherwise one PowerShell call, whose non-zero exit (the exec rejects) is `unreachable`.+ */+export async function collectWin32DevPorts(+ listing: Promise<SessionHostListing | null>,+ exec: (bin: string, args: string[]) => Promise<string>+): Promise<DevPortsReport> {+ let read: SessionHostListing | null+ try {+ read = await listing+ } catch {+ read = null+ }+ if (!read) return fail('unreachable')+ if (!read.running) return { ok: true, nodes: {} }+ if (read.sessions === null) return fail('unreachable')+ const panes: PaneRef[] = read.sessions+ .filter((row) => row.name.startsWith('nt-'))+ .map((row) => ({ session: row.name, panePid: row.pid, command: '' }))+ if (panes.length === 0) return { ok: true, nodes: {} }+ try {+ return parseWin32DevPortsProbe(await exec(POWERSHELL_EXE, powershellArgs(WIN32_DEV_PORTS_SCRIPT)), panes)+ } catch {+ return fail('unreachable')+ }+}+export interface LocalDevPortsOptions {/** The app's tmux (`PtyManager.getTmuxBin()`); null = no tmux, so there is no pane tree at all. */tmuxBin: () => string | nullexec?: (command: string) => Promise<string>platformName?: NodeJS.Platform+ /**+ * Windows: the session host's listing (`PtyManager.sessionHostListing()`), `undefined` when the+ * session host is not the backend (tmux persistence switched off) — then honestly unsupported.+ */+ sessionHost?: () => Promise<SessionHostListing | null> | undefined+ /** Windows: the PowerShell exec seam. */+ execWin?: (bin: string, args: string[]) => Promise<string>}-/** Runs the probe on this machine. Windows has no `/bin/sh` and no tmux: honestly unsupported. */+/** Runs the probe on this machine — the POSIX script, or on Windows the session-host leg above. */export async function collectLocalDevPorts(opts: LocalDevPortsOptions): Promise<DevPortsReport> {const platformName = opts.platformName ?? process.platform- if (platformName === 'win32') return fail('unsupported')+ if (platformName === 'win32') {+ const listing = opts.sessionHost?.()+ if (listing === undefined) return fail('unsupported')+ const execWin =+ opts.execWin ??+ (async (bin: string, args: string[]): Promise<string> => {+ const { stdout } = await runAsync(bin, args, {+ timeout: 15_000,+ maxBuffer: 16 * 1024 * 1024,+ windowsHide: true+ })+ return stdout+ })+ return collectWin32DevPorts(listing, execWin)+ }// No tmux means every terminal is a plain shell (PtyManager's fallback): no nt- pane tree exists// to own a port. Unsupported for this run rather than a "could not look" asked every 30 s.const tmuxBin = opts.tmuxBin()diff --git a/src/main/index.ts b/src/main/index.tsindex b830d9c83..d1ea69aa3 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -3361,6 +3361,8 @@ app.whenReady().then(async () => {// exit-code-gated runner shape as session memory above; forwarding rides the project's master.const devPorts = startDevPortsService({tmuxBin: () => ptyManager.getTmuxBin(),+ // Windows: the session host's panes, probed with one PowerShell call (core/dev-ports.ts).+ sessionHost: () => ptyManager.sessionHostListing(),remote: {isRemoteProject: sshScopePredicate({sshProjectIds: () => workspaceStore.sshProjectIds(),