feat(browser): replace the preview proxy with a real browser panel and an agent web tool (#2883)
The preview panel worked by proxying a dev server through OpenChamber's own origin and rewriting the HTML that came back. Anything the rewriter did not anticipate broke, and pages that refuse to be embedded never loaded at all. This deletes the proxy (-1604 lines and its tests) and merges the preview and browser panels into one surface backed by a real Chromium view. What the panel is now - A `<webview>` in its own session partition: logins and cookies persist, hot reload works because nothing is rewritten, DevTools are one click away. - Annotation: pick one element, drag a region, or draw freehand, write a note, and it reaches chat with a screenshot of the visible page with the marks on it. - Toolbar: hard reload, page zoom, device sizes, a light/dark switch that applies to the page rather than the app, and cookie/cache clearing scoped to the panel alone. - Several pages at once, each tab showing the page's own favicon, and an address bar that suggests pages already visited in this project. - Dev servers are listed from what is actually listening on the machine, checked against what a project announced, so a server is offered no matter how it was started. One that is still starting is waited for instead of failing. Remote dev servers The desktop app binds a local port and pipes raw bytes to the OpenChamber host over the existing authenticated connection, so the page keeps its own origin at the root of its own host. The reachable set is exactly what discovery reports and is re-checked per connection, so an authenticated client cannot dial arbitrary local services on the host. Links and redirects to another loopback port stay on the machine that served the page. A tunnel that cannot be opened is reported; it is never replaced by the plain loopback URL, which would answer from the user's own machine under a remote address. Agent control Browser actions are a separate `openchamber_web` tool: open, snapshot, click, type, scroll, inspect computed styles, resize between mobile/tablet/desktop, and capture a screenshot into `.openchamber/screenshots/` in the project. The existing `openchamber` tool keeps sessions, worktrees and scheduled tasks. Each has its own setting in the new Settings -> General -> OpenChamber Tools section, and the plugin is not injected at all when both are off. Capability belongs to the connected client, not to configuration: a client declares on its event stream that it can drive a page, which only a Chromium host does. Exactly one client performs each request — it claims the request before acting, and the first claim wins — because deciding by whose result arrives first would be too late for a click that already happened. No client listening is answered immediately with an explanation rather than a timeout. Runtime boundaries Web tabs get a plain iframe that can display a page but not inspect one. The VS Code extension no longer offers the surface at all, since nothing that makes the panel worth having works there. Mobile is unaffected. Native boundary Camera, microphone, location and device-picker requests from panel pages are denied — Electron grants them by default when no handler is set, and the panel loads whatever address the user types. Page capture, appearance emulation and storage clearing verify that their target belongs to the panel's own session instead of trusting a web-contents id from the renderer. Persisted state Stored `preview` tabs migrate to `browser` (v13 -> v14). Context panel tab limits are now per surface, so filling one surface no longer evicts another's tabs. Address history is stored per project and per runtime. Documentation `preview.mdx` and `desktop-browser.mdx` rewritten across all locales, the agent tool settings path corrected, new `DOCUMENTATION.md` for the browser-control broker and the dev tunnel, and the `ui-api-decoupling` skill updated where it still described the deleted proxy.
This commit is contained in:
committed by
GitHub
parent
50613bb170
commit
a5aa32446d
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* Parsers for listening-socket enumeration.
|
||||
*
|
||||
* Two platforms, two formats, one shape out. Both parsers are pure so the
|
||||
* fiddly parts — grouped records, IPv6 brackets, wildcard binds — are covered
|
||||
* by tests instead of by running the tools.
|
||||
*/
|
||||
|
||||
/** Hosts that mean "this machine" when a socket reports its bind address. */
|
||||
const LOOPBACK_TOKENS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);
|
||||
/** Wildcard binds are reachable over loopback too. */
|
||||
const WILDCARD_TOKENS = new Set(['*', '0.0.0.0', '[::]', '::']);
|
||||
|
||||
/**
|
||||
* Ports that are listening but are never the thing a user wants to preview.
|
||||
* Kept deliberately short: guessing too aggressively hides real dev servers.
|
||||
*/
|
||||
const IGNORED_PORTS = new Set([
|
||||
22, // ssh
|
||||
53, // dns
|
||||
445, // smb
|
||||
631, // cups
|
||||
5432, // postgres
|
||||
3306, // mysql
|
||||
6379, // redis
|
||||
27017, // mongodb
|
||||
9229, // node inspector
|
||||
]);
|
||||
|
||||
const splitHostPort = (value) => {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw) return null;
|
||||
|
||||
// IPv6 arrives bracketed: [::1]:5173
|
||||
if (raw.startsWith('[')) {
|
||||
const close = raw.indexOf(']');
|
||||
if (close === -1) return null;
|
||||
const host = raw.slice(0, close + 1);
|
||||
const rest = raw.slice(close + 1);
|
||||
if (!rest.startsWith(':')) return null;
|
||||
return { host, port: rest.slice(1) };
|
||||
}
|
||||
|
||||
const separator = raw.lastIndexOf(':');
|
||||
if (separator === -1) return null;
|
||||
return { host: raw.slice(0, separator), port: raw.slice(separator + 1) };
|
||||
};
|
||||
|
||||
const toPort = (value) => {
|
||||
const port = Number.parseInt(String(value || '').trim(), 10);
|
||||
return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* True when a bind address can be reached from this machine over loopback.
|
||||
* A socket bound to a specific LAN address only is intentionally excluded:
|
||||
* `http://localhost:<port>` would not reach it.
|
||||
*/
|
||||
export const isLocallyReachableHost = (host) => {
|
||||
const value = String(host || '').trim().toLowerCase();
|
||||
return LOOPBACK_TOKENS.has(value) || WILDCARD_TOKENS.has(value);
|
||||
};
|
||||
|
||||
const isIgnoredDevPort = (port) => IGNORED_PORTS.has(port);
|
||||
|
||||
/**
|
||||
* Parses `lsof -iTCP -sTCP:LISTEN -P -n -F pcn`.
|
||||
*
|
||||
* The `-F` format emits one field per line, prefixed by a letter, and is
|
||||
* stateful: `p`/`c` lines open a process record and every following `n` line
|
||||
* belongs to it until the next `p`. A single process commonly reports the same
|
||||
* port twice (IPv4 and IPv6), so results are de-duplicated by port.
|
||||
*/
|
||||
export const parseLsofListeners = (output) => {
|
||||
const byPort = new Map();
|
||||
let pid = null;
|
||||
let command = '';
|
||||
|
||||
for (const line of String(output || '').split('\n')) {
|
||||
if (!line) continue;
|
||||
const tag = line[0];
|
||||
const value = line.slice(1);
|
||||
|
||||
if (tag === 'p') {
|
||||
const parsedPid = Number.parseInt(value, 10);
|
||||
pid = Number.isInteger(parsedPid) ? parsedPid : null;
|
||||
command = '';
|
||||
continue;
|
||||
}
|
||||
if (tag === 'c') {
|
||||
command = value.trim();
|
||||
continue;
|
||||
}
|
||||
if (tag !== 'n') continue;
|
||||
|
||||
// `n` values look like `*:5173`, `127.0.0.1:5173`, or `[::1]:5173`.
|
||||
// Established sockets contain `->`; LISTEN filtering should exclude them,
|
||||
// but the guard keeps a mixed invocation honest.
|
||||
if (value.includes('->')) continue;
|
||||
|
||||
const parsed = splitHostPort(value);
|
||||
if (!parsed) continue;
|
||||
const port = toPort(parsed.port);
|
||||
if (port === null) continue;
|
||||
if (!isLocallyReachableHost(parsed.host)) continue;
|
||||
|
||||
const existing = byPort.get(port);
|
||||
if (existing && existing.pid !== null) continue;
|
||||
byPort.set(port, { port, pid, command });
|
||||
}
|
||||
|
||||
return [...byPort.values()].sort((left, right) => left.port - right.port);
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses `netstat -ano -p TCP` on Windows, where no per-process command name is
|
||||
* available without a second call; `command` stays empty and callers fall back
|
||||
* to the port alone.
|
||||
*/
|
||||
export const parseNetstatListeners = (output) => {
|
||||
const byPort = new Map();
|
||||
|
||||
for (const line of String(output || '').split('\n')) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
if (parts.length < 4) continue;
|
||||
if (!/^tcp$/i.test(parts[0])) continue;
|
||||
if (!/^LISTENING$/i.test(parts[3])) continue;
|
||||
|
||||
const parsed = splitHostPort(parts[1]);
|
||||
if (!parsed) continue;
|
||||
const port = toPort(parsed.port);
|
||||
if (port === null) continue;
|
||||
if (!isLocallyReachableHost(parsed.host)) continue;
|
||||
|
||||
const pid = Number.parseInt(parts[4] ?? '', 10);
|
||||
if (byPort.has(port)) continue;
|
||||
byPort.set(port, { port, pid: Number.isInteger(pid) ? pid : null, command: '' });
|
||||
}
|
||||
|
||||
return [...byPort.values()].sort((left, right) => left.port - right.port);
|
||||
};
|
||||
|
||||
/**
|
||||
* Narrows raw listeners to the ones worth offering as a preview target.
|
||||
*
|
||||
* `ownPorts` removes OpenChamber's own listeners — offering the user a preview
|
||||
* of the app they are already looking at is pure noise.
|
||||
*/
|
||||
export const selectDevServerCandidates = (listeners, { ownPorts = [], ownPids = [] } = {}) => {
|
||||
const excludedPorts = new Set(ownPorts.filter((port) => Number.isInteger(port)));
|
||||
const excludedPids = new Set(ownPids.filter((pid) => Number.isInteger(pid)));
|
||||
|
||||
return listeners.filter((entry) => {
|
||||
if (excludedPorts.has(entry.port)) return false;
|
||||
if (entry.pid !== null && excludedPids.has(entry.pid)) return false;
|
||||
if (isIgnoredDevPort(entry.port)) return false;
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
/** Linux reports LISTEN as state 0A in /proc/net/tcp. */
|
||||
const PROC_STATE_LISTEN = '0A';
|
||||
/** Wildcard binds, as /proc writes them: IPv4 0.0.0.0 and IPv6 :: */
|
||||
const PROC_WILDCARD_ADDRESSES = new Set(['00000000', '00000000000000000000000000000000']);
|
||||
/** Loopback: 127.0.0.1 (little-endian per word) and ::1 */
|
||||
const PROC_LOOPBACK_ADDRESSES = new Set(['0100007F', '00000000000000000000000001000000']);
|
||||
|
||||
/**
|
||||
* Parses `/proc/net/tcp` and `/proc/net/tcp6`.
|
||||
*
|
||||
* The fallback for hosts without `lsof`, which is most containers — and a
|
||||
* deployed OpenChamber is exactly where a dev server needs discovering. Reads a
|
||||
* kernel file rather than shelling out, so it cannot be defeated by a missing
|
||||
* binary or a stripped PATH.
|
||||
*
|
||||
* No process name or pid: mapping a socket to its owner means walking every
|
||||
* /proc/<pid>/fd, which is far more work than the label is worth.
|
||||
*/
|
||||
export const parseProcNetTcpListeners = (output) => {
|
||||
const byPort = new Map();
|
||||
|
||||
for (const line of String(output || '').split('\n')) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
// sl, local_address, rem_address, st, ...
|
||||
if (parts.length < 4) continue;
|
||||
if (parts[3] !== PROC_STATE_LISTEN) continue;
|
||||
|
||||
const [address, portHex] = String(parts[1] || '').split(':');
|
||||
if (!address || !portHex) continue;
|
||||
|
||||
const normalizedAddress = address.toUpperCase();
|
||||
if (!PROC_WILDCARD_ADDRESSES.has(normalizedAddress) && !PROC_LOOPBACK_ADDRESSES.has(normalizedAddress)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const port = Number.parseInt(portHex, 16);
|
||||
if (!Number.isInteger(port) || port <= 0 || port > 65535) continue;
|
||||
if (byPort.has(port)) continue;
|
||||
byPort.set(port, { port, pid: null, command: '' });
|
||||
}
|
||||
|
||||
return [...byPort.values()].sort((left, right) => left.port - right.port);
|
||||
};
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
|
||||
import {
|
||||
isLocallyReachableHost,
|
||||
parseLsofListeners,
|
||||
parseProcNetTcpListeners,
|
||||
parseNetstatListeners,
|
||||
selectDevServerCandidates,
|
||||
} from './parse.js';
|
||||
|
||||
describe('lsof listener parsing', () => {
|
||||
test('associates every socket with the process record above it', () => {
|
||||
const output = [
|
||||
'p1234', 'cnode', 'n*:5173',
|
||||
'p5678', 'cpython3', 'n127.0.0.1:8000',
|
||||
].join('\n');
|
||||
|
||||
expect(parseLsofListeners(output)).toEqual([
|
||||
{ port: 5173, pid: 1234, command: 'node' },
|
||||
{ port: 8000, pid: 5678, command: 'python3' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('keeps one entry when a process binds the same port on IPv4 and IPv6', () => {
|
||||
const output = ['p1234', 'cnode', 'n*:5173', 'n[::1]:5173'].join('\n');
|
||||
expect(parseLsofListeners(output)).toEqual([{ port: 5173, pid: 1234, command: 'node' }]);
|
||||
});
|
||||
|
||||
test('unwraps bracketed IPv6 addresses', () => {
|
||||
expect(parseLsofListeners(['p1', 'cnode', 'n[::1]:3000'].join('\n')))
|
||||
.toEqual([{ port: 3000, pid: 1, command: 'node' }]);
|
||||
});
|
||||
|
||||
test('skips sockets bound only to a LAN address, which localhost cannot reach', () => {
|
||||
expect(parseLsofListeners(['p1', 'cnode', 'n192.168.1.10:5173'].join('\n'))).toEqual([]);
|
||||
});
|
||||
|
||||
test('skips established connections that slipped past the LISTEN filter', () => {
|
||||
expect(parseLsofListeners(['p1', 'cnode', 'n127.0.0.1:5173->127.0.0.1:60123'].join('\n')))
|
||||
.toEqual([]);
|
||||
});
|
||||
|
||||
test('returns sorted results', () => {
|
||||
const output = ['p1', 'cnode', 'n*:9000', 'n*:3000', 'n*:5173'].join('\n');
|
||||
expect(parseLsofListeners(output).map((entry) => entry.port)).toEqual([3000, 5173, 9000]);
|
||||
});
|
||||
|
||||
test('tolerates empty and malformed output rather than throwing', () => {
|
||||
expect(parseLsofListeners('')).toEqual([]);
|
||||
expect(parseLsofListeners(null)).toEqual([]);
|
||||
expect(parseLsofListeners('garbage\nn:\nnnotaport')).toEqual([]);
|
||||
});
|
||||
|
||||
test('rejects out-of-range ports', () => {
|
||||
expect(parseLsofListeners(['p1', 'cnode', 'n*:70000', 'n*:0'].join('\n'))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('netstat listener parsing', () => {
|
||||
const output = [
|
||||
'Active Connections',
|
||||
'',
|
||||
' Proto Local Address Foreign Address State PID',
|
||||
' TCP 0.0.0.0:5173 0.0.0.0:0 LISTENING 4242',
|
||||
' TCP 127.0.0.1:8000 0.0.0.0:0 LISTENING 9001',
|
||||
' TCP 192.168.0.5:9999 0.0.0.0:0 LISTENING 9002',
|
||||
' TCP 127.0.0.1:5173 127.0.0.1:60123 ESTABLISHED 9003',
|
||||
].join('\n');
|
||||
|
||||
test('takes listening loopback and wildcard sockets with their pid', () => {
|
||||
expect(parseNetstatListeners(output)).toEqual([
|
||||
{ port: 5173, pid: 4242, command: '' },
|
||||
{ port: 8000, pid: 9001, command: '' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('ignores established connections and LAN-only binds', () => {
|
||||
const ports = parseNetstatListeners(output).map((entry) => entry.port);
|
||||
expect(ports).not.toContain(9999);
|
||||
});
|
||||
|
||||
test('tolerates empty output', () => {
|
||||
expect(parseNetstatListeners('')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('host reachability', () => {
|
||||
test('accepts loopback and wildcard binds', () => {
|
||||
for (const host of ['127.0.0.1', 'localhost', '[::1]', '*', '0.0.0.0', '[::]']) {
|
||||
expect(isLocallyReachableHost(host)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects a specific LAN address', () => {
|
||||
expect(isLocallyReachableHost('192.168.1.4')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('candidate selection', () => {
|
||||
const listeners = [
|
||||
{ port: 5173, pid: 10, command: 'node' },
|
||||
{ port: 5432, pid: 11, command: 'postgres' },
|
||||
{ port: 4096, pid: 12, command: 'openchamber' },
|
||||
{ port: 3000, pid: 13, command: 'node' },
|
||||
];
|
||||
|
||||
test('drops OpenChamber own ports so the app never offers itself', () => {
|
||||
const ports = selectDevServerCandidates(listeners, { ownPorts: [4096] }).map((entry) => entry.port);
|
||||
expect(ports).toEqual([5173, 3000]);
|
||||
});
|
||||
|
||||
test('drops sockets owned by our own process', () => {
|
||||
const ports = selectDevServerCandidates(listeners, { ownPids: [13] }).map((entry) => entry.port);
|
||||
expect(ports).toEqual([5173, 4096]);
|
||||
});
|
||||
|
||||
test('drops well-known infrastructure ports that are never previewable', () => {
|
||||
const ports = selectDevServerCandidates(listeners).map((entry) => entry.port);
|
||||
expect(ports).not.toContain(5432);
|
||||
});
|
||||
|
||||
test('keeps everything else, including unusual ports', () => {
|
||||
const ports = selectDevServerCandidates([{ port: 12345, pid: 1, command: 'bun' }]).map((entry) => entry.port);
|
||||
expect(ports).toEqual([12345]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('proc net tcp parsing', () => {
|
||||
const header = ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode';
|
||||
|
||||
test('takes listening sockets on loopback and wildcard binds', () => {
|
||||
const output = [
|
||||
header,
|
||||
' 0: 00000000:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 12345 1 0000 100 0',
|
||||
' 1: 0100007F:0BB8 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 12346 1 0000 100 0',
|
||||
].join('\n');
|
||||
|
||||
expect(parseProcNetTcpListeners(output)).toEqual([
|
||||
{ port: 3000, pid: null, command: '' },
|
||||
{ port: 8080, pid: null, command: '' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('ignores sockets that are not listening', () => {
|
||||
const output = [
|
||||
header,
|
||||
' 0: 0100007F:1F90 0100007F:C350 01 00000000:00000000 00:00000000 00000000 1000 0 12345 1 0000 100 0',
|
||||
].join('\n');
|
||||
expect(parseProcNetTcpListeners(output)).toEqual([]);
|
||||
});
|
||||
|
||||
test('ignores a bind to a specific LAN address', () => {
|
||||
const output = [
|
||||
header,
|
||||
' 0: 0A00020F:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 12345 1 0000 100 0',
|
||||
].join('\n');
|
||||
expect(parseProcNetTcpListeners(output)).toEqual([]);
|
||||
});
|
||||
|
||||
test('reads the IPv6 table, including ::1 and ::', () => {
|
||||
const output = [
|
||||
header,
|
||||
' 0: 00000000000000000000000001000000:1F90 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 1 1 0 0 0',
|
||||
' 1: 00000000000000000000000000000000:0BB8 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 1 1 0 0 0',
|
||||
].join('\n');
|
||||
expect(parseProcNetTcpListeners(output).map((entry) => entry.port)).toEqual([3000, 8080]);
|
||||
});
|
||||
|
||||
test('tolerates an empty or malformed table', () => {
|
||||
expect(parseProcNetTcpListeners('')).toEqual([]);
|
||||
expect(parseProcNetTcpListeners(header)).toEqual([]);
|
||||
expect(parseProcNetTcpListeners('garbage')).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Dev-server discovery.
|
||||
*
|
||||
* Answers "what is listening on this machine that I could preview". The old
|
||||
* approach guessed from `package.json` scripts, which told us what *could* be
|
||||
* started, never what was actually running — so it was wrong exactly when the
|
||||
* user needed it. Enumerating listening sockets reports the truth.
|
||||
*
|
||||
* Discovery is advisory. A failed scan reports failure; it never reports an
|
||||
* empty list, because a caller cannot tell "nothing is running" from "the scan
|
||||
* broke" and would render the wrong empty state.
|
||||
*/
|
||||
import fsPromises from 'node:fs/promises';
|
||||
|
||||
import {
|
||||
parseLsofListeners,
|
||||
parseNetstatListeners,
|
||||
parseProcNetTcpListeners,
|
||||
selectDevServerCandidates,
|
||||
} from './parse.js';
|
||||
|
||||
const SCAN_TIMEOUT_MS = 2_500;
|
||||
/** Enumeration is cheap but not free; a short cache absorbs panel re-renders. */
|
||||
const CACHE_TTL_MS = 3_000;
|
||||
|
||||
const runCommand = (spawn, command, args, timeoutMs) => new Promise((resolve) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(command, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
|
||||
} catch {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
let stdout = '';
|
||||
let settled = false;
|
||||
const finish = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
try { child.kill(); } catch { /* already exited */ }
|
||||
resolve(value);
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => finish(null), timeoutMs);
|
||||
child.stdout?.on('data', (chunk) => { stdout += String(chunk); });
|
||||
child.on('error', () => finish(null));
|
||||
child.on('close', (code) => finish(code === 0 || stdout ? stdout : null));
|
||||
});
|
||||
|
||||
/**
|
||||
* Reads the kernel's socket tables. Containers routinely ship without `lsof`,
|
||||
* and a deployed OpenChamber is precisely where discovery has to work, so this
|
||||
* is tried whenever the command is unavailable.
|
||||
*/
|
||||
const readProcListeners = async (readFile) => {
|
||||
const tables = await Promise.all(['/proc/net/tcp', '/proc/net/tcp6'].map(
|
||||
(path) => readFile(path, 'utf8').catch(() => null),
|
||||
));
|
||||
if (tables.every((table) => table === null)) return null;
|
||||
const byPort = new Map();
|
||||
for (const table of tables) {
|
||||
if (table === null) continue;
|
||||
for (const entry of parseProcNetTcpListeners(table)) {
|
||||
if (!byPort.has(entry.port)) byPort.set(entry.port, entry);
|
||||
}
|
||||
}
|
||||
return [...byPort.values()].sort((left, right) => left.port - right.port);
|
||||
};
|
||||
|
||||
export const createDevServerScanner = ({ spawn, platform, readFile = fsPromises.readFile }) => {
|
||||
let cache = null;
|
||||
|
||||
const scan = async () => {
|
||||
const isWindows = platform === 'win32';
|
||||
if (isWindows) {
|
||||
const output = await runCommand(spawn, 'netstat', ['-ano', '-p', 'TCP'], SCAN_TIMEOUT_MS);
|
||||
if (output === null) return { ok: false, reason: 'netstat-unavailable' };
|
||||
return { ok: true, listeners: parseNetstatListeners(output) };
|
||||
}
|
||||
|
||||
const output = await runCommand(spawn, 'lsof', ['-iTCP', '-sTCP:LISTEN', '-P', '-n', '-F', 'pcn'], SCAN_TIMEOUT_MS);
|
||||
if (output !== null) return { ok: true, listeners: parseLsofListeners(output) };
|
||||
|
||||
const procListeners = await readProcListeners(readFile);
|
||||
if (procListeners !== null) return { ok: true, listeners: procListeners };
|
||||
|
||||
return { ok: false, reason: 'no-listener-source' };
|
||||
};
|
||||
|
||||
return {
|
||||
/**
|
||||
* @param {{ ownPorts?: number[] }} options
|
||||
* @returns {Promise<{ ok: true, servers: Array<{ port: number, pid: number|null, command: string, url: string }> } | { ok: false, reason: string }>}
|
||||
*/
|
||||
async discover({ ownPorts = [] } = {}) {
|
||||
const now = Date.now();
|
||||
if (cache && now - cache.at < CACHE_TTL_MS) return cache.value;
|
||||
|
||||
const result = await scan();
|
||||
if (!result.ok) {
|
||||
// Not cached: a transient failure should not suppress the next attempt.
|
||||
return result;
|
||||
}
|
||||
|
||||
const servers = selectDevServerCandidates(result.listeners, {
|
||||
ownPorts,
|
||||
ownPids: [process.pid],
|
||||
}).map((entry) => ({
|
||||
...entry,
|
||||
url: `http://localhost:${entry.port}/`,
|
||||
}));
|
||||
|
||||
const value = { ok: true, servers };
|
||||
cache = { at: now, value };
|
||||
return value;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export function registerDevServerRoutes(app, { scanner, getOwnPorts }) {
|
||||
app.get('/api/dev-servers', async (req, res) => {
|
||||
try {
|
||||
const ownPorts = typeof getOwnPorts === 'function' ? getOwnPorts() : [];
|
||||
const result = await scanner.discover({ ownPorts: Array.isArray(ownPorts) ? ownPorts : [] });
|
||||
if (!result.ok) {
|
||||
res.status(503).json({ error: 'Port discovery is unavailable', reason: result.reason });
|
||||
return;
|
||||
}
|
||||
res.json({ servers: result.servers });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error?.message || 'Port discovery failed' });
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user