"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
// THE SPEAKER BADGE ON THE WALK (UI notes 2026-10-30, #15): "Speaker: matches
// Ember 0.93 / Kirsche 0.83", with the reference sets it was measured against,
// and "Check speaker", which queues `umtool speaker-check
--clip ` as
// a job through the machine's heavy slot (POST /api/report/speaker-check). The
// voices are the project's speakers.json; "Add to a voice" puts this clip in
// one. An aid to the ear: the verdict is still the walk's.
type Score = { name: string; score: number; best: number | null; inReference?: boolean };
type Badge = {
speakers: { name: string; clips: string[]; videos: string[]; channels: string[]; inReference: boolean }[];
result: null | { scores: Score[]; label?: "matches" | "unsure" | "none"; best?: string; margin?: number | null; why?: string; line: string; madeAt: string | null; speechSeconds?: number };
reference: null | { name: string; pieces: number; kept: number; clips: string[]; recordings: { channel: string; video: string }[] }[];
running: null | { id: string; state: string };
error?: string;
};
type JobPoll = { id: string; state: "running" | "done" | "failed"; error: string | null; log: string[] };
export default function SpeakerBadge({ project, clip }: { project: string; clip: string }) {
const [badge, setBadge] = useState(null);
const [job, setJob] = useState(null);
const [err, setErr] = useState(null);
const [voice, setVoice] = useState("");
const [adding, setAdding] = useState(false);
const timer = useRef | null>(null);
const load = useCallback(async () => {
const r = await fetch(`/api/report/speaker-check?project=${encodeURIComponent(project)}&clip=${encodeURIComponent(clip)}`, { cache: "no-store" });
const j = (await r.json().catch(() => null)) as Badge | null;
if (!r.ok || !j) {
setErr(j?.error ?? `HTTP ${r.status}`);
return;
}
setBadge(j);
}, [project, clip]);
useEffect(() => {
void load();
return () => {
if (timer.current) clearTimeout(timer.current);
};
}, [load]);
const follow = useCallback(
(id: string) => {
const tick = async () => {
const r = await fetch(`/api/report/speaker-check?job=${encodeURIComponent(id)}`, { cache: "no-store" });
const j = (await r.json().catch(() => null)) as JobPoll | null;
if (!j) return;
setJob(j);
if (j.state === "running") timer.current = setTimeout(() => void tick(), 1000);
else void load();
};
void tick();
},
[load],
);
const check = async () => {
setErr(null);
const r = await fetch("/api/report/speaker-check", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ project, clip }),
});
const j = (await r.json().catch(() => ({}))) as { job?: { id: string }; error?: string };
if (!r.ok || !j.job) {
setErr(j.error ?? `HTTP ${r.status}`);
return;
}
follow(j.job.id);
};
const addTo = async () => {
const name = voice.trim();
if (!name) return;
setErr(null);
const r = await fetch("/api/report/speaker-check", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ project, clip, addTo: name }),
});
const j = (await r.json().catch(() => ({}))) as { error?: string };
if (!r.ok) setErr(j.error ?? `HTTP ${r.status}`);
setVoice("");
setAdding(false);
void load();
};
if (!badge) return err ? {err} : null;
const res = badge.result;
const running = job?.state === "running" || (!!badge.running && !job);
const label = res?.label ?? (res ? "unscored" : "unchecked");
const tone = label === "matches" ? "text-[var(--color-good)]" : label === "none" ? "text-[var(--color-dirty)]" : "text-text-2";
const mine = badge.speakers.find((s) => s.inReference);
const refWords = (badge.reference ?? badge.speakers.map((s) => ({ name: s.name, pieces: s.clips.length + s.videos.length, kept: 0, clips: s.clips, recordings: [] })))
.map((s) => `${s.name}: ${s.pieces} piece${s.pieces === 1 ? "" : "s"}${s.kept ? ` (${s.kept} kept)` : ""}`)
.join(" · ");
// Compact: one line in the verdict bar (the bench is a one-screen layout at
// 1366×768 -- clip-bench.spec), the voice box only when asked for.
const refShort = (badge.reference ?? badge.speakers.map((s) => ({ name: s.name, pieces: s.clips.length + s.videos.length })))
.map((s) => `${s.name} ${s.pieces}`)
.join(" · ");
return (
Speaker: {res ? res.line : badge.speakers.length ? "not checked" : "no voices named"}
{res && (
vs {refShort || "—"}
)}
{mine && in {mine.name}’s voice }
void check()}
className={buttonVariants({ variant: "quiet", size: "sm" })}
title={
badge.speakers.length
? "scores this clip's voice against each named voice (TitaNet-small, local) as a job through the heavy slot"
: "name the voices first: + voice, or umtool speaker-check --set 'Name=…'"
}
>
{running ? "Checking…" : "Check speaker"}
{adding ? (
setVoice(e.target.value)}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Enter") void addTo();
if (e.key === "Escape") setAdding(false);
}}
placeholder="voice name"
className="w-[7.5rem] rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px]"
/>
{badge.speakers.map((s) => (
))}
void addTo()} className={buttonVariants({ variant: "quiet", size: "sm" })} title="this clip is that voice: it joins the voice's reference set (speakers.json)">
Add
) : (
setAdding(true)} className={buttonVariants({ variant: "quiet", size: "sm" })} title="this clip is a known voice: add it to that voice's reference set (speakers.json)">
+ voice
)}
{job?.state === "failed" && (
{job.error ?? job.log.at(-1) ?? "the check failed"}
)}
{err && (
{err}
)}
);
}