Files
shumai/apps/web/e2e/tests/file/view-transcript.spec.ts
T
Yiling-J d3899d1257 feat(video): add video transcripts (#559)
* feat(video): generate transcripts with the local embedding server

* feat(video): show saved transcripts in the player

* fix(video): preserve transcript seek timestamps

* fix(video): refine transcript viewing and generation

* feat(video): resize transcripts and follow playback earlier

* fix(video): animate transcript playback scrolling

* fix(video): transcribe from the smallest full proxy

* fix(video): refine the sync to playback button

* feat(video): edit transcript segment text inline

* fix(video): keep transcript segment highlighted over edit button

* docs(video): note embedding server version for transcripts
2026-12-04 13:49:25 +08:00

473 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { Locator } from '@playwright/test'
import { expect, test } from '../../fixtures'
import { seedProjectMember } from '../../helpers/team'
test.use({ fileOptions: { mediaType: 'video' } })
test('reads, searches and follows a saved transcript in the video player', async ({
file,
prisma,
}) => {
const { page, projectId, fileId } = file
await page.setViewportSize({ width: 1280, height: 720 })
await page.emulateMedia({ colorScheme: 'dark' })
await expect
.poll(() =>
prisma.asset.findUnique({
where: { id: fileId },
select: { status: true, media: true },
}),
)
.toMatchObject({ status: 'processed', media: { proxyType: 'video' } })
await prisma.assetTranscript.create({
data: {
assetId: fileId,
language: 'en',
model: 'whisper-tiny',
workflowTaskId: 'english-test',
segments: {
create: [
{ position: 0, startMs: 0, endMs: 180, text: 'Signal. signal.' },
...Array.from({ length: 28 }, (_, index) => ({
position: index + 1,
startMs: 300 + index * 12,
endMs: 312 + index * 12,
text: `Intervening segment ${index + 1}`,
})),
{ position: 29, startMs: 720, endMs: 980, text: 'Final signal.' },
{ position: 30, startMs: 995, endMs: 1000, text: 'Closing word.' },
],
},
},
})
await prisma.assetTranscript.create({
data: {
assetId: fileId,
language: 'zh',
model: 'whisper-tiny',
workflowTaskId: 'chinese-test',
segments: { create: { position: 0, startMs: 0, endMs: 700, text: '你好。' } },
},
})
await page.goto(`/projects/${projectId}/files/${fileId}`)
const toggle = page.getByRole('button', { name: 'Show transcript' })
const navigator = page.getByRole('link', { name: 'Preview', exact: true })
await expect(navigator).toBeVisible()
await toggle.click()
const panel = page.getByRole('complementary', { name: 'Transcript' })
const divider = page.getByRole('separator', { name: 'Resize transcript' })
const first = panel.getByRole('button', { name: /Signal\. signal\./ })
const last = panel.getByRole('button', { name: /Final signal\./ })
const video = page.locator('video').first()
const sync = panel.getByRole('button', { name: 'Sync to playback' })
await expect(navigator).toBeHidden()
await expect(panel).toHaveCSS('width', '384px')
await expect(toggle).toHaveAttribute('aria-expanded', 'true')
await expect(toggle).toHaveCSS('cursor', 'pointer')
await expect(first).toHaveAttribute('aria-current', 'true')
await expect(first.getByText('Signal. signal.', { exact: true })).toHaveCSS('font-weight', '700')
await expect(first).toHaveCSS('background-color', 'rgba(0, 0, 0, 0)')
await expect(first).toContainText('00:00.000 – 00:00.180')
const dragDivider = async (handle: Locator, delta: number) => {
const box = await handle.boundingBox()
if (!box) throw new Error('Expected the divider to be visible')
const x = box.x + box.width / 2
const y = box.y + box.height / 2
await page.mouse.move(x, y)
await page.mouse.down()
await page.mouse.move(x + delta, y, { steps: 8 })
await page.mouse.up()
}
await dragDivider(divider, 256)
await expect(panel).toHaveCSS('width', '576px')
await dragDivider(divider, -384)
await expect(panel).toHaveCSS('width', '256px')
await divider.press('ArrowRight')
await expect(divider).toHaveAttribute('aria-valuenow', '21')
await divider.press('Home')
await expect(panel).toHaveCSS('width', '256px')
await dragDivider(divider, 128)
await expect(panel).toHaveCSS('width', '384px')
const viewport = panel.locator('[data-slot=scroll-area-viewport]')
const nearBottomId = await viewport.evaluate((element) => {
const view = element.getBoundingClientRect()
const nearBottom = Array.from(element.querySelectorAll('li[data-segment-id]')).find((row) => {
const { top, bottom } = row.getBoundingClientRect()
return top > view.top + view.height * 0.75 && bottom < view.bottom
})
return nearBottom?.getAttribute('data-segment-id')
})
if (!nearBottomId) throw new Error('Expected a visible segment in the bottom quarter')
const nearBottom = panel
.locator(`[data-segment-id="${nearBottomId}"]`)
.getByRole('button', { name: /Intervening segment/ })
await viewport.evaluate((element) => {
let scrollSteps = 0
const record = () => {
element.setAttribute('data-test-scroll-steps', String(++scrollSteps))
if (scrollSteps === 2) element.removeEventListener('scroll', record)
}
element.addEventListener('scroll', record)
})
await nearBottom.click()
await expect(nearBottom).toHaveAttribute('aria-current', 'true')
await expect
.poll(() =>
nearBottom.evaluate((element) => {
const view = element.closest('[data-slot=scroll-area-viewport]')!.getBoundingClientRect()
const row = element.getBoundingClientRect()
return (row.top + row.height / 2 - view.top) / view.height
}),
)
.toBeCloseTo(0.5, 1)
await expect(viewport).toHaveAttribute('data-test-scroll-steps', '2')
await expect(sync).toBeHidden()
await page.emulateMedia({ reducedMotion: 'reduce' })
await viewport.evaluate((element) => {
let previousTop = element.scrollTop
const record = () => {
const top = element.scrollTop
if (top < previousTop) {
element.setAttribute('data-test-first-reverse-scroll-top', String(top))
element.removeEventListener('scroll', record)
}
previousTop = top
}
element.addEventListener('scroll', record)
})
await video.evaluate((element) => {
const media = element as HTMLVideoElement
media.currentTime = 0
})
await expect(first).toHaveAttribute('aria-current', 'true')
await expect(first).toBeInViewport()
await expect(viewport).toHaveAttribute('data-test-first-reverse-scroll-top', '0')
await page.emulateMedia({ reducedMotion: 'no-preference' })
await panel.getByRole('button', { name: 'Search transcript' }).click()
const search = panel.getByRole('searchbox', { name: 'Search transcript' })
await expect(search).toBeFocused()
await search.fill('SIGNAL.')
await expect(panel.getByText('1 / 3')).toBeVisible()
const match = panel.locator('[data-current-match]')
await expect(match).toHaveCSS('padding-left', '1px')
await expect(match).toHaveCSS('padding-right', '1px')
await panel.getByRole('button', { name: 'Next match' }).click()
await expect(panel.getByText('2 / 3')).toBeVisible()
await search.press('Enter')
await expect(panel.getByText('3 / 3')).toBeVisible()
await expect(last).toBeInViewport()
await expect(first).toHaveAttribute('aria-current', 'true')
await last.click()
await expect(last).toHaveAttribute('aria-current', 'true')
await expect
.poll(() => video.evaluate((element) => (element as HTMLVideoElement).currentTime))
.toBeCloseTo(0.72, 1)
await expect(video).toHaveJSProperty('paused', true)
await panel.getByRole('button', { name: 'Next match' }).click()
await expect(panel.getByText('1 / 3')).toBeVisible()
await panel.getByRole('button', { name: 'Previous match' }).click()
await expect(panel.getByText('3 / 3')).toBeVisible()
await search.fill('unmatched')
await expect(panel.getByText('0 / 0')).toBeVisible()
await search.press('Escape')
await expect(search).toBeHidden()
await sync.click()
await expect(sync).toBeHidden()
await viewport.hover()
await page.mouse.wheel(0, -2500)
await expect(sync).toBeVisible()
await expect(page.locator('html')).toHaveClass('dark')
const background = await panel.evaluate((element) => getComputedStyle(element).backgroundColor)
await expect(sync).toHaveCSS('background-color', background)
await expect(sync.locator('svg')).toHaveCount(0)
expect(
await sync.evaluate(
(element) =>
parseFloat(getComputedStyle(element).borderTopLeftRadius) >= element.clientHeight / 2,
),
).toBe(true)
await sync.hover()
await expect(sync).not.toHaveCSS('background-color', background)
await expect(sync).toHaveCSS('background-color', /^oklch\([^/]+\)$/)
await expect(last).not.toBeInViewport()
await expect(last).toHaveAttribute('aria-current', 'true')
await viewport.evaluate((element) => {
element.addEventListener(
'scroll',
() => {
element.dispatchEvent(new WheelEvent('wheel', { bubbles: true, deltaY: -120 }))
element.setAttribute('data-test-follow-interrupted', 'true')
},
{ once: true },
)
})
await sync.click()
await expect(viewport).toHaveAttribute('data-test-follow-interrupted', 'true')
await expect(sync).toBeVisible()
await expect(last).not.toBeInViewport()
await sync.click()
await expect(last).toBeInViewport()
await expect(sync).toBeHidden()
await video.evaluate((element) => {
const media = element as HTMLVideoElement
media.currentTime = 0.22
})
await expect(panel.locator('[aria-current=true]')).toHaveCount(0)
await video.evaluate((element) => {
const media = element as HTMLVideoElement
media.currentTime = 0
})
await expect(first).toHaveAttribute('aria-current', 'true')
await expect(first).toBeInViewport()
await video.evaluate(async (element) => {
const media = element as HTMLVideoElement
media.playbackRate = 0.5
await media.play()
})
await expect(last).toBeInViewport()
await expect(sync).toBeHidden()
await expect(video).toHaveJSProperty('ended', true)
await last.press('Enter')
await expect(last).toHaveAttribute('aria-current', 'true')
await expect(video).toHaveJSProperty('paused', true)
const closingWord = panel.getByRole('button', { name: /Closing word\./ })
await closingWord.click()
await expect
.poll(() =>
video.evaluate((element) => {
const media = element as HTMLVideoElement
return { seeking: media.seeking, timeMs: Math.round(media.currentTime * 1000) }
}),
)
.toEqual({ seeking: false, timeMs: 995 })
await expect(closingWord).toHaveAttribute('aria-current', 'true')
await expect(video).toHaveJSProperty('paused', true)
await panel.getByRole('combobox', { name: 'Language' }).selectOption('zh')
await expect(panel.getByText('你好。')).toBeVisible()
await expect(last).toHaveCount(0)
await dragDivider(divider, 64)
await expect(panel).toHaveCSS('width', '448px')
await panel.getByRole('button', { name: 'Close transcript' }).click()
await expect(panel).toBeHidden()
await expect(navigator).toBeVisible()
await expect(toggle).toBeFocused()
await toggle.click()
await expect(panel).toHaveCSS('width', '448px')
const commentsDivider = page.locator('main [data-slot="resize-handle"]:not([role="separator"])')
await dragDivider(commentsDivider, -200)
await page.setViewportSize({ width: 840, height: 720 })
await expect
.poll(async () => Number(await divider.getAttribute('aria-valuemax')))
.toBeLessThan(20)
await divider.press('End')
await page.setViewportSize({ width: 1280, height: 720 })
await dragDivider(commentsDivider, 200)
await expect(panel).toHaveCSS('width', '448px')
await panel.getByRole('button', { name: 'Close transcript' }).click()
await page.setViewportSize({ width: 390, height: 844 })
const comments = page.getByTestId('mobile-bottom-sheet')
await expect(comments).toBeVisible()
await toggle.click()
await expect(panel).toBeVisible()
await expect(video).toBeVisible()
await expect(comments).toBeHidden()
await panel.getByRole('button', { name: 'Close transcript' }).click()
await expect(comments).toBeVisible()
})
test('edits segment text inline while preserving timestamps and reviewer access', async ({
file,
browser,
prisma,
}) => {
const { page, context, teamId, projectId, fileId } = file
await expect
.poll(async () => (await prisma.asset.findUnique({ where: { id: fileId } }))?.status)
.toBe('processed')
const transcript = await prisma.assetTranscript.create({
data: {
assetId: fileId,
language: 'en',
model: 'whisper-tiny',
workflowTaskId: 'edit-transcript-test',
segments: { create: { position: 0, startMs: 125, endMs: 950, text: 'Original text' } },
},
include: { segments: true },
})
const [segment] = transcript.segments
const url = `/projects/${projectId}/files/${fileId}`
const editPath = `/api/files/${fileId}/transcripts/en/segments/${segment.id}`
const timestamps = '00:00.125 – 00:00.950'
await page.goto(url)
const toggle = page.getByRole('button', { name: 'Show transcript' })
await toggle.click()
const panel = page.getByRole('complementary', { name: 'Transcript' })
const row = panel.getByRole('listitem')
const seek = row.getByRole('button', { name: /Original text/ })
const edit = row.getByRole('button', { name: 'Edit segment text' })
const draft = row.getByRole('textbox', { name: 'Edit segment text' })
const video = page.locator('video').first()
await expect(edit).toHaveCSS('opacity', '0')
await seek.hover()
await expect(edit).toHaveCSS('opacity', '1')
const highlight = await seek.evaluate((element) => getComputedStyle(element).backgroundColor)
expect(highlight).not.toBe('rgba(0, 0, 0, 0)')
await edit.hover()
await expect(seek).toHaveCSS('background-color', highlight)
await video.evaluate(async (element) => {
const media = element as HTMLVideoElement
media.loop = true
await media.play()
})
await expect(video).toHaveJSProperty('paused', false)
await edit.click()
await expect(video).toHaveJSProperty('paused', true)
await expect(draft).toBeFocused()
await expect(draft).toHaveValue('Original text')
await expect(row.getByText(timestamps)).toBeVisible()
await draft.fill('Discard this draft')
await draft.press('Escape')
await expect(edit).toBeFocused()
await expect(row.getByText('Original text')).toBeVisible()
await panel.getByRole('button', { name: 'Search transcript' }).click()
await panel.getByRole('searchbox').fill('corrected')
await expect(panel.getByText('0 / 0')).toBeVisible()
await edit.click()
await draft.fill('Corrected text')
await page.route(`**${editPath}`, (route) => route.fulfill({ status: 503 }), { times: 1 })
await row.getByRole('button', { name: 'Save', exact: true }).click()
await expect(row.getByRole('alert')).toHaveText('Could not save this segment.')
await expect(draft).toHaveValue('Corrected text')
await row.getByRole('button', { name: 'Save', exact: true }).click()
await expect(row.getByRole('button', { name: /Corrected text/ })).toBeVisible()
await expect(panel.getByText('1 / 1')).toBeVisible()
await expect(video).toHaveJSProperty('paused', true)
const reviewer = await seedProjectMember(
prisma,
teamId,
projectId,
'reviewer',
'project',
browser,
context,
)
const reviewerContext = reviewer.context!
try {
const reviewerPage = await reviewerContext.newPage()
await reviewerPage.goto(url)
await reviewerPage.getByRole('button', { name: 'Show transcript' }).click()
const reviewerPanel = reviewerPage.getByRole('complementary', { name: 'Transcript' })
await expect(reviewerPanel.getByText('Corrected text')).toBeVisible()
await expect(reviewerPanel.getByRole('button', { name: 'Edit segment text' })).toHaveCount(0)
const response = await reviewerContext.request.patch(editPath, { data: { text: 'Denied' } })
expect(response.status()).toBe(403)
} finally {
await reviewerContext.close()
}
await edit.click()
await expect(draft).toHaveValue('Corrected text')
await draft.fill('')
await row.getByRole('button', { name: 'Save', exact: true }).click()
await expect(panel.getByText('0 / 0')).toBeVisible()
await page.reload()
await toggle.click()
await expect(row.getByRole('button', { name: timestamps })).toBeVisible()
await edit.click()
await expect(draft).toHaveValue('')
await row.getByRole('button', { name: 'Cancel' }).click()
await expect(row.getByRole('button', { name: timestamps })).toBeVisible()
expect(await prisma.assetTranscriptSegment.findUnique({ where: { id: segment.id } })).toEqual({
...segment,
text: '',
})
})
test('uses the displayed video version and hides the toggle for versions without a transcript', async ({
file,
prisma,
}) => {
const { page, projectId, fileId, rootFolderId } = file
await expect
.poll(() =>
prisma.asset.findUnique({
where: { id: fileId },
select: { status: true, media: true },
}),
)
.toMatchObject({ status: 'processed', media: { proxyType: 'video' } })
const latest = await prisma.asset.findUniqueOrThrow({ where: { id: fileId } })
if (!latest.media) throw new Error('Expected processed video media')
const stack = await prisma.asset.create({
data: {
projectId,
parentId: rootFolderId,
name: latest.name,
type: 'version_stack',
status: 'processed',
fileCount: 2,
},
})
await prisma.asset.update({
where: { id: fileId },
data: { parentId: stack.id, sortIndex: 'a0' },
})
const old = await prisma.asset.create({
data: {
projectId,
parentId: stack.id,
name: 'Earlier video.mp4',
type: 'file',
status: 'processed',
mediaType: latest.mediaType,
storageKeyId: latest.storageKeyId,
media: latest.media,
sizeByte: latest.sizeByte,
sortIndex: 'a1',
},
})
await prisma.assetTranscript.create({
data: {
assetId: fileId,
language: 'en',
model: 'whisper-tiny',
workflowTaskId: 'latest-version-test',
segments: {
create: { position: 0, startMs: 0, endMs: 950, text: 'Latest version text' },
},
},
})
const stackUrl = `/projects/${projectId}/files/${stack.id}`
await page.goto(stackUrl)
const toggle = page.getByRole('button', { name: 'Show transcript' })
await toggle.click()
const panel = page.getByRole('complementary', { name: 'Transcript' })
await expect(panel.getByText('Latest version text')).toBeVisible()
const [languages] = await Promise.all([
page.waitForResponse(`**/api/files/${old.id}/transcripts`),
page.goto(`${stackUrl}?version=${old.id}`),
])
expect(await languages.json()).toEqual({ languages: [] })
await expect(panel).toBeHidden()
await expect(toggle).toBeHidden()
})