commit 078ac8441547cbe01b86ada422f06562bf4e99c5
parent c40d9606b0212c9a38e45d992b0c243a91ed7521
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 02:39:49 -0400
umtool: /research (ask bar, scope preview, results as lit lines, facets, reader, reading log) and /research/archive (the inventory heatmap); e2e/research.spec.ts
The e2e server reads the research fixture as its local corpus
(TRANSCRIPT_LOCAL_DIR); the spec holds a search's total and ids to
enumerate_matches through createCorpusTools on the same dir.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
15 files changed, 1761 insertions(+), 2 deletions(-)
diff --git a/umtool/app/research/archive/page.tsx b/umtool/app/research/archive/page.tsx
@@ -0,0 +1,64 @@
+import Link from "next/link";
+import AppShell from "@/components/shell/AppShell";
+import ArchiveInventory from "@/components/research/ArchiveInventory";
+import { badgeVariants } from "@/components/ui/badge";
+import { scopeFrom } from "@/lib/research/corpus";
+import { coverageOf } from "@/lib/research/coverage";
+import { researchArchiveHref, researchHref } from "@/lib/research/hrefs";
+import { listSources } from "@/lib/research/sources";
+import type { CoverageResponse } from "@/lib/research/types";
+
+export const dynamic = "force-dynamic";
+
+// THE ARCHIVE INVENTORY (plans/umtool-redesign.md, "Research, first-class" 6):
+// what the archive can and cannot answer -- channels × years, what is held and
+// what is published, the gaps. A static segment under app/research/, so it is
+// never a case id when R2 adds /research/<case>. The numbers are
+// lib/research/coverage.ts's; the grid is the client's (hover, keys, Table).
+export default async function ArchivePage({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
+ const sp = await searchParams;
+ const params = new URLSearchParams();
+ for (const [k, v] of Object.entries(sp)) for (const x of Array.isArray(v) ? v : v !== undefined ? [v] : []) params.append(k, x);
+ const sources = await listSources();
+ const scope = scopeFrom(params);
+ if (!scope.source || !sources.some((s) => s.handle === scope.source)) scope.source = sources[0].handle;
+ let data: CoverageResponse | null = null;
+ let error: string | null = null;
+ try {
+ data = await coverageOf(scope);
+ } catch (e) {
+ error = (e as Error).message;
+ }
+ const at = (handle: string) => (handle === sources[0].handle ? undefined : handle);
+ return (
+ <div className="flex h-full flex-col">
+ <AppShell
+ active="research"
+ crumbs={[{ href: researchHref(), label: "research" }, { label: "archive" }]}
+ meta="what the archive can answer · by year"
+ note={data ? `${data.rows.length} channels · ${data.years.length ? `${data.years[0]}–${data.years[data.years.length - 1]}` : "no dates"}` : undefined}
+ />
+ <nav aria-label="Source" className="flex flex-wrap items-center gap-1.5 border-b border-seam px-7 py-2.5">
+ {sources.map((s) => (
+ <Link
+ key={s.handle}
+ href={researchArchiveHref({ source: at(s.handle) })}
+ aria-current={s.handle === scope.source ? "page" : undefined}
+ className={badgeVariants({ variant: s.handle === scope.source ? "on" : "neutral", size: "md" })}
+ >
+ {s.label}
+ </Link>
+ ))}
+ </nav>
+ <div className="min-h-0 flex-1 overflow-auto px-7 pb-6">
+ {error ? (
+ <p role="alert" className="pt-4 text-[13px] text-reject-text">
+ {error}
+ </p>
+ ) : data ? (
+ <ArchiveInventory data={data} />
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/umtool/app/research/page.tsx b/umtool/app/research/page.tsx
@@ -0,0 +1,47 @@
+import Link from "next/link";
+import AppShell from "@/components/shell/AppShell";
+import ResearchView from "@/components/research/ResearchView";
+import { buttonVariants } from "@/components/ui/button";
+import { scopeFrom, scopeOf } from "@/lib/research/corpus";
+import { researchArchiveHref } from "@/lib/research/hrefs";
+import { listSources } from "@/lib/research/sources";
+import type { ScopeSummary } from "@/lib/research/types";
+
+export const dynamic = "force-dynamic";
+
+// RESEARCH (plans/umtool-redesign.md, R1): ask the corpus, see what the scope
+// holds before anything runs, read every hit in its transcript, keep a
+// reading log. The page is the client's (components/research/ResearchView.tsx);
+// this reads the sources and the scope's preview so the first frame has them.
+// A search itself is never run here: it is one scan, and the page shows it
+// running.
+export default async function ResearchPage({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
+ const sp = await searchParams;
+ const params = new URLSearchParams();
+ for (const [k, v] of Object.entries(sp)) for (const x of Array.isArray(v) ? v : v !== undefined ? [v] : []) params.append(k, x);
+ const sources = await listSources();
+ const scope = scopeFrom(params);
+ if (!scope.source || !sources.some((s) => s.handle === scope.source)) scope.source = sources[0].handle;
+ let summary: ScopeSummary | null = null;
+ let summaryError: string | null = null;
+ try {
+ summary = await scopeOf(scope);
+ } catch (e) {
+ summaryError = (e as Error).message;
+ }
+ const q = typeof sp.q === "string" ? sp.q : "";
+ return (
+ <div className="flex h-full flex-col">
+ <AppShell
+ active="research"
+ crumbs={[{ label: "research" }]}
+ actions={
+ <Link href={researchArchiveHref({ source: scope.source === sources[0].handle ? undefined : scope.source })} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Archive inventory
+ </Link>
+ }
+ />
+ <ResearchView sources={sources} initialQuery={q} initialScope={scope} initialSummary={summary} initialSummaryError={summaryError} />
+ </div>
+ );
+}
diff --git a/umtool/components/research/ArchiveInventory.tsx b/umtool/components/research/ArchiveInventory.tsx
@@ -0,0 +1,228 @@
+"use client";
+
+import { useRef, useState } from "react";
+import { VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { Table, TD, TH } from "@/components/ui/table";
+import { cn } from "@/lib/utils";
+import type { CoverageResponse, CoverageRow } from "@/lib/research/types";
+
+// ---------------------------------------------------------------------------
+// THE ARCHIVE INVENTORY (canvas `#view-archive`): channels × years, a number in
+// every cell, the Meter ramp (--m1..--m5, each with its own ink so the number
+// reads on it), a gap over 60 days marked under the cell in the doubt line, "—"
+// where nothing is held. Hover or focus a cell for what it holds; the arrow keys
+// walk the grid; Table shows the same numbers as rows.
+//
+// Two measures: HELD (what the editor has on disk, channel_coverage) and
+// PUBLISHED (what this source's summaries list, by upload year). The ramp is
+// sequential and fixed (the canvas's bins), so two archives read alike.
+// ---------------------------------------------------------------------------
+
+type Measure = "held" | "published";
+
+const BINS = [50, 200, 600, 1200];
+const binOf = (n: number) => (!n ? 0 : 1 + BINS.filter((b) => n >= b).length);
+const RAMP = [
+ "bg-transparent text-muted-2 shadow-[inset_0_0_0_1px_var(--seam)]",
+ "bg-m1 text-[var(--m1-ink)]",
+ "bg-m2 text-[var(--m2-ink)]",
+ "bg-m3 text-[var(--m3-ink)]",
+ "bg-m4 text-[var(--m4-ink)]",
+ "bg-m5 text-[var(--m5-ink)]",
+];
+const nf = new Intl.NumberFormat("en-US");
+
+function countOf(r: CoverageRow, m: Measure, y: string): number {
+ return (m === "held" ? r.held?.byYear[y] : r.published.byYear[y]) ?? 0;
+}
+
+function tipOf(r: CoverageRow, m: Measure, y: string): string {
+ const n = countOf(r, m, y);
+ const parts = [`${r.name} · ${y}`, n ? `${nf.format(n)} ${m === "held" ? "held" : "published"}` : m === "held" ? "nothing held" : "nothing published"];
+ if (m === "held" && r.published.byYear[y]) parts.push(`${nf.format(r.published.byYear[y])} published`);
+ if (m === "published" && r.held?.byYear[y]) parts.push(`${nf.format(r.held.byYear[y])} held`);
+ const t = r.tracks?.[y];
+ if (t && t.transcript + t.captions + t.unknown > 0) parts.push(`transcripts ${t.transcript} · captions ${t.captions}${t.unknown ? ` · unknown ${t.unknown}` : ""}`);
+ const missing = r.published.missingByYear[y];
+ if (missing) parts.push(Object.entries(missing).map(([s, k]) => `${k} ${(VIDEO_STATE_LABELS[s as VideoState] ?? s).toLowerCase()}`).join(", "));
+ if (r.held?.gapYears.includes(y)) parts.push("gap over 60 days");
+ return parts.join(" · ");
+}
+
+export default function ArchiveInventory({ data }: { data: CoverageResponse }) {
+ const [measure, setMeasure] = useState<Measure>(data.held.via === "none" ? "published" : "held");
+ const [table, setTable] = useState(false);
+ const [tip, setTip] = useState<{ text: string; x: number; y: number } | null>(null);
+ const [focus, setFocus] = useState<[number, number]>([0, 0]);
+ const host = useRef<HTMLDivElement>(null);
+ const grid = useRef<HTMLTableElement>(null);
+ const { years, rows } = data;
+
+ const showTip = (el: HTMLElement) => {
+ const h = host.current?.getBoundingClientRect();
+ const r = el.getBoundingClientRect();
+ if (!h) return;
+ setTip({ text: el.dataset.tip ?? "", x: r.left - h.left + (host.current?.scrollLeft ?? 0), y: r.bottom - h.top + (host.current?.scrollTop ?? 0) + 6 });
+ };
+
+ const move = (e: React.KeyboardEvent, ri: number, ci: number) => {
+ const d: Record<string, [number, number]> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
+ const k = d[e.key] ?? (e.key === "Home" ? [0, -ci] : e.key === "End" ? [0, years.length - 1 - ci] : null);
+ if (!k) return;
+ e.preventDefault();
+ const nr = Math.max(0, Math.min(rows.length - 1, ri + k[0]));
+ const nc = Math.max(0, Math.min(years.length - 1, ci + k[1]));
+ setFocus([nr, nc]);
+ grid.current?.querySelector<HTMLElement>(`td[data-cell="${nr}:${nc}"]`)?.focus();
+ };
+
+ const total = (r: CoverageRow) => (measure === "held" ? r.held?.total : r.published.total);
+
+ return (
+ <>
+ <div className="flex flex-wrap items-center gap-x-3.5 gap-y-1.5 py-3.5 text-[12px] text-muted">
+ <span role="group" aria-label="Measure" className="inline-flex gap-1">
+ {(["held", "published"] as const).map((m) => (
+ <button
+ key={m}
+ type="button"
+ aria-pressed={measure === m}
+ disabled={m === "held" && data.held.via === "none"}
+ className={badgeVariants({ variant: measure === m ? "on" : "neutral", size: "md" })}
+ onClick={() => setMeasure(m)}
+ >
+ {m === "held" ? "Videos held" : "Videos published"}
+ </button>
+ ))}
+ </span>
+ <span className="inline-flex items-center gap-[2px]" aria-label="Ramp">
+ <span className="mr-1 font-mono text-[10.5px]">1</span>
+ {RAMP.slice(1).map((c, i) => (
+ <i key={i} className={cn("inline-block h-3 w-[30px] rounded-[2px]", c)} />
+ ))}
+ <span className="ml-1 font-mono text-[10.5px]">1,200+</span>
+ </span>
+ {measure === "held" && (
+ <span>
+ <i className="mr-1 inline-block h-0 w-3.5 border-b-2 border-doubt align-[3px]" />
+ gap over {data.gapDays} days that year
+ </span>
+ )}
+ <span>— nothing {measure === "held" ? "held" : "published"}</span>
+ <button type="button" aria-pressed={table} className={cn(buttonVariants({ variant: "outline", size: "sm" }), "ml-auto")} onClick={() => setTable((t) => !t)}>
+ {table ? "Heatmap" : "Table"}
+ </button>
+ </div>
+
+ {data.held.note && (
+ <p data-held-note={data.held.via} className="mb-3 text-[12px] text-text-2">
+ Held: {data.held.note}.
+ </p>
+ )}
+
+ {rows.length === 0 ? (
+ <p className="text-[13px] text-text-2">This source lists no channels.</p>
+ ) : table ? (
+ <Table aria-label="Inventory table">
+ <thead>
+ <tr>
+ <TH>Channel</TH>
+ <TH>Year</TH>
+ <TH className="text-right">Held</TH>
+ <TH className="text-right">Published</TH>
+ <TH className="text-right">Transcripts</TH>
+ <TH className="text-right">Captions</TH>
+ <TH>Gap</TH>
+ </tr>
+ </thead>
+ <tbody>
+ {rows.flatMap((r) =>
+ years
+ .filter((y) => r.held?.byYear[y] || r.published.byYear[y])
+ .map((y) => (
+ <tr key={`${r.key}-${y}`}>
+ <TD>{r.name}</TD>
+ <TD numeric className="text-left">
+ {y}
+ </TD>
+ <TD numeric>{r.held ? nf.format(r.held.byYear[y] ?? 0) : "—"}</TD>
+ <TD numeric>{nf.format(r.published.byYear[y] ?? 0)}</TD>
+ <TD numeric>{r.tracks?.[y] ? r.tracks[y].transcript : "—"}</TD>
+ <TD numeric>{r.tracks?.[y] ? r.tracks[y].captions : "—"}</TD>
+ <TD>{r.held?.gapYears.includes(y) ? "over 60 days" : ""}</TD>
+ </tr>
+ )),
+ )}
+ </tbody>
+ </Table>
+ ) : (
+ <div ref={host} className="relative overflow-auto pb-2" onMouseLeave={() => setTip(null)}>
+ <table ref={grid} aria-label="Inventory" data-heat="" className="border-separate border-spacing-[2px] text-[12px]">
+ <thead>
+ <tr>
+ <th />
+ {years.map((y) => (
+ <th key={y} scope="col" className="px-1 py-0.5 text-center font-mono text-[11px] font-medium text-muted">
+ {y.slice(2)}
+ </th>
+ ))}
+ <th scope="col" className="pl-2.5 text-right font-mono text-[11px] font-medium text-meter">
+ {measure}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((r, ri) => (
+ <tr key={r.key} data-row={r.slug}>
+ <th scope="row" className="whitespace-nowrap pr-3.5 text-left text-[12.5px] font-medium text-text-2">
+ {r.name}
+ {r.localOnly && <span className="ml-1.5 font-mono text-[9.5px] uppercase tracking-wider text-muted">local only</span>}
+ </th>
+ {years.map((y, ci) => {
+ const n = countOf(r, measure, y);
+ const gap = measure === "held" && r.held?.gapYears.includes(y);
+ const t = tipOf(r, measure, y);
+ return (
+ <td
+ key={y}
+ data-cell={`${ri}:${ci}`}
+ data-year={y}
+ data-n={n}
+ data-gap={gap ? "" : undefined}
+ data-tip={t}
+ aria-label={t}
+ tabIndex={focus[0] === ri && focus[1] === ci ? 0 : -1}
+ onMouseEnter={(e) => showTip(e.currentTarget)}
+ onFocus={(e) => {
+ setFocus([ri, ci]);
+ showTip(e.currentTarget);
+ }}
+ onBlur={() => setTip(null)}
+ onKeyDown={(e) => move(e, ri, ci)}
+ className={cn(
+ "h-[34px] w-[58px] rounded-[2px] text-center font-mono text-[11px] tabular-nums outline-none focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-signal",
+ RAMP[binOf(n)],
+ gap && (n ? "shadow-[inset_0_-2px_0_var(--doubt)]" : "shadow-[inset_0_0_0_1px_var(--seam),inset_0_-2px_0_var(--doubt)]"),
+ )}
+ >
+ {n ? nf.format(n) : "—"}
+ </td>
+ );
+ })}
+ <th className="pl-2.5 text-right font-mono text-[11px] font-medium text-meter">{total(r) != null ? nf.format(total(r)!) : "—"}</th>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {tip && (
+ <div role="tooltip" data-heat-tip="" className="pointer-events-none absolute z-10 whitespace-nowrap rounded-[3px] border border-seam-2 bg-panel-2 px-2 py-1.5 text-[12px] text-text" style={{ left: tip.x, top: tip.y }}>
+ {tip.text}
+ </div>
+ )}
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/umtool/components/research/Facets.tsx b/umtool/components/research/Facets.tsx
@@ -0,0 +1,119 @@
+"use client";
+
+import { VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
+import { cn } from "@/lib/utils";
+import type { Facets as FacetCounts } from "@/lib/research/types";
+
+// ---------------------------------------------------------------------------
+// The facets column (canvas `.facets`): the year histogram, channels, the
+// text (our transcription or the platform's captions), the state on the
+// platform, and the reading log's three piles. Every count is MEASUREMENT, so
+// it is Meter; a facet is a button that narrows the list on this page -- the
+// search is not run again, and the header says "showing N of M".
+// ---------------------------------------------------------------------------
+
+export type FacetPick = { year?: string; channel?: string; track?: string; state?: string; reading?: "read" | "skipped" | "unread" };
+
+const TRACK_WORD: Record<string, string> = { transcript: "transcription", captions: "captions", unknown: "not known", post: "posts" };
+
+function Row({ label, n, of, on, onClick }: { label: string; n: number; of?: number; on: boolean; onClick: () => void }) {
+ return (
+ <button
+ type="button"
+ aria-label={`${label}: ${n}`}
+ aria-pressed={on}
+ onClick={onClick}
+ className={cn(
+ "mb-1.5 grid w-full grid-cols-[minmax(0,1fr)_auto] gap-x-2 gap-y-0.5 rounded-[2px] text-left text-[12px] text-text-2 hover:text-text",
+ on && "text-text underline decoration-muted underline-offset-[3px]",
+ )}
+ >
+ <span className="truncate">{label}</span>
+ <span className="font-mono text-[11.5px] text-meter">{n}</span>
+ {of !== undefined && (
+ <span className="col-span-2 h-[3px] rounded-r-sm bg-seam" aria-hidden="true">
+ <i className="block h-full rounded-r-sm bg-meter" style={{ width: `${of > 0 ? Math.max(4, (n / of) * 100) : 0}%` }} />
+ </span>
+ )}
+ </button>
+ );
+}
+
+export default function Facets({
+ facets,
+ reading,
+ pick,
+ onPick,
+}: {
+ facets: FacetCounts;
+ reading: { read: number; skipped: number; unread: number };
+ pick: FacetPick;
+ onPick: (p: FacetPick) => void;
+}) {
+ const peak = Math.max(1, ...facets.years.map((y) => y.n));
+ const chMax = Math.max(1, ...facets.channels.map((c) => c.n));
+ const set = <K extends keyof FacetPick>(k: K, v: FacetPick[K]) => onPick({ ...pick, [k]: pick[k] === v ? undefined : v });
+ const tracks = Object.entries(facets.tracks).sort((a, b) => b[1] - a[1]);
+ const states = Object.entries(facets.states).sort((a, b) => b[1] - a[1]);
+ return (
+ <aside aria-label="Facets" data-facets="" className="min-h-0 overflow-auto border-l border-seam pb-4 pl-4 pr-[22px] pt-1">
+ {facets.years.length > 0 && (
+ <>
+ <span className="micro mb-2 mt-3 block">Year</span>
+ <div role="group" aria-label="Recordings per year" className="grid h-16 items-end gap-[3px]" style={{ gridTemplateColumns: `repeat(${facets.years.length}, minmax(0, 1fr))` }}>
+ {facets.years.map((y) => (
+ <button
+ key={y.year}
+ type="button"
+ aria-pressed={pick.year === y.year}
+ aria-label={`${y.year}: ${y.n} ${y.n === 1 ? "recording" : "recordings"}`}
+ disabled={y.n === 0}
+ onClick={() => set("year", y.year)}
+ data-year={y.year}
+ className="flex h-full min-w-0 flex-col items-center justify-end disabled:opacity-100"
+ >
+ <em className="mb-0.5 font-mono text-[9.5px] not-italic text-text-2">{y.n}</em>
+ {y.n > 0 ? (
+ <i className={cn("block w-full rounded-t-[2px] bg-meter", pick.year === y.year && "outline outline-2 outline-offset-1 outline-text")} style={{ height: `${(y.n / peak) * 70}%` }} />
+ ) : (
+ <i className="block w-full border-b border-seam-2" />
+ )}
+ <span className="mt-[3px] font-mono text-[9.5px] text-muted-2">{y.year.slice(2)}</span>
+ </button>
+ ))}
+ </div>
+ </>
+ )}
+
+ <span className="micro mb-2 mt-3 block">Channel</span>
+ {facets.channels.slice(0, 8).map((c) => (
+ <Row key={c.slug} label={c.name} n={c.n} of={chMax} on={pick.channel === c.slug} onClick={() => set("channel", c.slug)} />
+ ))}
+ {facets.channels.length > 8 && (
+ <div className="mb-1.5 grid grid-cols-[minmax(0,1fr)_auto] gap-x-2 text-[12px] text-muted-2">
+ <span>{facets.channels.length - 8} more</span>
+ <span className="font-mono text-[11.5px] text-meter">{facets.channels.slice(8).reduce((n, c) => n + c.n, 0)}</span>
+ </div>
+ )}
+
+ <span className="micro mb-2 mt-3 block">Text</span>
+ {tracks.map(([t, n]) => (
+ <Row key={t} label={TRACK_WORD[t] ?? t} n={n} on={pick.track === t} onClick={() => set("track", t)} />
+ ))}
+
+ {states.length > 1 && (
+ <>
+ <span className="micro mb-2 mt-3 block">State</span>
+ {states.map(([s, n]) => (
+ <Row key={s} label={VIDEO_STATE_LABELS[s as VideoState] ?? s} n={n} on={pick.state === s} onClick={() => set("state", s)} />
+ ))}
+ </>
+ )}
+
+ <span className="micro mb-2 mt-3 block">Reading</span>
+ {(["read", "skipped", "unread"] as const).map((r) => (
+ <Row key={r} label={r} n={reading[r]} on={pick.reading === r} onClick={() => set("reading", r)} />
+ ))}
+ </aside>
+ );
+}
diff --git a/umtool/components/research/Reader.tsx b/umtool/components/research/Reader.tsx
@@ -0,0 +1,167 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
+import { clock } from "@/components/ui/clock";
+import { EmptyState } from "@/components/ui/empty-state";
+import { ReaderPane, paperButtonVariants } from "@/components/ui/reader-pane";
+import { isoDate } from "@/lib/research/facets.mjs";
+import { researchMediaApi } from "@/lib/research/hrefs";
+import type { FetchAnswer, LocalMedia, WindowResponse } from "@/lib/research/types";
+
+// ---------------------------------------------------------------------------
+// The reader on the Research page (canvas `.paper`): the transcript around the
+// lit hit, on the pale surface, the hit's cue lit among dim ones; ± widens or
+// narrows the window; the footer's actions name what they do.
+//
+// Copy citation the house format: "quote" [title @ m:ss](moment link)
+// Play from m:ss a file umtool can play from this machine (a fetched
+// window, a kept source or its audio), from the cite
+// Fetch clip the seconds behind the cite, through the editor's
+// fetch-window route, as the MCP's fetch_clip asks
+// ---------------------------------------------------------------------------
+
+const TRACK: Record<string, string> = { transcript: "transcription", captions: "captions", unknown: "text of unknown kind" };
+
+/** The best local file for a second: a window holding it, else a whole source, else audio. */
+export function playable(media: LocalMedia[], at: number): LocalMedia | null {
+ const windows = media.filter((m) => m.kind === "window" && m.from !== undefined && m.to !== undefined && m.from <= at && at <= m.to);
+ windows.sort((a, b) => a.to! - a.from! - (b.to! - b.from!));
+ return windows[0] ?? media.find((m) => m.kind === "source") ?? media.find((m) => m.kind === "audio") ?? null;
+}
+
+export default function Reader({
+ source,
+ win,
+ error,
+ loading,
+ span,
+ onSpan,
+ copied,
+ onCopy,
+ fetchState,
+ onFetch,
+}: {
+ source: string;
+ win: WindowResponse | null;
+ error: string | null;
+ loading: boolean;
+ span: number;
+ onSpan: (s: number) => void;
+ copied: boolean;
+ onCopy: () => void;
+ fetchState: FetchAnswer | { state: "asking" } | null;
+ onFetch: () => void;
+}) {
+ const [playing, setPlaying] = useState<LocalMedia | null>(null);
+ const video = useRef<HTMLVideoElement>(null);
+ useEffect(() => setPlaying(null), [win?.videoId, win?.at]);
+
+ if (!win) {
+ return (
+ <aside aria-label="Reader" data-reader="" className="reader">
+ <div className="flex flex-1 items-center justify-center px-6">
+ {error ? (
+ <p role="alert" className="text-[12.5px] text-reader-ink">
+ {error}
+ </p>
+ ) : (
+ <EmptyState title={loading ? "Reading…" : "Light a line to read it here"} className="text-reader-dim [&_p]:text-reader-2" />
+ )}
+ </div>
+ </aside>
+ );
+ }
+
+ if (win.kind === "post") {
+ return (
+ <ReaderPane
+ source={win.title}
+ byline={[win.channelName, isoDate(win.uploadDate), win.localOnly ? "local only" : null]}
+ footer={
+ <button type="button" className={paperButtonVariants({ variant: "go" })} onClick={onCopy}>
+ {copied ? "Copied" : "Copy citation"}
+ </button>
+ }
+ fine={win.citation.text}
+ >
+ <p>{win.text}</p>
+ </ReaderPane>
+ );
+ }
+
+ const file = playable(win.media, win.at);
+ const offset = playing?.kind === "window" ? win.at - (playing.from ?? 0) : win.at;
+ const state = VIDEO_STATE_LABELS[win.state as VideoState] ?? win.state;
+ const fetching = fetchState && (fetchState.state === "asking" || fetchState.state === "queued");
+ return (
+ <ReaderPane
+ key={`${win.videoId}@${win.at}:${win.span}`}
+ source={win.title}
+ byline={[
+ win.channelName,
+ `uploaded ${isoDate(win.uploadDate)}`,
+ state.toLowerCase(),
+ <span key="t" className="font-mono text-[11.5px]">
+ {TRACK[win.track] ?? win.track} · {win.cueCount.toLocaleString("en-US")} cues
+ </span>,
+ win.localOnly ? "local only" : null,
+ ]}
+ cite={win.duration > 0 ? { at: win.at, duration: win.duration } : undefined}
+ note={win.trackLabel ? `The hit is in the ${win.trackLabel}` : undefined}
+ cues={win.cues.map((c, i) => ({ t: c.t, text: c.text, lit: i === win.lit, id: `cue-${c.t}` }))}
+ footer={
+ <>
+ {playing && (
+ <video
+ ref={video}
+ data-player=""
+ controls
+ autoPlay
+ className="mb-1 max-h-[180px] w-full basis-full rounded-[2px] bg-black"
+ src={researchMediaApi({ source, channel: win.channelSlug, video: win.videoId, file: playing.name })}
+ onLoadedMetadata={(e) => {
+ e.currentTarget.currentTime = Math.max(0, offset);
+ }}
+ />
+ )}
+ <button type="button" className={paperButtonVariants({ variant: "go" })} onClick={onCopy}>
+ {copied ? "Copied" : "Copy citation"}
+ </button>
+ {file && (
+ <button type="button" className={paperButtonVariants()} onClick={() => setPlaying(file)}>
+ Play from {clock(win.at)}
+ </button>
+ )}
+ {(!file || file.kind !== "window") && (
+ <button type="button" className={paperButtonVariants()} disabled={!!fetching} onClick={onFetch}>
+ {fetching ? "Fetching…" : "Fetch clip"}
+ </button>
+ )}
+ <span className="ml-auto inline-flex items-center gap-1">
+ <button type="button" aria-label="Narrower window" className={paperButtonVariants()} disabled={span <= 15} onClick={() => onSpan(Math.max(15, Math.round(span / 2)))}>
+ −
+ </button>
+ <button type="button" aria-label="Wider window" className={paperButtonVariants()} disabled={span >= 600} onClick={() => onSpan(Math.min(600, span * 2))}>
+ +
+ </button>
+ </span>
+ {fetchState && fetchState.state !== "asking" && (
+ <span data-fetch-state={fetchState.state} role={fetchState.state === "failed" ? "alert" : "status"} className="basis-full text-[12px] text-reader-2">
+ {fetchState.state === "ready"
+ ? `Clip ${fetchState.cached ? "already held" : "fetched"}${fetchState.from !== undefined ? ` · ${clock(fetchState.from)}–${clock(fetchState.to ?? fetchState.from)}` : ""}`
+ : fetchState.state === "queued"
+ ? `The editor is fetching it (job ${fetchState.job}, ${fetchState.status})`
+ : `Fetch clip: ${fetchState.message}`}
+ </span>
+ )}
+ </>
+ }
+ fine={
+ <>
+ ± {win.span} s · <span data-citation="">{win.citation.text}</span>
+ </>
+ }
+ />
+ );
+}
diff --git a/umtool/components/research/ResearchView.tsx b/umtool/components/research/ResearchView.tsx
@@ -0,0 +1,513 @@
+"use client";
+
+import Link from "next/link";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { EmptyState } from "@/components/ui/empty-state";
+import { KeyHint } from "@/components/ui/kbd";
+import type { LitDetail } from "@/components/ui/lit-list";
+import { useHydrated } from "@/components/ui/use-hydrated";
+import { yearOf } from "@/lib/research/facets.mjs";
+import { researchArchiveHref, researchHref, researchScopeApi, researchWindowApi } from "@/lib/research/hrefs";
+import { parseAsk } from "@/lib/research/query.mjs";
+import type { FetchAnswer, LogMarks, ResultHit, Scope, ScopeSummary, SearchResponse, SourceOption, WindowResponse } from "@/lib/research/types";
+import Facets, { type FacetPick } from "./Facets";
+import Reader from "./Reader";
+import Results, { parseLineId } from "./Results";
+import ScopeBar from "./ScopeBar";
+
+// ---------------------------------------------------------------------------
+// RESEARCH (plans/umtool-redesign.md, "Research, first-class"; canvas
+// `#view-research`): the ask bar, the scope and what it holds, the results as
+// lit lines grouped by recording with an honest header, the facets, the
+// reader, and the reading log.
+//
+// A search is ONE call for the whole match set (POST /api/research/search ->
+// enumerate_matches' scan); the page never pages the engine. Facets and "show
+// more" narrow or extend what is DRAWN, never what was searched. The query and
+// the scope live in the URL (replaceState), so a search is a link.
+//
+// Keys: j/k lines (the list), r read · s skip · u unread (the lit recording,
+// then the next), c copy citation, / the ask bar.
+// ---------------------------------------------------------------------------
+
+const PAGE = 200;
+const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']";
+
+type Lit = { key: string; i: number };
+
+const nf = new Intl.NumberFormat("en-US");
+
+async function json<T>(r: Response): Promise<T> {
+ const body = await r.json().catch(() => null);
+ if (!r.ok) throw new Error((body as { error?: string } | null)?.error ?? `HTTP ${r.status}`);
+ return body as T;
+}
+
+function sameScope(a: Scope, b: Scope) {
+ return JSON.stringify({ ...a, channels: [...(a.channels ?? [])].sort() }) === JSON.stringify({ ...b, channels: [...(b.channels ?? [])].sort() });
+}
+
+export default function ResearchView({
+ sources,
+ initialQuery,
+ initialScope,
+ initialSummary,
+ initialSummaryError,
+}: {
+ sources: SourceOption[];
+ initialQuery: string;
+ initialScope: Scope;
+ initialSummary: ScopeSummary | null;
+ initialSummaryError: string | null;
+}) {
+ const hydrated = useHydrated();
+ const askRef = useRef<HTMLInputElement>(null);
+ const listRef = useRef<HTMLDivElement>(null);
+ const [ask, setAsk] = useState(initialQuery);
+ const [scope, setScope] = useState<Scope>(initialScope);
+ const [summary, setSummary] = useState<ScopeSummary | null>(initialSummary);
+ const [summaryError, setSummaryError] = useState<string | null>(initialSummaryError);
+ const [summaryLoading, setSummaryLoading] = useState(false);
+ const [res, setRes] = useState<SearchResponse | null>(null);
+ const [ranScope, setRanScope] = useState<Scope | null>(null);
+ const [searching, setSearching] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [marks, setMarks] = useState<LogMarks>({});
+ const [logError, setLogError] = useState<string | null>(null);
+ const [pick, setPick] = useState<FacetPick>({});
+ const [shown, setShown] = useState(PAGE);
+ const [lit, setLit] = useState<Lit | null>(null);
+ const [span, setSpan] = useState(30);
+ const [win, setWin] = useState<WindowResponse | null>(null);
+ const [winError, setWinError] = useState<string | null>(null);
+ const [winLoading, setWinLoading] = useState(false);
+ const [copied, setCopied] = useState(false);
+ const [fetchState, setFetchState] = useState<FetchAnswer | { state: "asking" } | null>(null);
+
+ // ── the scope preview, re-read when the scope changes ──
+ const firstScope = useRef(true);
+ useEffect(() => {
+ if (firstScope.current) {
+ firstScope.current = false;
+ return;
+ }
+ const ctl = new AbortController();
+ setSummaryLoading(true);
+ const t = setTimeout(() => {
+ fetch(researchScopeApi(scope), { signal: ctl.signal, cache: "no-store" })
+ .then((r) => json<ScopeSummary>(r))
+ .then((s) => {
+ setSummary(s);
+ setSummaryError(null);
+ })
+ .catch((e: Error) => {
+ if (e.name !== "AbortError") setSummaryError(e.message);
+ })
+ .finally(() => setSummaryLoading(false));
+ }, 200);
+ return () => {
+ clearTimeout(t);
+ ctl.abort();
+ };
+ }, [scope]);
+
+ // ── search: once, the whole set ──
+ const run = useCallback(
+ async (q: string, s: Scope, fresh = false) => {
+ const parsed = parseAsk(q);
+ if (parsed.error) {
+ setError(parsed.error);
+ return;
+ }
+ setSearching(true);
+ setError(null);
+ try {
+ const r = await json<SearchResponse>(
+ await fetch("/api/research/search", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ q,
+ source: s.source,
+ channels: s.channels,
+ from: s.dateFrom,
+ to: s.dateTo,
+ states: s.states,
+ media: s.mediaType,
+ posts: s.posts,
+ fresh,
+ }),
+ }),
+ );
+ setRes(r);
+ setRanScope(s);
+ setMarks(r.log.marks);
+ setLogError(r.log.error ?? null);
+ setPick({});
+ setShown(PAGE);
+ setLit(null);
+ setWin(null);
+ window.history.replaceState(null, "", researchHref({ q, ...s, source: r.source.handle === sources[0]?.handle ? undefined : r.source.handle }));
+ // The search counted the scope's tracks: the preview can say so now.
+ fetch(researchScopeApi(s), { cache: "no-store" })
+ .then((x) => json<ScopeSummary>(x))
+ .then(setSummary)
+ .catch(() => {});
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setSearching(false);
+ }
+ },
+ [sources],
+ );
+
+ // A link with ?q= runs on arrival.
+ const ranInitial = useRef(false);
+ useEffect(() => {
+ if (ranInitial.current || !initialQuery) return;
+ ranInitial.current = true;
+ void run(initialQuery, initialScope);
+ }, [initialQuery, initialScope, run]);
+
+ // ── what is drawn: the facets narrow it ──
+ const visible = useMemo(() => {
+ if (!res) return [];
+ return res.hits.filter((h) => {
+ if (pick.year && yearOf(h.uploadDate) !== pick.year) return false;
+ if (pick.channel && h.channelSlug !== pick.channel) return false;
+ if (pick.track && h.track !== pick.track) return false;
+ if (pick.state && h.state !== pick.state) return false;
+ if (pick.reading && (marks[h.key]?.state ?? "unread") !== pick.reading) return false;
+ return true;
+ });
+ }, [res, pick, marks]);
+ const drawn = visible.slice(0, shown);
+ const reading = useMemo(() => {
+ const t = { read: 0, skipped: 0, unread: 0 };
+ for (const h of res?.hits ?? []) t[marks[h.key]?.state ?? "unread"]++;
+ return t;
+ }, [res, marks]);
+ const byKey = useMemo(() => new Map((res?.hits ?? []).map((h) => [h.key, h])), [res]);
+ const litHit: ResultHit | null = lit ? (byKey.get(lit.key) ?? null) : null;
+ const litSnip = litHit && lit ? (litHit.snippets[lit.i] ?? null) : null;
+
+ const onLight = useCallback((d: LitDetail) => {
+ const p = parseLineId(d.id);
+ if (p) setLit(p);
+ }, []);
+
+ // ── the reader follows the lit line ──
+ useEffect(() => setSpan(30), [lit?.key, lit?.i]);
+ useEffect(() => {
+ setFetchState(null);
+ setCopied(false);
+ }, [lit?.key, lit?.i]);
+ useEffect(() => {
+ if (!res || !litHit || !litSnip) return;
+ const ctl = new AbortController();
+ setWinLoading(true);
+ setWinError(null);
+ const t = setTimeout(() => {
+ fetch(
+ researchWindowApi({
+ source: res.source.handle,
+ channel: litHit.channelKey,
+ video: litHit.videoId,
+ t: litSnip.t,
+ span,
+ ...(litSnip.track ? { track: litSnip.track } : {}),
+ kind: litHit.kind,
+ }),
+ { signal: ctl.signal, cache: "no-store" },
+ )
+ .then((r) => json<WindowResponse>(r))
+ .then(setWin)
+ .catch((e: Error) => {
+ if (e.name !== "AbortError") {
+ setWin(null);
+ setWinError(e.message);
+ }
+ })
+ .finally(() => setWinLoading(false));
+ }, 120);
+ return () => {
+ clearTimeout(t);
+ ctl.abort();
+ };
+ }, [res, litHit, litSnip, span]);
+
+ // ── the reading log ──
+ const markLit = useCallback(
+ async (state: "read" | "skipped" | "unread") => {
+ if (!res || !litHit) return;
+ const key = litHit.key;
+ setMarks((m) => {
+ const next = { ...m };
+ if (state === "unread") delete next[key];
+ else next[key] = { state, at: new Date().toISOString() };
+ return next;
+ });
+ // On to the next recording, so r r r walks the list.
+ if (state !== "unread") {
+ const sections = [...(listRef.current?.querySelectorAll<HTMLElement>("[data-hit]") ?? [])];
+ const at = sections.findIndex((s) => s.dataset.hit === key);
+ const next = sections[at + 1]?.querySelector<HTMLElement>("[data-lit-line]");
+ if (next) {
+ next.focus({ preventScroll: true });
+ next.scrollIntoView({ block: "nearest" });
+ }
+ }
+ try {
+ const r = await json<{ marks: LogMarks }>(
+ await fetch("/api/research/log", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ session: res.session,
+ key,
+ state,
+ query: res.query,
+ scope: { source: res.source.handle, ...(ranScope ?? {}) },
+ }),
+ }),
+ );
+ setMarks(r.marks);
+ setLogError(null);
+ } catch (e) {
+ setLogError((e as Error).message);
+ }
+ },
+ [res, litHit, ranScope],
+ );
+
+ const copy = useCallback(async () => {
+ if (!win) return;
+ try {
+ await navigator.clipboard.writeText(win.citation.text);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1600);
+ } catch {
+ window.prompt("Copy the citation", win.citation.text);
+ }
+ }, [win]);
+
+ // ── fetch clip, through the editor, polled by job ──
+ const fetchClip = useCallback(async () => {
+ if (!res || !litHit || !win) return;
+ const cue = win.cues[win.lit];
+ const start = cue?.t ?? win.at;
+ const end = cue ? Math.max(cue.end, start + 1) : win.at + 5;
+ setFetchState({ state: "asking" });
+ try {
+ let a = await json<FetchAnswer>(
+ await fetch("/api/research/fetch", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ source: res.source.handle,
+ channel: litHit.channelKey,
+ video: litHit.videoId,
+ start,
+ end,
+ reason: `umtool research: "${res.query}" @ ${win.citation.text.match(/@ ([\d:]+)\]/)?.[1] ?? start}`,
+ }),
+ }),
+ );
+ setFetchState(a);
+ for (let n = 0; a.state === "queued" && n < 300; n++) {
+ await new Promise((r) => setTimeout(r, 1500));
+ a = await json<FetchAnswer>(
+ await fetch("/api/research/fetch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ job: a.job }) }),
+ );
+ setFetchState(a);
+ }
+ if (a.state === "ready") {
+ // The clip is in the corpus now: the window's media list offers it.
+ const w = await json<WindowResponse>(
+ await fetch(researchWindowApi({ source: res.source.handle, channel: litHit.channelKey, video: litHit.videoId, t: win.at, span: win.span }), { cache: "no-store" }),
+ );
+ setWin(w);
+ setFetchState(a);
+ }
+ } catch (e) {
+ setFetchState({ state: "failed", message: (e as Error).message });
+ }
+ }, [res, litHit, win]);
+
+ // ── keys ──
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.metaKey || e.ctrlKey || e.altKey || e.defaultPrevented) return;
+ if ((e.target as HTMLElement | null)?.closest?.(TYPING)) return;
+ if (e.key === "/") {
+ e.preventDefault();
+ askRef.current?.focus();
+ askRef.current?.select();
+ } else if (e.key === "r") void markLit("read");
+ else if (e.key === "s") void markLit("skipped");
+ else if (e.key === "u") void markLit("unread");
+ else if (e.key === "c") void copy();
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, [markLit, copy]);
+
+ const stale = !!res && !!ranScope && !sameScope(ranScope, scope);
+ const filtered = visible.length !== (res?.hits.length ?? 0);
+ const parsedAsk = parseAsk(ask);
+
+ return (
+ <div className="grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)_minmax(360px,34%)]">
+ <div className="flex min-h-0 min-w-0 flex-col">
+ <form
+ role="search"
+ className="grid grid-cols-[minmax(0,1fr)_auto] gap-2.5 px-7 pb-2.5 pt-4"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void run(ask, scope, true);
+ }}
+ >
+ <label className="flex items-center gap-2.5 rounded-[3px] border border-seam-2 bg-panel px-3 py-2 focus-within:border-muted">
+ <span aria-hidden="true" className="font-mono text-muted-2">
+ ⌕
+ </span>
+ <input
+ ref={askRef}
+ name="q"
+ aria-label="Ask"
+ autoComplete="off"
+ spellCheck={false}
+ value={ask}
+ onChange={(e) => setAsk(e.target.value)}
+ placeholder="what was said"
+ className="min-w-0 flex-1 bg-transparent text-[15px] text-text outline-none placeholder:text-muted-2"
+ />
+ <span className="whitespace-nowrap text-[12px] text-muted-2">
+ {ask.trim() && parsedAsk.kind !== "phrase" ? (parsedAsk.kind === "near" ? `near: ${parsedAsk.near?.n} words, one line` : "regex") : "phrase · regex /…/ · a near:8 b"}
+ </span>
+ </label>
+ <button type="submit" disabled={!hydrated || searching} className={buttonVariants({ variant: "outline", size: "md" })}>
+ {searching ? "Searching…" : "Search"} <kbd>↵</kbd>
+ </button>
+ </form>
+
+ <ScopeBar
+ sources={sources}
+ scope={scope}
+ summary={summary}
+ summaryError={summaryError}
+ loading={summaryLoading}
+ disabled={!hydrated}
+ onChange={(next) => setScope({ ...next, source: next.source || scope.source })}
+ />
+
+ {error && (
+ <p role="alert" className="px-7 pt-3 text-[13px] text-reject-text">
+ {error}
+ </p>
+ )}
+
+ {res && (
+ <div data-honest="" className="flex flex-wrap items-baseline gap-x-4 gap-y-1 px-7 pb-2.5 pt-3 text-[13px]">
+ <b className="font-semibold" data-total={res.total}>
+ {nf.format(res.total)} {res.total === 1 ? "recording" : "recordings"}
+ </b>
+ <span className="text-text-2">
+ {res.complete ? (
+ <span data-coverage="full">· full coverage</span>
+ ) : (
+ <span data-coverage="partial">
+ · <span className="text-doubt-text">Partial</span> — not reached: {res.notReached.length ? res.notReached.join(", ") : "—"}
+ {res.stopped ? ` · stopped in ${res.stopped.channel} at page ${res.stopped.page} of ${res.stopped.pages}` : ""}
+ </span>
+ )}{" "}
+ · {nf.format(res.matches)} lines · {nf.format(res.scanned.pages)} pages
+ {res.mirrorsFolded > 0 ? ` · ${res.mirrorsFolded} ${res.mirrorsFolded === 1 ? "mirror" : "mirrors"} folded` : ""}
+ {res.aliases.length ? ` · aliases: ${res.aliases.join(", ")}` : ""}
+ {filtered ? ` · showing ${visible.length} of ${res.total}` : ""}
+ </span>
+ {stale && <span className="text-[12px] text-doubt-text">The scope changed: Search to run it</span>}
+ <span data-reading="" className="ml-auto font-mono text-[12px] text-meter">
+ read {reading.read} of {res.total}
+ {reading.skipped ? ` · ${reading.skipped} skipped` : ""}
+ </span>
+ {res.warnings.length > 0 && <span className="basis-full text-[12px] text-doubt-text">{res.warnings.join("; ")}</span>}
+ {logError && (
+ <span role="alert" className="basis-full text-[12px] text-reject-text">
+ The reading log: {logError}
+ </span>
+ )}
+ </div>
+ )}
+
+ {res ? (
+ <div className="grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)_176px] gap-x-[22px] pl-7">
+ <div ref={listRef} className="min-h-0 overflow-auto pb-4 pr-1">
+ {drawn.length === 0 ? (
+ <EmptyState title={res.total === 0 ? `No recording says “${res.query}”` : "No recording matches these facets"}>
+ {res.total === 0 ? "in this scope" : null}
+ </EmptyState>
+ ) : (
+ <Results key={`${res.session}:${JSON.stringify(pick)}`} hits={drawn} marks={marks} onLight={onLight} />
+ )}
+ {visible.length > drawn.length && (
+ <div className="flex items-center gap-2.5 py-2.5 text-[12.5px] text-muted-2">
+ <span className="font-mono text-[12px] text-meter">{visible.length - drawn.length}</span> more recordings below
+ <button type="button" className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => setShown((n) => n + PAGE)}>
+ Show {Math.min(PAGE, visible.length - drawn.length)} more
+ </button>
+ </div>
+ )}
+ {drawn.length > 0 && (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 pt-3 text-[11.5px] text-muted-2">
+ <KeyHint keys={["j", "k"]}>line</KeyHint>
+ <KeyHint keys={["r"]}>read</KeyHint>
+ <KeyHint keys={["s"]}>skip</KeyHint>
+ <KeyHint keys={["u"]}>unread</KeyHint>
+ <KeyHint keys={["c"]}>copy citation</KeyHint>
+ <KeyHint keys={["/"]}>ask</KeyHint>
+ <span className="ml-auto">
+ {res.batches} {res.batches === 1 ? "batch" : "batches"} of 8 for a sweep
+ </span>
+ </div>
+ )}
+ </div>
+ <Facets facets={res.facets} reading={reading} pick={pick} onPick={(p) => setPick(p)} />
+ </div>
+ ) : (
+ <div className="flex-1 px-7 pt-6">
+ {searching ? (
+ <p className="text-[13px] text-text-2" role="status">
+ Searching the whole scope, once…
+ </p>
+ ) : (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-muted-2">
+ <KeyHint keys={["/"]}>ask</KeyHint>
+ <KeyHint keys={["↵"]}>search</KeyHint>
+ <span>A search reads the whole scope once and says what it did not reach.</span>
+ <Link href={researchArchiveHref({ source: scope.source === sources[0]?.handle ? undefined : scope.source })} className="ink-link">
+ What the archive holds
+ </Link>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ <Reader
+ source={res?.source.handle ?? scope.source}
+ win={litHit && win && win.videoId === litHit.videoId ? win : null}
+ error={winError}
+ loading={winLoading}
+ span={span}
+ onSpan={setSpan}
+ copied={copied}
+ onCopy={copy}
+ fetchState={fetchState}
+ onFetch={fetchClip}
+ />
+ </div>
+ );
+}
diff --git a/umtool/components/research/Results.tsx b/umtool/components/research/Results.tsx
@@ -0,0 +1,101 @@
+"use client";
+
+import { memo } from "react";
+import { CiteThread } from "@/components/ui/cite-thread";
+import { LitList, type LitDetail } from "@/components/ui/lit-list";
+import { LitLine, LitOnly } from "@/components/ui/lit-line";
+import { isoDate } from "@/lib/research/facets.mjs";
+import { cn } from "@/lib/utils";
+import type { LogMarks, ResultHit, Snip } from "@/lib/research/types";
+
+// ---------------------------------------------------------------------------
+// The results (canvas `.rec` / `.rs`): one group per RECORDING (mirrors
+// folded into it), one lit line per matching line -- its timecode, the line
+// with the match marked, the recording's reading state -- and the cite thread
+// on the lit line only. The page's one global list: j/k from anywhere.
+// ---------------------------------------------------------------------------
+
+const TRACK: Record<string, string> = { transcript: "transcription", captions: "captions", unknown: "", post: "post" };
+
+function Marked({ s }: { s: Snip }) {
+ const out: React.ReactNode[] = [];
+ let at = 0;
+ for (const [a, b] of s.marks) {
+ if (a > at) out.push(s.text.slice(at, a));
+ out.push(
+ <mark key={a} className="bg-transparent text-inherit underline decoration-seam-2 underline-offset-[3px] group-data-[lit]:text-signal-text group-data-[lit]:decoration-signal">
+ {s.text.slice(a, b)}
+ </mark>,
+ );
+ at = b;
+ }
+ if (at < s.text.length) out.push(s.text.slice(at));
+ return <>{out}</>;
+}
+
+export const lineId = (key: string, i: number) => `${key}|${i}`;
+export const parseLineId = (id: string | null): { key: string; i: number } | null => {
+ if (!id) return null;
+ const bar = id.lastIndexOf("|");
+ return bar < 0 ? null : { key: id.slice(0, bar), i: Number(id.slice(bar + 1)) };
+};
+
+function Group({ h, mark }: { h: ResultHit; mark: "read" | "skipped" | undefined }) {
+ const state = mark ?? "unread";
+ return (
+ <section data-hit={h.key} className="mt-2.5" aria-label={h.title}>
+ <div className="flex items-baseline gap-2.5 pb-1 pt-1.5 text-[12.5px] text-text-2">
+ <b className="max-w-[62%] truncate font-medium text-text">{h.kind === "post" ? `Post by ${h.author ?? h.channelName}` : h.title}</b>
+ <span className="truncate whitespace-nowrap font-mono text-[11px] text-muted-2">
+ {h.channelName} · {isoDate(h.uploadDate)}
+ {h.mirrors?.length ? ` · ⧉ +${h.mirrors.length}` : ""}
+ {h.localOnly ? " · local only" : ""}
+ </span>
+ <span className="ml-auto whitespace-nowrap font-mono text-[11px] text-muted-2">
+ {[TRACK[h.track], h.state !== "available" ? h.state.replace("_", " ") : ""].filter(Boolean).join(" · ")}
+ </span>
+ </div>
+ {h.snippets.map((s, i) => (
+ <LitLine key={i} id={lineId(h.key, i)} className="group grid grid-cols-[62px_minmax(0,1fr)_auto] items-baseline gap-x-3 text-[13px]">
+ <span className="font-mono text-[11.5px] tabular-nums">{s.scope && s.t === 0 ? s.scope : h.kind === "post" ? "post" : s.clock}</span>
+ <span className="truncate">
+ <Marked s={s} />
+ </span>
+ <span data-read={state} className={cn("font-mono text-[11px]", state === "read" ? "text-meter" : "text-muted-2")}>
+ {state}
+ </span>
+ {h.duration && !s.scope ? (
+ <LitOnly className="col-[2/-1] mt-1">
+ <CiteThread at={s.t} duration={h.duration} />
+ </LitOnly>
+ ) : null}
+ </LitLine>
+ ))}
+ {h.matches > h.snippets.length && (
+ <div className="py-1 pl-5 text-[11.5px] text-muted-2">
+ +{h.matches - h.snippets.length} more {h.matches - h.snippets.length === 1 ? "line" : "lines"} in this recording
+ </div>
+ )}
+ </section>
+ );
+}
+
+const MemoGroup = memo(Group);
+
+export default function Results({
+ hits,
+ marks,
+ onLight,
+}: {
+ hits: ResultHit[];
+ marks: LogMarks;
+ onLight: (d: LitDetail) => void;
+}) {
+ return (
+ <LitList label="Results" global onLight={onLight}>
+ {hits.map((h) => (
+ <MemoGroup key={h.key} h={h} mark={marks[h.key]?.state} />
+ ))}
+ </LitList>
+ );
+}
diff --git a/umtool/components/research/ScopeBar.tsx b/umtool/components/research/ScopeBar.tsx
@@ -0,0 +1,209 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+import { VIDEO_STATES, VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
+import { badgeVariants } from "@/components/ui/badge";
+import { controlClass } from "@/components/ui/field";
+import { cn } from "@/lib/utils";
+import type { Scope, ScopeSummary, SourceOption } from "@/lib/research/types";
+
+// ---------------------------------------------------------------------------
+// The scope chips and the "holds …" line under them (canvas `.scope`): which
+// corpus, which channels, which dates, states and types, posts or not -- and,
+// BEFORE anything runs, what that scope holds. A chip that opens is a native
+// <details>, so it works from the keyboard with no script of its own; one
+// click outside closes whichever is open.
+// ---------------------------------------------------------------------------
+
+const chip = (on: boolean) =>
+ cn(badgeVariants({ variant: on ? "on" : "neutral", size: "md" }), "cursor-pointer select-none list-none [&::-webkit-details-marker]:hidden");
+
+const nf = new Intl.NumberFormat("en-US");
+const year = (d: string | null) => (d ? d.slice(0, 4) : "");
+const pct = (n: number, of: number) => (of > 0 ? `${Math.round((n / of) * 100)}%` : "0%");
+
+function Pop({ label, on, children, wide = false }: { label: React.ReactNode; on: boolean; children: React.ReactNode; wide?: boolean }) {
+ return (
+ <details className="relative" data-scope-pop="">
+ <summary className={chip(on)}>
+ {label} <span className="text-muted">▾</span>
+ </summary>
+ <div
+ className={cn(
+ "absolute left-0 z-30 mt-1 max-h-[340px] overflow-auto rounded-[3px] border border-seam-2 bg-panel p-2.5 text-[12.5px] shadow-[0_8px_24px_rgb(0_0_0/0.35)]",
+ wide ? "w-[300px]" : "w-[230px]",
+ )}
+ >
+ {children}
+ </div>
+ </details>
+ );
+}
+
+export default function ScopeBar({
+ sources,
+ scope,
+ summary,
+ summaryError,
+ loading,
+ disabled,
+ onChange,
+}: {
+ sources: SourceOption[];
+ scope: Scope;
+ summary: ScopeSummary | null;
+ summaryError: string | null;
+ loading: boolean;
+ disabled: boolean;
+ onChange: (next: Scope) => void;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ // One click outside closes an open chip.
+ useEffect(() => {
+ const close = (e: MouseEvent) => {
+ for (const d of ref.current?.querySelectorAll<HTMLDetailsElement>("details[open]") ?? []) {
+ if (!d.contains(e.target as Node)) d.open = false;
+ }
+ };
+ document.addEventListener("click", close);
+ return () => document.removeEventListener("click", close);
+ }, []);
+
+ const channels = summary?.channels ?? [];
+ const chosen = new Set(scope.channels ?? []);
+ const states = new Set(scope.states ?? []);
+ const toggle = (set: Set<string>, v: string) => {
+ const next = new Set(set);
+ if (next.has(v)) next.delete(v);
+ else next.add(v);
+ return [...next];
+ };
+ const source = sources.find((s) => s.handle === scope.source) ?? sources[0];
+ const tracks = summary?.tracks;
+ const trackTotal = tracks ? tracks.transcript + tracks.captions + tracks.unknown : 0;
+
+ return (
+ <div ref={ref} data-scope="" className="flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b border-seam px-7 pb-3">
+ <label className="sr-only" htmlFor="research-source">
+ Source
+ </label>
+ <select
+ id="research-source"
+ aria-label="Source"
+ disabled={disabled}
+ value={source?.handle ?? ""}
+ onChange={(e) => onChange({ source: e.target.value })}
+ className={cn(controlClass, "max-w-[260px] py-[3px] text-[12px]")}
+ >
+ {sources.map((s) => (
+ <option key={s.handle} value={s.handle}>
+ {s.label}
+ {s.detail ? ` · ${s.detail}` : ""}
+ </option>
+ ))}
+ </select>
+
+ <Pop
+ on={chosen.size > 0}
+ wide
+ label={chosen.size === 0 ? `All ${channels.length} channels` : chosen.size === 1 ? channels.find((c) => chosen.has(c.key))?.name ?? "1 channel" : `${chosen.size} channels`}
+ >
+ <fieldset disabled={disabled} className="grid gap-1">
+ <legend className="micro mb-1.5">Channels</legend>
+ {channels.map((c) => (
+ <label key={c.key} className="flex items-baseline gap-2 text-text-2">
+ <input type="checkbox" checked={chosen.has(c.key)} onChange={() => onChange({ ...scope, channels: toggle(chosen, c.key) })} />
+ <span className="min-w-0 flex-1 truncate">{c.name}</span>
+ {c.localOnly && <span className="font-mono text-[10px] uppercase tracking-wider text-muted">local only</span>}
+ {c.videoCount != null && <span className="font-mono text-[11px] text-meter">{nf.format(c.videoCount)}</span>}
+ </label>
+ ))}
+ {chosen.size > 0 && (
+ <button type="button" className="mt-1 justify-self-start text-[12px] text-muted-2 hover:text-text" onClick={() => onChange({ ...scope, channels: [] })}>
+ Every channel
+ </button>
+ )}
+ </fieldset>
+ </Pop>
+
+ <Pop on={!!(scope.dateFrom || scope.dateTo)} label={scope.dateFrom || scope.dateTo ? `${scope.dateFrom ?? "…"} – ${scope.dateTo ?? "…"}` : "Any date"}>
+ <fieldset disabled={disabled} className="grid gap-2">
+ <legend className="micro mb-1">Uploaded</legend>
+ <label className="grid gap-0.5 text-text-2">
+ From
+ <input type="date" className={controlClass} value={scope.dateFrom ?? ""} onChange={(e) => onChange({ ...scope, dateFrom: e.target.value || undefined })} />
+ </label>
+ <label className="grid gap-0.5 text-text-2">
+ To
+ <input type="date" className={controlClass} value={scope.dateTo ?? ""} onChange={(e) => onChange({ ...scope, dateTo: e.target.value || undefined })} />
+ </label>
+ </fieldset>
+ </Pop>
+
+ <Pop on={states.size > 0} label={states.size === 0 ? "Any state" : [...states].map((s) => VIDEO_STATE_LABELS[s as VideoState] ?? s).join(", ")}>
+ <fieldset disabled={disabled} className="grid gap-1">
+ <legend className="micro mb-1.5">On the platform</legend>
+ {VIDEO_STATES.map((s) => (
+ <label key={s} className="flex items-center gap-2 text-text-2">
+ <input type="checkbox" checked={states.has(s)} onChange={() => onChange({ ...scope, states: toggle(states, s) })} />
+ {VIDEO_STATE_LABELS[s]}
+ </label>
+ ))}
+ </fieldset>
+ </Pop>
+
+ <Pop on={!!scope.mediaType} label={scope.mediaType === "video" ? "Videos" : scope.mediaType === "livestream" ? "Streams" : "Videos and streams"}>
+ <fieldset disabled={disabled} className="grid gap-1">
+ <legend className="micro mb-1.5">Type</legend>
+ {([undefined, "video", "livestream"] as const).map((m) => (
+ <label key={m ?? "any"} className="flex items-center gap-2 text-text-2">
+ <input type="radio" name="research-media" checked={scope.mediaType === m} onChange={() => onChange({ ...scope, mediaType: m })} />
+ {m === "video" ? "Videos only" : m === "livestream" ? "Streams only" : "Both"}
+ </label>
+ ))}
+ </fieldset>
+ </Pop>
+
+ <button
+ type="button"
+ disabled={disabled}
+ aria-pressed={scope.posts === true}
+ className={chip(scope.posts === true)}
+ onClick={() => onChange({ ...scope, posts: !scope.posts })}
+ >
+ {scope.posts ? "Posts included" : "+ Posts"}
+ </button>
+
+ <div data-holds="" aria-live="polite" className="mt-1 basis-full font-mono text-[12px] text-muted">
+ {summaryError ? (
+ <span role="alert" className="text-reject-text">
+ {summaryError}
+ </span>
+ ) : !summary ? (
+ <span>{loading ? "reading the scope…" : "—"}</span>
+ ) : (
+ <>
+ holds{" "}
+ <b className="font-medium text-text-2">
+ {summary.selected} {summary.selected === 1 ? "channel" : "channels"} · {nf.format(summary.videos)} videos
+ {summary.first && summary.last ? ` · ${year(summary.first)}–${year(summary.last)}` : ""}
+ </b>
+ {tracks && trackTotal > 0 ? (
+ <span data-tracks="">
+ {" "}
+ · transcripts {pct(tracks.transcript, trackTotal)} · captions {pct(tracks.captions, trackTotal)}
+ {tracks.unknown > 0 ? ` · unknown ${pct(tracks.unknown, trackTotal)}` : ""}
+ {tracks.counted < tracks.of ? ` (${tracks.counted} of ${tracks.of} channels counted)` : ""}
+ </span>
+ ) : (
+ <span> · transcripts vs captions: counted by the first full search</span>
+ )}
+ {summary.aliases > 0 ? " · aliases on" : ""}
+ {summary.warnings.length > 0 && <span className="text-doubt-text"> · {summary.warnings.join("; ")}</span>}
+ {loading && <span className="text-muted-2"> · updating…</span>}
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -29,6 +29,7 @@ import { makeMediaSurfacesFixture } from "./media-surfaces-fixture.mjs";
import { makeDeleteFixture } from "./delete-fixture.mjs";
import { makeDraftReviewFixture } from "./draft-review-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
+import { makeResearchFixture } from "./research-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song"));
@@ -1929,10 +1930,14 @@ makeMediaSurfacesFixture({ dest, articles: ARTICLES, manifest, cachedWindow: pat
// reports/delete-fixture (a project with two takes); article-delete.spec.ts
// writes its draft (omega) itself.
makeDeleteFixture({ dest, articles: ARTICLES, reports });
+// R1: Research's local corpus (research-public/, TRANSCRIPT_LOCAL_DIR) and the
+// held channels its inventory reads on disk.
+const { pub: RESEARCH_PUBLIC } = makeResearchFixture({ dest, channels: CHANNELS });
console.log(`fixture at ${dest}`);
console.log(` SITES_DIR=${SITES}`);
console.log(` ARTICLES_DIR=${ARTICLES}`);
+console.log(` TRANSCRIPT_LOCAL_DIR=${RESEARCH_PUBLIC} (research: 4 channels, 12 recordings)`);
console.log(` video-notes-fixture (generated, built, schedule + take alt), timeline-fixture (teaser, a01-a03, post p1)`);
if (planned) console.log(` planned clip (used in a build): ${planned}`);
console.log(` videos/: alpha (4 cuts, 3 variants), beta (2 cuts), deck (1 cut, 2 variants)`);
diff --git a/umtool/e2e/fixtures/research-enumerate.ts b/umtool/e2e/fixtures/research-enumerate.ts
@@ -0,0 +1,19 @@
+// The fixture's enumerate total, as the MCP gives it: `enumerate_matches`
+// through createCorpusTools (the in-process tools Claude Code's and the
+// generation jobs' agents call) over a composed public dir. research.spec.ts
+// runs it with tsx and holds the page's total and ids to it.
+//
+// tsx e2e/fixtures/research-enumerate.ts <public dir> <query> [<args json>]
+// -> {"total": N, "ids": [...], "partial": false}
+import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
+
+const [dir, query, extra] = process.argv.slice(2);
+const tools = await createCorpusTools({ source: `local:${dir}` });
+try {
+ const text = await tools.call("enumerate_matches", { query, content_types: ["video"], ...(extra ? JSON.parse(extra) : {}) });
+ const total = Number(/(\d+) match\(es\);/.exec(text)?.[1] ?? "0");
+ const ids = [...text.matchAll(/^- ([^ |]+) \| /gm)].map((m) => m[1]);
+ process.stdout.write(`${JSON.stringify({ total, ids, partial: /COVERAGE PARTIAL/.test(text) })}\n`);
+} finally {
+ await tools.close();
+}
diff --git a/umtool/e2e/research.spec.ts b/umtool/e2e/research.spec.ts
@@ -0,0 +1,273 @@
+import { test, expect, type Page } from "@playwright/test";
+import { spawnSync } from "node:child_process";
+import { existsSync, readFileSync, readdirSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { RESEARCH_PHRASE } from "./fixtures/research-fixture.mjs";
+import { researchArchiveHref, researchHref } from "../lib/research/hrefs";
+import { nearRegex } from "../lib/research/query.mjs";
+import { WARM_TIMEOUT, warm } from "./warm";
+
+// ---------------------------------------------------------------------------
+// Research (plans/umtool-redesign.md, R1) on the fixture corpus
+// (e2e/fixtures/research-fixture.mjs: a composed public dir the server reads
+// as its local corpus, TRANSCRIPT_LOCAL_DIR): the scope preview before
+// anything runs, a search whose total and ids ARE enumerate_matches' over the
+// same corpus, the facets, the reading log round trip, the reader's window
+// with the hit lit, the citation in the house format, j/k, the clip fetched
+// through the editor (stubbed), and the archive inventory.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PUBLIC = path.join(FIXTURE, "research-public");
+const SESSIONS = path.join(FIXTURE, ".umtool", "research", "sessions");
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+
+/** enumerate_matches through createCorpusTools, over the fixture's public dir. */
+function enumerated(query: string, extra: Record<string, unknown> = {}): { total: number; ids: string[]; partial: boolean } {
+ const r = spawnSync("pnpm", ["exec", "tsx", path.join(HERE, "fixtures", "research-enumerate.ts"), PUBLIC, query, JSON.stringify(extra)], {
+ cwd: path.join(HERE, ".."),
+ encoding: "utf8",
+ });
+ if (r.status !== 0) throw new Error(`research-enumerate failed: ${r.stderr}`);
+ return JSON.parse(r.stdout.trim().split("\n").pop()!);
+}
+
+const holds = (page: Page) => page.locator("[data-holds]");
+const honest = (page: Page) => page.locator("[data-honest]");
+const results = (page: Page) => page.getByRole("group", { name: "Results" });
+const reader = (page: Page) => page.getByRole("complementary", { name: "Reader" });
+const litLine = (page: Page) => results(page).locator("[data-lit-line][data-lit]");
+
+async function search(page: Page, q = RESEARCH_PHRASE) {
+ await page.getByRole("textbox", { name: "Ask" }).fill(q);
+ await page.getByRole("button", { name: /^Search/ }).click();
+ await expect(honest(page)).toBeVisible({ timeout: 30_000 });
+}
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ await warm(playwright, [researchHref(), researchArchiveHref(), "/api/research/scope", "/api/research/coverage"]);
+});
+
+test("the scope says what it holds before anything runs, and follows the chips", async ({ page }) => {
+ await page.goto(researchHref());
+ await expect(page.getByRole("navigation", { name: "Breadcrumb" }).locator("h1")).toHaveText("research");
+ await expect(holds(page)).toContainText("4 channels · 12 videos · 2019–2026");
+ // Nothing has been searched in this scope by this test yet.
+ await expect(page.locator("[data-honest]")).toHaveCount(0);
+
+ // One channel: its own count and span.
+ await page.getByText("All 4 channels").click();
+ await page.getByRole("checkbox", { name: /Night Desk/ }).check();
+ await expect(holds(page)).toContainText("1 channel · 3 videos · 2022–2025");
+ // A date window narrows the count (the summaries index), before any search.
+ await page.getByText("Any date").click();
+ await page.getByLabel("From").fill("2023-01-01");
+ await expect(holds(page)).toContainText("1 channel · 2 videos · 2023–2025");
+ // A Candace channel is offered on the local corpus, marked local only.
+ await page.locator("[data-scope] summary", { hasText: "Night Desk" }).click();
+ await expect(page.locator("[data-scope] label", { hasText: "Local Only Fixture" })).toContainText("local only");
+});
+
+test("a search finds exactly what enumerate_matches lists for the same scope: total, ids, order", async ({ page }) => {
+ const want = enumerated(RESEARCH_PHRASE);
+ expect(want.total).toBe(8);
+ await page.goto(researchHref());
+ await search(page);
+ await expect(honest(page).locator("[data-total]")).toHaveAttribute("data-total", String(want.total));
+ await expect(honest(page)).toContainText(`${want.total} recordings`);
+ await expect(honest(page).locator("[data-coverage]")).toHaveAttribute("data-coverage", "full");
+ await expect(honest(page)).toContainText("1 mirror folded");
+ const keys = await results(page).locator("[data-hit]").evaluateAll((els) => els.map((e) => (e as HTMLElement).dataset.hit!.split("/")[1]));
+ expect(keys).toEqual(want.ids);
+ // The search is a link: the query is in the address.
+ await expect(page).toHaveURL(/[?&]q=lighthouse\+budget/);
+
+ // The scope preview learned transcripts vs captions from the search.
+ await expect(holds(page).locator("[data-tracks]")).toContainText("transcripts 42% · captions 58%");
+
+ // One channel, the same parity.
+ const nd = enumerated(RESEARCH_PHRASE, { channels: ["night-desk"] });
+ await page.goto(researchHref({ q: RESEARCH_PHRASE, channels: ["night-desk"] }));
+ await expect(honest(page).locator("[data-total]")).toHaveAttribute("data-total", String(nd.total), { timeout: 30_000 });
+ expect(nd.ids).toEqual(["nd-2023"]);
+});
+
+test("the facets: years with their gaps, channels, text, state -- each narrows what is drawn", async ({ page }) => {
+ await page.goto(researchHref({ q: RESEARCH_PHRASE }));
+ await expect(honest(page)).toBeVisible({ timeout: 30_000 });
+ const facets = page.getByRole("complementary", { name: "Facets" });
+ const years = facets.getByRole("group", { name: "Recordings per year" }).getByRole("button");
+ await expect(years).toHaveCount(8);
+ await expect(facets.getByRole("button", { name: "2020: 0 recordings" })).toBeDisabled();
+ await expect(facets.getByRole("button", { name: "2022: 1 recording" })).toBeVisible();
+ await expect(facets.getByRole("button", { name: "Harbor Radio: 5" })).toBeVisible();
+ await expect(facets.getByRole("button", { name: "captions: 5" })).toBeVisible();
+ await expect(facets.getByRole("button", { name: "transcription: 3" })).toBeVisible();
+ await expect(facets.getByRole("button", { name: "Deleted: 1" })).toBeVisible();
+
+ await facets.getByRole("button", { name: "Night Desk: 1" }).click();
+ await expect(honest(page)).toContainText("showing 1 of 8");
+ await expect(results(page).locator("[data-hit]")).toHaveCount(1);
+ await facets.getByRole("button", { name: "Night Desk: 1" }).click();
+ await facets.getByRole("button", { name: "2024: 1 recording" }).click();
+ await expect(results(page).locator("[data-hit]")).toHaveCount(1);
+ await expect(results(page).locator("[data-hit]")).toHaveAttribute("data-hit", "harbor-radio/hr-2024a");
+});
+
+test("j/k walk the lines; the reader shows the lit hit's window with its cue lit", async ({ page }) => {
+ await page.goto(researchHref({ q: RESEARCH_PHRASE }));
+ await expect(honest(page)).toBeVisible({ timeout: 30_000 });
+ await expect(litLine(page)).toHaveCount(1);
+ const first = await litLine(page).getAttribute("data-lit-id");
+ expect(first).toBe("harbor-radio/hr-2019a|0");
+ await page.keyboard.press("j");
+ await expect(litLine(page)).toHaveAttribute("data-lit-id", "harbor-radio/hr-2021a|0");
+ await page.keyboard.press("j");
+ await expect(litLine(page)).toHaveAttribute("data-lit-id", "harbor-radio/hr-2021a|1");
+ await page.keyboard.press("k");
+ await expect(litLine(page)).toHaveAttribute("data-lit-id", "harbor-radio/hr-2021a|0");
+ // The cite thread is on the lit line only.
+ await expect(litLine(page).locator(".cite-thread")).toBeVisible();
+
+ // The audit: its window, the hit lit among dim cues, the length on the thread.
+ await results(page).locator('[data-lit-id="harbor-radio/hr-2024a|0"]').click();
+ const r = reader(page);
+ await expect(r).toContainText("Harbor Radio 140: the audit");
+ await expect(r).toContainText("deleted");
+ const lit = r.locator("[data-lit-line][data-lit]");
+ await expect(lit).toContainText("How much was the lighthouse budget? You cut it all,");
+ await expect(lit).toContainText("1:22:52");
+ await expect(r.locator(".cite-thread").first()).toHaveAttribute("data-cite-at", "4972");
+ expect(await r.locator("[data-lit-line]").count()).toBeGreaterThan(10);
+ // ± narrows and widens the window.
+ const wide = await r.locator("[data-lit-line]").count();
+ await r.getByRole("button", { name: "Narrower window" }).click();
+ await expect(r.getByText("± 15 s")).toBeVisible();
+ expect(await r.locator("[data-lit-line]").count()).toBeLessThan(wide);
+});
+
+test("Copy citation and c put the house format on the clipboard", async ({ page, context }) => {
+ await context.grantPermissions(["clipboard-read", "clipboard-write"]);
+ await page.goto(researchHref({ q: RESEARCH_PHRASE }));
+ await expect(honest(page)).toBeVisible({ timeout: 30_000 });
+ await results(page).locator('[data-lit-id="harbor-radio/hr-2024a|0"]').click();
+ const want =
+ '"How much was the lighthouse budget? You cut it all," [Harbor Radio 140: the audit @ 1:22:52](https://archive.example/?v=harbor-radio%2Fhr-2024a&t=4972)';
+ await expect(reader(page).locator("[data-citation]")).toHaveText(want);
+ await reader(page).getByRole("button", { name: "Copy citation" }).click();
+ await expect(reader(page).getByRole("button", { name: "Copied" })).toBeVisible();
+ expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(want);
+
+ await page.evaluate(() => navigator.clipboard.writeText(""));
+ await results(page).locator('[data-lit-id="night-desk/nd-2023|0"]').focus();
+ await expect(reader(page).locator("[data-citation]")).toContainText("[Night Desk: the keeper @ 6:40](https://archive.example/?v=night-desk%2Fnd-2023&t=400)");
+ await page.keyboard.press("c");
+ await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(
+ '"the keeper never saw the lighthouse budget" [Night Desk: the keeper @ 6:40](https://archive.example/?v=night-desk%2Fnd-2023&t=400)',
+ );
+});
+
+test("the reading log: r and s mark and move on, survive a reload, and live umtool-side", async ({ page }) => {
+ await page.goto(researchHref({ q: RESEARCH_PHRASE, channels: ["harbor-radio"] }));
+ await expect(honest(page)).toBeVisible({ timeout: 30_000 });
+ await expect(honest(page).locator("[data-reading]")).toHaveText("read 0 of 5");
+ await page.keyboard.press("r");
+ await expect(honest(page).locator("[data-reading]")).toHaveText("read 1 of 5");
+ // r moved the light to the next recording.
+ await expect(litLine(page)).toHaveAttribute("data-lit-id", "harbor-radio/hr-2021a|0");
+ await page.keyboard.press("s");
+ await expect(honest(page).locator("[data-reading]")).toHaveText("read 1 of 5 · 1 skipped");
+ await expect(results(page).locator('[data-hit="harbor-radio/hr-2019a"] [data-read]').first()).toHaveText("read");
+ await expect(results(page).locator('[data-hit="harbor-radio/hr-2021a"] [data-read]').first()).toHaveText("skipped");
+
+ // Stored under REPORTS_ROOT/.umtool/research/sessions/, never in the corpus.
+ await expect.poll(() => (existsSync(SESSIONS) ? readdirSync(SESSIONS).length : 0)).toBeGreaterThan(0);
+ const docs = readdirSync(SESSIONS).map((f) => JSON.parse(readFileSync(path.join(SESSIONS, f), "utf8")));
+ const doc = docs.find((d) => d.marks?.["harbor-radio/hr-2021a"]);
+ expect(doc?.format).toBe("umtool-research-log");
+ expect(doc?.query).toBe(RESEARCH_PHRASE);
+ expect(doc?.marks["harbor-radio/hr-2019a"].state).toBe("read");
+ expect(doc?.marks["harbor-radio/hr-2021a"].state).toBe("skipped");
+
+ await page.reload();
+ await expect(honest(page).locator("[data-reading]")).toHaveText("read 1 of 5 · 1 skipped", { timeout: 30_000 });
+ // The Reading facet narrows to the unread.
+ await page.getByRole("complementary", { name: "Facets" }).getByRole("button", { name: "unread: 3" }).click();
+ await expect(results(page).locator("[data-hit]")).toHaveCount(3);
+ // u clears a mark.
+ await page.getByRole("complementary", { name: "Facets" }).getByRole("button", { name: "unread: 3" }).click();
+ await results(page).locator('[data-lit-id="harbor-radio/hr-2019a|0"]').click();
+ await page.keyboard.press("u");
+ await expect(honest(page).locator("[data-reading]")).toHaveText("read 0 of 5 · 1 skipped");
+});
+
+test("/ focuses the ask bar; a regex and near: say what they are", async ({ page }) => {
+ await page.goto(researchHref());
+ await page.locator("body").click();
+ await page.keyboard.press("/");
+ await expect(page.getByRole("textbox", { name: "Ask" })).toBeFocused();
+ await page.keyboard.type("/light\\w+ keeper/");
+ await expect(page.getByRole("search")).toContainText("regex");
+ await page.keyboard.press("Enter");
+ const re = enumerated("light\\w+ keeper", { regex: true });
+ await expect(honest(page).locator("[data-total]")).toHaveAttribute("data-total", String(re.total), { timeout: 30_000 });
+ expect(re.total).toBeGreaterThan(0);
+ await search(page, "keeper near:3 lighthouse");
+ await expect(page.getByRole("search")).toContainText("near: 3 words, one line");
+ const near = enumerated(nearRegex("keeper", "lighthouse", 3), { regex: true });
+ await expect(honest(page).locator("[data-total]")).toHaveAttribute("data-total", String(near.total));
+});
+
+test("Fetch clip asks the editor exactly as fetch_clip does, then plays the window", async ({ page }) => {
+ await page.goto(researchHref({ q: RESEARCH_PHRASE }));
+ await expect(honest(page)).toBeVisible({ timeout: 30_000 });
+ await results(page).locator('[data-lit-id="night-desk/nd-2023|0"]').click();
+ const r = reader(page);
+ await expect(r.locator("[data-citation]")).toContainText("Night Desk: the keeper @ 6:40");
+ await expect(r.getByRole("button", { name: /^Play from/ })).toHaveCount(0);
+ await r.getByRole("button", { name: "Fetch clip" }).click();
+ await expect(r.locator("[data-fetch-state=ready]")).toContainText("Clip fetched", { timeout: 20_000 });
+ await expect(r.getByRole("button", { name: "Play from 6:40" })).toBeVisible();
+ const asked = (JSON.parse(readFileSync(STUB_LOG, "utf8")) as Record<string, unknown>[]).filter((q) => q.channelSlug === "night-desk");
+ expect(asked.at(-1)).toMatchObject({ channelSlug: "night-desk", from: 397, to: 406.8, pad: 3, requestedBy: "umtool" });
+ expect(String(asked.at(-1)?.reason)).toContain('umtool research: "lighthouse budget"');
+ await r.getByRole("button", { name: "Play from 6:40" }).click();
+ await expect(r.locator("video[data-player]")).toHaveAttribute("src", /\/api\/research\/media\?/);
+ const res = await page.request.get((await r.locator("video[data-player]").getAttribute("src"))!, { headers: { range: "bytes=0-99" } });
+ expect(res.status()).toBe(206);
+ expect(res.headers()["content-type"]).toBe("video/mp4");
+});
+
+test("the archive inventory: channels × years, held vs published, gaps, keys, a table", async ({ page }) => {
+ await page.goto(researchArchiveHref());
+ await expect(page.getByRole("navigation", { name: "Breadcrumb" }).locator("h1")).toHaveText("archive");
+ const heat = page.getByRole("table", { name: "Inventory" });
+ await expect(heat).toBeVisible();
+ // No editor answers coverage here (the stub has no such route): read on disk, and said so.
+ await expect(page.locator("[data-held-note=disk]")).toContainText("read on disk instead");
+ await expect(heat.locator("thead th")).toHaveCount(1 + 8 + 1);
+ const hr = heat.locator('tr[data-row="harbor-radio"]');
+ await expect(hr.locator('td[data-year="2022"]')).toHaveText("1");
+ await expect(hr.locator('td[data-year="2020"]')).toHaveText("—");
+ await expect(hr.locator('td[data-year="2020"]')).toHaveAttribute("data-gap", "");
+ await expect(heat.locator('tr[data-row="harbor-radio-rumble"] td[data-year="2025"]')).toHaveText("—");
+
+ // Published: what the source lists, whether held or not.
+ await page.getByRole("button", { name: "Videos published" }).click();
+ await expect(hr.locator('td[data-year="2022"]')).toHaveText("2");
+ await expect(heat.locator('tr[data-row="harbor-radio-rumble"] td[data-year="2025"]')).toHaveText("1");
+
+ // Keys and the tooltip.
+ await hr.locator('td[data-year="2022"]').hover();
+ await expect(page.locator("[data-heat-tip]")).toContainText("Harbor Radio · 2022 · 2 published · 1 held");
+ await hr.locator('td[data-year="2024"]').click();
+ await page.keyboard.press("ArrowRight");
+ await expect(hr.locator('td[data-year="2025"]')).toBeFocused();
+ await expect(page.locator("[data-heat-tip]")).toContainText("Harbor Radio · 2025");
+
+ await page.getByRole("button", { name: "Table" }).click();
+ await expect(page.getByRole("table", { name: "Inventory table" })).toContainText("Night Desk");
+});
diff --git a/umtool/lib/research/coverage.ts b/umtool/lib/research/coverage.ts
@@ -90,7 +90,7 @@ export async function coverageOf(scope: Scope): Promise<CoverageResponse> {
// Published, from the summaries index (one read for every channel).
const published = new Map<string, CoverageRow["published"]>();
const index = source.videoIndex ? await source.videoIndex().catch(() => null) : null;
- for (const ch of channels) published.set(ch.slug, { total: 0, byYear: {}, byState: {} });
+ for (const ch of channels) published.set(ch.slug, { total: 0, byYear: {}, byState: {}, missingByYear: {} });
if (index) {
for (const v of index.values()) {
const p = published.get(v.channelSlug);
@@ -99,6 +99,10 @@ export async function coverageOf(scope: Scope): Promise<CoverageResponse> {
const y = yearOf(v.uploadDate);
if (y) p.byYear[y] = (p.byYear[y] ?? 0) + 1;
p.byState[v.state] = (p.byState[v.state] ?? 0) + 1;
+ if (y && v.state !== "available") {
+ const m = (p.missingByYear[y] ??= {});
+ m[v.state] = (m[v.state] ?? 0) + 1;
+ }
}
}
for (const ch of channels) {
diff --git a/umtool/lib/research/parity.test.ts b/umtool/lib/research/parity.test.ts
@@ -149,6 +149,7 @@ test("the inventory: no WORKER_TOKEN, so the local corpus is read on disk, and t
assert.equal(hr.held?.byYear["2022"], 1);
assert.ok(hr.held!.gapYears.includes("2020"), "2019 → 2021 is a gap over 60 days");
assert.equal(hr.published.byState.deleted, 1);
+ assert.deepEqual(hr.published.missingByYear, { "2024": { deleted: 1 }, "2026": { unlisted: 1 } });
assert.deepEqual(hr.tracks?.["2022"], { transcript: 1, captions: 1, unknown: 0 });
assert.equal(c.rows.find((r) => r.slug === "harbor-radio-rumble")!.held, null);
});
diff --git a/umtool/lib/research/types.ts b/umtool/lib/research/types.ts
@@ -187,7 +187,13 @@ export type CoverageRow = {
name: string;
localOnly?: boolean;
/** Published: the source's summaries, by upload year. */
- published: { total: number; byYear: Record<string, number>; byState: Record<string, number> };
+ published: {
+ total: number;
+ byYear: Record<string, number>;
+ byState: Record<string, number>;
+ /** The states that are not "available", per year. */
+ missingByYear: Record<string, Record<string, number>>;
+ };
/** Held on disk (channel_coverage), by coverage date; null when not known. */
held: {
total: number;
diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts
@@ -135,6 +135,9 @@ export default defineConfig({
// The article store (/articles, release 26): the fixture's own, for the
// same reason -- an article's notes.json is written beside it.
`ARTICLES_DIR=${FIXTURE}/articles ` +
+ // Research's local corpus (R1): the fixture's composed public dir, read as
+ // the MCP's --local reads one -- never the checkout's export/public.
+ `TRANSCRIPT_LOCAL_DIR=${FIXTURE}/research-public TRANSCRIPT_HUB_URL= ` +
// The generation usage ledger (release 27): the fixture's, never the
// checkout's .generation/usage.jsonl.
`GENERATION_USAGE_FILE=${FIXTURE}/generation-usage.jsonl ` +