Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(device-link): connect desktop and mobile LAN direct transport

Lizica4b90752235
diff --git a/apps/desktop/src/capture-renderer/directLinkHost.ts b/apps/desktop/src/capture-renderer/directLinkHost.ts
new file mode 100644
index 0000000000..f87e380b5a
--- /dev/null
+++ b/apps/desktop/src/capture-renderer/directLinkHost.ts
@@ -0,0 +1,10 @@
+import { createDirectRtcRuntime, createDirectRuntimeHost } from '@cindy/device-link';
+import type { DirectLinkHostApi } from '../shared/directLink';
+
+/** No UI, media capture, filesystem or credentials in this data-only process. */
+export function startDirectLinkHost(api: DirectLinkHostApi) {
+ const host = createDirectRuntimeHost(createDirectRtcRuntime(), api.event);
+ const off = api.onCommand((command) => { void host.command(command); });
+ void api.register().catch(() => host.dispose());
+ return () => { off(); host.dispose(); };
+}
diff --git a/apps/desktop/src/capture-renderer/entry.ts b/apps/desktop/src/capture-renderer/entry.ts
index f37cdff98b..a171d1a5eb 100644
--- a/apps/desktop/src/capture-renderer/entry.ts
+++ b/apps/desktop/src/capture-renderer/entry.ts
@@ -1,4 +1,6 @@
import { startFilePeerHost } from './filePeerHost';
+import { startDirectLinkHost } from './directLinkHost';
+import type { DirectLinkHostApi } from '../shared/directLink';
import type { FilePeerHostApi } from '../shared/filePeer';
import type { DesktopCaptureApi } from '../shared/remoteDesktop';
import { startDesktopCaptureHost } from '../renderer/features/remote-desktop/captureHost';
@@ -7,9 +9,10 @@ declare global {
interface Window {
desktopCapture: DesktopCaptureApi;
filePeerHost?: FilePeerHostApi;
+ directLinkHost?: DirectLinkHostApi;
}
}
-const dispose = window.filePeerHost
+const dispose = window.directLinkHost ? startDirectLinkHost(window.directLinkHost) : window.filePeerHost
? startFilePeerHost(window.filePeerHost)
: startDesktopCaptureHost(window.desktopCapture);
window.addEventListener('unload', dispose, { once: true });
diff --git a/apps/desktop/src/main/device-link/__tests__/directLink.test.ts b/apps/desktop/src/main/device-link/__tests__/directLink.test.ts
new file mode 100644
index 0000000000..12bad2e8ca
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/directLink.test.ts
@@ -0,0 +1,67 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import type { DirectRuntimeCommand, DirectRuntimeEvents } from '@cindy/device-link';
+const fake = vi.hoisted(() => ({
+ handlers: new Map<string, (...args: any[]) => any>(), commands: [] as DirectRuntimeCommand[],
+ starts: 0, closes: 0, failed: undefined as (() => void) | undefined,
+ ready: undefined as Promise<void> | undefined,
+}));
+vi.mock('electron', () => ({ ipcMain: { handle: (name: string, fn: (...args: any[]) => any) => fake.handlers.set(name, fn) } }));
+vi.mock('../../logger', () => ({ createLogger: () => ({ warn() {} }) }));
+vi.mock('../../remote-desktop/captureWindow', () => ({ DesktopCaptureWindow: class {
+ constructor(failed: () => void) { fake.failed = failed; }
+ contents = { isDestroyed: () => false, send: (_name: string, c: DirectRuntimeCommand) => {
+ fake.commands.push(c);
+ if (c.action === 'offer' || c.action === 'answer' || c.action === 'accept')
+ fake.handlers.get('direct-link:host:event')!({ trusted: true }, { type: 'reply', id: c.id, ok: true, value: 'fixture-sdp' });
+ } };
+ async start() { fake.starts++; await fake.ready; }
+ dispose() { fake.closes++; }
+ registered(event: { trusted: boolean }) { this.assertSender(event); }
+ assertSender(event: { trusted: boolean }) { if (!event.trusted) throw new Error('PERMISSION_DENIED'); }
+} }));
+import { desktopDirectRuntime } from '../directLink';
+
+// Native startup and sender/lifetime boundary cannot be exercised by the browser-only
+// transport tests. No real windows, sockets, credentials or module resets in unit tier.
+afterEach(() => { desktopDirectRuntime.suspend?.(); fake.commands = []; fake.ready = undefined; vi.useRealTimers(); });
+const events = (): DirectRuntimeEvents => ({ open: vi.fn(), closed: vi.fn(), message: vi.fn(), drained: vi.fn() });
+
+it('starts one isolated process lazily and routes authorized native frames to their registered peer', async () => {
+ const before = fake.starts, observer = events();
+ const a = desktopDirectRuntime.create('one', observer), b = desktopDirectRuntime.create('two', events());
+ expect(fake.starts).toBe(before);
+ expect(await a.offer()).toBe('fixture-sdp'); expect(await b.offer()).toBe('fixture-sdp');
+ expect(fake.starts).toBe(before + 1);
+ const receive = fake.handlers.get('direct-link:host:event')!;
+ receive({ trusted: true }, { type: 'open', connection: 'one' });
+ receive({ trusted: true }, { type: 'message', connection: 'unknown', text: 'foreign' });
+ receive({ trusted: true }, { type: 'message', connection: 'one', text: 'authorized' });
+ expect(observer.open).toHaveBeenCalledOnce(); expect(observer.message).toHaveBeenCalledExactlyOnceWith('authorized');
+ a.send('outbound'); expect(fake.commands.at(-1)).toMatchObject({ action: 'send', connection: 'one', text: 'outbound' });
+});
+
+it('rejects foreign senders before processing any bridge event', async () => {
+ const observer = events(), session = desktopDirectRuntime.create('one', observer);
+ await session.offer();
+ expect(() => fake.handlers.get('direct-link:host:event')!({ trusted: false }, { type: 'open', connection: 'one' })).toThrow('PERMISSION_DENIED');
+ expect(observer.open).not.toHaveBeenCalled();
+});
+
+it('does not create a late session after the authenticated owner was suspended during startup', async () => {
+ let resolve!: () => void;
+ fake.ready = new Promise(r => { resolve = r; });
+ const session = desktopDirectRuntime.create('one', events());
+ const opening = session.offer(), rejected = expect(opening).rejects.toThrow('CLOSED');
+ desktopDirectRuntime.suspend?.(); resolve(); await rejected;
+ expect(fake.commands).toHaveLength(0);
+});
+
+it('releases active paths after a renderer crash and bounds automatic process restarts', async () => {
+ vi.useFakeTimers();
+ const observer = events(), session = desktopDirectRuntime.create('one', observer);
+ await session.offer();
+ fake.failed!(); expect(observer.closed).toHaveBeenCalledOnce();
+ const second = desktopDirectRuntime.create('two', events()); await second.offer();
+ fake.failed!();
+ await expect(desktopDirectRuntime.create('three', events()).offer()).rejects.toThrow('UNAVAILABLE');
+});
diff --git a/apps/desktop/src/main/device-link/directLink.ts b/apps/desktop/src/main/device-link/directLink.ts
new file mode 100644
index 0000000000..4119caf15d
--- /dev/null
+++ b/apps/desktop/src/main/device-link/directLink.ts
@@ -0,0 +1,83 @@
+import { ipcMain } from 'electron';
+import { createDirectRuntimeBridge, type DirectRuntime, type DirectRuntimeSession,
+ type DirectRuntimeEvents } from '@cindy/device-link';
+import { DIRECT_LINK_LOCAL } from '../../shared/directLink';
+import { DesktopCaptureWindow } from '../remote-desktop/captureWindow';
+import { createLogger } from '../logger';
+
+const log = createLogger('device-link:direct');
+const bridge = createDirectRuntimeBridge();
+let detach: (() => void) | undefined;
+let starting: Promise<void> | undefined;
+let epoch = 0;
+let registered = false;
+let crashes = 0;
+let stableTimer: ReturnType<typeof setTimeout> | undefined;
+const host = new DesktopCaptureWindow(() => {
+ crashes += 1;
+ suspend();
+ log.warn('data transport process stopped; active peers fall back to relay');
+}, 'direct');
+
+function suspend() {
+ epoch += 1;
+ clearTimeout(stableTimer);
+ detach?.();
+ detach = undefined;
+ starting = undefined;
+ host.dispose();
+}
+function ensureStarted(): Promise<void> {
+ if (detach) return Promise.resolve();
+ if (starting) return starting;
+ if (crashes >= 2) return Promise.reject(new Error('DIRECT_RUNTIME_UNAVAILABLE'));
+ if (!registered) {
+ registered = true;
+ ipcMain.handle(DIRECT_LINK_LOCAL.REGISTER, (event) => host.registered(event));
+ ipcMain.handle(DIRECT_LINK_LOCAL.EVENT, (event, payload: unknown) => {
+ host.assertSender(event);
+ // Bridge validates shape, frame sizes, connection ownership and pending operation IDs.
+ bridge.receive(payload);
+ });
+ }
+ const generation = epoch;
+ const work = host.start().then(() => {
+ if (epoch !== generation) throw new Error('DIRECT_RUNTIME_CLOSED');
+ detach = bridge.attach((command) => {
+ const contents = host.contents;
+ if (!contents || contents.isDestroyed()) throw new Error('DIRECT_RUNTIME_CLOSED');
+ contents.send(DIRECT_LINK_LOCAL.COMMAND, command);
+ });
+ stableTimer = setTimeout(() => { crashes = 0; }, 60_000);
+ stableTimer.unref();
+ }).catch((error) => {
+ // Constructor/setup failures may precede the window's own failure callback.
+ if (generation === epoch) { crashes += 1; suspend(); }
+ throw error;
+ }).finally(() => { if (starting === work) starting = undefined; });
+ starting = work;
+ return work;
+}
+
+/** Startup is deferred until a capable, authorized peer actually needs a LAN path. */
+export const desktopDirectRuntime: DirectRuntime = {
+ create(id: string, events: DirectRuntimeEvents): DirectRuntimeSession {
+ const generation = epoch;
+ let session: DirectRuntimeSession | undefined;
+ let closed = false;
+ const get = async () => {
+ await ensureStarted();
+ if (closed || generation !== epoch) throw new Error('DIRECT_RUNTIME_CLOSED');
+ return session ??= bridge.runtime.create(id, events);
+ };
+ return {
+ offer: async () => (await get()).offer(),
+ accept: async (sdp) => (await get()).accept(sdp),
+ answer: async (sdp) => (await get()).answer(sdp),
+ send: (text) => { if (!session || closed) throw new Error('DIRECT_RUNTIME_CLOSED'); session.send(text); },
+ get bufferedAmount() { return session?.bufferedAmount ?? 0; },
+ close: () => { closed = true; session?.close(); },
+ };
+ },
+ suspend,
+};
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index bba8d1cc27..19233540f1 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -15,6 +15,7 @@ import { PluginSyncAccess } from './pluginSyncAccess.js';
import os from 'node:os';
import { tryPeerInvoke, stopFilePeers } from './filePeer';
+import { desktopDirectRuntime } from './directLink';
import { assertBackgroundLinkAccepted, linkOpenCapabilities } from './backgroundLink';
import { deviceName, initializeDeviceName } from './deviceName';
import { desktopTransferCodec } from './transferCodec';
@@ -704,6 +705,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
return membership && token ? { realm: authManager.getActiveAuthRealm(), membership, authDevice: authManager.getDeviceId(), token } : null;
};
client = new DeviceLinkClient({
+ directRuntime: desktopDirectRuntime,
getWsUrl: wsUrl,
transferCodec: desktopTransferCodec,
getToken: async () => {
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts
index b6a47cc683..51aa3fe84d 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts
@@ -221,11 +221,11 @@ it('capture CSP forbids arbitrary network, application frames and inline/eval sc
expect(csp).not.toMatch(/https:|wss:|unsafe-inline|unsafe-eval/);
});
-it('keeps file transport separate and denies capture permissions', async () => {
- const owner = new DesktopCaptureWindow(vi.fn(), 'files');
+it.each(['files', 'direct'] as const)('keeps %s transport separate and denies capture permissions', async (mode) => {
+ const owner = new DesktopCaptureWindow(vi.fn(), mode);
const ready = owner.start();
const win = fake.windows[0], ses = fake.sessions[0];
- expect(win.webContents.mainFrame.url).toBe('http://localhost:9988/index.html?mode=files');
+ expect(win.webContents.mainFrame.url).toBe(`http://localhost:9988/index.html?mode=${mode}`);
owner.registered(event(win));
await ready;
const check = ses.setPermissionCheckHandler.mock.calls[0][0];
diff --git a/apps/desktop/src/main/remote-desktop/captureWindow.ts b/apps/desktop/src/main/remote-desktop/captureWindow.ts
index 521d6a4a09..3689d59e55 100644
--- a/apps/desktop/src/main/remote-desktop/captureWindow.ts
+++ b/apps/desktop/src/main/remote-desktop/captureWindow.ts
@@ -24,12 +24,12 @@ export class DesktopCaptureWindow {
const base = DESKTOP_CAPTURE_VITE_DEV_SERVER_URL
? new URL('index.html', DESKTOP_CAPTURE_VITE_DEV_SERVER_URL).href
: CAPTURE_URL;
- return this.mode === 'files' ? `${base}?mode=files` : base;
+ return this.mode === 'desktop' ? base : `${base}?mode=${this.mode}`;
}
constructor(
private readonly failed: () => void,
- private readonly mode: 'desktop' | 'files' = 'desktop',
+ private readonly mode: 'desktop' | 'files' | 'direct' = 'desktop',
) {}
get contents() {
@@ -62,7 +62,7 @@ export class DesktopCaptureWindow {
private getSession(): Session {
if (this.captureSession) return this.captureSession;
const ses = session.fromPartition(
- this.mode === 'files' ? 'cindy-file-peer' : 'cindy-desktop-capture',
+ this.mode === 'desktop' ? 'cindy-desktop-capture' : this.mode === 'files' ? 'cindy-file-peer' : 'cindy-direct-peer',
{ cache: false },
);
this.captureSession = ses;
@@ -103,8 +103,8 @@ export class DesktopCaptureWindow {
url.host !== 'capture' ||
(url.search !== '' &&
!(
- this.mode === 'files' &&
- url.search === '?mode=files' &&
+ this.mode !== 'desktop' &&
+ url.search === `?mode=${this.mode}` &&
url.pathname === '/index.html'
)) ||
!/^\/(?:index\.html|assets\/[A-Za-z0-9_-]+\.js)$/.test(url.pathname)
diff --git a/apps/desktop/src/preload/desktopCapturePreload.ts b/apps/desktop/src/preload/desktopCapturePreload.ts
index 445e395518..853f1a3782 100644
--- a/apps/desktop/src/preload/desktopCapturePreload.ts
+++ b/apps/desktop/src/preload/desktopCapturePreload.ts
@@ -1,5 +1,7 @@
import { FILE_PEER_LOCAL, type FilePeerHostApi, type FilePeerCommand } from '../shared/filePeer';
import { contextBridge, ipcRenderer } from 'electron';
+import { DIRECT_LINK_LOCAL, type DirectLinkHostApi } from '../shared/directLink';
+import type { DirectRuntimeCommand } from '@cindy/device-link';
import {
DESKTOP_LOCAL,
type DesktopCaptureApi,
@@ -26,7 +28,18 @@ const api: DesktopCaptureApi = {
nativeFrame: (lease) => ipcRenderer.invoke(DESKTOP_LOCAL.NATIVE_FRAME, lease),
nativeAudio: (lease) => ipcRenderer.invoke(DESKTOP_LOCAL.NATIVE_AUDIO, lease),
};
-if (location.search === '?mode=files') {
+if (location.search === '?mode=direct') {
+ const direct: DirectLinkHostApi = {
+ register: () => ipcRenderer.invoke(DIRECT_LINK_LOCAL.REGISTER),
+ event: (event) => { void ipcRenderer.invoke(DIRECT_LINK_LOCAL.EVENT, event).catch(() => {}); },
+ onCommand: (listener) => {
+ const wrapped = (_event: Electron.IpcRendererEvent, command: DirectRuntimeCommand) => listener(command);
+ ipcRenderer.on(DIRECT_LINK_LOCAL.COMMAND, wrapped);
+ return () => { ipcRenderer.removeListener(DIRECT_LINK_LOCAL.COMMAND, wrapped); };
+ },
+ };
+ contextBridge.exposeInMainWorld('directLinkHost', direct);
+} else if (location.search === '?mode=files') {
const files: FilePeerHostApi = {
closed: (connection) => ipcRenderer.invoke(FILE_PEER_LOCAL.CLOSED, connection),
register: () => ipcRenderer.invoke(FILE_PEER_LOCAL.REGISTER),
diff --git a/apps/desktop/src/shared/directLink.ts b/apps/desktop/src/shared/directLink.ts
new file mode 100644
index 0000000000..b40779f886
--- /dev/null
+++ b/apps/desktop/src/shared/directLink.ts
@@ -0,0 +1,11 @@
+import type { DirectRuntimeCommand, DirectRuntimeEvent } from '@cindy/device-link';
+export const DIRECT_LINK_LOCAL = {
+ REGISTER: 'direct-link:host:register',
+ COMMAND: 'direct-link:host:command',
+ EVENT: 'direct-link:host:event',
+} as const;
+export interface DirectLinkHostApi {
+ register(): Promise<void>;
+ onCommand(fn: (command: DirectRuntimeCommand) => void): () => void;
+ event(event: DirectRuntimeEvent): void;
+}
diff --git a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
index f6d5118cfb..e208987b08 100644
--- a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
+++ b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
@@ -4,6 +4,8 @@ import type { WebView } from 'react-native-webview';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, expect, it, vi } from 'vitest';
import { PeerFileTransport } from '@/device-link/peerFileTransport';
+import { DirectLinkTransport } from '@/device-link/DirectLinkTransport';
+import { createDirectRuntimeBridge } from '@cindy/device-link';
import { HtmlSnapshotReader } from '@/session/HtmlFileReader';
import type { MobileHtmlPreview } from '@/session/mobileHtmlPreview';
import type { HtmlPreviewProgress, PrepareMobileHtmlPreview } from '@/session/mobileHtmlPreview';
@@ -112,6 +114,57 @@ it.each(['onContentProcessDidTerminate', 'onRenderProcessGone'])('recreates peer
expect(state.install).toHaveBeenCalledTimes(2);
});
+// Production bridge lifecycle, separate from file transfers: a backgrounded/crashed
+// data-only WebView must immediately release paths and reject old document callbacks.
+it.each(['onContentProcessDidTerminate', 'onRenderProcessGone'])('releases the LAN path after %s with bounded restarts', async event => {
+ const bridge = createDirectRuntimeBridge(), closed = vi.fn();
+ root = createRoot(document.createElement('div'));
+ act(() => root!.render(createElement(DirectLinkTransport, { bridge, enabled: true, owner: 'one' })));
+ const message = (type: string, extra = {}) => ({ nativeEvent: { data: JSON.stringify({ type, ...extra }) } });
+ act(() => state.props.onMessage(message('ready')));
+ bridge.runtime.create('one', { closed, open() {}, message() {}, drained() {} });
+ const old = state.props;
+ act(() => old[event]());
+ expect(closed).toHaveBeenCalledOnce();
+ expect(state.mounts).toBe(2);
+ act(() => old.onMessage(message('ready')));
+ expect(() => bridge.runtime.create('two', { closed, open() {}, message() {}, drained() {} })).toThrow('UNAVAILABLE');
+ act(() => state.props.onMessage(message('ready')));
+ bridge.runtime.create('two', { closed, open() {}, message() {}, drained() {} });
+ act(() => state.props[event]());
+ expect(closed).toHaveBeenCalledTimes(2);
+ expect(state.mounts).toBe(2);
+ expect(() => bridge.runtime.create('three', { closed, open() {}, message() {}, drained() {} })).toThrow('UNAVAILABLE');
+});
+
+it('does not accept LAN bridge callbacks across backgrounding, owner changes or unmount', () => {
+ const bridge = createDirectRuntimeBridge(), closed = vi.fn();
+ const events = { closed, open() {}, message() {}, drained() {} };
+ const ready = { nativeEvent: { data: '{"type":"ready"}' } };
+ root = createRoot(document.createElement('div'));
+ act(() => root!.render(createElement(DirectLinkTransport, { bridge, enabled: true, owner: 'one' })));
+ act(() => state.props.onMessage(ready));
+ bridge.runtime.create('one', events);
+ const old = state.props;
+ act(() => { for (const fn of state.appStateListeners) fn('background'); });
+ expect(closed).toHaveBeenCalledOnce();
+ act(() => { for (const fn of state.appStateListeners) fn('active'); });
+ act(() => old.onMessage(ready));
+ expect(() => bridge.runtime.create('two', events)).toThrow('UNAVAILABLE');
+ act(() => state.props.onMessage(ready));
+ bridge.runtime.create('two', events);
+ const previousOwner = state.props;
+ act(() => root!.render(createElement(DirectLinkTransport, { bridge, enabled: true, owner: 'two' })));
+ expect(closed).toHaveBeenCalledTimes(2);
+ act(() => previousOwner.onMessage(ready));
+ expect(() => bridge.runtime.create('three', events)).toThrow('UNAVAILABLE');
+ act(() => state.props.onMessage(ready));
+ const disposed = state.props;
+ act(() => root!.unmount()); root = undefined;
+ act(() => disposed.onMessage(ready));
+ expect(() => bridge.runtime.create('three', events)).toThrow('UNAVAILABLE');
+});
+
it.each(['onContentProcessDidTerminate', 'onRenderProcessGone'])('routes snapshot %s to the existing error owner', (event) => {
root = createRoot(document.createElement('div'));
const onError = vi.fn();
diff --git a/apps/mobile/src/__tests__/historyViewProvider.test.tsx b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
index 9ef176ad95..42588f1e6c 100644
--- a/apps/mobile/src/__tests__/historyViewProvider.test.tsx
+++ b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
@@ -14,6 +14,8 @@ import {
} from '@cindy/device-link';
import { isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';
import { DeviceLinkProvider, useDeviceLink, type DeviceLinkContextValue } from '../device-link/DeviceLinkContext';
+// Platform process lifecycle is covered in fileWebViewTermination.test.tsx.
+vi.mock('../device-link/DirectLinkTransport', () => ({ DirectLinkTransport: () => null }));
import { useMobileMakerTransport } from '../device-link/useMobileMakerTransport';
import type { MobileMakerTransport } from '../device-link/mobileMakerTransport';
import { acquireDeviceSendSlot, resetDeviceResponsivenessTracking, settleDeviceSend, unresponsiveDevicesStore } from '../device-link/unresponsiveDevicesStore';
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 73bc2c2f23..57a850aba7 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -1,4 +1,5 @@
import Constants from 'expo-constants';
+import { DirectLinkTransport } from './DirectLinkTransport';
import { tryMobilePeerInvoke, resetMobilePeer } from './peerFileRegistry';
import { isHistoryViewUnavailable, type HistoryWorkPatch } from '@cindy/maker-shared/message-window';
import { findRemoteHistoryView } from '@/session/remoteHistoryView';
@@ -12,6 +13,7 @@ import { dispatchCredentialSwitchOutcome } from '@/session/credentialSwitchOutco
import { mobileRuntimeIdentity } from '@/debug/mobileRuntimeIdentity';
import {
DeviceLinkClient,
+ createDirectRuntimeBridge,
isSharedTaskPeer,
probeSharedTaskHost,
sharedTaskTopics,
@@ -385,6 +387,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
}
const auth = useAuth();
+ const [directBridge] = useState(() => createDirectRuntimeBridge());
const sharedTaskApi = useSharedTaskApi();
const currentDataOwnerIdRef = useRef<string | null>(auth.user?.id ?? null);
currentDataOwnerIdRef.current = auth.user?.id ?? null;
@@ -953,6 +956,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// 会被 scheduler generation 丢弃,不能写回新账号。
peerRecoverySchedulerRef.current?.clear();
const client = new DeviceLinkClient({
+ directRuntime: directBridge.runtime,
getWsUrl: () => deviceLinkWsUrl(),
getToken: auth.getAccessToken,
getHello: () => ({
@@ -1656,7 +1660,11 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
subscriptionVersion,
]);
- return <DeviceLinkContext.Provider value={value}>{children}</DeviceLinkContext.Provider>;
+ return <DeviceLinkContext.Provider value={value}>
+ <DirectLinkTransport key={`${auth.accountGeneration}:${connectionEpoch}`} bridge={directBridge}
+ owner={`${auth.accountGeneration}:${connectionEpoch}`} enabled={auth.isAuthenticated && status === 'online'} />
+ {children}
+ </DeviceLinkContext.Provider>;
}
function VisualMockDeviceLinkProvider({ children }: { children: ReactNode }) {
diff --git a/apps/mobile/src/device-link/DirectLinkTransport.tsx b/apps/mobile/src/device-link/DirectLinkTransport.tsx
new file mode 100644
index 0000000000..5c8b2cb6d2
--- /dev/null
+++ b/apps/mobile/src/device-link/DirectLinkTransport.tsx
@@ -0,0 +1,71 @@
+import { useEffect, useRef, useState } from 'react';
+import { AppState, View } from 'react-native';
+import { WebView } from 'react-native-webview';
+import { DIRECT_LINK_RUNTIME_SOURCE, MAX_FRAME_BYTES, type createDirectRuntimeBridge } from '@cindy/device-link';
+import { mobileDebugLog } from '@/debug/mobileDebugLog';
+
+const origin = 'https://cindy-device-link.invalid';
+const html = `<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; connect-src 'none';"><script>
+${DIRECT_LINK_RUNTIME_SOURCE}
+const host=CindyDirectLink.create(event=>window.ReactNativeWebView.postMessage(JSON.stringify(event)));
+window.directLinkCommand=command=>host.command(command);
+window.ReactNativeWebView.postMessage(JSON.stringify({type:'ready'}));
+</script>`;
+
+/** Data-only WebView, separate from previews and media transfers. Closing this
+ * process immediately releases its paths; DeviceLink replays pending frames via relay. */
+export function DirectLinkTransport({ bridge, enabled, owner }: {
+ bridge: ReturnType<typeof createDirectRuntimeBridge>;
+ enabled: boolean;
+ owner: string;
+}) {
+ const view = useRef<WebView>(null);
+ const detach = useRef<(() => void) | undefined>(undefined);
+ const [foreground, setForeground] = useState(AppState.currentState === 'active');
+ const [crashes, setCrashes] = useState(0);
+ const [lifecycle, setLifecycle] = useState(0);
+ const key = `${owner}:${crashes}:${lifecycle}`;
+ const live = useRef(key);
+ live.current = key;
+ const active = enabled && foreground && crashes < 2;
+ const activeRef = useRef(active);
+ activeRef.current = active;
+ const release = () => { detach.current?.(); detach.current = undefined; };
+ useEffect(() => {
+ const subscription = AppState.addEventListener('change', (state) => {
+ if (state !== 'active') { activeRef.current = false; release(); setLifecycle(n => n + 1); }
+ setForeground(state === 'active');
+ });
+ return () => { activeRef.current = false; live.current = 'disposed'; subscription.remove(); release(); };
+ }, []);
+ useEffect(() => () => release(), [key, active, bridge]);
+ const terminated = () => {
+ if (live.current !== key) return;
+ release();
+ setCrashes((n) => Math.min(2, n + 1));
+ mobileDebugLog('warn', 'device-link', 'LAN transport process stopped; using relay');
+ };
+ if (!active) return null;
+ return <View pointerEvents="none" accessible={false}
+ style={{ position: 'absolute', width: 1, height: 1, opacity: 0 }}>
+ <WebView ref={view} key={key} source={{ html, baseUrl: origin }} javaScriptEnabled
+ originWhitelist={[origin]}
+ onShouldStartLoadWithRequest={(r) => r.url === origin || r.url === `${origin}/` || r.url === 'about:blank'}
+ allowFileAccess={false} allowFileAccessFromFileURLs={false} allowUniversalAccessFromFileURLs={false}
+ setSupportMultipleWindows={false} mixedContentMode="never" mediaCapturePermissionGrantType="deny" incognito
+ onContentProcessDidTerminate={terminated} onRenderProcessGone={terminated}
+ onMessage={(event) => {
+ if (live.current !== key || !activeRef.current || event.nativeEvent.data.length > 6 * MAX_FRAME_BYTES) return;
+ try {
+ const message = JSON.parse(event.nativeEvent.data);
+ if (message.type === 'ready') {
+ if (detach.current) return;
+ detach.current = bridge.attach((command) => {
+ if (live.current !== key || !activeRef.current || !view.current) throw new Error('DIRECT_RUNTIME_CLOSED');
+ view.current.injectJavaScript(`window.directLinkCommand(${JSON.stringify(command)});true;`);
+ });
+ } else bridge.receive(message);
+ } catch { /* Malformed local bridge messages never reach DeviceLink. */ }
+ }} />
+ </View>;
+}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 6eeb2547e1..326c880b40 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1,5 +1,27 @@
# 跨端协议兼容
+## Device Link 局域网优先直连
+
+可靠链路的 `link-open/link-accept` 增加可选能力 `direct-link-v1`。双方均支持且已完成
+现有授权与可靠握手后,字典序较小的 deviceId 后台发起 WebRTC DataChannel;信令通过
+既有 relay `push` 的 `device-link:direct-signal` channel 发送,含 offer/answer/close、
+随机通道 ID 及两端当前 transport stream。客户端验证账号范围、双方能力、链路就绪与
+stream 匹配后才处理;信令不进入业务可靠 FIFO,也不走直连。超时或信令丢失由独立退避
+重试恢复,普通业务继续走 relay,不产生新 invoke 白名单权限或服务端协议版本。
+
+数据通道 `device-link-v1` 只使用可靠有序 SCTP;同一完整 envelope 拆为不超过 16 KiB 的
+二进制片,首字节 0/1 表示续片/末片,剩余字节是 UTF-8。单条最多 `MAX_FRAME_BYTES`,
+重组有字节、分片数和超时边界;在原可靠层接收之前重组,序号、去重与 ACK 语义不变。
+桥接在途字节与 SCTP bufferedAmount 一起参与背压,平台静默失效同样会触发原有中继回退。
+
+旧端不声明能力,双方仍走 relay;只升级一端不会启用直连。Desktop 与 Mobile 均接入,
+同账号远程供应商沿用这条共享路径;跨账号供应商分享和共享任务继续由 relay 逐帧授权。
+不改数据库、服务端、Mobile 原生依赖或配置。Mobile 使用现有 WebView,iOS 的 WebKit
+网络行为参考 [Apple TN3179](https://developer.apple.com/documentation/technotes/tn3179-understanding-local-network-privacy)。
+平台不可用或系统阻止局域网访问时沿用 relay,不能阻断业务。真实跨设备、iOS/Android
+前后台及系统网络权限的发布验收必须另记实测证据;浏览器本机 smoke 不等同于真机通过。
+
+
## 灵动岛完成卡操作
`local-db:sessions:activity` 追加可选的 `completionToken`,由任务所属进程按完成卡代次签发。
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index ce702e0fb0..9af28996e2 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -132,7 +132,8 @@ relay 以 close 1013 `inbound backpressure` 主动断连,此时任何「立即
产品要求:Device Link 的设备间功能(含手机)在两端已授权、网络实际可达时优先直连,
直连失败、超时或中途断开时自动改走 relay,不能让功能卡住,也不能重复执行命令。
选路与兜底在 `packages/device-link` 统一实现(`directPath.ts` 与 `DeviceLinkClient`),
-平台只负责建立通道并调用 `attachDirectPath`。
+`directNegotiation.ts` 在双方可靠链路确认后自动协商,平台提供数据专用 WebRTC runtime,
+由统一协商层调用 `attachDirectPath`,不要求用户手工建立通道。
- **分工**:relay 仍是控制面——登录、在线状态、账号归属、link-open/accept/close、
链路确认 ACK 都只走 relay。直连只承载已建立可靠链路上的 reliable-transport 帧
@@ -151,9 +152,22 @@ relay 以 close 1013 `inbound backpressure` 主动断连,此时任何「立即
`packages/device-link/src/__tests__/client.test.ts`「直连优先、中继兜底」:两个控制端
共用同一被控端,其中一个的直连静默,断言命令只执行一次、结果经 relay 送达,另一个
控制端仍走直连、在途请求与 relay 连接不受影响。
-- **范围**:本阶段只有连接层选路与兜底,没有平台接入通道时行为与改动前完全相同,
- 也没有 wire 变更。relay 断线期间链路随之复位,直连暂不单独维持链路。Desktop 与
- Mobile 经已授权信令建立 WebRTC 直连、手机局域网权限等平台接入另行实现。
+- **接入**:Desktop 复用 `DesktopCaptureWindow` 的隔离数据进程(`mode=direct`),Mobile
+ 使用 `DirectLinkTransport.tsx` 的隔离 WebView;二者共用 `directRtcRuntime.ts` 与
+ `directRuntimeBridge.ts`。只收集 host ICE candidates(不请求 STUN/TURN),局域网不可达
+ 继续走现有 relay;协商不阻塞正在进行的业务请求。同账号远程供应商的控制、结果和推送
+ 复用同一条数据路径。手机退后台、WebView 崩溃、账号/区域切换立即释放旧通道。
+- **兼容**:双方都声明 `direct-link-v1` 才尝试。信令以既有 relay push 承载,绑定两端
+ 当前 stream;旧端、平台尚未就绪或协商失败均继续使用 relay。每对设备只有字典序较小的
+ deviceId 发起 offer,失败按 5–60 秒退避;最多 16 个 peer,单次协商 15 秒。
+ relay 断线仍复位链路,直连暂不独立维持;不新增服务端依赖或 Mobile 原生依赖/配置。
+- **验证**:`client.test.ts` 的自动协商矩阵覆盖新旧端、平台不可用、远程 Agent 调用和两个
+ 控制端隔离回退;`directRuntimeBridge.test.ts` 覆盖桥接背压、迟到事件与流代次;
+ `scripts/direct-link-smoke.mjs <Chrome路径>` 运行真实 WebRTC 与手机静态 runtime,验证
+ UTF-8 大结果不经中继、断线回退只执行一次、另一控制端继续直连。该浏览器验证不能替代
+ iOS/Android 和两台真实电脑的跨设备验收。
+ `node scripts/direct-link-electron-smoke.mjs` 另外启动两个临时 Electron 进程,验证生产
+ Main/preload/隔离 renderer 的真实 IPC、WebRTC 与中继回退;账号和 userData 均为独立 fixture。
## 远程 Agent 的拉取与恢复(`maker:remote-agent:v1`)
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index f98cfc4090..abd1f7104b 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -34,6 +34,8 @@ import {
parseTransportPayload,
} from '../transport.js';
import { PLUGIN_SYNC_CHANNEL } from '../pluginSyncProtocol.js';
+import { DIRECT_LINK_SIGNAL, type DirectRuntime, type DirectRuntimeEvents } from '../directNegotiation.js';
+import { createDirectRuntimeBridge, createDirectRuntimeHost } from '../directRuntimeBridge.js';
import { DL_CONTACTS_SYNC_CHANNEL } from '../contactsSyncProtocol.js';
import { resolveRemoteInvokeTimeoutMs } from '../invokePolicy.js';
import { SESSION_ACTIVITY_CHANNEL } from '../topics.js';
@@ -800,7 +802,7 @@ function makeRelayClient(
relay: MemoryRelay,
deviceId: string,
timing?: ConstructorParameters<typeof DeviceLinkClient>[0]['timing'],
- extra?: Pick<ConstructorParameters<typeof DeviceLinkClient>[0], 'transferCodec' | 'invokeMetrics'>,
+ extra?: Pick<ConstructorParameters<typeof DeviceLinkClient>[0], 'transferCodec' | 'invokeMetrics' | 'directRuntime'>,
): DeviceLinkClient {
return new DeviceLinkClient({
...extra,
@@ -10530,6 +10532,107 @@ function connectDirect(
const reliableKinds = (envs: readonly Envelope[] | undefined, kind: Envelope['kind'], src?: string): number =>
(envs ?? []).filter(env => env.kind === kind && parseTransportPayload(env.payload) && (!src || env.src === src)).length;
+/** #6825 lacked automatic negotiation. Exercise real clients and native bridges;
+ * only RTC is in memory. Protect compatibility, per-peer fallback and revocation. */
+class MemoryDirectRuntime {
+ readonly sessions = new Map<string, Array<{ events: DirectRuntimeEvents; closed: boolean; drop: boolean }>>();
+ frames = 0;
+ createRuntime(): DirectRuntime {
+ const native: DirectRuntime = { create: (id, events) => {
+ const row = { events, closed: false, drop: false };
+ const pair = this.sessions.get(id) ?? [];
+ this.sessions.set(id, pair);
+ pair.push(row);
+ return {
+ offer: async () => id, accept: async () => id,
+ answer: async () => { queueMicrotask(() => pair.forEach(p => { if (!p.closed) p.events.open(); })); },
+ send: (text) => {
+ if (row.closed) throw new Error('closed');
+ this.frames++;
+ const other = pair.find(p => p !== row);
+ if (!row.drop && other && !other.closed) setTimeout(() => other.events.message(text), 0);
+ },
+ bufferedAmount: 0,
+ close: () => pair.forEach(p => { if (!p.closed) { p.closed = true; p.events.closed(); } }),
+ };
+ } };
+ const bridge = createDirectRuntimeBridge();
+ const host = createDirectRuntimeHost(native, event => bridge.receive(event));
+ const detach = bridge.attach(command => { void host.command(command); });
+ return { ...bridge.runtime, suspend: () => { detach(); host.dispose(); } };
+ }
+}
+
+describe('automatic LAN connection through platform bridges', () => {
+ it.each(['both', 'old-host', 'old-viewer', 'unavailable'] as const)('negotiates automatically and keeps %s compatible', async mode => {
+ vi.useFakeTimers();
+ const relay = new MemoryRelay(), rtc = new MemoryDirectRuntime();
+ const unavailable: DirectRuntime = { create: () => { throw new Error('native not ready'); } };
+ const host = makeRelayClient(relay, 'desktop', undefined,
+ mode === 'old-host' ? {} : { directRuntime: mode === 'unavailable' ? unavailable : rtc.createRuntime() });
+ const viewer = makeRelayClient(relay, 'viewer', undefined,
+ mode === 'old-viewer' ? {} : { directRuntime: rtc.createRuntime() });
+ const pump = () => relay.settle(async () => { await vi.advanceTimersByTimeAsync(1); });
+ let executions = 0;
+ host.onFrame(env => {
+ if (env.kind === 'link-open') host.sendLinkAccept(env.src!, env.id!, { appVersion: '1', allowlistHash: 'hash' });
+ if (env.kind === 'invoke') { executions++; host.sendInvokeResult(env.src!, env.id!, { ok: true, result: 'remote-provider-result' }); }
+ });
+ try {
+ host.start(); viewer.start(); await pump();
+ const opening = viewer.openLink('desktop', { controllerName: 'Phone', protocolVersion: 1, appVersion: '1' });
+ await pump(); await opening;
+ expect(viewer.getPeerPath('desktop')).toBe(mode === 'both' ? 'direct' : 'relay');
+ const before = reliableKinds(relay.deliveredTo.get('desktop'), 'invoke');
+ const result = viewer.invoke('desktop', { channel: 'maker:remote-agent:v1', args: [{ op: 'poll', runId: 'one' }] });
+ await pump(); expect(await result).toEqual({ ok: true, result: 'remote-provider-result' });
+ expect(executions).toBe(1);
+ expect(reliableKinds(relay.deliveredTo.get('desktop'), 'invoke') - before).toBe(mode === 'both' ? 0 : 1);
+ } finally { host.stop(); viewer.stop(); vi.useRealTimers(); }
+ });
+
+ it.each(['close', 'silent-result'] as const)('falls back after %s without executing twice or disturbing a second controller', async failure => {
+ vi.useFakeTimers();
+ const relay = new MemoryRelay(), rtc = new MemoryDirectRuntime();
+ const options = { requestTimeoutMs: 30_000, transportRetryIntervalMs: 500 };
+ const host = makeRelayClient(relay, 'desktop', options, { directRuntime: rtc.createRuntime() });
+ const a = makeRelayClient(relay, 'viewer-a', options, { directRuntime: rtc.createRuntime() });
+ const b = makeRelayClient(relay, 'viewer-b', options, { directRuntime: rtc.createRuntime() });
+ const pump = () => relay.settle(async () => { await vi.advanceTimersByTimeAsync(1); });
+ const executions: string[] = [];
+ host.onFrame(env => {
+ if (env.kind === 'link-open') host.sendLinkAccept(env.src!, env.id!, { appVersion: '1', allowlistHash: 'hash' });
+ if (env.kind === 'invoke') { executions.push(env.src!); host.sendInvokeResult(env.src!, env.id!, { ok: true, result: 'done' }); }
+ });
+ try {
+ host.start(); a.start(); b.start(); await pump();
+ for (const viewer of [a, b]) {
+ const opening = viewer.openLink('desktop', { controllerName: 'Viewer', protocolVersion: 1, appVersion: '1' });
+ await pump(); await opening;
+ }
+ expect(a.getPeerPath('desktop')).toBe('direct'); expect(b.getPeerPath('desktop')).toBe('direct');
+ const first = [...rtc.sessions.values()][0];
+ if (failure === 'close') first[0].events.closed(); else first[0].drop = true;
+ const result = a.invoke('desktop', { channel: 'maker:remote-agent:v1', args: [{ op: 'send' }] });
+ const other = b.invoke('desktop', { channel: 'maker:remote-agent:v1', args: [{ op: 'poll' }] });
+ await pump();
+ for (let n = 0; n < 5 && a.getPeerPath('desktop') !== 'relay'; n++) {
+ await vi.advanceTimersByTimeAsync(500); await pump();
+ }
+ await pump();
+ expect(await result).toEqual({ ok: true, result: 'done' });
+ expect(await other).toEqual({ ok: true, result: 'done' });
+ expect(executions.sort()).toEqual(['viewer-a', 'viewer-b']);
+ expect(a.getPeerPath('desktop')).toBe('relay'); expect(b.getPeerPath('desktop')).toBe('direct');
+ expect(host.getStatus()).toBe('online');
+ a.closeLink('desktop', 'user'); await pump();
+ await vi.advanceTimersByTimeAsync(65_000); await pump();
+ expect(a.getPeerPath('desktop')).toBe('relay');
+ expect([...rtc.sessions.values()][0].every(p => p.closed)).toBe(true);
+ } finally { host.stop(); a.stop(); b.stop(); vi.useRealTimers(); }
+ });
+});
+
describe('直连优先、中继兜底(Device Link direct path)', () => {
it('replays a partially written large head while an older relay tail is still in flight', async () => {
vi.useFakeTimers();
diff --git a/packages/device-link/src/__tests__/directRuntimeBridge.test.ts b/packages/device-link/src/__tests__/directRuntimeBridge.test.ts
new file mode 100644
index 0000000000..d0eab10bbb
--- /dev/null
+++ b/packages/device-link/src/__tests__/directRuntimeBridge.test.ts
@@ -0,0 +1,85 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { createDirectRuntimeBridge, type DirectRuntimeCommand } from '../directRuntimeBridge.js';
+import { DirectLinkNegotiator, parseDirectSignal, type DirectRuntimeEvents } from '../directNegotiation.js';
+
+// Production bridge/negotiator lifetimes absent from #6825: native queue pressure,
+// stale callbacks, pending handshake cancellation and authenticated stream binding.
+// Unit tier: in-memory native messages, fake time, no sockets or platform processes.
+afterEach(() => vi.useRealTimers());
+const observers = () => ({ open: vi.fn(), message: vi.fn(), drained: vi.fn(), closed: vi.fn() });
+
+it('counts UTF-8 bytes still crossing the native bridge and ignores stale buffer acknowledgements', async () => {
+ const bridge = createDirectRuntimeBridge(), events = observers(), sent: DirectRuntimeCommand[] = [];
+ const detach = bridge.attach(c => sent.push(c));
+ const session = bridge.runtime.create('one', events);
+ bridge.receive({ type: 'open', connection: 'one' });
+ session.send('😀');
+ expect(session.bufferedAmount).toBe(4);
+ bridge.receive({ type: 'buffer', connection: 'one', sequence: 1, buffered: 512 });
+ expect(session.bufferedAmount).toBe(512);
+ bridge.receive({ type: 'buffer', connection: 'one', sequence: 0, buffered: 0 });
+ expect(session.bufferedAmount).toBe(512);
+ bridge.receive({ type: 'buffer', connection: 'one', sequence: 1, buffered: 0 });
+ await Promise.resolve();
+ expect(session.bufferedAmount).toBe(0);
+ expect(events.drained).toHaveBeenCalled();
+ expect(sent[0]).toMatchObject({ action: 'send', sequence: 1, text: '😀' });
+ detach();
+});
+
+it('releases pending operations on native loss and refuses late replies or frames from that process', async () => {
+ const bridge = createDirectRuntimeBridge(), events = observers(), sent: DirectRuntimeCommand[] = [];
+ const detach = bridge.attach(c => sent.push(c));
+ const session = bridge.runtime.create('one', events);
+ const result = session.offer();
+ const rejected = expect(result).rejects.toThrow('CLOSED');
+ detach(); await rejected;
+ bridge.receive({ type: 'reply', id: sent[0].id, ok: true, value: 'late-sdp' });
+ bridge.receive({ type: 'open', connection: 'one' });
+ bridge.receive({ type: 'message', connection: 'one', text: 'late-frame' });
+ expect(events.closed).toHaveBeenCalledOnce();
+ expect(events.open).not.toHaveBeenCalled(); expect(events.message).not.toHaveBeenCalled();
+ expect(() => session.send('late-send')).toThrow('CLOSED');
+});
+
+it('bounds a stalled native command without affecting another peer', async () => {
+ vi.useFakeTimers();
+ const bridge = createDirectRuntimeBridge(), one = observers(), two = observers();
+ const detach = bridge.attach(() => {});
+ const first = bridge.runtime.create('one', one), second = bridge.runtime.create('two', two);
+ bridge.receive({ type: 'open', connection: 'two' });
+ const result = first.offer(), rejected = expect(result).rejects.toThrow('TIMEOUT');
+ await vi.advanceTimersByTimeAsync(10_000); await rejected;
+ expect(one.closed).toHaveBeenCalledOnce(); expect(two.closed).not.toHaveBeenCalled();
+ expect(() => second.send('healthy')).not.toThrow();
+ detach();
+});
+
+it('does not revive an authorized peer after its in-flight offer is cancelled', async () => {
+ vi.useFakeTimers();
+ let resolve!: (sdp: string) => void, callbacks!: DirectRuntimeEvents;
+ const close = vi.fn(), signal = vi.fn(), attach = vi.fn();
+ const controller = new DirectLinkNegotiator({
+ runtime: { create(_id, events) { callbacks = events; return { offer: () => new Promise(r => { resolve = r; }),
+ accept: async () => 'answer', answer: async () => {}, send() {}, bufferedAmount: 0, close }; } },
+ identity: () => 'a', streams: () => ({ local: 'a-stream', remote: 'b-stream' }),
+ id: () => 'attempt', signal, attach,
+ });
+ controller.ready('b'); controller.forget('b');
+ resolve('late-offer'); callbacks.open(); await Promise.resolve(); await vi.advanceTimersByTimeAsync(65_000);
+ expect(signal).not.toHaveBeenCalled(); expect(attach).not.toHaveBeenCalled(); expect(close).toHaveBeenCalledOnce();
+});
+
+it('binds incoming negotiation to both current transport streams', async () => {
+ const create = vi.fn();
+ const controller = new DirectLinkNegotiator({ runtime: { create }, identity: () => 'b',
+ streams: () => ({ local: 'b-new', remote: 'a-new' }), id: () => 'id', signal() {}, attach: vi.fn(),
+ });
+ for (const [stream, targetStream] of [['a-old', 'b-new'], ['a-new', 'b-old']]) {
+ controller.receive('a', { action: 'offer', id: 'old-offer', stream, targetStream, sdp: 'offer' });
+ }
+ expect(create).not.toHaveBeenCalled();
+ expect(parseDirectSignal({ action: 'offer', id: 'valid', stream: 'a', targetStream: 'b', sdp: 'x'.repeat(128 * 1024 + 1) })).toBeNull();
+ expect(parseDirectSignal({ action: 'offer', id: 'valid', stream: 'a', targetStream: 'b' })).toBeNull();
+ controller.clear();
+});
diff --git a/packages/device-link/src/__tests__/filePeerRuntimeSource.test.ts b/packages/device-link/src/__tests__/filePeerRuntimeSource.test.ts
index daa9950745..d8fae06723 100644
--- a/packages/device-link/src/__tests__/filePeerRuntimeSource.test.ts
+++ b/packages/device-link/src/__tests__/filePeerRuntimeSource.test.ts
@@ -1,10 +1,10 @@
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { it } from "vitest";
-it("ships a current static WebView runtime without relying on native function serialization", () => {
+it.each(['file-peer-runtime.mjs', 'direct-link-runtime.mjs'])("ships current %s without native function serialization", (script) => {
execFileSync(process.execPath, [
fileURLToPath(
- new URL("../../../../scripts/file-peer-runtime.mjs", import.meta.url),
+ new URL(`../../../../scripts/${script}`, import.meta.url),
),
"--check",
]);
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index e2dcae514d..f3155b660b 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -70,6 +70,8 @@ import {
type RetransmitEstimate,
} from './transport.js';
import { PLUGIN_SYNC_CHANNEL } from './pluginSyncProtocol.js';
+import { DIRECT_LINK_CAPABILITY, DIRECT_LINK_SIGNAL, DirectLinkNegotiator, parseDirectSignal,
+ type DirectRuntime } from './directNegotiation.js';
import { MAKER_EVENT_BATCH_CHANNEL } from './topics.js';
import {
DIRECT_PATH_HIGH_WATER_BYTES,
@@ -247,6 +249,8 @@ export interface DeviceLinkLogger {
}
export interface DeviceLinkClientOptions {
+ /** Host WebRTC adapter. Both peers must opt in; unavailable/old hosts keep using relay. */
+ directRuntime?: DirectRuntime;
/** relay 的完整 ws(s) URL,如 wss://host/api/device-link/ws */
getWsUrl(): string;
/** 每次(重)连前取新鲜 token;null = 当前无登录态,跳过本轮并按退避重试 */
@@ -867,10 +871,30 @@ export class DeviceLinkClient {
* 数据面帧;没有通道或通道失效时,同一批帧照常走 relay。
*/
private readonly directPaths = new Map<string, DeviceLinkDirectChannel>();
+ private readonly directPeerSupport = new Set<string>();
+ private readonly directNegotiator?: DirectLinkNegotiator;
private peerPathHandlers = new Set<(change: DeviceLinkPeerPathChanged) => void>();
constructor(opts: DeviceLinkClientOptions) {
this.opts = opts;
+ if (opts.directRuntime) this.directNegotiator = new DirectLinkNegotiator({
+ runtime: opts.directRuntime,
+ identity: () => this.selfDeviceId,
+ streams: (id) => {
+ const peer = this.peerTransport.get(id);
+ return !this.stopped && this.status === 'online' && !isScopedPeer(id)
+ && this.directPeerSupport.has(id) && peer?.reliable && peer.receiveReady
+ && this.isPeerSendReady(peer) && peer.remoteStreamId
+ ? { local: peer.streamId, remote: peer.remoteStreamId } : null;
+ },
+ id: createRequestId,
+ signal: (dst, payload) => {
+ // Signaling is a control plane: never put SDP or close notices onto the direct path.
+ this.sendBestEffortRoutedEnvelope({ v: PROTOCOL_VERSION, kind: 'push', dst,
+ payload: { channel: DIRECT_LINK_SIGNAL, payload } });
+ },
+ attach: (id, channel) => this.attachDirectPath(id, channel),
+ });
this.invokeResultCache = new InvokeResultCache(opts.transferCodec);
this.timing = { ...DEFAULT_TIMING, ...opts.timing };
this.log = opts.logger ?? {
@@ -1636,6 +1660,7 @@ export class DeviceLinkClient {
? {
capabilities: this.mergeCapabilities(payload?.capabilities, [
DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT,
+ ...(this.directNegotiator && !isScopedPeer(dst) ? [DIRECT_LINK_CAPABILITY] : []),
...(peerSupportsLinkConfirm
? [DEVICE_LINK_CAPABILITY_RELIABLE_LINK_CONFIRM]
: []),
@@ -3065,6 +3090,11 @@ export class DeviceLinkClient {
private readonly inboundInvokeTransfer = new InboundInvokeTransferOptions();
private emitFrame(env: Envelope): boolean | Promise<boolean> {
+ if (env.kind === 'push' && (env.payload as { channel?: string })?.channel === DIRECT_LINK_SIGNAL) {
+ const signal = parseDirectSignal((env.payload as { payload?: unknown }).payload);
+ if (signal && env.src && !isScopedPeer(env.src)) this.directNegotiator?.receive(env.src, signal);
+ return true;
+ }
if (env.kind === 'invoke' && env.src && env.id && !isScopedPeer(env.src)) {
this.inboundInvokeTransfer.record(env.src, env.id, env.payload);
}
@@ -3502,6 +3532,9 @@ export class DeviceLinkClient {
* relay、不重建链路、不影响其它设备的链路与在途请求。
*/
private detachDirectPath(deviceId: string, reason: DeviceLinkDirectCloseReason): void {
+ if (reason === 'link-closed' || reason === 'peer-offline' || reason === 'stopped') {
+ this.directNegotiator?.forget(deviceId);
+ }
const channel = this.directPaths.get(deviceId);
if (!channel) return;
this.directPaths.delete(deviceId);
@@ -3941,6 +3974,10 @@ export class DeviceLinkClient {
}
private markPeerLinkDown(peer: PeerTransportState): void {
+ for (const [id, state] of this.peerTransport) if (state === peer) {
+ this.detachDirectPath(id, 'link-closed');
+ break;
+ }
peer.duplicateOpenRepair = null;
peer.confirmedGapRepair = null;
if (peer.pendingLinkConfirmation?.timer) {
@@ -4081,6 +4118,12 @@ export class DeviceLinkClient {
source: 'inbound-open' | 'outbound-accept' = 'inbound-open',
): void {
const peer = this.getPeerTransport(dst);
+ if (this.directNegotiator && !isScopedPeer(dst) && capabilities?.includes(DIRECT_LINK_CAPABILITY)) {
+ this.directPeerSupport.add(dst);
+ } else {
+ this.directPeerSupport.delete(dst);
+ this.directNegotiator?.forget(dst);
+ }
const reliable = (
Array.isArray(capabilities)
&& capabilities.includes(DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT)
@@ -4104,6 +4147,8 @@ export class DeviceLinkClient {
? remoteBaseSeq!
: 1;
if (peer.remoteStreamId !== nextRemoteStreamId) {
+ this.directNegotiator?.forget(dst);
+ this.detachDirectPath(dst, 'link-closed');
peer.receive.clear();
peer.duplicateOpenRepair = null;
peer.confirmedGapRepair = null;
@@ -4137,6 +4182,7 @@ export class DeviceLinkClient {
DEVICE_LINK_CAPABILITY_RELIABLE_LINK_CONFIRM,
DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT,
DEVICE_LINK_CAPABILITY_TRANSPORT_TIMEOUT_CLOSE,
+ ...(this.directNegotiator && !isScopedPeer(dst) ? [DIRECT_LINK_CAPABILITY] : []),
]),
transportStreamId: typeof payload.transportStreamId === 'string'
? payload.transportStreamId
@@ -4905,6 +4951,8 @@ export class DeviceLinkClient {
}
peer.sendPhase = 'ready';
peer.pendingLinkConfirmation = null;
+ // Defer until this handshake commits; negotiation never occupies the reliable FIFO.
+ void Promise.resolve().then(() => this.directNegotiator?.ready(dst));
this.logRecoveryStage(dst, 'send-ready');
this.cancelTimeoutCloseNotify(dst);
if (resume.duplicateOpen) {
@@ -5251,6 +5299,9 @@ export class DeviceLinkClient {
}
private clearPeerTransport(): void {
+ this.directNegotiator?.clear();
+ this.directPeerSupport.clear();
+ this.opts.directRuntime?.suspend?.();
for (const peer of this.peerTransport.values()) {
if (peer.retryTimer) clearInterval(peer.retryTimer);
if (peer.pendingLinkConfirmation?.timer) clearTimeout(peer.pendingLinkConfirmation.timer);
diff --git a/packages/device-link/src/directNegotiation.ts b/packages/device-link/src/directNegotiation.ts
new file mode 100644
index 0000000000..e293a29c27
--- /dev/null
+++ b/packages/device-link/src/directNegotiation.ts
@@ -0,0 +1,201 @@
+import type { DeviceLinkDirectChannel, DeviceLinkDirectPathHandle } from './directPath.js';
+
+/** Optional, end-to-end capability. Signaling always stays on the authenticated relay. */
+export const DIRECT_LINK_CAPABILITY = 'direct-link-v1';
+export const DIRECT_LINK_SIGNAL = 'device-link:direct-signal';
+export const DIRECT_LINK_MAX_PEERS = 16;
+export const DIRECT_LINK_TIMEOUT_MS = 15_000;
+export const DIRECT_LINK_MAX_SDP = 128 * 1024;
+
+export interface DirectRuntimeEvents {
+ open(): void;
+ message(text: string): void;
+ drained(): void;
+ closed(): void;
+}
+export interface DirectRuntimeSession {
+ offer(): Promise<string>;
+ accept(sdp: string): Promise<string>;
+ answer(sdp: string): Promise<void>;
+ send(text: string): void;
+ readonly bufferedAmount: number;
+ close(): void;
+}
+/** Browser WebRTC is injected by each host; no Electron/React dependency here. */
+export interface DirectRuntime {
+ create(id: string, events: DirectRuntimeEvents): DirectRuntimeSession;
+ /** Release the platform process when the authenticated relay generation ends. */
+ suspend?(): void;
+}
+export type DirectSignal = {
+ action: 'offer' | 'answer' | 'close';
+ id: string;
+ stream: string;
+ targetStream: string;
+ sdp?: string;
+};
+export function parseDirectSignal(value: unknown): DirectSignal | null {
+ if (!value || typeof value !== 'object') return null;
+ const v = value as Record<string, unknown>;
+ if ((v.action !== 'offer' && v.action !== 'answer' && v.action !== 'close')
+ || typeof v.id !== 'string' || !/^[a-zA-Z0-9-]{1,64}$/.test(v.id)
+ || typeof v.stream !== 'string' || v.stream.length > 128 || !v.stream
+ || typeof v.targetStream !== 'string' || v.targetStream.length > 128 || !v.targetStream) return null;
+ if (v.action !== 'close' && (typeof v.sdp !== 'string' || !v.sdp || v.sdp.length > DIRECT_LINK_MAX_SDP)) return null;
+ return { action: v.action as DirectSignal['action'], id: v.id, stream: v.stream,
+ targetStream: v.targetStream, ...(v.action !== 'close' ? { sdp: v.sdp as string } : {}) };
+}
+interface Attempt {
+ id: string;
+ localStream: string;
+ remoteStream: string;
+ session: DirectRuntimeSession;
+ handle?: DeviceLinkDirectPathHandle;
+ timer?: ReturnType<typeof setTimeout>;
+ opened: boolean;
+}
+interface Peer {
+ attempt?: Attempt;
+ retry?: ReturnType<typeof setTimeout>;
+ failures: number;
+}
+
+/** One bounded negotiation per authorized peer; failures never delay ordinary relay traffic. */
+export class DirectLinkNegotiator {
+ private readonly peers = new Map<string, Peer>();
+ constructor(private readonly deps: {
+ runtime: DirectRuntime;
+ identity(): string | null;
+ streams(peer: string): { local: string; remote: string } | null;
+ id(): string;
+ signal(peer: string, signal: DirectSignal): void;
+ attach(peer: string, channel: DeviceLinkDirectChannel): DeviceLinkDirectPathHandle;
+ }) {}
+
+ ready(peerId: string): void {
+ if (!this.deps.streams(peerId)) return;
+ // Both endpoints run this, including a Mobile which only initiated a control link.
+ // Exactly one creates offers, so mutual control cannot create glare or two channels.
+ const self = this.deps.identity();
+ if (!self || self >= peerId) return;
+ let peer = this.peers.get(peerId);
+ if (!peer) {
+ if (this.peers.size >= DIRECT_LINK_MAX_PEERS) return;
+ peer = { failures: 0 };
+ this.peers.set(peerId, peer);
+ }
+ if (peer.attempt || peer.retry) return;
+ const attempt = this.createAttempt(peerId, peer, this.deps.id());
+ if (!attempt) return;
+ void attempt.session.offer().then((sdp) => {
+ if (this.current(peerId, peer, attempt)) this.send(peerId, attempt, 'offer', sdp);
+ }).catch(() => this.fail(peerId, peer!, attempt));
+ }
+
+ receive(peerId: string, signal: DirectSignal): void {
+ const streams = this.deps.streams(peerId);
+ if (!streams || signal.stream !== streams.remote || signal.targetStream !== streams.local) return;
+ let peer = this.peers.get(peerId);
+ if (signal.action === 'offer') {
+ const self = this.deps.identity();
+ if (!self || peerId >= self) return;
+ if (!peer) {
+ if (this.peers.size >= DIRECT_LINK_MAX_PEERS) return;
+ peer = { failures: 0 };
+ this.peers.set(peerId, peer);
+ }
+ if (peer.attempt?.id === signal.id) return;
+ // A live session is not displaced by a duplicate/late offer. A retry first closes it.
+ if (peer.attempt) return;
+ const attempt = this.createAttempt(peerId, peer, signal.id);
+ if (!attempt) return;
+ void attempt.session.accept(signal.sdp!).then((sdp) => {
+ if (this.current(peerId, peer!, attempt)) this.send(peerId, attempt, 'answer', sdp);
+ }).catch(() => this.fail(peerId, peer!, attempt));
+ } else if (peer?.attempt?.id === signal.id) {
+ const attempt = peer.attempt;
+ if (signal.action === 'close') this.fail(peerId, peer, attempt, false);
+ else if (this.deps.identity()! < peerId) {
+ void attempt.session.answer(signal.sdp!).catch(() => this.fail(peerId, peer!, attempt));
+ }
+ }
+ }
+
+ forget(peerId: string): void {
+ const peer = this.peers.get(peerId);
+ if (!peer) return;
+ this.peers.delete(peerId);
+ clearTimeout(peer.retry);
+ const attempt = peer.attempt;
+ peer.attempt = undefined;
+ if (attempt) {
+ clearTimeout(attempt.timer);
+ attempt.handle?.closed();
+ attempt.session.close();
+ }
+ }
+ clear(): void { for (const id of this.peers.keys()) this.forget(id); }
+
+ private current(peerId: string, peer: Peer, attempt: Attempt): boolean {
+ const streams = this.deps.streams(peerId);
+ return this.peers.get(peerId) === peer && peer.attempt === attempt
+ && streams?.local === attempt.localStream && streams.remote === attempt.remoteStream;
+ }
+ private createAttempt(peerId: string, peer: Peer, id: string): Attempt | null {
+ const streams = this.deps.streams(peerId);
+ if (!streams) return null;
+ let attempt: Attempt;
+ try {
+ const session = this.deps.runtime.create(id, {
+ open: () => {
+ if (!this.current(peerId, peer, attempt) || attempt.opened) return;
+ clearTimeout(attempt.timer);
+ attempt.opened = true;
+ attempt.timer = setTimeout(() => {
+ if (this.current(peerId, peer, attempt)) peer.failures = 0;
+ }, 60_000);
+ const channel: DeviceLinkDirectChannel = {
+ send: (text) => session.send(text),
+ get bufferedAmount() { return session.bufferedAmount; },
+ close: () => this.fail(peerId, peer, attempt),
+ };
+ attempt.handle = this.deps.attach(peerId, channel);
+ },
+ message: (text) => { if (this.current(peerId, peer, attempt)) attempt.handle?.receive(text); },
+ drained: () => { if (this.current(peerId, peer, attempt)) attempt.handle?.drained(); },
+ closed: () => this.fail(peerId, peer, attempt),
+ });
+ attempt = { id, localStream: streams.local, remoteStream: streams.remote, session, opened: false };
+ peer.attempt = attempt;
+ attempt.timer = setTimeout(() => this.fail(peerId, peer, attempt), DIRECT_LINK_TIMEOUT_MS);
+ return attempt;
+ } catch {
+ this.retry(peerId, peer);
+ return null;
+ }
+ }
+ private send(peerId: string, attempt: Attempt, action: DirectSignal['action'], sdp?: string): void {
+ if (sdp && sdp.length > DIRECT_LINK_MAX_SDP) throw new Error('DIRECT_SDP_TOO_LARGE');
+ this.deps.signal(peerId, { action, id: attempt.id, stream: attempt.localStream,
+ targetStream: attempt.remoteStream, ...(sdp ? { sdp } : {}) });
+ }
+ private fail(peerId: string, peer: Peer, attempt: Attempt, notify = true): void {
+ if (this.peers.get(peerId) !== peer || peer.attempt !== attempt) return;
+ peer.attempt = undefined;
+ clearTimeout(attempt.timer);
+ // Clear the registration first: closing the channel can synchronously call us again.
+ attempt.handle?.closed();
+ attempt.session.close();
+ if (notify) { try { this.send(peerId, attempt, 'close'); } catch { /* Relay may be offline. */ } }
+ this.retry(peerId, peer);
+ }
+ private retry(peerId: string, peer: Peer): void {
+ if (this.peers.get(peerId) !== peer || peer.retry || !this.deps.streams(peerId)
+ || !this.deps.identity() || this.deps.identity()! >= peerId) return;
+ const delay = Math.min(60_000, 5_000 * 2 ** Math.min(peer.failures++, 4));
+ peer.retry = setTimeout(() => {
+ peer.retry = undefined;
+ if (this.peers.get(peerId) === peer) this.ready(peerId);
+ }, delay);
+ }
+}
diff --git a/packages/device-link/src/directRtcRuntime.ts b/packages/device-link/src/directRtcRuntime.ts
new file mode 100644
index 0000000000..a2cc979248
--- /dev/null
+++ b/packages/device-link/src/directRtcRuntime.ts
@@ -0,0 +1,101 @@
+/// <reference lib="dom" />
+import { MAX_FRAME_BYTES } from './protocol.js';
+import type { DirectRuntime, DirectRuntimeEvents, DirectRuntimeSession } from './directNegotiation.js';
+
+/** Data-only WebRTC, shared by Electron and the isolated Mobile WebView. No STUN/TURN:
+ * host candidates try the LAN, and the existing authenticated relay is the fallback.
+ * Binary fragments preserve UTF-8 (including surrogate pairs) across 16 KiB SCTP limits. */
+export function createDirectRtcRuntime(): DirectRuntime {
+ return { create(_id: string, events: DirectRuntimeEvents): DirectRuntimeSession {
+ const pc = new RTCPeerConnection({ iceServers: [] });
+ let dc: RTCDataChannel | undefined;
+ let closed = false;
+ let receiveBytes = 0;
+ let parts: Uint8Array[] = [];
+ let receiveTimer: ReturnType<typeof setTimeout> | undefined;
+ const encoder = new TextEncoder();
+ const decoder = new TextDecoder('utf-8', { fatal: true });
+ const close = () => {
+ if (closed) return;
+ closed = true;
+ clearTimeout(receiveTimer);
+ parts = [];
+ dc?.close();
+ pc.close();
+ events.closed();
+ };
+ const bind = (channel: RTCDataChannel) => {
+ if (closed || dc || channel.label !== 'device-link-v1' || !channel.ordered
+ || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) { channel.close(); return; }
+ dc = channel;
+ dc.binaryType = 'arraybuffer';
+ dc.bufferedAmountLowThreshold = 128 * 1024;
+ dc.onopen = () => { if (!closed) events.open(); };
+ dc.onclose = close;
+ dc.onerror = close;
+ dc.onbufferedamountlow = () => { if (!closed) events.drained(); };
+ dc.onmessage = ({ data }) => {
+ try {
+ if (closed || !(data instanceof ArrayBuffer) || data.byteLength < 2 || data.byteLength > 16 * 1024) throw new Error();
+ const frame = new Uint8Array(data);
+ if (frame[0] !== 0 && frame[0] !== 1) throw new Error();
+ receiveBytes += frame.length - 1;
+ if (receiveBytes > MAX_FRAME_BYTES || parts.length >= 256) throw new Error();
+ parts.push(frame.subarray(1));
+ clearTimeout(receiveTimer);
+ if (frame[0] === 0) { receiveTimer = setTimeout(close, 10_000); return; }
+ const bytes = new Uint8Array(receiveBytes);
+ let offset = 0;
+ for (const part of parts) { bytes.set(part, offset); offset += part.length; }
+ parts = [];
+ receiveBytes = 0;
+ events.message(decoder.decode(bytes));
+ } catch { close(); }
+ };
+ };
+ pc.ondatachannel = ({ channel }) => bind(channel);
+ pc.onconnectionstatechange = () => {
+ if (['failed', 'closed', 'disconnected'].includes(pc.connectionState)) close();
+ };
+ const gather = async (description: RTCSessionDescriptionInit): Promise<string> => {
+ await pc.setLocalDescription(description);
+ if (pc.iceGatheringState !== 'complete' && !closed) await new Promise<void>((resolve) => {
+ const timer = setTimeout(done, 3_000);
+ function done() { clearTimeout(timer); pc.removeEventListener('icegatheringstatechange', changed); resolve(); }
+ function changed() { if (pc.iceGatheringState === 'complete' || closed) done(); }
+ pc.addEventListener('icegatheringstatechange', changed);
+ changed();
+ });
+ if (closed || !pc.localDescription?.sdp) throw new Error('DIRECT_CHANNEL_CLOSED');
+ return pc.localDescription.sdp;
+ };
+ return {
+ async offer() {
+ bind(pc.createDataChannel('device-link-v1', { ordered: true }));
+ return gather(await pc.createOffer());
+ },
+ async accept(sdp) {
+ await pc.setRemoteDescription({ type: 'offer', sdp });
+ return gather(await pc.createAnswer());
+ },
+ async answer(sdp) { await pc.setRemoteDescription({ type: 'answer', sdp }); },
+ send(text) {
+ if (closed || dc?.readyState !== 'open') throw new Error('DIRECT_CHANNEL_CLOSED');
+ const bytes = encoder.encode(text);
+ if (!bytes.length || bytes.length > MAX_FRAME_BYTES || dc.bufferedAmount > 3 * MAX_FRAME_BYTES) throw new Error('DIRECT_CHANNEL_BACKPRESSURE');
+ try {
+ for (let offset = 0; offset < bytes.length; offset += 16 * 1024 - 1) {
+ const end = Math.min(bytes.length, offset + 16 * 1024 - 1);
+ const frame = new Uint8Array(end - offset + 1);
+ frame[0] = end === bytes.length ? 1 : 0;
+ frame.set(bytes.subarray(offset, end), 1);
+ dc.send(frame.buffer);
+ }
+ events.drained();
+ } catch (error) { close(); throw error; }
+ },
+ get bufferedAmount() { return dc?.bufferedAmount ?? 0; },
+ close,
+ };
+ } };
+}
diff --git a/packages/device-link/src/directRuntimeBridge.ts b/packages/device-link/src/directRuntimeBridge.ts
new file mode 100644
index 0000000000..05dfd4c17f
--- /dev/null
+++ b/packages/device-link/src/directRuntimeBridge.ts
@@ -0,0 +1,151 @@
+import { MAX_FRAME_BYTES } from './protocol.js';
+import { byteLength } from './transport.js';
+import { DIRECT_LINK_MAX_PEERS, DIRECT_LINK_MAX_SDP, type DirectRuntime,
+ type DirectRuntimeEvents, type DirectRuntimeSession } from './directNegotiation.js';
+
+export type DirectRuntimeCommand = { id: string; connection: string } & (
+ | { action: 'offer' | 'close' }
+ | { action: 'accept' | 'answer'; sdp: string }
+ | { action: 'send'; text: string; sequence: number }
+);
+export type DirectRuntimeEvent =
+ | { type: 'reply'; id: string; ok: boolean; value?: string }
+ | { type: 'open' | 'closed'; connection: string }
+ | { type: 'message'; connection: string; text: string }
+ | { type: 'buffer'; connection: string; sequence: number; buffered: number };
+
+/** Same bridge on Desktop IPC and Mobile WebView. Buffers include messages still
+ * crossing the native bridge; a frozen renderer cannot look like an empty channel. */
+export function createDirectRuntimeBridge() {
+ let transport: ((command: DirectRuntimeCommand) => void) | undefined;
+ let nextId = 0;
+ const sessions = new Map<string, { events: DirectRuntimeEvents; buffered: number;
+ queue: Map<number, number>; sequence: number; acknowledged: number; open: boolean }>();
+ const pending = new Map<string, { connection: string; resolve(value: string): void;
+ reject(error: Error): void; timer: ReturnType<typeof setTimeout> }>();
+ const close = (connection: string, notify = true) => {
+ const s = sessions.get(connection);
+ if (!s) return;
+ sessions.delete(connection);
+ for (const [id, p] of pending) if (p.connection === connection) {
+ pending.delete(id); clearTimeout(p.timer); p.reject(new Error('DIRECT_CHANNEL_CLOSED'));
+ }
+ if (notify) { try { transport?.({ id: String(++nextId), action: 'close', connection }); } catch { /* Host gone. */ } }
+ s.events.closed();
+ };
+ const invoke = (connection: string, action: 'offer' | 'accept' | 'answer', sdp?: string) => new Promise<string>((resolve, reject) => {
+ if (!sessions.has(connection) || !transport) { reject(new Error('DIRECT_RUNTIME_UNAVAILABLE')); return; }
+ const id = String(++nextId);
+ const timer = setTimeout(() => { pending.delete(id); reject(new Error('DIRECT_RUNTIME_TIMEOUT')); close(connection); }, 10_000);
+ pending.set(id, { connection, resolve, reject, timer });
+ try {
+ transport(action === 'offer' ? { id, connection, action } : { id, connection, action, sdp: sdp! });
+ } catch { close(connection); }
+ });
+ const runtime: DirectRuntime = { create(connection, events): DirectRuntimeSession {
+ if (!transport || sessions.has(connection) || sessions.size >= DIRECT_LINK_MAX_PEERS) throw new Error('DIRECT_RUNTIME_UNAVAILABLE');
+ const s = { events, buffered: 0, queue: new Map<number, number>(), sequence: 0, acknowledged: 0, open: false };
+ sessions.set(connection, s);
+ return {
+ offer: () => invoke(connection, 'offer'), accept: (sdp) => invoke(connection, 'accept', sdp),
+ answer: async (sdp) => { await invoke(connection, 'answer', sdp); },
+ send(text) {
+ const bytes = byteLength(text);
+ if (sessions.get(connection) !== s || !s.open || !transport || bytes > MAX_FRAME_BYTES
+ || s.buffered + [...s.queue.values()].reduce((a, b) => a + b, 0) + bytes > 3 * MAX_FRAME_BYTES) throw new Error('DIRECT_CHANNEL_CLOSED');
+ const sequence = ++s.sequence;
+ s.queue.set(sequence, bytes);
+ try { transport({ id: String(++nextId), action: 'send', connection, text, sequence }); }
+ catch (error) { close(connection); throw error; }
+ },
+ get bufferedAmount() { return s.buffered + [...s.queue.values()].reduce((a, b) => a + b, 0); },
+ close: () => close(connection),
+ };
+ } };
+ return {
+ runtime,
+ attach(send: (command: DirectRuntimeCommand) => void) {
+ transport = send;
+ return () => {
+ if (transport !== send) return;
+ transport = undefined;
+ for (const connection of sessions.keys()) close(connection, false);
+ };
+ },
+ receive(value: unknown) {
+ if (!value || typeof value !== 'object') return;
+ const e = value as Record<string, unknown>;
+ if (e.type === 'reply' && typeof e.id === 'string') {
+ const p = pending.get(e.id);
+ if (!p) return;
+ pending.delete(e.id); clearTimeout(p.timer);
+ if (e.ok === true && (e.value === undefined || (typeof e.value === 'string' && e.value.length <= DIRECT_LINK_MAX_SDP))) p.resolve((e.value as string) ?? '');
+ else { p.reject(new Error('DIRECT_RUNTIME_FAILED')); close(p.connection); }
+ return;
+ }
+ if (typeof e.connection !== 'string') return;
+ const s = sessions.get(e.connection);
+ if (!s) return;
+ if (e.type === 'open') { if (!s.open) { s.open = true; s.events.open(); } }
+ else if (e.type === 'closed') close(e.connection, false);
+ else if (e.type === 'message') {
+ if (!s.open || typeof e.text !== 'string' || e.text.length > MAX_FRAME_BYTES || byteLength(e.text) > MAX_FRAME_BYTES) close(e.connection);
+ else s.events.message(e.text);
+ } else if (e.type === 'buffer' && Number.isSafeInteger(e.sequence) && Number.isFinite(e.buffered)
+ && (e.sequence as number) >= s.acknowledged && (e.sequence as number) <= s.sequence
+ && (e.buffered as number) >= 0 && (e.buffered as number) <= 8 * MAX_FRAME_BYTES) {
+ for (const sequence of s.queue.keys()) if (sequence <= (e.sequence as number)) s.queue.delete(sequence);
+ s.acknowledged = e.sequence as number;
+ s.buffered = e.buffered as number;
+ // IPC/WebView delivery may be synchronous in hosts/tests; don't reenter sendReliableFrames.
+ void Promise.resolve().then(() => { if (sessions.get(e.connection as string) === s) s.events.drained(); });
+ }
+ },
+ };
+}
+
+/** Runs only in the data-only browser process. Only the host creates connection IDs. */
+export function createDirectRuntimeHost(runtime: DirectRuntime, emit: (event: DirectRuntimeEvent) => void) {
+ const sessions = new Map<string, { session: DirectRuntimeSession; sequence: number }>();
+ const close = (id: string) => { const s = sessions.get(id); sessions.delete(id); s?.session.close(); };
+ return {
+ async command(c: DirectRuntimeCommand) {
+ if (!c || typeof c.connection !== 'string' || !/^[a-zA-Z0-9-]{1,64}$/.test(c.connection) || typeof c.id !== 'string') return;
+ try {
+ let s = sessions.get(c.connection);
+ if (c.action === 'offer' || c.action === 'accept') {
+ if (s || sessions.size >= DIRECT_LINK_MAX_PEERS) throw new Error();
+ const session = runtime.create(c.connection, {
+ open: () => emit({ type: 'open', connection: c.connection }),
+ message: (text) => emit({ type: 'message', connection: c.connection, text }),
+ drained: () => { const current = sessions.get(c.connection); if (current) emit({ type: 'buffer', connection: c.connection, sequence: current.sequence, buffered: current.session.bufferedAmount }); },
+ closed: () => { if (sessions.has(c.connection)) { sessions.delete(c.connection); emit({ type: 'closed', connection: c.connection }); } },
+ });
+ s = { session, sequence: 0 };
+ sessions.set(c.connection, s);
+ }
+ if (c.action === 'close') { close(c.connection); return; }
+ if (!s) throw new Error();
+ let value: string | undefined;
+ if (c.action === 'offer') value = await s.session.offer();
+ else if (c.action === 'accept' || c.action === 'answer') {
+ if (typeof c.sdp !== 'string' || !c.sdp || c.sdp.length > DIRECT_LINK_MAX_SDP) throw new Error();
+ if (c.action === 'accept') value = await s.session.accept(c.sdp);
+ else await s.session.answer(c.sdp);
+ } else if (c.action === 'send') {
+ if (typeof c.text !== 'string' || byteLength(c.text) > MAX_FRAME_BYTES || c.sequence !== s.sequence + 1) throw new Error();
+ s.session.send(c.text);
+ s.sequence = c.sequence;
+ emit({ type: 'buffer', connection: c.connection, sequence: s.sequence, buffered: s.session.bufferedAmount });
+ return;
+ } else throw new Error();
+ emit({ type: 'reply', id: c.id, ok: true, ...(value ? { value } : {}) });
+ } catch {
+ emit({ type: 'reply', id: c.id, ok: false });
+ close(c.connection);
+ emit({ type: 'closed', connection: c.connection });
+ }
+ },
+ dispose() { for (const id of sessions.keys()) close(id); },
+ };
+}
diff --git a/packages/device-link/src/directRuntimeSource.ts b/packages/device-link/src/directRuntimeSource.ts
new file mode 100644
index 0000000000..20586aca0c
--- /dev/null
+++ b/packages/device-link/src/directRuntimeSource.ts
@@ -0,0 +1,2 @@
+// Generated by node scripts/direct-link-runtime.mjs. Do not edit.
+export const DIRECT_LINK_RUNTIME_SOURCE = "\"use strict\";var CindyDirectLink=(()=>{var h=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var k=(i,r)=>{for(var t in r)h(i,t,{get:r[t],enumerable:!0})},N=(i,r,t,n)=>{if(r&&typeof r==\"object\"||typeof r==\"function\")for(let e of v(r))!b.call(i,e)&&e!==t&&h(i,e,{get:()=>r[e],enumerable:!(n=P(r,e))||n.enumerable});return i};var D=i=>N(h({},\"__esModule\",{value:!0}),i);var V={};k(V,{create:()=>Y});var m=2*1024*1024,G=4*1024*1024;var ve=128*1024;var be=4*1024*1024,ke=16*1024*1024;var Ne=16*1024*1024,De=8*1024*1024;var xe=5*6e4;function S(i){let r=0;for(let t=0;t<i.length;t+=1){let n=i.codePointAt(t);n>65535&&(t+=1),r+=n<=127?1:n<=2047?2:n<=65535?3:4}return r}function R(i,r){let t=new Map,n=e=>{let o=t.get(e);t.delete(e),o?.session.close()};return{async command(e){if(!(!e||typeof e.connection!=\"string\"||!/^[a-zA-Z0-9-]{1,64}$/.test(e.connection)||typeof e.id!=\"string\"))try{let o=t.get(e.connection);if(e.action===\"offer\"||e.action===\"accept\"){if(o||t.size>=16)throw new Error;o={session:i.create(e.connection,{open:()=>r({type:\"open\",connection:e.connection}),message:p=>r({type:\"message\",connection:e.connection,text:p}),drained:()=>{let p=t.get(e.connection);p&&r({type:\"buffer\",connection:e.connection,sequence:p.sequence,buffered:p.session.bufferedAmount})},closed:()=>{t.has(e.connection)&&(t.delete(e.connection),r({type:\"closed\",connection:e.connection}))}}),sequence:0},t.set(e.connection,o)}if(e.action===\"close\"){n(e.connection);return}if(!o)throw new Error;let d;if(e.action===\"offer\")d=await o.session.offer();else if(e.action===\"accept\"||e.action===\"answer\"){if(typeof e.sdp!=\"string\"||!e.sdp||e.sdp.length>131072)throw new Error;e.action===\"accept\"?d=await o.session.accept(e.sdp):await o.session.answer(e.sdp)}else if(e.action===\"send\"){if(typeof e.text!=\"string\"||S(e.text)>m||e.sequence!==o.sequence+1)throw new Error;o.session.send(e.text),o.sequence=e.sequence,r({type:\"buffer\",connection:e.connection,sequence:o.sequence,buffered:o.session.bufferedAmount});return}else throw new Error;r({type:\"reply\",id:e.id,ok:!0,...d?{value:d}:{}})}catch{r({type:\"reply\",id:e.id,ok:!1}),n(e.connection),r({type:\"closed\",connection:e.connection})}},dispose(){for(let e of t.keys())n(e)}}}function I(){return{create(i,r){let t=new RTCPeerConnection({iceServers:[]}),n,e=!1,o=0,d=[],g,p=new TextEncoder,A=new TextDecoder(\"utf-8\",{fatal:!0}),f=()=>{e||(e=!0,clearTimeout(g),d=[],n?.close(),t.close(),r.closed())},E=s=>{if(e||n||s.label!==\"device-link-v1\"||!s.ordered||s.maxRetransmits!==null||s.maxPacketLifeTime!==null){s.close();return}n=s,n.binaryType=\"arraybuffer\",n.bufferedAmountLowThreshold=128*1024,n.onopen=()=>{e||r.open()},n.onclose=f,n.onerror=f,n.onbufferedamountlow=()=>{e||r.drained()},n.onmessage=({data:c})=>{try{if(e||!(c instanceof ArrayBuffer)||c.byteLength<2||c.byteLength>16*1024)throw new Error;let a=new Uint8Array(c);if(a[0]!==0&&a[0]!==1)throw new Error;if(o+=a.length-1,o>m||d.length>=256)throw new Error;if(d.push(a.subarray(1)),clearTimeout(g),a[0]===0){g=setTimeout(f,1e4);return}let u=new Uint8Array(o),l=0;for(let y of d)u.set(y,l),l+=y.length;d=[],o=0,r.message(A.decode(u))}catch{f()}}};t.ondatachannel=({channel:s})=>E(s),t.onconnectionstatechange=()=>{[\"failed\",\"closed\",\"disconnected\"].includes(t.connectionState)&&f()};let T=async s=>{if(await t.setLocalDescription(s),t.iceGatheringState!==\"complete\"&&!e&&await new Promise(c=>{let a=setTimeout(u,3e3);function u(){clearTimeout(a),t.removeEventListener(\"icegatheringstatechange\",l),c()}function l(){(t.iceGatheringState===\"complete\"||e)&&u()}t.addEventListener(\"icegatheringstatechange\",l),l()}),e||!t.localDescription?.sdp)throw new Error(\"DIRECT_CHANNEL_CLOSED\");return t.localDescription.sdp};return{async offer(){return E(t.createDataChannel(\"device-link-v1\",{ordered:!0})),T(await t.createOffer())},async accept(s){return await t.setRemoteDescription({type:\"offer\",sdp:s}),T(await t.createAnswer())},async answer(s){await t.setRemoteDescription({type:\"answer\",sdp:s})},send(s){if(e||n?.readyState!==\"open\")throw new Error(\"DIRECT_CHANNEL_CLOSED\");let c=p.encode(s);if(!c.length||c.length>m||n.bufferedAmount>3*m)throw new Error(\"DIRECT_CHANNEL_BACKPRESSURE\");try{for(let a=0;a<c.length;a+=16*1024-1){let u=Math.min(c.length,a+16384-1),l=new Uint8Array(u-a+1);l[0]=u===c.length?1:0,l.set(c.subarray(a,u),1),n.send(l.buffer)}r.drained()}catch(a){throw f(),a}},get bufferedAmount(){return n?.bufferedAmount??0},close:f}}}}function Y(i){return R(I(),i)}return D(V);})();\n";
diff --git a/packages/device-link/src/directWebViewRuntime.ts b/packages/device-link/src/directWebViewRuntime.ts
new file mode 100644
index 0000000000..59e16a012d
--- /dev/null
+++ b/packages/device-link/src/directWebViewRuntime.ts
@@ -0,0 +1,5 @@
+import { createDirectRuntimeHost } from './directRuntimeBridge.js';
+import { createDirectRtcRuntime } from './directRtcRuntime.js';
+export function create(emit: Parameters<typeof createDirectRuntimeHost>[1]) {
+ return createDirectRuntimeHost(createDirectRtcRuntime(), emit);
+}
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index c05042f5ed..42e34ad313 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -11,6 +11,10 @@ export * from "./protocol.js";
export * from "./allowlist.js";
export * from "./client.js";
export * from "./directPath.js";
+export * from "./directNegotiation.js";
+export * from "./directRuntimeBridge.js";
+export * from "./directRtcRuntime.js";
+export { DIRECT_LINK_RUNTIME_SOURCE } from "./directRuntimeSource.js";
export * from "./transport.js";
export * from "./invokeTransfer.js";
export * from "./topics.js";
diff --git a/scripts/direct-link-electron-smoke.mjs b/scripts/direct-link-electron-smoke.mjs
new file mode 100644
index 0000000000..0174ed464f
--- /dev/null
+++ b/scripts/direct-link-electron-smoke.mjs
@@ -0,0 +1,123 @@
+// Two real Electron clients, production isolated renderer/preload/main adapter,
+// loopback WS fixture. No account, app installation or developer data is used.
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { spawn } from 'node:child_process';
+const root = fileURLToPath(new URL('../', import.meta.url));
+const require = createRequire(new URL('../apps/desktop/package.json', import.meta.url));
+const { build } = require('esbuild');
+const { WebSocketServer } = require('ws');
+const temp = await mkdtemp(path.join(os.tmpdir(), 'cindy-direct-electron-'));
+const mainDir = path.join(temp, 'main'), renderer = path.join(temp, 'renderer', 'capture');
+const children = [], peers = new Map(), physical = [];
+const server = new WebSocketServer({ host: '127.0.0.1', port: 0 });
+await new Promise(resolve => server.once('listening', resolve));
+const url = `ws://127.0.0.1:${server.address().port}`;
+server.on('connection', socket => {
+ let source;
+ socket.on('message', text => {
+ const e = JSON.parse(String(text));
+ physical.push({ ...e, source });
+ if (e.kind === 'hello') {
+ source = e.payload.deviceName; peers.set(source, socket);
+ socket.send(JSON.stringify({ v: 1, kind: 'hello-ack', payload: { serverProtocolVersion: 1, deviceId: source, userId: 'fixture' } }));
+ } else if (e.kind === 'ping') socket.send(JSON.stringify({ v: 1, kind: 'pong' }));
+ else peers.get(e.dst)?.send(JSON.stringify({ ...e, src: source }));
+ });
+});
+try {
+ await mkdir(mainDir); await mkdir(path.join(renderer, 'assets'), { recursive: true });
+ await mkdir(path.join(temp, 'desktop')); await mkdir(path.join(temp, 'viewer'));
+ const shared = { bundle: true, platform: 'node', format: 'cjs', external: ['electron'],
+ define: { DESKTOP_CAPTURE_VITE_DEV_SERVER_URL: 'undefined', DESKTOP_CAPTURE_VITE_NAME: '"capture"' } };
+ const main = await build({ ...shared, write: false, plugins: [{ name: 'fixture-logger', setup(builder) {
+ builder.onLoad({ filter: /[\\/]main[\\/]logger\.ts$/ }, () => ({ contents:
+ 'export const createLogger = () => ({debug(){},info(){},warn(){},error(){}});', loader: 'ts' }));
+ } }], stdin: { resolveDir: root, contents: `
+ import { app, protocol } from 'electron';
+ import WebSocket from 'ws';
+ import { DeviceLinkClient } from './packages/device-link/src/client.ts';
+ import { desktopDirectRuntime } from './apps/desktop/src/main/device-link/directLink.ts';
+ const name=app.commandLine.getSwitchValue('smoke-role'), url=app.commandLine.getSwitchValue('smoke-ws'), data=app.commandLine.getSwitchValue('smoke-data');
+ app.setPath('userData',data);
+ protocol.registerSchemesAsPrivileged([{scheme:'cindy-desktop-capture',privileges:{standard:true,secure:true,supportFetchAPI:true}}]);
+ let client, count=0;
+ process.stdin.on('data',()=>{client?.stop();app.quit();});
+ app.whenReady().then(async()=>{
+ client=new DeviceLinkClient({directRuntime:desktopDirectRuntime,getWsUrl:()=>url,getToken:async()=> 'fixture',
+ getHello:()=>({deviceName:name,platform:process.platform,appVersion:'1',remoteControlEnabled:true,busy:false}),
+ createWebSocket:(u,headers)=>new WebSocket(u,{headers}),
+ logger:{debug(){},info(){},warn(...a){console.error(...a)},error(...a){console.error(...a)}},
+ timing:{requestTimeoutMs:20000,transportRetryIntervalMs:500}});
+ client.onFrame(e=>{
+ if(e.kind==='link-open')client.sendLinkAccept(e.src,e.id,{appVersion:'1',allowlistHash:'fixture'});
+ if(e.kind==='invoke'){
+ count++;const action=e.payload.args?.[0];
+ if(action==='break')desktopDirectRuntime.suspend();
+ client.sendInvokeResult(e.src,e.id,{ok:true,result:action==='large'?'局域网😀'.repeat(80000):count});
+ }
+ });
+ const wait=async(fn)=>{const until=Date.now()+25000;while(!fn()){if(Date.now()>until)throw Error('Electron smoke timeout');await new Promise(r=>setTimeout(r,20));}};
+ client.start();await wait(()=>client.getStatus()==='online');
+ if(name==='desktop'){console.log('HOST_READY');return;}
+ await client.openLink('desktop',{controllerName:'Desktop viewer',protocolVersion:1,appVersion:'1'});
+ await wait(()=>client.getPeerPath('desktop')==='direct');
+ console.log('DIRECT_READY');
+ const first=await client.invoke('desktop',{channel:'maker:remote-agent:v1',args:['large']});
+ if(first.result!=='局域网😀'.repeat(80000))throw Error('corrupt result');
+ console.log('DIRECT_RESULT');
+ const second=await client.invoke('desktop',{channel:'maker:remote-agent:v1',args:['break']});
+ if(second.result!==2)throw Error('duplicated execution');
+ console.log('ELECTRON_SMOKE_OK');client.stop();app.quit();
+ }).catch(e=>{console.error(e);client?.stop();app.exit(1);});
+ ` } });
+ await writeFile(path.join(mainDir, 'index.js'), main.outputFiles[0].text);
+ await build({ ...shared, entryPoints: [path.join(root, 'apps/desktop/src/preload/desktopCapturePreload.ts')],
+ outfile: path.join(mainDir, 'desktopCapturePreload.js') });
+ await build({ bundle: true, platform: 'browser', format: 'iife', outfile: path.join(renderer, 'assets', 'direct.js'),
+ stdin: { resolveDir: root, contents: `import {startDirectLinkHost} from './apps/desktop/src/capture-renderer/directLinkHost.ts'; startDirectLinkHost(window.directLinkHost);` } });
+ await writeFile(path.join(renderer, 'index.html'), '<!doctype html><script src="./assets/direct.js"></script>');
+ function launch(name) {
+ let stdout = '', stderr = '';
+ const env = { ...process.env }; delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(require('electron'), [path.join(mainDir, 'index.js'), `--smoke-role=${name}`, `--smoke-ws=${url}`, `--smoke-data=${path.join(temp, name)}`],
+ { windowsHide: true, env, stdio: ['pipe', 'pipe', 'pipe'] });
+ children.push(child);
+ child.stdout.on('data', chunk => { stdout += chunk; }); child.stderr.on('data', chunk => { stderr += chunk; });
+ const done = new Promise((resolve, reject) => {
+ child.on('error', reject); child.on('exit', code => code === 0 ? resolve() : reject(new Error(`${name}: ${code}\n${stderr.slice(-5000)}\n${stdout}`)));
+ });
+ // Attach a rejection handler immediately even while waiting for HOST_READY.
+ void done.catch(() => {});
+ return { child, done, output: () => stdout, errors: () => stderr };
+ }
+ const host = launch('desktop');
+ const until = Date.now() + 30_000;
+ while (!host.output().includes('HOST_READY')) {
+ if (Date.now() > until || host.child.exitCode !== null) throw new Error(`host not ready (${host.child.exitCode}): ${host.output()} ${host.errors()}`);
+ await new Promise(r => setTimeout(r, 30));
+ }
+ const viewer = launch('viewer');
+ const timer = setTimeout(() => { for (const c of children) c.kill(); }, 60_000);
+ try { await viewer.done; } finally { clearTimeout(timer); }
+ assert.match(viewer.output(), /DIRECT_READY/); assert.match(viewer.output(), /ELECTRON_SMOKE_OK/);
+ const relayReplays = physical.filter(e => e.kind === 'invoke').length;
+ // Closing before its ACK can replay the second request with its original sequence.
+ // The fixture's result=2 proves that this copy did not execute the command twice.
+ assert.ok(relayReplays <= 1, 'only the interrupted request may replay through relay');
+ assert.equal(physical.filter(e => e.kind === 'invoke-result').length, 1, 'only the interrupted result should fall back to relay');
+ host.child.stdin.write('stop\n'); await host.done;
+ console.log(JSON.stringify({ nativeProcesses: 2, directUtf8Bytes: 1_040_000, relayReplays,
+ relayFallbackResults: 1, executions: 2, result: 'passed' }, null, 2));
+} finally {
+ for (const child of children) if (child.exitCode === null) child.kill();
+ for (const socket of server.clients) socket.terminate();
+ await new Promise(resolve => server.close(resolve));
+ // Only the unique directory created above is recursively removed.
+ if (path.dirname(path.resolve(temp)) === path.resolve(os.tmpdir()) && path.basename(temp).startsWith('cindy-direct-electron-'))
+ await rm(temp, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 });
+}
diff --git a/scripts/direct-link-runtime.mjs b/scripts/direct-link-runtime.mjs
new file mode 100644
index 0000000000..7de329dcdb
--- /dev/null
+++ b/scripts/direct-link-runtime.mjs
@@ -0,0 +1,15 @@
+// The browser source is bundled before Hermes; shared implementation remains ordinary TS.
+import { createRequire } from 'node:module';
+import { readFile, writeFile } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+const require = createRequire(new URL('../apps/desktop/package.json', import.meta.url));
+const { build } = require('esbuild');
+const entry = fileURLToPath(new URL('../packages/device-link/src/directWebViewRuntime.ts', import.meta.url));
+const destination = new URL('../packages/device-link/src/directRuntimeSource.ts', import.meta.url);
+const output = await build({ entryPoints: [entry], bundle: true, write: false, format: 'iife',
+ globalName: 'CindyDirectLink', target: 'es2020', minify: true });
+const content = '// Generated by node scripts/direct-link-runtime.mjs. Do not edit.\n'
+ + 'export const DIRECT_LINK_RUNTIME_SOURCE = ' + JSON.stringify(output.outputFiles[0].text) + ';\n';
+if (process.argv.includes('--check')) {
+ if (await readFile(destination, 'utf8') !== content) throw new Error('Run node scripts/direct-link-runtime.mjs');
+} else await writeFile(destination, content);
diff --git a/scripts/direct-link-smoke.mjs b/scripts/direct-link-smoke.mjs
new file mode 100644
index 0000000000..84ec73e3e9
--- /dev/null
+++ b/scripts/direct-link-smoke.mjs
@@ -0,0 +1,93 @@
+// Real Chromium WebRTC + production clients/bridges; loopback fixture relay, no accounts.
+// Usage: node scripts/direct-link-smoke.mjs <Chrome executable>
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+import { fileURLToPath } from 'node:url';
+const require = createRequire(new URL('../apps/desktop/package.json', import.meta.url));
+const { build } = require('esbuild');
+const { chromium } = require('playwright-core');
+const executablePath = process.argv[2];
+if (!executablePath) throw new Error('Pass a Chrome executable');
+const output = await build({ stdin: {
+ contents: `export { DeviceLinkClient } from './packages/device-link/src/client.ts';
+ export { createDirectRtcRuntime } from './packages/device-link/src/directRtcRuntime.ts';
+ export { createDirectRuntimeBridge, createDirectRuntimeHost } from './packages/device-link/src/directRuntimeBridge.ts';
+ export { DIRECT_LINK_RUNTIME_SOURCE } from './packages/device-link/src/directRuntimeSource.ts';`,
+ resolveDir: fileURLToPath(new URL('../', import.meta.url)),
+}, bundle: true, write: false, format: 'iife', globalName: 'DirectSmoke', platform: 'browser' });
+const browser = await chromium.launch({ executablePath, headless: true, chromiumSandbox: true });
+try {
+ const page = await browser.newPage();
+ await page.addScriptTag({ content: output.outputFiles[0].text });
+ const result = await page.evaluate(async () => {
+ const { DeviceLinkClient, createDirectRtcRuntime, createDirectRuntimeBridge, createDirectRuntimeHost } = DirectSmoke;
+ const sockets = new Map(), physical = [], sessions = [], errors = [];
+ const wait = async (condition) => {
+ const deadline = Date.now() + 20_000;
+ while (!condition()) { if (Date.now() > deadline) throw new Error(`smoke timeout: ${JSON.stringify(errors)}`); await new Promise(r => setTimeout(r, 10)); }
+ };
+ const rtc = createDirectRtcRuntime();
+ const hostRuntime = { create(id, events) {
+ const session = rtc.create(id, events); sessions.push(session); return session;
+ } };
+ // Exercise exactly the serialized runtime that iOS/Android WebViews load.
+ const script = document.createElement('script'); script.textContent = DirectSmoke.DIRECT_LINK_RUNTIME_SOURCE; document.head.append(script);
+ const mobileBridge = createDirectRuntimeBridge();
+ const mobileRuntime = CindyDirectLink.create(event => mobileBridge.receive(JSON.parse(JSON.stringify(event))));
+ mobileBridge.attach(command => { void mobileRuntime.command(JSON.parse(JSON.stringify(command))); });
+ const secondBridge = createDirectRuntimeBridge();
+ const secondRuntime = createDirectRuntimeHost(createDirectRtcRuntime(), event => secondBridge.receive(event));
+ secondBridge.attach(command => { void secondRuntime.command(command); });
+ function client(id, directRuntime) {
+ return new DeviceLinkClient({ directRuntime, getWsUrl: () => 'ws://fixture.invalid', getToken: async () => 'fixture',
+ getHello: () => ({ deviceName: id, platform: 'test', appVersion: '1', remoteControlEnabled: true, busy: false }),
+ logger: { debug() {}, info() {}, warn: (...args) => errors.push(args.join(' ')), error: (...args) => errors.push(args.join(' ')) },
+ createWebSocket() {
+ const handlers = new Map();
+ const ws = { bufferedAmount: 0, on(event, callback) { handlers.set(event, callback); },
+ close() {}, deliver(env) { handlers.get('message')?.({ toString: () => JSON.stringify(env) }); },
+ send(text) {
+ const env = JSON.parse(text); physical.push({ from: id, ...env });
+ if (env.kind === 'hello') setTimeout(() => ws.deliver({ v: 1, kind: 'hello-ack', payload: { serverProtocolVersion: 1, deviceId: id, userId: 'fixture' } }), 0);
+ else if (env.kind === 'ping') setTimeout(() => ws.deliver({ v: 1, kind: 'pong' }), 0);
+ else setTimeout(() => sockets.get(env.dst)?.deliver({ ...env, src: id }), 0);
+ },
+ };
+ sockets.set(id, ws); setTimeout(() => handlers.get('open')?.(), 0); return ws;
+ }, timing: { transportRetryIntervalMs: 500, requestTimeoutMs: 20_000 },
+ });
+ }
+ const desktop = client('desktop', hostRuntime), mobile = client('phone-a', mobileBridge.runtime), other = client('phone-b', secondBridge.runtime);
+ let executions = 0, breakNext = false;
+ const large = '局域网😀'.repeat(80_000);
+ desktop.onFrame(env => {
+ if (env.kind === 'link-open') desktop.sendLinkAccept(env.src, env.id, { appVersion: '1', allowlistHash: 'fixture' });
+ if (env.kind === 'invoke') {
+ executions++;
+ if (breakNext) { breakNext = false; sessions[0].close(); }
+ desktop.sendInvokeResult(env.src, env.id, { ok: true, result: (env.payload.args ?? [])[0] === 'large' ? large : 'provider-event' });
+ }
+ });
+ try {
+ for (const c of [desktop, mobile, other]) c.start();
+ await wait(() => [desktop, mobile, other].every(c => c.getStatus() === 'online'));
+ for (const c of [mobile, other]) await c.openLink('desktop', { controllerName: 'Viewer', protocolVersion: 1, appVersion: '1' });
+ await wait(() => mobile.getPeerPath('desktop') === 'direct' && other.getPeerPath('desktop') === 'direct');
+ const before = physical.length;
+ const reply = await mobile.invoke('desktop', { channel: 'maker:remote-agent:v1', args: ['large'] });
+ const relayBusiness = physical.slice(before).filter(e => ['invoke', 'invoke-result'].includes(e.kind));
+ if (reply.result !== large || relayBusiness.length) throw new Error('LAN transfer used relay or corrupted UTF-8');
+ breakNext = true;
+ const fallback = await mobile.invoke('desktop', { channel: 'maker:remote-agent:v1', args: ['poll'] });
+ const healthy = await other.invoke('desktop', { channel: 'maker:remote-agent:v1', args: ['poll'] });
+ if (fallback.result !== 'provider-event' || healthy.result !== 'provider-event' || executions !== 3
+ || other.getPeerPath('desktop') !== 'direct') throw new Error('fallback duplicated work or disrupted another peer');
+ return { directUtf8Bytes: new TextEncoder().encode(reply.result).length, relayBusinessFramesDuringDirect: relayBusiness.length,
+ executions, fallback: fallback.ok, secondController: other.getPeerPath('desktop'),
+ signaling: physical.filter(e => e.payload?.channel === 'device-link:direct-signal').length, errors };
+ } finally { for (const c of [desktop, mobile, other]) c.stop(); mobileRuntime.dispose(); secondRuntime.dispose(); }
+ });
+ assert.equal(result.relayBusinessFramesDuringDirect, 0);
+ assert.equal(result.fallback, true);
+ console.log(JSON.stringify(result, null, 2));
+} finally { await browser.close(); }