"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { badgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import type { NoteReply, ReplyProposal } from "@/lib/annotations/types"; import { edgeClock } from "@/lib/report/clipEditorModel.mjs"; import { cn } from "@/lib/utils"; // --------------------------------------------------------------------------- // THE ASSISTANT IN THE CLIP EDITOR (release 36 lane D): optional, every part. // // the labels clip-suggestions.json: a label on each clip and unused // proposal (its why on hover, and under the selected clip), a // rank the list can be sorted by; stale labels are marked // Suggest one editor job (`report-draft` task `clips-suggest`, routed by // settings.generation) that labels the proposals; its progress // Ask on a comment: a job that answers it as the agent, with at most // one edit the operator applies with Apply // // /api/report/clip-suggest is the only route. Nothing here edits a clip: an // Apply goes through the clip editor's own writer, on the operator's click. // --------------------------------------------------------------------------- export type SuggestionItem = { label: string; why: string; rank: number; score?: number; start?: number; end?: number }; export type SuggestJob = { id: string; mode: "labels" | "ask"; note?: string; status: string; ended: boolean; queue: { key?: string; position?: number } | null; progress: { metric: string; current: number; target: number } | null; last: string | null; summary: string | null; }; export type SuggestView = { suggestions: { model: string; at: string; proposedAt?: string | null; items: Record } | null; error: string | null; state: { stale: boolean; why: string | null; passNewer: boolean; staleIds: string[]; missing: string[] }; hasReactions: boolean; route: { route: "code" | "api" | "local" | null; model: string | null; why: string | null } | null; editorError: string | null; job: SuggestJob | null; }; export type ClipSuggest = { view: SuggestView | null; job: SuggestJob | null; error: string | null; /** The label of a proposal, or null. */ labelOf: (proposal: string | null | undefined) => (SuggestionItem & { id: string; stale: boolean }) | null; start: (body: { mode: "labels"; proposals?: string[] } | { mode: "ask"; note: string }) => Promise; cancel: () => Promise; /** Bumped every time a job is seen to end (a page reloads what it wrote). */ ended: number; }; export function useClipSuggest(project: string): ClipSuggest { const [view, setView] = useState(null); const [job, setJob] = useState(null); const [error, setError] = useState(null); const [ended, setEnded] = useState(0); const load = useCallback(async () => { const r = await fetch(`/api/report/clip-suggest?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null); if (!r) return; const j = (await r.json().catch(() => null)) as (SuggestView & { error?: string }) | null; if (!r.ok || !j) { setError(j?.error ?? `HTTP ${r.status}`); return; } setView(j); setJob(j.job && !j.job.ended ? j.job : null); }, [project]); useEffect(() => { void load(); }, [load]); const live = job && !job.ended ? job.id : null; const mode = useRef(null); mode.current = job; useEffect(() => { if (!live) return; const t = setInterval(async () => { const r = await fetch(`/api/report/clip-suggest?project=${encodeURIComponent(project)}&job=${encodeURIComponent(live)}`, { cache: "no-store" }).catch(() => null); if (!r?.ok) return; const j = (await r.json()) as SuggestJob; setJob({ ...j, ...(mode.current?.note && !j.note ? { note: mode.current.note } : {}) }); if (j.ended) { setEnded((n) => n + 1); await load(); setJob(j); } }, 1500); return () => clearInterval(t); }, [live, project, load]); const start = useCallback( async (body: { mode: "labels"; proposals?: string[] } | { mode: "ask"; note: string }) => { setError(null); const r = await fetch("/api/report/clip-suggest", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) }); const j = (await r.json().catch(() => ({}))) as { job?: SuggestJob; error?: string }; if (j.job) setJob({ ...j.job, ...(body.mode === "ask" ? { note: body.note } : {}) }); if (!r.ok) setError(j.error ?? `HTTP ${r.status}`); }, [project], ); const cancel = useCallback(async () => { if (!job) return; await fetch(`/api/report/clip-suggest?cancel=${encodeURIComponent(job.id)}&project=${encodeURIComponent(project)}`, { method: "POST" }).catch(() => null); }, [job, project]); const items = view?.suggestions?.items ?? null; const staleIds = view?.state.staleIds; const fileStale = !!view?.state.passNewer; const labelOf = useCallback( (proposal: string | null | undefined) => { if (!proposal || !items?.[proposal]) return null; return { id: proposal, ...items[proposal], stale: fileStale || !!staleIds?.includes(proposal) }; }, [items, staleIds, fileStale], ); return { view, job, error, labelOf, start, cancel, ended }; } /** A clip's or a proposal's label: its words, its why on hover; marked when stale. */ export function SuggestLabel({ item, className }: { item: (SuggestionItem & { id: string; stale: boolean }) | null; className?: string }) { if (!item) return null; return ( {item.label} ); } /** The selected clip's label and why, under its provenance. */ export function SuggestWhy({ item }: { item: (SuggestionItem & { id: string; stale: boolean }) | null }) { if (!item) return null; return (

{item.label} · the assistant ranks it {item.rank} {item.stale ? " · stale" : ""} · {item.why}

); } const jobLine = (j: SuggestJob) => { const what = j.mode === "ask" ? "Asking the assistant" : "Labelling the proposals"; if (j.ended) return j.status === "done" ? (j.summary ?? "Done") : `${j.mode === "ask" ? "The ask" : "Suggest"} ${j.status}${j.last ? ` — ${j.last}` : ""}`; if (j.status === "queued") return `${what} — queued${j.queue?.position ? ` (${j.queue.position} in line on ${j.queue.key ?? "the draft queue"})` : ""}`; return `${what}${j.progress ? ` — ${j.progress.current}/${j.progress.target} ${j.progress.metric}` : ""}${j.last ? ` · ${j.last}` : ""}`; }; /** Suggest, its progress, the labels' state and the sort toggle — in the side column. */ export function SuggestPanel({ s, sorted, onSort }: { s: ClipSuggest; sorted: boolean; onSort: (on: boolean) => void }) { const v = s.view; if (!v?.hasReactions) return null; const n = v.suggestions ? Object.keys(v.suggestions.items).length : 0; const running = !!s.job && !s.job.ended; const blocked = v.route?.why ?? null; return (

The assistant

{running && ( )} {n > 0 && ( )}
{n > 0 && v.suggestions && (

{n} labelled by {v.suggestions.model} · {new Date(v.suggestions.at).toLocaleString()}

)} {v.state.stale && (

Stale: {v.state.why}.

)} {blocked &&

{blocked}

} {s.job && (

{jobLine(s.job)}

)} {(s.error || v.error) && (

{s.error ?? v.error}

)}
); } /** What an agent reply proposes, in words. */ export function proposalWords(p: ReplyProposal): string { if (p.kind === "assist") return `${p.ops} edit${p.ops === 1 ? "" : "s"} of the look or the cut (the Ask box)`; if (p.kind === "trim") return `trim ${p.clip} to ${edgeClock(p.from)}–${edgeClock(p.to)} (${(p.to - p.from).toFixed(1)} s)`; if (p.kind === "merge") return `merge ${p.clip} with ${p.with}`; return `cut ${p.clip}`; } /** * Under an agent's reply that carries a proposal: Apply (the clip editor's own * writer does it) while nobody has answered the reply since. `canApply`: why * not, or null. */ export function ReplyProposalRow({ reply, index, replies, canApply, busy, onApply, }: { reply: NoteReply; index: number; replies: NoteReply[]; canApply: (p: ReplyProposal) => string | null; busy: boolean; onApply: (p: ReplyProposal) => void; }) { const p = reply.proposal; if (!p || reply.author !== "agent") return null; const answered = replies.slice(index + 1).some((r) => r.author === "operator"); const why = canApply(p); return (
proposes {proposalWords(p)} {answered ? ( answered ) : ( )} {why && !answered && {why}}
); }