import Link from "next/link"; import path from "node:path"; import { correctionsOf, reviewOf, unfetchedNeedingJudgement, walkReadiness, } from "@/lib/projects/report.mjs"; import { listTakes } from "@/lib/report/takes.mjs"; import { buttonVariants } from "@/components/ui/button"; import { narrationRecordHref, postBenchHref, clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, openInDraftHref, takesHref, trailerHref } from "@/lib/hrefs"; import { readTrailerBeats } from "@/lib/report/trailerBeats.mjs"; import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs"; import FetchUnfetchedButton from "../FetchUnfetchedButton"; import PlayLink from "../PlayLink"; import { AddClipToggle } from "../AddClip"; import { Advanced, Options } from "@/components/ui/disclosure"; import PronunciationPanel from "../PronunciationPanel"; import AddPosts from "../AddPosts"; import { ImportItems, LintButton } from "../TakeTools"; import TightWindowsPanel from "./TightWindowsPanel"; import { clipRecord, storedUrlOf } from "@/lib/clips/stored"; import { Fragment } from "react"; import { deckOn } from "umtool-report-to-video/deck"; import { postItemSeconds } from "umtool-report-to-video/post-item"; import { sectionModel, sectionWords } from "@/lib/report/sectionEdit.mjs"; import { GroupBar, RowControls, RowNotes, SectionBar, TimelineList, type GroupInfo, type SectionInfo } from "../TimelineEditor"; import { groupModel } from "@/lib/report/claimGroups.mjs"; import { Pill, TONE, hms, type ReportTabProps } from "./shared"; import VoiceMatchPanel from "./VoiceMatchPanel"; import FetchWindowsPanel from "./FetchWindowsPanel"; import GroupProposalsPanel from "./GroupProposalsPanel"; import CandidatesPanel from "./CandidatesPanel"; import { readCandidates } from "@/lib/report/candidates.mjs"; import BenchPrepPanel from "./BenchPrepPanel"; import { lastStartedRun, projectFetchBody, readFetchRuns } from "@/lib/report/fetchWindows.mjs"; import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; import { trailerCandidates } from "@/lib/report/trailerCandidates.mjs"; import IntroRow from "./IntroEditor"; import RemovedClips, { type RemovedRow } from "./RemovedClips"; import { readRemoved, removedOutOfCut, removedSourceOf } from "@/lib/report/manifest.mjs"; import { rejectReasonOf } from "@/lib/report/rejectReasons.mjs"; // The inspector panels for this week's hand edits (umtool redesign L6), mounted here until L7's workspace inspector. import { InspectorToggle, WhenOpen } from "../inspector/shared"; import TitleInspector from "../inspector/TitleInspector"; import ProvenanceInspector from "../inspector/ProvenanceInspector"; import TeaserInspector from "../inspector/TeaserInspector"; import LedgerInspector from "../inspector/LedgerInspector"; import PostItemInspector from "../inspector/PostItemInspector"; import LinksInspector from "../inspector/LinksInspector"; import StillInspector from "../inspector/StillInspector"; // The Cut tab: the timeline, read back -- the walk into it, its takes, every // entry with what is wrong with it, and the corrections the walk collected. // Moved from ReportProject unchanged (P4a-1). export default async function CutTab({ project, detail, search, tabHref }: ReportTabProps) { const { manifest: m, entries } = detail; const corrections = correctionsOf(m) as { id: string; channel: string | null; video: string; at: number; href: string; text: string; verdict: "confirmed" | "incorrect" | "rejected" | "unreviewed"; }[]; const clips = entries.filter((e) => e.kind === "clip"); // The clips taken out on record and still out (removed.json), each with Restore (un-reject). const removed: RemovedRow[] = (removedOutOfCut(await readRemoved(project.dir), m) as Record[]).map((r) => ({ id: String(r.id), source: removedSourceOf(r, m), why: rejectReasonOf(String(r.reason ?? ""))?.label ?? String(r.reason ?? "removed"), note: typeof r.note === "string" ? r.note : typeof r.correction === "string" ? r.correction : null, when: typeof r.when === "string" ? r.when : null, })); // The walk's ★ clips, as trailer beats (lib/report/trailerCandidates.mjs). const candidates = trailerCandidates(m); // How much of the cut has been walked. One definition, shared with the bench // header and `umtool corrections`. const review = reviewOf(m); // And how much of it can be walked TODAY: the walk visits the clips that // still need judgement and have something to play, so the gap between these // two numbers is what is waiting on a download rather than on somebody. const readiness = walkReadiness(clips); // What the walk is waiting on: the same clips the rows below mark "not // fetched yet". const pendingFetch = unfetchedNeedingJudgement(clips) as string[]; // How many of them store a media URL the editor can cut from (release 32 R6): // the button offers "Cut from the stored media URL" only when some do. const storedPending = ( await Promise.all( pendingFetch.map(async (id) => { const rec = clipRecord(m, id); return rec ? (await storedUrlOf(rec.channel, rec.video)).stored : false; }), ) ).filter(Boolean).length; const walkStart = (readiness.readyIds[0] as string | undefined) ?? clips[0]?.id; // Add posts (posts reel) leads on a cut of posts or an empty one; on a cut of clips it waits under Options. const postsFirst = entries.length === 0 || entries.some((x) => x.kind === "post"); const postChannels = [...new Set(entries.filter((x) => x.kind === "post" && typeof x.post === "string").map((x) => String(x.post).split("/")[0]))]; const showAll = search.all === "1"; // The candidates inbox (UI notes item 14): its panel once a sweep has proposed something; until // then one line in the timeline's heading says how proposals come in (no panel, no height). const hasCandidates = (await readCandidates(project.dir)).exists === true; const takes = await listTakes(project.dir); // The trailer's beats (promo/trailer-beats.json): how many, for the Trailer link. const trailerBeats = await readTrailerBeats(project.dir).then((d) => d.beats.length, () => null); // A montage (clips carrying `montage`) is ruled on the clip deck (release 34): // how many of its instances have no ruling yet. const montage = montageClipsOf(m) as { id: string }[]; const unruled = montage.length ? await readRulingsState(project.dir).then(({ doc }) => { const keys = momentKeysOf(m) as Map; return montage.filter((e) => !doc.rulings[keys.get(e.id) ?? ""]).length; }) : 0; // The clip editor (release 35 C2): a cut that is not a montage -- how many // of its clips the clip finder proposed (`assist`), and how many a person // has edited since. const assisted = (m?.timeline ?? []).filter((e: { type?: string; assist?: unknown }) => e?.type === "clip" && e.assist && typeof e.assist === "object") as { assist: { by?: string } }[]; const assistedByYou = assisted.filter((e) => e.assist.by === "operator").length; // Fetch windows (release 35): the body the button sends, sized here; a run // still going is followed when the page opens. A rulings file that does not // parse leaves the button out (the clip deck says what is wrong with it). const fetchBody = clips.length ? await projectFetchBody(project) .then(async ({ body, skipped }) => ({ items: body.items.length, skipped: skipped.length, lastRun: lastStartedRun(await readFetchRuns(project.dir)) })) .catch(() => null) : null; // Who is speaking, per clip (release 34): voice-match.json, keyed by the // source moment (clipMomentKey, the rulings' key), so a re-seed keeps its scores. const voices = await readVoiceMatch(project.dir); const voiceOf = (e: Record) => { const key = voices ? (clipMomentKey({ ...e, type: "clip" }, m) as string | null) : null; return key ? voices!.clips[key] ?? null : null; }; // ---- what a clip's "mix" link opens --------------------------------------- // // The widest cached RAW window, not the built segment. Three reasons: it // exists as soon as a clip has been fetched once (segments only exist after a // build), it has NO CHROME burned in -- which is what a mix is looking at -- // and it is the file the bench already has peaks for. The built segment is the // fallback, and the link says which it is. // // start/end are the clip's window MINUS the file's own start, because a mix // spec is relative to the file it names. The arithmetic is exact and known // here; making the client do it would be a second place to get it wrong. const mixHref = (e: { id: string; start: number; end: number; widest: { name: string; path: string; from: number } | null; segment: string | null; }): string | null => { const q = new URLSearchParams(); if (e.widest) { // The window's own path, not a rebuild of it: the editor fetches into // the corpus, so "out/clips-raw/" is a file that is not there. q.set("body", e.widest.path); q.set("start", (e.start - e.widest.from).toFixed(2)); q.set("end", (e.end - e.widest.from).toFixed(2)); } else if (e.segment) { q.set("body", path.join(project.dir, e.segment)); } else { return null; } q.set("from", project.id); q.set("clip", e.id); return `${toolsMixHref()}?${q}`; }; // The deck's sections (its markers, lib/report/sectionEdit.mjs): a bar // opens each one, after the clip its marker follows. const sectionBars = (() => { const after = new Map(); if (!deckOn(m?.render)) return { opening: null as SectionInfo | null, after, sectionOf: null as Map | null }; const model = sectionModel(m); const words = (s: (typeof model.sections)[number]) => ({ ...s, words: sectionWords(s) }) as SectionInfo; model.placed.forEach((p: { pos: number }, i: number) => after.set(p.pos, words(model.sections[i + 1]))); // Under the deck a row's § is its deck section (the markers), not the legacy `section` field. return { opening: model.sections.length > 1 ? words(model.sections[0]) : null, after, sectionOf: model.sections.length > 1 ? (model.sectionOf as Map) : null }; })(); // The claim groups (lib/report/claimGroups.mjs): a bar before each group's // first clip, inside its section; its clips' rows indented under it. const groupBars = (() => { const model = sectionModel(m); const list = (groupModel(m) as GroupInfo[]).map((g) => ({ ...g, color: (model.sections[g.section] as { color?: string | null } | undefined)?.color ?? null })); const at = new Map(list.map((g) => [g.at, g])); const of = new Map(); for (const g of list) for (const id of g.ids) of.set(id, g.id); return { list, at, of }; })(); const renderRow = (e: (typeof entries)[number], at: number) => { // Anything that is not a CLIP renders generically. The timeline's // vocabulary is open -- one real manifest carries `scroll` and // `chart` beside its cards -- and a page that only knows two words // either crashes on the third or silently drops it. // A POST ITEM (report-to-video/post-item.mjs): its own glyph, the post's day, author and // first words, what it carries, how long it plays, and its bench. if (e.kind === "post") { const media = (Array.isArray(e.media) ? e.media : []) as { kind?: string }[]; const words = String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim(); const inGroup = groupBars.of.get(e.id); return (
  • ❝ {e.id} {String(e.date ?? "").slice(0, 10)} {e.author ?? ""} {e.handle ? ` @${e.handle}` : ""} {e.repostedBy ? repost : null} {(Array.isArray(e.parents) && e.parents.length) || e.parentShot || e.replyingTo ? reply : null} {media.length ? media.map((m) => m.kind).join(" + ") : "text"} {postItemSeconds(e).toFixed(1)}s{typeof e.hold === "number" ? " (hold)" : ""} bench {/* Its excerpt by selection, its media on/off, my recording (the inspector, L6). */}
    {words &&
    {words.length > 160 ? `${words.slice(0, 157)}…` : words}
    }
  • ); } if (e.kind !== "clip") { return (
  • {e.id} {e.style ? `${e.kind} · ${e.style}` : e.kind} {e.heading ?? e.title ?? e.label ?? ""} {e.seconds != null && {e.seconds}s} {e.kind === "teaser" && ( )}
  • ); } // `endsSentence === null` means the source has no punctuation to // read, which is a different thing to say than "this cut is fine". const midSentence = e.endsSentence === false && !e.lockEnd && !e.lock; const inGroup = groupBars.of.get(e.id); return (
  • {e.id} {e.video} {hms(e.start)}–{hms(e.end)} ({(e.end - e.start).toFixed(1)}s) {e.lock && locked} {!e.lock && e.lockStart && start pinned} {!e.lock && e.lockEnd && end pinned} {/* The walk's favourite (a trailer candidate) and a deliberate repeat. */} {e.star === true && ( ★ trailer )} {typeof e.repeatOf === "string" && e.repeatOf && ( repeats {e.repeatOf} )} {/* The PLAYER's question, and the walk's: is this clip watchable end to end right now. `data-cached` keeps the BUILD's -- the padded window it would fetch -- because the build chain reads it and they are different. */} {e.fetched ? ( cached ) : ( not fetched yet )} {e.segment && segment built} {(() => { const v = voiceOf(e); if (!v) return null; return ( {typeof v.score !== "number" ? `voice: ${v.why ?? "not scored"}` : `voice ${v.score.toFixed(2)} · ${v.label}`} ); })()} {!e.hasCues && ( no cues )} {midSentence && ends mid-sentence} {e.noPunctuation && source unpunctuated} {e.proposed && ( widener would move it )} {mixHref(e) ? ( mix ) : ( // Never a dead link that 400s: a clip with nothing // fetched has nothing to open. fetch it first )} bench → §{sectionBars.sectionOf?.get(e.id) ?? e.section ?? 0}
    {(showAll || midSentence || e.proposed) && e.quote && (

    “{String(e.quote).slice(0, 240)} {String(e.quote).length > 240 ? "…" : ""}”

    )} {typeof e.walkNote === "string" && e.walkNote && (

    walk note {e.walkNote}

    )} {midSentence && e.endCueText && (

    cut lands inside: “…{String(e.endCueText).trim().slice(-64)}”

    )} {e.proposed && (

    resolve-windows would make it {hms(e.proposed.start)}–{hms(e.proposed.end)} — set lock if this window is deliberate

    )}
  • ); }; return ( <>
    {/* A cut of posts is read aloud: its recording session (lane/post-narration). */} {entries.some((x) => x.kind === "post") && ( Record the narration › )} {/* ---- the way in ---- Every clip row carries a bench link, which is the right control for "go to that one" and the wrong one for "start". Reviewing a cut is watching every clip in order, and the first clip is where that begins -- so it is a button in the title bar rather than the eleventh link on a page whose first screenful is decisions, sources and the build chain. */} {clips.length > 0 && (
    {/* Where the walk STARTS is where the walk goes: the first clip that still needs an answer and can be played. A cut whose first clip is already judged (or not fetched) would otherwise open on a clip `n` immediately leaves. */} Walk the cut → start at {walkStart} p / n move between clips · {review.reviewed} of {review.total}{" "} reviewed{review.incorrect > 0 ? ` · ${review.incorrect} incorrect` : ""} {review.rejected > 0 ? ` · ${review.rejected} rejected` : ""} {" · "} ready {readiness.ready} of {readiness.needing} needing judgement
    )} {/* The whole cut played in the browser in its final look, no render (the Play view). */} {entries.length > 0 && ( Play the cut )} {/* Add a clip, as one flow (lane/ui-simplify): find, in/out on the cues, place, add, fetched. */} {/* A cut of posts (or an empty one): the archive's posts it does not play yet (posts reel); else under Options. */} {postsFirst && } {/* Alternative renders of part of the cut, judged on their own page -- where the first one is made, too (release 33's take maker). */} {takes.exists ? ( Takes — {takes.takes.length} ) : ( Make takes )}
    {/* Everything else, folded (lane/ui-simplify): Options the common, Advanced the rare; open state remembered per viewer. */}
    {!postsFirst && } {/* Check before render, on the cut itself (umtool lint

    ): the build's lint and the files its posts name. */} {entries.length > 0 && } {/* Items of another project into the draft (umtool timeline

    import-item): cloned, their files linked in. */} {/* A montage's instances, ruled by ear before a render (release 34). */} {montage.length > 0 && ( Clips — {unruled ? `${unruled} of ${montage.length} to rule` : `${montage.length} ruled`} )} {/* Any other cut's clips -- an assistant's above all -- adjusted by a person (release 35 C2). */} {montage.length === 0 && clips.length > 0 && ( Clip editor — {clips.length} clip{clips.length === 1 ? "" : "s"} {assisted.length ? ` · ${assisted.length} by the assistant${assistedByYou ? `, ${assistedByYou} edited by you` : ""}` : ""} )} {/* The trailer's beats: the running length against the platform's limit (UI notes item 11). */} {clips.length > 0 && ( {trailerBeats ? `Trailer — ${trailerBeats} beat${trailerBeats === 1 ? "" : "s"}` : trailerBeats === null ? "Trailer (beats file unreadable)" : "Trailer beats"} )} {/* The saved versions and takes: each played read-only, or opened in the draft to edit (L3). */} {takes.takes.some((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) && ( versions {[...takes.takes] .filter((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) .sort((a: { order?: number }, b: { order?: number }) => (b.order ?? 0) - (a.order ?? 0)) .slice(0, 6) .map((t: { id: string; label: string; draft?: boolean }) => ( open ))} )} {fetchBody && } {/* A cut of posts: what the voices say (the lexicon) and who reads whom (the voice map). */} {entries.some((x) => x.kind === "post") && ( )} {/* The project's own facts, each an inspector panel (L6): what agents set by hand this week. */} {clips.length > 0 && } {(Array.isArray(m?.ledger) || m?.ledgerSchema) && } {clips.length > 0 && ( )} {/* Tight windows: each clip to its sentence, for review (UI notes item 4) -- a button until pressed. */} {clips.length > 0 && } {clips.length > 0 && (

    {/* The bench's first-open work (a long recording's excerpt, the waveform), made ahead in the background (lib/report/benchPrep.mjs). */}
    )}
    {/* --- the timeline --------------------------------------------- */}

    the cut — {entries.length} entries, in array order {!hasCandidates && ( · no candidates: umtool candidates {project.id} import <sweep.md> )}

    {/* The gap between "ready" and "needing", closed in one press. Every row below it that reads "not fetched yet" is one of these, and closing them one bench page at a time was the loop this replaces. The default pad is the fetch route's own (±20 s), so a clip fetched here and a clip fetched from the bench land in the same file. */} {pendingFetch.length > 0 && (
    ({ id, padBefore: 20, padAfter: 20 }))} storedUrlClips={storedPending} />
    )} {/* The intro the cut opens on (render.intro), first, and its editor with a live preview (lane intro-play). */} {/* A teaser or closing card, inserted (the inspector, L6; `umtool timeline

    teaser-insert`). */}

    {sectionBars.opening && } {entries.map((e, at) => ( {groupBars.at.get(at) && } {renderRow(e, at)} {sectionBars.after.get(at) && } ))}
    {showAll ? "hide quotes" : "show every quote"}
    {/* The candidates inbox: a sweep's proposed clips, each inserted only by a press (UI notes item 14). */} {hasCandidates && } {clips.length > 0 && } {/* --- the walk's ★ clips: the trailer's candidates ------------------- */} {candidates.length > 0 && (

    ★ trailer candidates — {candidates.length} · {candidates.reduce((n, b) => n + b.end - b.start, 0).toFixed(1)} s

      {candidates.map((b) => (
    • {b.id} {hms(b.start)}–{hms(b.end)} ({(b.end - b.start).toFixed(1)} s) {b.quote && “{b.quote.slice(0, 120)}{b.quote.length > 120 ? "…" : ""}”} {b.walkNote && — {b.walkNote}}
    • ))}

    umtool trailer {project.id} --candidates --json prints them as a trailer’s{" "} --beats-json.{" "} Add them on the Trailer page .

    )} {/* --- corrections ------------------------------------------------ */} {/* Not a decision and not a defect in the CUT: a correction says the REPORT got something wrong -- wrong speaker, wrong addressee, wrong date -- and the fix belongs to the next sweep, not to this manifest. So it is collected here rather than filed in the inbox, in the same shape `umtool corrections` prints, because the list's real destination is somebody's next prompt. */} {corrections.length > 0 && (

    corrections for the next pass —{" "} {corrections.filter((c) => c.verdict === "incorrect").length} {corrections.some((c) => c.verdict !== "incorrect") && ` · ${corrections.filter((c) => c.verdict !== "incorrect").length} notes on clips the report got right`}

      {corrections.map((c) => (
    • {/* A note on a CONFIRMED clip is not a defect, and a reader who cannot tell the two apart goes off to fix a clip nobody complained about. */} {c.verdict !== "incorrect" && note · {c.verdict === "rejected" ? "rejected, facts right" : "confirmed"}}{" "} {c.id} {" "} {c.channel}/{c.video} @ {hms(c.at)} {" "} the moment
      {c.text}
    • ))}

    umtool corrections {project.id} prints the same list as markdown, with the moment links, ready to paste into the next sweep.

    )} ); }