Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-desktop): 补发网络候选并隔离媒体重连
Dash23c5b3afe398
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.tsindex 750a69baf9..b630237fb3 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts@@ -1,7 +1,7 @@import { describe, expect, it, vi } from 'vitest';import { RemoteDesktopController, type DesktopControllerDeps } from '../controller';import { acquireHumanDesktopInput, withAgentDesktopInput } from '../inputOwnership';-import type { RemoteDesktopLease } from '@cindy/device-link';+import type { RemoteDesktopIceReply, RemoteDesktopLease } from '@cindy/device-link';function harness() {let now = 1000;@@ -39,37 +39,81 @@ function harness() {};}describe('remote desktop authority and lifecycle', () => {- it.each(['release', 'takeover', 'revoke'] as const)('invalidates pending resolution after %s without stopping replacement control', async (action) => {- const h = harness();- const { lease } = await h.start();- await h.controller.request('phone', { op: 'control', lease, enabled: true });- let finish!: () => void;- let isCurrent!: () => boolean;- h.deps.resolution = vi.fn((_display, _mode, current) => {- isCurrent = current;- return new Promise<void>((resolve) => { finish = resolve; });- });- const pending = h.controller.request('phone', { op: 'resolution', lease, modeId: '1' });- expect(isCurrent()).toBe(true);- let currentLease = lease;- if (action === 'release') {- await h.controller.request('phone', { op: 'control', lease, enabled: false });- await h.controller.request('phone', { op: 'control', lease, enabled: true });- } else if (action === 'takeover') {- const next = await h.controller.request('other', { op: 'start', displayId: '1', takeover: true }) as RemoteDesktopLease;- currentLease = next.lease;- await h.controller.request('other', { op: 'control', lease: currentLease, enabled: true });- } else {- h.revoke();- }- expect(isCurrent()).toBe(false);- finish();- await expect(pending).rejects.toThrow('DESKTOP_LEASE_EXPIRED');- if (action !== 'revoke') {- expect(h.controller.hasLease(currentLease)).toBe(true);- expect(h.controller.state?.controlling).toBe(true);- }+ it('keeps ICE and media retries inside their peer lease, including after takeover', async () => {+ const h = harness(),+ first = await h.start();+ let finish!: (value: RemoteDesktopIceReply) => void;+ h.deps.ice = vi.fn(+ () =>+ new Promise<RemoteDesktopIceReply>((resolve) => {+ finish = resolve;+ }),+ );+ const ice = { op: 'ice', lease: first.lease, attemptId: 'a', after: 0, candidates: [] };+ await expect(h.controller.request('other', ice)).rejects.toThrow('DESKTOP_LEASE_EXPIRED');+ expect(h.deps.ice).not.toHaveBeenCalled();+ expect(h.deps.stopVideo).not.toHaveBeenCalled();+ for (const attemptId of ['a', 'b'])+ await h.controller.request('phone', {+ op: 'offer',+ lease: first.lease,+ sdp: 'offer',+ attemptId,+ });+ expect(h.deps.stopInput).not.toHaveBeenCalled();+ expect(h.controller.hasLease(first.lease)).toBe(true);+ const pending = h.controller.request('phone', ice);+ const next = (await h.controller.request('other', {+ op: 'start',+ displayId: '1',+ takeover: true,+ })) as RemoteDesktopLease;+ const stopped = vi.mocked(h.deps.stopVideo).mock.calls.length;+ finish({ attemptId: 'a', next: 0, candidates: [], complete: false });+ await expect(pending).rejects.toThrow('DESKTOP_STOPPED');+ expect(h.controller.hasLease(next.lease)).toBe(true);+ expect(h.deps.stopVideo).toHaveBeenCalledTimes(stopped);});+ it.each(['release', 'takeover', 'revoke'] as const)(+ 'invalidates pending resolution after %s without stopping replacement control',+ async (action) => {+ const h = harness();+ const { lease } = await h.start();+ await h.controller.request('phone', { op: 'control', lease, enabled: true });+ let finish!: () => void;+ let isCurrent!: () => boolean;+ h.deps.resolution = vi.fn((_display, _mode, current) => {+ isCurrent = current;+ return new Promise<void>((resolve) => {+ finish = resolve;+ });+ });+ const pending = h.controller.request('phone', { op: 'resolution', lease, modeId: '1' });+ expect(isCurrent()).toBe(true);+ let currentLease = lease;+ if (action === 'release') {+ await h.controller.request('phone', { op: 'control', lease, enabled: false });+ await h.controller.request('phone', { op: 'control', lease, enabled: true });+ } else if (action === 'takeover') {+ const next = (await h.controller.request('other', {+ op: 'start',+ displayId: '1',+ takeover: true,+ })) as RemoteDesktopLease;+ currentLease = next.lease;+ await h.controller.request('other', { op: 'control', lease: currentLease, enabled: true });+ } else {+ h.revoke();+ }+ expect(isCurrent()).toBe(false);+ finish();+ await expect(pending).rejects.toThrow('DESKTOP_LEASE_EXPIRED');+ if (action !== 'revoke') {+ expect(h.controller.hasLease(currentLease)).toBe(true);+ expect(h.controller.state?.controlling).toBe(true);+ }+ },+ );it('takes over only explicitly and prevents the evicted device from automatically returning', async () => {const h = harness();const first = await h.start();diff --git a/apps/desktop/src/main/remote-desktop/__tests__/hostCommands.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/hostCommands.test.tsnew file mode 100644index 0000000000..d34c60f778--- /dev/null+++ b/apps/desktop/src/main/remote-desktop/__tests__/hostCommands.test.ts@@ -0,0 +1,70 @@+import { readFileSync } from 'node:fs';+import { transpileModule, ScriptTarget } from 'typescript';+import { afterEach, expect, it, vi } from 'vitest';+import { parseDesktopIceReply } from '@cindy/device-link';+const source = readFileSync(new URL('../index.ts', import.meta.url), 'utf8');+function between(start: string, end: string) {+ const from = source.indexOf(start),+ to = source.indexOf(end, from);+ if (from < 0 || to < 0) throw new Error('Host command source missing');+ return source.slice(from, to);+}+function harness() {+ const host = { isDestroyed: () => false, send: vi.fn() },+ stopVideo = vi.fn();+ let reply!: (event: object, id: string, value: unknown) => void;+ const deps = {+ host,+ stopVideo,+ parseDesktopIceReply,+ setTimeout,+ clearTimeout,+ assertTrustedAppRendererEvent() {},+ throwIpcError: () => {+ throw new Error('PERMISSION_DENIED');+ },+ DESKTOP_LOCAL: { COMMAND: 'command', REPLY: 'reply' },+ ipcMain: {+ handle: (_name: string, handler: typeof reply) => {+ reply = handler;+ },+ },+ };+ const code = `let pending:any=null, videoAttempt='attempt';+ ${between('function requestHost(', 'async function ice(')}+ ${between('ipcMain.handle(DESKTOP_LOCAL.REPLY,', 'ipcMain.handle(\n DESKTOP_LOCAL.INPUT,')}+ return requestHost;`;+ const js = transpileModule(code, { compilerOptions: { target: ScriptTarget.ES2022 } }).outputText;+ const request = new Function(...Object.keys(deps), js)(...Object.values(deps));+ return {+ host,+ stopVideo,+ request,+ reply: (id: string, data: unknown, sender = host) => reply({ sender }, id, data),+ };+}+afterEach(() => vi.useRealTimers());+it.each(['ice', 'offer'])('limits %s timeout cleanup to the correct resource', async (op) => {+ vi.useFakeTimers();+ const h = harness();+ const result = h.request({ id: 'first', op }, 4000);+ const rejected = expect(result).rejects.toThrow('DESKTOP_VIDEO_TIMEOUT');+ await vi.advanceTimersByTimeAsync(4000);+ await rejected;+ expect(h.stopVideo).toHaveBeenCalledTimes(op === 'offer' ? 1 : 0);+ const next = h.request({ id: 'next', op: 'offer' }, 10_000);+ expect(() => h.reply('first', 'late')).toThrow('PERMISSION_DENIED');+ h.reply('next', 'answer');+ await expect(next).resolves.toBe('answer');+});+it('rejects a concurrent command and malformed ICE without stopping healthy video', async () => {+ vi.useFakeTimers();+ const h = harness();+ const result = h.request({ id: 'ice', op: 'ice' }, 4000);+ await expect(h.request({ id: 'offer', op: 'offer' }, 4000)).rejects.toThrow('DESKTOP_VIDEO_BUSY');+ expect(h.host.send).toHaveBeenCalledTimes(1);+ h.reply('ice', { attemptId: 'wrong', candidates: [], next: 0, complete: true });+ await expect(result).rejects.toThrow('DESKTOP_VIDEO_STOPPED');+ expect(h.stopVideo).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+});diff --git a/apps/desktop/src/main/remote-desktop/controller.ts b/apps/desktop/src/main/remote-desktop/controller.tsindex ee9b4182b4..86f0656373 100644--- a/apps/desktop/src/main/remote-desktop/controller.ts+++ b/apps/desktop/src/main/remote-desktop/controller.ts@@ -11,6 +11,8 @@ import {type RemoteDesktopCapabilities,type RemoteDesktopLease,type RemoteDesktopPermissions,+ type RemoteDesktopIceRequest,+ type RemoteDesktopIceReply,desktopPermissionReady,} from '@cindy/device-link';@@ -28,7 +30,9 @@ export interface DesktopControllerDeps {sdp: string,settings?: RemoteDesktopVideoSettings,cursorOverlay?: boolean,+ attemptId?: string,): Promise<string>;+ ice?(request: RemoteDesktopIceRequest): Promise<RemoteDesktopIceReply>;displayModes?(displayId: string): Promise<RemoteDesktopDisplayMode[]>;resolution?(displayId: string, modeId: string, isCurrent: () => boolean): Promise<void>;clipboard?(@@ -291,10 +295,22 @@ export class RemoteDesktopController {return { ok: true };}case 'offer': {- const sdp = await this.deps.offer(active, request.sdp, request.settings, request.cursorOverlay);+ const sdp = await this.deps.offer(+ active,+ request.sdp,+ request.settings,+ request.cursorOverlay,+ request.attemptId,+ );this.require(peer, request.lease);return { sdp };}+ case 'ice': {+ if (!this.deps.ice) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');+ const result = await this.deps.ice(request);+ this.require(peer, request.lease);+ return result;+ }}}}diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.tsindex e285b465e9..d103406cc2 100644--- a/apps/desktop/src/main/remote-desktop/index.ts+++ b/apps/desktop/src/main/remote-desktop/index.ts@@ -14,10 +14,17 @@ import {import { randomUUID } from 'node:crypto';import {isDesktopPermission,+ parseDesktopIceReply,+ type RemoteDesktopIceRequest,+ type RemoteDesktopIceReply,type RemoteDesktopLease,type RemoteDesktopVideoSettings,} from '@cindy/device-link';-import { DESKTOP_LOCAL, type DesktopHostCommand } from '../../shared/remoteDesktop';+import {+ DESKTOP_LOCAL,+ type DesktopHostCommand,+ type DesktopHostReply,+} from '../../shared/remoteDesktop';import {assertTrustedAppRendererEvent,isTrustedAppRendererWindow,@@ -101,15 +108,18 @@ let offerGeneration = 0;let nativeOverlay = false;let nativeSettings: RemoteDesktopVideoSettings | undefined;let preparingOffer = false;+let videoAttempt: string | undefined;let pending: {id: string;- resolve(sdp: string): void;+ op: 'offer' | 'ice';+ resolve(result: DesktopHostReply): void;reject(error: Error): void;timer: ReturnType<typeof setTimeout>;} | null = null;const input = new DesktopInputHost(() => remoteDesktop.stop());function stopVideo(): void {offerGeneration++;+ videoAttempt = undefined;nativeOverlay = false;nativeSettings = undefined;nativeCapture.stop();@@ -146,6 +156,7 @@ async function offer(sdp: string,settings?: RemoteDesktopVideoSettings,cursorOverlay?: boolean,+ attemptId?: string,): Promise<string> {if (!host ||@@ -168,14 +179,15 @@ async function offer(nativeAvailable ||=process.platform === 'win32' && (await readWindowsDesktopSupport()) === 'ready';try {- const available = nativeAvailable- ? await Promise.race([- sources(),- new Promise<never>((_, reject) => {- enumerationTimer = setTimeout(() => reject(new Error('DESKTOP_VIDEO_TIMEOUT')), 2000);- }),- ])- : await sources();+ const available = await Promise.race([+ sources(),+ new Promise<never>((_, reject) => {+ enumerationTimer = setTimeout(+ () => reject(new Error('DESKTOP_VIDEO_TIMEOUT')),+ nativeAvailable ? 2000 : 5000,+ );+ }),+ ]);source = desktopCaptureSource(available, lease.display.id, screen.getAllDisplays());} catch (error) {// A locked macOS session can reject Chromium's source enumeration even@@ -205,18 +217,10 @@ async function offer(nativeOverlay = cursorOverlay === true && process.platform === 'darwin';nativeSettings = settings;setVideoLease(lease.lease);- return new Promise<string>((resolve, reject) => {- const id = randomUUID();- const timer = setTimeout(() => {- if (pending?.id === id) {- pending = null;- stopVideo();- reject(new Error('DESKTOP_VIDEO_TIMEOUT'));- }- }, 10_000);- pending = { id, resolve, reject, timer };- currentHost.send(DESKTOP_LOCAL.COMMAND, {- id,+ videoAttempt = attemptId;+ const result = await requestHost(+ {+ id: randomUUID(),op: 'offer',sourceId: source?.id,nativeCapture: nativeAvailable,@@ -224,10 +228,59 @@ async function offer(lease: lease.lease,sdp,settings,- } satisfies DesktopHostCommand);+ attemptId,+ },+ 18_000,+ );+ if (typeof result !== 'string') throw new Error('DESKTOP_VIDEO_UNAVAILABLE');+ return result;+}++/** One bounded command to the existing capture owner; never reset the shared device link. */+function requestHost(+ command: DesktopHostCommand & { op: 'offer' | 'ice' },+ timeoutMs: number,+): Promise<DesktopHostReply> {+ const currentHost = host;+ if (!currentHost || currentHost.isDestroyed())+ return Promise.reject(new Error('DESKTOP_VIDEO_UNAVAILABLE'));+ if (pending) return Promise.reject(new Error('DESKTOP_VIDEO_BUSY'));+ return new Promise((resolve, reject) => {+ const { id } = command;+ const timer = setTimeout(() => {+ if (pending?.id === id) {+ pending = null;+ if (command.op === 'offer') stopVideo();+ reject(new Error('DESKTOP_VIDEO_TIMEOUT'));+ }+ }, timeoutMs);+ pending = { id, op: command.op, resolve, reject, timer };+ try {+ currentHost.send(DESKTOP_LOCAL.COMMAND, command);+ } catch {+ stopVideo();+ }});}+async function ice(request: RemoteDesktopIceRequest): Promise<RemoteDesktopIceReply> {+ if (+ request.lease !== videoLease ||+ request.attemptId !== videoAttempt ||+ !remoteDesktop.hasLease(request.lease)+ )+ throw new Error('DESKTOP_VIDEO_STOPPED');+ const generation = offerGeneration;+ const result = await requestHost({ ...request, id: randomUUID() }, 4000);+ if (+ generation !== offerGeneration ||+ request.lease !== videoLease ||+ request.attemptId !== videoAttempt+ )+ throw new Error('DESKTOP_VIDEO_STOPPED');+ return parseDesktopIceReply(result);+}+export const remoteDesktop = new RemoteDesktopController({authorized: (peer) => {const settings = readDeviceLinkSettings();@@ -247,6 +300,7 @@ export const remoteDesktop = new RemoteDesktopController({clipboardContent: process.platform === 'darwin' || process.platform === 'win32',clipboardText: process.platform === 'darwin' || process.platform === 'win32',videoSettings: true,+ trickleIce: true,backgroundViewing: true,systemAudio: supportsSystemAudio,displayModes: process.platform === 'darwin',@@ -286,6 +340,7 @@ export const remoteDesktop = new RemoteDesktopController({input: (events) => input.input(events),stopInput: () => input.stop(),offer,+ ice,stopVideo,changed: () => {// Applies to the viewer lease, not the global remote-control preference.@@ -468,10 +523,29 @@ export function registerRemoteDesktopIpc(refreshBackgroundThrottling: () => voidconst request = pending;pending = null;clearTimeout(request.timer);- if (typeof sdp === 'string' && sdp.length <= 64_000) request.resolve(sdp);- else {- stopVideo();- request.reject(new Error('DESKTOP_VIDEO_UNAVAILABLE'));+ try {+ if (+ sdp &&+ typeof sdp === 'object' &&+ 'error' in sdp &&+ [+ 'DESKTOP_AUDIO_UNAVAILABLE',+ 'DESKTOP_VIDEO_UNAVAILABLE',+ 'DESKTOP_VIDEO_TIMEOUT',+ 'DESKTOP_VIDEO_STOPPED',+ ].includes(String(sdp.error))+ )+ throw new Error(String(sdp.error));+ if (request.op === 'offer' && typeof sdp === 'string' && sdp.length <= 64_000)+ request.resolve(sdp);+ else if (request.op === 'ice') {+ const result = parseDesktopIceReply(sdp);+ if (result.attemptId !== videoAttempt) throw new Error('DESKTOP_VIDEO_STOPPED');+ request.resolve(result);+ } else throw new Error('DESKTOP_VIDEO_UNAVAILABLE');+ } catch (error) {+ if (request.op === 'offer') stopVideo();+ request.reject(error instanceof Error ? error : new Error('DESKTOP_VIDEO_UNAVAILABLE'));}});ipcMain.handle(diff --git a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsx b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsxindex cd1df1ba10..b8add113da 100644--- a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsx+++ b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsx@@ -1,6 +1,14 @@import { useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { isDesktopInput, type DesktopInput, type RemoteDesktopCursor } from '@cindy/device-link';+import {+ isDesktopInput,+ parseDesktopIceCandidates,+ REMOTE_DESKTOP_ICE_SERVERS,+ REMOTE_DESKTOP_NETWORK,+ type RemoteDesktopIceCandidate,+ type DesktopInput,+ type RemoteDesktopCursor,+} from '@cindy/device-link';import type { DesktopLocalState } from '../../../shared/remoteDesktop';import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { RemoteDesktopPermissions } from '@/components/settings/RemoteDesktopPermissions';@@ -25,8 +33,24 @@ export function RemoteDesktopHost() {let native: Awaited<ReturnType<typeof nativeCaptureStream>> | null = null;let recoverCapture: (() => void) | null = null;let activeLease: string | null = null;+ let attemptId: string | undefined;+ let localCandidates: RemoteDesktopIceCandidate[] = [];+ let remoteCandidates = new Set<string>();+ let disconnectedTimer: ReturnType<typeof setTimeout> | undefined;+ let gatheringTimer: ReturnType<typeof setTimeout> | undefined;+ let finishGathering: (() => void) | undefined;+ let exchanging = false;const stop = () => {generation++;+ exchanging = false;+ clearTimeout(disconnectedTimer);+ clearTimeout(gatheringTimer);+ finishGathering?.();+ finishGathering = undefined;+ disconnectedTimer = gatheringTimer = undefined;+ attemptId = undefined;+ localCandidates = [];+ remoteCandidates = new Set();latestCursor = undefined;if (cursorTimer) clearInterval(cursorTimer);cursorTimer = null;@@ -42,6 +66,55 @@ export function RemoteDesktopHost() {stream = null;};const unsubscribe = api.onCommand((command) => {+ if (command.op === 'ice') {+ const rtc = peer,+ current = generation;+ if (exchanging) {+ void api.reply(command.id, { error: 'DESKTOP_VIDEO_STOPPED' }).catch(() => {});+ return;+ }+ exchanging = true;+ const seen = remoteCandidates;+ void (async () => {+ if (+ !rtc ||+ command.lease !== activeLease ||+ !attemptId ||+ command.attemptId !== attemptId ||+ !Number.isSafeInteger(command.after) ||+ command.after! < 0 ||+ command.after! > localCandidates.length+ )+ throw new Error('DESKTOP_VIDEO_STOPPED');+ for (const candidate of parseDesktopIceCandidates(command.candidates)) {+ if (current !== generation) throw new Error('DESKTOP_VIDEO_STOPPED');+ const key = JSON.stringify(candidate);+ if (seen.has(key)) continue;+ if (seen.size >= REMOTE_DESKTOP_NETWORK.maxCandidates)+ throw new Error('DESKTOP_VIDEO_UNAVAILABLE');+ await rtc.addIceCandidate(candidate);+ seen.add(key);+ }+ if (current !== generation) throw new Error('DESKTOP_VIDEO_STOPPED');+ const candidates = localCandidates.slice(+ command.after,+ command.after! + REMOTE_DESKTOP_NETWORK.batchSize,+ );+ await api.reply(command.id, {+ attemptId,+ candidates,+ next: command.after! + candidates.length,+ complete:+ rtc.iceGatheringState === 'complete' &&+ command.after! + candidates.length === localCandidates.length,+ });+ })()+ .catch(() => api.reply(command.id, { error: 'DESKTOP_VIDEO_STOPPED' }).catch(() => {}))+ .finally(() => {+ if (current === generation) exchanging = false;+ });+ return;+ }if (command.op === 'capture-reset') {if (command.lease === activeLease) {native?.clear();@@ -60,6 +133,7 @@ export function RemoteDesktopHost() {const current = generation;const lease = command.lease;activeLease = lease;+ attemptId = command.attemptId;void (async () => {try {const capture = async () =>@@ -156,9 +230,24 @@ export function RemoteDesktopHost() {}stream = captured;const rtc = new RTCPeerConnection({- iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],+ iceServers: REMOTE_DESKTOP_ICE_SERVERS,});peer = rtc;+ rtc.onicecandidate = ({ candidate }) => {+ if (!command.attemptId || current !== generation || !candidate?.candidate) return;+ if (localCandidates.length >= REMOTE_DESKTOP_NETWORK.maxCandidates) {+ stop();+ return;+ }+ localCandidates.push({+ candidate: candidate.candidate,+ sdpMid: candidate.sdpMid,+ sdpMLineIndex: candidate.sdpMLineIndex,+ ...(candidate.usernameFragment+ ? { usernameFragment: candidate.usernameFragment }+ : {}),+ });+ };let recovering = false;recoverCapture = () => {if (!command.nativeCapture || native || recovering || current !== generation) return;@@ -182,11 +271,20 @@ export function RemoteDesktopHost() {track.onmute = () => recoverCapture?.();});rtc.onconnectionstatechange = () => {- if (- current === generation &&- ['failed', 'closed', 'disconnected'].includes(rtc.connectionState)- )+ if (current !== generation) return;+ if (['failed', 'closed'].includes(rtc.connectionState)) {stop();+ return;+ }+ if (rtc.connectionState === 'disconnected') {+ if (!disconnectedTimer)+ disconnectedTimer = setTimeout(() => {+ if (current === generation && rtc.connectionState === 'disconnected') stop();+ }, REMOTE_DESKTOP_NETWORK.disconnectedMs);+ } else {+ clearTimeout(disconnectedTimer);+ disconnectedTimer = undefined;+ }};rtc.ondatachannel = ({ channel }) => {if (channel.label !== 'input-v1') {@@ -259,25 +357,37 @@ export function RemoteDesktopHost() {}await sender.setParameters(parameters);}- await new Promise<void>((resolve) => {- if (rtc.iceGatheringState === 'complete') {- resolve();- return;- }- const timer = setTimeout(resolve, 3500);- rtc.onicegatheringstatechange = () => {+ if (!command.attemptId)+ await new Promise<void>((resolve) => {+ finishGathering = resolve;if (rtc.iceGatheringState === 'complete') {- clearTimeout(timer);resolve();+ return;}- };- });+ gatheringTimer = setTimeout(resolve, REMOTE_DESKTOP_NETWORK.legacyGatherMs);+ rtc.onicegatheringstatechange = () => {+ if (rtc.iceGatheringState === 'complete') {+ clearTimeout(gatheringTimer);+ resolve();+ }+ };+ });if (current === generation)await api.reply(command.id, rtc.localDescription?.sdp ?? null);- } catch {+ } catch (error) {if (current === generation) {stop();- await api.reply(command.id, null).catch(() => {});+ const code = error instanceof Error ? error.message : '';+ await api+ .reply(command.id, {+ error:+ code === 'DESKTOP_AUDIO_UNAVAILABLE'+ ? code+ : code === 'DESKTOP_VIDEO_TIMEOUT'+ ? code+ : 'DESKTOP_VIDEO_UNAVAILABLE',+ })+ .catch(() => {});}}})();diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/RemoteDesktopHost.test.tsx b/apps/desktop/src/renderer/features/remote-desktop/__tests__/RemoteDesktopHost.test.tsxindex 74b94cd665..dafeafac8a 100644--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/RemoteDesktopHost.test.tsx+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/RemoteDesktopHost.test.tsx@@ -8,27 +8,162 @@ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => kvi.mock('@/components/ui/confirm-dialog', () => ({ ConfirmDialog: () => null }));vi.mock('@/components/settings/RemoteDesktopPermissions', () => ({ RemoteDesktopPermissions: () => null }));vi.mock('../nativeCaptureStream', () => ({ nativeCaptureStream: vi.fn() }));-afterEach(() => { cleanup(); vi.unstubAllGlobals(); });+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++it.each(['rejected', 'missing'] as const)(+ 'rejects native video with %s requested audio and releases capture',+ async (audio) => {+ const track = { stop: vi.fn() };+ const stream = {+ getTracks: () => [track],+ getVideoTracks: () => [track],+ getAudioTracks: () => [],+ addTrack: vi.fn(),+ };+ const stopNative = vi.fn();+ vi.mocked(nativeCaptureStream).mockResolvedValue({+ stream,+ stop: stopNative,+ } as unknown as Awaited<ReturnType<typeof nativeCaptureStream>>);+ const capture =+ audio === 'rejected'+ ? vi.fn().mockRejectedValue(new Error('unavailable'))+ : vi.fn().mockResolvedValue(stream);+ vi.stubGlobal('navigator', { mediaDevices: { getDisplayMedia: capture } });+ let command!: (value: unknown) => void;+ const reply = vi.fn().mockResolvedValue(undefined);+ Object.assign(window, {+ electronAPI: {+ remoteDesktop: {+ onCommand: (callback: typeof command) => {+ command = callback;+ return () => {};+ },+ registerHost: vi.fn().mockResolvedValue(undefined),+ state: vi.fn().mockResolvedValue(null),+ stop: vi.fn().mockResolvedValue(undefined),+ reply,+ },+ },+ });+ render(<RemoteDesktopHost />);+ await act(async () => {+ command({+ op: 'offer',+ id: 'offer',+ lease: 'lease',+ sdp: 'sdp',+ sourceId: 'screen:1',+ nativeCapture: true,+ cursorOverlay: true,+ settings: { audio: true, fps: 30 },+ });+ });+ expect(reply).toHaveBeenCalledWith('offer', { error: 'DESKTOP_AUDIO_UNAVAILABLE' });+ expect(stopNative).toHaveBeenCalled();+ expect(track.stop).toHaveBeenCalled();+ },+);-it.each(['rejected', 'missing'] as const)('rejects native video with %s requested audio and releases capture', async (audio) => {- const track = { stop: vi.fn() };- const stream = { getTracks: () => [track], getVideoTracks: () => [track], getAudioTracks: () => [], addTrack: vi.fn() };- const stopNative = vi.fn();- vi.mocked(nativeCaptureStream).mockResolvedValue({ stream, stop: stopNative } as unknown as Awaited<ReturnType<typeof nativeCaptureStream>>);- const capture = audio === 'rejected' ? vi.fn().mockRejectedValue(new Error('unavailable')) : vi.fn().mockResolvedValue(stream);- vi.stubGlobal('navigator', { mediaDevices: { getDisplayMedia: capture } });- let command!: (value: unknown) => void;+it('exchanges replayable candidates without recapturing, tolerates transient disconnect and fences old attempts', async () => {+ vi.useFakeTimers();+ const peers: any[] = [];+ class Peer {+ connectionState = 'new';+ iceGatheringState = 'gathering';+ localDescription = { sdp: 'answer' };+ onconnectionstatechange = () => {};+ onicecandidate = (_event: any) => {};+ close = vi.fn(() => {+ this.connectionState = 'closed';+ this.onconnectionstatechange();+ });+ addIceCandidate = vi.fn(async () => {});+ constructor() {+ peers.push(this);+ }+ addTrack() {}+ getSenders() {+ return [];+ }+ async setRemoteDescription() {}+ async setLocalDescription() {}+ async createAnswer() {+ return {};+ }+ }+ vi.stubGlobal('RTCPeerConnection', Peer);+ const track = { stop: vi.fn() },+ stream = { getTracks: () => [track], getVideoTracks: () => [track] };+ const capture = vi.fn().mockResolvedValue(stream);+ vi.stubGlobal('navigator', { mediaDevices: { getUserMedia: capture } });+ let command!: (value: any) => void;const reply = vi.fn().mockResolvedValue(undefined);- Object.assign(window, { electronAPI: { remoteDesktop: {- onCommand: (callback: typeof command) => { command = callback; return () => {}; },- registerHost: vi.fn().mockResolvedValue(undefined), state: vi.fn().mockResolvedValue(null),- stop: vi.fn().mockResolvedValue(undefined), reply,- } } });+ Object.assign(window, {+ electronAPI: {+ remoteDesktop: {+ onCommand: (cb: typeof command) => {+ command = cb;+ return () => {};+ },+ reply,+ registerHost: vi.fn().mockResolvedValue(undefined),+ state: vi.fn().mockResolvedValue(null),+ stop: vi.fn().mockResolvedValue(undefined),+ },+ },+ });render(<RemoteDesktopHost />);- await act(async () => {- command({ op: 'offer', id: 'offer', lease: 'lease', sdp: 'sdp', sourceId: 'screen:1', nativeCapture: true, cursorOverlay: true, settings: { audio: true, fps: 30 } });+ const offer = {+ op: 'offer',+ id: 'offer',+ lease: 'lease',+ sdp: 'sdp',+ sourceId: 'screen:1',+ attemptId: 'a',+ };+ await act(async () => command(offer));+ expect(reply).toHaveBeenCalledWith('offer', 'answer'); // No gather delay for new endpoints.+ const candidate = {+ candidate: 'candidate:1 1 UDP 100 192.0.2.1 5000 typ host',+ sdpMid: '0',+ sdpMLineIndex: 0,+ };+ peers[0].onicecandidate({ candidate });+ const ice = {+ op: 'ice',+ id: 'ice',+ lease: 'lease',+ attemptId: 'a',+ after: 0,+ candidates: [candidate],+ };+ await act(async () => command(ice));+ await act(async () => command({ ...ice, id: 'replay' }));+ expect(reply).toHaveBeenCalledWith('replay', {+ attemptId: 'a',+ next: 1,+ candidates: [candidate],+ complete: false,});- expect(reply).toHaveBeenCalledWith('offer', null);- expect(stopNative).toHaveBeenCalled();- expect(track.stop).toHaveBeenCalled();+ expect(peers[0].addIceCandidate).toHaveBeenCalledTimes(1);+ expect(capture).toHaveBeenCalledTimes(1);+ expect(track.stop).not.toHaveBeenCalled();+ peers[0].connectionState = 'disconnected';+ peers[0].onconnectionstatechange();+ await act(() => vi.advanceTimersByTimeAsync(4999));+ expect(peers[0].close).not.toHaveBeenCalled();+ peers[0].connectionState = 'connected';+ peers[0].onconnectionstatechange();+ await act(() => vi.advanceTimersByTimeAsync(2));+ expect(peers[0].close).not.toHaveBeenCalled();+ await act(async () => command({ ...offer, id: 'new', attemptId: 'b' }));+ await act(async () => command({ ...ice, id: 'old' }));+ expect(reply).toHaveBeenCalledWith('old', { error: 'DESKTOP_VIDEO_STOPPED' });+ expect(peers[1].addIceCandidate).not.toHaveBeenCalled();+ expect(peers[1].close).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/shared/remoteDesktop.ts b/apps/desktop/src/shared/remoteDesktop.tsindex fa5ef32d08..245909f213 100644--- a/apps/desktop/src/shared/remoteDesktop.ts+++ b/apps/desktop/src/shared/remoteDesktop.ts@@ -4,6 +4,8 @@ import type {DesktopPermission,RemoteDesktopVideoSettings,RemoteDesktopPermissions,+ RemoteDesktopIceCandidate,+ RemoteDesktopIceReply,} from '@cindy/device-link';export const DESKTOP_LOCAL = {STATE: 'remote-desktop:state',@@ -22,7 +24,10 @@ export const DESKTOP_LOCAL = {} as const;export interface DesktopHostCommand {id: string;- op: 'offer' | 'stop' | 'capture-reset';+ op: 'offer' | 'stop' | 'capture-reset' | 'ice';+ attemptId?: string;+ candidates?: RemoteDesktopIceCandidate[];+ after?: number;nativeCapture?: boolean;cursorOverlay?: boolean;lease?: string;@@ -36,6 +41,17 @@ export interface DesktopLocalState {permissionGuide?: boolean;windowsSupport?: WindowsDesktopSupport;}+export type DesktopHostReply =+ | string+ | RemoteDesktopIceReply+ | {+ error:+ | 'DESKTOP_AUDIO_UNAVAILABLE'+ | 'DESKTOP_VIDEO_UNAVAILABLE'+ | 'DESKTOP_VIDEO_TIMEOUT'+ | 'DESKTOP_VIDEO_STOPPED';+ }+ | null;export type WindowsDesktopSupport = 'ready' | 'missing' | 'installRequired' | 'unavailable';export interface RemoteDesktopApi {state(checkWindowsSupport?: boolean): Promise<DesktopLocalState>;@@ -47,7 +63,7 @@ export interface RemoteDesktopApi {dismissPermissionGuide(): Promise<void>;registerHost(): Promise<void>;onCommand(listener: (command: DesktopHostCommand) => void): () => void;- reply(id: string, sdp: string | null): Promise<void>;+ reply(id: string, result: DesktopHostReply): Promise<void>;viewHeartbeat(lease: string): Promise<void>;nativeFrame(lease: string): Promise<string | RemoteDesktopCursorFrame | null>;input(lease: string, sequence: number, events: DesktopInput[]): Promise<void>;diff --git a/apps/mobile/scripts/remote-desktop-network-smoke.mjs b/apps/mobile/scripts/remote-desktop-network-smoke.mjsnew file mode 100644index 0000000000..ed0eb5fe0d--- /dev/null+++ b/apps/mobile/scripts/remote-desktop-network-smoke.mjs@@ -0,0 +1,224 @@+/** Local real-Chromium RTC smoke (no account, desktop capture, or public network).+ * node --import tsx apps/mobile/scripts/remote-desktop-network-smoke.mjs [chromium-executable]+ * Uses the installed Playwright browser; does not download one or alter app state.+ * This exercises the production WebView script, not WKWebView or cross-NAT/TURN.+ */+import { createServer } from "node:http";+import assert from "node:assert/strict";+import { chromium } from "playwright-core";+import { remoteDesktopViewerHtml } from "../src/remote-desktop/viewerHtml.ts";++const html = remoteDesktopViewerHtml("#222222", "#ffffff");+const server = createServer((req, res) => {+ res.writeHead(200, { "content-type": "text/html" });+ res.end(+ req.url === "/viewer"+ ? html+ : '<!doctype html><canvas width="640" height="360"></canvas>',+ );+});+await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+let browser;+try {+ browser = await chromium.launch({+ headless: true,+ executablePath: process.argv[2],+ });+ const context = await browser.newContext();+ const host = await context.newPage(),+ viewer = await context.newPage();+ const origin = `http://127.0.0.1:${server.address().port}`;+ await host.goto(origin);+ let activeAttempt,+ dropped = false,+ streaming = 0,+ exchanges = 0;+ const errors = [];+ const send = (message) =>+ viewer.evaluate(+ (data) =>+ window.dispatchEvent(+ new MessageEvent("message", { data: JSON.stringify(data) }),+ ),+ message,+ );+ const stripCandidates = (sdp) =>+ sdp+ .split("\r\n")+ .filter(+ (line) =>+ !line.startsWith("a=candidate:") && line !== "a=end-of-candidates",+ )+ .join("\r\n");+ await viewer.exposeFunction("signal", async (text) => {+ const message = JSON.parse(text);+ try {+ if (message.type === "ready") {+ await send({+ type: "init",+ epoch: "lease",+ width: 640,+ height: 360,+ trickleIce: true,+ });+ await send({ type: "control", enabled: true });+ } else if (message.type === "offer") {+ activeAttempt = message.attemptId;+ const answer = await host.evaluate(async (sdp) => {+ window.rtc?.close();+ clearInterval(window.paint);+ window.inputs = [];+ window.candidates = [];+ window.seen = new Set();+ const rtc = new RTCPeerConnection({ iceServers: [] });+ window.rtc = rtc;+ rtc.onicecandidate = ({ candidate }) => {+ if (candidate?.candidate)+ window.candidates.push(candidate.toJSON());+ };+ rtc.ondatachannel = ({ channel }) => {+ window.channel = channel;+ channel.onmessage = ({ data }) =>+ window.inputs.push(JSON.parse(data));+ };+ const canvas = document.querySelector("canvas"),+ ctx = canvas.getContext("2d");+ let frame = 0;+ window.paint = setInterval(() => {+ ctx.fillStyle = frame++ % 2 ? "#005599" : "#22aadd";+ ctx.fillRect(0, 0, 640, 360);+ }, 33);+ const stream = canvas.captureStream(30);+ stream.getTracks().forEach((track) => rtc.addTrack(track, stream));+ await rtc.setRemoteDescription({ type: "offer", sdp });+ await rtc.setLocalDescription(await rtc.createAnswer());+ return rtc.localDescription.sdp;+ }, stripCandidates(message.sdp));+ await send({+ type: "answer",+ epoch: "lease",+ attemptId: message.attemptId,+ sdp: stripCandidates(answer),+ });+ } else if (+ message.type === "ice" &&+ message.attemptId === activeAttempt+ ) {+ exchanges++;+ const reply = await host.evaluate(async ({ candidates, after }) => {+ for (const candidate of candidates) {+ const key = JSON.stringify(candidate);+ if (window.seen.has(key)) continue;+ await window.rtc.addIceCandidate(candidate);+ window.seen.add(key);+ }+ const batch = window.candidates.slice(after, after + 16);+ return {+ candidates: batch,+ next: after + batch.length,+ complete:+ window.rtc.iceGatheringState === "complete" &&+ after + batch.length === window.candidates.length,+ };+ }, message);+ // Force a lost signaling reply; replay must retain the same candidate cursor.+ if (!dropped) {+ dropped = true;+ return;+ }+ await send({+ type: "ice",+ epoch: "lease",+ attemptId: message.attemptId,+ exchangeId: message.exchangeId,+ ...reply,+ });+ await viewer.evaluate(() => {+ window.receivedIceReply = true;+ });+ } else if (message.type === "streaming") streaming++;+ else if (message.type === "input")+ await send({ type: "ack", epoch: "lease", sequence: message.sequence });+ } catch {+ errors.push(message.type);+ }+ });+ await viewer.addInitScript(() => {+ window.ReactNativeWebView = {+ postMessage: (data) => void window.signal(data),+ };+ const NativePeer = window.RTCPeerConnection;+ window.RTCPeerConnection = class extends NativePeer {+ constructor(config) {+ super({ ...config, iceServers: [] });+ window.viewerPeer = this;+ }+ };+ });+ await viewer.goto(`${origin}/viewer`);+ await viewer.waitForFunction(+ () =>+ document.querySelector("video")?.videoWidth > 0 &&+ window.viewerPeer?.connectionState === "connected",+ null,+ { timeout: 25_000 },+ );+ // Peer-reflexive discovery can connect from just one side's candidates before+ // the lost reply is replayed. Independently require that signaling also heals.+ await viewer.waitForFunction(() => window.receivedIceReply, null, {+ timeout: 10_000,+ });+ assert.ok(exchanges >= 2, "dropped exchange was retried");+ await send({+ type: "events",+ events: [+ { kind: "key", code: "KeyA", down: true },+ { kind: "key", code: "KeyA", down: false },+ ],+ });+ await host.waitForFunction(+ () => window.inputs.some((m) => m.events?.some((e) => e.code === "KeyA")),+ null,+ { timeout: 5000 },+ );+ const oldAttempt = activeAttempt;+ await host.evaluate(() => window.rtc.close());+ await viewer.waitForFunction(+ () => window.viewerPeer?.connectionState !== "connected",+ null,+ { timeout: 15_000 },+ );+ await viewer.waitForFunction(+ () => window.viewerPeer?.connectionState === "connected",+ null,+ { timeout: 30_000 },+ );+ assert.notEqual(+ activeAttempt,+ oldAttempt,+ "media recovered with a new attempt",+ );+ await viewer.waitForFunction(+ () => document.querySelector("video")?.videoWidth > 0,+ );+ await send({ type: "stop" });+ assert.equal(+ await viewer.evaluate(() => window.viewerPeer.connectionState),+ "closed",+ );+ assert.deepEqual(errors, []);+ console.log(+ JSON.stringify({+ result: "PASS",+ exchanges,+ streaming,+ delayedCandidates: true,+ lostReply: true,+ input: true,+ mediaRecovery: true,+ }),+ );+} finally {+ await browser?.close();+ await new Promise((resolve) => server.close(resolve));+}diff --git a/apps/mobile/src/__tests__/invokeTimeouts.test.ts b/apps/mobile/src/__tests__/invokeTimeouts.test.tsindex b1311ab02a..2a23c4644b 100644--- a/apps/mobile/src/__tests__/invokeTimeouts.test.ts+++ b/apps/mobile/src/__tests__/invokeTimeouts.test.ts@@ -6,14 +6,22 @@ import {resolveMobileInvokeTimeoutMs,} from '@/device-link/invokeTimeouts';-describe('resolveMobileInvokeTimeoutMs', () => {- it('allows a large history row to finish on a slow link without widening small status reads', () => {- expect(resolveMobileInvokeTimeoutMs('local-db:messages:list')).toBe(30_000);- expect(resolveMobileInvokeTimeoutMs('maker:list-active')).toBeUndefined();+describe("resolveMobileInvokeTimeoutMs", () => {+ it("allows remote desktop capture and ICE to finish without widening other device reads", () => {+ expect(resolveMobileInvokeTimeoutMs("device-link:remote-desktop:v1")).toBe(+ 30_000,+ );+ expect(resolveMobileInvokeTimeoutMs("device-link:state")).toBeUndefined();+ });+ it("allows a large history row to finish on a slow link without widening small status reads", () => {+ expect(resolveMobileInvokeTimeoutMs("local-db:messages:list")).toBe(30_000);+ expect(resolveMobileInvokeTimeoutMs("maker:list-active")).toBeUndefined();});- it('mobile 精确表优先:media / 文件搜索 / 词典学习保住收紧前的 30s 窗口', () => {- expect(resolveMobileInvokeTimeoutMs('device-link:media:fetch')).toBe(30_000);- expect(resolveMobileInvokeTimeoutMs('file-browser:remote-op')).toBe(30_000);+ it("mobile 精确表优先:media / 文件搜索 / 词典学习保住收紧前的 30s 窗口", () => {+ expect(resolveMobileInvokeTimeoutMs("device-link:media:fetch")).toBe(+ 30_000,+ );+ expect(resolveMobileInvokeTimeoutMs("file-browser:remote-op")).toBe(30_000);// 词典学习:桌面 advisor 的 managed refiner 单次尝试空闲窗 12s 且会换备选// profile 重试,合法执行可超 15s;15s 默认误超时会把后台学习计入熔断失败。expect(resolveMobileInvokeTimeoutMs('device-link:voice:dictionary-learning')).toBe(30_000);diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsxindex 15e1819cc1..99d39e619d 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx@@ -35,6 +35,11 @@ import { X } from "lucide-react-native";import { useTranslation } from "react-i18next";import {REMOTE_DESKTOP_CHANNEL,+ isDesktopAttemptId,+ isDesktopIceCursor,+ parseDesktopIceCandidates,+ parseDesktopIceReply,+ type RemoteDesktopIceReply,isRemoteDesktopCursor,type RemoteDesktopCursor,REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS,@@ -178,6 +183,7 @@ export default function RemoteDesktopScreen() {const connecting = useRef(false);const ready = useRef(false);const streaming = useRef(false);+ const mediaAttempt = useRef<string | null>(null);const receiveWindow = useRef({since: Date.now(),bytes: 0,@@ -196,8 +202,11 @@ export default function RemoteDesktopScreen() {const [frameReady, setFrameReady] = useState(false);const [controlReady, setControlReady] = useState(false);const connectionPending = !error && (!lease || !frameReady || !controlReady);+ const showConnectionStatus = connectionPending || (!error && status === "reconnecting");const connectionLabel = t(- recovery.current.at ? "remoteDesktop.reconnecting" : "remoteDesktop.connecting",+ recovery.current.at || status === "reconnecting"+ ? "remoteDesktop.reconnecting"+ : "remoteDesktop.connecting",);const [busy, setBusy] = useState(false);const [inputMode, setInputMode] = useInputModePreference();@@ -254,8 +263,10 @@ export default function RemoteDesktopScreen() {send,]);const request = useCallback(- <T,>(message: RemoteDesktopRequest) =>- linkRef.current.invoke<T>(deviceId, REMOTE_DESKTOP_CHANNEL, [message]),+ <T,>(message: RemoteDesktopRequest, preSend?: () => void) =>+ linkRef.current.invoke<T>(deviceId, REMOTE_DESKTOP_CHANNEL, [message], {+ preSend,+ }),[deviceId],);const transferClipboard = async (action: "copy" | "paste") => {@@ -322,6 +333,7 @@ export default function RemoteDesktopScreen() {connecting.current = false;const previous = active.current;active.current = null;+ mediaAttempt.current = null;heldKeys.current.clear();streaming.current = false;receiveWindow.current = {@@ -452,6 +464,7 @@ export default function RemoteDesktopScreen() {}send({type: "init",+ trickleIce: result.trickleIce === true,epoch: next.lease,width: display.width,height: display.height,@@ -715,39 +728,133 @@ export default function RemoteDesktopScreen() {}const current = active.current;if (!current || message.epoch !== current.lease) return;+ const requireMediaAttempt = () => {+ if (+ active.current !== current ||+ mediaAttempt.current !== message.attemptId+ )+ throw new Error("DESKTOP_VIDEO_STOPPED");+ };switch (message.type) {case "offer":- if (typeof message.sdp !== "string" || message.sdp.length > 64_000)+ if (+ typeof message.sdp !== "string" ||+ message.sdp.length > 64_000 ||+ !isDesktopAttemptId(message.attemptId)+ )return;- void request<{ sdp: string }>({- op: "offer",- lease: current.lease,- sdp: message.sdp,- cursorOverlay: caps?.cursorOverlay === true,- ...(caps?.videoSettings- ? {- settings: {- ...videoSettingsRef.current,- audio: Boolean(- caps.systemAudio && videoSettingsRef.current.audio,- ),- },- }- : {}),- })+ mediaAttempt.current = message.attemptId;+ void request<{ sdp: string }>(+ {+ op: "offer",+ lease: current.lease,+ sdp: message.sdp,+ ...(caps?.trickleIce ? { attemptId: message.attemptId } : {}),+ cursorOverlay: caps?.cursorOverlay === true,+ ...(caps?.videoSettings+ ? {+ settings: {+ ...videoSettingsRef.current,+ audio: Boolean(+ caps.systemAudio && videoSettingsRef.current.audio,+ ),+ },+ }+ : {}),+ },+ requireMediaAttempt,+ ).then((answer) => {- if (active.current === current)- send({ type: "answer", sdp: answer.sdp });+ if (+ active.current === current &&+ mediaAttempt.current === message.attemptId+ )+ send({+ type: "answer",+ epoch: current.lease,+ attemptId: message.attemptId,+ sdp: answer.sdp,+ });})- .catch(() => {- if (active.current === current) {- send({ type: "fallback" });+ .catch((error) => {+ if (+ active.current === current &&+ mediaAttempt.current === message.attemptId+ ) {+ const permanent =+ /DESKTOP_(AUDIO_UNAVAILABLE|SCREEN_PERMISSION_REQUIRED|DISABLED|STOPPED|LEASE_EXPIRED)/.test(+ String(error),+ );+ send({+ type: "fallback",+ epoch: current.lease,+ attemptId: message.attemptId,+ retry: !permanent,+ });setStatus("compatibility");setSettingBusy(false);setSettingNotice(t("remoteDesktop.videoSettingsFailed"));}});break;+ case "ice": {+ if (+ !caps?.trickleIce ||+ message.attemptId !== mediaAttempt.current ||+ !isDesktopAttemptId(message.attemptId) ||+ !isDesktopIceCursor(message.after) ||+ !Number.isSafeInteger(message.exchangeId)+ )+ return;+ let candidates;+ try {+ candidates = parseDesktopIceCandidates(message.candidates);+ } catch {+ return;+ }+ void request<RemoteDesktopIceReply>(+ {+ op: "ice",+ lease: current.lease,+ attemptId: message.attemptId,+ after: message.after,+ candidates,+ },+ requireMediaAttempt,+ )+ .then((value) => {+ const reply = parseDesktopIceReply(value);+ if (+ active.current === current &&+ mediaAttempt.current === message.attemptId &&+ reply.attemptId === message.attemptId+ )+ send({+ type: "ice",+ epoch: current.lease,+ exchangeId: message.exchangeId,+ ...reply,+ });+ })+ .catch(() => {+ if (+ active.current === current &&+ mediaAttempt.current === message.attemptId+ )+ send({+ type: "ice",+ epoch: current.lease,+ attemptId: message.attemptId,+ exchangeId: message.exchangeId,+ error: true,+ });+ });+ break;+ }+ case "reconnecting":+ if (message.attemptId === mediaAttempt.current)+ setStatus("reconnecting");+ break;case "pipCapability":setCanPip(message.supported === true);break;@@ -1156,7 +1263,7 @@ export default function RemoteDesktopScreen() {style={styles.webview}testID="remoteDesktop.viewer"/>- {(connectionPending || (!lease && error)) && (+ {(showConnectionStatus || (!lease && error)) && (<ViewpointerEvents="box-none"style={[@@ -1164,7 +1271,7 @@ export default function RemoteDesktopScreen() {{ top: edgePadding.paddingTop + spacing.xs + 44 + spacing.lg },]}>- {connectionPending ? (+ {showConnectionStatus ? (<Viewstyle={styles.connectionBadge}accessibilityRole="progressbar"@@ -1196,7 +1303,7 @@ export default function RemoteDesktopScreen() {)}</View>)}- {lease && !connectionPending && !lease.controlling && !operations && (+ {lease && !showConnectionStatus && !lease.controlling && !operations && (<Textstyle={[styles.viewOnly,@@ -1206,7 +1313,7 @@ export default function RemoteDesktopScreen() {{t("remoteDesktop.viewOnly")}</Text>)}- {lease && !connectionPending && !operations && !landscape && (+ {lease && !showConnectionStatus && !operations && !landscape && (<RemoteDesktopNetworkStatusstats={network}video={status === "live"}@@ -1226,7 +1333,7 @@ export default function RemoteDesktopScreen() {landscape={landscape}topInset={edgePadding.paddingTop}title={deviceName}- caption={connectionPending ? connectionLabel : `${t(`remoteDesktop.${status}`)}${lease ? ` · ${t(lease.controlling ? "remoteDesktop.controlling" : "remoteDesktop.viewOnly")}` : ""}`}+ caption={showConnectionStatus ? connectionLabel : `${t(`remoteDesktop.${status}`)}${lease ? ` · ${t(lease.controlling ? "remoteDesktop.controlling" : "remoteDesktop.viewOnly")}` : ""}`}onClose={() => setOperations(false)}footer={<RemoteDesktopDisconnect onPress={leave} />}>diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsxindex b4e2fb624d..cb2de282b1 100644--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx@@ -17,6 +17,7 @@ const fixture = vi.hoisted(() => ({message: null as null | ((e: unknown) => void),size: { width: 390, height: 844 },canControl: true,+ trickleIce: false,focused: true,status: "online",appState: null as null | ((state: string) => void),@@ -182,6 +183,7 @@ beforeEach(() => {fixture.status = "online";AppState.currentState = "active";fixture.canControl = true;+ fixture.trickleIce = false;fixture.size = { width: 390, height: 844 };fixture.openLink.mockResolvedValue({});fixture.invoke.mockImplementation(async (_device, _channel, [request]) => {@@ -189,6 +191,7 @@ beforeEach(() => {case "capabilities":return {version: 1,+ trickleIce: fixture.trickleIce,automaticReconnect: true,enabled: true,canControl: fixture.canControl,@@ -294,19 +297,157 @@ describe("remote desktop controls", () => {const offer = () =>fixture.message!({nativeEvent: {- data: JSON.stringify({ type: "offer", epoch: "lease", sdp: "offer" }),+ data: JSON.stringify({+ type: "offer",+ epoch: "lease",+ attemptId: "1",+ sdp: "offer",+ }),},});act(offer);await act(async () => control({ controlling: true }));expect(host.querySelector('[data-testid="remoteDesktop.connectingStatus"]')).toBeNull();await act(async () => answer({ sdp: "valid-answer" }));- expect(sent()).toContainEqual({ type: "answer", sdp: "valid-answer" });+ expect(sent()).toContainEqual({+ type: "answer",+ epoch: "lease",+ attemptId: "1",+ sdp: "valid-answer",+ });act(offer);act(() => root.unmount());mounted = false;await act(async () => answer({ sdp: "late-answer" }));- expect(sent()).not.toContainEqual({ type: "answer", sdp: "late-answer" });+ expect(+ sent().some((m) => m.type === "answer" && m.sdp === "late-answer"),+ ).toBe(false);+ });+ it("fences late signaling within one lease and preserves the legacy desktop path", async () => {+ await connect();+ const original = fixture.invoke.getMockImplementation()!;+ const answers: ((value: object) => void)[] = [];+ fixture.invoke.mockImplementation((...args) =>+ args[2][0].op === "offer"+ ? new Promise((resolve) => answers.push(resolve))+ : original(...args),+ );+ const offer = (attemptId: string) =>+ act(() =>+ fixture.message!({+ nativeEvent: {+ data: JSON.stringify({+ type: "offer",+ epoch: "lease",+ attemptId,+ sdp: "offer",+ }),+ },+ }),+ );+ offer("old");+ offer("new");+ expect(+ requests()+ .filter((m) => m.op === "offer")+ .every((m) => m.attemptId === undefined),+ ).toBe(true);+ const oldSend = fixture.invoke.mock.calls.find(+ (call) => call[2][0].op === "offer",+ )![3].preSend;+ expect(oldSend).toThrow("DESKTOP_VIDEO_STOPPED");+ await act(async () => answers[0]({ sdp: "old" }));+ expect(sent().some((m) => m.type === "answer" && m.sdp === "old")).toBe(+ false,+ );+ await act(async () => answers[1]({ sdp: "new" }));+ expect(sent()).toContainEqual({+ type: "answer",+ epoch: "lease",+ attemptId: "new",+ sdp: "new",+ });+ expect(requests().filter((m) => m.op === "start")).toHaveLength(1);+ });+ it("forwards bounded ICE batches only when both endpoints support incremental signaling", async () => {+ fixture.trickleIce = true;+ await connect();+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation((...args) => {+ const r = args[2][0];+ return r.op === "ice"+ ? Promise.resolve({+ attemptId: r.attemptId,+ next: r.after,+ candidates: [],+ complete: true,+ })+ : original(...args);+ });+ const message = (data: object) =>+ act(async () =>+ fixture.message!({+ nativeEvent: { data: JSON.stringify({ epoch: "lease", ...data }) },+ }),+ );+ await message({ type: "offer", attemptId: "a", sdp: "offer" });+ await message({+ type: "ice",+ attemptId: "a",+ after: 0,+ candidates: [],+ exchangeId: 1,+ });+ expect(sent()).toContainEqual({+ type: "ice",+ epoch: "lease",+ attemptId: "a",+ next: 0,+ candidates: [],+ complete: true,+ exchangeId: 1,+ });+ await message({+ type: "ice",+ attemptId: "stale",+ after: 0,+ candidates: [],+ exchangeId: 2,+ });+ await message({+ type: "ice",+ attemptId: "a",+ after: -1,+ candidates: [],+ exchangeId: 3,+ });+ expect(requests().filter((m) => m.op === "ice")).toHaveLength(1);+ });+ it.each([false, true])("shows media recovery without replacing the lease (landscape=%s)", async (landscape) => {+ if (landscape) {+ fixture.size = { width: 844, height: 390 };+ act(() => root.render(<RemoteDesktopScreen />));+ }+ await connect();+ const message = (type: string) => act(async () => {+ fixture.message!({ nativeEvent: { data: JSON.stringify({+ type, epoch: "lease", attemptId: "1", sdp: "offer",+ }) } });+ });+ await message("offer");+ await message("streaming");+ const ownership = () => requests().filter((r) => ["start", "control", "stop"].includes(r.op));+ const previousOwnership = [...ownership()];+ await message("reconnecting");+ const badge = () => host.querySelector('[data-testid="remoteDesktop.connectingStatus"]');+ expect(badge()?.textContent).toBe("remoteDesktop.reconnecting");+ expect(host.textContent).not.toContain("remoteDesktop.viewOnly");+ expect(host.querySelector('[data-testid="remoteDesktop.viewer"]')).not.toBeNull();+ expect(button("keyboard").disabled).toBe(false);+ expect(ownership()).toEqual(previousOwnership);+ await message("streaming");+ expect(badge()).toBeNull();+ expect(ownership()).toEqual(previousOwnership);});it("shows live receive rate, rejects old lease samples, and expires stale metrics", async () => {await connect();diff --git a/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts b/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.tsnew file mode 100644index 0000000000..fa8d78086c--- /dev/null+++ b/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts@@ -0,0 +1,247 @@+import vm from "node:vm";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { REMOTE_DESKTOP_NETWORK as net } from "@cindy/device-link";+import { DESKTOP_RTC_SCRIPT } from "../viewerRtc";++// Executes the exact static script embedded in WKWebView, with only RTC/DOM replaced.+function viewer(trickle = true) {+ const messages: any[] = [];+ const peers: any[] = [];+ class Peer {+ connectionState = "new";+ iceGatheringState = "gathering";+ remoteDescription: any = null;+ localDescription = { sdp: "offer" };+ onconnectionstatechange = () => {};+ onicecandidate = (_event: any) => {};+ onicegatheringstatechange = () => {};+ channel = { readyState: "open", close: vi.fn(), send: vi.fn() };+ close = vi.fn(() => {+ this.connectionState = "closed";+ this.onconnectionstatechange();+ });+ addIceCandidate = vi.fn(async (_candidate: any) => {});+ setRemoteDescription = vi.fn(async (value: any) => {+ this.remoteDescription = value;+ });+ constructor() {+ peers.push(this);+ }+ createDataChannel() {+ return this.channel;+ }+ addTransceiver() {}+ async createOffer() {+ return this.localDescription;+ }+ async setLocalDescription() {}+ async getStats() {+ return new Map();+ }+ }+ const video = {+ style: { display: "none" },+ srcObject: null,+ onplaying: null,+ play: async () => {},+ };+ const image = { style: { display: "block" }, removeAttribute() {} };+ const retained = vi.fn();+ const release = vi.fn();+ const context = vm.createContext({+ net,+ iceServers: [],+ window: { RTCPeerConnection: Peer },+ RTCPeerConnection: Peer,+ video,+ image,+ document: {},+ Date,+ Map,+ Set,+ setTimeout,+ clearTimeout,+ setInterval,+ clearInterval,+ retainFrame: retained,+ release,+ render() {},+ receiveCursor() {},+ networkStats: () => ({ sample: null }),+ post: (message: any) => messages.push(message),+ });+ const api = vm.runInContext(+ `+ let pc=null,dc=null,generation=0,epoch='lease',statsTimer=null,statsSample=null;+ ${DESKTOP_RTC_SCRIPT}+ trickleIce=${trickle};+ ({start:connect,answer:receiveAnswer,ice:receiveIce,fail:failRtc,+ stop:()=>{epoch=null;closeRtc();}})+ `,+ context,+ );+ const latest = (type: string) =>+ messages.filter((m) => m.type === type).at(-1);+ return {+ api,+ peers,+ messages,+ latest,+ video,+ retained,+ release,+ answer: async () => api.answer({ ...latest("offer"), sdp: "answer" }),+ change: (state: string, peer = peers.at(-1)) => {+ peer.connectionState = state;+ peer.onconnectionstatechange();+ },+ reply: async (extra: any = {}) =>+ api.ice({+ ...latest("ice"),+ candidates: [],+ next: latest("ice").after,+ complete: false,+ ...extra,+ }),+ };+}+const candidate = {+ candidate: "candidate:1 1 UDP 100 192.0.2.1 5000 typ host",+ sdpMid: "0",+ sdpMLineIndex: 0,+};+beforeEach(() => vi.useFakeTimers());+afterEach(() => vi.useRealTimers());++it("sends an early offer, then flushes candidates gathered after the answer", async () => {+ const h = viewer();+ await h.api.start();+ expect(h.latest("offer")).toMatchObject({ attemptId: "1", sdp: "offer" });+ await h.answer();+ await h.reply();+ h.peers[0].onicecandidate({ candidate });+ await vi.advanceTimersByTimeAsync(net.pollMs);+ expect(h.latest("ice").candidates).toEqual([candidate]);+ await h.reply({ candidates: [candidate], next: 1 });+ expect(h.peers[0].addIceCandidate).toHaveBeenCalledWith(candidate);+ h.api.stop();+ expect(vi.getTimerCount()).toBe(0);+});++it("retains video on transient disconnection and cancels the grace timeout after recovery", async () => {+ const h = viewer();+ await h.api.start();+ await h.answer();+ h.video.style.display = "block";+ h.change("connected");+ h.change("disconnected");+ expect(h.latest("reconnecting")).toBeDefined();+ await vi.advanceTimersByTimeAsync(net.disconnectedMs - 1);+ expect(h.peers[0].close).not.toHaveBeenCalled();+ expect(h.video.style.display).toBe("block");+ h.change("connected");+ await vi.advanceTimersByTimeAsync(2);+ expect(h.latest("streaming")).toBeDefined();+ expect(h.peers).toHaveLength(1);+ h.api.stop();+});++it("retries only three times, keeps a frame, and cancels every timer on exit", async () => {+ const h = viewer();+ await h.api.start();+ for (const delay of net.retryMs) {+ h.change("failed");+ await vi.advanceTimersByTimeAsync(delay);+ }+ h.change("failed");+ await vi.advanceTimersByTimeAsync(120_000);+ expect(h.peers).toHaveLength(4);+ expect(h.retained).toHaveBeenCalled();+ h.api.stop();+ expect(vi.getTimerCount()).toBe(0);+});++it("does not replenish retry budget from a brief connection", async () => {+ const h = viewer();+ await h.api.start();+ for (const delay of net.retryMs) {+ h.change("connected");+ await vi.advanceTimersByTimeAsync(1000);+ h.change("failed");+ await vi.advanceTimersByTimeAsync(delay);+ }+ h.change("failed");+ await vi.advanceTimersByTimeAsync(60_000);+ expect(h.peers).toHaveLength(4);+ h.api.stop();+});++it("separates answer wait from connection checks and drops the previous attempt answer", async () => {+ const h = viewer();+ await h.api.start();+ const old = h.latest("offer");+ await vi.advanceTimersByTimeAsync(net.answerMs - 1);+ expect(h.peers[0].close).not.toHaveBeenCalled();+ await h.answer();+ await vi.advanceTimersByTimeAsync(net.connectMs - 1);+ expect(h.peers[0].close).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1 + net.retryMs[0]);+ await h.api.answer({ ...old, sdp: "stale" });+ expect(h.peers[1].setRemoteDescription).not.toHaveBeenCalled();+ h.api.stop();+});++it("does not acknowledge unsent candidates when an earlier exchange reply arrives late", async () => {+ const h = viewer();+ await h.api.start();+ await h.answer();+ const old = h.latest("ice");+ h.peers[0].onicecandidate({ candidate });+ await vi.advanceTimersByTimeAsync(4500);+ const next = h.latest("ice");+ expect(next.exchangeId).not.toBe(old.exchangeId);+ await h.api.ice({ ...old, candidates: [], next: 0, complete: true });+ await h.reply({ error: true });+ await vi.advanceTimersByTimeAsync(1000);+ expect(h.latest("ice").candidates).toEqual([candidate]);+ await h.reply();+ await vi.advanceTimersByTimeAsync(net.pollMs);+ expect(h.latest("ice").candidates).toEqual([]);+ h.api.stop();+});++it("preserves the legacy full-SDP path when capability is absent", async () => {+ const h = viewer(false);+ const starting = h.api.start();+ await vi.advanceTimersByTimeAsync(net.legacyGatherMs - 1);+ expect(h.latest("offer")).toBeUndefined();+ await vi.advanceTimersByTimeAsync(1);+ await starting;+ await h.answer();+ expect(h.latest("ice")).toBeUndefined();+ h.api.stop();+});++it("cannot let a stopped viewer or stale candidate change a different viewer", async () => {+ const a = viewer(),+ b = viewer();+ await a.api.start();+ await b.api.start();+ await a.answer();+ const old = a.latest("ice");+ a.api.stop();+ await a.api.ice({ ...old, candidates: [candidate], next: 1 });+ await vi.advanceTimersByTimeAsync(1000);+ expect(a.peers[0].addIceCandidate).not.toHaveBeenCalled();+ expect(b.peers[0].close).not.toHaveBeenCalled();+ b.api.stop();+});++it("does not retry an unavailable platform or a permanent host error", async () => {+ const h = viewer();+ await h.api.start();+ h.api.fail("host", false);+ await vi.advanceTimersByTimeAsync(120_000);+ expect(h.peers).toHaveLength(1);+ h.api.stop();+});diff --git a/apps/mobile/src/remote-desktop/viewerHtml.ts b/apps/mobile/src/remote-desktop/viewerHtml.tsindex 9271b33d3f..f55d4758f4 100644--- a/apps/mobile/src/remote-desktop/viewerHtml.ts+++ b/apps/mobile/src/remote-desktop/viewerHtml.ts@@ -1,5 +1,10 @@import { DESKTOP_TRANSFORM_SCRIPT } from "./geometry";-import { DESKTOP_KEY_CODES } from "@cindy/device-link";+import {+ DESKTOP_KEY_CODES,+ REMOTE_DESKTOP_ICE_SERVERS,+ REMOTE_DESKTOP_NETWORK,+} from "@cindy/device-link";+import { DESKTOP_RTC_SCRIPT } from "./viewerRtc";import { DESKTOP_NETWORK_STATS_SCRIPT } from "./networkStats";export function remoteDesktopViewerHtml(@@ -34,6 +39,7 @@ export function remoteDesktopViewerHtml(</div><textarea id="keyboard-input" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" aria-label="Keyboard"></textarea><script>const transform=${DESKTOP_TRANSFORM_SCRIPT};const networkStats=${DESKTOP_NETWORK_STATS_SCRIPT};+ const net=${JSON.stringify(REMOTE_DESKTOP_NETWORK)},iceServers=${JSON.stringify(REMOTE_DESKTOP_ICE_SERVERS)};const validKeys=new Set(${JSON.stringify(DESKTOP_KEY_CODES)});${VIEWER_SCRIPT}</script></body></html>`;@@ -193,7 +199,7 @@ const VIEWER_SCRIPT = String.raw`else if(event.kind==='scroll'&&tail?.kind==='scroll'){tail.dx=Math.max(-2000,Math.min(2000,tail.dx+event.dx));tail.dy=Math.max(-2000,Math.min(2000,tail.dy+event.dy));}else pending.push(event);if(pending.length>64){pending=[{kind:'release'}];control=false;post({type:'inputOverflow'});}}- function flush(){if(!pending.length||sending)return;const events=pending.splice(0,64),sequence=++seq;if(dc&&dc.readyState==='open'&&dc.bufferedAmount<16384){dc.send(JSON.stringify({sequence,events}));}else{sending=true;post({type:'input',sequence,events});}}+ function flush(){if(!pending.length||sending)return;const events=pending.splice(0,64),sequence=++seq;if(pc?.connectionState==='connected'&&dc&&dc.readyState==='open'&&dc.bufferedAmount<16384){dc.send(JSON.stringify({sequence,events}));}else{sending=true;post({type:'input',sequence,events});}}setInterval(()=>{// Hold displacement controls speed, even without further pointer moves.// Skip missed ticks while awaiting ACK instead of building a scroll backlog.@@ -284,23 +290,7 @@ const VIEWER_SCRIPT = String.raw`const canvas=document.createElement('canvas');try{const scale=Math.min(1,1280/Math.max(video.videoWidth,video.videoHeight));canvas.width=Math.max(1,Math.round(video.videoWidth*scale));canvas.height=Math.max(1,Math.round(video.videoHeight*scale));const context=canvas.getContext('2d');if(context){context.drawImage(video,0,0,canvas.width,canvas.height);image.src=canvas.toDataURL('image/jpeg',.7);}}catch{/* Keep the previous compatibility frame if WebKit cannot read video. */}finally{canvas.width=0;canvas.height=0;}}- function closeRtc(preserveFrame=true){if(preserveFrame)retainFrame();generation++;clearInterval(statsTimer);statsTimer=null;statsSample=null;if(dc)dc.close();if(pc)pc.close();pc=null;dc=null;video.srcObject=null;video.style.display='none';image.style.display='block';if(!preserveFrame)image.removeAttribute('src');}- async function connect(){closeRtc();const g=generation;if(!window.RTCPeerConnection){post({type:'fallback'});return;}- try{const rtc=new RTCPeerConnection({iceServers:[{urls:'stun:stun.l.google.com:19302'}]});pc=rtc;dc=rtc.createDataChannel('input-v1');rtc.addTransceiver('video',{direction:'recvonly'});rtc.addTransceiver('audio',{direction:'recvonly'});- dc.onmessage=e=>{try{if(g!==generation||pc!==rtc)return;if(typeof e.data!=='string'||e.data.length>80000)return;const message=JSON.parse(e.data);if(message.type==='cursor')receiveCursor(message.cursor);if((video.webkitPresentationMode==='picture-in-picture'||document.pictureInPictureElement===video)&&message.type==='viewPing'&&typeof message.challenge==='string'&&message.challenge.length<=64&&dc?.readyState==='open')dc.send(message.challenge);}catch{}};- let readingStats=false;- statsTimer=setInterval(async()=>{- if(readingStats||g!==generation)return;readingStats=true;- try{const stats=await rtc.getStats();if(g!==generation||pc!==rtc)return;const result=networkStats(stats,statsSample);statsSample=result.sample;post({type:'network',transport:result.transport,bytesPerSecond:result.bytesPerSecond,latencyMs:result.latencyMs});}catch{/* Metrics must never interrupt the stream. */}finally{readingStats=false;}- },1000);- rtc.ontrack=e=>{if(g!==generation)return;video.srcObject=e.streams[0]||new MediaStream([e.track]);video.play().catch(()=>{});};- video.onplaying=()=>{if(g!==generation)return;video.style.display='block';image.style.display='none';post({type:'streaming'});post({type:'pipCapability',supported:!!(video.webkitSupportsPresentationMode?.('picture-in-picture')||document.pictureInPictureEnabled)});render();};- rtc.onconnectionstatechange=()=>{if(g===generation&&['failed','disconnected','closed'].includes(rtc.connectionState)){release();closeRtc();post({type:'fallback'});}};- await rtc.setLocalDescription(await rtc.createOffer());await new Promise(resolve=>{if(rtc.iceGatheringState==='complete')return resolve();const timer=setTimeout(resolve,3000);rtc.onicegatheringstatechange=()=>{if(rtc.iceGatheringState==='complete'){clearTimeout(timer);resolve();}};});- if(g===generation)post({type:'offer',sdp:rtc.localDescription.sdp});- setTimeout(()=>{if(g===generation&&rtc.connectionState!=='connected'){closeRtc();post({type:'fallback'});}},12000);- }catch{if(g===generation){closeRtc();post({type:'fallback'});}}- }+ ${DESKTOP_RTC_SCRIPT}function reportPresentation(){post({type:'presentation',active:video.webkitPresentationMode==='picture-in-picture'||document.pictureInPictureElement===video});}video.addEventListener('webkitpresentationmodechanged',reportPresentation);video.addEventListener('enterpictureinpicture',reportPresentation);@@ -317,7 +307,7 @@ const VIEWER_SCRIPT = String.raw`}else if(video.webkitSetPresentationMode)video.webkitSetPresentationMode('inline');else if(document.pictureInPictureElement)document.exitPictureInPicture().catch(()=>{});}catch{post({type:'presentationFailed'});}break;- case 'videoSettings':video.muted=!message.audio;connect();break;+ case 'videoSettings':video.muted=!message.audio;retries=0;connect();break;case 'keyboard':showKeyboard(message.enabled===true);break;case 'resume':if(video.srcObject)video.play().catch(()=>{});break;case 'releaseInput':release();break;@@ -332,10 +322,11 @@ const VIEWER_SCRIPT = String.raw`}}if(!message.enabled){for(const button of heldMouse.keys())queue({kind:'button',button,down:false,x:cx,y:cy});heldMouse.clear();resetWheel();flush();}for(const [edge,value] of [['bottom',message.bottomInset],['right',message.rightInset]])if(Number.isFinite(value)&&value>=0&&value<=4096)mouseButtons.style[edge]=value+'px';showMouseButtons=message.enabled===true;for(const name of ['left','right','wheel'])if(typeof message.labels?.[name]==='string')document.getElementById('mouse-'+name).setAttribute('aria-label',message.labels[name]);updateMouseButtons();break;- case 'init':followRest=null;cursorNeedsEntry=true;stopPanAnimation();resetCursor();control=false;release();pending=[];sending=false;seq=0;epoch=message.epoch;dw=message.width;dh=message.height;fillHeight=message.fillHeight===true;video.muted=!message.audio;render();connect();break;+ case 'init':followRest=null;cursorNeedsEntry=true;stopPanAnimation();resetCursor();control=false;release();pending=[];sending=false;seq=0;epoch=message.epoch;dw=message.width;dh=message.height;fillHeight=message.fillHeight===true;video.muted=!message.audio;trickleIce=message.trickleIce===true;retries=0;render();connect();break;case 'viewport':fillHeight=message.fillHeight===true;release();render();break;- case 'answer':if(pc){const current=pc;pc.setRemoteDescription({type:'answer',sdp:message.sdp}).catch(()=>{if(pc===current){closeRtc();post({type:'fallback'});}});}break;- case 'fallback':closeRtc();break;+ case 'answer':if(message.epoch===epoch)void receiveAnswer(message);break;+ case 'ice':if(message.epoch===epoch)void receiveIce(message);break;+ case 'fallback':if(message.epoch===epoch&&message.attemptId===attemptId)failRtc('host',message.retry!==false);break;case 'frame':{if('cursor' in message)receiveCursor(message.cursor);else resetCursor();const frameEpoch=epoch;image.onload=()=>{if(epoch===frameEpoch)post({type:'framePresented'});};image.src='data:image/jpeg;base64,'+message.jpeg;break;}case 'control':release();control=message.enabled;if(!control)showKeyboard(false);pending=[];updateMouseButtons();render();break;case 'mode':release();if(message.mode!=='pointer')followRest=null;settlePan();clearTimeout(touchCursorTimer);touchCursorVisible=false;mode=message.mode;render();break;diff --git a/apps/mobile/src/remote-desktop/viewerRtc.ts b/apps/mobile/src/remote-desktop/viewerRtc.tsnew file mode 100644index 0000000000..eca56980cf--- /dev/null+++ b/apps/mobile/src/remote-desktop/viewerRtc.ts@@ -0,0 +1,113 @@+/** Static WebView code: stays independent of Hermes function serialization.+ * A media attempt owns its timers/candidates. The native screen retains the human lease.+ */+export const DESKTOP_RTC_SCRIPT = String.raw`+ let trickleIce=false,attemptId=null,retries=0,exchangeId=0;+ let retryTimer=null,deadlineTimer=null,disconnectTimer=null,stableTimer=null,iceTimer=null,gatherTimer=null,gatherDone=null;+ let localCandidates=[],localAck=0,remoteAfter=0,icePending=null,remoteSeen=new Set(),exchangeUntil=0,remoteComplete=false;+ function clearRtcTimers(){+ for(const timer of [retryTimer,deadlineTimer,disconnectTimer,stableTimer,iceTimer,gatherTimer])clearTimeout(timer);+ retryTimer=deadlineTimer=disconnectTimer=stableTimer=iceTimer=gatherTimer=null;+ if(gatherDone){gatherDone();gatherDone=null;}+ }+ function closeRtc(preserveFrame=true){+ if(preserveFrame)retainFrame();generation++;clearRtcTimers();+ localCandidates=[];localAck=remoteAfter=0;icePending=null;remoteSeen=new Set();attemptId=null;+ clearInterval(statsTimer);statsTimer=null;statsSample=null;+ if(dc)dc.close();if(pc)pc.close();pc=null;dc=null;+ video.onplaying=null;video.srcObject=null;video.style.display='none';image.style.display='block';+ if(!preserveFrame)image.removeAttribute('src');+ }+ function failRtc(reason,canRetry=true){+ const failedAttempt=attemptId;+ release();closeRtc();post({type:'fallback',attemptId:failedAttempt,reason});+ if(canRetry&&epoch&&retries<net.retryMs.length){+ const delay=net.retryMs[retries++];+ retryTimer=setTimeout(()=>{retryTimer=null;if(epoch)connect();},delay);+ }+ }+ function pollIce(){+ if(!pc||!trickleIce||!pc.remoteDescription||icePending||Date.now()>=exchangeUntil)return;+ const candidates=localCandidates.slice(localAck,localAck+net.batchSize);+ icePending={after:remoteAfter,sent:candidates.length,exchangeId:++exchangeId};+ post({type:'ice',attemptId,candidates,after:remoteAfter,exchangeId});+ iceTimer=setTimeout(()=>{icePending=null;pollIce();},4500);+ }+ async function receiveIce(message){+ if(!pc||!icePending||message.attemptId!==attemptId||message.exchangeId!==icePending.exchangeId)return;+ const rtc=pc,g=generation,batch=icePending;+ clearTimeout(iceTimer);+ try{+ if(message.error){icePending=null;iceTimer=setTimeout(pollIce,1000);return;}+ if(!Array.isArray(message.candidates)||message.candidates.length>net.batchSize||message.next!==batch.after+message.candidates.length||message.next>net.maxCandidates)throw new Error();+ for(const candidate of message.candidates){+ if(g!==generation)return;+ const key=JSON.stringify(candidate);+ if(remoteSeen.has(key))continue;+ if(remoteSeen.size>=net.maxCandidates)throw new Error();+ await rtc.addIceCandidate(candidate);+ if(g!==generation)return;+ remoteSeen.add(key);+ }+ if(g!==generation)return;+ localAck+=batch.sent;remoteAfter=message.next;remoteComplete=message.complete===true;icePending=null;+ if(!(remoteComplete&&rtc.iceGatheringState==='complete'&&localAck===localCandidates.length))+ iceTimer=setTimeout(pollIce,net.pollMs);+ }catch{if(g===generation)failRtc('candidates');}+ }+ async function receiveAnswer(message){+ if(!pc||message.attemptId!==attemptId)return;+ const rtc=pc,g=generation;+ try{+ await rtc.setRemoteDescription({type:'answer',sdp:message.sdp});+ if(g!==generation)return;+ clearTimeout(deadlineTimer);+ deadlineTimer=setTimeout(()=>{if(g===generation&&rtc.connectionState!=='connected')failRtc('connect-timeout');},net.connectMs);+ exchangeUntil=Date.now()+net.exchangeMs;pollIce();+ }catch{if(g===generation)failRtc('answer');}+ }+ async function connect(){+ closeRtc();const g=generation;attemptId=String(g);+ if(!window.RTCPeerConnection){failRtc('unsupported',false);return;}+ try{+ const rtc=new RTCPeerConnection({iceServers});pc=rtc;+ dc=rtc.createDataChannel('input-v1');rtc.addTransceiver('video',{direction:'recvonly'});rtc.addTransceiver('audio',{direction:'recvonly'});+ rtc.onicecandidate=({candidate})=>{+ if(g!==generation||!candidate?.candidate||!trickleIce)return;+ if(localCandidates.length>=net.maxCandidates){failRtc('candidate-limit',false);return;}+ localCandidates.push({candidate:candidate.candidate,sdpMid:candidate.sdpMid,sdpMLineIndex:candidate.sdpMLineIndex,+ ...(candidate.usernameFragment?{usernameFragment:candidate.usernameFragment}:{})});+ // Gathering continues after the offer; the serial exchange flushes late addresses.+ };+ dc.onmessage=e=>{try{if(g!==generation||pc!==rtc)return;if(typeof e.data!=='string'||e.data.length>80000)return;const message=JSON.parse(e.data);if(message.type==='cursor')receiveCursor(message.cursor);if((video.webkitPresentationMode==='picture-in-picture'||document.pictureInPictureElement===video)&&message.type==='viewPing'&&typeof message.challenge==='string'&&message.challenge.length<=64&&dc?.readyState==='open')dc.send(message.challenge);}catch{}};+ let readingStats=false;+ statsTimer=setInterval(async()=>{+ if(readingStats||g!==generation)return;readingStats=true;+ try{const stats=await rtc.getStats();if(g!==generation||pc!==rtc)return;const result=networkStats(stats,statsSample);statsSample=result.sample;post({type:'network',transport:result.transport,bytesPerSecond:result.bytesPerSecond,latencyMs:result.latencyMs});}catch{}finally{readingStats=false;}+ },1000);+ rtc.ontrack=e=>{if(g!==generation)return;video.srcObject=e.streams[0]||new MediaStream([e.track]);video.play().catch(()=>{});};+ video.onplaying=()=>{if(g!==generation)return;video.style.display='block';image.style.display='none';post({type:'streaming',attemptId});post({type:'pipCapability',supported:!!(video.webkitSupportsPresentationMode?.('picture-in-picture')||document.pictureInPictureEnabled)});render();};+ rtc.onconnectionstatechange=()=>{+ if(g!==generation)return;+ if(['failed','closed'].includes(rtc.connectionState)){failRtc('transport');return;}+ if(rtc.connectionState==='disconnected'){+ clearTimeout(stableTimer);stableTimer=null;+ if(!disconnectTimer){release();post({type:'reconnecting',attemptId});disconnectTimer=setTimeout(()=>{if(g===generation)failRtc('disconnected');},net.disconnectedMs);}+ }else if(rtc.connectionState==='connected'){+ clearTimeout(disconnectTimer);disconnectTimer=null;clearTimeout(deadlineTimer);+ if(!stableTimer)stableTimer=setTimeout(()=>{if(g===generation)retries=0;},net.stableMs);+ if(video.style.display==='block')post({type:'streaming',attemptId});+ }+ };+ await rtc.setLocalDescription(await rtc.createOffer());+ if(!trickleIce)await new Promise(resolve=>{+ if(rtc.iceGatheringState==='complete')return resolve();gatherDone=resolve;+ gatherTimer=setTimeout(resolve,net.legacyGatherMs);+ rtc.onicegatheringstatechange=()=>{if(rtc.iceGatheringState==='complete'){clearTimeout(gatherTimer);resolve();}};+ });+ if(g!==generation)return;+ post({type:'offer',attemptId,sdp:rtc.localDescription.sdp});+ deadlineTimer=setTimeout(()=>{if(g===generation)failRtc('answer-timeout');},net.answerMs);+ }catch{if(g===generation)failRtc('setup');}+ }+`;diff --git a/docs/remote-desktop.md b/docs/remote-desktop.mdindex 66c36d1d28..abd4ed7cf0 100644--- a/docs/remote-desktop.md+++ b/docs/remote-desktop.md@@ -56,8 +56,10 @@ the existing, trusted main renderer, with exact Main-side host identity checks.The phone runs a dedicated trusted inline WebView document; the untrusted HTMLpreview's restrictions are unchanged. The mobile presentation module requests scene rotation and a playback audio sessionfor system picture in picture. This requires a new native mobile build. Voice-recording and ordinary audio retain their foreground-only runtime policy. The current direct-connection ICE configuration uses a public STUN-server; there is no bundled TURN service.+recording and ordinary audio retain their foreground-only runtime policy. Direct+connections use independent Cloudflare and Google STUN endpoints; there is no+bundled TURN service. Neither public endpoint guarantees reachability in mainland+China or across every carrier.When WebRTC is unavailable or cannot connect, the phone uses an explicitlylabeled compatibility mode: JPEG at at most 1280 pixels per dimension, at most@@ -67,6 +69,72 @@ This mode trades frame rate and clarity for reachability. It is suitable forordinary desktop work, not game streaming. A production TURN service is thefollow-up needed for consistently smooth video across restrictive networks.+### Incremental ICE and media recovery++New desktops advertise optional `trickleIce`. When both endpoints support it,+the phone sends its offer without waiting for candidate gathering, and the+desktop answers after capture is ready. Candidates discovered later travel via+the existing authenticated `device-link:remote-desktop:v1` invoke channel's+`ice` operation. No new server message kind, listening port or credential store+is introduced. Older endpoints retain the full-SDP path, with a five-second+gathering deadline.++Three identifiers have different lifetimes:++- The peer-bound lease owns viewing/control. Media recovery never obtains a new+ lease, takes over another viewer or renews authorization on its own.+- `attemptId` owns one offer/answer and its peer connection. Replacing an attempt+ invalidates asynchronous capture, answers and candidate responses from its+ predecessor. The host rechecks the lease after asynchronous work.+- A viewer-local `exchangeId` owns one candidate request/reply. A late response+ cannot acknowledge candidates from a later request. The host's `after`/`next`+ cursor reads a retained candidate buffer, so retrying a lost reply is safe.++Candidate batches contain at most 16 entries, with at most 128 candidates per+attempt and 2,048 characters per candidate. Fields and cursors are validated on+both sides. Duplicate candidates are applied once. A timed-out exchange does+not tear down healthy video; polling is bounded to 30 seconds. SDP, candidate+addresses, credentials and desktop content are not added to logs.++| Phase | Bound |+| --- | --- |+| Desktop source enumeration | 2 seconds with native capture, 5 seconds otherwise |+| Desktop offer command | 18 seconds |+| Remote-desktop invoke | 30 seconds; other invoke channels are unchanged |+| Viewer waiting for answer | 25 seconds |+| ICE checks after answer | 15 seconds |+| Temporary media disconnect | 5-second grace period |+| Automatic media retries | 1, 3 and 8 seconds; restored after 30 seconds connected |++On a transient disconnect the viewer keeps the picture, releases held input and+shows the existing reconnecting badge. Input uses the existing authorized invoke+path while the data channel is disconnected. Recovery changes only this remote+desktop's media connection; shared device-link sessions and other peers are never+reset. Exhausted retries leave the existing JPEG compatibility transport+available. Explicit stop, lease replacement and leaving the page cancel timers+and invalidate late work. Permission/capture errors that require user action do+not repeatedly start media attempts.++For mainland-China deployment, restrictive NAT and UDP-blocked networks still+need authenticated regional TURN with short-lived credentials and UDP plus+TCP/TLS fallback, tested across carriers. This change does not provision that+infrastructure or add an unconfigured TURN option. Native ICE retains available+LAN, IPv6 and overlay-network candidates; being on Tailscale does not itself+prove that the media path is direct.++Deterministic tests exercise candidate replay, stale generations, bounded retry,+lease takeover isolation and old-version signaling. The loopback smoke harness+uses real Chromium WebRTC and synthetic video, delays candidate delivery, loses+an exchange response, verifies input and recovers after closing the host peer:++```sh+node --import tsx apps/mobile/scripts/remote-desktop-network-smoke.mjs [chromium-executable]+```++This harness does not validate WKWebView, Android WebView, carrier NAT, regional+STUN availability, TURN relay performance or Windows native capture. Those need+device/network verification before claiming a measured connection-success gain.+## Authority and lifetimeOn macOS, enabling remote desktop automatically checks screen recording in thediff --git a/packages/device-link/src/__tests__/remoteDesktopIce.test.ts b/packages/device-link/src/__tests__/remoteDesktopIce.test.tsnew file mode 100644index 0000000000..25504d0465--- /dev/null+++ b/packages/device-link/src/__tests__/remoteDesktopIce.test.ts@@ -0,0 +1,77 @@+import { expect, it } from "vitest";+import { parseRemoteDesktopRequest } from "../remoteDesktop";+import { parseDesktopIceReply } from "../remoteDesktopIce";+const candidate = {+ candidate: "candidate:1 1 UDP 100 192.0.2.1 5000 typ host",+ sdpMid: "0",+ sdpMLineIndex: 0,+};+const request = {+ op: "ice",+ lease: "lease",+ attemptId: "attempt",+ after: 0,+ candidates: [candidate],+};+it("projects candidate fields and retains both old and incremental offer shapes", () => {+ expect(+ parseRemoteDesktopRequest({+ ...request,+ candidates: [{ ...candidate, secret: "ignored" }],+ }),+ ).toEqual(request);+ expect(+ parseRemoteDesktopRequest({ op: "offer", lease: "lease", sdp: "sdp" }),+ ).toEqual({ op: "offer", lease: "lease", sdp: "sdp" });+ for (const settings of [undefined, { fps: 30, bitrate: 0, audio: false }])+ expect(+ parseRemoteDesktopRequest({+ op: "offer",+ lease: "lease",+ sdp: "sdp",+ attemptId: "new",+ settings,+ }),+ ).toMatchObject({ attemptId: "new" });+});+it.each([+ { attemptId: "" },+ { attemptId: "a".repeat(129) },+ { lease: "" },+ { after: -1 },+ { after: 129 },+ { after: 0.5 },+ { candidates: Array(17).fill(candidate) },+ { candidates: [{ ...candidate, candidate: "a".repeat(2049) }] },+ { candidates: [{ ...candidate, sdpMid: null, sdpMLineIndex: null }] },+ { candidates: [{ ...candidate, sdpMLineIndex: 32 }] },+ { candidates: [{ ...candidate, usernameFragment: 7 }] },+])("rejects unbounded or malformed signaling %j", (bad) => {+ expect(() => parseRemoteDesktopRequest({ ...request, ...bad })).toThrow();+});+it("validates host replies independently from requests", () => {+ expect(+ parseDesktopIceReply({+ attemptId: "attempt",+ next: 1,+ complete: false,+ candidates: [candidate],+ }),+ ).toMatchObject({ next: 1 });+ expect(() =>+ parseDesktopIceReply({+ attemptId: "attempt",+ next: 129,+ complete: false,+ candidates: [],+ }),+ ).toThrow();+ expect(() =>+ parseDesktopIceReply({+ attemptId: "attempt",+ next: 0,+ complete: 1,+ candidates: [],+ }),+ ).toThrow();+});diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 1ae324fcd8..f3ec1aa7cf 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -652,6 +652,9 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set([* client-agnostic:mobile/web 控制端应使用同一映射(与 allowlist 同为协议契约)。*/export const INVOKE_TIMEOUT_OVERRIDES_MS: Readonly<Record<string, number>> = {+ // Source enumeration (<=5s), capture/legacy ICE (<=18s), plus reply delivery.+ // Keep mobile's shorter 15s default from prematurely aborting negotiation.+ "device-link:remote-desktop:v1": 30_000,// 被控端 CMD_TIMEOUT_MS(30s)+ CMD_KILL_GRACE_MS(5s)+ 5s 回程余量'desktop-cmd:run': 40_000,// 被控端 worktree:create 含 git worktree add(--no-checkout)+ 白名单文件选择性diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.tsindex 05ff178312..6f2431e6e8 100644--- a/packages/device-link/src/index.ts+++ b/packages/device-link/src/index.ts@@ -16,5 +16,6 @@ export * from './attachmentOssRef.js';export * from './contactsSyncProtocol.js';export * from './remoteResources.js';export * from './remoteDesktop.js';+export * from './remoteDesktopIce.js';export * from './remoteClipboard.js';export * from './remoteCursor.js';diff --git a/packages/device-link/src/remoteDesktop.ts b/packages/device-link/src/remoteDesktop.tsindex c241eae0d2..b569ecfaec 100644--- a/packages/device-link/src/remoteDesktop.ts+++ b/packages/device-link/src/remoteDesktop.ts@@ -1,4 +1,13 @@-import { parseClipboardContentRequest, type ClipboardContentRequest } from "./remoteClipboard";+import {+ parseClipboardContentRequest,+ type ClipboardContentRequest,+} from "./remoteClipboard";+import {+ isDesktopAttemptId,+ isDesktopIceCursor,+ parseDesktopIceCandidates,+ type RemoteDesktopIceRequest,+} from "./remoteDesktopIce";/** Additive, same-account business channel. Never broadcast screen data or input. */export const REMOTE_DESKTOP_CHANNEL = "device-link:remote-desktop:v1";export const REMOTE_DESKTOP_LEASE_MS = 12_000;@@ -117,6 +126,7 @@ export interface RemoteDesktopCapabilities {/** Explicit same-account replacement of the active viewer. */connectionTakeover?: boolean;videoSettings?: boolean;+ trickleIce?: boolean;systemAudio?: boolean;displayModes?: boolean;backgroundViewing?: boolean;@@ -147,6 +157,7 @@ export interface RemoteDesktopLease {controlling: boolean;}export type RemoteDesktopRequest =+ | RemoteDesktopIceRequest| ClipboardContentRequest| { op: "capabilities" }| { op: "permissions"; action: "check" | "guide" }@@ -159,6 +170,7 @@ export type RemoteDesktopRequest =op: "offer";lease: string;sdp: string;+ attemptId?: string;cursorOverlay?: boolean;settings?: RemoteDesktopVideoSettings;}@@ -195,7 +207,19 @@ export function parseRemoteDesktopRequest(if (typeof v.lease !== "string" || v.lease.length > 128 || !v.lease)throw new Error("INVALID_LEASE");const lease = v.lease;- if (v.op === "clipboardContent") return parseClipboardContentRequest(v, lease);+ if (v.op === "ice") {+ if (!isDesktopAttemptId(v.attemptId) || !isDesktopIceCursor(v.after))+ throw new Error("INVALID_REQUEST");+ return {+ op: "ice",+ lease,+ attemptId: v.attemptId,+ after: v.after,+ candidates: parseDesktopIceCandidates(v.candidates),+ };+ }+ if (v.op === "clipboardContent")+ return parseClipboardContentRequest(v, lease);if (v.op === "clipboard") {if (v.action === "copy") return { op: v.op, lease, action: "copy" };if (v.action === "paste" && typeof v.text === "string" && v.text.length > 0 && v.text.length <= REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS)@@ -221,9 +245,16 @@ export function parseRemoteDesktopRequest()return { op: v.op, lease, modeId: v.modeId };if (v.op === "offer" && typeof v.sdp === "string" && v.sdp.length <= 64_000) {- if (v.cursorOverlay !== undefined && typeof v.cursorOverlay !== "boolean") throw new Error("INVALID_REQUEST");- const overlay = v.cursorOverlay === true ? { cursorOverlay: true } : {};- if (v.settings === undefined) return { op: v.op, lease, sdp: v.sdp, ...overlay };+ if (v.cursorOverlay !== undefined && typeof v.cursorOverlay !== "boolean")+ throw new Error("INVALID_REQUEST");+ if (v.attemptId !== undefined && !isDesktopAttemptId(v.attemptId))+ throw new Error("INVALID_REQUEST");+ const overlay = {+ ...(v.cursorOverlay === true ? { cursorOverlay: true } : {}),+ ...(v.attemptId === undefined ? {} : { attemptId: v.attemptId }),+ };+ if (v.settings === undefined)+ return { op: v.op, lease, sdp: v.sdp, ...overlay };const settings = v.settings as RemoteDesktopVideoSettings;if (!settings ||diff --git a/packages/device-link/src/remoteDesktopIce.ts b/packages/device-link/src/remoteDesktopIce.tsnew file mode 100644index 0000000000..248f304af0--- /dev/null+++ b/packages/device-link/src/remoteDesktopIce.ts@@ -0,0 +1,104 @@+/** Bounded, additive signaling inside the existing peer-authorized desktop channel. */+export interface RemoteDesktopIceCandidate {+ candidate: string;+ sdpMid: string | null;+ sdpMLineIndex: number | null;+ usernameFragment?: string;+}+export interface RemoteDesktopIceRequest {+ op: "ice";+ lease: string;+ attemptId: string;+ candidates: RemoteDesktopIceCandidate[];+ after: number;+}+export interface RemoteDesktopIceReply {+ attemptId: string;+ candidates: RemoteDesktopIceCandidate[];+ next: number;+ complete: boolean;+}+// Independent operators; neither endpoint is a guarantee of mainland reachability.+export const REMOTE_DESKTOP_ICE_SERVERS = [+ { urls: "stun:stun.cloudflare.com:3478" },+ { urls: "stun:stun.l.google.com:19302" },+];+export const REMOTE_DESKTOP_NETWORK = {+ maxCandidates: 128,+ batchSize: 16,+ pollMs: 250,+ exchangeMs: 30_000,+ disconnectedMs: 5_000,+ answerMs: 25_000,+ connectMs: 15_000,+ legacyGatherMs: 5_000,+ stableMs: 30_000,+ retryMs: [1_000, 3_000, 8_000],+};+export function isDesktopAttemptId(value: unknown): value is string {+ return typeof value === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(value);+}+export function parseDesktopIceCandidates(+ value: unknown,+): RemoteDesktopIceCandidate[] {+ if (!Array.isArray(value) || value.length > REMOTE_DESKTOP_NETWORK.batchSize)+ throw new Error("INVALID_DESKTOP_ICE");+ return value.map((v) => {+ if (+ !v ||+ typeof v !== "object" ||+ typeof v.candidate !== "string" ||+ !v.candidate.startsWith("candidate:") ||+ v.candidate.length > 2048 ||+ !(+ v.sdpMid === null ||+ (typeof v.sdpMid === "string" && v.sdpMid.length <= 128)+ ) ||+ !(+ v.sdpMLineIndex === null ||+ (Number.isInteger(v.sdpMLineIndex) &&+ v.sdpMLineIndex >= 0 &&+ v.sdpMLineIndex < 32)+ ) ||+ (v.sdpMid === null && v.sdpMLineIndex === null) ||+ !(+ v.usernameFragment === undefined ||+ (typeof v.usernameFragment === "string" &&+ v.usernameFragment.length <= 256)+ )+ )+ throw new Error("INVALID_DESKTOP_ICE");+ return {+ candidate: v.candidate,+ sdpMid: v.sdpMid,+ sdpMLineIndex: v.sdpMLineIndex,+ ...(v.usernameFragment === undefined+ ? {}+ : { usernameFragment: v.usernameFragment }),+ };+ });+}+export function isDesktopIceCursor(value: unknown): value is number {+ return (+ typeof value === "number" &&+ Number.isSafeInteger(value) &&+ value >= 0 &&+ value <= REMOTE_DESKTOP_NETWORK.maxCandidates+ );+}+export function parseDesktopIceReply(value: unknown): RemoteDesktopIceReply {+ const v = value as RemoteDesktopIceReply | null;+ if (+ !v ||+ !isDesktopAttemptId(v.attemptId) ||+ !isDesktopIceCursor(v.next) ||+ typeof v.complete !== "boolean"+ )+ throw new Error("INVALID_DESKTOP_ICE");+ return {+ attemptId: v.attemptId,+ next: v.next,+ complete: v.complete,+ candidates: parseDesktopIceCandidates(v.candidates),+ };+}