Skip to content

Commit 731c873

Browse files
fix(desktop): a hidden preview tab no longer keeps the display awake after a screenshot (pingdotgg#25978)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 675d2bd commit 731c873

2 files changed

Lines changed: 63 additions & 43 deletions

File tree

‎apps/desktop/src/preview/DesktopBrowserHost.test.ts‎

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -607,20 +607,21 @@ describe("DesktopBrowserHost", () => {
607607
params: { sessionId: "t3-preview-page-1" },
608608
});
609609
expect(yield* Queue.take(replies)).toBe(3);
610-
expect(painting).toEqual([true, false]);
610+
expect(painting).toEqual([true]);
611611

612612
// The agent's screenshot waits its turn; painting lets the abandoned one finish first.
613613
yield* command(host, 4, "Page.captureScreenshot");
614614
yield* settle;
615-
expect(painting).toEqual([true, false, true]);
615+
expect(painting).toEqual([true]);
616616
debuggee.release();
617617
expect(yield* Queue.take(replies)).toBe(2);
618618
yield* settle;
619619
expect(debuggee.sent).toEqual([undefined, 4]);
620+
expect(painting).toEqual([true]);
620621
debuggee.release();
621622
expect(yield* Queue.take(replies)).toBe(4);
622623
yield* settle;
623-
expect(painting).toEqual([true, false, true, false]);
624+
expect(painting).toEqual([true, false]);
624625
}).pipe(Effect.scoped),
625626
);
626627

@@ -645,14 +646,19 @@ describe("DesktopBrowserHost", () => {
645646
expect(yield* Queue.take(replies)).toBe(2);
646647
yield* raw({ id: 3, method: "Page.captureScreenshot", sessionId: "t3-preview-page-1" });
647648
yield* settle;
648-
expect(painting).toEqual([true, false, true]);
649+
expect(painting).toEqual([true]);
649650
yield* raw({
650651
id: 4,
651652
method: "Target.detachFromTarget",
652653
params: { sessionId: "t3-preview-page-1" },
653654
});
654655
expect(yield* Queue.take(replies)).toBe(4);
655-
expect(painting).toEqual([true, false, true, false]);
656+
657+
// The agent's answers late; the viewer's is dropped unsent, so nothing is left to paint.
658+
debuggee.release();
659+
yield* settle;
660+
expect(debuggee.sent).toEqual([1]);
661+
expect(painting).toEqual([true, false]);
656662
yield* TestClock.adjust("1 minute");
657663
expect(debuggee.focusEmulation).toEqual([true, false]);
658664
}).pipe(Effect.scoped),
@@ -682,7 +688,7 @@ describe("DesktopBrowserHost", () => {
682688
}).pipe(Effect.scoped),
683689
);
684690

685-
it.effect("stops painting for a screenshot still queued when the agent's turn ends", () =>
691+
it.effect("holds no focus for a screenshot still queued when the agent's turn ends", () =>
686692
Effect.gen(function* () {
687693
const host = yield* DesktopBrowserHost.make;
688694
const debuggee = makeDebuggee();
@@ -697,15 +703,18 @@ describe("DesktopBrowserHost", () => {
697703
yield* settle;
698704
yield* turn(false);
699705
yield* settle;
700-
expect(painting).toEqual([true, false]);
706+
expect(painting).toEqual([true]);
701707

702-
// The first answers late; the second still goes in turn, but holds nothing.
708+
// The first answers late; the second still goes in turn, painting but holding no focus.
703709
debuggee.releaseFirst();
704710
yield* settle;
705711
expect(debuggee.sent).toEqual([1, 2]);
706-
expect(painting).toEqual([true, false]);
707712
yield* TestClock.adjust("1 minute");
708713
expect(debuggee.focusEmulation).toEqual([true, false]);
714+
expect(painting).toEqual([true]);
715+
debuggee.release();
716+
yield* settle;
717+
expect(painting).toEqual([true, false]);
709718
}).pipe(Effect.scoped),
710719
);
711720

@@ -952,7 +961,7 @@ describe("DesktopBrowserHost", () => {
952961
}).pipe(Effect.scoped),
953962
);
954963

955-
it.effect("stops painting for a screenshot Chromium never answers", () =>
964+
it.effect("stops painting for a screenshot Chromium never answers once its document goes", () =>
956965
Effect.gen(function* () {
957966
const host = yield* DesktopBrowserHost.make;
958967
const debuggee = makeDebuggee();
@@ -961,32 +970,34 @@ describe("DesktopBrowserHost", () => {
961970
const turn = (active: boolean) =>
962971
host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
963972

964-
// The server gave up on it, and the agent's turn ends.
973+
// The server gave up on it, and the agent's turn ends; Chromium still holds the capture.
965974
yield* turn(true);
966975
yield* command(host, 1, "Page.captureScreenshot");
967976
yield* settle;
968977
yield* turn(false);
969978
yield* settle;
970-
expect(painting).toEqual([true, false]);
979+
expect(painting).toEqual([true]);
971980

972981
// The page loads a new document, which also frees the screenshot turn.
973982
debuggee.navigate();
983+
expect(painting).toEqual([true, false]);
974984
yield* command(host, 2, "Page.captureScreenshot");
975985
yield* settle;
976986
debuggee.navigate();
977987
yield* settle;
978988
expect(painting).toEqual([true, false, true, false]);
979989

980-
// The server releases the relay.
990+
// The server releases the relay; Chromium still holds the capture.
981991
yield* command(host, 3, "Page.captureScreenshot");
982992
yield* settle;
983993
yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
984994
yield* settle;
985-
expect(painting).toEqual([true, false, true, false, true, false]);
995+
expect(painting).toEqual([true, false, true, false, true]);
986996

987997
// The guest detaches; a replacement starts with no screenshot pending.
988998
const replacement = makeDebuggee();
989999
host.attach(key, replacement.tab);
1000+
expect(painting).toEqual([true, false, true, false, true, false]);
9901001
yield* command(host, 4, "Page.captureScreenshot");
9911002
yield* settle;
9921003
host.detach(key);

‎apps/desktop/src/preview/DesktopBrowserHost.ts‎

Lines changed: 38 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ interface AttachedTab {
4949
readonly debuggee: DesktopBrowserTabDebugger;
5050
relay: CdpRelayConnection | null;
5151
screenshotTurn: object | null;
52-
/** Each holds focus and painting while `held` and whoever queued it still waits on it. */
52+
/** Each keeps the guest painting while whoever queued it still waits, and focused while `held`. */
5353
readonly waitingScreenshots: Array<{
5454
readonly start: () => void;
5555
readonly live: () => boolean;
@@ -62,10 +62,9 @@ interface AttachedTab {
6262
focusChange: Promise<void> | null;
6363
focusUses: number;
6464
/** Each pending command, by the extra session waiting on it; the main connection's have none. */
65-
readonly focusPending: Map<
66-
object,
67-
{ readonly owner: string | undefined; readonly paints: boolean }
68-
>;
65+
readonly focusPending: Map<object, string | undefined>;
66+
/** Screenshots Chromium was sent and has not answered; each keeps its wake lock until then. */
67+
readonly capturing: Set<object>;
6968
/** Whether the client keeps the guest painting, as published on `painting`. */
7069
painting: boolean;
7170
/**
@@ -150,7 +149,7 @@ export const make = Effect.gen(function* () {
150149
tab: AttachedTab,
151150
relay: CdpRelayConnection,
152151
ownerLive: () => boolean,
153-
/** Sends only while `current` holds; holds focus and painting only while `held`. */
152+
/** Sends only while `current` holds; holds focus only while `held`. */
154153
capture: (current: () => boolean, held: boolean) => Promise<unknown>,
155154
) =>
156155
new Promise<unknown>((resolve, reject) => {
@@ -238,38 +237,42 @@ export const make = Effect.gen(function* () {
238237
const active =
239238
tabs.get(keyOf(tab.key)) === tab &&
240239
(tab.screencasts.size > 0 ||
241-
waitingHolds(tab) ||
242-
[...tab.focusPending.values()].some((hold) => hold.paints));
240+
tab.capturing.size > 0 ||
241+
tab.waitingScreenshots.some((waiting) => waiting.live()));
243242
if (tab.painting === active) return;
244243
tab.painting = active;
245244
runFork(PubSub.publish(painting, { key: tab.key, active }));
246245
};
247246

248247
/** A command may wait on the page's next frame, so the guest stays focused until it settles. */
249-
const holdFocus = <A>(
250-
tab: AttachedTab,
251-
method: string,
252-
owner: string | undefined,
253-
work: () => Promise<A>,
254-
) => {
248+
const holdFocus = <A>(tab: AttachedTab, owner: string | undefined, work: () => Promise<A>) => {
255249
const pending = {};
256-
tab.focusPending.set(pending, { owner, paints: method === "Page.captureScreenshot" });
250+
tab.focusPending.set(pending, owner);
257251
tab.focusUses += 1;
258252
setFocusEmulation(tab, true);
259253
releaseFocusWhenIdle(tab);
260-
syncPainting(tab);
261254
return work().finally(() => {
262255
if (!tab.focusPending.delete(pending)) return;
263256
tab.focusUses += 1;
264257
releaseFocusWhenIdle(tab);
258+
});
259+
};
260+
261+
/** Chromium answers a capture, and frees its wake lock, only once the guest paints a frame. */
262+
const paintUntilAnswered = <A>(tab: AttachedTab, send: () => Promise<A>) => {
263+
const sent = {};
264+
tab.capturing.add(sent);
265+
syncPainting(tab);
266+
return send().finally(() => {
267+
tab.capturing.delete(sent);
265268
syncPainting(tab);
266269
});
267270
};
268271

269272
/**
270273
* Chromium can leave a command unanswered, so the screenshot guard's release points
271-
* also end every hold: a released relay has no one waiting, and a new document answers
272-
* nothing pending from the old one. A released relay's screencast has no viewer to stop it.
274+
* also end every focus hold: a released relay has no one waiting, and a new document
275+
* answers nothing pending from the old one. A released relay's screencast has no viewer.
273276
*/
274277
const dropFocusHolds = (tab: AttachedTab) => {
275278
tab.focusPending.clear();
@@ -287,24 +290,24 @@ export const make = Effect.gen(function* () {
287290
/** A detached session, such as a closed viewer, waits on nothing it sent. */
288291
const dropSessionHolds = (tab: AttachedTab, owner: string) => {
289292
tab.screencasts.delete(owner);
290-
for (const [pending, hold] of tab.focusPending) {
291-
if (hold.owner === owner) tab.focusPending.delete(pending);
293+
for (const [pending, holder] of tab.focusPending) {
294+
if (holder === owner) tab.focusPending.delete(pending);
292295
}
293296
releaseFocusWhenIdle(tab);
294297
syncPainting(tab);
295298
};
296299

297300
/**
298301
* A command the server stopped waiting on, such as a timed-out screenshot or evaluation,
299-
* may never settle; the turn's end ends every hold. The agent also sends on its own extra
302+
* may never settle; the turn's end ends every focus hold. The agent also sends on its own extra
300303
* session, so this cannot spare other sessions; a viewer's screencast still holds.
301304
*/
302305
const endAgentTurn = (threadId: string) => {
303306
agentTurns.delete(threadId);
304307
for (const tab of tabs.values()) {
305308
if (tab.key.threadId !== threadId) continue;
306309
tab.agentUsed = false;
307-
// Still sent in turn, so the queue keeps moving, but no longer kept painting.
310+
// Still sent in turn, so the queue keeps moving, but no longer kept focused.
308311
for (const waiting of tab.waitingScreenshots) waiting.held = false;
309312
dropFocusHolds(tab);
310313
}
@@ -325,8 +328,10 @@ export const make = Effect.gen(function* () {
325328
if (sessionId === undefined && method === "Page.startScreencast") {
326329
tab.screencasts.add(owner);
327330
if (owner !== undefined) streamingOwners.add(owner);
331+
syncPainting(tab);
328332
} else if (sessionId === undefined && method === "Page.stopScreencast") {
329333
tab.screencasts.delete(owner);
334+
syncPainting(tab);
330335
}
331336
// A person's input through a viewer, or Playwright's own housekeeping, is not the agent's.
332337
if (
@@ -339,9 +344,11 @@ export const make = Effect.gen(function* () {
339344
const forward = (current?: () => boolean) => {
340345
const change = tab.focusChange;
341346
const run = () =>
342-
tab.relay === relay && (current === undefined || current())
343-
? send(method, params, sessionId)
344-
: Promise.reject(new Error("The page this screenshot was for has moved on."));
347+
tab.relay !== relay || (current !== undefined && !current())
348+
? Promise.reject(new Error("The page this screenshot was for has moved on."))
349+
: current === undefined
350+
? send(method, params, sessionId)
351+
: paintUntilAnswered(tab, () => send(method, params, sessionId));
345352
return change === null ? run() : change.then(run);
346353
};
347354
return method === "Page.captureScreenshot"
@@ -350,17 +357,17 @@ export const make = Effect.gen(function* () {
350357
relay,
351358
() => owner === undefined || !detachedOwners.has(owner),
352359
(current, held) =>
353-
held ? holdFocus(tab, method, owner, () => forward(current)) : forward(current),
360+
held ? holdFocus(tab, owner, () => forward(current)) : forward(current),
354361
)
355362
: method === "Page.startScreencast"
356-
? holdFocus(tab, method, owner, forward).catch((cause: unknown) => {
363+
? holdFocus(tab, owner, forward).catch((cause: unknown) => {
357364
// A viewer can outlive a refused stream; nothing is streaming for it.
358365
if (sessionId === undefined && tab.relay === relay) tab.screencasts.delete(owner);
359366
releaseFocusWhenIdle(tab);
360367
syncPainting(tab);
361368
throw cause;
362369
})
363-
: holdFocus(tab, method, owner, forward);
370+
: holdFocus(tab, owner, forward);
364371
},
365372
sessionDetached: (owner) => {
366373
detachedOwners.add(owner);
@@ -447,6 +454,7 @@ export const make = Effect.gen(function* () {
447454
focusChange: null,
448455
focusUses: 0,
449456
focusPending: new Map(),
457+
capturing: new Set(),
450458
painting: false,
451459
agentUsed: false,
452460
focusReleasing: false,
@@ -461,7 +469,8 @@ export const make = Effect.gen(function* () {
461469
// A screenshot pending when the page loads a new document, a reload included, can
462470
// stay unanswered. A crashed page lands here once it reloads, well after its renderer died.
463471
onNewDocument: () => {
464-
// Before the next screenshot starts, so its own hold survives.
472+
// Before the next screenshot starts, so its own holds survive.
473+
tab.capturing.clear();
465474
dropFocusHolds(tab);
466475
if (tab.screenshotTurn !== null) nextScreenshot(tab);
467476
},

0 commit comments

Comments
 (0)