mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 00:49:28 +00:00
test(webui): add frame-accurate comment seek roundtrip e2e
Extend the backend-free video-player harness with the app's real comment↔player wiring (onTimeUpdate capture, player.currentTime(second) seek on comment click, and a remount to simulate a second user) and add a Playwright spec. User A comments on 5 distinct random frames (regenerated each run); user B reloads and clicks each comment. Asserts the seconds-based roundtrip is loss-free: frameA -> second=frameA/fps -> seek(second) -> floor(second*fps+0.45) == frameA, so the comment is stored at the frame the author saw and the reader lands on that exact frame.
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
import { type ReactElement, useCallback, useRef, useState } from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import type Player from 'video.js/dist/types/player'
|
||||
import VideoPlayer from '@/ui/components/viewers/video-player'
|
||||
import { calculateFrameCenterTime } from '@/ui/components/viewers/utils'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import { sampleVideoAsset } from './fixture'
|
||||
import { SAMPLE_FRAME_RATE, sampleVideoAsset } from './fixture'
|
||||
|
||||
/**
|
||||
* Backend-free harness page that mounts the *real* VideoPlayer component with a
|
||||
@@ -12,26 +15,143 @@ import { sampleVideoAsset } from './fixture'
|
||||
* 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.
|
||||
*
|
||||
* On top of the bare player, this harness reproduces — with the app's *real*
|
||||
* code paths — the comment↔player wiring that production uses
|
||||
* (`routes/projects/$projectId/files/$fileId.tsx` + `file-viewer.tsx`):
|
||||
*
|
||||
* - `onTimeUpdate` captures the player's current time in seconds. This is the
|
||||
* exact value the app stores as a comment's `second` (see message-input's
|
||||
* `onSendMessage(..., currentTime)`).
|
||||
* - "Create comment" snapshots that `second` and appends a comment. Each
|
||||
* comment renders its derived frame `Math.round(second * fps)`, matching
|
||||
* message-card's timestamp derivation.
|
||||
* - Clicking a comment runs the app's real seek: `player.currentTime(second)`
|
||||
* followed by `player.pause()`, exactly like the route's
|
||||
* `handleCommentSelect`. That raw seek drives useFramePlayer's external
|
||||
* `seeked` handler, which recomputes the frame from the media clock.
|
||||
* - "Reload as user B" remounts the player with a fresh key (starting at
|
||||
* frame 0) to simulate a second user opening the page, while the comment
|
||||
* list persists.
|
||||
*
|
||||
* All comment controls live OUTSIDE the player's constrained 800x600 box so the
|
||||
* player's layout is byte-for-byte identical to what play-pause.spec.ts expects
|
||||
* (the box constraint prevents the drawing-canvas ResizeObserver from feeding
|
||||
* its width back and growing unbounded).
|
||||
*/
|
||||
useUiStore.setState({ videoTimeDisplayMode: 'frames' })
|
||||
|
||||
interface HarnessComment {
|
||||
id: string
|
||||
second: number
|
||||
frame: number
|
||||
}
|
||||
|
||||
function Harness(): ReactElement {
|
||||
const playerRef = useRef<Player | null>(null)
|
||||
// Latest player time (seconds) as reported by the real onTimeUpdate prop.
|
||||
const currentTimeRef = useRef<number>(0)
|
||||
const seekInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const [comments, setComments] = useState<HarnessComment[]>([])
|
||||
// Bumping this key remounts VideoPlayer, simulating a fresh page load (user B).
|
||||
const [playerKey, setPlayerKey] = useState<number>(0)
|
||||
|
||||
const handleTimeUpdate = useCallback((time: number) => {
|
||||
currentTimeRef.current = time
|
||||
}, [])
|
||||
|
||||
// Deterministic setup seek for "user A": land exactly on a target frame using
|
||||
// a real external seek to the frame-center time (the same class of seek the
|
||||
// timeline/comment paths use). This positions the player without depending on
|
||||
// the thing under test (the comment roundtrip).
|
||||
const handleSeekToFrame = useCallback(() => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
const frame = Number.parseInt(seekInputRef.current?.value ?? '', 10)
|
||||
if (Number.isNaN(frame)) return
|
||||
player.currentTime(calculateFrameCenterTime(frame, SAMPLE_FRAME_RATE))
|
||||
player.pause()
|
||||
}, [])
|
||||
|
||||
// "User A" creates a comment: captures the current time in seconds exactly as
|
||||
// the app does, then derives the displayed frame the same way message-card does.
|
||||
const handleCreateComment = useCallback(() => {
|
||||
const second = currentTimeRef.current
|
||||
setComments((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: `comment-${prev.length}`,
|
||||
second,
|
||||
frame: Math.round(second * SAMPLE_FRAME_RATE),
|
||||
},
|
||||
])
|
||||
}, [])
|
||||
|
||||
// "User B" clicks a comment: the app's real seek path.
|
||||
const handleCommentClick = useCallback((second: number) => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
player.currentTime(second)
|
||||
player.pause()
|
||||
}, [])
|
||||
|
||||
const handleReloadAsUserB = useCallback(() => {
|
||||
setPlayerKey((k) => k + 1)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Player box: identical constrained container to the real file-viewer. */}
|
||||
<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
|
||||
key={playerKey}
|
||||
data={sampleVideoAsset}
|
||||
playerRef={playerRef}
|
||||
onTimeUpdate={handleTimeUpdate}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Comment controls: kept outside the player box so they cannot affect its
|
||||
layout / ResizeObserver behaviour. */}
|
||||
<div data-testid="comment-panel">
|
||||
<input ref={seekInputRef} data-testid="seek-frame-input" type="number" />
|
||||
<button data-testid="seek-frame-go" onClick={handleSeekToFrame}>
|
||||
Seek to frame
|
||||
</button>
|
||||
<button data-testid="create-comment" onClick={handleCreateComment}>
|
||||
Create comment
|
||||
</button>
|
||||
<button data-testid="reload-user-b" onClick={handleReloadAsUserB}>
|
||||
Reload as user B
|
||||
</button>
|
||||
<ul data-testid="comment-list">
|
||||
{comments.map((comment, index) => (
|
||||
<li
|
||||
key={comment.id}
|
||||
data-testid="comment-item"
|
||||
data-comment-index={index}
|
||||
data-comment-frame={comment.frame}
|
||||
data-comment-second={comment.second}
|
||||
onClick={() => handleCommentClick(comment.second)}
|
||||
>
|
||||
Frame {comment.frame}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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>,
|
||||
)
|
||||
ReactDOM.createRoot(rootElement).render(<Harness />)
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
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 two independent
|
||||
* surfaces that must stay frame-locked after a seek:
|
||||
* - the native <video> element (video.js engine / media clock),
|
||||
* - the numeric frame readout (derived from useFramePlayer's currentFrame).
|
||||
*/
|
||||
export interface CommentSeekSnapshot {
|
||||
paused: 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Page object for the comment-seek scenario. It drives the extended video-player
|
||||
* harness that reproduces the app's real comment↔player wiring: capturing a
|
||||
* comment's `second` from `onTimeUpdate`, seeking on comment click via
|
||||
* `player.currentTime(second)`, and remounting the player to simulate a second
|
||||
* user opening the page.
|
||||
*/
|
||||
export class CommentSeekPage {
|
||||
readonly page: Page
|
||||
readonly video: Locator
|
||||
readonly timeReadout: Locator
|
||||
readonly seekFrameInput: Locator
|
||||
readonly seekFrameGo: Locator
|
||||
readonly createComment: Locator
|
||||
readonly reloadUserB: Locator
|
||||
readonly commentItems: Locator
|
||||
|
||||
constructor(page: Page) {
|
||||
this.page = page
|
||||
this.video = page.locator(VIDEO_SELECTOR).first()
|
||||
this.timeReadout = page.getByTestId('time-readout')
|
||||
this.seekFrameInput = page.getByTestId('seek-frame-input')
|
||||
this.seekFrameGo = page.getByTestId('seek-frame-go')
|
||||
this.createComment = page.getByTestId('create-comment')
|
||||
this.reloadUserB = page.getByTestId('reload-user-b')
|
||||
this.commentItems = page.getByTestId('comment-item')
|
||||
}
|
||||
|
||||
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 },
|
||||
)
|
||||
await this.page.waitForFunction(
|
||||
(selector) => /\d+\s*\/\s*\d+\s*fr/.test(document.querySelector(selector)?.textContent ?? ''),
|
||||
'[data-testid="time-readout"]',
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The fixture has no audio track, but WebKit headless can refuse to start
|
||||
* playback for a potentially-audible clip without an explicit muted flag. We
|
||||
* never play here, but mute defensively to keep engine behaviour consistent.
|
||||
*/
|
||||
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
|
||||
}
|
||||
|
||||
/** Read a coherent snapshot of the native clock and the frame readout. */
|
||||
async snapshot(): Promise<CommentSeekSnapshot> {
|
||||
const [native, readoutFrame] = await Promise.all([
|
||||
this.video.evaluate((el: HTMLVideoElement, fps: number) => {
|
||||
return {
|
||||
paused: el.paused,
|
||||
currentTime: el.currentTime,
|
||||
nativeFrame: Math.floor(el.currentTime * fps + 0.45),
|
||||
}
|
||||
}, SAMPLE_FRAME_RATE),
|
||||
this.readoutFrame(),
|
||||
])
|
||||
|
||||
return {
|
||||
paused: native.paused,
|
||||
currentTime: native.currentTime,
|
||||
nativeFrame: native.nativeFrame,
|
||||
readoutFrame,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministically position the player on an exact frame (simulating user A
|
||||
* scrubbing there) and wait until it has fully settled: paused, with the
|
||||
* native clock and the readout both agreeing on the target frame.
|
||||
*/
|
||||
async seekToFrame(frame: number): Promise<void> {
|
||||
await this.seekFrameInput.fill(String(frame))
|
||||
await this.seekFrameGo.click()
|
||||
await this.waitUntilSettledOn(frame)
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait until the player has settled to a stable, paused frame whose native
|
||||
* clock and readout both equal `frame`.
|
||||
*/
|
||||
async waitUntilSettledOn(frame: number): Promise<void> {
|
||||
// currentTime stops changing between consecutive reads (seek + nudge done).
|
||||
await this.page.waitForFunction(
|
||||
async (selector) => {
|
||||
const el = document.querySelector(selector) as HTMLVideoElement | null
|
||||
if (!el) return false
|
||||
const a = el.currentTime
|
||||
await new Promise((r) => setTimeout(r, 80))
|
||||
return Math.abs(el.currentTime - a) < 1e-3
|
||||
},
|
||||
VIDEO_SELECTOR,
|
||||
{ timeout: 5_000 },
|
||||
)
|
||||
// Native clock and readout converge on the requested integer frame.
|
||||
await this.expectFrameSettled(frame)
|
||||
}
|
||||
|
||||
private async expectFrameSettled(frame: number): Promise<void> {
|
||||
await this.page.waitForFunction(
|
||||
({ selector, fps, target }) => {
|
||||
const el = document.querySelector(selector) as HTMLVideoElement | null
|
||||
if (!el || !el.paused) return false
|
||||
const nativeFrame = Math.floor(el.currentTime * fps + 0.45)
|
||||
const readoutEl = document.querySelector('[data-testid="time-readout"]')
|
||||
const match = (readoutEl?.textContent ?? '').match(/(\d+)\s*\/\s*\d+\s*fr/)
|
||||
const readoutFrame = match ? Number.parseInt(match[1], 10) : Number.NaN
|
||||
return nativeFrame === target && readoutFrame === target
|
||||
},
|
||||
{ selector: VIDEO_SELECTOR, fps: SAMPLE_FRAME_RATE, target: frame },
|
||||
{ timeout: 5_000 },
|
||||
)
|
||||
}
|
||||
|
||||
async clickCreateComment(): Promise<void> {
|
||||
const before = await this.commentItems.count()
|
||||
await this.createComment.click()
|
||||
await this.page.waitForFunction(
|
||||
(expected) => document.querySelectorAll('[data-testid="comment-item"]').length === expected,
|
||||
before + 1,
|
||||
{ timeout: 5_000 },
|
||||
)
|
||||
}
|
||||
|
||||
async commentCount(): Promise<number> {
|
||||
return this.commentItems.count()
|
||||
}
|
||||
|
||||
/** The derived frame indices shown on each comment, in list order. */
|
||||
async commentFrames(): Promise<number[]> {
|
||||
const values = await this.commentItems.evaluateAll((nodes) =>
|
||||
nodes.map((n) => Number.parseInt(n.getAttribute('data-comment-frame') ?? '', 10)),
|
||||
)
|
||||
return values
|
||||
}
|
||||
|
||||
clickCommentByIndex(index: number): Promise<void> {
|
||||
return this.commentItems.nth(index).click()
|
||||
}
|
||||
|
||||
/** Simulate a second user opening the page: remount the player at frame 0. */
|
||||
async reloadAsUserB(): Promise<void> {
|
||||
await this.reloadUserB.click()
|
||||
await this.waitUntilReady()
|
||||
}
|
||||
}
|
||||
|
||||
export const FRAME_RATE = SAMPLE_FRAME_RATE
|
||||
export const TOTAL_FRAMES = SAMPLE_TOTAL_FRAMES
|
||||
@@ -0,0 +1,110 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { CommentSeekPage, TOTAL_FRAMES } from '../pages/comment-seek.page'
|
||||
|
||||
/**
|
||||
* Frame-accurate comment seek roundtrip.
|
||||
*
|
||||
* Simulates two users against the *real* comment↔player wiring:
|
||||
* 1. User A scrubs to a frame, pauses, and creates a comment. The app stores
|
||||
* the comment's timestamp as `second = currentFrame / fps` (a float in
|
||||
* seconds — never a frame integer), captured via the player's real
|
||||
* `onTimeUpdate` prop.
|
||||
* 2. User B opens the page fresh (the player remounts at frame 0) and clicks
|
||||
* the comment, which runs the app's real seek `player.currentTime(second)`.
|
||||
* useFramePlayer then recomputes the frame from the media clock as
|
||||
* `floor(second * fps + 0.45)`.
|
||||
*
|
||||
* The invariant under test is that this seconds-based roundtrip is loss-free:
|
||||
* frameA -> second = frameA/fps -> (stored) -> seek(second)
|
||||
* -> floor(second*fps + 0.45) == frameA
|
||||
*
|
||||
* We exercise it on 5 distinct frames chosen randomly on every run, so any
|
||||
* off-by-one in the conversion surfaces across runs and is caught deterministically
|
||||
* for the sampled frames within a run.
|
||||
*/
|
||||
|
||||
const COMMENT_COUNT = 5
|
||||
|
||||
/**
|
||||
* Pick `count` distinct random frame indices in a safe range. We avoid frame 0
|
||||
* (the player's post-reload starting state, so "seeked back" is a real change)
|
||||
* and the final frame (to dodge the native `ended` edge case).
|
||||
*/
|
||||
function pickRandomFrames(count: number): number[] {
|
||||
const min = 1
|
||||
const max = TOTAL_FRAMES - 2
|
||||
const chosen = new Set<number>()
|
||||
while (chosen.size < count) {
|
||||
chosen.add(min + Math.floor(Math.random() * (max - min + 1)))
|
||||
}
|
||||
return [...chosen].sort((a, b) => a - b)
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// Mock every backend call so this stays a pure frontend test. The harness never
|
||||
// hits the API, but this guarantees isolation regardless. Patterns are anchored
|
||||
// to the origin root so they don't match Vite-served source modules.
|
||||
await page.route(/^https?:\/\/[^/]+\/(api|files)\//, (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }),
|
||||
)
|
||||
})
|
||||
|
||||
test.describe('video player comment seek roundtrip', () => {
|
||||
test('user A comments on 5 random frames, user B seeks back to each', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const frames = pickRandomFrames(COMMENT_COUNT)
|
||||
// Record the sampled frames so a failing run is reproducible.
|
||||
testInfo.annotations.push({ type: 'random-frames', description: frames.join(', ') })
|
||||
|
||||
const cs = new CommentSeekPage(page)
|
||||
await cs.goto()
|
||||
await cs.muteNativeVideo()
|
||||
|
||||
// Starts paused at frame 0.
|
||||
const initial = await cs.snapshot()
|
||||
expect(initial.paused).toBe(true)
|
||||
expect(initial.readoutFrame).toBe(0)
|
||||
|
||||
// -- Phase A: user A authors a comment on each random frame. --
|
||||
for (const frame of frames) {
|
||||
await cs.seekToFrame(frame)
|
||||
|
||||
// The frame user A is actually looking at (readout and native clock agree).
|
||||
const authored = await cs.snapshot()
|
||||
expect(authored.paused).toBe(true)
|
||||
expect(authored.readoutFrame).toBe(frame)
|
||||
expect(authored.nativeFrame).toBe(frame)
|
||||
|
||||
await cs.clickCreateComment()
|
||||
|
||||
// Goal 1: the comment is stored at exactly the frame user A saw.
|
||||
const commentFrames = await cs.commentFrames()
|
||||
expect(commentFrames[commentFrames.length - 1]).toBe(frame)
|
||||
}
|
||||
|
||||
// All five comments exist and correspond, in order, to the authored frames.
|
||||
expect(await cs.commentCount()).toBe(COMMENT_COUNT)
|
||||
expect(await cs.commentFrames()).toEqual(frames)
|
||||
|
||||
// -- Phase B: a second user opens the page fresh (player remounts at 0). --
|
||||
await cs.reloadAsUserB()
|
||||
await cs.muteNativeVideo()
|
||||
const afterReload = await cs.snapshot()
|
||||
expect(afterReload.readoutFrame).toBe(0)
|
||||
|
||||
// Clicking each comment lands the player back on exactly user A's frame.
|
||||
const commentFrames = await cs.commentFrames()
|
||||
for (let index = 0; index < commentFrames.length; index++) {
|
||||
const frame = commentFrames[index]
|
||||
await cs.clickCommentByIndex(index)
|
||||
await cs.waitUntilSettledOn(frame)
|
||||
|
||||
// Goal 2: user B sees exactly the frame user A commented on.
|
||||
const seen = await cs.snapshot()
|
||||
expect(seen.paused).toBe(true)
|
||||
expect(seen.readoutFrame).toBe(frame)
|
||||
expect(seen.nativeFrame).toBe(frame)
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user