From dca98ed4c84b3258cfee6d0feb80b37fbdd978d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Mon, 23 Nov 2026 22:48:39 +0000 Subject: [PATCH] fix(player): a slow load fails only past its system's limit, and a late timeline still fires ready (#8594) * fix(player): a slow load fails only past its system's limit, and a late timeline still fires ready Windows 90 s, macOS 120 s, Linux 30 s, any other system 120 s, in place of 8 s. Past the limit the probe reports once and keeps listening; ready carries readyMs, the time from the frame's load to its timeline. * feat(player): ready names the load limit it had, and the sandbox test waits for Linux's limit * fix(player): time each film's load from its navigation, by the clock * refactor(player): split the probe's poll tick into its read, settle and limit steps --- docs/packages/player.mdx | 6 +- packages/player/README.md | 72 +++---- packages/player/src/composition-probe.ts | 106 +++++++--- .../src/compositionProbeReadiness.test.ts | 27 +-- .../player/src/hyperframes-player.test.ts | 40 +++- packages/player/src/hyperframes-player.ts | 27 ++- packages/player/src/loadLimit.test.ts | 194 ++++++++++++++++++ .../player/src/probeTerminalReadiness.test.ts | 19 +- .../player/src/sealedLateTimeline.test.ts | 28 +-- .../src/sealedStaticComposition.test.ts | 15 +- .../player/tests/browser/sandbox-origin.ts | 3 +- 11 files changed, 418 insertions(+), 119 deletions(-) create mode 100644 packages/player/src/loadLimit.test.ts diff --git a/docs/packages/player.mdx b/docs/packages/player.mdx index cfd8404745..98e9f13537 100644 --- a/docs/packages/player.mdx +++ b/docs/packages/player.mdx @@ -70,7 +70,7 @@ leaves a paused film paused. | `low-power-idle` | boolean | false | While paused, check in once a second, not every 80 ms (many-player pages) | | `disable-click-to-play` | boolean | false | A click on the player no longer plays or pauses, so the page can handle it | | `disable-fullscreen` | boolean | false | Hide the fullscreen button in the controls (`disableFullscreen`) | -| `no-load-timeout` | boolean | false | A slow load never fails at 8 s, so the page owns the deadline; script and runtime errors still fail at once | +| `no-load-timeout` | boolean | false | A slow load never fails at the load limit, so the page owns the deadline; script and runtime errors still fail at once | | `range-start` | number | — | Film second where playback starts, loops back to and parks when paused (`rangeStart`) | | `range-end` | number | — | Film second the range ends before: it stops or loops on the frame before it (`rangeEnd`) | @@ -134,7 +134,7 @@ player.addEventListener("timeupdate", (event) => { | Event | Detail | Description | | -------------- | ----------------- | ------------------------------------------------------------ | -| `ready` | `{ duration, compositionWidth, compositionHeight }` | Composition loaded and timeline discovered | +| `ready` | `{ duration, compositionWidth, compositionHeight, readyMs, loadLimitMs }` | Composition loaded and timeline discovered. `readyMs`: milliseconds from the frame's load to its timeline; `loadLimitMs`: the load limit it had. Both `null` for a video | | `durationchange` | `{ duration }` | The duration changed after `ready` | | `resize` | `{ compositionWidth, compositionHeight }` | The composition's size changed | | `timeupdate` | `{ currentTime }` | Playback position changed, approximately 10 times per second | @@ -145,7 +145,7 @@ player.addEventListener("timeupdate", (event) => { | `ratechange` | — | Playback rate changed | | `volumechange` | — | Volume or muted state changed | | `scenes` | `{ scenes }` | The runtime reported its scene list | -| `error` | `{ message }` | Load or runtime error; a video adds its `MediaError` `code` | +| `error` | `{ message }` | Load or runtime error, or no timeline within the load limit (Windows 90 s, Linux 30 s, other systems 120 s). The player keeps listening, so a timeline that comes later still fires `ready`. A video adds its `MediaError` `code` | | `playbackerror` | `{ source, error }` | The browser blocked playback, for example unmuted autoplay | ## Custom icons and loading mark diff --git a/packages/player/README.md b/packages/player/README.md index 3be1a95e1d..ca95a7ba50 100644 --- a/packages/player/README.md +++ b/packages/player/README.md @@ -71,29 +71,29 @@ Show a static image before playback starts: ## Attributes -| Attribute | Type | Default | Description | -| ----------------------- | ------------------------------- | ------------- | --------------------------------------------------------------------------- | -| `src` | string | — | URL to the composition HTML file, or to a video file with `type` | -| `type` | string | — | A `video/...` type (e.g. `video/mp4`) plays `src` as a video file | -| `audio-src` | string | — | Audio URL for parent-frame playback (mobile) | -| `width` | number | 1920 | Composition width in pixels (aspect ratio) | -| `height` | number | 1080 | Composition height in pixels (aspect ratio) | -| `controls` | boolean | false | Show play/pause, scrubber, time, volume, speed, and fullscreen controls | -| `muted` | boolean | false | Mute audio playback | -| `audio-locked` | boolean | false | Force-mute and hide the volume controls so the viewer cannot turn sound on | -| `poster` | string | — | Image URL shown before playback starts | -| `playback-rate` | number | 1 | Speed multiplier (0.5 = half, 2 = double) | -| `autoplay` | boolean | false | Start playing when ready | -| `loop` | boolean | false | Restart when the composition ends | -| `shader-capture-scale` | number | — | Shader transition snapshot scale forwarded to browser previews (`0.25`-`1`) | -| `shader-loading` | `composition \| player \| none` | `composition` | Controls shader transition prep loading UI ownership | -| `assets-loading-ui` | `player \| none` | `player` | `none` never shows the loading-assets card; asset events still fire | -| `low-power-idle` | boolean | false | While paused, check in once a second, not every 80 ms (many-player pages) | -| `disable-click-to-play` | boolean | false | A click on the player no longer plays or pauses (host overlays own clicks) | -| `disable-fullscreen` | boolean | false | Hide the fullscreen button; `requestFullscreen()` still works | -| `no-load-timeout` | boolean | false | Slow loads never fail at 8 s; the page owns the deadline. Errors still fail | -| `range-start` | number | — | Film second where playback starts, loops back to and parks when paused | -| `range-end` | number | — | Film second the range ends before: it stops or loops on the frame before it | +| Attribute | Type | Default | Description | +| ----------------------- | ------------------------------- | ------------- | -------------------------------------------------------------------------------------- | +| `src` | string | — | URL to the composition HTML file, or to a video file with `type` | +| `type` | string | — | A `video/...` type (e.g. `video/mp4`) plays `src` as a video file | +| `audio-src` | string | — | Audio URL for parent-frame playback (mobile) | +| `width` | number | 1920 | Composition width in pixels (aspect ratio) | +| `height` | number | 1080 | Composition height in pixels (aspect ratio) | +| `controls` | boolean | false | Show play/pause, scrubber, time, volume, speed, and fullscreen controls | +| `muted` | boolean | false | Mute audio playback | +| `audio-locked` | boolean | false | Force-mute and hide the volume controls so the viewer cannot turn sound on | +| `poster` | string | — | Image URL shown before playback starts | +| `playback-rate` | number | 1 | Speed multiplier (0.5 = half, 2 = double) | +| `autoplay` | boolean | false | Start playing when ready | +| `loop` | boolean | false | Restart when the composition ends | +| `shader-capture-scale` | number | — | Shader transition snapshot scale forwarded to browser previews (`0.25`-`1`) | +| `shader-loading` | `composition \| player \| none` | `composition` | Controls shader transition prep loading UI ownership | +| `assets-loading-ui` | `player \| none` | `player` | `none` never shows the loading-assets card; asset events still fire | +| `low-power-idle` | boolean | false | While paused, check in once a second, not every 80 ms (many-player pages) | +| `disable-click-to-play` | boolean | false | A click on the player no longer plays or pauses (host overlays own clicks) | +| `disable-fullscreen` | boolean | false | Hide the fullscreen button; `requestFullscreen()` still works | +| `no-load-timeout` | boolean | false | Slow loads never fail at the load limit; the page owns the deadline. Errors still fail | +| `range-start` | number | — | Film second where playback starts, loops back to and parks when paused | +| `range-end` | number | — | Film second the range ends before: it stops or loops on the frame before it | `range-start` and `range-end` play the moment [start, end) of the film. The player parks on `range-start` at `ready`, and again when a paused playhead falls outside a new range; `play()` from outside the range starts there. At the end it holds the last frame before `range-end` and fires `ended`, or wraps to `range-start` with `loop`. A current runtime stops on that frame itself; video and `__timelines` players stop on their next clock tick and step back to it; an older runtime stops when the player sees its time pass the end. `currentTime` and `duration` stay in film time. A range past the film is cut to its end and an empty or negative one is ignored; both fire `rangeclamped`. @@ -259,19 +259,19 @@ function StudioPreview({ src }: { src: string }) { ## Events -| Event | Detail | Fired when | -| ----------------------- | --------------------------------------------------- | ------------------------------------------ | -| `ready` | `{ duration, compositionWidth, compositionHeight }` | Composition loaded and duration determined | -| `durationchange` | `{ duration }` | The duration changed after `ready` | -| `resize` | `{ compositionWidth, compositionHeight }` | The composition's size changed | -| `play` | — | Playback started | -| `pause` | — | Playback paused | -| `timeupdate` | `{ currentTime }` | Playback position changed (~10 fps) | -| `ended` | — | Reached the end (when not looping) | -| `rangeclamped` | `{ rangeStart, rangeEnd, duration }` | The range was cut to the film, or ignored | -| `error` | `{ message }` (video mode: `{ message, code }`) | Composition or video failed to load | -| `playbackerror` | `{ source, error }` | The browser blocked playback | -| `shadertransitionstate` | `{ compositionId, state }` | Shader transition cache/capture progress | +| Event | Detail | Fired when | +| ----------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `ready` | `{ duration, compositionWidth, compositionHeight, readyMs, loadLimitMs }` | Composition loaded and duration determined; `readyMs` is the time from the frame's load to its timeline and `loadLimitMs` the load limit it had, both `null` for a video | +| `durationchange` | `{ duration }` | The duration changed after `ready` | +| `resize` | `{ compositionWidth, compositionHeight }` | The composition's size changed | +| `play` | — | Playback started | +| `pause` | — | Playback paused | +| `timeupdate` | `{ currentTime }` | Playback position changed (~10 fps) | +| `ended` | — | Reached the end (when not looping) | +| `rangeclamped` | `{ rangeStart, rangeEnd, duration }` | The range was cut to the film, or ignored | +| `error` | `{ message }` (video mode: `{ message, code }`) | Composition or video failed to load, or no timeline came within the load limit (Windows 90 s, Linux 30 s, other systems 120 s); a later timeline still fires `ready` | +| `playbackerror` | `{ source, error }` | The browser blocked playback | +| `shadertransitionstate` | `{ compositionId, state }` | Shader transition cache/capture progress | ```js player.addEventListener("ready", (e) => { diff --git a/packages/player/src/composition-probe.ts b/packages/player/src/composition-probe.ts index b3b76a12cd..03d9156cb8 100644 --- a/packages/player/src/composition-probe.ts +++ b/packages/player/src/composition-probe.ts @@ -4,7 +4,7 @@ * * The probe interval polls every 200 ms until one of: * - An adapter or the document resolves with a positive duration, or - * - 40 attempts (~8 s) expire without a result, unless the host owns the deadline. + * - this system's `loadLimitMs` passes (reported once; polling goes on), unless the host owns the deadline. * * The `CompositionProbe` class owns the interval; the caller must call * `stop()` on disconnect or src change. @@ -60,6 +60,20 @@ export function readPositiveDimension(value: string | null): number | null { export { readCompositionSizeFromDocument }; +const POLL_MS = 200; +const LATE_POLL_MS = 1_000; + +type PlatformNavigator = Pick & { userAgentData?: { platform?: string } }; + +/** How long a film may load before it counts as failed: about p99 of first frames on that OS, plus 30%. */ +export function loadLimitMs(nav: PlatformNavigator = navigator): number { + const platform = nav.userAgentData?.platform || nav.userAgent; + if (/Android|CrOS|Chrome OS/i.test(platform)) return 120_000; + if (/Win/.test(platform)) return 90_000; + if (/Linux|X11/i.test(platform)) return 30_000; + return 120_000; +} + type ProbeOutcome = | { kind: "ready"; result: ProbeResult } | { kind: "error"; message: string } @@ -80,15 +94,33 @@ export class CompositionProbe { private _runtimeInjected = false; private _runtimeScript: HTMLScriptElement | null = null; private _failure: { document: Document | null; deadline: boolean } | null = null; + private _startedAt = performance.now(); + private _limitMs = loadLimitMs(); + private _navigationPending = false; + private _timedFromNavigation = false; get failed(): boolean { - if (this._failure === null) return false; - const unreadableFrameMayStillPost = - this._failure.deadline && this._iframe.contentDocument === null; - if (unreadableFrameMayStillPost) return false; + if (this._failure === null || this._failure.deadline) return false; return this._failure.document === this._iframe.contentDocument; } + /** Since the host navigated the frame to this document; null for one the frame opened itself. */ + elapsedMs(): number | null { + return this._timedFromNavigation ? performance.now() - this._startedAt : null; + } + + /** The host is navigating the frame: its next document's load is timed from now. */ + markNavigation(): void { + this._startedAt = performance.now(); + this._limitMs = loadLimitMs(); + this._navigationPending = true; + this._timedFromNavigation = true; + } + + get limitMs(): number { + return this._limitMs; + } + constructor( private readonly _iframe: HTMLIFrameElement, private readonly _callbacks: ProbeCallbacks, @@ -104,36 +136,50 @@ export class CompositionProbe { this.stop(); this._failure = null; this._runtimeInjected = false; + if (!this._navigationPending) { + this._startedAt = performance.now(); + this._limitMs = loadLimitMs(); + this._timedFromNavigation = false; + } + this._navigationPending = false; let attempts = 0; + let limitReached = false; - this._interval = setInterval(() => { + const tick = () => { attempts++; - let outcome: ProbeOutcome = null; - try { - outcome = this._poll(attempts); - } catch (error) { - if (!(error instanceof DOMException && error.name === "SecurityError")) { - outcome = { - kind: "error", - message: error instanceof Error ? error.message : String(error), - }; - } - } - const deadline = outcome === null; - outcome ??= this._deadlineOutcome(attempts); - if (outcome) { - this.stop(); - if (outcome.kind === "error") { - this._failure = { document: this._iframe.contentDocument, deadline }; - this._callbacks.onError(outcome.message); - } else this._callbacks.onReady(outcome.result); - } - }, 200); + const outcome = this._readOutcomeAcrossOrigins(attempts); + if (outcome) return this._settle(outcome); + if (limitReached || performance.now() - this._startedAt < this._limitMs) return; + limitReached = true; + if (!this._callbacks.hostOwnsDeadline?.()) this._failAtLimit(tick); + }; + this._interval = setInterval(tick, POLL_MS); } - private _deadlineOutcome(attempts: number): ProbeOutcome { - if (attempts < 40 || this._callbacks.hostOwnsDeadline?.()) return null; - return { kind: "error", message: "Composition timeline not found after 8s" }; + private _readOutcomeAcrossOrigins(attempts: number): ProbeOutcome { + try { + return this._poll(attempts); + } catch (error) { + if (error instanceof DOMException && error.name === "SecurityError") return null; + return { kind: "error", message: error instanceof Error ? error.message : String(error) }; + } + } + + private _settle(outcome: NonNullable): void { + this.stop(); + if (outcome.kind === "ready") { + this._callbacks.onReady(outcome.result); + return; + } + this._failure = { document: this._iframe.contentDocument, deadline: false }; + this._callbacks.onError(outcome.message); + } + + private _failAtLimit(tick: () => void): void { + if (this._interval) clearInterval(this._interval); + this._interval = setInterval(tick, LATE_POLL_MS); + this._failure = { document: this._iframe.contentDocument, deadline: true }; + this._callbacks.onError(`Composition timeline not found after ${this._limitMs / 1000}s`); } private _poll(attempts: number): ProbeOutcome { diff --git a/packages/player/src/compositionProbeReadiness.test.ts b/packages/player/src/compositionProbeReadiness.test.ts index fbd32ccfef..42a4ebe129 100644 --- a/packages/player/src/compositionProbeReadiness.test.ts +++ b/packages/player/src/compositionProbeReadiness.test.ts @@ -1,5 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { CompositionProbe } from "./composition-probe.js"; +import { CompositionProbe, loadLimitMs } from "./composition-probe.js"; + +const LIMIT = loadLimitMs(); +const TIMED_OUT = `Composition timeline not found after ${LIMIT / 1000}s`; function mount(markup: string, globals: Record = {}) { const iframe = document.createElement("iframe"); @@ -111,33 +114,33 @@ describe("composition probe readiness", () => { vi.advanceTimersByTime(7800); expect(onError).toHaveBeenCalledExactlyOnceWith("Uncaught Error: child setup failed"); }); - it("times out pending runtime injection at eight seconds", () => { + it("times out pending runtime injection at the load limit", () => { const { onReady, onError } = mount( '
', ); - vi.advanceTimersByTime(7999); + vi.advanceTimersByTime(LIMIT - 1); expect(onError).not.toHaveBeenCalled(); vi.advanceTimersByTime(1); - expect(onError).toHaveBeenCalledExactlyOnceWith("Composition timeline not found after 8s"); + expect(onError).toHaveBeenCalledExactlyOnceWith(TIMED_OUT); expect(onReady).not.toHaveBeenCalled(); - vi.advanceTimersByTime(8000); + vi.advanceTimersByTime(LIMIT); expect(onError).toHaveBeenCalledOnce(); }); it("does not invent duration for an unresolved document", () => { const { onReady, onError } = mount('
'); - vi.advanceTimersByTime(8000); + vi.advanceTimersByTime(LIMIT); expect(onReady).not.toHaveBeenCalled(); - expect(onError).toHaveBeenCalledExactlyOnceWith("Composition timeline not found after 8s"); + expect(onError).toHaveBeenCalledExactlyOnceWith(TIMED_OUT); }); - it("rejects initialization later than eight seconds", () => { + it("accepts initialization later than the load limit, after reporting it", () => { const { iframe, onReady, onError } = mount('
'); - vi.advanceTimersByTime(8000); + vi.advanceTimersByTime(LIMIT); Object.assign(iframe.contentWindow!, { __player: { getDuration: () => 6 } }); vi.advanceTimersByTime(1000); - expect(onReady).not.toHaveBeenCalled(); - expect(onError).toHaveBeenCalledOnce(); + expect(onError).toHaveBeenCalledExactlyOnceWith(TIMED_OUT); + expect(onReady).toHaveBeenCalledOnce(); }); - it("accepts initialization inside the eight-second budget", () => { + it("accepts initialization inside the load limit", () => { const { iframe, onReady, onError } = mount('
'); vi.advanceTimersByTime(7400); Object.assign(iframe.contentWindow!, { __player: { getDuration: () => 6 } }); diff --git a/packages/player/src/hyperframes-player.test.ts b/packages/player/src/hyperframes-player.test.ts index 35888a7a65..f7a421b424 100644 --- a/packages/player/src/hyperframes-player.test.ts +++ b/packages/player/src/hyperframes-player.test.ts @@ -2424,7 +2424,15 @@ describe("HyperframesPlayer runtime ready handshake", () => { expect(player.ready).toBe(true); expect(player.duration).toBe(4); - expect(readyEvents).toEqual([{ duration: 4, compositionWidth: 1920, compositionHeight: 1080 }]); + expect(readyEvents).toEqual([ + { + duration: 4, + compositionWidth: 1920, + compositionHeight: 1080, + readyMs: null, + loadLimitMs: expect.any(Number), + }, + ]); }); it("reports the picture size in ready and as public properties", () => { @@ -2435,7 +2443,15 @@ describe("HyperframesPlayer runtime ready handshake", () => { player._onMessage(timelineMessage(120, { compositionWidth: 1080, compositionHeight: 1920 })); - expect(readyEvents).toEqual([{ duration: 4, compositionWidth: 1080, compositionHeight: 1920 }]); + expect(readyEvents).toEqual([ + { + duration: 4, + compositionWidth: 1080, + compositionHeight: 1920, + readyMs: null, + loadLimitMs: expect.any(Number), + }, + ]); expect(player.compositionWidth).toBe(1080); expect(player.compositionHeight).toBe(1920); }); @@ -2452,7 +2468,15 @@ describe("HyperframesPlayer runtime ready handshake", () => { compositionSize: { width: 1080, height: 1350 }, }); - expect(readyEvents).toEqual([{ duration: 5, compositionWidth: 1080, compositionHeight: 1350 }]); + expect(readyEvents).toEqual([ + { + duration: 5, + compositionWidth: 1080, + compositionHeight: 1350, + readyMs: null, + loadLimitMs: expect.any(Number), + }, + ]); }); it("fires a timeline message's events only after the whole message is applied", () => { @@ -3069,7 +3093,15 @@ describe("HyperframesPlayer video mode", () => { loadMetadata(videoOf(player)); - expect(readies).toEqual([{ duration: 6, compositionWidth: 1080, compositionHeight: 1920 }]); + expect(readies).toEqual([ + { + duration: 6, + compositionWidth: 1080, + compositionHeight: 1920, + readyMs: null, + loadLimitMs: null, + }, + ]); expect(player.ready).toBe(true); }); diff --git a/packages/player/src/hyperframes-player.ts b/packages/player/src/hyperframes-player.ts index 7e15a909fc..295bf9cbe9 100644 --- a/packages/player/src/hyperframes-player.ts +++ b/packages/player/src/hyperframes-player.ts @@ -90,6 +90,8 @@ type PendingRuntimeDataDelivery = { timeoutId: number; }; +const roundOrNull = (ms: number | null) => (ms === null ? null : Math.round(ms)); + function clampPlaybackRate(rate: number): number { if (!Number.isFinite(rate) || rate <= 0) return 1; return Math.max(MIN_PLAYBACK_RATE, Math.min(MAX_PLAYBACK_RATE, rate)); @@ -249,7 +251,7 @@ class HyperframesPlayer extends HTMLElement { this.posterEl = setupPoster(this.shadow, this.getAttribute("poster"), this.posterEl); if (this.hasAttribute("audio-src")) this._media.setupFromUrl(this.getAttribute("audio-src")!); if (this.hasAttribute("srcdoc")) - this.iframe.srcdoc = prepareSrcdocForElement(this, this.getAttribute("srcdoc")!); + this._navigateFrame({ srcdoc: prepareSrcdocForElement(this, this.getAttribute("srcdoc")!) }); if (this.hasAttribute("src")) this._loadSrc(this.getAttribute("src")!); // Host-environment audio lock: when the embedding host (e.g. Claude @@ -304,9 +306,9 @@ class HyperframesPlayer extends HTMLElement { if (val !== null) { this._pauseForVideoSwitch(); this._teardownVideo(); - this.iframe.srcdoc = prepareSrcdocForElement(this, val); + this._navigateFrame({ srcdoc: prepareSrcdocForElement(this, val) }); } else { - this.iframe.removeAttribute("srcdoc"); + this._navigateFrame({ srcdoc: null }); const src = this.getAttribute("src"); if (src !== null && this._wantsVideo()) this._navigateSrc(src); } @@ -397,11 +399,11 @@ class HyperframesPlayer extends HTMLElement { this._abandonComposition("Sandbox policy changed before runtime data was applied"); const srcdoc = this.getAttribute("srcdoc"); if (srcdoc !== null) { - this.iframe.srcdoc = prepareSrcdocForElement(this, srcdoc); + this._navigateFrame({ srcdoc: prepareSrcdocForElement(this, srcdoc) }); return; } const src = this.getAttribute("src"); - if (src === null) this.iframe.src = "about:blank"; + if (src === null) this._navigateFrame({ src: "about:blank" }); else this._loadSrc(src); } @@ -1047,7 +1049,9 @@ class HyperframesPlayer extends HTMLElement { // explanatory rejection the caller gets from every other navigating path. this._abandonComposition("Shader options changed before runtime data was applied"); if (this.hasAttribute("srcdoc")) { - this.iframe.srcdoc = prepareSrcdocForElement(this, this.getAttribute("srcdoc") || ""); + this._navigateFrame({ + srcdoc: prepareSrcdocForElement(this, this.getAttribute("srcdoc") || ""), + }); return; } if (this.hasAttribute("src")) this._loadSrc(this.getAttribute("src") || ""); @@ -1080,7 +1084,14 @@ class HyperframesPlayer extends HTMLElement { return; } this._teardownVideo(); - this.iframe.src = prepareSrcForElement(this, src); + this._navigateFrame({ src: prepareSrcForElement(this, src) }); + } + + private _navigateFrame(to: { src: string } | { srcdoc: string | null }): void { + this.probe.markNavigation(); + if (!("srcdoc" in to)) this.iframe.src = to.src; + else if (to.srcdoc === null) this.iframe.removeAttribute("srcdoc"); + else this.iframe.srcdoc = to.srcdoc; } private _loadVideo(src: string): void { @@ -1556,6 +1567,8 @@ class HyperframesPlayer extends HTMLElement { duration: this._duration, compositionWidth: this._compositionWidth, compositionHeight: this._compositionHeight, + readyMs: this._videoSource ? null : roundOrNull(this.probe.elapsedMs()), + loadLimitMs: this._videoSource ? null : this.probe.limitMs, }; this._emit(new CustomEvent("ready", { detail })); // Once ready: covers a size message that never came, and lets a zero-size player warn. diff --git a/packages/player/src/loadLimit.test.ts b/packages/player/src/loadLimit.test.ts new file mode 100644 index 0000000000..3f61fa33fc --- /dev/null +++ b/packages/player/src/loadLimit.test.ts @@ -0,0 +1,194 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { CompositionProbe, loadLimitMs } from "./composition-probe.js"; +import type { HyperframesPlayer } from "./hyperframes-player.js"; + +describe("loadLimitMs", () => { + it.each([ + [{ userAgentData: { platform: "Windows" }, userAgent: "" }, 90_000], + [{ userAgentData: { platform: "macOS" }, userAgent: "" }, 120_000], + [{ userAgentData: { platform: "Linux" }, userAgent: "" }, 30_000], + [{ userAgentData: { platform: "Chrome OS" }, userAgent: "" }, 120_000], + [{ userAgentData: { platform: "Android" }, userAgent: "" }, 120_000], + [{ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0" }, 90_000], + [{ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_5) Safari/605.1.15" }, 120_000], + [{ userAgent: "Mozilla/5.0 (X11; Linux x86_64) Chrome/131.0" }, 30_000], + [{ userAgent: "Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) Chrome/131.0" }, 120_000], + [{ userAgent: "Mozilla/5.0 (Linux; Android 14; Pixel 8) Chrome/131.0" }, 120_000], + [{ userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) Safari/604.1" }, 120_000], + [{ userAgent: "" }, 120_000], + ])("gives %o %i ms", (nav, limit) => { + expect(loadLimitMs(nav)).toBe(limit); + }); +}); + +describe("a film past its load limit", () => { + beforeEach(async () => { + await import("./hyperframes-player.js"); + vi.useFakeTimers(); + }); + afterEach(() => { + document.body.innerHTML = ""; + vi.clearAllTimers(); + vi.useRealTimers(); + }); + + const LINUX = 30_000; + + function openFrame() { + const iframe = document.createElement("iframe"); + document.body.appendChild(iframe); + iframe.contentDocument!.body.innerHTML = '
'; + const onReady = vi.fn(); + const onError = vi.fn(); + const probe = new CompositionProbe(iframe, { onReady, onError }); + probe.start(); + return { win: iframe.contentWindow!, onReady, onError }; + } + + function mountPlayer() { + const player = document.createElement("hyperframes-player") as HyperframesPlayer; + document.body.appendChild(player); + const iframe = player.shadowRoot!.querySelector("iframe")!; + iframe.contentDocument!.body.innerHTML = '
'; + const events: string[] = []; + const readies: Array<{ readyMs: number | null; loadLimitMs: number | null }> = []; + player.addEventListener("error", (event: Event) => + events.push(`error ${(event as CustomEvent<{ message: string }>).detail.message}`), + ); + player.addEventListener("ready", (event) => { + events.push("ready"); + readies.push((event as CustomEvent<(typeof readies)[number]>).detail); + }); + iframe.dispatchEvent(new Event("load")); + const postTimeline = () => + window.dispatchEvent( + new MessageEvent("message", { + source: iframe.contentWindow, + data: { source: "hf-preview", type: "timeline", durationInFrames: 120 }, + }), + ); + return { player, events, readies, postTimeline }; + } + + it("is still loading at 8 s and fails once at the system's limit, naming it", () => { + expect(loadLimitMs()).toBe(LINUX); + const { onError } = openFrame(); + vi.advanceTimersByTime(8_000); + expect(onError).not.toHaveBeenCalled(); + vi.advanceTimersByTime(LINUX - 8_000); + expect(onError).toHaveBeenCalledExactlyOnceWith("Composition timeline not found after 30s"); + vi.advanceTimersByTime(LINUX); + expect(onError).toHaveBeenCalledOnce(); + }); + + it("still resolves a timeline its document gets after the limit", () => { + const { win, onReady, onError } = openFrame(); + vi.advanceTimersByTime(LINUX + 10_000); + expect(onError).toHaveBeenCalledOnce(); + Object.assign(win, { __player: { getDuration: () => 6 } }); + vi.advanceTimersByTime(1_000); + expect(onReady).toHaveBeenCalledOnce(); + expect(onReady.mock.calls[0][0].duration).toBe(6); + }); + + it("fires ready for a timeline posted after the limit, after its error", () => { + const { player, events, postTimeline } = mountPlayer(); + vi.advanceTimersByTime(LINUX); + postTimeline(); + expect(events).toEqual(["error Composition timeline not found after 30s", "ready"]); + expect(player.ready).toBe(true); + }); + + it("reads the document five times a second until the limit, then once a second", () => { + const iframe = document.createElement("iframe"); + document.body.appendChild(iframe); + iframe.contentDocument!.body.innerHTML = '
'; + const probe = new CompositionProbe(iframe, { onReady: vi.fn(), onError: vi.fn() }); + const reads = vi.spyOn(iframe, "contentDocument", "get"); + probe.start(); + const readsOver = (ms: number) => { + const from = reads.mock.calls.length; + vi.advanceTimersByTime(ms); + return reads.mock.calls.length - from; + }; + vi.advanceTimersByTime(10_000); + const early = readsOver(2_000); + vi.advanceTimersByTime(LINUX - 12_000 + 2_000); + expect(readsOver(2_000) * 5).toBe(early); + probe.stop(); + }); + + it("stops reading a film past its limit once the player leaves the page", () => { + const { player } = mountPlayer(); + vi.advanceTimersByTime(LINUX + 2_000); + const reads = vi.spyOn(player.iframeElement, "contentDocument", "get"); + player.remove(); + const after = reads.mock.calls.length; + vi.advanceTimersByTime(5_000); + expect(reads.mock.calls.length).toBe(after); + }); + + it("fails at the limit by the clock when a throttled tab polls less often", () => { + const { onError } = openFrame(); + vi.advanceTimersByTime(400); + const now = performance.now(); + vi.spyOn(performance, "now").mockReturnValue(now + LINUX); + vi.advanceTimersByTime(200); + expect(onError).toHaveBeenCalledExactlyOnceWith("Composition timeline not found after 30s"); + }); + + function navigatedPlayer() { + const player = document.createElement("hyperframes-player") as HyperframesPlayer; + player.setAttribute("src", "film-1.html"); + document.body.appendChild(player); + const iframe = player.shadowRoot!.querySelector("iframe")!; + const readies: Array<{ readyMs: number | null; loadLimitMs: number | null }> = []; + player.addEventListener("ready", (event) => + readies.push((event as CustomEvent<(typeof readies)[number]>).detail), + ); + const postTimeline = () => + window.dispatchEvent( + new MessageEvent("message", { + source: iframe.contentWindow, + data: { source: "hf-preview", type: "timeline", durationInFrames: 120 }, + }), + ); + return { player, iframe, readies, postTimeline }; + } + + it("times a timeline posted before load from the navigation, with the limit it had", () => { + const { readies, postTimeline } = navigatedPlayer(); + vi.advanceTimersByTime(1_200); + postTimeline(); + expect(readies).toEqual([expect.objectContaining({ readyMs: 1_200, loadLimitMs: LINUX })]); + }); + + it("times each later film from its own navigation", () => { + const { player, iframe, readies, postTimeline } = navigatedPlayer(); + vi.advanceTimersByTime(1_200); + iframe.dispatchEvent(new Event("load")); + postTimeline(); + vi.advanceTimersByTime(4_000); + player.setAttribute("src", "film-2.html"); + vi.advanceTimersByTime(500); + postTimeline(); + expect(readies.map((ready) => ready.readyMs)).toEqual([1_200, 500]); + }); + + it("times the film a removed srcdoc falls back to from that removal", () => { + const { player, readies, postTimeline } = navigatedPlayer(); + player.setAttribute("srcdoc", "

draft

"); + vi.advanceTimersByTime(4_000); + player.removeAttribute("srcdoc"); + vi.advanceTimersByTime(700); + postTimeline(); + expect(readies.map((ready) => ready.readyMs)).toEqual([700]); + }); + + it("reports no load time for a document the frame opened itself", () => { + const { readies, postTimeline } = mountPlayer(); + vi.advanceTimersByTime(1_200); + postTimeline(); + expect(readies).toEqual([expect.objectContaining({ readyMs: null, loadLimitMs: LINUX })]); + }); +}); diff --git a/packages/player/src/probeTerminalReadiness.test.ts b/packages/player/src/probeTerminalReadiness.test.ts index 6064647314..e8f8244f86 100644 --- a/packages/player/src/probeTerminalReadiness.test.ts +++ b/packages/player/src/probeTerminalReadiness.test.ts @@ -1,7 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { HyperframesPlayer } from "./hyperframes-player.js"; +import { loadLimitMs } from "./composition-probe.js"; import { RUNTIME_CDN_URL } from "./runtime-url.js"; +const LIMIT = loadLimitMs(); + function mountPlayer() { const player = document.createElement("hyperframes-player") as HyperframesPlayer; document.body.appendChild(player); @@ -52,19 +55,19 @@ describe("terminal probe readiness", () => { vi.useRealTimers(); }); - it("does not accept a runtime timeline message after the probe timed out", () => { + it("accepts a runtime timeline message after the load limit, after its error", () => { const { player, iframe, onError, onReady } = mountPlayer(); - vi.advanceTimersByTime(8000); + vi.advanceTimersByTime(LIMIT); expect(onError).toHaveBeenCalledOnce(); vi.advanceTimersByTime(1000); sendTimeline(iframe); - expectUnready(player, onReady); + expectTimelineReady(player, onReady); }); - it("waits past 8 s for a slow runtime when the host owns the deadline", () => { + it("waits past the load limit for a slow runtime when the host owns the deadline", () => { const { player, iframe, onError, onReady } = mountPlayer(); player.setAttribute("no-load-timeout", ""); - vi.advanceTimersByTime(20_000); + vi.advanceTimersByTime(LIMIT + 20_000); expect(onError).not.toHaveBeenCalled(); Object.assign(iframe.contentWindow!, { __player: { getDuration: () => 9 } }); vi.advanceTimersByTime(200); @@ -81,7 +84,7 @@ describe("terminal probe readiness", () => { it("rejects the failed document while its replacement is still navigating", () => { const { player, iframe, onReady } = mountPlayer(); - vi.advanceTimersByTime(8000); + vi.advanceTimersByTime(LIMIT); keepDocument(iframe, iframe.contentDocument); player.setAttribute("src", "next.html"); sendTimeline(iframe); @@ -90,7 +93,7 @@ describe("terminal probe readiness", () => { it("accepts the replacement document handshake before its load event", () => { const { player, iframe, onReady } = mountPlayer(); - vi.advanceTimersByTime(8000); + vi.advanceTimersByTime(LIMIT); keepDocument(iframe, iframe.contentDocument); player.setAttribute("src", "next.html"); const replacement = document.implementation.createHTMLDocument("Replacement"); @@ -102,7 +105,7 @@ describe("terminal probe readiness", () => { it("keeps an opaque document failure latched until its next load event", () => { const { player, iframe, onError, onReady } = mountPlayer(); keepDocument(iframe, null); - vi.advanceTimersByTime(8000); + vi.advanceTimersByTime(LIMIT); expect(onError).toHaveBeenCalledOnce(); player.setAttribute("src", "https://example.org/next.html"); sendTimeline(iframe); diff --git a/packages/player/src/sealedLateTimeline.test.ts b/packages/player/src/sealedLateTimeline.test.ts index 8ea6b7562f..fd700aec47 100644 --- a/packages/player/src/sealedLateTimeline.test.ts +++ b/packages/player/src/sealedLateTimeline.test.ts @@ -1,4 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { loadLimitMs } from "./composition-probe.js"; + +const LIMIT = loadLimitMs(); +const TIMED_OUT = `error Composition timeline not found after ${LIMIT / 1000}s`; type Player = HTMLElement & { ready: boolean; @@ -29,7 +33,7 @@ function sealedPlayer(sealed = true) { return { player, events, postTimeline }; } -describe("a sealed film whose timeline comes after the 8 s check", () => { +describe("a film whose timeline comes after the load limit", () => { beforeEach(async () => { vi.useFakeTimers(); await import("./hyperframes-player.js"); @@ -39,24 +43,24 @@ describe("a sealed film whose timeline comes after the 8 s check", () => { document.body.innerHTML = ""; }); - // fails without the fix: after the 8 s check gave up, the player dropped every later post from a sealed frame, so a - // film whose runtime was ready at 10 s stayed blank until something reloaded it. - it("shows the film when the timeline lands at 10 s", () => { + // fails without the fix: after the check gave up, the player dropped every later post from a sealed frame, so a + // film whose runtime was ready 2 s later stayed blank until something reloaded it. + it("shows a sealed film when the timeline lands 2 s after the limit", () => { const { player, events, postTimeline } = sealedPlayer(); - vi.advanceTimersByTime(8000); - expect(events).toEqual(["error Composition timeline not found after 8s"]); + vi.advanceTimersByTime(LIMIT); + expect(events).toEqual([TIMED_OUT]); vi.advanceTimersByTime(2000); postTimeline(); - expect(events).toEqual(["error Composition timeline not found after 8s", "ready"]); + expect(events).toEqual([TIMED_OUT, "ready"]); expect(player.ready).toBe(true); }); - it("a frame whose document the player reads keeps ignoring a post that comes after the check gave up", () => { + it("shows a film whose document the player reads when its post comes after the limit", () => { const { player, events, postTimeline } = sealedPlayer(false); - vi.advanceTimersByTime(8000); - expect(events).toEqual(["error Composition timeline not found after 8s"]); + vi.advanceTimersByTime(LIMIT); + expect(events).toEqual([TIMED_OUT]); postTimeline(); - expect(events).toEqual(["error Composition timeline not found after 8s"]); - expect(player.ready).toBe(false); + expect(events).toEqual([TIMED_OUT, "ready"]); + expect(player.ready).toBe(true); }); }); diff --git a/packages/player/src/sealedStaticComposition.test.ts b/packages/player/src/sealedStaticComposition.test.ts index 25f669d971..80641b2518 100644 --- a/packages/player/src/sealedStaticComposition.test.ts +++ b/packages/player/src/sealedStaticComposition.test.ts @@ -1,4 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { loadLimitMs } from "./composition-probe.js"; + +const LIMIT = loadLimitMs(); type Player = HTMLElement & { ready: boolean; @@ -36,7 +39,7 @@ function framedPlayer(sealed = true) { return { player, events, postStatic, postTimeline }; } -describe("a sealed film whose runtime boots after the 8 s check", () => { +describe("a sealed film whose runtime boots late", () => { beforeEach(async () => { vi.useFakeTimers(); await import("./hyperframes-player.js"); @@ -48,7 +51,7 @@ describe("a sealed film whose runtime boots after the 8 s check", () => { // fails without the fix: a sealed player could only wait for the runtime's timeline, so a film whose runtime booted // at 10 s showed "Composition timeline not found after 8s" while the same film unsealed was ready from its document. - it("is ready from its document's static read, with no 8 s error, and the runtime's timeline still lands", () => { + it("is ready from its document's static read, with no load error, and the runtime's timeline still lands", () => { const { player, events, postStatic, postTimeline } = framedPlayer(); vi.advanceTimersByTime(1000); postStatic(); @@ -73,16 +76,16 @@ describe("a sealed film whose runtime boots after the 8 s check", () => { ])("ignores a static read with %s", (_name, over) => { const { player, events, postStatic } = framedPlayer(); postStatic(over); - vi.advanceTimersByTime(8000); - expect(events).toEqual(["error Composition timeline not found after 8s"]); + vi.advanceTimersByTime(LIMIT); + expect(events).toEqual([`error Composition timeline not found after ${LIMIT / 1000}s`]); expect(player.ready).toBe(false); }); it("ignores a static read posted by any window but its own frame", () => { const { player, events, postStatic } = framedPlayer(); postStatic({}, window); - vi.advanceTimersByTime(8000); - expect(events).toEqual(["error Composition timeline not found after 8s"]); + vi.advanceTimersByTime(LIMIT); + expect(events).toEqual([`error Composition timeline not found after ${LIMIT / 1000}s`]); expect(player.ready).toBe(false); }); diff --git a/packages/player/tests/browser/sandbox-origin.ts b/packages/player/tests/browser/sandbox-origin.ts index c97ab29ae7..45cd932689 100644 --- a/packages/player/tests/browser/sandbox-origin.ts +++ b/packages/player/tests/browser/sandbox-origin.ts @@ -80,7 +80,8 @@ try { new MessageEvent("message", { data: w.__lastTimeline, source: frame.contentWindow }), ); const started = performance.now(); - while (performance.now() - started < 14_000 && w.__playerError === undefined) + // Linux's 30 s load limit, as on CI, plus slack. + while (performance.now() - started < 36_000 && w.__playerError === undefined) await new Promise((resolve) => setTimeout(resolve, 100)); return w.__playerError ?? null; });