diff --git a/images/chromium-headful/client/src/app.vue b/images/chromium-headful/client/src/app.vue index 0bcfdace..57c36601 100644 --- a/images/chromium-headful/client/src/app.vue +++ b/images/chromium-headful/client/src/app.vue @@ -34,7 +34,7 @@ - + -
+
- {{ $t('disconnected.message') }} + {{ reconnecting ? $t('connection.reconnecting') : $t('disconnected.message') }}
@@ -15,6 +15,19 @@ justify-content: center; align-items: center; + // the last frame stays visible underneath while the session is restored + &.reconnecting { + position: fixed; + top: 0; + left: 0; + z-index: 10; + background: rgba($color: #000, $alpha: 0.6); + + .message { + color: #fff; + } + } + .message-container { display: flex; justify-content: center; @@ -31,8 +44,10 @@ diff --git a/images/chromium-headful/client/src/components/video.vue b/images/chromium-headful/client/src/components/video.vue index ff26ee83..eacf4773 100644 --- a/images/chromium-headful/client/src/components/video.vue +++ b/images/chromium-headful/client/src/components/video.vue @@ -118,12 +118,13 @@
{{ touchNotice }}
0 + return coarse ? 'Tap to start live view' : 'Click to start live view' + } + get connecting() { return this.$accessor.connecting } @@ -728,9 +736,11 @@ } catch (err: any) { // if it still fails, we're not playing anything this.$accessor.video.pause() + this.askForTapIfRefused(err) } } else { this.$accessor.video.pause() + this.askForTapIfRefused(err) } } } @@ -1204,6 +1214,13 @@ if (!document.hidden) this.resumeVideo() } + // iOS Safari in Low Power Mode can refuse even a muted play() until a tap, + // so without a prompt the stream stays a black box. Other rejections, such as + // an AbortError from a new stream replacing a pending play(), retry on their own. + askForTapIfRefused(err: any) { + if (this.is_touch_device && err?.name === 'NotAllowedError') this.videoBlocked = true + } + onTouchCancel() { this.gestures.touchCancel() } @@ -1798,6 +1815,8 @@ onConnectedChanged(connected: boolean) { if (!connected) { this.resetKeyboard() + // a tap can't start a stream that is gone; the next one asks again if refused + this.videoBlocked = false } } diff --git a/images/chromium-headful/client/src/neko/base.ts b/images/chromium-headful/client/src/neko/base.ts index 0b81c810..bfcfaf1f 100644 --- a/images/chromium-headful/client/src/neko/base.ts +++ b/images/chromium-headful/client/src/neko/base.ts @@ -82,6 +82,9 @@ export const CONNECT_STAGE_TIMEOUT_MS = resolveConnectStageTimeoutMs( // prose. The three stages mean a bound expired; the rest never reached one. export type ConnectFailure = ConnectStage | 'unsupported' | 'peer' | 'server' +// the live view proxy closes a viewer with this once the browser session is gone +export const WS_CLOSE_SESSION_GONE = 4410 + export interface BaseEvents { info: (...message: any[]) => void warn: (...message: any[]) => void @@ -100,6 +103,10 @@ export abstract class BaseClient extends EventEmitter { protected _timeout?: number protected _stage?: ConnectStage protected _everConnected = false + // Some connect in this page succeeded, so a later drop is a dropped session + // to restore, and a reconnect attempt that fails is not a failed first connect. + protected _established = false + protected _sessionGone = false protected _gaveUp = false // Tagged where the failure happens, so a pre-connect disconnect is reported // with a reason an embedder can act on. Unset falls back to 'peer'. @@ -129,6 +136,30 @@ export abstract class BaseClient extends EventEmitter { return this.peerConnected && this.socketOpen } + // A dropped session can be restored unless the server ended it or the browser is gone. + get recoverable() { + return this._established && this._failure !== 'server' && !this._sessionGone + } + + // Whether media still arrives. A page that iOS suspended can come back with + // a socket that still reads as open and a peer the server already destroyed; + // neither fires an event, but no bytes arrive. Audio and video both stream + // continuously, so a short window is enough. + public async streamAlive(windowMs: number): Promise { + const peer = this._peer + if (!peer || !this.connected) return false + if (['disconnected', 'failed', 'closed'].includes(this._state)) return false + try { + const before = await receivedBytes(peer) + await new Promise((resolve) => window.setTimeout(resolve, windowMs)) + // a drop in the meantime is handled by its own event + if (peer !== this._peer) return true + return (await receivedBytes(peer)) > before + } catch { + return true + } + } + public connect(url: string, password: string, displayname: string) { if (this._gaveUp) { this.emit('debug', `not reconnecting, already gave up`) @@ -163,6 +194,7 @@ export abstract class BaseClient extends EventEmitter { this._ws.onclose = (event) => { this.emit('debug', `websocket closed: code=${event.code}, reason=${event.reason}`) this._failure = 'transport' + if (event.code === WS_CLOSE_SESSION_GONE) this._sessionGone = true this.onDisconnected(new Error('websocket closed')) } this.armStage('transport') @@ -226,6 +258,8 @@ export abstract class BaseClient extends EventEmitter { } this._state = 'disconnected' + // candidates from a dropped attempt must not reach the next peer + this._candidates = [] this._displayname = undefined this._id = '' } @@ -481,6 +515,11 @@ export abstract class BaseClient extends EventEmitter { return } + if (event === EVENT.SIGNAL.CLOSE) { + this.onDisconnected(new Error('peer closed by server')) + return + } + if (event === EVENT.SIGNAL.CANDIDATE) { const { data } = payload as SignalCandidatePayload const candidate: RTCIceCandidate = JSON.parse(data) @@ -519,7 +558,7 @@ export abstract class BaseClient extends EventEmitter { this.emit('error', (event as ErrorEvent).error) } - private postParentMessage(message: Record) { + protected postParentMessage(message: Record) { if (window.parent === window) { return } @@ -553,6 +592,7 @@ export abstract class BaseClient extends EventEmitter { } this._everConnected = true + this._established = true this.emit('debug', `connected`) this[EVENT.CONNECTED]() @@ -591,7 +631,8 @@ export abstract class BaseClient extends EventEmitter { // The bound expiring is this connect's terminal event, so report it here and // let onDisconnected take the ordinary disconnect path rather than reporting // a second event for the same failure. - this.reportFailure('KERNEL_CONNECTION_TIMEOUT', stage) + // a reconnect attempt that times out is retried, not reported as a failed connect + if (!this._established) this.reportFailure('KERNEL_CONNECTION_TIMEOUT', stage) this.onDisconnected(new Error(`${stage} timeout`)) } @@ -616,7 +657,7 @@ export abstract class BaseClient extends EventEmitter { // A disconnect before any peer was established is a failed connect, not a // dropped session. disconnect() clears the bound below, so without this the // parent frame would hear nothing at all. - if (!this._gaveUp && !this._everConnected) { + if (!this._gaveUp && !this._everConnected && !this._established) { this.giveUp(this._failure ?? 'peer', reason ?? new Error('connection failed')) return } @@ -637,3 +678,11 @@ export abstract class BaseClient extends EventEmitter { protected abstract [EVENT.TRACK](event: RTCTrackEvent): void protected abstract [EVENT.DATA](data: any): void } + +async function receivedBytes(peer: RTCPeerConnection) { + let bytes = 0 + ;(await peer.getStats()).forEach((stat) => { + if (stat.type === 'inbound-rtp') bytes += stat.bytesReceived || 0 + }) + return bytes +} diff --git a/images/chromium-headful/client/src/neko/events.ts b/images/chromium-headful/client/src/neko/events.ts index 239eefe0..3f1ee1b4 100644 --- a/images/chromium-headful/client/src/neko/events.ts +++ b/images/chromium-headful/client/src/neko/events.ts @@ -23,6 +23,7 @@ export const EVENT = { ANSWER: 'signal/answer', PROVIDE: 'signal/provide', CANDIDATE: 'signal/candidate', + CLOSE: 'signal/close', }, MEMBER: { LIST: 'member/list', @@ -100,6 +101,7 @@ export type SignalEvents = | typeof EVENT.SIGNAL.ANSWER | typeof EVENT.SIGNAL.PROVIDE | typeof EVENT.SIGNAL.CANDIDATE + | typeof EVENT.SIGNAL.CLOSE export type ChatEvents = typeof EVENT.CHAT.MESSAGE | typeof EVENT.CHAT.EMOTE diff --git a/images/chromium-headful/client/src/neko/index.ts b/images/chromium-headful/client/src/neko/index.ts index a64a53bf..1df21eba 100644 --- a/images/chromium-headful/client/src/neko/index.ts +++ b/images/chromium-headful/client/src/neko/index.ts @@ -5,6 +5,7 @@ import { Member } from './types' import { EVENT } from './events' import { accessor } from '~/store' import { parseCursorImage } from '~/utils/cursor-shape' +import { ProbeResult, Reconnector, probeResult } from '~/utils/reconnect' import { SystemMessagePayload, @@ -28,10 +29,31 @@ import { interface NekoEvents extends BaseEvents {} +// how long a page that comes back watches for media before reconnecting +const STREAM_CHECK_MS = 2000 +// a fetch on a dead network can hang, which would hold up the attempt +const PROBE_TIMEOUT_MS = 5000 + +async function probeLiveView(): Promise { + const abort = new AbortController() + const timer = window.setTimeout(() => abort.abort(), PROBE_TIMEOUT_MS) + try { + const response = await fetch(location.href, { cache: 'no-store', credentials: 'same-origin', signal: abort.signal }) + return probeResult(response.status) + } catch { + return 'unknown' + } finally { + window.clearTimeout(timer) + } +} + export class NekoClient extends BaseClient implements EventEmitter { private $vue!: Vue private $accessor!: typeof accessor private url!: string + private reconnector!: Reconnector + private credentials?: { password: string; displayname: string } + private checkingStream = false init(vue: Vue) { const url = @@ -48,6 +70,25 @@ export class NekoClient extends BaseClient implements EventEmitter { this.url = url // convert ws url to http url this.$vue.$http.defaults.baseURL = url.replace(/^ws/, 'http').replace(/\/ws$/, '') + + this.reconnector = new Reconnector({ + now: () => performance.now(), + setTimeout: (fn, ms) => window.setTimeout(fn, ms), + clearTimeout: (id) => window.clearTimeout(id), + hidden: () => document.hidden, + probe: probeLiveView, + connect: () => { + if (this.credentials) this.connect(this.url, this.credentials.password, this.credentials.displayname) + }, + onWaiting: (attempt) => { + this.$accessor.setReconnecting(true) + this.postParentMessage({ type: 'KERNEL_RECONNECTING', attempt }) + }, + onEnded: () => this.endSession(new Error('live view ended')), + }) + document.addEventListener('visibilitychange', this.onWake) + window.addEventListener('pageshow', this.onWake) + window.addEventListener('online', this.onWake) } private cleanup() { @@ -59,10 +100,13 @@ export class NekoClient extends BaseClient implements EventEmitter { } login(password: string, displayname: string) { + this.credentials = { password, displayname } this.connect(this.url, password, displayname) } logout() { + this.credentials = undefined + this.reconnector.stop() this.disconnect() this.cleanup() this.$vue.$swal({ @@ -76,14 +120,12 @@ export class NekoClient extends BaseClient implements EventEmitter { // Internal Events ///////////////////////////// protected [EVENT.RECONNECTING]() { - // KERNEL: Differentiate between temporary network issues and permanent disconnection - // If WebSocket is still open, this is likely a temporary ICE disconnection (network glitch) - // Allow WebRTC to attempt recovery automatically - // If WebSocket is closed, the browser process is likely gone - show disconnected overlay + // KERNEL: with the websocket still open this is likely a network glitch that + // WebRTC recovers from on its own; the server sends signal/close if it gives + // up on the peer. Without the websocket the session is gone, so restore it. if (!this.socketOpen) { - this.cleanup() + this.onDisconnected(new Error('peer disconnected')) } - // else: WebSocket still open, let WebRTC recover naturally } protected [EVENT.CONNECTING]() { @@ -91,6 +133,8 @@ export class NekoClient extends BaseClient implements EventEmitter { } protected [EVENT.CONNECTED]() { + this.reconnector.succeeded() + this.$accessor.setReconnecting(false) this.$accessor.user.setMember(this.id) this.$accessor.setConnected(true) @@ -110,7 +154,38 @@ export class NekoClient extends BaseClient implements EventEmitter { } protected [EVENT.DISCONNECTED](reason?: Error) { + if (this.recoverable && !this.reconnector.ended) { + this.reconnector.dropped() + this.cleanup() + return + } + this.endSession(reason) + } + + // A page that comes back may hold a session that died while it was away + // without any event saying so. + private onWake = async () => { + if (document.hidden) return + if (this.reconnector.active) { + this.reconnector.wake() + return + } + if (!this._established || this.reconnector.ended || this.checkingStream) return + this.checkingStream = true + try { + if (!(await this.streamAlive(STREAM_CHECK_MS))) this.onDisconnected(new Error('stream stopped')) + } finally { + this.checkingStream = false + } + } + + private endSession(reason?: Error) { + this.reconnector.stop() this.cleanup() + this.$accessor.setReconnecting(false) + if (this._established) { + this.postParentMessage({ type: 'KERNEL_DISCONNECTED', reason: reason ? reason.message : undefined }) + } this.$vue.$notify({ group: 'neko', @@ -166,6 +241,10 @@ export class NekoClient extends BaseClient implements EventEmitter { } protected [EVENT.SYSTEM.DISCONNECT]({ message }: SystemMessagePayload) { + // neko sends this as it stops, on a restart as well as on teardown; the + // socket close that follows decides whether to reconnect + if (message == 'connection shutdown') return + if (message == 'kicked') { this.$accessor.logout() message = this.$vue.$t('connection.kicked') as string diff --git a/images/chromium-headful/client/src/store/index.ts b/images/chromium-headful/client/src/store/index.ts index 2bc6c91a..9b8bc09e 100644 --- a/images/chromium-headful/client/src/store/index.ts +++ b/images/chromium-headful/client/src/store/index.ts @@ -20,6 +20,8 @@ export const state = () => ({ active: false, connecting: false, connected: false, + // a dropped session is being restored + reconnecting: false, locked: {} as Record, }) @@ -46,6 +48,10 @@ export const mutations = mutationTree(state, { state.connecting = true }, + setReconnecting(state, reconnecting: boolean) { + state.reconnecting = reconnecting + }, + setConnected(state, connected: boolean) { state.connected = connected state.connecting = false diff --git a/images/chromium-headful/client/src/utils/reconnect.ts b/images/chromium-headful/client/src/utils/reconnect.ts new file mode 100644 index 00000000..d373d07d --- /dev/null +++ b/images/chromium-headful/client/src/utils/reconnect.ts @@ -0,0 +1,119 @@ +// Brings a dropped live view session back. A phone that locks or backgrounds +// the page loses the websocket, the WebRTC peer, or both, and nothing else +// reconnects. Attempts back off while they keep failing, wait while the page is +// hidden (a suspended page can't connect anyway), and start at once when the +// page comes back. Before each attempt the live view page is fetched again: the +// proxy answers 4xx once the browser is gone or the link no longer grants +// access, and that ends the session instead of retrying forever. + +export const RECONNECT_BACKOFF_MS = [0, 1000, 2000, 4000, 8000] +export const RECONNECT_MAX_DELAY_MS = 10000 +// a session that drops sooner than this after connecting keeps backing off, +// so one that connects and drops right away can't retry in a tight loop +export const RECONNECT_STABLE_MS = 10000 + +// ok: the page is still served. ended: the proxy refused it for good. +// unknown: a network error or 5xx, which says nothing about the session. +export type ProbeResult = 'ok' | 'ended' | 'unknown' + +export interface ReconnectDeps { + now(): number + setTimeout(fn: () => void, ms: number): number + clearTimeout(id: number): void + hidden(): boolean + probe(): Promise + connect(): void + // an attempt is pending; attempt counts from 1 for each drop + onWaiting(attempt: number): void + onEnded(): void +} + +export function reconnectDelay(failures: number) { + return failures < RECONNECT_BACKOFF_MS.length ? RECONNECT_BACKOFF_MS[failures] : RECONNECT_MAX_DELAY_MS +} + +// Status codes from the live view proxy that mean the session is over. +export function probeResult(status: number): ProbeResult { + if (status >= 200 && status < 400) return 'ok' + if ([401, 403, 404, 410].includes(status)) return 'ended' + return 'unknown' +} + +export class Reconnector { + private phase: 'idle' | 'waiting' | 'connecting' | 'ended' = 'idle' + private failures = 0 + private connectedAt = -Infinity + private timer?: number + + constructor(private deps: ReconnectDeps) {} + + get active() { + return this.phase === 'waiting' || this.phase === 'connecting' + } + + get ended() { + return this.phase === 'ended' + } + + // the session, or the attempt to restore it, dropped + dropped() { + if (this.phase === 'ended') return + if (this.phase === 'connecting') this.failures++ + else if (this.phase === 'idle') { + this.failures = this.deps.now() - this.connectedAt < RECONNECT_STABLE_MS ? this.failures + 1 : 0 + } + this.phase = 'waiting' + this.deps.onWaiting(this.failures + 1) + this.schedule(reconnectDelay(this.failures)) + } + + succeeded() { + this.clear() + this.connectedAt = this.deps.now() + this.phase = 'idle' + } + + // the page became visible, was restored, or the network came back + wake() { + if (this.phase !== 'waiting') return + this.clear() + this.attempt() + } + + stop() { + this.clear() + this.phase = 'ended' + } + + private schedule(ms: number) { + this.clear() + this.timer = this.deps.setTimeout(() => { + this.timer = undefined + this.attempt() + }, ms) + } + + private clear() { + if (this.timer === undefined) return + this.deps.clearTimeout(this.timer) + this.timer = undefined + } + + private async attempt() { + if (this.phase !== 'waiting' || this.deps.hidden()) return + this.phase = 'connecting' + const result = await this.deps.probe() + if (this.phase !== 'connecting') return + if (result === 'ended') { + this.phase = 'ended' + this.deps.onEnded() + return + } + // the page hid during the fetch; a suspended page can't hold the socket + if (this.deps.hidden()) { + this.phase = 'waiting' + return + } + this.deps.connect() + } +} diff --git a/images/chromium-headful/client/tests/connect-bound.test.ts b/images/chromium-headful/client/tests/connect-bound.test.ts index 6f294542..9f520b59 100644 --- a/images/chromium-headful/client/tests/connect-bound.test.ts +++ b/images/chromium-headful/client/tests/connect-bound.test.ts @@ -454,3 +454,159 @@ describe('live view connect failures', () => { }) }) }) + +// A client whose first connect succeeded, as a live view looks before a phone locks. +async function establishedClient() { + const client = new TestClient() + client.connect('ws://host/ws', 'pw', 'kernel') + client.openSocket() + await client.provide() + client.connectPeer() + return client +} + +describe('live view dropped sessions', () => { + test('a socket that closes after connecting is a recoverable drop, not a connect failure', async () => { + const client = await establishedClient() + + client['_ws']!.onclose({ code: 1006, reason: '' } as CloseEvent) + + expect(posted).toEqual([]) + expect(client.reasons.map((r) => r?.message)).toEqual(['websocket closed']) + expect(client.recoverable).toBe(true) + expect(client['_ws']).toBeUndefined() + }) + + test('signal/close from the server drops the session while the socket is open', async () => { + const client = await establishedClient() + const socket = client['_ws']! + + await client['onMessage']({ data: JSON.stringify({ event: 'signal/close' }) } as MessageEvent) + + expect(socket.readyState).toBe(3) + expect(client.reasons.map((r) => r?.message)).toEqual(['peer closed by server']) + expect(client.recoverable).toBe(true) + expect(posted).toEqual([]) + }) + + test('a reconnect attempt that fails before connecting is retried, not reported', async () => { + const client = await establishedClient() + client['_ws']!.onclose({ code: 1006, reason: '' } as CloseEvent) + + client.connect('ws://host/ws', 'pw', 'kernel') + client['_ws']!.onclose({ code: 1006, reason: '' } as CloseEvent) + + expect(posted).toEqual([]) + expect(client['_gaveUp']).toBe(false) + expect(client.recoverable).toBe(true) + client.connect('ws://host/ws', 'pw', 'kernel') + expect(client['_ws']).toBeDefined() + }) + + test('a reconnect attempt that times out is retried, not reported', async () => { + const client = await establishedClient() + client['_ws']!.onclose({ code: 1006, reason: '' } as CloseEvent) + + client.connect('ws://host/ws', 'pw', 'kernel') + runTimers(CONNECT_STAGE_TIMEOUT_MS.transport) + + expect(posted).toEqual([]) + expect(client['_gaveUp']).toBe(false) + expect(client.reasons.map((r) => r?.message)).toEqual(['websocket closed', 'transport timeout']) + }) + + test('a reconnect attempt that succeeds reports connected again', async () => { + const client = await establishedClient() + client['_ws']!.onclose({ code: 1006, reason: '' } as CloseEvent) + + client.connect('ws://host/ws', 'pw', 'kernel') + client.openSocket() + await client.provide() + client.connectPeer() + + expect(client.connectEvents).toBe(2) + expect(posted).toEqual([]) + }) + + test('a close the proxy marks as session gone ends the session', async () => { + const client = await establishedClient() + + client['_ws']!.onclose({ code: 4410, reason: 'session no longer exists' } as CloseEvent) + + expect(client.recoverable).toBe(false) + expect(posted).toEqual([]) + }) + + test('candidates buffered by a dropped attempt do not reach the next peer', async () => { + const client = await establishedClient() + client['_ws']!.onclose({ code: 1006, reason: '' } as CloseEvent) + + client.connect('ws://host/ws', 'pw', 'kernel') + client.openSocket() + await client['onMessage']({ + data: JSON.stringify({ event: 'signal/candidate', data: JSON.stringify({ candidate: 'stale' }) }), + } as MessageEvent) + expect(client['_candidates']).toHaveLength(1) + client['_ws']!.onclose({ code: 1006, reason: '' } as CloseEvent) + + expect(client['_candidates']).toEqual([]) + }) + + test('a disconnect the server sends ends the session', async () => { + const client = await establishedClient() + + client['_failure'] = 'server' + client['onDisconnected'](new Error('kicked')) + + expect(client.recoverable).toBe(false) + }) + + test('a connect that never succeeded is not recoverable', () => { + const client = new TestClient() + client.connect('ws://host/ws', 'pw', 'kernel') + client['_ws']!.onclose({ code: 1006, reason: '' } as CloseEvent) + + expect(client.recoverable).toBe(false) + expect(posted.map((m) => m.type)).toEqual(['KERNEL_CONNECTION_FAILED']) + }) +}) + +describe('live view stream liveness', () => { + function withStats(client: TestClient, samples: number[]) { + client['_peer']!.getStats = (async () => { + const bytes = samples.shift() ?? 0 + return new Map([['in', { type: 'inbound-rtp', bytesReceived: bytes }]]) + }) as unknown as RTCPeerConnection['getStats'] + } + + async function check(client: TestClient) { + const alive = client.streamAlive(2000) + // let the first sample resolve and the wait start + await Promise.resolve() + await Promise.resolve() + runTimers(2000) + return alive + } + + test('a stream that still receives bytes is alive', async () => { + const client = await establishedClient() + withStats(client, [1000, 5000]) + expect(await check(client)).toBe(true) + }) + + test('a stream that receives nothing is dead', async () => { + const client = await establishedClient() + withStats(client, [1000, 1000]) + expect(await check(client)).toBe(false) + }) + + test('a peer that ICE marks disconnected is dead without waiting', async () => { + const client = await establishedClient() + client['_state'] = 'disconnected' + expect(await client.streamAlive(2000)).toBe(false) + }) + + test('a client with no session is not alive', async () => { + expect(await new TestClient().streamAlive(2000)).toBe(false) + }) +}) diff --git a/images/chromium-headful/client/tests/reconnect.test.ts b/images/chromium-headful/client/tests/reconnect.test.ts new file mode 100644 index 00000000..3ae768f7 --- /dev/null +++ b/images/chromium-headful/client/tests/reconnect.test.ts @@ -0,0 +1,223 @@ +import { describe, expect, test } from 'bun:test' +import { + ProbeResult, + RECONNECT_MAX_DELAY_MS, + RECONNECT_STABLE_MS, + Reconnector, + probeResult, + reconnectDelay, +} from '../src/utils/reconnect' + +// A reconnector on a fake clock. `probe` answers each attempt's page fetch. +function harness(probe: () => ProbeResult = () => 'ok') { + let now = 0 + let hidden = false + let timers: { id: number; at: number; fn: () => void }[] = [] + let nextId = 1 + const events: string[] = [] + const reconnect = new Reconnector({ + now: () => now, + setTimeout: (fn, ms) => { + timers.push({ id: nextId, at: now + ms, fn }) + return nextId++ + }, + clearTimeout: (id) => { + timers = timers.filter((t) => t.id !== id) + }, + hidden: () => hidden, + probe: async () => probe(), + connect: () => events.push(`connect@${now}`), + onWaiting: (attempt) => events.push(`waiting ${attempt}`), + onEnded: () => events.push('ended'), + }) + // runs every timer due within ms, then lets the probe promise settle + const advance = async (ms: number) => { + const until = now + ms + for (;;) { + const due = timers.filter((t) => t.at <= until).sort((a, b) => a.at - b.at)[0] + if (!due) break + timers = timers.filter((t) => t !== due) + now = due.at + due.fn() + await Promise.resolve() + await Promise.resolve() + } + now = until + } + const flush = async () => { + await Promise.resolve() + await Promise.resolve() + } + return { + reconnect, + events, + advance, + flush, + setHidden: (h: boolean) => (hidden = h), + pending: () => timers.length, + tick: (ms: number) => (now += ms), + } +} + +describe('reconnect backoff', () => { + test('retries at once, then backs off and caps', () => { + expect([0, 1, 2, 3, 4].map(reconnectDelay)).toEqual([0, 1000, 2000, 4000, 8000]) + expect(reconnectDelay(5)).toBe(RECONNECT_MAX_DELAY_MS) + expect(reconnectDelay(50)).toBe(RECONNECT_MAX_DELAY_MS) + }) + + test('the proxy ends the session only with a refusal', () => { + expect(probeResult(200)).toBe('ok') + for (const status of [401, 403, 404, 410]) expect(probeResult(status)).toBe('ended') + // the proxy answers 502 while a browser wakes, and 5xx says nothing about the session + for (const status of [429, 500, 502, 503]) expect(probeResult(status)).toBe('unknown') + }) +}) + +describe('reconnector', () => { + test('a dropped session reconnects right away', async () => { + const h = harness() + h.tick(RECONNECT_STABLE_MS) + h.reconnect.dropped() + expect(h.reconnect.active).toBe(true) + await h.advance(0) + expect(h.events).toEqual(['waiting 1', 'connect@10000']) + }) + + test('attempts that keep failing back off', async () => { + const h = harness() + h.tick(RECONNECT_STABLE_MS) + h.reconnect.dropped() + await h.advance(0) + for (let i = 0; i < 3; i++) { + h.reconnect.dropped() + await h.advance(10000) + } + expect(h.events).toEqual([ + 'waiting 1', + 'connect@10000', + 'waiting 2', + 'connect@11000', + 'waiting 3', + 'connect@22000', + 'waiting 4', + 'connect@34000', + ]) + }) + + test('a session that connects and drops at once keeps backing off', async () => { + const h = harness() + h.reconnect.succeeded() + h.reconnect.dropped() + await h.advance(0) + expect(h.events).toEqual(['waiting 2']) + await h.advance(1000) + expect(h.events).toEqual(['waiting 2', 'connect@1000']) + }) + + test('a session that stayed up starts over', async () => { + const h = harness() + h.tick(RECONNECT_STABLE_MS) + h.reconnect.dropped() + await h.advance(0) + h.reconnect.dropped() + await h.advance(1000) + h.reconnect.succeeded() + h.tick(RECONNECT_STABLE_MS) + h.events.length = 0 + h.reconnect.dropped() + await h.advance(0) + expect(h.events).toEqual(['waiting 1', 'connect@21000']) + }) + + test('a hidden page waits, and connects as soon as it is shown', async () => { + const h = harness() + h.setHidden(true) + h.tick(RECONNECT_STABLE_MS) + h.reconnect.dropped() + await h.advance(30000) + expect(h.events).toEqual(['waiting 1']) + h.setHidden(false) + h.reconnect.wake() + await h.flush() + expect(h.events).toEqual(['waiting 1', 'connect@40000']) + }) + + test('a page that hides during the fetch waits instead of connecting', async () => { + const h = harness() + let hideDuringProbe = true + const original = h.reconnect['deps'].probe + h.reconnect['deps'].probe = async () => { + if (hideDuringProbe) h.setHidden(true) + return original() + } + h.tick(RECONNECT_STABLE_MS) + h.reconnect.dropped() + await h.advance(0) + expect(h.events).toEqual(['waiting 1']) + expect(h.reconnect.active).toBe(true) + + hideDuringProbe = false + h.setHidden(false) + h.reconnect.wake() + await h.flush() + expect(h.events).toEqual(['waiting 1', 'connect@10000']) + }) + + test('waking skips the backoff', async () => { + const h = harness() + h.tick(RECONNECT_STABLE_MS) + h.reconnect.dropped() + await h.advance(0) + h.reconnect.dropped() + h.reconnect.dropped() + h.reconnect.wake() + await h.flush() + expect(h.events.at(-1)).toBe('connect@10000') + expect(h.pending()).toBe(0) + }) + + test('waking while an attempt runs does not start another', async () => { + const h = harness() + h.tick(RECONNECT_STABLE_MS) + h.reconnect.dropped() + await h.advance(0) + h.reconnect.wake() + h.reconnect.wake() + await h.flush() + expect(h.events.filter((e) => e.startsWith('connect'))).toHaveLength(1) + }) + + test('a refused page ends the session without connecting', async () => { + const h = harness(() => 'ended') + h.tick(RECONNECT_STABLE_MS) + h.reconnect.dropped() + await h.advance(0) + expect(h.events).toEqual(['waiting 1', 'ended']) + expect(h.reconnect.ended).toBe(true) + h.reconnect.dropped() + h.reconnect.wake() + await h.advance(60000) + expect(h.events).toEqual(['waiting 1', 'ended']) + }) + + test('a network error still attempts the connect', async () => { + const h = harness(() => 'unknown') + h.tick(RECONNECT_STABLE_MS) + h.reconnect.dropped() + await h.advance(0) + expect(h.events).toEqual(['waiting 1', 'connect@10000']) + }) + + test('stopping cancels a pending attempt', async () => { + const h = harness() + h.tick(RECONNECT_STABLE_MS) + h.reconnect.dropped() + await h.advance(0) + h.reconnect.dropped() + h.reconnect.stop() + await h.advance(60000) + expect(h.events).toEqual(['waiting 1', 'connect@10000', 'waiting 2']) + expect(h.reconnect.active).toBe(false) + }) +}) diff --git a/images/chromium-headful/client/tests/video-autoplay.test.ts b/images/chromium-headful/client/tests/video-autoplay.test.ts new file mode 100644 index 00000000..145b0236 --- /dev/null +++ b/images/chromium-headful/client/tests/video-autoplay.test.ts @@ -0,0 +1,170 @@ +import { describe, expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { runInNewContext } from 'node:vm' +import ts from 'typescript' +import { parseComponent } from 'vue-template-compiler' + +// Load the real component methods without mounting its media player or child components. +const script = parseComponent(readFileSync(new URL('../src/components/video.vue', import.meta.url), 'utf8')).script! + .content +const compiled = ts.transpileModule(script, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020, experimentalDecorators: true }, +}).outputText + +function videoPrototype(globals: Record = {}) { + const exports: { default?: { prototype: Record } } = {} + const noDecorator = () => () => undefined + runInNewContext(compiled, { + exports, + require: (name: string) => { + if (name === 'vue-property-decorator') { + return { + Vue: class {}, + Component: () => (type: unknown) => type, + Ref: noDecorator, + Watch: noDecorator, + Prop: noDecorator, + } + } + return {} + }, + ...globals, + }) + return exports.default!.prototype +} + +function refusal(name: string) { + return Object.assign(new Error(name), { name }) +} + +// The first play() after the stream loads, with the browser's answer to an +// unmuted and a muted play(): null plays, a string rejects with that error. +function firstLoad(options: { touch: boolean; unmuted: string | null; muted: string | null; startMuted?: boolean }) { + const store: string[] = [] + const video = { + paused: true, + muted: !!options.startMuted, + play() { + const error = this.muted ? options.muted : options.unmuted + if (error) return Promise.reject(refusal(error)) + this.paused = false + return Promise.resolve() + }, + } + const component = Object.create(videoPrototype(), { + is_touch_device: { get: () => options.touch }, + }) + Object.assign(component, { + _video: video, + isVideoSyncing: false, + videoBlocked: false, + $accessor: { + video: { + setMuted: (muted: boolean) => store.push(`muted ${muted}`), + pause: () => store.push('pause'), + }, + }, + }) + return { component, video, store, start: () => component.onPlayingChanged(true) } +} + +describe('first load autoplay', () => { + test('asks for a tap on a phone that refuses even a muted play', async () => { + // iOS Safari in Low Power Mode + const { component, video, store, start } = firstLoad({ + touch: true, + unmuted: 'NotAllowedError', + muted: 'NotAllowedError', + }) + await start() + expect(video.paused).toBe(true) + expect(store).toEqual(['muted true', 'pause']) + expect(component.videoBlocked).toBe(true) + }) + + test('asks for a tap when an already muted play is refused', async () => { + const { component, start } = firstLoad({ + touch: true, + unmuted: 'NotAllowedError', + muted: 'NotAllowedError', + startMuted: true, + }) + await start() + expect(component.videoBlocked).toBe(true) + }) + + test('plays muted without a prompt when only sound is refused', async () => { + // iOS and Android browsers outside Low Power Mode + const { component, video, store, start } = firstLoad({ touch: true, unmuted: 'NotAllowedError', muted: null }) + await start() + expect(video).toMatchObject({ paused: false, muted: true }) + expect(store).toEqual(['muted true']) + expect(component.videoBlocked).toBe(false) + }) + + test('plays with sound without a prompt when allowed', async () => { + const { component, video, store, start } = firstLoad({ touch: true, unmuted: null, muted: null }) + await start() + expect(video).toMatchObject({ paused: false, muted: false }) + expect(store).toEqual([]) + expect(component.videoBlocked).toBe(false) + }) + + test('shows no prompt for a play interrupted by a new stream', async () => { + const { component, start } = firstLoad({ touch: true, unmuted: 'AbortError', muted: 'AbortError' }) + await start() + expect(component.videoBlocked).toBe(false) + }) + + test('shows no prompt on a desktop, where the button cannot resume the video', async () => { + const { component, start } = firstLoad({ touch: false, unmuted: 'NotAllowedError', muted: 'NotAllowedError' }) + await start() + expect(component.videoBlocked).toBe(false) + }) + + test('a drop hides the prompt, and a refused play after reconnecting asks again', async () => { + const { component, start } = firstLoad({ touch: true, unmuted: 'NotAllowedError', muted: 'NotAllowedError' }) + await start() + expect(component.videoBlocked).toBe(true) + + component.resetKeyboard = () => {} + component.onConnectedChanged(false) + expect(component.videoBlocked).toBe(false) + + // the reconnected stream plays again, and iOS refuses it again + component._video.paused = true + await start() + expect(component.videoBlocked).toBe(true) + }) +}) + +describe('start prompt', () => { + const template = parseComponent(readFileSync(new URL('../src/components/video.vue', import.meta.url), 'utf8')) + .template!.content + + function prompt(globals: Record) { + const proto = videoPrototype(globals) + return Object.getOwnPropertyDescriptor(proto, 'startPrompt')!.get!.call({}) + } + + test('asks for a tap on a coarse pointer', () => { + const matchMedia = (query: string) => ({ matches: query === '(pointer: coarse)' }) + expect(prompt({ window: { matchMedia }, navigator: {} })).toBe('Tap to start live view') + }) + + test('asks for a click on a fine pointer', () => { + const matchMedia = () => ({ matches: false }) + expect(prompt({ window: { matchMedia }, navigator: { maxTouchPoints: 5 } })).toBe('Click to start live view') + }) + + test('falls back to touch support without matchMedia', () => { + expect(prompt({ window: { ontouchstart: null }, navigator: {} })).toBe('Tap to start live view') + expect(prompt({ window: {}, navigator: { maxTouchPoints: 0 } })).toBe('Click to start live view') + }) + + test('the button reads and announces the same prompt', () => { + const button = template.slice(template.indexOf('class="touch-button video-resume"')) + expect(button.slice(0, button.indexOf(''))).toContain(':aria-label="startPrompt"') + expect(button.slice(0, button.indexOf(''))).toContain('{{ startPrompt }}') + }) +})