Skip to content
TypeScript

perf(desktop): skip duplicate browser updates (#8018)

Bilal Bakr72c44a847c0a
diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts
index 9c06d244830..adc72672977 100644
--- a/apps/desktop/src/preview/Manager.test.ts
+++ b/apps/desktop/src/preview/Manager.test.ts
@@ -332,8 +332,18 @@ const settle = function* (until: () => boolean) {
const makeTestPictureInPictureWindow = (loadURL: () => Promise<void> = async () => undefined) => {
const listeners = new Map<string, () => void>();
+ const webContentsListeners = new Map<string, () => void>();
const send = vi.fn();
let destroyed = false;
+ const webContents = {
+ on: vi.fn((event: string, listener: () => void) => {
+ webContentsListeners.set(event, listener);
+ }),
+ off: vi.fn((event: string) => {
+ webContentsListeners.delete(event);
+ }),
+ send,
+ };
const pictureInPictureWindow = {
isDestroyed: vi.fn(() => destroyed),
once: vi.fn((event: string, listener: () => void) => {
@@ -353,11 +363,12 @@ const makeTestPictureInPictureWindow = (loadURL: () => Promise<void> = async ()
destroyed = true;
listeners.get("closed")?.();
}),
- webContents: {
- send,
+ get webContents() {
+ if (destroyed) throw new Error("Picture-in-picture window is closed.");
+ return webContents;
},
};
- return { pictureInPictureWindow, send };
+ return { pictureInPictureWindow, send, webContentsListeners };
};
describe("PreviewManager", () => {
@@ -2413,6 +2424,8 @@ describe("PreviewManager", () => {
pictureInPictureListeners.get("closed")?.();
}),
webContents: {
+ on: vi.fn(),
+ off: vi.fn(),
send: pictureInPictureSend,
},
};
@@ -2478,6 +2491,7 @@ describe("PreviewManager", () => {
);
expect(states.at(-1)?.pictureInPicture).toBe(true);
expect(capturePage).toHaveBeenCalledOnce();
+ const pictureInPictureFramesBeforeRecording = pictureInPictureSend.mock.calls.length;
yield* manager.startRecording("tab_pip");
expect(capturePage).toHaveBeenCalledOnce();
@@ -2485,6 +2499,7 @@ describe("PreviewManager", () => {
yield* TestClock.adjust(100);
expect(capturePage).toHaveBeenCalledTimes(2);
+ expect(pictureInPictureSend).toHaveBeenCalledTimes(pictureInPictureFramesBeforeRecording);
expect(recordingFrames).toHaveLength(1);
yield* manager.stopRecording("tab_pip");
@@ -2492,9 +2507,7 @@ describe("PreviewManager", () => {
const framesBeforePictureInPictureOnlyTick = pictureInPictureSend.mock.calls.length;
yield* TestClock.adjust(100);
expect(capturePage).toHaveBeenCalledTimes(3);
- expect(pictureInPictureSend.mock.calls.length).toBeGreaterThan(
- framesBeforePictureInPictureOnlyTick,
- );
+ expect(pictureInPictureSend.mock.calls.length).toBe(framesBeforePictureInPictureOnlyTick);
expect(recordingFrames).toHaveLength(1);
setBackgroundThrottling.mockImplementationOnce(() => {
@@ -2511,6 +2524,213 @@ describe("PreviewManager", () => {
),
);
+ effectIt.effect("starts picture-in-picture without an extra recording capture", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const jpeg = Buffer.from("shared-preview-frame");
+ const capturePage = vi.fn(async () => ({
+ toJPEG: () => jpeg,
+ getSize: () => ({ width: 1280, height: 720 }),
+ }));
+ fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
+ const { pictureInPictureWindow, send } = makeTestPictureInPictureWindow();
+ browserWindowConstructor.mockImplementation(function () {
+ return pictureInPictureWindow;
+ });
+ const recordingFrames: DesktopPreviewRecordingFrame[] = [];
+
+ yield* manager.subscribeRecordingFrames((frame) =>
+ Effect.sync(() => {
+ recordingFrames.push(frame);
+ }),
+ );
+ yield* manager.createTab("tab_recording_then_pip");
+ yield* manager.registerWebview("tab_recording_then_pip", 42);
+ yield* manager.startRecording("tab_recording_then_pip");
+
+ expect(recordingFrames).toHaveLength(1);
+ yield* manager.openPictureInPicture("tab_recording_then_pip");
+ expect(capturePage).toHaveBeenCalledOnce();
+ expect(send).not.toHaveBeenCalled();
+
+ yield* TestClock.adjust(100);
+
+ expect(capturePage).toHaveBeenCalledTimes(2);
+ expect(recordingFrames).toHaveLength(2);
+ expect(send).toHaveBeenCalledOnce();
+ yield* manager.closePictureInPicture("tab_recording_then_pip");
+ yield* manager.stopRecording("tab_recording_then_pip");
+ }),
+ ),
+ );
+
+ effectIt.effect("stops frame capture when the native picture-in-picture window closes", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const capturePage = vi.fn(async () => ({
+ toJPEG: () => Buffer.from("native-close-preview-frame"),
+ getSize: () => ({ width: 1280, height: 720 }),
+ }));
+ fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
+ const { pictureInPictureWindow } = makeTestPictureInPictureWindow();
+ browserWindowConstructor.mockImplementation(function () {
+ return pictureInPictureWindow;
+ });
+ const states: PreviewManager.PreviewTabState[] = [];
+ yield* manager.subscribeStateChanges((_tabId, state) =>
+ Effect.sync(() => {
+ states.push(state);
+ }),
+ );
+
+ yield* manager.createTab("tab_native_pip_close");
+ yield* manager.registerWebview("tab_native_pip_close", 42);
+ yield* manager.openPictureInPicture("tab_native_pip_close");
+
+ pictureInPictureWindow.close();
+ yield* settle(() => states.at(-1)?.pictureInPicture === false);
+
+ expect(states.at(-1)?.pictureInPicture).toBe(false);
+ const capturesAfterClose = capturePage.mock.calls.length;
+ yield* TestClock.adjust(200);
+ expect(capturePage).toHaveBeenCalledTimes(capturesAfterClose);
+ }),
+ ),
+ );
+
+ effectIt.effect("retries an unchanged picture-in-picture frame after delivery fails", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const jpeg = Buffer.from("retry-preview-frame");
+ const capturePage = vi.fn(async () => ({
+ toJPEG: () => jpeg,
+ getSize: () => ({ width: 1280, height: 720 }),
+ }));
+ fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
+ const { pictureInPictureWindow, send } = makeTestPictureInPictureWindow();
+ send.mockImplementationOnce(() => {
+ throw new Error("picture-in-picture delivery failed");
+ });
+ browserWindowConstructor.mockImplementation(function () {
+ return pictureInPictureWindow;
+ });
+
+ yield* manager.createTab("tab_pip_delivery_retry");
+ yield* manager.registerWebview("tab_pip_delivery_retry", 42);
+ yield* manager.openPictureInPicture("tab_pip_delivery_retry");
+ expect(send).toHaveBeenCalledOnce();
+
+ yield* TestClock.adjust(100);
+
+ expect(capturePage).toHaveBeenCalledTimes(2);
+ expect(send).toHaveBeenCalledTimes(2);
+ yield* manager.closePictureInPicture("tab_pip_delivery_retry");
+ }),
+ ),
+ );
+
+ effectIt.effect("replays an unchanged picture-in-picture frame after its renderer reloads", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const jpeg = Buffer.from("reloaded-preview-frame");
+ const capturePage = vi.fn(async () => ({
+ toJPEG: () => jpeg,
+ getSize: () => ({ width: 1280, height: 720 }),
+ }));
+ fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
+ const { pictureInPictureWindow, send, webContentsListeners } =
+ makeTestPictureInPictureWindow();
+ browserWindowConstructor.mockImplementation(function () {
+ return pictureInPictureWindow;
+ });
+
+ yield* manager.createTab("tab_pip_reload");
+ yield* manager.registerWebview("tab_pip_reload", 42);
+ yield* manager.openPictureInPicture("tab_pip_reload");
+ expect(send).toHaveBeenCalledOnce();
+
+ webContentsListeners.get("did-finish-load")?.();
+ yield* TestClock.adjust(100);
+
+ expect(send).toHaveBeenCalledTimes(2);
+ yield* manager.closePictureInPicture("tab_pip_reload");
+ }),
+ ),
+ );
+
+ effectIt.effect("keeps recording cadence when pixels remain unchanged", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const unchanged = Buffer.from("unchanged-preview-frame");
+ const capturePage = vi.fn(async () => ({
+ toJPEG: () => unchanged,
+ getSize: () => ({ width: 1280, height: 720 }),
+ }));
+ fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
+ const frames: DesktopPreviewRecordingFrame[] = [];
+
+ yield* manager.subscribeRecordingFrames((frame) =>
+ Effect.sync(() => {
+ frames.push(frame);
+ }),
+ );
+ yield* manager.createTab("tab_unchanged_frame");
+ yield* manager.registerWebview("tab_unchanged_frame", 42);
+ yield* manager.startRecording("tab_unchanged_frame");
+
+ expect(frames.map((frame) => frame.data)).toEqual([unchanged.toString("base64")]);
+
+ yield* TestClock.adjust(100);
+
+ expect(capturePage).toHaveBeenCalledTimes(2);
+ expect(frames.map((frame) => frame.data)).toEqual([
+ unchanged.toString("base64"),
+ unchanged.toString("base64"),
+ ]);
+
+ yield* TestClock.adjust(100);
+
+ expect(capturePage).toHaveBeenCalledTimes(3);
+ expect(frames.map((frame) => frame.data)).toEqual([
+ unchanged.toString("base64"),
+ unchanged.toString("base64"),
+ unchanged.toString("base64"),
+ ]);
+ yield* manager.stopRecording("tab_unchanged_frame");
+ }),
+ ),
+ );
+
+ effectIt.effect("retries recording delivery when pixels remain unchanged", () =>
+ withManager((manager) =>
+ Effect.gen(function* () {
+ const jpeg = Buffer.from("retry-recording-frame");
+ const capturePage = vi.fn(async () => ({
+ toJPEG: () => jpeg,
+ getSize: () => ({ width: 1280, height: 720 }),
+ }));
+ fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
+ let deliveries = 0;
+
+ yield* manager.subscribeRecordingFrames(() =>
+ Effect.sync(() => {
+ deliveries += 1;
+ if (deliveries === 1) throw new Error("recording delivery failed");
+ }),
+ );
+ yield* manager.createTab("tab_recording_delivery_retry");
+ yield* manager.registerWebview("tab_recording_delivery_retry", 42);
+ yield* manager.startRecording("tab_recording_delivery_retry");
+ expect(deliveries).toBe(1);
+
+ yield* TestClock.adjust(100);
+
+ expect(deliveries).toBe(2);
+ yield* manager.stopRecording("tab_recording_delivery_retry");
+ }),
+ ),
+ );
+
effectIt.effect("retries a cold hidden-tab capture without dropping recording", () =>
withManager((manager) =>
Effect.gen(function* () {
diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts
index 0112204503c..758f2ecba3d 100644
--- a/apps/desktop/src/preview/Manager.ts
+++ b/apps/desktop/src/preview/Manager.ts
@@ -381,6 +381,7 @@ type FrameCaptureConsumer = "picture-in-picture" | "recording";
interface FrameCaptureSession {
readonly scope: Scope.Closeable;
readonly consumers: ReadonlySet<FrameCaptureConsumer>;
+ readonly lastPictureInPictureFrame: Buffer | null;
}
interface PictureInPictureSession {
@@ -671,7 +672,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return [
undefined,
replaceMap(sessions, (copy) => {
- copy.set(tabId, { ...current, consumers });
+ copy.set(tabId, {
+ ...current,
+ consumers,
+ lastPictureInPictureFrame:
+ consumer === "picture-in-picture" ? null : current.lastPictureInPictureFrame,
+ });
}),
] as const;
}
@@ -2615,18 +2621,25 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
tabId,
webContentsId: wc.id,
},
- () => image.toJPEG(RECORDING_JPEG_QUALITY).toString("base64"),
+ () => image.toJPEG(RECORDING_JPEG_QUALITY),
);
+ const frameSession = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(tabId);
+ if (frameSession?.scope !== captureSession.scope) return;
+ const recording = frameSession.consumers.has("recording");
+ const pictureInPicture =
+ frameSession.consumers.has("picture-in-picture") &&
+ frameSession.lastPictureInPictureFrame?.equals(encoded) !== true;
+ if (!recording && !pictureInPicture) return;
const receivedAt = yield* currentIso;
const frame: DesktopPreviewRecordingFrame = {
tabId,
- data: encoded,
+ data: encoded.toString("base64"),
width: size.width,
height: size.height,
receivedAt,
};
const deliveries: Array<Effect.Effect<void>> = [];
- if (currentCaptureSession.consumers.has("recording")) {
+ if (recording) {
const listeners = yield* Ref.get(recordingFrameListenersRef);
deliveries.push(
Effect.forEach(
@@ -2636,7 +2649,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
),
);
}
- if (currentCaptureSession.consumers.has("picture-in-picture")) {
+ if (pictureInPicture) {
const pictureInPictureWindow = (yield* SynchronizedRef.get(pictureInPictureSessionsRef)).get(
tabId,
)?.window;
@@ -2686,6 +2699,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
},
);
+ yield* SynchronizedRef.update(frameCaptureSessionsRef, (sessions) => {
+ if (sessions.get(tabId) !== frameSession) return sessions;
+ return replaceMap(sessions, (copy) => {
+ copy.set(tabId, {
+ ...frameSession,
+ lastPictureInPictureFrame: encoded,
+ });
+ });
+ });
}).pipe(
Effect.catch((error) =>
Effect.logWarning("Picture-in-picture frame delivery failed.", {
@@ -2753,6 +2775,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
copy.set(tabId, {
scope,
consumers: new Set([consumer]),
+ lastPictureInPictureFrame: null,
});
}),
] as const;
@@ -2907,6 +2930,18 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
),
);
};
+ const onDidFinishLoad = () => {
+ runFork(
+ SynchronizedRef.update(frameCaptureSessionsRef, (sessions) => {
+ const current = sessions.get(tabId);
+ if (!current?.consumers.has("picture-in-picture")) return sessions;
+ return replaceMap(sessions, (copy) => {
+ copy.set(tabId, { ...current, lastPictureInPictureFrame: null });
+ });
+ }),
+ );
+ };
+ const pipWebContents = pictureInPictureWindow.webContents;
yield* attempt(
{
operation: "pictureInPicture.configure",
@@ -2927,6 +2962,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
skipTransformProcessType: true,
});
}
+ pipWebContents.on("did-finish-load", onDidFinishLoad);
},
).pipe(
Effect.onError(() =>
@@ -2941,6 +2977,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
),
),
);
+ yield* Scope.addFinalizer(
+ initializationScope,
+ Effect.sync(() => {
+ pipWebContents.off("did-finish-load", onDidFinishLoad);
+ }).pipe(Effect.ignore),
+ );
yield* SynchronizedRef.update(pictureInPictureSessionsRef, (sessions) =>
replaceMap(sessions, (copy) => {
copy.set(tabId, session);
diff --git a/apps/web/src/previewStateStore.test.ts b/apps/web/src/previewStateStore.test.ts
index bfe5d46b187..321dd68c09a 100644
--- a/apps/web/src/previewStateStore.test.ts
+++ b/apps/web/src/previewStateStore.test.ts
@@ -20,6 +20,7 @@ import {
rememberPreviewUrl,
removePreviewThread,
resetPreviewStateForTests,
+ subscribeThreadPreviewState,
setActivePreviewTab,
updatePreviewServerSnapshot,
} from "./previewStateStore";
@@ -331,6 +332,38 @@ describe("previewStateStore (single-tab)", () => {
expect(state.snapshot?.canGoBack).toBe(false);
});
+ it("does not publish duplicate desktop browser state", () => {
+ const snapshot = makeSnapshot();
+ applyPreviewServerSnapshot(ref, snapshot);
+ const overlay = {
+ hasWebContents: true,
+ canGoBack: true,
+ canGoForward: false,
+ loading: false,
+ zoomFactor: 1,
+ pictureInPicture: false,
+ colorScheme: "system" as const,
+ audioMuted: false,
+ audible: false,
+ controller: "none" as const,
+ favicon: {
+ dataUrl: "data:image/png;base64,AA==",
+ pageUrl: "https://example.com",
+ capturedAt: 1,
+ },
+ };
+ let updateCount = 0;
+ const unsubscribe = subscribeThreadPreviewState(ref, () => {
+ updateCount += 1;
+ });
+
+ applyPreviewDesktopState(ref, snapshot.tabId, overlay);
+ applyPreviewDesktopState(ref, snapshot.tabId, { ...overlay, favicon: { ...overlay.favicon } });
+ unsubscribe();
+
+ expect(updateCount).toBe(1);
+ });
+
it("retains multiple tabs and switches active desktop state", () => {
const first = makeSnapshot();
const second = { ...makeSnapshot(), tabId: "tab_2", updatedAt: "2026-01-02T00:00:00.000Z" };
diff --git a/apps/web/src/previewStateStore.ts b/apps/web/src/previewStateStore.ts
index a40e65fbc6a..eb1052feeb8 100644
--- a/apps/web/src/previewStateStore.ts
+++ b/apps/web/src/previewStateStore.ts
@@ -368,12 +368,39 @@ export function reconcilePreviewServerSessions(
});
}
+function isPreviewStateEqual(
+ previous: DesktopPreviewOverlay | null,
+ next: DesktopPreviewOverlay | null,
+) {
+ return (
+ previous === next ||
+ (previous !== null &&
+ next !== null &&
+ previous.hasWebContents === next.hasWebContents &&
+ previous.canGoBack === next.canGoBack &&
+ previous.canGoForward === next.canGoForward &&
+ previous.loading === next.loading &&
+ previous.zoomFactor === next.zoomFactor &&
+ previous.pictureInPicture === next.pictureInPicture &&
+ previous.colorScheme === next.colorScheme &&
+ previous.audioMuted === next.audioMuted &&
+ previous.audible === next.audible &&
+ previous.controller === next.controller &&
+ previous.favicon?.dataUrl === next.favicon?.dataUrl &&
+ previous.favicon?.pageUrl === next.favicon?.pageUrl &&
+ previous.favicon?.capturedAt === next.favicon?.capturedAt)
+ );
+}
+
export function applyPreviewDesktopState(
ref: ScopedThreadRef,
tabId: string,
overlay: DesktopPreviewOverlay | null,
): void {
updateThreadPreviewState(ref, (current) => {
+ if (isPreviewStateEqual(current.desktopByTabId[tabId] ?? null, overlay)) {
+ return current;
+ }
const desktopByTabId = { ...current.desktopByTabId };
if (overlay) desktopByTabId[tabId] = overlay;
else delete desktopByTabId[tabId];