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。

fix(remote-desktop): 并行准备认证并修复视频切换闪白 (#4272)

Dashc93e9d10dc93
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
index 6711f56e22..d1dd95989f 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
@@ -29,6 +29,7 @@ import {
} from "expo-router";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { WebView, type WebViewMessageEvent } from "react-native-webview";
+import { connectionDiagnostics } from "./connectionDiagnostics";
import { transferClipboardContent } from "./clipboardTransfer";
import * as Clipboard from "expo-clipboard";
import { RemoteDesktopClipboardButton } from "./RemoteDesktopClipboardButton";
@@ -210,6 +211,7 @@ export default function RemoteDesktopScreen() {
resuming: false,
});
const generation = useRef(0);
+ const timing = useRef<ReturnType<typeof connectionDiagnostics> | null>(null);
const alive = useRef(true);
const connecting = useRef(false);
const ready = useRef(false);
@@ -223,6 +225,7 @@ export default function RemoteDesktopScreen() {
});
const [network, setNetwork] = useState<DesktopNetworkStats | null>(null);
const frameBusy = useRef<string | null>(null);
+ const unlockFrame = useRef<((presented: boolean) => void) | null>(null);
const inputBusy = useRef<string | null>(null);
const [lease, setLease] = useState<RemoteDesktopLease | null>(null);
exitLock.current =
@@ -387,7 +390,11 @@ export default function RemoteDesktopScreen() {
const stop = useCallback(
(preserveFrame = false, exiting = false) => {
+ timing.current?.("stopped");
+ timing.current = null;
generation.current++;
+ unlockFrame.current?.(false);
+ unlockFrame.current = null;
presentation.current = false;
if (presentationTimer.current) clearTimeout(presentationTimer.current);
presentationTimer.current = null;
@@ -509,29 +516,22 @@ export default function RemoteDesktopScreen() {
if (displayId) recovery.current.resuming = false; // Explicit display selection.
connecting.current = true;
const current = generation.current;
+ const mark = connectionDiagnostics(current);
+ timing.current = mark;
+ mark("connect");
setError(null);
setStatus(recovery.current.at ? "reconnecting" : "connecting");
try {
await linkRef.current.openLink(deviceId);
if (current !== generation.current) return;
- let result = await request<RemoteDesktopCapabilities>({
+ mark("link-ready");
+ const result = await request<RemoteDesktopCapabilities>({
op: "capabilities",
});
if (current !== generation.current) return;
+ mark("capabilities");
if (result?.version !== 1) throw new Error("CHANNEL_NOT_ALLOWED");
- // Publish host eligibility synchronously before native credential work;
- // React may not have rendered the capability response yet.
capsRef.current = { deviceId, value: result };
- if (result.enabled && supportsAutoUnlock(result.platform)) {
- await securityRef.current.maybeUnlock();
- if (current !== generation.current) return;
- result = await request<RemoteDesktopCapabilities>({
- op: "capabilities",
- });
- if (current !== generation.current) return;
- if (result?.version !== 1) throw new Error("CHANNEL_NOT_ALLOWED");
- capsRef.current = { deviceId, value: result };
- }
setHostCaps({ deviceId, value: result });
if (!result.enabled) throw new Error("DESKTOP_DISABLED");
if (recovery.current.resuming && !result.automaticReconnect)
@@ -541,6 +541,20 @@ export default function RemoteDesktopScreen() {
(d) => d.id === (displayId ?? recovery.current.displayId),
) ?? result.displays[0];
if (!display) throw new Error("DESKTOP_DISPLAY_MISSING");
+ if (supportsAutoUnlock(result.platform)) {
+ const firstFrame = new Promise<boolean>((resolve) => {
+ unlockFrame.current = resolve;
+ });
+ void securityRef.current.maybeUnlock(async () => {
+ if (
+ !(await firstFrame) ||
+ current !== generation.current ||
+ !focusedRef.current ||
+ !recovery.current.enabled
+ )
+ throw new Error("CREDENTIAL_CANCELLED");
+ });
+ }
recovery.current.displayId = display.id;
const resuming = recovery.current.resuming;
// The host may start successfully even when its reply is lost.
@@ -558,6 +572,7 @@ export default function RemoteDesktopScreen() {
void request({ op: "stop", lease: next.lease }).catch(() => {});
return;
}
+ mark("capture-started");
active.current = next;
receiveWindow.current = {
since: Date.now(),
@@ -607,6 +622,7 @@ export default function RemoteDesktopScreen() {
setLease({ ...next });
send({ type: "control", enabled: control.controlling });
}
+ mark("control-ready");
setControlReady(true);
} catch (cause) {
if (current === generation.current) fail(cause);
@@ -628,6 +644,19 @@ export default function RemoteDesktopScreen() {
);
const connectRef = useRef(connect);
connectRef.current = connect;
+ useEffect(() => {
+ // Authentication preparation is already running; only the native prompt
+ // waits for a frame from this lease. stop() releases cancelled waiters.
+ if (
+ frameReady &&
+ focused &&
+ lease &&
+ active.current?.lease === lease.lease
+ ) {
+ unlockFrame.current?.(true);
+ unlockFrame.current = null;
+ }
+ }, [frameReady, focused, lease?.lease]);
const pause = useCallback(
(exiting = false) => {
void stop(true, exiting);
@@ -1098,7 +1127,12 @@ export default function RemoteDesktopScreen() {
setOperations(true);
if (AppState.currentState === "background") pause();
break;
+ case "videoFrameReady":
+ if (mediaAttempt.current === message.attemptId)
+ timing.current?.("video-frame-ready");
+ break;
case "streaming":
+ timing.current?.("video-presented");
setFrameReady(true);
setSettingBusy(false);
recovery.current.delay = 1000;
@@ -1107,6 +1141,7 @@ export default function RemoteDesktopScreen() {
setStatus("live");
break;
case "framePresented":
+ timing.current?.("screenshot-presented");
setFrameReady(true);
break;
case "fallback":
@@ -1527,7 +1562,9 @@ export default function RemoteDesktopScreen() {
hideKeyboardAccessoryView
textInteractionEnabled={false}
allowsLinkPreview={false}
- {...(Platform.OS === "ios" ? { dataDetectorTypes: "none" as const } : {})}
+ {...(Platform.OS === "ios"
+ ? { dataDetectorTypes: "none" as const }
+ : {})}
javaScriptEnabled
allowsInlineMediaPlayback
mediaPlaybackRequiresUserAction={false}
diff --git a/apps/mobile/src/remote-desktop/__tests__/autoUnlockSettings.test.tsx b/apps/mobile/src/remote-desktop/__tests__/autoUnlockSettings.test.tsx
index a94fc0dbeb..209c1bd922 100644
--- a/apps/mobile/src/remote-desktop/__tests__/autoUnlockSettings.test.tsx
+++ b/apps/mobile/src/remote-desktop/__tests__/autoUnlockSettings.test.tsx
@@ -232,7 +232,8 @@ it("does not start authentication when the screen loses focus during host prepar
finish({ version: 1, ready: true, descriptor: "test-descriptor" });
await pending;
});
- expect(fixture.configure).not.toHaveBeenCalled();
+ // Identity preparation started in parallel, but cancellation still prevents the prompt.
+ expect(fixture.configure).toHaveBeenCalledOnce();
expect(fixture.ensure).not.toHaveBeenCalled();
});
it("uses the native password-only default when biometrics are unavailable", async () => {
@@ -367,3 +368,122 @@ it("preserves an explicit Face ID off choice when automatic unlock is enabled ag
expect(value.biometricVerification).toBe(false);
expect(fixture.biometric).not.toHaveBeenCalled();
});
+
+it("lets a reconnect prepare after a cancelled pre-frame attempt without repeating a shown prompt", async () => {
+ fixture.settings.autoUnlock = true;
+ fixture.invoke.mockResolvedValue({
+ version: 1,
+ state: "locked",
+ ready: true,
+ descriptor: "test-descriptor",
+ });
+ const prompt = vi.fn();
+ fixture.ensure.mockImplementation(async (...args: any[]) => {
+ await args[4].beforeAuthentication();
+ prompt();
+ });
+ let cancel!: (error: Error) => void;
+ const frame = new Promise<void>((_resolve, reject) => {
+ cancel = reject;
+ });
+ let first!: Promise<void>, retry!: Promise<void>;
+ await act(async () => {
+ first = value.maybeUnlock(() => frame);
+ });
+ expect(fixture.ensure).toHaveBeenCalledTimes(1);
+ expect(prompt).not.toHaveBeenCalled();
+ await act(async () => {
+ retry = value.maybeUnlock(async () => {});
+ });
+ expect(fixture.ensure).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ cancel(new Error("CREDENTIAL_CANCELLED"));
+ await Promise.all([first, retry]);
+ });
+ expect(fixture.ensure).toHaveBeenCalledTimes(2);
+ expect(prompt).toHaveBeenCalledTimes(1);
+ expect(fixture.close).toHaveBeenCalledTimes(2);
+ await act(async () => value.maybeUnlock(async () => {}));
+ expect(fixture.ensure).toHaveBeenCalledTimes(2);
+});
+
+it("cancels a prepared prompt if the page loses focus before the first frame", async () => {
+ fixture.settings.autoUnlock = true;
+ fixture.invoke.mockResolvedValue({
+ version: 1,
+ state: "locked",
+ ready: true,
+ descriptor: "test-descriptor",
+ });
+ const prompt = vi.fn();
+ fixture.ensure.mockImplementation(async (...args: any[]) => {
+ await args[4].beforeAuthentication();
+ prompt();
+ });
+ let showFrame!: () => void;
+ const frame = new Promise<void>((resolve) => {
+ showFrame = resolve;
+ });
+ let pending!: Promise<void>;
+ await act(async () => {
+ pending = value.maybeUnlock(() => frame);
+ });
+ await act(async () => root.render(createElement(Probe, { active: false })));
+ await act(async () => {
+ showFrame();
+ await pending;
+ });
+ expect(prompt).not.toHaveBeenCalled();
+ expect(fixture.close).toHaveBeenCalled();
+});
+
+it("prepares phone identity while the host is still preparing", async () => {
+ fixture.settings.autoUnlock = true;
+ fixture.invoke.mockResolvedValueOnce({ version: 1, state: "locked" });
+ let finish!: (value: unknown) => void;
+ fixture.invoke.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ let operation!: Promise<void>;
+ await act(async () => {
+ operation = value.maybeUnlock();
+ });
+ expect(fixture.configure).toHaveBeenCalledOnce();
+ expect(fixture.ensure).not.toHaveBeenCalled();
+ await act(async () => {
+ finish({ version: 1, ready: true, descriptor: "test-descriptor" });
+ await operation;
+ });
+ expect(fixture.ensure).toHaveBeenCalledOnce();
+});
+
+it("drains native preparation after host failure before releasing the attempt", async () => {
+ fixture.settings.autoUnlock = true;
+ fixture.invoke.mockResolvedValueOnce({ version: 1, state: "locked" });
+ let finish!: () => void;
+ fixture.configure.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ fixture.invoke.mockRejectedValueOnce(new Error("CREDENTIAL_UNAVAILABLE"));
+ let operation!: Promise<void>;
+ let settled = false;
+ await act(async () => {
+ operation = value.maybeUnlock().then(() => {
+ settled = true;
+ });
+ });
+ expect(settled).toBe(false);
+ expect(fixture.ensure).not.toHaveBeenCalled();
+ await act(async () => {
+ finish();
+ await operation;
+ });
+ expect(settled).toBe(true);
+ expect(fixture.ensure).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/remote-desktop/__tests__/connectionDiagnostics.test.ts b/apps/mobile/src/remote-desktop/__tests__/connectionDiagnostics.test.ts
new file mode 100644
index 0000000000..d8c5eec4b9
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/__tests__/connectionDiagnostics.test.ts
@@ -0,0 +1,20 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { setMobileDebugSink } from "@/debug/mobileDebugLog";
+import { connectionDiagnostics } from "../connectionDiagnostics";
+afterEach(() => setMobileDebugSink(undefined));
+it("records elapsed milestones once and ignores callbacks after stop", () => {
+ const sink = vi.fn();
+ setMobileDebugSink(sink);
+ let now = 100;
+ const mark = connectionDiagnostics(2, () => now);
+ mark("connect");
+ now = 150;
+ mark("screenshot-presented");
+ mark("screenshot-presented");
+ now = 190;
+ mark("stopped");
+ mark("video-presented");
+ expect(sink).toHaveBeenCalledTimes(3);
+ expect(JSON.stringify(sink.mock.calls)).toContain('"elapsedMs":50');
+ expect(JSON.stringify(sink.mock.calls)).not.toContain("video-presented");
+});
diff --git a/apps/mobile/src/remote-desktop/__tests__/credentialSession.test.ts b/apps/mobile/src/remote-desktop/__tests__/credentialSession.test.ts
index d355bbfaa6..855edde5cb 100644
--- a/apps/mobile/src/remote-desktop/__tests__/credentialSession.test.ts
+++ b/apps/mobile/src/remote-desktop/__tests__/credentialSession.test.ts
@@ -79,6 +79,54 @@ describe("native credential session coordination", () => {
"exchange",
]);
});
+ it.each(["frame", "cancel", "close", "owner"])(
+ "prepares the channel before the first-frame gate and handles %s",
+ async (outcome) => {
+ fixture.native.beginUnlock.mockResolvedValue({
+ handle: "local",
+ offer: "signed-offer",
+ });
+ const session = new RemoteDesktopCredentialSession();
+ let release!: () => void;
+ let cancel!: (error: Error) => void;
+ const frame = new Promise<void>((resolve, reject) => {
+ release = resolve;
+ cancel = reject;
+ });
+ const beforeAuthentication = vi.fn(() => frame);
+ const result = session
+ .ensure("computer", invoke, "en", "dark", {
+ setup: false,
+ biometric: true,
+ descriptor: "public-descriptor",
+ beforeAuthentication,
+ })
+ .then(
+ () => "authenticated",
+ (error: Error) => error.message,
+ );
+ await vi.waitFor(() =>
+ expect(beforeAuthentication).toHaveBeenCalledTimes(1),
+ );
+ expect(invoke.mock.calls.map((call) => call[2][0].kind)).toEqual([
+ "open",
+ "exchange",
+ ]);
+ expect(fixture.native.password).not.toHaveBeenCalled();
+ if (outcome === "close") session.close();
+ if (outcome === "owner")
+ fixture.owner = { ...fixture.owner, generation: 2 };
+ if (outcome === "cancel") cancel(new Error("CREDENTIAL_CANCELLED"));
+ else release();
+ expect(await result).toBe(
+ outcome === "frame" ? "authenticated" : "CREDENTIAL_CANCELLED",
+ );
+ expect(fixture.native.password).toHaveBeenCalledTimes(
+ outcome === "frame" ? 1 : 0,
+ );
+ session.close();
+ },
+ );
it("passes only public descriptors over the existing connection during local pairing", async () => {
fixture.native.beginUnlock.mockResolvedValue({
handle: "local",
diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
index 619c9f9891..a282b88a21 100644
--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
@@ -46,7 +46,7 @@ const fixture = vi.hoisted(() => ({
lockSupported: true,
alert: vi.fn(),
resetUnlockAttempt: vi.fn(),
- maybeUnlock: vi.fn(async () => {}),
+ maybeUnlock: vi.fn(async (_beforeAuthentication?: () => Promise<void>) => {}),
hostPlatform: "darwin" as string | undefined,
deviceId: "computer",
getHost: (() => undefined) as () => string | undefined,
@@ -310,6 +310,7 @@ beforeEach(() => {
fixture.deviceId = "computer";
fixture.securityAutoUnlock = false;
fixture.securityBusy = false;
+ fixture.maybeUnlock.mockReset().mockResolvedValue(undefined);
fixture.themeMode = "light";
fixture.lockOnExit = false;
fixture.lockSupported = true;
@@ -820,6 +821,99 @@ describe("remote desktop controls", () => {
{ op: "stop", lease: "lease", lockScreen: true },
]);
});
+ it.each(["framePresented", "streaming"])(
+ "prepares authentication alongside capture and waits for %s before Face ID",
+ async (firstFrame) => {
+ let finishUnlock!: () => void;
+ const prompt = vi.fn();
+ fixture.maybeUnlock.mockImplementationOnce(
+ async (beforeAuthentication) => {
+ await beforeAuthentication!();
+ prompt();
+ await new Promise<void>((resolve) => {
+ finishUnlock = resolve;
+ });
+ },
+ );
+ await act(async () => {
+ fixture.message!({ nativeEvent: { data: '{"type":"ready"}' } });
+ });
+ expect(requests().filter((r) => r.op === "capabilities")).toHaveLength(1);
+ expect(requests().some((r) => r.op === "start")).toBe(true);
+ expect(sent().some((m) => m.type === "init")).toBe(true);
+ expect(fixture.maybeUnlock).toHaveBeenCalledTimes(1);
+ expect(prompt).not.toHaveBeenCalled();
+
+ await act(async () => {
+ fixture.message!({
+ nativeEvent: {
+ data: JSON.stringify({
+ type: firstFrame,
+ epoch: "lease",
+ }),
+ },
+ });
+ });
+ expect(fixture.maybeUnlock).toHaveBeenCalledTimes(1);
+ expect(prompt).toHaveBeenCalledTimes(1);
+ expect(
+ host.querySelector('[data-testid="remoteDesktop.connectingStatus"]'),
+ ).toBeNull();
+ const stops = requests().filter((r) => r.op === "stop").length;
+ await act(async () => {
+ AppState.currentState = "inactive";
+ fixture.appState!("inactive");
+ fixture.message!({
+ nativeEvent: { data: '{"type":"streaming","epoch":"lease"}' },
+ });
+ fixture.message!({
+ nativeEvent: { data: '{"type":"framePresented","epoch":"lease"}' },
+ });
+ await vi.advanceTimersByTimeAsync(3000);
+ });
+ expect(requests().some((r) => r.op === "heartbeat")).toBe(true);
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(stops);
+ expect(fixture.maybeUnlock).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ finishUnlock();
+ AppState.currentState = "active";
+ fixture.appState!("active");
+ });
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(stops);
+ },
+ );
+ it("does not unlock for a stale frame or a frame arriving after leaving", async () => {
+ const prompt = vi.fn();
+ let outcome!: Promise<string>;
+ fixture.maybeUnlock.mockImplementationOnce(async (beforeAuthentication) => {
+ outcome = beforeAuthentication!().then(
+ () => {
+ prompt();
+ return "shown";
+ },
+ (error: Error) => error.message,
+ );
+ await outcome;
+ });
+ await act(async () => {
+ fixture.message!({ nativeEvent: { data: '{"type":"ready"}' } });
+ fixture.message!({
+ nativeEvent: { data: '{"type":"framePresented","epoch":"old-lease"}' },
+ });
+ });
+ expect(fixture.maybeUnlock).toHaveBeenCalledTimes(1);
+ expect(prompt).not.toHaveBeenCalled();
+ fixture.focused = false;
+ await act(async () => root.render(<RemoteDesktopScreen />));
+ await act(async () => {
+ fixture.message!({
+ nativeEvent: { data: '{"type":"framePresented","epoch":"lease"}' },
+ });
+ });
+ expect(await outcome).toBe("CREDENTIAL_CANCELLED");
+ expect(prompt).not.toHaveBeenCalled();
+ });
it("places optional unlock under Operation Security without gating the desktop", async () => {
await connect();
expect(requests().some((request) => request.op === "start")).toBe(true);
diff --git a/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts b/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts
index 51a678d7aa..70514eec0f 100644
--- a/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts
+++ b/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts
@@ -4,7 +4,7 @@ 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, autoConfig = true) {
+function viewer(trickle = true, autoConfig = true, frameCallback = true) {
let api: any;
const messages: any[] = [];
const peers: any[] = [];
@@ -40,10 +40,24 @@ function viewer(trickle = true, autoConfig = true) {
return new Map();
}
}
+ let callbackId = 0;
+ const videoFrames = new Map<number, () => void>();
+ const paints = new Map<number, () => void>();
const video = {
- style: { display: "none" },
+ style: { display: "none", zIndex: "0" },
srcObject: null,
- onplaying: null,
+ onplaying: null as null | (() => void),
+ readyState: 2,
+ videoWidth: 1920,
+ videoHeight: 1080,
+ requestVideoFrameCallback: frameCallback
+ ? (callback: () => void) => {
+ const id = ++callbackId;
+ videoFrames.set(id, callback);
+ return id;
+ }
+ : undefined,
+ cancelVideoFrameCallback: (id: number) => videoFrames.delete(id),
play: async () => {},
};
const image = { style: { display: "block" }, removeAttribute() {} };
@@ -64,6 +78,12 @@ function viewer(trickle = true, autoConfig = true) {
clearTimeout,
setInterval,
clearInterval,
+ requestAnimationFrame: (callback: () => void) => {
+ const id = ++callbackId;
+ paints.set(id, callback);
+ return id;
+ },
+ cancelAnimationFrame: (id: number) => paints.delete(id),
retainFrame: retained,
release,
render() {},
@@ -93,6 +113,19 @@ function viewer(trickle = true, autoConfig = true) {
messages,
latest,
video,
+ image,
+ videoFrames,
+ paints,
+ frame: () => {
+ const batch = [...videoFrames.values()];
+ videoFrames.clear();
+ batch.forEach((cb) => cb());
+ },
+ paint: () => {
+ const batch = [...paints.values()];
+ paints.clear();
+ batch.forEach((cb) => cb());
+ },
retained,
release,
answer: async () => api.answer({ ...latest("offer"), sdp: "answer" }),
@@ -137,7 +170,10 @@ it("retains video on transient disconnection and cancels the grace timeout after
const h = viewer();
await h.api.start();
await h.answer();
- h.video.style.display = "block";
+ h.video.onplaying!();
+ h.frame();
+ h.paint();
+ h.paint();
h.change("connected");
h.change("disconnected");
expect(h.latest("reconnecting")).toBeDefined();
@@ -324,3 +360,72 @@ it("never starts media after exit while credentials are pending", async () => {
expect(h.peers).toHaveLength(0);
expect(vi.getTimerCount()).toBe(0);
});
+
+it("keeps the screenshot backing when promoting the first video frame", async () => {
+ const h = viewer();
+ await h.api.start();
+ h.video.onplaying!();
+ h.video.onplaying!();
+ h.change("connected");
+ expect(h.video.style.display).toBe("block");
+ expect(h.video.style.zIndex).toBe("0");
+ expect(h.image.style.display).toBe("block");
+ expect(h.videoFrames.size).toBe(1);
+ expect(h.latest("streaming")).toBeUndefined();
+ h.frame();
+ h.paint();
+ expect(h.image.style.display).toBe("block");
+ expect(h.latest("pipCapability")).toBeUndefined();
+ h.paint();
+ expect(h.image.style.display).toBe("block");
+ expect(h.video.style.zIndex).toBe("2");
+ expect(h.messages.filter((m) => m.type === "streaming")).toHaveLength(1);
+ h.video.onplaying!();
+ expect(h.videoFrames.size).toBe(0);
+ h.api.stop();
+ expect(h.video.style.zIndex).toBe("0");
+ expect(h.image.style.display).toBe("block");
+});
+
+it.each(["frame", "paint"])(
+ "cancels a pending %s callback and ignores it after a new attempt",
+ async (phase) => {
+ const h = viewer();
+ await h.api.start();
+ h.video.onplaying!();
+ if (phase === "paint") h.frame();
+ const stale = [
+ ...(phase === "frame" ? h.videoFrames : h.paints).values(),
+ ][0];
+ await h.api.start();
+ expect(h.videoFrames.size).toBe(0);
+ expect(h.paints.size).toBe(0);
+ stale();
+ expect(h.paints.size).toBe(0);
+ expect(h.image.style.display).toBe("block");
+ expect(h.latest("streaming")).toBeUndefined();
+ h.api.stop();
+ },
+);
+
+it("waits for decoded dimensions before painting when video frame callbacks are unavailable", async () => {
+ const h = viewer(true, true, false);
+ await h.api.start();
+ h.video.readyState = 1;
+ h.video.videoWidth = 0;
+ h.video.onplaying!();
+ h.paint();
+ h.paint();
+ expect(h.image.style.display).toBe("block");
+ h.video.readyState = 2;
+ h.video.videoWidth = 1920;
+ h.paint();
+ h.paint();
+ expect(h.latest("streaming")).toBeUndefined();
+ h.paint();
+ expect(h.image.style.display).toBe("block");
+ expect(h.video.style.zIndex).toBe("2");
+ expect(h.latest("streaming")).toBeDefined();
+ h.api.stop();
+ expect(h.paints.size).toBe(0);
+});
diff --git a/apps/mobile/src/remote-desktop/connectionDiagnostics.ts b/apps/mobile/src/remote-desktop/connectionDiagnostics.ts
new file mode 100644
index 0000000000..73016fad03
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/connectionDiagnostics.ts
@@ -0,0 +1,31 @@
+import { mobileDebugLog } from "@/debug/mobileDebugLog";
+
+type Stage =
+ | "connect"
+ | "link-ready"
+ | "capabilities"
+ | "capture-started"
+ | "control-ready"
+ | "screenshot-presented"
+ | "video-frame-ready"
+ | "video-presented"
+ | "stopped";
+/** One sample per milestone, with no host IDs or media/credential content. */
+export function connectionDiagnostics(
+ attempt: number,
+ now = () => performance.now(),
+) {
+ const started = now();
+ const seen = new Set<Stage>();
+ let stopped = false;
+ return (stage: Stage) => {
+ if (stopped || seen.has(stage)) return;
+ seen.add(stage);
+ if (stage === "stopped") stopped = true;
+ mobileDebugLog("info", "device-link", "remote-desktop-timing", {
+ attempt,
+ stage,
+ elapsedMs: Math.max(0, Math.round(now() - started)),
+ });
+ };
+}
diff --git a/apps/mobile/src/remote-desktop/credentialDiagnostics.ts b/apps/mobile/src/remote-desktop/credentialDiagnostics.ts
index 3fde1a39f6..9bd80d6a1c 100644
--- a/apps/mobile/src/remote-desktop/credentialDiagnostics.ts
+++ b/apps/mobile/src/remote-desktop/credentialDiagnostics.ts
@@ -1,6 +1,7 @@
import { mobileDebugLog } from "@/debug/mobileDebugLog";
type Stage =
+ | "wait-for-first-frame"
| "enable-face-id"
| "change-face-id"
| "scope"
diff --git a/apps/mobile/src/remote-desktop/credentialSession.ts b/apps/mobile/src/remote-desktop/credentialSession.ts
index 2567ebb29e..58995c6046 100644
--- a/apps/mobile/src/remote-desktop/credentialSession.ts
+++ b/apps/mobile/src/remote-desktop/credentialSession.ts
@@ -117,7 +117,12 @@ export class RemoteDesktopCredentialSession {
invoke: Invoke,
locale: string,
theme: "light" | "dark",
- unlock?: { setup: boolean; biometric: boolean; descriptor: string },
+ unlock?: {
+ setup: boolean;
+ biometric: boolean;
+ descriptor: string;
+ beforeAuthentication?: () => Promise<void>;
+ },
): Promise<void> {
const native = remoteCredentials;
if (!native) throw new Error("CREDENTIAL_NATIVE_UPGRADE_REQUIRED");
@@ -196,6 +201,11 @@ export class RemoteDesktopCredentialSession {
throw error;
}
}
+ // Prepare the secure channel while capture starts, but do not request
+ // password/Face ID until the caller has shown this connection's first frame.
+ if (unlock?.beforeAuthentication)
+ await credentialStep("wait-for-first-frame", unlock.beforeAuthentication);
+ check();
const state = this.state!;
const ciphertext = await credentialStep("password-or-face-id", () =>
state.pending
diff --git a/apps/mobile/src/remote-desktop/useAutoUnlockSettings.ts b/apps/mobile/src/remote-desktop/useAutoUnlockSettings.ts
index 073b5e53ec..950052fad8 100644
--- a/apps/mobile/src/remote-desktop/useAutoUnlockSettings.ts
+++ b/apps/mobile/src/remote-desktop/useAutoUnlockSettings.ts
@@ -53,6 +53,7 @@ export function useAutoUnlockSettings(
pending = useRef(false),
attempted = useRef(false);
const epoch = useRef(0);
+ const changeSettled = useRef<Promise<void>>(Promise.resolve());
const transaction = useRef<RemoteDesktopCredentialSession | null>(null);
const owner = getMobileAuthOwner();
useEffect(() => {
@@ -112,6 +113,7 @@ export function useAutoUnlockSettings(
setup: boolean,
biometric: boolean,
requestBiometric = false,
+ beforeAuthentication?: () => Promise<void>,
) {
const current = await credentialStep("scope", scope),
token = await credentialStep("access-token", () => auth.getAccessToken());
@@ -123,25 +125,31 @@ export function useAutoUnlockSettings(
};
await credentialStep("open-link", () => link.openLink(target));
current.check();
- const ready = await credentialStep("host-prepare", () =>
- invoke<{ version: number; ready: boolean; descriptor: string }>(
- target,
- REMOTE_DESKTOP_CHANNEL,
- [{ op: "credential", version: 1, kind: "prepare", setup }],
- { preSend: current.check },
+ // Both preparations must settle before allowing another authentication attempt.
+ // In particular, a host failure must not leave native configure running behind it.
+ const [hostPreparation, phonePreparation] = await Promise.allSettled([
+ credentialStep("host-prepare", () =>
+ invoke<{ version: number; ready: boolean; descriptor: string }>(
+ target,
+ REMOTE_DESKTOP_CHANNEL,
+ [{ op: "credential", version: 1, kind: "prepare", setup }],
+ { preSend: current.check },
+ ),
),
- );
+ credentialStep("phone-configure", () =>
+ configureCredentialIdentity(token),
+ ),
+ ]);
current.check();
+ if (hostPreparation.status === "rejected") throw hostPreparation.reason;
+ if (phonePreparation.status === "rejected") throw phonePreparation.reason;
+ const ready = hostPreparation.value;
if (
ready?.version !== 1 ||
!ready.ready ||
typeof ready.descriptor !== "string"
)
throw new Error("CREDENTIAL_UNAVAILABLE");
- await credentialStep("phone-configure", () =>
- configureCredentialIdentity(token),
- );
- current.check();
const session = new RemoteDesktopCredentialSession();
transaction.current = session;
try {
@@ -149,6 +157,14 @@ export function useAutoUnlockSettings(
setup,
biometric,
descriptor: ready.descriptor,
+ ...(beforeAuthentication
+ ? {
+ beforeAuthentication: async () => {
+ await beforeAuthentication();
+ current.check();
+ },
+ }
+ : {}),
});
current.check();
if (setup) {
@@ -181,6 +197,10 @@ export function useAutoUnlockSettings(
const generation = epoch.current;
const actionOwner = getMobileAuthOwner();
pending.current = true;
+ let settle!: () => void;
+ changeSettled.current = new Promise<void>((resolve) => {
+ settle = resolve;
+ });
setBusy(true);
setNotice(null);
try {
@@ -209,6 +229,7 @@ export function useAutoUnlockSettings(
pending.current = false;
if (mounted.current) setBusy(false);
}
+ settle();
}
}
return {
@@ -247,8 +268,13 @@ export function useAutoUnlockSettings(
resetConnectionAttempt: () => {
attempted.current = false;
},
- maybeUnlock: async () => {
+ maybeUnlock: async (beforeAuthentication?: () => Promise<void>) => {
+ const requestEpoch = epoch.current;
+ // A reconnect may arrive while its cancelled preparation is unwinding.
+ // Wait for cleanup instead of skipping that connection or overlapping native sessions.
+ if (pending.current) await changeSettled.current;
if (
+ requestEpoch !== epoch.current ||
!available ||
!supportsAutoUnlock(getHostPlatform()) ||
attempted.current ||
@@ -267,8 +293,23 @@ export function useAutoUnlockSettings(
);
current.check();
if (status?.version !== 1 || status.state !== "locked") return;
- attempted.current = true;
- await change(() => authenticate(false, saved.biometricVerification));
+ if (!beforeAuthentication) attempted.current = true;
+ await change(() =>
+ authenticate(
+ false,
+ saved.biometricVerification,
+ false,
+ beforeAuthentication
+ ? async () => {
+ await beforeAuthentication();
+ current.check();
+ // Preparation cancelled before the first frame must not consume
+ // the one automatic prompt allowed for this connection attempt.
+ attempted.current = true;
+ }
+ : undefined,
+ ),
+ );
} catch {
if (mounted.current)
setNotice(t("remoteDesktop.autoUnlockUnavailable"));
diff --git a/apps/mobile/src/remote-desktop/viewerHtml.ts b/apps/mobile/src/remote-desktop/viewerHtml.ts
index ed69e89932..23baf5fe24 100644
--- a/apps/mobile/src/remote-desktop/viewerHtml.ts
+++ b/apps/mobile/src/remote-desktop/viewerHtml.ts
@@ -15,10 +15,10 @@ export function remoteDesktopViewerHtml(
const color = (v: string) =>
/^#[0-9a-f]{3,8}$/i.test(v) ? v : "transparent";
return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; media-src blob:; connect-src 'none'"><style>
- *{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:${color(surface)};touch-action:none;overscroll-behavior:none}#stage{position:absolute;inset:0;overflow:hidden;z-index:0}video,img{position:absolute;max-width:none;pointer-events:none;transform-origin:0 0}video{display:none}#cursor{position:absolute;z-index:2;width:18px;height:18px;border:2px solid ${color(foreground)};border-radius:50%;pointer-events:none;display:none;transform:translate(-50%,-50%)}
+ *{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:${color(surface)};touch-action:none;overscroll-behavior:none}#stage{position:absolute;inset:0;overflow:hidden;z-index:0}video,img{position:absolute;max-width:none;pointer-events:none;transform-origin:0 0}video{display:none;z-index:0}#cursor{position:absolute;z-index:3;width:18px;height:18px;border:2px solid ${color(foreground)};border-radius:50%;pointer-events:none;display:none;transform:translate(-50%,-50%)}
#cursor-image{position:absolute;inset:0;width:100%;height:100%}
#stage,#stage *{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-user-drag:none}
- video,img{border:0;outline:0}img:not([src]){visibility:hidden}
+ video,img{border:0;outline:0}#image{z-index:1}img:not([src]){visibility:hidden}
:root{--surface:${color(surface)};--foreground:${color(foreground)}}
#keyboard-input{position:absolute;left:0;bottom:0;width:1px;height:1px;opacity:.01;font-size:16px;pointer-events:none;border:0;padding:0;resize:none}
#mouse-buttons{position:absolute;inset:0;pointer-events:none;display:none;color:var(--foreground);opacity:.85}
@@ -286,7 +286,7 @@ const VIEWER_SCRIPT = String.raw`
// Keep one bounded frame in this document only; never persist desktop pixels.
// Snapshot before detaching the track. A JPEG fallback already lives in image.
function retainFrame(){
- if(video.style.display!=='block'||video.readyState<2||!video.videoWidth||!video.videoHeight)return;
+ if(!videoPresented||video.style.display!=='block'||video.readyState<2||!video.videoWidth||!video.videoHeight)return;
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;}
}
@@ -311,7 +311,7 @@ const VIEWER_SCRIPT = String.raw`
case 'keyboard':showKeyboard(message.enabled===true);break;
case 'resume':if(video.srcObject)video.play().catch(()=>{});break;
case 'releaseInput':release();break;
- case 'theme':if(/^#[0-9a-f]{3,8}$/i.test(message.surface)){document.body.style.background=message.surface;document.documentElement.style.setProperty('--surface',message.surface);}if(/^#[0-9a-f]{3,8}$/i.test(message.foreground)){cursor.style.borderColor=message.foreground;document.documentElement.style.setProperty('--foreground',message.foreground);}break;
+ case 'theme':if(/^#[0-9a-f]{3,8}$/i.test(message.surface)){document.body.style.background=message.surface;document.documentElement.style.background=message.surface;document.documentElement.style.setProperty('--surface',message.surface);}if(/^#[0-9a-f]{3,8}$/i.test(message.foreground)){cursor.style.borderColor=message.foreground;document.documentElement.style.setProperty('--foreground',message.foreground);}break;
case 'mouseButtons':if(Number.isFinite(message.bottomInset))viewportBottomInset=Math.max(0,Math.min(stage.clientHeight-1,message.bottomInset));if(Number.isFinite(message.leftInset)){const left=Math.max(0,Math.min(stage.clientWidth-1,message.leftInset));if(left!==viewportLeftInset){viewportLeftInset=left;settlePan();render();}}if(Number.isFinite(message.rightInset)){const inset=Math.max(0,Math.min(stage.clientWidth-1,message.rightInset));if(inset!==viewportRightInset){viewportRightInset=inset;settlePan();render();}}const keyboardInset=fillHeight&&message.keyboardOpen===true?viewportBottomInset:0;
if(keyboardInset!==keyboardViewportInset){
const wasOpen=keyboardViewportInset>0;keyboardViewportInset=keyboardInset;
diff --git a/apps/mobile/src/remote-desktop/viewerRtc.ts b/apps/mobile/src/remote-desktop/viewerRtc.ts
index 98dd2aac37..3b3c828e2a 100644
--- a/apps/mobile/src/remote-desktop/viewerRtc.ts
+++ b/apps/mobile/src/remote-desktop/viewerRtc.ts
@@ -4,6 +4,31 @@
export const DESKTOP_RTC_SCRIPT = String.raw`
let trickleIce=false,attemptId=null,retries=0,exchangeId=0;
let configPending=false;
+ let videoPresented=false,videoFrameCallback=null,videoPaintCallback=null;
+ function cancelVideoHandoff(){
+ if(videoFrameCallback!==null)video.cancelVideoFrameCallback?.(videoFrameCallback);
+ if(videoPaintCallback!==null)cancelAnimationFrame(videoPaintCallback);
+ videoFrameCallback=videoPaintCallback=null;
+ }
+ function revealVideo(g){
+ post({type:'videoFrameReady',attemptId});
+ // Keep the JPEG decoded and painted as a backing layer. Promote the video
+ // only after its first frame; removing the image exposes WebKit repaint gaps.
+ videoPaintCallback=requestAnimationFrame(()=>{
+ if(g!==generation)return;
+ videoPaintCallback=requestAnimationFrame(()=>{
+ if(g!==generation)return;
+ videoPaintCallback=null;videoPresented=true;video.style.zIndex='2';
+ post({type:'streaming',attemptId});
+ post({type:'pipCapability',supported:!!(video.webkitSupportsPresentationMode?.('picture-in-picture')||document.pictureInPictureEnabled)});
+ });
+ });
+ }
+ function waitForVideoFrame(g){
+ if(g!==generation)return;
+ if(video.readyState>=2&&video.videoWidth>0&&video.videoHeight>0){revealVideo(g);return;}
+ videoPaintCallback=requestAnimationFrame(()=>waitForVideoFrame(g));
+ }
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(){
@@ -14,10 +39,11 @@ export const DESKTOP_RTC_SCRIPT = String.raw`
function closeRtc(preserveFrame=true){
configPending=false;
if(preserveFrame)retainFrame();generation++;clearRtcTimers();
+ cancelVideoHandoff();videoPresented=false;
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';
+ video.onplaying=null;video.srcObject=null;video.style.display='none';video.style.zIndex='0';image.style.display='block';
if(!preserveFrame)image.removeAttribute('src');
}
function failRtc(reason,canRetry=true){
@@ -98,7 +124,16 @@ export const DESKTOP_RTC_SCRIPT = String.raw`
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();};
+ video.onplaying=()=>{
+ if(g!==generation||videoPresented||videoFrameCallback!==null||videoPaintCallback!==null)return;
+ video.style.display='block';render();
+ if(typeof video.requestVideoFrameCallback==='function'){
+ videoFrameCallback=video.requestVideoFrameCallback(()=>{
+ if(g!==generation)return;
+ videoFrameCallback=null;revealVideo(g);
+ });
+ }else waitForVideoFrame(g);
+ };
rtc.onconnectionstatechange=()=>{
if(g!==generation)return;
if(['failed','closed'].includes(rtc.connectionState)){failRtc('transport');return;}
@@ -108,7 +143,7 @@ export const DESKTOP_RTC_SCRIPT = String.raw`
}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});
+ if(videoPresented)post({type:'streaming',attemptId});
}
};
await rtc.setLocalDescription(await rtc.createOffer());