test(webui): add playwright e2e framework with video player play/pause test

Add a Playwright UI integration test framework for the frame-accurate video
player. Tests run against a backend-free harness served by Bun's native HTML
bundler (matching the project's Bun-based dev/prod serving), so no database,
auth or transcode pipeline is required.

- Add @playwright/test with chromium/firefox/webkit projects; the browser is
  selectable via the Playwright --project flag (webkit = Safari engine).
- Serve the harness with Bun.serve + bun-plugin-tailwind (no separate Vite
  toolchain); commit a deterministic 16x16/5s/30fps fixture video and matching
  AssetInfo.
- Add a play/pause spec covering both the play control and clicking the video
  area, asserting the native video clock, seekbar fill and frame readout stay
  frame-locked after pause (settle-aware, tolerance-based assertions).
- Mock all backend API calls (anchored /api/ and /files/ routes) for isolation.
- Exclude e2e specs from Vitest; add a separate CI job (webkit on macOS).
This commit is contained in:
yiling
2026-07-03 14:50:38 +08:00
parent 7c3412686c
commit 469f68b25d
15 changed files with 563 additions and 16 deletions
+41
View File
@@ -55,3 +55,44 @@ jobs:
echo "Smoke testing shumai-transcode..."
bun run /tmp/shumai-local-release/node/node_modules/@shumai-one/shumai-transcode/bin/shumai-transcode-app.js --check
e2e_video_player:
name: E2E (${{ matrix.project }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
project: chromium
- os: ubuntu-latest
project: firefox
# WebKit is the Safari engine; run it on a macOS runner to validate
# Safari compatibility.
- os: macos-latest
project: webkit
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: latest
- name: Install dependencies
run: bun install
- name: Install Playwright browser (${{ matrix.project }})
run: bunx playwright install --with-deps ${{ matrix.project }}
- name: Run video player e2e tests
run: bun run test:e2e --project=${{ matrix.project }}
- name: Upload Playwright report
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v4
with:
name: playwright-report-${{ matrix.project }}
path: playwright-report/
retention-days: 7
+6
View File
@@ -11,3 +11,9 @@ data/
*.db
*.diff
*.orig
# Playwright
/playwright-report/
/test-results/
/blob-report/
/playwright/.cache/
+22 -13
View File
@@ -11,6 +11,7 @@
"devDependencies": {
"@eslint/js": "10.0.1",
"@inlang/paraglide-js": "2.20.0",
"@playwright/test": "1.61.1",
"@testcontainers/postgresql": "12.0.1",
"@types/bun": "1.3.14",
"@types/node": "25.9.1",
@@ -33,7 +34,7 @@
},
"apps/agent": {
"name": "@shumai/agent-app",
"version": "0.1.2",
"version": "0.1.5",
"bin": {
"shumai-agent": "./src/index.ts",
},
@@ -45,7 +46,7 @@
},
"apps/cli": {
"name": "@shumai/cli",
"version": "0.1.2",
"version": "0.1.5",
"bin": {
"shumai-cli": "./src/index.ts",
},
@@ -60,7 +61,7 @@
},
"apps/transcode": {
"name": "@shumai/transcode-app",
"version": "0.1.2",
"version": "0.1.5",
"bin": {
"shumai-transcode": "./src/index.ts",
},
@@ -72,7 +73,7 @@
},
"apps/web": {
"name": "@shumai/web-app",
"version": "0.1.2",
"version": "0.1.5",
"dependencies": {
"@shumai/agent": "workspace:*",
"@shumai/api": "workspace:*",
@@ -87,7 +88,7 @@
},
"packages/agent": {
"name": "@shumai/agent",
"version": "0.1.2",
"version": "0.1.5",
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.52",
"@earendil-works/pi-agent-core": "0.78.0",
@@ -111,7 +112,7 @@
},
"packages/api": {
"name": "@shumai/api",
"version": "0.1.2",
"version": "0.1.5",
"dependencies": {
"@hono/zod-validator": "0.7.6",
"@shumai/core": "workspace:*",
@@ -125,7 +126,7 @@
},
"packages/core": {
"name": "@shumai/core",
"version": "0.1.2",
"version": "0.1.5",
"dependencies": {
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
@@ -152,7 +153,7 @@
},
"packages/db": {
"name": "@shumai/db",
"version": "0.1.2",
"version": "0.1.5",
"dependencies": {
"@earendil-works/pi-agent-core": "0.78.0",
"@prisma/adapter-pg": "7.8.0",
@@ -168,18 +169,18 @@
},
"packages/dtos": {
"name": "@shumai/dtos",
"version": "0.1.2",
"version": "0.1.5",
"dependencies": {
"zod": "4.4.3",
},
},
"packages/tableprinter": {
"name": "@shumai/tableprinter",
"version": "0.1.2",
"version": "0.1.5",
},
"packages/transcode": {
"name": "@shumai/transcode",
"version": "0.1.2",
"version": "0.1.5",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
@@ -193,7 +194,7 @@
},
"packages/webui": {
"name": "@shumai/webui",
"version": "0.1.2",
"version": "0.1.5",
"dependencies": {
"@base-ui/react": "1.5.0",
"@dnd-kit/abstract": "0.4.0",
@@ -294,7 +295,7 @@
},
"packages/workflow-core": {
"name": "@shumai/workflow-core",
"version": "0.1.2",
"version": "0.1.5",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
@@ -761,6 +762,8 @@
"@pkgr/core": ["@pkgr/core@0.3.6", "", {}, "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA=="],
"@playwright/test": ["@playwright/test@1.61.1", "", { "dependencies": { "playwright": "1.61.1" }, "bin": { "playwright": "cli.js" } }, "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig=="],
"@pondwader/socks5-server": ["@pondwader/socks5-server@1.0.10", "", {}, "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg=="],
"@preact/signals-core": ["@preact/signals-core@1.14.2", "", {}, "sha512-RZHdBj9ZF4n40Rp4jS052EHHjBWf96P9oNdXPfhQTovCuWY9iQn3Gq+gOTJSgBO9A/JBuPfMOWsSX/lIU9Pc/A=="],
@@ -2249,6 +2252,10 @@
"pkg-types": ["pkg-types@2.3.1", "", { "dependencies": { "confbox": "^0.2.4", "exsolve": "^1.0.8", "pathe": "^2.0.3" } }, "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg=="],
"playwright": ["playwright@1.61.1", "", { "dependencies": { "playwright-core": "1.61.1" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ=="],
"playwright-core": ["playwright-core@1.61.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg=="],
"possible-typed-array-names": ["possible-typed-array-names@1.1.0", "", {}, "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg=="],
"postcss": ["postcss@8.5.15", "", { "dependencies": { "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A=="],
@@ -3027,6 +3034,8 @@
"pg-types/postgres-array": ["postgres-array@2.0.0", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="],
"playwright/fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
"prisma-json-types-generator/semver": ["semver@7.8.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg=="],
"protobufjs/@types/node": ["@types/node@22.19.19", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew=="],
+6
View File
@@ -18,6 +18,11 @@
"typecheck": "tsc --noEmit",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"test": "bun --bun vitest run",
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui",
"test:e2e:report": "playwright show-report",
"test:e2e:install": "playwright install --with-deps",
"harness:dev": "bun run packages/webui/e2e/harness/serve.ts",
"format": "prettier --write .",
"db:migrate": "bun run prisma migrate dev",
"db:deploy": "bun run prisma migrate deploy",
@@ -38,6 +43,7 @@
"devDependencies": {
"@eslint/js": "10.0.1",
"@inlang/paraglide-js": "2.20.0",
"@playwright/test": "1.61.1",
"@testcontainers/postgresql": "12.0.1",
"@types/bun": "1.3.14",
"@types/node": "25.9.1",
@@ -262,6 +262,7 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
onMouseLeave={handleMouseLeave}
onMouseDown={handleMouseDown}
onTouchStart={handleTouchStart}
data-testid="seekbar"
>
{/* Hidden Preview Video Element */}
<video
@@ -316,6 +317,7 @@ const ProgressBar: React.FC<ProgressBarProps> = ({
<div
className="relative absolute top-0 left-0 h-full rounded-full bg-primary"
style={{ width: `${progressPercent}%` }}
data-testid="seekbar-fill"
>
{/* Thumb (Playhead) - visible on group hover or active */}
<div
@@ -165,7 +165,13 @@ const ControlBar: React.FC<ControlBarProps> = ({
>
{/* Left Side: Play, Vol, Time */}
<div className="flex items-center gap-4">
<button onClick={togglePlay} className="hover:text-primary transition-colors">
<button
onClick={togglePlay}
className="hover:text-primary transition-colors"
data-testid="play-toggle"
data-playing={state.isPlaying}
aria-label={state.isPlaying ? 'Pause' : 'Play'}
>
{state.isPlaying ? (
<Pause className="w-6 h-6 fill-current" />
) : (
@@ -206,7 +212,9 @@ const ControlBar: React.FC<ControlBarProps> = ({
</div>
<div className="flex items-center gap-1 text-sm font-medium tabular-nums select-none min-w-[100px]">
<span className="text-muted-foreground font-mono">{displayString}</span>
<span className="text-muted-foreground font-mono" data-testid="time-readout">
{displayString}
</span>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button className="h-6 w-6 inline-flex items-center justify-center rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer focus:outline-none">
@@ -911,6 +919,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
)}
onClick={togglePlay}
data-vjs-player
data-testid="video-area"
>
{/* Hidden VideoJS container */}
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
Binary file not shown.
+50
View File
@@ -0,0 +1,50 @@
import type { AssetInfo } from '@shumai/dtos'
/**
* Deterministic metadata for the committed fixture video
* (packages/webui/e2e/fixtures/sample.mp4).
*
* Generated with:
* ffmpeg -f lavfi -i testsrc=size=16x16:rate=30 -t 5 -pix_fmt yuv420p sample.mp4
*
* Verified via ffprobe: 16x16, 30/1 fps, duration 5.0s, 150 frames.
* These constants are shared by the harness and the Playwright specs so the
* frame-accurate assertions have known-good expected values.
*/
export const SAMPLE_FRAME_RATE = 30
export const SAMPLE_TOTAL_FRAMES = 150
export const SAMPLE_DURATION = 5
export const SAMPLE_WIDTH = 16
export const SAMPLE_HEIGHT = 16
/**
* The fixture video is served statically by the harness Vite server
* (publicDir points at packages/webui/e2e/fixtures), so it is reachable at
* the site root. No backend is involved.
*/
export const SAMPLE_VIDEO_URL = '/sample.mp4'
export const sampleVideoAsset: AssetInfo = {
id: 'e2e-sample-asset',
name: 'sample.mp4',
sizeByte: 6170,
fileCount: 1,
type: 'file',
status: 'ready',
mediaType: 'video',
createdAt: '2024-01-01T00:00:00.000Z',
updatedAt: '2024-01-01T00:00:00.000Z',
media: {
original: {
downloadUrl: SAMPLE_VIDEO_URL,
key: 'sample.mp4',
},
metadata: {
duration: SAMPLE_DURATION,
originalWidth: SAMPLE_WIDTH,
originalHeight: SAMPLE_HEIGHT,
frameRate: SAMPLE_FRAME_RATE,
totalFrames: SAMPLE_TOTAL_FRAMES,
},
},
}
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="../../globals.css" />
<title>Video Player E2E Harness</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
+37
View File
@@ -0,0 +1,37 @@
import ReactDOM from 'react-dom/client'
import VideoPlayer from '@/ui/components/viewers/video-player'
import { useUiStore } from '@/ui/stores/ui'
import { sampleVideoAsset } from './fixture'
/**
* Backend-free harness page that mounts the *real* VideoPlayer component with a
* fixture AssetInfo pointing at a locally served sample video. No API/router/
* query providers are required for playback, so this isolates the frame-accurate
* player logic (useFramePlayer + ProgressBar + video.js) for UI integration tests.
*
* We force the time readout into "frames" mode so specs can parse the exact
* integer frame index the UI is displaying and assert it against the native
* <video> clock and the seekbar fill.
*/
useUiStore.setState({ videoTimeDisplayMode: 'frames' })
const rootElement = document.getElementById('root')
if (!rootElement) {
throw new Error('Harness root element not found')
}
// Replicate the exact constrained container the real app (file-viewer) mounts
// the player inside: a `flex flex-col flex-1 h-full overflow-hidden` wrapper that
// itself sits in a bounded flex parent. This gives the player root a definite
// 800x600 box and prevents the video area's canvas from feeding its width back
// through the ResizeObserver (which otherwise grows unbounded in a bare stage).
ReactDOM.createRoot(rootElement).render(
<div
data-testid="harness-stage"
style={{ width: '800px', height: '600px', display: 'flex', overflow: 'hidden' }}
>
<div className="flex flex-col flex-1 h-full overflow-hidden relative">
<VideoPlayer data={sampleVideoAsset} />
</div>
</div>,
)
+34
View File
@@ -0,0 +1,34 @@
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import index from './index.html'
/**
* Backend-free harness server for the Playwright e2e suite.
*
* Uses Bun's native HTML bundler (the same path the real app uses via
* `Bun.serve({ routes })` in apps/web) so the test toolchain matches the
* project's Bun-based dev/prod serving. Tailwind is applied through the
* `bun-plugin-tailwind` entry configured in the repo's bunfig.toml
* ([serve.static]). It serves:
* - the harness page (index.html -> main.tsx, bundled on the fly), and
* - the committed fixture video from ../fixtures at the site root.
*/
const here = dirname(fileURLToPath(import.meta.url))
const fixturesDir = join(here, '..', 'fixtures')
const port = process.env.HARNESS_PORT ? Number(process.env.HARNESS_PORT) : 5199
const server = Bun.serve({
port,
development: true,
routes: {
'/sample.mp4': () =>
new Response(Bun.file(join(fixturesDir, 'sample.mp4')), {
headers: { 'Content-Type': 'video/mp4' },
}),
'/': index,
'/*': index,
},
})
console.log(`🎬 Video player harness running at ${server.url}`)
@@ -0,0 +1,139 @@
import type { Locator, Page } from '@playwright/test'
import { SAMPLE_FRAME_RATE, SAMPLE_TOTAL_FRAMES } from '../harness/fixture'
const VIDEO_SELECTOR = '[data-testid="video-area"] video'
/**
* Snapshot of the player's synchronized state, read from the three independent
* surfaces that must stay frame-locked:
* - the native <video> element (video.js engine / media clock),
* - the seekbar fill (derived from useFramePlayer's currentFrame),
* - the numeric frame readout (also derived from currentFrame).
*/
export interface PlayerSnapshot {
paused: boolean
ended: boolean
currentTime: number
/** Frame index implied by the native media clock: floor(t * fps + 0.45). */
nativeFrame: number
/** Frame index shown in the "N / M fr" readout. */
readoutFrame: number
/** Seekbar fill width as a fraction (0..1) of the track width. */
seekbarFraction: number
}
export class VideoPlayerPage {
readonly page: Page
readonly stage: Locator
readonly videoArea: Locator
readonly playToggle: Locator
readonly video: Locator
readonly seekbar: Locator
readonly seekbarFill: Locator
readonly timeReadout: Locator
constructor(page: Page) {
this.page = page
this.stage = page.getByTestId('harness-stage')
this.videoArea = page.getByTestId('video-area')
this.playToggle = page.getByTestId('play-toggle')
this.video = page.locator(VIDEO_SELECTOR).first()
this.seekbar = page.getByTestId('seekbar')
this.seekbarFill = page.getByTestId('seekbar-fill')
this.timeReadout = page.getByTestId('time-readout')
}
async goto(): Promise<void> {
await this.page.goto('/')
await this.waitUntilReady()
}
/** Wait until the video.js engine has metadata and a usable frame readout. */
async waitUntilReady(): Promise<void> {
await this.video.waitFor({ state: 'attached' })
await this.page.waitForFunction(
(selector) => {
const el = document.querySelector(selector) as HTMLVideoElement | null
return !!el && el.readyState >= 1 /* HAVE_METADATA */ && Number.isFinite(el.duration)
},
VIDEO_SELECTOR,
{ timeout: 15_000 },
)
// The readout renders "N / M fr" once currentFrame state is wired up.
await this.page.waitForFunction(
(selector) => /\d+\s*\/\s*\d+\s*fr/.test(document.querySelector(selector)?.textContent ?? ''),
'[data-testid="time-readout"]',
{ timeout: 15_000 },
)
}
/**
* Some engines (notably WebKit headless) refuse to start playback for a clip
* that could produce sound without an explicit muted flag. The fixture has no
* audio track, but we mute defensively so play() resolves consistently.
*/
async muteNativeVideo(): Promise<void> {
await this.video.evaluate((el: HTMLVideoElement) => {
el.muted = true
})
}
async isPaused(): Promise<boolean> {
return this.video.evaluate((el: HTMLVideoElement) => el.paused)
}
async currentTime(): Promise<number> {
return this.video.evaluate((el: HTMLVideoElement) => el.currentTime)
}
private async readoutFrame(): Promise<number> {
const text = (await this.timeReadout.textContent()) ?? ''
const match = text.match(/(\d+)\s*\/\s*\d+\s*fr/)
return match ? Number.parseInt(match[1], 10) : Number.NaN
}
private async seekbarFraction(): Promise<number> {
const track = await this.seekbar.boundingBox()
const fill = await this.seekbarFill.boundingBox()
if (!track || !fill || track.width === 0) return 0
return fill.width / track.width
}
/** Read a coherent snapshot of all three synchronized surfaces. */
async snapshot(): Promise<PlayerSnapshot> {
const [native, readoutFrame, seekbarFraction] = await Promise.all([
this.video.evaluate((el: HTMLVideoElement, fps: number) => {
return {
paused: el.paused,
ended: el.ended,
currentTime: el.currentTime,
nativeFrame: Math.floor(el.currentTime * fps + 0.45),
}
}, SAMPLE_FRAME_RATE),
this.readoutFrame(),
this.seekbarFraction(),
])
return {
paused: native.paused,
ended: native.ended,
currentTime: native.currentTime,
nativeFrame: native.nativeFrame,
readoutFrame,
seekbarFraction,
}
}
clickPlayToggle(): Promise<void> {
return this.playToggle.click()
}
clickVideoArea(): Promise<void> {
// The drawing-canvas overlay is pointer-events:none when not drawing, so the
// click lands on the video-area div and triggers togglePlay.
return this.videoArea.click({ position: { x: 20, y: 20 } })
}
}
export const FRAME_RATE = SAMPLE_FRAME_RATE
export const TOTAL_FRAMES = SAMPLE_TOTAL_FRAMES
+141
View File
@@ -0,0 +1,141 @@
import { expect, test } from '@playwright/test'
import { FRAME_RATE, TOTAL_FRAMES, VideoPlayerPage } from '../pages/video-player.page'
/**
* Pure UI integration test for the frame-accurate video player.
*
* The player keeps three surfaces in lockstep off a single `currentFrame` state:
* 1. the native <video> element (video.js media clock),
* 2. the seekbar fill, and
* 3. the numeric frame readout.
*
* On pause, useFramePlayer snaps the native clock to the paused frame's center
* time, so after a short settle the native frame, the readout frame and the
* seekbar fill must all agree. We assert that invariant here rather than trusting
* any single surface.
*/
const SEEKBAR_TOLERANCE = 0.01 // fraction of the track (~1%), covers sub-pixel + thumb rounding
const HALF_FRAME_SECONDS = 1 / (2 * FRAME_RATE)
test.beforeEach(async ({ page }) => {
// Mock every backend call so this stays a pure frontend test. The player never
// hits the API during play/pause, but this guarantees isolation regardless.
//
// NOTE: the patterns are anchored to the origin root (/api/, /files/) so they
// only match real backend requests and NOT Vite-served source modules whose
// paths happen to contain those segments (e.g. /packages/webui/api/client.ts).
await page.route(/^https?:\/\/[^/]+\/(api|files)\//, (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }),
)
})
/**
* Wait until the player has settled to a stable, paused, fully-synchronized
* frame, then assert the native clock, the readout and the seekbar all agree.
*/
async function expectPausedAndSynchronized(vp: VideoPlayerPage): Promise<void> {
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(true)
// Wait for the pause snap + external-seek nudge to fully settle: currentTime
// stops changing between consecutive reads.
await expect
.poll(
async () => {
const a = await vp.currentTime()
await vp.page.waitForTimeout(80)
const b = await vp.currentTime()
return Math.abs(b - a) < 1e-3
},
{ timeout: 5_000 },
)
.toBe(true)
// The UI frame and the native-clock frame converge on the same integer.
await expect
.poll(
async () => {
const snap = await vp.snapshot()
return snap.readoutFrame === snap.nativeFrame
},
{ timeout: 5_000 },
)
.toBe(true)
const snap = await vp.snapshot()
expect(snap.paused).toBe(true)
// Readout <-> native media clock.
expect(snap.readoutFrame).toBe(snap.nativeFrame)
// Seekbar fill <-> frame index.
expect(Math.abs(snap.seekbarFraction - snap.nativeFrame / TOTAL_FRAMES)).toBeLessThan(
SEEKBAR_TOLERANCE,
)
// Native clock is snapped to the paused frame's center time.
const frameCenter = snap.nativeFrame / FRAME_RATE + HALF_FRAME_SECONDS
expect(Math.abs(snap.currentTime - frameCenter)).toBeLessThan(HALF_FRAME_SECONDS + 1e-6)
}
/** Assert the player is genuinely stopped: the frame does not advance over time. */
async function expectPlayheadStopped(vp: VideoPlayerPage): Promise<void> {
const first = await vp.snapshot()
await vp.page.waitForTimeout(300)
const second = await vp.snapshot()
// The integer frame is the robust "not advancing" signal.
expect(second.readoutFrame).toBe(first.readoutFrame)
// currentTime must not advance meaningfully. A playing video would move ~0.3s
// in 300ms; a stopped one moves less than a frame (browser seeks land *near*,
// not exactly on, the requested frame-center, and the pause snap may still be
// settling), so half a frame cleanly separates stopped from playing.
expect(Math.abs(second.currentTime - first.currentTime)).toBeLessThan(HALF_FRAME_SECONDS)
}
test.describe('video player play/pause', () => {
test('toggles via the play/pause control', async ({ page }) => {
const vp = new VideoPlayerPage(page)
await vp.goto()
await vp.muteNativeVideo()
// Starts paused at frame 0.
const initial = await vp.snapshot()
expect(initial.paused).toBe(true)
expect(initial.readoutFrame).toBe(0)
// Play via the control -> playback starts and the readout advances.
await vp.clickPlayToggle()
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(false)
await expect
.poll(async () => (await vp.snapshot()).readoutFrame, { timeout: 5_000 })
.toBeGreaterThan(initial.readoutFrame)
// Pause via the control -> everything re-synchronizes and stays put.
await vp.clickPlayToggle()
await expectPausedAndSynchronized(vp)
await expectPlayheadStopped(vp)
})
test('toggles via clicking the video area', async ({ page }) => {
const vp = new VideoPlayerPage(page)
await vp.goto()
await vp.muteNativeVideo()
const initial = await vp.snapshot()
expect(initial.paused).toBe(true)
expect(initial.readoutFrame).toBe(0)
// Click the video surface to play.
await vp.clickVideoArea()
await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(false)
await expect
.poll(async () => (await vp.snapshot()).readoutFrame, { timeout: 5_000 })
.toBeGreaterThan(initial.readoutFrame)
// Click again to pause -> native clock, readout and seekbar agree.
await vp.clickVideoArea()
await expectPausedAndSynchronized(vp)
await expectPlayheadStopped(vp)
})
})
+57
View File
@@ -0,0 +1,57 @@
import { defineConfig, devices } from '@playwright/test'
/**
* Playwright configuration for the webui UI integration tests.
*
* The suite runs against a backend-free harness (packages/webui/e2e) served by
* Bun's native HTML bundler, so no database, auth or transcode pipeline is
* required.
*
* Browser selection: pass `--project=<name>` to pick an engine, e.g.
* bun run test:e2e --project=webkit # WebKit (Safari engine), used on macOS CI
* bun run test:e2e --project=chromium
* bun run test:e2e --project=firefox
*/
export default defineConfig({
testDir: './packages/webui/e2e/tests',
testMatch: '**/*.spec.ts',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: process.env.CI ? [['list'], ['html', { open: 'never' }]] : 'list',
timeout: 60_000,
expect: { timeout: 10_000 },
use: {
// `baseURL` is Playwright's required option key and cannot be renamed.
// eslint-disable-next-line @typescript-eslint/naming-convention
baseURL: 'http://localhost:5199',
trace: 'on-first-retry',
video: 'retain-on-failure',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
],
// Launch the isolated harness dev server (Bun's native HTML bundler) before
// the tests.
webServer: {
command: 'bun run packages/webui/e2e/harness/serve.ts',
url: 'http://localhost:5199',
reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
})
+4 -1
View File
@@ -1,5 +1,5 @@
import tsconfigPaths from 'vite-tsconfig-paths'
import { defineConfig } from 'vitest/config'
import { configDefaults, defineConfig } from 'vitest/config'
export default defineConfig({
plugins: [tsconfigPaths()],
@@ -7,6 +7,9 @@ export default defineConfig({
globalSetup: './packages/db/src/test-global-setup.ts',
globals: false,
pool: 'forks',
// Playwright e2e specs live under packages/webui/e2e and are run by the
// Playwright runner (bun run test:e2e), not Vitest.
exclude: [...configDefaults.exclude, 'packages/webui/e2e/**'],
server: {
deps: {
inline: ['zod'],