diff --git a/docs/TASKS.md b/docs/TASKS.md index b34df6b..0a2cd9b 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -31,7 +31,7 @@ Statuses: done (PR merged) · doing (branch open, pending review) · remaining | ID | Task | Branch | Verification | Status | |---|---|---|---|---| -| _(empty)_ | | | | | +| T3.1 | App shell + input + voice + generate | `arch/tts/t3.1` | 51 Vitest (17 new); ESLint; `tsc --noEmit`; Prettier (CRLF); live + mock Vite builds; mock-mode Chromium check (AC3/AC4/AC6, upload, preview playback, generate→succeeded, cancel); 196 pytest; Ruff check/format; strict mypy; `git diff --check` | Awaiting PR review | ## Remaining @@ -45,15 +45,12 @@ _All P1 tasks done._ ### P2 — HTTP surface -| ID | Task | Files | Deps | Acceptance criteria (summary) | -|---|---|---|---|---| -| T2.1 | Uploads + voices routes | `src/tts/api/routes/uploads.py`, `voices.py` | T0.3, T1.1 | Upload validation, preview WAV, no-voice response | +_All P2 tasks done._ ### P3 — UI against contracts | ID | Task | Files | Deps | Acceptance criteria (summary) | |---|---|---|---|---| -| T3.1 | App shell + input + voice + generate | `frontend/src/App.tsx`, components, state wiring | T0.5 | Input/upload, validation, settings ranges, voice preview, no-voice guidance | | T3.2 | Playback + downloads | `frontend/src/` playback components and hook | T0.5 | Highlight/seek/reset behavior and correctly named downloads | | T3.3 | History | `frontend/src/` history component | T0.5 | History preview, restore, and individual deletion | @@ -124,3 +121,8 @@ _All P1 tasks done._ - T2.2 SSE: sends `RETRY_LINE` once, then `subscriber.events()` frames until the terminal event; `Cache-Control: no-cache` and `X-Accel-Buffering: no` mitigate R6. No explicit unsubscribe on client disconnect — the manager closes the subscriber queue at the terminal event, so no stream registration leaks. Unknown ids (malformed or well-formed) are 404 before the stream opens. - T2.2 test layout: `tests/unit/test_api_generations_routes.py` and `tests/integration/test_api_generations_flow.py` (unique basenames; see the T1.2 note). Unit tests use a fake job manager with a real DAL so no engine is imported; the integration test runs a real generation against `en_US-lessac-medium` and verifies SSE replay, detail, WAV, SRT/VTT, and delete. - T2.3 scope resolution: expanded §14.2 to include app lifespan/service wiring, CLI serving and voice installation, and persisted default-voice responses in health and voice-list routes; the tracker note had assigned startup wiring to T2.3 while the original owned-file list omitted it. `jobs.manager.bootstrap` already existed from T1.6 and is reused. Unit tests disable automatic bootstrap except for the explicit offline-startup case. On this Windows checkout, `npm run format:check` assumes LF while tracked frontend files are checked out as CRLF (`core.autocrlf=true`); `npm run format:check -- --end-of-line crlf` passes without changing files. +- T3.1 decisions: `App.tsx` bootstraps `listVoices` + `getSettings` on mount and applies the persisted default voice, rate, and volume through the existing §12 actions (no new reducer actions; `appContext.tsx` untouched). Local pre-flight validation lives in the new T3.1-owned `components/validation.ts`: empty/whitespace → `EMPTY_INPUT` without a request, >50,000 chars → `INPUT_TOO_LONG`, no selected voice → `NO_VOICES_INSTALLED`. `MAX_INPUT_CHARS` mirrors §11's default because §9 does not expose the server's configured limit; the server remains authoritative. Sliders clamp into §9.2 ranges (`clampRate`, `clampVolume`) and show numeric values. +- T3.1 settings persistence: §12 assigns `putSettings` on blur to `VoicePanel`, so T3.1 implements it and loads persisted settings on mount; §14.2's T4.1 wording "settings persistence" is reduced to live-mode verification. Live persistence is unverified here because the mock API resets on reload. +- T3.1 downstream contract (T3.2): `GenerateBar` owns the only SSE subscription and sets `current.audioUrl` after fetching the detail + audio blob. If the blob fetch fails after a `succeeded` event (or the detail fetch fails), the current entry is unlocked with `audioUrl`/`detail` absent and an error banner is shown, so `PlaybackPanel` must render a ready-state message instead of assuming audio exists. T3.3's history restore should load detail + audio via `SELECT_HISTORY_ITEM` without opening a stream. +- T3.1 testing: no jsdom/Testing Library was added (§5 lists vitest only). 17 new Vitest tests cover validation/clamping and static markup (no-voice explanation, control ranges, section order); AC3, AC4, AC6, text upload, preview playback, generate→succeeded, and cancel were verified in mock mode with a temporary headless-Chromium Playwright script (removed after the run, not committed). +- T3.1 shared-file note: `styles.css` (created by T0.5, not assigned to a later task) received additive form/progress styles; `components/validation.ts` is a new T3.1-owned helper module not listed in §6's frontend tree. The P2 "remaining" table was already marked done in an uncommitted edit at task start; it was kept because it matches T2.3's merged state. diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsx index 4f1e06c..4f938b9 100644 --- a/frontend/src/App.test.tsx +++ b/frontend/src/App.test.tsx @@ -11,7 +11,7 @@ function renderApp(): string { ); } -describe("App placeholder", () => { +describe("App shell", () => { it("renders the section stack in the documented order", () => { const html = renderApp(); const headings = [ @@ -26,6 +26,16 @@ describe("App placeholder", () => { expect([...positions].sort((a, b) => a - b)).toEqual(positions); }); + it("renders the input, voice, and generate controls", () => { + const html = renderApp(); + expect(html).toContain('id="input-text"'); + expect(html).toContain('accept=".txt,text/plain"'); + expect(html).toContain('id="voice-select"'); + expect(html).toContain('id="rate-slider"'); + expect(html).toContain('id="volume-slider"'); + expect(html).toMatch(/]*disabled[^>]*>Generate audio<\/button>/); + }); + it("shows the no-voice state and empty history", () => { const html = renderApp(); expect(html).toContain("No voices installed"); diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 96abc5e..d9d0057 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,16 +1,64 @@ /** - * Placeholder shell for the single page (ARCHITECTURE.md section 12). + * Single page layout (ARCHITECTURE.md section 12). * - * Sections are laid out in their final order so the component tasks (T3.1–T3.3) - * can replace each one without moving the page furniture. + * Sections stack in their documented order. The playback and history sections + * stay as placeholders until T3.2/T3.3 replace them, so each task can own its + * own component file. */ -import { apiMode } from "./api"; +import { useEffect } from "react"; +import { api, apiMode } from "./api"; +import { toApiError } from "./api/client"; +import { ErrorBanner } from "./components/ErrorBanner"; +import { GenerateBar } from "./components/GenerateBar"; +import { InputPanel } from "./components/InputPanel"; +import { VoicePanel } from "./components/VoicePanel"; +import { clampRate, clampVolume } from "./components/validation"; import { useApp } from "./state/appContext"; export function App() { - const { state } = useApp(); - const selectedVoice = state.voices.find((voice) => voice.id === state.selectedVoiceId); + const { state, dispatch } = useApp(); + + useEffect(() => { + let cancelled = false; + + async function bootstrap(): Promise { + try { + const list = await api.listVoices(); + if (cancelled) { + return; + } + dispatch({ type: "VOICES_LOADED", voices: list.items }); + if (list.items.some((voice) => voice.id === list.defaultVoiceId)) { + dispatch({ type: "SET_VOICE", voiceId: list.defaultVoiceId }); + } + + const settings = await api.getSettings(); + if (cancelled) { + return; + } + dispatch({ type: "SET_RATE", rate: clampRate(settings.rate) }); + dispatch({ type: "SET_VOLUME", volume: clampVolume(settings.volume) }); + if (list.items.some((voice) => voice.id === settings.defaultVoiceId)) { + dispatch({ type: "SET_VOICE", voiceId: settings.defaultVoiceId }); + } + } catch (error) { + if (cancelled) { + return; + } + const failure = toApiError(error); + dispatch({ + type: "SET_ERROR", + error: { code: failure.code, message: failure.message, details: failure.details }, + }); + } + } + + void bootstrap(); + return () => { + cancelled = true; + }; + }, [dispatch]); return (
@@ -20,48 +68,10 @@ export function App() { {apiMode === "mock" ?

Mock mode: sample data

: null} - {state.error !== null && ( -
-

Something went wrong

-

{state.error.message}

-
- )} - -
-

Text

-

Paste text or upload a .txt file for review.

-

- {state.inputText.length.toLocaleString()} characters - {state.sourceFilename === null ? "" : ` · ${state.sourceFilename}`} -

-
- -
-

Voice and settings

-

Choose an installed voice, preview it, and set rate and volume.

-

- {state.voices.length === 0 - ? "No voices installed" - : `${state.voices.length} voice${state.voices.length === 1 ? "" : "s"} · ${ - selectedVoice?.name ?? "none selected" - }`} -

-

- Rate {state.rate.toFixed(1)}× · Volume {Math.round(state.volume * 100)}% -

-
- -
-

Generate

-

Start, watch progress, and cancel a generation.

-

- {state.current === null - ? "Nothing generated yet" - : `${state.current.status} · sentence ${state.current.sentenceIndex} of ${ - state.current.sentenceCount - }`} -

-
+ + + +

Playback and subtitles

diff --git a/frontend/src/components/ErrorBanner.tsx b/frontend/src/components/ErrorBanner.tsx new file mode 100644 index 0000000..01c1c93 --- /dev/null +++ b/frontend/src/components/ErrorBanner.tsx @@ -0,0 +1,32 @@ +/** + * Single error surface for the whole page (ARCHITECTURE.md section 16: every + * frontend error goes through here with its message and corrective action). + */ + +import { useApp } from "../state/appContext"; + +export function ErrorBanner() { + const { state, dispatch } = useApp(); + + if (state.error === null) { + return null; + } + + return ( +
+
+

Something went wrong

+ +
+

{state.error.message}

+
+ ); +} diff --git a/frontend/src/components/GenerateBar.test.tsx b/frontend/src/components/GenerateBar.test.tsx new file mode 100644 index 0000000..41d28f7 --- /dev/null +++ b/frontend/src/components/GenerateBar.test.tsx @@ -0,0 +1,28 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { AppProvider } from "../state/appContext"; +import { GenerateBar } from "./GenerateBar"; + +function renderBar(): string { + return renderToStaticMarkup( + + + , + ); +} + +describe("GenerateBar", () => { + it("disables generation with an install explanation when there are no voices", () => { + const html = renderBar(); + expect(html).toMatch(/]*disabled[^>]*>Generate audio<\/button>/); + expect(html).toContain("No voices installed, so generation is disabled."); + expect(html).toContain("tts add-voice"); + expect(html).not.toContain("Cancel generation"); + }); + + it("starts from the empty state without a progress bar", () => { + const html = renderBar(); + expect(html).toContain("Nothing generated yet"); + expect(html).not.toContain(" 0 + ? `Generating: ${current.sentenceIndex} of ${current.sentenceCount} sentences done.` + : "Generating…"; + case "cancelling": + return "Cancelling…"; + case "succeeded": + return current.detail === undefined + ? "Finished, but the details could not be loaded. Check the message above." + : "Audio ready."; + case "failed": + return "Generation failed. See the message above."; + case "cancelled": + return "Generation cancelled. No audio was saved."; + } +} + +function isActive(current: CurrentGeneration | null): boolean { + return ( + current !== null && + (current.status === "queued" || current.status === "running" || current.status === "cancelling") + ); +} + +export function GenerateBar() { + const { state, dispatch } = useApp(); + const closeStreamRef = useRef<(() => void) | null>(null); + const audioUrlRef = useRef(null); + const currentIdRef = useRef(null); + const progressRef = useRef({ sentenceIndex: 0, sentenceCount: 0 }); + const current = state.current; + + useEffect(() => { + currentIdRef.current = current?.id ?? null; + progressRef.current = { + sentenceIndex: current?.sentenceIndex ?? 0, + sentenceCount: current?.sentenceCount ?? 0, + }; + }, [current]); + + useEffect(() => { + return () => { + closeStreamRef.current?.(); + closeStreamRef.current = null; + if (audioUrlRef.current !== null) { + URL.revokeObjectURL(audioUrlRef.current); + audioUrlRef.current = null; + } + }; + }, []); + + function closeStream(): void { + closeStreamRef.current?.(); + closeStreamRef.current = null; + } + + function releaseAudio(): void { + if (audioUrlRef.current !== null) { + URL.revokeObjectURL(audioUrlRef.current); + audioUrlRef.current = null; + } + } + + function dispatchFailure(error: unknown): void { + const failure = toApiError(error); + dispatch({ + type: "SET_ERROR", + error: { code: failure.code, message: failure.message, details: failure.details }, + }); + } + + async function loadResult(generationId: string): Promise { + let detail: GenerationDetail; + try { + detail = await api.getGeneration(generationId); + } catch (error) { + dispatchFailure(error); + if (currentIdRef.current === generationId) { + dispatch({ + type: "GENERATION_PROGRESS", + id: generationId, + status: "succeeded", + ...progressRef.current, + }); + } + return; + } + + let audioUrl: string | undefined; + try { + const blob = await api.getAudioBlob(generationId); + if (currentIdRef.current !== generationId) { + return; + } + audioUrl = URL.createObjectURL(blob); + } catch (error) { + dispatchFailure(error); + } + + if (currentIdRef.current !== generationId) { + if (audioUrl !== undefined) { + URL.revokeObjectURL(audioUrl); + } + return; + } + if (audioUrl !== undefined) { + releaseAudio(); + audioUrlRef.current = audioUrl; + } + dispatch({ type: "GENERATION_SUCCEEDED", id: generationId, detail, audioUrl }); + } + + async function handleStreamEvent(event: GenerationStreamEvent): Promise { + switch (event.type) { + case "progress": + dispatch({ + type: "GENERATION_PROGRESS", + id: event.payload.generationId, + status: event.payload.status, + sentenceIndex: event.payload.sentenceIndex, + sentenceCount: event.payload.sentenceCount, + }); + return; + case "cancelled": + closeStream(); + dispatch({ type: "GENERATION_CANCELLED", id: event.payload.generationId }); + return; + case "failed": + closeStream(); + dispatch({ + type: "GENERATION_FAILED", + id: event.payload.generationId, + error: event.payload.error, + }); + return; + case "succeeded": + closeStream(); + await loadResult(event.payload.generationId); + return; + } + } + + async function handleGenerate(): Promise { + const problem = validateGeneration(state.inputText, state.selectedVoiceId); + if (problem !== null) { + dispatch({ type: "SET_ERROR", error: problem }); + return; + } + + closeStream(); + releaseAudio(); + try { + const status = await api.createGeneration({ + text: state.inputText, + voiceId: state.selectedVoiceId ?? undefined, + rate: state.rate, + volume: state.volume, + }); + dispatch({ type: "GENERATION_CREATED", id: status.generationId, status: status.status }); + currentIdRef.current = status.generationId; + progressRef.current = { sentenceIndex: 0, sentenceCount: 0 }; + closeStreamRef.current = api.openEventStream(status.generationId, (event) => { + void handleStreamEvent(event); + }); + } catch (error) { + dispatchFailure(error); + } + } + + async function handleCancel(): Promise { + const current = state.current; + if (current === null || current.status === "cancelling") { + return; + } + try { + const status = await api.cancelGeneration(current.id); + if (status.status === "cancelled") { + closeStream(); + dispatch({ type: "GENERATION_CANCELLED", id: current.id }); + return; + } + dispatch({ + type: "GENERATION_PROGRESS", + id: current.id, + status: status.status, + sentenceIndex: current.sentenceIndex, + sentenceCount: current.sentenceCount, + }); + } catch (error) { + dispatchFailure(error); + } + } + + const active = isActive(current); + const hasVoices = state.voices.length > 0; + + return ( +
+

Generate

+ + {hasVoices ? ( +

+ Start a generation, watch progress, and cancel if you change your mind. +

+ ) : ( +

+ No voices installed, so generation is disabled. Run{" "} + tts add-voice <name> in a terminal, then reload this page. +

+ )} + +

+ {statusLabel(current)} +

+ {active && current !== null && current.sentenceCount > 0 ? ( + + ) : null} + +
+ + {active ? ( + + ) : null} +
+
+ ); +} diff --git a/frontend/src/components/InputPanel.test.tsx b/frontend/src/components/InputPanel.test.tsx new file mode 100644 index 0000000..1ca4c43 --- /dev/null +++ b/frontend/src/components/InputPanel.test.tsx @@ -0,0 +1,31 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { AppProvider } from "../state/appContext"; +import { InputPanel } from "./InputPanel"; + +function renderPanel(): string { + return renderToStaticMarkup( + + + , + ); +} + +describe("InputPanel", () => { + it("renders an editable textarea and the character budget", () => { + const html = renderPanel(); + expect(html).toContain('id="input-text"'); + expect(html).toContain(" { + const html = renderPanel(); + expect(html).toContain('accept=".txt,text/plain"'); + expect(html).toContain("Only plain-text .txt files up to 2 MB are accepted."); + }); + + it("shows no length warning for empty input", () => { + expect(renderPanel()).not.toContain("Shorten the text before generating."); + }); +}); diff --git a/frontend/src/components/InputPanel.tsx b/frontend/src/components/InputPanel.tsx new file mode 100644 index 0000000..7c1955f --- /dev/null +++ b/frontend/src/components/InputPanel.tsx @@ -0,0 +1,84 @@ +/** + * Text input and plain-text upload (ARCHITECTURE.md section 12, FR-01). + * + * Uploading never starts a generation: the decoded text lands in the textarea + * so the user can review or edit it first (section 9.2). + */ + +import type { ChangeEvent } from "react"; +import { api } from "../api"; +import { toApiError } from "../api/client"; +import { useApp } from "../state/appContext"; +import { MAX_INPUT_CHARS, inputTooLongMessage } from "./validation"; + +export function InputPanel() { + const { state, dispatch } = useApp(); + const tooLong = state.inputText.length > MAX_INPUT_CHARS; + + async function handleFile(event: ChangeEvent): Promise { + const input = event.currentTarget; + const file = input.files?.[0]; + input.value = ""; + if (file === undefined) { + return; + } + try { + const upload = await api.uploadFile(file); + dispatch({ type: "SET_INPUT", text: upload.text }); + dispatch({ type: "SET_SOURCE_FILE", filename: upload.filename }); + } catch (error) { + const failure = toApiError(error); + dispatch({ + type: "SET_ERROR", + error: { code: failure.code, message: failure.message, details: failure.details }, + }); + } + } + + return ( +
+

Text

+ +
+ +