import { For, Show, Suspense, createEffect, createSignal, onCleanup } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { getAiCapabilities } from "@/api/ai"; import { getPodcastJobById, getPodcastJobResultById, podcastAudioUrl, postPodcastJob, postPodcastJobCancel, } from "@/api/podcast"; import { formatApiError, type PodcastFormat, type PodcastJobArtifacts, type PodcastJobStatus } from "@/api/client"; import { Alert } from "@/components/ui/alert"; import { Button, buttonVariants } from "@/components/ui/button"; import { IconDownload, IconWaveform, IconX } from "@/components/ui/icons"; import { Label } from "@/components/ui/label"; import { Select } from "@/components/ui/select"; import { PodcastHistory } from "@/components/notes/podcast-history"; import { podcastDownloadFilename, usePodcastDownloadT } from "@/components/notes/podcast-download"; import { cn } from "@/lib/cn"; import { createLivePoll } from "@/lib/create-live-poll"; import { useT } from "@/stores/preferences-context"; const POLL_MS = 2_000; export function PodcastPanel(props: { noteId: string; active?: boolean; noteTitle?: string }) { const t = useT(); const downloadT = usePodcastDownloadT(); const [format, setFormat] = createSignal("duz_okuma"); const [jobId, setJobId] = createSignal(""); const [status, setStatus] = createSignal(null); const [artifacts, setArtifacts] = createSignal(null); const [error, setError] = createSignal(""); const [submitting, setSubmitting] = createSignal(false); const [cancelling, setCancelling] = createSignal(false); // The service's own estimate, taken from the submit receipt. It is never // restated by the status door, so it is shown as the one estimate it is and // never recomputed into a countdown the backend did not promise. const [etaSecs, setEtaSecs] = createSignal(null); let generation = 0; // Declared before the resource below: its source runs during setup, so a // later `const active` would be read in its temporal dead zone. const active = () => props.active !== false; const [capabilities] = createResource(() => (active() ? getAiCapabilities() : null)); const storageKey = () => `hezarfen.podcast.${props.noteId}`; // A cancelled or finished job is simply not polled again; the ticker below // asks whether there is live work rather than being torn down. const stopPolling = () => { generation += 1; }; const poll = async (id: string, token: number) => { try { const next = await getPodcastJobById(id); if (token !== generation || !active()) return; setStatus(next); if (next.state === "done") { const result = await getPodcastJobResultById(id); if (token === generation) setArtifacts(result); return; } if (next.state === "failed") { setError(t("podcast.failed")); } } catch (err) { if (token === generation) setError(formatApiError(err)); } }; createEffect(() => { const noteId = props.noteId; const enabled = active(); generation += 1; const token = generation; setJobId(""); setStatus(null); setArtifacts(null); setEtaSecs(null); setError(""); if (!enabled || !noteId || typeof sessionStorage === "undefined") return; const stored = sessionStorage.getItem(storageKey()); if (stored) { setJobId(stored); void poll(stored, token); } }); onCleanup(() => { generation += 1; }); const submit = async () => { if (submitting()) return; generation += 1; const token = generation; setSubmitting(true); setError(""); setArtifacts(null); try { const receipt = await postPodcastJob({ source_id: props.noteId, format: format() }); if (token !== generation) return; setJobId(receipt.job_id); setStatus({ job_id: receipt.job_id, state: receipt.state, stage: "queued", progress: 0 }); setEtaSecs(receipt.eta_secs); if (typeof sessionStorage !== "undefined") sessionStorage.setItem(storageKey(), receipt.job_id); } catch (err) { setError(formatApiError(err)); } finally { if (token === generation) setSubmitting(false); } }; const cancel = async () => { const id = jobId(); if (!id || cancelling()) return; setCancelling(true); setError(""); try { await postPodcastJobCancel(id); stopPolling(); setStatus((current) => current ? { ...current, state: "cancelled" } : current); if (typeof sessionStorage !== "undefined") sessionStorage.removeItem(storageKey()); } catch (err) { setError(formatApiError(err)); } finally { setCancelling(false); } }; const progress = () => Math.round(Math.min(1, Math.max(0, status()?.progress ?? 0)) * 100); const working = () => ["queued", "running"].includes(status()?.state ?? ""); // Poll through the shared primitive so a parked tab stops asking and a // tab-back is fresh at once — the hand-rolled timeout chain did neither. createLivePoll(() => { const id = jobId(); if (id && working() && active()) void poll(id, generation); }, POLL_MS); const available = () => { const current = capabilities(); if (!current || capabilities.error) return true; return current.enabled && current.capabilities.some((item) => item.capability === "podcast.submit" && item.workers > 0); }; const stateLabel = (state: string) => { if (state === "queued") return t("podcast.state.queued"); if (state === "running") return t("podcast.state.running"); if (state === "done") return t("podcast.state.done"); if (state === "failed") return t("podcast.state.failed"); if (state === "cancelled") return t("podcast.state.cancelled"); return t("podcast.state.running"); }; const formatOptions = () => [ { value: "duz_okuma", label: t("podcast.format.duz_okuma") }, { value: "tek_ogretici", label: t("podcast.format.tek_ogretici") }, { value: "ogrenci_hoca", label: t("podcast.format.ogrenci_hoca") }, ]; return (

{t("common.loading")}

} >

{t("podcast.title")}

{t("podcast.description")}

{(message) => {message()}} {t("podcast.unavailable")}
{(current) => (
{stateLabel(current().state)} {progress()}%
{/* The stage names itself in the service's own vocabulary and is not an enumerated set, so only the prefix is translated — the value is shown as it came rather than guessed at. */}
{(stage) => ( {t("podcast.stageLabel")} {stage()} )} {t("podcast.etaHint", { secs: etaSecs()! })}
)} {(result) => (

{t("podcast.ready")}

{downloadT("podcast.download.label")}
)}
); }