Archilyzer · Source

archilyzer

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

commit a99ac31cda3ffd28a7f8927f8e541e082d0d0a4e
parent 46cca1692c4bcb8b7ee62600f1e84f970f074ddd
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 15:18:46 -0400

umtool: the assistant in the clip editor — labels, Sort by the assistant's rank, Suggest, Ask the assistant, Apply

Labels on each clip and unused proposal (stale ones marked), a sort toggle,
Suggest and Ask start the editor's clips-suggest job (/api/report/clip-suggest)
and show its progress; an agent reply may carry one proposal (trim, merge, cut)
that Apply performs through the clip editor's writer on the operator's click.

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

Diffstat:
Aumtool/app/api/report/clip-suggest/route.ts | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/notes/NoteThread.tsx | 18++++++++++++++----
Mumtool/components/projects/review/ClipEditor.tsx | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Aumtool/components/projects/review/ClipSuggest.tsx | 260+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/annotations/shape.mjs | 56+++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/lib/annotations/types.ts | 10++++++++--
Aumtool/lib/report/clipSuggest.mjs | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipSuggest.test.mjs | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 817 insertions(+), 17 deletions(-)

diff --git a/umtool/app/api/report/clip-suggest/route.ts b/umtool/app/api/report/clip-suggest/route.ts @@ -0,0 +1,121 @@ +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { askEditor, cancelDraftJob, EditorError, readDraftJob, readPolicy } from "@/lib/articles/generation"; +import { + SuggestRequestError, + clearSuggestJob, + draftBodyOf, + parseSuggestRequest, + readSuggestJob, + suggestJobView, + suggestRouteOf, + suggestionsView, + writeSuggestJob, +} from "@/lib/report/clipSuggest.mjs"; + +export const dynamic = "force-dynamic"; + +// THE ASSISTANT IN THE CLIP EDITOR (release 36 lane D) -- optional, every +// part of it: the labels (Suggest), and an answer to a comment (Ask the +// assistant). The model runs in the EDITOR, routed by settings.generation (a +// `report-draft` job, task `clips-suggest`); this route asks it with the +// shared WORKER_TOKEN (lib/articles/generation.ts askEditor), remembers the +// job for the page and follows it. It never writes the manifest or a clip. +// +// GET ?project=<id> the labels, their stale state, the route, the job being followed +// GET ?project=<id>&job=<jobId> that job (ended: forgotten) +// POST { project, mode?: "labels", proposals? } | { project, mode: "ask", note } → { jobId, job } +// POST ?cancel=<jobId>&project=<id> stop it +const headers = { "cache-control": "no-store" }; + +async function suggestProject(id: unknown) { + const project = await projectRef(String(id ?? "")); + if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) }; + if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "the assistant's labels are a report video's" }, { status: 400, headers }) }; + return { project }; +} + +const failed = (e: unknown) => { + const status = e instanceof EditorError ? e.status : e instanceof SuggestRequestError ? 400 : 500; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); +}; + +async function jobOf(dir: string, id: string) { + const rec = await readSuggestJob(dir); + const job = await readDraftJob(id, 40); + const view = suggestJobView(rec && rec.jobId === id ? rec : null, job); + if (view.ended) await clearSuggestJob(dir, id); + return view; +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await suggestProject(url.searchParams.get("project")); + if ("error" in r) return r.error; + const dir = r.project.dir; + const id = url.searchParams.get("job"); + if (id) { + try { + return Response.json(await jobOf(dir, id), { headers }); + } catch (e) { + return failed(e); + } + } + const view = await suggestionsView(dir); + // The route and the followed job need the editor; without one the labels still show. + const policy = await readPolicy().catch((e: unknown) => e as Error); + const rec = await readSuggestJob(dir); + let job = null; + if (rec) { + job = await jobOf(dir, rec.jobId).catch(async (e: unknown) => { + // The editor no longer knows it (restarted): forget it. + if (e instanceof EditorError && e.status === 404) await clearSuggestJob(dir, rec.jobId); + return null; + }); + } + return Response.json( + { + ...view, + route: policy instanceof Error ? null : suggestRouteOf(policy.generation, dir), + editorError: policy instanceof Error ? policy.message : null, + job, + }, + { headers }, + ); +} + +export async function POST(request: Request) { + const url = new URL(request.url); + const cancel = url.searchParams.get("cancel"); + if (cancel) { + const r = await suggestProject(url.searchParams.get("project")); + if ("error" in r) return r.error; + try { + await cancelDraftJob(cancel); + return Response.json({ cancelled: true }, { headers }); + } catch (e) { + return failed(e); + } + } + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); + const r = await suggestProject(body.project); + if ("error" in r) return r.error; + const dir = r.project.dir; + try { + const req = parseSuggestRequest(body); + const running = await readSuggestJob(dir); + if (running) { + const view = await jobOf(dir, running.jobId).catch(() => null); + if (view && !view.ended) return Response.json({ error: "the assistant is already working on this project", job: view }, { status: 409, headers }); + } + const answer = await askEditor<{ jobId?: string }>("/api/ops/report-draft", { method: "POST", body: draftBodyOf(dir, req) }); + const jobId = String(answer.jobId ?? ""); + if (!jobId) return Response.json({ error: "the editor started no job" }, { status: 502, headers }); + await writeSuggestJob(dir, { jobId, mode: req.mode, ...(req.mode === "ask" ? { note: req.note } : {}), at: new Date().toISOString() }); + const job = await jobOf(dir, jobId).catch(() => ({ id: jobId, mode: req.mode, status: "queued", ended: false, queue: null, progress: null, last: null, summary: null })); + return Response.json({ ok: true, jobId, job }, { headers }); + } catch (e) { + return failed(e); + } +} diff --git a/umtool/components/notes/NoteThread.tsx b/umtool/components/notes/NoteThread.tsx @@ -2,7 +2,7 @@ import { useState } from "react"; import { badgeVariants } from "@/components/ui/badge"; -import type { Note, NoteOp } from "@/lib/annotations/types"; +import type { Note, NoteOp, NoteReply } from "@/lib/annotations/types"; // One note: its text, who wrote it, its status, the replies, and what can be // done to it. Shared by the timed notes, the row notes and the take notes. @@ -14,12 +14,18 @@ export function NoteThread({ write, busy, head, + actions, + afterReply, }: { note: Note; write: (op: NoteOp) => Promise<unknown>; busy: boolean; /** What the note is on, drawn before its text (a timestamp, an entry id). */ head?: React.ReactNode; + /** More of the note's actions, after Reply (release 36: the clip editor's Ask the assistant). */ + actions?: React.ReactNode; + /** Drawn under one reply (release 36: an agent reply's proposal and its Apply). */ + afterReply?: (reply: NoteReply, index: number) => React.ReactNode; }) { const [reply, setReply] = useState<string | null>(null); const open = note.status === "open"; @@ -52,6 +58,7 @@ export function NoteThread({ <button type="button" data-note-action="reply" disabled={busy} onClick={() => setReply((r) => (r === null ? "" : null))} className="ink-link disabled:opacity-40"> Reply </button> + {actions} {note.author === "operator" && ( <button type="button" data-note-action="delete" disabled={busy} onClick={() => void write({ op: "delete", id: note.id })} className="text-[var(--color-dim)] hover:text-text disabled:opacity-40"> Delete @@ -60,9 +67,12 @@ export function NoteThread({ </span> </div> {note.replies.map((r, i) => ( - <div key={i} data-note-reply={i} className="ml-4 flex flex-wrap items-baseline gap-1.5 text-[11px]"> - {r.author === "agent" && <span className={badgeVariants({ variant: "meter", size: "sm" })}>agent</span>} - <span className="whitespace-pre-wrap text-[var(--color-dim)]">{r.text}</span> + <div key={i}> + <div data-note-reply={i} className="ml-4 flex flex-wrap items-baseline gap-1.5 text-[11px]"> + {r.author === "agent" && <span className={badgeVariants({ variant: "meter", size: "sm" })}>agent</span>} + <span className="whitespace-pre-wrap text-[var(--color-dim)]">{r.text}</span> + </div> + {afterReply?.(r, i)} </div> ))} {reply !== null && ( diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx @@ -12,6 +12,9 @@ import { edgeClock, provenanceWords, quoteBetween, roleOf, snapCut, snapPoints } import type { EditorClip, EditorView, Neighbourhood, Proposal, RenderTarget, Speaker, Turn } from "@/lib/report/clipEditorTypes"; import { cn } from "@/lib/utils"; import { startTakeJob } from "../NewTakePanel"; +// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply (all optional). +import type { ReplyProposal } from "@/lib/annotations/types"; +import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy, useClipSuggest, type ClipSuggest } from "./ClipSuggest"; // --------------------------------------------------------------------------- // THE CLIP EDITOR (release 35 C2): a person hops in on an assistant's clips. @@ -95,6 +98,10 @@ export default function ClipEditor({ const committed = cutOf(clip); const cut = draft ?? committed; const speakers = view.reactions?.speakers ?? []; + // The assistant (release 36 lane D): labels, a rank to sort by, Suggest, Ask. + const assistant = useClipSuggest(project); + const [byRank, setByRank] = useState(false); + const rankOf = (proposal: string | null | undefined) => assistant.labelOf(proposal)?.rank ?? Number.POSITIVE_INFINITY; // The page's address names the clip, so a reload (or a link) lands on it. useEffect(() => { @@ -282,6 +289,24 @@ export default function ClipEditor({ }, 1500); return () => clearInterval(t); }, [proposing, reload]); + // An agent reply's proposal, applied ON THE OPERATOR'S CLICK through the + // writer every other edit here uses (release 36 lane D). + const canApply = (p: ReplyProposal): string | null => { + const at = clips.findIndex((c) => c.id === p.clip); + if (at < 0) return `${p.clip} is no longer in the cut`; + if (p.kind === "merge" && clips[at + 1]?.id !== p.with) return `${p.with} is no longer the next clip`; + return null; + }; + const applyProposal = async (p: ReplyProposal): Promise<boolean> => { + await flush(); + const j = + p.kind === "trim" + ? await write({ op: "trim", clip: p.clip, cutStart: p.from, cutEnd: p.to }, `Applied: ${proposalWords(p)}`) + : p.kind === "merge" + ? await write({ op: "merge", clip: p.clip }, `Applied: ${proposalWords(p)}`) + : await write({ op: "ruling", clip: p.clip, verdict: "cut" }, `Applied: ${proposalWords(p)}`); + return !!j; + }; const rx = view.reactions; const rolesStale = rolesChanged || (!!rx?.rolesChangedAt && (!rx.proposedAt || rx.rolesChangedAt > rx.proposedAt)); const snap = () => { @@ -380,6 +405,7 @@ export default function ClipEditor({ {prov} </p> )} + <SuggestWhy item={assistant.labelOf(assist?.proposal)} /> {(quoteNow ?? clip.quote) && ( <p data-editor-quote="" className="m-0 max-w-[70ch] text-[13px] leading-snug text-text"> {quoteNow || clip.quote} @@ -529,7 +555,7 @@ export default function ClipEditor({ </div> {/* ---- comments and history ---------------------------------------- */} - <ClipNotes project={project} clipId={clip.id} /> + <ClipNotes project={project} clipId={clip.id} assistant={assistant} canApply={canApply} onApply={applyProposal} /> {edits.length > 0 && ( <details data-editor-history={edits.length} className="text-[12px] text-text-2"> <summary className="cursor-pointer text-muted">{plural(edits.length, "edit")} to this clip</summary> @@ -547,12 +573,13 @@ export default function ClipEditor({ {/* ---- the list, the proposals, the speakers, the take --------------- */} <aside className="flex min-h-0 flex-col gap-3 overflow-auto border-t border-seam bg-panel p-3 lg:border-l lg:border-t-0" data-editor-side=""> + <SuggestPanel s={assistant} sorted={byRank} onSort={setByRank} /> <section> <h2 className="micro mb-1"> {plural(clips.length, "clip")} · {clips.filter((c) => c.ruling === "keep").length} kept · {clips.filter((c) => c.ruling === "cut").length} cut </h2> <ol className="m-0 list-none space-y-0.5 p-0" data-editor-list=""> - {clips.map((c) => { + {(byRank ? [...clips].sort((a, b) => rankOf(a.assist?.proposal) - rankOf(b.assist?.proposal)) : clips).map((c) => { const cc = cutOf(c); return ( <li key={c.id}> @@ -567,6 +594,7 @@ export default function ClipEditor({ <span className="num font-mono text-[11px] text-muted"> {edgeClock(cc.cutStart)} · {(cc.cutEnd - cc.cutStart).toFixed(0)} s </span> + <SuggestLabel item={assistant.labelOf(c.assist?.proposal)} /> <span className="ml-auto flex gap-1"> {c.assist?.by === "operator" && <span className={badgeVariants({ variant: "info", size: "sm" })}>you</span>} {c.ruling && <span className={rulingBadge(c.ruling)}>{c.ruling}</span>} @@ -587,15 +615,19 @@ export default function ClipEditor({ <p className="m-0 text-[12px] text-muted">Every proposal is in the cut.</p> ) : ( <ul className="m-0 list-none space-y-1 p-0"> - {view.reactions.proposals.map((p) => ( + {(byRank ? [...view.reactions.proposals].sort((a, b) => rankOf(a.id) - rankOf(b.id)) : view.reactions.proposals).map((p) => ( <li key={p.id} data-proposal={p.id} className="flex items-baseline gap-2 text-[12px] text-text-2"> <span className="font-mono text-[11.5px]">{p.id}</span> <span className="num font-mono text-[11px] text-muted"> {edgeClock(p.start)} · {(p.end - p.start).toFixed(0)} s{typeof p.score === "number" ? ` · ${p.score.toFixed(2)}` : ""} </span> - <span className="min-w-0 flex-1 truncate" title={p.why}> - {p.why} - </span> + {assistant.labelOf(p.id) ? ( + <SuggestLabel item={assistant.labelOf(p.id)} className="flex-1" /> + ) : ( + <span className="min-w-0 flex-1 truncate" title={p.why}> + {p.why} + </span> + )} <button type="button" data-bring-in={p.id} disabled={busy} onClick={() => bringIn(p)} className={buttonVariants({ size: "sm" })}> Bring in </button> @@ -994,8 +1026,28 @@ function EdgeControl({ edge, value, onNudge, onSet, onPlayhead }: { edge: "in" | } /** The notes on one clip: its thread (an agent's replies too), resolve / reopen, a box for another. */ -function ClipNotes({ project, clipId }: { project: string; clipId: string }) { +function ClipNotes({ + project, + clipId, + assistant, + canApply, + onApply, +}: { + project: string; + clipId: string; + /** Release 36 lane D: Ask the assistant on a comment, and Apply its proposal. */ + assistant?: ClipSuggest; + canApply?: (p: ReplyProposal) => string | null; + onApply?: (p: ReplyProposal) => Promise<boolean>; +}) { const notes = useSharedNotes({ project }); + const reloadNotes = notes.reload; + // An Ask's reply lands in notes.json from the editor's job: read it again when a job ends. + useEffect(() => { + if (assistant?.ended) void reloadNotes(); + }, [assistant?.ended, reloadNotes]); + const askJob = assistant?.job && assistant.job.mode === "ask" ? assistant.job : null; + const askBlocked = assistant?.view?.route?.why ?? null; const [text, setText] = useState(""); const mine = notesOn(notes.notes, { kind: "entry", entry: clipId }).filter((n) => n.anchor.kind !== "moment"); const open = mine.filter((n) => n.status === "open").length; @@ -1008,7 +1060,45 @@ function ClipNotes({ project, clipId }: { project: string; clipId: string }) { <section data-clip-notes={clipId} data-open-notes={open} className="space-y-1.5 rounded-[3px] border border-seam bg-panel p-2.5"> <h2 className="micro m-0">Comments{mine.length ? ` — ${open} open of ${mine.length}` : ""}</h2> {mine.map((n) => ( - <NoteThread key={n.id} note={n} write={notes.write} busy={notes.busy} head={n.anchor.kind === "edit" ? <span className={badgeVariants({ variant: "info", size: "sm" })}>edit · {n.anchor.field}</span> : null} /> + <NoteThread + key={n.id} + note={n} + write={notes.write} + busy={notes.busy} + head={n.anchor.kind === "edit" ? <span className={badgeVariants({ variant: "info", size: "sm" })}>edit · {n.anchor.field}</span> : null} + actions={ + assistant?.view?.hasReactions && n.status === "open" && n.anchor.kind === "entry" ? ( + <button + type="button" + data-note-action="ask" + disabled={notes.busy || !!askBlocked || (!!askJob && !askJob.ended)} + title={askBlocked ?? "the assistant reads this comment, the clip's words and its neighbours, and replies here; an edit it proposes waits for your Apply"} + onClick={() => void assistant.start({ mode: "ask", note: n.id })} + className="ink-link disabled:opacity-40" + > + {askJob && askJob.note === n.id && !askJob.ended ? "Asking…" : "Ask the assistant"} + </button> + ) : null + } + afterReply={ + canApply && onApply + ? (r, i) => ( + <ReplyProposalRow + reply={r} + index={i} + replies={n.replies} + canApply={canApply} + busy={notes.busy} + onApply={(p) => + void onApply(p).then((ok) => { + if (ok) void notes.write({ op: "reply", id: n.id, text: `Applied: ${proposalWords(p)}` }); + }) + } + /> + ) + : undefined + } + /> ))} <div className="flex flex-wrap items-start gap-2"> <textarea @@ -1027,6 +1117,12 @@ function ClipNotes({ project, clipId }: { project: string; clipId: string }) { Add comment </button> </div> + {askJob && ( + <div className="text-[11.5px] text-text-2" data-ask-job={askJob.status}> + {askJob.ended ? (askJob.status === "done" ? (askJob.summary ?? "The assistant replied") : `The ask ${askJob.status}${askJob.last ? ` — ${askJob.last}` : ""}`) : `Asking the assistant${askJob.status === "queued" ? " — queued" : ""}…`} + </div> + )} + {assistant?.error && <div className="text-[12px] text-reject-text" data-ask-error="">{assistant.error}</div>} {notes.error && <div className="text-[12px] text-reject-text">{notes.error}</div>} </section> ); diff --git a/umtool/components/projects/review/ClipSuggest.tsx b/umtool/components/projects/review/ClipSuggest.tsx @@ -0,0 +1,260 @@ +"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<string, SuggestionItem> } | 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<void>; + cancel: () => Promise<void>; + /** 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<SuggestView | null>(null); + const [job, setJob] = useState<SuggestJob | null>(null); + const [error, setError] = useState<string | null>(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<SuggestJob | null>(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 ( + <span + data-suggest-label={item.id} + data-suggest-rank={item.rank} + data-suggest-stale={item.stale ? "" : undefined} + title={`${item.why}${item.stale ? " (stale: the proposal changed since)" : ""}`} + className={cn("min-w-0 truncate text-[12px] text-text-2", item.stale && "italic text-muted", className)} + > + {item.label} + </span> + ); +} + +/** 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 ( + <p data-suggest-why={item.id} className="m-0 text-[12.5px] text-text-2"> + <span className="font-medium text-text">{item.label}</span> · the assistant ranks it {item.rank} + {item.stale ? " · stale" : ""} · {item.why} + </p> + ); +} + +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 ( + <section data-suggest-panel={n} data-suggest-state={v.state.stale ? "stale" : n ? "fresh" : "none"} className="space-y-1"> + <h2 className="micro m-0">The assistant</h2> + <div className="flex flex-wrap items-center gap-2 text-[12px] text-text-2"> + <button + type="button" + data-suggest-button="" + disabled={running || !!blocked} + title={blocked ?? (v.route?.model ? `labels and a rank for every proposal, on ${v.route.model}; nothing in the cut changes` : "labels and a rank for every proposal; nothing in the cut changes")} + onClick={() => void s.start({ mode: "labels" })} + className={buttonVariants({ size: "sm" })} + > + {running && s.job?.mode === "labels" ? "Suggesting…" : n ? "Suggest again" : "Suggest"} + </button> + {running && ( + <button type="button" data-suggest-cancel="" onClick={() => void s.cancel()} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Stop + </button> + )} + {n > 0 && ( + <label className="inline-flex items-center gap-1"> + <input type="checkbox" data-suggest-sort="" checked={sorted} onChange={(e) => onSort(e.target.checked)} /> + Sort by the assistant&rsquo;s rank + </label> + )} + </div> + {n > 0 && v.suggestions && ( + <p className="m-0 text-[11.5px] text-muted" data-suggest-meta=""> + {n} labelled by {v.suggestions.model} · {new Date(v.suggestions.at).toLocaleString()} + </p> + )} + {v.state.stale && ( + <p className="m-0 text-[11.5px] text-doubt-text" data-suggest-stale-line=""> + Stale: {v.state.why}. + </p> + )} + {blocked && <p className="m-0 text-[11.5px] text-muted" data-suggest-blocked="">{blocked}</p>} + {s.job && ( + <p className="m-0 text-[11.5px] text-text-2" data-suggest-job={s.job.status} data-suggest-job-mode={s.job.mode}> + {jobLine(s.job)} + </p> + )} + {(s.error || v.error) && ( + <p role="alert" className="m-0 text-[11.5px] text-reject-text" data-suggest-error=""> + {s.error ?? v.error} + </p> + )} + </section> + ); +} + +/** What an agent reply proposes, in words. */ +export function proposalWords(p: ReplyProposal): string { + 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 ( + <div data-reply-proposal={p.kind} className="ml-4 flex flex-wrap items-center gap-1.5 text-[11px] text-text-2"> + <span className={badgeVariants({ variant: "meter", size: "sm" })}>proposes</span> + <span>{proposalWords(p)}</span> + {answered ? ( + <span className="text-muted" data-reply-proposal-answered="">answered</span> + ) : ( + <button type="button" data-apply-proposal={p.kind} disabled={busy || !!why} title={why ?? "do it now, through the clip editor (Undo on the Cut tab takes a merge back)"} onClick={() => onApply(p)} className={buttonVariants({ variant: "go", size: "sm" })}> + Apply + </button> + )} + {why && !answered && <span className="text-muted">{why}</span>} + </div> + ); +} diff --git a/umtool/lib/annotations/shape.mjs b/umtool/lib/annotations/shape.mjs @@ -117,6 +117,42 @@ export function validateAnchor(raw) { } } +export const REPLY_PROPOSAL_KINDS = ["trim", "merge", "cut"]; + +/** + * An agent reply's proposal (release 36 lane D, "Ask the assistant"): ONE + * edit of one clip the clip editor can perform on the operator's click — + * { kind: "trim", clip, from, to, basis? } the clip's new cut, seconds on the recording + * { kind: "merge", clip, with, basis? } the clip and the next one, joined + * { kind: "cut", clip, basis? } the clip ruled out + * `basis` is the clip's cut when the agent read it ({ cutStart, cutEnd }). + * Never applied by whoever writes it. `{ proposal }` or `{ error }`. + * @param {unknown} raw + */ +export function validateReplyProposal(raw) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { error: "proposal is not an object" }; + const p = /** @type {Record<string, unknown>} */ (raw); + if (!REPLY_PROPOSAL_KINDS.includes(/** @type {string} */ (p.kind))) return { error: `proposal kind must be one of ${REPLY_PROPOSAL_KINDS.join(", ")}` }; + if (!short(p.clip, 128) || !ID.test(p.clip)) return { error: "proposal needs the clip's id" }; + const fin = (v) => typeof v === "number" && Number.isFinite(v); + const out = { kind: p.kind, clip: p.clip }; + if (p.kind === "trim") { + if (!fin(p.from) || !fin(p.to) || p.from < 0 || p.to - p.from < 0.5) return { error: "a trim proposal needs from ≥ 0 and to at least half a second after it" }; + out.from = Math.round(p.from * 100) / 100; + out.to = Math.round(p.to * 100) / 100; + } + if (p.kind === "merge") { + if (!short(p.with, 128) || !ID.test(p.with)) return { error: "a merge proposal needs the next clip's id (with)" }; + out.with = p.with; + } + if (p.basis !== undefined) { + const b = /** @type {Record<string, unknown>} */ (p.basis); + if (!b || typeof b !== "object" || !fin(b.cutStart) || !fin(b.cutEnd)) return { error: "proposal basis is { cutStart, cutEnd }" }; + out.basis = { cutStart: b.cutStart, cutEnd: b.cutEnd }; + } + return { proposal: out }; +} + /** @returns {{ subject: Record<string, string> } | { error: string }} */ export function validateSubject(raw) { if (!raw || typeof raw !== "object") return { error: "subject is not an object" }; @@ -179,7 +215,13 @@ export function parseNotesDoc(raw) { const replies = []; for (const r of n.replies) { if (!r || !NOTE_AUTHORS.includes(r.author) || !isStr(r.text) || !isStr(r.at)) return { error: `${where}.replies` }; - replies.push({ author: r.author, text: r.text, at: r.at }); + const reply = { author: r.author, text: r.text, at: r.at }; + if (r.proposal !== undefined) { + const p = validateReplyProposal(r.proposal); + if ("error" in p) return { error: `${where}.replies: ${p.error}` }; + reply.proposal = p.proposal; + } + replies.push(reply); } const note = { id: n.id, status: n.status, author: n.author, text: n.text, at: n.at, updatedAt: n.updatedAt, anchor: a.anchor, replies }; if (isStr(n.resolvedAt)) note.resolvedAt = n.resolvedAt; @@ -227,7 +269,8 @@ function setStatus(note, status, by, now) { * { op: "add", text, anchor } a new open note * { op: "edit", id, text?, anchor? } rewrite it (its author only) * { op: "status", id, status } open | resolved | wontfix - * { op: "reply", id, text, resolve? } a threaded reply, optionally resolving + * { op: "reply", id, text, resolve?, proposal? } a threaded reply, optionally resolving; + * an AGENT's may carry one proposal (validateReplyProposal) * { op: "delete", id } remove the note * { op: "delete-reply", id, index } remove one reply * { op: "source", source } correct which file to edit @@ -268,7 +311,14 @@ export function applyOp(doc, op, by, now = new Date().toISOString()) { } case "reply": { const note = find(doc, op.id); - note.replies.push({ author: by, text: cleanText(op.text), at: now }); + const reply = { author: by, text: cleanText(op.text), at: now }; + if (op.proposal !== undefined && op.proposal !== null) { + if (by !== "agent") throw new NoteError("only an agent's reply carries a proposal: the operator applies it"); + const p = validateReplyProposal(op.proposal); + if ("error" in p) throw new NoteError(p.error); + reply.proposal = p.proposal; + } + note.replies.push(reply); note.updatedAt = now; if (op.resolve) setStatus(note, "resolved", by, now); return note; diff --git a/umtool/lib/annotations/types.ts b/umtool/lib/annotations/types.ts @@ -44,7 +44,13 @@ export type Anchor = export type AnchorKind = Anchor["kind"]; -export type NoteReply = { author: NoteAuthor; text: string; at: string }; +/** An agent reply's one proposed edit of a clip (release 36 lane D): applied only by the operator's click. */ +export type ReplyProposal = + | { kind: "trim"; clip: string; from: number; to: number; basis?: { cutStart: number; cutEnd: number } } + | { kind: "merge"; clip: string; with: string; basis?: { cutStart: number; cutEnd: number } } + | { kind: "cut"; clip: string; basis?: { cutStart: number; cutEnd: number } }; + +export type NoteReply = { author: NoteAuthor; text: string; at: string; proposal?: ReplyProposal }; export type Note = { id: string; @@ -89,7 +95,7 @@ export type NoteOp = | { op: "add"; text: string; anchor: Anchor } | { op: "edit"; id: string; text?: string; anchor?: Anchor } | { op: "status"; id: string; status: NoteStatus } - | { op: "reply"; id: string; text: string; resolve?: boolean } + | { op: "reply"; id: string; text: string; resolve?: boolean; proposal?: ReplyProposal } | { op: "delete"; id: string } | { op: "delete-reply"; id: string; index: number } | { op: "source"; source: NotesSource }; diff --git a/umtool/lib/report/clipSuggest.mjs b/umtool/lib/report/clipSuggest.mjs @@ -0,0 +1,142 @@ +// THE ASSISTANT IN THE CLIP EDITOR, umtool's half (release 36 lane D): the +// labels file read for the page, the request a Suggest or an Ask sends the +// editor, and the editor job the page follows. +// +// clip-suggestions.json written by the EDITOR's `report-draft` task +// `clips-suggest` (its one writer, common's +// lib/clips/suggest.mjs); read here with its stale +// state — shown, marked, never hidden +// .clip-suggest-job.json the editor job the page is following, so a reload +// (or another tab) shows its progress; umtool's own +// file, cleared when the job is seen to end +// +// Everything is optional: with no labels file, no editor, generation routed +// to Claude Code or no model at all, the clip editor works as before. Nothing +// here calls a model, and nothing here writes the manifest or a clip. +import { readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; +import { readSuggestions, suggestionsState } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; + +export const SUGGEST_TASK = "clips-suggest"; +export const SUGGEST_JOB_FILE = ".clip-suggest-job.json"; +const JOB_RE = /^[A-Za-z0-9_-]+$/; +const NOTE_RE = /^n_[a-z0-9]{4,32}$/; +const PROPOSAL_RE = /^[A-Za-z0-9._:-]{1,64}$/; +const RESULT_MARKER = "@@report-draft "; +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +export class SuggestRequestError extends Error {} + +/** The labels and their state, for the page: `{ suggestions, error, state }`. */ +export async function suggestionsView(dir) { + const [{ doc, error }, reactions] = await Promise.all([readSuggestions(dir), readReactions(dir)]); + return { suggestions: doc, error, state: suggestionsState(doc, reactions), hasReactions: !!reactions }; +} + +/** + * A POST's body, judged: `{ mode: "labels", proposals? }` (Suggest) or + * `{ mode: "ask", note }` (Ask the assistant on one comment). + * @param {unknown} body + */ +export function parseSuggestRequest(body) { + if (!isObj(body)) throw new SuggestRequestError("a body is { project, mode, … }"); + const mode = body.mode ?? "labels"; + if (mode === "labels") { + if (body.note !== undefined) throw new SuggestRequestError("a note is an Ask's (mode: \"ask\")"); + if (body.proposals === undefined || body.proposals === null) return { mode }; + if (!Array.isArray(body.proposals) || !body.proposals.length || !body.proposals.every((p) => typeof p === "string" && PROPOSAL_RE.test(p))) { + throw new SuggestRequestError("proposals is a list of proposal ids"); + } + return { mode, proposals: [...new Set(body.proposals)] }; + } + if (mode === "ask") { + if (typeof body.note !== "string" || !NOTE_RE.test(body.note)) throw new SuggestRequestError("an Ask names the note it answers (n_…)"); + return { mode, note: body.note }; + } + throw new SuggestRequestError('mode is "labels" or "ask"'); +} + +/** The editor's `report-draft` body for a request on a project directory. */ +export function draftBodyOf(dir, req) { + return { + task: SUGGEST_TASK, + project: dir, + ...(req.mode === "ask" ? { note: req.note } : {}), + ...(req.proposals ? { proposals: req.proposals } : {}), + }; +} + +const jobFileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, SUGGEST_JOB_FILE); + +/** The job the page follows, or null: `{ jobId, mode, note?, at }`. */ +export async function readSuggestJob(dir) { + try { + const j = JSON.parse(await readFile(jobFileOf(dir), "utf8")); + return isObj(j) && typeof j.jobId === "string" && JOB_RE.test(j.jobId) ? j : null; + } catch { + return null; + } +} + +/** Remember the job a Suggest or an Ask started (tmp + rename). */ +export async function writeSuggestJob(dir, rec) { + const file = jobFileOf(dir); + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(tmp, `${JSON.stringify(rec)}\n`); + await rename(tmp, file); +} + +/** Forget it — only when it is still that job. */ +export async function clearSuggestJob(dir, jobId) { + const cur = await readSuggestJob(dir); + if (cur && cur.jobId === jobId) await rm(jobFileOf(dir), { force: true }); +} + +/** The job's `@@report-draft` result in its log tail, or null. */ +export function suggestMarkerOf(tail) { + for (let i = (tail?.length ?? 0) - 1; i >= 0; i--) { + const at = String(tail[i]).indexOf(RESULT_MARKER); + if (at < 0) continue; + try { + return JSON.parse(String(tail[i]).slice(at + RESULT_MARKER.length)); + } catch { + return null; + } + } + return null; +} + +export const ENDED = Object.freeze(["done", "failed", "cancelled", "interrupted"]); + +/** What the page shows of a job: its state, progress, last line, and its result once it ended. */ +export function suggestJobView(rec, job) { + const marker = suggestMarkerOf(job.tail); + const last = [...(job.tail ?? [])].reverse().find((l) => !String(l).includes(RESULT_MARKER)) ?? null; + return { + id: job.id, + mode: rec?.mode ?? marker?.kind ?? "labels", + ...(rec?.note ? { note: rec.note } : {}), + status: job.status, + ended: ENDED.includes(job.status), + queue: job.queue ?? null, + progress: job.progress ?? null, + last: last === null ? null : String(last).slice(0, 300), + summary: typeof marker?.summary === "string" ? marker.summary : null, + }; +} + +/** + * How the task is routed, for the button: `{ route, model, why }` from the + * policy's generation block, or null without one. `why` is set when the + * button cannot start a job here (routed to Claude Code). + */ +export function suggestRouteOf(generation, dir) { + if (!isObj(generation) || !isObj(generation.routes)) return null; + const route = generation.routes[SUGGEST_TASK] ?? null; + if (route === "code") { + return { route, model: null, why: `routed to Claude Code — in a session: /gen label the clips of ${dir}` }; + } + const model = route === "api" ? generation.models?.api : route === "local" ? generation.models?.local : null; + return { route, model: typeof model === "string" ? model : null, why: route ? null : "the editor's policy routes no clips-suggest" }; +} diff --git a/umtool/lib/report/clipSuggest.test.mjs b/umtool/lib/report/clipSuggest.test.mjs @@ -0,0 +1,115 @@ +// Release 36 lane D: the assistant in the clip editor, umtool's half — the +// labels read with their stale state, the request a Suggest or an Ask sends, +// the job the page follows — and an agent reply's proposal in notes.json +// (only an agent's, validated, kept on read). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { writeReactionProject, labelAnswer, PROJECT_NOTE } from "yt-dlp-transcript-common/testing/clips/reactionProject.mjs"; +import { suggestionsDocOf, writeSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; +import { + SuggestRequestError, + clearSuggestJob, + draftBodyOf, + parseSuggestRequest, + readSuggestJob, + suggestJobView, + suggestMarkerOf, + suggestRouteOf, + suggestionsView, + writeSuggestJob, +} from "./clipSuggest.mjs"; +import { applyOp, emptyDoc, NoteError, parseNotesDoc, validateReplyProposal } from "../annotations/shape.mjs"; + +test("the labels for the page: none, fresh, then stale once the proposals are made again", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "umtool-suggest-")); + try { + const { reactions } = writeReactionProject(dir); + let v = await suggestionsView(dir); + assert.deepEqual(v, { suggestions: null, error: null, state: { stale: false, why: null, passNewer: false, staleIds: [], missing: [] }, hasReactions: true }); + await writeSuggestions(dir, suggestionsDocOf({ model: "qwen3:8b", at: "2026-10-19T02:00:00.000Z", reactions, fresh: labelAnswer(["p001", "p003"]).items })); + v = await suggestionsView(dir); + assert.equal(v.suggestions.items.p003.rank, 1); + assert.equal(v.state.stale, false); + assert.deepEqual(v.state.missing, ["p002", "p004", "p005"]); + await writeFile(path.join(dir, "reactions.json"), JSON.stringify({ ...reactions, proposedAt: "2026-10-20T00:00:00.000Z" })); + v = await suggestionsView(dir); + assert.equal(v.state.stale, true); + assert.equal(v.state.passNewer, true); + // A project the clip finder never ran on: no panel. + const empty = await mkdtemp(path.join(os.tmpdir(), "umtool-suggest-none-")); + assert.equal((await suggestionsView(empty)).hasReactions, false); + await rm(empty, { recursive: true, force: true }); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a request: labels (all, or some proposals) or an Ask on one note; the editor's body; the route's button", () => { + assert.deepEqual(parseSuggestRequest({ project: "x" }), { mode: "labels" }); + assert.deepEqual(parseSuggestRequest({ mode: "labels", proposals: ["p001", "p001", "p002"] }), { mode: "labels", proposals: ["p001", "p002"] }); + assert.deepEqual(parseSuggestRequest({ mode: "ask", note: PROJECT_NOTE }), { mode: "ask", note: PROJECT_NOTE }); + assert.throws(() => parseSuggestRequest({ mode: "ask" }), SuggestRequestError); + assert.throws(() => parseSuggestRequest({ mode: "labels", proposals: ["../x"] }), /proposal ids/); + assert.throws(() => parseSuggestRequest({ mode: "apply" }), /"labels" or "ask"/); + assert.deepEqual(draftBodyOf("/r/p", { mode: "ask", note: PROJECT_NOTE }), { task: "clips-suggest", project: "/r/p", note: PROJECT_NOTE }); + assert.deepEqual(draftBodyOf("/r/p", { mode: "labels", proposals: ["p002"] }), { task: "clips-suggest", project: "/r/p", proposals: ["p002"] }); + const generation = { routes: { "clips-suggest": "local" }, models: { api: "claude-sonnet-5-5", local: "qwen3:8b" } }; + assert.deepEqual(suggestRouteOf(generation, "/r/p"), { route: "local", model: "qwen3:8b", why: null }); + assert.deepEqual(suggestRouteOf({ ...generation, routes: { "clips-suggest": "code" } }, "/r/p"), { + route: "code", + model: null, + why: "routed to Claude Code — in a session: /gen label the clips of /r/p", + }); + assert.equal(suggestRouteOf(null, "/r/p"), null); +}); + +test("the followed job: remembered, shown with its progress and result, forgotten only when it is that job", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "umtool-suggest-job-")); + try { + assert.equal(await readSuggestJob(dir), null); + await writeSuggestJob(dir, { jobId: "job-1", mode: "ask", note: PROJECT_NOTE, at: "t" }); + assert.deepEqual(await readSuggestJob(dir), { jobId: "job-1", mode: "ask", note: PROJECT_NOTE, at: "t" }); + await clearSuggestJob(dir, "job-2"); + assert.ok(await readSuggestJob(dir)); + const tail = ["clips-suggest ask …", "replied to n_synth0001, proposing a trim to 94.8–99 s", '@@report-draft {"task":"clips-suggest","kind":"ask","status":"done","summary":"replied to n_synth0001 on r002"}']; + assert.equal(suggestMarkerOf(tail).kind, "ask"); + assert.deepEqual(suggestJobView(await readSuggestJob(dir), { id: "job-1", status: "done", queue: null, progress: null, tail }), { + id: "job-1", + mode: "ask", + note: PROJECT_NOTE, + status: "done", + ended: true, + queue: null, + progress: null, + last: "replied to n_synth0001, proposing a trim to 94.8–99 s", + summary: "replied to n_synth0001 on r002", + }); + await clearSuggestJob(dir, "job-1"); + assert.equal(await readSuggestJob(dir), null); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a reply's proposal: an agent's only, validated, kept when notes.json is read again", () => { + const doc = emptyDoc({ kind: "video-project", project: "p" }); + const note = applyOp(doc, { op: "add", text: "start it on the laugh", anchor: { kind: "entry", entry: "r002" } }, "operator"); + const trim = { kind: "trim", clip: "r002", from: 94.8, to: 99, basis: { cutStart: 88, cutEnd: 99 } }; + assert.throws(() => applyOp(doc, { op: "reply", id: note.id, text: "I did it", proposal: trim }, "operator"), NoteError); + assert.throws(() => applyOp(doc, { op: "reply", id: note.id, text: "x", proposal: { kind: "trim", clip: "r002", from: 99, to: 99.2 } }, "agent"), /half a second/); + assert.throws(() => applyOp(doc, { op: "reply", id: note.id, text: "x", proposal: { kind: "merge", clip: "r002" } }, "agent"), /the next clip's id/); + assert.throws(() => applyOp(doc, { op: "reply", id: note.id, text: "x", proposal: { kind: "delete", clip: "r002" } }, "agent"), /trim, merge, cut/); + applyOp(doc, { op: "reply", id: note.id, text: "Start on the laugh.", proposal: trim }, "agent"); + applyOp(doc, { op: "reply", id: note.id, text: "plain reply" }, "agent"); + const again = parseNotesDoc(JSON.parse(JSON.stringify(doc))); + assert.ok("doc" in again); + assert.deepEqual(again.doc.notes[0].replies.map((r) => r.proposal ?? null), [trim, null]); + // A hand-broken proposal makes the file unreadable rather than being dropped. + const broken = JSON.parse(JSON.stringify(doc)); + broken.notes[0].replies[0].proposal.to = "soon"; + assert.match(parseNotesDoc(broken).error, /replies: a trim proposal needs/); + assert.deepEqual(validateReplyProposal({ kind: "cut", clip: "r003", extra: 1 }), { proposal: { kind: "cut", clip: "r003" } }); +});