diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c97be34..d2c1f831 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **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. - **video**: Search for languages when generating video transcripts. You can save and edit Simplified and Traditional Chinese versions on the same video. +- **video**: Open the transcript panel directly from the video player even when a video does not have a transcript yet (when transcription is enabled and you have edit permission), start transcript generation from the panel, and see live generating status until the transcript appears. - **integrations**: Set and test an embedding server URL under **Team Settings → Integrations**. A URL set through environment variables appears read-only. Once the server is configured, enable the Transcript Agent to generate video transcripts and receive an internal comment if a job fails. The updated embedding and full Docker Compose files create and enable the agent automatically with a distinct avatar. For an existing deployment, create and enable the Transcript Agent under **Team Settings → Agents**, or add this line to the Shumai service’s `environment` block in your Compose file. diff --git a/apps/web/e2e/README.md b/apps/web/e2e/README.md index 543252ec..7f6deb6a 100644 --- a/apps/web/e2e/README.md +++ b/apps/web/e2e/README.md @@ -123,6 +123,7 @@ apps/web/e2e/ | 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, switch to Traditional Chinese, resize the desktop panel, jump to a segment, pause and resume playback following through manual scrolling and sync, 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` | +| Generate a transcript from the empty video detail transcript panel when transcription is enabled, poll single-file status, handle failed jobs, transition to saved segments, and hide the toggle for reviewers | `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` | diff --git a/apps/web/e2e/tests/file/view-transcript.spec.ts b/apps/web/e2e/tests/file/view-transcript.spec.ts index 74655c54..fdc8ea52 100644 --- a/apps/web/e2e/tests/file/view-transcript.spec.ts +++ b/apps/web/e2e/tests/file/view-transcript.spec.ts @@ -450,3 +450,141 @@ test('uses the displayed video version and hides the toggle for versions without await expect(panel).toBeHidden() await expect(toggle).toBeHidden() }) + +test('generates a transcript from the empty panel, polls status, and renders when complete', async ({ + file, + browser, + prisma, +}) => { + const { page, context, teamId, projectId, fileId, fileName } = file + await page.setViewportSize({ width: 1280, height: 720 }) + await expect + .poll(() => + prisma.asset.findUnique({ + where: { id: fileId }, + select: { status: true, media: true }, + }), + ) + .toMatchObject({ status: 'processed', media: { proxyType: 'video' } }) + + let statusRequests = 0 + let activeTaskId: string | undefined + page.on('request', (request) => { + if (new URL(request.url()).pathname === `/api/files/${fileId}/transcription-status`) { + statusRequests++ + } + }) + + 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' }], + }, + }), + ) + await page.route(`**/api/files/${fileId}/transcripts`, async (route) => { + if (route.request().method() !== 'POST') { + await route.continue() + return + } + const task = await prisma.workflowTask.create({ + data: { projectId, assetId: fileId, type: 'ai_transcription', status: 'processing' }, + }) + activeTaskId = task.id + await route.fulfill({ status: 202, json: { kind: 'queued', taskId: task.id } }) + }) + + const url = `/projects/${projectId}/files/${fileId}` + + // Read-only reviewers should still not see the toggle when no transcript exists. + const reviewer = await seedProjectMember( + prisma, + teamId, + projectId, + 'reviewer', + 'project', + browser, + context, + ) + const reviewerContext = reviewer.context! + try { + const reviewerPage = await reviewerContext.newPage() + await reviewerPage.route('**/api/signup-info', async (route) => { + const response = await route.fetch() + await route.fulfill({ json: { ...(await response.json()), transcriptionEnabled: true } }) + }) + const [reviewerLanguages] = await Promise.all([ + reviewerPage.waitForResponse(`**/api/files/${fileId}/transcripts`), + reviewerPage.goto(url), + ]) + expect(await reviewerLanguages.json()).toEqual({ languages: [] }) + await expect(reviewerPage.getByRole('button', { name: 'Show transcript' })).toBeHidden() + } finally { + await reviewerContext.close() + } + + await page.goto(url) + const toggle = page.getByRole('button', { name: 'Show transcript' }) + await expect(toggle).toBeVisible() + await toggle.click() + + const panel = page.getByRole('complementary', { name: 'Transcript' }) + await expect(panel.getByText('No transcript yet')).toBeVisible() + await expect(panel.getByRole('combobox', { name: 'Language' })).toHaveCount(0) + await expect(panel.getByRole('button', { name: 'Search transcript' })).toHaveCount(0) + + const generateButton = panel.getByRole('button', { name: 'Generate Transcripts' }) + await generateButton.click() + + const dialog = page.getByRole('dialog', { name: 'Generate Transcripts' }) + await expect(dialog).toBeVisible() + await expect(dialog.getByText(fileName)).toBeVisible() + const submit = dialog.getByRole('button', { name: 'Generate', exact: true }) + await expect(submit).toBeEnabled() + await submit.click() + + await expect(dialog).toBeHidden() + await expect(panel.getByRole('status')).toContainText('Transcribing…') + await expect(generateButton).toHaveCount(0) + const requestsBeforePoll = statusRequests + await expect.poll(() => statusRequests).toBeGreaterThan(requestsBeforePoll) + + // Failed jobs return to the default empty state. + await prisma.workflowTask.update({ + where: { id: activeTaskId! }, + data: { status: 'failed', output: { error: 'The video does not contain an audio track' } }, + }) + await expect(panel.getByText('No transcript yet')).toBeVisible() + await expect(generateButton).toBeVisible() + + // Start again and complete with a saved transcript; panel should transition seamlessly. + await generateButton.click() + await expect(dialog).toBeVisible() + await submit.click() + await expect(dialog).toBeHidden() + await expect(panel.getByRole('status')).toContainText('Transcribing…') + + await prisma.assetTranscript.create({ + data: { + assetId: fileId, + language: 'en', + model: 'whisper-tiny', + workflowTaskId: activeTaskId!, + segments: { + create: { position: 0, startMs: 0, endMs: 900, text: 'Generated from detail panel.' }, + }, + }, + }) + await prisma.workflowTask.update({ + where: { id: activeTaskId! }, + data: { status: 'completed' }, + }) + + await expect(panel.getByText('Generated from detail panel.')).toBeVisible() + await expect(panel.getByRole('combobox', { name: 'Language' })).toBeVisible() +}) diff --git a/packages/webui/components/file-viewer/mobile-file-detail.test.tsx b/packages/webui/components/file-viewer/mobile-file-detail.test.tsx index 1f05ffcc..78e9e686 100644 --- a/packages/webui/components/file-viewer/mobile-file-detail.test.tsx +++ b/packages/webui/components/file-viewer/mobile-file-detail.test.tsx @@ -62,6 +62,12 @@ vi.mock('@/ui/api/client', () => ({ json: async () => ({ languages: [] }), }), }, + 'transcription-status': { + $get: vi.fn().mockResolvedValue({ + ok: true, + json: async () => null, + }), + }, comments: { $get: vi.fn().mockResolvedValue({ ok: true, @@ -70,6 +76,12 @@ vi.mock('@/ui/api/client', () => ({ }, }, }, + 'signup-info': { + $get: vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ transcriptionEnabled: false }), + }), + }, me: { $get: vi.fn().mockResolvedValue({ ok: true, diff --git a/packages/webui/components/file-viewer/mobile-file-detail.tsx b/packages/webui/components/file-viewer/mobile-file-detail.tsx index 3691d08e..a28c65a9 100644 --- a/packages/webui/components/file-viewer/mobile-file-detail.tsx +++ b/packages/webui/components/file-viewer/mobile-file-detail.tsx @@ -102,7 +102,10 @@ export function MobileFileDetail({ const { canEdit } = usePermissions(projectId) const { members } = useMemberStore() const mediaControllerRef = useRef(null) - const transcript = useVideoTranscript(!isPublic && file.id === activeFileId ? file : undefined) + const transcript = useVideoTranscript(!isPublic && file.id === activeFileId ? file : undefined, { + canEdit: canEdit && !isPublic, + projectId, + }) const [sheetHeightPercent, setSheetHeightPercent] = useState(50) const [annotations, setAnnotations] = useState([]) diff --git a/packages/webui/components/file-viewer/transcript-panel.test.tsx b/packages/webui/components/file-viewer/transcript-panel.test.tsx new file mode 100644 index 00000000..b1e55360 --- /dev/null +++ b/packages/webui/components/file-viewer/transcript-panel.test.tsx @@ -0,0 +1,151 @@ +// @vitest-environment happy-dom +import type { MediaController } from '@/ui/components/viewers/types' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import React, { createRef } from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { TranscriptPanel } from './transcript-panel' + +const mockLanguagesGet = vi.fn() +const mockGeneratePost = vi.fn() + +vi.mock('@/ui/api/client', () => ({ + client: { + api: { + transcription: { + languages: { + $get: () => mockLanguagesGet(), + }, + }, + files: { + ':fileId': { + transcripts: { + $post: (...args: unknown[]) => mockGeneratePost(...args), + ':language': { + $get: vi.fn(), + }, + }, + }, + }, + }, + }, +})) + +describe('TranscriptPanel empty and generating states', () => { + let queryClient: QueryClient + + beforeEach(() => { + queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + }, + }) + mockLanguagesGet.mockResolvedValue({ + ok: true, + json: async () => ({ + model: 'whisper-tiny', + languages: [{ code: 'en', name: 'English' }], + }), + }) + mockGeneratePost.mockResolvedValue({ + ok: true, + json: async () => ({ kind: 'queued', taskId: 'task-1' }), + }) + }) + + afterEach(() => { + cleanup() + queryClient.clear() + vi.clearAllMocks() + }) + + it('shows empty state with Generate Transcripts button and opens the dialog to submit', async () => { + const onJobAccepted = vi.fn().mockResolvedValue(undefined) + const mediaControllerRef = createRef() + + render( + + + , + ) + + expect(screen.getByText('No transcript yet')).toBeDefined() + expect(screen.queryByRole('combobox', { name: 'Language' })).toBeNull() + expect(screen.queryByRole('button', { name: 'Search transcript' })).toBeNull() + + fireEvent.click(screen.getByRole('button', { name: 'Generate Transcripts' })) + + const dialog = await screen.findByRole('dialog', { name: 'Generate Transcripts' }) + expect(dialog).toBeDefined() + const generateButton = screen.getByRole('button', { name: 'Generate' }) + await waitFor(() => expect((generateButton as HTMLButtonElement).disabled).toBe(false)) + + fireEvent.click(generateButton) + + await waitFor(() => expect(onJobAccepted).toHaveBeenCalledWith('video-1')) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + }) + + it('disables the Generate Transcripts button when the video proxy is not ready', () => { + const mediaControllerRef = createRef() + + render( + + + , + ) + + const button = screen.getByRole('button', { name: 'Generate Transcripts' }) as HTMLButtonElement + expect(button.disabled).toBe(true) + }) + + it('shows a spinner and transcribing status while a job is running', () => { + const mediaControllerRef = createRef() + + render( + + + , + ) + + const status = screen.getByRole('status') + expect(status.textContent).toContain('Transcribing…') + expect(screen.queryByRole('button', { name: 'Generate Transcripts' })).toBeNull() + }) +}) diff --git a/packages/webui/components/file-viewer/transcript-panel.tsx b/packages/webui/components/file-viewer/transcript-panel.tsx index 67a73551..d8fffdb3 100644 --- a/packages/webui/components/file-viewer/transcript-panel.tsx +++ b/packages/webui/components/file-viewer/transcript-panel.tsx @@ -1,5 +1,14 @@ import { client } from '@/ui/api/client' +import { GenerateTranscriptsDialog } from '@/ui/components/file-browser/generate-transcripts-dialog' import { Button } from '@/ui/components/ui/button' +import { + Empty, + EmptyContent, + EmptyDescription, + EmptyHeader, + EmptyMedia, + EmptyTitle, +} from '@/ui/components/ui/empty' import { Input } from '@/ui/components/ui/input' import { NativeSelect, NativeSelectOption } from '@/ui/components/ui/native-select' import { ScrollArea } from '@/ui/components/ui/scroll-area' @@ -10,8 +19,8 @@ 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 { skipToken, useQuery } from '@tanstack/react-query' +import { Captions, ChevronDown, ChevronUp, Loader2, Search, X } from 'lucide-react' import { memo, useCallback, @@ -29,8 +38,13 @@ import { useTranscriptScroll } from './use-transcript-scroll' interface TranscriptPanelProps { id: string assetId: string + assetName?: string languages: string[] canEdit: boolean + canGenerate?: boolean + canStartGeneration?: boolean + isTranscribing?: boolean + onJobAccepted?: (assetId: string) => Promise mediaControllerRef: RefObject onClose: () => void className?: string @@ -60,8 +74,13 @@ function findMatches(segments: TranscriptSegment[], search: string) { export const TranscriptPanel = memo(function TranscriptPanel({ id, assetId, + assetName = '', languages, canEdit, + canGenerate = false, + canStartGeneration = false, + isTranscribing = false, + onJobAccepted, mediaControllerRef, onClose, className, @@ -76,29 +95,33 @@ export const TranscriptPanel = memo(function TranscriptPanel({ })) .sort((a, b) => a.name.localeCompare(b.name, locale)) }, [languages, locale]) + const hasTranscript = options.length > 0 const [preferredLanguage, setPreferredLanguage] = useState(locale) - const language = options.find(({ code }) => code === preferredLanguage)?.code ?? options[0].code + 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() const [editingId, setEditingId] = useState() + const [generateDialogOpen, setGenerateDialogOpen] = useState(false) const toggleSearchRef = useRef(null) const closeRef = useRef(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() - }, + queryKey: savedTranscriptKey(assetId, language ?? ''), + queryFn: language + ? 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() + } + : skipToken, retry: false, }) const segments = transcript.data?.segments ?? noSegments @@ -180,39 +203,45 @@ export const TranscriptPanel = memo(function TranscriptPanel({ >
-
- { - cancelScroll() - setPreferredLanguage(event.target.value) - setMatchIndex(0) - setFollowing(true) - }} - > - {options.map(({ code, name }) => ( - - {name} - - ))} - -
+ {hasTranscript && language ? ( +
+ { + cancelScroll() + setPreferredLanguage(event.target.value) + setMatchIndex(0) + setFollowing(true) + }} + > + {options.map(({ code, name }) => ( + + {name} + + ))} + +
+ ) : ( +

{m.transcript_title()}

+ )}
- + {hasTranscript && ( + + )}
- {searchOpen && ( + {hasTranscript && searchOpen && (
)}
- {transcript.isPending && ( -

- {m.loading()} -

- )} - {transcript.isError && ( -
-

- {m.transcript_load_failed()} -

- -
- )} - {transcript.data && ( -
- -
    - {segments.map((segment) => { - const segmentMatches = matches.bySegment.get(segment.id) - return ( - index === selectedMatch) - ? selectedMatch - : undefined - } - mediaControllerRef={mediaControllerRef} - canEdit={canEdit} - onEdit={canEdit && !editingId ? startEditing : undefined} - editTarget={ - segment.id === editingId - ? { assetId, language, onFinish: finishEditing } - : undefined - } - /> - ) - })} -
-
- {!following && !editingId && ( -
-
+ ) : ( + + + + + + {m.transcript_empty_title()} + {m.transcript_empty_description()} + + {canGenerate && onJobAccepted && ( + + + + )} + + ) + ) : ( + <> + {transcript.isPending && ( +

+ {m.loading()} +

+ )} + {transcript.isError && ( +
+

+ {m.transcript_load_failed()} +

+
)} -
+ {transcript.data && language && ( +
+ +
    + {segments.map((segment) => { + const segmentMatches = matches.bySegment.get(segment.id) + return ( + index === selectedMatch) + ? selectedMatch + : undefined + } + mediaControllerRef={mediaControllerRef} + canEdit={canEdit} + onEdit={canEdit && !editingId ? startEditing : undefined} + editTarget={ + segment.id === editingId + ? { assetId, language, onFinish: finishEditing } + : undefined + } + /> + ) + })} +
+
+ {!following && !editingId && ( +
+ +
+ )} +
+ )} + + )} + {!hasTranscript && generateDialogOpen && canGenerate && onJobAccepted && ( + setGenerateDialogOpen(false)} + /> )} ) diff --git a/packages/webui/hooks/use-server-features.ts b/packages/webui/hooks/use-server-features.ts index a7d7c5b5..a8e0a6ca 100644 --- a/packages/webui/hooks/use-server-features.ts +++ b/packages/webui/hooks/use-server-features.ts @@ -1,9 +1,10 @@ import { useQuery } from '@tanstack/react-query' import { client } from '@/ui/api/client' -export function useServerFeatures() { +export function useServerFeatures(enabled = true) { return useQuery({ queryKey: ['signup-info'], + enabled, queryFn: async () => { const res = await client.api['signup-info'].$get() if (!res.ok) return null diff --git a/packages/webui/hooks/use-video-transcript.test.tsx b/packages/webui/hooks/use-video-transcript.test.tsx new file mode 100644 index 00000000..be5260c7 --- /dev/null +++ b/packages/webui/hooks/use-video-transcript.test.tsx @@ -0,0 +1,213 @@ +// @vitest-environment happy-dom +import type { AssetInfo, TranscriptJobStatus } from '@shumai/dtos' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, cleanup, renderHook, waitFor } from '@testing-library/react' +import React from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { fileTranscriptionStatusKey, useVideoTranscript } from './use-video-transcript' + +const mockSignupInfoGet = vi.fn() +const mockTranscriptsGet = vi.fn() +const mockTranscriptionStatusGet = vi.fn() + +vi.mock('@/ui/api/client', () => ({ + client: { + api: { + 'signup-info': { + $get: () => mockSignupInfoGet(), + }, + files: { + ':fileId': { + transcripts: { + $get: (...args: unknown[]) => mockTranscriptsGet(...args), + }, + 'transcription-status': { + $get: (...args: unknown[]) => mockTranscriptionStatusGet(...args), + }, + }, + }, + }, + }, +})) + +function createWrapper(queryClient: QueryClient) { + return function Wrapper({ children }: { children: React.ReactNode }) { + return {children} + } +} + +const readyVideo: AssetInfo = { + id: 'video-1', + name: 'demo.mp4', + status: 'processed', + proxyType: 'video', + media: { + videoTranscodes: [{ key: 'proxies/720p.mp4', resolution: '720p', width: 1280, height: 720 }], + }, +} as AssetInfo + +describe('useVideoTranscript', () => { + let queryClient: QueryClient + + beforeEach(() => { + queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + }, + }) + mockSignupInfoGet.mockResolvedValue({ + ok: true, + json: async () => ({ transcriptionEnabled: false }), + }) + mockTranscriptsGet.mockResolvedValue({ + ok: true, + json: async () => ({ languages: [] }), + }) + mockTranscriptionStatusGet.mockResolvedValue({ + ok: true, + json: async () => null, + }) + }) + + afterEach(() => { + cleanup() + queryClient.clear() + vi.clearAllMocks() + }) + + it('hides the toggle when there is no transcript and transcription is disabled', async () => { + const { result } = renderHook( + () => useVideoTranscript(readyVideo, { canEdit: true, projectId: 'proj-1' }), + { wrapper: createWrapper(queryClient) }, + ) + + await waitFor(() => expect(mockTranscriptsGet).toHaveBeenCalledOnce()) + await waitFor(() => expect(mockSignupInfoGet).toHaveBeenCalledOnce()) + expect(result.current).toBeUndefined() + expect(mockTranscriptionStatusGet).not.toHaveBeenCalled() + }) + + it('hides the toggle for read-only users when there is no transcript even if transcription is enabled', async () => { + mockSignupInfoGet.mockResolvedValue({ + ok: true, + json: async () => ({ transcriptionEnabled: true }), + }) + + const { result } = renderHook( + () => useVideoTranscript(readyVideo, { canEdit: false, projectId: 'proj-1' }), + { wrapper: createWrapper(queryClient) }, + ) + + await waitFor(() => expect(mockTranscriptsGet).toHaveBeenCalledOnce()) + expect(result.current).toBeUndefined() + expect(mockSignupInfoGet).not.toHaveBeenCalled() + expect(mockTranscriptionStatusGet).not.toHaveBeenCalled() + }) + + it('shows the toggle for read-only users when a saved transcript exists', async () => { + mockTranscriptsGet.mockResolvedValue({ + ok: true, + json: async () => ({ languages: ['en'] }), + }) + + const { result } = renderHook( + () => useVideoTranscript(readyVideo, { canEdit: false, projectId: 'proj-1' }), + { wrapper: createWrapper(queryClient) }, + ) + + await waitFor(() => expect(result.current).toBeDefined()) + act(() => result.current?.toggle.onToggle()) + expect(result.current?.panel?.languages).toEqual(['en']) + expect(result.current?.panel?.canGenerate).toBe(false) + }) + + it('shows the empty panel for editors when transcription is enabled and tracks status until completion', async () => { + mockSignupInfoGet.mockResolvedValue({ + ok: true, + json: async () => ({ transcriptionEnabled: true }), + }) + let savedLanguages: string[] = [] + let currentStatus: TranscriptJobStatus | null = null + mockTranscriptsGet.mockImplementation(async () => ({ + ok: true, + json: async () => ({ languages: savedLanguages }), + })) + mockTranscriptionStatusGet.mockImplementation(async () => ({ + ok: true, + json: async () => currentStatus, + })) + + const { result } = renderHook( + () => useVideoTranscript(readyVideo, { canEdit: true, projectId: 'proj-1' }), + { wrapper: createWrapper(queryClient) }, + ) + + await waitFor(() => expect(result.current).toBeDefined()) + act(() => result.current?.toggle.onToggle()) + expect(result.current?.panel).toMatchObject({ + assetId: 'video-1', + assetName: 'demo.mp4', + languages: [], + canGenerate: true, + canStartGeneration: true, + isTranscribing: false, + }) + + currentStatus = { status: 'processing', taskId: 'task-1' } + await act(async () => { + await result.current?.panel?.onJobAccepted('video-1') + }) + + await waitFor(() => expect(result.current?.panel?.isTranscribing).toBe(true)) + expect(queryClient.getQueryData(['project-transcription-status', 'proj-1'])).toEqual([ + 'video-1', + ]) + + savedLanguages = ['en'] + currentStatus = { status: 'completed', taskId: 'task-1' } + await act(async () => { + await queryClient.refetchQueries({ + queryKey: fileTranscriptionStatusKey('video-1'), + exact: true, + }) + }) + + await waitFor(() => expect(result.current?.panel?.languages).toEqual(['en'])) + expect(result.current?.panel?.isTranscribing).toBe(false) + expect(queryClient.getQueryData(['project-transcription-status', 'proj-1'])).toEqual([]) + }) + + it('returns to idle empty state and invalidates comments when a tracked job fails', async () => { + mockSignupInfoGet.mockResolvedValue({ + ok: true, + json: async () => ({ transcriptionEnabled: true }), + }) + let currentStatus: TranscriptJobStatus | null = { status: 'processing', taskId: 'task-2' } + mockTranscriptionStatusGet.mockImplementation(async () => ({ + ok: true, + json: async () => currentStatus, + })) + const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries') + + const { result } = renderHook( + () => useVideoTranscript(readyVideo, { canEdit: true, projectId: 'proj-1' }), + { wrapper: createWrapper(queryClient) }, + ) + + await waitFor(() => expect(result.current).toBeDefined()) + act(() => result.current?.toggle.onToggle()) + await waitFor(() => expect(result.current?.panel?.isTranscribing).toBe(true)) + + currentStatus = { status: 'failed', taskId: 'task-2', reason: 'noAudio' } + await act(async () => { + await queryClient.refetchQueries({ + queryKey: fileTranscriptionStatusKey('video-1'), + exact: true, + }) + }) + + await waitFor(() => expect(result.current?.panel?.isTranscribing).toBe(false)) + expect(result.current?.panel?.languages).toEqual([]) + expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['files', 'video-1', 'comments'] }) + }) +}) diff --git a/packages/webui/hooks/use-video-transcript.ts b/packages/webui/hooks/use-video-transcript.ts index 112e791f..f9fa5033 100644 --- a/packages/webui/hooks/use-video-transcript.ts +++ b/packages/webui/hooks/use-video-transcript.ts @@ -1,7 +1,14 @@ import { client } from '@/ui/api/client' -import type { AssetInfo } from '@shumai/dtos' -import { skipToken, useQuery } from '@tanstack/react-query' +import { m } from '@/ui/paraglide/messages.js' +import { + isTranscriptVideoReady, + selectTranscriptVideoProxyKey, + type AssetInfo, + type TranscriptJobStatus, +} from '@shumai/dtos' +import { skipToken, useQuery, useQueryClient } from '@tanstack/react-query' import { useCallback, useId, useRef, useState } from 'react' +import { useServerFeatures } from './use-server-features' export const savedTranscriptLanguagesKey = (assetId?: string) => ['files', assetId, 'transcripts'] as const @@ -9,11 +16,39 @@ export const savedTranscriptLanguagesKey = (assetId?: string) => export const savedTranscriptKey = (assetId: string, language: string) => [...savedTranscriptLanguagesKey(assetId), language] as const -export function useVideoTranscript(file?: Pick) { - const assetId = - file?.proxyType === 'video' - ? (file.versionStack?.versions.find(({ current }) => current)?.id ?? file.id) - : undefined +export const fileTranscriptionStatusKey = (assetId?: string) => + ['files', assetId, 'transcription-status'] as const + +type VideoTranscriptFile = Pick< + AssetInfo, + 'id' | 'name' | 'status' | 'proxyType' | 'media' | 'versionStack' +> + +interface UseVideoTranscriptOptions { + canEdit?: boolean + projectId?: string +} + +function isActiveTranscriptJob(status?: TranscriptJobStatus | null): boolean { + return status?.status === 'pending' || status?.status === 'processing' +} + +export function useVideoTranscript( + file?: VideoTranscriptFile, + options?: UseVideoTranscriptOptions, +) { + const queryClient = useQueryClient() + const canEdit = Boolean(options?.canEdit) + const projectId = options?.projectId + const currentVersion = file?.versionStack?.versions.find(({ current }) => current) + const assetId = file?.proxyType === 'video' ? (currentVersion?.id ?? file.id) : undefined + const assetName = currentVersion?.name || file?.name || '' + const assetStatus = currentVersion?.status ?? file?.status ?? '' + const canStartGeneration = + Boolean(assetId) && + isTranscriptVideoReady(assetStatus) && + Boolean(selectTranscriptVideoProxyKey(file?.media)) + const panelId = useId() const buttonRef = useRef(null) const [selection, setSelection] = useState({ assetId, open: false }) @@ -21,6 +56,9 @@ export function useVideoTranscript(file?: Pick { + const statusKey = fileTranscriptionStatusKey(assetId) + const response = await client.api.files[':fileId']['transcription-status'].$get( + { param: { fileId: assetId } }, + { init: { signal } }, + ) + if (!response.ok) throw new Error(m.transcript_status_unavailable()) + const next = (await response.json()) as TranscriptJobStatus | null + signal.throwIfAborted() + + const previous = queryClient.getQueryData(statusKey) + const wasActive = isActiveTranscriptJob(previous) + const isActive = isActiveTranscriptJob(next) + + if ((wasActive || previous === undefined) && next?.status === 'completed') { + await queryClient.invalidateQueries({ + queryKey: savedTranscriptLanguagesKey(assetId), + exact: true, + }) + signal.throwIfAborted() + } + + if (wasActive && !isActive) { + if (next?.status === 'failed') { + void queryClient.invalidateQueries({ queryKey: ['files', assetId, 'comments'] }) + if (file?.id && file.id !== assetId) { + void queryClient.invalidateQueries({ queryKey: ['files', file.id, 'comments'] }) + } + } + if (projectId) { + const projectStatusKey = ['project-transcription-status', projectId] as const + queryClient.setQueryData(projectStatusKey, (current) => + current?.filter((id) => id !== assetId), + ) + void queryClient.invalidateQueries({ + queryKey: projectStatusKey, + exact: true, + }) + } + } + + return next + } + : skipToken, + refetchInterval: ({ state }) => (isActiveTranscriptJob(state.data) ? 2000 : false), + }) + + const isTranscribing = shouldTrackStatus && isActiveTranscriptJob(statusQuery.data) + + const trackJob = useCallback( + async (targetAssetId: string) => { + const statusKey = fileTranscriptionStatusKey(targetAssetId) + // Discard any status request that started before the job was accepted. + await queryClient.cancelQueries({ queryKey: statusKey, exact: true }) + queryClient.setQueryData(statusKey, (current) => + isActiveTranscriptJob(current) ? current : { status: 'pending', taskId: '' }, + ) + void queryClient.invalidateQueries({ queryKey: statusKey, exact: true }) + + if (projectId) { + const projectStatusKey = ['project-transcription-status', projectId] as const + await queryClient.cancelQueries({ queryKey: projectStatusKey, exact: true }) + queryClient.setQueryData(projectStatusKey, (current) => + current?.includes(targetAssetId) ? current : [...(current ?? []), targetAssetId], + ) + void queryClient.invalidateQueries({ queryKey: projectStatusKey, exact: true }) + } + }, + [projectId, queryClient], + ) + const close = useCallback(() => { setSelection({ assetId, open: false }) buttonRef.current?.focus({ preventScroll: true }) }, [assetId]) - if (!assetId || !data?.languages.length) return undefined + if (!assetId || languages === undefined || (!hasTranscript && !canGenerate)) return undefined const open = selection.assetId === assetId && selection.open return { - panel: open ? { id: panelId, assetId, languages: data.languages, onClose: close } : undefined, + panel: open + ? { + id: panelId, + assetId, + assetName, + languages, + canGenerate, + canStartGeneration, + isTranscribing, + onJobAccepted: trackJob, + onClose: close, + } + : undefined, toggle: { panelId, open, diff --git a/packages/webui/messages/en.json b/packages/webui/messages/en.json index 28abd952..437156cb 100644 --- a/packages/webui/messages/en.json +++ b/packages/webui/messages/en.json @@ -1847,5 +1847,7 @@ "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." + "transcript_save_failed": "Could not save this segment.", + "transcript_empty_title": "No transcript yet", + "transcript_empty_description": "Generate a transcript to read, search, and jump through this video." } diff --git a/packages/webui/messages/ko.json b/packages/webui/messages/ko.json index b1186b99..1da14a44 100644 --- a/packages/webui/messages/ko.json +++ b/packages/webui/messages/ko.json @@ -1777,5 +1777,7 @@ "transcript_sync_to_playback": "재생 위치에 맞추기", "transcript_load_failed": "이 전사를 불러올 수 없습니다.", "transcript_edit_segment": "구간 텍스트 편집", - "transcript_save_failed": "이 구간을 저장할 수 없습니다." + "transcript_save_failed": "이 구간을 저장할 수 없습니다.", + "transcript_empty_title": "아직 전사가 없습니다", + "transcript_empty_description": "전사를 생성하여 동영상 내용을 읽고 검색하며 원하는 위치로 이동하세요." } diff --git a/packages/webui/messages/zh.json b/packages/webui/messages/zh.json index 73b50e7c..2c829170 100644 --- a/packages/webui/messages/zh.json +++ b/packages/webui/messages/zh.json @@ -1847,5 +1847,7 @@ "transcript_sync_to_playback": "同步到播放位置", "transcript_load_failed": "无法加载此转录。", "transcript_edit_segment": "编辑片段文本", - "transcript_save_failed": "无法保存此片段。" + "transcript_save_failed": "无法保存此片段。", + "transcript_empty_title": "暂无转录", + "transcript_empty_description": "生成转录后,即可阅读、搜索并跳转到视频对应位置。" } diff --git a/packages/webui/routes/projects/$projectId/files/$fileId.lazy.tsx b/packages/webui/routes/projects/$projectId/files/$fileId.lazy.tsx index 509967e7..2d76bdf3 100644 --- a/packages/webui/routes/projects/$projectId/files/$fileId.lazy.tsx +++ b/packages/webui/routes/projects/$projectId/files/$fileId.lazy.tsx @@ -216,6 +216,7 @@ function FileViewPage() { const fileData = versionData || stackData const transcript = useVideoTranscript( !isMobile && !isCompareMode && fileData?.id === activeFileId ? fileData : undefined, + { canEdit, projectId }, ) const versionsDataList = versionAssetId ? versionsList : stackData?.versionStack?.versions