The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 08:00 UTC
perf(desktop): picture-in-picture stops re-encoding an unchanged page (#20070)
Co-authored-by: Aaron Queen <bompus@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 15, 2026 at 20:26 UTC
3962ae8586333310eeef655c917389b35f7b679d
2 files changed
+103
-12
apps/desktop/src/preview/Manager.test.ts
+57
@@ -329,6 +329,8 @@ const withManager = <A>(
329
330
interface TestCapturedPreviewImage {
331
readonly toJPEG: () => Buffer;
332
+ /** Only fixtures that deliver picture-in-picture frames need pixels to fingerprint. */
333
+ readonly toBitmap?: () => Buffer;
334
readonly getSize: () => { readonly width: number; readonly height: number };
335
}
336
@@ -3454,6 +3456,7 @@ describe("PreviewManager", () => {
3456
const jpeg = Buffer.from("shared-preview-frame");
3457
const capturePage = vi.fn(async () => ({
3458
toJPEG: () => jpeg,
3459
+ toBitmap: () => jpeg,
3460
getSize: () => ({ width: 1280, height: 720 }),
3461
}));
3462
fromId.mockReturnValue({
@@ -3612,6 +3615,7 @@ describe("PreviewManager", () => {
3615
const jpeg = Buffer.from("shared-preview-frame");
3616
const capturePage = vi.fn(async () => ({
3617
toJPEG: () => jpeg,
3618
+ toBitmap: () => jpeg,
3619
getSize: () => ({ width: 1280, height: 720 }),
3620
}));
3621
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
@@ -3687,6 +3691,7 @@ describe("PreviewManager", () => {
3691
const jpeg = Buffer.from("retry-preview-frame");
3692
const capturePage = vi.fn(async () => ({
3693
toJPEG: () => jpeg,
3694
+ toBitmap: () => jpeg,
3695
getSize: () => ({ width: 1280, height: 720 }),
3696
}));
3697
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
@@ -3718,6 +3723,7 @@ describe("PreviewManager", () => {
3723
const jpeg = Buffer.from("reloaded-preview-frame");
3724
const capturePage = vi.fn(async () => ({
3725
toJPEG: () => jpeg,
3726
+ toBitmap: () => jpeg,
3727
getSize: () => ({ width: 1280, height: 720 }),
3728
}));
3729
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
@@ -3741,11 +3747,62 @@ describe("PreviewManager", () => {
3747
),
3748
);
3749
3750
+ effectIt.effect("encodes a picture-in-picture frame only when the page changes", () =>
3751
+ withManager((manager) =>
3752
+ Effect.gen(function* () {
3753
+ let page = "static-page";
3754
+ let pixelsReadable = true;
3755
+ const toJPEG = vi.fn((pixels: string) => Buffer.from(`jpeg:${pixels}`));
3756
+ const capturePage = vi.fn(async () => {
3757
+ const pixels = page;
3758
+ return {
3759
+ toJPEG: () => toJPEG(pixels),
3760
+ toBitmap: () => (pixelsReadable ? Buffer.from(pixels) : Buffer.alloc(0)),
3761
+ getSize: () => ({ width: 1280, height: 720 }),
3762
+ };
3763
+ });
3764
+ fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
3765
+ const { pictureInPictureWindow, send } = makeTestPictureInPictureWindow();
3766
+ browserWindowConstructor.mockImplementation(function () {
3767
+ return pictureInPictureWindow;
3768
+ });
3769
+
3770
+ yield* manager.createTab("tab_pip_unchanged");
3771
+ yield* manager.registerWebview("tab_pip_unchanged", 42);
3772
+ yield* manager.openPictureInPicture("tab_pip_unchanged");
3773
+ yield* TestClock.adjust(100);
3774
+
3775
+ expect(capturePage).toHaveBeenCalledTimes(2);
3776
+ expect(toJPEG).toHaveBeenCalledOnce();
3777
+ expect(send).toHaveBeenCalledOnce();
3778
+
3779
+ page = "changed-page";
3780
+ yield* TestClock.adjust(100);
3781
+
3782
+ expect(toJPEG).toHaveBeenCalledTimes(2);
3783
+ expect(send).toHaveBeenCalledTimes(2);
3784
+ expect(send).toHaveBeenLastCalledWith(
3785
+ "desktop:preview-pip-frame",
3786
+ expect.objectContaining({ data: Buffer.from("jpeg:changed-page").toString("base64") }),
3787
+ );
3788
+
3789
+ // A frame whose pixels cannot be read has no fingerprint and is still delivered.
3790
+ pixelsReadable = false;
3791
+ yield* TestClock.adjust(100);
3792
+
3793
+ expect(toJPEG).toHaveBeenCalledTimes(3);
3794
+ expect(send).toHaveBeenCalledTimes(3);
3795
+ yield* manager.closePictureInPicture("tab_pip_unchanged");
3796
+ }),
3797
+ ),
3798
+ );
3799
+
3800
effectIt.effect("drops empty frames before picture-in-picture delivery", () =>
3801
withManager((manager) =>
3802
Effect.gen(function* () {
3803
const validImage: TestCapturedPreviewImage = {
3804
toJPEG: () => Buffer.from("valid-preview-frame"),
3805
+ toBitmap: () => Buffer.from("valid-preview-frame"),
3806
getSize: () => ({ width: 1280, height: 720 }),
3807
};
3808
const capturePage = vi.fn(async () => validImage);
apps/desktop/src/preview/Manager.ts
+46
-12
@@ -5,6 +5,7 @@
5
* elements live in the renderer; we only attach listeners and forward state
6
* here). Single layer-scoped browser session partition.
7
*/
8
+import * as NodeZlib from "node:zlib";
9
import {
10
DesktopPreviewRecordingInputSchema,
11
DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER,
@@ -318,6 +319,33 @@ const cropAnnotationScreenshot = (
319
return { dataUrl: cropped.toDataURL(), width: size.width, height: size.height, cropRect };
320
};
321
322
+/**
323
+ * Electron converts `toBitmap()` output to sRGB by default. Captures on P3 Macs are
324
+ * P3, so that conversion costs more per tick than the JPEG encode the fingerprint
325
+ * replaces. An invalid target color space has no Skia color space, so `readPixels`
326
+ * copies the pixels without a color transform. The fingerprint only compares frames
327
+ * with each other, so color accuracy is irrelevant.
328
+ */
329
+const FINGERPRINT_BITMAP_OPTIONS: Electron.ToBitmapOptions = {
330
+ colorSpace: { primaries: "invalid", transfer: "invalid", matrix: "invalid", range: "invalid" },
331
+};
332
+
333
+/**
334
+ * Identity of a captured frame: cheap enough to compute every tick, unlike a JPEG
335
+ * encode. Null when the pixels could not be read (Electron reports a failed
336
+ * `readPixels` as an empty buffer), so the caller treats the frame as changed.
337
+ */
338
+const fingerprintCapturedFrame = (image: Electron.NativeImage, size: Electron.Size) => {
339
+ let bitmap: Buffer;
340
+ try {
341
+ bitmap = image.toBitmap(FINGERPRINT_BITMAP_OPTIONS);
342
+ } catch {
343
+ return null;
344
+ }
345
+ if (bitmap.byteLength === 0) return null;
346
+ return `${size.width}x${size.height}:${NodeZlib.crc32(bitmap)}`;
347
+};
348
+
349
const findZoomStep = (current: number): number => {
350
const index = ZOOM_LEVELS.findIndex(
351
(level) => Math.abs(level - current) < ZOOM_EPSILON || level > current,
@@ -370,7 +398,7 @@ interface FrameCaptureSession {
398
readonly scope: Scope.Closeable | null;
399
readonly consumers: ReadonlySet<FrameCaptureConsumer>;
400
readonly unthrottledWebContentsIds: ReadonlySet<number>;
373
- readonly lastPictureInPictureFrame: Buffer | null;
401
+ readonly lastPictureInPictureFingerprint: string | null;
402
}
403
404
interface PictureInPictureSession {
@@ -793,8 +821,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
821
...current,
822
scope: consumer === "picture-in-picture" ? null : current.scope,
823
consumers,
796
- lastPictureInPictureFrame:
797
- consumer === "picture-in-picture" ? null : current.lastPictureInPictureFrame,
824
+ lastPictureInPictureFingerprint:
825
+ consumer === "picture-in-picture"
826
+ ? null
827
+ : current.lastPictureInPictureFingerprint,
828
});
829
}),
830
] as const;
@@ -2584,6 +2614,16 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2614
) {
2615
return;
2616
}
2617
+ const frameSession = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(tabId);
2618
+ if (frameSession?.scope !== captureSession.scope) return;
2619
+ // Fingerprint the raw pixels before encoding so an unchanged page skips the
2620
+ // synchronous JPEG encode, the base64 copy and the IPC send. An unreadable
2621
+ // frame has no fingerprint and is always delivered.
2622
+ const fingerprint = fingerprintCapturedFrame(image, size);
2623
+ const pictureInPicture =
2624
+ frameSession.consumers.has("picture-in-picture") &&
2625
+ (fingerprint === null || frameSession.lastPictureInPictureFingerprint !== fingerprint);
2626
+ if (!pictureInPicture) return;
2627
const encoded = yield* attempt(
2628
{
2629
operation: "frameCapture.encodeFrame",
@@ -2592,12 +2632,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2632
},
2633
() => image.toJPEG(PICTURE_IN_PICTURE_JPEG_QUALITY),
2634
);
2595
- const frameSession = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(tabId);
2596
- if (frameSession?.scope !== captureSession.scope) return;
2597
- const pictureInPicture =
2598
- frameSession.consumers.has("picture-in-picture") &&
2599
- frameSession.lastPictureInPictureFrame?.equals(encoded) !== true;
2600
- if (!pictureInPicture) return;
2635
const receivedAt = yield* currentIso;
2636
const frame: DesktopPreviewRecordingFrame = {
2637
tabId,
@@ -2662,7 +2696,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2696
return replaceMap(sessions, (copy) => {
2697
copy.set(tabId, {
2698
...frameSession,
2665
- lastPictureInPictureFrame: encoded,
2699
+ lastPictureInPictureFingerprint: fingerprint,
2700
});
2701
});
2702
});
@@ -2754,7 +2788,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2788
scope,
2789
consumers: new Set([consumer]),
2790
unthrottledWebContentsIds: new Set([wc.id]),
2757
- lastPictureInPictureFrame: null,
2791
+ lastPictureInPictureFingerprint: null,
2792
});
2793
}),
2794
] as const;
@@ -2920,7 +2954,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2954
const current = sessions.get(tabId);
2955
if (!current?.consumers.has("picture-in-picture")) return sessions;
2956
return replaceMap(sessions, (copy) => {
2923
- copy.set(tabId, { ...current, lastPictureInPictureFrame: null });
2957
+ copy.set(tabId, { ...current, lastPictureInPictureFingerprint: null });
2958
});
2959
}),
2960
);