"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { badgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { useSharedNotes } from "@/components/notes/NotesProvider"; import { NoteThread } from "@/components/notes/NoteThread"; import { cn } from "@/lib/utils"; import type { NoteReply } from "@/lib/annotations/types"; // --------------------------------------------------------------------------- // THE ASK BOX (release 38 lane E): the video assistant, optional in every // part. A request in words ("make the joins 0.15 s with less smear") starts // the editor's `video-assist` job (routed by settings.generation: local by // default, through the GPU arbiter); its PROPOSALS come back as a diff list // -- Apply all, Apply one, Dismiss -- and nothing is written until Apply, // which re-checks each op and writes through the manifest's own writers // (/api/report/video-assist, lib/report/videoAssist.mjs). A note on the whole // project can be asked too: the assistant replies on it, with an Apply. // Preview join renders the first joins in the current look (the heavy slot). // With generation routed elsewhere or no editor the box says so; the panel it // sits in is the manual path. // --------------------------------------------------------------------------- type Scope = "look" | "clips" | "fx" | "all"; type ProposedOp = { id: string; op: Record; diff: string; warning?: string; status: "proposed" | "applied" | "dismissed" | "failed"; error?: string; now?: string | null; diffNow?: string | null }; export type Proposals = { at: string; model: string; request: string; scope: string; note?: string; reply?: string; ops: ProposedOp[]; refused: { op: Record; why: string }[] }; export type Job = { id: string; status: string; ended: boolean; queue: { key?: string; position?: number } | null; last: string | null; summary: string | null; note?: string; request?: string }; export type View = { proposals: Proposals | null; error: string | null; route: { route: "code" | "api" | "local" | null; model: string | null; why: string | null } | null; editorError: string | null; job: Job | null; token: string | null; }; type Preview = { size: number; mtimeMs: number; stale: boolean; record: { clips?: string[] } | null } | null; type PreviewJob = { id: string; state: string; error: string | null }; export const routeLine = (v: View): string => { if (!v.route) return `The assistant needs the editor${v.editorError ? ` (${v.editorError})` : ""}. Every setting here is a field you can change by hand.`; if (v.route.why) return `${v.route.why}. Every setting here is a field you can change by hand.`; if (v.route.route === "local") return `On the local model${v.route.model ? ` (${v.route.model})` : ""}, through the GPU: it waits while a transcription runs. Nothing changes until you Apply.`; return `On the Claude API${v.route.model ? ` (${v.route.model})` : ""}. Nothing changes until you Apply.`; }; export const jobLine = (j: Job): string => { if (j.ended) return j.status === "done" ? (j.summary ?? "Done") : `The ask ${j.status}${j.last ? ` — ${j.last}` : ""}`; if (j.status === "queued") { const gpu = j.queue?.key === "draft:local"; return `Queued${j.queue?.position ? ` (${j.queue.position} in line)` : ""}${gpu ? " — waiting for the GPU (a transcription runs first)" : ""}`; } return `Asking the assistant${j.last ? ` · ${j.last}` : ""}`; }; const STATUS_WORD: Record = { proposed: "proposed", applied: "applied", dismissed: "dismissed", failed: "not applied" }; export function useAssist(project: string) { const [view, setView] = useState(null); const [job, setJob] = useState(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); const [ended, setEnded] = useState(0); const load = useCallback(async () => { const r = await fetch(`/api/report/video-assist?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null); if (!r) return; const j = (await r.json().catch(() => null)) as (View & { error?: string }) | null; if (!r.ok || !j) { setError(j?.error ?? `HTTP ${r.status}`); return; } setView(j); if (j.job && !j.job.ended) setJob(j.job); }, [project]); useEffect(() => { void load(); }, [load]); const live = job && !job.ended ? job.id : null; useEffect(() => { if (!live) return; const t = setInterval(async () => { const r = await fetch(`/api/report/video-assist?project=${encodeURIComponent(project)}&job=${encodeURIComponent(live)}`, { cache: "no-store" }).catch(() => null); if (!r?.ok) return; const j = (await r.json()) as Job; setJob(j); if (j.ended) { setEnded((n) => n + 1); await load(); } }, 1500); return () => clearInterval(t); }, [live, project, load]); const post = useCallback( async (body: Record) => { setBusy(true); setError(null); try { const r = await fetch("/api/report/video-assist", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) }); const j = (await r.json().catch(() => ({}))) as Record; return { ok: r.ok, status: r.status, json: j }; } finally { setBusy(false); } }, [project], ); const ask = useCallback( async (body: { request: string; scope: Scope } | { note: string; scope: Scope }) => { // The last ask's line goes: what shows next is this one's. setJob(null); const r = await post(body); if (r.json.job) setJob(r.json.job as Job); if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`)); return r.ok; }, [post], ); const apply = useCallback( async (ids: string[] | null, at?: string) => { const r = await post({ action: "apply", token: view?.token ?? null, ...(ids ? { ids } : {}), ...(at ? { at } : {}) }); if (r.status === 409) { await load(); setError(`${String(r.json.error ?? "the cut changed")} — reloaded; check and apply again`); return false; } if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`)); await load(); return r.ok && Array.isArray(r.json.applied) && (r.json.applied as unknown[]).length > 0; }, [post, view?.token, load], ); const dismiss = useCallback( async (ids: string[] | null) => { const r = await post({ action: "dismiss", ...(ids ? { ids } : {}), ...(view?.proposals ? { at: view.proposals.at } : {}) }); if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`)); await load(); }, [post, view?.proposals, load], ); const cancel = useCallback(async () => { if (!job) return; await fetch(`/api/report/video-assist?cancel=${encodeURIComponent(job.id)}&project=${encodeURIComponent(project)}`, { method: "POST" }).catch(() => null); }, [job, project]); return { view, job, error, busy, ended, load, ask, apply, dismiss, cancel }; } /** The proposals as a diff list: Apply one, Apply all, Dismiss. */ export function ProposalList({ p, busy, onApply, onDismiss }: { p: Proposals; busy: boolean; onApply: (ids: string[] | null) => void; onDismiss: () => void }) { const waiting = p.ops.filter((o) => o.status === "proposed" || o.status === "failed"); const applicable = waiting.filter((o) => !o.now); return (

“{p.request}” — {p.model} · {new Date(p.at).toLocaleString()}

{p.reply && (

{p.reply}

)} {p.ops.length === 0 &&

No edit proposed.

} {p.ops.length > 0 && (
    {p.ops.map((o) => (
  • {o.status === "proposed" && o.diffNow && o.diffNow !== o.diff ? o.diffNow : o.diff} {o.status !== "proposed" && {STATUS_WORD[o.status]}} {(o.status === "proposed" || o.status === "failed") && ( )} {o.warning && {o.warning}} {o.now && (o.status === "proposed" || o.status === "failed") && ( now: {o.now} )} {o.error && o.status === "failed" && !o.now && {o.error}}
  • ))}
)} {p.refused.length > 0 && (
    {p.refused.map((r, i) => (
  • not proposed: {r.why}
  • ))}
)} {waiting.length > 0 && (
)}
); } /** Preview join: the first joins in the look as saved (a render in the heavy slot), played here. */ function JoinPreview({ project, version }: { project: string; version: string }) { const [preview, setPreview] = useState(null); const [job, setJob] = useState(null); const [error, setError] = useState(null); const load = useCallback(async () => { const r = await fetch(`/api/report/join-preview?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null); if (!r?.ok) return; const j = (await r.json()) as { preview: Preview; running: PreviewJob | null }; setPreview(j.preview); if (j.running) setJob(j.running); }, [project]); useEffect(() => { void load(); }, [load, version]); const running = job?.state === "running"; useEffect(() => { if (!job || job.state !== "running") return; const t = setInterval(async () => { const r = await fetch(`/api/report/join-preview?job=${job.id}`, { cache: "no-store" }).catch(() => null); if (!r?.ok) return; const j = (await r.json()) as PreviewJob; setJob(j); if (j.state !== "running") await load(); }, 1500); return () => clearInterval(t); }, [job, load]); const start = async () => { setError(null); const r = await fetch("/api/report/join-preview", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project }) }); const j = (await r.json().catch(() => ({}))) as { job?: PreviewJob; error?: string }; if (!r.ok || !j.job) setError(j.error ?? `HTTP ${r.status}`); else setJob(j.job); }; return (
{running && ( )} {preview?.stale && the look changed since this preview} {job && !running && job.state !== "done" && preview {job.state}{job.error ? `: ${job.error}` : ""}} {error && ( {error} )}
{preview && (
); } /** * Under an agent's reply that carries the assistant's proposals (`assist`): * how many, and Apply all -- only while they are the proposals on file and * something still waits. Nothing is written until the click. */ export function AssistReplyApply({ reply: r, proposals: p, busy, apply, onApplied, variant = "go", }: { reply: NoteReply; proposals: Proposals | null; busy: boolean; apply: (ids: string[] | null, at?: string) => Promise; onApplied: () => void; /** "outline" where the page's one primary action is another (the Play view's Save note). */ variant?: "go" | "outline"; }) { const pr = r.proposal; if (!pr || pr.kind !== "assist" || r.author !== "agent") return null; const current = !!p && p.at === pr.at; const waiting = current ? p!.ops.filter((o) => o.status === "proposed" && !o.now).length : 0; return (
proposes {pr.ops} edit{pr.ops === 1 ? "" : "s"} {!current ? ( a newer ask replaced these ) : waiting ? ( ) : ( nothing waiting )}
); } /** The project-level notes, each with Ask the assistant; an agent reply's proposals with Apply all. */ function ProjectNotes({ project, a, scope, apply }: { project: string; a: ReturnType; scope: Scope; apply: (ids: string[] | null, at?: string) => Promise }) { const notes = useSharedNotes({ project }); const reloadNotes = notes.reload; useEffect(() => { if (a.ended) void reloadNotes(); }, [a.ended, reloadNotes]); const [text, setText] = useState(""); const whole = notes.notes.filter((n) => n.anchor.kind === "whole"); const blocked = a.view?.route?.why ?? (a.view && !a.view.route ? "the assistant needs the editor" : null); const asking = a.job && !a.job.ended ? a.job.note : null; const p = a.view?.proposals ?? null; const add = async () => { if (!text.trim()) return; const n = await notes.write({ op: "add", text, anchor: { kind: "whole" } }); if (n) setText(""); }; return (

Notes on the project{whole.length ? ` — ${whole.filter((n) => n.status === "open").length} open` : ""}

{whole.map((n) => ( void a.ask({ note: n.id, scope })} className="ink-link disabled:opacity-40" > {asking === n.id ? "Asking…" : "Ask the assistant"} ) : null } afterReply={(r) => void notes.write({ op: "reply", id: n.id, text: "Applied the assistant's edits" })} />} /> ))}