From 72a7f68c92cf901584b2f89405d5beadbb4dab85 Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Fri, 4 Dec 2026 15:37:58 +0800 Subject: [PATCH] fix(video): transcribe archived videos and show progress (#560) --- apps/web/e2e/README.md | 2 +- .../project/generate-transcripts.spec.ts | 78 +++++++++++---- .../agent/src/activities/transcription.ts | 8 +- packages/api/src/transcript.test.ts | 24 +++++ packages/api/src/transcript.ts | 10 ++ .../core/src/transcript/transcript.test.ts | 81 +++++++++++++++- packages/core/src/transcript/transcript.ts | 17 +++- packages/dtos/src/transcript.ts | 7 ++ .../e2e/workflow/transcribe-video.test.ts | 58 +++++++++-- .../file-browser/context-menu.test.tsx | 26 +++-- .../components/file-browser/context-menu.tsx | 33 +++---- .../components/file-browser/file-browser.tsx | 16 +++- .../components/file-browser/file-card.tsx | 12 ++- .../file-browser/file-list-item.tsx | 9 +- .../generate-transcripts-dialog.tsx | 95 +++---------------- .../file-browser/mobile-file-browser.tsx | 11 +++ .../webui/hooks/use-transcription-jobs.ts | 48 ++++++++++ packages/webui/lib/transcript.ts | 20 ++++ packages/webui/messages/en.json | 8 +- packages/webui/messages/ko.json | 8 +- packages/webui/messages/zh.json | 8 +- 21 files changed, 408 insertions(+), 171 deletions(-) create mode 100644 packages/webui/hooks/use-transcription-jobs.ts create mode 100644 packages/webui/lib/transcript.ts diff --git a/apps/web/e2e/README.md b/apps/web/e2e/README.md index 9fc9fa38..9b0b64c2 100644 --- a/apps/web/e2e/README.md +++ b/apps/web/e2e/README.md @@ -76,7 +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 generates a transcript from an archived video's context menu, sees progress in card and list metadata across a refresh, and reuses the project status across folders | `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` | diff --git a/apps/web/e2e/tests/project/generate-transcripts.spec.ts b/apps/web/e2e/tests/project/generate-transcripts.spec.ts index 1da87799..9b40e3d7 100644 --- a/apps/web/e2e/tests/project/generate-transcripts.spec.ts +++ b/apps/web/e2e/tests/project/generate-transcripts.spec.ts @@ -1,17 +1,28 @@ import { expect, test } from '../../fixtures' +import { seedFolder } from '../../helpers/assets' 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 ({ +test('starts a transcript for an archived video and tracks it in the file metadata', async ({ file, prisma, }) => { - const { page, projectId, fileId, fileName } = file - let status: TranscriptJobStatus = { taskId: 'previous-transcript', status: 'completed' } + const { page, projectId, rootFolderId, fileId, fileName } = file + const projectPath = `/projects/${projectId}` + const statusPath = `/api${projectPath}/transcription-status` + const folder = await seedFolder(prisma, projectId, rootFolderId, 'Other folder') const expectedLanguages = ['zh', 'en'] let submissions = 0 + let rejectSubmission = true + let statusRequests = 0 + page.on('request', (request) => { + if (new URL(request.url()).pathname === statusPath) { + expect(request.method()).toBe('GET') + expect(request.postData()).toBeNull() + statusRequests++ + } + }) await page.route('**/api/signup-info', async (route) => { const response = await route.fetch() await route.fulfill({ json: { ...(await response.json()), transcriptionEnabled: true } }) @@ -27,14 +38,18 @@ test('selects a transcription language from the video context menu and tracks th }, }), ) - 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 } }) + if (rejectSubmission) { + rejectSubmission = false + await route.fulfill({ status: 503 }) + return + } + const task = await prisma.workflowTask.create({ + data: { projectId, assetId: fileId, type: 'ai_transcription', status: 'processing' }, + }) + submissions++ + await route.fulfill({ status: 202, json: { kind: 'queued', taskId: task.id } }) }) await expect @@ -48,14 +63,21 @@ test('selects a transcription language from the video context menu and tracks th await prisma.asset.update({ where: { id: fileId }, data: { status: 'processing' } }) const [signupInfo] = await Promise.all([ page.waitForResponse('**/api/signup-info'), - page.goto(`/projects/${projectId}`), + page.goto(projectPath), ]) 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() + await prisma.asset.update({ where: { id: fileId }, data: { status: 'archived' } }) + const [idleStatus] = await Promise.all([page.waitForResponse(`**${statusPath}`), page.reload()]) + expect(await idleStatus.json()).toEqual({ assetIds: [] }) + const idleRequests = statusRequests + await fileCard(page, folder.name).dblclick() + await expect(page).toHaveURL(`${projectPath}/folders/${folder.id}`) + await page.goBack() + await expect(fileCard(page, fileName)).toBeVisible() + expect(statusRequests).toBe(idleRequests) const openDialog = async () => { await fileCard(page, fileName).click({ button: 'right' }) await action.click() @@ -64,24 +86,40 @@ test('selects a transcription language from the video context menu and tracks th 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.') + const metadata = fileCard(page, fileName).getByTestId('file-card-metadata') 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.getByRole('alert')).toBeVisible() + await expect(language).toHaveValue('Chinese') + await generate.click() await expect(dialog).toBeHidden() - status = { taskId: status.taskId, status: 'completed' } + await expect(metadata).toHaveText('Transcribing…') + + await page.reload() + await expect(metadata).toHaveText('Transcribing…') + await page.getByRole('button', { name: 'List View' }).click() + const dateCell = fileCard(page, fileName).getByTestId('file-list-item-date') + await expect(dateCell).toHaveText('Transcribing…') + const activeTranscript = { + assetId: fileId, + type: 'ai_transcription', + status: 'processing', + } as const + await prisma.workflowTask.updateMany({ where: activeTranscript, data: { status: 'completed' } }) + await expect(dateCell).toHaveText(/\d/) + const modifiedDate = await dateCell.innerText() 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() + await expect(dateCell).toHaveText('Transcribing…') + await prisma.workflowTask.updateMany({ where: activeTranscript, data: { status: 'failed' } }) + await expect(dateCell).toHaveText(modifiedDate) + await expect(page.getByText('Transcript generation failed.', { exact: true })).toHaveCount(0) }) diff --git a/packages/agent/src/activities/transcription.ts b/packages/agent/src/activities/transcription.ts index 15747147..fa9360da 100644 --- a/packages/agent/src/activities/transcription.ts +++ b/packages/agent/src/activities/transcription.ts @@ -13,7 +13,11 @@ import { 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 { + selectTranscriptVideoProxyKey, + transcriptionErrors, + transcriptVideoStatuses, +} from '@shumai/dtos' import { ApplicationFailure, defineStep, @@ -66,7 +70,7 @@ export const extractTranscriptAudioActivity = defineStep( where: { id: assetId, type: 'file', - status: 'processed', + status: { in: [...transcriptVideoStatuses] }, isDeleted: false, mediaType: { startsWith: 'video/' }, }, diff --git a/packages/api/src/transcript.test.ts b/packages/api/src/transcript.test.ts index e3f027a9..10870fe4 100644 --- a/packages/api/src/transcript.test.ts +++ b/packages/api/src/transcript.test.ts @@ -29,6 +29,30 @@ describe('Transcript API', () => { expect(await response.json()).toEqual(list) }) + it('requires project edit access to list file IDs with active transcription', async () => { + const request = () => app.request('/projects/project-id/transcription-status') + const permission = vi + .spyOn(authzService, 'hasPermission') + .mockRejectedValue(new HTTPException(403)) + const list = vi.spyOn(transcriptService, 'listActiveAssetIds').mockResolvedValue(['file-id']) + + expect((await request()).status).toBe(403) + expect(list).not.toHaveBeenCalled() + + permission.mockResolvedValue(undefined) + const response = await request() + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ assetIds: ['file-id'] }) + expect(permission).toHaveBeenLastCalledWith( + expect.objectContaining({ + type: ResourceType.Project, + permission: Permission.Edit, + id: 'project-id', + }), + ) + expect(list).toHaveBeenCalledWith('project-id') + }) + it('returns saved languages and segments with asset read access', async () => { const permission = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined) const list = vi diff --git a/packages/api/src/transcript.ts b/packages/api/src/transcript.ts index 2868555c..2ff8e841 100644 --- a/packages/api/src/transcript.ts +++ b/packages/api/src/transcript.ts @@ -12,6 +12,16 @@ import { z } from 'zod' const route = new Hono<{ Variables: { user: User } }>() .get('/transcription/languages', async (c) => c.json(await transcriptService.listLanguages())) + .get('/projects/:projectId/transcription-status', async (c) => { + const projectId = c.req.param('projectId') + await authzService.hasPermission({ + user: c.get('user'), + permission: Permission.Edit, + type: ResourceType.Project, + id: projectId, + }) + return c.json({ assetIds: await transcriptService.listActiveAssetIds(projectId) }) + }) .get('/files/:fileId/transcripts', async (c) => { const assetId = c.req.param('fileId') await authzService.hasPermission({ diff --git a/packages/core/src/transcript/transcript.test.ts b/packages/core/src/transcript/transcript.test.ts index ac5002b4..011cddae 100644 --- a/packages/core/src/transcript/transcript.test.ts +++ b/packages/core/src/transcript/transcript.test.ts @@ -1,4 +1,4 @@ -import { prisma, WorkflowTaskType } from '@shumai/db' +import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' import { transcriptionErrors } from '@shumai/dtos' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -177,6 +177,85 @@ describe('TranscriptService', () => { expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0) }) + it.each(['archiving', 'archived', 'restoring'] as const)( + 'queues generation from a full proxy while the video is %s', + async (status) => { + await prisma.asset.update({ where: { id: assetId }, data: { status } }) + await expect(transcriptService.generate(assetId, 'en')).resolves.toMatchObject({ + kind: 'queued', + }) + }, + ) + + it('lists each live project file with a pending or running transcription once', async () => { + const project = await prisma.project.findUniqueOrThrow({ where: { id: projectId } }) + const otherProject = await prisma.project.create({ + data: { name: 'Another project', teamId: project.teamId }, + }) + const [running, finished, deleted, external, transcoding] = await Promise.all( + [ + { projectId, name: 'Running video' }, + { projectId, name: 'Finished video' }, + { projectId, name: 'Deleted video', isDeleted: true }, + { projectId: otherProject.id, name: 'External video' }, + { projectId, name: 'Transcoding video' }, + ].map((file) => + prisma.asset.create({ data: { ...file, type: 'file', status: 'processed' } }), + ), + ) + await expect(transcriptService.listActiveAssetIds(projectId)).resolves.toEqual([]) + + await prisma.workflowTask.createMany({ + data: [ + { assetId, status: WorkflowTaskStatus.pending }, + { assetId, status: WorkflowTaskStatus.processing }, + { assetId, status: WorkflowTaskStatus.failed }, + { assetId: running.id, status: WorkflowTaskStatus.processing }, + { assetId: finished.id, status: WorkflowTaskStatus.completed }, + { assetId: finished.id, status: WorkflowTaskStatus.failed }, + { assetId: deleted.id, status: WorkflowTaskStatus.pending }, + { assetId: external.id, status: WorkflowTaskStatus.processing }, + { + assetId: transcoding.id, + status: WorkflowTaskStatus.pending, + type: WorkflowTaskType.transcode_video, + }, + ].map((job) => ({ type: WorkflowTaskType.ai_transcription, ...job })), + }) + await expect(transcriptService.listActiveAssetIds(projectId)).resolves.toEqual( + [assetId, running.id].sort().reverse(), + ) + await expect(transcriptService.listActiveAssetIds(otherProject.id)).resolves.toEqual([ + external.id, + ]) + }) + + it('rejects an archived video without a full proxy', async () => { + await prisma.asset.update({ + where: { id: assetId }, + data: { status: 'archived', media: { ...media, videoTranscodes: [] } }, + }) + await expect(transcriptService.generate(assetId, 'en')).rejects.toMatchObject({ + status: 400, + message: transcriptionErrors.noProxy, + }) + expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0) + }) + + it.each(['archiving', 'archived', 'restoring'] as const)( + 'saves a transcript when the video has become %s while the job runs', + async (status) => { + const taskId = await generateAndStart('en') + await prisma.asset.update({ where: { id: assetId }, data: { status } }) + await expect( + transcriptService.saveResult({ taskId, assetId, model, language: 'en', segments }), + ).resolves.toBe(true) + await expect(transcriptService.getSavedTranscript(assetId, 'en')).resolves.toMatchObject({ + segments, + }) + }, + ) + 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 }, diff --git a/packages/core/src/transcript/transcript.ts b/packages/core/src/transcript/transcript.ts index 781f8ba9..f318f084 100644 --- a/packages/core/src/transcript/transcript.ts +++ b/packages/core/src/transcript/transcript.ts @@ -9,6 +9,7 @@ import { import { selectTranscriptVideoProxyKey, transcriptionErrors, + transcriptVideoStatuses, type GenerateTranscriptResult, type SavedTranscript, type SavedTranscriptLanguages, @@ -96,7 +97,7 @@ export class TranscriptService { where: { id: assetId, type: 'file', - status: 'processed', + status: { in: [...transcriptVideoStatuses] }, isDeleted: false, mediaType: { startsWith: 'video/' }, }, @@ -173,6 +174,18 @@ export class TranscriptService { } } + async listActiveAssetIds(projectId: string): Promise { + const assets = await prisma.$queryRaw<{ assetId: string }[]>` + SELECT DISTINCT task.asset_id AS "assetId" + FROM workflow_tasks task + JOIN assets asset ON asset.id = task.asset_id + WHERE asset.project_id = ${projectId} AND NOT asset.is_deleted AND asset.type = 'file' + AND task.type = ${type}::"WorkflowTaskType" AND task.status IN ('pending', 'processing') + ORDER BY task.asset_id DESC + ` + return assets.map(({ assetId }) => assetId) + } + async saveResult(params: { taskId: string assetId: string @@ -184,7 +197,7 @@ export class TranscriptService { 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' + WHERE id = ${assetId} AND NOT is_deleted AND status::text IN (${Prisma.join(transcriptVideoStatuses)}) FOR UPDATE ` if (!asset) return false diff --git a/packages/dtos/src/transcript.ts b/packages/dtos/src/transcript.ts index 752be7cd..81ec1dde 100644 --- a/packages/dtos/src/transcript.ts +++ b/packages/dtos/src/transcript.ts @@ -37,6 +37,13 @@ interface TranscriptVideoProxy { height: number } +// Archive and restore move the original while the full video proxy stays available. +export const transcriptVideoStatuses = ['processed', 'archiving', 'archived', 'restoring'] as const + +export function isTranscriptVideoReady(status: string) { + return transcriptVideoStatuses.some((readyStatus) => readyStatus === status) +} + export function selectTranscriptVideoProxyKey( media?: { videoTranscodes?: TranscriptVideoProxy[]; videoPreview?: { key?: string } } | null, ): string | undefined { diff --git a/packages/e2e/workflow/transcribe-video.test.ts b/packages/e2e/workflow/transcribe-video.test.ts index a48a31ff..08ffb55e 100644 --- a/packages/e2e/workflow/transcribe-video.test.ts +++ b/packages/e2e/workflow/transcribe-video.test.ts @@ -4,12 +4,18 @@ import { tmpdir } from 'node:os' import { basename, join } from 'node:path' import { promisify } from 'node:util' import { initAgentWorkflows } from '@shumai/agent' +import { assetService } from '@shumai/core/src/asset/asset' +import { + getArchiveStorageService, + resetArchiveStorageServiceForTests, +} from '@shumai/core/src/s3/archive-storage' 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 { initTranscodeWorkflows } from '@shumai/transcode' +import { TaskQueueAgent, TaskQueueArchive, workflowService } from '@shumai/workflow-core' import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' const execFileAsync = promisify(execFile) @@ -110,8 +116,12 @@ describe('Transcribe video workflow', () => { vi.stubEnv('S3_BUCKET', bucket) vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai') vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', `${provider.url}v1/embeddings/`) + vi.stubEnv('ARCHIVE_STORAGE_BACKEND', 'local') + vi.stubEnv('ARCHIVE_LOCAL_ROOT', join(directory, 'archive')) + resetArchiveStorageServiceForTests() initAgentWorkflows() - await workflowService.startWorkers(TaskQueueAgent) + initTranscodeWorkflows() + await workflowService.startWorkers([TaskQueueAgent, TaskQueueArchive]) }) beforeEach(() => { @@ -126,10 +136,11 @@ describe('Transcribe video workflow', () => { await provider?.stop(true) await s3Service.deletePrefix(bucket, '') if (directory) await rm(directory, { recursive: true, force: true }) + resetArchiveStorageServiceForTests() vi.unstubAllEnvs() }) - async function submitVideo(name: string, language: string | null) { + async function createVideo(name: string, originalKey = 'video/unavailable-original.mkv') { 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 } @@ -138,14 +149,14 @@ describe('Transcribe video workflow', () => { s3Service.uploadFileToKey(join(directory, basename(key)), key, 'video/mp4'), ), ) - const asset = await prisma.asset.create({ + return 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' } }, + storageKey: { create: { key: originalKey } }, media: { proxyType: 'video', videoTranscodes: [largerProxy, preview, fullProxy], @@ -160,14 +171,47 @@ describe('Transcribe video workflow', () => { }, }, }) - const result = await transcriptService.generate(asset.id, language) + } + + async function startTranscript(assetId: string, language: string | null) { + const result = await transcriptService.generate(assetId, language) if (result.kind !== 'queued') throw new Error(`Unexpected generation result ${result.kind}`) return { - assetId: asset.id, + assetId, task: await prisma.workflowTask.findUniqueOrThrow({ where: { id: result.taskId } }), } } + async function submitVideo(name: string, language: string | null) { + const asset = await createVideo(name) + return await startTranscript(asset.id, language) + } + + it('generates and saves a transcript after the archive workflow moves the original', async () => { + const originalKey = 'video/archive-original.mkv' + await s3Service.uploadFileToKey(join(directory, 'audio.mkv'), originalKey, 'video/x-matroska') + const asset = await createVideo('audio.mp4', originalKey) + const { taskIds } = await assetService.archiveAssets([asset.id]) + expect(taskIds).toHaveLength(1) + const archiveTask = await prisma.workflowTask.findUniqueOrThrow({ where: { id: taskIds[0] } }) + await workflowService.executeWait(archiveTask, 20_000) + await expect(prisma.asset.findUnique({ where: { id: asset.id } })).resolves.toMatchObject({ + status: 'archived', + }) + await expect(s3Service.headObject(bucket, originalKey)).rejects.toThrow('NoSuchKey') + await expect(getArchiveStorageService().headObject(originalKey)).resolves.toMatchObject({ + size: expect.any(Number), + }) + + const { task } = await startTranscript(asset.id, 'en') + await workflowService.executeWait(task, 20_000) + + expect(uploads).toHaveLength(1) + await expect(transcriptService.getSavedTranscript(asset.id, 'en')).resolves.toMatchObject({ + segments: [{ startMs: 1012, endMs: 1875, text: 'Hello' }], + }) + }, 45_000) + 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) diff --git a/packages/webui/components/file-browser/context-menu.test.tsx b/packages/webui/components/file-browser/context-menu.test.tsx index bb318990..d68464c4 100644 --- a/packages/webui/components/file-browser/context-menu.test.tsx +++ b/packages/webui/components/file-browser/context-menu.test.tsx @@ -96,7 +96,7 @@ describe('FileBrowserContextMenu', () => { expect(screen.queryByRole('menuitem', { name: 'Open in new tab' })).toBeNull() }) - it('starts transcription on the displayed video file in a stack', () => { + it('starts transcription on the displayed archived video in a stack', () => { const onGenerateTranscripts = vi.fn() renderWithMenu( { @@ -107,7 +107,7 @@ describe('FileBrowserContextMenu', () => { id: stackItem.id, versions: [ { id: 'old', name: 'old.mp4', version: 1, current: false }, - { id: 'current', name: 'current.mp4', version: 2, current: true }, + { id: 'current', name: 'current.mp4', version: 2, current: true, status: 'archived' }, ], }, }, @@ -120,10 +120,27 @@ describe('FileBrowserContextMenu', () => { expect(onGenerateTranscripts).toHaveBeenCalledWith('current', 'current.mp4') }) + it.each(['archiving', 'archived', 'restoring'])( + 'starts transcription on a video that is %s', + (status) => { + const onGenerateTranscripts = vi.fn() + renderWithMenu( + { ...fileItem, proxyType: 'video', status, media: { videoTranscodes: [fullProxy] } }, + { onGenerateTranscripts }, + ) + + fireEvent.contextMenu(screen.getByTestId('context-trigger')) + fireEvent.click(screen.getByRole('menuitem', { name: 'Generate Transcripts' })) + + expect(onGenerateTranscripts).toHaveBeenCalledWith(fileItem.id, fileItem.name) + }, + ) + it.each([ { status: 'uploaded', media: undefined }, { status: 'processing', media: { videoTranscodes: [fullProxy] } }, { status: 'processed', media: { videoPreview: { url: '/preview.mp4', key: 'preview.mp4' } } }, + { status: 'archived', media: undefined }, ])('disables generation for a $status video until a full proxy is ready', ({ status, media }) => { const onGenerateTranscripts = vi.fn() renderWithMenu( @@ -150,11 +167,6 @@ describe('FileBrowserContextMenu', () => { 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')) diff --git a/packages/webui/components/file-browser/context-menu.tsx b/packages/webui/components/file-browser/context-menu.tsx index 998d4d57..be2c692c 100644 --- a/packages/webui/components/file-browser/context-menu.tsx +++ b/packages/webui/components/file-browser/context-menu.tsx @@ -1,4 +1,10 @@ -import { selectTranscriptVideoProxyKey, type AssetInfo, type ShareLinkInfo } from '@shumai/dtos' +import { + isTranscriptVideoReady, + selectTranscriptVideoProxyKey, + type AssetInfo, + type ShareLinkInfo, +} from '@shumai/dtos' +import { getTranscriptVideo } from '@/ui/lib/transcript' import { m } from '@/ui/paraglide/messages.js' import { ContextMenuContent, @@ -239,17 +245,8 @@ export function FileBrowserContextMenu({ ) - 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 transcriptVideo = getTranscriptVideo(item) + const transcriptReady = transcriptVideo && isTranscriptVideoReady(transcriptVideo.status) const contextMenuContent = isItemSelected && selectedIds.size > 1 ? ( @@ -376,14 +373,12 @@ export function FileBrowserContextMenu({ {findSimilarItem} {canEdit && onGenerateTranscripts && - transcriptAssetId && - ['uploading', 'uploaded', 'processing', 'processed'].includes(transcriptAssetStatus) && - isTranscriptVideo && ( + transcriptVideo && + (transcriptReady || + ['uploading', 'uploaded', 'processing'].includes(transcriptVideo.status)) && ( - onGenerateTranscripts(transcriptAssetId, videoVersion?.name || item.name) - } + disabled={!transcriptReady || !selectTranscriptVideoProxyKey(item.media)} + onSelect={() => onGenerateTranscripts(transcriptVideo.id, transcriptVideo.name)} > {m.generate_transcripts()} diff --git a/packages/webui/components/file-browser/file-browser.tsx b/packages/webui/components/file-browser/file-browser.tsx index a475d13a..f4ccea4b 100644 --- a/packages/webui/components/file-browser/file-browser.tsx +++ b/packages/webui/components/file-browser/file-browser.tsx @@ -7,6 +7,8 @@ import { usePermissions } from '@/ui/hooks/use-permissions' import { useShareLinkActions } from '@/ui/hooks/use-share-link-actions' import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils' import { formatSize } from '@/ui/lib/format' +import { getTranscriptVideo } from '@/ui/lib/transcript' +import { useTranscriptionJobs } from '@/ui/hooks/use-transcription-jobs' import { useFieldStore } from '@/ui/stores/fields' import { useUploadStore } from '@/ui/stores/upload' import { uploadFilesWithUppy } from '@/ui/lib/uploader' @@ -164,7 +166,6 @@ export function FileBrowser({ const [contextMenuItem, setContextMenuItem] = useState(null) const [similarImage, setSimilarImage] = useState(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, @@ -615,6 +616,8 @@ export function FileBrowser({ const [targetVersionFileId, setTargetVersionFileId] = useState(null) const fileContextMenu = useRef(false) const { canEdit, canAdmin } = usePermissions(projectId) + const canGenerateTranscripts = !!transcriptionEnabled && canEdit && !isShareView && !isPublic + const { transcribingAssetIds, trackJob } = useTranscriptionJobs(projectId, canGenerateTranscripts) const scrollContainerRef = useRef(null) @@ -725,6 +728,7 @@ export function FileBrowser({ isPublic, allowDownload, fields: displayedFields, + isTranscribing: transcribingAssetIds.has(getTranscriptVideo(item)?.id ?? ''), canEdit, isTeamOwner: canAdmin, onCopy: handleCopy, @@ -1128,9 +1132,7 @@ export function FileBrowser({ onCopy={handleCopy} onFindSimilar={semanticSearchEnabled && rootFolderId ? setSimilarImage : undefined} onGenerateTranscripts={ - transcriptionEnabled && !isShareView && !isPublic - ? (id, name) => setTranscriptVideo({ id, name }) - : undefined + canGenerateTranscripts ? (id, name) => setTranscriptVideo({ id, name }) : undefined } onNewFolder={handleNewFolder} onUploadFile={handleUploadFilesClick} @@ -1197,7 +1199,11 @@ export function FileBrowser({ key={transcriptVideo.id} assetId={transcriptVideo.id} name={transcriptVideo.name} - onClose={closeTranscriptDialog} + isTranscribing={transcribingAssetIds.has(transcriptVideo.id)} + onJobAccepted={trackJob} + onClose={() => + setTranscriptVideo((current) => (current?.id === transcriptVideo.id ? null : current)) + } /> )} diff --git a/packages/webui/components/file-browser/file-card.tsx b/packages/webui/components/file-browser/file-card.tsx index d924e6d7..59229db3 100644 --- a/packages/webui/components/file-browser/file-card.tsx +++ b/packages/webui/components/file-browser/file-card.tsx @@ -85,6 +85,7 @@ interface FileCardProps { isRecents?: boolean selectedCount?: number fields?: MetadataFieldInfo[] + isTranscribing?: boolean isShareView?: boolean isPublic?: boolean canEdit?: boolean @@ -122,6 +123,7 @@ export function FileCard({ isRecents, selectedCount, fields = [], + isTranscribing = false, isShareView, isPublic = false, canEdit = true, @@ -343,6 +345,8 @@ export function FileCard({ } } else if (isProcessing) { statusText = m.preparing() + } else if (isTranscribing) { + statusText = m.transcript_generating() } const failedErrorMessage = displayItem.media?.error || m.processing_failed() @@ -613,7 +617,11 @@ export function FileCard({ }} > -

+

{statusText ?? creatorText}

@@ -622,7 +630,7 @@ export function FileCard({ side="bottom" className="max-w-md break-all text-wrap [text-wrap:normal] text-left" > - {creatorText} + {isTranscribing ? m.transcript_generating() : creatorText} )} diff --git a/packages/webui/components/file-browser/file-list-item.tsx b/packages/webui/components/file-browser/file-list-item.tsx index 57ba453e..f3ba3190 100644 --- a/packages/webui/components/file-browser/file-list-item.tsx +++ b/packages/webui/components/file-browser/file-list-item.tsx @@ -38,6 +38,7 @@ interface FileListItemProps { dragState?: DragState disabled?: boolean fields: MetadataFieldInfo[] + isTranscribing?: boolean columnSizing?: Record canEdit?: boolean isRecents?: boolean @@ -64,6 +65,7 @@ export function FileListItem({ dragState, disabled, fields, + isTranscribing = false, columnSizing, canEdit = true, isRecents, @@ -395,8 +397,11 @@ export function FileListItem({ }} >
- - {formatDate(displayItem.updatedAt)} + + {isTranscribing ? m.transcript_generating() : formatDate(displayItem.updatedAt)} {!isRecents && ( - diff --git a/packages/webui/components/file-browser/mobile-file-browser.tsx b/packages/webui/components/file-browser/mobile-file-browser.tsx index b0557c96..9d5f3064 100644 --- a/packages/webui/components/file-browser/mobile-file-browser.tsx +++ b/packages/webui/components/file-browser/mobile-file-browser.tsx @@ -2,6 +2,9 @@ import { client } from '@/ui/api/client' import { usePermissions } from '@/ui/hooks/use-permissions' +import { useServerFeatures } from '@/ui/hooks/use-server-features' +import { useTranscriptionJobs } from '@/ui/hooks/use-transcription-jobs' +import { getTranscriptVideo } from '@/ui/lib/transcript' import { m } from '@/ui/paraglide/messages.js' import { useUploadStore } from '@/ui/stores/upload' import { uploadFilesWithUppy } from '@/ui/lib/uploader' @@ -130,6 +133,11 @@ export function MobileFileBrowser({ const queryClient = useQueryClient() useBatchFileStatus({ teamId, items: files }) const { canEdit, canAdmin } = usePermissions(projectId) + const transcriptionEnabled = useServerFeatures().data?.transcriptionEnabled + const { transcribingAssetIds } = useTranscriptionJobs( + projectId, + !!transcriptionEnabled && canEdit && !isShareView && !isPublic, + ) const fileInputRef = useRef(null) const folderInputRef = useRef(null) @@ -573,6 +581,9 @@ export function MobileFileBrowser({ key={file.id} teamId={teamId} item={file} + isTranscribing={transcribingAssetIds.has( + getTranscriptVideo(file)?.id ?? '', + )} isSelected={selectedItem?.id === file.id} isChecked={selectedIds.has(file.id!)} isEditing={editingItemId === file.id} diff --git a/packages/webui/hooks/use-transcription-jobs.ts b/packages/webui/hooks/use-transcription-jobs.ts new file mode 100644 index 00000000..9b9904a2 --- /dev/null +++ b/packages/webui/hooks/use-transcription-jobs.ts @@ -0,0 +1,48 @@ +import { useMemo } from 'react' +import { useQuery, useQueryClient } from '@tanstack/react-query' +import { client } from '@/ui/api/client' +import { m } from '@/ui/paraglide/messages.js' +import { savedTranscriptLanguagesKey } from './use-video-transcript' + +export function useTranscriptionJobs(projectId: string, enabled: boolean) { + const queryClient = useQueryClient() + const queryKey = ['project-transcription-status', projectId] as const + const { data } = useQuery({ + queryKey, + enabled, + // Folder routes can remount the browser. Reuse the project's cached jobs on navigation. + refetchOnMount: false, + queryFn: async ({ signal }) => { + const response = await client.api.projects[':projectId']['transcription-status'].$get( + { param: { projectId } }, + { init: { signal } }, + ) + if (!response.ok) throw new Error(m.transcript_status_unavailable()) + const { assetIds } = await response.json() + signal.throwIfAborted() + + const activeIds = new Set(assetIds) + const previousIds = queryClient.getQueryData(queryKey) ?? [] + for (const id of previousIds) { + if (!activeIds.has(id)) { + void queryClient.invalidateQueries({ queryKey: savedTranscriptLanguagesKey(id) }) + } + } + return assetIds + }, + refetchInterval: ({ state }) => (state.data?.length ? 2000 : false), + }) + + const transcribingAssetIds = useMemo(() => new Set(enabled ? data : undefined), [data, enabled]) + + async function trackJob(assetId: string) { + // Discard any request that started before the job was accepted. + await queryClient.cancelQueries({ queryKey, exact: true }) + queryClient.setQueryData(queryKey, (current) => + current?.includes(assetId) ? current : [...(current ?? []), assetId], + ) + void queryClient.invalidateQueries({ queryKey, exact: true }) + } + + return { transcribingAssetIds, trackJob } +} diff --git a/packages/webui/lib/transcript.ts b/packages/webui/lib/transcript.ts new file mode 100644 index 00000000..7e71dfe5 --- /dev/null +++ b/packages/webui/lib/transcript.ts @@ -0,0 +1,20 @@ +import type { AssetInfo } from '@shumai/dtos' + +export function getTranscriptVideo(item: AssetInfo) { + const isVideo = item.proxyType ? item.proxyType === 'video' : item.mediaType?.startsWith('video/') + if (!isVideo) return undefined + + if (item.type === 'version_stack') { + const version = item.versionStack?.versions.find(({ current }) => current) + if (version) { + return { + id: version.id, + name: version.name || item.name, + status: version.status ?? item.status, + } + } + } + if (item.type === 'file' && item.id) { + return { id: item.id, name: item.name, status: item.status } + } +} diff --git a/packages/webui/messages/en.json b/packages/webui/messages/en.json index 150d0267..7fbc34b7 100644 --- a/packages/webui/messages/en.json +++ b/packages/webui/messages/en.json @@ -1813,14 +1813,8 @@ "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_generating": "Transcribing…", "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.", diff --git a/packages/webui/messages/ko.json b/packages/webui/messages/ko.json index 6407d622..af3c4664 100644 --- a/packages/webui/messages/ko.json +++ b/packages/webui/messages/ko.json @@ -1743,14 +1743,8 @@ "failed_to_update_comment": "댓글을 수정하지 못했습니다", "generate_transcripts": "전사 생성", "transcript_language_auto": "자동 감지", - "transcript_queued": "전사 작업이 대기열에 추가되었습니다.", - "transcript_generating": "전사를 생성하는 중…", - "transcript_completed": "전사를 생성했습니다.", + "transcript_generating": "전사 중…", "transcript_no_speech": "음성이 감지되지 않았습니다.", - "transcript_no_audio": "이 동영상에는 오디오 트랙이 없습니다.", - "transcript_proxy_required": "전체 동영상 프록시 준비가 완료되면 전사를 생성할 수 있습니다.", - "transcript_audio_too_large": "오디오가 임베딩 서버의 업로드 한도를 초과합니다.", - "transcript_failed": "전사 생성에 실패했습니다.", "transcript_submit_failed": "전사 생성을 시작할 수 없습니다.", "transcript_already_exists": "이 언어의 전사가 이미 있습니다.", "transcript_languages_unavailable": "전사 언어를 불러올 수 없습니다.", diff --git a/packages/webui/messages/zh.json b/packages/webui/messages/zh.json index 9fd83c7c..b4029d0d 100644 --- a/packages/webui/messages/zh.json +++ b/packages/webui/messages/zh.json @@ -1813,14 +1813,8 @@ "failed_to_update_comment": "更新评论失败", "generate_transcripts": "生成转录", "transcript_language_auto": "自动检测", - "transcript_queued": "转录任务已加入队列。", - "transcript_generating": "正在生成转录…", - "transcript_completed": "转录已生成。", + "transcript_generating": "正在转录…", "transcript_no_speech": "未检测到语音。", - "transcript_no_audio": "此视频没有音轨。", - "transcript_proxy_required": "视频代理转码完成后才能生成转录。", - "transcript_audio_too_large": "音频超出嵌入服务器的上传大小限制。", - "transcript_failed": "转录生成失败。", "transcript_submit_failed": "无法启动转录生成。", "transcript_already_exists": "此语言的转录已存在。", "transcript_languages_unavailable": "无法加载转录语言。",