diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 8e96129293fc8..5ef5c1e2dce9c 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -780,6 +780,36 @@ describe("DesktopBrowserHost", () => { }), ); + it.effect("keeps painting while the agent's turn is using the tab", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const painting = yield* watchPainting(host); + const turn = (active: boolean) => + host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active })); + + yield* turn(true); + // Playwright's actionability check waits for the page's next frame. + yield* command(host, 1, "Runtime.callFunctionOn"); + yield* settle; + expect(painting).toEqual([true]); + + yield* turn(false); + yield* settle; + expect(painting).toEqual([true, false]); + + // Outside a turn the guest paints until the agent goes idle. + yield* command(host, 2, "Input.dispatchMouseEvent"); + yield* settle; + expect(painting).toEqual([true, false, true]); + debuggee.release(); + yield* settle; + yield* TestClock.adjust("1 minute"); + expect(painting).toEqual([true, false, true, false]); + }).pipe(Effect.scoped), + ); + it.effect("lets a guest throttle when Chromium refuses a viewer's screencast", () => Effect.gen(function* () { const host = yield* makeDrawnHost; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index ce5d7074a786c..68fc37b6cf2fd 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -237,20 +237,22 @@ export const make = Effect.gen(function* () { // The agent pauses to think between steps; its tab stays focused until the turn ends. if (tab.agentUsed && agentTurns.has(tab.key.threadId)) return; tab.agentUsed = false; + syncPainting(tab); if (tabs.get(keyOf(tab.key)) === tab) setFocusEmulation(tab, false); }), ); }; /** - * Electron composites no offscreen guest, so its screenshot or screencast waits for a frame - * that never comes. The client paints the guest behind the app while one is pending; the - * capture then finishes on its own, and the guest goes back offscreen once none is. + * Electron composites no offscreen guest, so a capture, or agent input that waits on the + * next frame, waits forever. The client paints the guest behind the app while one is pending + * or the agent drives it, and the guest goes back offscreen once neither holds. */ const syncPainting = (tab: AttachedTab) => { const active = tabs.get(keyOf(tab.key)) === tab && - (tab.screencasts.size > 0 || + (tab.agentUsed || + tab.screencasts.size > 0 || tab.capturing.size > 0 || tab.waitingScreenshots.some((waiting) => waiting.live())); if (tab.painting === active) return; @@ -387,6 +389,7 @@ export const make = Effect.gen(function* () { if (owner === undefined || !streamingOwners.has(owner)) { tab.agentUsed = true; tab.agentLedAt = performance.now(); + syncPainting(tab); } else if (method.startsWith("Input.") && !POINTER_TRAVEL.has(params["type"])) { tab.agentLedAt = Number.NEGATIVE_INFINITY; } diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 9c15a0e0a4a95..70b59ece79ab2 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -333,6 +333,7 @@ const makeTestPreviewWebContents = ( isCurrentlyAudible: () => false, on: vi.fn(), off: vi.fn(), + once: vi.fn(), ipc: { on: vi.fn(), off: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, @@ -1994,6 +1995,7 @@ describe("PreviewManager", () => { const hostThrottling = vi.fn(); yield* manager.setMainWindow({ isDestroyed: () => false, + isVisible: () => false, once: vi.fn(), webContents: { setBackgroundThrottling: hostThrottling }, } as never); @@ -2087,6 +2089,7 @@ describe("PreviewManager", () => { effectIt.effect("keeps every recorded guest unthrottled until its frame capture stops", () => withManager((manager) => Effect.gen(function* () { + let minimized = false; const setBackgroundThrottling = vi.fn(); const capturePage = vi.fn(async () => ({ toJPEG: () => Buffer.from("recording-frame"), @@ -2109,6 +2112,8 @@ describe("PreviewManager", () => { yield* manager.registerWebview("tab_capture_throttling_2", 42); yield* manager.setMainWindow({ isDestroyed: () => false, + isVisible: () => true, + isMinimized: () => minimized, once: vi.fn(), webContents: { setBackgroundThrottling }, } as never); @@ -2122,9 +2127,10 @@ describe("PreviewManager", () => { yield* manager.stopRecording("tab_capture_throttling_1"); expect(setBackgroundThrottling.mock.calls).toEqual([[false]]); - expect(firstWebContents.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); + expect(firstWebContents.setBackgroundThrottling.mock.calls).toEqual([[false], [false]]); expect(secondWebContents.setBackgroundThrottling.mock.calls).toEqual([[false]]); + minimized = true; yield* manager.stopRecording("tab_capture_throttling_2"); expect(setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); expect(secondWebContents.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); @@ -2132,6 +2138,51 @@ describe("PreviewManager", () => { ), ); + effectIt.effect("throttles idle preview guests while the app is hidden, not a recorded one", () => + withManager((manager) => + Effect.gen(function* () { + let hidden = false; + const capturePage = vi.fn(async () => ({ + toJPEG: () => Buffer.from("recording-frame"), + getSize: () => ({ width: 1280, height: 720 }), + })); + const host = makeTestHostWebContents(); + const recorded = makeTestPreviewWebContents(capturePage, 41, host); + const idle = makeTestPreviewWebContents(capturePage, 43, host); + const webContentsById = new Map([ + [41, recorded], + [43, idle], + ]); + fromId.mockImplementation((id) => + id === undefined ? null : (webContentsById.get(id) ?? null), + ); + yield* manager.prepareWebview(recorded as never); + yield* manager.prepareWebview(idle as never); + yield* manager.createTab("tab_hidden_recording"); + yield* manager.registerWebview("tab_hidden_recording", 41); + yield* manager.setMainWindow({ + isDestroyed: () => false, + isVisible: () => !hidden, + isMinimized: () => false, + once: vi.fn(), + webContents: { setBackgroundThrottling: vi.fn() }, + } as never); + yield* manager.startRecording("tab_hidden_recording"); + host.displayMediaHandler()?.({ frame: host.mainFrame }, () => {}); + + hidden = true; + yield* manager.syncGuestThrottling(); + expect(idle.setBackgroundThrottling.mock.calls).toEqual([[true]]); + expect(recorded.setBackgroundThrottling.mock.calls).toEqual([[false]]); + + hidden = false; + yield* manager.syncGuestThrottling(); + expect(idle.setBackgroundThrottling.mock.calls).toEqual([[true], [false]]); + expect(recorded.setBackgroundThrottling.mock.calls).toEqual([[false]]); + }), + ), + ); + effectIt.effect("does not commit failed starts and retries throttle restoration", () => withManager((manager) => Effect.gen(function* () { @@ -2145,6 +2196,7 @@ describe("PreviewManager", () => { yield* manager.createTab("tab_capture_throttling_failure"); yield* manager.registerWebview("tab_capture_throttling_failure", 42); yield* manager.setMainWindow({ + isVisible: () => false, isDestroyed: () => false, once: vi.fn(), webContents: { setBackgroundThrottling }, @@ -2195,6 +2247,7 @@ describe("PreviewManager", () => { yield* manager.createTab("tab_shutdown"); yield* manager.registerWebview("tab_shutdown", 42); yield* manager.setMainWindow({ + isVisible: () => false, isDestroyed: () => false, once: (event: string, listener: () => void) => windowEvents.set(event, listener), webContents: { setBackgroundThrottling: vi.fn() }, @@ -2221,6 +2274,7 @@ describe("PreviewManager", () => { let destroyed = false; const replacement = yield* manager .setMainWindow({ + isVisible: () => false, isDestroyed: () => destroyed, once: vi.fn(), webContents: { setBackgroundThrottling: vi.fn() }, @@ -2267,6 +2321,7 @@ describe("PreviewManager", () => { yield* manager.createTab("tab_replaced_window_close"); yield* manager.registerWebview("tab_replaced_window_close", 42); yield* manager.setMainWindow({ + isVisible: () => false, isDestroyed: () => false, once: vi.fn((event: string, listener: () => void) => { if (event === "closed") closeFirstWindow = listener; @@ -2274,6 +2329,7 @@ describe("PreviewManager", () => { webContents: { setBackgroundThrottling: firstWindowThrottling }, } as never); yield* manager.setMainWindow({ + isVisible: () => false, isDestroyed: () => false, once: vi.fn(), webContents: { setBackgroundThrottling: replacementWindowThrottling }, @@ -2313,6 +2369,7 @@ describe("PreviewManager", () => { yield* manager.registerWebview("tab_window_close_recording", 42); yield* manager.registerWebview("tab_window_close_race", 43); yield* manager.setMainWindow({ + isVisible: () => false, isDestroyed: () => false, once: vi.fn((event: string, listener: () => void) => { if (event === "closed") closeMainWindow = listener; @@ -2339,6 +2396,7 @@ describe("PreviewManager", () => { expect(grants).toEqual([{}]); yield* manager.setMainWindow({ + isVisible: () => false, isDestroyed: () => false, once: vi.fn(), webContents: { setBackgroundThrottling: replacementWindowThrottling }, @@ -2374,6 +2432,7 @@ describe("PreviewManager", () => { yield* manager.createTab("tab_window_close_warmup"); yield* manager.registerWebview("tab_window_close_warmup", 42); yield* manager.setMainWindow({ + isVisible: () => false, isDestroyed: () => false, once: vi.fn((event: string, listener: () => void) => { if (event === "closed") closeMainWindow = listener; @@ -2465,6 +2524,8 @@ describe("PreviewManager", () => { const manager = yield* PreviewManager.PreviewManager; yield* manager.setMainWindow({ isDestroyed: () => false, + isVisible: () => false, + isMinimized: () => false, once: vi.fn(), webContents: mainWebContents, } as never); diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 531e269a07f11..40cccfb52ad38 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -608,6 +608,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const displayMediaHandlerSessions = new WeakSet(); let frameCaptureWindowOpen = true; let currentMainWindow: BrowserWindow | undefined; + const previewGuests = new Set(); + const mainWindowOnScreen = () => { + const window = currentMainWindow; + return ( + window !== undefined && !window.isDestroyed() && window.isVisible() && !window.isMinimized() + ); + }; let mainWindowCleanupFiber: Fiber.Fiber | undefined; const tabLifecycleLocks = new Map< string, @@ -726,12 +733,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const restoreFrameCaptureWebContentsBackgroundThrottling = Effect.fnUntraced(function* ( webContentsIds: ReadonlySet, ) { + const enabled = !mainWindowOnScreen(); yield* Effect.forEach( webContentsIds, (webContentsId) => { const wc = webContents.fromId(webContentsId); if (!wc || wc.isDestroyed()) return Effect.void; - return setFrameCaptureWebContentsBackgroundThrottling(wc, true).pipe( + return setFrameCaptureWebContentsBackgroundThrottling(wc, enabled).pipe( Effect.retry({ times: 2 }), Effect.catch((error) => Effect.logWarning("Failed to restore preview webview frame capture throttling.", { @@ -744,6 +752,26 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function { concurrency: "unbounded", discard: true }, ); }); + /** + * Preview guests attach unthrottled so a parked page keeps its heartbeats while the app is on + * screen; a hidden app throttles them again, except a guest a capture still needs. + */ + const syncGuestThrottling = Effect.fn("PreviewManager.syncGuestThrottling")(function* () { + yield* SynchronizedRef.modifyEffect(frameCaptureSessionsRef, (sessions) => + Effect.gen(function* () { + const captured = new Set( + [...sessions.values()].flatMap((session) => [...session.unthrottledWebContentsIds]), + ); + const enabled = !mainWindowOnScreen(); + yield* Effect.forEach( + [...previewGuests].filter((wc) => !captured.has(wc.id)), + (wc) => setFrameCaptureWebContentsBackgroundThrottling(wc, enabled).pipe(Effect.ignore), + { discard: true }, + ); + return [undefined, sessions] as const; + }), + ); + }); const keepFrameCaptureWebContentsUnthrottled = Effect.fnUntraced(function* ( tabId: string, wc: Electron.WebContents, @@ -2091,6 +2119,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ) { yield* rendererHistory.register(wc, { surface: "preview" }); const webContentsId = wc.id; + previewGuests.add(wc); + if (currentMainWindow !== undefined && !mainWindowOnScreen()) { + yield* setFrameCaptureWebContentsBackgroundThrottling(wc, true).pipe(Effect.ignore); + } wc.on("did-start-navigation", (event) => { if (event.isMainFrame && !event.isSameDocument) guestLoadFailures.delete(webContentsId); }); @@ -2103,6 +2135,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); }); wc.once("destroyed", () => { + previewGuests.delete(wc); guestLoadFailures.delete(webContentsId); runFork( Effect.gen(function* () { @@ -3755,6 +3788,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function pickElement, updateAnnotationVoice, prepareWebview, + syncGuestThrottling, reapplyZoom, refresh, stopLoading, @@ -3956,6 +3990,7 @@ export class PreviewManager extends Context.Service< webContentsId: number, ) => Effect.Effect; readonly prepareWebview: (webContents: Electron.WebContents) => Effect.Effect; + readonly syncGuestThrottling: () => Effect.Effect; readonly navigate: (tabId: string, url: string) => Effect.Effect; readonly goBack: (tabId: string) => Effect.Effect; readonly goForward: (tabId: string) => Effect.Effect; @@ -4132,6 +4167,7 @@ export const make = Effect.gen(function* PreviewManagerMake() { closeTab: operations.closeTab, registerWebview: operations.registerWebview, prepareWebview: operations.prepareWebview, + syncGuestThrottling: operations.syncGuestThrottling, navigate: operations.navigate, goBack: operations.goBack, goForward: operations.goForward, diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index e4e426b1975ae..47ea3a4a42959 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -1560,6 +1560,7 @@ describe("DesktopWindow", () => { }); assert.deepEqual(webPreferences.additionalArguments, expected); + assert.strictEqual(webPreferences.backgroundThrottling, false); }).pipe(Effect.provide(layer)); }), ); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index c99fbb52c49e2..5ad472cf8eb50 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -635,6 +635,8 @@ export const make = Effect.gen(function* () { webPreferences.nodeIntegrationInSubFrames = false; webPreferences.contextIsolation = false; webPreferences.disableHtmlFullscreenWindowResize = true; + // A parked page keeps its timers while the app is on screen; see syncGuestThrottling. + webPreferences.backgroundThrottling = false; if (previewPasskeys.bridgeEnabled) { webPreferences.additionalArguments = [ ...(webPreferences.additionalArguments ?? []), @@ -648,6 +650,11 @@ export const make = Effect.gen(function* () { ]; } }); + const syncPreviewGuestThrottling = () => void runPromise(previewManager.syncGuestThrottling()); + window.on("hide", syncPreviewGuestThrottling); + window.on("show", syncPreviewGuestThrottling); + window.on("minimize", syncPreviewGuestThrottling); + window.on("restore", syncPreviewGuestThrottling); const contextMenuContents = new WeakSet(); const installContextMenu = ( diff --git a/apps/web/src/browser/HostedBrowserWebview.tsx b/apps/web/src/browser/HostedBrowserWebview.tsx index 766f94b597903..edfc5ac5d099d 100644 --- a/apps/web/src/browser/HostedBrowserWebview.tsx +++ b/apps/web/src/browser/HostedBrowserWebview.tsx @@ -14,7 +14,7 @@ import { import { usePreviewBridge } from "~/components/preview/usePreviewBridge"; import { useClientSettingsHydrated } from "~/hooks/useSettings"; import { useViewportSize } from "~/hooks/useViewportSize"; -import { cn, isMacPlatform } from "~/lib/utils"; +import { cn } from "~/lib/utils"; import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore"; import { useActiveBrowserRecordingTabIds } from "./browserRecording"; @@ -352,8 +352,6 @@ export function HostedBrowserWebview(props: { const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({ active, renderingActive, - // Electron 43 can permanently blank a macOS webview after `visibility: hidden`. - keepPaintableWhenInactive: isMacPlatform(navigator.platform), cornerRadius: presentation.cornerRadius, zIndex: presentation.zIndex, rect: lastRect, diff --git a/apps/web/src/browser/hostedBrowserWebviewStyle.ts b/apps/web/src/browser/hostedBrowserWebviewStyle.ts index f37c222b08e9c..628ff302e1d3a 100644 --- a/apps/web/src/browser/hostedBrowserWebviewStyle.ts +++ b/apps/web/src/browser/hostedBrowserWebviewStyle.ts @@ -21,21 +21,12 @@ const HIDDEN_BROWSER_WEBVIEW_OFFSET = -100_000; export function resolveHostedBrowserWebviewWrapperStyle(input: { readonly active: boolean; readonly renderingActive: boolean; - readonly keepPaintableWhenInactive?: boolean; readonly cornerRadius?: number; readonly zIndex?: number; readonly rect: BrowserSurfaceRect | null; readonly hiddenSize: HostedBrowserWebviewSize; }): HostedBrowserWebviewWrapperStyle { - const { - active, - cornerRadius = 0, - hiddenSize, - keepPaintableWhenInactive = false, - rect, - renderingActive, - zIndex = 30, - } = input; + const { active, cornerRadius = 0, hiddenSize, rect, renderingActive, zIndex = 30 } = input; if (active && rect) { return { left: rect.x, @@ -68,6 +59,6 @@ export function resolveHostedBrowserWebviewWrapperStyle(input: { height: hiddenSize.height, zIndex: -1, pointerEvents: "none", - visibility: keepPaintableWhenInactive ? "visible" : "hidden", + visibility: "hidden", }; } diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 962cfd089dd2b..2e2256455bcc0 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -619,7 +619,7 @@ export interface DesktopPreviewTabState { /** Chromium reports playback even when audioMuted is true. */ audible: boolean; controller: "human" | "agent" | "none"; - /** A screenshot or stream of the guest is pending, so the client keeps it painting while hidden. */ + /** A screenshot, stream, or agent command needs the guest, so the client keeps it painting while hidden. */ capturing: boolean; favicon?: DesktopPreviewFavicon; updatedAt: string;