fix(desktop): stop hidden previews draining battery (#8567)
This commit is contained in:
1 parent
a40aef4ccb
commit
ff1761012a
9 files changed
+113
-31
No files matched your search
@@ -29,6 +29,8 @@ export function ElectronBrowserHost() {
|
||||
previewState.serverEpoch,
|
||||
snapshot.tabId,
|
||||
),
|
||||
pictureInPicture:
|
||||
previewState.desktopByTabId[snapshot.tabId]?.pictureInPicture ?? false,
|
||||
zoomFactor: previewState.desktopByTabId[snapshot.tabId]?.zoomFactor ?? 1,
|
||||
}))
|
||||
: [];
|
||||
@@ -80,7 +82,7 @@ export function ElectronBrowserHost() {
|
||||
if (!isElectron) return null;
|
||||
return (
|
||||
<div className="contents" data-electron-browser-host>
|
||||
{sessions.map(({ threadRef, snapshot, runtimeTabId, zoomFactor }) => {
|
||||
{sessions.map(({ threadRef, snapshot, runtimeTabId, pictureInPicture, zoomFactor }) => {
|
||||
const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
|
||||
return (
|
||||
<HostedBrowserWebview
|
||||
@@ -90,6 +92,7 @@ export function ElectronBrowserHost() {
|
||||
runtimeTabId={runtimeTabId}
|
||||
initialUrl={url}
|
||||
viewport={snapshot.viewport ?? FILL_PREVIEW_VIEWPORT}
|
||||
pictureInPicture={pictureInPicture}
|
||||
zoomFactor={zoomFactor}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -9,6 +9,7 @@ import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
import { useActiveBrowserRecordingTabIds } from "./browserRecording";
|
||||
import {
|
||||
browserViewportSettingKey,
|
||||
resolveBrowserViewportLayout,
|
||||
@@ -47,9 +48,11 @@ export function HostedBrowserWebview(props: {
|
||||
readonly runtimeTabId: string;
|
||||
readonly initialUrl: string | null;
|
||||
readonly viewport: PreviewViewportSetting;
|
||||
readonly pictureInPicture: boolean;
|
||||
readonly zoomFactor: number;
|
||||
}) {
|
||||
const { threadRef, tabId, runtimeTabId, initialUrl, viewport, zoomFactor } = props;
|
||||
const { threadRef, tabId, runtimeTabId, initialUrl, viewport, pictureInPicture, zoomFactor } =
|
||||
props;
|
||||
const config = usePreviewWebviewConfig(threadRef.environmentId);
|
||||
const [initialSrc] = useState(() => initialUrl ?? "about:blank");
|
||||
const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
|
||||
@@ -70,6 +73,10 @@ export function HostedBrowserWebview(props: {
|
||||
};
|
||||
}),
|
||||
);
|
||||
const backgroundActivity = useBrowserSurfaceStore(
|
||||
(state) => (state.activityByTabId[runtimeTabId] ?? 0) > 0,
|
||||
);
|
||||
const recordingActive = useActiveBrowserRecordingTabIds().has(runtimeTabId);
|
||||
usePreviewBridge({ threadRef, tabId, runtimeTabId });
|
||||
|
||||
useEffect(() => {
|
||||
@@ -231,8 +238,10 @@ export function HostedBrowserWebview(props: {
|
||||
|
||||
if (!config) return null;
|
||||
|
||||
const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive;
|
||||
const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({
|
||||
active,
|
||||
renderingActive,
|
||||
cornerRadius: presentation.cornerRadius,
|
||||
rect: lastRect,
|
||||
hiddenSize,
|
||||
@@ -244,6 +253,7 @@ export function HostedBrowserWebview(props: {
|
||||
className="fixed overflow-hidden bg-muted/35"
|
||||
style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
|
||||
onScroll={syncContentPresentation}
|
||||
data-preview-rendering={renderingActive ? "active" : "suspended"}
|
||||
data-preview-viewport={runtimeTabId}
|
||||
>
|
||||
<div className="relative" style={{ width: layout.canvasWidth, height: layout.canvasHeight }}>
|
||||
|
||||
@@ -179,10 +179,10 @@ describe("browser recording", () => {
|
||||
|
||||
it("starts recording for a visible tab", async () => {
|
||||
await startBrowserRecording("recording-tab");
|
||||
|
||||
expect(events).toEqual(["start-screencast", "publish:recording-tab"]);
|
||||
const startupEvents = [...events];
|
||||
|
||||
await stopBrowserRecording("recording-tab");
|
||||
expect(startupEvents).toEqual(["publish:recording-tab", "start-screencast"]);
|
||||
});
|
||||
|
||||
it("records a hidden tab without requiring it to become visible", async () => {
|
||||
@@ -195,11 +195,11 @@ describe("browser recording", () => {
|
||||
};
|
||||
|
||||
await startBrowserRecording("recording-tab");
|
||||
const startupEvents = [...events];
|
||||
|
||||
expect(startScreencast).toHaveBeenCalledWith("recording-tab");
|
||||
expect(events).toEqual(["start-screencast", "publish:recording-tab"]);
|
||||
|
||||
await stopBrowserRecording("recording-tab");
|
||||
expect(startupEvents).toEqual(["publish:recording-tab", "start-screencast"]);
|
||||
});
|
||||
|
||||
it("fails startup instead of locking a fallback size when no frame arrives", async () => {
|
||||
|
||||
@@ -122,6 +122,12 @@ export function useActiveBrowserRecordingTabIds(): ReadonlySet<string> {
|
||||
const activeRecordings = new Map<string, ActiveRecording>();
|
||||
let unsubscribeFrames: (() => void) | null = null;
|
||||
|
||||
const publishActiveRecordingTabIds = (): void => {
|
||||
appAtomRegistry.set(activeBrowserRecordingTabIdsAtom, {
|
||||
tabIds: new Set(activeRecordings.keys()),
|
||||
});
|
||||
};
|
||||
|
||||
export const BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS = 5_000;
|
||||
export const BROWSER_RECORDING_FIRST_FRAME_SIZE_TIMEOUT_MS = 5_000;
|
||||
|
||||
@@ -228,9 +234,7 @@ const clearActiveRecording = (recording: ActiveRecording): void => {
|
||||
unsubscribeFrames?.();
|
||||
unsubscribeFrames = null;
|
||||
}
|
||||
appAtomRegistry.set(activeBrowserRecordingTabIdsAtom, {
|
||||
tabIds: new Set(activeRecordings.keys()),
|
||||
});
|
||||
publishActiveRecordingTabIds();
|
||||
};
|
||||
|
||||
const cleanupFailedRecordingStart = async (
|
||||
@@ -377,6 +381,7 @@ export async function startBrowserRecording(
|
||||
lifecycle: { phase: "starting" },
|
||||
};
|
||||
activeRecordings.set(tabId, recording);
|
||||
publishActiveRecordingTabIds();
|
||||
try {
|
||||
try {
|
||||
unsubscribeFrames ??= bridge.recording.onFrame(drawFrame);
|
||||
@@ -487,9 +492,6 @@ export async function startBrowserRecording(
|
||||
if (recording.lifecycle.phase === "starting") {
|
||||
recording.lifecycle = { phase: "recording" };
|
||||
}
|
||||
appAtomRegistry.set(activeBrowserRecordingTabIdsAtom, {
|
||||
tabIds: new Set(activeRecordings.keys()),
|
||||
});
|
||||
return startedAt;
|
||||
} finally {
|
||||
settleStartup?.();
|
||||
|
||||
@@ -2,13 +2,25 @@ import { beforeEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
acquireBrowserSurface,
|
||||
acquireBrowserSurfaceActivity,
|
||||
resolveBrowserSurfacePanelRect,
|
||||
useBrowserSurfaceStore,
|
||||
} from "./browserSurfaceStore";
|
||||
|
||||
describe("browserSurfaceStore", () => {
|
||||
beforeEach(() => {
|
||||
useBrowserSurfaceStore.setState({ byTabId: {} });
|
||||
useBrowserSurfaceStore.setState({ activityByTabId: {}, byTabId: {} });
|
||||
});
|
||||
|
||||
it("keeps concurrent background work active until every lease is released", () => {
|
||||
const first = acquireBrowserSurfaceActivity("background-browser");
|
||||
const second = acquireBrowserSurfaceActivity("background-browser");
|
||||
|
||||
first();
|
||||
expect(useBrowserSurfaceStore.getState().activityByTabId["background-browser"]).toBe(1);
|
||||
|
||||
second();
|
||||
expect(useBrowserSurfaceStore.getState().activityByTabId["background-browser"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("freezes the source content dimensions for a fitted presentation", () => {
|
||||
|
||||
@@ -29,7 +29,9 @@ export interface BrowserSurfaceContentPresentation {
|
||||
}
|
||||
|
||||
interface BrowserSurfaceStoreState {
|
||||
readonly activityByTabId: Record<string, number>;
|
||||
readonly byTabId: Record<string, BrowserSurfacePresentation>;
|
||||
readonly acquireActivity: (tabId: string) => () => void;
|
||||
readonly claim: (tabId: string, owner: symbol, fitSourceContent: boolean) => void;
|
||||
readonly present: (
|
||||
tabId: string,
|
||||
@@ -63,7 +65,28 @@ const rectEquals = (left: BrowserSurfaceRect | null, right: BrowserSurfaceRect):
|
||||
left.height === right.height;
|
||||
|
||||
export const useBrowserSurfaceStore = create<BrowserSurfaceStoreState>()((set) => ({
|
||||
activityByTabId: {},
|
||||
byTabId: {},
|
||||
acquireActivity: (tabId) => {
|
||||
let released = false;
|
||||
set((state) => ({
|
||||
activityByTabId: {
|
||||
...state.activityByTabId,
|
||||
[tabId]: (state.activityByTabId[tabId] ?? 0) + 1,
|
||||
},
|
||||
}));
|
||||
return () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
set((state) => {
|
||||
const count = state.activityByTabId[tabId] ?? 0;
|
||||
const activityByTabId = { ...state.activityByTabId };
|
||||
if (count <= 1) delete activityByTabId[tabId];
|
||||
else activityByTabId[tabId] = count - 1;
|
||||
return { activityByTabId };
|
||||
});
|
||||
};
|
||||
},
|
||||
claim: (tabId, owner, fitSourceContent) =>
|
||||
set((state) => {
|
||||
const current = state.byTabId[tabId];
|
||||
@@ -171,6 +194,9 @@ export const useBrowserSurfaceStore = create<BrowserSurfaceStoreState>()((set) =
|
||||
}),
|
||||
}));
|
||||
|
||||
export const acquireBrowserSurfaceActivity = (tabId: string): (() => void) =>
|
||||
useBrowserSurfaceStore.getState().acquireActivity(tabId);
|
||||
|
||||
export function acquireBrowserSurface(
|
||||
tabId: string,
|
||||
fitSourceContent = false,
|
||||
|
||||
@@ -10,6 +10,7 @@ describe("resolveHostedBrowserWebviewWrapperStyle", () => {
|
||||
expect(
|
||||
resolveHostedBrowserWebviewWrapperStyle({
|
||||
active: true,
|
||||
renderingActive: true,
|
||||
rect: { x: 12, y: 34, width: 800, height: 600 },
|
||||
hiddenSize: { width: 1280, height: 800 },
|
||||
}),
|
||||
@@ -27,6 +28,7 @@ describe("resolveHostedBrowserWebviewWrapperStyle", () => {
|
||||
expect(
|
||||
resolveHostedBrowserWebviewWrapperStyle({
|
||||
active: true,
|
||||
renderingActive: true,
|
||||
cornerRadius: 12,
|
||||
rect: { x: 12, y: 34, width: 360, height: 203 },
|
||||
hiddenSize: { width: 1280, height: 800 },
|
||||
@@ -40,9 +42,10 @@ describe("resolveHostedBrowserWebviewWrapperStyle", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an inactive webview paintable while moving it offscreen", () => {
|
||||
it("suspends painting for an inactive webview", () => {
|
||||
const style = resolveHostedBrowserWebviewWrapperStyle({
|
||||
active: false,
|
||||
renderingActive: false,
|
||||
rect: { x: 12, y: 34, width: 800, height: 600 },
|
||||
hiddenSize: { width: 393, height: 852 },
|
||||
});
|
||||
@@ -54,6 +57,25 @@ describe("resolveHostedBrowserWebviewWrapperStyle", () => {
|
||||
height: 852,
|
||||
zIndex: -1,
|
||||
pointerEvents: "none",
|
||||
visibility: "hidden",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an active background task paintable offscreen", () => {
|
||||
const style = resolveHostedBrowserWebviewWrapperStyle({
|
||||
active: false,
|
||||
renderingActive: true,
|
||||
rect: null,
|
||||
hiddenSize: { width: 1280, height: 800 },
|
||||
});
|
||||
|
||||
expect(style).toEqual({
|
||||
left: HIDDEN_BROWSER_WEBVIEW_OFFSET,
|
||||
top: HIDDEN_BROWSER_WEBVIEW_OFFSET,
|
||||
width: 1280,
|
||||
height: 800,
|
||||
zIndex: -1,
|
||||
pointerEvents: "none",
|
||||
visibility: "visible",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,18 +13,19 @@ export interface HostedBrowserWebviewWrapperStyle {
|
||||
readonly zIndex: number;
|
||||
readonly pointerEvents: "auto" | "none";
|
||||
readonly borderRadius?: number;
|
||||
readonly visibility?: "visible";
|
||||
readonly visibility?: "hidden" | "visible";
|
||||
}
|
||||
|
||||
export const HIDDEN_BROWSER_WEBVIEW_OFFSET = -100_000;
|
||||
|
||||
export function resolveHostedBrowserWebviewWrapperStyle(input: {
|
||||
readonly active: boolean;
|
||||
readonly renderingActive: boolean;
|
||||
readonly cornerRadius?: number;
|
||||
readonly rect: BrowserSurfaceRect | null;
|
||||
readonly hiddenSize: HostedBrowserWebviewSize;
|
||||
}): HostedBrowserWebviewWrapperStyle {
|
||||
const { active, cornerRadius = 0, hiddenSize, rect } = input;
|
||||
const { active, cornerRadius = 0, hiddenSize, rect, renderingActive } = input;
|
||||
if (active && rect) {
|
||||
return {
|
||||
left: rect.x,
|
||||
@@ -44,9 +45,6 @@ export function resolveHostedBrowserWebviewWrapperStyle(input: {
|
||||
height: hiddenSize.height,
|
||||
zIndex: -1,
|
||||
pointerEvents: "none",
|
||||
// Keep the guest CSS-visible even while physically offscreen. Electron
|
||||
// webviews can keep metadata/status alive under `visibility:hidden` while
|
||||
// CDP Runtime/Input commands stall, which breaks offscreen automation.
|
||||
visibility: "visible",
|
||||
visibility: renderingActive ? "visible" : "hidden",
|
||||
};
|
||||
}
|
||||
@@ -37,7 +37,10 @@ import {
|
||||
stopBrowserRecording,
|
||||
} from "~/browser/browserRecording";
|
||||
import { resolveBrowserRecordingStopTarget } from "~/browser/browserRecordingScope";
|
||||
import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
|
||||
import {
|
||||
acquireBrowserSurfaceActivity,
|
||||
useBrowserSurfaceStore,
|
||||
} from "~/browser/browserSurfaceStore";
|
||||
import { browserDefaultOpenViewport, resolveBrowserDefaults } from "~/browser/browserDefaults";
|
||||
import { runBrowserViewportMutation } from "~/browser/browserViewportActions";
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
@@ -98,7 +101,7 @@ const waitForDesktopOverlay = async (
|
||||
operation,
|
||||
requestId,
|
||||
});
|
||||
if (state.desktopByTabId[tabId] && previewBridge) {
|
||||
if (state.desktopByTabId[tabId] && previewBridge && isPreviewWebviewRendering(runtimeTabId)) {
|
||||
const status = await previewBridge.automation.status(runtimeTabId);
|
||||
if (status.available) return;
|
||||
}
|
||||
@@ -121,6 +124,11 @@ const findPreviewWebview = (tabId: string): ExecutablePreviewWebview | null =>
|
||||
(candidate) => candidate.getAttribute("data-preview-tab") === tabId,
|
||||
) ?? null;
|
||||
|
||||
const isPreviewWebviewRendering = (runtimeTabId: string): boolean => {
|
||||
const wrapper = findPreviewWebview(runtimeTabId)?.closest<HTMLElement>("[data-preview-viewport]");
|
||||
return wrapper?.getAttribute("data-preview-rendering") === "active";
|
||||
};
|
||||
|
||||
const readWebviewViewport = async (
|
||||
webview: ExecutablePreviewWebview,
|
||||
): Promise<PreviewRenderedViewportSize | null> => {
|
||||
@@ -212,8 +220,12 @@ const currentStatus = async (
|
||||
const visible = runtimeTabId
|
||||
? (useBrowserSurfaceStore.getState().byTabId[runtimeTabId]?.visible ?? false)
|
||||
: false;
|
||||
const renderingActive = runtimeTabId ? isPreviewWebviewRendering(runtimeTabId) : false;
|
||||
const viewportSetting = snapshot ? (snapshot.viewport ?? FILL_PREVIEW_VIEWPORT) : undefined;
|
||||
const viewport = runtimeTabId ? await readRenderedViewport(runtimeTabId).catch(() => null) : null;
|
||||
const viewport =
|
||||
runtimeTabId && renderingActive
|
||||
? await readRenderedViewport(runtimeTabId).catch(() => null)
|
||||
: null;
|
||||
const viewportStatus = {
|
||||
...(viewportSetting === undefined ? {} : { viewportSetting }),
|
||||
...(viewport === null ? {} : { viewport }),
|
||||
@@ -307,6 +319,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
threadId: request.threadId,
|
||||
};
|
||||
let tabId = request.tabId ?? null;
|
||||
const browserActivity = { release: null as (() => void) | null };
|
||||
try {
|
||||
let state = readThreadPreviewState(threadRef);
|
||||
const needsSessionSync = needsPreviewAutomationSessionSync(state, request.tabId);
|
||||
@@ -340,6 +353,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
}
|
||||
const readyState = readThreadPreviewState(threadRef);
|
||||
const runtimeTabId = previewRuntimeTabId(threadRef, readyState.serverEpoch, readyTabId);
|
||||
browserActivity.release ??= acquireBrowserSurfaceActivity(runtimeTabId);
|
||||
await waitForDesktopOverlay(
|
||||
threadRef,
|
||||
request.requestId,
|
||||
@@ -440,14 +454,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
usePreviewMiniPlayerStore.getState().open(threadRef, activeTabId);
|
||||
}
|
||||
if (activeSnapshot && previewAutomationOpenNeedsOverlay(input, activeSnapshot)) {
|
||||
await waitForDesktopOverlay(
|
||||
threadRef,
|
||||
request.requestId,
|
||||
activeTabId,
|
||||
activeRuntimeTabId,
|
||||
request.operation,
|
||||
request.timeoutMs,
|
||||
);
|
||||
await requireReadyTab();
|
||||
}
|
||||
if (shouldPresentPreview) {
|
||||
// React commits the thread-bound surface asynchronously. Settle
|
||||
@@ -678,6 +685,8 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
tabId,
|
||||
cause,
|
||||
});
|
||||
} finally {
|
||||
browserActivity.release?.();
|
||||
}
|
||||
},
|
||||
[environmentId, listPreviews, open, registry, resize],
|
||||
|
||||
Reference in new issue
Block a user