Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/TASKS.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Statuses: done (PR merged) · doing (branch open, pending review) · remaining

| ID | Task | Branch | Verification | Status |
|---|---|---|---|---|
| _(empty)_ | | | | |
| T3.2 | Playback + downloads | `arch/tts/t3.2` | 83 Vitest (32 new); ESLint; `tsc --noEmit`; Prettier (CRLF); live + mock Vite builds; mock-mode Chromium 13/13 (highlight advance/pause, word click, cue click, ArrowRight ±5 s, Space toggle, ended reset, WAV/SRT/VTT names + content); 196 pytest; Ruff check/format; strict mypy; `git diff --check` | Open — pending review |

## Remaining

Expand All @@ -52,7 +52,6 @@ _All P2 tasks done._

| ID | Task | Files | Deps | Acceptance criteria (summary) |
|---|---|---|---|---|
| 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 |

### P4 — Integration
Expand Down Expand Up @@ -127,3 +126,8 @@ _All P2 tasks done._
- 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.
- T3.2 decisions: `usePlayback` uses a callback ref for `<audio>` (the element lives in a ref, not state) so the rAF loop and media-event handlers never mutate a state value and React's effect lint stays clean. Exported pure helpers (`findActiveWordIndex`, `firstWordIndexAtOrAfter`, `clampSeconds`) carry the §10.3 binary search: a word is active only while `startMs <= t <= endMs`, so gaps and post-end times highlight nothing; `ended` clears the highlight; media events (`loadedmetadata`, `emptied`) reset it when `audioUrl` changes. Keyboard Space / ArrowLeft / ArrowRight ignore inputs, textareas, selects, buttons, links, and contenteditable targets, so native activation still works.
- T3.2 download naming: `fetch` cannot read the server's `Content-Disposition` header, so `DownloadBar.downloadFilename` rebuilds the T2.2 rule client-side: first ≤ 6 `[A-Za-z0-9]+` words joined by `-` (ASCII-only, so `Über café` → `ber-caf` exactly like the Python regex), lowercased, `speech` fallback, plus the UTC `YYYYMMDD-HHMMSS` of `createdAt`. Frozen downstream for T5.1's AC9/AC10 specs.
- T3.2 accessibility decision: word spans are mouse-only seek targets; sentence cue `<button>`s, the ±5 s buttons, and the keyboard shortcuts are the keyboard paths, avoiding thousands of tab stops on a 10k-word input. T4.2 owns the a11y pass and should revisit if it wants word-level keyboard seek. `PlaybackPanel` also renders the T3.1 succeeded-without-audio ready state instead of assuming a blob exists.
- T3.2 downstream contract (T3.3): `SubtitleView` and `DownloadBar` are prop-driven; history restore only needs `SELECT_HISTORY_ITEM` with a detail + audio URL, and `PlaybackPanel` picks it up with no further wiring.
- T3.2 shared-file note: `App.tsx` and `styles.css` are not assigned to T3.2 but received additive edits — T3.1's placeholder comment hands playback to T3.2/T3.3, so `App.tsx` now renders `PlaybackPanel` and keeps the history placeholder for T3.3; `styles.css` gained playback/subtitle/download rules. `contracts.ts`, `appContext.tsx`, and `api/*` were untouched (all needed types/actions already existed).
11 changes: 4 additions & 7 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
/**
* Single page layout (ARCHITECTURE.md section 12).
*
* 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.
* Sections stack in their documented order. The history section stays as a
* placeholder until T3.3 replaces it, so that task can own its component file.
*/

import { useEffect } from "react";
Expand All @@ -12,6 +11,7 @@ import { toApiError } from "./api/client";
import { ErrorBanner } from "./components/ErrorBanner";
import { GenerateBar } from "./components/GenerateBar";
import { InputPanel } from "./components/InputPanel";
import { PlaybackPanel } from "./components/PlaybackPanel";
import { VoicePanel } from "./components/VoicePanel";
import { clampRate, clampVolume } from "./components/validation";
import { useApp } from "./state/appContext";
Expand Down Expand Up @@ -73,10 +73,7 @@ export function App() {
<VoicePanel />
<GenerateBar />

<section className="section" aria-labelledby="playback-heading">
<h2 id="playback-heading">Playback and subtitles</h2>
<p className="hint">Audio, word highlighting, seek, and downloads appear here.</p>
</section>
<PlaybackPanel />

<section className="section" aria-labelledby="history-heading">
<h2 id="history-heading">History</h2>
Expand Down
79 changes: 79 additions & 0 deletions frontend/src/components/DownloadBar.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { AppProvider } from "../state/appContext";
import type { GenerationDetail } from "../types/contracts";
import { DownloadBar, downloadFilename, downloadStem, downloadTimestamp } from "./DownloadBar";

const DETAIL: GenerationDetail = {
generationId: "11111111-1111-4111-8111-111111111111",
status: "succeeded",
createdAt: "2026-11-20T19:04:45Z",
sourceType: "text",
inputPreview: "Hello world.",
inputFilename: null,
voiceId: "en_US-lessac-medium",
voiceName: "Lessac",
rate: 1,
volume: 1,
durationSeconds: 12.5,
error: null,
text: "Hello world.",
sampleRate: 22050,
alignedWordRatio: 1,
wordTimings: [],
cues: [],
};

describe("downloadTimestamp", () => {
it("formats the creation time in UTC", () => {
expect(downloadTimestamp("2026-11-20T19:04:45.123456Z")).toBe("20261120-190445");
});

it("converts offset timestamps to UTC", () => {
expect(downloadTimestamp("2026-11-20T20:04:45+01:00")).toBe("20261120-190445");
});
});

describe("downloadStem", () => {
it("takes at most six words, lowercased and hyphen-joined", () => {
expect(
downloadStem("Hello, world! This is a test of the filename builder.", "2026-11-20T19:04:45Z"),
).toBe("hello-world-this-is-a-test_20261120-190445");
});

it("ignores non-ASCII characters the same way the API regex does", () => {
expect(downloadStem("Über café", "2026-11-20T19:04:45Z")).toBe("ber-caf_20261120-190445");
});

it("falls back to speech when the input has no usable characters", () => {
expect(downloadStem(" ", "2026-11-20T19:04:45Z")).toBe("speech_20261120-190445");
});
});

describe("downloadFilename", () => {
it("appends the file extension", () => {
expect(downloadFilename("Hello world.", "2026-11-20T19:04:45Z", "wav")).toBe(
"hello-world_20261120-190445.wav",
);
expect(downloadFilename("Hello world.", "2026-11-20T19:04:45Z", "srt")).toBe(
"hello-world_20261120-190445.srt",
);
expect(downloadFilename("Hello world.", "2026-11-20T19:04:45Z", "vtt")).toBe(
"hello-world_20261120-190445.vtt",
);
});
});

describe("DownloadBar", () => {
it("offers all three downloads", () => {
const html = renderToStaticMarkup(
<AppProvider>
<DownloadBar detail={DETAIL} />
</AppProvider>,
);
expect(html).toContain("Download audio (WAV)");
expect(html).toContain("Download subtitles (SRT)");
expect(html).toContain("Download subtitles (VTT)");
expect(html).toContain("first words of the input");
});
});
152 changes: 152 additions & 0 deletions frontend/src/components/DownloadBar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/**
* Audio and subtitle downloads (ARCHITECTURE.md sections 9.2 and 12, FR-07).
*
* The browser cannot read the server's `Content-Disposition` header through
* `fetch`, so the download name is rebuilt with the same §9.2 rule the API
* uses: first ≤ 6 words of the input, lowercased, joined by `-`, plus the UTC
* `createdAt` timestamp as `YYYYMMDD-HHMMSS`.
*/

import { useState } from "react";
import { api } from "../api";
import { toApiError } from "../api/client";
import { useApp } from "../state/appContext";
import type { GenerationDetail, SubtitleFormat } from "../types/contracts";

export type DownloadKind = "wav" | SubtitleFormat;

const SLUG_WORDS = 6;

function pad(value: number): string {
return String(value).padStart(2, "0");
}

/** UTC `YYYYMMDD-HHMMSS`, the timestamp half of the §9.2 download name. */
export function downloadTimestamp(createdAt: string): string {
const date = new Date(createdAt);
const safe = Number.isNaN(date.getTime()) ? new Date() : date;
return (
`${safe.getUTCFullYear()}${pad(safe.getUTCMonth() + 1)}${pad(safe.getUTCDate())}` +
`-${pad(safe.getUTCHours())}${pad(safe.getUTCMinutes())}${pad(safe.getUTCSeconds())}`
);
}

/** The `{slug}_{timestamp}` stem shared by all three download files. */
export function downloadStem(input: string, createdAt: string): string {
const words = (input.match(/[A-Za-z0-9]+/g) ?? []).slice(0, SLUG_WORDS);
const slug =
words
.join("-")
.toLowerCase()
.replace(/[^a-z0-9-]/g, "")
.replace(/^-+|-+$/g, "") || "speech";
return `${slug}_${downloadTimestamp(createdAt)}`;
}

export function downloadFilename(
input: string,
createdAt: string,
extension: DownloadKind,
): string {
return `${downloadStem(input, createdAt)}.${extension}`;
}

/** Triggers a browser download for an already-fetched blob. */
function saveBlob(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = filename;
anchor.rel = "noopener";
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
window.setTimeout(() => {
URL.revokeObjectURL(url);
}, 0);
}

export interface DownloadBarProps {
detail: GenerationDetail;
}

export function DownloadBar({ detail }: DownloadBarProps) {
const { dispatch } = useApp();
const [busy, setBusy] = useState<DownloadKind | null>(null);
const input = detail.text ?? detail.inputPreview;

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 downloadAudio(): Promise<void> {
setBusy("wav");
try {
const blob = await api.getAudioBlob(detail.generationId);
saveBlob(blob, downloadFilename(input, detail.createdAt, "wav"));
} catch (error) {
dispatchFailure(error);
} finally {
setBusy(null);
}
}

async function downloadSubtitles(format: SubtitleFormat): Promise<void> {
setBusy(format);
try {
const text = await api.getSubtitlesText(detail.generationId, format);
const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
saveBlob(blob, downloadFilename(input, detail.createdAt, format));
} catch (error) {
dispatchFailure(error);
} finally {
setBusy(null);
}
}

const disabled = busy !== null;

return (
<div className="download-block">
<h3>Downloads</h3>
<p className="hint">
Files are named after the first words of the input and when the generation was created.
</p>
<div className="button-row download-row">
<button
type="button"
disabled={disabled}
onClick={() => {
void downloadAudio();
}}
>
{busy === "wav" ? "Preparing WAV…" : "Download audio (WAV)"}
</button>
<button
type="button"
className="secondary"
disabled={disabled}
onClick={() => {
void downloadSubtitles("srt");
}}
>
{busy === "srt" ? "Preparing SRT…" : "Download subtitles (SRT)"}
</button>
<button
type="button"
className="secondary"
disabled={disabled}
onClick={() => {
void downloadSubtitles("vtt");
}}
>
{busy === "vtt" ? "Preparing VTT…" : "Download subtitles (VTT)"}
</button>
</div>
</div>
);
}
85 changes: 85 additions & 0 deletions frontend/src/components/PlaybackPanel.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { AppProvider, type CurrentGeneration } from "../state/appContext";
import type { GenerationDetail } from "../types/contracts";
import { isInteractiveTarget, playbackMessage, PlaybackPanel } from "./PlaybackPanel";

const DETAIL: GenerationDetail = {
generationId: "11111111-1111-4111-8111-111111111111",
status: "succeeded",
createdAt: "2026-11-20T19:04:45Z",
sourceType: "text",
inputPreview: "Hello world.",
inputFilename: null,
voiceId: "en_US-lessac-medium",
voiceName: "Lessac",
rate: 1,
volume: 1,
durationSeconds: 1,
error: null,
text: "Hello world.",
sampleRate: 22050,
alignedWordRatio: 1,
wordTimings: [{ text: "Hello", startMs: 0, endMs: 400, aligned: true }],
cues: [{ index: 1, startMs: 0, endMs: 400, text: "Hello" }],
};

function current(overrides: Partial<CurrentGeneration>): CurrentGeneration {
return {
id: "11111111-1111-4111-8111-111111111111",
status: "succeeded",
sentenceIndex: 0,
sentenceCount: 0,
...overrides,
};
}

describe("playbackMessage", () => {
it("prompts for a generation when nothing exists yet", () => {
expect(playbackMessage(null)).toContain("Generate audio");
});

it("has no message for a succeeded entry with details", () => {
expect(playbackMessage(current({ detail: DETAIL }))).toBeNull();
});

it("explains a succeeded entry whose details are missing", () => {
expect(playbackMessage(current({ detail: undefined }))).toContain(
"details could not be loaded",
);
});

it("explains failed, cancelled, and in-progress entries", () => {
expect(playbackMessage(current({ status: "failed" }))).toContain("failed");
expect(playbackMessage(current({ status: "cancelled" }))).toContain("cancelled");
expect(playbackMessage(current({ status: "running" }))).toContain("when generation finishes");
});
});

describe("isInteractiveTarget", () => {
it("keeps native behavior for form controls and links", () => {
for (const tagName of ["INPUT", "TEXTAREA", "SELECT", "BUTTON", "a"]) {
expect(isInteractiveTarget({ tagName })).toBe(true);
}
expect(isInteractiveTarget({ isContentEditable: true })).toBe(true);
});

it("allows shortcuts on non-interactive targets", () => {
expect(isInteractiveTarget(null)).toBe(false);
expect(isInteractiveTarget({ tagName: "DIV" })).toBe(false);
expect(isInteractiveTarget({})).toBe(false);
});
});

describe("PlaybackPanel", () => {
it("renders the section heading and the empty state", () => {
const html = renderToStaticMarkup(
<AppProvider>
<PlaybackPanel />
</AppProvider>,
);
expect(html).toContain("Playback and subtitles");
expect(html).toContain("Generate audio to play it back here.");
expect(html).not.toContain("<audio");
});
});
Loading