Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit c31d6bb61fe769e96429e743b60b2f3c2ba04631
parent a1344020d40e7de7d189b7f5da2ed555469bad92
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 05:01:58 -0400

umtool: /research/<case> — the board — and pinning from Research's results and reader

The board (canvas "Research board"): snapshot slips on the reader surface,
claim line and note on the desk, the flags (speaker not checked, drifted with
the words there now, en-orig differs), sections and order by alt+j/k or a drag,
re-verify, copy and download as cited markdown, the hand-offs behind their
plans, and the side panel (scope, searched, read N of M, stored). Research
pins the lit hit with p or Pin to board, to the chosen case or one it asks
for, and lists the cases before a search.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/app/research/[case]/page.tsx | 46++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/research/page.tsx | 14+++++++++++++-
Aumtool/components/research/BoardView.tsx | 596+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/research/HandoffDialog.tsx | 167+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/research/PinTarget.tsx | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/research/QuoteSlip.tsx | 264+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/research/Reader.tsx | 50++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/components/research/ResearchView.tsx | 195++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/lib/research/boards.test.ts | 2++
Mumtool/lib/research/boards.ts | 11++++++-----
Mumtool/lib/research/hrefs.ts | 30++++++++++++++++++++++++++++--
11 files changed, 1516 insertions(+), 19 deletions(-)

diff --git a/umtool/app/research/[case]/page.tsx b/umtool/app/research/[case]/page.tsx @@ -0,0 +1,46 @@ +import Link from "next/link"; +import AppHeader from "@/components/shell/AppHeader"; +import AppRail from "@/components/shell/AppRail"; +import BoardView from "@/components/research/BoardView"; +import { EmptyState } from "@/components/ui/empty-state"; +import { caseView } from "@/lib/research/boards"; +import { researchHref } from "@/lib/research/hrefs"; +import type { CaseView } from "@/lib/research/case-types"; + +export const dynamic = "force-dynamic"; + +// A RESEARCH BOARD (plans/umtool-redesign.md, R2; canvas "Research board"): +// one case, umtool-side under REPORTS_ROOT/.umtool/research/<case>/. The +// static segments beside it (archive, and R3's runs) win over this one, and +// the case store reserves their names. The board is the client's +// (components/research/BoardView.tsx); this reads the case for the first frame. +export default async function CasePage({ params }: { params: Promise<{ case: string }> }) { + const { case: id } = await params; + let view: CaseView | null = null; + let error: { status: number; message: string } | null = null; + try { + view = await caseView(decodeURIComponent(id)); + } catch (e) { + error = { status: (e as { status?: number }).status ?? 500, message: (e as Error).message }; + } + return ( + <div className="flex h-full flex-col"> + <AppRail active="research" /> + {view ? ( + <BoardView initial={view} /> + ) : ( + <> + <AppHeader crumbs={[{ href: researchHref(), label: "research" }, { label: id }]} /> + <div className="px-7 pt-6"> + <EmptyState title={error?.status === 404 ? `No case “${id}”` : "This case cannot be read"}> + <span role="alert">{error?.message}</span>{" "} + <Link href={researchHref()} className="ink-link"> + Research + </Link> + </EmptyState> + </div> + </> + )} + </div> + ); +} diff --git a/umtool/app/research/page.tsx b/umtool/app/research/page.tsx @@ -2,6 +2,7 @@ import Link from "next/link"; import AppShell from "@/components/shell/AppShell"; import ResearchView from "@/components/research/ResearchView"; import { buttonVariants } from "@/components/ui/button"; +import { listCases } from "@/lib/research/boards"; import { scopeFrom, scopeOf } from "@/lib/research/corpus"; import { researchArchiveHref } from "@/lib/research/hrefs"; import { listSources } from "@/lib/research/sources"; @@ -30,6 +31,9 @@ export default async function ResearchPage({ searchParams }: { searchParams: Pro summaryError = (e as Error).message; } const q = typeof sp.q === "string" ? sp.q : ""; + // R2: the cases a pin can go to, and the one the URL chose. + const cases = await listCases().catch(() => []); + const initialCase = typeof sp.case === "string" ? sp.case : null; return ( <div className="flex h-full flex-col"> <AppShell @@ -41,7 +45,15 @@ export default async function ResearchPage({ searchParams }: { searchParams: Pro </Link> } /> - <ResearchView sources={sources} initialQuery={q} initialScope={scope} initialSummary={summary} initialSummaryError={summaryError} /> + <ResearchView + sources={sources} + initialQuery={q} + initialScope={scope} + initialSummary={summary} + initialSummaryError={summaryError} + initialCases={cases} + initialCase={initialCase} + /> </div> ); } diff --git a/umtool/components/research/BoardView.tsx b/umtool/components/research/BoardView.tsx @@ -0,0 +1,596 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import AppHeader from "@/components/shell/AppHeader"; +import { buttonVariants } from "@/components/ui/button"; +import { Dialog } from "@/components/ui/dialog"; +import { EmptyState } from "@/components/ui/empty-state"; +import { KeyHint } from "@/components/ui/kbd"; +import { LitList, type LitDetail } from "@/components/ui/lit-list"; +import { LitActions, LitLine } from "@/components/ui/lit-line"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { groupsOf, moveQuote, moveSection, placeQuote } from "@/lib/research/board.mjs"; +import type { BoardGroup, CaseView, Quote } from "@/lib/research/case-types"; +import { + researchCaseApi, + researchCaseExportApi, + researchCaseQuoteApi, + researchCaseVerifyApi, + researchFromCaseHref, + researchHref, +} from "@/lib/research/hrefs"; +import HandoffDialog from "./HandoffDialog"; +import QuoteSlip, { quoteLineId } from "./QuoteSlip"; + +// --------------------------------------------------------------------------- +// THE RESEARCH BOARD (plans/umtool-redesign.md, R2; canvas "Research board", +// `#view-board`): a case's quotes as snapshot slips in sections and order, +// our claim line and note under each, the flags, and the side panel -- the +// hand-offs, the scope, what was searched and read, where it is stored. +// +// One lit list: section heads and quotes are its lines. Keys (never while +// typing): j/k lines · alt+j/alt+k move the lit quote (across sections) or +// section · e claim · n note · s speaker checked · m section · x remove · +// a add section · r rename (the lit section, else the case) · v re-verify · +// c copy as cited markdown · / search more. Drag a quote by its grip. +// +// Every change is the API's (app/api/research/cases/route.ts); the board +// redraws from what it answers. +// --------------------------------------------------------------------------- + +const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']"; +const sectionLineId = (sid: string | null) => `s:${sid ?? "unsorted"}`; + +async function call<T>(url: string, method: string, body?: unknown): Promise<T> { + const r = await fetch(url, { + method, + headers: { "content-type": "application/json" }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + cache: "no-store", + }); + const j = (await r.json().catch(() => null)) as (T & { error?: string }) | null; + if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`); + return j as T; +} + +function SectionHead({ g, lit, busy, onRename, onRemove, onDropTop }: { g: BoardGroup; lit: boolean; busy: boolean; onRename: () => void; onRemove: () => void; onDropTop: () => void }) { + const [over, setOver] = useState(false); + return ( + <LitLine + id={sectionLineId(g.id)} + initial={lit} + data-section={g.id ?? ""} + aria-label={`Section: ${g.title}`} + onDragOver={(e) => { + if (!e.dataTransfer.types.includes("application/x-umtool-quote")) return; + e.preventDefault(); + setOver(true); + }} + onDragLeave={() => setOver(false)} + onDrop={(e) => { + e.preventDefault(); + setOver(false); + onDropTop(); + }} + className={`mb-2 flex items-baseline gap-2.5 border-b-0 pb-1.5 pt-3 ${over ? "shadow-[0_2px_0_var(--signal)]" : ""}`} + > + <h2 className="m-0 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted">{g.title}</h2> + <span className="font-mono text-[11.5px] text-meter">{g.quotes.length}</span> + {g.id !== null && ( + <LitActions className="ml-auto"> + <button type="button" disabled={busy} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={onRename}> + Rename + </button> + <button type="button" disabled={busy} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={onRemove}> + Remove section + </button> + </LitActions> + )} + </LitLine> + ); +} + +type Ask = + | { kind: "add-section" } + | { kind: "rename-section"; sid: string; title: string } + | { kind: "remove-section"; sid: string; title: string; n: number } + | { kind: "rename-case" } + | { kind: "remove-quote"; q: Quote }; + +export default function BoardView({ initial }: { initial: CaseView }) { + const router = useRouter(); + const hydrated = useHydrated(); + const [view, setView] = useState<CaseView>(initial); + const [busy, setBusy] = useState(false); + const [status, setStatus] = useState<{ text: string; href?: string; tone?: "error" } | null>(null); + const [litId, setLitId] = useState<string | null>(null); + const [listKey, setListKey] = useState(0); + const [ask, setAsk] = useState<Ask | null>(null); + const [askText, setAskText] = useState(""); + const [handoff, setHandoff] = useState<"article" | "video" | null>(null); + const [notes, setNotes] = useState(initial.case.notes); + const dragging = useRef<string | null>(null); + const doc = view.case; + const groups = useMemo(() => groupsOf(doc) as unknown as BoardGroup[], [doc]); + const byId = useMemo(() => new Map(doc.quotes.map((q) => [q.id, q])), [doc]); + const litQuote = litId?.startsWith("q:") ? (byId.get(litId.slice(2)) ?? null) : null; + const litSection = litId?.startsWith("s:") && litId !== "s:unsorted" ? (doc.sections.find((s) => s.id === litId.slice(2)) ?? null) : null; + + const say = (text: string, extra: { href?: string; tone?: "error" } = {}) => setStatus({ text, ...extra }); + const fail = (e: unknown) => say((e as Error).message, { tone: "error" }); + + // After a move, the moved line keeps the light (the list is redrawn). + const refocus = useRef<string | null>(null); + useEffect(() => { + const id = refocus.current; + if (!id) return; + refocus.current = null; + const el = document.querySelector<HTMLElement>(`[data-lit-id="${CSS.escape(id)}"]`); + el?.focus({ preventScroll: true }); + el?.scrollIntoView({ block: "nearest" }); + }, [listKey]); + + const arrange = useCallback( + async (next: { sections: unknown; order: unknown } | null, keep: string | null) => { + if (!next) return; + setBusy(true); + try { + const v = await call<CaseView>(researchCaseApi(doc.id), "PATCH", next); + refocus.current = keep; + if (keep) setLitId(keep); + setView(v); + setListKey((k) => k + 1); + } catch (e) { + fail(e); + } finally { + setBusy(false); + } + }, + [doc.id], + ); + + const patchQuote = useCallback( + async (qid: string, body: Record<string, unknown>) => { + setBusy(true); + try { + const r = await call<{ case: CaseView }>(researchCaseQuoteApi(doc.id, qid), "PATCH", body); + setView(r.case); + if ("section" in body) { + refocus.current = quoteLineId(qid); + setListKey((k) => k + 1); + } + if (body.useCurrentWords) say("The quote now has the transcript's current words; the old ones are kept in its history."); + } catch (e) { + fail(e); + } finally { + setBusy(false); + } + }, + [doc.id], + ); + + const patchCase = useCallback( + async (body: Record<string, unknown>, keep: string | null = null) => { + setBusy(true); + try { + const v = await call<CaseView>(researchCaseApi(doc.id), "PATCH", body); + setView(v); + if (body.sections) { + refocus.current = keep; + setListKey((k) => k + 1); + } + return v; + } catch (e) { + fail(e); + return null; + } finally { + setBusy(false); + } + }, + [doc.id], + ); + + const verify = useCallback(async () => { + setBusy(true); + say("Re-reading every quote at its cite…"); + try { + const r = await call<{ results: { id: string; verify: { status: string; enOrig?: unknown } }[]; case: CaseView }>(researchCaseVerifyApi(doc.id), "POST", {}); + setView(r.case); + const n = (s: string) => r.results.filter((x) => x.verify.status === s).length; + const en = r.results.filter((x) => x.verify.enOrig).length; + say( + `Re-verified ${r.results.length}: ${n("ok")} as pinned, ${n("drifted")} drifted, ${n("missing")} missing` + + (n("unreadable") ? `, ${n("unreadable")} not readable` : "") + + (en ? `; en-orig differs at ${en}` : ""), + ); + } catch (e) { + fail(e); + } finally { + setBusy(false); + } + }, [doc.id]); + + const copyMarkdown = useCallback(async () => { + try { + const r = await fetch(researchCaseExportApi(doc.id), { cache: "no-store" }); + if (!r.ok) throw new Error((await r.json().catch(() => null))?.error ?? `HTTP ${r.status}`); + const md = await r.text(); + try { + await navigator.clipboard.writeText(md); + say(`Copied the board as cited markdown (${md.split("\n").length} lines)`); + } catch { + window.prompt("Copy the board's markdown", md); + } + } catch (e) { + fail(e); + } + }, [doc.id]); + + const removeQuote = useCallback( + async (q: Quote) => { + setBusy(true); + try { + const r = await call<{ case: CaseView }>(researchCaseQuoteApi(doc.id, q.id), "DELETE"); + setView(r.case); + setListKey((k) => k + 1); + say(`Removed “${q.text.slice(0, 60)}${q.text.length > 60 ? "…" : ""}”`); + } catch (e) { + fail(e); + } finally { + setBusy(false); + } + }, + [doc.id], + ); + + const openAsk = (a: Ask) => { + setAsk(a); + setAskText(a.kind === "rename-section" ? a.title : a.kind === "rename-case" ? doc.title : ""); + }; + + const submitAsk = async () => { + const a = ask; + if (!a) return; + const t = askText.trim(); + setAsk(null); + if (a.kind === "add-section" && t) { + const v = await patchCase({ sections: [...doc.sections, { title: t }] }); + const added = v?.case.sections.at(-1); + if (added) { + refocus.current = sectionLineId(added.id); + setLitId(sectionLineId(added.id)); + setListKey((k) => k + 1); + } + } else if (a.kind === "rename-section" && t) { + await patchCase({ sections: doc.sections.map((s) => (s.id === a.sid ? { id: s.id, title: t } : s)) }, sectionLineId(a.sid)); + } else if (a.kind === "remove-section") { + await patchCase({ sections: doc.sections.filter((s) => s.id !== a.sid) }, sectionLineId(null)); + } else if (a.kind === "rename-case" && t) { + await patchCase({ title: t }); + } else if (a.kind === "remove-quote") { + await removeQuote(a.q); + } + }; + + const onDropOn = (target: string, after: boolean) => { + const qid = dragging.current; + dragging.current = null; + if (!qid || qid === target) return; + const t = byId.get(target); + if (!t) return; + const g = groups.find((x) => x.quotes.some((q) => q.id === target))!; + const without = g.quotes.filter((q) => q.id !== qid); + const at = without.findIndex((q) => q.id === target) + (after ? 1 : 0); + void arrange(placeQuote(doc, qid, g.id, at), quoteLineId(qid)); + }; + + // ── keys ── + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.defaultPrevented || e.metaKey || e.ctrlKey) return; + if ((e.target as HTMLElement | null)?.closest?.(TYPING)) return; + if (document.querySelector("dialog[open]")) return; + if (e.altKey) { + const dir = e.code === "KeyJ" || e.key === "ArrowDown" ? 1 : e.code === "KeyK" || e.key === "ArrowUp" ? -1 : 0; + if (!dir || busy) return; + e.preventDefault(); + if (litQuote) void arrange(moveQuote(doc, litQuote.id, dir), quoteLineId(litQuote.id)); + else if (litSection) void arrange(moveSection(doc, litSection.id, dir), sectionLineId(litSection.id)); + return; + } + const focusField = (f: string) => { + if (!litQuote) return; + const el = document.querySelector<HTMLElement>(`[data-quote="${litQuote.id}"] [data-field="${f}"]`); + if (el) { + e.preventDefault(); + el.focus(); + } + }; + switch (e.key) { + case "e": + focusField("claim"); + break; + case "n": + focusField("note"); + break; + case "m": + focusField("section"); + break; + case "s": + if (litQuote && litQuote.cite.kind !== "post") void patchQuote(litQuote.id, { speakerChecked: !litQuote.speakerChecked }); + break; + case "x": + case "Delete": + if (litQuote) openAsk({ kind: "remove-quote", q: litQuote }); + break; + case "a": + e.preventDefault(); + openAsk({ kind: "add-section" }); + break; + case "r": + e.preventDefault(); + if (litSection) openAsk({ kind: "rename-section", sid: litSection.id, title: litSection.title }); + else openAsk({ kind: "rename-case" }); + break; + case "v": + if (!busy) void verify(); + break; + case "c": + void copyMarkdown(); + break; + case "/": + e.preventDefault(); + router.push(researchFromCaseHref(doc)); + break; + } + }; + document.addEventListener("keydown", onKey); + return () => document.removeEventListener("keydown", onKey); + }); + + const onLight = useCallback((d: LitDetail) => setLitId(d.id), []); + + const s = doc.scope; + const where = view.sourceLabel ?? (s.source ? s.source.replace(/^(local|remote|hub):/, "") : "no source yet"); + const scopeLine = [where, s.channels?.length ? `${s.channels.length} ${s.channels.length === 1 ? "channel" : "channels"}` : "all channels", s.dateFrom || s.dateTo ? `${s.dateFrom ?? "…"} – ${s.dateTo ?? "…"}` : ""].filter(Boolean).join(" · "); + const se = doc.search; + const meta = [ + `${doc.quotes.length} ${doc.quotes.length === 1 ? "quote" : "quotes"}`, + `${doc.sections.length} ${doc.sections.length === 1 ? "section" : "sections"}`, + s.query ? `from “${s.query}”` : "", + view.sourceLabel ?? "", + ] + .filter(Boolean) + .join(" · "); + const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length; + + return ( + <> + <AppHeader + crumbs={[{ href: researchHref(), label: "research" }, { label: doc.title }]} + meta={ + <> + <span className="micro mr-2">Research · case</span> + <span data-board-meta="">{meta}</span> + {drifted > 0 && <span className="ml-2 text-doubt-text">· {drifted} drifted or missing</span>} + </> + } + actions={ + <> + <button type="button" disabled={!hydrated || busy || !doc.quotes.length} className={buttonVariants({ variant: "outline", size: "sm" })} onClick={verify}> + Re-verify quotes <kbd>v</kbd> + </button> + <button type="button" disabled={!hydrated || !doc.quotes.length} className={buttonVariants({ variant: "outline", size: "sm" })} onClick={copyMarkdown}> + Copy as cited markdown <kbd>c</kbd> + </button> + <a href={researchCaseExportApi(doc.id, { download: true })} download className={buttonVariants({ variant: "quiet", size: "sm" })}> + Download .md + </a> + </> + } + /> + <div className="grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)_300px]"> + <div className="flex min-h-0 min-w-0 flex-col"> + <div className="min-h-0 flex-1 overflow-auto px-7 pb-4 pt-2"> + {doc.quotes.length === 0 && doc.sections.length === 0 ? ( + <EmptyState title="No quotes on this board yet"> + <Link prefetch={false} href={researchFromCaseHref(doc)} className="ink-link"> + Search and pin to it + </Link> + </EmptyState> + ) : ( + <LitList key={listKey} label="Board" global onLight={onLight}> + {groups.map((g) => ( + <section key={g.id ?? "unsorted"} data-group={g.id ?? ""}> + <SectionHead + g={g} + lit={litId === sectionLineId(g.id)} + busy={busy} + onRename={() => g.id && openAsk({ kind: "rename-section", sid: g.id, title: g.title })} + onRemove={() => g.id && openAsk({ kind: "remove-section", sid: g.id, title: g.title, n: g.quotes.length })} + onDropTop={() => { + const qid = dragging.current; + dragging.current = null; + if (qid) void arrange(placeQuote(doc, qid, g.id, 0), quoteLineId(qid)); + }} + /> + {g.quotes.map((q) => ( + <QuoteSlip + key={q.id} + q={q} + sections={doc.sections} + lit={litId === quoteLineId(q.id)} + busy={busy} + onPatch={(body) => void patchQuote(q.id, body)} + onRemove={() => openAsk({ kind: "remove-quote", q })} + onDragStart={(id) => (dragging.current = id)} + onDropOn={onDropOn} + /> + ))} + {g.quotes.length === 0 && <p className="mb-3 pl-5 text-[12px] text-muted-2">Empty: move a quote here with alt+j/k, its Section menu, or a drag.</p>} + </section> + ))} + </LitList> + )} + </div> + <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-seam px-7 py-2 text-[11.5px] text-muted-2"> + <KeyHint keys={["j", "k"]}>line</KeyHint> + <KeyHint keys={["alt+j", "alt+k"]}>move</KeyHint> + <KeyHint keys={["e"]}>claim</KeyHint> + <KeyHint keys={["n"]}>note</KeyHint> + <KeyHint keys={["s"]}>speaker</KeyHint> + <KeyHint keys={["m"]}>section</KeyHint> + <KeyHint keys={["a"]}>add section</KeyHint> + <KeyHint keys={["r"]}>rename</KeyHint> + <KeyHint keys={["x"]}>remove</KeyHint> + <KeyHint keys={["/"]}>search more</KeyHint> + {status && ( + <span role={status.tone === "error" ? "alert" : "status"} data-board-status="" className={`ml-auto text-[12px] ${status.tone === "error" ? "text-reject-text" : "text-text-2"}`}> + {status.text} + {status.href && ( + <> + {" · "} + <Link prefetch={false} href={status.href} className="ink-link"> + Open + </Link> + </> + )} + </span> + )} + </div> + </div> + + <aside aria-label="Case" className="grid min-h-0 content-start gap-[18px] overflow-auto border-l border-seam bg-panel px-[22px] py-[18px]"> + <div> + <span className="micro">Hand off</span> + <div className="mt-2 grid gap-2"> + <button type="button" disabled={!hydrated || !doc.quotes.length} className={`${buttonVariants({ variant: "go" })} justify-start`} onClick={() => setHandoff("article")}> + Draft an article from this board + </button> + <button type="button" disabled={!hydrated || !doc.quotes.length} className={`${buttonVariants({ variant: "outline" })} justify-start`} onClick={() => setHandoff("video")}> + Start a video from this board + </button> + </div> + {view.localOnly > 0 && <p className="mt-2 text-[12px] text-doubt-text">{view.localOnly} local-only: no article (it could be published); a video stays local.</p>} + </div> + <dl data-case-facts="" className="m-0 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3.5 gap-y-1.5 text-[12.5px]"> + <dt className="text-muted">Scope</dt> + <dd className="m-0 text-text-2">{scopeLine}</dd> + <dt className="text-muted">Searched</dt> + <dd className="m-0 text-text-2" data-searched=""> + {se ? `${se.total.toLocaleString("en-US")} ${se.total === 1 ? "recording" : "recordings"}, ${se.complete ? "complete" : "partial"}` : "nothing yet"} + </dd> + <dt className="text-muted">Read</dt> + <dd className="m-0 font-mono text-meter" data-read=""> + {se && view.reading ? `${view.reading.read} of ${se.total.toLocaleString("en-US")}` : "—"} + </dd> + <dt className="text-muted">Stored</dt> + <dd className="m-0 break-all font-mono text-[11px] text-text-2">{view.stored}</dd> + <dt className="text-muted">Piece</dt> + <dd className="m-0 font-mono text-[11px] text-text-2">{view.piece}</dd> + </dl> + <div className="grid gap-1.5"> + <Link prefetch={false} href={researchFromCaseHref(doc)} className={`${buttonVariants({ variant: "outline", size: "sm" })} justify-self-start`}> + Search and pin more <kbd>/</kbd> + </Link> + <button type="button" disabled={!hydrated || busy} className={`${buttonVariants({ variant: "quiet", size: "sm" })} justify-self-start`} onClick={() => openAsk({ kind: "add-section" })}> + + Section <kbd>a</kbd> + </button> + </div> + <label className="grid gap-1 text-[12px]"> + <span className="micro">Notes</span> + <textarea + aria-label="Case notes" + value={notes} + rows={4} + onChange={(e) => setNotes(e.target.value)} + onBlur={() => notes !== doc.notes && void patchCase({ notes })} + placeholder="What this case is about; the export's summary" + className="resize-y rounded-[3px] border border-seam-2 bg-ground px-2 py-1.5 text-[12.5px] text-text outline-none placeholder:text-muted-2 focus:border-muted" + /> + </label> + {doc.handoffs.length > 0 && ( + <div className="grid gap-1 text-[12px]"> + <span className="micro">Made from it</span> + {doc.handoffs.map((h, i) => ( + <Link prefetch={false} key={`${h.href}-${i}`} href={h.href} className="ink-link"> + {h.to === "article" ? "Article" : "Video"} · {h.what ?? h.href} · {h.at.slice(0, 10)} + </Link> + ))} + </div> + )} + <p className="m-0 text-[12px] text-muted">A board is umtool-side state; nothing here writes to the corpus.</p> + </aside> + </div> + + <Dialog + open={ask !== null} + onClose={() => setAsk(null)} + title={ + ask?.kind === "add-section" + ? "Add a section" + : ask?.kind === "rename-section" + ? "Rename the section" + : ask?.kind === "remove-section" + ? "Remove the section" + : ask?.kind === "rename-case" + ? "Rename the case" + : "Remove the quote" + } + > + <form + className="grid gap-3" + onSubmit={(e) => { + e.preventDefault(); + void submitAsk(); + }} + > + {ask?.kind === "remove-quote" ? ( + <p className="m-0 text-[13px] text-text-2"> + Remove <span className="font-serif text-text">“{ask.q.text.slice(0, 140)}”</span> from the board? Its claim and note go with it; the transcript is not touched. + </p> + ) : ask?.kind === "remove-section" ? ( + <p className="m-0 text-[13px] text-text-2"> + Remove “{ask.title}”? {ask.n ? `Its ${ask.n} ${ask.n === 1 ? "quote goes" : "quotes go"} to Unsorted.` : "It holds no quotes."} + </p> + ) : ( + <input + autoFocus + aria-label="Title" + value={askText} + maxLength={120} + onChange={(e) => setAskText(e.target.value)} + className="rounded-[3px] border border-seam-2 bg-ground px-2.5 py-1.5 text-[13.5px] text-text outline-none focus:border-muted" + /> + )} + <div className="flex justify-end gap-2"> + <button type="button" className={buttonVariants({ variant: "quiet" })} onClick={() => setAsk(null)}> + Cancel + </button> + <button + type="submit" + data-confirm="" + disabled={ask?.kind !== "remove-quote" && ask?.kind !== "remove-section" && !askText.trim()} + className={buttonVariants({ variant: ask?.kind === "remove-quote" || ask?.kind === "remove-section" ? "destructive" : "go" })} + > + {ask?.kind === "add-section" ? "Add section" : ask?.kind === "remove-quote" ? "Remove quote" : ask?.kind === "remove-section" ? "Remove section" : "Rename"} + </button> + </div> + </form> + </Dialog> + + <HandoffDialog + caseId={doc.id} + to={handoff} + onClose={() => setHandoff(null)} + onDone={(href, what) => { + setHandoff(null); + say(what, { href }); + void call<CaseView>(researchCaseApi(doc.id), "GET").then(setView, () => {}); + }} + /> + </> + ); +} diff --git a/umtool/components/research/HandoffDialog.tsx b/umtool/components/research/HandoffDialog.tsx @@ -0,0 +1,167 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { Dialog } from "@/components/ui/dialog"; +import { researchCaseHandoffApi } from "@/lib/research/hrefs"; +import type { ArticlePlan, HandoffPlan, VideoPlan } from "@/lib/research/case-types"; + +// --------------------------------------------------------------------------- +// A HAND-OFF from the board, plan then confirm (lib/research/handoff.ts): the +// plan is read when the dialog opens and nothing is written until the one +// button that names what it does is pressed. An article spends money (the +// model and its cap are on the plan); a video writes a project. +// --------------------------------------------------------------------------- + +async function post<T>(url: string, body: unknown): Promise<T> { + const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const j = (await r.json().catch(() => null)) as (T & { error?: string }) | null; + if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`); + return j as T; +} + +function Row({ k, children }: { k: string; children: React.ReactNode }) { + return ( + <> + <dt className="text-muted">{k}</dt> + <dd className="m-0 min-w-0 break-words text-text-2">{children}</dd> + </> + ); +} + +function ArticleBody({ p }: { p: ArticlePlan }) { + return ( + <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1.5 text-[12.5px]"> + <Row k="Article"> + <span className="font-mono">{p.article}</span> {p.articleExists ? "(exists: a new iteration)" : "(new, in the making)"} + </Row> + <Row k="Question">{p.question}</Row> + <Row k="Channels">{p.channels.join(", ") || "—"}</Row> + {(p.dateFrom || p.dateTo) && ( + <Row k="Dates"> + {p.dateFrom ?? "…"} – {p.dateTo ?? "…"} + </Row> + )} + <Row k="Seed"> + the board as cited markdown: {p.seed.quotes} {p.seed.quotes === 1 ? "quote" : "quotes"}, {p.seed.chars.toLocaleString("en-US")} characters + </Row> + <Row k="Runs on"> + {p.model ? <span className="font-mono">{p.model}</span> : "the editor cannot be asked"} + {p.capUsd !== null ? ( + <> + {" "} + · spends up to <span className="font-mono text-meter">${p.capUsd.toFixed(2)}</span> + </> + ) : null} + </Row> + </dl> + ); +} + +function VideoBody({ p }: { p: VideoPlan }) { + return ( + <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1.5 text-[12.5px]"> + <Row k="Project"> + <span className="font-mono">{p.slug}</span> + </Row> + <Row k="Title">{p.title}</Row> + <Row k="Clips"> + {p.clips.length} — each the cue span of a pinned quote + <ol className="mt-1 max-h-[160px] list-none overflow-auto p-0 font-mono text-[11px] text-muted-2"> + {p.clips.map((c) => ( + <li key={c.id} className="truncate"> + {c.id} {c.channel}/{c.video} {c.start}–{c.end} “{c.quote}” + </li> + ))} + </ol> + </Row> + <Row k="Origin">{p.siteOrigin ? <span className="font-mono">{p.siteOrigin}</span> : "not set"}</Row> + <Row k="Writes"> + <span className="font-mono">{p.writes}</span> + </Row> + </dl> + ); +} + +export default function HandoffDialog({ + caseId, + to, + onClose, + onDone, +}: { + caseId: string; + to: "article" | "video" | null; + onClose: () => void; + onDone: (href: string, what: string) => void; +}) { + const [plan, setPlan] = useState<HandoffPlan | null>(null); + const [error, setError] = useState<string | null>(null); + const [working, setWorking] = useState(false); + useEffect(() => { + setPlan(null); + setError(null); + if (!to) return; + let live = true; + post<{ plan: HandoffPlan }>(researchCaseHandoffApi(caseId), { to }) + .then((r) => live && setPlan(r.plan)) + .catch((e: Error) => live && setError(e.message)); + return () => { + live = false; + }; + }, [caseId, to]); + + const confirm = async () => { + if (!plan) return; + setWorking(true); + setError(null); + try { + const r = await post<{ href: string }>(researchCaseHandoffApi(caseId), { to, confirm: true, ...(plan.to === "article" ? { article: plan.article } : { slug: plan.slug }) }); + onDone(r.href, plan.to === "article" ? `The sweep for ${plan.article} is queued` : `Project ${plan.slug} written`); + } catch (e) { + setError((e as Error).message); + } finally { + setWorking(false); + } + }; + + const title = to === "article" ? "Draft an article from this board" : "Start a video from this board"; + const blocked = !plan || plan.refusals.length > 0 || (plan.to === "article" && !!plan.policyError); + return ( + <Dialog open={to !== null} onClose={onClose} title={title} data-handoff={to ?? ""}> + {!plan && !error && ( + <p role="status" className="text-[12.5px] text-text-2"> + Reading the plan… + </p> + )} + {plan && (plan.to === "article" ? <ArticleBody p={plan} /> : <VideoBody p={plan} />)} + {plan && plan.refusals.length > 0 && ( + <ul data-refusals="" className="mt-3 grid list-none gap-1 p-0 text-[12.5px] text-reject-text"> + {plan.refusals.map((r) => ( + <li key={r}>{r}</li> + ))} + </ul> + )} + {plan && plan.to === "article" && plan.policyError && <p className="mt-3 text-[12.5px] text-reject-text">The editor: {plan.policyError}</p>} + {plan && plan.warnings.length > 0 && ( + <ul data-warnings="" className="mt-3 grid list-none gap-1 p-0 text-[12px] text-doubt-text"> + {plan.warnings.map((w) => ( + <li key={w}>{w}</li> + ))} + </ul> + )} + {error && ( + <p role="alert" className="mt-3 text-[12.5px] text-reject-text"> + {error} + </p> + )} + <div className="mt-4 flex items-center justify-end gap-2"> + <button type="button" className={buttonVariants({ variant: "quiet" })} onClick={onClose}> + Cancel + </button> + <button type="button" data-confirm="" disabled={blocked || working} className={buttonVariants({ variant: "go" })} onClick={confirm}> + {working ? "Working…" : plan?.to === "article" ? `Start the sweep${plan.capUsd !== null ? ` (up to $${plan.capUsd.toFixed(2)})` : ""}` : "Create the project"} + </button> + </div> + </Dialog> + ); +} diff --git a/umtool/components/research/PinTarget.tsx b/umtool/components/research/PinTarget.tsx @@ -0,0 +1,160 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { Dialog } from "@/components/ui/dialog"; +import { LitGroup, LitLine } from "@/components/ui/lit-line"; +import { LitList } from "@/components/ui/lit-list"; +import { researchCaseHref } from "@/lib/research/hrefs"; +import type { CaseSummary } from "@/lib/research/case-types"; + +// --------------------------------------------------------------------------- +// WHERE A PIN GOES, on the Research page (R2): the board chooser beside the +// ask bar, the dialog that asks when nothing is chosen (an existing case, or a +// new one named for the query), and the Cases list the page shows before a +// search. +// --------------------------------------------------------------------------- + +export function BoardChooser({ + cases, + value, + disabled, + onChange, + onNew, +}: { + cases: CaseSummary[]; + value: string | null; + disabled: boolean; + onChange: (id: string | null) => void; + onNew: () => void; +}) { + const current = cases.find((c) => c.id === value); + return ( + <span className="flex items-center gap-1.5"> + <select + id="pin-board" + aria-label="Board" + title="The board a pin (p) goes to" + value={value ?? ""} + disabled={disabled} + onChange={(e) => { + if (e.target.value === "+new") onNew(); + else onChange(e.target.value || null); + }} + className="max-w-[12rem] rounded-[3px] border border-seam-2 bg-panel px-2 py-[5px] text-[12.5px] text-text" + > + <option value="">Board: ask on pin</option> + {cases.map((c) => ( + <option key={c.id} value={c.id}> + Board: {c.title} ({c.quotes}) + </option> + ))} + <option value="+new">New case…</option> + </select> + {current && ( + <Link href={researchCaseHref(current.id)} prefetch={false} className="ink-link text-[12px]"> + Open + </Link> + )} + </span> + ); +} + +export function PinDialog({ + open, + mode, + cases, + query, + error, + working, + onPick, + onCreate, + onClose, +}: { + open: boolean; + /** "pin": a pin is waiting for its board; "new": only name a new case. */ + mode: "pin" | "new"; + cases: CaseSummary[]; + query: string; + error: string | null; + working: boolean; + onPick: (id: string) => void; + onCreate: (title: string) => void; + onClose: () => void; +}) { + const [title, setTitle] = useState(query); + useEffect(() => { + if (open) setTitle(query); + }, [open, query]); + return ( + <Dialog open={open} onClose={onClose} title={mode === "pin" ? "Pin to which board?" : "New case"} data-pin-dialog=""> + <form + className="flex items-center gap-2" + onSubmit={(e) => { + e.preventDefault(); + if (title.trim()) onCreate(title.trim()); + }} + > + <input + autoFocus + aria-label="New case title" + value={title} + maxLength={120} + onChange={(e) => setTitle(e.target.value)} + placeholder="A new case's title" + className="min-w-0 flex-1 rounded-[3px] border border-seam-2 bg-ground px-2.5 py-1.5 text-[13.5px] text-text outline-none focus:border-muted" + /> + <button type="submit" disabled={working || !title.trim()} className={buttonVariants({ variant: "go" })}> + {mode === "pin" ? "New case and pin" : "Create case"} + </button> + </form> + {cases.length > 0 && ( + <div className="mt-3 grid max-h-[40vh] gap-1 overflow-auto"> + <span className="micro">Or an open case</span> + {cases.map((c) => ( + <button + key={c.id} + type="button" + disabled={working} + onClick={() => onPick(c.id)} + className="flex items-baseline gap-2.5 rounded-[3px] border border-seam px-2.5 py-1.5 text-left text-[13px] text-text hover:border-muted hover:bg-panel-2" + > + <span className="min-w-0 flex-1 truncate">{c.title}</span> + <span className="font-mono text-[11px] text-meter">{c.quotes}</span> + </button> + ))} + </div> + )} + {error && ( + <p role="alert" className="mt-3 text-[12.5px] text-reject-text"> + {error} + </p> + )} + </Dialog> + ); +} + +/** The cases, before a search (canvas: Research's Cases). */ +export function CaseList({ cases }: { cases: CaseSummary[] }) { + if (!cases.length) return null; + return ( + <LitList label="Cases" className="mt-6 max-w-[860px]"> + <LitGroup title="Cases" count={cases.length} note="pin a hit with p to put it on the chosen board"> + {cases.map((c) => ( + <LitLine key={c.id} id={c.id} data-case={c.id} className="grid grid-cols-[minmax(0,1fr)_auto_auto] items-baseline gap-x-4 text-[13px]"> + <Link href={researchCaseHref(c.id)} prefetch={false} className="min-w-0 truncate text-inherit hover:underline"> + {c.title} + {c.error && <span className="ml-2 text-[12px] text-reject-text">{c.error}</span>} + </Link> + <span className="whitespace-nowrap font-mono text-[11.5px] text-meter"> + {c.quotes} {c.quotes === 1 ? "quote" : "quotes"} · {c.sections} {c.sections === 1 ? "section" : "sections"} + {c.drifted ? <span className="text-doubt-text"> · {c.drifted} drifted</span> : null} + </span> + <span className="whitespace-nowrap font-mono text-[11px] text-muted-2">{c.updatedAt.slice(0, 10)}</span> + </LitLine> + ))} + </LitGroup> + </LitList> + ); +} diff --git a/umtool/components/research/QuoteSlip.tsx b/umtool/components/research/QuoteSlip.tsx @@ -0,0 +1,264 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { LitLine, LitOnly } from "@/components/ui/lit-line"; +import { isoDate } from "@/lib/research/facets.mjs"; +import type { CaseSection, Quote } from "@/lib/research/case-types"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// One QUOTE on the board (canvas `.quote`): the words on the reader surface +// (a slip: verbatim, the source's), its cite in mono under them; then on the +// desk what is OURS -- the claim line, the note, the flags (speaker not +// checked; drifted, missing, en-orig differs) and what the last re-verify +// read. Paper is the record, ink is our work: a quote is never styled as our +// claim, nor our claim as a quote. +// +// The claim and the note are edited in place: Enter or leaving the field +// saves, Escape puts it back. The line is a lit line of the board's list; its +// grip drags it. +// --------------------------------------------------------------------------- + +const TRACK: Record<string, string> = { transcript: "transcription", captions: "captions", unknown: "", post: "post" }; + +export const quoteLineId = (qid: string) => `q:${qid}`; + +function InlineField({ + label, + value, + placeholder, + onSave, + field, + className, + max, +}: { + label: string; + value: string; + placeholder: string; + onSave: (v: string) => void; + field: "claim" | "note"; + className?: string; + max: number; +}) { + const [v, setV] = useState(value); + const ref = useRef<HTMLInputElement>(null); + useEffect(() => setV(value), [value]); + const back = () => ref.current?.closest<HTMLElement>("[data-lit-line]")?.focus({ preventScroll: true }); + return ( + <input + ref={ref} + data-field={field} + aria-label={label} + value={v} + maxLength={max} + placeholder={placeholder} + spellCheck + onChange={(e) => setV(e.target.value)} + onBlur={() => { + if (v.trim() !== value.trim()) onSave(v); + }} + onKeyDown={(e) => { + if (e.key === "Enter") { + e.preventDefault(); + if (v.trim() !== value.trim()) onSave(v); + back(); + } else if (e.key === "Escape") { + e.preventDefault(); + e.stopPropagation(); + setV(value); + back(); + } + }} + className={cn( + "min-w-0 rounded-[2px] border border-transparent bg-transparent px-1 py-0.5 outline-none placeholder:text-muted-2 hover:border-seam focus:border-seam-2 focus:bg-ground", + className, + )} + /> + ); +} + +export default function QuoteSlip({ + q, + sections, + lit, + busy, + onPatch, + onRemove, + onDragStart, + onDropOn, +}: { + q: Quote; + sections: CaseSection[]; + lit: boolean; + busy: boolean; + onPatch: (body: Record<string, unknown>) => void; + onRemove: () => void; + onDragStart: (qid: string) => void; + onDropOn: (qid: string, after: boolean) => void; +}) { + const [over, setOver] = useState<"before" | "after" | null>(null); + const c = q.cite; + const v = q.verify; + const where = [ + c.title, + c.channelName ?? c.channel, + c.date ? isoDate(c.date) : "", + c.kind === "post" ? "" : c.clock, + c.trackId ? `${c.trackId} track` : TRACK[c.track ?? ""] ?? "", + c.localOnly ? "local only" : "", + ].filter(Boolean); + const drifted = v?.status === "drifted"; + return ( + <LitLine + id={quoteLineId(q.id)} + initial={lit} + data-quote={q.id} + data-verify={v?.status ?? "never"} + aria-label={`Quote: ${q.text.slice(0, 80)}`} + onDragOver={(e) => { + if (!e.dataTransfer.types.includes("application/x-umtool-quote")) return; + e.preventDefault(); + const r = e.currentTarget.getBoundingClientRect(); + setOver(e.clientY > r.top + r.height / 2 ? "after" : "before"); + }} + onDragLeave={() => setOver(null)} + onDrop={(e) => { + e.preventDefault(); + const after = over === "after"; + setOver(null); + onDropOn(q.id, after); + }} + className={cn( + "mb-3 grid grid-cols-[22px_minmax(0,1fr)] rounded-[3px] border border-seam bg-panel p-0 last:border-b", + over === "before" && "shadow-[0_-2px_0_var(--signal)]", + over === "after" && "shadow-[0_2px_0_var(--signal)]", + )} + > + <span + draggable + aria-hidden="true" + title="Drag to move" + onDragStart={(e) => { + e.dataTransfer.setData("application/x-umtool-quote", q.id); + e.dataTransfer.effectAllowed = "move"; + onDragStart(q.id); + }} + className="cursor-grab select-none pt-3.5 text-center font-mono text-[12px] text-muted-2" + > + ⋮⋮ + </span> + <div className="min-w-0"> + <div data-slip="" className="mr-2.5 mt-2.5 rounded-[2px] bg-reader px-3.5 py-2.5 text-reader-ink shadow-[inset_0_0_0_1px_var(--reader-edge)]"> + <p className="m-0 font-serif text-[16px] leading-[1.45]">“{q.text}”</p> + <div className="mt-1.5 truncate font-mono text-[11px] text-reader-dim" data-cite=""> + {c.url ? ( + <a href={c.url} target="_blank" rel="noreferrer" className="hover:text-reader-ink hover:underline" tabIndex={lit ? 0 : -1}> + {where.join(" · ")} + </a> + ) : ( + where.join(" · ") + )} + </div> + </div> + <div className="grid gap-1 py-2 pr-3 text-[13px]"> + <div className="flex items-baseline gap-1.5"> + <span className="micro shrink-0">Claim</span> + <InlineField + field="claim" + label="Claim" + value={q.claim} + placeholder="No claim line yet" + max={400} + onSave={(claim) => onPatch({ claim })} + className="flex-1 text-text" + /> + </div> + <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-muted-2"> + {c.kind !== "post" && + (q.speakerChecked ? ( + <span data-speaker="checked" className="text-muted">Speaker checked</span> + ) : ( + <span data-speaker="unchecked" className="text-doubt-text before:mr-1 before:font-mono before:text-doubt before:content-['?']"> + Speaker not checked + </span> + ))} + {drifted && ( + <span data-flag="drifted" className="text-doubt-text before:mr-1 before:font-mono before:text-doubt before:content-['≠']"> + Drifted + </span> + )} + {v?.status === "missing" && <span data-flag="missing" className="text-reject-text">Missing</span>} + {v?.enOrig && ( + <span data-flag="en-orig" className="text-doubt-text before:mr-1 before:font-mono before:text-doubt before:content-['≠']"> + en-orig differs + </span> + )} + <span className="flex min-w-[12rem] flex-1 items-baseline gap-1"> + <span className="shrink-0">note:</span> + <InlineField field="note" label="Note" value={q.note} placeholder="Add note" max={2000} onSave={(note) => onPatch({ note })} className="flex-1 text-text-2" /> + </span> + {v?.status === "ok" && <span className="font-mono text-[11px]">verified {v.at.slice(0, 10)}</span>} + {!v && <span className="font-mono text-[11px]">not re-verified</span>} + </div> + <LitOnly> + <div className="flex flex-wrap items-center gap-1.5 pt-0.5"> + <label className="sr-only" htmlFor={`sec-${q.id}`}> + Section + </label> + <select + id={`sec-${q.id}`} + data-field="section" + value={q.section ?? ""} + disabled={busy} + onChange={(e) => onPatch({ section: e.target.value || null })} + className="max-w-[11rem] rounded-[3px] border border-seam-2 bg-panel px-1.5 py-[3px] text-[11.5px] text-text" + > + <option value="">Unsorted</option> + {sections.map((s) => ( + <option key={s.id} value={s.id}> + {s.title} + </option> + ))} + </select> + <button type="button" disabled={busy} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => onPatch({ speakerChecked: !q.speakerChecked })}> + {q.speakerChecked ? "Mark speaker not checked" : "Mark speaker checked"} + </button> + <button type="button" disabled={busy} className={buttonVariants({ variant: "destructive", size: "sm" })} onClick={onRemove}> + Remove + </button> + </div> + </LitOnly> + {drifted && ( + <div data-drift="" className="grid gap-1 rounded-[2px] border border-seam-2 px-2.5 py-1.5 text-[12px] text-text-2"> + <span> + Re-verified {v.at.slice(0, 10)}: the transcript at {c.clock} now reads + </span> + <span data-now="" className="font-serif text-[14px] text-text"> + {v.now ? `“${v.now}”` : <em className="not-italic text-muted-2">(no words there now)</em>} + </span> + <span className="flex items-center gap-2"> + <span className="text-muted-2">The quote above keeps the words as pinned.</span> + {v.now ? ( + <button type="button" disabled={busy} className={buttonVariants({ variant: "outline", size: "sm" })} onClick={() => onPatch({ useCurrentWords: true })}> + Use the current words + </button> + ) : null} + </span> + </div> + )} + {v?.status === "missing" && <div className="text-[12px] text-reject-text">{v.message ?? "The recording was not found at its cite."}</div>} + {v?.status === "unreadable" && <div className="text-[12px] text-doubt-text">Not re-verified: {v.message}</div>} + {v?.message && v.status === "ok" && <div className="text-[12px] text-muted-2">{v.message}</div>} + {v?.enOrig && ( + <div data-en-orig="" className="text-[12px] text-text-2"> + {v.enOrig.quoted === "en" ? "Quoted from the served en track; en-orig, the words as spoken, says " : "The served en track says otherwise here; en-orig says "} + <span className="font-serif text-[13.5px] text-text">“{v.enOrig.text}”</span> + {v.enOrig.quoted === "en" ? " — check the audio before using it." : ""} + </div> + )} + </div> + </div> + </LitLine> + ); +} diff --git a/umtool/components/research/Reader.tsx b/umtool/components/research/Reader.tsx @@ -1,5 +1,6 @@ "use client"; +import Link from "next/link"; 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"; @@ -14,6 +15,7 @@ import type { FetchAnswer, LocalMedia, WindowResponse } from "@/lib/research/typ // 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. // +// Pin to board the cited cue to the chosen case, as a snapshot quote (R2) // 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 @@ -30,6 +32,31 @@ export function playable(media: LocalMedia[], at: number): LocalMedia | null { return windows[0] ?? media.find((m) => m.kind === "source") ?? media.find((m) => m.kind === "audio") ?? null; } +function PinButton({ onPin, pinning, board }: { onPin: () => void; pinning: boolean; board: string | null }) { + return ( + <button type="button" data-pin="" title={board ? `Pin to “${board}”` : "Pin to a board (asks which)"} className={paperButtonVariants({ variant: "go" })} disabled={pinning} onClick={onPin}> + {pinning ? "Pinning…" : "Pin to board"} + </button> + ); +} + +function PinNote({ pinned }: { pinned: { text: string; href?: string; tone?: "error" } | null }) { + if (!pinned) return null; + return ( + <span data-pinned="" role={pinned.tone === "error" ? "alert" : "status"} className="basis-full text-[12px] text-reader-2"> + {pinned.text} + {pinned.href && ( + <> + {" · "} + <Link prefetch={false} href={pinned.href} className="underline underline-offset-2 hover:text-reader-ink"> + Open board + </Link> + </> + )} + </span> + ); +} + export default function Reader({ source, win, @@ -41,7 +68,16 @@ export default function Reader({ onCopy, fetchState, onFetch, + onPin, + pinning, + pinned, + board, }: { + onPin: () => void; + pinning: boolean; + pinned: { text: string; href?: string; tone?: "error" } | null; + /** The chosen case's title, or null: a pin asks which. */ + board: string | null; source: string; win: WindowResponse | null; error: string | null; @@ -91,9 +127,13 @@ export default function Reader({ 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> + <> + <PinButton onPin={onPin} pinning={pinning} board={board} /> + <button type="button" className={paperButtonVariants()} onClick={onCopy}> + {copied ? "Copied" : "Copy citation"} + </button> + <PinNote pinned={pinned} /> + </> } fine={win.citation.text} > @@ -137,7 +177,8 @@ export default function Reader({ }} /> )} - <button type="button" className={paperButtonVariants({ variant: "go" })} onClick={onCopy}> + <PinButton onPin={onPin} pinning={pinning} board={board} /> + <button type="button" className={paperButtonVariants()} onClick={onCopy}> {copied ? "Copied" : "Copy citation"} </button> {file && ( @@ -158,6 +199,7 @@ export default function Reader({ + </button> </span> + <PinNote pinned={pinned} /> {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" diff --git a/umtool/components/research/ResearchView.tsx b/umtool/components/research/ResearchView.tsx @@ -8,13 +8,15 @@ 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 { researchArchiveHref, researchCaseHref, researchCaseQuotesApi, researchCasesApi, 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 type { CaseDoc, CaseSummary, CaseView, Quote } from "@/lib/research/case-types"; import Facets, { type FacetPick } from "./Facets"; import Reader from "./Reader"; import Results, { parseLineId } from "./Results"; import ScopeBar from "./ScopeBar"; +import { BoardChooser, CaseList, PinDialog } from "./PinTarget"; // --------------------------------------------------------------------------- // RESEARCH (plans/umtool-redesign.md, "Research, first-class"; canvas @@ -28,11 +30,36 @@ import ScopeBar from "./ScopeBar"; // 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. +// then the next), c copy citation, p pin to the board (R2), / the ask bar. +// +// PINS (R2): the lit hit -- its cited cue, read again by the server -- goes to +// the chosen case as a snapshot quote, with this search's session, so the +// case takes its reading log. With no case chosen, the pin asks which (or +// names a new one for the query). The choice is in the URL (`case=`) and +// remembered in this browser. // --------------------------------------------------------------------------- const PAGE = 200; const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']"; +const BOARD_KEY = "umtool:research-board"; + +const summaryOf = (d: CaseDoc): CaseSummary => ({ + id: d.id, + piece: `c:${d.id}`, + title: d.title, + quotes: d.quotes.length, + sections: d.sections.length, + updatedAt: d.updatedAt, + scope: d.scope, + drifted: d.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length, +}); + +function setUrlCase(id: string | null) { + const u = new URL(window.location.href); + if (id) u.searchParams.set("case", id); + else u.searchParams.delete("case"); + window.history.replaceState(null, "", `${u.pathname}${u.search}`); +} type Lit = { key: string; i: number }; @@ -54,7 +81,11 @@ export default function ResearchView({ initialScope, initialSummary, initialSummaryError, + initialCases, + initialCase, }: { + initialCases: CaseSummary[]; + initialCase: string | null; sources: SourceOption[]; initialQuery: string; initialScope: Scope; @@ -84,6 +115,35 @@ export default function ResearchView({ const [winLoading, setWinLoading] = useState(false); const [copied, setCopied] = useState(false); const [fetchState, setFetchState] = useState<FetchAnswer | { state: "asking" } | null>(null); + const [cases, setCases] = useState<CaseSummary[]>(initialCases); + const [board, setBoard] = useState<string | null>(initialCase && initialCases.some((c) => c.id === initialCase) ? initialCase : null); + const [pinAsk, setPinAsk] = useState<"pin" | "new" | null>(null); + const [pinWorking, setPinWorking] = useState(false); + const [pinError, setPinError] = useState<string | null>(null); + const [pinned, setPinned] = useState<{ text: string; href?: string; tone?: "error" } | null>(null); + + // The board chosen last time, when the URL names none. + useEffect(() => { + if (board) return; + try { + const was = window.localStorage.getItem(BOARD_KEY); + if (was && initialCases.some((c) => c.id === was)) setBoard(was); + } catch { + /* no storage: nothing remembered */ + } + // once, on arrival + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + const chooseBoard = useCallback((id: string | null) => { + setBoard(id); + setUrlCase(id); + try { + if (id) window.localStorage.setItem(BOARD_KEY, id); + else window.localStorage.removeItem(BOARD_KEY); + } catch { + /* the URL still says it */ + } + }, []); // ── the scope preview, re-read when the scope changes ── const firstScope = useRef(true); @@ -148,7 +208,7 @@ export default function ResearchView({ setShown(PAGE); setLit(null); setWin(null); - window.history.replaceState(null, "", researchHref({ q, ...s, source: r.source.handle === sources[0]?.handle ? undefined : r.source.handle })); + window.history.replaceState(null, "", researchHref({ q, ...s, source: r.source.handle === sources[0]?.handle ? undefined : r.source.handle, case: new URL(window.location.href).searchParams.get("case") ?? undefined })); // The search counted the scope's tracks: the preview can say so now. fetch(researchScopeApi(s), { cache: "no-store" }) .then((x) => json<ScopeSummary>(x)) @@ -337,6 +397,91 @@ export default function ResearchView({ } }, [res, litHit, win]); + // ── pin to a board (R2) ── + const pinTo = useCallback( + async (caseId: string) => { + if (!res || !litHit || !litSnip) return; + if (litHit.kind !== "post" && litSnip.scope) { + setPinned({ text: `A hit in the ${litSnip.scope} has no moment to pin`, tone: "error" }); + return; + } + // The reader's cited cue when it is this hit's window; else the snippet's second. + const cue = win && win.videoId === litHit.videoId && win.lit >= 0 ? win.cues[win.lit] : null; + setPinWorking(true); + try { + const r = await json<{ quote: Quote; duplicate: boolean; case: CaseView }>( + await fetch(researchCaseQuotesApi(caseId), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + source: res.source.handle, + channel: litHit.channelKey, + video: litHit.videoId, + t: litHit.kind === "post" ? 0 : (cue?.t ?? litSnip.t), + ...(litSnip.track ? { track: litSnip.track } : {}), + kind: litHit.kind, + search: { session: res.session, query: res.query, total: res.total, complete: res.complete, notReached: res.notReached, sourceLabel: res.source.label }, + scope: { ...(ranScope ?? {}), source: res.source.handle, query: res.query, ...(res.regex ? { regex: true } : {}) }, + }), + }), + ); + const sum = summaryOf(r.case.case); + setCases((cs) => [sum, ...cs.filter((c) => c.id !== sum.id)]); + setPinned({ + text: r.duplicate ? `Already on “${sum.title}” (${r.quote.id})` : `Pinned to “${sum.title}” · ${sum.quotes} ${sum.quotes === 1 ? "quote" : "quotes"}`, + href: researchCaseHref(caseId), + }); + setPinAsk(null); + setPinError(null); + } catch (e) { + if (pinAsk) setPinError((e as Error).message); + else setPinned({ text: `Pin: ${(e as Error).message}`, tone: "error" }); + } finally { + setPinWorking(false); + } + }, + [res, litHit, litSnip, win, ranScope, pinAsk], + ); + + const pin = useCallback(() => { + if (!res || !litHit) return; + if (board && cases.some((c) => c.id === board)) void pinTo(board); + else { + setPinError(null); + setPinAsk("pin"); + } + }, [res, litHit, board, cases, pinTo]); + + const createCase = useCallback( + async (title: string) => { + setPinWorking(true); + setPinError(null); + try { + const r = await json<{ case: CaseDoc }>( + await fetch(researchCasesApi(), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ title, query: res?.query ?? ask, scope: { ...(ranScope ?? scope), ...(res ? { source: res.source.handle } : {}) } }), + }), + ); + const sum = summaryOf(r.case); + setCases((cs) => [sum, ...cs]); + chooseBoard(sum.id); + if (pinAsk === "pin" && res && litHit) await pinTo(sum.id); + else { + setPinAsk(null); + setPinned({ text: `New case “${sum.title}”: pins go to it`, href: researchCaseHref(sum.id) }); + } + } catch (e) { + setPinError((e as Error).message); + } finally { + setPinWorking(false); + } + }, + [res, ask, ranScope, scope, chooseBoard, pinAsk, litHit, pinTo], + ); + useEffect(() => setPinned(null), [lit?.key, lit?.i]); + // ── keys ── useEffect(() => { const onKey = (e: KeyboardEvent) => { @@ -350,10 +495,14 @@ export default function ResearchView({ else if (e.key === "s") void markLit("skipped"); else if (e.key === "u") void markLit("unread"); else if (e.key === "c") void copy(); + else if (e.key === "p") { + e.preventDefault(); + pin(); + } }; document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey); - }, [markLit, copy]); + }, [markLit, copy, pin]); const stale = !!res && !!ranScope && !sameScope(ranScope, scope); const filtered = visible.length !== (res?.hits.length ?? 0); @@ -389,9 +538,21 @@ export default function ResearchView({ {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> + <span className="flex items-center gap-3"> + <button type="submit" disabled={!hydrated || searching} className={buttonVariants({ variant: "outline", size: "md" })}> + {searching ? "Searching…" : "Search"} <kbd>↵</kbd> + </button> + <BoardChooser + cases={cases} + value={board} + disabled={!hydrated} + onChange={chooseBoard} + onNew={() => { + setPinError(null); + setPinAsk("new"); + }} + /> + </span> </form> <ScopeBar @@ -468,6 +629,7 @@ export default function ResearchView({ <KeyHint keys={["s"]}>skip</KeyHint> <KeyHint keys={["u"]}>unread</KeyHint> <KeyHint keys={["c"]}>copy citation</KeyHint> + <KeyHint keys={["p"]}>pin to board</KeyHint> <KeyHint keys={["/"]}>ask</KeyHint> <span className="ml-auto"> {res.batches} {res.batches === 1 ? "batch" : "batches"} of 8 for a sweep @@ -493,6 +655,7 @@ export default function ResearchView({ </Link> </div> )} + {!searching && <CaseList cases={cases} />} </div> )} </div> @@ -508,6 +671,24 @@ export default function ResearchView({ onCopy={copy} fetchState={fetchState} onFetch={fetchClip} + onPin={pin} + pinning={pinWorking} + pinned={pinned} + board={cases.find((c) => c.id === board)?.title ?? null} + /> + <PinDialog + open={pinAsk !== null} + mode={pinAsk ?? "pin"} + cases={pinAsk === "pin" ? cases : []} + query={res?.query ?? ask} + error={pinError} + working={pinWorking} + onPick={(id) => { + chooseBoard(id); + void pinTo(id); + }} + onCreate={(title) => void createCase(title)} + onClose={() => setPinAsk(null)} /> </div> ); diff --git a/umtool/lib/research/boards.test.ts b/umtool/lib/research/boards.test.ts @@ -110,6 +110,8 @@ test("re-verify: an intact quote is ok, a changed one drifted with old and new, assert.equal(by.q1.now, fixture.DRIFTED_QUOTE.now); assert.equal(doc.quotes.find((q) => q.id === "q1")!.text, fixture.DRIFTED_QUOTE.was, "never silently updated"); assert.equal(by.q2.status, "ok"); + assert.equal(by.q2.nowAt, undefined, "where it was pinned"); + assert.equal(by.q2.message, undefined); assert.equal(by.q2.enOrig, undefined); assert.equal(by.q3.status, "ok", "the en words are what the en track says"); assert.deepEqual(by.q3.enOrig, { text: fixture.EN_REWRITE.orig, quoted: "en", other: fixture.EN_REWRITE.en }); diff --git a/umtool/lib/research/boards.ts b/umtool/lib/research/boards.ts @@ -237,14 +237,15 @@ export async function verifyQuote(q: Quote, now = new Date()): Promise<QuoteVeri if (!cues.length) { status = { status: "drifted", at, now: "", message: `no cues within 30 s of ${clock(c.t)}${c.trackId ? ` on the ${c.trackId} track` : ""} now` }; } else if (holdsWords(joined(cues), q.text)) { - // Where the words start now: the first run of cues that holds them. + // Where the words start now: the cue the shortest run holding them + // starts with -- a run that still holds them without its first cue + // started too early. let nowAt: number | null = null; for (let i = 0; i < cues.length && nowAt === null; i++) { for (let k = i; k < Math.min(cues.length, i + MAX_PIN_CUES); k++) { - if (holdsWords(joined(cues.slice(i, k + 1)), q.text)) { - nowAt = cues[i].t; - break; - } + if (!holdsWords(joined(cues.slice(i, k + 1)), q.text)) continue; + if (k === i || !holdsWords(joined(cues.slice(i + 1, k + 1)), q.text)) nowAt = cues[i].t; + break; } } if (nowAt !== null && Math.abs(nowAt - c.t) >= 1) status = { status: "ok", at, nowAt, message: `the words now start at ${clock(nowAt)} (pinned at ${clock(c.t)})` }; diff --git a/umtool/lib/research/hrefs.ts b/umtool/lib/research/hrefs.ts @@ -7,7 +7,7 @@ import { withQuery } from "../hrefs"; import type { Scope } from "./types"; -export type ResearchQuery = Partial<Scope> & { q?: string }; +export type ResearchQuery = Partial<Scope> & { q?: string; /** The case a pin goes to (R2). */ case?: string }; function scopeQuery(s: Partial<Scope>) { return { @@ -23,7 +23,33 @@ function scopeQuery(s: Partial<Scope>) { /** The Research page, with a query and a scope when given. */ export function researchHref(q: ResearchQuery = {}): string { - return withQuery("/research", { q: q.q, ...scopeQuery(q) }); + return withQuery("/research", { q: q.q, ...scopeQuery(q), case: q.case }); +} + +// ── R2: the boards (cases) ── + +const enc = encodeURIComponent; + +/** A case's board. */ +export function researchCaseHref(id: string): string { + return `/research/${enc(id)}`; +} + +/** Research with a case's scope and query, pins going to the case. */ +export function researchFromCaseHref(c: { id: string; scope: Partial<Scope> & { query?: string } }): string { + const { query, ...scope } = c.scope; + return researchHref({ ...scope, q: query, case: c.id }); +} + +/** The case API (app/api/research/cases/route.ts documents it). */ +export const researchCasesApi = () => "/api/research/cases"; +export const researchCaseApi = (id: string) => `/api/research/cases/${enc(id)}`; +export const researchCaseQuotesApi = (id: string) => `/api/research/cases/${enc(id)}/quotes`; +export const researchCaseQuoteApi = (id: string, qid: string) => `/api/research/cases/${enc(id)}/quotes/${enc(qid)}`; +export const researchCaseVerifyApi = (id: string) => `/api/research/cases/${enc(id)}/verify`; +export const researchCaseHandoffApi = (id: string) => `/api/research/cases/${enc(id)}/handoff`; +export function researchCaseExportApi(id: string, opts: { download?: boolean } = {}): string { + return withQuery(`/api/research/cases/${enc(id)}/export.md`, { download: opts.download === true }); } /** The archive inventory (channels × years). */