// 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"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.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 = tmpPathFor(file); 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" }; }