TypeScript
fix(preview): improve browser recording quality (#8839)
maria3958111057c1
diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.tsindex 5229d36c31f..718ebd2a3cf 100644--- a/apps/desktop/src/ipc/methods/preview.ts+++ b/apps/desktop/src/ipc/methods/preview.ts@@ -11,6 +11,7 @@ import {DesktopPreviewConfigInputSchema,DesktopPreviewNavigateInputSchema,DesktopPreviewRecordingArtifactSchema,+ DesktopPreviewRecordingSourceSchema,DesktopPreviewRecordingSaveInputSchema,DesktopPreviewRegisterWebviewInputSchema,DesktopPreviewScreenshotArtifactSchema,@@ -173,11 +174,15 @@ export const cancelPickElement = tabMethod("desktop.ipc.preview.cancelPickElement",(manager, tabId) => manager.cancelPickElement(tabId),);-export const startRecording = tabMethod(- IpcChannels.PREVIEW_RECORDING_START_CHANNEL,- "desktop.ipc.preview.startRecording",- (manager, tabId) => manager.startRecording(tabId),-);+export const startRecording = DesktopIpc.makeIpcMethod({+ channel: IpcChannels.PREVIEW_RECORDING_START_CHANNEL,+ payload: DesktopPreviewTabInputSchema,+ result: DesktopPreviewRecordingSourceSchema,+ handler: Effect.fn("desktop.ipc.preview.startRecording")(function* ({ tabId }) {+ const manager = yield* PreviewManager.PreviewManager;+ return yield* manager.startRecording(tabId);+ }),+});export const stopRecording = tabMethod(IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL,"desktop.ipc.preview.stopRecording",diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.tsindex adc72672977..0cd85c710ea 100644--- a/apps/desktop/src/preview/Manager.test.ts+++ b/apps/desktop/src/preview/Manager.test.ts@@ -36,6 +36,14 @@ describe("fitPictureInPictureContentSize", () => {});});+describe("recordingFileExtension", () => {+ it("derives the artifact extension from the recorder's actual mime type", () => {+ expect(PreviewManager.recordingFileExtension("video/mp4;codecs=avc1.640028")).toBe("mp4");+ expect(PreviewManager.recordingFileExtension("video/webm;codecs=vp9")).toBe("webm");+ expect(PreviewManager.recordingFileExtension("video/x-matroska")).toBe("matroska");+ });+});+describe("isPreviewRefreshShortcut", () => {const input = (overrides: Partial<Electron.Input> = {}) =>({@@ -207,6 +215,9 @@ const makeTestPreviewWebContents = () =>({id,+ hostWebContents: { id: 7 },+ getMediaSourceId: vi.fn(() => `tab:${id}`),+ executeJavaScript: vi.fn(async () => ({ width: 1280, height: 720 })),isDestroyed: () => false,getType: () => "webview",getURL: () => "https://example.com",@@ -1666,7 +1677,9 @@ describe("PreviewManager", () => {const recreated = yield* Fiber.join(recreateFiber);const registrationExit = yield* Fiber.await(registrationFiber);- for (const exit of [registrationExit, recordingExit]) {+ for (const exit of [registrationExit, recordingExit] as ReadonlyArray<+ Exit.Exit<unknown, PreviewManager.PreviewManagerError>+ >) {expect(Exit.isFailure(exit)).toBe(true);if (Exit.isSuccess(exit)) continue;expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({@@ -2062,7 +2075,7 @@ describe("PreviewManager", () => {),);- effectIt.effect("captures hidden preview recordings independently for concurrent tabs", () =>+ effectIt.effect("returns native media sources for concurrent preview recordings", () =>withManager((manager) =>Effect.gen(function* () {const firstJpeg = Buffer.from("first-recording-frame");@@ -2084,6 +2097,11 @@ describe("PreviewManager", () => {) =>({id,+ hostWebContents: { id: 7 },+ getMediaSourceId: vi.fn(() => `tab:${id}`),+ executeJavaScript: vi.fn(async () =>+ id === 41 ? { width: 800, height: 600 } : { width: 390, height: 844 },+ ),isDestroyed: () => false,getType: () => "webview",getURL: () => `https://example.com/${id}`,@@ -2115,41 +2133,21 @@ describe("PreviewManager", () => {fromId.mockImplementation((id) =>id === undefined ? null : (webContentsById.get(id) ?? null),);- const frames: DesktopPreviewRecordingFrame[] = [];-- yield* manager.subscribeRecordingFrames((frame) =>- Effect.sync(() => {- frames.push(frame);- }),- );yield* manager.createTab("tab_1");yield* manager.createTab("tab_2");yield* manager.registerWebview("tab_1", 41);yield* manager.registerWebview("tab_2", 42);- yield* Effect.all([manager.startRecording("tab_1"), manager.startRecording("tab_2")], {- concurrency: 2,- discard: true,- });+ const sources = yield* Effect.all(+ [manager.startRecording("tab_1"), manager.startRecording("tab_2")],+ { concurrency: 2 },+ );+ expect(sources).toEqual([+ { sourceId: "tab:41", width: 800, height: 600 },+ { sourceId: "tab:42", width: 390, height: 844 },+ ]);expect(firstCapturePage).toHaveBeenCalledOnce();expect(secondCapturePage).toHaveBeenCalledOnce();- expect(frames).toHaveLength(2);- expect(frames).toEqual(- expect.arrayContaining([- expect.objectContaining({- tabId: "tab_1",- data: firstJpeg.toString("base64"),- width: 800,- height: 600,- }),- expect.objectContaining({- tabId: "tab_2",- data: secondJpeg.toString("base64"),- width: 390,- height: 844,- }),- ]),- );expect(firstSendCommand).not.toHaveBeenCalledWith("Page.startScreencast",expect.anything(),@@ -2167,203 +2165,178 @@ describe("PreviewManager", () => {),);- effectIt.effect("drops a captured frame when the tab webview changes during capture", () =>+ effectIt.effect("continues native recording when the source warmup fails", () =>withManager((manager) =>Effect.gen(function* () {- const staleImage: TestCapturedPreviewImage = {- toJPEG: vi.fn(() => Buffer.from("stale-recording-frame")),- getSize: vi.fn(() => ({ width: 1280, height: 720 })),- };- let markCaptureStarted!: () => void;- const captureStarted = new Promise<void>((resolve) => {- markCaptureStarted = resolve;- });- let resolveCapture: ((image: TestCapturedPreviewImage) => void) | undefined;- const staleCapturePage = vi.fn(() => {- markCaptureStarted();- return new Promise<TestCapturedPreviewImage>((resolve) => {- resolveCapture = resolve;- });+ const capturePage = vi.fn(async () => {+ throw new Error("source is not ready");});- const replacementCapturePage = vi.fn(async () => ({- toJPEG: () => Buffer.from("replacement-recording-frame"),- getSize: () => ({ width: 1280, height: 720 }),- }));- const initialWebContents = makeTestPreviewWebContents(staleCapturePage, 42);- const replacementWebContents = makeTestPreviewWebContents(replacementCapturePage, 43);- fromId.mockImplementation((webContentsId?: number) => {- if (webContentsId === 42) return initialWebContents;- if (webContentsId === 43) return replacementWebContents;- return null;+ const getMediaSourceId = vi.fn(() => "tab:42");+ const webContents = Object.assign(makeTestPreviewWebContents(capturePage), {+ executeJavaScript: vi.fn(async () => ({ width: 1280, height: 720 })),+ getMediaSourceId,});- const frames: DesktopPreviewRecordingFrame[] = [];+ fromId.mockReturnValue(webContents);- yield* manager.subscribeRecordingFrames((frame) =>- Effect.sync(() => {- frames.push(frame);- }),- );- yield* manager.createTab("tab_capture_replaced");- yield* manager.registerWebview("tab_capture_replaced", 42);- const recordingFiber = yield* manager- .startRecording("tab_capture_replaced")- .pipe(Effect.forkChild({ startImmediately: true }));- yield* Effect.promise(() => captureStarted);-- yield* manager.registerWebview("tab_capture_replaced", 43);- resolveCapture?.(staleImage);- yield* Fiber.join(recordingFiber);+ yield* manager.createTab("tab_recording_warmup_failure");+ yield* manager.registerWebview("tab_recording_warmup_failure", 42);- expect(staleImage.getSize).not.toHaveBeenCalled();- expect(staleImage.toJPEG).not.toHaveBeenCalled();- expect(frames).toHaveLength(0);- expect(replacementCapturePage).not.toHaveBeenCalled();+ expect(yield* manager.startRecording("tab_recording_warmup_failure")).toEqual({+ sourceId: "tab:42",+ width: 1280,+ height: 720,+ });+ expect(capturePage).toHaveBeenCalledTimes(2);+ expect(getMediaSourceId).toHaveBeenCalledOnce();- yield* manager.stopRecording("tab_capture_replaced");+ yield* manager.stopRecording("tab_recording_warmup_failure");}),),);- effectIt.effect("keeps an in-flight frame when a capture consumer is added", () =>+ effectIt.effect("reports invalid native recording dimensions as a structured error", () =>withManager((manager) =>Effect.gen(function* () {- const image: TestCapturedPreviewImage = {- toJPEG: vi.fn(() => Buffer.from("shared-in-flight-frame")),- getSize: vi.fn(() => ({ width: 1280, height: 720 })),- };- let markCaptureStarted!: () => void;- const captureStarted = new Promise<void>((resolve) => {- markCaptureStarted = resolve;- });- let resolveCapture: ((captured: TestCapturedPreviewImage) => void) | undefined;- const capturePage = vi.fn(() => {- markCaptureStarted();- return new Promise<TestCapturedPreviewImage>((resolve) => {- resolveCapture = resolve;- });- });- fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));- const { pictureInPictureWindow, send } = makeTestPictureInPictureWindow();- browserWindowConstructor.mockImplementation(function () {- return pictureInPictureWindow;+ const capturePage = vi.fn(async () => ({+ toJPEG: () => Buffer.from("unused-recording-frame"),+ getSize: () => ({ width: 1280, height: 720 }),+ }));+ const getMediaSourceId = vi.fn(() => "tab:42");+ const webContents = Object.assign(makeTestPreviewWebContents(capturePage), {+ executeJavaScript: vi.fn(async () => ({ width: 0, height: 720 })),+ getMediaSourceId,});- const recordingFrames: DesktopPreviewRecordingFrame[] = [];- yield* manager.subscribeRecordingFrames((frame) =>- Effect.sync(() => {- recordingFrames.push(frame);- }),- );-- yield* manager.createTab("tab_capture_consumer_added");- yield* manager.registerWebview("tab_capture_consumer_added", 42);- const recordingFiber = yield* manager- .startRecording("tab_capture_consumer_added")- .pipe(Effect.forkChild({ startImmediately: true }));- yield* Effect.promise(() => captureStarted);+ fromId.mockReturnValue(webContents);- yield* manager.openPictureInPicture("tab_capture_consumer_added");- resolveCapture?.(image);- yield* Fiber.join(recordingFiber);+ yield* manager.createTab("tab_invalid_recording_size");+ yield* manager.registerWebview("tab_invalid_recording_size", 42);+ const exit = yield* Effect.exit(manager.startRecording("tab_invalid_recording_size"));- expect(recordingFrames).toHaveLength(1);- expect(send).toHaveBeenCalledWith(- "desktop:preview-pip-frame",- expect.objectContaining({- tabId: "tab_capture_consumer_added",- data: Buffer.from("shared-in-flight-frame").toString("base64"),- }),- );-- yield* manager.stopRecording("tab_capture_consumer_added");- yield* manager.closePictureInPicture("tab_capture_consumer_added");+ expect(Exit.isFailure(exit)).toBe(true);+ if (Exit.isSuccess(exit)) return;+ expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({+ _tag: "PreviewRecordingSourceSizeUnavailableError",+ tabId: "tab_invalid_recording_size",+ webContentsId: 42,+ });+ expect(getMediaSourceId).not.toHaveBeenCalled();}),),);- effectIt.effect("emits debugger screencast frames only while recording is active", () =>+ effectIt.effect("keeps a newer recording lease when an earlier start fails", () =>withManager((manager) =>Effect.gen(function* () {- let debuggerMessage:- | ((event: unknown, method: string, params: Record<string, unknown>) => void)- | undefined;+ const setBackgroundThrottling = vi.fn();const capturePage = vi.fn(async () => ({- toJPEG: () => Buffer.from("scheduled-recording-frame"),+ toJPEG: () => Buffer.from("unused-recording-frame"),getSize: () => ({ width: 1280, height: 720 }),}));- const sendCommand = vi.fn(async (method: string) =>- method === "Runtime.evaluate" ? { result: { value: null } } : undefined,- );- fromId.mockReturnValue({- id: 42,+ let markMeasurementStarted!: () => void;+ const measurementStarted = new Promise<void>((resolve) => {+ markMeasurementStarted = resolve;+ });+ let rejectFirstMeasurement!: (error: Error) => void;+ const executeJavaScript = vi+ .fn<(expression: string, userGesture?: boolean) => Promise<unknown>>()+ .mockImplementationOnce(() => {+ markMeasurementStarted();+ return new Promise((_, reject) => {+ rejectFirstMeasurement = reject;+ });+ })+ .mockResolvedValue({ width: 1280, height: 720 });+ const webContents = Object.assign(makeTestPreviewWebContents(capturePage), {+ executeJavaScript,+ });+ fromId.mockReturnValue(webContents);++ yield* manager.createTab("tab_recording_start_race");+ yield* manager.registerWebview("tab_recording_start_race", 42);+ yield* manager.setMainWindow({isDestroyed: () => false,- getType: () => "webview",- getURL: () => "https://example.com",- getTitle: () => "Example",- isLoading: () => false,- isDevToolsOpened: () => false,- getZoomFactor: () => 1,- setZoomFactor: vi.fn(),- setAudioMuted: vi.fn(),- isCurrentlyAudible: () => false,- on: vi.fn(),- off: vi.fn(),- ipc: { on: vi.fn(), off: vi.fn() },- send: webviewSend,- navigationHistory: { canGoBack: () => false, canGoForward: () => false },- setWindowOpenHandler: vi.fn(),- debugger: {- isAttached: () => false,- attach: vi.fn(),- sendCommand,- on: vi.fn(- (- event: string,- listener: (event: unknown, method: string, params: Record<string, unknown>) => void,- ) => {- if (event === "message") debuggerMessage = listener;- },- ),- off: vi.fn(),- },- capturePage,+ once: vi.fn(),+ webContents: { setBackgroundThrottling },} as never);- const recordingFrames: DesktopPreviewRecordingFrame[] = [];- yield* manager.subscribeRecordingFrames((frame) =>- Effect.sync(() => {- recordingFrames.push(frame);- }),- );- yield* manager.createTab("tab_screencast_guard");- yield* manager.registerWebview("tab_screencast_guard", 42);- yield* manager.automationEvaluate("tab_screencast_guard", { expression: "null" });+ const firstStart = yield* manager+ .startRecording("tab_recording_start_race")+ .pipe(Effect.forkChild({ startImmediately: true }));+ yield* Effect.promise(() => measurementStarted);+ const secondStart = yield* manager+ .startRecording("tab_recording_start_race")+ .pipe(Effect.forkChild({ startImmediately: true }));+ yield* Effect.yieldNow;+ expect(executeJavaScript).toHaveBeenCalledOnce();- debuggerMessage?.({}, "Page.screencastFrame", {- sessionId: 1,- data: "inactive-frame",- metadata: { deviceWidth: 1280, deviceHeight: 720 },+ rejectFirstMeasurement(new Error("first measurement failed"));+ const firstExit = yield* Fiber.await(firstStart);+ expect(Exit.isFailure(firstExit)).toBe(true);+ expect(yield* Fiber.join(secondStart)).toEqual({+ sourceId: "tab:42",+ width: 1280,+ height: 720,});- yield* Effect.yieldNow;- expect(recordingFrames).toHaveLength(0);- yield* manager.startRecording("tab_screencast_guard");- recordingFrames.length = 0;- debuggerMessage?.({}, "Page.screencastFrame", {- sessionId: 2,- data: "active-frame",- metadata: { deviceWidth: 1280, deviceHeight: 720 },+ yield* manager.stopRecording("tab_recording_start_race");+ expect(setBackgroundThrottling.mock.calls).toEqual([[false], [true], [false], [true]]);+ }),+ ),+ );++ effectIt.effect("serializes recording source acquisition with webview replacement", () =>+ withManager((manager) =>+ Effect.gen(function* () {+ const capturePage = vi.fn(async () => ({+ toJPEG: () => Buffer.from("unused-recording-frame"),+ getSize: () => ({ width: 1280, height: 720 }),+ }));+ let markMeasurementStarted!: () => void;+ const measurementStarted = new Promise<void>((resolve) => {+ markMeasurementStarted = resolve;});+ let finishMeasurement!: (size: { readonly width: number; readonly height: number }) => void;+ const executeJavaScript = vi.fn(+ () =>+ new Promise<{ readonly width: number; readonly height: number }>((resolve) => {+ markMeasurementStarted();+ finishMeasurement = resolve;+ }),+ );+ const initialWebContents = Object.assign(makeTestPreviewWebContents(capturePage, 42), {+ executeJavaScript,+ });+ const replacementOn = vi.fn();+ const replacementWebContents = Object.assign(makeTestPreviewWebContents(capturePage, 43), {+ on: replacementOn,+ });+ fromId.mockImplementation((id) => {+ if (id === 42) return initialWebContents;+ if (id === 43) return replacementWebContents;+ return null;+ });++ yield* manager.createTab("tab_recording_replacement_race");+ yield* manager.registerWebview("tab_recording_replacement_race", 42);+ const start = yield* manager+ .startRecording("tab_recording_replacement_race")+ .pipe(Effect.forkChild({ startImmediately: true }));+ yield* Effect.promise(() => measurementStarted);+ const replacement = yield* manager+ .registerWebview("tab_recording_replacement_race", 43)+ .pipe(Effect.forkChild({ startImmediately: true }));yield* Effect.yieldNow;+ expect(replacementOn).not.toHaveBeenCalled();- expect(recordingFrames).toEqual([- expect.objectContaining({- tabId: "tab_screencast_guard",- data: "active-frame",- width: 1280,- height: 720,- }),- ]);- yield* manager.stopRecording("tab_screencast_guard");+ finishMeasurement({ width: 1280, height: 720 });+ expect(yield* Fiber.join(start)).toEqual({+ sourceId: "tab:42",+ width: 1280,+ height: 720,+ });+ yield* Fiber.join(replacement);+ expect(replacementOn).toHaveBeenCalled();+ yield* manager.stopRecording("tab_recording_replacement_race");}),),);@@ -2381,6 +2354,8 @@ describe("PreviewManager", () => {fromId.mockReturnValue({id: 42,hostWebContents: mainWindowWebContents,+ getMediaSourceId: vi.fn(() => "tab:42"),+ executeJavaScript: vi.fn(async () => ({ width: 1280, height: 720 })),isDestroyed: () => false,getType: () => "webview",getURL: () => "https://example.com",@@ -2494,21 +2469,21 @@ describe("PreviewManager", () => {const pictureInPictureFramesBeforeRecording = pictureInPictureSend.mock.calls.length;yield* manager.startRecording("tab_pip");- expect(capturePage).toHaveBeenCalledOnce();+ expect(capturePage).toHaveBeenCalledTimes(2);expect(recordingFrames).toHaveLength(0);yield* TestClock.adjust(100);- expect(capturePage).toHaveBeenCalledTimes(2);+ expect(capturePage).toHaveBeenCalledTimes(3);expect(pictureInPictureSend).toHaveBeenCalledTimes(pictureInPictureFramesBeforeRecording);- expect(recordingFrames).toHaveLength(1);+ expect(recordingFrames).toHaveLength(0);yield* manager.stopRecording("tab_pip");expect(setBackgroundThrottling.mock.calls).toEqual([[false]]);const framesBeforePictureInPictureOnlyTick = pictureInPictureSend.mock.calls.length;yield* TestClock.adjust(100);- expect(capturePage).toHaveBeenCalledTimes(3);+ expect(capturePage).toHaveBeenCalledTimes(4);expect(pictureInPictureSend.mock.calls.length).toBe(framesBeforePictureInPictureOnlyTick);- expect(recordingFrames).toHaveLength(1);+ expect(recordingFrames).toHaveLength(0);setBackgroundThrottling.mockImplementationOnce(() => {throw new Error("picture-in-picture throttling restore failed");@@ -2524,7 +2499,7 @@ describe("PreviewManager", () => {),);- effectIt.effect("starts picture-in-picture without an extra recording capture", () =>+ effectIt.effect("keeps picture-in-picture capture separate from recording warmup", () =>withManager((manager) =>Effect.gen(function* () {const jpeg = Buffer.from("shared-preview-frame");@@ -2548,15 +2523,16 @@ describe("PreviewManager", () => {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(recordingFrames).toHaveLength(0);expect(capturePage).toHaveBeenCalledOnce();- expect(send).not.toHaveBeenCalled();+ yield* manager.openPictureInPicture("tab_recording_then_pip");+ expect(capturePage).toHaveBeenCalledTimes(2);+ expect(send).toHaveBeenCalledOnce();yield* TestClock.adjust(100);- expect(capturePage).toHaveBeenCalledTimes(2);- expect(recordingFrames).toHaveLength(2);+ expect(capturePage).toHaveBeenCalledTimes(3);+ expect(recordingFrames).toHaveLength(0);expect(send).toHaveBeenCalledOnce();yield* manager.closePictureInPicture("tab_recording_then_pip");yield* manager.stopRecording("tab_recording_then_pip");@@ -2658,121 +2634,6 @@ describe("PreviewManager", () => {),);- 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* () {- const jpeg = Buffer.from("recovered-preview-frame");- const capturePage = vi.fn(async () => ({- toJPEG: () => jpeg,- getSize: () => ({ width: 1280, height: 720 }),- }));- capturePage.mockRejectedValueOnce(new Error("UnknownVizError"));- fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));- const frames: DesktopPreviewRecordingFrame[] = [];-- yield* manager.subscribeRecordingFrames((frame) =>- Effect.sync(() => {- frames.push(frame);- }),- );- yield* manager.createTab("tab_cold_capture");- yield* manager.registerWebview("tab_cold_capture", 42);-- yield* manager.startRecording("tab_cold_capture");-- expect(capturePage).toHaveBeenCalledOnce();- expect(frames).toHaveLength(0);-- yield* TestClock.adjust(100);-- expect(capturePage).toHaveBeenCalledTimes(2);- expect(frames).toEqual([- expect.objectContaining({- tabId: "tab_cold_capture",- data: jpeg.toString("base64"),- width: 1280,- height: 720,- }),- ]);-- yield* manager.stopRecording("tab_cold_capture");- }),- ),- );-effectIt.effect("drops empty frames before picture-in-picture delivery", () =>withManager((manager) =>Effect.gen(function* () {diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.tsindex 758f2ecba3d..7d11b2614c1 100644--- a/apps/desktop/src/preview/Manager.ts+++ b/apps/desktop/src/preview/Manager.ts@@ -16,6 +16,7 @@ import type {PreviewAnnotationSubmissionResult,DesktopPreviewRecordingArtifact,DesktopPreviewRecordingFrame,+ DesktopPreviewRecordingSource,DesktopPreviewScreenshotArtifact,DesktopPreviewTabDefaults,PreviewAutomationClickInput,@@ -108,8 +109,10 @@ const MAX_EVALUATION_BYTES = 64_000;const MAX_VISIBLE_TEXT_LENGTH = 20_000;const MAX_INTERACTIVE_ELEMENTS = 200;const MAX_SCREENSHOT_WIDTH = 1280;-const RECORDING_FRAME_INTERVAL_MS = Math.ceil(1_000 / 12);-const RECORDING_JPEG_QUALITY = 80;+const RECORDING_SOURCE_SIZE_EXPRESSION =+ "({ width: Math.round(globalThis.innerWidth), height: Math.round(globalThis.innerHeight) })";+const PICTURE_IN_PICTURE_FRAME_INTERVAL_MS = Math.ceil(1_000 / 12);+const PICTURE_IN_PICTURE_JPEG_QUALITY = 80;const PICTURE_IN_PICTURE_INITIAL_WIDTH = 480;const PICTURE_IN_PICTURE_INITIAL_HEIGHT = 320;const PICTURE_IN_PICTURE_MIN_WIDTH = 240;@@ -188,6 +191,12 @@ export const fitPictureInPictureContentSize = (return [Math.round(width), Math.round(height)];};+export const recordingFileExtension = (mimeType: string): string => {+ const subtype = mimeType.split(";", 1)[0]?.trim().toLowerCase().split("/")[1] ?? "";+ const extension = subtype.replace(/^x-/, "").replace(/[^a-z0-9]/g, "");+ return extension || "video";+};+const artifactSiteSlug = (rawUrl: string): string => {try {const url = new URL(rawUrl);@@ -379,7 +388,7 @@ interface ManagedListeners {type FrameCaptureConsumer = "picture-in-picture" | "recording";interface FrameCaptureSession {- readonly scope: Scope.Closeable;+ readonly scope: Scope.Closeable | null;readonly consumers: ReadonlySet<FrameCaptureConsumer>;readonly lastPictureInPictureFrame: Buffer | null;}@@ -670,10 +679,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(functionconsumers.delete(consumer);if (consumers.size > 0) {return [- undefined,+ consumer === "picture-in-picture" ? current.scope : undefined,replaceMap(sessions, (copy) => {copy.set(tabId, {...current,+ scope: consumer === "picture-in-picture" ? null : current.scope,consumers,lastPictureInPictureFrame:consumer === "picture-in-picture" ? null : current.lastPictureInPictureFrame,@@ -2575,7 +2585,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(functiontabId: string,) {const captureSession = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(tabId);- if (!captureSession) return;+ if (!captureSession?.consumers.has("picture-in-picture") || captureSession.scope === null)+ return;const wc = yield* requireWebContents(tabId);const image = yield* attemptPromise({@@ -2621,15 +2632,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(functiontabId,webContentsId: wc.id,},- () => image.toJPEG(RECORDING_JPEG_QUALITY),+ () => image.toJPEG(PICTURE_IN_PICTURE_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;+ if (!pictureInPicture) return;const receivedAt = yield* currentIso;const frame: DesktopPreviewRecordingFrame = {tabId,@@ -2639,16 +2649,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(functionreceivedAt,};const deliveries: Array<Effect.Effect<void>> = [];- if (recording) {- const listeners = yield* Ref.get(recordingFrameListenersRef);- deliveries.push(- Effect.forEach(- listeners,- (listener) => deliverEvent("recording-frame", frame.tabId, () => listener(frame)),- { discard: true },- ),- );- }if (pictureInPicture) {const pictureInPictureWindow = (yield* SynchronizedRef.get(pictureInPictureSessionsRef)).get(tabId,@@ -2726,12 +2726,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(functiontabId: string,consumer: FrameCaptureConsumer,) {- // Validate the tab synchronously, but treat capturePage failures as- // transient. Chromium can return UnknownVizError while a hidden guest is- // warming its first compositor frame; the scheduled loop should keep the- // consumer alive and recover instead of tearing recording/PiP back down.+ // Recording keeps only the activity lease. Picture-in-picture owns the+ // capturePage loop and tolerates transient compositor warmup failures.yield* requireWebContents(tabId);- const captureNextFrame = Effect.sleep(RECORDING_FRAME_INTERVAL_MS).pipe(+ const captureNextFrame = Effect.sleep(PICTURE_IN_PICTURE_FRAME_INTERVAL_MS).pipe(Effect.andThen(capturePreviewFrame(tabId)),Effect.catch((error) =>Effect.logWarning("Background preview frame capture failed.", {@@ -2740,48 +2738,60 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function}),),);- const created = yield* SynchronizedRef.modifyEffect(frameCaptureSessionsRef, (sessions) => {- return Effect.gen(function* () {- if (!frameCaptureWindowOpen) {- return yield* new PreviewMainWindowClosedError({ tabId });- }- const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);- if (!tab || (yield* Ref.get(closingTabIdsRef)).has(tabId)) {- return yield* new PreviewTabNotFoundError({ tabId });- }- const current = sessions.get(tabId);- if (current) {- if (current.consumers.has(consumer)) {- return [false, sessions] as const;+ const captureInitialFrame = yield* SynchronizedRef.modifyEffect(+ frameCaptureSessionsRef,+ (sessions) => {+ return Effect.gen(function* () {+ if (!frameCaptureWindowOpen) {+ return yield* new PreviewMainWindowClosedError({ tabId });+ }+ const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);+ if (!tab || (yield* Ref.get(closingTabIdsRef)).has(tabId)) {+ return yield* new PreviewTabNotFoundError({ tabId });+ }+ const current = sessions.get(tabId);+ if (current) {+ if (current.consumers.has(consumer)) {+ return [false, sessions] as const;+ }+ let scope = current.scope;+ if (consumer === "picture-in-picture" && scope === null) {+ scope = yield* Scope.fork(parentScope, "sequential");+ yield* Effect.forkIn(Effect.forever(captureNextFrame), scope);+ }+ return [+ consumer === "picture-in-picture",+ replaceMap(sessions, (copy) => {+ copy.set(tabId, {+ ...current,+ scope,+ consumers: new Set([...current.consumers, consumer]),+ });+ }),+ ] as const;+ }+ if (sessions.size === 0) {+ yield* setFrameCaptureBackgroundThrottling(false);+ }+ const scope =+ consumer === "picture-in-picture" ? yield* Scope.fork(parentScope, "sequential") : null;+ if (scope !== null) {+ yield* Effect.forkIn(Effect.forever(captureNextFrame), scope);}return [- false,+ consumer === "picture-in-picture",replaceMap(sessions, (copy) => {copy.set(tabId, {- ...current,- consumers: new Set([...current.consumers, consumer]),+ scope,+ consumers: new Set([consumer]),+ lastPictureInPictureFrame: null,});}),] as const;- }- if (sessions.size === 0) {- yield* setFrameCaptureBackgroundThrottling(false);- }- const scope = yield* Scope.fork(parentScope, "sequential");- yield* Effect.forkIn(Effect.forever(captureNextFrame), scope);- return [- true,- replaceMap(sessions, (copy) => {- copy.set(tabId, {- scope,- consumers: new Set([consumer]),- lastPictureInPictureFrame: null,- });- }),- ] as const;- });- }).pipe(Effect.uninterruptible);- if (!created) return;+ });+ },+ ).pipe(Effect.uninterruptible);+ if (!captureInitialFrame) return;yield* capturePreviewFrame(tabId).pipe(Effect.catch((error) =>Effect.logWarning("Initial background preview frame was not ready; capture will retry.", {@@ -3090,11 +3100,77 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function});const startRecording = Effect.fn("PreviewManager.startRecording")(function* (tabId: string) {- yield* startFrameCapture(tabId, "recording");+ if ((yield* Ref.get(closingTabIdsRef)).has(tabId)) {+ return yield* new PreviewTabNotFoundError({ tabId });+ }+ return yield* withTabLifecycleLock(+ tabId,+ Effect.gen(function* () {+ yield* startFrameCapture(tabId, "recording");+ const wc = yield* requireWebContents(tabId);+ const requestWebContents = wc.hostWebContents;+ if (requestWebContents === null) {+ return yield* new PreviewMainWindowClosedError({ tabId });+ }+ const measuredSize = yield* attemptPromise(+ {+ operation: "recording.measureSource",+ tabId,+ webContentsId: wc.id,+ },+ () => wc.executeJavaScript(RECORDING_SOURCE_SIZE_EXPRESSION, true),+ );+ if (+ typeof measuredSize !== "object" ||+ measuredSize === null ||+ !("width" in measuredSize) ||+ !("height" in measuredSize) ||+ typeof measuredSize.width !== "number" ||+ typeof measuredSize.height !== "number" ||+ !Number.isInteger(measuredSize.width) ||+ !Number.isInteger(measuredSize.height) ||+ measuredSize.width <= 0 ||+ measuredSize.height <= 0+ ) {+ return yield* new PreviewRecordingSourceSizeUnavailableError({+ tabId,+ webContentsId: wc.id,+ });+ }+ yield* attemptPromise(+ {+ operation: "recording.warmSource",+ tabId,+ webContentsId: wc.id,+ },+ () => wc.capturePage().then(() => undefined),+ ).pipe(Effect.retry({ times: 1 }), Effect.ignore);+ const currentWebContents = yield* requireWebContents(tabId);+ if (currentWebContents !== wc || wc.isDestroyed()) {+ return yield* new PreviewWebContentsNotFoundError({+ tabId,+ webContentsId: wc.id,+ });+ }+ const sourceId = yield* attempt(+ {+ operation: "recording.getMediaSourceId",+ tabId,+ webContentsId: wc.id,+ },+ () => wc.getMediaSourceId(requestWebContents),+ );+ return {+ sourceId,+ width: measuredSize.width,+ height: measuredSize.height,+ } satisfies DesktopPreviewRecordingSource;+ }).pipe(Effect.onError(() => stopFrameCapture(tabId, "recording").pipe(Effect.ignore))),+ );});const stopRecording = Effect.fn("PreviewManager.stopRecording")(function* (tabId: string) {- yield* stopFrameCapture(tabId, "recording");+ yield* withTabLifecycleLock(tabId, stopFrameCapture(tabId, "recording"));});const saveRecording = Effect.fn("PreviewManager.saveRecording")(function* (@@ -3104,7 +3180,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function) {const [createdAt, millis] = yield* Effect.all([currentIso, currentMillis]);const id = `browser-recording-${millis.toString(36)}`;- const extension = mimeType.includes("mp4") ? "mp4" : "webm";+ const extension = recordingFileExtension(mimeType);const artifactPath = path.join(resolvedArtifactDirectory, `${id}.${extension}`);yield* fileSystem.makeDirectory(resolvedArtifactDirectory, { recursive: true }).pipe(Effect.mapError(@@ -3904,6 +3980,15 @@ export class PreviewMainWindowClosedError extends Schema.TaggedErrorClass<Previe}}+export class PreviewRecordingSourceSizeUnavailableError extends Schema.TaggedErrorClass<PreviewRecordingSourceSizeUnavailableError>()(+ "PreviewRecordingSourceSizeUnavailableError",+ { tabId: Schema.String, webContentsId: Schema.Number },+) {+ override get message(): string {+ return `Preview media source dimensions are unavailable for tab ${this.tabId}`;+ }+}+export class PreviewOperationError extends Schema.TaggedErrorClass<PreviewOperationError>()("PreviewOperationError",{@@ -4111,6 +4196,7 @@ export const PreviewManagerError = Schema.Union([PreviewWebContentsNotFoundError,PreviewWebviewNotInitializedError,PreviewMainWindowClosedError,+ PreviewRecordingSourceSizeUnavailableError,PreviewOperationError,PreviewArtifactPathOutsideDirectoryError,PreviewArtifactImageLoadError,@@ -4188,7 +4274,9 @@ export class PreviewManager extends Context.Service<readonly copyArtifactToClipboard: (path: string) => Effect.Effect<void, PreviewManagerError>;readonly openPictureInPicture: (tabId: string) => Effect.Effect<void, PreviewManagerError>;readonly closePictureInPicture: (tabId: string) => Effect.Effect<void, PreviewManagerError>;- readonly startRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;+ readonly startRecording: (+ tabId: string,+ ) => Effect.Effect<DesktopPreviewRecordingSource, PreviewManagerError>;readonly stopRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;readonly saveRecording: (tabId: string,diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.tsindex e32a5e2d080..736311eb464 100644--- a/apps/desktop/src/settings/DesktopClientSettings.test.ts+++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts@@ -17,6 +17,7 @@ const clientSettings: ClientSettings = {browserDefaultViewport: { _tag: "preset", width: 1024, height: 600, presetId: "nest-hub" },browserDefaultZoomFactor: 1.25,browserDefaultAppearance: "dark",+ browserRecordingFrameRate: 60,browserAutoShowFloatingPreview: false,confirmQuit: true,confirmThreadArchive: true,diff --git a/apps/web/src/browser/browserRecording.test.ts b/apps/web/src/browser/browserRecording.test.tsindex ed954942a87..f45a69c601c 100644--- a/apps/web/src/browser/browserRecording.test.ts+++ b/apps/web/src/browser/browserRecording.test.ts@@ -1,77 +1,37 @@import { EnvironmentId, ThreadId } from "@t3tools/contracts";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";-const {- events,- frameSubscription,- onFrame,- registrySet,- save,- startScreencast,- stopScreencast,- surfaceState,-} = vi.hoisted(() => {- const events: string[] = [];- type Frame = {- readonly tabId: string;- readonly data: string;- readonly width: number;- readonly height: number;- readonly receivedAt: string;- };- const frameSubscription: { listener: ((frame: Frame) => void) | null } = {- listener: null,- };- const surfaceState = {- byTabId: {} as Record<string, unknown>,- };- return {- events,- frameSubscription,- onFrame: vi.fn((listener: (frame: Frame) => void) => {- frameSubscription.listener = listener;- return () => {- if (frameSubscription.listener === listener) frameSubscription.listener = null;- };- }),- registrySet: vi.fn((_atom: unknown, value: { readonly tabIds: ReadonlySet<string> }) => {- events.push(- value.tabIds.size === 0 ? "clear" : `publish:${Array.from(value.tabIds).join(",")}`,- );- }),- save: vi.fn(async (tabId: string) => ({- id: "recording-test",- tabId,- path: "/tmp/recording-test.webm",- mimeType: "video/webm" as const,- sizeBytes: 0,- createdAt: "2026-06-26T00:00:00.000Z",- })),- startScreencast: vi.fn(async (tabId: string) => {- events.push("start-screencast");- const surface = surfaceState.byTabId[tabId] as- | {- readonly content?: { readonly width: number; readonly height: number };- readonly rect?: { readonly width: number; readonly height: number };- }- | undefined;- const size = surface?.content ?? surface?.rect;- frameSubscription.listener?.({+const { clientSettings, events, getUserMedia, registrySet, save, startScreencast, stopScreencast } =+ vi.hoisted(() => {+ const events: string[] = [];+ return {+ clientSettings: { browserRecordingFrameRate: 30 as 30 | 60 },+ events,+ getUserMedia: vi.fn(),+ registrySet: vi.fn((_atom: unknown, value: { readonly tabIds: ReadonlySet<string> }) => {+ events.push(+ value.tabIds.size === 0 ? "clear" : `publish:${Array.from(value.tabIds).join(",")}`,+ );+ }),+ save: vi.fn(async (tabId: string) => ({+ id: "recording-test",tabId,- data: "initial-frame",- width: size?.width ?? 1280,- height: size?.height ?? 800,- receivedAt: "2026-06-26T00:00:00.000Z",- });- }),- stopScreencast: vi.fn(async () => undefined),- surfaceState,- };-});+ path: "/tmp/recording-test.webm",+ mimeType: "video/webm" as const,+ sizeBytes: 0,+ createdAt: "2026-06-26T00:00:00.000Z",+ })),+ startScreencast: vi.fn(async (tabId: string) => {+ events.push("start-screencast");+ return { sourceId: `source:${tabId}`, width: 1000, height: 620 };+ }),+ stopScreencast: vi.fn(async () => undefined),+ };+ });vi.mock("~/components/preview/previewBridge", () => ({previewBridge: {- recording: { onFrame, save, startScreencast, stopScreencast },+ recording: { onFrame: vi.fn(), save, startScreencast, stopScreencast },},}));@@ -79,32 +39,49 @@ vi.mock("~/rpc/atomRegistry", () => ({appAtomRegistry: { set: registrySet },}));-vi.mock("./browserSurfaceStore", () => ({- useBrowserSurfaceStore: {- getState: () => surfaceState,- },+vi.mock("~/hooks/useSettings", () => ({+ ensureClientSettingsHydrated: vi.fn(async () => undefined),+ getClientSettings: () => clientSettings,}));import {- BROWSER_RECORDING_FIRST_FRAME_SIZE_TIMEOUT_MS,+ BROWSER_RECORDING_PAINT_SETTLE_TIMEOUT_MS,BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS,+ BrowserRecordingCaptureTimeoutError,BrowserRecordingConflictError,+ BrowserRecordingFormatUnavailableError,findActiveBrowserRecordingRuntimeTabId,readActiveBrowserRecordingTabIds,readActiveBrowserRecordingTargets,startBrowserRecording,stopBrowserRecording,} from "./browserRecording";+import { useBrowserSurfaceStore } from "./browserSurfaceStore";import { previewRuntimeTabId } from "./previewRuntimeTabId";class FakeMediaRecorder {- static isTypeSupported(): boolean {- return true;+ static readonly instances: FakeMediaRecorder[] = [];+ static supportedTypes = new Set(["video/webm;codecs=vp9"]);+ static outputMimeType: string | undefined;+ static stopError: unknown;+ static isTypeSupported(type: string): boolean {+ return this.supportedTypes.has(type);}state: RecordingState = "inactive";+ readonly mimeType: string;+ readonly stream: MediaStream;+ readonly options: MediaRecorderOptions | undefined;private readonly listeners = new Map<string, Set<EventListenerOrEventListenerObject>>();+ constructor(stream: MediaStream, options?: MediaRecorderOptions) {+ this.stream = stream;+ this.options = options;+ this.mimeType =+ FakeMediaRecorder.outputMimeType ?? options?.mimeType ?? "video/browser-default";+ FakeMediaRecorder.instances.push(this);+ }+addEventListener(type: string, listener: EventListenerOrEventListenerObject): void {const listeners = this.listeners.get(type) ?? new Set();listeners.add(listener);@@ -116,6 +93,7 @@ class FakeMediaRecorder {}stop(): void {+ if (FakeMediaRecorder.stopError !== undefined) throw FakeMediaRecorder.stopError;this.state = "inactive";for (const listener of this.listeners.get("stop") ?? []) {if (typeof listener === "function") listener(new Event("stop"));@@ -124,52 +102,31 @@ class FakeMediaRecorder {}}-const emitRecordingFrame = () => {- frameSubscription.listener?.({- tabId: "recording-tab",- data: "startup-frame",- width: 800,- height: 600,- receivedAt: "2026-06-26T00:00:00.000Z",- });-};-describe("browser recording", () => {+ let animationFrameCount = 0;+beforeEach(() => {events.length = 0;- frameSubscription.listener = null;- surfaceState.byTabId = {- "recording-tab": {- visible: true,- rect: { x: 0, y: 0, width: 800, height: 600 },- content: { x: 0, y: 0, width: 800, height: 600, scale: 1, scrollLeft: 0, scrollTop: 0 },- },- };vi.clearAllMocks();+ FakeMediaRecorder.instances.length = 0;+ FakeMediaRecorder.supportedTypes = new Set(["video/webm;codecs=vp9"]);+ FakeMediaRecorder.outputMimeType = undefined;+ FakeMediaRecorder.stopError = undefined;+ clientSettings.browserRecordingFrameRate = 30;+ animationFrameCount = 0;vi.stubGlobal("window", globalThis);+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ animationFrameCount += 1;+ callback(animationFrameCount);+ return animationFrameCount;+ });+ vi.stubGlobal("cancelAnimationFrame", vi.fn());vi.stubGlobal("MediaRecorder", FakeMediaRecorder as unknown as typeof MediaRecorder);- class ImmediateImage {- private loadListener: EventListenerOrEventListenerObject | undefined;-- addEventListener(type: string, listener: EventListenerOrEventListenerObject): void {- if (type === "load") this.loadListener = listener;- }-- set src(_value: string) {- const event = new Event("load");- if (typeof this.loadListener === "function") this.loadListener(event);- else this.loadListener?.handleEvent(event);- }- }- vi.stubGlobal("Image", ImmediateImage as unknown as typeof Image);- vi.stubGlobal("document", {- createElement: () => ({- width: 0,- height: 0,- captureStream: () => ({}),- getContext: () => ({ drawImage: vi.fn(), fillRect: vi.fn(), fillStyle: "" }),- }),+ getUserMedia.mockResolvedValue({+ getTracks: () => [{ stop: vi.fn() }],});+ vi.stubGlobal("navigator", { mediaDevices: { getUserMedia } });+ useBrowserSurfaceStore.setState({ activityByTabId: {}, byTabId: {} });});afterEach(() => {@@ -185,146 +142,189 @@ describe("browser recording", () => {expect(startupEvents).toEqual(["publish:recording-tab", "start-screencast"]);});- it("records a hidden tab without requiring it to become visible", async () => {- surfaceState.byTabId = {- "recording-tab": {- visible: false,- rect: { x: 0, y: 0, width: 800, height: 600 },- content: { x: 0, y: 0, width: 800, height: 600, scale: 1, scrollLeft: 0, scrollTop: 0 },- },- };+ it("paints and holds a hidden browser surface for the recording lifetime", async () => {+ startScreencast.mockImplementationOnce(async (tabId: string) => {+ expect(animationFrameCount).toBe(2);+ expect(useBrowserSurfaceStore.getState().activityByTabId[tabId]).toBe(1);+ return { sourceId: `source:${tabId}`, width: 1000, height: 620 };+ });+ getUserMedia.mockImplementationOnce(async () => {+ expect(animationFrameCount).toBe(2);+ expect(useBrowserSurfaceStore.getState().activityByTabId["background-tab"]).toBe(1);+ return { getTracks: () => [{ stop: vi.fn() }] };+ });- await startBrowserRecording("recording-tab");- const startupEvents = [...events];+ await startBrowserRecording("background-tab");+ expect(useBrowserSurfaceStore.getState().activityByTabId["background-tab"]).toBe(1);- expect(startScreencast).toHaveBeenCalledWith("recording-tab");- await stopBrowserRecording("recording-tab");- expect(startupEvents).toEqual(["publish:recording-tab", "start-screencast"]);+ await stopBrowserRecording("background-tab");+ expect(useBrowserSurfaceStore.getState().activityByTabId["background-tab"]).toBeUndefined();});- it("fails startup instead of locking a fallback size when no frame arrives", async () => {+ it("bounds compositor warmup when animation frames are paused", async () => {vi.useFakeTimers();- startScreencast.mockImplementationOnce(async () => {- events.push("start-screencast");- });+ const cancelAnimationFrame = vi.fn();+ vi.stubGlobal(+ "requestAnimationFrame",+ vi.fn(() => 42),+ );+ vi.stubGlobal("cancelAnimationFrame", cancelAnimationFrame);- const startPromise = startBrowserRecording("recording-tab");- const rejection = expect(startPromise).rejects.toMatchObject({- operation: "wait-first-frame",- tabId: "recording-tab",+ const startPromise = startBrowserRecording("hidden-window-tab");+ await vi.advanceTimersByTimeAsync(BROWSER_RECORDING_PAINT_SETTLE_TIMEOUT_MS);++ await startPromise;+ expect(cancelAnimationFrame).toHaveBeenCalledWith(42);+ await stopBrowserRecording("hidden-window-tab");+ });++ it("records the native tab stream at the preview's current dimensions", async () => {+ const stopTrack = vi.fn();+ const stream = { getTracks: () => [{ stop: stopTrack }] } as unknown as MediaStream;+ getUserMedia.mockResolvedValueOnce(stream);++ await startBrowserRecording("recording-tab");++ expect(getUserMedia).toHaveBeenCalledWith({+ audio: false,+ video: {+ mandatory: {+ chromeMediaSource: "tab",+ chromeMediaSourceId: "source:recording-tab",+ minWidth: 1000,+ maxWidth: 1000,+ minHeight: 620,+ maxHeight: 620,+ maxFrameRate: 30,+ },+ },});- await Promise.resolve();- await vi.advanceTimersByTimeAsync(BROWSER_RECORDING_FIRST_FRAME_SIZE_TIMEOUT_MS);+ expect(FakeMediaRecorder.instances[0]?.stream).toBe(stream);- await rejection;- expect(stopScreencast).toHaveBeenCalledWith("recording-tab");- expect(events.at(-1)).toBe("clear");+ await stopBrowserRecording("recording-tab");+ expect(stopTrack).toHaveBeenCalledOnce();});- it("fixes hidden recording dimensions before MediaRecorder starts", async () => {- const drawImage = vi.fn();- const fillRect = vi.fn();- let capturedStreamSize: { readonly width: number; readonly height: number } | undefined;- const canvas = {- width: 0,- height: 0,- captureStream: () => {- capturedStreamSize = { width: canvas.width, height: canvas.height };- return {};+ it("uses the configured recording frame rate", async () => {+ clientSettings.browserRecordingFrameRate = 60;++ await startBrowserRecording("recording-tab");++ expect(getUserMedia).toHaveBeenCalledWith({+ audio: false,+ video: {+ mandatory: expect.objectContaining({ maxFrameRate: 60 }),},- getContext: () => ({ drawImage, fillRect, fillStyle: "" }),- };- vi.stubGlobal("document", {- createElement: () => canvas,});- surfaceState.byTabId = {};- startScreencast.mockImplementationOnce(async (tabId: string) => {- events.push("start-screencast");- frameSubscription.listener?.({- tabId,- data: "captured-frame",- width: 390,- height: 844,- receivedAt: "2026-06-26T00:00:00.000Z",- });+ await stopBrowserRecording("recording-tab");+ });++ it("stops the native stream when MediaRecorder cleanup fails", async () => {+ const stopTrack = vi.fn();+ getUserMedia.mockResolvedValueOnce({+ getTracks: () => [{ stop: stopTrack }],});await startBrowserRecording("recording-tab");+ FakeMediaRecorder.stopError = new Error("stop failed");- expect(canvas).toMatchObject({ width: 390, height: 844 });- expect(capturedStreamSize).toEqual({ width: 390, height: 844 });- expect(drawImage).toHaveBeenCalledWith(expect.anything(), 0, 0, 390, 844);-- frameSubscription.listener?.({+ await expect(stopBrowserRecording("recording-tab")).rejects.toMatchObject({+ operation: "cleanup",tabId: "recording-tab",- data: "different-sized-frame",- width: 1280,- height: 720,- receivedAt: "2026-06-26T00:00:01.000Z",});+ expect(stopTrack).toHaveBeenCalledOnce();+ });- expect(canvas).toMatchObject({ width: 390, height: 844 });- expect(fillRect).toHaveBeenLastCalledWith(0, 0, 390, 844);+ it("uses the best supported encoder and saves the recorder's actual format", async () => {+ FakeMediaRecorder.supportedTypes = new Set([+ "video/mp4;codecs=avc1.42e01e",+ "video/webm;codecs=vp9",+ "video/webm;codecs=av1",+ ]);+ FakeMediaRecorder.outputMimeType = "video/webm;codecs=av01";+ await startBrowserRecording("recording-tab");await stopBrowserRecording("recording-tab");- });- it("draws the newest decoded frames without starving behind decode latency", async () => {- const drawImage = vi.fn();- class DeferredImage {- static readonly instances: DeferredImage[] = [];- private loadListener: EventListenerOrEventListenerObject | undefined;+ expect(FakeMediaRecorder.instances[0]?.options).toEqual({+ mimeType: "video/webm;codecs=av1",+ });+ expect(save).toHaveBeenCalledWith(+ "recording-tab",+ "video/webm;codecs=av01",+ expect.any(Uint8Array),+ );+ });- constructor() {- DeferredImage.instances.push(this);- }+ it("lets the browser select the format when no preferred encoding is supported", async () => {+ FakeMediaRecorder.supportedTypes = new Set();+ FakeMediaRecorder.outputMimeType = "video/platform-default";- addEventListener(type: string, listener: EventListenerOrEventListenerObject): void {- if (type === "load") this.loadListener = listener;- }+ await startBrowserRecording("recording-tab");+ await stopBrowserRecording("recording-tab");- set src(_value: string) {}+ expect(FakeMediaRecorder.instances[0]?.options).toBeUndefined();+ expect(save).toHaveBeenCalledWith(+ "recording-tab",+ "video/platform-default",+ expect.any(Uint8Array),+ );+ });- finishLoading(): void {- const event = new Event("load");- if (typeof this.loadListener === "function") this.loadListener(event);- else this.loadListener?.handleEvent(event);- }- }- vi.stubGlobal("Image", DeferredImage as unknown as typeof Image);- vi.stubGlobal("document", {- createElement: () => ({- width: 0,- height: 0,- captureStream: () => ({}),- getContext: () => ({ drawImage, fillRect: vi.fn(), fillStyle: "" }),- }),- });+ it("reports when MediaRecorder provides no output format", async () => {+ FakeMediaRecorder.supportedTypes = new Set();+ FakeMediaRecorder.outputMimeType = "";await startBrowserRecording("recording-tab");- frameSubscription.listener?.({++ await expect(stopBrowserRecording("recording-tab")).rejects.toBeInstanceOf(+ BrowserRecordingFormatUnavailableError,+ );+ expect(save).not.toHaveBeenCalled();+ expect(readActiveBrowserRecordingTabIds()).toEqual(new Set());+ });++ it("releases the native capture lease when stream acquisition fails", async () => {+ getUserMedia.mockRejectedValueOnce(new Error("capture failed"));++ await expect(startBrowserRecording("recording-tab")).rejects.toMatchObject({+ operation: "capture-media-stream",tabId: "recording-tab",- data: "second-frame",- width: 800,- height: 600,- receivedAt: "2026-06-26T00:00:01.000Z",});- frameSubscription.listener?.({++ expect(stopScreencast).toHaveBeenCalledWith("recording-tab");+ expect(events.at(-1)).toBe("clear");+ });++ it("times out stalled stream acquisition and stops a late stream", async () => {+ vi.useFakeTimers();+ let finishCapture!: (stream: MediaStream) => void;+ const stopTrack = vi.fn();+ getUserMedia.mockImplementationOnce(+ () =>+ new Promise<MediaStream>((resolve) => {+ finishCapture = resolve;+ }),+ );++ const startPromise = startBrowserRecording("recording-tab");+ await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalledOnce());+ const rejection = expect(startPromise).rejects.toMatchObject({+ _tag: "BrowserRecordingCaptureTimeoutError",tabId: "recording-tab",- data: "third-frame",- width: 800,- height: 600,- receivedAt: "2026-06-26T00:00:02.000Z",+ timeoutMs: BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS,});+ await vi.advanceTimersByTimeAsync(BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS);- DeferredImage.instances[1]?.finishLoading();- expect(drawImage).toHaveBeenCalledOnce();- DeferredImage.instances[2]?.finishLoading();- expect(drawImage).toHaveBeenCalledTimes(2);- DeferredImage.instances[0]?.finishLoading();- expect(drawImage).toHaveBeenCalledTimes(2);+ await rejection;+ await expect(startPromise).rejects.toBeInstanceOf(BrowserRecordingCaptureTimeoutError);+ expect(stopScreencast).toHaveBeenCalledWith("recording-tab");+ expect(readActiveBrowserRecordingTabIds()).toEqual(new Set());+ expect(useBrowserSurfaceStore.getState().activityByTabId["recording-tab"]).toBeUndefined();- await stopBrowserRecording("recording-tab");+ finishCapture({ getTracks: () => [{ stop: stopTrack }] } as unknown as MediaStream);+ await vi.advanceTimersByTimeAsync(0);+ expect(stopTrack).toHaveBeenCalledOnce();});it("records separate tabs concurrently", async () => {@@ -336,22 +336,12 @@ describe("browser recording", () => {environmentId: EnvironmentId.make("environment-recording"),threadId: ThreadId.make("thread-recording-second"),};- surfaceState.byTabId = {- ...surfaceState.byTabId,- "recording-tab-2": {- visible: false,- rect: { x: 0, y: 0, width: 390, height: 844 },- content: { x: 0, y: 0, width: 390, height: 844, scale: 1, scrollLeft: 0, scrollTop: 0 },- },- };-await Promise.all([startBrowserRecording("recording-tab", firstThreadRef),startBrowserRecording("recording-tab-2", secondThreadRef),]);expect(startScreencast).toHaveBeenCalledTimes(2);- expect(onFrame).toHaveBeenCalledOnce();expect(events).toContain("publish:recording-tab,recording-tab-2");expect(readActiveBrowserRecordingTabIds()).toEqual(new Set(["recording-tab", "recording-tab-2"]),@@ -372,22 +362,6 @@ describe("browser recording", () => {threadId: ThreadId.make("thread-recording-scoped"),};const runtimeTabId = previewRuntimeTabId(threadRef, "epoch-a", "tab_1");- surfaceState.byTabId = {- [runtimeTabId]: {- visible: false,- rect: { x: 0, y: 0, width: 1280, height: 800 },- content: {- x: 0,- y: 0,- width: 1280,- height: 800,- scale: 1,- scrollLeft: 0,- scrollTop: 0,- },- },- };-await startBrowserRecording(runtimeTabId, threadRef, "tab_1");expect(startScreencast).toHaveBeenCalledWith(runtimeTabId);@@ -408,18 +382,12 @@ describe("browser recording", () => {it("does not report success for a second start while the first is still starting", async () => {let finishStartingScreencast: (() => void) | undefined;- startScreencast.mockImplementationOnce(async (tabId: string) => {+ startScreencast.mockImplementationOnce(async () => {events.push("start-screencast");- frameSubscription.listener?.({- tabId,- data: "initial-frame",- width: 800,- height: 600,- receivedAt: "2026-06-26T00:00:00.000Z",- });await new Promise<void>((resolve) => {finishStartingScreencast = resolve;});+ return { sourceId: "source:recording-tab", width: 1000, height: 620 };});const firstStart = startBrowserRecording("recording-tab");@@ -484,7 +452,7 @@ describe("browser recording", () => {await new Promise<void>((resolve) => {finishStartingScreencast = resolve;});- emitRecordingFrame();+ return { sourceId: "source:recording-tab", width: 1000, height: 620 };});const startPromise = startBrowserRecording("recording-tab");@@ -508,7 +476,7 @@ describe("browser recording", () => {await new Promise<void>((resolve) => {finishStartingScreencast = resolve;});- emitRecordingFrame();+ return { sourceId: "source:recording-tab", width: 1000, height: 620 };});const firstStart = startBrowserRecording("recording-tab");@@ -535,7 +503,7 @@ describe("browser recording", () => {await new Promise<void>((resolve) => {finishStartingScreencast = resolve;});- emitRecordingFrame();+ return { sourceId: "source:recording-tab", width: 1000, height: 620 };});stopScreencast.mockRejectedValueOnce(new Error("initial stop failed"));@@ -569,15 +537,14 @@ describe("browser recording", () => {await new Promise<void>((resolve) => {finishStartingScreencast = resolve;});- emitRecordingFrame();+ return { sourceId: "source:recording-tab", width: 1000, height: 620 };});const startPromise = startBrowserRecording("recording-tab");- expect(startScreencast).toHaveBeenCalledOnce();+ await vi.waitFor(() => expect(startScreencast).toHaveBeenCalledOnce());const stopPromise = stopBrowserRecording("recording-tab");- await Promise.resolve();- await Promise.resolve();+ await vi.advanceTimersByTimeAsync(0);expect(stopScreencast).not.toHaveBeenCalled();const rejection = expect(stopPromise).rejects.toMatchObject({@@ -593,6 +560,7 @@ describe("browser recording", () => {);finishStartingScreencast?.();+ await vi.advanceTimersByTimeAsync(32);await startPromise;const cleanupResult = await stopBrowserRecording("recording-tab");expect(cleanupResult).toBeNull();diff --git a/apps/web/src/browser/browserRecording.ts b/apps/web/src/browser/browserRecording.tsindex 33d4610da12..e242f25c7d2 100644--- a/apps/web/src/browser/browserRecording.ts+++ b/apps/web/src/browser/browserRecording.ts@@ -1,6 +1,6 @@import type {DesktopPreviewRecordingArtifact,- DesktopPreviewRecordingFrame,+ DesktopPreviewRecordingSource,ScopedThreadRef,} from "@t3tools/contracts";import { useAtomValue } from "@effect/atom-react";@@ -8,8 +8,10 @@ import * as Schema from "effect/Schema";import { Atom } from "effect/unstable/reactivity";import { previewBridge } from "~/components/preview/previewBridge";+import { ensureClientSettingsHydrated, getClientSettings } from "~/hooks/useSettings";import { appAtomRegistry } from "~/rpc/atomRegistry";-import { useBrowserSurfaceStore } from "./browserSurfaceStore";++import { acquireBrowserSurfaceActivity } from "./browserSurfaceStore";export class BrowserRecordingUnavailableError extends Schema.TaggedErrorClass<BrowserRecordingUnavailableError>()("BrowserRecordingUnavailableError",@@ -34,16 +36,24 @@ export class BrowserRecordingConflictError extends Schema.TaggedErrorClass<Brows}}-export class BrowserRecordingCanvasUnavailableError extends Schema.TaggedErrorClass<BrowserRecordingCanvasUnavailableError>()(- "BrowserRecordingCanvasUnavailableError",+export class BrowserRecordingFormatUnavailableError extends Schema.TaggedErrorClass<BrowserRecordingFormatUnavailableError>()(+ "BrowserRecordingFormatUnavailableError",+ { tabId: Schema.String },+) {+ override get message(): string {+ return `MediaRecorder did not report an output format for tab ${this.tabId}.`;+ }+}++export class BrowserRecordingCaptureTimeoutError extends Schema.TaggedErrorClass<BrowserRecordingCaptureTimeoutError>()(+ "BrowserRecordingCaptureTimeoutError",{tabId: Schema.String,- width: Schema.Number,- height: Schema.Number,+ timeoutMs: Schema.Number,},) {override get message(): string {- return `Browser recording canvas ${this.width}x${this.height} is unavailable for tab ${this.tabId}.`;+ return `Browser recording media capture for tab ${this.tabId} did not settle within ${this.timeoutMs}ms.`;}}@@ -52,11 +62,10 @@ export class BrowserRecordingOperationError extends Schema.TaggedErrorClass<Brow{operation: Schema.Literals(["initialize-media-recorder",- "subscribe-frames",+ "capture-media-stream","start-media-recorder","start-screencast","stop-screencast",- "wait-first-frame","wait-startup","stop-media-recorder","save-artifact",@@ -72,6 +81,7 @@ export class BrowserRecordingOperationError extends Schema.TaggedErrorClass<Brow}const isBrowserRecordingOperationError = Schema.is(BrowserRecordingOperationError);+const isBrowserRecordingCaptureTimeoutError = Schema.is(BrowserRecordingCaptureTimeoutError);type BrowserRecordingLifecycle =| { readonly phase: "starting" }@@ -82,23 +92,17 @@ type BrowserRecordingLifecycle =};interface ActiveRecording {- /** Desktop-scoped identity used by capture and surface stores. */+ /** Desktop-scoped identity used by the native capture lease. */readonly tabId: string;/** Server-local identity returned by preview automation tools. */readonly serverTabId: string;readonly threadRef: ScopedThreadRef | null;- readonly canvas: HTMLCanvasElement;- readonly context: CanvasRenderingContext2D;readonly chunks: Blob[];readonly startedAt: string;readonly startupSettled: Promise<void>;- readonly firstFrameSize: Promise<"frame" | "cancelled">;- readonly settleFirstFrameSize: (outcome: "frame" | "cancelled") => void;+ releaseSurfaceActivity: (() => void) | null;+ stream: MediaStream | null;recorder: MediaRecorder | null;- mimeType: string | null;- frameSizeEstablished: boolean;- frameSequence: number;- lastDrawnFrameSequence: number;lifecycle: BrowserRecordingLifecycle;}@@ -120,7 +124,6 @@ export function useActiveBrowserRecordingTabIds(): ReadonlySet<string> {}const activeRecordings = new Map<string, ActiveRecording>();-let unsubscribeFrames: (() => void) | null = null;const publishActiveRecordingTabIds = (): void => {appAtomRegistry.set(activeBrowserRecordingTabIdsAtom, {@@ -129,7 +132,7 @@ const publishActiveRecordingTabIds = (): void => {};export const BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS = 5_000;-export const BROWSER_RECORDING_FIRST_FRAME_SIZE_TIMEOUT_MS = 5_000;+export const BROWSER_RECORDING_PAINT_SETTLE_TIMEOUT_MS = 250;export function readActiveBrowserRecordingTabIds(threadRef?: ScopedThreadRef): ReadonlySet<string> {const tabIds = new Set<string>();@@ -167,55 +170,38 @@ export function findActiveBrowserRecordingRuntimeTabId();}-const preferredMimeType = (): string => {- const candidates = ["video/mp4;codecs=avc1.42E01E", "video/webm;codecs=vp9", "video/webm"];- return candidates.find((candidate) => MediaRecorder.isTypeSupported(candidate)) ?? "video/webm";+const preferredMimeTypes = [+ "video/webm;codecs=av1",+ "video/webm;codecs=vp9",+ "video/mp4;codecs=avc1.640028",+ "video/mp4;codecs=avc1.42e01e",+ "video/webm;codecs=vp8",+ "video/webm",+] as const;++const createMediaRecorder = (stream: MediaStream): MediaRecorder => {+ const mimeType = preferredMimeTypes.find((candidate) => MediaRecorder.isTypeSupported(candidate));+ return mimeType ? new MediaRecorder(stream, { mimeType }) : new MediaRecorder(stream);};-const drawFrame = (frame: DesktopPreviewRecordingFrame): void => {- const recording = activeRecordings.get(frame.tabId);- if (!recording) return;- if (- !Number.isFinite(frame.width) ||- !Number.isFinite(frame.height) ||- frame.width <= 0 ||- frame.height <= 0- ) {- return;- }- const width = Math.max(1, Math.round(frame.width));- const height = Math.max(1, Math.round(frame.height));- if (!recording.frameSizeEstablished) {- recording.canvas.width = width;- recording.canvas.height = height;- recording.frameSizeEstablished = true;- recording.settleFirstFrameSize("frame");- }- const frameSequence = ++recording.frameSequence;- const image = new Image();- image.addEventListener(- "load",- () => {- if (- activeRecordings.get(frame.tabId) !== recording ||- frameSequence <= recording.lastDrawnFrameSequence- ) {- return;- }- recording.lastDrawnFrameSequence = frameSequence;- const scale = Math.min(recording.canvas.width / width, recording.canvas.height / height);- const targetWidth = width * scale;- const targetHeight = height * scale;- const targetX = (recording.canvas.width - targetWidth) / 2;- const targetY = (recording.canvas.height - targetHeight) / 2;- recording.context.fillStyle = "#000000";- recording.context.fillRect(0, 0, recording.canvas.width, recording.canvas.height);- recording.context.drawImage(image, targetX, targetY, targetWidth, targetHeight);- },- { once: true },- );- image.src = `data:image/jpeg;base64,${frame.data}`;-};+const captureTabMediaStream = (+ source: DesktopPreviewRecordingSource,+ frameRate: number,+): Promise<MediaStream> =>+ navigator.mediaDevices.getUserMedia({+ audio: false,+ video: {+ mandatory: {+ chromeMediaSource: "tab",+ chromeMediaSourceId: source.sourceId,+ minWidth: source.width,+ maxWidth: source.width,+ minHeight: source.height,+ maxHeight: source.height,+ maxFrameRate: frameRate,+ },+ } as unknown as MediaTrackConstraints,+ });const stopMediaRecorder = async (recorder: MediaRecorder | null): Promise<void> => {if (!recorder || recorder.state === "inactive") return;@@ -226,17 +212,76 @@ const stopMediaRecorder = async (recorder: MediaRecorder | null): Promise<void>await stopped;};+const stopMediaStream = (stream: MediaStream | null): void => {+ for (const track of stream?.getTracks() ?? []) track.stop();+};++const captureTabMediaStreamWithTimeout = async (+ tabId: string,+ source: DesktopPreviewRecordingSource,+ frameRate: number,+): Promise<MediaStream> => {+ let acceptStream = true;+ let timeoutId: number | null = null;+ const streamPromise = captureTabMediaStream(source, frameRate).then((stream) => {+ if (!acceptStream) stopMediaStream(stream);+ return stream;+ });+ try {+ return await Promise.race([+ streamPromise,+ new Promise<never>((_, reject) => {+ timeoutId = window.setTimeout(+ () =>+ reject(+ new BrowserRecordingCaptureTimeoutError({+ tabId,+ timeoutMs: BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS,+ }),+ ),+ BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS,+ );+ }),+ ]);+ } finally {+ acceptStream = false;+ if (timeoutId !== null) window.clearTimeout(timeoutId);+ }+};+const clearActiveRecording = (recording: ActiveRecording): void => {+ recording.releaseSurfaceActivity?.();+ recording.releaseSurfaceActivity = null;if (activeRecordings.get(recording.tabId) !== recording) return;- recording.settleFirstFrameSize("cancelled");activeRecordings.delete(recording.tabId);- if (activeRecordings.size === 0) {- unsubscribeFrames?.();- unsubscribeFrames = null;- }publishActiveRecordingTabIds();};+const waitForBrowserRecordingPaint = async (): Promise<void> => {+ let firstFrameId: number | null = null;+ let secondFrameId: number | null = null;+ let timeoutId: number | null = null;+ const painted = new Promise<void>((resolve) => {+ firstFrameId = window.requestAnimationFrame(() => {+ firstFrameId = null;+ secondFrameId = window.requestAnimationFrame(() => {+ secondFrameId = null;+ resolve();+ });+ });+ });+ const timedOut = new Promise<void>((resolve) => {+ timeoutId = window.setTimeout(resolve, BROWSER_RECORDING_PAINT_SETTLE_TIMEOUT_MS);+ });+ try {+ await Promise.race([painted, timedOut]);+ } finally {+ if (timeoutId !== null) window.clearTimeout(timeoutId);+ if (firstFrameId !== null) window.cancelAnimationFrame(firstFrameId);+ if (secondFrameId !== null) window.cancelAnimationFrame(secondFrameId);+ }+};+const cleanupFailedRecordingStart = async (bridge: NonNullable<typeof previewBridge>,recording: ActiveRecording,@@ -251,6 +296,11 @@ const cleanupFailedRecordingStart = async (await stopMediaRecorder(recording.recorder);} catch (error) {errors.push(error);+ }+ try {+ stopMediaStream(recording.stream);+ } catch (error) {+ errors.push(error);} finally {clearActiveRecording(recording);}@@ -276,19 +326,6 @@ const recordingStartupCancelledError = (const isRecordingStarting = (recording: ActiveRecording): boolean =>activeRecordings.get(recording.tabId) === recording && recording.lifecycle.phase === "starting";-const waitForFirstFrameSize = async (recording: ActiveRecording): Promise<boolean> => {- if (recording.frameSizeEstablished) return true;- let timeout: ReturnType<typeof setTimeout> | null = null;- const outcome = await Promise.race([- recording.firstFrameSize,- new Promise<"timeout">((resolve) => {- timeout = setTimeout(() => resolve("timeout"), BROWSER_RECORDING_FIRST_FRAME_SIZE_TIMEOUT_MS);- }),- ]);- if (timeout !== null) clearTimeout(timeout);- return outcome === "frame";-};-const waitForRecordingStartupToSettle = async (recording: ActiveRecording): Promise<void> => {let timeout: ReturnType<typeof setTimeout> | null = null;try {@@ -339,62 +376,35 @@ export async function startBrowserRecording(activeTabId: activeLogicalRecording,});}- const surface = useBrowserSurfaceStore.getState().byTabId[tabId];- const recordingSize = surface?.content ?? surface?.rect;- const canvas = document.createElement("canvas");- canvas.width = Math.max(1, recordingSize?.width ?? 1280);- canvas.height = Math.max(1, recordingSize?.height ?? 800);- const context = canvas.getContext("2d", { alpha: false });- if (!context) {- throw new BrowserRecordingCanvasUnavailableError({- tabId,- width: canvas.width,- height: canvas.height,- });- }const startedAt = new Date().toISOString();const chunks: Blob[] = [];let settleStartup: (() => void) | undefined;const startupSettled = new Promise<void>((resolve) => {settleStartup = resolve;});- let settleFirstFrameSize: ((outcome: "frame" | "cancelled") => void) | undefined;- const firstFrameSize = new Promise<"frame" | "cancelled">((resolve) => {- settleFirstFrameSize = resolve;- });+ const releaseSurfaceActivity = acquireBrowserSurfaceActivity(tabId);const recording: ActiveRecording = {tabId,serverTabId,threadRef,- canvas,- context,chunks,startedAt,startupSettled,- firstFrameSize,- settleFirstFrameSize: (outcome) => settleFirstFrameSize?.(outcome),+ releaseSurfaceActivity,+ stream: null,recorder: null,- mimeType: null,- frameSizeEstablished: false,- frameSequence: 0,- lastDrawnFrameSequence: 0,lifecycle: { phase: "starting" },};activeRecordings.set(tabId, recording);publishActiveRecordingTabIds();try {+ const frameRatePromise = ensureClientSettingsHydrated().then(+ () => getClientSettings().browserRecordingFrameRate,+ );+ const [frameRate] = await Promise.all([frameRatePromise, waitForBrowserRecordingPaint()]);+ let source: DesktopPreviewRecordingSource;try {- unsubscribeFrames ??= bridge.recording.onFrame(drawFrame);- } catch (cause) {- clearActiveRecording(recording);- throw new BrowserRecordingOperationError({- operation: "subscribe-frames",- tabId,- cause,- });- }- try {- await bridge.recording.startScreencast(tabId);+ source = await bridge.recording.startScreencast(tabId);} catch (cause) {if (!isRecordingStarting(recording)) {throw recordingStartupCancelledError(recording, cause);@@ -425,34 +435,29 @@ export async function startBrowserRecording(throw recordingStartupCancelledError(recording);};await throwIfStartupCancelled();- const hasFirstFrame = await waitForFirstFrameSize(recording);- await throwIfStartupCancelled();- if (!hasFirstFrame) {- const cause = new Error(`No valid recording frame arrived for tab ${tabId}.`);+ try {+ recording.stream = await captureTabMediaStreamWithTimeout(tabId, source, frameRate);+ } catch (cause) {const cleanupCause = await cleanupFailedRecordingStart(bridge, recording);+ if (isBrowserRecordingCaptureTimeoutError(cause) && cleanupCause === undefined) throw cause;throw new BrowserRecordingOperationError({- operation: "wait-first-frame",+ operation: "capture-media-stream",tabId,cause:cleanupCause === undefined? cause: new AggregateError([cause, cleanupCause],- `Browser recording frame wait and cleanup failed for tab ${tabId}.`,+ `Browser media capture and cleanup failed for tab ${tabId}.`,{ cause },),});}+ await throwIfStartupCancelled();- let mimeType: string;let recorder: MediaRecorder;try {- mimeType = preferredMimeType();- recorder = new MediaRecorder(canvas.captureStream(12), {- mimeType,- videoBitsPerSecond: 4_000_000,- });- recording.mimeType = mimeType;+ recorder = createMediaRecorder(recording.stream);recording.recorder = recorder;recorder.addEventListener("dataavailable", (event) => {if (event.data.size > 0) chunks.push(event.data);@@ -520,7 +525,7 @@ const finalizeBrowserRecording = async (cause,});}- if (!recording.recorder || !recording.mimeType) {+ if (!recording.recorder) {result = { _tag: "Success", artifact: null };} else {try {@@ -532,11 +537,17 @@ const finalizeBrowserRecording = async (cause,});}+ const mimeType =+ recording.recorder.mimeType ||+ recording.chunks.find((chunk) => chunk.type.length > 0)?.type;+ if (!mimeType) {+ throw new BrowserRecordingFormatUnavailableError({ tabId });+ }try {- const blob = new Blob(recording.chunks, { type: recording.mimeType });+ const blob = new Blob(recording.chunks, { type: mimeType });const artifact = await bridge.recording.save(tabId,- recording.mimeType,+ mimeType,new Uint8Array(await blob.arrayBuffer()),);result = { _tag: "Success", artifact };@@ -560,18 +571,34 @@ const finalizeBrowserRecording = async (throw result.error;}- let cleanupError: BrowserRecordingOperationError | undefined;+ const cleanupErrors: unknown[] = [];try {await stopMediaRecorder(recording.recorder);} catch (cause) {- cleanupError = new BrowserRecordingOperationError({- operation: "stop-media-recorder",- tabId,- cause,- });+ cleanupErrors.push(cause);+ }+ try {+ stopMediaStream(recording.stream);+ } catch (cause) {+ cleanupErrors.push(cause);} finally {clearActiveRecording(recording);}+ const cleanupError =+ cleanupErrors.length === 0+ ? undefined+ : new BrowserRecordingOperationError({+ operation: "cleanup",+ tabId,+ cause:+ cleanupErrors.length === 1+ ? cleanupErrors[0]+ : new AggregateError(+ cleanupErrors,+ `Browser recording media cleanup failed for tab ${tabId}.`,+ { cause: cleanupErrors[0] },+ ),+ });if (result._tag === "Failure") {if (cleanupError) {@@ -598,6 +625,7 @@ const discardBrowserRecording = async (try {await bridge.recording.stopScreencast(recording.tabId).catch(() => undefined);await stopMediaRecorder(recording.recorder).catch(() => undefined);+ stopMediaStream(recording.stream);return null;} finally {clearActiveRecording(recording);diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsxindex f3b773f7bc8..d6c52a21e0a 100644--- a/apps/web/src/components/settings/IntegrationsSettings.tsx+++ b/apps/web/src/components/settings/IntegrationsSettings.tsx@@ -7,7 +7,9 @@* @module IntegrationsSettings*/import {+ BROWSER_RECORDING_FRAME_RATES,DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,+ DEFAULT_BROWSER_RECORDING_FRAME_RATE,DEFAULT_BROWSER_VIEWPORT,DEFAULT_PREVIEW_APPEARANCE,DEFAULT_UNIFIED_SETTINGS,@@ -355,6 +357,51 @@ function BrowserAppearanceSetting({ disabled }: { readonly disabled: boolean }));}+function BrowserRecordingFrameRateSetting({ disabled }: { readonly disabled: boolean }) {+ const frameRate = useClientSettings((settings) => settings.browserRecordingFrameRate);+ const updateSettings = useUpdatePrimarySettings();++ return (+ <SettingsRow+ {...searchableSetting("browser-recording-frame-rate")}+ description="Maximum frame rate for browser recordings. 30 fps is the default and uses less CPU and storage; 60 fps captures smoother motion."+ resetAction={+ !disabled && frameRate !== DEFAULT_BROWSER_RECORDING_FRAME_RATE ? (+ <SettingResetButton+ label="browser recording frame rate"+ onClick={() =>+ updateSettings({ browserRecordingFrameRate: DEFAULT_BROWSER_RECORDING_FRAME_RATE })+ }+ />+ ) : null+ }+ control={+ <Select+ disabled={disabled}+ value={String(frameRate)}+ onValueChange={(value) => {+ const next = BROWSER_RECORDING_FRAME_RATES.find((rate) => String(rate) === value);+ if (next !== undefined) {+ updateSettings({ browserRecordingFrameRate: next });+ }+ }}+ >+ <SelectTrigger className="w-full sm:w-40" aria-label="Browser recording frame rate">+ <SelectValue>{frameRate} fps</SelectValue>+ </SelectTrigger>+ <SelectPopup align="end" alignItemWithTrigger={false}>+ {BROWSER_RECORDING_FRAME_RATES.map((rate) => (+ <SelectItem hideIndicator key={rate} value={String(rate)}>+ {rate} fps+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ }+ />+ );+}+function AgentBrowserAccessSetting() {const settings = usePrimarySettings();const updateSettings = useUpdatePrimarySettings();@@ -461,6 +508,7 @@ export function IntegrationsSettingsPanel() {<BrowserViewportSetting disabled={previewDefaultsDisabled} /><BrowserZoomSetting disabled={previewDefaultsDisabled} /><BrowserAppearanceSetting disabled={previewDefaultsDisabled} />+ <BrowserRecordingFrameRateSetting disabled={previewDefaultsDisabled} /><BrowserAutoShowFloatingPreviewSetting disabled={previewDefaultsDisabled} /></>);diff --git a/apps/web/src/components/settings/SettingsPanels.logic.test.ts b/apps/web/src/components/settings/SettingsPanels.logic.test.tsindex 5c715eb4eb2..490d248595f 100644--- a/apps/web/src/components/settings/SettingsPanels.logic.test.ts+++ b/apps/web/src/components/settings/SettingsPanels.logic.test.ts@@ -268,9 +268,16 @@ describe("getChangedBrowserSettingLabels", () => {browserDefaultViewport: { _tag: "freeform", width: 900, height: 600 },browserDefaultZoomFactor: 1.5,browserDefaultAppearance: "dark",+ browserRecordingFrameRate: 60,browserAutoShowFloatingPreview: !DEFAULT_UNIFIED_SETTINGS.browserAutoShowFloatingPreview,}),- ).toEqual(["Browser viewport", "Browser zoom", "Browser appearance", "Floating preview"]);+ ).toEqual([+ "Browser viewport",+ "Browser zoom",+ "Browser appearance",+ "Recording frame rate",+ "Floating preview",+ ]);});});diff --git a/apps/web/src/components/settings/SettingsPanels.logic.ts b/apps/web/src/components/settings/SettingsPanels.logic.tsindex a5d5d995849..331391dbc46 100644--- a/apps/web/src/components/settings/SettingsPanels.logic.ts+++ b/apps/web/src/components/settings/SettingsPanels.logic.ts@@ -114,6 +114,7 @@ export type BrowserDefaultSettings = Pick<| "browserDefaultViewport"| "browserDefaultZoomFactor"| "browserDefaultAppearance"+ | "browserRecordingFrameRate"| "browserAutoShowFloatingPreview">;@@ -151,6 +152,9 @@ export function getChangedBrowserSettingLabels(settings: BrowserDefaultSettings)...(settings.browserDefaultAppearance !== DEFAULT_UNIFIED_SETTINGS.browserDefaultAppearance? ["Browser appearance"]: []),+ ...(settings.browserRecordingFrameRate !== DEFAULT_UNIFIED_SETTINGS.browserRecordingFrameRate+ ? ["Recording frame rate"]+ : []),...(settings.browserAutoShowFloatingPreview !==DEFAULT_UNIFIED_SETTINGS.browserAutoShowFloatingPreview? ["Floating preview"]diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex b486a0eefea..dbb2d96daa0 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -553,6 +553,7 @@ export function useSettingsRestore(onRestored?: () => void) {settings.browserDefaultViewport,settings.browserDefaultZoomFactor,settings.browserDefaultAppearance,+ settings.browserRecordingFrameRate,settings.browserAutoShowFloatingPreview,settings.appearanceContrast,settings.enableAgentBrowserAccess,@@ -688,6 +689,7 @@ export function useSettingsRestore(onRestored?: () => void) {browserDefaultViewport: DEFAULT_UNIFIED_SETTINGS.browserDefaultViewport,browserDefaultZoomFactor: DEFAULT_UNIFIED_SETTINGS.browserDefaultZoomFactor,browserDefaultAppearance: DEFAULT_UNIFIED_SETTINGS.browserDefaultAppearance,+ browserRecordingFrameRate: DEFAULT_UNIFIED_SETTINGS.browserRecordingFrameRate,browserAutoShowFloatingPreview: DEFAULT_UNIFIED_SETTINGS.browserAutoShowFloatingPreview,// Re-granted like any other default. The confirmation dialog lists it by// name, so a user restoring defaults is told the agent regains accessdiff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.tsindex 9ed854b87d2..c560d0b43d9 100644--- a/apps/web/src/components/settings/settingsSearch.test.ts+++ b/apps/web/src/components/settings/settingsSearch.test.ts@@ -98,4 +98,12 @@ describe("searchSettings", () => {targetId: "appearance",});});++ it("routes browser recording quality to integrations", () => {+ expect(searchSettings("recording frame rate")[0]).toMatchObject({+ id: "browser-recording-frame-rate",+ to: "/settings/integrations",+ targetId: "browser",+ });+ });});diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.tsindex b924f5f6a51..1e0d715f68b 100644--- a/apps/web/src/components/settings/settingsSearch.ts+++ b/apps/web/src/components/settings/settingsSearch.ts@@ -237,6 +237,12 @@ export const SETTINGS_SEARCH_ITEMS = [to: "/settings/integrations",targetId: "browser",},+ {+ id: "browser-recording-frame-rate",+ title: "Browser recording frame rate",+ to: "/settings/integrations",+ targetId: "browser",+ },{id: "browser-auto-show-floating-preview",title: "Auto-show floating preview",diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.tsindex 19300aac328..b7847927833 100644--- a/packages/contracts/src/ipc.ts+++ b/packages/contracts/src/ipc.ts@@ -734,6 +734,19 @@ export const DesktopPreviewRecordingFrameSchema: Schema.Codec<DesktopPreviewRecoreceivedAt: Schema.String,});+export interface DesktopPreviewRecordingSource {+ sourceId: string;+ width: number;+ height: number;+}++export const DesktopPreviewRecordingSourceSchema: Schema.Codec<DesktopPreviewRecordingSource> =+ Schema.Struct({+ sourceId: Schema.String,+ width: Schema.Int.check(Schema.isGreaterThan(0)),+ height: Schema.Int.check(Schema.isGreaterThan(0)),+ });+export interface DesktopPreviewRecordingArtifact {id: string;tabId: string;@@ -1215,7 +1228,7 @@ export interface DesktopPreviewBridge {close: (tabId: string) => Promise<void>;};recording: {- startScreencast: (tabId: string) => Promise<void>;+ startScreencast: (tabId: string) => Promise<DesktopPreviewRecordingSource>;stopScreencast: (tabId: string) => Promise<void>;save: (tabId: string,diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.tsindex 32851e735a3..e94a66435b1 100644--- a/packages/contracts/src/settings.test.ts+++ b/packages/contracts/src/settings.test.ts@@ -66,6 +66,26 @@ describe("ClientSettings word wrap", () => {});});+describe("ClientSettings browser recording frame rate", () => {+ it("defaults to 30 fps", () => {+ expect(decodeClientSettings({}).browserRecordingFrameRate).toBe(30);+ });++ it.each([30, 60])("accepts a supported frame rate: %s", (frameRate) => {+ expect(+ decodeClientSettings({ browserRecordingFrameRate: frameRate }).browserRecordingFrameRate,+ ).toBe(frameRate);+ expect(+ decodeClientSettingsPatch({ browserRecordingFrameRate: frameRate }).browserRecordingFrameRate,+ ).toBe(frameRate);+ });++ it.each([24, 59, 120])("rejects an unsupported frame rate: %s", (frameRate) => {+ expect(() => decodeClientSettings({ browserRecordingFrameRate: frameRate })).toThrow();+ expect(() => decodeClientSettingsPatch({ browserRecordingFrameRate: frameRate })).toThrow();+ });+});+describe("ClientSettings glass opacity", () => {it("defaults to a readable translucent surface", () => {expect(decodeClientSettings({}).glassOpacity).toBe(80);diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex b6b09574bfe..b721ce976d1 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -147,11 +147,16 @@ export type DefaultThemePreference = typeof DefaultThemePreference.Type;/*** Defaults for the in-app preview browser, applied whenever a tab is opened* without an explicit viewport/zoom/appearance — by the user opening a browser- * tab, or by an agent calling `preview_open` with no size. Client-local- * because the Chromium guest they configure is desktop-local.+ * tab, or by an agent calling `preview_open` with no size. Recording quality is+ * client-local for the same reason: the Chromium guest being captured belongs+ * to the desktop app.*/export const DEFAULT_BROWSER_VIEWPORT: PreviewViewportSetting = FILL_PREVIEW_VIEWPORT;export const DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW = true;+export const BROWSER_RECORDING_FRAME_RATES = [30, 60] as const;+export const BrowserRecordingFrameRate = Schema.Literals(BROWSER_RECORDING_FRAME_RATES);+export type BrowserRecordingFrameRate = typeof BrowserRecordingFrameRate.Type;+export const DEFAULT_BROWSER_RECORDING_FRAME_RATE: BrowserRecordingFrameRate = 30;export const ClientSettingsSchema = Schema.Struct({appearanceContrast: AppearanceContrast.pipe(@@ -166,6 +171,9 @@ export const ClientSettingsSchema = Schema.Struct({browserDefaultAppearance: PreviewAppearancePreference.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_PREVIEW_APPEARANCE)),),+ browserRecordingFrameRate: BrowserRecordingFrameRate.pipe(+ Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_RECORDING_FRAME_RATE)),+ ),/*** Whether an agent opening a preview pops the floating mini player into* view. Only applies when the agent didn't ask either way — an explicit@@ -926,6 +934,7 @@ export const ClientSettingsPatch = Schema.Struct({browserDefaultViewport: Schema.optionalKey(PreviewViewportSetting),browserDefaultZoomFactor: Schema.optionalKey(PreviewZoomFactor),browserDefaultAppearance: Schema.optionalKey(PreviewAppearancePreference),+ browserRecordingFrameRate: Schema.optionalKey(BrowserRecordingFrameRate),browserAutoShowFloatingPreview: Schema.optionalKey(Schema.Boolean),confirmQuit: Schema.optionalKey(Schema.Boolean),confirmThreadArchive: Schema.optionalKey(Schema.Boolean),