forge
Explore
Log in

Don't you dare go Hollow

🐛 seekable podcast audio, one-player episode list, school name

Browse files at this commit

f1158ba79f19ed402a26f6169fd62bd43201ccf1Burak BoduroğluParent: 57d6f86
  • fix
    • 🐛 seekable podcast audio, one-player episode list, school name
Show full message
fix: 🐛 seekable podcast audio, one-player episode list, school name
- the audio door ignores Range and streams chunked, so the browser could
  not seek (seekable [0,0]); the player now loads the file once and seeks
  in a local copy when the stream cannot serve the target, and prefetches
  it on first play so later skips are instant
- episodes: one player on top for the selected episode, a plain list under
  it (narration, date, length, download); the note title is no longer
  repeated on every row, the newest finished episode is preselected and a
  just-finished generation hands off to the list instead of its own box
- unfinished rows are muted with their state; raw error codes move to a
  tooltip
- the session school's name (GET /school) shows under the brand in the
  sidebar and the mobile top bar
- docs: backend note on Range support for the audio door
docs/backend/podcast-transcript-request.mdmodified+12 -0
@@ -44,3 +44,15 @@ If the backend prefers a separate door (for example
44 the studio inspector load it lazily), or different field names, the frontend44 the studio inspector load it lazily), or different field names, the frontend
45 changes in one place: the type above and the `transcript` prop passed to45 changes in one place: the type above and the `transcript` prop passed to
46 `PodcastPlayer`.46 `PodcastPlayer`.
47+
48+## Related: the audio door cannot be seeked
49+
50+`GET /podcast/jobs/{id}/audio` answers `200` with `Transfer-Encoding: chunked`,
51+no `Content-Length`, no `Accept-Ranges`, and ignores a `Range` header
52+(checked 2026-09-23). Browsers then report `seekable` as `[0, 0]` and every
53+seek snaps back to 0:00. The frontend works around it by loading the whole
54+file once (`getPodcastJobAudioBlob`) and seeking in a local copy, which costs
55+a full download before the first seek. Answering `Range` with `206 Partial
56+Content` (plus `Accept-Ranges: bytes` and `Content-Length` on the full
57+response) would make seeking instant; the player already prefers the stream
58+whenever the browser says it can seek there.
src/api/__tests__/podcast/podcast.test.tsmodified+14 -1
@@ -1,5 +1,6 @@
1 import { afterEach, describe, expect, it, vi } from "vitest";1 import { afterEach, describe, expect, it, vi } from "vitest";
2 import {2 import {
3+ getPodcastJobAudioBlob,
3 getPodcastJobById,4 getPodcastJobById,
4 getPodcastJobResultById,5 getPodcastJobResultById,
5 listPodcastJobs,6 listPodcastJobs,
@@ -7,7 +8,7 @@ import {
7 postPodcastJob,8 postPodcastJob,
8 postPodcastJobCancel,9 postPodcastJobCancel,
9 } from "../../podcast";10 } from "../../podcast";
10-import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch";11+import { lastFetchCall, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch";
11 12
12 describe("podcast API", () => {13 describe("podcast API", () => {
13 afterEach(() => {14 afterEach(() => {
@@ -86,6 +87,18 @@ describe("podcast API", () => {
86 expect(podcastAudioUrl("j 1")).toBe("/api/podcast/jobs/j%201/audio");87 expect(podcastAudioUrl("j 1")).toBe("/api/podcast/jobs/j%201/audio");
87 });88 });
88 89
90+ it("getPodcastJobAudioBlob loads the whole episode from the same door", async () => {
91+ const blob = new Blob(["mp3"], { type: "audio/mpeg" });
92+ mockFetchBlob(blob);
93+
94+ const result = await getPodcastJobAudioBlob("j 1");
95+ expect(result.type).toBe("audio/mpeg");
96+
97+ const [url, init] = lastFetchCall();
98+ expect(url).toBe("/api/podcast/jobs/j%201/audio");
99+ expect(init?.method ?? "GET").toBe("GET");
100+ });
101+
89 it("listPodcastJobs asks for the whole history when no note is given", async () => {102 it("listPodcastJobs asks for the whole history when no note is given", async () => {
90 mockFetchSuccess({ items: [], total: 0, limit: 10, offset: 0 });103 mockFetchSuccess({ items: [], total: 0, limit: 10, offset: 0 });
91 104
src/api/podcast/getPodcastJobAudioBlob.tsadded+10 -0
@@ -0,0 +1,10 @@
1+import { blobClient } from "../client";
2+
3+/**
4+ * The whole produced episode as one Blob. The audio door streams chunked with
5+ * no length and ignores `Range`, so a browser cannot seek on the stream; the
6+ * player loads this once and seeks inside a local object URL instead.
7+ */
8+export function getPodcastJobAudioBlob(jobId: string, signal?: AbortSignal): Promise<Blob> {
9+ return blobClient(`/podcast/jobs/${encodeURIComponent(jobId)}/audio`, signal);
10+}
src/api/podcast/index.tsmodified+1 -0
@@ -4,3 +4,4 @@ export * from "./getPodcastJobById";
4 export * from "./getPodcastJobResultById";4 export * from "./getPodcastJobResultById";
5 export * from "./postPodcastJobCancel";5 export * from "./postPodcastJobCancel";
6 export * from "./podcastAudioUrl";6 export * from "./podcastAudioUrl";
7+export * from "./getPodcastJobAudioBlob";
src/components/layout/app-shell.tsxmodified+9 -2
@@ -19,6 +19,7 @@ import { IconPanelLeft, IconSparkles } from "@/components/ui/icons";
19 import { Toaster } from "@/components/ui/toast";19 import { Toaster } from "@/components/ui/toast";
20 import { useAuth } from "@/stores/auth-context";20 import { useAuth } from "@/stores/auth-context";
21 import { useModules } from "@/stores/modules-context";21 import { useModules } from "@/stores/modules-context";
22+import { useSchool } from "@/stores/school-context";
22 import { celebiPanelOpen, openCelebiPanel, setCelebiPanelOpen } from "@/stores/celebi-panel";23 import { celebiPanelOpen, openCelebiPanel, setCelebiPanelOpen } from "@/stores/celebi-panel";
23 import { commandPaletteOpen, openCommandPalette, setCommandPaletteOpen } from "@/stores/command-palette";24 import { commandPaletteOpen, openCommandPalette, setCommandPaletteOpen } from "@/stores/command-palette";
24 import { quickActionsSuppressed } from "@/stores/quick-actions";25 import { quickActionsSuppressed } from "@/stores/quick-actions";
@@ -35,6 +36,7 @@ export function AppShell(props: ParentProps) {
35 const auth = useAuth();36 const auth = useAuth();
36 const prefs = usePreferences();37 const prefs = usePreferences();
37 const t = useT();38 const t = useT();
39+ const school = useSchool();
38 const modules = useModules();40 const modules = useModules();
39 const navigate = useNavigate();41 const navigate = useNavigate();
40 const [mobileOpen, setMobileOpen] = createSignal(false);42 const [mobileOpen, setMobileOpen] = createSignal(false);
@@ -112,13 +114,18 @@ export function AppShell(props: ParentProps) {
112 <Link114 <Link
113 to="/"115 to="/"
114 class={cn("flex min-w-0 items-center gap-2.5", collapsed() ? "justify-center" : "flex-1")}116 class={cn("flex min-w-0 items-center gap-2.5", collapsed() ? "justify-center" : "flex-1")}
115- title={t("app.name")}117+ title={school.name() ? `${t("app.name")} · ${school.name()}` : t("app.name")}
116 >118 >
117 <span class="flex h-8 w-8 shrink-0 items-center justify-center text-foreground">119 <span class="flex h-8 w-8 shrink-0 items-center justify-center text-foreground">
118 <LogoMark size={28} />120 <LogoMark size={28} />
119 </span>121 </span>
120 <Show when={!collapsed()}>122 <Show when={!collapsed()}>
121- <span class="truncate text-base font-semibold tracking-tight text-foreground dark:text-white 2xl:text-lg">{t("app.name")}</span>123+ <span class="flex min-w-0 flex-col leading-tight">
124+ <span class="truncate text-base font-semibold tracking-tight text-foreground dark:text-white 2xl:text-lg">{t("app.name")}</span>
125+ <Show when={school.name()}>
126+ {(name) => <span class="truncate text-xs font-medium text-muted-foreground">{name()}</span>}
127+ </Show>
128+ </span>
122 </Show>129 </Show>
123 </Link>130 </Link>
124 </div>131 </div>
src/components/layout/nav-bar.tsxmodified+7 -2
@@ -8,10 +8,12 @@ import { ThemeModeControl } from "@/components/layout/theme-mode-control";
8 import { LocaleSwitcher } from "@/components/layout/locale-switcher";8 import { LocaleSwitcher } from "@/components/layout/locale-switcher";
9 import { IconMenu, IconX } from "@/components/ui/icons";9 import { IconMenu, IconX } from "@/components/ui/icons";
10 import { useAuth } from "@/stores/auth-context";10 import { useAuth } from "@/stores/auth-context";
11+import { useSchool } from "@/stores/school-context";
11 import { useT } from "@/stores/preferences-context";12 import { useT } from "@/stores/preferences-context";
12 13
13 export function NavBar() {14 export function NavBar() {
14 const auth = useAuth();15 const auth = useAuth();
16+ const school = useSchool();
15 const t = useT();17 const t = useT();
16 const [mobileOpen, setMobileOpen] = createSignal(false);18 const [mobileOpen, setMobileOpen] = createSignal(false);
17 19
@@ -36,8 +38,11 @@ export function NavBar() {
36 <span class="flex h-8 w-8 shrink-0 items-center justify-center text-foreground">38 <span class="flex h-8 w-8 shrink-0 items-center justify-center text-foreground">
37 <LogoMark size={28} />39 <LogoMark size={28} />
38 </span>40 </span>
39- <span class="truncate text-base font-semibold tracking-tight sm:text-lg">41+ <span class="flex min-w-0 flex-col leading-tight">
40- {t("app.name")}42+ <span class="truncate text-base font-semibold tracking-tight sm:text-lg">{t("app.name")}</span>
43+ <Show when={auth.user() && school.name()}>
44+ <span class="truncate text-xs font-medium text-muted-foreground">{school.name()}</span>
45+ </Show>
41 </span>46 </span>
42 </Link>47 </Link>
43 48
src/components/notes/podcast-history.test.tsxmodified+35 -26
@@ -8,6 +8,7 @@ import { PreferencesProvider } from "@/stores/preferences-context";
8 const podcastApi = vi.hoisted(() => ({8 const podcastApi = vi.hoisted(() => ({
9 listPodcastJobs: vi.fn(),9 listPodcastJobs: vi.fn(),
10 podcastAudioUrl: vi.fn((jobId: string) => `/api/podcast/jobs/${encodeURIComponent(jobId)}/audio`),10 podcastAudioUrl: vi.fn((jobId: string) => `/api/podcast/jobs/${encodeURIComponent(jobId)}/audio`),
11+ getPodcastJobAudioBlob: vi.fn(),
11 }));12 }));
12 13
13 vi.mock("@/api/podcast", () => podcastApi);14 vi.mock("@/api/podcast", () => podcastApi);
@@ -51,18 +52,27 @@ describe("PodcastHistory", () => {
51 </PreferencesProvider>52 </PreferencesProvider>
52 ));53 ));
53 54
54- it("renders a finished row's title, state and duration, and plays it by job id", async () => {55+ it("names rows by narration, selects the newest finished one and plays a picked row", async () => {
55- podcastApi.listPodcastJobs.mockResolvedValue(page([job({})]));56+ podcastApi.listPodcastJobs.mockResolvedValue(
57+ page([job({ job_id: "job-2", format: "ogrenci_hoca" }), job({ job_id: "job-1" })]),
58+ );
56 59
57 renderHistory("note-1");60 renderHistory("note-1");
58 61
59- await waitFor(() => expect(screen.getByText("Hücre")).toBeTruthy());62+ // Scoped to one note, the note's title is not repeated on every row.
60- expect(screen.getByText("Hazır")).toBeTruthy();63+ await waitFor(() => expect(screen.getAllByText("Öğrenci ve öğretmen").length).toBeGreaterThan(0));
61- expect(screen.getByText("12:34")).toBeTruthy();64+ expect(screen.queryByText("Hücre")).toBeNull();
65+ expect(screen.getAllByText("12:34").length).toBeGreaterThan(0);
66+ // One player, on the newest finished episode, not playing on its own.
67+ expect(document.querySelectorAll("audio")).toHaveLength(1);
68+ expect(document.querySelector("audio")?.getAttribute("src")).toBe("/api/podcast/jobs/job-2/audio");
62 69
63- fireEvent.click(screen.getByRole("button", { name: "Bölümü oynat" }));70+ fireEvent.click(screen.getByRole("button", { name: /^Bölümü oynat: Düz okuma/ }));
64- expect(podcastApi.podcastAudioUrl).toHaveBeenCalledWith("job-1");71+
65- expect(document.querySelector("audio")?.getAttribute("src")).toBe("/api/podcast/jobs/job-1/audio");72+ await waitFor(() =>
73+ expect(document.querySelector("audio")?.getAttribute("src")).toBe("/api/podcast/jobs/job-1/audio"),
74+ );
75+ expect(document.querySelectorAll("audio")).toHaveLength(1);
66 });76 });
67 77
68 it("gives a non-done row no play control", async () => {78 it("gives a non-done row no play control", async () => {
@@ -82,10 +92,11 @@ describe("PodcastHistory", () => {
82 92
83 renderHistory("note-1");93 renderHistory("note-1");
84 94
85- await waitFor(() => expect(screen.getByText("Hücre")).toBeTruthy());95+ await waitFor(() => expect(screen.getAllByRole("link", { name: "Bölümü indir" }).length).toBeGreaterThan(0));
86- const link = screen.getByRole("link", { name: "Bölümü indir" }) as HTMLAnchorElement;96+ for (const link of screen.getAllByRole("link", { name: "Bölümü indir" }) as HTMLAnchorElement[]) {
87- expect(link.getAttribute("href")).toBe("/api/podcast/jobs/job-1/audio");97+ expect(link.getAttribute("href")).toBe("/api/podcast/jobs/job-1/audio");
88- expect(link.getAttribute("download")).toBe("Hücre.mp3");98+ expect(link.getAttribute("download")).toBe("Hücre.mp3");
99+ }
89 });100 });
90 101
91 it("gives a non-done row no download control", async () => {102 it("gives a non-done row no download control", async () => {
@@ -140,12 +151,13 @@ describe("PodcastHistory", () => {
140 expect(podcastApi.listPodcastJobs).not.toHaveBeenCalled();151 expect(podcastApi.listPodcastJobs).not.toHaveBeenCalled();
141 });152 });
142 153
143- it("falls back to the note id when the note is gone", async () => {154+ it("falls back to the note id for a download when the note is gone", async () => {
144 podcastApi.listPodcastJobs.mockResolvedValue(page([job({ source_id: "note-gone", source_title: null })]));155 podcastApi.listPodcastJobs.mockResolvedValue(page([job({ source_id: "note-gone", source_title: null })]));
145 156
146 renderHistory("note-1");157 renderHistory("note-1");
147 158
148- await waitFor(() => expect(screen.getByText("note-gone")).toBeTruthy());159+ await waitFor(() => expect(screen.getAllByRole("link", { name: "Bölümü indir" }).length).toBeGreaterThan(0));
160+ expect(screen.getAllByRole("link", { name: "Bölümü indir" })[0].getAttribute("download")).toBe("note-gone.mp3");
149 });161 });
150 162
151 it("refetches when the panel signals a finished generation", async () => {163 it("refetches when the panel signals a finished generation", async () => {
@@ -164,46 +176,43 @@ describe("PodcastHistory", () => {
164 });176 });
165 177
166 it("paginates the selected note's podcast history", async () => {178 it("paginates the selected note's podcast history", async () => {
167- const first = job({ job_id: "job-1", source_title: "İlk bölüm" });179+ const first = job({ job_id: "job-1", format: "duz_okuma" });
168- const second = job({ job_id: "job-2", source_title: "İkinci bölüm" });180+ const second = job({ job_id: "job-2", format: "tek_ogretici" });
169 podcastApi.listPodcastJobs181 podcastApi.listPodcastJobs
170 .mockResolvedValueOnce(page([first], 11, 0))182 .mockResolvedValueOnce(page([first], 11, 0))
171 .mockResolvedValueOnce(page([second], 11, 10));183 .mockResolvedValueOnce(page([second], 11, 10));
172 184
173 renderHistory("note-1");185 renderHistory("note-1");
174 186
175- await waitFor(() => expect(screen.getByText("İlk bölüm")).toBeTruthy());187+ await waitFor(() => expect(screen.getAllByText("Düz okuma").length).toBeGreaterThan(0));
176 expect(screen.getByText("1 / 2")).toBeTruthy();188 expect(screen.getByText("1 / 2")).toBeTruthy();
177 189
178 fireEvent.click(screen.getByRole("button", { name: "Sonraki" }));190 fireEvent.click(screen.getByRole("button", { name: "Sonraki" }));
179 191
180- await waitFor(() => expect(screen.getByText("İkinci bölüm")).toBeTruthy());192+ await waitFor(() => expect(screen.getAllByText("Tek öğretici").length).toBeGreaterThan(0));
181 expect(podcastApi.listPodcastJobs).toHaveBeenLastCalledWith({ limit: 10, offset: 10, sourceId: "note-1" });193 expect(podcastApi.listPodcastJobs).toHaveBeenLastCalledWith({ limit: 10, offset: 10, sourceId: "note-1" });
182 expect(screen.getByText("2 / 2")).toBeTruthy();194 expect(screen.getByText("2 / 2")).toBeTruthy();
183 });195 });
184 196
185 it("marks each episode with the narration the service settled on", async () => {197 it("marks each episode with the narration the service settled on", async () => {
186 podcastApi.listPodcastJobs.mockResolvedValue(198 podcastApi.listPodcastJobs.mockResolvedValue(
187- page([199+ page([job({ job_id: "job-1", format: "duz_okuma" }), job({ job_id: "job-2", format: "ogrenci_hoca" })]),
188- job({ job_id: "job-1", source_title: "Düz", format: "duz_okuma" }),
189- job({ job_id: "job-2", source_title: "İkili", format: "ogrenci_hoca" }),
190- ]),
191 );200 );
192 201
193 renderHistory("note-1");202 renderHistory("note-1");
194 203
195- await waitFor(() => expect(screen.getByText("Düz okuma")).toBeTruthy());204+ await waitFor(() => expect(screen.getAllByText("Düz okuma").length).toBeGreaterThan(0));
196- expect(screen.getByText("Öğrenci ve öğretmen")).toBeTruthy();205+ expect(screen.getAllByText("Öğrenci ve öğretmen").length).toBeGreaterThan(0);
197 });206 });
198 207
199- it("leaves a job the service has not settled a format for unmarked", async () => {208+ it("names an episode the service has not settled a format for plainly", async () => {
200 podcastApi.listPodcastJobs.mockResolvedValue(209 podcastApi.listPodcastJobs.mockResolvedValue(
201 page([job({ state: "queued", format: null, duration_secs: null, finished_at: null })]),210 page([job({ state: "queued", format: null, duration_secs: null, finished_at: null })]),
202 );211 );
203 212
204 renderHistory("note-1");213 renderHistory("note-1");
205 214
206- await waitFor(() => expect(screen.getByText("Hücre")).toBeTruthy());215+ await waitFor(() => expect(screen.getByText("Bölüm")).toBeTruthy());
207 expect(screen.queryByText("Düz okuma")).toBeNull();216 expect(screen.queryByText("Düz okuma")).toBeNull();
208 });217 });
209 });218 });
src/components/notes/podcast-history.tsxmodified+123 -83
@@ -1,20 +1,19 @@
1 import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js";1 import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js";
2 import { createResponsivePageSize } from "@/lib/create-page-size";2 import { createResponsivePageSize } from "@/lib/create-page-size";
3 import { createResource } from "@/lib/create-resource";3 import { createResource } from "@/lib/create-resource";
4-import { formatApiError } from "@/api/client";4+import { formatApiError, type PodcastJobSummary, type PodcastTranscriptSegment } from "@/api/client";
5 import type { MessageKey } from "@/i18n/messages";5 import type { MessageKey } from "@/i18n/messages";
6 import { listPodcastJobs, podcastAudioUrl } from "@/api/podcast";6 import { listPodcastJobs, podcastAudioUrl } from "@/api/podcast";
7 import { Alert } from "@/components/ui/alert";7 import { Alert } from "@/components/ui/alert";
8 import { Badge } from "@/components/ui/badge";8 import { Badge } from "@/components/ui/badge";
9-import { Button, buttonVariants } from "@/components/ui/button";
10 import { EmptyInline } from "@/components/ui/empty-inline";9 import { EmptyInline } from "@/components/ui/empty-inline";
11 import { PageSpinner } from "@/components/ui/page-spinner";10 import { PageSpinner } from "@/components/ui/page-spinner";
12 import { TablePagination } from "@/components/ui/table-pagination";11 import { TablePagination } from "@/components/ui/table-pagination";
13-import { IconDownload, IconPlay } from "@/components/ui/icons";12+import { IconDownload, IconPlay, IconWaveform } from "@/components/ui/icons";
14 import { PodcastPlayer } from "@/components/notes/podcast-player";13 import { PodcastPlayer } from "@/components/notes/podcast-player";
15 import { cn } from "@/lib/cn";14 import { cn } from "@/lib/cn";
16 import { podcastDownloadFilename, usePodcastDownloadT } from "@/components/notes/podcast-download";15 import { podcastDownloadFilename, usePodcastDownloadT } from "@/components/notes/podcast-download";
17-import { formatDate, formatDurationClock } from "@/lib/format";16+import { formatDateTime, formatDurationClock } from "@/lib/format";
18 import { usePreferences, useT } from "@/stores/preferences-context";17 import { usePreferences, useT } from "@/stores/preferences-context";
19 18
20 const HISTORY_PAGE_SIZE = 10;19 const HISTORY_PAGE_SIZE = 10;
@@ -29,18 +28,26 @@ const FORMAT_KEYS: Record<string, MessageKey> = {
29 };28 };
30 29
31 /**30 /**
32- * The caller's own episodes, under the Ses Atölyesi panel. One-directional:31+ * The note's episodes: one player on top for the selected episode, and a
33- * the studio produces, this only reads. A finished episode plays through the32+ * plain list under it — narration, when, how long. A row is picked, not
34- * same job-id audio door the panel's own player uses.33+ * expanded, so there is only ever one player and one set of controls.
35 *34 *
36- * The list always follows the note selected in the studio. There is no second35+ * The newest finished episode is selected on load (not played); a generation
37- * global-history scope here: the podcast tab is about the current note.36+ * the panel just finished is selected as it lands. Unfinished rows stay in
37+ * the list, muted, with their state instead of a player.
38 */38 */
39-export function PodcastHistory(props: { noteId?: string; active?: boolean; refetchKey?: string | number }) {39+export function PodcastHistory(props: {
40+ noteId?: string;
41+ active?: boolean;
42+ refetchKey?: string | number;
43+ /** The transcript of the episode the panel just produced, if the service sent one. */
44+ transcript?: { jobId: string; segments: PodcastTranscriptSegment[] } | null;
45+}) {
40 const t = useT();46 const t = useT();
41 const downloadT = usePodcastDownloadT();47 const downloadT = usePodcastDownloadT();
42 const { locale } = usePreferences();48 const { locale } = usePreferences();
43- const [playing, setPlaying] = createSignal("");49+ const [selected, setSelected] = createSignal("");
50+ const [autoplay, setAutoplay] = createSignal(false);
44 const [page, setPage] = createSignal(0);51 const [page, setPage] = createSignal(0);
45 const pageSize = createResponsivePageSize(HISTORY_PAGE_SIZE);52 const pageSize = createResponsivePageSize(HISTORY_PAGE_SIZE);
46 const active = () => props.active !== false;53 const active = () => props.active !== false;
@@ -49,6 +56,8 @@ export function PodcastHistory(props: { noteId?: string; active?: boolean; refet
49 props.noteId;56 props.noteId;
50 pageSize();57 pageSize();
51 setPage(0);58 setPage(0);
59+ setSelected("");
60+ setAutoplay(false);
52 });61 });
53 62
54 // The source is the scope string, not a fresh object: an identity-stable63 // The source is the scope string, not a fresh object: an identity-stable
@@ -60,10 +69,15 @@ export function PodcastHistory(props: { noteId?: string; active?: boolean; refet
60 );69 );
61 70
62 // The panel bumps the key ("", then the job id) when a generation finishes;71 // The panel bumps the key ("", then the job id) when a generation finishes;
63- // pull a fresh page so the episode it just produced appears. The history72+ // pull a fresh page so the episode it just produced appears, and select it.
64- // never starts work itself.
65 createEffect(() => {73 createEffect(() => {
66- if (props.refetchKey) void refetch();74+ const key = props.refetchKey;
75+ if (!key) return;
76+ void refetch();
77+ if (typeof key === "string") {
78+ setSelected(key);
79+ setAutoplay(false);
80+ }
67 });81 });
68 82
69 const jobs = () => list()?.items ?? [];83 const jobs = () => list()?.items ?? [];
@@ -74,12 +88,18 @@ export function PodcastHistory(props: { noteId?: string; active?: boolean; refet
74 if (page() > totalPages() - 1) setPage(totalPages() - 1);88 if (page() > totalPages() - 1) setPage(totalPages() - 1);
75 });89 });
76 90
77- const stateVariant = (state: string) => {91+ // Nothing picked yet (or the pick left the page): fall back to the newest
78- if (state === "done") return "success" as const;92+ // finished episode on screen.
79- if (state === "failed") return "destructive" as const;93+ createEffect(() => {
80- if (state === "cancelled") return "secondary" as const;94+ const rows = jobs();
81- return "warning" as const;95+ if (rows.some((row) => row.job_id === selected() && row.state === "done")) return;
82- };96+ const first = rows.find((row) => row.state === "done");
97+ // A just-finished job may not be on the refetched page yet; keep it picked.
98+ const waitingForFresh = !!props.refetchKey && props.refetchKey === selected();
99+ if (first && !waitingForFresh) setSelected(first.job_id);
100+ });
101+ const current = createMemo(() => jobs().find((row) => row.job_id === selected() && row.state === "done") ?? null);
102+
83 const formatLabel = (format: string | null) => {103 const formatLabel = (format: string | null) => {
84 if (!format) return "";104 if (!format) return "";
85 const key = FORMAT_KEYS[format];105 const key = FORMAT_KEYS[format];
@@ -91,12 +111,24 @@ export function PodcastHistory(props: { noteId?: string; active?: boolean; refet
91 if (state === "cancelled") return t("podcast.history.state.cancelled");111 if (state === "cancelled") return t("podcast.history.state.cancelled");
92 return t("podcast.history.state.pending");112 return t("podcast.history.state.pending");
93 };113 };
114+ const stateVariant = (state: string) => {
115+ if (state === "failed") return "destructive" as const;
116+ if (state === "cancelled") return "secondary" as const;
117+ return "warning" as const;
118+ };
119+ // Scoped to one note, every row narrates the same note — its title would
120+ // only repeat; the narration names the episode instead.
121+ const rowTitle = (row: PodcastJobSummary) =>
122+ props.noteId ? formatLabel(row.format) || t("podcast.history.episode") : row.source_title ?? row.source_id;
123+ const noteName = (row: PodcastJobSummary) => row.source_title ?? row.source_id;
124+ const pick = (row: PodcastJobSummary) => {
125+ setSelected(row.job_id);
126+ setAutoplay(true);
127+ };
94 128
95 return (129 return (
96 <div class="space-y-3 border-t border-border-line pt-4">130 <div class="space-y-3 border-t border-border-line pt-4">
97- <div class="flex flex-wrap items-center justify-between gap-x-3 gap-y-2">131+ <h3 class="text-sm font-semibold">{t("podcast.history.title")}</h3>
98- <h3 class="text-sm font-semibold">{t("podcast.history.title")}</h3>
99- </div>
100 132
101 <Show when={list.error}>133 <Show when={list.error}>
102 <Alert variant="destructive">{formatApiError(list.error)}</Alert>134 <Alert variant="destructive">{formatApiError(list.error)}</Alert>
@@ -108,78 +140,87 @@ export function PodcastHistory(props: { noteId?: string; active?: boolean; refet
108 when={jobs().length > 0}140 when={jobs().length > 0}
109 fallback={141 fallback={
110 <EmptyInline142 <EmptyInline
111- title={143+ title={props.noteId ? t("podcast.history.emptyNote") : t("podcast.history.empty")}
112- props.noteId
113- ? t("podcast.history.emptyNote")
114- : t("podcast.history.empty")
115- }
116 hint={t("podcast.history.emptyHint")}144 hint={t("podcast.history.emptyHint")}
117 />145 />
118 }146 }
119 >147 >
120- <ul class="space-y-2">148+ <Show when={current()} keyed>
149+ {(row) => (
150+ <PodcastPlayer
151+ jobId={row.job_id}
152+ title={rowTitle(row)}
153+ subtitle={formatDateTime(row.created_at, locale())}
154+ downloadName={noteName(row)}
155+ durationSecs={row.duration_secs}
156+ transcript={props.transcript?.jobId === row.job_id ? props.transcript.segments : null}
157+ autoplay={autoplay()}
158+ />
159+ )}
160+ </Show>
161+
162+ <ul class="divide-y divide-border-hairline overflow-hidden rounded-lg border border-border-hairline">
121 <For each={jobs()}>163 <For each={jobs()}>
122- {(row) => (164+ {(row) => {
123- <li class="rounded-lg border border-border/60 p-3">165+ const isCurrent = () => current()?.job_id === row.job_id;
124- <div class="flex items-center gap-3">166+ return (
125- <div class="min-w-0 flex-1">167+ <li class={cn("flex items-center gap-1 pr-1.5", isCurrent() && "bg-primary/5")}>
126- <p class="truncate text-sm font-medium">{row.source_title ?? row.source_id}</p>168+ <Show
127- <div class="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">169+ when={row.state === "done"}
128- <Badge variant={stateVariant(row.state)}>{stateLabel(row.state)}</Badge>170+ fallback={
129- <Show when={formatLabel(row.format)}>171+ <div class="flex min-w-0 flex-1 items-center gap-3 px-3 py-2.5 text-muted-foreground" title={row.error_code ?? undefined}>
130- {(label) => <Badge variant="outline">{label()}</Badge>}172+ <span class="flex h-7 w-7 shrink-0 items-center justify-center" aria-hidden="true">
131- </Show>173+ <span class="h-1.5 w-1.5 rounded-full bg-current opacity-50" />
132- <Show when={row.state === "failed" && row.error_code}>174+ </span>
133- <span class="mono">{row.error_code}</span>175+ <span class="min-w-0 flex-1">
134- </Show>176+ <span class="block truncate text-sm">{rowTitle(row)}</span>
135- <span>{formatDate(row.created_at, locale())}</span>177+ <span class="block truncate text-xs">{formatDateTime(row.created_at, locale())}</span>
136- <Show when={row.duration_secs != null}>178+ </span>
137- <span class="tabular-nums">{formatDurationClock((row.duration_secs ?? 0) * 1000)}</span>179+ <Badge variant={stateVariant(row.state)}>{stateLabel(row.state)}</Badge>
138- </Show>180+ </div>
139- </div>181+ }
140- </div>182+ >
141- <Show when={row.state === "done"}>183+ <button
142- <div class="flex shrink-0 items-center gap-2">
143- <Button
144 type="button"184 type="button"
145- size="sm"185+ class="flex min-w-0 flex-1 items-center gap-3 px-3 py-2.5 text-left transition-colors hover:bg-muted/60 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
146- variant="outline"186+ aria-label={`${t("podcast.history.play")}: ${rowTitle(row)}, ${formatDateTime(row.created_at, locale())}`}
147- class="shrink-0 rounded-lg"187+ aria-current={isCurrent() ? "true" : undefined}
148- aria-label={t("podcast.history.play")}188+ onClick={() => pick(row)}
149- aria-expanded={playing() === row.job_id}
150- onClick={() => setPlaying(playing() === row.job_id ? "" : row.job_id)}
151 >189 >
152- <IconPlay class="h-3.5 w-3.5" />190+ <span
153- </Button>191+ class={cn(
192+ "flex h-7 w-7 shrink-0 items-center justify-center rounded-full",
193+ isCurrent() ? "bg-primary text-primary-foreground" : "bg-muted text-foreground/70",
194+ )}
195+ aria-hidden="true"
196+ >
197+ <Show when={isCurrent()} fallback={<IconPlay class="ml-px h-3 w-3" />}>
198+ <IconWaveform class="h-3.5 w-3.5" />
199+ </Show>
200+ </span>
201+ <span class="min-w-0 flex-1">
202+ <span class={cn("block truncate text-sm", isCurrent() ? "font-semibold" : "font-medium")}>{rowTitle(row)}</span>
203+ <span class="block truncate text-xs text-muted-foreground">{formatDateTime(row.created_at, locale())}</span>
204+ </span>
205+ <Show when={row.duration_secs != null}>
206+ <span class="shrink-0 text-xs tabular-nums text-muted-foreground">
207+ {formatDurationClock((row.duration_secs ?? 0) * 1000)}
208+ </span>
209+ </Show>
210+ </button>
154 <a211 <a
155 href={podcastAudioUrl(row.job_id)}212 href={podcastAudioUrl(row.job_id)}
156- download={podcastDownloadFilename(213+ download={podcastDownloadFilename(noteName(row), downloadT("podcast.download.fallback"))}
157- row.source_title ?? row.source_id,
158- downloadT("podcast.download.fallback"),
159- )}
160 aria-label={downloadT("podcast.download.aria")}214 aria-label={downloadT("podcast.download.aria")}
161- class={cn(buttonVariants({ variant: "outline", size: "sm" }), "shrink-0 rounded-lg")}215+ title={downloadT("podcast.download.label")}
216+ class="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
162 >217 >
163 <IconDownload class="h-4 w-4" />218 <IconDownload class="h-4 w-4" />
164- {downloadT("podcast.download.label")}
165 </a>219 </a>
166- </div>220+ </Show>
167- </Show>221+ </li>
168- </div>222+ );
169- {/* The player opens in the row the reader clicked. A single223+ }}
170- one under the whole list put it a screen away from the
171- episode it belonged to. */}
172- <Show when={playing() === row.job_id}>
173- <PodcastPlayer
174- class="mt-3"
175- jobId={row.job_id}
176- durationSecs={row.duration_secs}
177- download={false}
178- autoplay
179- />
180- </Show>
181- </li>
182- )}
183 </For>224 </For>
184 </ul>225 </ul>
185 </Show>226 </Show>
@@ -188,7 +229,6 @@ export function PodcastHistory(props: { noteId?: string; active?: boolean; refet
188 </Show>229 </Show>
189 </Suspense>230 </Suspense>
190 </Show>231 </Show>
191-
192 </div>232 </div>
193 );233 );
194 }234 }
src/components/notes/podcast-panel.test.tsxmodified+42 -4
@@ -10,6 +10,7 @@ const podcastApi = vi.hoisted(() => ({
10 postPodcastJobCancel: vi.fn(),10 postPodcastJobCancel: vi.fn(),
11 listPodcastJobs: vi.fn(async () => ({ items: [], total: 0, limit: 10, offset: 0 })),11 listPodcastJobs: vi.fn(async () => ({ items: [], total: 0, limit: 10, offset: 0 })),
12 podcastAudioUrl: vi.fn((jobId: string) => `/api/podcast/jobs/${encodeURIComponent(jobId)}/audio`),12 podcastAudioUrl: vi.fn((jobId: string) => `/api/podcast/jobs/${encodeURIComponent(jobId)}/audio`),
13+ getPodcastJobAudioBlob: vi.fn(),
13 }));14 }));
14 15
15 vi.mock("@/api/podcast", () => podcastApi);16 vi.mock("@/api/podcast", () => podcastApi);
@@ -58,6 +59,24 @@ describe("PodcastPanel", () => {
58 // stream by `job_id`. Handing it `audio_id` (the output-root path) composes59 // stream by `job_id`. Handing it `audio_id` (the output-root path) composes
59 // a URL the backend has no route for, and the player dies silently.60 // a URL the backend has no route for, and the player dies silently.
60 sessionStorage.setItem("hezarfen.podcast.note-7", "pj1");61 sessionStorage.setItem("hezarfen.podcast.note-7", "pj1");
62+ podcastApi.listPodcastJobs.mockResolvedValue({
63+ items: [
64+ {
65+ job_id: "pj1",
66+ state: "done",
67+ format: "duz_okuma",
68+ source_id: "note-7",
69+ source_title: "Hücre ve Canlıların Ortak Özellikleri",
70+ created_at: 1,
71+ finished_at: 2,
72+ duration_secs: 42,
73+ error_code: null,
74+ },
75+ ],
76+ total: 1,
77+ limit: 10,
78+ offset: 0,
79+ });
61 podcastApi.getPodcastJobById.mockResolvedValue({ job_id: "pj1", state: "done", stage: "done", progress: 1 });80 podcastApi.getPodcastJobById.mockResolvedValue({ job_id: "pj1", state: "done", stage: "done", progress: 1 });
62 podcastApi.getPodcastJobResultById.mockResolvedValue({81 podcastApi.getPodcastJobResultById.mockResolvedValue({
63 job_id: "pj1",82 job_id: "pj1",
@@ -72,15 +91,33 @@ describe("PodcastPanel", () => {
72 </PreferencesProvider>91 </PreferencesProvider>
73 ));92 ));
74 93
94+ // The finished job hands off to the episode list, which selects it.
75 await waitFor(() => {95 await waitFor(() => {
76- expect(screen.getByText("Your episode is ready.")).toBeTruthy();96+ expect(document.querySelector("audio")?.getAttribute("src")).toBe("/api/podcast/jobs/pj1/audio");
77 });97 });
78 expect(podcastApi.podcastAudioUrl).toHaveBeenCalledWith("pj1");98 expect(podcastApi.podcastAudioUrl).toHaveBeenCalledWith("pj1");
79- expect(document.querySelector("audio")?.getAttribute("src")).toBe("/api/podcast/jobs/pj1/audio");
80 });99 });
81 100
82 it("downloads the finished episode under the note's own title", async () => {101 it("downloads the finished episode under the note's own title", async () => {
83 sessionStorage.setItem("hezarfen.podcast.note-7", "pj1");102 sessionStorage.setItem("hezarfen.podcast.note-7", "pj1");
103+ podcastApi.listPodcastJobs.mockResolvedValue({
104+ items: [
105+ {
106+ job_id: "pj1",
107+ state: "done",
108+ format: "duz_okuma",
109+ source_id: "note-7",
110+ source_title: "Hücre ve Canlıların Ortak Özellikleri",
111+ created_at: 1,
112+ finished_at: 2,
113+ duration_secs: 42,
114+ error_code: null,
115+ },
116+ ],
117+ total: 1,
118+ limit: 10,
119+ offset: 0,
120+ });
84 podcastApi.getPodcastJobById.mockResolvedValue({ job_id: "pj1", state: "done", stage: "done", progress: 1 });121 podcastApi.getPodcastJobById.mockResolvedValue({ job_id: "pj1", state: "done", stage: "done", progress: 1 });
85 podcastApi.getPodcastJobResultById.mockResolvedValue({122 podcastApi.getPodcastJobResultById.mockResolvedValue({
86 job_id: "pj1",123 job_id: "pj1",
@@ -96,15 +133,16 @@ describe("PodcastPanel", () => {
96 ));133 ));
97 134
98 await waitFor(() => {135 await waitFor(() => {
99- expect(screen.getByText("Your episode is ready.")).toBeTruthy();136+ expect(screen.getAllByRole("link", { name: "Download episode" }).length).toBeGreaterThan(0);
100 });137 });
101- const link = screen.getByRole("link", { name: "Download episode" }) as HTMLAnchorElement;138+ const link = screen.getAllByRole("link", { name: "Download episode" })[0] as HTMLAnchorElement;
102 expect(link.getAttribute("href")).toBe("/api/podcast/jobs/pj1/audio");139 expect(link.getAttribute("href")).toBe("/api/podcast/jobs/pj1/audio");
103 expect(link.getAttribute("download")).toBe("Hücre ve Canlıların Ortak Özellikleri.mp3");140 expect(link.getAttribute("download")).toBe("Hücre ve Canlıların Ortak Özellikleri.mp3");
104 });141 });
105 142
106 it("shows no download control while the episode is still being made", async () => {143 it("shows no download control while the episode is still being made", async () => {
107 sessionStorage.setItem("hezarfen.podcast.note-7", "pj2");144 sessionStorage.setItem("hezarfen.podcast.note-7", "pj2");
145+ podcastApi.listPodcastJobs.mockResolvedValue({ items: [], total: 0, limit: 10, offset: 0 });
108 podcastApi.getPodcastJobById.mockResolvedValue({ job_id: "pj2", state: "running", stage: "script", progress: 0.4 });146 podcastApi.getPodcastJobById.mockResolvedValue({ job_id: "pj2", state: "running", stage: "script", progress: 0.4 });
109 147
110 render(() => (148 render(() => (
src/components/notes/podcast-panel.tsxmodified+5 -17
@@ -10,7 +10,6 @@ import { Label } from "@/components/ui/label";
10 import { Select } from "@/components/ui/select";10 import { Select } from "@/components/ui/select";
11 import { PodcastHistory } from "@/components/notes/podcast-history";11 import { PodcastHistory } from "@/components/notes/podcast-history";
12 import { PodcastStageTrail, type PodcastStageEntry } from "@/components/notes/podcast-stage-trail";12 import { PodcastStageTrail, type PodcastStageEntry } from "@/components/notes/podcast-stage-trail";
13-import { PodcastPlayer } from "@/components/notes/podcast-player";
14 import { createLivePoll } from "@/lib/create-live-poll";13 import { createLivePoll } from "@/lib/create-live-poll";
15 import { useT } from "@/stores/preferences-context";14 import { useT } from "@/stores/preferences-context";
16 15
@@ -205,7 +204,8 @@ export function PodcastPanel(props: { noteId: string; active?: boolean; noteTitl
205 </Button>204 </Button>
206 </div>205 </div>
207 206
208- <Show when={status()}>207+ {/* A finished job hands off to the episode list, which selects it. */}
208+ <Show when={status()?.state === "done" ? null : status()}>
209 {(current) => (209 {(current) => (
210 <div class="space-y-3 rounded-lg border border-border-hairline bg-surface-overlay/40 p-3">210 <div class="space-y-3 rounded-lg border border-border-hairline bg-surface-overlay/40 p-3">
211 {/* Compact textual metadata over a progress bar: the state, how far211 {/* Compact textual metadata over a progress bar: the state, how far
@@ -238,25 +238,13 @@ export function PodcastPanel(props: { noteId: string; active?: boolean; noteTitl
238 )}238 )}
239 </Show>239 </Show>
240 240
241- <Show when={artifacts()}>
242- {(result) => (
243- <div class="space-y-2 rounded-lg border border-success/25 bg-success/5 p-3">
244- <p class="text-sm font-medium">{t("podcast.ready")}</p>
245- <PodcastPlayer
246- jobId={result().job_id}
247- title={props.noteTitle}
248- subtitle={result().format ? formatOptions().find((option) => option.value === result().format)?.label : undefined}
249- durationSecs={result().duration_secs}
250- transcript={result().transcript}
251- />
252- </div>
253- )}
254- </Show>
255-
256 <PodcastHistory241 <PodcastHistory
257 noteId={props.noteId}242 noteId={props.noteId}
258 active={active()}243 active={active()}
259 refetchKey={status()?.state === "done" ? jobId() : ""}244 refetchKey={status()?.state === "done" ? jobId() : ""}
245+ transcript={
246+ artifacts()?.transcript?.length ? { jobId: artifacts()!.job_id, segments: artifacts()!.transcript! } : null
247+ }
260 />248 />
261 </section>249 </section>
262 </Suspense>250 </Suspense>
src/components/notes/podcast-player.test.tsxmodified+6 -0
@@ -33,6 +33,12 @@ describe("PodcastPlayer", () => {
33 vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(() => {});33 vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(() => {});
34 // Nor element scrolling, which the transcript's follow uses.34 // Nor element scrolling, which the transcript's follow uses.
35 Element.prototype.scrollTo ??= () => {};35 Element.prototype.scrollTo ??= () => {};
36+ // A stream the server lets the browser seek in, so no local copy is loaded.
37+ vi.spyOn(HTMLMediaElement.prototype, "seekable", "get").mockReturnValue({
38+ length: 1,
39+ start: () => 0,
40+ end: () => 754,
41+ } as unknown as TimeRanges);
36 });42 });
37 43
38 afterEach(() => {44 afterEach(() => {
src/components/notes/podcast-player.tsxmodified+5 -2
@@ -1,5 +1,5 @@
1 import { Show, createSignal } from "solid-js";1 import { Show, createSignal } from "solid-js";
2-import { podcastAudioUrl } from "@/api/podcast";2+import { getPodcastJobAudioBlob, podcastAudioUrl } from "@/api/podcast";
3 import type { PodcastTranscriptSegment } from "@/api/client";3 import type { PodcastTranscriptSegment } from "@/api/client";
4 import { AudioPlayer, type AudioPlayerController } from "@/components/ui/audio-player";4 import { AudioPlayer, type AudioPlayerController } from "@/components/ui/audio-player";
5 import { IconDownload, IconTranscript } from "@/components/ui/icons";5 import { IconDownload, IconTranscript } from "@/components/ui/icons";
@@ -22,6 +22,8 @@ export function PodcastPlayer(props: {
22 autoplay?: boolean;22 autoplay?: boolean;
23 /** Off where the surrounding row already offers the download. */23 /** Off where the surrounding row already offers the download. */
24 download?: boolean;24 download?: boolean;
25+ /** The download's filename stem; defaults to the title. */
26+ downloadName?: string;
25 class?: string;27 class?: string;
26 }) {28 }) {
27 const t = useT();29 const t = useT();
@@ -38,6 +40,7 @@ export function PodcastPlayer(props: {
38 title={props.title}40 title={props.title}
39 subtitle={props.subtitle}41 subtitle={props.subtitle}
40 durationHint={props.durationSecs}42 durationHint={props.durationSecs}
43+ loadBlob={(signal) => getPodcastJobAudioBlob(props.jobId, signal)}
41 autoplay={props.autoplay}44 autoplay={props.autoplay}
42 onTimeUpdate={setCurrentSecs}45 onTimeUpdate={setCurrentSecs}
43 controller={(value) => (controller = value)}46 controller={(value) => (controller = value)}
@@ -45,7 +48,7 @@ export function PodcastPlayer(props: {
45 <Show when={props.download !== false}>48 <Show when={props.download !== false}>
46 <a49 <a
47 href={podcastAudioUrl(props.jobId)}50 href={podcastAudioUrl(props.jobId)}
48- download={podcastDownloadFilename(props.title, downloadT("podcast.download.fallback"))}51+ download={podcastDownloadFilename(props.downloadName ?? props.title, downloadT("podcast.download.fallback"))}
49 aria-label={downloadT("podcast.download.aria")}52 aria-label={downloadT("podcast.download.aria")}
50 title={downloadT("podcast.download.label")}53 title={downloadT("podcast.download.label")}
51 class="inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"54 class="inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
src/components/ui/audio-player.tsxmodified+122 -8
@@ -51,6 +51,12 @@ export type AudioPlayerProps = {
51 actions?: JSX.Element;51 actions?: JSX.Element;
52 /** Extra controls at the end of the transport row (transcript toggle, …). */52 /** Extra controls at the end of the transport row (transcript toggle, …). */
53 extra?: JSX.Element;53 extra?: JSX.Element;
54+ /**
55+ * Loads the whole file. Given, a seek the stream cannot serve (a server
56+ * that ignores `Range` leaves `seekable` empty) switches the player to a
57+ * local copy of it instead of snapping back to 0:00.
58+ */
59+ loadBlob?: (signal: AbortSignal) => Promise<Blob>;
54 onTimeUpdate?: (secs: number) => void;60 onTimeUpdate?: (secs: number) => void;
55 controller?: (controller: AudioPlayerController) => void;61 controller?: (controller: AudioPlayerController) => void;
56 class?: string;62 class?: string;
@@ -77,6 +83,54 @@ export function AudioPlayer(props: AudioPlayerProps) {
77 const [volume, setVolume] = createSignal(readStored(VOLUME_KEY, 1, (v) => v >= 0 && v <= 1));83 const [volume, setVolume] = createSignal(readStored(VOLUME_KEY, 1, (v) => v >= 0 && v <= 1));
78 const [muted, setMuted] = createSignal(false);84 const [muted, setMuted] = createSignal(false);
79 const [failed, setFailed] = createSignal(false);85 const [failed, setFailed] = createSignal(false);
86+ // Seeking waits on the local copy; the seek bar already shows the target.
87+ const [seeking, setSeeking] = createSignal(false);
88+ const [source, setSource] = createSignal(props.src);
89+
90+ // The local copy of the file, loaded once per `src` on first play or on the
91+ // first seek the stream cannot serve.
92+ let objectUrl: string | null = null;
93+ let localLoad: Promise<string | null> | null = null;
94+ let abort: AbortController | null = null;
95+ let pendingSeek: number | null = null;
96+ let resumeAfterSeek = false;
97+ let seekToken = 0;
98+ let afterLoad: (() => void) | null = null;
99+
100+ const dropLocal = () => {
101+ abort?.abort();
102+ abort = null;
103+ localLoad = null;
104+ if (objectUrl) URL.revokeObjectURL(objectUrl);
105+ objectUrl = null;
106+ };
107+ const loadLocal = (): Promise<string | null> => {
108+ const load = props.loadBlob;
109+ if (!load) return Promise.resolve(null);
110+ if (!localLoad) {
111+ const controller = new AbortController();
112+ abort = controller;
113+ localLoad = load(controller.signal).then(
114+ (blob) => {
115+ if (controller.signal.aborted) return null;
116+ objectUrl = URL.createObjectURL(blob);
117+ return objectUrl;
118+ },
119+ () => {
120+ if (abort === controller) localLoad = null;
121+ return null;
122+ },
123+ );
124+ }
125+ return localLoad;
126+ };
127+ const canSeekTo = (secs: number) => {
128+ const ranges = audio.seekable;
129+ for (let i = 0; i < ranges.length; i += 1) {
130+ if (ranges.end(i) > 0 && secs >= ranges.start(i) && secs <= ranges.end(i)) return true;
131+ }
132+ return false;
133+ };
80 134
81 const duration = () => mediaDuration() ?? (props.durationHint && props.durationHint > 0 ? props.durationHint : null);135 const duration = () => mediaDuration() ?? (props.durationHint && props.durationHint > 0 ? props.durationHint : null);
82 const fraction = (value: number) => {136 const fraction = (value: number) => {
@@ -87,10 +141,50 @@ export function AudioPlayer(props: AudioPlayerProps) {
87 const seek = (secs: number) => {141 const seek = (secs: number) => {
88 const total = duration();142 const total = duration();
89 const next = Math.max(0, total ? Math.min(total, secs) : secs);143 const next = Math.max(0, total ? Math.min(total, secs) : secs);
90- audio.currentTime = next;
91 setCurrent(next);144 setCurrent(next);
145+ if (!props.loadBlob || canSeekTo(next)) {
146+ audio.currentTime = next;
147+ return;
148+ }
149+ // The stream cannot go there: hold the target, pause the stream at its
150+ // wrong position, and resume from the target on the local copy.
151+ const token = ++seekToken;
152+ pendingSeek = next;
153+ resumeAfterSeek ||= !audio.paused;
154+ audio.pause();
155+ setSeeking(true);
156+ void loadLocal().then((url) => {
157+ if (token !== seekToken) return;
158+ const at = pendingSeek ?? next;
159+ const resume = resumeAfterSeek;
160+ pendingSeek = null;
161+ resumeAfterSeek = false;
162+ if (!url) {
163+ setSeeking(false);
164+ setCurrent(audio.currentTime);
165+ setFailed(true);
166+ return;
167+ }
168+ afterLoad = () => {
169+ audio.currentTime = at;
170+ setCurrent(at);
171+ setSeeking(false);
172+ if (resume) play();
173+ };
174+ if (source() === url) {
175+ const run = afterLoad;
176+ afterLoad = null;
177+ run();
178+ } else {
179+ setSource(url);
180+ }
181+ });
92 };182 };
93 const play = () => {183 const play = () => {
184+ if (pendingSeek != null) {
185+ resumeAfterSeek = true;
186+ return;
187+ }
94 setFailed(false);188 setFailed(false);
95 void audio.play().catch(() => {189 void audio.play().catch(() => {
96 // A refused autoplay or an aborted load is not a broken file; the190 // A refused autoplay or an aborted load is not a broken file; the
@@ -98,7 +192,11 @@ export function AudioPlayer(props: AudioPlayerProps) {
98 setPlaying(false);192 setPlaying(false);
99 });193 });
100 };194 };
101- const toggle = () => (audio.paused ? play() : audio.pause());195+ const toggle = () => {
196+ if (pendingSeek != null) resumeAfterSeek = !resumeAfterSeek;
197+ else if (audio.paused) play();
198+ else audio.pause();
199+ };
102 const skip = (delta: number) => seek(audio.currentTime + delta);200 const skip = (delta: number) => seek(audio.currentTime + delta);
103 const cycleRate = () => {201 const cycleRate = () => {
104 const index = RATES.indexOf(rate() as (typeof RATES)[number]);202 const index = RATES.indexOf(rate() as (typeof RATES)[number]);
@@ -120,6 +218,7 @@ export function AudioPlayer(props: AudioPlayerProps) {
120 onCleanup(() => {218 onCleanup(() => {
121 players.delete(audio);219 players.delete(audio);
122 audio?.pause();220 audio?.pause();
221+ dropLocal();
123 });222 });
124 223
125 createEffect(() => {224 createEffect(() => {
@@ -133,7 +232,14 @@ export function AudioPlayer(props: AudioPlayerProps) {
133 });232 });
134 // A new episode in the same player starts from its own beginning.233 // A new episode in the same player starts from its own beginning.
135 createEffect(() => {234 createEffect(() => {
136- void props.src;235+ const src = props.src;
236+ dropLocal();
237+ seekToken += 1;
238+ pendingSeek = null;
239+ resumeAfterSeek = false;
240+ afterLoad = null;
241+ setSeeking(false);
242+ setSource(src);
137 setCurrent(0);243 setCurrent(0);
138 setMediaDuration(null);244 setMediaDuration(null);
139 setBuffered(0);245 setBuffered(0);
@@ -184,22 +290,30 @@ export function AudioPlayer(props: AudioPlayerProps) {
184 >290 >
185 <audio291 <audio
186 ref={audio}292 ref={audio}
187- src={props.src}293+ src={source()}
188 preload="metadata"294 preload="metadata"
189 autoplay={props.autoplay}295 autoplay={props.autoplay}
190 onPlay={() => {296 onPlay={() => {
191 for (const other of players) if (other !== audio) other.pause();297 for (const other of players) if (other !== audio) other.pause();
192 setPlaying(true);298 setPlaying(true);
299+ // Fetched while the stream plays, so later skips are instant.
300+ void loadLocal();
193 }}301 }}
194 onPause={() => setPlaying(false)}302 onPause={() => setPlaying(false)}
195 onEnded={() => setPlaying(false)}303 onEnded={() => setPlaying(false)}
196 onWaiting={() => setBuffering(true)}304 onWaiting={() => setBuffering(true)}
197 onPlaying={() => setBuffering(false)}305 onPlaying={() => setBuffering(false)}
198 onCanPlay={() => setBuffering(false)}306 onCanPlay={() => setBuffering(false)}
199- onLoadedMetadata={syncDuration}307+ onLoadedMetadata={() => {
308+ syncDuration();
309+ const run = afterLoad;
310+ afterLoad = null;
311+ run?.();
312+ }}
200 onDurationChange={syncDuration}313 onDurationChange={syncDuration}
201 onProgress={syncBuffered}314 onProgress={syncBuffered}
202 onTimeUpdate={() => {315 onTimeUpdate={() => {
316+ if (pendingSeek != null) return;
203 setCurrent(audio.currentTime);317 setCurrent(audio.currentTime);
204 props.onTimeUpdate?.(audio.currentTime);318 props.onTimeUpdate?.(audio.currentTime);
205 }}319 }}
@@ -215,12 +329,12 @@ export function AudioPlayer(props: AudioPlayerProps) {
215 type="button"329 type="button"
216 class={cn(330 class={cn(
217 "relative flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",331 "relative flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
218- buffering() && playing() && "animate-pulse",332+ (seeking() || (buffering() && playing())) && "animate-pulse",
219 )}333 )}
220- aria-label={playing() ? t("audio.pause") : t("audio.play")}334+ aria-label={playing() || seeking() ? t("audio.pause") : t("audio.play")}
221 onClick={toggle}335 onClick={toggle}
222 >336 >
223- <Show when={playing()} fallback={<IconPlay class="ml-0.5 h-5 w-5" />}>337+ <Show when={playing() || seeking()} fallback={<IconPlay class="ml-0.5 h-5 w-5" />}>
224 <IconPause class="h-5 w-5" />338 <IconPause class="h-5 w-5" />
225 </Show>339 </Show>
226 </button>340 </button>
src/i18n/locales/en.tsmodified+2 -2
@@ -1063,7 +1063,6 @@ export const en: Dict = {
1063 "podcast.create": "Create podcast",1063 "podcast.create": "Create podcast",
1064 "podcast.submitting": "Starting…",1064 "podcast.submitting": "Starting…",
1065 "podcast.cancel": "Cancel production",1065 "podcast.cancel": "Cancel production",
1066- "podcast.ready": "Your episode is ready.",
1067 "podcast.failed": "The podcast could not be created. Try again.",1066 "podcast.failed": "The podcast could not be created. Try again.",
1068 "podcast.unavailable": "Podcast production is not connected right now. Try again when a podcast worker is available.",1067 "podcast.unavailable": "Podcast production is not connected right now. Try again when a podcast worker is available.",
1069 "podcast.state.queued": "Waiting in queue",1068 "podcast.state.queued": "Waiting in queue",
@@ -1071,7 +1070,8 @@ export const en: Dict = {
1071 "podcast.state.done": "Ready",1070 "podcast.state.done": "Ready",
1072 "podcast.state.failed": "Failed",1071 "podcast.state.failed": "Failed",
1073 "podcast.state.cancelled": "Cancelled",1072 "podcast.state.cancelled": "Cancelled",
1074- "podcast.history.title": "Recent episodes",1073+ "podcast.history.title": "Episodes",
1074+ "podcast.history.episode": "Episode",
1075 "podcast.history.state.pending": "Preparing",1075 "podcast.history.state.pending": "Preparing",
1076 "podcast.history.state.done": "Ready",1076 "podcast.history.state.done": "Ready",
1077 "podcast.history.state.failed": "Failed",1077 "podcast.history.state.failed": "Failed",
src/i18n/locales/tr.tsmodified+2 -2
@@ -1059,7 +1059,6 @@ export const tr: Dict = {
1059 "podcast.create": "Podcast oluştur",1059 "podcast.create": "Podcast oluştur",
1060 "podcast.submitting": "Başlatılıyor…",1060 "podcast.submitting": "Başlatılıyor…",
1061 "podcast.cancel": "Üretimi iptal et",1061 "podcast.cancel": "Üretimi iptal et",
1062- "podcast.ready": "Bölümünüz hazır.",
1063 "podcast.failed": "Podcast oluşturulamadı. Tekrar deneyin.",1062 "podcast.failed": "Podcast oluşturulamadı. Tekrar deneyin.",
1064 "podcast.unavailable": "Podcast üretim servisi şu anda bağlı değil. Podcast worker hazır olduğunda tekrar deneyin.",1063 "podcast.unavailable": "Podcast üretim servisi şu anda bağlı değil. Podcast worker hazır olduğunda tekrar deneyin.",
1065 "podcast.state.queued": "Sırada bekliyor",1064 "podcast.state.queued": "Sırada bekliyor",
@@ -1067,7 +1066,8 @@ export const tr: Dict = {
1067 "podcast.state.done": "Hazır",1066 "podcast.state.done": "Hazır",
1068 "podcast.state.failed": "Başarısız",1067 "podcast.state.failed": "Başarısız",
1069 "podcast.state.cancelled": "İptal edildi",1068 "podcast.state.cancelled": "İptal edildi",
1070- "podcast.history.title": "Son bölümler",1069+ "podcast.history.title": "Bölümler",
1070+ "podcast.history.episode": "Bölüm",
1071 "podcast.history.state.pending": "Hazırlanıyor",1071 "podcast.history.state.pending": "Hazırlanıyor",
1072 "podcast.history.state.done": "Hazır",1072 "podcast.history.state.done": "Hazır",
1073 "podcast.history.state.failed": "Başarısız",1073 "podcast.history.state.failed": "Başarısız",
src/i18n/messages.tsmodified+1 -1
@@ -1050,7 +1050,6 @@ export type MessageKey =
1050 | "podcast.create"1050 | "podcast.create"
1051 | "podcast.submitting"1051 | "podcast.submitting"
1052 | "podcast.cancel"1052 | "podcast.cancel"
1053- | "podcast.ready"
1054 | "podcast.failed"1053 | "podcast.failed"
1055 | "podcast.unavailable"1054 | "podcast.unavailable"
1056 | "podcast.state.queued"1055 | "podcast.state.queued"
@@ -1059,6 +1058,7 @@ export type MessageKey =
1059 | "podcast.state.failed"1058 | "podcast.state.failed"
1060 | "podcast.state.cancelled"1059 | "podcast.state.cancelled"
1061 | "podcast.history.title"1060 | "podcast.history.title"
1061+ | "podcast.history.episode"
1062 | "podcast.history.state.pending"1062 | "podcast.history.state.pending"
1063 | "podcast.history.state.done"1063 | "podcast.history.state.done"
1064 | "podcast.history.state.failed"1064 | "podcast.history.state.failed"
src/routes/router.tsxmodified+6 -3
@@ -12,6 +12,7 @@ import { NotFoundPage } from "@/components/system/not-found-page";
12 import { PageSpinner } from "@/components/ui/page-spinner";12 import { PageSpinner } from "@/components/ui/page-spinner";
13 import { AuthProvider } from "@/stores/auth-context";13 import { AuthProvider } from "@/stores/auth-context";
14 import { ModulesProvider } from "@/stores/modules-context";14 import { ModulesProvider } from "@/stores/modules-context";
15+import { SchoolProvider } from "@/stores/school-context";
15 import { AttendanceRedirect } from "@/components/layout/attendance-redirect";16 import { AttendanceRedirect } from "@/components/layout/attendance-redirect";
16 import { PreferencesProvider } from "@/stores/preferences-context";17 import { PreferencesProvider } from "@/stores/preferences-context";
17 18
@@ -90,9 +91,11 @@ function RootComponent() {
90 <PreferencesProvider>91 <PreferencesProvider>
91 <AuthProvider>92 <AuthProvider>
92 <ModulesProvider>93 <ModulesProvider>
93- <AppShell>94+ <SchoolProvider>
94- <Outlet />95+ <AppShell>
95- </AppShell>96+ <Outlet />
97+ </AppShell>
98+ </SchoolProvider>
96 </ModulesProvider>99 </ModulesProvider>
97 </AuthProvider>100 </AuthProvider>
98 </PreferencesProvider>101 </PreferencesProvider>
src/stores/school-context.tsxadded+39 -0
@@ -0,0 +1,39 @@
1+import { type Accessor, type ParentProps, createContext, createMemo, useContext } from "solid-js";
2+import { createResource } from "@/lib/create-resource";
3+import { getSchool } from "@/api/school";
4+import { useAuth } from "@/stores/auth-context";
5+
6+type SchoolContextValue = {
7+ /** The session school's display name; null while logged out, loading, or failed. */
8+ name: Accessor<string | null>;
9+};
10+
11+const SchoolContext = createContext<SchoolContextValue>();
12+
13+export function SchoolProvider(props: ParentProps) {
14+ const auth = useAuth();
15+ // Keyed on the account id, so switching school (a new session) refetches.
16+ // Seeded with null so no reader ever suspends the shell on it.
17+ const userId = createMemo(() => auth.user()?.id ?? null);
18+ const [school] = createResource(
19+ userId,
20+ async (id) => {
21+ if (id === null) return null;
22+ try {
23+ return await getSchool();
24+ } catch {
25+ return null;
26+ }
27+ },
28+ { initialValue: null },
29+ );
30+
31+ return <SchoolContext.Provider value={{ name: () => school()?.name ?? null }}>{props.children}</SchoolContext.Provider>;
32+}
33+
34+const NO_SCHOOL: SchoolContextValue = { name: () => null };
35+
36+/** Outside a provider (isolated component tests) there is simply no name to show. */
37+export function useSchool(): SchoolContextValue {
38+ return useContext(SchoolContext) ?? NO_SCHOOL;
39+}