🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(device): expose a port from the working sidebar (#19886)
Arvin Xu9b16b68d6570
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 810bbb1fb66..4cd26584f76 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2560,6 +2560,25 @@"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.invalidPort": "Enter a port between 1 and 65535",+ "workingPanel.overview.ports.loadFailed": "Couldn't load ports",+ "workingPanel.overview.ports.loading": "Loading…",+ "workingPanel.overview.ports.more": "+{{count}}",+ "workingPanel.overview.ports.none": "None",+ "workingPanel.overview.ports.openFailed": "Could not open the link",+ "workingPanel.overview.ports.popupBlocked": "Allow pop-ups for this site to open the link",+ "workingPanel.overview.ports.revoke": "Stop sharing",+ "workingPanel.overview.ports.revokeFailed": "Could not stop sharing",+ "workingPanel.overview.ports.revoked": "Sharing stopped",+ "workingPanel.overview.ports.title": "Ports","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/en-US/labs.json b/locales/en-US/labs.jsonindex 161090d58eb..f244fd8cf24 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -14,6 +14,8 @@"features.codexAppServer.title": "Codex App Server Runtime","features.desktopSplitView.desc": "Show two desktop tabs side by side, with independent navigation and a resizable divider.","features.desktopSplitView.title": "Split Tab View",+ "features.deviceTunnel.desc": "Give a port on the working device a link, so a dev server running there can be opened from here. The link only works for people who can reach that device.",+ "features.deviceTunnel.title": "Remote Port Links","features.evalCapture.desc": "Adds a message action that captures a conversation turn — its prior context, input and the answer it produced — as an evaluation test case.","features.evalCapture.title": "Save a turn as an eval case","features.gatewayMux.desc": "Route every agent run in this tab over one shared gateway WebSocket instead of opening a socket per run. Reconnects and event replay are handled per run on the shared connection.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 7e0ec0ecbee..169efcb6cbd 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2560,6 +2560,25 @@"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.invalidPort": "请输入 1–65535 之间的端口",+ "workingPanel.overview.ports.loadFailed": "读取端口失败",+ "workingPanel.overview.ports.loading": "正在读取…",+ "workingPanel.overview.ports.more": "+{{count}}",+ "workingPanel.overview.ports.none": "未开放",+ "workingPanel.overview.ports.openFailed": "打开链接失败",+ "workingPanel.overview.ports.popupBlocked": "请允许本站弹出窗口后再打开链接",+ "workingPanel.overview.ports.revoke": "停止共享",+ "workingPanel.overview.ports.revokeFailed": "停止共享失败",+ "workingPanel.overview.ports.revoked": "已停止共享",+ "workingPanel.overview.ports.title": "端口","workingPanel.overview.sync.ahead_one": "领先 {{count}} 个提交","workingPanel.overview.sync.ahead_other": "领先 {{count}} 个提交","workingPanel.overview.sync.behind_one": "落后 {{count}} 个提交",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex c8fb43918cb..b07fa548451 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -14,6 +14,8 @@"features.codexAppServer.title": "Codex App Server 运行时","features.desktopSplitView.desc": "在桌面端并排显示两个标签页,支持独立导航和拖拽调整分栏宽度。","features.desktopSplitView.title": "标签页分栏",+ "features.deviceTunnel.desc": "给工作设备上的端口一个链接,在这里就能打开那台机器上跑着的 dev server。链接只对能访问该设备的人有效。",+ "features.deviceTunnel.title": "远程端口链接","features.evalCapture.desc": "在消息动作里增加一项,把一轮对话(前置上下文、本轮输入与它产生的回答)捕获成评测用例。","features.evalCapture.title": "把对话保存为评测用例","features.gatewayMux.desc": "当前标签页里的所有智能体运行共用一条网关 WebSocket,而不是每次运行各开一条;断线重连与事件回放在这条共享连接上按运行分别处理。",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 73b53a22307..7ca02d53542 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2700,6 +2700,26 @@ 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.invalidPort': 'Enter a port between 1 and 65535',+ 'workingPanel.overview.ports.loadFailed': "Couldn't load ports",+ 'workingPanel.overview.ports.loading': 'Loading…',+ 'workingPanel.overview.ports.popupBlocked': 'Allow pop-ups for this site to open the link',+ 'workingPanel.overview.ports.more': '+{{count}}',+ 'workingPanel.overview.ports.none': 'None',+ 'workingPanel.overview.ports.openFailed': 'Could not open the link',+ 'workingPanel.overview.ports.revoke': 'Stop sharing',+ 'workingPanel.overview.ports.revokeFailed': 'Could not stop sharing',+ 'workingPanel.overview.ports.revoked': 'Sharing stopped',+ 'workingPanel.overview.ports.title': 'Ports','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/locales/src/default/labs.ts b/packages/locales/src/default/labs.tsindex 6126cfc20d2..928d7341619 100644--- a/packages/locales/src/default/labs.ts+++ b/packages/locales/src/default/labs.ts@@ -27,6 +27,9 @@ export default {'features.evalCapture.desc':'Adds a message action that captures a conversation turn — its prior context, input and the answer it produced — as an evaluation test case.','features.evalCapture.title': 'Save a turn as an eval case',+ 'features.deviceTunnel.desc':+ 'Give a port on the working device a link, so a dev server running there can be opened from here. The link only works for people who can reach that device.',+ 'features.deviceTunnel.title': 'Remote Port Links','features.gatewayMux.desc':'Route every agent run in this tab over one shared gateway WebSocket instead of opening a socket per run. Reconnects and event replay are handled per run on the shared connection.','features.gatewayMux.title': 'Single-connection Gateway (experimental)',diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex b7f3cf46238..95af92c9868 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -226,6 +226,11 @@ export const UserLabSchema = z.object({* delivery checklist inline)*/enableTopicAcceptance: z.boolean().optional(),+ /**+ * expose a port on the working device through a tunnel link, so a dev server+ * running there can be opened from this UI+ */+ enableDeviceTunnel: z.boolean().optional(),});export type UserLab = z.infer<typeof UserLabSchema>;diff --git a/src/features/Conversation/WorkingSidebar/Overview/PortSwitcher.tsx b/src/features/Conversation/WorkingSidebar/Overview/PortSwitcher.tsxnew file mode 100644index 00000000000..71d6d7eb917--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/PortSwitcher.tsx@@ -0,0 +1,257 @@+import { Icon, Input, Tooltip } from '@lobehub/ui';+import {+ DropdownMenuItem,+ DropdownMenuPopup,+ DropdownMenuPortal,+ DropdownMenuPositioner,+ 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 { useTranslation } from 'react-i18next';++import { usePortTunnels } from './usePortTunnels';++const styles = createStaticStyles(({ css, cssVar }) => ({+ action: css`+ cursor: pointer;++ display: flex;+ flex-shrink: 0;+ align-items: center;++ padding: 2px;+ border: none;+ border-radius: 4px;++ color: ${cssVar.colorTextTertiary};++ background: transparent;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimaryBorder};+ outline-offset: 1px;+ }+ `,+ container: css`+ display: flex;+ flex-direction: column;+ width: 260px;+ padding: 4px;+ `,+ empty: css`+ padding-block: 10px;+ padding-inline: 8px;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ retry: css`+ cursor: pointer;++ padding: 0;+ border: none;++ font-size: 12px;+ color: ${cssVar.colorInfo};++ background: transparent;+ `,+ state: css`+ display: flex;+ gap: 6px;+ align-items: center;++ padding-block: 10px;+ padding-inline: 8px;++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ host: css`+ overflow: hidden;+ flex: 1;++ min-width: 0;++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ hint: css`+ padding-block: 6px 2px;+ padding-inline: 8px;++ font-size: 11px;+ line-height: 16px;+ color: ${cssVar.colorTextQuaternary};+ `,+ item: css`+ display: flex;+ gap: 8px;+ align-items: center;+ `,+ port: css`+ flex-shrink: 0;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ font-weight: 500;+ color: ${cssVar.colorText};+ `,+ section: css`+ padding-block: 6px 4px;+ padding-inline: 8px;++ font-size: 11px;+ font-weight: 500;+ color: ${cssVar.colorTextTertiary};+ `,+}));++interface PortSwitcherProps {+ children: ReactElement;+ deviceId: 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.+ */+const PortSwitcher = memo<PortSwitcherProps>(({ children, deviceId }) => {+ const { t } = useTranslation('chat');+ const { t: tCommon } = useTranslation('common');+ const [open, setOpen] = useState(false);+ const close = useCallback(() => setOpen(false), []);++ const {+ busySlug,+ copyLink,+ creating,+ error,+ exposePort,+ isLoading,+ openLink,+ port,+ refresh,+ revokeLink,+ setPort,+ tunnels,+ } = usePortTunnels(deviceId, open, close);++ return (+ <DropdownMenuRoot open={open} onOpenChange={setOpen}>+ <DropdownMenuTrigger>{children}</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')}+ </button>+ </div>+ ) : tunnels.length === 0 ? (+ <div className={styles.empty}>{t('workingPanel.overview.ports.empty')}</div>+ ) : (+ tunnels.map((link) => (+ <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}+ />+ <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>+ </DropdownMenuItem>+ ))+ )}++ <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>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ );+});++PortSwitcher.displayName = 'PortSwitcher';++export default PortSwitcher;diff --git a/src/features/Conversation/WorkingSidebar/Overview/__tests__/usePortTunnels.test.ts b/src/features/Conversation/WorkingSidebar/Overview/__tests__/usePortTunnels.test.tsnew file mode 100644index 00000000000..8c88de62854--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/__tests__/usePortTunnels.test.ts@@ -0,0 +1,222 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { usePortTunnels } from '../usePortTunnels';++const createTunnel = vi.hoisted(() => vi.fn());+const openTunnel = vi.hoisted(() => vi.fn());+const revokeTunnel = vi.hoisted(() => vi.fn());+const toastError = vi.hoisted(() => vi.fn());+const toastSuccess = vi.hoisted(() => vi.fn());+const copyToClipboard = vi.hoisted(() => vi.fn());+const mutate = vi.hoisted(() => vi.fn());+const tunnels = vi.hoisted(() => ({+ error: undefined as unknown,+ isLoading: false,+ value: [] as unknown[] | undefined,+}));+const isDesktop = vi.hoisted(() => ({ value: false }));++vi.mock('@/services/device', () => ({+ deviceService: { createTunnel, openTunnel, revokeTunnel },+}));++vi.mock('@/store/device', () => ({+ useFetchDeviceTunnels: () => ({+ data: tunnels.value,+ error: tunnels.error,+ isLoading: tunnels.isLoading,+ mutate,+ }),+}));++vi.mock('@lobechat/const', () => ({+ get isDesktop() {+ return isDesktop.value;+ },+}));++vi.mock('@lobehub/ui', () => ({ copyToClipboard }));+vi.mock('@lobehub/ui/base-ui', () => ({+ toast: { error: toastError, success: toastSuccess },+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++const link = {+ createdAt: 1,+ deviceId: 'device-1',+ hostname: '3000--abcdefgh.lobe.sh',+ port: 3000,+ slug: 'abcdefgh',+ url: 'https://3000--abcdefgh.lobe.sh/',+};++const onOpened = vi.fn();+const setup = () => renderHook(() => usePortTunnels('device-1', true, onOpened));++/** A pre-opened tab: `window.open` is called before the token round trip. */+const tab = { close: vi.fn(), location: { href: '' }, opener: {} as unknown };++beforeEach(() => {+ vi.clearAllMocks();+ tunnels.value = [];+ tunnels.error = undefined;+ tunnels.isLoading = false;+ isDesktop.value = false;+ tab.location.href = '';+ tab.opener = {};+ vi.stubGlobal(+ 'open',+ vi.fn(() => tab),+ );+});++describe('usePortTunnels', () => {+ it('exposes a port and opens it straight away', async () => {+ createTunnel.mockResolvedValue({+ ...link,+ openUrl: 'https://3000--abcdefgh.lobe.sh/?token=fresh',+ });+ const { result } = setup();++ act(() => result.current.setPort('3000'));+ await act(() => result.current.exposePort());++ expect(createTunnel).toHaveBeenCalledWith({ deviceId: 'device-1', port: 3000 });+ // Typing 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();++ act(() => result.current.setPort(value));+ await act(() => result.current.exposePort());++ 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];+ openTunnel.mockResolvedValue({ openUrl: `${link.url}?token=minted`, url: link.url });+ const { result } = setup();++ await act(() => result.current.openLink(link));++ expect(openTunnel).toHaveBeenCalledWith({ slug: 'abcdefgh' });+ expect(tab.location.href).toBe('https://3000--abcdefgh.lobe.sh/?token=minted');+ // The clean URL 401s for anyone who doesn't already hold the session cookie.+ expect(tab.location.href).not.toBe(link.url);+ });++ it('puts an openable link on the clipboard, not the bare hostname', async () => {+ openTunnel.mockResolvedValue({ openUrl: `${link.url}?token=minted`, url: link.url });+ const { result } = setup();++ await act(() => result.current.copyLink(link));++ expect(copyToClipboard).toHaveBeenCalledWith('https://3000--abcdefgh.lobe.sh/?token=minted');+ expect(toastSuccess).toHaveBeenCalledWith('workingPanel.overview.ports.copied');+ });++ it('refreshes the list after revoking', async () => {+ revokeTunnel.mockResolvedValue({ success: true });+ const { result } = setup();++ await act(() => result.current.revokeLink(link));++ expect(revokeTunnel).toHaveBeenCalledWith({ slug: 'abcdefgh' });+ expect(mutate).toHaveBeenCalled();+ await waitFor(() => expect(result.current.busySlug).toBeUndefined());+ });++ it('reports a failed exposure instead of silently doing nothing', async () => {+ createTunnel.mockRejectedValue(new Error('offline'));+ const { result } = setup();++ act(() => result.current.setPort('5173'));+ await act(() => result.current.exposePort());++ 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);+ });++ it('never navigates to a non-http URL the server might return', async () => {+ openTunnel.mockResolvedValue({ openUrl: 'javascript:alert(1)', url: link.url });+ const { result } = setup();++ await act(() => result.current.openLink(link));++ expect(tab.location.href).toBe('');+ expect(tab.close).toHaveBeenCalled();+ });++ describe('popup survival', () => {+ it('claims the tab before the token round trip, and severs its opener', async () => {+ openTunnel.mockResolvedValue({ openUrl: `${link.url}?token=minted`, url: link.url });+ const { result } = setup();++ const pending = act(() => result.current.openLink(link));+ // Claimed synchronously: after the await the click is no longer user+ // activation and the browser blocks the popup.+ expect(window.open).toHaveBeenCalledWith('about:blank', '_blank');+ await pending;++ expect(tab.opener).toBeNull();+ });++ it('reports a blocked popup instead of silently doing nothing', async () => {+ vi.stubGlobal(+ 'open',+ vi.fn(() => null),+ );+ const { result } = setup();++ await act(() => result.current.openLink(link));++ expect(toastError).toHaveBeenCalledWith('workingPanel.overview.ports.popupBlocked');+ expect(openTunnel).not.toHaveBeenCalled();+ });++ it('opens directly on desktop, where window.open reaches the shell', async () => {+ isDesktop.value = true;+ openTunnel.mockResolvedValue({ openUrl: `${link.url}?token=minted`, url: link.url });+ const { result } = setup();++ await act(() => result.current.openLink(link));++ // No about:blank: a reserved tab would launch an empty browser window.+ expect(window.open).toHaveBeenCalledTimes(1);+ expect(window.open).toHaveBeenCalledWith(+ 'https://3000--abcdefgh.lobe.sh/?token=minted',+ '_blank',+ 'noopener,noreferrer',+ );+ });+ });++ describe('list states', () => {+ it('keeps loading and failure distinct from an empty list', () => {+ tunnels.value = undefined;+ tunnels.isLoading = true;+ expect(setup().result.current).toMatchObject({ isLoading: true, tunnels: [] });++ tunnels.isLoading = false;+ tunnels.error = new Error('offline');+ // Callers need the error itself: "couldn't ask" must not render as+ // "nothing is exposed".+ expect(setup().result.current.error).toBeTruthy();+ });+ });+});diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsxindex 6133316a354..3d98afd0782 100644--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx@@ -14,6 +14,7 @@ import {FileTextIcon,GitBranchIcon,GitForkIcon,+ GlobeIcon,LaptopIcon,RefreshCwIcon,TriangleAlertIcon,@@ -42,11 +43,14 @@ import {useFetchGitWorktrees,useReviewPatches,} from '@/store/device';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';import ProgressSection from '../ProgressSection';import { collectChangeStats, isLinkedWorktreeCheckout, shouldShowCiLabel } from './overviewData';import OverviewHeader from './OverviewHeader';import { ChevronRight, OverviewRow, PickerGlyph, rowStyles } from './OverviewRow';+import PortSwitcher from './PortSwitcher';import { sectionStyles } from './sectionStyles';const styles = createStaticStyles(({ css }) => ({@@ -92,6 +96,7 @@ const Overview = memo<OverviewProps>(const { t: tDevice } = useTranslation('device');const { t: tCommon } = useTranslation('common');const isHetero = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);+ const tunnelsEnabled = useUserStore(labPreferSelectors.enableDeviceTunnel);const topicId = useChatStore((s) => s.activeTopicId);const threadId = useChatStore((s) => s.activeThreadId);const works = useChatStore((s) =>@@ -327,6 +332,17 @@ 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>diff --git a/src/features/Conversation/WorkingSidebar/Overview/usePortTunnels.ts b/src/features/Conversation/WorkingSidebar/Overview/usePortTunnels.tsnew file mode 100644index 00000000000..a465430d246--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/usePortTunnels.ts@@ -0,0 +1,150 @@+import { isDesktop } from '@lobechat/const';+import { copyToClipboard } from '@lobehub/ui';+import { toast } from '@lobehub/ui/base-ui';+import { useCallback, 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';++/**+ * State and actions behind the Ports row.+ *+ * The rule worth keeping in one place: a link is stored clean and the token+ * 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) => {+ const { t } = useTranslation('chat');+ const [port, setPort] = useState('');+ const [busySlug, setBusySlug] = useState<string>();+ const [creating, setCreating] = useState(false);++ const { data: tunnels, error, isLoading, mutate } = useFetchDeviceTunnels(deviceId, open);++ /**+ * Claim the tab while the click is still the browser's idea of user+ * activation — minting the token is a round trip, and a `window.open` after+ * it gets blocked as a popup. Desktop needs none of this: `window.open` is+ * routed to `shell.openExternal`, and a reserved `about:blank` would just+ * launch an empty browser tab.+ */+ const reserveTab = useCallback((): Window | null => {+ if (isDesktop) return null;+ const tab = window.open('about:blank', '_blank');+ // `noopener` can't be used here (it makes `open` return null, leaving+ // nothing to navigate), so sever the link while the tab is still+ // same-origin instead.+ if (tab) tab.opener = null;+ return tab;+ }, []);++ const navigateTab = useCallback((tab: Window | null, url: string) => {+ // Defense in depth: only ever hand http(s) to a tab or the shell.+ if (!isSafeExternalUrl(url)) {+ tab?.close();+ return;+ }+ if (tab) tab.location.href = url;+ else window.open(url, '_blank', 'noopener,noreferrer');+ }, []);++ const openLink = useCallback(+ async (link: DeviceTunnelLink) => {+ const tab = reserveTab();+ if (!tab && !isDesktop) {+ toast.error(t('workingPanel.overview.ports.popupBlocked'));+ return;+ }++ setBusySlug(link.slug);+ try {+ const { openUrl } = await deviceService.openTunnel({ slug: link.slug });+ navigateTab(tab, openUrl);+ onOpened();+ } catch {+ tab?.close();+ toast.error(t('workingPanel.overview.ports.openFailed'));+ } finally {+ setBusySlug(undefined);+ }+ },+ [navigateTab, onOpened, reserveTab, t],+ );++ const copyLink = useCallback(+ async (link: DeviceTunnelLink) => {+ try {+ // The clean URL 401s for anyone without the session cookie, so what+ // goes on the clipboard has to be an openable one.+ const { openUrl } = await deviceService.openTunnel({ slug: link.slug });+ await copyToClipboard(openUrl);+ toast.success(t('workingPanel.overview.ports.copied'));+ } catch {+ toast.error(t('workingPanel.overview.ports.openFailed'));+ }+ },+ [t],+ );++ const revokeLink = useCallback(+ async (link: DeviceTunnelLink) => {+ setBusySlug(link.slug);+ try {+ await deviceService.revokeTunnel({ slug: link.slug });+ await mutate();+ toast.success(t('workingPanel.overview.ports.revoked'));+ } catch {+ toast.error(t('workingPanel.overview.ports.revokeFailed'));+ } finally {+ setBusySlug(undefined);+ }+ },+ [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;+ }++ 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]);++ return {+ busySlug,+ copyLink,+ creating,+ error,+ exposePort,+ isLoading,+ openLink,+ port,+ refresh: mutate,+ revokeLink,+ setPort,+ tunnels: tunnels ?? [],+ };+};diff --git a/src/features/Settings/labs/features.ts b/src/features/Settings/labs/features.tsindex dc3397e8968..7a8e9af6f4f 100644--- a/src/features/Settings/labs/features.ts+++ b/src/features/Settings/labs/features.ts@@ -17,6 +17,7 @@ type LabFeatureI18nKey =| 'claudeCodeSdk'| 'codexAppServer'| 'desktopSplitView'+ | 'deviceTunnel'| 'evalCapture'| 'gatewayMux'| 'heteroSessionImport'@@ -90,6 +91,12 @@ export const LAB_FEATURES: LabFeatureItem[] = [searchKeywords: ['acceptance', 'checklist'],stage: 'alpha',},+ {+ flag: 'enableDeviceTunnel',+ i18nKey: 'deviceTunnel',+ searchKeywords: ['tunnel', 'port forwarding', 'dev server', 'localhost'],+ stage: 'alpha',+ },{flag: 'enableProjects',i18nKey: 'projects',diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 82aaab38aa9..a3fa2276b82 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,),+ tunnels: def('device:tunnels', (workspaceId: string | null, deviceId: string) => [+ 'device:tunnels',+ workspaceId,+ deviceId,+ ]),gitAheadBehind: def('device:gitAheadBehind', (deviceId: string, path: string) => ['device:gitAheadBehind',deviceId,diff --git a/src/services/device.ts b/src/services/device.tsindex 63900d50c21..51f26f33554 100644--- a/src/services/device.ts+++ b/src/services/device.ts@@ -45,6 +45,29 @@ class DeviceService {scanAgents(input: Parameters<DeviceClient['scanAgents']['query']>[0]) {return lambdaClient.device.scanAgents.query(input);}++ /** Live tunnel links, optionally narrowed to one device. */+ listTunnels(input?: Parameters<DeviceClient['listTunnels']['query']>[0]) {+ return lambdaClient.device.listTunnels.query(input);+ }++ /** Expose a port on a device and get back a link, ready to open. */+ createTunnel(input: Parameters<DeviceClient['createTunnel']['mutate']>[0]) {+ return lambdaClient.device.createTunnel.mutate(input);+ }++ /**+ * Mint the one-shot token that opens an existing link. Called per click:+ * tokens are short-lived and never stored alongside the link.+ */+ openTunnel(input: Parameters<DeviceClient['openTunnel']['mutate']>[0]) {+ return lambdaClient.device.openTunnel.mutate(input);+ }++ /** Revoke a link. */+ revokeTunnel(input: Parameters<DeviceClient['revokeTunnel']['mutate']>[0]) {+ return lambdaClient.device.revokeTunnel.mutate(input);+ }}export const deviceService = new DeviceService();diff --git a/src/store/device/index.ts b/src/store/device/index.tsindex 31fdedebd5e..c9b9abd6101 100644--- a/src/store/device/index.ts+++ b/src/store/device/index.ts@@ -2,3 +2,4 @@ export * from './deviceCwd';export * from './gitHooks';export * from './selectors';export * from './store';+export * from './tunnelHooks';diff --git a/src/store/device/tunnelHooks.ts b/src/store/device/tunnelHooks.tsnew file mode 100644index 00000000000..7a8bd61e278--- /dev/null+++ b/src/store/device/tunnelHooks.ts@@ -0,0 +1,32 @@+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useClientDataSWR } from '@/libs/swr';+import { deviceKeys } from '@/libs/swr/keys';+import { deviceService } from '@/services/device';++export interface DeviceTunnelLink {+ createdAt: number;+ deviceId: string;+ expiresAt?: number;+ hostname: string;+ port: number;+ slug: string;+ url: string;+}++/**+ * Tunnel links for one device: a port on that machine, reachable at+ * `https://<port>--<slug>.lobe.sh/`.+ *+ * Read-only and on demand — no polling. A link's lifetime is measured in days,+ * and the list only changes when this UI creates or revokes one, so the local+ * mutations below refresh it rather than a background interval.+ */+export const useFetchDeviceTunnels = (deviceId?: string, enabled = true) => {+ const workspaceId = useActiveWorkspaceId();++ return useClientDataSWR<DeviceTunnelLink[]>(+ enabled && deviceId ? deviceKeys.tunnels(workspaceId, deviceId) : null,+ async () => deviceService.listTunnels({ deviceId }),+ { revalidateOnFocus: false },+ );+};diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.tsindex 4e5d365f2d7..282bf07e281 100644--- a/src/store/user/slices/preference/selectors/labPrefer.ts+++ b/src/store/user/slices/preference/selectors/labPrefer.ts@@ -11,6 +11,7 @@ export const labPreferSelectors = {s.preference.lab?.enableArtifactDeployment ?? false,enableClaudeCodeSdk: (s: UserState): boolean => s.preference.lab?.enableClaudeCodeSdk ?? false,enableCodexAppServer: (s: UserState): boolean => s.preference.lab?.enableCodexAppServer ?? false,+ enableDeviceTunnel: (s: UserState): boolean => s.preference.lab?.enableDeviceTunnel ?? false,enableDesktopSplitView: (s: UserState): boolean =>s.preference.lab?.enableDesktopSplitView ?? false,enableEvalCapture: (s: UserState): boolean => s.preference.lab?.enableEvalCapture ?? false,