The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 24, 14:00 UTC
fix(desktop): stop hidden previews draining battery (#8567)
Bilal Bakr committed
Aug 29, 2026 at 00:26 UTC
ff1761012af46ceb5f1ecc9b2be00aae288a1691
9 files changed
+113
-31
apps/web/src/browser/ElectronBrowserHost.tsx
+4
-1
@@ -29,6 +29,8 @@ export function ElectronBrowserHost() {
29
previewState.serverEpoch,
30
snapshot.tabId,
31
),
32
+ pictureInPicture:
33
+ previewState.desktopByTabId[snapshot.tabId]?.pictureInPicture ?? false,
34
zoomFactor: previewState.desktopByTabId[snapshot.tabId]?.zoomFactor ?? 1,
35
}))
36
: [];
@@ -80,7 +82,7 @@ export function ElectronBrowserHost() {
82
if (!isElectron) return null;
83
return (
84
<div className="contents" data-electron-browser-host>
83
- {sessions.map(({ threadRef, snapshot, runtimeTabId, zoomFactor }) => {
85
+ {sessions.map(({ threadRef, snapshot, runtimeTabId, pictureInPicture, zoomFactor }) => {
86
const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
87
return (
88
<HostedBrowserWebview
@@ -90,6 +92,7 @@ export function ElectronBrowserHost() {
92
runtimeTabId={runtimeTabId}
93
initialUrl={url}
94
viewport={snapshot.viewport ?? FILL_PREVIEW_VIEWPORT}
95
+ pictureInPicture={pictureInPicture}
96
zoomFactor={zoomFactor}
97
/>
98
);
apps/web/src/browser/HostedBrowserWebview.tsx
+11
-1
@@ -9,6 +9,7 @@ import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
9
import { cn } from "~/lib/utils";
10
11
import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
12
+import { useActiveBrowserRecordingTabIds } from "./browserRecording";
13
import {
14
browserViewportSettingKey,
15
resolveBrowserViewportLayout,
@@ -47,9 +48,11 @@ export function HostedBrowserWebview(props: {
48
readonly runtimeTabId: string;
49
readonly initialUrl: string | null;
50
readonly viewport: PreviewViewportSetting;
51
+ readonly pictureInPicture: boolean;
52
readonly zoomFactor: number;
53
}) {
52
- const { threadRef, tabId, runtimeTabId, initialUrl, viewport, zoomFactor } = props;
54
+ const { threadRef, tabId, runtimeTabId, initialUrl, viewport, pictureInPicture, zoomFactor } =
55
+ props;
56
const config = usePreviewWebviewConfig(threadRef.environmentId);
57
const [initialSrc] = useState(() => initialUrl ?? "about:blank");
58
const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
@@ -70,6 +73,10 @@ export function HostedBrowserWebview(props: {
73
};
74
}),
75
);
76
+ const backgroundActivity = useBrowserSurfaceStore(
77
+ (state) => (state.activityByTabId[runtimeTabId] ?? 0) > 0,
78
+ );
79
+ const recordingActive = useActiveBrowserRecordingTabIds().has(runtimeTabId);
80
usePreviewBridge({ threadRef, tabId, runtimeTabId });
81
82
useEffect(() => {
@@ -231,8 +238,10 @@ export function HostedBrowserWebview(props: {
238
239
if (!config) return null;
240
241
+ const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive;
242
const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({
243
active,
244
+ renderingActive,
245
cornerRadius: presentation.cornerRadius,
246
rect: lastRect,
247
hiddenSize,
@@ -244,6 +253,7 @@ export function HostedBrowserWebview(props: {
253
className="fixed overflow-hidden bg-muted/35"
254
style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
255
onScroll={syncContentPresentation}
256
+ data-preview-rendering={renderingActive ? "active" : "suspended"}
257
data-preview-viewport={runtimeTabId}
258
>
259
<div className="relative" style={{ width: layout.canvasWidth, height: layout.canvasHeight }}>
apps/web/src/browser/browserRecording.test.ts
+4
-4
@@ -179,10 +179,10 @@ describe("browser recording", () => {
179
180
it("starts recording for a visible tab", async () => {
181
await startBrowserRecording("recording-tab");
182
-
183
- expect(events).toEqual(["start-screencast", "publish:recording-tab"]);
182
+ const startupEvents = [...events];
183
184
await stopBrowserRecording("recording-tab");
185
+ expect(startupEvents).toEqual(["publish:recording-tab", "start-screencast"]);
186
});
187
188
it("records a hidden tab without requiring it to become visible", async () => {
@@ -195,11 +195,11 @@ describe("browser recording", () => {
195
};
196
197
await startBrowserRecording("recording-tab");
198
+ const startupEvents = [...events];
199
200
expect(startScreencast).toHaveBeenCalledWith("recording-tab");
200
- expect(events).toEqual(["start-screencast", "publish:recording-tab"]);
201
-
201
await stopBrowserRecording("recording-tab");
202
+ expect(startupEvents).toEqual(["publish:recording-tab", "start-screencast"]);
203
});
204
205
it("fails startup instead of locking a fallback size when no frame arrives", async () => {
apps/web/src/browser/browserRecording.ts
+8
-6
@@ -122,6 +122,12 @@ export function useActiveBrowserRecordingTabIds(): ReadonlySet<string> {
122
const activeRecordings = new Map<string, ActiveRecording>();
123
let unsubscribeFrames: (() => void) | null = null;
124
125
+const publishActiveRecordingTabIds = (): void => {
126
+ appAtomRegistry.set(activeBrowserRecordingTabIdsAtom, {
127
+ tabIds: new Set(activeRecordings.keys()),
128
+ });
129
+};
130
+
131
export const BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS = 5_000;
132
export const BROWSER_RECORDING_FIRST_FRAME_SIZE_TIMEOUT_MS = 5_000;
133
@@ -228,9 +234,7 @@ const clearActiveRecording = (recording: ActiveRecording): void => {
234
unsubscribeFrames?.();
235
unsubscribeFrames = null;
236
}
231
- appAtomRegistry.set(activeBrowserRecordingTabIdsAtom, {
232
- tabIds: new Set(activeRecordings.keys()),
233
- });
237
+ publishActiveRecordingTabIds();
238
};
239
240
const cleanupFailedRecordingStart = async (
@@ -377,6 +381,7 @@ export async function startBrowserRecording(
381
lifecycle: { phase: "starting" },
382
};
383
activeRecordings.set(tabId, recording);
384
+ publishActiveRecordingTabIds();
385
try {
386
try {
387
unsubscribeFrames ??= bridge.recording.onFrame(drawFrame);
@@ -487,9 +492,6 @@ export async function startBrowserRecording(
492
if (recording.lifecycle.phase === "starting") {
493
recording.lifecycle = { phase: "recording" };
494
}
490
- appAtomRegistry.set(activeBrowserRecordingTabIdsAtom, {
491
- tabIds: new Set(activeRecordings.keys()),
492
- });
495
return startedAt;
496
} finally {
497
settleStartup?.();
apps/web/src/browser/browserSurfaceStore.test.ts
+13
-1
@@ -2,13 +2,25 @@ import { beforeEach, describe, expect, it } from "vite-plus/test";
2
3
import {
4
acquireBrowserSurface,
5
+ acquireBrowserSurfaceActivity,
6
resolveBrowserSurfacePanelRect,
7
useBrowserSurfaceStore,
8
} from "./browserSurfaceStore";
9
10
describe("browserSurfaceStore", () => {
11
beforeEach(() => {
11
- useBrowserSurfaceStore.setState({ byTabId: {} });
12
+ useBrowserSurfaceStore.setState({ activityByTabId: {}, byTabId: {} });
13
+ });
14
+
15
+ it("keeps concurrent background work active until every lease is released", () => {
16
+ const first = acquireBrowserSurfaceActivity("background-browser");
17
+ const second = acquireBrowserSurfaceActivity("background-browser");
18
+
19
+ first();
20
+ expect(useBrowserSurfaceStore.getState().activityByTabId["background-browser"]).toBe(1);
21
+
22
+ second();
23
+ expect(useBrowserSurfaceStore.getState().activityByTabId["background-browser"]).toBeUndefined();
24
});
25
26
it("freezes the source content dimensions for a fitted presentation", () => {
apps/web/src/browser/browserSurfaceStore.ts
+26
@@ -29,7 +29,9 @@ export interface BrowserSurfaceContentPresentation {
29
}
30
31
interface BrowserSurfaceStoreState {
32
+ readonly activityByTabId: Record<string, number>;
33
readonly byTabId: Record<string, BrowserSurfacePresentation>;
34
+ readonly acquireActivity: (tabId: string) => () => void;
35
readonly claim: (tabId: string, owner: symbol, fitSourceContent: boolean) => void;
36
readonly present: (
37
tabId: string,
@@ -63,7 +65,28 @@ const rectEquals = (left: BrowserSurfaceRect | null, right: BrowserSurfaceRect):
65
left.height === right.height;
66
67
export const useBrowserSurfaceStore = create<BrowserSurfaceStoreState>()((set) => ({
68
+ activityByTabId: {},
69
byTabId: {},
70
+ acquireActivity: (tabId) => {
71
+ let released = false;
72
+ set((state) => ({
73
+ activityByTabId: {
74
+ ...state.activityByTabId,
75
+ [tabId]: (state.activityByTabId[tabId] ?? 0) + 1,
76
+ },
77
+ }));
78
+ return () => {
79
+ if (released) return;
80
+ released = true;
81
+ set((state) => {
82
+ const count = state.activityByTabId[tabId] ?? 0;
83
+ const activityByTabId = { ...state.activityByTabId };
84
+ if (count <= 1) delete activityByTabId[tabId];
85
+ else activityByTabId[tabId] = count - 1;
86
+ return { activityByTabId };
87
+ });
88
+ };
89
+ },
90
claim: (tabId, owner, fitSourceContent) =>
91
set((state) => {
92
const current = state.byTabId[tabId];
@@ -171,6 +194,9 @@ export const useBrowserSurfaceStore = create<BrowserSurfaceStoreState>()((set) =
194
}),
195
}));
196
197
+export const acquireBrowserSurfaceActivity = (tabId: string): (() => void) =>
198
+ useBrowserSurfaceStore.getState().acquireActivity(tabId);
199
+
200
export function acquireBrowserSurface(
201
tabId: string,
202
fitSourceContent = false,
apps/web/src/browser/hostedBrowserWebviewStyle.test.ts
+23
-1
@@ -10,6 +10,7 @@ describe("resolveHostedBrowserWebviewWrapperStyle", () => {
10
expect(
11
resolveHostedBrowserWebviewWrapperStyle({
12
active: true,
13
+ renderingActive: true,
14
rect: { x: 12, y: 34, width: 800, height: 600 },
15
hiddenSize: { width: 1280, height: 800 },
16
}),
@@ -27,6 +28,7 @@ describe("resolveHostedBrowserWebviewWrapperStyle", () => {
28
expect(
29
resolveHostedBrowserWebviewWrapperStyle({
30
active: true,
31
+ renderingActive: true,
32
cornerRadius: 12,
33
rect: { x: 12, y: 34, width: 360, height: 203 },
34
hiddenSize: { width: 1280, height: 800 },
@@ -40,9 +42,10 @@ describe("resolveHostedBrowserWebviewWrapperStyle", () => {
42
});
43
});
44
43
- it("keeps an inactive webview paintable while moving it offscreen", () => {
45
+ it("suspends painting for an inactive webview", () => {
46
const style = resolveHostedBrowserWebviewWrapperStyle({
47
active: false,
48
+ renderingActive: false,
49
rect: { x: 12, y: 34, width: 800, height: 600 },
50
hiddenSize: { width: 393, height: 852 },
51
});
@@ -54,6 +57,25 @@ describe("resolveHostedBrowserWebviewWrapperStyle", () => {
57
height: 852,
58
zIndex: -1,
59
pointerEvents: "none",
60
+ visibility: "hidden",
61
+ });
62
+ });
63
+
64
+ it("keeps an active background task paintable offscreen", () => {
65
+ const style = resolveHostedBrowserWebviewWrapperStyle({
66
+ active: false,
67
+ renderingActive: true,
68
+ rect: null,
69
+ hiddenSize: { width: 1280, height: 800 },
70
+ });
71
+
72
+ expect(style).toEqual({
73
+ left: HIDDEN_BROWSER_WEBVIEW_OFFSET,
74
+ top: HIDDEN_BROWSER_WEBVIEW_OFFSET,
75
+ width: 1280,
76
+ height: 800,
77
+ zIndex: -1,
78
+ pointerEvents: "none",
79
visibility: "visible",
80
});
81
});
apps/web/src/browser/hostedBrowserWebviewStyle.ts
+4
-6
@@ -13,18 +13,19 @@ export interface HostedBrowserWebviewWrapperStyle {
13
readonly zIndex: number;
14
readonly pointerEvents: "auto" | "none";
15
readonly borderRadius?: number;
16
- readonly visibility?: "visible";
16
+ readonly visibility?: "hidden" | "visible";
17
}
18
19
export const HIDDEN_BROWSER_WEBVIEW_OFFSET = -100_000;
20
21
export function resolveHostedBrowserWebviewWrapperStyle(input: {
22
readonly active: boolean;
23
+ readonly renderingActive: boolean;
24
readonly cornerRadius?: number;
25
readonly rect: BrowserSurfaceRect | null;
26
readonly hiddenSize: HostedBrowserWebviewSize;
27
}): HostedBrowserWebviewWrapperStyle {
27
- const { active, cornerRadius = 0, hiddenSize, rect } = input;
28
+ const { active, cornerRadius = 0, hiddenSize, rect, renderingActive } = input;
29
if (active && rect) {
30
return {
31
left: rect.x,
@@ -44,9 +45,6 @@ export function resolveHostedBrowserWebviewWrapperStyle(input: {
45
height: hiddenSize.height,
46
zIndex: -1,
47
pointerEvents: "none",
47
- // Keep the guest CSS-visible even while physically offscreen. Electron
48
- // webviews can keep metadata/status alive under `visibility:hidden` while
49
- // CDP Runtime/Input commands stall, which breaks offscreen automation.
50
- visibility: "visible",
48
+ visibility: renderingActive ? "visible" : "hidden",
49
};
50
}
apps/web/src/components/preview/PreviewAutomationHosts.tsx
+20
-11
@@ -37,7 +37,10 @@ import {
37
stopBrowserRecording,
38
} from "~/browser/browserRecording";
39
import { resolveBrowserRecordingStopTarget } from "~/browser/browserRecordingScope";
40
-import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
40
+import {
41
+ acquireBrowserSurfaceActivity,
42
+ useBrowserSurfaceStore,
43
+} from "~/browser/browserSurfaceStore";
44
import { browserDefaultOpenViewport, resolveBrowserDefaults } from "~/browser/browserDefaults";
45
import { runBrowserViewportMutation } from "~/browser/browserViewportActions";
46
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
@@ -98,7 +101,7 @@ const waitForDesktopOverlay = async (
101
operation,
102
requestId,
103
});
101
- if (state.desktopByTabId[tabId] && previewBridge) {
104
+ if (state.desktopByTabId[tabId] && previewBridge && isPreviewWebviewRendering(runtimeTabId)) {
105
const status = await previewBridge.automation.status(runtimeTabId);
106
if (status.available) return;
107
}
@@ -121,6 +124,11 @@ const findPreviewWebview = (tabId: string): ExecutablePreviewWebview | null =>
124
(candidate) => candidate.getAttribute("data-preview-tab") === tabId,
125
) ?? null;
126
127
+const isPreviewWebviewRendering = (runtimeTabId: string): boolean => {
128
+ const wrapper = findPreviewWebview(runtimeTabId)?.closest<HTMLElement>("[data-preview-viewport]");
129
+ return wrapper?.getAttribute("data-preview-rendering") === "active";
130
+};
131
+
132
const readWebviewViewport = async (
133
webview: ExecutablePreviewWebview,
134
): Promise<PreviewRenderedViewportSize | null> => {
@@ -212,8 +220,12 @@ const currentStatus = async (
220
const visible = runtimeTabId
221
? (useBrowserSurfaceStore.getState().byTabId[runtimeTabId]?.visible ?? false)
222
: false;
223
+ const renderingActive = runtimeTabId ? isPreviewWebviewRendering(runtimeTabId) : false;
224
const viewportSetting = snapshot ? (snapshot.viewport ?? FILL_PREVIEW_VIEWPORT) : undefined;
216
- const viewport = runtimeTabId ? await readRenderedViewport(runtimeTabId).catch(() => null) : null;
225
+ const viewport =
226
+ runtimeTabId && renderingActive
227
+ ? await readRenderedViewport(runtimeTabId).catch(() => null)
228
+ : null;
229
const viewportStatus = {
230
...(viewportSetting === undefined ? {} : { viewportSetting }),
231
...(viewport === null ? {} : { viewport }),
@@ -307,6 +319,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
319
threadId: request.threadId,
320
};
321
let tabId = request.tabId ?? null;
322
+ const browserActivity = { release: null as (() => void) | null };
323
try {
324
let state = readThreadPreviewState(threadRef);
325
const needsSessionSync = needsPreviewAutomationSessionSync(state, request.tabId);
@@ -340,6 +353,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
353
}
354
const readyState = readThreadPreviewState(threadRef);
355
const runtimeTabId = previewRuntimeTabId(threadRef, readyState.serverEpoch, readyTabId);
356
+ browserActivity.release ??= acquireBrowserSurfaceActivity(runtimeTabId);
357
await waitForDesktopOverlay(
358
threadRef,
359
request.requestId,
@@ -440,14 +454,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
454
usePreviewMiniPlayerStore.getState().open(threadRef, activeTabId);
455
}
456
if (activeSnapshot && previewAutomationOpenNeedsOverlay(input, activeSnapshot)) {
443
- await waitForDesktopOverlay(
444
- threadRef,
445
- request.requestId,
446
- activeTabId,
447
- activeRuntimeTabId,
448
- request.operation,
449
- request.timeoutMs,
450
- );
457
+ await requireReadyTab();
458
}
459
if (shouldPresentPreview) {
460
// React commits the thread-bound surface asynchronously. Settle
@@ -678,6 +685,8 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
685
tabId,
686
cause,
687
});
688
+ } finally {
689
+ browserActivity.release?.();
690
}
691
},
692
[environmentId, listPreviews, open, registry, resize],