Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(device): detect listening ports and expose them in one click (#19895)

Arvin Xu52ac257e4b4b
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 24326c7affa..d81005afcae 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -1277,6 +1277,25 @@ export const deviceRouter = router({
return { ...link, openUrl: await buildTunnelOpenUrl(link.url, ctx) };
}),
+ /**
+ * Ports the device is listening on, so the UI can offer "5173 · vite" to
+ * expose in one click. Gated like creating a tunnel: seeing which ports are
+ * open is only useful to someone allowed to expose them. `null` means the
+ * device couldn't answer (offline, or a client that predates detection).
+ */
+ listListeningPorts: deviceProcedure
+ .input(z.object({ cwd: z.string().optional(), deviceId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ await assertTunnelDeviceWritable(ctx, input.deviceId);
+ const result = await deviceGateway.listListeningPorts({
+ cwd: input.cwd,
+ deviceId: input.deviceId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ return result ?? null;
+ }),
+
/** Live tunnel links the caller can reach, newest first. */
listTunnels: deviceProcedure
.input(z.object({ deviceId: z.string().optional() }).optional())
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index a34c2c204e2..de4ebb94f07 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -40,6 +40,7 @@ import type {
DeviceGitWorkingTreePatches,
DeviceGitWorkingTreeStatus,
DeviceGitWorktreeListItem,
+ DeviceListeningPortsResult,
DeviceListProjectSkillsResult,
DeviceLocalFilePreviewResult,
DeviceMoveProjectFileItem,
@@ -1778,6 +1779,42 @@ export class DeviceGateway {
}
}
+ /**
+ * TCP ports the device is listening on that a tunnel can reach, with the
+ * project's own ports marked. Resolves undefined when the device is
+ * offline or predates the RPC — the UI then says it can't read the ports.
+ */
+ async listListeningPorts(params: {
+ cwd?: string;
+ deviceId: string;
+ timeout?: number;
+ userId: string;
+ workspaceId?: string;
+ }): Promise<DeviceListeningPortsResult | undefined> {
+ const { cwd, deviceId, timeout = 10_000, userId, workspaceId } = params;
+ const client = this.getClient();
+ if (!client) return undefined;
+
+ try {
+ const result = await client.invokeRpc<DeviceListeningPortsResult>(
+ { deviceId, timeout, userId, workspaceId },
+ { method: 'listListeningPorts', params: { cwd } },
+ );
+ if (!result.success || !result.data) {
+ log('listListeningPorts: failed for deviceId=%s', deviceId);
+ return undefined;
+ }
+ return result.data;
+ } catch (error) {
+ log(
+ 'listListeningPorts: error for deviceId=%s (%s)',
+ deviceId,
+ error instanceof Error ? error.name : typeof error,
+ );
+ return undefined;
+ }
+ }
+
private getClient(): GatewayHttpClient | null {
const url = gatewayEnv.DEVICE_GATEWAY_URL;
const token = gatewayEnv.DEVICE_GATEWAY_SERVICE_TOKEN;
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 4cd26584f76..9a063367be6 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2560,14 +2560,16 @@
"workingPanel.overview.execution.local": "This device",
"workingPanel.overview.files": "Files",
"workingPanel.overview.outputs": "Outputs",
- "workingPanel.overview.ports.addPlaceholder": "Port number, Enter to open",
"workingPanel.overview.ports.copied": "Link copied",
"workingPanel.overview.ports.copy": "Copy link",
"workingPanel.overview.ports.createFailed": "Could not expose the port",
- "workingPanel.overview.ports.empty": "No port exposed yet",
- "workingPanel.overview.ports.expose": "Expose a port",
- "workingPanel.overview.ports.heading": "Exposed ports",
- "workingPanel.overview.ports.hint": "The link carries a one-time token and only opens for people who can reach this device.",
+ "workingPanel.overview.ports.detected.available": "{{count}} to open",
+ "workingPanel.overview.ports.detected.expose": "Open",
+ "workingPanel.overview.ports.detected.heading": "Detected",
+ "workingPanel.overview.ports.detected.hideOthers": "Hide other ports",
+ "workingPanel.overview.ports.detected.none": "Nothing from this project is listening yet",
+ "workingPanel.overview.ports.detected.others": "Other ports ({{count}})",
+ "workingPanel.overview.ports.detected.refresh": "Rescan",
"workingPanel.overview.ports.invalidPort": "Enter a port between 1 and 65535",
"workingPanel.overview.ports.loadFailed": "Couldn't load ports",
"workingPanel.overview.ports.loading": "Loading…",
@@ -2579,6 +2581,7 @@
"workingPanel.overview.ports.revokeFailed": "Could not stop sharing",
"workingPanel.overview.ports.revoked": "Sharing stopped",
"workingPanel.overview.ports.title": "Ports",
+ "workingPanel.overview.ports.unavailable": "Can't read this device's ports right now",
"workingPanel.overview.sync.ahead_one": "{{count}} commit ahead",
"workingPanel.overview.sync.ahead_other": "{{count}} commits ahead",
"workingPanel.overview.sync.behind_one": "{{count}} commit behind",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 169efcb6cbd..88be487be56 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2560,14 +2560,16 @@
"workingPanel.overview.execution.local": "此设备",
"workingPanel.overview.files": "文件",
"workingPanel.overview.outputs": "产物",
- "workingPanel.overview.ports.addPlaceholder": "输入端口号,回车打开",
"workingPanel.overview.ports.copied": "链接已复制",
"workingPanel.overview.ports.copy": "复制链接",
"workingPanel.overview.ports.createFailed": "开放端口失败",
- "workingPanel.overview.ports.empty": "还没有开放端口",
- "workingPanel.overview.ports.expose": "开放端口",
- "workingPanel.overview.ports.heading": "已开放的端口",
- "workingPanel.overview.ports.hint": "链接带一次性令牌,只有能访问这台设备的人打得开。",
+ "workingPanel.overview.ports.detected.available": "{{count}} 个可开放",
+ "workingPanel.overview.ports.detected.expose": "开放",
+ "workingPanel.overview.ports.detected.heading": "检测到的端口",
+ "workingPanel.overview.ports.detected.hideOthers": "收起其它端口",
+ "workingPanel.overview.ports.detected.none": "这个项目里还没有在跑的服务",
+ "workingPanel.overview.ports.detected.others": "其它端口({{count}})",
+ "workingPanel.overview.ports.detected.refresh": "重新检测",
"workingPanel.overview.ports.invalidPort": "请输入 1–65535 之间的端口",
"workingPanel.overview.ports.loadFailed": "读取端口失败",
"workingPanel.overview.ports.loading": "正在读取…",
@@ -2579,6 +2581,7 @@
"workingPanel.overview.ports.revokeFailed": "停止共享失败",
"workingPanel.overview.ports.revoked": "已停止共享",
"workingPanel.overview.ports.title": "端口",
+ "workingPanel.overview.ports.unavailable": "暂时无法读取这台设备的端口",
"workingPanel.overview.sync.ahead_one": "领先 {{count}} 个提交",
"workingPanel.overview.sync.ahead_other": "领先 {{count}} 个提交",
"workingPanel.overview.sync.behind_one": "落后 {{count}} 个提交",
diff --git a/packages/device-control/src/__tests__/listeningPorts.test.ts b/packages/device-control/src/__tests__/listeningPorts.test.ts
new file mode 100644
index 00000000000..c8ebc6fbc01
--- /dev/null
+++ b/packages/device-control/src/__tests__/listeningPorts.test.ts
@@ -0,0 +1,171 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ classifyAddress,
+ parseLsofCwd,
+ parseLsofListen,
+ parseNetstat,
+ parseProcNetTcp,
+ parseTasklist,
+ summarizeListeners,
+} from '../listeningPorts';
+
+describe('classifyAddress', () => {
+ it.each([
+ ['*', 'any'],
+ ['0.0.0.0', 'any'],
+ ['[::]', 'any'],
+ ['127.0.0.1', 'ipv4-loopback'],
+ ['[::1]', 'ipv6-loopback'],
+ ['192.168.1.20', 'unreachable'],
+ ])('%s → %s', (address, kind) => {
+ expect(classifyAddress(address)).toBe(kind);
+ });
+});
+
+describe('macOS lsof', () => {
+ // Real `lsof -nP -iTCP -sTCP:LISTEN -F pcn` shape.
+ const listen = [
+ 'p19146',
+ 'cnode',
+ 'f32',
+ 'n[::1]:5173',
+ 'p607',
+ 'cPython',
+ 'f4',
+ 'n*:18000',
+ 'f5',
+ 'n127.0.0.1:18000',
+ 'p900',
+ 'cpostgres',
+ 'f6',
+ 'n192.168.1.20:5432',
+ ].join('\n');
+
+ it('parses pid, command and every listening address', () => {
+ expect(parseLsofListen(listen)).toEqual([
+ { address: '[::1]', command: 'node', pid: 19146, port: 5173 },
+ { address: '*', command: 'Python', pid: 607, port: 18000 },
+ { address: '127.0.0.1', command: 'Python', pid: 607, port: 18000 },
+ { address: '192.168.1.20', command: 'postgres', pid: 900, port: 5432 },
+ ]);
+ });
+
+ it('parses the cwd lookup', () => {
+ const cwds = parseLsofCwd(
+ ['p19146', 'fcwd', 'n/private/tmp/app', 'p607', 'fcwd', 'n/'].join('\n'),
+ );
+ expect([...cwds]).toEqual([
+ [19146, '/private/tmp/app'],
+ [607, '/'],
+ ]);
+ });
+});
+
+describe('Linux /proc/net/tcp', () => {
+ const header =
+ ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode';
+
+ it('decodes listening IPv4 sockets and skips other states', () => {
+ const content = [
+ header,
+ ' 0: 0100007F:1435 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 11111 1',
+ ' 1: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 22222 1',
+ ' 2: 0100007F:1435 0100007F:C350 01 00000000:00000000 00:00000000 00000000 1000 0 33333 1',
+ ].join('\n');
+
+ expect(parseProcNetTcp(content, 'v4')).toEqual([
+ { address: '127.0.0.1', inode: '11111', port: 5173 },
+ { address: '0.0.0.0', inode: '22222', port: 22 },
+ ]);
+ });
+
+ it('decodes IPv6 loopback and wildcard', () => {
+ const content = [
+ header,
+ ' 0: 00000000000000000000000001000000:1435 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 44444 1',
+ ' 1: 00000000000000000000000000000000:0BB8 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 55555 1',
+ ].join('\n');
+
+ expect(parseProcNetTcp(content, 'v6')).toEqual([
+ { address: '::1', inode: '44444', port: 5173 },
+ { address: '::', inode: '55555', port: 3000 },
+ ]);
+ });
+});
+
+describe('Windows netstat', () => {
+ it('parses LISTENING rows for both families', () => {
+ const output = [
+ 'Active Connections',
+ ' Proto Local Address Foreign Address State PID',
+ ' TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 1044',
+ ' TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 8812',
+ ' TCP [::1]:3000 [::]:0 LISTENING 9001',
+ ' TCP 10.0.0.4:52100 20.1.1.1:443 ESTABLISHED 7000',
+ ].join('\r\n');
+
+ expect(parseNetstat(output)).toEqual([
+ { address: '0.0.0.0', pid: 1044, port: 135 },
+ { address: '127.0.0.1', pid: 8812, port: 5173 },
+ { address: '[::1]', pid: 9001, port: 3000 },
+ ]);
+ });
+
+ it('parses tasklist image names', () => {
+ const names = parseTasklist(
+ '"node.exe","8812","Console","1","52,120 K"\r\n"svchost.exe","1044","Services","0","9,000 K"',
+ );
+ expect(names.get(8812)).toBe('node.exe');
+ expect(names.get(1044)).toBe('svchost.exe');
+ });
+});
+
+describe('summarizeListeners', () => {
+ const entries = [
+ { address: '[::1]', command: 'node', pid: 1, port: 5173 },
+ { address: '*', command: 'postgres', pid: 2, port: 5432 },
+ { address: '127.0.0.1', command: 'next-server', pid: 3, port: 3000 },
+ { address: '[::1]', command: 'next-server', pid: 3, port: 3000 },
+ { address: '192.168.1.20', command: 'lan-only', pid: 4, port: 8080 },
+ { address: '127.0.0.1', command: 'lobehub', pid: 99, port: 7777 },
+ ];
+ const cwds = new Map([
+ [1, '/work/app/packages/web'],
+ [2, '/'],
+ [3, '/work/app'],
+ [4, '/work/app'],
+ ]);
+
+ it('puts the project first, folds families, and drops what a tunnel cannot reach', () => {
+ const ports = summarizeListeners(entries, { cwd: '/work/app', cwds, ownPid: 99 });
+
+ expect(ports).toEqual([
+ {
+ command: 'next-server',
+ cwd: '/work/app',
+ inProject: true,
+ loopback: 'both',
+ pid: 3,
+ port: 3000,
+ },
+ {
+ command: 'node',
+ cwd: '/work/app/packages/web',
+ inProject: true,
+ loopback: 'ipv6',
+ pid: 1,
+ port: 5173,
+ },
+ { command: 'postgres', cwd: '/', inProject: false, loopback: 'both', pid: 2, port: 5432 },
+ ]);
+ });
+
+ it('does not treat a sibling directory with a shared prefix as inside the project', () => {
+ const ports = summarizeListeners([{ address: '*', command: 'node', pid: 5, port: 4000 }], {
+ cwd: '/work/app',
+ cwds: new Map([[5, '/work/app-old']]),
+ });
+ expect(ports[0].inProject).toBe(false);
+ });
+});
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index 388a50fcd7e..f422f6a0f5b 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -29,6 +29,7 @@ import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQ
import { getCodexQuota, type GetCodexQuotaParams } from './codexQuota';
import { defaultCopyAssetForPublish, defaultReadExternalAssetForPublish } from './filePreview';
import { getKimiCodeQuota, type GetKimiCodeQuotaParams } from './kimiCodeQuota';
+import { listListeningPorts, type ListListeningPortsParams } from './listeningPorts';
import { defaultListProjectDirectory } from './projectFileIndex';
import { prepareSkillDirectory } from './skillDirectory';
import type {
@@ -98,6 +99,7 @@ export const DEVICE_RPC_METHODS = [
'pullGitBranch',
'pushGitBranch',
'revertGitFile',
+ 'listListeningPorts',
] as const;
export type DeviceRpcMethod = (typeof DEVICE_RPC_METHODS)[number];
@@ -165,6 +167,10 @@ export const executeDeviceRpc = async (
return prepareSkillDirectory(params as PrepareSkillDirectoryParams, deps);
}
+ case 'listListeningPorts': {
+ return listListeningPorts(params as ListListeningPortsParams);
+ }
+
case 'browseDirectory': {
return browseDirectory(params as BrowseDirectoryParams);
}
diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.ts
index 622243cbc7c..3237d73960e 100644
--- a/packages/device-control/src/index.ts
+++ b/packages/device-control/src/index.ts
@@ -7,6 +7,12 @@ export {
EXTERNAL_PUBLISH_ASSET_MAX_BYTES,
} from './filePreview';
export { getKimiCodeQuota, type GetKimiCodeQuotaParams } from './kimiCodeQuota';
+export {
+ type ListeningPort,
+ listListeningPorts,
+ type ListListeningPortsParams,
+ type ListListeningPortsResult,
+} from './listeningPorts';
export {
defaultGetProjectFileIndex,
defaultListProjectDirectory,
diff --git a/packages/device-control/src/listeningPorts.ts b/packages/device-control/src/listeningPorts.ts
new file mode 100644
index 00000000000..58b6ef2ad8c
--- /dev/null
+++ b/packages/device-control/src/listeningPorts.ts
@@ -0,0 +1,318 @@
+import { execFile } from 'node:child_process';
+import { readdir, readFile, readlink, realpath } from 'node:fs/promises';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+const execFileAsync = promisify(execFile);
+
+/**
+ * Find the TCP ports this machine is listening on that a tunnel could reach,
+ * and which of them belong to a given project — so the UI can offer "5173 ·
+ * vite" instead of asking the user to remember a port number.
+ *
+ * Only loopback or wildcard binds are reported: a tunnel dials `127.0.0.1` (or
+ * `::1`), so a server bound to one LAN address only is unreachable anyway.
+ * Parsing is split from collection so every platform's format is testable on
+ * any platform.
+ */
+
+export interface ListenEntry {
+ /** Address exactly as the OS reported it, e.g. `*`, `127.0.0.1`, `::1`. */
+ address: string;
+ command?: string;
+ pid?: number;
+ port: number;
+}
+
+export type LoopbackFamily = 'both' | 'ipv4' | 'ipv6';
+
+export interface ListeningPort {
+ command?: string;
+ cwd?: string;
+ /** The listening process runs inside the requested project directory. */
+ inProject: boolean;
+ /** Which loopback address reaches it — `ipv6` means `::1` only. */
+ loopback: LoopbackFamily;
+ pid?: number;
+ port: number;
+}
+
+export interface ListListeningPortsParams {
+ /** Project directory; ports whose process runs inside it are marked `inProject`. */
+ cwd?: string;
+}
+
+export interface ListListeningPortsResult {
+ ports: ListeningPort[];
+ /** False when this platform's detector isn't available (e.g. no `lsof`). */
+ supported: boolean;
+}
+
+const MAX_PORTS = 50;
+const COMMAND_TIMEOUT_MS = 5000;
+
+// ─── Address classification ───
+
+type AddressKind = 'any' | 'ipv4-loopback' | 'ipv6-loopback' | 'unreachable';
+
+export const classifyAddress = (address: string): AddressKind => {
+ const bare = address.replaceAll(/^\[|\]$/g, '');
+ if (bare === '*' || bare === '0.0.0.0' || bare === '::' || bare === '::0') return 'any';
+ if (bare.startsWith('127.')) return 'ipv4-loopback';
+ if (bare === '::1' || bare === '::ffff:127.0.0.1') return 'ipv6-loopback';
+ return 'unreachable';
+};
+
+// ─── macOS / BSD: lsof ───
+
+/** Parse `lsof -nP -iTCP -sTCP:LISTEN -F pcn` field output. */
+export const parseLsofListen = (output: string): ListenEntry[] => {
+ const entries: ListenEntry[] = [];
+ let pid: number | undefined;
+ let command: string | undefined;
+
+ for (const line of output.split('\n')) {
+ const tag = line[0];
+ const value = line.slice(1);
+ if (tag === 'p') {
+ pid = Number(value);
+ command = undefined;
+ } else if (tag === 'c') {
+ command = value;
+ } else if (tag === 'n') {
+ const sep = value.lastIndexOf(':');
+ const port = Number(value.slice(sep + 1));
+ if (sep > 0 && Number.isInteger(port) && port > 0) {
+ entries.push({ address: value.slice(0, sep), command, pid, port });
+ }
+ }
+ }
+ return entries;
+};
+
+/** Parse `lsof -a -p <pids> -d cwd -Fpn` into pid → cwd. */
+export const parseLsofCwd = (output: string): Map<number, string> => {
+ const cwds = new Map<number, string>();
+ let pid: number | undefined;
+ for (const line of output.split('\n')) {
+ if (line[0] === 'p') pid = Number(line.slice(1));
+ else if (line[0] === 'n' && pid !== undefined) cwds.set(pid, line.slice(1));
+ }
+ return cwds;
+};
+
+// ─── Linux: /proc/net/tcp{,6} ───
+
+const LISTEN_STATE = '0A';
+
+const decodeProcIpv4 = (hex: string) =>
+ [hex.slice(6, 8), hex.slice(4, 6), hex.slice(2, 4), hex.slice(0, 2)]
+ .map((byte) => Number.parseInt(byte, 16))
+ .join('.');
+
+const decodeProcIpv6 = (hex: string): string => {
+ if (/^0+$/.test(hex)) return '::';
+ if (hex === '00000000000000000000000001000000') return '::1';
+ if (hex === '0000000000000000FFFF00000100007F') return '::ffff:127.0.0.1';
+ return hex; // any other v6 bind is unreachable over loopback; keep it opaque
+};
+
+/** Parse `/proc/net/tcp` or `/proc/net/tcp6` into listening sockets keyed by inode. */
+export const parseProcNetTcp = (
+ content: string,
+ family: 'v4' | 'v6',
+): Array<{ address: string; inode: string; port: number }> =>
+ content
+ .split('\n')
+ .slice(1)
+ .map((line) => line.trim().split(/\s+/))
+ .filter((cols) => cols.length > 9 && cols[3] === LISTEN_STATE)
+ .map((cols) => {
+ const [addrHex, portHex] = cols[1].split(':');
+ return {
+ address: family === 'v4' ? decodeProcIpv4(addrHex) : decodeProcIpv6(addrHex.toUpperCase()),
+ inode: cols[9],
+ port: Number.parseInt(portHex, 16),
+ };
+ });
+
+// ─── Windows: netstat ───
+
+/** Parse `netstat -ano -p TCP` / `-p TCPv6` LISTENING rows. */
+export const parseNetstat = (output: string): ListenEntry[] =>
+ output
+ .split('\n')
+ .map((line) => line.trim().split(/\s+/))
+ .filter((cols) => cols[0] === 'TCP' && cols[3] === 'LISTENING')
+ .map((cols) => {
+ const local = cols[1];
+ const sep = local.lastIndexOf(':');
+ return {
+ address: local.slice(0, sep),
+ pid: Number(cols[4]),
+ port: Number(local.slice(sep + 1)),
+ };
+ });
+
+/** Parse `tasklist /FO CSV /NH` into pid → image name. */
+export const parseTasklist = (output: string): Map<number, string> => {
+ const names = new Map<number, string>();
+ for (const line of output.split('\n')) {
+ const cols = line.match(/"([^"]*)"/g)?.map((col) => col.slice(1, -1));
+ if (cols && cols.length > 1) names.set(Number(cols[1]), cols[0]);
+ }
+ return names;
+};
+
+// ─── Assembly ───
+
+const isInside = (dir: string | undefined, root: string | undefined) => {
+ if (!dir || !root) return false;
+ const rel = path.relative(path.resolve(root), path.resolve(dir));
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+};
+
+/**
+ * Fold raw sockets into one row per port, keep only loopback-reachable ones,
+ * drop this process's own listeners, and put the project's ports first.
+ */
+export const summarizeListeners = (
+ entries: ListenEntry[],
+ options: { cwd?: string; cwds?: Map<number, string>; ownPid?: number },
+): ListeningPort[] => {
+ const byPort = new Map<number, { entry: ListenEntry; kinds: Set<AddressKind> }>();
+
+ for (const entry of entries) {
+ if (options.ownPid !== undefined && entry.pid === options.ownPid) continue;
+ const kind = classifyAddress(entry.address);
+ if (kind === 'unreachable') continue;
+ const existing = byPort.get(entry.port);
+ if (existing) existing.kinds.add(kind);
+ else byPort.set(entry.port, { entry, kinds: new Set([kind]) });
+ }
+
+ const ports = [...byPort.values()].map(({ entry, kinds }) => {
+ const v4 = kinds.has('any') || kinds.has('ipv4-loopback');
+ const v6 = kinds.has('any') || kinds.has('ipv6-loopback');
+ const cwd = entry.pid === undefined ? undefined : options.cwds?.get(entry.pid);
+ return {
+ ...(entry.command ? { command: entry.command } : {}),
+ ...(cwd ? { cwd } : {}),
+ inProject: isInside(cwd, options.cwd),
+ loopback: (v4 && v6 ? 'both' : v4 ? 'ipv4' : 'ipv6') as LoopbackFamily,
+ ...(entry.pid === undefined ? {} : { pid: entry.pid }),
+ port: entry.port,
+ };
+ });
+
+ return ports
+ .sort((a, b) => Number(b.inProject) - Number(a.inProject) || a.port - b.port)
+ .slice(0, MAX_PORTS);
+};
+
+const run = async (file: string, args: string[]) =>
+ (await execFileAsync(file, args, { maxBuffer: 4 * 1024 * 1024, timeout: COMMAND_TIMEOUT_MS }))
+ .stdout;
+
+const collectDarwin = async () => {
+ // lsof exits 1 when nothing matches; that is an empty list, not a failure.
+ const listen = await run('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN', '-F', 'pcn']).catch(
+ (error: { code?: number | string; stdout?: string }) => {
+ if (error.code === 1) return error.stdout ?? '';
+ throw error;
+ },
+ );
+ const entries = parseLsofListen(listen);
+ const pids = [...new Set(entries.map((e) => e.pid).filter((p): p is number => !!p))];
+ const cwds = pids.length
+ ? parseLsofCwd(
+ await run('lsof', ['-a', '-p', pids.join(','), '-d', 'cwd', '-Fpn']).catch(
+ (error: { stdout?: string }) => error.stdout ?? '',
+ ),
+ )
+ : new Map<number, string>();
+ return { cwds, entries };
+};
+
+const collectLinux = async () => {
+ const sockets = [
+ ...parseProcNetTcp(await readFile('/proc/net/tcp', 'utf8').catch(() => ''), 'v4'),
+ ...parseProcNetTcp(await readFile('/proc/net/tcp6', 'utf8').catch(() => ''), 'v6'),
+ ];
+ const wanted = new Set(sockets.map((s) => s.inode));
+ const owner = new Map<string, number>();
+
+ // Map socket inodes back to processes. Only this user's processes are
+ // readable, which is exactly the set a tunnel should offer.
+ for (const pidDir of await readdir('/proc').catch(() => [] as string[])) {
+ if (!/^\d+$/.test(pidDir)) continue;
+ const fds = await readdir(`/proc/${pidDir}/fd`).catch(() => [] as string[]);
+ for (const fd of fds) {
+ const target = await readlink(`/proc/${pidDir}/fd/${fd}`).catch(() => '');
+ const inode = /^socket:\[(\d+)\]$/.exec(target)?.[1];
+ if (inode && wanted.has(inode)) owner.set(inode, Number(pidDir));
+ }
+ }
+
+ const cwds = new Map<number, string>();
+ const commands = new Map<number, string>();
+ for (const pid of new Set(owner.values())) {
+ const cwd = await readlink(`/proc/${pid}/cwd`).catch(() => undefined);
+ if (cwd) cwds.set(pid, cwd);
+ const comm = await readFile(`/proc/${pid}/comm`, 'utf8').catch(() => undefined);
+ if (comm) commands.set(pid, comm.trim());
+ }
+
+ const entries: ListenEntry[] = sockets.map((socket) => {
+ const pid = owner.get(socket.inode);
+ return {
+ address: socket.address,
+ ...(pid === undefined ? {} : { command: commands.get(pid), pid }),
+ port: socket.port,
+ };
+ });
+ return { cwds, entries };
+};
+
+const collectWindows = async () => {
+ const [v4, v6, tasks] = await Promise.all([
+ run('netstat', ['-ano', '-p', 'TCP']),
+ run('netstat', ['-ano', '-p', 'TCPv6']),
+ run('tasklist', ['/FO', 'CSV', '/NH']).catch(() => ''),
+ ]);
+ const names = parseTasklist(tasks);
+ // Windows exposes no cheap per-process cwd, so nothing is marked in-project.
+ const entries = [...parseNetstat(v4), ...parseNetstat(v6)].map((entry) => ({
+ ...entry,
+ command: entry.pid === undefined ? undefined : names.get(entry.pid),
+ }));
+ return { cwds: new Map<number, string>(), entries };
+};
+
+export const listListeningPorts = async (
+ params: ListListeningPortsParams = {},
+): Promise<ListListeningPortsResult> => {
+ const collect =
+ process.platform === 'darwin'
+ ? collectDarwin
+ : process.platform === 'linux'
+ ? collectLinux
+ : process.platform === 'win32'
+ ? collectWindows
+ : undefined;
+ if (!collect) return { ports: [], supported: false };
+
+ try {
+ const { cwds, entries } = await collect();
+ // The OS reports resolved paths (macOS `/tmp` → `/private/tmp`), so the
+ // project root has to be resolved the same way before comparing.
+ const cwd = params.cwd ? await realpath(params.cwd).catch(() => params.cwd) : undefined;
+ return {
+ ports: summarizeListeners(entries, { cwd, cwds, ownPid: process.pid }),
+ supported: true,
+ };
+ } catch {
+ // e.g. `lsof` missing: say so, so the UI can fall back to manual entry.
+ return { ports: [], supported: false };
+ }
+};
diff --git a/packages/device-gateway-client/src/loopback.test.ts b/packages/device-gateway-client/src/loopback.test.ts
new file mode 100644
index 00000000000..000088dfcf5
--- /dev/null
+++ b/packages/device-gateway-client/src/loopback.test.ts
@@ -0,0 +1,152 @@
+import http from 'node:http';
+import type { AddressInfo } from 'node:net';
+
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+
+import { ensureLoopbackBypassesProxy, LoopbackResolver } from './loopback';
+import { DeviceTunnelHost } from './tunnel';
+import type { TunnelClientFrame } from './types';
+
+describe('LoopbackResolver', () => {
+ it('keeps 127.0.0.1 when IPv4 answers', async () => {
+ const probe = vi.fn(async () => true);
+ expect(await new LoopbackResolver(probe).resolve({ host: '127.0.0.1', port: 3000 })).toBe(
+ '127.0.0.1',
+ );
+ expect(probe).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to ::1 when only IPv6 answers', async () => {
+ const probe = vi.fn(async (host: string) => host === '::1');
+ expect(await new LoopbackResolver(probe).resolve({ host: '127.0.0.1', port: 5173 })).toBe(
+ '::1',
+ );
+ });
+
+ it('returns 127.0.0.1 when nothing answers, so the real request reports the real error', async () => {
+ expect(
+ await new LoopbackResolver(async () => false).resolve({ host: '127.0.0.1', port: 9 }),
+ ).toBe('127.0.0.1');
+ });
+
+ it('caches per port and forgets on demand', async () => {
+ const probe = vi.fn(async (host: string) => host === '::1');
+ const resolver = new LoopbackResolver(probe);
+
+ await resolver.resolve({ host: '127.0.0.1', port: 5173 });
+ await resolver.resolve({ host: '127.0.0.1', port: 5173 });
+ expect(probe).toHaveBeenCalledTimes(2); // v4 refused + v6 accepted, once
+
+ resolver.forget(5173);
+ await resolver.resolve({ host: '127.0.0.1', port: 5173 });
+ expect(probe).toHaveBeenCalledTimes(4);
+ });
+
+ it('leaves any other target alone', async () => {
+ const probe = vi.fn(async () => false);
+ expect(await new LoopbackResolver(probe).resolve({ host: '::1', port: 1 })).toBe('::1');
+ expect(probe).not.toHaveBeenCalled();
+ });
+});
+
+describe('ensureLoopbackBypassesProxy', () => {
+ it('adds every loopback spelling, including bracketed ::1, when a proxy is set', () => {
+ // The common setting that still proxies `http://[::1]:5173/`.
+ const env: Record<string, string | undefined> = {
+ HTTP_PROXY: 'http://127.0.0.1:7890',
+ NO_PROXY: 'localhost, 127.0.0.1, ::1',
+ };
+ ensureLoopbackBypassesProxy(env);
+
+ expect(env.NO_PROXY?.split(',')).toEqual(['localhost', '127.0.0.1', '::1', '[::1]']);
+ expect(env.no_proxy?.split(',')).toEqual(['localhost', '127.0.0.1', '::1', '[::1]']);
+ });
+
+ it('keeps existing exclusions and does not duplicate', () => {
+ const env: Record<string, string | undefined> = {
+ https_proxy: 'http://p:1',
+ no_proxy: 'corp.local,[::1]',
+ };
+ ensureLoopbackBypassesProxy(env);
+ expect(env.no_proxy).toBe('corp.local,[::1],localhost,127.0.0.1,::1');
+ });
+
+ it("carries one casing's exclusions into the other instead of replacing them", () => {
+ // Only one casing holds the corporate bypass list. A tool that prefers the
+ // other casing must still see it, not a loopback-only list.
+ const env: Record<string, string | undefined> = {
+ HTTP_PROXY: 'http://proxy:8080',
+ no_proxy: '.corp.internal,10.0.0.0/8',
+ };
+ ensureLoopbackBypassesProxy(env);
+
+ const expected = '.corp.internal,10.0.0.0/8,localhost,127.0.0.1,::1,[::1]';
+ expect(env.NO_PROXY).toBe(expected);
+ expect(env.no_proxy).toBe(expected);
+ });
+
+ it('merges exclusions that differ between the two casings', () => {
+ const env: Record<string, string | undefined> = {
+ HTTP_PROXY: 'http://proxy:8080',
+ NO_PROXY: 'a.internal,localhost',
+ no_proxy: 'b.internal',
+ };
+ ensureLoopbackBypassesProxy(env);
+
+ const expected = 'a.internal,localhost,b.internal,127.0.0.1,::1,[::1]';
+ expect(env.NO_PROXY).toBe(expected);
+ expect(env.no_proxy).toBe(expected);
+ });
+
+ it('leaves the environment alone when no proxy is configured', () => {
+ const env: Record<string, string | undefined> = { NO_PROXY: 'corp.local' };
+ ensureLoopbackBypassesProxy(env);
+ expect(env).toEqual({ NO_PROXY: 'corp.local' });
+ });
+});
+
+describe('tunnel to a dev server bound to ::1 only', () => {
+ // What `vite` with no `--host` does on macOS: listen on [::1] alone.
+ let server: http.Server;
+ let port: number;
+
+ beforeAll(async () => {
+ server = http.createServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'text/plain' });
+ res.end('served over ::1');
+ });
+ await new Promise<void>((resolve) => server.listen(0, '::1', resolve));
+ port = (server.address() as AddressInfo).port;
+ });
+
+ afterAll(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ it('reaches it even though the gateway pins 127.0.0.1', async () => {
+ const frames: TunnelClientFrame[] = [];
+ const host = new DeviceTunnelHost({ send: (frame) => frames.push(frame) });
+
+ host.handleFrame({
+ connId: 'c1',
+ head: { headers: [], method: 'GET', path: '/' },
+ target: { host: '127.0.0.1', port },
+ type: 'tunnel_open',
+ });
+ host.handleFrame({ connId: 'c1', data: '', fin: true, seq: 1, type: 'tunnel_data' });
+
+ await vi.waitFor(
+ () => expect(frames.some((f) => f.type === 'tunnel_data' && f.fin)).toBe(true),
+ { timeout: 5000 },
+ );
+ expect(frames.find((f) => f.type === 'tunnel_open_ack')).toMatchObject({
+ head: { status: 200 },
+ ok: true,
+ });
+ const body = frames
+ .filter((f) => f.type === 'tunnel_data' && f.data)
+ .map((f) => Buffer.from((f as { data: string }).data, 'base64').toString())
+ .join('');
+ expect(body).toBe('served over ::1');
+ });
+});
diff --git a/packages/device-gateway-client/src/loopback.ts b/packages/device-gateway-client/src/loopback.ts
new file mode 100644
index 00000000000..e2875832a3a
--- /dev/null
+++ b/packages/device-gateway-client/src/loopback.ts
@@ -0,0 +1,113 @@
+import net from 'node:net';
+
+/**
+ * Which loopback address actually answers on a port.
+ *
+ * The gateway pins tunnel targets to `127.0.0.1`, but plenty of dev servers
+ * bind `localhost`, which newer Node resolves to `::1` only — `vite` with no
+ * `--host` does exactly that on macOS. Dialing `127.0.0.1` then gets
+ * ECONNREFUSED for a server that is plainly running. So before a tunnel dials
+ * out, probe the port and fall back to `::1` when IPv4 refuses. Both are
+ * loopback, so the security boundary is unchanged.
+ *
+ * Probing is a TCP connect-and-close, done before the real request so the
+ * request itself (and any streamed body) is only ever sent once. Results are
+ * cached briefly per port; a stale answer costs one failed request, after
+ * which the cache entry is dropped.
+ */
+
+const PROBE_TIMEOUT_MS = 1000;
+
+/** Every spelling of loopback a proxy exclusion list might need. */
+const LOOPBACK_NO_PROXY = ['localhost', '127.0.0.1', '::1', '[::1]'];
+
+/**
+ * Make sure loopback traffic never goes to an HTTP proxy.
+ *
+ * A tunnel only ever dials this machine, but with `HTTP_PROXY` set, Node's
+ * env-proxy mode (`NODE_USE_ENV_PROXY=1`) sends requests to the proxy unless
+ * `NO_PROXY` matches the host — and the common `NO_PROXY=...,::1` does not
+ * match the bracketed `[::1]` a URL carries, so the `::1` fallback below
+ * would land on the proxy and come back as its 502. Adding every loopback
+ * spelling is correct for any process: nothing should proxy loopback.
+ *
+ * Node reads these variables per request, so this takes effect immediately.
+ * Bun snapshots them at startup, so a source run under `bun` with a proxy set
+ * still needs `[::1]` in `NO_PROXY` from the environment.
+ */
+export const ensureLoopbackBypassesProxy = (
+ env: Record<string, string | undefined> = process.env,
+): void => {
+ const hasProxy = [
+ 'HTTP_PROXY',
+ 'HTTPS_PROXY',
+ 'http_proxy',
+ 'https_proxy',
+ 'ALL_PROXY',
+ 'all_proxy',
+ ].some((name) => !!env[name]);
+ if (!hasProxy) return;
+
+ // Tools disagree on which casing wins, so both end up holding the same list:
+ // everything either one already excluded, plus loopback. Writing loopback
+ // alone into the casing that was unset would make a tool that prefers it
+ // drop the user's own exclusions (e.g. a corporate bypass list).
+ const entries: string[] = [];
+ for (const name of ['NO_PROXY', 'no_proxy']) {
+ for (const entry of (env[name] ?? '').split(',')) {
+ const host = entry.trim();
+ if (host && !entries.includes(host)) entries.push(host);
+ }
+ }
+ for (const host of LOOPBACK_NO_PROXY) if (!entries.includes(host)) entries.push(host);
+
+ const merged = entries.join(',');
+ for (const name of ['NO_PROXY', 'no_proxy']) if (env[name] !== merged) env[name] = merged;
+};
+
+const CACHE_TTL_MS = 30_000;
+
+type Probe = (host: string, port: number) => Promise<boolean>;
+
+const tcpProbe: Probe = (host, port) =>
+ new Promise((resolve) => {
+ const socket = net.connect({ host, port });
+ const done = (ok: boolean) => {
+ socket.destroy();
+ resolve(ok);
+ };
+ socket.setTimeout(PROBE_TIMEOUT_MS, () => done(false));
+ socket.once('connect', () => done(true));
+ socket.once('error', () => done(false));
+ });
+
+export class LoopbackResolver {
+ private cache = new Map<number, { expires: number; host: string }>();
+
+ constructor(private probe: Probe = tcpProbe) {}
+
+ /**
+ * The host to dial for `target`. Anything other than `127.0.0.1` passes
+ * through untouched; for `127.0.0.1` the answer is `::1` only when IPv4
+ * refuses and IPv6 accepts. If neither answers, `127.0.0.1` is returned so
+ * the real request produces the real error.
+ */
+ async resolve(target: { host: string; port: number }): Promise<string> {
+ if (target.host !== '127.0.0.1') return target.host;
+
+ const cached = this.cache.get(target.port);
+ if (cached && cached.expires > Date.now()) return cached.host;
+
+ let host = '127.0.0.1';
+ if (!(await this.probe('127.0.0.1', target.port)) && (await this.probe('::1', target.port))) {
+ host = '::1';
+ }
+ this.cache.set(target.port, { expires: Date.now() + CACHE_TTL_MS, host });
+ return host;
+ }
+
+ /** Forget a port's answer, e.g. after a request to it failed to connect. */
+ forget(port: number): void {
+ this.cache.delete(port);
+ }
+}
diff --git a/packages/device-gateway-client/src/tunnel.ts b/packages/device-gateway-client/src/tunnel.ts
index 70fe3c1e37e..77c59a93687 100644
--- a/packages/device-gateway-client/src/tunnel.ts
+++ b/packages/device-gateway-client/src/tunnel.ts
@@ -1,6 +1,7 @@
import { Buffer } from 'node:buffer';
import type { GatewayClientLogger } from './client';
+import { ensureLoopbackBypassesProxy, LoopbackResolver } from './loopback';
import type {
TunnelClientFrame,
TunnelOpenMessage,
@@ -64,6 +65,8 @@ export interface DeviceTunnelHostOptions {
/** Injectable for tests; defaults to global `fetch`. */
fetchImpl?: TunnelFetch;
logger?: GatewayClientLogger;
+ /** Injectable for tests; defaults to a TCP-probing resolver. */
+ loopback?: LoopbackResolver;
/** Tunnels served at once. Extra opens are rejected rather than queued. */
maxConcurrent?: number;
/** Sends a frame up the device WebSocket. */
@@ -107,6 +110,7 @@ export class DeviceTunnelHost {
private logger: GatewayClientLogger;
private maxConcurrent: number;
private send: (frame: TunnelClientFrame) => void;
+ private loopback: LoopbackResolver;
private sockets: DeviceWsTunnelHost;
constructor(options: DeviceTunnelHostOptions) {
@@ -114,7 +118,11 @@ export class DeviceTunnelHost {
this.logger = options.logger ?? noopLogger;
this.maxConcurrent = options.maxConcurrent ?? 32;
this.send = options.send;
+ this.loopback = options.loopback ?? new LoopbackResolver();
+ // Tunnels dial loopback only; an HTTP proxy must never see that traffic.
+ ensureLoopbackBypassesProxy();
this.sockets = new DeviceWsTunnelHost({
+ loopback: this.loopback,
backlog: options.backlog,
createSocket: options.createUpstreamSocket,
logger: this.logger,
@@ -274,10 +282,11 @@ export class DeviceTunnelHost {
{ highWaterMark: 0 },
);
- // An IPv6 literal needs brackets or the URL is invalid.
- const authority = target.host.includes(':') ? `[${target.host}]` : target.host;
-
try {
+ // `localhost` dev servers often listen on `::1` only; see LoopbackResolver.
+ const host = await this.loopback.resolve(target);
+ // An IPv6 literal needs brackets or the URL is invalid.
+ const authority = host.includes(':') ? `[${host}]` : host;
const response = await this.fetchImpl(`http://${authority}:${target.port}${head.path}`, {
body,
// Required by undici whenever the body is a stream.
@@ -320,6 +329,8 @@ export class DeviceTunnelHost {
} catch (error) {
if (conn.closed) return;
const reason = describeError(error);
+ // A cached host may have gone stale (server restarted on the other family).
+ if (!conn.headSent) this.loopback.forget(target.port);
if (conn.headSent) {
this.send({ connId: conn.connId, reason, type: 'tunnel_close' });
} else {
diff --git a/packages/device-gateway-client/src/wsTunnel.test.ts b/packages/device-gateway-client/src/wsTunnel.test.ts
index 6f98bdb26dd..d897e2f0e6f 100644
--- a/packages/device-gateway-client/src/wsTunnel.test.ts
+++ b/packages/device-gateway-client/src/wsTunnel.test.ts
@@ -4,6 +4,7 @@ import type { AddressInfo } from 'node:net';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { type WebSocket as ServerSocket, WebSocketServer } from 'ws';
+import { LoopbackResolver } from './loopback';
import { DeviceTunnelHost } from './tunnel';
import type { TunnelClientFrame } from './types';
import { WS_RELAY_HARD_LIMIT, WS_RELAY_HIGH_WATER, WS_RELAY_LOW_WATER } from './wsTunnel';
@@ -199,16 +200,22 @@ describe('WebSocket relay backpressure', () => {
return { emit: (event: string, ...args: any[]) => handlers[event]?.(...args), socket };
};
- const setupFake = () => {
+ const setupFake = async () => {
const upstream = fakeUpstream();
const backlog = { value: 0 };
const frames: TunnelClientFrame[] = [];
const host = new DeviceTunnelHost({
backlog: () => backlog.value,
createUpstreamSocket: () => upstream.socket as never,
+ // No real TCP probe under fake timers.
+ loopback: new LoopbackResolver(async () => true),
send: (frame) => frames.push(frame),
});
open(host, 'b1');
+ // The dial runs after the (async) loopback resolution.
+ await vi.waitFor(() => expect(upstream.socket).toBeDefined());
+ await Promise.resolve();
+ await Promise.resolve();
upstream.emit('open');
return { backlog, frames, host, upstream };
};
@@ -216,8 +223,33 @@ describe('WebSocket relay backpressure', () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
- it('pauses a fast producer above the high mark and resumes once drained', () => {
- const { backlog, host, upstream } = setupFake();
+ it.each(['error', 'close'] as const)(
+ 'probes the loopback address again after a dial that fails with %s before opening',
+ async (event) => {
+ const upstream = fakeUpstream();
+ const probe = vi.fn(async () => true);
+ const host = new DeviceTunnelHost({
+ createUpstreamSocket: () => upstream.socket as never,
+ loopback: new LoopbackResolver(probe),
+ send: () => {},
+ });
+
+ open(host, 'r1');
+ await vi.waitFor(() => expect(probe).toHaveBeenCalledTimes(1));
+ await Promise.resolve();
+ await Promise.resolve();
+ // The server went away (e.g. restarted on the other address family).
+ if (event === 'error') upstream.emit('error', new Error('ECONNREFUSED'));
+ else upstream.emit('close', 1006, Buffer.from(''));
+
+ // HMR reconnects immediately: the stale cached host must not be reused.
+ open(host, 'r2');
+ await vi.waitFor(() => expect(probe).toHaveBeenCalledTimes(2));
+ },
+ );
+
+ it('pauses a fast producer above the high mark and resumes once drained', async () => {
+ const { backlog, host, upstream } = await setupFake();
backlog.value = WS_RELAY_HIGH_WATER + 1;
upstream.emit('message', Buffer.from('hmr update'), false);
@@ -234,8 +266,8 @@ describe('WebSocket relay backpressure', () => {
host.closeAll('TEST');
});
- it('keeps relaying without pausing while the uplink keeps up', () => {
- const { backlog, frames, host, upstream } = setupFake();
+ it('keeps relaying without pausing while the uplink keeps up', async () => {
+ const { backlog, frames, host, upstream } = await setupFake();
backlog.value = 1024;
upstream.emit('message', Buffer.from('a'), false);
@@ -246,8 +278,8 @@ describe('WebSocket relay backpressure', () => {
host.closeAll('TEST');
});
- it('closes with 1013 when the backlog blows past the hard cap', () => {
- const { backlog, frames, host, upstream } = setupFake();
+ it('closes with 1013 when the backlog blows past the hard cap', async () => {
+ const { backlog, frames, host, upstream } = await setupFake();
backlog.value = WS_RELAY_HARD_LIMIT + 1;
upstream.emit('message', Buffer.from('x'), false);
@@ -262,8 +294,8 @@ describe('WebSocket relay backpressure', () => {
expect(host.activeCount).toBe(0);
});
- it('stops polling the backlog once the tunnel is gone', () => {
- const { backlog, host, upstream } = setupFake();
+ it('stops polling the backlog once the tunnel is gone', async () => {
+ const { backlog, host, upstream } = await setupFake();
backlog.value = WS_RELAY_HIGH_WATER + 1;
upstream.emit('message', Buffer.from('x'), false);
diff --git a/packages/device-gateway-client/src/wsTunnel.ts b/packages/device-gateway-client/src/wsTunnel.ts
index dc7b2461db8..3250e38a463 100644
--- a/packages/device-gateway-client/src/wsTunnel.ts
+++ b/packages/device-gateway-client/src/wsTunnel.ts
@@ -3,6 +3,7 @@ import { Buffer } from 'node:buffer';
import WebSocket from 'ws';
import type { GatewayClientLogger } from './client';
+import type { LoopbackResolver } from './loopback';
import type {
TunnelClientFrame,
TunnelWsCloseMessage,
@@ -71,7 +72,8 @@ interface WsTunnel {
/** Polls the backlog while the upstream is paused. */
drainTimer?: ReturnType<typeof setInterval>;
opened: boolean;
- socket: TunnelUpstreamSocket;
+ /** Set once the loopback address is resolved and the dial has started. */
+ socket?: TunnelUpstreamSocket;
}
export class DeviceWsTunnelHost {
@@ -83,6 +85,7 @@ export class DeviceWsTunnelHost {
backlog?: () => number;
createSocket?: TunnelUpstreamFactory;
logger: GatewayClientLogger;
+ loopback?: LoopbackResolver;
send: (frame: TunnelClientFrame) => void;
},
) {}
@@ -92,11 +95,22 @@ export class DeviceWsTunnelHost {
}
open(frame: TunnelWsOpenMessage): void {
- const { connId, head, target } = frame;
+ const { connId } = frame;
if (this.tunnels.has(connId)) return;
+ // Registered before the async dial, so a close that races it still lands.
+ const tunnel: WsTunnel = { closed: false, connId, opened: false };
+ this.tunnels.set(connId, tunnel);
+ void this.dial(tunnel, frame);
+ }
+
+ private async dial(tunnel: WsTunnel, frame: TunnelWsOpenMessage): Promise<void> {
+ const { connId, head, target } = frame;
+ // `localhost` dev servers often listen on `::1` only; see LoopbackResolver.
+ const host = this.options.loopback ? await this.options.loopback.resolve(target) : target.host;
+ if (tunnel.closed) return;
// An IPv6 literal needs brackets or the URL is invalid.
- const authority = target.host.includes(':') ? `[${target.host}]` : target.host;
+ const authority = host.includes(':') ? `[${host}]` : host;
let socket: TunnelUpstreamSocket;
try {
socket = (this.options.createSocket ?? defaultFactory)(
@@ -104,12 +118,11 @@ export class DeviceWsTunnelHost {
head.protocols,
);
} catch (error) {
+ this.release(tunnel);
this.fail(connId, error);
return;
}
-
- const tunnel: WsTunnel = { closed: false, connId, opened: false, socket };
- this.tunnels.set(connId, tunnel);
+ tunnel.socket = socket;
socket.on('open', () => {
tunnel.opened = true;
@@ -132,10 +145,16 @@ export class DeviceWsTunnelHost {
this.applyBackpressure(tunnel);
});
+ // A dial that never completed may have hit the wrong loopback address (the
+ // server restarted on the other family); drop the cached answer so the
+ // next attempt — HMR reconnects right away — probes again.
+ const forgetHost = () => this.options.loopback?.forget(target.port);
+
socket.on('close', (code, reason) => {
if (tunnel.closed) return;
this.release(tunnel);
if (!tunnel.opened) {
+ forgetHost();
this.options.send({
connId,
error: 'UPSTREAM_CLOSED',
@@ -152,6 +171,7 @@ export class DeviceWsTunnelHost {
// Before the handshake completes the gateway is still waiting on an ack;
// after it, the browser needs a close.
if (!tunnel.opened) {
+ forgetHost();
this.release(tunnel);
this.fail(connId, error);
return;
@@ -163,7 +183,7 @@ export class DeviceWsTunnelHost {
/** A browser message for the upstream socket. */
message(frame: TunnelWsDataMessage): void {
const tunnel = this.tunnels.get(frame.connId);
- if (!tunnel || tunnel.closed || !tunnel.opened) return;
+ if (!tunnel?.socket || tunnel.closed || !tunnel.opened) return;
tunnel.socket.send(frame.binary ? Buffer.from(frame.data, 'base64') : frame.data);
}
@@ -173,9 +193,9 @@ export class DeviceWsTunnelHost {
if (!tunnel || tunnel.closed) return;
this.release(tunnel);
try {
- tunnel.socket.close(sendableCode(frame.code), (frame.reason ?? '').slice(0, 100));
+ tunnel.socket?.close(sendableCode(frame.code), (frame.reason ?? '').slice(0, 100));
} catch {
- tunnel.socket.terminate();
+ tunnel.socket?.terminate();
}
}
@@ -183,7 +203,7 @@ export class DeviceWsTunnelHost {
closeAll(): void {
for (const tunnel of this.tunnels.values()) {
this.release(tunnel);
- tunnel.socket.terminate();
+ tunnel.socket?.terminate();
}
}
@@ -195,7 +215,7 @@ export class DeviceWsTunnelHost {
if (backlog > WS_RELAY_HARD_LIMIT) {
this.options.logger.warn(`[tunnel] ws ${tunnel.connId} relay backlog ${backlog}B, closing`);
this.release(tunnel);
- tunnel.socket.close(1013, 'RELAY_BACKLOG');
+ tunnel.socket?.close(1013, 'RELAY_BACKLOG');
this.options.send({
code: 1013,
connId: tunnel.connId,
@@ -207,13 +227,13 @@ export class DeviceWsTunnelHost {
if (backlog <= WS_RELAY_HIGH_WATER || tunnel.drainTimer) return;
- tunnel.socket.pause();
+ tunnel.socket?.pause();
tunnel.drainTimer = setInterval(() => {
if (tunnel.closed) return;
if ((this.options.backlog?.() ?? 0) > WS_RELAY_LOW_WATER) return;
clearInterval(tunnel.drainTimer);
tunnel.drainTimer = undefined;
- tunnel.socket.resume();
+ tunnel.socket?.resume();
}, WS_RELAY_DRAIN_POLL_MS);
}
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 7ca02d53542..02c1bc4ce55 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2700,15 +2700,16 @@ export default {
'workingPanel.overview.execution.local': 'This device',
'workingPanel.overview.files': 'Files',
'workingPanel.overview.outputs': 'Outputs',
- 'workingPanel.overview.ports.addPlaceholder': 'Port number, Enter to open',
'workingPanel.overview.ports.copied': 'Link copied',
'workingPanel.overview.ports.copy': 'Copy link',
'workingPanel.overview.ports.createFailed': 'Could not expose the port',
- 'workingPanel.overview.ports.empty': 'No port exposed yet',
- 'workingPanel.overview.ports.expose': 'Expose a port',
- 'workingPanel.overview.ports.heading': 'Exposed ports',
- 'workingPanel.overview.ports.hint':
- 'The link carries a one-time token and only opens for people who can reach this device.',
+ 'workingPanel.overview.ports.detected.available': '{{count}} to open',
+ 'workingPanel.overview.ports.detected.expose': 'Open',
+ 'workingPanel.overview.ports.detected.heading': 'Detected',
+ 'workingPanel.overview.ports.detected.hideOthers': 'Hide other ports',
+ 'workingPanel.overview.ports.detected.none': 'Nothing from this project is listening yet',
+ 'workingPanel.overview.ports.detected.others': 'Other ports ({{count}})',
+ 'workingPanel.overview.ports.detected.refresh': 'Rescan',
'workingPanel.overview.ports.invalidPort': 'Enter a port between 1 and 65535',
'workingPanel.overview.ports.loadFailed': "Couldn't load ports",
'workingPanel.overview.ports.loading': 'Loading…',
@@ -2720,6 +2721,7 @@ export default {
'workingPanel.overview.ports.revokeFailed': 'Could not stop sharing',
'workingPanel.overview.ports.revoked': 'Sharing stopped',
'workingPanel.overview.ports.title': 'Ports',
+ 'workingPanel.overview.ports.unavailable': "Can't read this device's ports right now",
'workingPanel.overview.sync.ahead_one': '{{count}} commit ahead',
'workingPanel.overview.sync.ahead_other': '{{count}} commits ahead',
'workingPanel.overview.sync.behind_one': '{{count}} commit behind',
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index ced26fef6a5..232b3e99d2c 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -951,3 +951,22 @@ export const workingDirConfigSchema = z.object({
path: z.string(),
repoType: z.enum(['git', 'github']).optional(),
});
+
+/** One TCP port a device is listening on that a tunnel can reach. */
+export interface DeviceListeningPort {
+ command?: string;
+ cwd?: string;
+ /** The listening process runs inside the requested project directory. */
+ inProject: boolean;
+ /** Which loopback address reaches it — `ipv6` means `::1` only. */
+ loopback: 'both' | 'ipv4' | 'ipv6';
+ pid?: number;
+ port: number;
+}
+
+/** Result of the `listListeningPorts` device RPC. */
+export interface DeviceListeningPortsResult {
+ ports: DeviceListeningPort[];
+ /** False when the device has no detector for its platform. */
+ supported: boolean;
+}
diff --git a/src/features/Conversation/WorkingSidebar/Overview/PortSwitcher.tsx b/src/features/Conversation/WorkingSidebar/Overview/PortSwitcher.tsx
index 71d6d7eb917..1129af2463e 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/PortSwitcher.tsx
+++ b/src/features/Conversation/WorkingSidebar/Overview/PortSwitcher.tsx
@@ -1,4 +1,5 @@
-import { Icon, Input, Tooltip } from '@lobehub/ui';
+import type { DeviceListeningPort } from '@lobechat/types';
+import { Icon, Tooltip } from '@lobehub/ui';
import {
DropdownMenuItem,
DropdownMenuPopup,
@@ -7,11 +8,28 @@ import {
DropdownMenuRoot,
DropdownMenuTrigger,
} from '@lobehub/ui/base-ui';
-import { createStaticStyles } from 'antd-style';
-import { CopyIcon, GlobeIcon, LoaderCircleIcon, PlugZapIcon, XIcon } from 'lucide-react';
-import { memo, type ReactElement, useCallback, useState } from 'react';
+import { createStaticStyles, cx } from 'antd-style';
+import {
+ CopyIcon,
+ GlobeIcon,
+ LoaderCircleIcon,
+ RefreshCwIcon,
+ ServerIcon,
+ XIcon,
+} from 'lucide-react';
+import {
+ type KeyboardEvent,
+ memo,
+ type MouseEvent,
+ type ReactNode,
+ useCallback,
+ useState,
+} from 'react';
import { useTranslation } from 'react-i18next';
+import type { DeviceTunnelLink } from '@/store/device';
+
+import { OverviewRow, PickerGlyph } from './OverviewRow';
import { usePortTunnels } from './usePortTunnels';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -21,8 +39,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
display: flex;
flex-shrink: 0;
align-items: center;
+ justify-content: center;
- padding: 2px;
+ width: 20px;
+ height: 20px;
+ padding: 0;
border: none;
border-radius: 4px;
@@ -40,6 +61,30 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
outline-offset: 1px;
}
`,
+ actions: css`
+ display: flex;
+ flex-shrink: 0;
+ gap: 2px;
+ align-items: center;
+
+ /* Pull the last glyph flush with the text trailing of the other rows. */
+ margin-inline-end: -4px;
+ `,
+ available: css`
+ font-size: 12px;
+ color: ${cssVar.colorPrimary};
+ `,
+ command: css`
+ overflow: hidden;
+ flex-shrink: 1;
+
+ min-width: 0;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
container: css`
display: flex;
flex-direction: column;
@@ -52,27 +97,23 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
font-size: 12px;
color: ${cssVar.colorTextTertiary};
`,
- retry: css`
- cursor: pointer;
-
- padding: 0;
- border: none;
-
+ expose: css`
+ flex-shrink: 0;
font-size: 12px;
- color: ${cssVar.colorInfo};
-
- background: transparent;
+ font-weight: 500;
`,
- state: css`
- display: flex;
- gap: 6px;
- align-items: center;
+ /**
+ * A port that is running but not exposed yet stays one step quieter than an
+ * exposed one; the full text color is kept for what is actually reachable.
+ * Port, glyph and "Open" inherit it, so hover lifts the whole row at once.
+ */
+ idle: css`
+ color: ${cssVar.colorTextSecondary};
- padding-block: 10px;
- padding-inline: 8px;
-
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
+ &:hover,
+ &[data-highlighted] {
+ color: ${cssVar.colorText};
+ }
`,
host: css`
overflow: hidden;
@@ -85,19 +126,32 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
text-overflow: ellipsis;
white-space: nowrap;
`,
- hint: css`
- padding-block: 6px 2px;
- padding-inline: 8px;
+ header: css`
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+
+ padding-block: 6px 4px;
+ padding-inline: 8px 4px;
font-size: 11px;
- line-height: 16px;
- color: ${cssVar.colorTextQuaternary};
+ font-weight: 500;
+ color: ${cssVar.colorTextTertiary};
`,
item: css`
display: flex;
gap: 8px;
align-items: center;
`,
+ othersList: css`
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+
+ /* A dev machine listens on dozens of ports; the list scrolls inside the
+ menu instead of pushing it past the viewport. */
+ max-height: 200px;
+ `,
port: css`
flex-shrink: 0;
@@ -106,144 +160,284 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
font-weight: 500;
color: ${cssVar.colorText};
`,
- section: css`
- padding-block: 6px 4px;
+ portIdle: css`
+ color: inherit;
+ `,
+ retry: css`
+ cursor: pointer;
+
+ padding: 0;
+ border: none;
+
+ font-size: 12px;
+ color: ${cssVar.colorInfo};
+
+ background: transparent;
+ `,
+ spacer: css`
+ flex: 1;
+ min-width: 0;
+ `,
+ state: css`
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ padding-block: 10px;
padding-inline: 8px;
- font-size: 11px;
- font-weight: 500;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ toggle: css`
+ font-size: 12px;
color: ${cssVar.colorTextTertiary};
`,
}));
interface PortSwitcherProps {
- children: ReactElement;
+ /** Whether the working panel is showing; detection only runs while it is. */
+ active: boolean;
deviceId: string;
+ /** Project directory, so the device can say which ports belong to it. */
+ workingDirectory?: string;
}
/**
- * Exposes a port on the working device as a link. Opening is a two-step by
- * design: the stored link is clean, and the token that opens it is minted per
- * click, so nothing long-lived sits in the UI or the clipboard.
+ * The ports of the working device, as one list: ports that already have a link
+ * sit on top (open, copy, stop), the project's running servers follow with one
+ * click to expose, and everything else listening on the machine is folded away.
+ *
+ * Opening is two-step by design: the stored link is clean, and the token that
+ * opens it is minted per click, so nothing long-lived sits in the UI or the
+ * clipboard.
*/
-const PortSwitcher = memo<PortSwitcherProps>(({ children, deviceId }) => {
+const PortSwitcher = memo<PortSwitcherProps>(({ active, deviceId, workingDirectory }) => {
const { t } = useTranslation('chat');
const { t: tCommon } = useTranslation('common');
const [open, setOpen] = useState(false);
+ const [showOthers, setShowOthers] = useState(false);
const close = useCallback(() => setOpen(false), []);
const {
busySlug,
copyLink,
- creating,
+ creatingPort,
+ detected,
+ detectionAvailable,
+ detectionLoading,
error,
exposePort,
isLoading,
openLink,
- port,
+ otherPorts,
refresh,
+ refreshDetected,
revokeLink,
- setPort,
tunnels,
- } = usePortTunnels(deviceId, open, close);
+ } = usePortTunnels({ active, cwd: workingDirectory, deviceId, onOpened: close, open });
+
+ /**
+ * Port, then process. No "this project" tag: the main list only holds the
+ * project's own ports, and the rest are already folded under "Other ports".
+ */
+ const renderLabel = (port: number, info?: DeviceListeningPort) => (
+ <>
+ <span className={cx(styles.port, styles.portIdle)}>{port}</span>
+ {info?.command && (
+ <span className={styles.command} title={info.cwd}>
+ {info.command}
+ </span>
+ )}
+ <span className={styles.spacer} />
+ </>
+ );
+
+ /**
+ * A small button inside the menu: it acts on its own and never opens the
+ * tunnel. Kept out of the tab order because the menu focuses its first
+ * tabbable element on open, which would land here and pop its tooltip on
+ * every open; the menu items it sits on are reachable with the arrow keys.
+ */
+ const ownPress = (onPress: () => void) => ({
+ // Enter/Space must act on this button, not fall through to the menu item.
+ onKeyDown: (event: KeyboardEvent) => event.stopPropagation(),
+ tabIndex: -1,
+ onClick: (event: MouseEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ onPress();
+ },
+ });
+
+ const renderLink = (link: DeviceTunnelLink) => (
+ <DropdownMenuItem
+ className={styles.item}
+ key={link.slug}
+ onClick={(event) => {
+ event.preventDefault();
+ void openLink(link);
+ }}
+ >
+ <Icon
+ icon={busySlug === link.slug ? LoaderCircleIcon : GlobeIcon}
+ size={14}
+ spin={busySlug === link.slug}
+ />
+ {/* The link itself, so the row says where the port is reachable; copy sits
+ right beside it. A link starts with its port (`5199--slug.lobe.sh`),
+ so the port is drawn as the link's own prefix instead of repeated
+ before it — that leaves room for the whole domain. */}
+ <span className={styles.host} title={link.hostname}>
+ {link.hostname.startsWith(`${link.port}--`) ? (
+ <>
+ <span className={styles.port}>{link.port}</span>
+ {link.hostname.slice(String(link.port).length)}
+ </>
+ ) : (
+ link.hostname
+ )}
+ </span>
+ <span className={styles.actions}>
+ <Tooltip title={t('workingPanel.overview.ports.copy')}>
+ <button
+ aria-label={t('workingPanel.overview.ports.copy')}
+ className={styles.action}
+ type={'button'}
+ {...ownPress(() => void copyLink(link))}
+ >
+ <Icon icon={CopyIcon} size={13} />
+ </button>
+ </Tooltip>
+ <Tooltip title={t('workingPanel.overview.ports.revoke')}>
+ <button
+ aria-label={t('workingPanel.overview.ports.revoke')}
+ className={styles.action}
+ type={'button'}
+ {...ownPress(() => void revokeLink(link))}
+ >
+ <Icon icon={XIcon} size={13} />
+ </button>
+ </Tooltip>
+ </span>
+ </DropdownMenuItem>
+ );
+
+ const renderDetected = (item: DeviceListeningPort) => (
+ <DropdownMenuItem
+ className={cx(styles.item, styles.idle)}
+ key={item.port}
+ onClick={(event) => {
+ event.preventDefault();
+ void exposePort(item.port);
+ }}
+ >
+ <Icon
+ icon={creatingPort === item.port ? LoaderCircleIcon : ServerIcon}
+ size={14}
+ spin={creatingPort === item.port}
+ />
+ {renderLabel(item.port, item)}
+ <span className={styles.expose}>{t('workingPanel.overview.ports.detected.expose')}</span>
+ </DropdownMenuItem>
+ );
+
+ let body: ReactNode;
+ if (isLoading) {
+ body = (
+ <div className={styles.state}>
+ <Icon spin icon={LoaderCircleIcon} size={13} />
+ {t('workingPanel.overview.ports.loading')}
+ </div>
+ );
+ } else if (error) {
+ // "We couldn't ask" must not read as "nothing is open".
+ body = (
+ <div className={styles.state}>
+ {t('workingPanel.overview.ports.loadFailed')}
+ <button className={styles.retry} type={'button'} onClick={() => void refresh()}>
+ {tCommon('retry')}
+ </button>
+ </div>
+ );
+ } else if (tunnels.length === 0 && detected.length === 0) {
+ body = (
+ <div className={styles.empty}>
+ {detectionAvailable
+ ? t('workingPanel.overview.ports.detected.none')
+ : t('workingPanel.overview.ports.unavailable')}
+ </div>
+ );
+ } else {
+ body = (
+ <>
+ {tunnels.map(renderLink)}
+ {detected.map(renderDetected)}
+ </>
+ );
+ }
return (
<DropdownMenuRoot open={open} onOpenChange={setOpen}>
- <DropdownMenuTrigger>{children}</DropdownMenuTrigger>
+ <DropdownMenuTrigger>
+ <OverviewRow
+ interactive
+ icon={GlobeIcon}
+ value={t('workingPanel.overview.ports.title')}
+ trailing={
+ <>
+ {detected.length > 0 && (
+ // A running dev server the user hasn't exposed yet — say so
+ // without making them open the menu.
+ <span className={styles.available}>
+ {t('workingPanel.overview.ports.detected.available', { count: detected.length })}
+ </span>
+ )}
+ <PickerGlyph />
+ </>
+ }
+ />
+ </DropdownMenuTrigger>
<DropdownMenuPortal>
<DropdownMenuPositioner placement={'bottomLeft'} sideOffset={8}>
<DropdownMenuPopup>
<div className={styles.container}>
- <div className={styles.section}>{t('workingPanel.overview.ports.heading')}</div>
-
- {isLoading ? (
- <div className={styles.state}>
- <Icon spin icon={LoaderCircleIcon} size={13} />
- {t('workingPanel.overview.ports.loading')}
- </div>
- ) : error ? (
- // "We couldn't ask" must not read as "nothing is open".
- <div className={styles.state}>
- {t('workingPanel.overview.ports.loadFailed')}
- <button className={styles.retry} type={'button'} onClick={() => void refresh()}>
- {tCommon('retry')}
+ <div className={styles.header}>
+ {t('workingPanel.overview.ports.title')}
+ {/* Kept even when detection is unavailable: a device that just came
+ back online is otherwise stuck on the stale answer. */}
+ <Tooltip title={t('workingPanel.overview.ports.detected.refresh')}>
+ <button
+ aria-label={t('workingPanel.overview.ports.detected.refresh')}
+ className={styles.action}
+ type={'button'}
+ {...ownPress(() => void refreshDetected())}
+ >
+ <Icon icon={RefreshCwIcon} size={12} spin={detectionLoading} />
</button>
- </div>
- ) : tunnels.length === 0 ? (
- <div className={styles.empty}>{t('workingPanel.overview.ports.empty')}</div>
- ) : (
- tunnels.map((link) => (
+ </Tooltip>
+ </div>
+
+ {body}
+
+ {otherPorts.length > 0 && (
+ <>
<DropdownMenuItem
- className={styles.item}
- key={link.slug}
- onClick={(event) => {
- event.preventDefault();
- void openLink(link);
- }}
+ className={styles.toggle}
+ closeOnClick={false}
+ onClick={() => setShowOthers((value) => !value)}
>
- <Icon
- icon={busySlug === link.slug ? LoaderCircleIcon : GlobeIcon}
- size={14}
- spin={busySlug === link.slug}
- />
- <span className={styles.port}>{link.port}</span>
- <span className={styles.host}>{link.hostname}</span>
- <Tooltip title={t('workingPanel.overview.ports.copy')}>
- <button
- aria-label={t('workingPanel.overview.ports.copy')}
- className={styles.action}
- type={'button'}
- // Enter/Space must act on this button, not fall through
- // to the menu item and open the tunnel instead.
- onKeyDown={(event) => event.stopPropagation()}
- onClick={(event) => {
- event.preventDefault();
- event.stopPropagation();
- void copyLink(link);
- }}
- >
- <Icon icon={CopyIcon} size={13} />
- </button>
- </Tooltip>
- <Tooltip title={t('workingPanel.overview.ports.revoke')}>
- <button
- aria-label={t('workingPanel.overview.ports.revoke')}
- className={styles.action}
- type={'button'}
- onKeyDown={(event) => event.stopPropagation()}
- onClick={(event) => {
- event.preventDefault();
- event.stopPropagation();
- void revokeLink(link);
- }}
- >
- <Icon icon={XIcon} size={13} />
- </button>
- </Tooltip>
+ {showOthers
+ ? t('workingPanel.overview.ports.detected.hideOthers')
+ : t('workingPanel.overview.ports.detected.others', {
+ count: otherPorts.length,
+ })}
</DropdownMenuItem>
- ))
+ {showOthers && (
+ <div className={styles.othersList}>{otherPorts.map(renderDetected)}</div>
+ )}
+ </>
)}
-
- <div className={styles.section}>{t('workingPanel.overview.ports.expose')}</div>
- <Input
- disabled={creating}
- placeholder={t('workingPanel.overview.ports.addPlaceholder')}
- size={'small'}
- value={port}
- prefix={
- <Icon
- icon={creating ? LoaderCircleIcon : PlugZapIcon}
- size={14}
- spin={creating}
- />
- }
- onChange={(e) => setPort(e.target.value)}
- onKeyDown={(event) => {
- event.stopPropagation();
- if (event.key === 'Enter') void exposePort();
- }}
- />
- <div className={styles.hint}>{t('workingPanel.overview.ports.hint')}</div>
</div>
</DropdownMenuPopup>
</DropdownMenuPositioner>
diff --git a/src/features/Conversation/WorkingSidebar/Overview/__tests__/usePortTunnels.test.ts b/src/features/Conversation/WorkingSidebar/Overview/__tests__/usePortTunnels.test.ts
index 8c88de62854..c126c6a93ce 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/__tests__/usePortTunnels.test.ts
+++ b/src/features/Conversation/WorkingSidebar/Overview/__tests__/usePortTunnels.test.ts
@@ -16,18 +16,30 @@ const tunnels = vi.hoisted(() => ({
value: [] as unknown[] | undefined,
}));
const isDesktop = vi.hoisted(() => ({ value: false }));
+const detection = vi.hoisted(() => ({
+ data: undefined as unknown,
+ isLoading: false,
+ isValidating: false,
+ mutate: vi.fn(),
+}));
vi.mock('@/services/device', () => ({
deviceService: { createTunnel, openTunnel, revokeTunnel },
}));
+const tunnelsEnabledArgs = vi.hoisted(() => [] as boolean[]);
+
vi.mock('@/store/device', () => ({
- useFetchDeviceTunnels: () => ({
- data: tunnels.value,
- error: tunnels.error,
- isLoading: tunnels.isLoading,
- mutate,
- }),
+ useFetchDeviceListeningPorts: () => detection,
+ useFetchDeviceTunnels: (_deviceId: string, enabled: boolean) => {
+ tunnelsEnabledArgs.push(enabled);
+ return {
+ data: tunnels.value,
+ error: tunnels.error,
+ isLoading: tunnels.isLoading,
+ mutate,
+ };
+ },
}));
vi.mock('@lobechat/const', () => ({
@@ -55,7 +67,10 @@ const link = {
};
const onOpened = vi.fn();
-const setup = () => renderHook(() => usePortTunnels('device-1', true, onOpened));
+const setup = () =>
+ renderHook(() =>
+ usePortTunnels({ active: true, cwd: '/work/app', deviceId: 'device-1', onOpened, open: true }),
+ );
/** A pre-opened tab: `window.open` is called before the token round trip. */
const tab = { close: vi.fn(), location: { href: '' }, opener: {} as unknown };
@@ -66,6 +81,9 @@ beforeEach(() => {
tunnels.error = undefined;
tunnels.isLoading = false;
isDesktop.value = false;
+ detection.data = undefined;
+ detection.isLoading = false;
+ detection.isValidating = false;
tab.location.href = '';
tab.opener = {};
vi.stubGlobal(
@@ -82,28 +100,22 @@ describe('usePortTunnels', () => {
});
const { result } = setup();
- act(() => result.current.setPort('3000'));
- await act(() => result.current.exposePort());
+ await act(() => result.current.exposePort(3000));
expect(createTunnel).toHaveBeenCalledWith({ deviceId: 'device-1', port: 3000 });
- // Typing a port means "let me see it": no second click to open it.
+ // Choosing a port means "let me see it": no second click to open it.
expect(tab.location.href).toBe('https://3000--abcdefgh.lobe.sh/?token=fresh');
- expect(result.current.port).toBe('');
expect(onOpened).toHaveBeenCalled();
});
- it.each(['0', '70000', 'abc', '', ' ', '80.5'])(
- 'refuses %j without calling the server',
- async (value) => {
- const { result } = setup();
+ it.each([0, 70_000, 80.5, Number.NaN])('refuses %j without calling the server', async (value) => {
+ const { result } = setup();
- act(() => result.current.setPort(value));
- await act(() => result.current.exposePort());
+ await act(() => result.current.exposePort(value));
- expect(toastError).toHaveBeenCalledWith('workingPanel.overview.ports.invalidPort');
- expect(createTunnel).not.toHaveBeenCalled();
- },
- );
+ expect(toastError).toHaveBeenCalledWith('workingPanel.overview.ports.invalidPort');
+ expect(createTunnel).not.toHaveBeenCalled();
+ });
it('opens an existing link with a freshly minted token, never the stored URL', async () => {
tunnels.value = [link];
@@ -143,13 +155,12 @@ describe('usePortTunnels', () => {
createTunnel.mockRejectedValue(new Error('offline'));
const { result } = setup();
- act(() => result.current.setPort('5173'));
- await act(() => result.current.exposePort());
+ await act(() => result.current.exposePort(5173));
expect(toastError).toHaveBeenCalledWith('workingPanel.overview.ports.createFailed');
// The reserved tab must not be left sitting on about:blank.
expect(tab.close).toHaveBeenCalled();
- expect(result.current.creating).toBe(false);
+ expect(result.current.creatingPort).toBeUndefined();
});
it('never navigates to a non-http URL the server might return', async () => {
@@ -219,4 +230,66 @@ describe('usePortTunnels', () => {
expect(setup().result.current.error).toBeTruthy();
});
});
+
+ describe('detected ports', () => {
+ const port = (overrides: Record<string, unknown>) => ({
+ command: 'node',
+ inProject: true,
+ loopback: 'both',
+ port: 5173,
+ ...overrides,
+ });
+
+ it('offers the project ports that are not exposed yet, and keeps the rest aside', () => {
+ tunnels.value = [link]; // 3000 is already exposed
+ detection.data = {
+ ports: [
+ port({ port: 3000 }),
+ port({ port: 5173 }),
+ port({ command: 'postgres', inProject: false, port: 5432 }),
+ ],
+ supported: true,
+ };
+
+ const { result } = setup();
+
+ expect(result.current.detected.map((p) => p.port)).toEqual([5173]);
+ expect(result.current.otherPorts.map((p) => p.port)).toEqual([5432]);
+ expect(result.current.detectionAvailable).toBe(true);
+ });
+
+ it('drops a port from the detected list once it has a link', () => {
+ tunnels.value = [link];
+ detection.data = { ports: [port({ port: 3000 })], supported: true };
+
+ // The exposed row on top already shows it, with its link.
+ expect(setup().result.current).toMatchObject({ detected: [], otherPorts: [] });
+ });
+
+ it('reports no detection for a device that cannot answer', () => {
+ detection.data = null;
+ expect(setup().result.current).toMatchObject({ detected: [], detectionAvailable: false });
+ });
+
+ it('shows a rescan in progress even though the previous answer is still there', () => {
+ detection.data = { ports: [port({ port: 3000 })], supported: true };
+ detection.isValidating = true;
+ expect(setup().result.current.detectionLoading).toBe(true);
+ });
+ });
+
+ it('reads the link list while the panel shows, so the badge never counts an exposed port', () => {
+ tunnelsEnabledArgs.length = 0;
+ renderHook(() =>
+ usePortTunnels({
+ active: true,
+ cwd: '/work/app',
+ deviceId: 'device-1',
+ onOpened,
+ open: false,
+ }),
+ );
+ // Menu closed, panel showing: the list must still be requested.
+ expect(tunnelsEnabledArgs.at(-1)).toBe(true);
+ });
});
diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
index 3d98afd0782..d6600376693 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
@@ -14,7 +14,6 @@ import {
FileTextIcon,
GitBranchIcon,
GitForkIcon,
- GlobeIcon,
LaptopIcon,
RefreshCwIcon,
TriangleAlertIcon,
@@ -332,17 +331,6 @@ const Overview = memo<OverviewProps>(
onClick={() => onOpenTab('review')}
/>
- {tunnelsEnabled && deviceId && (
- <PortSwitcher deviceId={deviceId}>
- <OverviewRow
- interactive
- icon={GlobeIcon}
- trailing={<PickerGlyph />}
- value={t('workingPanel.overview.ports.title')}
- />
- </PortSwitcher>
- )}
-
{pullRequest && prVisual && ci && (
<Tooltip title={`#${pullRequest.number} ${pullRequest.title}`}>
<div>
@@ -421,7 +409,17 @@ const Overview = memo<OverviewProps>(
repoType={repoType}
onClick={() => onOpenTab('files')}
/>
- <Flexbox className={sectionStyles.section}>{workspaceSection}</Flexbox>
+ <Flexbox className={sectionStyles.section}>
+ {workspaceSection}
+ {/* Outside the git rows: a dev server runs in plain folders too. */}
+ {tunnelsEnabled && deviceId && (
+ <PortSwitcher
+ active={active}
+ deviceId={deviceId}
+ workingDirectory={workingDirectory}
+ />
+ )}
+ </Flexbox>
</>
)}
diff --git a/src/features/Conversation/WorkingSidebar/Overview/usePortTunnels.ts b/src/features/Conversation/WorkingSidebar/Overview/usePortTunnels.ts
index a465430d246..bcf5138b528 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/usePortTunnels.ts
+++ b/src/features/Conversation/WorkingSidebar/Overview/usePortTunnels.ts
@@ -1,12 +1,17 @@
import { isDesktop } from '@lobechat/const';
+import type { DeviceListeningPort } from '@lobechat/types';
import { copyToClipboard } from '@lobehub/ui';
import { toast } from '@lobehub/ui/base-ui';
-import { useCallback, useState } from 'react';
+import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { isSafeExternalUrl } from '@/features/Work/descriptors';
import { deviceService } from '@/services/device';
-import { type DeviceTunnelLink, useFetchDeviceTunnels } from '@/store/device';
+import {
+ type DeviceTunnelLink,
+ useFetchDeviceListeningPorts,
+ useFetchDeviceTunnels,
+} from '@/store/device';
/**
* State and actions behind the Ports row.
@@ -15,13 +20,47 @@ import { type DeviceTunnelLink, useFetchDeviceTunnels } from '@/store/device';
* that opens it is minted per action, so neither the UI nor the clipboard ever
* holds a long-lived credential.
*/
-export const usePortTunnels = (deviceId: string, open: boolean, onOpened: () => void) => {
+export const usePortTunnels = (options: {
+ /** Whether the working panel is showing; detection only runs while it is. */
+ active: boolean;
+ /** Project directory, so the device can say which ports are this project's. */
+ cwd?: string;
+ deviceId: string;
+ onOpened: () => void;
+ /** Whether the ports menu is open; the link list is only read while it is. */
+ open: boolean;
+}) => {
+ const { active, cwd, deviceId, onOpened, open } = options;
const { t } = useTranslation('chat');
- const [port, setPort] = useState('');
const [busySlug, setBusySlug] = useState<string>();
- const [creating, setCreating] = useState(false);
+ /** The port being exposed — typed or detected — so its row can show progress. */
+ const [creatingPort, setCreatingPort] = useState<number>();
- const { data: tunnels, error, isLoading, mutate } = useFetchDeviceTunnels(deviceId, open);
+ // Read whenever the panel shows, not only with the menu open: the row's
+ // "N to open" count subtracts already-exposed ports, and without the list it
+ // would count a port that already has a link.
+ const {
+ data: tunnels,
+ error,
+ isLoading,
+ mutate,
+ } = useFetchDeviceTunnels(deviceId, active || open);
+ const detection = useFetchDeviceListeningPorts(deviceId, cwd, active);
+
+ /**
+ * Detected ports minus the ones already exposed on this device. Only the
+ * project's own ports count as "available": a dev machine listens on dozens
+ * of unrelated ports (databases, Docker, system services).
+ */
+ const { detected, others } = useMemo(() => {
+ const ports = detection.data?.ports ?? [];
+ const exposed = new Set((tunnels ?? []).map((link) => link.port));
+ const fresh = ports.filter((p) => !exposed.has(p.port));
+ return {
+ detected: fresh.filter((p) => p.inProject),
+ others: fresh.filter((p) => !p.inProject),
+ };
+ }, [detection.data, tunnels]);
/**
* Claim the tab while the click is still the browser's idea of user
@@ -104,47 +143,54 @@ export const usePortTunnels = (deviceId: string, open: boolean, onOpened: () =>
[mutate, t],
);
- const exposePort = useCallback(async () => {
- const parsed = Number(port.trim());
- if (!port.trim() || !Number.isInteger(parsed) || parsed < 1 || parsed > 65_535) {
- toast.error(t('workingPanel.overview.ports.invalidPort'));
- return;
- }
+ /** Expose a detected port and open it. */
+ const exposePort = useCallback(
+ async (target: number) => {
+ if (!Number.isInteger(target) || target < 1 || target > 65_535) {
+ toast.error(t('workingPanel.overview.ports.invalidPort'));
+ return;
+ }
- const tab = reserveTab();
- if (!tab && !isDesktop) {
- toast.error(t('workingPanel.overview.ports.popupBlocked'));
- return;
- }
+ const tab = reserveTab();
+ if (!tab && !isDesktop) {
+ toast.error(t('workingPanel.overview.ports.popupBlocked'));
+ return;
+ }
- setCreating(true);
- try {
- const link = await deviceService.createTunnel({ deviceId, port: parsed });
- setPort('');
- await mutate();
- // Typing a port means "let me see it" — open it without a second click.
- navigateTab(tab, link.openUrl);
- onOpened();
- } catch {
- tab?.close();
- toast.error(t('workingPanel.overview.ports.createFailed'));
- } finally {
- setCreating(false);
- }
- }, [deviceId, mutate, navigateTab, onOpened, port, reserveTab, t]);
+ setCreatingPort(target);
+ try {
+ const link = await deviceService.createTunnel({ deviceId, port: target });
+ await mutate();
+ // Choosing a port means "let me see it" — open it without a second click.
+ navigateTab(tab, link.openUrl);
+ onOpened();
+ } catch {
+ tab?.close();
+ toast.error(t('workingPanel.overview.ports.createFailed'));
+ } finally {
+ setCreatingPort(undefined);
+ }
+ },
+ [deviceId, mutate, navigateTab, onOpened, reserveTab, t],
+ );
return {
busySlug,
copyLink,
- creating,
+ creatingPort,
+ detected,
+ /** False when the device can't detect (offline, or a client that predates it). */
+ detectionAvailable: !!detection.data?.supported,
+ // Validating, not loading: a manual rescan keeps the old data and must still spin.
+ detectionLoading: detection.isValidating,
error,
exposePort,
isLoading,
openLink,
- port,
refresh: mutate,
+ refreshDetected: detection.mutate,
+ otherPorts: others as DeviceListeningPort[],
revokeLink,
- setPort,
tunnels: tunnels ?? [],
};
};
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index a3fa2276b82..1120aa061bb 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -842,6 +842,11 @@ export const deviceKeys = {
(workspaceId: string | null, deviceId: string, path?: string, cursor?: string) =>
['device:browseDirectory', workspaceId, deviceId, path, cursor] as const,
),
+ listeningPorts: def(
+ 'device:listeningPorts',
+ (workspaceId: string | null, deviceId: string, cwd?: string) =>
+ ['device:listeningPorts', workspaceId, deviceId, cwd] as const,
+ ),
tunnels: def('device:tunnels', (workspaceId: string | null, deviceId: string) => [
'device:tunnels',
workspaceId,
diff --git a/src/services/device.ts b/src/services/device.ts
index 51f26f33554..588cea02ab5 100644
--- a/src/services/device.ts
+++ b/src/services/device.ts
@@ -64,6 +64,11 @@ class DeviceService {
return lambdaClient.device.openTunnel.mutate(input);
}
+ /** Ports the device is listening on; `null` when it can't answer. */
+ listListeningPorts(input: Parameters<DeviceClient['listListeningPorts']['query']>[0]) {
+ return lambdaClient.device.listListeningPorts.query(input);
+ }
+
/** Revoke a link. */
revokeTunnel(input: Parameters<DeviceClient['revokeTunnel']['mutate']>[0]) {
return lambdaClient.device.revokeTunnel.mutate(input);
diff --git a/src/store/device/tunnelHooks.ts b/src/store/device/tunnelHooks.ts
index 7a8bd61e278..3812bb3e9b0 100644
--- a/src/store/device/tunnelHooks.ts
+++ b/src/store/device/tunnelHooks.ts
@@ -1,3 +1,5 @@
+import type { DeviceListeningPortsResult } from '@lobechat/types';
+
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useClientDataSWR } from '@/libs/swr';
import { deviceKeys } from '@/libs/swr/keys';
@@ -30,3 +32,23 @@ export const useFetchDeviceTunnels = (deviceId?: string, enabled = true) => {
{ revalidateOnFocus: false },
);
};
+
+/**
+ * Ports the device is listening on, for one-click exposure. Asked when the
+ * working panel shows (and on focus) rather than polled: detection spawns a
+ * process on the device, and a port that appears later is one click of
+ * "refresh" away. `null` data means the device couldn't answer.
+ */
+export const useFetchDeviceListeningPorts = (
+ deviceId: string | undefined,
+ cwd: string | undefined,
+ enabled = true,
+) => {
+ const workspaceId = useActiveWorkspaceId();
+
+ return useClientDataSWR<DeviceListeningPortsResult | null>(
+ enabled && deviceId ? deviceKeys.listeningPorts(workspaceId, deviceId, cwd) : null,
+ async () => deviceService.listListeningPorts({ cwd, deviceId: deviceId! }),
+ { revalidateOnFocus: true },
+ );
+};