From 675c07a4ce493ef61e1b6be4b2c0a23e6aa95525 Mon Sep 17 00:00:00 2001 From: Chethan Date: Fri, 9 Oct 2026 11:44:18 +0530 Subject: [PATCH 01/15] style(editor): remove stray double blank lines in editor.scss --- src/editor.scss | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/editor.scss b/src/editor.scss index 579c56f..9af823b 100644 --- a/src/editor.scss +++ b/src/editor.scss @@ -891,7 +891,6 @@ animation: ce-spin 0.9s linear infinite; } - .ce-progress-track { width: 320px; max-width: 80%; @@ -1608,7 +1607,6 @@ color: #fff; } - /* Centered overlay: fade the backdrop only — no horizontal shift. */ /* Centered modal card: rise + scale in place. */ From 3801bb0254e2e20193206f9fec935e0cf137e058 Mon Sep 17 00:00:00 2001 From: Chethan Date: Fri, 9 Oct 2026 11:44:18 +0530 Subject: [PATCH 02/15] refactor(transcripts): remove legacy transcript create/approve/reject/poll flow The transcript APIs under content/v4/enrichment/object/* and the ?enrich=all read are replaced by the generic EnrichmentObject APIs, and phase 1 has no approve/reject/edit. Remove the old flow ahead of the new implementation. - ContentEditorService: drop createTranscript, updateTranscript, approveTranscript, rejectTranscript, readTranscripts and their endpoints - useEditor: drop the post-upload createTranscript call and the 20s transcript polling; hasTranscripts/transcripts/transcriptsChecked are inert until the enrichment-object read is added - TranscriptsDrawer: read-only, reads ed.transcripts; remove approve, reject, segment editing and status re-confirmation - i18n: remove 16 unused keys in all locales, reword NO_TRANSCRIPTS_SUB - editor.scss: remove styles for the removed UI - tests: remove suites for the removed behaviour, delete useEditor.test.ts --- src/components/TranscriptsDrawer.test.tsx | 740 ++-------------------- src/components/TranscriptsDrawer.tsx | 370 +---------- src/editor.scss | 42 -- src/i18n/translations.ar.ts | 18 +- src/i18n/translations.en.ts | 18 +- src/i18n/translations.fr.ts | 18 +- src/i18n/translations.hi.ts | 18 +- src/i18n/translations.pt.ts | 18 +- src/i18n/translations.ta.ts | 18 +- src/services/ContentEditorService.test.ts | 225 ------- src/services/ContentEditorService.ts | 70 +- src/test/mockEd.ts | 5 - src/useEditor.test.ts | 238 ------- src/useEditor.ts | 58 +- 14 files changed, 86 insertions(+), 1770 deletions(-) delete mode 100644 src/useEditor.test.ts diff --git a/src/components/TranscriptsDrawer.test.tsx b/src/components/TranscriptsDrawer.test.tsx index 32e1ea5..ac77245 100644 --- a/src/components/TranscriptsDrawer.test.tsx +++ b/src/components/TranscriptsDrawer.test.tsx @@ -1,22 +1,23 @@ -import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'; +import { render, screen, fireEvent } from '@testing-library/react'; import { describe, it, expect, vi, afterEach } from 'vitest'; import TranscriptsDrawer from './TranscriptsDrawer'; -import { makeEd, mockService, mockContent } from '../test/mockEd'; +import { makeEd } from '../test/mockEd'; +import type { RawTranscript } from '../types'; -const TRANSCRIPTS = [ +const TRANSCRIPTS: RawTranscript[] = [ { identifier: 't_en', code: 'c_en', language: 'English', languageCode: 'en', status: 'Live', sourceLanguage: true, captionsUrl: 'https://x/en.vtt', artifactUrl: 'https://x/en.json', generatedOn: '2026-08-03T05:00:00Z' }, { identifier: 't_hi', code: 'c_hi', language: 'Hindi', languageCode: 'hi', status: 'Review', sourceLanguage: false, artifactUrl: 'https://x/hi.json' }, { identifier: 't_ta', code: 'c_ta', language: 'Tamil', languageCode: 'ta', status: 'Processing', sourceLanguage: false }, { identifier: 't_te', code: 'c_te', language: 'Telugu', languageCode: 'te', status: 'Failed', sourceLanguage: false }, ]; +const open = (transcripts: RawTranscript[]) => + makeEd({ drawer: 'transcripts', transcripts, hasTranscripts: transcripts.length > 0 }); + describe('', () => { - it('loads and renders each language with its status when open', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service, content: { ...mockContent, mimeType: 'video/mp4' } }); - render(); - await waitFor(() => expect(service.readTranscripts).toHaveBeenCalledWith('do_1')); - expect(await screen.findByText('English')).toBeInTheDocument(); + it('renders each language from ed.transcripts with its status when open', () => { + render(); + expect(screen.getByText('English')).toBeInTheDocument(); expect(screen.getByText('Hindi')).toBeInTheDocument(); expect(screen.getByText('Tamil')).toBeInTheDocument(); expect(screen.getByText('Telugu')).toBeInTheDocument(); @@ -26,23 +27,16 @@ describe('', () => { expect(screen.getByText('SOURCE')).toBeInTheDocument(); }); - it('shows a placeholder icon and "Detecting language…" instead of blank/"??" when a Processing transcript has no language info yet', async () => { + it('shows a placeholder icon and "Detecting language…" instead of blank/"??" when a Processing transcript has no language info yet', () => { const noLanguageYet = [{ identifier: 't_x', code: 'c_x', language: '', status: 'Processing', sourceLanguage: true }]; - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(noLanguageYet) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - expect(await screen.findByText('Detecting language…')).toBeInTheDocument(); + render(); + expect(screen.getByText('Detecting language…')).toBeInTheDocument(); expect(screen.queryByText('??')).not.toBeInTheDocument(); }); - it('always lists the source language card first, regardless of its position in the backend response', async () => { - // TRANSCRIPTS has English (source) listed first already - reorder so it's last, - // to prove the UI is doing the sorting, not just reflecting response order. + it('always lists the source language card first, regardless of its position in the list', () => { const reordered = [...TRANSCRIPTS].reverse(); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(reordered) }); - const ed = makeEd({ drawer: 'transcripts', service }); - const { container } = render(); - await screen.findByText('English'); + const { container } = render(); const names = Array.from(container.querySelectorAll('.ce-transcript-name')).map((el) => el.textContent); // Reversed input is [Telugu, Tamil, Hindi, English] - source moves to front, // the rest keep their relative order: [English, Telugu, Tamil, Hindi]. @@ -50,390 +44,40 @@ describe('', () => { expect(names[names.length - 1]).toContain('Hindi'); }); - it('shows a note that other languages will appear once the source transcript is ready, when only the source exists so far', async () => { + it('shows a note that other languages will appear once the source transcript is ready, when only the source exists so far', () => { const sourceOnly = [{ identifier: 't_en', code: 'c_en', language: 'English', status: 'Review', sourceLanguage: true }]; - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(sourceOnly) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - expect(await screen.findByText(/Translations for other languages will appear/)).toBeInTheDocument(); + render(); + expect(screen.getByText(/Translations for other languages will appear/)).toBeInTheDocument(); }); - it('does not show the translations-pending note once other languages already exist (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); + it('does not show the translations-pending note once other languages already exist (negative)', () => { + render(); expect(screen.queryByText(/Translations for other languages will appear/)).not.toBeInTheDocument(); }); - it('shows a note that status changes can take a few minutes to fully sync', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - expect(await screen.findByText(/take a few minutes to fully sync/)).toBeInTheDocument(); - }); - - it('does not show the sync note once every language is Live - nothing left to approve/reject (negative)', async () => { - const allLive = TRANSCRIPTS.map((tr) => ({ ...tr, status: 'Live' })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(allLive) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - expect(screen.queryByText(/take a few minutes to fully sync/)).not.toBeInTheDocument(); - }); - - it('does not show the sync note in the empty state - nothing has happened yet to sync (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue([]) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('No transcripts yet'); - expect(screen.queryByText(/take a few minutes to fully sync/)).not.toBeInTheDocument(); + it('shows an empty state when there are no transcripts yet (negative)', () => { + render(); + expect(screen.getByText('No transcripts yet')).toBeInTheDocument(); + expect(screen.getByText('Transcripts appear here after this video is published.')).toBeInTheDocument(); }); - it('shows an empty state when there are no transcripts yet (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue([]) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - expect(await screen.findByText('No transcripts yet')).toBeInTheDocument(); - }); - - it('does not fetch when the drawer is closed (negative)', () => { - const service = mockService(); - const ed = makeEd({ drawer: null, service }); - render(); - expect(service.readTranscripts).not.toHaveBeenCalled(); - }); - - it('shows a distinct load-error state (not "no transcripts yet") when the read fails (negative)', async () => { - const readTranscripts = vi.fn().mockRejectedValue(new Error('Unauthorized')); - const service = mockService({ readTranscripts }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - expect(await screen.findByText("Couldn't load transcripts")).toBeInTheDocument(); - expect(screen.getByText('Unauthorized')).toBeInTheDocument(); - expect(screen.queryByText('No transcripts yet')).not.toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: 'Retry' })); - await waitFor(() => expect(readTranscripts).toHaveBeenCalledTimes(2)); - }); - - it('links a Live transcript\'s "Download captions" to its real captionsUrl', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - const link = await screen.findByRole('link', { name: 'Download captions' }); + it('links a Live transcript\'s "Download captions" to its real captionsUrl', () => { + render(); + const link = screen.getByRole('link', { name: 'Download captions' }); expect(link).toHaveAttribute('href', 'https://x/en.vtt'); expect(link).toHaveAttribute('download'); }); - it('shows only one download action for a Live transcript, not a duplicate (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); + it('shows only one download action for a Live transcript, not a duplicate (negative)', () => { + render(); expect(screen.getAllByRole('link', { name: 'Download captions' })).toHaveLength(1); }); - it('disables the processing/failed action buttons as not-yet-implemented (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Tamil'); - const comingSoonButtons = screen.getAllByRole('button', { name: 'Coming soon' }); - expect(comingSoonButtons).toHaveLength(2); // Tamil (Processing) + Telugu (Failed) - comingSoonButtons.forEach((btn) => expect(btn).toBeDisabled()); - }); - - it('offers a "Review" action (not disabled) for a review-status language with a transcript file', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - const reviewBtn = screen.getByRole('button', { name: 'Review' }); - expect(reviewBtn).not.toBeDisabled(); - }); - - describe('segments view — status, approve and reject', () => { - it('shows the status and enabled Approve/Reject buttons for a review-status language', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - expect(screen.getByText('Needs review')).toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Approve Transcript' })).not.toBeDisabled(); - expect(screen.getByRole('button', { name: 'Reject' })).not.toBeDisabled(); - vi.unstubAllGlobals(); - }); - - it('does not show Approve/Reject buttons for a Live language (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); - await screen.findByText('Hello.'); - expect(screen.getByText('Live')).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Approve Transcript' })).not.toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Reject' })).not.toBeInTheDocument(); - vi.unstubAllGlobals(); - }); - - it('approves a Review transcript and only shows Live once the re-read confirms it', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockResolvedValue({}); - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) - .mockResolvedValueOnce(TRANSCRIPTS.map((tr) => (tr.language === 'Hindi' ? { ...tr, status: 'Live' } : tr))); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - await waitFor(() => expect(approveTranscript).toHaveBeenCalledWith('do_1', 't_hi')); - await waitFor(() => expect(readTranscripts).toHaveBeenCalledTimes(2)); - await screen.findByText('Hindi'); - // Both English (already Live) and Hindi (just confirmed) now show Live. - await waitFor(() => expect(screen.getAllByText('Live')).toHaveLength(2)); - vi.unstubAllGlobals(); - }); - - it('rejects a Review transcript and only shows Draft once the re-read confirms it', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const rejectTranscript = vi.fn().mockResolvedValue({}); - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) - .mockResolvedValueOnce(TRANSCRIPTS.map((tr) => (tr.language === 'Hindi' ? { ...tr, status: 'Draft' } : tr))); - const service = mockService({ readTranscripts, rejectTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Reject' })); - await waitFor(() => expect(rejectTranscript).toHaveBeenCalledWith('do_1', 't_hi')); - await screen.findByText('Hindi'); - expect(await screen.findByText('Draft')).toBeInTheDocument(); - vi.unstubAllGlobals(); - }); - - it('shows a "still processing" message (not Live) when approve succeeds but the re-read has not caught up yet (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockResolvedValue({}); - // Confirm re-read still reports Review - the approve hasn't landed server-side yet. - const readTranscripts = vi.fn().mockResolvedValue(TRANSCRIPTS); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - expect(await screen.findByText(/Almost there/)).toBeInTheDocument(); - expect(screen.getByText('Updating…')).toBeInTheDocument(); // not falsely shown as Live... - expect(screen.queryByText('Needs review')).not.toBeInTheDocument(); // ...nor left showing "Needs review" as if nothing happened - expect(screen.getByText('Namaste.')).toBeInTheDocument(); // stayed on the language, didn't close - vi.unstubAllGlobals(); - }); - - it('treats a failed confirmation re-read as "still processing", not as an approve failure', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockResolvedValue({}); - // The approve write itself succeeds; only the follow-up confirm re-read hits a network blip. - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) // initial load - .mockRejectedValueOnce(new Error('network blip')); // confirm re-read after approve - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - await waitFor(() => expect(approveTranscript).toHaveBeenCalledWith('do_1', 't_hi')); - expect(await screen.findByText(/Almost there/)).toBeInTheDocument(); - expect(screen.queryByText("Couldn't complete this action. Please try again in a moment.")).not.toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Check again' })).toBeInTheDocument(); - vi.unstubAllGlobals(); - }); - - it('hides Approve/Reject while a just-submitted approve awaits confirmation - prevents a second, guaranteed-to-fail submit (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockResolvedValue({}); - // The approve itself succeeded server-side, but the confirm re-read hasn't caught up yet. - const readTranscripts = vi.fn().mockResolvedValue(TRANSCRIPTS); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - await screen.findByText(/Almost there/); - // Re-clicking Approve now would fail with ERR_TRANSCRIPT_NOT_IN_REVIEW, so it must be gone. - expect(screen.queryByRole('button', { name: 'Approve Transcript' })).not.toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Reject' })).not.toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Check again' })).toBeInTheDocument(); - expect(approveTranscript).toHaveBeenCalledTimes(1); - vi.unstubAllGlobals(); - }); - - it('confirms and closes once the user clicks "Check again" after a pending approve', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockResolvedValue({}); - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) - .mockResolvedValueOnce(TRANSCRIPTS) // confirm right after approve: still Review - .mockResolvedValueOnce(TRANSCRIPTS.map((tr) => (tr.language === 'Hindi' ? { ...tr, status: 'Live' } : tr))); // Check again: now Live - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - await screen.findByText(/Almost there/); - fireEvent.click(screen.getByRole('button', { name: 'Check again' })); - await waitFor(() => expect(readTranscripts).toHaveBeenCalledTimes(3)); - await screen.findByText('Hindi'); - await waitFor(() => expect(screen.getAllByText('Live')).toHaveLength(2)); - vi.unstubAllGlobals(); - }); - - it('surfaces an error (not an unhandled rejection) when "Check again" itself fails (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockResolvedValue({}); - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) - .mockResolvedValueOnce(TRANSCRIPTS) // confirm right after approve: still Review - .mockRejectedValueOnce(new Error('network blip')); // "Check again" click hits a network error - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - await screen.findByText(/Almost there/); - fireEvent.click(screen.getByRole('button', { name: 'Check again' })); - expect(await screen.findByText("Couldn't complete this action. Please try again in a moment.")).toBeInTheDocument(); - // Still recoverable - the retry action itself must survive its own failure. - expect(screen.getByRole('button', { name: 'Check again' })).not.toBeDisabled(); - vi.unstubAllGlobals(); - }); - - it('shows a plain retry message (not the raw backend errmsg) and stays on the language when approve fails (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockRejectedValue(new Error('ERR_TRANSCRIPT_NOT_IN_REVIEW')); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS), approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - expect(await screen.findByText(/Couldn't complete this action/)).toBeInTheDocument(); - expect(screen.queryByText('ERR_TRANSCRIPT_NOT_IN_REVIEW')).not.toBeInTheDocument(); - expect(screen.getByText('Namaste.')).toBeInTheDocument(); - vi.unstubAllGlobals(); - }); - - it('treats "currently Live" as success (not failure) when approve fails because it already landed - closes without an error, straight from the error text', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockRejectedValue(new Error('Transcript must be in Review status to approve (currently Live).')); - const readTranscripts = vi.fn().mockResolvedValue(TRANSCRIPTS); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - // Closes back to the language list instead of showing an error - the error text - // itself already proved the approve's goal (Live) was reached by something else. - await waitFor(() => expect(screen.queryByText('Namaste.')).not.toBeInTheDocument()); - await screen.findByText('Hindi'); - expect(screen.queryByText('Needs review')).not.toBeInTheDocument(); - expect(screen.queryByText(/Couldn't complete this action/)).not.toBeInTheDocument(); - await waitFor(() => expect(screen.getAllByText('Live')).toHaveLength(2)); // English (already) + Hindi (just synced) - // No extra network round-trip needed - the true status came straight from the error text. - expect(readTranscripts).toHaveBeenCalledTimes(1); - vi.unstubAllGlobals(); - }); - - it('treats "currently Draft" as success (not failure) when reject fails because it already landed', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const rejectTranscript = vi.fn().mockRejectedValue(new Error('Transcript must be in Review status to reject (currently Draft).')); - const readTranscripts = vi.fn().mockResolvedValue(TRANSCRIPTS); - const service = mockService({ readTranscripts, rejectTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Reject' })); - await waitFor(() => expect(screen.queryByText('Namaste.')).not.toBeInTheDocument()); - await screen.findByText('Hindi'); - expect(screen.queryByText(/Couldn't complete this action/)).not.toBeInTheDocument(); - expect(await screen.findByText('Draft')).toBeInTheDocument(); - expect(readTranscripts).toHaveBeenCalledTimes(1); - vi.unstubAllGlobals(); - }); - - it('still shows the retry error but syncs the badge from the error text when the real status is neither Live nor Draft (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockRejectedValue(new Error('Transcript must be in Review status to approve (currently Failed).')); - const readTranscripts = vi.fn().mockResolvedValue(TRANSCRIPTS); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - expect(await screen.findByText(/Couldn't complete this action/)).toBeInTheDocument(); - expect(screen.queryByText(/currently Failed/)).not.toBeInTheDocument(); - // Badge/buttons reflect the parsed status without any extra network call. - await waitFor(() => expect(screen.getByText('Failed')).toBeInTheDocument()); - expect(screen.queryByRole('button', { name: 'Approve Transcript' })).not.toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Reject' })).not.toBeInTheDocument(); - expect(readTranscripts).toHaveBeenCalledTimes(1); - vi.unstubAllGlobals(); - }); - - it('falls back to a fresh re-read when the error text has no parseable status (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const approveTranscript = vi.fn().mockRejectedValue(new Error('ERR_TRANSCRIPT_NOT_IN_REVIEW')); - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) - .mockResolvedValueOnce(TRANSCRIPTS.map((tr) => (tr.language === 'Hindi' ? { ...tr, status: 'Live' } : tr))); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getByRole('button', { name: 'Review' })); - await screen.findByText('Namaste.'); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - expect(await screen.findByText(/Couldn't complete this action/)).toBeInTheDocument(); - await waitFor(() => expect(readTranscripts).toHaveBeenCalledTimes(2)); - await waitFor(() => expect(screen.getByText('Live')).toBeInTheDocument()); - expect(screen.queryByText('Needs review')).not.toBeInTheDocument(); - vi.unstubAllGlobals(); - }); - - }); - - it('does not offer a "Generate transcript" action - only the checkbox-driven flow triggers it (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue([]) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('No transcripts yet'); - expect(screen.queryByRole('button', { name: 'Generate transcript' })).not.toBeInTheDocument(); - expect(service.createTranscript).not.toHaveBeenCalled(); + it('offers no approve, reject, modify or placeholder actions for any status (negative)', () => { + render(); + for (const name of ['Approve Transcript', 'Reject', 'Modify', 'Coming soon', 'Review', 'Edit']) { + expect(screen.queryByRole('button', { name })).not.toBeInTheDocument(); + } }); describe('segments view', () => { @@ -443,324 +87,52 @@ describe('', () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ start: 0, end: 2.5, text: 'Hello there.' }, { start: 2.5, end: 5, text: 'Welcome.' }] }), })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); + render(); + fireEvent.click(screen.getAllByRole('button', { name: 'View segments' })[0]); expect(await screen.findByText('Hello there.')).toBeInTheDocument(); expect(screen.getByText('Welcome.')).toBeInTheDocument(); expect(screen.getByText('0:00–0:02')).toBeInTheDocument(); expect(fetch).toHaveBeenCalledWith('https://x/en.json'); }); + it('renders segments read-only, with no textarea or edit/save controls (negative)', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hi.' }] }) })); + render(); + fireEvent.click(screen.getAllByRole('button', { name: 'View segments' })[0]); + await screen.findByText('Hi.'); + expect(screen.queryByRole('textbox')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument(); + }); + it('shows a load-error state when the JSON shape is unrecognized (negative)', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ unexpected: true }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); + render(); + fireEvent.click(screen.getAllByRole('button', { name: 'View segments' })[0]); expect(await screen.findByText("Couldn't load segments for this language.")).toBeInTheDocument(); }); it('shows a load-error state when the fetch itself fails (negative)', async () => { vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down'))); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); + render(); + fireEvent.click(screen.getAllByRole('button', { name: 'View segments' })[0]); expect(await screen.findByText("Couldn't load segments for this language.")).toBeInTheDocument(); }); it('returns to the language list via "Back to languages"', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hi.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); + render(); + fireEvent.click(screen.getAllByRole('button', { name: 'View segments' })[0]); await screen.findByText('Hi.'); fireEvent.click(screen.getByRole('button', { name: /Back to languages/ })); expect(await screen.findByText('English')).toBeInTheDocument(); expect(screen.queryByText('Hi.')).not.toBeInTheDocument(); }); - it('re-fetches the list when navigating back, so a status that changed while viewing segments isn\'t left stale', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hi.' }] }) })); - const readTranscripts = vi.fn() - .mockResolvedValueOnce(TRANSCRIPTS) - .mockResolvedValueOnce(TRANSCRIPTS.map((tr) => (tr.language === 'Hindi' ? { ...tr, status: 'Live' } : tr))); - const service = mockService({ readTranscripts }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); - await screen.findByText('Hi.'); - fireEvent.click(screen.getByRole('button', { name: /Back to languages/ })); - await waitFor(() => expect(readTranscripts).toHaveBeenCalledTimes(2)); - // Hindi (Review in the first fetch) now reflects the second fetch's Live status. - await screen.findByText('English'); - expect(await waitFor(() => screen.getAllByText('Live'))).toHaveLength(2); - }); - - it('does not offer "View segments" for a language with no artifactUrl (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - // Only English has artifactUrl in the fixture - exactly one "View segments" button. - expect(screen.getAllByRole('button', { name: 'View segments' })).toHaveLength(1); - }); - - describe('editing (source language, review status only)', () => { - // English is Live in the base fixture, so use a copy with its status set to Review. - const SOURCE_IN_REVIEW = TRANSCRIPTS.map((tr) => (tr.language === 'English' ? { ...tr, status: 'Review' } : tr)); - - it('shows a Modify button on the source-language card when it is in review, that opens segments straight into edit mode', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - expect(screen.queryByRole('button', { name: 'Modify' })).toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: 'Modify' })); - await screen.findByText('Hello there.'); - expect(screen.getByRole('textbox')).toHaveValue('Hello there.'); - }); - - it('does not show a Modify button for a non-source-language card (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - expect(screen.getAllByRole('button', { name: 'Modify' })).toHaveLength(1); - }); - - it('does not show a Modify button for a Live source-language card (negative)', async () => { - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - expect(screen.queryByRole('button', { name: 'Modify' })).not.toBeInTheDocument(); - }); - - it('shows an Edit button for a source-language transcript in review', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - expect(await screen.findByRole('button', { name: 'Edit' })).toBeInTheDocument(); - }); - - it('does not show an Edit button for a non-source-language transcript (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('Hindi'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[1]); - await screen.findByText('Namaste.'); - expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument(); - }); - - it('does not show an Edit button for a Live source-language transcript (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(TRANSCRIPTS) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getByRole('button', { name: 'View segments' })); - await screen.findByText('Hello there.'); - expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument(); - }); - - it('hides Edit while an approve is pending confirmation, even though activeLang.status is still stale "Review" (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const SOURCE_IN_REVIEW = TRANSCRIPTS.map((tr) => (tr.language === 'English' ? { ...tr, status: 'Review' } : tr)); - const approveTranscript = vi.fn().mockResolvedValue({}); - // Confirm re-read still reports Review - approve hasn't landed server-side yet. - const readTranscripts = vi.fn().mockResolvedValue(SOURCE_IN_REVIEW); - const service = mockService({ readTranscripts, approveTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - expect(screen.getByRole('button', { name: 'Edit' })).toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: 'Approve Transcript' })); - await screen.findByText(/Almost there/); - // Edit must disappear here - clicking it now would let the user start editing - // a transcript that's actually already Live, and Save would fail server-side. - expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument(); - }); - - it('turns segment text into an editable, pre-filled textarea after clicking Edit', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - const textbox = screen.getByRole('textbox') as HTMLTextAreaElement; - expect(textbox.value).toBe('Hello there.'); - fireEvent.change(textbox, { target: { value: 'Hello world.' } }); - expect(textbox.value).toBe('Hello world.'); - }); - - it('saves the full edited segment list via updateTranscript(contentId, transcriptId, segments)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ - json: async () => ({ segments: [{ id: 0, start: 0, end: 2.5, text: 'Hello there.' }, { id: 1, text: 'Bye.' }] }), - })); - const updateTranscript = vi.fn().mockResolvedValue({}); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW), updateTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - fireEvent.change(screen.getAllByRole('textbox')[0], { target: { value: 'Corrected text here' } }); - fireEvent.click(screen.getByRole('button', { name: 'Save' })); - await waitFor(() => expect(updateTranscript).toHaveBeenCalledWith('do_1', 't_en', [ - { id: 0, start: 0, end: 2.5, text: 'Corrected text here' }, - { id: 1, text: 'Bye.', start: undefined, end: undefined }, - ])); - }); - - it('preserves fields the parser does not model (e.g. Whisper seek/tokens) through an edit and save, changing only the edited text', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ - json: async () => ({ - segments: [{ id: 0, start: 0, end: 2.5, text: 'Hello there.', seek: 400, tokens: [1, 2, 3], avg_logprob: -0.2 }], - }), - })); - const updateTranscript = vi.fn().mockResolvedValue({}); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW), updateTranscript }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Corrected text here' } }); - fireEvent.click(screen.getByRole('button', { name: 'Save' })); - await waitFor(() => expect(updateTranscript).toHaveBeenCalledWith('do_1', 't_en', [ - { id: 0, start: 0, end: 2.5, text: 'Corrected text here', seek: 400, tokens: [1, 2, 3], avg_logprob: -0.2 }, - ])); - }); - - it('a slow fetch for a language the user has since left cannot land its segments onto the one now open (openSegments race guard)', async () => { - let resolveEnglish: (v: unknown) => void = () => {}; - const englishPromise = new Promise((resolve) => { resolveEnglish = resolve; }); - const fetchMock = vi.fn((url: string) => { - if (url === 'https://x/en.json') return englishPromise; - if (url === 'https://x/hi.json') return Promise.resolve({ json: async () => ({ segments: [{ text: 'Namaste.' }] }) }); - return Promise.reject(new Error(`unexpected url: ${url}`)); - }); - vi.stubGlobal('fetch', fetchMock); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - - // Start English's (slow) fetch, then leave before it resolves. - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('English', { selector: '.ce-transcript-segments-title' }); - fireEvent.click(screen.getByRole('button', { name: /Back to languages/ })); - // Back to languages now re-fetches the list - wait for it to land before continuing. - await screen.findAllByRole('button', { name: 'Review' }); - - // Open Hindi - its (fast) fetch resolves first. - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[1]); - await screen.findByText('Namaste.'); - - // English's slow fetch finally resolves - it must not overwrite Hindi's segments. - await act(async () => { - resolveEnglish({ json: async () => ({ segments: [{ text: 'English text that must not appear.' }] }) }); - await new Promise((r) => setTimeout(r, 0)); - await new Promise((r) => setTimeout(r, 0)); - }); - expect(screen.queryByText('English text that must not appear.')).not.toBeInTheDocument(); - expect(screen.getByText('Namaste.')).toBeInTheDocument(); - expect(screen.getByText('Hindi', { selector: '.ce-transcript-segments-title' })).toBeInTheDocument(); - vi.unstubAllGlobals(); - }); - - it('exits edit mode and shows the saved text after a successful save', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ id: 0, text: 'Hello there.' }] }) })); - const service = mockService({ - readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW), - updateTranscript: vi.fn().mockResolvedValue({}), - }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Corrected text here' } }); - fireEvent.click(screen.getByRole('button', { name: 'Save' })); - await waitFor(() => expect(screen.getByText('Corrected text here')).toBeInTheDocument()); - expect(screen.queryByRole('textbox')).not.toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Edit' })).toBeInTheDocument(); - }); - - it('shows an error and stays in edit mode when the save fails (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ id: 0, text: 'Hello there.' }] }) })); - const service = mockService({ - readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW), - updateTranscript: vi.fn().mockRejectedValue(new Error('Save failed')), - }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Corrected text here' } }); - fireEvent.click(screen.getByRole('button', { name: 'Save' })); - expect(await screen.findByText('Save failed')).toBeInTheDocument(); - expect(screen.getByRole('textbox')).toBeInTheDocument(); - }); - - it('discards edits and returns to read-only text on Cancel', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Edited text.' } }); - fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); - expect(screen.getByText('Hello there.')).toBeInTheDocument(); - expect(screen.queryByText('Edited text.')).not.toBeInTheDocument(); - expect(screen.queryByRole('textbox')).not.toBeInTheDocument(); - }); - - it('does not leak edit mode when re-opening segments after Back to languages (negative)', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => ({ segments: [{ text: 'Hello there.' }] }) })); - const service = mockService({ readTranscripts: vi.fn().mockResolvedValue(SOURCE_IN_REVIEW) }); - const ed = makeEd({ drawer: 'transcripts', service }); - render(); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - fireEvent.click(screen.getByRole('button', { name: 'Edit' })); - expect(screen.getByRole('textbox')).toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: /Back to languages/ })); - await screen.findByText('English'); - fireEvent.click(screen.getAllByRole('button', { name: 'Review' })[0]); - await screen.findByText('Hello there.'); - expect(screen.queryByRole('textbox')).not.toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Edit' })).toBeInTheDocument(); - }); + it('offers "View segments" only for languages that have an artifactUrl (negative)', () => { + render(); + // English and Hindi have artifactUrl in the fixture; Tamil and Telugu do not. + expect(screen.getAllByRole('button', { name: 'View segments' })).toHaveLength(2); }); }); }); diff --git a/src/components/TranscriptsDrawer.tsx b/src/components/TranscriptsDrawer.tsx index be463a0..15eb209 100644 --- a/src/components/TranscriptsDrawer.tsx +++ b/src/components/TranscriptsDrawer.tsx @@ -5,22 +5,12 @@ import type { RawTranscript, TranscriptSegment } from '../types'; import { t, tf } from '../i18n/i18n'; import { CaptionsIcon } from '../icons'; -interface ParsedSegments { - /** Display/editing view - only the fields the UI needs. */ - segments: TranscriptSegment[]; - /** The original segment objects, index-aligned with `segments`, kept around so a save - * can merge just the edited text back in rather than reconstructing (and thereby losing - * any field the parser doesn't know about, e.g. Whisper's seek/tokens/avg_logprob/...). */ - rawSegments: Record[]; -} - -/** Parses the artifactUrl transcript.json (Whisper-style `{segments:[...]}` or a bare array), returning null on any other shape. `rawSegments[i]` corresponds to `segments[i]` (a segment dropped for a non-string `text` is dropped from both, in lockstep). */ -function parseSegments(raw: unknown): ParsedSegments | null { +/** Parses the artifactUrl transcript.json (Whisper-style `{segments:[...]}` or a bare array), returning null on any other shape. */ +function parseSegments(raw: unknown): TranscriptSegment[] | null { const obj = raw as Record | null; const list = Array.isArray(raw) ? raw : Array.isArray(obj?.segments) ? (obj!.segments as unknown[]) : null; if (!list) return null; const segments: TranscriptSegment[] = []; - const rawSegments: Record[] = []; list.forEach((item, index) => { const o = item as Record; const text = o.text ?? o.transcript ?? o.content; @@ -33,9 +23,8 @@ function parseSegments(raw: unknown): ParsedSegments | null { start: typeof start === 'number' ? start : undefined, end: typeof end === 'number' ? end : undefined, }); - rawSegments.push(o); }); - return segments.length ? { segments, rawSegments } : null; + return segments.length ? segments : null; } function formatTimestamp(seconds?: number): string { @@ -45,15 +34,6 @@ function formatTimestamp(seconds?: number): string { return `${m}:${String(s).padStart(2, '0')}`; } -/** The five backend-confirmed transcript statuses: Draft, Processing, Review, Live, Failed. */ -const KNOWN_STATUSES = ['Draft', 'Processing', 'Review', 'Live', 'Failed']; - -/** Extracts the real status from the approve/reject error text (e.g. "currently Live"), which is more reliable than a follow-up re-read that can come back stale. */ -function parseCurrentStatusFromError(message: string): string | null { - const found = /currently\s+(\w+)/i.exec(message)?.[1]; - return found ? KNOWN_STATUSES.find((s) => s.toLowerCase() === found.toLowerCase()) ?? null : null; -} - type StatusTone = 'draft' | 'review' | 'processing' | 'live' | 'failed'; function statusTone(status?: string): StatusTone { @@ -95,246 +75,37 @@ function relativeTime(lang: string, iso?: string): string { return tf(lang, days === 1 ? 'TIME_DAY_AGO' : 'TIME_DAYS_AGO', { n: days }); } -/** TranscriptsDrawer — views/approves/rejects/edits content.enrichment.transcripts, fetched on open via a dedicated ?enrich=all read to avoid that cost elsewhere. */ +/** TranscriptsDrawer — read-only view of the transcripts held by the editor controller (`ed.transcripts`). */ const TranscriptsDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { - const { lang, drawer, setDrawer, content, service, showToast } = ed; + const { lang, drawer, setDrawer, transcripts } = ed; const open = drawer === 'transcripts'; - const [transcripts, setTranscripts] = useState([]); - const [loading, setLoading] = useState(false); - const [loadError, setLoadError] = useState(null); - /* Segments sub-view for one language. */ const [activeLang, setActiveLang] = useState(null); const [segments, setSegments] = useState(null); - const [rawSegments, setRawSegments] = useState[] | null>(null); const [segmentsLoading, setSegmentsLoading] = useState(false); const [segmentsError, setSegmentsError] = useState(false); /** Bumped by openSegments/closeSegments so a slow fetch for a language the user has * already navigated away from can't land its result onto the wrong (now-active) one. */ const segmentsRequestRef = useRef(0); - /* Source-language segments can be edited (text only). */ - const [isEditingSegments, setIsEditingSegments] = useState(false); - const [draftSegments, setDraftSegments] = useState(null); - const [isSaving, setIsSaving] = useState(false); - const [saveError, setSaveError] = useState(null); - - /* Approve/reject applies asynchronously server-side, so we re-read and only show the new status once confirmed. */ - const [isApproving, setIsApproving] = useState(false); - const [isRejecting, setIsRejecting] = useState(false); - const [isCheckingStatus, setIsCheckingStatus] = useState(false); - const [actionError, setActionError] = useState(null); - const [pendingExpectedStatus, setPendingExpectedStatus] = useState(null); - - const load = () => { - if (!content?.identifier) return; - setLoading(true); - setLoadError(null); - service - .readTranscripts(content.identifier) - .then(setTranscripts) - .catch((err) => { - setTranscripts([]); - // Distinct from a genuinely-empty result - don't let a failed read masquerade as "no transcripts yet". - setLoadError(String((err as Error)?.message ?? t(lang, 'ERROR_GENERIC'))); - }) - .finally(() => setLoading(false)); - }; - const closeSegments = () => { segmentsRequestRef.current += 1; // discard any in-flight fetch for the language we're leaving setActiveLang(null); setSegments(null); - setRawSegments(null); setSegmentsError(false); - setIsEditingSegments(false); - setDraftSegments(null); - setSaveError(null); - setActionError(null); - setPendingExpectedStatus(null); - }; - - /** "Back to languages" click handler - unlike closeSegments() alone (also used right after - * an already-fresh confirmed approve/reject), this re-fetches so manually navigating back - * without a confirmed action doesn't leave the list showing a stale, out-of-date status. */ - const backToLanguages = () => { - closeSegments(); - load(); - }; - - /** Single re-read to check whether an approve/reject has actually landed - - * updates the loaded list only when it truly matches, never assumes it. */ - const confirmTranscriptStatus = (transcriptId: string, expectedStatus: string): Promise => { - if (!content?.identifier) return Promise.resolve(false); - return service.readTranscripts(content.identifier).then((list) => { - const match = list.find((tr) => (tr.identifier ?? tr.code) === transcriptId); - if (match?.status === expectedStatus) { - setTranscripts(list); - return true; - } - return false; - }); - }; - - /** Re-syncs activeLang from the server when approve/reject itself fails, so the badge reflects the real status instead of contradicting the error below it. */ - const refreshActiveLangFromServer = (transcriptId: string): Promise => { - if (!content?.identifier) return Promise.resolve(); - return service.readTranscripts(content.identifier).then((list) => { - setTranscripts(list); - const fresh = list.find((tr) => (tr.identifier ?? tr.code) === transcriptId); - if (fresh) setActiveLang(fresh); - }); - }; - - /** Apply a status we already know for certain (parsed from an error, not a re-read) - * to both the list and the open segments view, without waiting on the network. */ - const applyKnownStatus = (transcriptId: string, status: string) => { - setTranscripts((list) => list.map((tr) => ((tr.identifier ?? tr.code) === transcriptId ? { ...tr, status } : tr))); - setActiveLang((prev) => (prev && (prev.identifier ?? prev.code) === transcriptId ? { ...prev, status } : prev)); - }; - - const startEditingSegments = () => { - if (!segments || !activeLang) return; - // Editing is only allowed while a transcript is genuinely in Review - a Live - // transcript is the published caption, so surface why instead of silently no-oping. - if (activeLang.status === 'Live') { - showToast(t(lang, 'ERROR_TRANSCRIPT_LIVE'), 'error'); - return; - } - if (activeLang.status !== 'Review') return; - setDraftSegments(segments.map((s) => ({ ...s }))); - setIsEditingSegments(true); - setSaveError(null); - }; - - const cancelEditingSegments = () => { - setIsEditingSegments(false); - setDraftSegments(null); - setSaveError(null); - }; - - const updateDraftSegmentText = (index: number, text: string) => { - setDraftSegments((prev) => (prev ? prev.map((s, i) => (i === index ? { ...s, text } : s)) : prev)); - }; - - const saveSegments = () => { - const transcriptId = activeLang?.identifier ?? activeLang?.code; - if (!draftSegments || !rawSegments || !content?.identifier || !transcriptId) return; - setIsSaving(true); - setSaveError(null); - // Merge only the edited text back into the original segment objects (index-aligned - // with draftSegments) instead of sending the reconstructed {id,text,start,end} view - - // any field the parser doesn't surface (Whisper's seek/tokens/avg_logprob/...) survives. - const merged = rawSegments.map((raw, i) => ({ ...raw, text: draftSegments[i]?.text ?? raw.text })); - service - .updateTranscript(content.identifier, transcriptId, merged) - .then(() => { - setSegments(draftSegments); - setRawSegments(merged); - setIsEditingSegments(false); - setDraftSegments(null); - }) - .catch((err) => { - setSaveError(String((err as Error)?.message ?? t(lang, 'ERROR_GENERIC'))); - }) - .finally(() => setIsSaving(false)); - }; - - const handleApprove = () => { - const transcriptId = activeLang?.identifier ?? activeLang?.code; - if (!activeLang || !content?.identifier || !transcriptId) return; - setIsApproving(true); - setActionError(null); - setPendingExpectedStatus(null); - service - .approveTranscript(content.identifier, transcriptId) - // A failed confirm re-read must not be reported as an approve failure - the - // approve itself already landed, so treat it the same as "not confirmed yet". - .then(() => confirmTranscriptStatus(transcriptId, 'Live').catch(() => false)) - .then((confirmed) => { - if (confirmed) closeSegments(); - else { - setActionError(t(lang, 'STATUS_UPDATE_PENDING')); - setPendingExpectedStatus('Live'); - } - }) - .catch((err) => { - const realStatus = parseCurrentStatusFromError(String((err as Error)?.message ?? '')); - if (realStatus) { - // Trust the error's own status over a re-read that may come back stale. - applyKnownStatus(transcriptId, realStatus); - if (realStatus === 'Live') { closeSegments(); return; } - setActionError(t(lang, 'ERROR_TRANSCRIPT_ACTION_FAILED')); - return; - } - // Unparseable error - re-sync from the server instead of surfacing a raw errmsg that could contradict the badge. - setActionError(t(lang, 'ERROR_TRANSCRIPT_ACTION_FAILED')); - return refreshActiveLangFromServer(transcriptId).catch(() => {}); - }) - .finally(() => setIsApproving(false)); - }; - - const handleReject = () => { - const transcriptId = activeLang?.identifier ?? activeLang?.code; - if (!activeLang || !content?.identifier || !transcriptId) return; - setIsRejecting(true); - setActionError(null); - setPendingExpectedStatus(null); - service - .rejectTranscript(content.identifier, transcriptId) - // Same reasoning as handleApprove: a failed confirm re-read isn't a reject failure. - .then(() => confirmTranscriptStatus(transcriptId, 'Draft').catch(() => false)) - .then((confirmed) => { - if (confirmed) closeSegments(); - else { - setActionError(t(lang, 'STATUS_UPDATE_PENDING')); - setPendingExpectedStatus('Draft'); - } - }) - .catch((err) => { - const realStatus = parseCurrentStatusFromError(String((err as Error)?.message ?? '')); - if (realStatus) { - applyKnownStatus(transcriptId, realStatus); - if (realStatus === 'Draft') { closeSegments(); return; } - setActionError(t(lang, 'ERROR_TRANSCRIPT_ACTION_FAILED')); - return; - } - setActionError(t(lang, 'ERROR_TRANSCRIPT_ACTION_FAILED')); - return refreshActiveLangFromServer(transcriptId).catch(() => {}); - }) - .finally(() => setIsRejecting(false)); - }; - - const handleRecheckStatus = () => { - const transcriptId = activeLang?.identifier ?? activeLang?.code; - if (!activeLang || !transcriptId || !pendingExpectedStatus) return; - setIsCheckingStatus(true); - confirmTranscriptStatus(transcriptId, pendingExpectedStatus) - .then((confirmed) => { - if (confirmed) closeSegments(); - else setActionError(t(lang, 'STATUS_UPDATE_PENDING')); - }) - .catch(() => setActionError(t(lang, 'ERROR_TRANSCRIPT_ACTION_FAILED'))) - .finally(() => setIsCheckingStatus(false)); }; useEffect(() => { - if (!open) { closeSegments(); return; } - load(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [open, content?.identifier]); + if (!open) closeSegments(); + }, [open, ed.content?.identifier]); - const openSegments = (tr: RawTranscript, startInEditMode = false) => { + const openSegments = (tr: RawTranscript) => { if (!tr.artifactUrl) return; const requestToken = ++segmentsRequestRef.current; setActiveLang(tr); setSegments(null); - setRawSegments(null); setSegmentsError(false); - setIsEditingSegments(false); - setDraftSegments(null); - setSaveError(null); setSegmentsLoading(true); fetch(tr.artifactUrl) .then((r) => r.json()) @@ -344,119 +115,41 @@ const TranscriptsDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { if (segmentsRequestRef.current !== requestToken) return; const parsed = parseSegments(json); if (!parsed) { setSegmentsError(true); return; } - setSegments(parsed.segments); - setRawSegments(parsed.rawSegments); - if (startInEditMode) { - setDraftSegments(parsed.segments.map((s) => ({ ...s }))); - setIsEditingSegments(true); - } + setSegments(parsed); }) .catch(() => { if (segmentsRequestRef.current === requestToken) setSegmentsError(true); }) .finally(() => { if (segmentsRequestRef.current === requestToken) setSegmentsLoading(false); }); }; - const handleModifyClick = (tr: RawTranscript) => { - // Editing is only allowed while a transcript is genuinely in Review - a Live - // transcript is the published caption, so surface why instead of silently no-oping. - if (tr.status === 'Live') { - showToast(t(lang, 'ERROR_TRANSCRIPT_LIVE'), 'error'); - return; - } - if (tr.status !== 'Review') return; - openSegments(tr, true); - }; - const renderSegmentsView = () => { const tone = statusTone(activeLang!.status); - // Editable only for a source-language transcript still in Review, and not while - // pendingExpectedStatus is set (activeLang.status is stale until the confirm re-read lands). - const canShowEditControls = - activeLang!.sourceLanguage && activeLang!.status === 'Review' && !pendingExpectedStatus && - !segmentsLoading && !segmentsError && !!segments; - const displaySegments = isEditingSegments ? draftSegments : segments; return (
-
{activeLang!.language}
- {pendingExpectedStatus ? ( - // Once the user has acted, don't keep showing "Needs review" (as if nothing - // happened) while we wait for the server to catch up - show a neutral pending state instead. - - {t(lang, 'STATUS_UPDATING')} - - ) : ( - - {statusLabel(lang, activeLang!.status)} - - )} + + {statusLabel(lang, activeLang!.status)} +
- {tone === 'review' && !isEditingSegments && !pendingExpectedStatus && ( -
- - -
- )} - {actionError && ( -
-

{actionError}

- {pendingExpectedStatus && ( - - )} -
- )} - {canShowEditControls && ( -
- {isEditingSegments ? ( - <> - - - - ) : ( - - )} -
- )} - {saveError &&

{saveError}

} {segmentsLoading ? (
- ) : segmentsError || !displaySegments ? ( + ) : segmentsError || !segments ? (

{t(lang, 'SEGMENTS_LOAD_ERROR')}

) : (
- {displaySegments.map((seg, i) => ( + {segments.map((seg, i) => (
{(seg.start != null || seg.end != null) && ( {formatTimestamp(seg.start)}{seg.end != null ? `–${formatTimestamp(seg.end)}` : ''} )} - {isEditingSegments ? ( -