diff --git a/TODO.md b/TODO.md index 78a868f..bd3e940 100644 --- a/TODO.md +++ b/TODO.md @@ -15,12 +15,10 @@ 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. -- Keep a transfer alive on phones: while a share waits or a transfer runs, hold a Screen Wake Lock - (`navigator.wakeLock.request('screen')`), else a phone that dims and locks suspends the tab and - the connection dies. The browser releases it whenever the page is hidden, so it has to be - requested again on `visibilitychange`. In the same phases, a `beforeunload` handler makes the - browser ask before a reload or a closed tab ends the share or transfer. Both go once it's done, - stopped or failed. +- Revisit the screen wake lock: a browser that keeps refusing it (e.g. in a power saving mode) logs + "screen may lock" each time the page is visible again, open whether once per session is enough. + `awake: …` doesn't cover a session that ends in an error, nor one that ends while a request is + still pending, the case the `wakeLock === request` checks in `holdWakeLock` are for. ## Open observations diff --git a/e2e.spec.ts b/e2e.spec.ts index a0b51f2..ebbd2b3 100644 --- a/e2e.spec.ts +++ b/e2e.spec.ts @@ -257,6 +257,50 @@ function holdReads() { 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()); +type FakeWakeLock = EventTarget & { released: boolean; release: () => Promise }; + +// 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. async function updateWorker(page: Page) { 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 // 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 diff --git a/src/App.vue b/src/App.vue index 35383ad..96fee01 100644 --- a/src/App.vue +++ b/src/App.vue @@ -293,6 +293,57 @@ function onReceive() { const saltLocked = computed( () => 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 | 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);