Keep the screen on and ask before leaving while a session is busy

While a share waits or a transfer runs, the page holds a Screen Wake Lock,
requested again once the page is visible, since the browser releases it
whenever it's hidden. A beforeunload handler makes the browser ask before a
reload or a closed tab ends the session, only while busy so the page stays
eligible for the back/forward cache otherwise. Covered by awake: with a fake
wake lock, a headless browser may not grant a real one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-30 13:51:51 +01:00
1 parent 870d55b44f
commit 44a8a72261
3 files changed
+128 -6

No files matched your search

+4 -6
View File
@@ -15,12 +15,10 @@
deployments on different versions, the receiver only sees "No sender with this code". Open how a deployments on different versions, the receiver only sees "No sender with this code". Open how a
mismatch would be reported, e.g. by trying the previous version's swarm too. mismatch would be reported, e.g. by trying the previous version's swarm too.
- Keep a transfer alive on phones: while a share waits or a transfer runs, hold a Screen Wake Lock - Revisit the screen wake lock: a browser that keeps refusing it (e.g. in a power saving mode) logs
(`navigator.wakeLock.request('screen')`), else a phone that dims and locks suspends the tab and "screen may lock" each time the page is visible again, open whether once per session is enough.
the connection dies. The browser releases it whenever the page is hidden, so it has to be `awake: …` doesn't cover a session that ends in an error, nor one that ends while a request is
requested again on `visibilitychange`. In the same phases, a `beforeunload` handler makes the still pending, the case the `wakeLock === request` checks in `holdWakeLock` are for.
browser ask before a reload or a closed tab ends the share or transfer. Both go once it's done,
stopped or failed.
## Open observations ## Open observations
+73
View File
@@ -257,6 +257,50 @@ function holdReads() {
const received = (page: Page) => page.evaluate(() => (window as unknown as { received: number }).received); const received = (page: Page) => page.evaluate(() => (window as unknown as { received: number }).received);
const release = (page: Page) => page.evaluate(() => (window as unknown as { release: () => void }).release()); const release = (page: Page) => page.evaluate(() => (window as unknown as { release: () => void }).release());
type FakeWakeLock = EventTarget & { released: boolean; release: () => Promise<void> };
// Init script for a page whose wake lock the test follows, a headless browser may not grant a real
// one. Like a browser, it refuses one to a hidden page and releases each once the page is hidden,
// which setHidden makes it. It runs in the hidden frames too, only the app's own window counts.
function fakeWakeLock() {
if (window !== window.top) return;
const page = window as unknown as { wakeLocks: FakeWakeLock[]; setHidden: (hidden: boolean) => void };
page.wakeLocks = [];
let hidden = false;
Object.defineProperty(document, 'hidden', { get: () => hidden });
const request = async () => {
if (hidden) throw new DOMException('page is hidden', 'NotAllowedError');
const sentinel: FakeWakeLock = Object.assign(new EventTarget(), {
released: false,
release: async () => {
if (sentinel.released) return;
sentinel.released = true;
sentinel.dispatchEvent(new Event('release'));
},
});
page.wakeLocks.push(sentinel);
return sentinel;
};
Object.defineProperty(navigator, 'wakeLock', { value: { request } });
page.setHidden = (value) => {
hidden = value;
if (hidden) for (const sentinel of page.wakeLocks) void sentinel.release();
document.dispatchEvent(new Event('visibilitychange'));
};
}
const setHidden = (page: Page, hidden: boolean) =>
page.evaluate((hidden) => (window as unknown as { setHidden: (hidden: boolean) => void }).setHidden(hidden), hidden);
// The wake locks the page holds, and whether it would ask before a reload or a closed tab.
const awake = (page: Page) =>
page.evaluate(() => {
const leave = new Event('beforeunload', { cancelable: true });
dispatchEvent(leave);
const { wakeLocks } = window as unknown as { wakeLocks: FakeWakeLock[] };
return { locks: wakeLocks.filter((sentinel) => !sentinel.released).length, asks: leave.defaultPrevented };
});
// Changes sw.js and has the page's browser install it, as after a deploy while the tab is open. // Changes sw.js and has the page's browser install it, as after a deploy while the tab is open.
async function updateWorker(page: Page) { async function updateWorker(page: Page) {
await expect await expect
@@ -764,6 +808,35 @@ for (const name of Object.keys(BROWSERS)) {
}); });
}); });
// While a session runs, the screen stays on and the browser asks before a reload or a closed tab
// ends it. Hidden, the page loses the wake lock and gets a new one once visible again.
test(`awake: ${name} keeps the screen on and asks before leaving while busy`, async () => {
const [sender, receiver] = await Promise.all([
open(name, { init: fakeWakeLock }),
open(name, { init: fakeWakeLock }),
]);
const source = await payload(randomBytes(100_000));
await withLogs(sender, receiver, async () => {
for (const page of [sender, receiver]) expect(await awake(page)).toEqual({ locks: 0, asks: false });
await connect('offline', sender, receiver, source);
for (const page of [sender, receiver]) await expect.poll(() => awake(page)).toEqual({ locks: 1, asks: true });
await setHidden(sender, true);
await expect.poll(() => awake(sender)).toEqual({ locks: 0, asks: true });
await setHidden(sender, false);
await expect.poll(() => awake(sender)).toEqual({ locks: 1, asks: true });
await expect(sender.locator('#log')).toContainText(/keeping the screen on[\s\S]*keeping the screen on/);
await sender.click('#confirm');
await receiver.click('#confirm');
await receiver.click('#download');
await expect(sender.locator('[data-phase=done] #send-status')).toHaveText('Delivered');
await expect(receiver.locator('[data-phase=done] #receive-status')).toHaveText('Download complete');
for (const page of [sender, receiver]) await expect.poll(() => awake(page)).toEqual({ locks: 0, asks: false });
});
});
// The proofs hold even against a man in the middle that opens and seals the signaling. They are // The proofs hold even against a man in the middle that opens and seals the signaling. They are
// genuine, made with the right key, only the real certificates' fingerprints they cover give the man // genuine, made with the right key, only the real certificates' fingerprints they cover give the man
// in the middle away. Whoever verifies first ends its connection, the other side may never get the // in the middle away. Whoever verifies first ends its connection, the other side may never get the
+51
View File
@@ -293,6 +293,57 @@ function onReceive() {
const saltLocked = computed( const saltLocked = computed(
() => viaTracker.value && side.value === 'send' && !['error', 'done', 'stopped'].includes(phase.value!), () => viaTracker.value && side.value === 'send' && !['error', 'done', 'stopped'].includes(phase.value!),
); );
// While a share waits or a transfer runs. A phone that dims and locks may suspend the tab and the
// connection dies, a reload or a closed tab ends it for sure.
const busy = computed(() => ['start', 'wait', 'retry', 'transfer'].includes(phase.value!));
// The screen's, held while busy. The browser releases it whenever the page is hidden, so it's
// requested again once the page is visible.
let wakeLock: Promise<WakeLockSentinel | undefined> | undefined;
function holdWakeLock() {
// Missing outside a secure context, e.g. the dev server opened by its LAN address.
if (!busy.value || document.hidden || wakeLock || !navigator.wakeLock) return;
const request = navigator.wakeLock.request('screen').then(
(sentinel) => {
sentinel.addEventListener('release', () => {
if (wakeLock === request) wakeLock = undefined;
});
// Unless let go of meanwhile, releaseWakeLock releases it then.
if (wakeLock === request) events.log('keeping the screen on');
return sentinel;
},
(failure) => {
if (wakeLock === request) wakeLock = undefined;
events.log(`screen may lock: ${failure instanceof Error ? failure.message : failure}`);
return undefined;
},
);
wakeLock = request;
}
// Forgotten right away, a session started before the browser released it requests a new one.
function releaseWakeLock() {
const request = wakeLock;
wakeLock = undefined;
request?.then((sentinel) => sentinel?.release());
}
// The browser asks before a reload or a closed tab ends it. Only while busy, a page with the handler
// may be kept out of the back/forward cache.
const confirmLeave = (event: BeforeUnloadEvent) => event.preventDefault();
watch(busy, (busy) => {
if (busy) {
holdWakeLock();
addEventListener('beforeunload', confirmLeave);
} else {
releaseWakeLock();
removeEventListener('beforeunload', confirmLeave);
}
});
document.addEventListener('visibilitychange', holdWakeLock);
</script> </script>
<template> <template>