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
This commit is contained in:
Yiling-J
2026-12-04 13:49:25 +08:00
committed by GitHub
parent e420f03b35
commit d3899d1257
69 changed files with 7635 additions and 174 deletions
+1
View File
@@ -10,6 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- **sessions**: See total tokens and estimated cost in the session logs footer, with a breakdown of input, output, and cached tokens.
- **projects**: Middle-click or Command/Ctrl-click a project to open it in a new tab. Use **Open in new tab** in a file or folder's context menu to keep your current view open.
- **video**: Update your local embedding server to v0.1.3 to generate video transcripts. Choose a language or detect it automatically, then open the transcript in the video player to switch languages, follow playback, search the text, jump to a segment, or edit its text.
### Fixed
+3
View File
@@ -76,6 +76,7 @@ apps/web/e2e/
| Owner creates a project with a cover image | `tests/project/create-project.spec.ts` |
| Owner opens project cards in new tabs with middle-click and modifier-click | `tests/project/open-in-new-tab.spec.ts` |
| Owner opens a folder card and a file row in new tabs from the context menu | `tests/project/open-in-new-tab.spec.ts` |
| Owner opens transcript generation from a video context menu, selects a language, and sees completion | `tests/project/generate-transcripts.spec.ts` |
| Owner uploads a file or an unsupported file via the "Upload File" context menu action | `tests/project/upload-file.spec.ts` |
| Owner deletes a file, finds it in recently deleted, and restores it | `tests/project/delete-restore.spec.ts` |
| Owner deletes a folder and still sees its contents preview and countdown in recently deleted | `tests/project/delete-restore.spec.ts` |
@@ -120,6 +121,8 @@ apps/web/e2e/
| Upload a txt file, wait for transcode, and create a comment with draw | `tests/file/txt-draw-comment.spec.ts` |
| Upload an image file, wait for transcode, and create a comment with draw | `tests/file/image-draw-comment.spec.ts` |
| Upload a video file, wait for transcode, and create a comment with draw at a non-zero timestamp | `tests/file/video-draw-comment.spec.ts` |
| Read and search saved video transcripts, resize the desktop panel, jump to a segment, verify smooth playback following and interruption, and check mobile and version-stack behavior | `tests/file/view-transcript.spec.ts` |
| Edit video transcript text inline, verify playback pauses and timestamps survive a blank edit, retry a failed save, and check reviewer permissions | `tests/file/view-transcript.spec.ts` |
| Upload an audio file, wait for transcode, and create a comment at a non-zero timestamp | `tests/file/audio-timestamp-comment.spec.ts` |
| Create internal and public comments, verify internal comments are hidden on public share links | `tests/file/internal-comment-and-edit.spec.ts` |
| Author edits comment text, switches to internal, removes timestamp, and updates attachments | `tests/file/internal-comment-and-edit.spec.ts` |
@@ -0,0 +1,472 @@
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()
})
@@ -0,0 +1,87 @@
import { expect, test } from '../../fixtures'
import { fileCard } from '../../helpers/files'
import type { TranscriptJobStatus } from '@shumai/dtos'
test.use({ fileOptions: { mediaType: 'video' } })
test('selects a transcription language from the video context menu and tracks the job', async ({
file,
prisma,
}) => {
const { page, projectId, fileId, fileName } = file
let status: TranscriptJobStatus = { taskId: 'previous-transcript', status: 'completed' }
const expectedLanguages = ['zh', 'en']
let submissions = 0
await page.route('**/api/signup-info', async (route) => {
const response = await route.fetch()
await route.fulfill({ json: { ...(await response.json()), transcriptionEnabled: true } })
})
await page.route('**/api/transcription/languages', (route) =>
route.fulfill({
json: {
model: 'whisper-tiny',
languages: [
{ code: 'en', name: 'English' },
{ code: 'zh', name: 'Chinese' },
],
},
}),
)
await page.route(`**/api/files/${fileId}/transcription-status`, (route) =>
route.fulfill({ json: status }),
)
await page.route(`**/api/files/${fileId}/transcripts`, async (route) => {
expect(route.request().postDataJSON()).toEqual({ language: expectedLanguages[submissions] })
const taskId = `transcript-task-${++submissions}`
status = { taskId, status: 'processing' }
await route.fulfill({ status: 202, json: { kind: 'queued', taskId } })
})
await expect
.poll(() =>
prisma.asset.findUnique({
where: { id: fileId },
select: { status: true, media: true },
}),
)
.toMatchObject({ status: 'processed', media: { proxyType: 'video' } })
await prisma.asset.update({ where: { id: fileId }, data: { status: 'processing' } })
const [signupInfo] = await Promise.all([
page.waitForResponse('**/api/signup-info'),
page.goto(`/projects/${projectId}`),
])
expect(await signupInfo.json()).toMatchObject({ transcriptionEnabled: true })
const action = page.getByRole('menuitem', { name: 'Generate Transcripts' })
await fileCard(page, fileName).click({ button: 'right' })
await expect(action).toBeDisabled()
await prisma.asset.update({ where: { id: fileId }, data: { status: 'processed' } })
await page.reload()
const openDialog = async () => {
await fileCard(page, fileName).click({ button: 'right' })
await action.click()
}
await openDialog()
const dialog = page.getByRole('dialog', { name: 'Generate Transcripts' })
const language = dialog.getByRole('combobox', { name: 'Language' })
const generate = dialog.getByRole('button', { name: 'Generate', exact: true })
await expect(dialog.getByRole('status')).toHaveText('Transcript generated.')
await expect(language).toHaveValue('Auto')
await language.fill('Chi')
await dialog.getByRole('option', { name: 'Chinese' }).click()
await expect(language).toHaveValue('Chinese')
await generate.click()
await expect(dialog.getByRole('status')).toHaveText('Generating transcript…')
await dialog.getByRole('button', { name: 'Close', exact: true }).click()
await expect(dialog).toBeHidden()
status = { taskId: status.taskId, status: 'completed' }
await openDialog()
await expect(generate).toBeEnabled()
await language.fill('Eng')
await dialog.getByRole('option', { name: 'English' }).click()
await generate.click()
await expect(dialog.getByRole('status')).toHaveText('Generating transcript…')
status = { taskId: status.taskId, status: 'completed' }
await expect(dialog).toBeHidden()
await expect(page.getByText('Transcript generated.', { exact: true })).toBeVisible()
})
@@ -0,0 +1,177 @@
import { execFile } from 'node:child_process'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { promisify } from 'node:util'
import { logger } from '@shumai/core/src/logger'
import { s3Service } from '@shumai/core/src/s3/s3'
import {
isLocalTranscriptionEnabled,
LocalTranscriptionError,
transcribeLocalAudio,
} from '@shumai/core/src/transcript/local-transcription'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import { selectPrimaryAudioStream } from '@shumai/core/src/transcode/transcode'
import { prisma } from '@shumai/db'
import { selectTranscriptVideoProxyKey, transcriptionErrors } from '@shumai/dtos'
import {
ApplicationFailure,
defineStep,
ensureLocalMediaFile,
getLocalTaskAbortSignal,
} from '@shumai/workflow-core'
import { z } from 'zod'
const execFileAsync = promisify(execFile)
const audioProbeSchema = z.object({
streams: z.array(
z.object({
index: z.number().int().nonnegative(),
// eslint-disable-next-line @typescript-eslint/naming-convention -- ffprobe field
codec_type: z.string(),
// eslint-disable-next-line @typescript-eslint/naming-convention -- ffprobe field
bit_rate: z.string().optional(),
disposition: z.record(z.string(), z.number()).optional(),
}),
),
})
async function removeTempDirectory(directory: string): Promise<void> {
try {
await rm(directory, { recursive: true, force: true })
} catch (error) {
logger.warn({ err: error, directory }, 'Failed to remove local transcription files')
}
}
export const extractTranscriptAudioActivity = defineStep(
async function extractTranscriptAudioActivity({
assetId,
taskId,
audioKey,
}: {
assetId: string
taskId: string
audioKey: string
}): Promise<void> {
if (!isLocalTranscriptionEnabled()) {
throw ApplicationFailure.create({
message: 'Local transcription is disabled',
nonRetryable: true,
})
}
const asset = await prisma.asset.findFirst({
where: {
id: assetId,
type: 'file',
status: 'processed',
isDeleted: false,
mediaType: { startsWith: 'video/' },
},
select: { media: true },
})
const proxyKey = selectTranscriptVideoProxyKey(asset?.media)
if (!proxyKey) {
throw ApplicationFailure.create({ message: transcriptionErrors.noProxy, nonRetryable: true })
}
const signal = getLocalTaskAbortSignal(taskId)
const directory = await mkdtemp(join(tmpdir(), 'shumai-transcript-'))
try {
const video = await ensureLocalMediaFile(proxyKey, join(directory, 'video.mp4'))
const { stdout } = await execFileAsync(
'ffprobe',
['-v', 'error', '-select_streams', 'a', '-show_streams', '-of', 'json', video],
{ signal },
)
const stream = selectPrimaryAudioStream(audioProbeSchema.parse(JSON.parse(stdout)).streams)
if (!stream) {
throw ApplicationFailure.create({
message: transcriptionErrors.noAudio,
nonRetryable: true,
})
}
const wav = join(directory, 'audio.wav')
// Keep the container timeline and fill any leading gap before the primary audio starts.
await execFileAsync(
'ffmpeg',
[
'-nostdin',
'-v',
'error',
'-copyts',
'-start_at_zero',
'-i',
video,
'-map',
`0:${stream.index}`,
'-af',
'aresample=16000:async=1:first_pts=0',
'-ac',
'1',
'-c:a',
'pcm_s16le',
wav,
],
{ signal },
)
signal?.throwIfAborted()
await s3Service.uploadFileToKey(wav, audioKey, 'audio/wav')
} finally {
await removeTempDirectory(directory)
}
},
)
export const transcribeAudioActivity = defineStep(async function transcribeAudioActivity({
taskId,
audioKey,
language,
model,
}: {
taskId: string
audioKey: string
language: string | null
model: string
}) {
const directory = await mkdtemp(join(tmpdir(), 'shumai-transcript-'))
try {
const path = await ensureLocalMediaFile(audioKey, join(directory, 'audio.wav'))
return await transcribeLocalAudio({
audio: Bun.file(path),
language,
model,
signal: getLocalTaskAbortSignal(taskId),
})
} catch (error) {
if (error instanceof LocalTranscriptionError) {
const { status } = error
if (status >= 400 && status < 500 && status !== 408 && status !== 429) {
throw ApplicationFailure.create({
message: status === 413 ? transcriptionErrors.tooLarge : error.message,
nonRetryable: true,
})
}
}
if (error instanceof z.ZodError || error instanceof SyntaxError) {
throw ApplicationFailure.create({
message: 'Invalid transcription response',
nonRetryable: true,
})
}
throw error
} finally {
await removeTempDirectory(directory)
}
})
export const saveTranscriptActivity = defineStep(async function saveTranscriptActivity(
params: Parameters<typeof transcriptService.saveResult>[0],
): Promise<void> {
if (!(await transcriptService.saveResult(params))) {
throw ApplicationFailure.create({ message: 'Video is no longer available', nonRetryable: true })
}
})
+2
View File
@@ -3,9 +3,11 @@ import { registerWorkflow } from '@shumai/workflow-core'
import { agentAutofillMedia } from './workflows/agent-autofill'
import { agentChat } from './workflows/agent-chat'
import { agentEmbeddingMedia } from './workflows/agent-embedding'
import { transcribeVideoWorkflow } from './workflows/transcribe-video'
export function initAgentWorkflows() {
registerWorkflow(WorkflowTaskType.ai_embedding, agentEmbeddingMedia)
registerWorkflow(WorkflowTaskType.ai_transcription, transcribeVideoWorkflow)
registerWorkflow(WorkflowTaskType.ai_metadata_autofill, agentAutofillMedia)
registerWorkflow(WorkflowTaskType.chat, agentChat)
}
@@ -0,0 +1,50 @@
import { logger } from '@shumai/core/src/logger'
import type { WorkflowTask } from '@shumai/db'
import { ApplicationFailure } from '@shumai/workflow-core'
import { deleteS3ObjectActivity } from '../activities/ai'
import {
extractTranscriptAudioActivity,
saveTranscriptActivity,
transcribeAudioActivity,
} from '../activities/transcription'
export async function transcribeVideoWorkflow(task: WorkflowTask): Promise<void> {
const request = task.payload?.transcription
if (!request) {
throw ApplicationFailure.create({
message: 'Missing transcription request',
nonRetryable: true,
})
}
const taskId = task.id
const assetId = task.assetId
const audioKey = `temp/transcripts/${taskId}.wav`
try {
await extractTranscriptAudioActivity({ assetId, taskId, audioKey })
const transcript = await transcribeAudioActivity({ taskId, audioKey, ...request })
if (request.language && transcript.language && request.language !== transcript.language) {
throw ApplicationFailure.create({
message: 'Transcription returned an unexpected language',
nonRetryable: true,
})
}
await saveTranscriptActivity({
taskId,
assetId,
model: request.model,
language: transcript.language,
segments: transcript.segments.map((segment) => ({
startMs: Math.round(segment.start * 1000),
endMs: Math.round(segment.end * 1000),
text: segment.text,
})),
})
} finally {
try {
await deleteS3ObjectActivity({ key: audioKey })
} catch (error) {
logger.error({ err: error, taskId, audioKey }, 'Failed to delete staged transcript audio')
}
}
}
+12
View File
@@ -13,9 +13,11 @@ describe('authn api', () => {
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
it('GET /signup-info', async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
mockGetSignupInfo.mockResolvedValue({
initialized: true,
demoMode: false,
@@ -29,6 +31,16 @@ describe('authn api', () => {
initialized: true,
demoMode: false,
archiveStorageEnabled: false,
transcriptionEnabled: false,
})
})
it('advertises transcription with the local embedding provider', async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
mockGetSignupInfo.mockResolvedValue({ initialized: true, demoMode: false })
const res = await new Hono().route('/', authnRoute).request('/signup-info')
expect(await res.json()).toMatchObject({ transcriptionEnabled: true })
})
})
+2
View File
@@ -4,6 +4,7 @@ import { userService } from '@shumai/core/src/user/user'
import { auth } from '@shumai/core/src/auth/auth'
import { createGuestToken } from '@shumai/core/src/auth/guest-token'
import { isArchiveStorageEnabled } from '@shumai/core/src/s3/archive-storage'
import { isLocalTranscriptionEnabled } from '@shumai/core/src/transcript/local-transcription'
import { z } from 'zod'
import { zValidator } from '@hono/zod-validator'
import { ulid } from 'ulid'
@@ -24,6 +25,7 @@ const route = app
initialized: info.initialized,
demoMode: info.demoMode,
archiveStorageEnabled: isArchiveStorageEnabled(),
transcriptionEnabled: isLocalTranscriptionEnabled(),
})
})
.get('/me', async (c) => {
+2
View File
@@ -31,6 +31,7 @@ import versionStackRoute from './versionStack'
import kanbanRoute from './kanban'
import mediaGenerationRoute from './media-generation'
import runnerWsRoute, { runnerWebsocket } from './runner-ws'
import transcriptRoute from './transcript'
export { runnerWebsocket }
@@ -72,6 +73,7 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
.route('/', teamRoute)
.route('/', versionStackRoute)
.route('/', fileRoute)
.route('/', transcriptRoute)
.route('/', folderRoute)
.route('/', agentRoute)
.route('/', chatRoute)
+172
View File
@@ -0,0 +1,172 @@
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import { Hono } from 'hono'
import { HTTPException } from 'hono/http-exception'
import { afterEach, describe, expect, it, vi } from 'vitest'
import transcriptRoute from './transcript'
describe('Transcript API', () => {
const app = new Hono().route('/', transcriptRoute)
const submit = (body: { language?: string }) =>
app.request('/files/file-id/transcripts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
const edit = (body: object, language = 'en') =>
app.request(`/files/file-id/transcripts/${language}/segments/segment-id`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
afterEach(() => vi.restoreAllMocks())
it('proxies the server language list', async () => {
const list = { model: 'whisper-tiny', languages: [{ code: 'en', name: 'English' }] }
vi.spyOn(transcriptService, 'listLanguages').mockResolvedValue(list)
const response = await app.request('/transcription/languages')
expect(await response.json()).toEqual(list)
})
it('returns saved languages and segments with asset read access', async () => {
const permission = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const list = vi
.spyOn(transcriptService, 'listSavedLanguages')
.mockResolvedValue({ languages: ['en'] })
const saved = {
id: 'transcript-id',
language: 'en',
segments: [{ id: 'segment-id', startMs: 0, endMs: 1400, text: 'Hello' }],
}
const get = vi.spyOn(transcriptService, 'getSavedTranscript').mockResolvedValue(saved)
const languages = await app.request('/files/file-id/transcripts')
expect(languages.status).toBe(200)
expect(await languages.json()).toEqual({ languages: ['en'] })
expect(list).toHaveBeenCalledWith('file-id')
const transcript = await app.request('/files/file-id/transcripts/en')
expect(transcript.status).toBe(200)
expect(await transcript.json()).toEqual(saved)
expect(get).toHaveBeenCalledWith('file-id', 'en')
expect(permission).toHaveBeenCalledTimes(2)
for (const [request] of permission.mock.calls) {
expect(request).toMatchObject({
type: ResourceType.Asset,
permission: Permission.Read,
id: 'file-id',
})
}
})
it('validates the saved language path and authorizes before reading saved data', async () => {
const permission = vi
.spyOn(authzService, 'hasPermission')
.mockRejectedValue(new HTTPException(403))
const list = vi.spyOn(transcriptService, 'listSavedLanguages')
const get = vi.spyOn(transcriptService, 'getSavedTranscript')
expect((await app.request('/files/file-id/transcripts/auto')).status).toBe(400)
expect((await app.request('/files/file-id/transcripts')).status).toBe(403)
expect((await app.request('/files/file-id/transcripts/en')).status).toBe(403)
expect(list).not.toHaveBeenCalled()
expect(get).not.toHaveBeenCalled()
permission.mockResolvedValue(undefined)
get.mockRejectedValue(new HTTPException(404))
expect((await app.request('/files/file-id/transcripts/zh')).status).toBe(404)
})
it('requires asset edit permission and accepts an empty segment', async () => {
const permission = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const segment = { id: 'segment-id', startMs: 0, endMs: 1400, text: '' }
const update = vi.spyOn(transcriptService, 'updateSegmentText').mockResolvedValue(segment)
const response = await edit({ text: '' })
expect(response.status).toBe(200)
expect(await response.json()).toEqual(segment)
expect(update).toHaveBeenCalledWith('file-id', 'en', 'segment-id', '')
expect(permission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
permission: Permission.Edit,
id: 'file-id',
}),
)
})
it('rejects invalid text and timing fields before handling segment edits', async () => {
const permission = vi.spyOn(authzService, 'hasPermission')
const update = vi.spyOn(transcriptService, 'updateSegmentText')
for (const body of [
{},
{ text: null },
{ text: 'invalid\0text' },
{ text: 'Hello', startMs: 1 },
{ text: 'Hello', endMs: 1 },
]) {
expect((await edit(body)).status).toBe(400)
}
expect((await edit({ text: 'Hello' }, 'auto')).status).toBe(400)
expect(permission).not.toHaveBeenCalled()
expect(update).not.toHaveBeenCalled()
})
it('does not edit for a read-only user and forwards missing segment errors', async () => {
const permission = vi
.spyOn(authzService, 'hasPermission')
.mockRejectedValue(new HTTPException(403))
const update = vi
.spyOn(transcriptService, 'updateSegmentText')
.mockRejectedValue(new HTTPException(404))
expect((await edit({ text: 'Hello' })).status).toBe(403)
expect(update).not.toHaveBeenCalled()
permission.mockResolvedValue(undefined)
expect((await edit({ text: 'Hello' })).status).toBe(404)
})
it('requires asset edit permission and returns a queued Auto job', async () => {
const permission = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const generate = vi
.spyOn(transcriptService, 'generate')
.mockResolvedValue({ kind: 'queued', taskId: 'task-id' })
const response = await submit({})
expect(response.status).toBe(202)
expect(await response.json()).toEqual({ kind: 'queued', taskId: 'task-id' })
expect(generate).toHaveBeenCalledWith('file-id', null)
expect(permission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
permission: Permission.Edit,
id: 'file-id',
}),
)
})
it('returns a saved transcript for an explicit language', async () => {
vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const saved = { kind: 'existing', transcriptId: 'transcript-id', language: 'en' } as const
vi.spyOn(transcriptService, 'generate').mockResolvedValue(saved)
const response = await submit({ language: 'en' })
expect(response.status).toBe(200)
expect(await response.json()).toEqual(saved)
expect(transcriptService.generate).toHaveBeenCalledWith('file-id', 'en')
})
it('rejects invalid language codes and denies reads and writes without edit permission', async () => {
vi.spyOn(authzService, 'hasPermission').mockRejectedValue(new HTTPException(403))
const generate = vi.spyOn(transcriptService, 'generate')
const status = vi.spyOn(transcriptService, 'getStatus')
expect((await submit({ language: 'auto' })).status).toBe(400)
expect((await submit({ language: 'en' })).status).toBe(403)
expect((await app.request('/files/file-id/transcription-status')).status).toBe(403)
expect(generate).not.toHaveBeenCalled()
expect(status).not.toHaveBeenCalled()
})
})
+90
View File
@@ -0,0 +1,90 @@
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import type { User } from '@shumai/db'
import {
generateTranscriptRequestSchema,
transcriptLanguageCodeSchema,
updateTranscriptSegmentRequestSchema,
} from '@shumai/dtos'
import { Hono } from 'hono'
import { z } from 'zod'
const route = new Hono<{ Variables: { user: User } }>()
.get('/transcription/languages', async (c) => c.json(await transcriptService.listLanguages()))
.get('/files/:fileId/transcripts', async (c) => {
const assetId = c.req.param('fileId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Read,
type: ResourceType.Asset,
id: assetId,
})
return c.json(await transcriptService.listSavedLanguages(assetId))
})
.get(
'/files/:fileId/transcripts/:language',
zValidator('param', z.object({ fileId: z.string(), language: transcriptLanguageCodeSchema })),
async (c) => {
const { fileId, language } = c.req.valid('param')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Read,
type: ResourceType.Asset,
id: fileId,
})
return c.json(await transcriptService.getSavedTranscript(fileId, language))
},
)
.patch(
'/files/:fileId/transcripts/:language/segments/:segmentId',
zValidator(
'param',
z.object({
fileId: z.string(),
language: transcriptLanguageCodeSchema,
segmentId: z.string(),
}),
),
zValidator('json', updateTranscriptSegmentRequestSchema),
async (c) => {
const { fileId, language, segmentId } = c.req.valid('param')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Edit,
type: ResourceType.Asset,
id: fileId,
})
const { text } = c.req.valid('json')
return c.json(await transcriptService.updateSegmentText(fileId, language, segmentId, text))
},
)
.post(
'/files/:fileId/transcripts',
zValidator('json', generateTranscriptRequestSchema),
async (c) => {
const assetId = c.req.param('fileId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Edit,
type: ResourceType.Asset,
id: assetId,
})
const { language } = c.req.valid('json')
const result = await transcriptService.generate(assetId, language ?? null)
return c.json(result, result.kind === 'queued' || result.kind === 'busy' ? 202 : 200)
},
)
.get('/files/:fileId/transcription-status', async (c) => {
const assetId = c.req.param('fileId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Edit,
type: ResourceType.Asset,
id: assetId,
})
return c.json(await transcriptService.getStatus(assetId))
})
export default route
+1
View File
@@ -2938,6 +2938,7 @@ export class AssetService {
type: a.type,
targetType: a.type === AssetType.symlink ? a.target?.type : null,
status: latestVersion.status,
mediaType: latestVersion.mediaType,
proxyType,
latestChildren,
preview,
@@ -1,6 +1,10 @@
export function getGemmaEmbeddingEndpoint(): string {
export function getGemmaOpenAiBaseUrl(): string {
const baseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL || 'http://localhost:9379/v1'
const url = baseUrl.replace(/\/+$/, '')
if (url.endsWith('/embeddings')) return url
return url.endsWith('/v1') ? `${url}/embeddings` : `${url}/v1/embeddings`
const url = baseUrl.replace(/\/+$/, '').replace(/\/embeddings$/, '')
return url.endsWith('/v1') ? url : `${url}/v1`
}
export function getGemmaEmbeddingEndpoint(): string {
const baseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL?.replace(/\/+$/, '')
return baseUrl?.endsWith('/embeddings') ? baseUrl : `${getGemmaOpenAiBaseUrl()}/embeddings`
}
@@ -0,0 +1,66 @@
import { getGemmaOpenAiBaseUrl } from '@shumai/core/src/search/gemma-embedding-endpoint'
import { transcriptLanguageCodeSchema, transcriptLanguagesSchema } from '@shumai/dtos'
import { z } from 'zod'
const transcriptEndpoint = () => `${getGemmaOpenAiBaseUrl()}/audio/transcriptions`
export function isLocalTranscriptionEnabled(): boolean {
return process.env.EMBEDDING_PROVIDER === 'gemma-embedding-2-openai'
}
export async function listLocalTranscriptionLanguages() {
const response = await fetch(`${transcriptEndpoint()}/languages`, {
signal: AbortSignal.timeout(5_000),
})
if (!response.ok) throw new Error(`Transcription languages endpoint returned ${response.status}`)
return transcriptLanguagesSchema.parse(await response.json())
}
const transcriptResponseSchema = z
.object({
language: transcriptLanguageCodeSchema.nullable(),
segments: z.array(
z
.object({ start: z.number().min(0), end: z.number().min(0), text: z.string().min(1) })
.refine((segment) => segment.end >= segment.start && segment.end < 2_147_483),
),
})
.refine((result) => result.language !== null || result.segments.length === 0)
export class LocalTranscriptionError extends Error {
constructor(readonly status: number) {
super(`Transcription server returned HTTP ${status}`)
}
}
export async function transcribeLocalAudio({
audio,
language,
model,
signal,
}: {
audio: Blob
language: string | null
model: string
signal?: AbortSignal
}) {
const form = new FormData()
form.set('file', audio, 'audio.wav')
form.set('model', model)
form.set('response_format', 'verbose_json')
if (language) form.set('language', language)
const timeout = AbortSignal.timeout(90 * 60 * 1000)
const response = await fetch(transcriptEndpoint(), {
method: 'POST',
body: form,
redirect: 'error',
timeout: false,
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
})
if (!response.ok) {
await response.body?.cancel()
throw new LocalTranscriptionError(response.status)
}
return transcriptResponseSchema.parse(await response.json())
}
@@ -0,0 +1,322 @@
import { prisma, WorkflowTaskType } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { transcriptionErrors } from '@shumai/dtos'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { transcriptService } from './transcript'
describe('TranscriptService', () => {
setupTestDbHooks()
let assetId: string
let projectId: string
const model = 'whisper-tiny'
const segments = [{ startMs: 125, endMs: 1425, text: 'Original segment' }]
const media: PrismaJson.MediaInfo = {
proxyType: 'video',
duration: 2,
filesize: 0,
frames: 50,
imageTranscodes: [],
videoTranscodes: [{ key: 'files/transcript-video-480p.mp4', width: 854, height: 480 }],
finishedAt: '2026-01-01T00:00:00Z',
metadata: null,
original: null,
}
beforeEach(async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
const team = await prisma.team.create({ data: { name: 'Transcript test' } })
const project = await prisma.project.create({
data: { name: 'Transcript test', teamId: team.id },
})
projectId = project.id
const asset = await prisma.asset.create({
data: {
name: 'Video',
type: 'file',
status: 'processed',
mediaType: 'video/mp4',
media,
project: { connect: { id: projectId } },
storageKey: { create: { key: 'files/transcript-video.mp4' } },
},
})
assetId = asset.id
vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
Response.json({
model,
languages: [
{ code: 'en', name: 'English' },
{ code: 'zh', name: 'Chinese' },
],
}),
)
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
async function generateAndStart(language: string | null) {
const result = await transcriptService.generate(assetId, language)
if (result.kind !== 'queued') throw new Error(`Unexpected generation result ${result.kind}`)
await prisma.workflowTask.update({
where: { id: result.taskId },
data: { status: 'processing' },
})
return result.taskId
}
it('lists only the asset’s saved languages and reads every segment in position order', async () => {
const otherAsset = await prisma.asset.create({
data: { name: 'Another video', type: 'file', status: 'processed', projectId },
})
const save = (id: string, language: string) =>
prisma.assetTranscript.create({
data: {
assetId: id,
language,
model,
workflowTaskId: 'test-task',
segments: {
create: [
{ position: 1, startMs: 2000, endMs: 3000, text: 'Second' },
{ position: 0, startMs: 125, endMs: 1425, text: 'First' },
],
},
},
include: { segments: true },
})
await expect(transcriptService.listSavedLanguages(assetId)).resolves.toEqual({ languages: [] })
const english = await save(assetId, 'en')
await save(assetId, 'zh')
await save(otherAsset.id, 'ko')
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
const savedLanguages = await transcriptService.listSavedLanguages(assetId)
expect(savedLanguages.languages.sort()).toEqual(['en', 'zh'])
const transcript = await transcriptService.getSavedTranscript(assetId, 'en')
expect(transcript).toEqual({
id: english.id,
language: 'en',
segments: [
{
id: english.segments.find(({ position }) => position === 0)?.id,
startMs: 125,
endMs: 1425,
text: 'First',
},
{
id: english.segments.find(({ position }) => position === 1)?.id,
startMs: 2000,
endMs: 3000,
text: 'Second',
},
],
})
await expect(transcriptService.getSavedTranscript(assetId, 'ko')).rejects.toMatchObject({
status: 404,
})
await prisma.asset.update({ where: { id: assetId }, data: { isDeleted: true } })
await expect(transcriptService.listSavedLanguages(assetId)).resolves.toEqual({ languages: [] })
await expect(transcriptService.getSavedTranscript(assetId, 'en')).rejects.toMatchObject({
status: 404,
})
expect(fetch).not.toHaveBeenCalled()
})
it('validates provider capability, language and asset eligibility before queuing', async () => {
await expect(transcriptService.listLanguages()).resolves.toMatchObject({ model })
await expect(transcriptService.generate(assetId, 'xx')).rejects.toMatchObject({ status: 400 })
await prisma.asset.update({ where: { id: assetId }, data: { mediaType: 'image/png' } })
await expect(transcriptService.generate(assetId, 'en')).rejects.toMatchObject({ status: 400 })
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
await expect(transcriptService.listLanguages()).rejects.toMatchObject({ status: 503 })
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({ status: 503 })
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
it('serializes requests for an asset and uses its project and workflow type', async () => {
const results = await Promise.all([
transcriptService.generate(assetId, 'en'),
transcriptService.generate(assetId, 'zh'),
])
expect(results.map((result) => result.kind).sort()).toEqual(['busy', 'queued'])
const tasks = await prisma.workflowTask.findMany({ where: { assetId } })
expect(tasks).toHaveLength(1)
expect(tasks[0]).toMatchObject({
projectId,
type: WorkflowTaskType.ai_transcription,
status: 'pending',
})
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId: tasks[0].id,
status: 'pending',
})
})
it('requires completed transcoding and a full proxy before queuing', async () => {
await prisma.asset.update({ where: { id: assetId }, data: { status: 'processing' } })
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({ status: 400 })
const preview = { key: 'files/transcript-video-180p.mp4', width: 320, height: 180 }
await prisma.asset.update({
where: { id: assetId },
data: {
status: 'processed',
media: { ...media, videoTranscodes: [], videoPreview: preview },
},
})
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({
status: 400,
message: transcriptionErrors.noProxy,
})
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
it('rejects an audio-only proxy even when the file was uploaded with a video MIME type', async () => {
await prisma.asset.update({
where: { id: assetId },
data: {
media: {
...media,
proxyType: 'audio',
videoTranscodes: [{ key: 'files/transcript-video-audio-proxy.mp4', width: 0, height: 0 }],
},
},
})
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({
status: 400,
message: transcriptionErrors.noProxy,
})
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
it('persists languages independently and preserves saved text on replay and requests for an existing language', async () => {
const enTaskId = await generateAndStart('en')
const first = { taskId: enTaskId, assetId, model, language: 'en', segments }
await transcriptService.saveResult(first)
const en = await prisma.assetTranscript.findUniqueOrThrow({
where: { assetIdLanguage: { assetId, language: 'en' } },
})
const segment = await prisma.assetTranscriptSegment.findUniqueOrThrow({
where: { transcriptIdPosition: { transcriptId: en.id, position: 0 } },
})
await expect(
transcriptService.updateSegmentText(assetId, 'en', segment.id, 'Edited'),
).resolves.toEqual({
id: segment.id,
startMs: 125,
endMs: 1425,
text: 'Edited',
})
await transcriptService.saveResult(first)
expect(await transcriptService.generate(assetId, 'en')).toEqual({
kind: 'existing',
transcriptId: en.id,
language: 'en',
})
const autoTaskId = await generateAndStart(null)
await transcriptService.saveResult({ ...first, taskId: autoTaskId })
expect(await transcriptService.generate(assetId, null)).toEqual({
kind: 'existing',
transcriptId: en.id,
language: 'en',
})
expect(
await prisma.assetTranscriptSegment.findMany({ where: { transcriptId: en.id } }),
).toMatchObject([
{
position: 0,
startMs: 125,
endMs: 1425,
text: 'Edited',
},
])
const zhTaskId = await generateAndStart('zh')
await transcriptService.saveResult({ ...first, taskId: zhTaskId, language: 'zh' })
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(2)
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(3)
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId: zhTaskId,
status: 'completed',
})
await prisma.asset.delete({ where: { id: assetId } })
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
expect(await prisma.assetTranscriptSegment.count({ where: { transcriptId: en.id } })).toBe(0)
})
it('saves empty segment text with generation disabled and scopes writes to the asset and language', async () => {
const taskId = await generateAndStart('en')
await transcriptService.saveResult({ taskId, assetId, model, language: 'en', segments })
const otherAsset = await prisma.asset.create({
data: { name: 'Another video', type: 'file', status: 'processed', projectId },
})
const [segment] = (await transcriptService.getSavedTranscript(assetId, 'en')).segments
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
for (const [fileId, language, segmentId] of [
[otherAsset.id, 'en', segment.id],
[assetId, 'zh', segment.id],
[assetId, 'en', 'missing-segment'],
]) {
await expect(
transcriptService.updateSegmentText(fileId, language, segmentId, 'Unexpected edit'),
).rejects.toMatchObject({ status: 404 })
}
expect(
await prisma.assetTranscriptSegment.findUnique({ where: { id: segment.id } }),
).toMatchObject(segment)
const cleared = { ...segment, text: '' }
await expect(
transcriptService.updateSegmentText(assetId, 'en', segment.id, ''),
).resolves.toEqual(cleared)
expect((await transcriptService.getSavedTranscript(assetId, 'en')).segments).toEqual([cleared])
await prisma.asset.update({ where: { id: assetId }, data: { isDeleted: true } })
await expect(
transcriptService.updateSegmentText(assetId, 'en', segment.id, 'Restored'),
).rejects.toMatchObject({
status: 404,
})
expect(
await prisma.assetTranscriptSegment.findUnique({ where: { id: segment.id } }),
).toMatchObject(cleared)
})
it('completes silence without creating a row for an unknown language', async () => {
const taskId = await generateAndStart(null)
await transcriptService.saveResult({ taskId, assetId, model, language: null, segments: [] })
expect(await transcriptService.getStatus(assetId)).toEqual({ taskId, status: 'no_speech' })
expect(await transcriptService.generate(assetId, null)).toEqual({ kind: 'no_speech' })
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
})
it.each(['tooLarge', 'noProxy'] as const)(
'preserves a failed job with reason %s',
async (reason) => {
const taskId = await generateAndStart(null)
await prisma.workflowTask.update({
where: { id: taskId },
data: {
status: 'failed',
output: { error: transcriptionErrors[reason] },
},
})
await transcriptService.saveResult({ taskId, assetId, model, language: 'en', segments })
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId,
status: 'failed',
reason,
})
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
},
)
})
+280
View File
@@ -0,0 +1,280 @@
import { logger } from '@shumai/core/src/logger'
import {
notifyWorkflowTaskCreated,
prisma,
Prisma,
WorkflowTaskType,
type WorkflowTask,
} from '@shumai/db'
import {
selectTranscriptVideoProxyKey,
transcriptionErrors,
type GenerateTranscriptResult,
type SavedTranscript,
type SavedTranscriptLanguages,
type TranscriptJobStatus,
type TranscriptSegment,
} from '@shumai/dtos'
import { HTTPException } from 'hono/http-exception'
import { isLocalTranscriptionEnabled, listLocalTranscriptionLanguages } from './local-transcription'
const type = WorkflowTaskType.ai_transcription
const transcriptSelection = { id: true, language: true } as const
const segmentSelection = { id: true, startMs: true, endMs: true, text: true } as const
type Segment = { startMs: number; endMs: number; text: string }
export class TranscriptService {
async listLanguages() {
this.requireEnabled()
try {
return await listLocalTranscriptionLanguages()
} catch (error) {
logger.warn({ err: error }, 'Failed to load local transcription languages')
throw new HTTPException(503, { message: 'Transcription languages are unavailable' })
}
}
async listSavedLanguages(assetId: string): Promise<SavedTranscriptLanguages> {
const transcripts = await prisma.assetTranscript.findMany({
where: { assetId, asset: { isDeleted: false } },
orderBy: { id: 'desc' },
select: { language: true },
})
return { languages: transcripts.map(({ language }) => language) }
}
async getSavedTranscript(assetId: string, language: string): Promise<SavedTranscript> {
const transcript = await prisma.assetTranscript.findUnique({
where: { assetIdLanguage: { assetId, language }, asset: { isDeleted: false } },
select: {
...transcriptSelection,
segments: {
orderBy: { position: 'asc' },
select: segmentSelection,
},
},
})
if (!transcript) throw new HTTPException(404, { message: 'Transcript not found' })
return transcript
}
async updateSegmentText(
assetId: string,
language: string,
segmentId: string,
text: string,
): Promise<TranscriptSegment> {
const [segment] = await prisma.assetTranscriptSegment.updateManyAndReturn({
where: { id: segmentId, transcript: { assetId, language, asset: { isDeleted: false } } },
data: { text },
select: segmentSelection,
})
if (!segment) throw new HTTPException(404, { message: 'Transcript segment not found' })
return segment
}
async generate(assetId: string, language: string | null): Promise<GenerateTranscriptResult> {
this.requireEnabled()
const saved = await this.findSaved(prisma, assetId, language)
if (saved) return saved
const { model, languages } = await this.listLanguages()
if (language && !languages.some((entry) => entry.code === language)) {
throw new HTTPException(400, { message: 'Unsupported transcription language' })
}
const { result, task } = await prisma.$transaction(
async (tx): Promise<{ result: GenerateTranscriptResult; task?: WorkflowTask }> => {
// Serialize submissions and result commits for a single video asset.
await tx.$queryRaw`SELECT id FROM assets WHERE id = ${assetId} FOR UPDATE`
const savedAfterLock = await this.findSaved(tx, assetId, language)
if (savedAfterLock) return { result: savedAfterLock }
const asset = await tx.asset.findFirst({
where: {
id: assetId,
type: 'file',
status: 'processed',
isDeleted: false,
mediaType: { startsWith: 'video/' },
},
select: { media: true, project: { select: { id: true, teamId: true } } },
})
if (!asset?.project) {
throw new HTTPException(400, { message: 'Transcripts require a processed video file' })
}
if (!selectTranscriptVideoProxyKey(asset.media)) {
throw new HTTPException(400, { message: transcriptionErrors.noProxy })
}
const active = await tx.workflowTask.findFirst({
where: { assetId, type, status: { in: ['pending', 'processing'] } },
orderBy: { id: 'desc' },
})
if (active) return { result: { kind: 'busy', taskId: active.id }, task: active }
// Notify the worker after commit so it can observe the task row as soon as it starts.
const [created] = await tx.workflowTask.createManyAndReturn({
data: {
assetId,
teamId: asset.project.teamId,
projectId: asset.project.id,
type,
status: 'pending',
payload: { projectId: asset.project.id, transcription: { language, model } },
},
})
return { result: { kind: 'queued', taskId: created.id }, task: created }
},
)
if (task?.status === 'pending') {
try {
await notifyWorkflowTaskCreated(task)
} catch (error) {
logger.error({ err: error, taskId: task.id }, 'Failed to queue transcript generation')
await prisma.workflowTask.updateMany({
where: { id: task.id, status: 'pending' },
data: { status: 'failed', output: { error: 'Failed to queue transcript generation' } },
})
throw new HTTPException(503, { message: 'Could not queue transcript generation' })
}
}
return result
}
async getStatus(assetId: string): Promise<TranscriptJobStatus | null> {
const task = await prisma.workflowTask.findFirst({
where: { assetId, type },
orderBy: { id: 'desc' },
select: { id: true, status: true, output: true },
})
if (!task?.status) return null
if (task.status === 'failed') {
const error = task.output?.error ?? ''
const reason = error.includes(transcriptionErrors.tooLarge)
? 'tooLarge'
: error.includes(transcriptionErrors.noAudio)
? 'noAudio'
: error.includes(transcriptionErrors.noProxy)
? 'noProxy'
: 'unknown'
return { status: 'failed', taskId: task.id, reason }
}
const transcript = task.output?.transcription
return {
taskId: task.id,
status:
task.status === 'completed' && transcript && 'noSpeech' in transcript
? 'no_speech'
: task.status,
}
}
async saveResult(params: {
taskId: string
assetId: string
model: string
language: string | null
segments: Segment[]
}): Promise<boolean> {
const { taskId, assetId, model, language, segments } = params
return await prisma.$transaction(async (tx) => {
const [asset] = await tx.$queryRaw<{ id: string }[]>`
SELECT id FROM assets
WHERE id = ${assetId} AND NOT is_deleted AND status = 'processed'
FOR UPDATE
`
if (!asset) return false
const task = await tx.workflowTask.updateMany({
where: { id: taskId, assetId, type, status: 'processing' },
data: { status: 'completed', model },
})
if (task.count === 0) return true
const existing = language
? await tx.assetTranscript.findUnique({
where: { assetIdLanguage: { assetId, language } },
select: transcriptSelection,
})
: null
const transcript =
existing ??
(language && segments.length > 0
? await tx.assetTranscript.create({
data: {
assetId,
language,
model,
workflowTaskId: taskId,
segments: {
createMany: {
data: segments.map((segment, position) => ({ ...segment, position })),
},
},
},
select: transcriptSelection,
})
: null)
await tx.workflowTask.update({
where: { id: taskId },
data: {
output: {
transcription: transcript
? { transcriptId: transcript.id, language: transcript.language }
: { noSpeech: true },
},
},
})
return true
})
}
private requireEnabled(): void {
if (!isLocalTranscriptionEnabled()) {
throw new HTTPException(503, { message: 'Local transcription is disabled' })
}
}
private async findSaved(
db: Pick<Prisma.TransactionClient, 'assetTranscript' | 'workflowTask'>,
assetId: string,
language: string | null,
): Promise<GenerateTranscriptResult | null> {
if (language) {
const transcript = await db.assetTranscript.findUnique({
where: { assetIdLanguage: { assetId, language } },
select: transcriptSelection,
})
return transcript ? { kind: 'existing', transcriptId: transcript.id, language } : null
}
const auto = await db.workflowTask.findFirst({
where: {
assetId,
type,
status: 'completed',
payload: { path: ['transcription', 'language'], equals: Prisma.JsonNull },
},
select: { output: true },
orderBy: { id: 'desc' },
})
const result = auto?.output?.transcription
if (!result) return null
if ('noSpeech' in result) return { kind: 'no_speech' }
const transcript = await db.assetTranscript.findUnique({
where: { id: result.transcriptId },
select: transcriptSelection,
})
return transcript
? { kind: 'existing', transcriptId: transcript.id, language: transcript.language }
: null
}
}
export const transcriptService = new TranscriptService()
@@ -0,0 +1,39 @@
-- AlterEnum
ALTER TYPE "WorkflowTaskType" ADD VALUE 'ai_transcription';
-- CreateTable
CREATE TABLE "asset_transcripts" (
"id" TEXT NOT NULL,
"asset_id" TEXT NOT NULL,
"language" TEXT NOT NULL,
"model" TEXT NOT NULL,
"workflow_task_id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "asset_transcripts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "asset_transcript_segments" (
"id" TEXT NOT NULL,
"transcript_id" TEXT NOT NULL,
"position" INTEGER NOT NULL,
"start_ms" INTEGER NOT NULL,
"end_ms" INTEGER NOT NULL,
"text" TEXT NOT NULL,
CONSTRAINT "asset_transcript_segments_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "asset_transcripts_asset_id_language_key" ON "asset_transcripts"("asset_id", "language");
-- CreateIndex
CREATE UNIQUE INDEX "asset_transcript_segments_transcript_id_position_key" ON "asset_transcript_segments"("transcript_id", "position");
-- AddForeignKey
ALTER TABLE "asset_transcripts" ADD CONSTRAINT "asset_transcripts_asset_id_fkey" FOREIGN KEY ("asset_id") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "asset_transcript_segments" ADD CONSTRAINT "asset_transcript_segments_transcript_id_fkey" FOREIGN KEY ("transcript_id") REFERENCES "asset_transcripts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+30
View File
@@ -129,6 +129,7 @@ enum WorkflowTaskType {
ai_metadata_autofill
chat
ai_embedding
ai_transcription
query_embedding_for_search
agent_tool_call // @deprecated: Agent tools now execute directly in-process via Core services
kanban_agent_run
@@ -619,6 +620,7 @@ model Asset {
commentAttachments AssetCommentAttachment[] @relation("AssetToCommentAttachment")
notifications Notification[] @relation("AssetToNotification")
embeddings AssetEmbedding[] @relation("AssetToEmbedding")
transcripts AssetTranscript[]
teamRootFolder Team? @relation("TeamToRootFolder")
projectRootFolder Project? @relation("ProjectToRootFolder")
@@ -775,6 +777,34 @@ model AssetEmbedding {
@@map("asset_embeddings")
}
model AssetTranscript {
id String @id @default(ulid())
assetId String @map("asset_id")
asset Asset @relation(fields: [assetId], references: [id], onDelete: Cascade)
language String
model String
workflowTaskId String @map("workflow_task_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
segments AssetTranscriptSegment[]
@@unique([assetId, language], name: "assetIdLanguage")
@@map("asset_transcripts")
}
model AssetTranscriptSegment {
id String @id @default(ulid())
transcriptId String @map("transcript_id")
transcript AssetTranscript @relation(fields: [transcriptId], references: [id], onDelete: Cascade)
position Int
startMs Int @map("start_ms")
endMs Int @map("end_ms")
text String @db.Text
@@unique([transcriptId, position], name: "transcriptIdPosition")
@@map("asset_transcript_segments")
}
model Invite {
id String @id @default(ulid())
code String @unique
+10
View File
@@ -137,6 +137,16 @@ export type AssetCommentReaction = Prisma.AssetCommentReactionModel
*
*/
export type AssetEmbedding = Prisma.AssetEmbeddingModel
/**
* Model AssetTranscript
*
*/
export type AssetTranscript = Prisma.AssetTranscriptModel
/**
* Model AssetTranscriptSegment
*
*/
export type AssetTranscriptSegment = Prisma.AssetTranscriptSegmentModel
/**
* Model Invite
*
+10
View File
@@ -161,6 +161,16 @@ export type AssetCommentReaction = Prisma.AssetCommentReactionModel
*
*/
export type AssetEmbedding = Prisma.AssetEmbeddingModel
/**
* Model AssetTranscript
*
*/
export type AssetTranscript = Prisma.AssetTranscriptModel
/**
* Model AssetTranscriptSegment
*
*/
export type AssetTranscriptSegment = Prisma.AssetTranscriptSegmentModel
/**
* Model Invite
*
+1
View File
@@ -158,6 +158,7 @@ export const WorkflowTaskType = {
ai_metadata_autofill: 'ai_metadata_autofill',
chat: 'chat',
ai_embedding: 'ai_embedding',
ai_transcription: 'ai_transcription',
query_embedding_for_search: 'query_embedding_for_search',
agent_tool_call: 'agent_tool_call',
kanban_agent_run: 'kanban_agent_run',
File diff suppressed because one or more lines are too long
+178 -1
View File
@@ -421,6 +421,8 @@ export const ModelName = {
AssetCommentAttachment: 'AssetCommentAttachment',
AssetCommentReaction: 'AssetCommentReaction',
AssetEmbedding: 'AssetEmbedding',
AssetTranscript: 'AssetTranscript',
AssetTranscriptSegment: 'AssetTranscriptSegment',
Invite: 'Invite',
MetadataField: 'MetadataField',
Notification: 'Notification',
@@ -474,7 +476,7 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
omit: GlobalOmitOptions
}
meta: {
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "runner" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "shareActivity" | "watermarkConfig" | "watermarkTemplate" | "watermarkFile" | "asset" | "storageKey" | "assetMetadataValue" | "assetAgentMd" | "assetComment" | "assetCommentAttachment" | "assetCommentReaction" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "mcpServer" | "agentMcpServer" | "mcpServerCredential" | "agentSession" | "agentSessionCommit" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage" | "auditLog" | "quotaRule" | "quotaRecord" | "kanbanGoal" | "kanbanTask" | "kanbanTaskLink" | "kanbanTaskAsset" | "kanbanTaskComment" | "kanbanTaskEvent" | "recentFileItem" | "jwks" | "oauthClient" | "oauthResource" | "oauthClientResource" | "oauthRefreshToken" | "oauthAccessToken" | "oauthConsent" | "oauthClientAssertion"
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "runner" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "shareActivity" | "watermarkConfig" | "watermarkTemplate" | "watermarkFile" | "asset" | "storageKey" | "assetMetadataValue" | "assetAgentMd" | "assetComment" | "assetCommentAttachment" | "assetCommentReaction" | "assetEmbedding" | "assetTranscript" | "assetTranscriptSegment" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "mcpServer" | "agentMcpServer" | "mcpServerCredential" | "agentSession" | "agentSessionCommit" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage" | "auditLog" | "quotaRule" | "quotaRecord" | "kanbanGoal" | "kanbanTask" | "kanbanTaskLink" | "kanbanTaskAsset" | "kanbanTaskComment" | "kanbanTaskEvent" | "recentFileItem" | "jwks" | "oauthClient" | "oauthResource" | "oauthClientResource" | "oauthRefreshToken" | "oauthAccessToken" | "oauthConsent" | "oauthClientAssertion"
txIsolationLevel: TransactionIsolationLevel
}
model: {
@@ -2254,6 +2256,154 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
}
}
}
AssetTranscript: {
payload: Prisma.$AssetTranscriptPayload<ExtArgs>
fields: Prisma.AssetTranscriptFieldRefs
operations: {
findUnique: {
args: Prisma.AssetTranscriptFindUniqueArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload> | null
}
findUniqueOrThrow: {
args: Prisma.AssetTranscriptFindUniqueOrThrowArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>
}
findFirst: {
args: Prisma.AssetTranscriptFindFirstArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload> | null
}
findFirstOrThrow: {
args: Prisma.AssetTranscriptFindFirstOrThrowArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>
}
findMany: {
args: Prisma.AssetTranscriptFindManyArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>[]
}
create: {
args: Prisma.AssetTranscriptCreateArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>
}
createMany: {
args: Prisma.AssetTranscriptCreateManyArgs<ExtArgs>
result: BatchPayload
}
createManyAndReturn: {
args: Prisma.AssetTranscriptCreateManyAndReturnArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>[]
}
delete: {
args: Prisma.AssetTranscriptDeleteArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>
}
update: {
args: Prisma.AssetTranscriptUpdateArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>
}
deleteMany: {
args: Prisma.AssetTranscriptDeleteManyArgs<ExtArgs>
result: BatchPayload
}
updateMany: {
args: Prisma.AssetTranscriptUpdateManyArgs<ExtArgs>
result: BatchPayload
}
updateManyAndReturn: {
args: Prisma.AssetTranscriptUpdateManyAndReturnArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>[]
}
upsert: {
args: Prisma.AssetTranscriptUpsertArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>
}
aggregate: {
args: Prisma.AssetTranscriptAggregateArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AggregateAssetTranscript>
}
groupBy: {
args: Prisma.AssetTranscriptGroupByArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AssetTranscriptGroupByOutputType>[]
}
count: {
args: Prisma.AssetTranscriptCountArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AssetTranscriptCountAggregateOutputType> | number
}
}
}
AssetTranscriptSegment: {
payload: Prisma.$AssetTranscriptSegmentPayload<ExtArgs>
fields: Prisma.AssetTranscriptSegmentFieldRefs
operations: {
findUnique: {
args: Prisma.AssetTranscriptSegmentFindUniqueArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload> | null
}
findUniqueOrThrow: {
args: Prisma.AssetTranscriptSegmentFindUniqueOrThrowArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>
}
findFirst: {
args: Prisma.AssetTranscriptSegmentFindFirstArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload> | null
}
findFirstOrThrow: {
args: Prisma.AssetTranscriptSegmentFindFirstOrThrowArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>
}
findMany: {
args: Prisma.AssetTranscriptSegmentFindManyArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>[]
}
create: {
args: Prisma.AssetTranscriptSegmentCreateArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>
}
createMany: {
args: Prisma.AssetTranscriptSegmentCreateManyArgs<ExtArgs>
result: BatchPayload
}
createManyAndReturn: {
args: Prisma.AssetTranscriptSegmentCreateManyAndReturnArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>[]
}
delete: {
args: Prisma.AssetTranscriptSegmentDeleteArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>
}
update: {
args: Prisma.AssetTranscriptSegmentUpdateArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>
}
deleteMany: {
args: Prisma.AssetTranscriptSegmentDeleteManyArgs<ExtArgs>
result: BatchPayload
}
updateMany: {
args: Prisma.AssetTranscriptSegmentUpdateManyArgs<ExtArgs>
result: BatchPayload
}
updateManyAndReturn: {
args: Prisma.AssetTranscriptSegmentUpdateManyAndReturnArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>[]
}
upsert: {
args: Prisma.AssetTranscriptSegmentUpsertArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>
}
aggregate: {
args: Prisma.AssetTranscriptSegmentAggregateArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AggregateAssetTranscriptSegment>
}
groupBy: {
args: Prisma.AssetTranscriptSegmentGroupByArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AssetTranscriptSegmentGroupByOutputType>[]
}
count: {
args: Prisma.AssetTranscriptSegmentCountArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AssetTranscriptSegmentCountAggregateOutputType> | number
}
}
}
Invite: {
payload: Prisma.$InvitePayload<ExtArgs>
fields: Prisma.InviteFieldRefs
@@ -5455,6 +5605,31 @@ export const AssetEmbeddingScalarFieldEnum = {
export type AssetEmbeddingScalarFieldEnum = (typeof AssetEmbeddingScalarFieldEnum)[keyof typeof AssetEmbeddingScalarFieldEnum]
export const AssetTranscriptScalarFieldEnum = {
id: 'id',
assetId: 'assetId',
language: 'language',
model: 'model',
workflowTaskId: 'workflowTaskId',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type AssetTranscriptScalarFieldEnum = (typeof AssetTranscriptScalarFieldEnum)[keyof typeof AssetTranscriptScalarFieldEnum]
export const AssetTranscriptSegmentScalarFieldEnum = {
id: 'id',
transcriptId: 'transcriptId',
position: 'position',
startMs: 'startMs',
endMs: 'endMs',
text: 'text'
} as const
export type AssetTranscriptSegmentScalarFieldEnum = (typeof AssetTranscriptSegmentScalarFieldEnum)[keyof typeof AssetTranscriptSegmentScalarFieldEnum]
export const InviteScalarFieldEnum = {
id: 'id',
code: 'code',
@@ -6747,6 +6922,8 @@ export type GlobalOmitConfig = {
assetCommentAttachment?: Prisma.AssetCommentAttachmentOmit
assetCommentReaction?: Prisma.AssetCommentReactionOmit
assetEmbedding?: Prisma.AssetEmbeddingOmit
assetTranscript?: Prisma.AssetTranscriptOmit
assetTranscriptSegment?: Prisma.AssetTranscriptSegmentOmit
invite?: Prisma.InviteOmit
metadataField?: Prisma.MetadataFieldOmit
notification?: Prisma.NotificationOmit
@@ -75,6 +75,8 @@ export const ModelName = {
AssetCommentAttachment: 'AssetCommentAttachment',
AssetCommentReaction: 'AssetCommentReaction',
AssetEmbedding: 'AssetEmbedding',
AssetTranscript: 'AssetTranscript',
AssetTranscriptSegment: 'AssetTranscriptSegment',
Invite: 'Invite',
MetadataField: 'MetadataField',
Notification: 'Notification',
@@ -481,6 +483,31 @@ export const AssetEmbeddingScalarFieldEnum = {
export type AssetEmbeddingScalarFieldEnum = (typeof AssetEmbeddingScalarFieldEnum)[keyof typeof AssetEmbeddingScalarFieldEnum]
export const AssetTranscriptScalarFieldEnum = {
id: 'id',
assetId: 'assetId',
language: 'language',
model: 'model',
workflowTaskId: 'workflowTaskId',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type AssetTranscriptScalarFieldEnum = (typeof AssetTranscriptScalarFieldEnum)[keyof typeof AssetTranscriptScalarFieldEnum]
export const AssetTranscriptSegmentScalarFieldEnum = {
id: 'id',
transcriptId: 'transcriptId',
position: 'position',
startMs: 'startMs',
endMs: 'endMs',
text: 'text'
} as const
export type AssetTranscriptSegmentScalarFieldEnum = (typeof AssetTranscriptSegmentScalarFieldEnum)[keyof typeof AssetTranscriptSegmentScalarFieldEnum]
export const InviteScalarFieldEnum = {
id: 'id',
code: 'code',
+2
View File
@@ -32,6 +32,8 @@ export type * from './models/AssetComment.ts'
export type * from './models/AssetCommentAttachment.ts'
export type * from './models/AssetCommentReaction.ts'
export type * from './models/AssetEmbedding.ts'
export type * from './models/AssetTranscript.ts'
export type * from './models/AssetTranscriptSegment.ts'
export type * from './models/Invite.ts'
export type * from './models/MetadataField.ts'
export type * from './models/Notification.ts'
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+5 -3
View File
@@ -18,6 +18,10 @@ export function registerWorkflowTrigger(cb: WorkflowTriggerCallback) {
onWorkflowTaskCreated = cb
}
export async function notifyWorkflowTaskCreated(task: WorkflowTask): Promise<void> {
if (task.status === 'pending') await onWorkflowTaskCreated?.(task)
}
// Global callback for workflow task cancellation (decouples db/core packages from workflow engine)
type WorkflowCancelCallback = (taskId: string) => Promise<void>
let onWorkflowTaskCancelled: WorkflowCancelCallback | null = null
@@ -149,9 +153,7 @@ function createPrismaClient() {
workflowTask: {
async create({ args, query }) {
const result = await query(args)
if (onWorkflowTaskCreated && (result as WorkflowTask).status === 'pending') {
onWorkflowTaskCreated(result as WorkflowTask).catch(console.error)
}
notifyWorkflowTaskCreated(result as WorkflowTask).catch(console.error)
return result
},
},
+2
View File
@@ -377,6 +377,7 @@ declare global {
imageAnnotation?: ImageAnnotationSpec
pdfPages?: PdfPagesSpec
videoChunks?: VideoChunksSpec
transcription?: { language: string | null; model: string }
/** Render that produced this result, if any (set by the read_asset pipeline). */
assetRead?: AssetReadRequest
watermark?: WatermarkTaskPayload
@@ -403,6 +404,7 @@ declare global {
export interface WorkflowTaskOutput {
error?: string
transcription?: { transcriptId: string; language: string } | { noSpeech: true }
recoveryAttempts?: number
[key: string]: unknown
}
+1
View File
@@ -86,6 +86,7 @@ export const assetInfoSchema = z.object({
type: z.string(),
targetType: z.string().optional().nullable(),
status: z.string(),
mediaType: z.string().nullable().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
latestChildren: z.array(childPreviewSchema).optional(),
preview: previewInfoSchema.nullable().optional(),
+1
View File
@@ -26,6 +26,7 @@ export * from './search'
export * from './share'
export * from './skill'
export * from './team'
export * from './transcript'
export * from './upload'
export * from './user-metadata'
export * from './versionStack'
+72
View File
@@ -0,0 +1,72 @@
import { z } from 'zod'
export const transcriptLanguageCodeSchema = z.string().regex(/^[a-z]{2,3}$/)
export type SavedTranscriptLanguages = { languages: string[] }
export type TranscriptSegment = {
id: string
startMs: number
endMs: number
text: string
}
export type SavedTranscript = {
id: string
language: string
segments: TranscriptSegment[]
}
export const generateTranscriptRequestSchema = z.object({
language: transcriptLanguageCodeSchema.optional(),
})
export const updateTranscriptSegmentRequestSchema = z.strictObject({
text: z.string().refine((text) => !text.includes('\0')),
})
export const transcriptLanguagesSchema = z.object({
model: z.string().min(1),
languages: z.array(z.object({ code: transcriptLanguageCodeSchema, name: z.string().min(1) })),
})
interface TranscriptVideoProxy {
key?: string
resolution?: string
width: number
height: number
}
export function selectTranscriptVideoProxyKey(
media?: { videoTranscodes?: TranscriptVideoProxy[]; videoPreview?: { key?: string } } | null,
): string | undefined {
let selectedKey: string | undefined
let smallestArea = Infinity
for (const proxy of media?.videoTranscodes ?? []) {
if (!proxy.key || proxy.key === media?.videoPreview?.key || proxy.resolution === '180p') {
continue
}
const area = proxy.width > 0 && proxy.height > 0 ? proxy.width * proxy.height : Infinity
if (area < smallestArea) {
selectedKey = proxy.key
smallestArea = area
}
}
return selectedKey
}
export const transcriptionErrors = {
noAudio: 'The video does not contain an audio track',
noProxy: 'A completed full video proxy is required to generate transcripts',
tooLarge: 'Audio exceeds the embedding server upload limit',
} as const
export type GenerateTranscriptResult =
| { kind: 'queued' | 'busy'; taskId: string }
| { kind: 'existing'; transcriptId: string; language: string }
| { kind: 'no_speech' }
export type TranscriptJobStatus =
| { status: 'pending' | 'processing' | 'completed' | 'no_speech'; taskId: string }
| { status: 'failed'; taskId: string; reason: keyof typeof transcriptionErrors | 'unknown' }
@@ -0,0 +1,238 @@
import { execFile } from 'node:child_process'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
import { promisify } from 'node:util'
import { initAgentWorkflows } from '@shumai/agent'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { TaskQueueAgent, workflowService } from '@shumai/workflow-core'
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
const execFileAsync = promisify(execFile)
const bucket = 'shumai-e2e-transcript'
const preview = { key: 'video/180p.mp4', resolution: '180p', width: 32, height: 32 }
const largerProxy = { key: 'video/720p.mp4', resolution: '720p', width: 96, height: 96 }
const languages = {
model: 'whisper-tiny',
languages: [
{ code: 'en', name: 'English' },
{ code: 'zh', name: 'Chinese' },
],
}
describe('Transcribe video workflow', () => {
setupTestDbHooks()
let directory: string
let provider: ReturnType<typeof Bun.serve>
let responseStatus = 200
let firstRequestBusy = false
let uploads: Array<{
language: FormDataEntryValue | null
length: string | null
hasTransferEncoding: boolean
model: FormDataEntryValue | null
format: FormDataEntryValue | null
audio: Buffer
}> = []
beforeAll(async () => {
directory = await mkdtemp(join(tmpdir(), 'shumai-e2e-transcripts-'))
await execFileAsync('ffmpeg', [
'-v',
'error',
'-f',
'lavfi',
'-i',
'color=size=64x64:duration=2',
'-itsoffset',
'1',
'-f',
'lavfi',
'-i',
'sine=frequency=440:duration=1',
'-c:v',
'mpeg4',
'-c:a',
'pcm_s16le',
join(directory, 'audio.mkv'),
])
const fullProxy = { width: 64, height: 64 }
for (const [fileName, { width, height }, disableAudio] of [
['audio.mp4', fullProxy, false],
['silent.mp4', fullProxy, true],
['720p.mp4', largerProxy, true],
['180p.mp4', preview, true],
] as const) {
await transcodeService.transcodeVideo({
inputFile: join(directory, 'audio.mkv'),
outputFile: join(directory, fileName),
width,
height,
frameRate: 25,
disableAudio,
hardwareAcceleration: 'off',
})
}
// Replace only the inference server and inspect what the worker sends over HTTP.
provider = Bun.serve({
hostname: '127.0.0.1',
port: 0,
async fetch(request) {
const path = new URL(request.url).pathname
if (path === '/v1/audio/transcriptions/languages') return Response.json(languages)
if (path !== '/v1/audio/transcriptions' || request.method !== 'POST')
return new Response(null, { status: 404 })
const form = await request.formData()
const file = form.get('file')
if (!(file instanceof File)) return new Response(null, { status: 400 })
uploads.push({
language: form.get('language'),
length: request.headers.get('content-length'),
hasTransferEncoding: request.headers.has('transfer-encoding'),
model: form.get('model'),
format: form.get('response_format'),
audio: Buffer.from(await file.arrayBuffer()),
})
if (firstRequestBusy && uploads.length === 1) return new Response(null, { status: 429 })
if (responseStatus !== 200) return new Response(null, { status: responseStatus })
return Response.json({
language: form.get('language') ?? 'en',
text: 'Hello',
segments: [{ start: 1.012, end: 1.875, text: 'Hello' }],
})
},
})
vi.stubEnv('S3_BUCKET', bucket)
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', `${provider.url}v1/embeddings/`)
initAgentWorkflows()
await workflowService.startWorkers(TaskQueueAgent)
})
beforeEach(() => {
uploads = []
responseStatus = 200
firstRequestBusy = false
})
afterAll(async () => {
await workflowService.shutdownWorkers()
workflowService.close()
await provider?.stop(true)
await s3Service.deletePrefix(bucket, '')
if (directory) await rm(directory, { recursive: true, force: true })
vi.unstubAllEnvs()
})
async function submitVideo(name: string, language: string | null) {
const team = await prisma.team.create({ data: { name: 'Transcription E2E' } })
const project = await prisma.project.create({ data: { name: 'Videos', teamId: team.id } })
const fullProxy = { key: `video/${name}`, resolution: '480p', width: 64, height: 64 }
await Promise.all(
[preview, largerProxy, fullProxy].map(({ key }) =>
s3Service.uploadFileToKey(join(directory, basename(key)), key, 'video/mp4'),
),
)
const asset = await prisma.asset.create({
data: {
name,
type: 'file',
status: 'processed',
project: { connect: { id: project.id } },
mediaType: 'video/x-matroska',
storageKey: { create: { key: 'video/unavailable-original.mkv' } },
media: {
proxyType: 'video',
videoTranscodes: [largerProxy, preview, fullProxy],
videoPreview: preview,
imageTranscodes: [],
duration: 2,
filesize: 0,
frames: 50,
finishedAt: new Date().toISOString(),
metadata: null,
original: null,
},
},
})
const result = await transcriptService.generate(asset.id, language)
if (result.kind !== 'queued') throw new Error(`Unexpected generation result ${result.kind}`)
return {
assetId: asset.id,
task: await prisma.workflowTask.findUniqueOrThrow({ where: { id: result.taskId } }),
}
}
it('uses the smallest full proxy to send a timeline-aligned WAV and saves the detected language and segments after retrying a busy server', async () => {
firstRequestBusy = true
const { task, assetId } = await submitVideo('audio.mp4', null)
await workflowService.executeWait(task, 20_000)
expect(uploads).toHaveLength(2)
const upload = uploads[1]
expect(upload).toMatchObject({
language: null,
hasTransferEncoding: false,
model: 'whisper-tiny',
format: 'verbose_json',
})
expect(Number(upload.length)).toBeGreaterThan(upload.audio.length)
expect(upload.audio.toString('ascii', 0, 4)).toBe('RIFF')
expect(upload.audio.readUInt16LE(22)).toBe(1)
expect(upload.audio.readUInt32LE(24)).toBe(16_000)
expect(upload.audio.readUInt16LE(34)).toBe(16)
const pcm = upload.audio.indexOf('data', 36) + 8
expect(upload.audio.subarray(pcm, pcm + 30_000).every((sample) => sample === 0)).toBe(true)
expect(upload.audio.subarray(pcm + 34_000).some((sample) => sample !== 0)).toBe(true)
const transcript = await prisma.assetTranscript.findUniqueOrThrow({
where: { assetIdLanguage: { assetId, language: 'en' } },
include: { segments: true },
})
expect(transcript).toMatchObject({
model: 'whisper-tiny',
workflowTaskId: task.id,
segments: [{ position: 0, startMs: 1012, endMs: 1875, text: 'Hello' }],
})
await vi.waitFor(async () =>
expect(await s3Service.listObjects(bucket, 'temp/transcripts/')).toEqual([]),
)
}, 24_000)
it('passes an explicit language and treats an upload limit error as permanent', async () => {
responseStatus = 413
const { task, assetId } = await submitVideo('audio.mp4', 'zh')
await expect(workflowService.executeWait(task, 20_000)).rejects.toThrow(
'Audio exceeds the embedding server upload limit',
)
expect(uploads).toHaveLength(1)
expect(uploads[0].language).toBe('zh')
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId: task.id,
status: 'failed',
reason: 'tooLarge',
})
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
await vi.waitFor(async () =>
expect(await s3Service.listObjects(bucket, 'temp/transcripts/')).toEqual([]),
)
}, 24_000)
it('fails with a clear message when the video has no audio track', async () => {
const { task, assetId } = await submitVideo('silent.mp4', null)
await expect(workflowService.executeWait(task, 20_000)).rejects.toThrow(
'The video does not contain an audio track',
)
expect(uploads).toHaveLength(0)
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId: task.id,
status: 'failed',
reason: 'noAudio',
})
}, 24_000)
})
+9 -54
View File
@@ -34,7 +34,15 @@ import { execFile } from 'child_process'
import { promisify } from 'util'
import { ulid } from 'ulid'
import { logger } from '@shumai/core/src/logger'
import { ApplicationFailure, defineStep, getLocalTaskAbortSignal } from '@shumai/workflow-core'
import {
ApplicationFailure,
defineStep,
ensureLocalMediaFile,
getErrorDetails,
getLocalTaskAbortSignal,
} from '@shumai/workflow-core'
export { ensureLocalMediaFile } from '@shumai/workflow-core'
const execFileAsync = promisify(execFile)
@@ -42,59 +50,6 @@ function getActivityCancellationSignal(taskId?: string): AbortSignal | undefined
return getLocalTaskAbortSignal(taskId)
}
function getErrorDetails(err: unknown): { code?: string; message: string; name?: string } {
if (err && typeof err === 'object') {
const record = err as Record<string, unknown>
return {
code: typeof record.code === 'string' ? record.code : undefined,
message:
typeof record.message === 'string'
? record.message
: err instanceof Error
? err.message
: String(err),
name: typeof record.name === 'string' ? record.name : undefined,
}
}
return {
message: String(err),
}
}
export async function ensureLocalMediaFile(assetKey: string, filePath: string): Promise<string> {
if (fs.existsSync(filePath)) {
return filePath
}
const dir = path.dirname(filePath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
const bucket = process.env.S3_BUCKET || 'shumai'
try {
await s3Service.downloadToFile(bucket, assetKey, filePath)
} catch (err) {
const { code, message, name } = getErrorDetails(err)
const lowerMsg = message.toLowerCase()
const lowerCode = (code || '').toLowerCase()
const lowerName = (name || '').toLowerCase()
if (
lowerCode === 'enoent' ||
lowerCode === 'nosuchkey' ||
lowerName === 'nosuchkey' ||
lowerMsg.includes('enoent') ||
lowerMsg.includes('nosuchkey')
) {
throw ApplicationFailure.create({
message: `Failed to download media to local file: ${message}`,
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
})
}
throw err
}
return filePath
}
export interface GetMediaInfoActivityParams {
assetId: string
assetKey: string
@@ -31,6 +31,15 @@ describe('FileBrowserContextMenu', () => {
updatedAt: '2026-01-01T00:00:00Z',
} as AssetInfo
const fullProxy = {
id: 'proxy-480p',
url: '/video-480p.mp4',
key: 'video-480p.mp4',
width: 854,
height: 480,
size: 100,
}
const renderWithMenu = (
item: AssetInfo,
props: Partial<React.ComponentProps<typeof FileBrowserContextMenu>> = {},
@@ -87,6 +96,71 @@ describe('FileBrowserContextMenu', () => {
expect(screen.queryByRole('menuitem', { name: 'Open in new tab' })).toBeNull()
})
it('starts transcription on the displayed video file in a stack', () => {
const onGenerateTranscripts = vi.fn()
renderWithMenu(
{
...stackItem,
proxyType: 'video',
media: { videoTranscodes: [fullProxy] },
versionStack: {
id: stackItem.id,
versions: [
{ id: 'old', name: 'old.mp4', version: 1, current: false },
{ id: 'current', name: 'current.mp4', version: 2, current: true },
],
},
},
{ onGenerateTranscripts },
)
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
fireEvent.click(screen.getByRole('menuitem', { name: 'Generate Transcripts' }))
expect(onGenerateTranscripts).toHaveBeenCalledWith('current', 'current.mp4')
})
it.each([
{ status: 'uploaded', media: undefined },
{ status: 'processing', media: { videoTranscodes: [fullProxy] } },
{ status: 'processed', media: { videoPreview: { url: '/preview.mp4', key: 'preview.mp4' } } },
])('disables generation for a $status video until a full proxy is ready', ({ status, media }) => {
const onGenerateTranscripts = vi.fn()
renderWithMenu(
{ ...fileItem, mediaType: 'video/mp4', status, media },
{ onGenerateTranscripts },
)
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
const action = screen.getByRole('menuitem', { name: 'Generate Transcripts' })
expect(action.getAttribute('aria-disabled')).toBe('true')
fireEvent.click(action)
expect(onGenerateTranscripts).not.toHaveBeenCalled()
})
it.each([
{
label: 'a read-only member',
item: { ...fileItem, proxyType: 'video' as const },
canEdit: false,
},
{ label: 'a non-video asset', item: fileItem, canEdit: true },
{
label: 'an audio-only upload with a video MIME type',
item: { ...fileItem, proxyType: 'audio' as const, mediaType: 'video/mp4' },
canEdit: true,
},
{
label: 'an archived video',
item: { ...fileItem, proxyType: 'video' as const, status: 'archived' },
canEdit: true,
},
])('hides the action for $label', ({ item, canEdit }) => {
renderWithMenu(item, { canEdit, onGenerateTranscripts: vi.fn() })
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
expect(screen.queryByRole('menuitem', { name: 'Generate Transcripts' })).toBeNull()
})
it('renders Manage versions for version_stack item when canEdit is true', () => {
const onManageVersions = vi.fn()
renderWithMenu(stackItem, { onManageVersions })
@@ -1,5 +1,4 @@
import type { AssetInfo } from '@shumai/dtos'
import type { ShareLinkInfo } from '@shumai/dtos'
import { selectTranscriptVideoProxyKey, type AssetInfo, type ShareLinkInfo } from '@shumai/dtos'
import { m } from '@/ui/paraglide/messages.js'
import {
ContextMenuContent,
@@ -27,6 +26,7 @@ import {
Copy,
Layers,
ScanSearch,
Captions,
} from 'lucide-react'
import { CopyContextMenuSub } from './copy-submenu'
import { isImageItem, type CopyKind } from './copy-options'
@@ -40,6 +40,7 @@ interface FileBrowserContextMenuProps {
onDownload: (items: AssetInfo[]) => void
onCopy?: (kind: CopyKind, items: AssetInfo[]) => void
onFindSimilar?: (item: AssetInfo) => void
onGenerateTranscripts?: (assetId: string, name: string) => void
onRestore: (items: AssetInfo[]) => void
onArchive?: (items: AssetInfo[]) => void
onRestoreArchive?: (items: AssetInfo[]) => void
@@ -75,6 +76,7 @@ export function FileBrowserContextMenu({
onDownload,
onCopy,
onFindSimilar,
onGenerateTranscripts,
onRestore,
onArchive,
onRestoreArchive,
@@ -237,6 +239,18 @@ export function FileBrowserContextMenu({
</ContextMenuItem>
)
const videoVersion =
item.type === 'version_stack'
? item.versionStack?.versions.find((version) => version.current)
: undefined
const transcriptAssetId = item.type === 'file' ? item.id : videoVersion?.id
const transcriptAssetStatus = videoVersion?.status ?? item.status
const isTranscriptVideo = item.proxyType
? item.proxyType === 'video'
: item.mediaType?.startsWith('video/')
const transcriptReady =
transcriptAssetStatus === 'processed' && Boolean(selectTranscriptVideoProxyKey(item.media))
const contextMenuContent =
isItemSelected && selectedIds.size > 1 ? (
<ContextMenuContent
@@ -360,6 +374,21 @@ export function FileBrowserContextMenu({
<span>{m.download()}</span>
</ContextMenuItem>
{findSimilarItem}
{canEdit &&
onGenerateTranscripts &&
transcriptAssetId &&
['uploading', 'uploaded', 'processing', 'processed'].includes(transcriptAssetStatus) &&
isTranscriptVideo && (
<ContextMenuItem
disabled={!transcriptReady}
onSelect={() =>
onGenerateTranscripts(transcriptAssetId, videoVersion?.name || item.name)
}
>
<Captions className="mr-2 h-4 w-4" />
<span>{m.generate_transcripts()}</span>
</ContextMenuItem>
)}
<CopyContextMenuSub
items={itemsToModify}
context={{
@@ -30,6 +30,7 @@ import { FilePreviewDialog } from '../file-preview-dialog'
import { ShareLinkCreatedDialog } from '../share-link-created-dialog'
import { FileBrowserContentSkeleton } from '../loading-skeletons'
import { FileBrowserContextMenu } from './context-menu'
import { GenerateTranscriptsDialog } from './generate-transcripts-dialog'
import { getItemInAppUrl } from './copy-options'
import { FindSimilarDialog } from '../search/find-similar-dialog'
import { useSemanticSearchEnabled } from '../search/use-semantic-search-enabled'
@@ -63,6 +64,7 @@ import { FileBrowserToolbar } from './toolbar'
import { useFileActions } from './use-file-actions'
import { useBatchFileStatus } from '@/ui/hooks/use-batch-file-status'
import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
import { useServerFeatures } from '@/ui/hooks/use-server-features'
import { ArchiveConfirmDialog } from '../archive-confirm-dialog'
interface FileBrowserProps {
@@ -161,6 +163,9 @@ export function FileBrowser({
}: FileBrowserProps) {
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
const [similarImage, setSimilarImage] = useState<AssetInfo | null>(null)
const [transcriptVideo, setTranscriptVideo] = useState<{ id: string; name: string } | null>(null)
const closeTranscriptDialog = useCallback(() => setTranscriptVideo(null), [])
const transcriptionEnabled = useServerFeatures().data?.transcriptionEnabled
const semanticSearchEnabled = useSemanticSearchEnabled(
teamId,
Boolean(
@@ -1122,6 +1127,11 @@ export function FileBrowser({
onDownload={handleDownload}
onCopy={handleCopy}
onFindSimilar={semanticSearchEnabled && rootFolderId ? setSimilarImage : undefined}
onGenerateTranscripts={
transcriptionEnabled && !isShareView && !isPublic
? (id, name) => setTranscriptVideo({ id, name })
: undefined
}
onNewFolder={handleNewFolder}
onUploadFile={handleUploadFilesClick}
onUploadFolder={handleUploadFolderClick}
@@ -1182,6 +1192,15 @@ export function FileBrowser({
)}
{renderContent()}
{transcriptVideo && (
<GenerateTranscriptsDialog
key={transcriptVideo.id}
assetId={transcriptVideo.id}
name={transcriptVideo.name}
onClose={closeTranscriptDialog}
/>
)}
{semanticSearchEnabled && similarImage && rootFolderId && (
<FindSimilarDialog
image={similarImage}
@@ -0,0 +1,227 @@
import { useEffect, useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { TranscriptJobStatus } from '@shumai/dtos'
import { toast } from 'sonner'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { savedTranscriptLanguagesKey } from '@/ui/hooks/use-video-transcript'
import { Button } from '@/ui/components/ui/button'
import {
Combobox,
ComboboxContent,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxList,
} from '@/ui/components/ui/combobox'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
function isActive(status?: TranscriptJobStatus | null) {
return status?.status === 'pending' || status?.status === 'processing'
}
function statusMessage(job: TranscriptJobStatus) {
switch (job.status) {
case 'pending':
return m.transcript_queued()
case 'processing':
return m.transcript_generating()
case 'completed':
return m.transcript_completed()
case 'no_speech':
return m.transcript_no_speech()
case 'failed':
if (job.reason === 'tooLarge') return m.transcript_audio_too_large()
if (job.reason === 'noAudio') return m.transcript_no_audio()
if (job.reason === 'noProxy') return m.transcript_proxy_required()
return m.transcript_failed()
}
}
export function GenerateTranscriptsDialog({
assetId,
name,
onClose,
}: {
assetId: string
name: string
onClose: () => void
}) {
const dialogRef = useRef<HTMLDivElement>(null)
const activeTaskId = useRef<string>(undefined)
const queryClient = useQueryClient()
const [language, setLanguage] = useState('')
const param = { fileId: assetId }
const statusKey = ['transcription-status', assetId]
const languages = useQuery({
queryKey: ['transcription-languages'],
queryFn: async () => {
const response = await client.api.transcription.languages.$get()
if (!response.ok) throw new Error(m.transcript_languages_unavailable())
return await response.json()
},
staleTime: 5 * 60 * 1000,
retry: false,
})
const job = useQuery({
queryKey: statusKey,
queryFn: async () => {
const response = await client.api.files[':fileId']['transcription-status'].$get({ param })
if (!response.ok) throw new Error(m.transcript_status_unavailable())
return await response.json()
},
refetchInterval: (query) => (isActive(query.state.data) ? 2_000 : false),
})
const hasFreshJobStatus = job.isFetchedAfterMount && job.isSuccess
useEffect(() => {
if (!job.data) return
if (isActive(job.data)) {
// Reopening the dialog can briefly show a cached status for a finished job.
if (hasFreshJobStatus) activeTaskId.current = job.data.taskId
return
}
if (job.data.status !== 'completed') return
void queryClient.invalidateQueries({ queryKey: savedTranscriptLanguagesKey(assetId) })
if (activeTaskId.current === job.data.taskId) {
activeTaskId.current = undefined
toast.success(m.transcript_completed())
onClose()
}
}, [assetId, hasFreshJobStatus, job.data, onClose, queryClient])
const generate = useMutation({
mutationFn: async () => {
const response = await client.api.files[':fileId'].transcripts.$post({
param,
json: { language: language || undefined },
})
if (!response.ok) throw new Error(m.transcript_submit_failed())
return await response.json()
},
onSuccess: (result) => {
if (result.kind === 'existing' || result.kind === 'no_speech') {
if (result.kind === 'existing') {
void queryClient.invalidateQueries({ queryKey: savedTranscriptLanguagesKey(assetId) })
}
toast.info(
result.kind === 'existing' ? m.transcript_already_exists() : m.transcript_no_speech(),
)
return
}
activeTaskId.current = result.taskId
queryClient.setQueryData<TranscriptJobStatus>(statusKey, {
status: 'pending',
taskId: result.taskId,
})
void queryClient.invalidateQueries({ queryKey: statusKey })
if (result.kind === 'queued') toast.success(m.transcript_queued())
},
})
const choices = [
{ code: '', name: m.transcript_language_auto() },
...(languages.data?.languages ?? []),
]
const busy = generate.isPending || isActive(job.data)
return (
<Dialog
open
onOpenChange={(open) => {
if (!open) onClose()
}}
>
<DialogContent ref={dialogRef} showCloseButton={false}>
<DialogHeader>
<DialogTitle>{m.generate_transcripts()}</DialogTitle>
<DialogDescription>{name}</DialogDescription>
</DialogHeader>
<Combobox
items={choices}
value={choices.find((choice) => choice.code === language)}
onValueChange={(choice) => setLanguage(choice?.code ?? '')}
itemToStringLabel={(choice) => choice.name}
isItemEqualToValue={(choice, value) => choice.code === value.code}
disabled={busy || languages.isPending || languages.isError}
>
<label htmlFor="transcript-language" className="text-sm font-medium">
{m.language()}
</label>
<ComboboxInput id="transcript-language" />
<ComboboxContent container={dialogRef}>
<ComboboxEmpty>{m.transcript_no_languages_found()}</ComboboxEmpty>
<ComboboxList>
{(choice) => (
<ComboboxItem key={choice.code} value={choice}>
{choice.name}
</ComboboxItem>
)}
</ComboboxList>
</ComboboxContent>
</Combobox>
{languages.isPending && (
<p role="status" className="text-sm text-muted-foreground">
{m.loading()}
</p>
)}
{languages.isError && (
<div className="flex items-center justify-between gap-2">
<p role="alert" className="text-sm text-destructive">
{m.transcript_languages_unavailable()}
</p>
<Button variant="outline" size="sm" onClick={() => languages.refetch()}>
{m.retry()}
</Button>
</div>
)}
{generate.isError && (
<p role="alert" className="text-sm text-destructive">
{generate.error.message}
</p>
)}
{job.isError && (
<p role="alert" className="text-sm text-destructive">
{m.transcript_status_unavailable()}
</p>
)}
{job.data && (
<p
role="status"
className={
job.data.status === 'failed'
? 'text-sm text-destructive'
: 'text-sm text-muted-foreground'
}
>
{statusMessage(job.data)}
</p>
)}
<DialogFooter>
<Button variant="outline" onClick={onClose}>
{m.close()}
</Button>
<Button
disabled={busy || !languages.data || job.isPending}
onClick={() => generate.mutate()}
>
{m.generate()}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -18,6 +18,7 @@ export function FileViewer({
shareId,
allowDownload,
autoPlay,
transcriptToggle,
children,
}: OuterFileViewerProps) {
const viewerDef = getViewerForFile(file)
@@ -37,6 +38,7 @@ export function FileViewer({
shareId={shareId}
allowDownload={allowDownload}
autoPlay={autoPlay}
transcriptToggle={transcriptToggle}
>
{children}
</ViewerComponent>
@@ -56,6 +56,12 @@ vi.mock('@/ui/api/client', () => ({
},
files: {
':fileId': {
transcripts: {
$get: vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ languages: [] }),
}),
},
comments: {
$get: vi.fn().mockResolvedValue({
ok: true,
@@ -21,6 +21,7 @@ import {
} from '@/ui/components/ui/dialog'
import { Input } from '@/ui/components/ui/input'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { useVideoTranscript } from '@/ui/hooks/use-video-transcript'
import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
import { m } from '@/ui/paraglide/messages.js'
import { useMemberStore } from '@/ui/stores/members'
@@ -32,6 +33,7 @@ import React, { useEffect, useMemo, useRef, useState } from 'react'
import type { MediaController } from '../viewers/types'
import { MobileFileBottomSheet } from './mobile-file-bottom-sheet'
import { MobileFileHeader } from './mobile-file-header'
import { TranscriptPanel } from './transcript-panel'
export interface MobileFileDetailProps {
projectId: string
@@ -100,6 +102,7 @@ export function MobileFileDetail({
const { canEdit } = usePermissions(projectId)
const { members } = useMemberStore()
const mediaControllerRef = useRef<MediaController | null>(null)
const transcript = useVideoTranscript(!isPublic && file.id === activeFileId ? file : undefined)
const [sheetHeightPercent, setSheetHeightPercent] = useState(50)
const [annotations, setAnnotations] = useState<Annotation[]>([])
@@ -268,28 +271,40 @@ export function MobileFileDetail({
startTime={startTime}
shareId={shareId}
allowDownload={allowDownload}
transcriptToggle={transcript?.toggle}
/>
</div>
{/* Part 3: Freely Draggable Bottom Sheet */}
<MobileFileBottomSheet
teamId={teamId}
projectId={projectId}
file={file}
onSaveField={onSaveField}
members={members}
onCommentSelect={handleCommentSelect}
hideAnnotationControl={file.proxyType === 'audio'}
readOnly={isPublic || !canEdit}
publicFields={publicFields}
isPublic={isPublic}
shareId={shareId}
currentTime={currentTime}
onTyping={() => mediaControllerRef.current?.pause()}
selectedCommentId={selectedCommentId}
heightPercent={sheetHeightPercent}
onHeightPercentChange={setSheetHeightPercent}
/>
{transcript?.panel && (
<TranscriptPanel
key={transcript.panel.assetId}
{...transcript.panel}
canEdit={canEdit}
mediaControllerRef={mediaControllerRef}
className="z-20 h-[46dvh] w-full rounded-t-2xl border-t border-border"
/>
)}
<div className={transcript?.panel ? 'hidden' : 'contents'}>
<MobileFileBottomSheet
teamId={teamId}
projectId={projectId}
file={file}
onSaveField={onSaveField}
members={members}
onCommentSelect={handleCommentSelect}
hideAnnotationControl={file.proxyType === 'audio'}
readOnly={isPublic || !canEdit}
publicFields={publicFields}
isPublic={isPublic}
shareId={shareId}
currentTime={currentTime}
onTyping={() => mediaControllerRef.current?.pause()}
selectedCommentId={selectedCommentId}
heightPercent={sheetHeightPercent}
onHeightPercentChange={setSheetHeightPercent}
/>
</div>
{/* Dialogs */}
{!isPublic && isLinkedTasksOpen && (
@@ -0,0 +1,112 @@
import { ResizeHandle } from '@/ui/components/resize-handle'
import { m } from '@/ui/paraglide/messages.js'
import {
useCallback,
useLayoutEffect,
useRef,
useState,
type ComponentProps,
type Dispatch,
type SetStateAction,
} from 'react'
import { TranscriptPanel } from './transcript-panel'
const minTranscriptWidth = 20
const maxTranscriptWidth = 45
const preferredPlayerWidth = 256
const keyboardSteps = new Map([
['ArrowLeft', -1],
['ArrowRight', 1],
['Home', -maxTranscriptWidth],
['End', maxTranscriptWidth],
])
interface ResizableTranscriptPanelProps extends Omit<
ComponentProps<typeof TranscriptPanel>,
'className'
> {
widthPercent: number
setWidthPercent: Dispatch<SetStateAction<number>>
}
export function ResizableTranscriptPanel({
widthPercent,
setWidthPercent,
...panelProps
}: ResizableTranscriptPanelProps) {
const sheetRef = useRef<HTMLDivElement>(null)
const [maxWidthPercent, setMaxWidthPercent] = useState(maxTranscriptWidth)
const minWidthPercent = Math.min(minTranscriptWidth, maxWidthPercent)
useLayoutEffect(() => {
const viewer = sheetRef.current?.parentElement
if (!viewer) return
const updateLimit = () => {
const viewerWidth = viewer.clientWidth
const playerWidth = Math.min(preferredPlayerWidth, viewerWidth / 2)
const availablePercent = ((viewerWidth - playerWidth) / window.innerWidth) * 100
setMaxWidthPercent(Math.min(maxTranscriptWidth, availablePercent))
}
updateLimit()
const observer = new ResizeObserver(updateLimit)
observer.observe(viewer)
window.addEventListener('resize', updateLimit)
return () => {
observer.disconnect()
window.removeEventListener('resize', updateLimit)
}
}, [])
const adjustWidth = useCallback(
(deltaPercent: number) => {
setWidthPercent((previous) => {
const displayedWidth = Math.min(previous, maxWidthPercent)
const nextWidth = Math.min(
maxWidthPercent,
Math.max(minWidthPercent, displayedWidth + deltaPercent),
)
return nextWidth === displayedWidth ? previous : nextWidth
})
},
[maxWidthPercent, minWidthPercent, setWidthPercent],
)
const onResize = useCallback(
(deltaPixels: number) => adjustWidth((deltaPixels / window.innerWidth) * 100),
[adjustWidth],
)
const displayedWidth = Math.min(widthPercent, maxWidthPercent)
return (
<>
<div ref={sheetRef} className="min-w-0 shrink-0" style={{ width: `${displayedWidth}vw` }}>
<TranscriptPanel {...panelProps} className="h-full" />
</div>
<ResizeHandle
role="separator"
aria-orientation="vertical"
aria-label={m.transcript_resize()}
aria-controls={panelProps.id}
aria-valuemin={Math.round(minWidthPercent)}
aria-valuemax={Math.round(maxWidthPercent)}
aria-valuenow={Math.round(displayedWidth)}
aria-valuetext={`${Math.round(displayedWidth)}%`}
tabIndex={0}
className="shrink-0 focus-visible:outline-2 focus-visible:outline-ring"
hitAreaClassName="left-0 -right-3"
onResize={onResize}
onKeyDown={(event) => {
const step = keyboardSteps.get(event.key)
if (step === undefined) return
event.preventDefault()
event.stopPropagation()
adjustWidth(step)
}}
/>
</>
)
}
@@ -0,0 +1,352 @@
import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { NativeSelect, NativeSelectOption } from '@/ui/components/ui/native-select'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import type { MediaController } from '@/ui/components/viewers/types'
import { savedTranscriptKey } from '@/ui/hooks/use-video-transcript'
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import { getLocale } from '@/ui/paraglide/runtime.js'
import type { TranscriptSegment } from '@shumai/dtos'
import { useQuery } from '@tanstack/react-query'
import { ChevronDown, ChevronUp, Search, X } from 'lucide-react'
import {
memo,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type RefObject,
} from 'react'
import { TranscriptSegmentRow, type TextMatch } from './transcript-segment-row'
import { createTranscriptTimeline } from './transcript-timeline'
import { useTranscriptScroll } from './use-transcript-scroll'
interface TranscriptPanelProps {
id: string
assetId: string
languages: string[]
canEdit: boolean
mediaControllerRef: RefObject<MediaController | null>
onClose: () => void
className?: string
}
const noSegments: TranscriptSegment[] = []
function findMatches(segments: TranscriptSegment[], search: string) {
const bySegment = new Map<string, TextMatch[]>()
let total = 0
const query = search.trim()
if (!query) return { bySegment, total }
const literal = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const expression = new RegExp(literal, 'giu')
for (const segment of segments) {
const matches = Array.from(segment.text.matchAll(expression), ({ index, 0: text }) => ({
index: total++,
start: index,
end: index + text.length,
}))
if (matches.length) bySegment.set(segment.id, matches)
}
return { bySegment, total }
}
export const TranscriptPanel = memo(function TranscriptPanel({
id,
assetId,
languages,
canEdit,
mediaControllerRef,
onClose,
className,
}: TranscriptPanelProps) {
const locale = getLocale()
const options = useMemo(() => {
const names = new Intl.DisplayNames(locale, { type: 'language' })
return languages
.map((code) => ({ code, name: names.of(code) ?? code }))
.sort((a, b) => a.name.localeCompare(b.name, locale))
}, [languages, locale])
const [preferredLanguage, setPreferredLanguage] = useState<string>(locale)
const language = options.find(({ code }) => code === preferredLanguage)?.code ?? options[0].code
const [searchOpen, setSearchOpen] = useState(false)
const [search, setSearch] = useState('')
const [matchIndex, setMatchIndex] = useState(0)
const [following, setFollowing] = useState(true)
const [activeId, setActiveId] = useState<string>()
const [editingId, setEditingId] = useState<string>()
const toggleSearchRef = useRef<HTMLButtonElement>(null)
const closeRef = useRef<HTMLButtonElement>(null)
const { viewportRef, setViewport, scrollTo, cancelScroll, onScroll, onWheel } =
useTranscriptScroll(() => setFollowing(false))
const transcript = useQuery({
queryKey: savedTranscriptKey(assetId, language),
queryFn: async ({ signal }) => {
const response = await client.api.files[':fileId'].transcripts[':language'].$get(
{ param: { fileId: assetId, language } },
{ init: { signal } },
)
if (!response.ok) throw new Error(m.transcript_load_failed())
return await response.json()
},
retry: false,
})
const segments = transcript.data?.segments ?? noSegments
const activeAt = useMemo(() => createTranscriptTimeline(segments), [segments])
const matches = useMemo(() => findMatches(segments, search), [segments, search])
const selectedMatch = matches.total ? matchIndex % matches.total : undefined
const startEditing = useCallback(
(segmentId: string) => {
mediaControllerRef.current?.pause()
cancelScroll()
setEditingId(segmentId)
},
[cancelScroll, mediaControllerRef],
)
const finishEditing = useCallback(() => setEditingId(undefined), [])
useEffect(() => closeRef.current?.focus({ preventScroll: true }), [])
useEffect(() => {
let active: string | undefined
setActiveId(undefined)
return mediaControllerRef.current?.subscribeToPlaybackTime?.((second) => {
const segmentId = activeAt(second * 1000)
if (segmentId === active) return
active = segmentId
setActiveId(segmentId)
})
}, [activeAt, mediaControllerRef])
useLayoutEffect(() => {
if (editingId) {
scrollTo(viewportRef.current?.querySelector(`[data-segment-id="${CSS.escape(editingId)}"]`))
}
}, [editingId])
useLayoutEffect(() => {
if (following && activeId && !editingId) {
scrollTo(viewportRef.current?.querySelector(`[data-segment-id="${CSS.escape(activeId)}"]`), {
followPlayback: true,
})
}
}, [activeId, following, editingId])
useLayoutEffect(() => {
if (selectedMatch === undefined || editingId) return
setFollowing(false)
scrollTo(viewportRef.current?.querySelector('[data-current-match]'), { bottomInset: 48 })
}, [matches, selectedMatch, editingId])
function toggleSearch() {
if (searchOpen) {
setSearch('')
setMatchIndex(0)
toggleSearchRef.current?.focus({ preventScroll: true })
}
setSearchOpen(!searchOpen)
}
function moveMatch(step: number) {
if (selectedMatch === undefined || editingId) return
setFollowing(false)
setMatchIndex((selectedMatch + step + matches.total) % matches.total)
if (matches.total === 1) {
scrollTo(viewportRef.current?.querySelector('[data-current-match]'), { bottomInset: 48 })
}
}
return (
<aside
id={id}
aria-label={m.transcript_title()}
onKeyDown={(event) => {
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') event.stopPropagation()
}}
className={cn(
'flex min-h-0 shrink-0 flex-col overflow-hidden bg-background text-foreground',
className,
)}
>
<div className="shrink-0 space-y-2 border-b border-border p-2">
<div className="flex items-center justify-between gap-2">
<div className="min-w-0 [&>[data-slot=native-select-wrapper]]:max-w-full">
<NativeSelect
size="sm"
className="max-w-40 truncate"
aria-label={m.language()}
value={language}
disabled={!!editingId}
onChange={(event) => {
cancelScroll()
setPreferredLanguage(event.target.value)
setMatchIndex(0)
setFollowing(true)
}}
>
{options.map(({ code, name }) => (
<NativeSelectOption key={code} value={code}>
{name}
</NativeSelectOption>
))}
</NativeSelect>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
ref={toggleSearchRef}
size="icon-sm"
variant="ghost"
aria-expanded={searchOpen}
aria-label={m.transcript_search()}
title={m.transcript_search()}
onClick={toggleSearch}
>
<Search />
</Button>
<Button
ref={closeRef}
size="icon-sm"
variant="ghost"
aria-label={m.transcript_close()}
title={m.transcript_close()}
onClick={onClose}
>
<X />
</Button>
</div>
</div>
{searchOpen && (
<div className="flex items-center gap-1">
<Input
autoFocus
type="search"
className="h-8 min-w-0 px-2"
aria-label={m.transcript_search()}
placeholder={m.transcript_search()}
value={search}
onChange={(event) => {
setSearch(event.target.value)
setMatchIndex(0)
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === 'Escape') {
event.preventDefault()
event.stopPropagation()
if (event.key === 'Escape') toggleSearch()
else moveMatch(event.shiftKey ? -1 : 1)
}
}}
/>
{search.trim() && (
<output className="shrink-0 px-1 text-xs tabular-nums text-muted-foreground">
{m.transcript_search_count({
current: selectedMatch === undefined ? 0 : selectedMatch + 1,
total: matches.total,
})}
</output>
)}
<Button
size="icon-sm"
variant="ghost"
className="shrink-0"
aria-label={m.transcript_previous_match()}
title={m.transcript_previous_match()}
disabled={!matches.total || !!editingId}
onClick={() => moveMatch(-1)}
>
<ChevronUp />
</Button>
<Button
size="icon-sm"
variant="ghost"
className="shrink-0"
aria-label={m.transcript_next_match()}
title={m.transcript_next_match()}
disabled={!matches.total || !!editingId}
onClick={() => moveMatch(1)}
>
<ChevronDown />
</Button>
</div>
)}
</div>
{transcript.isPending && (
<p role="status" className="p-3 text-sm text-muted-foreground">
{m.loading()}
</p>
)}
{transcript.isError && (
<div className="space-y-2 p-3">
<p role="alert" className="text-sm text-destructive">
{m.transcript_load_failed()}
</p>
<Button size="sm" variant="outline" onClick={() => void transcript.refetch()}>
{m.retry()}
</Button>
</div>
)}
{transcript.data && (
<div className="relative min-h-0 flex-1">
<ScrollArea
className="h-full [&>div>div]:block!"
viewportProps={{
ref: setViewport,
tabIndex: 0,
className: '[overflow-anchor:none]',
onScroll,
onWheel,
}}
>
<ol className="space-y-0.5 px-2 pt-2 pb-14">
{segments.map((segment) => {
const segmentMatches = matches.bySegment.get(segment.id)
return (
<TranscriptSegmentRow
key={segment.id}
segment={segment}
active={segment.id === activeId}
matches={segmentMatches}
selectedMatch={
segmentMatches?.some(({ index }) => index === selectedMatch)
? selectedMatch
: undefined
}
mediaControllerRef={mediaControllerRef}
canEdit={canEdit}
onEdit={canEdit && !editingId ? startEditing : undefined}
editTarget={
segment.id === editingId
? { assetId, language, onFinish: finishEditing }
: undefined
}
/>
)
})}
</ol>
</ScrollArea>
{!following && !editingId && (
<div className="pointer-events-none absolute inset-x-0 bottom-3 flex justify-center px-2">
<Button
size="sm"
variant="outline"
className="pointer-events-auto rounded-full shadow-md dark:bg-background dark:hover:bg-accent"
onClick={() => {
viewportRef.current?.focus({ preventScroll: true })
setFollowing(true)
}}
>
{m.transcript_sync_to_playback()}
</Button>
</div>
)}
</div>
)}
</aside>
)
})
@@ -0,0 +1,231 @@
import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import { Textarea } from '@/ui/components/ui/textarea'
import type { MediaController } from '@/ui/components/viewers/types'
import { formatTime } from '@/ui/components/viewers/video/utils'
import { savedTranscriptKey } from '@/ui/hooks/use-video-transcript'
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import type { SavedTranscript, TranscriptSegment } from '@shumai/dtos'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { Pencil } from 'lucide-react'
import { memo, useLayoutEffect, useRef, useState, type RefObject } from 'react'
export interface TextMatch {
index: number
start: number
end: number
}
interface SegmentEditTarget {
assetId: string
language: string
onFinish: () => void
}
function formatTranscriptTime(ms: number) {
return `${formatTime(ms / 1000)}.${String(ms % 1000).padStart(3, '0')}`
}
function SegmentEditor({
segment,
assetId,
language,
onFinish,
}: SegmentEditTarget & { segment: TranscriptSegment }) {
const [text, setText] = useState(segment.text)
const inputRef = useRef<HTMLTextAreaElement>(null)
const queryClient = useQueryClient()
const queryKey = savedTranscriptKey(assetId, language)
const save = useMutation({
mutationFn: async (draft: string) => {
const response = await client.api.files[':fileId'].transcripts[':language'].segments[
':segmentId'
].$patch({
param: { fileId: assetId, language, segmentId: segment.id },
json: { text: draft },
})
if (!response.ok) throw new Error(m.transcript_save_failed())
return await response.json()
},
onSuccess: async (updated) => {
await queryClient.cancelQueries({ queryKey, exact: true })
queryClient.setQueryData<SavedTranscript>(queryKey, (current) => {
if (!current) return current
return {
...current,
segments: current.segments.map((item) => (item.id === updated.id ? updated : item)),
}
})
},
})
useLayoutEffect(() => inputRef.current?.focus({ preventScroll: true }), [])
return (
<form
className="space-y-2"
onSubmit={(event) => {
event.preventDefault()
if (!save.isPending) save.mutate(text, { onSuccess: onFinish })
}}
onKeyDown={(event) => {
event.stopPropagation()
if (event.key === 'Escape' && !event.nativeEvent.isComposing && !save.isPending) {
event.preventDefault()
onFinish()
}
}}
>
<Textarea
ref={inputRef}
aria-label={m.transcript_edit_segment()}
className="max-h-40 resize-none"
dir="auto"
value={text}
readOnly={save.isPending}
onChange={(event) => setText(event.target.value)}
/>
{save.isError && (
<p role="alert" className="text-sm text-destructive">
{m.transcript_save_failed()}
</p>
)}
<div className="flex justify-end gap-2">
<Button
type="button"
size="sm"
variant="ghost"
disabled={save.isPending}
onClick={onFinish}
>
{m.cancel()}
</Button>
<Button type="submit" size="sm" disabled={save.isPending}>
{save.isPending ? m.saving() : m.save()}
</Button>
</div>
</form>
)
}
export const TranscriptSegmentRow = memo(function TranscriptSegmentRow({
segment,
active,
matches,
selectedMatch,
mediaControllerRef,
canEdit,
onEdit,
editTarget,
}: {
segment: TranscriptSegment
active: boolean
matches?: TextMatch[]
selectedMatch?: number
mediaControllerRef: RefObject<MediaController | null>
canEdit: boolean
onEdit?: (segmentId: string) => void
editTarget?: SegmentEditTarget
}) {
const editButtonRef = useRef<HTMLButtonElement>(null)
const restoreFocus = useRef(false)
useLayoutEffect(() => {
if (!editTarget && restoreFocus.current) {
restoreFocus.current = false
editButtonRef.current?.focus({ preventScroll: true })
}
}, [editTarget])
const timestamp = (
<span
className={cn(
'mb-1 block font-mono text-xs tabular-nums text-muted-foreground',
canEdit && !editTarget && 'pe-7',
)}
dir="ltr"
>
{formatTranscriptTime(segment.startMs)} – {formatTranscriptTime(segment.endMs)}
</span>
)
if (editTarget) {
return (
<li data-segment-id={segment.id} className="px-3 py-2">
{timestamp}
<SegmentEditor {...editTarget} segment={segment} />
</li>
)
}
let textOffset = 0
return (
<li data-segment-id={segment.id} className="group/segment relative">
<button
type="button"
aria-current={active ? 'true' : undefined}
className="block w-full cursor-pointer select-text rounded-md px-3 py-2 text-start group-hover/segment:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:outline-none"
onClick={(event) => {
const selection = window.getSelection()
if (
event.detail > 0 &&
selection?.anchorNode &&
!selection.isCollapsed &&
event.currentTarget.contains(selection.anchorNode)
) {
return
}
mediaControllerRef.current?.seekTo(segment.startMs / 1000, { exact: true })
}}
>
{timestamp}
<span
className={cn(
'block text-sm leading-relaxed whitespace-pre-wrap wrap-anywhere',
active && 'font-bold text-primary',
)}
dir="auto"
>
{matches?.map((match) => {
const preceding = segment.text.slice(textOffset, match.start)
textOffset = match.end
const selected = selectedMatch === match.index
return (
<span key={match.start}>
{preceding}
<mark
data-current-match={selected ? '' : undefined}
className={cn(
'rounded-sm bg-primary/15 px-px text-foreground',
selected && 'bg-primary text-primary-foreground',
)}
>
{segment.text.slice(match.start, match.end)}
</mark>
</span>
)
})}
{segment.text.slice(textOffset)}
</span>
</button>
{onEdit && (
<Button
ref={editButtonRef}
type="button"
size="icon-xs"
variant="ghost"
aria-label={m.transcript_edit_segment()}
title={m.transcript_edit_segment()}
className="absolute end-2 top-1 text-muted-foreground transition-opacity pointer-fine:opacity-0 pointer-fine:group-hover/segment:opacity-100 pointer-fine:group-focus-within/segment:opacity-100"
onClick={() => {
restoreFocus.current = true
onEdit(segment.id)
}}
>
<Pencil />
</Button>
)}
</li>
)
})
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest'
import { createTranscriptTimeline } from './transcript-timeline'
describe('createTranscriptTimeline', () => {
it('uses inclusive starts and exclusive ends for adjacent segments and gaps', () => {
const at = createTranscriptTimeline([
{ id: 'later', startMs: 2000, endMs: 2500, text: '' },
{ id: 'first', startMs: 300, endMs: 1000, text: '' },
{ id: 'second', startMs: 1000, endMs: 1700, text: '' },
])
expect(at(0)).toBeUndefined()
expect(at(300)).toBe('first')
expect(at(1000)).toBe('second')
expect(at(1700)).toBeUndefined()
expect(at(2000)).toBe('later')
expect(at(2500)).toBeUndefined()
})
it('finds the latest active start when a shorter segment overlaps a longer one', () => {
const at = createTranscriptTimeline([
{ id: 'long', startMs: 0, endMs: 4000, text: '' },
{ id: 'short', startMs: 1050, endMs: 1120, text: '' },
])
expect(at(1049.5)).toBe('long')
expect(at(1050)).toBe('short')
expect(at(1120)).toBe('long')
expect(at(4000)).toBeUndefined()
expect(createTranscriptTimeline([])(0)).toBeUndefined()
})
it('uses the new segment at an exact millisecond after converting the seek through seconds', () => {
const at = createTranscriptTimeline([
{ id: 'before', startMs: 1800, endMs: 2010, text: '' },
{ id: 'after', startMs: 2010, endMs: 2200, text: '' },
])
expect(at(2009.999)).toBe('before')
expect(at((2010 / 1000) * 1000)).toBe('after')
})
})
@@ -0,0 +1,30 @@
import type { TranscriptSegment } from '@shumai/dtos'
export function createTranscriptTimeline(segments: TranscriptSegment[]) {
const ordered = [...segments].sort((a, b) => a.startMs - b.startMs)
let latestEndMs = 0
const timeline = ordered.map((segment) => {
latestEndMs = Math.max(latestEndMs, segment.endMs)
return { segment, latestEndMs }
})
return (playbackTimeMs: number): string | undefined => {
// Remove floating-point noise around millisecond boundaries while keeping microsecond precision.
const timeMs = Math.round(playbackTimeMs * 1000) / 1000
let first = 0
let last = timeline.length
while (first < last) {
const middle = Math.floor((first + last) / 2)
if (timeline[middle].segment.startMs <= timeMs) first = middle + 1
else last = middle
}
// Prefer the most recent start when segments overlap. The running maximum bounds
// the backward scan even in long gaps or after the last segment.
for (let index = first - 1; index >= 0; index--) {
const { segment, latestEndMs } = timeline[index]
if (latestEndMs <= timeMs) break
if (segment.endMs > timeMs) return segment.id
}
}
}
@@ -0,0 +1,135 @@
import { useCallback, useEffect, useRef, type UIEvent, type WheelEvent } from 'react'
const followDurationMs = 220
interface FollowAnimation {
viewport: HTMLDivElement
targetTop: number
frame: number
}
export function useTranscriptScroll(onManualScroll: () => void) {
const viewportRef = useRef<HTMLDivElement>(null)
const scrollPosition = useRef(0)
const animation = useRef<FollowAnimation | null>(null)
const cancelScroll = useCallback(() => {
if (animation.current) cancelAnimationFrame(animation.current.frame)
animation.current = null
}, [])
const setViewport = useCallback(
(viewport: HTMLDivElement | null) => {
if (viewportRef.current === viewport) return
cancelScroll()
viewportRef.current = viewport
scrollPosition.current = viewport?.scrollTop ?? 0
},
[cancelScroll],
)
useEffect(() => cancelScroll, [cancelScroll])
function setScrollTop(viewport: HTMLDivElement, top: number) {
viewport.scrollTop = top
scrollPosition.current = viewport.scrollTop
}
function detectManualScroll(viewport: HTMLDivElement) {
const top = viewport.scrollTop
if (top === scrollPosition.current) return false
// A height or width change may clamp the browser's last scroll position.
const clampedTop = Math.min(
scrollPosition.current,
viewport.scrollHeight - viewport.clientHeight,
)
scrollPosition.current = top
if (top === clampedTop) return false
cancelScroll()
onManualScroll()
return true
}
function animateFollow(viewport: HTMLDivElement, top: number) {
const targetTop = Math.max(0, Math.min(top, viewport.scrollHeight - viewport.clientHeight))
if (animation.current?.viewport === viewport) {
if (detectManualScroll(viewport) || animation.current?.targetTop === targetTop) return
}
cancelScroll()
const startTop = viewport.scrollTop
scrollPosition.current = startTop
if (startTop === targetTop) return
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
setScrollTop(viewport, targetTop)
return
}
const motion = { viewport, targetTop, frame: 0 }
let startedAt: number | undefined
const step = (time: number) => {
if (animation.current !== motion) return
if (viewportRef.current !== viewport) {
animation.current = null
return
}
if (detectManualScroll(viewport)) return
startedAt ??= time
const progress = Math.min(1, (time - startedAt) / followDurationMs)
const eased = 1 - (1 - progress) ** 3
setScrollTop(viewport, startTop + (targetTop - startTop) * eased)
if (progress === 1) animation.current = null
else motion.frame = requestAnimationFrame(step)
}
animation.current = motion
motion.frame = requestAnimationFrame(step)
}
function scrollTo(
target: HTMLElement | null | undefined,
{ bottomInset = 0, followPlayback = false } = {},
) {
if (!followPlayback) cancelScroll()
const viewport = viewportRef.current
if (!viewport || !target) return
const item = target.getBoundingClientRect()
const { top, bottom } = viewport.getBoundingClientRect()
if (followPlayback) {
const height = bottom - top
// Check where the segment will settle so nearby segments don't restart the motion.
const pendingTop =
animation.current?.viewport === viewport ? animation.current.targetTop : viewport.scrollTop
const relativeTop = item.top - top
const settledTop = relativeTop + viewport.scrollTop - pendingTop
if (settledTop < 0 || settledTop + item.height / 2 >= height * 0.75) {
const centerOffset = Math.max(0, (height - item.height) / 2)
animateFollow(viewport, viewport.scrollTop + relativeTop - centerOffset)
}
return
}
const visibleBottom = bottom - bottomInset
if (item.top < top || item.height > visibleBottom - top) {
setScrollTop(viewport, viewport.scrollTop + item.top - top)
} else if (item.bottom > visibleBottom) {
setScrollTop(viewport, viewport.scrollTop + item.bottom - visibleBottom)
}
}
function onScroll(event: UIEvent<HTMLDivElement>) {
detectManualScroll(event.currentTarget)
}
function onWheel(event: WheelEvent<HTMLDivElement>) {
if (event.deltaY !== 0 && !event.ctrlKey && animation.current) {
cancelScroll()
onManualScroll()
}
}
return { viewportRef, setViewport, scrollTo, cancelScroll, onScroll, onWheel }
}
+22 -14
View File
@@ -1,14 +1,19 @@
import { cn } from '@/ui/lib/utils'
import { useEffect, useRef, useState } from 'react'
interface ResizeHandleProps {
interface ResizeHandleProps extends Omit<
React.ComponentProps<'div'>,
'children' | 'onMouseDown' | 'onResize'
> {
onResize: (delta: number) => void
className?: string
hitAreaClassName?: string
}
export const ResizeHandle: React.FC<ResizeHandleProps> = ({
onResize,
hitAreaClassName,
className = '',
...props
}) => {
const [isDragging, setIsDragging] = useState(false)
const startXref = useRef(0)
@@ -50,36 +55,39 @@ export const ResizeHandle: React.FC<ResizeHandleProps> = ({
startXref.current = e.clientX
}
// Common hit area that is always larger than the visible element for usability
const HitArea = () => (
<div className="absolute inset-y-0 -left-4 -right-4 z-20 cursor-col-resize touch-none" />
)
return (
<div
className={`group relative z-20 flex h-full w-[2px] cursor-col-resize items-center justify-center bg-border transition-all hover:bg-transparent ${className}`}
{...props}
data-slot="resize-handle"
className={`group/resize relative z-20 flex h-full w-[2px] cursor-col-resize items-center justify-center bg-border transition-all hover:bg-transparent ${className}`}
onMouseDown={handleMouseDown}
>
<HitArea />
<div
aria-hidden="true"
className={cn(
'absolute inset-y-0 -left-4 -right-4 z-20 cursor-col-resize touch-none',
hitAreaClassName,
)}
/>
{/* The glowing vertical line */}
<div
className={`absolute inset-y-0 w-[2px] transition-all duration-300 ease-out
className={`pointer-events-none absolute inset-y-0 w-[2px] transition-all duration-300 ease-out
${
isDragging
? 'bg-blue-600 shadow-[0_0_15px_rgba(37,99,235,0.6)] opacity-100'
: 'bg-blue-400 opacity-0 group-hover:opacity-100 group-hover:shadow-[0_0_8px_rgba(96,165,250,0.5)]'
: 'bg-blue-400 opacity-0 group-hover/resize:opacity-100 group-hover/resize:shadow-[0_0_8px_rgba(96,165,250,0.5)]'
}
`}
/>
{/* The central drag handle (Pill) */}
<div
className={`absolute top-1/2 left-1/2 h-10 w-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-blue-600 transition-all duration-300 ease-out
className={`pointer-events-none absolute top-1/2 left-1/2 h-10 w-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-blue-600 transition-all duration-300 ease-out
${
isDragging
? 'opacity-100 scale-100 shadow-[0_0_10px_rgba(37,99,235,0.5)]'
: 'opacity-0 scale-75 group-hover:opacity-100 group-hover:scale-100'
: 'opacity-0 scale-75 group-hover/resize:opacity-100 group-hover/resize:scale-100'
}`}
/>
</div>
+4 -2
View File
@@ -89,14 +89,16 @@ function ComboboxContent({
align = 'start',
alignOffset = 0,
anchor,
container,
...props
}: ComboboxPrimitive.Popup.Props &
Pick<
ComboboxPrimitive.Positioner.Props,
'side' | 'align' | 'sideOffset' | 'alignOffset' | 'anchor'
>) {
> &
Pick<ComboboxPrimitive.Portal.Props, 'container'>) {
return (
<ComboboxPrimitive.Portal>
<ComboboxPrimitive.Portal container={container}>
<ComboboxPrimitive.Positioner
side={side}
sideOffset={sideOffset}
+9 -2
View File
@@ -6,8 +6,11 @@ import { cn } from '@/ui/lib/utils'
function ScrollArea({
className,
children,
viewportProps,
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root> & {
viewportProps?: React.ComponentProps<typeof ScrollAreaPrimitive.Viewport>
}) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
@@ -15,8 +18,12 @@ function ScrollArea({
{...props}
>
<ScrollAreaPrimitive.Viewport
{...viewportProps}
data-slot="scroll-area-viewport"
className="size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
className={cn(
'size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1',
viewportProps?.className,
)}
>
{children}
</ScrollAreaPrimitive.Viewport>
+10 -1
View File
@@ -6,9 +6,17 @@ import type React from 'react'
export interface MediaController {
play: () => void
pause: () => void
seekTo: (second: number) => void
seekTo: (second: number, options?: { exact?: boolean }) => void
getCurrentTime?: () => number
getDuration?: () => number
subscribeToPlaybackTime?: (listener: (second: number) => void) => (() => void) | undefined
}
export interface TranscriptToggle {
panelId: string
open: boolean
buttonRef: React.RefObject<HTMLButtonElement | null>
onToggle: () => void
}
export interface FileViewerProps {
@@ -23,6 +31,7 @@ export interface FileViewerProps {
/** When false, the viewer hides its download affordances. Defaults to true. */
allowDownload?: boolean
autoPlay?: boolean
transcriptToggle?: TranscriptToggle
children?: React.ReactNode
}
@@ -25,6 +25,7 @@ import {
import ProgressBar from './progress-bar'
import { formatTime, formatTimecode } from './utils'
import type { ControlBarProps, DisplayTranscode } from './video-control-bar'
import { TranscriptToggleButton } from './transcript-toggle-button'
export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
state,
@@ -47,6 +48,7 @@ export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
onMouseEnter,
onMouseLeave,
isLoading: propIsLoading,
transcriptToggle,
}) => {
const isLoading = propIsLoading ?? state.isLoading ?? false
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
@@ -188,6 +190,9 @@ export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
{/* Right Side: Settings (Quality + Speed) & Fullscreen */}
<div className="flex items-center gap-1 shrink-0">
{transcriptToggle && !isAudio && !state.isFullScreen && (
<TranscriptToggleButton {...transcriptToggle} className="p-1" />
)}
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button
@@ -0,0 +1,31 @@
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import { ListVideo } from 'lucide-react'
import type { TranscriptToggle } from '../types'
export function TranscriptToggleButton({
panelId,
open,
buttonRef,
onToggle,
className,
}: TranscriptToggle & { className?: string }) {
return (
<button
ref={buttonRef}
type="button"
aria-label={m.transcript_view()}
aria-expanded={open}
aria-controls={open ? panelId : undefined}
title={m.transcript_view()}
className={cn(
'shrink-0 cursor-pointer rounded transition-colors hover:text-primary focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none',
open && 'text-primary',
className,
)}
onClick={onToggle}
>
<ListVideo className="size-5" aria-hidden="true" />
</button>
)
}
@@ -109,6 +109,136 @@ afterEach(() => {
// --- Tests --------------------------------------------------------------------
describe('useFramePlayer exact timestamp seeking', () => {
it.each([true, false])('keeps the settled timestamp with paused=%s', async (paused) => {
const video = new FakeVideo()
video.paused = paused
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
let exactSeek: Promise<void> | undefined
act(() => {
exactSeek = result.current.seekToTime(0.995, true)
})
await act(async () => {
video.dispatchEvent(new Event('seeked'))
await exactSeek
})
expect(video.currentTime).toBe(0.995)
expect(video.paused).toBe(paused)
expect(result.current.currentFrame).toBe(29)
act(() => {
video.currentTime = 0.996
video.dispatchEvent(new Event('seeked'))
})
expect(video.currentTime).toBeCloseTo(29.5 / 30)
})
it('keeps the latest transcript seek queued behind a frame seek when playback is paused mid-seek', async () => {
const video = new FakeVideo()
video.paused = false
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
const seeks: Promise<void>[] = []
act(() => {
seeks.push(result.current.seekToFrame(18))
seeks.push(result.current.seekToTime(0.005, true))
seeks.push(result.current.seekToTime(0.995, true))
})
expect(video.currentTime).toBeCloseTo(18.5 / 30)
await act(async () => {
video.dispatchEvent(new Event('seeked'))
})
expect(video.currentTime).toBe(0.995)
act(() => video.pause())
await act(async () => {
video.dispatchEvent(new Event('seeked'))
await Promise.all(seeks)
})
expect(video.currentTime).toBe(0.995)
expect(video.paused).toBe(true)
expect(result.current.currentFrame).toBe(29)
})
it('keeps the exact timestamp when the native seek completes after the seek queue times out', async () => {
vi.useFakeTimers()
try {
const video = new FakeVideo()
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
let exactSeek: Promise<void> | undefined
act(() => {
exactSeek = result.current.seekToTime(0.995, true)
})
await act(async () => {
await vi.advanceTimersByTimeAsync(501)
await exactSeek
})
act(() => video.dispatchEvent(new Event('seeked')))
expect(video.currentTime).toBe(0.995)
} finally {
vi.useRealTimers()
}
})
it.each(['controller', 'native'] as const)(
'lets a newer ordinary %s seek supersede a timed-out exact seek',
async (source) => {
vi.useFakeTimers()
try {
const video = new FakeVideo()
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
await act(async () => {
const exactSeek = result.current.seekToTime(0.995, true)
await vi.advanceTimersByTimeAsync(501)
await exactSeek
})
act(() => {
if (source === 'controller') {
void result.current.seekToTime(0.995)
} else {
video.currentTime = 0.996
}
video.dispatchEvent(new Event('seeking'))
video.dispatchEvent(new Event('seeked'))
})
expect(video.currentTime).toBeCloseTo(29.5 / 30)
} finally {
vi.useRealTimers()
}
},
)
it('lets a comment seek supersede both the active and queued transcript seeks', async () => {
const video = new FakeVideo()
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
const transcriptSeeks: Promise<void>[] = []
act(() => {
transcriptSeeks.push(result.current.seekToTime(0.5, true))
transcriptSeeks.push(result.current.seekToTime(0.7, true))
void result.current.seekToTime(0.996)
})
expect(video.currentTime).toBe(0.996)
await act(async () => video.dispatchEvent(new Event('seeked')))
expect(video.currentTime).toBeCloseTo(29.5 / 30)
await Promise.all(transcriptSeeks)
expect(result.current.currentFrame).toBe(29)
})
})
describe('useFramePlayer Safari playhead synchronization', () => {
it('does not rewind the playhead on play when currentTime leads the presented frame', () => {
const video = new FakeVideo()
@@ -5,10 +5,22 @@ export interface UseFramePlayerResult {
currentFrame: number
setCurrentFrame: React.Dispatch<React.SetStateAction<number>>
seekToFrame: (targetFrame: number) => Promise<void>
seekToTime: (second: number, exact?: boolean) => Promise<void>
pauseForScrub: () => void
isSeeking: React.RefObject<boolean>
}
interface SeekTarget {
frame: number
exactSecond?: number
}
interface SeekSession {
completion: Promise<void> | null
pending: SeekTarget | null
finishWait: (() => void) | null
}
interface HtmlVideoElementWithCallback {
requestVideoFrameCallback?: (
callback: (now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => void,
@@ -29,9 +41,9 @@ export function useFramePlayer(
): UseFramePlayerResult {
const [currentFrame, setCurrentFrame] = useState<number>(0)
const isSeekingRef = useRef<boolean>(false)
const seekCompletionRef = useRef<Promise<void> | null>(null)
const exactSeekRef = useRef<{ video: HTMLVideoElement; second: number } | null>(null)
const seekSessionRef = useRef<SeekSession | null>(null)
const isPlayingRef = useRef<boolean>(false)
const pendingSeekFrameRef = useRef<number | null>(null)
const scrubPauseRef = useRef(false)
const currentFrameRef = useRef<number>(currentFrame)
currentFrameRef.current = currentFrame
@@ -186,7 +198,9 @@ export function useFramePlayer(
// Snap the playhead to the center of the paused frame to align browser compositor
// Skip snapping if the video has ended to preserve the native ended state and allow native replay
if (!video.ended && !scrubPause) {
const exactSeekPending =
exactSeekRef.current?.video === video && (isSeekingRef.current || video.seeking)
if (!video.ended && !scrubPause && !exactSeekPending) {
const safeCenterTime = calculateFrameCenterTime(clamped, frameRate)
video.currentTime = safeCenterTime
}
@@ -237,47 +251,50 @@ export function useFramePlayer(
}
}, [videoRef])
const seekToFrame = useCallback(
async (targetFrame: number) => {
const seek = useCallback(
async (target: SeekTarget) => {
const video = videoRef.current
if (!video) return
const roundedFrame = Math.round(targetFrame)
const clampedFrame = Math.max(0, Math.min(roundedFrame, totalFrames - 1))
// If a seek is already active, queue this target and update UI state optimistically
if (seekCompletionRef.current) {
pendingSeekFrameRef.current = clampedFrame
setCurrentFrame(clampedFrame)
return seekCompletionRef.current
const activeSession = seekSessionRef.current
if (activeSession?.completion) {
activeSession.pending = target
setCurrentFrame(target.frame)
return activeSession.completion
}
const session: SeekSession = { completion: null, pending: null, finishWait: null }
seekSessionRef.current = session
isSeekingRef.current = true
setCurrentFrame(clampedFrame) // Optimistic update for active seek
setCurrentFrame(target.frame) // Optimistic update for active seek
const performSeek = async (frameToSeek: number) => {
const safeTargetTime = calculateFrameCenterTime(frameToSeek, frameRate)
const performSeek = async ({ frame, exactSecond }: SeekTarget) => {
exactSeekRef.current = exactSecond === undefined ? null : { video, second: exactSecond }
const wasPlaying = !video.paused
video.currentTime = safeTargetTime
video.currentTime = exactSecond ?? calculateFrameCenterTime(frame, frameRate)
// Wait for native seek to complete (with a 500ms fallback timeout to prevent hanging)
await new Promise<void>((resolve) => {
let timeoutId: ReturnType<typeof setTimeout> | null = null
const onSeeked = () => {
if (timeoutId) clearTimeout(timeoutId)
const finishWait = () => {
clearTimeout(timeoutId)
video.removeEventListener('seeked', onSeeked)
session.finishWait = null
resolve()
}
const onSeeked = () => {
if (!video.seeking) finishWait()
}
const timeoutId = setTimeout(finishWait, 500)
session.finishWait = finishWait
video.addEventListener('seeked', onSeeked)
timeoutId = setTimeout(() => {
video.removeEventListener('seeked', onSeeked)
resolve()
}, 500)
})
if (seekSessionRef.current !== session) return
// Pause only if we started paused and the user hasn't pressed play in the meantime
if (!wasPlaying && !isPlayingRef.current) {
if (exactSecond === undefined && !wasPlaying && !isPlayingRef.current) {
video.pause()
}
@@ -300,25 +317,55 @@ export function useFramePlayer(
const runSeeks = async () => {
try {
// Process the latest queued seek before signaling completion to any caller.
let nextFrame: number | null = clampedFrame
while (nextFrame !== null) {
await performSeek(nextFrame)
nextFrame = pendingSeekFrameRef.current
pendingSeekFrameRef.current = null
let next: SeekTarget | null = target
while (next !== null && seekSessionRef.current === session) {
await performSeek(next)
next = session.pending
session.pending = null
}
} finally {
seekCompletionRef.current = null
pendingSeekFrameRef.current = null
isSeekingRef.current = false
if (seekSessionRef.current === session) {
seekSessionRef.current = null
isSeekingRef.current = false
}
}
}
seekCompletionRef.current = runSeeks()
await seekCompletionRef.current
session.completion = runSeeks()
return session.completion
},
[videoRef, frameRate, totalFrames],
)
const seekToFrame = useCallback(
(targetFrame: number) =>
seek({ frame: Math.max(0, Math.min(Math.round(targetFrame), totalFrames - 1)) }),
[seek, totalFrames],
)
const seekToTime = useCallback(
(second: number, exact = false) => {
if (!exact) {
// Ordinary timestamp seeks take effect immediately, superseding queued frame and transcript seeks.
const previousSession = seekSessionRef.current
seekSessionRef.current = null
isSeekingRef.current = false
previousSession?.finishWait?.()
exactSeekRef.current = null
const video = videoRef.current
if (video) video.currentTime = second
return Promise.resolve()
}
const frame = Math.floor(second * frameRate + 0.45)
return seek({
frame: Math.max(0, Math.min(frame, totalFrames - 1)),
exactSecond: second,
})
},
[seek, videoRef, frameRate, totalFrames],
)
// Keyboard Shortcuts Keydown Listener
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
@@ -353,12 +400,26 @@ export function useFramePlayer(
const video = videoRef.current
if (!video) return
const handleSeeking = () => {
const exactSeek = exactSeekRef.current
// A newer native seek can replace the pending target.
if (exactSeek?.video === video && Math.abs(exactSeek.second - video.currentTime) > 0.000001) {
exactSeekRef.current = null
}
}
const handleExternalSeeked = () => {
// Only sync if this seek was not triggered internally by seekToFrame
if (video.seeking) return
// The queue may have timed out while the browser was still seeking.
const preserveTime = exactSeekRef.current?.video === video
if (preserveTime) exactSeekRef.current = null
// The queue updates its own seeks when they settle.
if (!isSeekingRef.current) {
const actualFrame = Math.floor(video.currentTime * frameRate + 0.45)
const finalFrame = Math.max(0, Math.min(actualFrame, totalFrames - 1))
setCurrentFrame(finalFrame)
if (preserveTime) return
// Nudge to safe frame center to guarantee correct browser decoding
const safeCenterTime = calculateFrameCenterTime(finalFrame, frameRate)
@@ -369,8 +430,10 @@ export function useFramePlayer(
}
}
video.addEventListener('seeking', handleSeeking)
video.addEventListener('seeked', handleExternalSeeked)
return () => {
video.removeEventListener('seeking', handleSeeking)
video.removeEventListener('seeked', handleExternalSeeked)
}
}, [videoRef.current, frameRate, totalFrames])
@@ -379,6 +442,7 @@ export function useFramePlayer(
currentFrame,
setCurrentFrame,
seekToFrame,
seekToTime,
pauseForScrub,
isSeeking: isSeekingRef,
}
@@ -30,6 +30,8 @@ import { Slider } from '../../ui/slider'
import ProgressBar, { type SeekbarScrubHandlers } from './progress-bar'
import { formatTime, formatTimecode } from './utils'
import { getVideoResolutionLabel } from '@/ui/lib/media'
import type { TranscriptToggle } from '../types'
import { TranscriptToggleButton } from './transcript-toggle-button'
export interface PlayerState {
isPlaying: boolean
@@ -96,6 +98,7 @@ export interface ControlBarProps {
/** When false, hides the download affordance. Defaults to true. */
allowDownload?: boolean
isLoading?: boolean
transcriptToggle?: TranscriptToggle
}
export const VideoControlBar: React.FC<ControlBarProps> = ({
@@ -125,6 +128,7 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
onMouseLeave,
allowDownload = true,
isLoading: propIsLoading,
transcriptToggle,
}) => {
const isLoading = propIsLoading ?? state.isLoading ?? false
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
@@ -423,6 +427,10 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
</DropdownMenu>
)}
{transcriptToggle && !isAudio && !state.isFullScreen && (
<TranscriptToggleButton {...transcriptToggle} />
)}
{/* Download */}
{allowDownload &&
(isAudio ? (
@@ -32,11 +32,14 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
children,
allowDownload,
autoPlay,
transcriptToggle,
},
ref,
) => {
const hlsRef = useRef<Hls | null>(null)
const videoRef = useRef<HTMLVideoElement | null>(null)
const refreshPlaybackTime = useRef<() => void>(undefined)
const scrubTime = useRef<number | null>(null)
const [activeAutoResolution, setActiveAutoResolution] = useState<string | undefined>(undefined)
const [isHlsManualSupported, setIsHlsManualSupported] = useState<boolean>(true)
const isHls = Boolean(data.media?.isHls && data.media.hls?.url)
@@ -123,15 +126,13 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
pause: () => {
videoRef.current?.pause()
},
seekTo: (second: number) => {
seekTo: (second, options) => {
if (pendingResolutionCorrectionRef.current) {
pendingResolutionCorrectionRef.current()
pendingResolutionCorrectionRef.current = null
}
setHasStartedPlaying(true)
if (videoRef.current) {
videoRef.current.currentTime = second
}
void seekToTime(second, options?.exact)
},
getCurrentTime: () => {
return (videoRef.current ? videoRef.current.currentTime : 0) ?? 0
@@ -139,6 +140,20 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
getDuration: () => {
return (videoRef.current ? videoRef.current.duration : 0) ?? 0
},
subscribeToPlaybackTime: (listener) => {
const video = videoRef.current
if (!video) return
const update = () => listener(scrubTime.current ?? video.currentTime)
const events = ['timeupdate', 'seeking', 'seeked', 'loadedmetadata', 'ended']
refreshPlaybackTime.current = update
for (const event of events) video.addEventListener(event, update)
update()
return () => {
if (refreshPlaybackTime.current === update) refreshPlaybackTime.current = undefined
for (const event of events) video.removeEventListener(event, update)
}
},
}))
const isOverControlsRef = useRef(false)
@@ -271,7 +286,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
const isAudio = data.proxyType === 'audio'
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
const { currentFrame, seekToFrame, pauseForScrub } = useFramePlayer(
const { currentFrame, seekToFrame, seekToTime, pauseForScrub } = useFramePlayer(
videoRef,
frameRate,
totalFrames,
@@ -303,6 +318,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
const displayFrame = scrubFrame ?? currentFrame
const isScrubbing = scrubFrame !== null
const currentTime = displayFrame / frameRate
scrubTime.current = isScrubbing ? currentTime : null
const duration = totalFrames / frameRate
const progress = duration > 0 ? (currentTime / duration) * 100 : 0
@@ -323,6 +339,10 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
}
}, [currentFrame, frameRate, onTimeUpdate])
useEffect(() => {
refreshPlaybackTime.current?.()
}, [currentFrame, scrubFrame, frameRate])
// Initialize player (Hls.js or native HTML5 video)
useEffect(() => {
const video = videoRef.current
@@ -1159,6 +1179,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
onMouseLeave={handleControlsMouseLeave}
allowDownload={allowDownload}
isLoading={isLoading}
transcriptToggle={transcriptToggle}
/>
) : (
<VideoControlBar
@@ -1187,6 +1208,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
onMouseLeave={handleControlsMouseLeave}
allowDownload={allowDownload}
isLoading={isLoading}
transcriptToggle={transcriptToggle}
/>
)}
</div>
+2 -17
View File
@@ -1,5 +1,4 @@
import { useQuery } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { useServerFeatures } from './use-server-features'
export interface ArchiveConfig {
archiveStorageEnabled: boolean
@@ -7,21 +6,7 @@ export interface ArchiveConfig {
}
export function useArchiveConfig(): ArchiveConfig {
const { data, isLoading } = useQuery({
queryKey: ['signup-info'],
queryFn: async () => {
const res = await client.api['signup-info'].$get()
if (!res.ok) {
return { initialized: true, demoMode: false, archiveStorageEnabled: false }
}
return (await res.json()) as {
initialized?: boolean
demoMode?: boolean
archiveStorageEnabled?: boolean
}
},
staleTime: 5 * 60 * 1000,
})
const { data, isLoading } = useServerFeatures()
return {
archiveStorageEnabled: Boolean(data?.archiveStorageEnabled),
@@ -0,0 +1,14 @@
import { useQuery } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
export function useServerFeatures() {
return useQuery({
queryKey: ['signup-info'],
queryFn: async () => {
const res = await client.api['signup-info'].$get()
if (!res.ok) return null
return await res.json()
},
staleTime: 5 * 60 * 1000,
})
}
@@ -0,0 +1,55 @@
import { client } from '@/ui/api/client'
import type { AssetInfo } from '@shumai/dtos'
import { skipToken, useQuery } from '@tanstack/react-query'
import { useCallback, useId, useRef, useState } from 'react'
export const savedTranscriptLanguagesKey = (assetId?: string) =>
['files', assetId, 'transcripts'] as const
export const savedTranscriptKey = (assetId: string, language: string) =>
[...savedTranscriptLanguagesKey(assetId), language] as const
export function useVideoTranscript(file?: Pick<AssetInfo, 'id' | 'proxyType' | 'versionStack'>) {
const assetId =
file?.proxyType === 'video'
? (file.versionStack?.versions.find(({ current }) => current)?.id ?? file.id)
: undefined
const panelId = useId()
const buttonRef = useRef<HTMLButtonElement>(null)
const [selection, setSelection] = useState({ assetId, open: false })
if (selection.assetId !== assetId) {
setSelection({ assetId, open: false })
}
const { data } = useQuery({
queryKey: savedTranscriptLanguagesKey(assetId),
queryFn: assetId
? async ({ signal }) => {
const response = await client.api.files[':fileId'].transcripts.$get(
{ param: { fileId: assetId } },
{ init: { signal } },
)
if (!response.ok) throw new Error('Could not fetch saved transcript languages')
return await response.json()
}
: skipToken,
})
const close = useCallback(() => {
setSelection({ assetId, open: false })
buttonRef.current?.focus({ preventScroll: true })
}, [assetId])
if (!assetId || !data?.languages.length) return undefined
const open = selection.assetId === assetId && selection.open
return {
panel: open ? { id: panelId, assetId, languages: data.languages, onClose: close } : undefined,
toggle: {
panelId,
open,
buttonRef,
onToggle: open ? close : () => setSelection({ assetId, open: true }),
},
}
}
+28 -1
View File
@@ -1810,5 +1810,32 @@
"internal_comment_tooltip": "Internal comment — hidden from public share links",
"internal_reply_locked_tooltip": "Replies to internal comments are always internal",
"remove_timestamp": "Remove timestamp",
"failed_to_update_comment": "Failed to update comment"
"failed_to_update_comment": "Failed to update comment",
"generate_transcripts": "Generate Transcripts",
"transcript_language_auto": "Auto",
"transcript_queued": "Transcript generation queued.",
"transcript_generating": "Generating transcript…",
"transcript_completed": "Transcript generated.",
"transcript_no_speech": "No speech detected.",
"transcript_no_audio": "This video has no audio track.",
"transcript_proxy_required": "A full video proxy must be ready before you can generate transcripts.",
"transcript_audio_too_large": "The audio exceeds the embedding server’s upload limit.",
"transcript_failed": "Transcript generation failed.",
"transcript_submit_failed": "Could not start transcript generation.",
"transcript_already_exists": "A transcript already exists for this language.",
"transcript_languages_unavailable": "Could not load transcription languages.",
"transcript_no_languages_found": "No matching languages.",
"transcript_status_unavailable": "Could not check transcript status.",
"transcript_title": "Transcript",
"transcript_view": "Show transcript",
"transcript_close": "Close transcript",
"transcript_resize": "Resize transcript",
"transcript_search": "Search transcript",
"transcript_search_count": "{current} / {total}",
"transcript_previous_match": "Previous match",
"transcript_next_match": "Next match",
"transcript_sync_to_playback": "Sync to playback",
"transcript_load_failed": "Could not load this transcript.",
"transcript_edit_segment": "Edit segment text",
"transcript_save_failed": "Could not save this segment."
}
+28 -1
View File
@@ -1740,5 +1740,32 @@
"internal_comment_tooltip": "내부 댓글 — 공개 공유 링크에는 표시되지 않음",
"internal_reply_locked_tooltip": "내부 댓글에 대한 답글은 항상 내부 댓글로 작성됩니다",
"remove_timestamp": "타임스탬프 제거",
"failed_to_update_comment": "댓글을 수정하지 못했습니다"
"failed_to_update_comment": "댓글을 수정하지 못했습니다",
"generate_transcripts": "전사 생성",
"transcript_language_auto": "자동 감지",
"transcript_queued": "전사 작업이 대기열에 추가되었습니다.",
"transcript_generating": "전사를 생성하는 중…",
"transcript_completed": "전사를 생성했습니다.",
"transcript_no_speech": "음성이 감지되지 않았습니다.",
"transcript_no_audio": "이 동영상에는 오디오 트랙이 없습니다.",
"transcript_proxy_required": "전체 동영상 프록시 준비가 완료되면 전사를 생성할 수 있습니다.",
"transcript_audio_too_large": "오디오가 임베딩 서버의 업로드 한도를 초과합니다.",
"transcript_failed": "전사 생성에 실패했습니다.",
"transcript_submit_failed": "전사 생성을 시작할 수 없습니다.",
"transcript_already_exists": "이 언어의 전사가 이미 있습니다.",
"transcript_languages_unavailable": "전사 언어를 불러올 수 없습니다.",
"transcript_no_languages_found": "일치하는 언어가 없습니다.",
"transcript_status_unavailable": "전사 상태를 확인할 수 없습니다.",
"transcript_title": "전사",
"transcript_view": "전사 보기",
"transcript_close": "전사 닫기",
"transcript_resize": "전사 패널 크기 조정",
"transcript_search": "전사 검색",
"transcript_search_count": "{current} / {total}",
"transcript_previous_match": "이전 검색 결과",
"transcript_next_match": "다음 검색 결과",
"transcript_sync_to_playback": "재생 위치에 맞추기",
"transcript_load_failed": "이 전사를 불러올 수 없습니다.",
"transcript_edit_segment": "구간 텍스트 편집",
"transcript_save_failed": "이 구간을 저장할 수 없습니다."
}
+28 -1
View File
@@ -1810,5 +1810,32 @@
"internal_comment_tooltip": "内部评论 — 不会在公开分享链接中显示",
"internal_reply_locked_tooltip": "回复内部评论时只能发送内部评论",
"remove_timestamp": "移除时间戳",
"failed_to_update_comment": "更新评论失败"
"failed_to_update_comment": "更新评论失败",
"generate_transcripts": "生成转录",
"transcript_language_auto": "自动检测",
"transcript_queued": "转录任务已加入队列。",
"transcript_generating": "正在生成转录…",
"transcript_completed": "转录已生成。",
"transcript_no_speech": "未检测到语音。",
"transcript_no_audio": "此视频没有音轨。",
"transcript_proxy_required": "视频代理转码完成后才能生成转录。",
"transcript_audio_too_large": "音频超出嵌入服务器的上传大小限制。",
"transcript_failed": "转录生成失败。",
"transcript_submit_failed": "无法启动转录生成。",
"transcript_already_exists": "此语言的转录已存在。",
"transcript_languages_unavailable": "无法加载转录语言。",
"transcript_no_languages_found": "没有匹配的语言。",
"transcript_status_unavailable": "无法获取转录状态。",
"transcript_title": "转录",
"transcript_view": "显示转录",
"transcript_close": "关闭转录",
"transcript_resize": "调整转录面板宽度",
"transcript_search": "搜索转录",
"transcript_search_count": "{current} / {total}",
"transcript_previous_match": "上一个结果",
"transcript_next_match": "下一个结果",
"transcript_sync_to_playback": "同步到播放位置",
"transcript_load_failed": "无法加载此转录。",
"transcript_edit_segment": "编辑片段文本",
"transcript_save_failed": "无法保存此片段。"
}
@@ -7,6 +7,7 @@ import { FileViewer } from '@/ui/components/file-viewer'
import { FileViewerLeftSidebar } from '@/ui/components/file-viewer-left-sidebar'
import { FileViewerRightSidebar } from '@/ui/components/file-viewer-right-sidebar'
import { MobileFileDetail } from '@/ui/components/file-viewer/mobile-file-detail'
import { ResizableTranscriptPanel } from '@/ui/components/file-viewer/resizable-transcript-panel'
import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
import { ResizeHandle } from '@/ui/components/resize-handle'
import { ShareLinkCreatedDialog } from '@/ui/components/share-link-created-dialog'
@@ -14,6 +15,7 @@ import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
import { useIsMobile } from '@/ui/hooks/use-mobile'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { useShareLinkActions } from '@/ui/hooks/use-share-link-actions'
import { useVideoTranscript } from '@/ui/hooks/use-video-transcript'
import { m } from '@/ui/paraglide/messages.js'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import { useChatbotStore } from '@/ui/stores/chatbot'
@@ -81,6 +83,7 @@ function FileViewPage() {
} = useShareLinkActions({ projectId, enabled: canEdit })
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const [transcriptWidthPercent, setTranscriptWidthPercent] = useState(30)
const [annotations, setAnnotations] = useState<Annotation[]>([])
const { fileViewRightSidebarCollapsed } = useUiStore()
const { isChatbotOpen } = useChatbotStore()
@@ -211,6 +214,9 @@ function FileViewPage() {
const isError = isStackError || (!!versionAssetId && isVersionError)
const isFetching = isStackFetching || (!!versionAssetId && isVersionFetching)
const fileData = versionData || stackData
const transcript = useVideoTranscript(
!isMobile && !isCompareMode && fileData?.id === activeFileId ? fileData : undefined,
)
const versionsDataList = versionAssetId ? versionsList : stackData?.versionStack?.versions
const parentFolderId = fileData?.ancestorFolders?.[0]?.id ?? projectInfo?.rootFolder ?? ''
@@ -817,7 +823,7 @@ function FileViewPage() {
return (
<div className="h-full flex flex-1 flex-col bg-background">
<div className="h-full flex flex-1 overflow-hidden">
<div className="flex-1 relative">
<div className="relative min-w-0 flex-1">
{isFetching && !isCompareMode && (
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/50">
<Loader2 className="h-8 w-8 animate-spin text-foreground" />
@@ -851,15 +857,28 @@ function FileViewPage() {
onSeek={handleSeek}
annotations={annotations}
startTime={startTime}
transcriptToggle={transcript?.toggle}
>
<FileViewerLeftSidebar
projectId={projectId}
currentAssetId={activeFileId}
parentFolderId={parentFolderId}
initialFiles={carouselState.files}
initialNextCursor={carouselState.nextCursor}
isLoading={isCarouselLoading}
/>
{transcript?.panel && (
<ResizableTranscriptPanel
key={transcript.panel.assetId}
{...transcript.panel}
canEdit={canEdit}
mediaControllerRef={mediaControllerRef}
widthPercent={transcriptWidthPercent}
setWidthPercent={setTranscriptWidthPercent}
/>
)}
<div className={transcript?.panel ? 'hidden' : 'contents'}>
<FileViewerLeftSidebar
projectId={projectId}
currentAssetId={activeFileId}
parentFolderId={parentFolderId}
initialFiles={carouselState.files}
initialNextCursor={carouselState.nextCursor}
isLoading={isCarouselLoading}
/>
</div>
</FileViewer>
)}
</div>
@@ -0,0 +1,57 @@
import { s3Service } from '@shumai/core/src/s3/s3'
import * as fs from 'node:fs'
import * as path from 'node:path'
import { ApplicationFailure } from '../workflow-utils'
export function getErrorDetails(err: unknown): { code?: string; message: string; name?: string } {
if (err && typeof err === 'object') {
const record = err as Record<string, unknown>
return {
code: typeof record.code === 'string' ? record.code : undefined,
message:
typeof record.message === 'string'
? record.message
: err instanceof Error
? err.message
: String(err),
name: typeof record.name === 'string' ? record.name : undefined,
}
}
return {
message: String(err),
}
}
export async function ensureLocalMediaFile(assetKey: string, filePath: string): Promise<string> {
if (fs.existsSync(filePath)) {
return filePath
}
const dir = path.dirname(filePath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
const bucket = process.env.S3_BUCKET || 'shumai'
try {
await s3Service.downloadToFile(bucket, assetKey, filePath)
} catch (err) {
const { code, message, name } = getErrorDetails(err)
const lowerMsg = message.toLowerCase()
const lowerCode = (code || '').toLowerCase()
const lowerName = (name || '').toLowerCase()
if (
lowerCode === 'enoent' ||
lowerCode === 'nosuchkey' ||
lowerName === 'nosuchkey' ||
lowerMsg.includes('enoent') ||
lowerMsg.includes('nosuchkey')
) {
throw ApplicationFailure.create({
message: `Failed to download media to local file: ${message}`,
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
})
}
throw err
}
return filePath
}
@@ -57,6 +57,7 @@ export function getDbosDatabaseUrl(rawUrl?: string): string {
export function getQueueForTaskType(type: string | null | undefined): string {
switch (type) {
case WorkflowTaskType.ai_embedding:
case WorkflowTaskType.ai_transcription:
case WorkflowTaskType.ai_metadata_autofill:
case WorkflowTaskType.chat:
return TaskQueueAgent
+1
View File
@@ -2,4 +2,5 @@ export * from './dbos-executor'
export * from './workflow-utils'
export * from './workflow'
export * from './activities/task'
export * from './activities/media'
export * from './local-task-storage'