Archilyzer · Source

archilyzer

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

commit 6571e0a71328a4d471d072442e54a470c967bb1e
parent da4ed5aff09593ced004482c41268ef72fc3169f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 10 Nov 2026 11:28:53 -0500

Merge main (L4 needs-you, L10 vertical deck) into lane/workspace

PlayCut resolved onto the extracted core: main's 9:16 player sizing (`tall`, PLAYER_MAX_W_TALL) and VersionVerdict kept in
PlayCut, the stacked deck's post hero card (geometry `post`) moved into playCore's PlayStage; the workspace's viewer
fits the frame's own shape.

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

Diffstat:
Mcommon/lib/report/look.mjs | 30+++++++++++++++++++++++++++---
Mcommon/lib/report/vertical.d.mts | 6++++++
Mcommon/lib/report/vertical.mjs | 36+++++++++++++++++++++++++++++++++---
Mumtool/app/api/report/chrome/preview/route.ts | 9++++++---
Mumtool/app/api/report/links/route.ts | 24++++++++++++------------
Mumtool/app/api/report/quick-clip/route.ts | 10++++++++--
Aumtool/app/api/report/quick-clip/strip/route.ts | 22++++++++++++++++++++++
Mumtool/app/api/report/takes/verdict/route.ts | 7+++++++
Mumtool/app/api/report/timeline/route.ts | 4++++
Mumtool/app/api/report/window/route.ts | 4++++
Mumtool/app/page.tsx | 47++++++++++++++++++++++++++++++++++-------------
Mumtool/components/inbox/InboxList.tsx | 32+++++++++++++++++++++++++++++---
Aumtool/components/inbox/QuickClip.tsx | 238+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/AddClip.tsx | 43++++++++++---------------------------------
Mumtool/components/projects/OnscreenSection.tsx | 2+-
Aumtool/components/projects/bench/WordStrip.tsx | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/DecisionSettle.tsx | 39++++++++++++++++++++++++++++++++-------
Mumtool/components/projects/review/ClipEditor.tsx | 33+++------------------------------
Mumtool/components/projects/review/PlayCut.tsx | 12++++++++++--
Aumtool/components/projects/review/VersionVerdict.tsx | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/playCore.tsx | 17+++++++++++------
Mumtool/components/projects/workspace/Workspace.tsx | 6++++--
Mumtool/components/shell/AppRail.tsx | 28++++++----------------------
Mumtool/components/shell/RecentCuts.tsx | 13+++++++------
Mumtool/components/shell/RunningList.tsx | 17+++++++++--------
Mumtool/docs/cli.md | 6++++--
Mumtool/docs/knobs.md | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/e2e/fixtures/editor-stub-services.mjs | 25+++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 5+++++
Mumtool/e2e/fixtures/make-fixture.mjs | 14++++++++++++++
Mumtool/e2e/fixtures/measure-extras-fixture.mjs | 6++++--
Aumtool/e2e/fixtures/needs-you-fixture.mjs | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/inbox-engine.spec.ts | 3++-
Aumtool/e2e/needs-you.spec.ts | 243+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/running.spec.ts | 14++++++++------
Aumtool/e2e/vertical-deck.spec.ts | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/cli/groups.mjs | 8++++++--
Mumtool/lib/cli/verbs.mjs | 2++
Mumtool/lib/decisions.ts | 6+++++-
Mumtool/lib/inbox.ts | 24+++++++++++++++++++++---
Aumtool/lib/inbox/caseCues.mjs | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/caseCues.ts | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/checks.mjs | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/inbox/groups.mjs | 39+++++++++++++++++++++++++++++++++++++--
Aumtool/lib/inbox/needs-you.test.ts | 279+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/projectCalls.ts | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/versions.mjs | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/walk.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/inbox/what.mjs | 7+++++++
Aumtool/lib/inbox/xJar.mjs | 41+++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/xJar.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/machine.ts | 17+++++++++++++++--
Mumtool/lib/projects/report.mjs | 21++++++++++++++++++---
Mumtool/lib/report/knobsCli.mjs | 5+++--
Mumtool/lib/report/linksCli.mjs | 64++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mumtool/lib/report/manifest.mjs | 4+++-
Aumtool/lib/report/momentLink.mjs | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/momentLink.test.mjs | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/onscreen.mjs | 14+++++++++++---
Mumtool/lib/report/quickClip.mjs | 19++++++++++++++++---
Aumtool/lib/report/quickClipStrip.mjs | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/quickClipStrip.test.mjs | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/quoteCheck.test.mjs | 4++++
Mumtool/lib/report/takeCli.mjs | 21++++++++++++++++++++-
Mumtool/lib/report/takePreview.mjs | 9++++++---
Mumtool/lib/report/takePreview.test.mjs | 2++
Mumtool/lib/report/versions.test.mjs | 20++++++++++++++++++++
Mumtool/lib/report/verticalCli.mjs | 31++++++++++++++++++++++++++++---
Mumtool/playwright.config.ts | 2++
Mumtool/report-to-video/build-video.mjs | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/report-to-video/chrome-deck.mjs | 15+++++++++------
Mumtool/report-to-video/chrome-instruments.mjs | 73++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/report-to-video/chrome-story.mjs | 8+++++---
Aumtool/report-to-video/chrome-vdeck.mjs | 358+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/compose-chrome.mjs | 8+++++++-
Mumtool/report-to-video/deck.mjs | 211++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/report-to-video/instruments.mjs | 7++++---
Mumtool/report-to-video/lint.mjs | 39+++++++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/measure-extras.mjs | 30+++++++++++++++++++++++-------
Mumtool/report-to-video/modules/blur.mjs | 2++
Mumtool/report-to-video/modules/chapter.mjs | 2++
Mumtool/report-to-video/modules/contract.mjs | 11+++++++++++
Mumtool/report-to-video/modules/counter.mjs | 2++
Mumtool/report-to-video/modules/dial-finale.mjs | 2++
Mumtool/report-to-video/modules/dial.mjs | 2++
Mumtool/report-to-video/modules/fx.mjs | 2++
Mumtool/report-to-video/modules/index.mjs | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/modules/intro.mjs | 2++
Mumtool/report-to-video/modules/measure-extras-module.mjs | 2++
Mumtool/report-to-video/modules/odometer.mjs | 2++
Mumtool/report-to-video/modules/pair.mjs | 2++
Mumtool/report-to-video/modules/qr.mjs | 2++
Mumtool/report-to-video/modules/rail.mjs | 2++
Mumtool/report-to-video/modules/section-title.mjs | 2++
Mumtool/report-to-video/modules/shelf.mjs | 2++
Mumtool/report-to-video/modules/shell.mjs | 14++++++++++++++
Mumtool/report-to-video/modules/stamp.mjs | 2++
Mumtool/report-to-video/modules/stats.mjs | 2++
Mumtool/report-to-video/modules/status.mjs | 2++
Mumtool/report-to-video/modules/subtitle.mjs | 2++
Mumtool/report-to-video/modules/teaser.mjs | 2++
Mumtool/report-to-video/modules/trail.mjs | 2++
Mumtool/report-to-video/outro.mjs | 195++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/report-to-video/outro.test.mjs | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/reel-intro.mjs | 10+++++++---
Mumtool/report-to-video/reframe.mjs | 42++++++++++++++++++++++++++++++++++++++----
Mumtool/report-to-video/render-estimate.mjs | 21+++++++++++++++++++--
Mumtool/report-to-video/subtitle-lines.test.mjs | 7+++++--
Aumtool/report-to-video/vertical-deck.mjs | 282+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/vertical-deck.test.mjs | 415+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/vertical.mjs | 11++++++++---
112 files changed, 4767 insertions(+), 306 deletions(-)

diff --git a/common/lib/report/look.mjs b/common/lib/report/look.mjs @@ -18,7 +18,7 @@ // styles with `umtool look <p> intro=<style>`, and every writer checks it here. import { introPatchValue, validateIntro } from "./intro.mjs"; // `format` and `vertical` (lane vertical): the cut rendered 9:16, and a clip's side post (./vertical.mjs). -import { VERTICAL_CLIP_LAYOUTS, validateVerticalFormat } from "./vertical.mjs"; +import { CLIP_OWN_LAYOUTS, validateVerticalFormat } from "./vertical.mjs"; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const num = (v) => typeof v === "number" && Number.isFinite(v); @@ -313,8 +313,11 @@ export function verticalErrors(v, who = "vertical") { if (v === undefined || v === null) return []; if (!isObj(v)) return [`${who} must be an object ({crop: [x, y, w, h]}), not ${q(v)}`]; const errors = []; - for (const k of Object.keys(v)) if (k !== "crop" && k !== "aspect" && k !== "layout") errors.push(`${who}.${k} is not a setting here (crop, aspect, layout)`); - if (v.layout !== undefined && !VERTICAL_CLIP_LAYOUTS.includes(v.layout)) errors.push(`${who}.layout must be one of ${VERTICAL_CLIP_LAYOUTS.join(", ")}`); + for (const k of Object.keys(v)) if (!["crop", "aspect", "layout", "crops"].includes(k)) errors.push(`${who}.${k} is not a setting here (crop, aspect, layout, crops)`); + if (v.layout !== undefined && !CLIP_OWN_LAYOUTS.includes(v.layout)) errors.push(`${who}.layout must be one of ${CLIP_OWN_LAYOUTS.join(", ")}`); + // The stacked deck's two crops (`layout: "twocrop"`): two boxes of the source, the first on top. Any shape: + // each is fitted to its band (cut to the band's aspect about its centre). + if (v.crops !== undefined || v.layout === "twocrop") errors.push(...twoCropErrors(v, who)); // A clip may set its vertical layout alone: the crop is then the centred one. if (v.crop === undefined && v.layout !== undefined) return errors; if (v.aspect !== undefined && (!num(v.aspect) || v.aspect <= 0.2 || v.aspect > 5)) { @@ -339,6 +342,27 @@ export function verticalErrors(v, who = "vertical") { return errors; } +/** A clip's `vertical.crops` (and the "twocrop" layout that needs them), as sentences. */ +function twoCropErrors(v, who) { + const errors = []; + const c = v.crops; + if (v.layout === "twocrop" && c === undefined) return [`${who}.layout "twocrop" needs ${who}.crops: [[x, y, w, h], [x, y, w, h]] (the top crop first)`]; + if (v.layout !== undefined && v.layout !== "twocrop") errors.push(`${who}.crops are the "twocrop" layout's (set ${who}.layout=twocrop, or remove the crops)`); + if (!Array.isArray(c) || c.length !== 2) return [...errors, `${who}.crops must be two boxes [[x, y, w, h], [x, y, w, h]], fractions of the source picture`]; + const E = 1e-3; + c.forEach((b, i) => { + const at = `${who}.crops[${i}]`; + if (!Array.isArray(b) || b.length !== 4 || !b.every(num)) { + errors.push(`${at} must be [x, y, w, h], four fractions of the source picture`); + return; + } + const [x, y, w, h] = b; + if (w <= 0.02 || h <= 0.02) errors.push(`${at}'s width and height must be above 0.02 of the picture`); + if (x < -E || y < -E || x + w > 1 + E || y + h > 1 + E) errors.push(`${at} must lie inside the picture (each of x, y, x + w, y + h from 0 to 1)`); + }); + return errors; +} + /** Every clip's `vertical`. */ export function validateVertical(manifest) { const errors = []; diff --git a/common/lib/report/vertical.d.mts b/common/lib/report/vertical.d.mts @@ -5,7 +5,9 @@ type Render = Record<string, unknown> | null | undefined; export type ClipLayout = "full" | "framed" | "quote"; export type PostLayout = "card" | "stack" | "media"; export type SideLayout = "split" | "overlay"; +export type VerticalDeck = "stacked" | "bare"; export type VerticalKnobs = { + deck: VerticalDeck; clip: ClipLayout; post: PostLayout; side: SideLayout; @@ -18,6 +20,8 @@ export type VerticalKnobs = { }; export const RENDER_FORMATS: readonly ("landscape" | "vertical")[]; export const VERTICAL_CLIP_LAYOUTS: readonly ClipLayout[]; +export const CLIP_OWN_LAYOUTS: readonly (ClipLayout | "twocrop")[]; +export const VERTICAL_DECKS: readonly VerticalDeck[]; export const VERTICAL_POST_LAYOUTS: readonly PostLayout[]; export const VERTICAL_SIDE_LAYOUTS: readonly SideLayout[]; export const LANDSCAPE_SIDE_PLACES: readonly ("right" | "left")[]; @@ -34,6 +38,8 @@ export const VERTICAL_SAFE_MAX: Readonly<{ top: number; bottom: number; right: n export function verticalOn(render: Render): boolean; export function verticalKnobs(render: Render): VerticalKnobs; export function clipLayoutOf(entry: unknown, render: Render): ClipLayout; +export function stackedDeckWanted(render: Render): boolean; +export function clipTwoCrop(entry: unknown): [number[], number[]] | null; export function validateVerticalRender(manifest: unknown): string[]; export function sideErrors(side: unknown, who?: string, opts?: { itemIds?: Set<string> | null }): string[]; export function validateClipSides(manifest: unknown): string[]; diff --git a/common/lib/report/vertical.mjs b/common/lib/report/vertical.mjs @@ -2,7 +2,11 @@ // 9:16 for the shorts platforms, and the side post a clip may carry. // // render.format "vertical" | "landscape" absent = landscape, the cut as it always was -// render.vertical { clip?, post?, side?, captions?, hook?, tag?, safe?, loudness?, maxSeconds? } +// render.vertical { deck?, clip?, post?, side?, captions?, hook?, tag?, safe?, loudness?, maxSeconds? } +// deck "stacked" (the default: a cut that has a deck keeps it in 9:16 -- the rail under the top band, +// the picture at full width, the captions under it, the instruments in two columns, +// the source line and its QR above the bottom band; report-to-video/vertical-deck.mjs) +// "bare" (the vertical format as it first shipped: no header, footer, QR, rail or deck) // clip "full" (T1: a 9:16 crop, big word captions in the lower middle, a source tag) // "framed" (T2: the whole 16:9 picture in the middle third over a blurred enlargement // of itself; captions below, a hook band above) @@ -27,7 +31,9 @@ // `from`/`to` are seconds into the clip as it plays; `place` overrides the cut's // render.vertical.side for this clip ("split" | "overlay"), or, in a landscape cut, // "right" (the default) | "left" for the panel's side. -// clip.vertical.layout this clip's own layout ("full" | "framed" | "quote") over the cut's. +// clip.vertical.layout this clip's own layout ("full" | "framed" | "quote") over the cut's -- or, in the +// stacked deck, "twocrop": two crops of its picture stacked, `vertical.crops: [[x,y,w,h],[x,y,w,h]]` +// (fractions of the source; the first on top), a strip of the instruments between them. // // PURE: no fs, no ffmpeg. Plain ESM with a .d.mts beside it. @@ -37,6 +43,10 @@ const q = (v) => JSON.stringify(v); export const RENDER_FORMATS = Object.freeze(["landscape", "vertical"]); export const VERTICAL_CLIP_LAYOUTS = Object.freeze(["full", "framed", "quote"]); +/** A clip's OWN layouts: the cut's, and the stacked deck's two crops (a clip's alone: it needs its crops). */ +export const CLIP_OWN_LAYOUTS = Object.freeze([...VERTICAL_CLIP_LAYOUTS, "twocrop"]); +/** What a vertical cut does with the deck: keep it stacked in 9:16, or drop it (the bare vertical). */ +export const VERTICAL_DECKS = Object.freeze(["stacked", "bare"]); export const VERTICAL_POST_LAYOUTS = Object.freeze(["card", "stack", "media"]); export const VERTICAL_SIDE_LAYOUTS = Object.freeze(["split", "overlay"]); /** Where a side post sits in a LANDSCAPE cut. */ @@ -54,6 +64,7 @@ export const VERTICAL_HEIGHT = 1920; /** The shorts conventions, as knobs: what a cut that sets none gets. */ export const VERTICAL_DEFAULTS = Object.freeze({ + deck: "stacked", clip: "full", post: "card", side: "split", @@ -74,6 +85,7 @@ export const verticalOn = (render) => render?.format === "vertical"; export function verticalKnobs(render) { const v = isObj(render?.vertical) ? render.vertical : {}; return { + deck: VERTICAL_DECKS.includes(v.deck) ? v.deck : VERTICAL_DEFAULTS.deck, clip: VERTICAL_CLIP_LAYOUTS.includes(v.clip) ? v.clip : VERTICAL_DEFAULTS.clip, post: VERTICAL_POST_LAYOUTS.includes(v.post) ? v.post : VERTICAL_DEFAULTS.post, side: VERTICAL_SIDE_LAYOUTS.includes(v.side) ? v.side : VERTICAL_DEFAULTS.side, @@ -86,12 +98,29 @@ export function verticalKnobs(render) { }; } -/** A clip's layout in a vertical cut: its own `vertical.layout`, else the cut's. */ +/** A clip's layout in a vertical cut: its own `vertical.layout`, else the cut's ("twocrop" is the stacked deck's: clipTwoCrop). */ export function clipLayoutOf(entry, render) { const own = entry?.vertical?.layout; return VERTICAL_CLIP_LAYOUTS.includes(own) ? own : verticalKnobs(render).clip; } +/** + * Does this cut keep its deck in 9:16 (the stacked deck)? A vertical cut whose `render.vertical.deck` is + * "stacked" (the default) AND that has a deck to keep (`render.chrome`, the HyperFrames deck). A cut with no + * deck is the bare vertical whatever it says. + */ +export function stackedDeckWanted(render) { + const c = render?.chrome; + return verticalOn(render) && verticalKnobs(render).deck === "stacked" && isObj(c) && c.engine === "hyperframes" && c.layout === "deck"; +} + +/** A clip's two crops (`vertical.layout: "twocrop"`, `vertical.crops`), or null: the stacked deck plays it so. */ +export function clipTwoCrop(entry) { + const v = entry?.vertical; + if (!isObj(v) || v.layout !== "twocrop" || !Array.isArray(v.crops) || v.crops.length !== 2) return null; + return v.crops.every((c) => Array.isArray(c) && c.length === 4 && c.every(num)) ? v.crops.map((c) => [...c]) : null; +} + /** Every reason `render.format` / `render.vertical` cannot be built. */ export function validateVerticalRender(manifest) { const r = manifest?.render; @@ -106,6 +135,7 @@ export function validateVerticalRender(manifest) { const oneOf = (k, list) => { if (v[k] !== undefined && !list.includes(v[k])) errors.push(`render.vertical.${k} must be one of ${list.join(", ")}, not ${q(v[k])}`); }; + oneOf("deck", VERTICAL_DECKS); oneOf("clip", VERTICAL_CLIP_LAYOUTS); oneOf("post", VERTICAL_POST_LAYOUTS); oneOf("side", VERTICAL_SIDE_LAYOUTS); diff --git a/umtool/app/api/report/chrome/preview/route.ts b/umtool/app/api/report/chrome/preview/route.ts @@ -22,6 +22,7 @@ import { resolveFactcheck, stampsDrawn, tallyAlways, tallyOf } from "umtool-repo import { counterOrder } from "umtool-report-to-video/counter"; import { cachedTakeManifest, takePlayDir, writePlayManifest } from "@/lib/report/takeManifest.mjs"; import { isTakeId } from "@/lib/report/takes.mjs"; +import { stackedOn } from "umtool-report-to-video/vertical-deck"; export const dynamic = "force-dynamic"; @@ -197,8 +198,10 @@ export async function POST(request: Request) { } catch (e) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500 }); } - // `posts: false` -- the clip bench's strip, which has no footage to lay them on. - const windows = body.posts === false ? [] : await composePostsPreviews(target, r.variant, schedule); + // `posts: false` -- the clip bench's strip, which has no footage to lay them on. The stacked vertical deck draws + // no popups (they have no vertical form: vertical-deck.mjs), nor the landscape finale's page. + const stacked = stackedOn(render); + const windows = body.posts === false || stacked ? [] : await composePostsPreviews(target, r.variant, schedule); const stamp = Date.now(); const isFeed = body.posts !== false && (schedule as { layout?: string }).layout === "feed"; let feed: Record<string, unknown> | null = null; @@ -240,7 +243,7 @@ export async function POST(request: Request) { // Not on the bench's strip either. const fin = (schedule as { finale?: { from: number; to: number } }).finale ?? null; let finale: Record<string, unknown> | null = null; - if (body.posts !== false && fin) { + if (body.posts !== false && fin && !stacked) { let error: string | null = null; try { await composeFinalePreview(target, r.variant, schedule); diff --git a/umtool/app/api/report/links/route.ts b/umtool/app/api/report/links/route.ts @@ -2,8 +2,8 @@ import { projectRef } from "@/lib/projects"; import { readManifest } from "@/lib/projects/report.mjs"; import { linkVerdicts, readLinkCheck, runLinkCheck } from "@/lib/report/linkCheck.mjs"; import { refuseCaller } from "@/lib/report/caller"; -import { withEditNotes } from "@/lib/report/guard"; -import { updateClip } from "@/lib/report/manifest.mjs"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; +import { applyLinkFixes } from "@/lib/report/linksCli.mjs"; export const dynamic = "force-dynamic"; @@ -17,7 +17,10 @@ export const dynamic = "force-dynamic"; // GET ?project=<id> the recorded check (out/links.json) read against the manifest as it is now // POST { project, fix? } check now, record it, and answer the same; `fix`: first // rewrite every dead link the last check knows the fix for -// (a Twitch id the site serves as v<id>) through the window writer +// (a Twitch id the site serves as v<id>; a Rumble folder id as the +// embed id the archive serves, `siteVideo` -- "Use embed ids") +// through the window writer, after one undo point (linksCli.mjs +// applyLinkFixes, `umtool links <p> --fix`'s own) const headers = { "cache-control": "no-store" }; async function answer(dir: string, doc: Awaited<ReturnType<typeof readLinkCheck>>) { @@ -36,6 +39,9 @@ export async function GET(request: Request) { export async function POST(request: Request) { const refused = refuseCaller(request, "/api/report/links"); if (refused) return refused; + // Another site's page may not write here (lib/report/sameOrigin.mjs: Sec-Fetch-Site, Origin, a loopback Host). + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); const b = (await request.json().catch(() => null)) as { project?: unknown; fix?: unknown } | null; if (!b || typeof b !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); const project = await projectRef(String(b.project ?? "")); @@ -43,16 +49,10 @@ export async function POST(request: Request) { let m = await readManifest(project.dir); if (!m) return Response.json({ error: "the project has no video.manifest.json" }, { status: 400, headers }); try { - const fixed: { clip: string; from: string; to: string }[] = []; + let fixed: { clip: string; from: string; to: string; siteVideo?: string }[] = []; if (b.fix === true) { - const last = await readLinkCheck(project.dir); - const now = new Map(((m.timeline ?? []) as { id: string; citeUrl?: string }[]).map((e) => [e.id, e.citeUrl])); - for (const l of last?.links ?? []) { - // Only a link still exactly what the check saw: an edit since is somebody's decision. - if (l.state !== "dead" || !l.fix || now.get(l.clip) !== l.url) continue; - await withEditNotes(project, () => updateClip(project.dir, l.clip, { citeUrl: l.fix })); - fixed.push({ clip: l.clip, from: l.url, to: l.fix }); - } + // Only a clip still as the recorded check saw it: an edit since is somebody's decision. + fixed = (await applyLinkFixes(project, m, await readLinkCheck(project.dir), { guard: true })).fixed; if (fixed.length) m = await readManifest(project.dir); } const doc = await runLinkCheck(project.dir, m); diff --git a/umtool/app/api/report/quick-clip/route.ts b/umtool/app/api/report/quick-clip/route.ts @@ -1,6 +1,7 @@ import path from "node:path"; import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; import { UMTOOL_DIR } from "@/lib/report/driver.mjs"; import { quickClipSpec } from "@/lib/report/quickClip.mjs"; @@ -23,11 +24,14 @@ const SITE_RE = /^[a-z0-9][a-z0-9._-]*$/i; export async function POST(request: Request) { const refused = refuseCaller(request, "/api/report/quick-clip"); if (refused) return refused; + // Another site's page may not write here (lib/report/sameOrigin.mjs: Sec-Fetch-Site, Origin, a loopback Host). + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; if (!body || typeof body !== "object") return Response.json({ error: "expected JSON" }, { status: 400, headers }); const spec = String(body.spec ?? "").trim(); if (!quickClipSpec(spec)) { - return Response.json({ error: 'spec is <channel>/<video>@<start>-<end> in seconds, the end after the start, its ids neither "." nor starting "-"' }, { status: 400, headers }); + return Response.json({ error: 'spec is <channel>/<video>@<start>-<end> in seconds, the end after the start, its ids not dots, the channel not starting "-", the video only when a YouTube id (11 characters)' }, { status: 400, headers }); } const snap = body.snap === undefined || body.snap === null || body.snap === "" ? null : String(body.snap); if (snap !== null && snap !== "words") return Response.json({ error: "snap is words, or nothing" }, { status: 400, headers }); @@ -37,8 +41,10 @@ export async function POST(request: Request) { const running = runningJob(); if (running) return Response.json({ error: `a job is already running (${running.kind}) — make the clip when it is done`, running: jobView(running) }, { status: 409, headers }); const argv = [ - process.execPath, path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "clip", spec, + process.execPath, path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "clip", ...(snap ? ["--snap", snap] : []), ...(title ? ["--title", title] : []), ...(site ? ["--site", site] : []), "--progress", "ndjson", + // The spec after `--`: never read as a flag, whatever its ids (a YouTube id may start with `-`). + "--", spec, ]; const job = startJob(`quick clip ${spec}`, [{ cwd: UMTOOL_DIR, env: {}, label: `quick clip ${spec}${snap ? " (snapped to the words)" : ""}`, argv, ndjson: true, timeoutMs: 90 * 60_000 }]); return Response.json({ ok: true, job: jobView(job) }, { status: 202, headers }); diff --git a/umtool/app/api/report/quick-clip/strip/route.ts b/umtool/app/api/report/quick-clip/strip/route.ts @@ -0,0 +1,22 @@ +import { MomentError, quickClipStrip } from "@/lib/report/quickClipStrip.mjs"; + +export const dynamic = "force-dynamic"; + +// HOME'S QUICK CLIP BOX, before the render (umtool redesign L4; lib/report/quickClipStrip.mjs): a pasted moment +// -- an archive, YouTube or Rumble link with its time, or `<channel>/<video>@<start>-<end>` -- found in the +// corpus, its span, and the words around it to set the edges by. Reads only; the render is POST +// /api/report/quick-clip. +// +// GET ?moment=<text> -> { spec, channel, video, start, end, from, to, words | null, cues | null, wordsFrom, title, duration } +// | 400 { error } not a moment, or not in this corpus +const headers = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const moment = new URL(request.url).searchParams.get("moment") ?? ""; + try { + return Response.json(await quickClipStrip(moment), { headers }); + } catch (e) { + const status = e instanceof MomentError ? 400 : 500; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); + } +} diff --git a/umtool/app/api/report/takes/verdict/route.ts b/umtool/app/api/report/takes/verdict/route.ts @@ -1,5 +1,7 @@ import { projectRef } from "@/lib/projects"; import { isTakeId, listTakes, readVerdicts, setTakeVerdict } from "@/lib/report/takes.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; export const dynamic = "force-dynamic"; @@ -18,6 +20,11 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/takes/verdict"); + if (refused) return refused; + // Another site's page may not write here (lib/report/sameOrigin.mjs: Sec-Fetch-Site, Origin, a loopback Host). + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); const body = (await request.json().catch(() => null)) as { project?: string; take?: string; diff --git a/umtool/app/api/report/timeline/route.ts b/umtool/app/api/report/timeline/route.ts @@ -1,5 +1,6 @@ import { invalidateProjects } from "@/lib/projects"; import { withEditNotes } from "@/lib/report/guard"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; import { StaleToken, StructureRefused, @@ -134,6 +135,9 @@ const atOf = (v: unknown) => (v === undefined || v === null || v === "" ? null : export async function POST(request: Request) { const refused = refuseCaller(request, "/api/report/timeline"); if (refused) return refused; + // Another site's page may not write here (lib/report/sameOrigin.mjs: Sec-Fetch-Site, Origin, a loopback Host). + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); let body: Body; try { body = await request.json(); diff --git a/umtool/app/api/report/window/route.ts b/umtool/app/api/report/window/route.ts @@ -3,6 +3,7 @@ import { MarksOutside, StaleToken, updateClip } from "@/lib/report/manifest.mjs" import { updateTakeClip } from "@/lib/report/takeEdit.mjs"; import { resolveClip } from "@/lib/report/serve.mjs"; import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; export const dynamic = "force-dynamic"; @@ -19,6 +20,9 @@ export const dynamic = "force-dynamic"; export async function PUT(request: Request) { const refused = refuseCaller(request, "/api/report/window"); if (refused) return refused; + // Another site's page may not write here (lib/report/sameOrigin.mjs: Sec-Fetch-Site, Origin, a loopback Host). + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); let body: Record<string, unknown>; try { body = await request.json(); diff --git a/umtool/app/page.tsx b/umtool/app/page.tsx @@ -13,6 +13,10 @@ import { whatOf } from "@/lib/inbox/what.mjs"; import type { Decision } from "@/lib/decisions"; import type { LifecycleState } from "@/lib/lifecycle"; import { playHrefOfPiece } from "@/components/projects/playable"; +import QuickClip from "@/components/inbox/QuickClip"; +import RunningList from "@/components/shell/RunningList"; +import RecentCuts from "@/components/shell/RecentCuts"; +import { initialRunning } from "@/lib/activity"; export const dynamic = "force-dynamic"; @@ -25,7 +29,13 @@ export const dynamic = "force-dynamic"; // What the dashboard's panels were: a call became a card here (a tool the // pipeline needs that is missing, a disk nearly full); the rest -- recent // jobs, project states, sources, deliverables, tools and disk -- is on -// /settings/system. What is running is in the rail. +// /settings/system. +// +// WHAT NEEDS YOU (umtool redesign L4): beside the list, the Quick clip box (a +// moment link to a basic mp4 and its share line, components/inbox/QuickClip.tsx), +// what is Running and the Recent cuts -- the rail's, until the rail kept +// navigation only. A card whose rows agree on a one-press settle (Use embed ids, +// Run quote-check, Snap the cut to the words, Check links) presses it in place. // // `?from=<slug>/<id>` is the editor's "make a video" hand-off (VideoPanel, // VideoNavStrip): redirects.mjs sends it to /create?from=… (P5) before this @@ -44,13 +54,13 @@ async function machineCards(): Promise<InboxCard[]> { return (await machineCalls()).map((m) => ({ key: `machine:${m.kind}`, piece: null, - title: "umtool", + title: m.title ?? "umtool", kind: m.kind, what: whatOf(m.kind), why: m.why, count: m.count, severity: "blocking", - action: { label: m.kind === "machine-tool" ? "Check tools" : "Open system", href: systemHref() }, + action: m.action ?? { label: m.kind === "machine-tool" ? "Check tools" : "Open system", href: systemHref() }, lifecycle: "active" as const, })); } @@ -71,6 +81,8 @@ function toCard(group: string, c: GroupCard, lifecycle: LifecycleState, muted = lifecycle, ...(muted ? { muted } : {}), finish: c.kind === "looks-done", + project: c.project, + settle: c.settle ?? null, }; } @@ -172,17 +184,26 @@ export default async function Inbox({ </p> )} - <div className="mb-1 mt-1 flex items-end gap-3.5" data-inbox-count={head.calls}> - <span className="display text-[72px] font-[850] leading-[0.8]">{head.calls}</span> - <span className="pb-0.5 text-[13px] text-text-2"> - {head.calls === 1 ? "call waiting on you" : "calls waiting on you"} - <small className="block text-[12px] text-muted" data-inbox-note=""> - {headlineNote(head)} - </small> - </span> - </div> + <div className="grid gap-x-6 gap-y-5 min-[1280px]:grid-cols-[minmax(0,1fr)_300px]"> + <div className="min-w-0"> + <div className="mb-1 mt-1 flex items-end gap-3.5" data-inbox-count={head.calls}> + <span className="display text-[72px] font-[850] leading-[0.8]">{head.calls}</span> + <span className="pb-0.5 text-[13px] text-text-2"> + {head.calls === 1 ? "call waiting on you" : "calls waiting on you"} + <small className="block text-[12px] text-muted" data-inbox-note=""> + {headlineNote(head)} + </small> + </span> + </div> - <InboxList groups={all} /> + <InboxList groups={all} /> + </div> + <aside data-home-aside="" className="min-w-0 space-y-4 min-[1280px]:sticky min-[1280px]:top-4 min-[1280px]:self-start"> + <QuickClip /> + <RunningList initial={initialRunning()} /> + <RecentCuts /> + </aside> + </div> </main> <UndoBar /> </div> diff --git a/umtool/components/inbox/InboxList.tsx b/umtool/components/inbox/InboxList.tsx @@ -9,6 +9,8 @@ import { cn } from "@/lib/utils"; import { LifecycleButton, MuteButton, type LifecycleState } from "@/components/piece/Lifecycle"; import Menu from "@/components/piece/Menu"; import { PhoneOnly } from "@/components/shell/phone"; +import DecisionSettle from "@/components/projects/report/DecisionSettle"; +import type { Decision } from "@/lib/decisions"; // --------------------------------------------------------------------------- // The Inbox's cards as ONE lit list (canvas "Inbox"): a group head, then a @@ -45,6 +47,14 @@ export type InboxCard = { finish?: boolean; /** A report video's Play address (at the card's note), when the piece has one. */ play?: string | null; + /** The project the card's rows are about (its settle is pressed on it). */ + project?: string; + /** + * ONE-CLICK (umtool redesign L4): the settle its rows agree on (lib/inbox/groups.mjs mergeSettle), pressed + * in place -- Use embed ids, Run quote-check, Snap the cut to the words, Check links -- through the + * routes the project page's Checks list presses (DecisionSettle). The card's title links where it is settled. + */ + settle?: Decision["settle"] | null; }; export type InboxGroup = { @@ -117,6 +127,10 @@ export default function InboxList({ groups }: { groups: InboxGroup[] }) { function Card({ card: c }: { card: InboxCard }) { const parked = c.lifecycle !== "active"; + // A research case's card (`c:`): cases have no lifecycle or mutes yet, so no Park or Mute. + const parkable = !!c.piece && !c.piece.startsWith("c:"); + // Pressed in place only on an active, unmuted card: a hidden one's action is its way back. + const oneClick = !!(c.settle && c.project && !parked && !c.muted && !c.finish); return ( <LitLine id={c.key} @@ -132,7 +146,15 @@ function Card({ card: c }: { card: InboxCard }) { > <div className="min-w-0 basis-full sm:basis-auto"> <b className="line-clamp-2 font-medium text-inherit sm:block sm:truncate" data-card-title=""> - {c.title} <span className="font-normal text-muted-2">·</span> {c.what} + {oneClick ? ( + <Link href={c.action.href} prefetch={false} data-card-link="" className="text-inherit no-underline hover:underline" title={c.action.label}> + {c.title} <span className="font-normal text-muted-2">·</span> {c.what} + </Link> + ) : ( + <> + {c.title} <span className="font-normal text-muted-2">·</span> {c.what} + </> + )} </b> <small className="line-clamp-2 text-[12px] text-muted-2 sm:block sm:truncate">{c.why}</small> </div> @@ -146,6 +168,10 @@ function Card({ card: c }: { card: InboxCard }) { <LifecycleButton piece={c.piece} title={c.title} from={c.lifecycle} to="active" label="Reactivate" variant="outline" size="md" className="lit-go max-md:min-h-11" /> ) : c.finish && c.piece ? ( <LifecycleButton piece={c.piece} title={c.title} from={c.lifecycle} to="done" label="Mark done" variant="outline" size="md" className="lit-go max-md:min-h-11" /> + ) : oneClick && c.settle && c.project ? ( + <span data-card-settle={c.settle.kind}> + <DecisionSettle project={c.project} settle={c.settle} size="md" className="lit-go max-md:min-h-11" /> + </span> ) : ( <Link href={c.action.href} prefetch={false} data-action-link="" className={cn(buttonVariants({ variant: "outline", size: "md" }), "lit-go max-md:min-h-11")}> {c.action.label} @@ -158,14 +184,14 @@ function Card({ card: c }: { card: InboxCard }) { )} </span> <LitActions className="ml-auto gap-0.5 sm:ml-0 max-md:hidden"> - {!parked && !c.muted && c.piece && ( + {!parked && !c.muted && c.piece && parkable && ( <> <LifecycleButton piece={c.piece} title={c.title} from={c.lifecycle} to="parked" label="Park" /> <MuteButton piece={c.piece} kind={c.kind} title={c.title} muted={false} label={c.finish ? "Not yet" : "Mute"} /> </> )} </LitActions> - {!parked && !c.muted && c.piece && ( + {!parked && !c.muted && c.piece && parkable && ( <PhoneOnly> <Menu data-inbox-more={c.key} diff --git a/umtool/components/inbox/QuickClip.tsx b/umtool/components/inbox/QuickClip.tsx @@ -0,0 +1,238 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useRef, useState } from "react"; +import WordStrip from "@/components/projects/bench/WordStrip"; +import CopyShareLine from "@/components/projects/CopyShareLine"; +import { buttonVariants } from "@/components/ui/button"; +import { ingredientHref, takesHref } from "@/lib/hrefs"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// QUICK CLIP, ON HOME (umtool redesign L4; L1's `umtool clip`): paste a moment +// -- an archive, YouTube or Rumble link with its time, or +// `<channel>/<video>@<start>-<end>` -- and it is found in the corpus with the +// words around it (GET /api/report/quick-clip/strip); set the edges on the +// word strip (a click starts there, shift-click ends there) or nudge them; +// Render runs `umtool clip` as one job (POST /api/report/quick-clip: the window +// asked of the editor, rendered basic, the heavy slot); then the share line, +// copied (the take panel's Copy share line). The terminal twin: +// `umtool clip <channel>/<video>@<start>-<end> [--snap words]`. +// --------------------------------------------------------------------------- + +type Strip = { + spec: string; + channel: string; + video: string; + start: number; + end: number; + from: number; + to: number; + words: { w: string; start: number; end?: number }[] | null; + cues: { start: number; end: number; text: string }[] | null; + wordsFrom: string | null; + title: string | null; +}; +type Done = { project: string; output: string; share: { platform: string | null; archive: string | null; text: string } }; +type Run = { id: string; state: string; log: string[] }; + +const r2 = (x: number) => Math.round(x * 100) / 100; +const clock = (s: number) => { + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const ss = (s % 60).toFixed(2).padStart(5, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; +}; +const NUDGES = [-0.5, -0.1, 0.1, 0.5]; + +export default function QuickClip() { + const [text, setText] = useState(""); + const [strip, setStrip] = useState<Strip | null>(null); + const [cut, setCut] = useState<{ cutStart: number; cutEnd: number } | null>(null); + const [snap, setSnap] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const [run, setRun] = useState<Run | null>(null); + const [done, setDone] = useState<Done | null>(null); + const timer = useRef<number | null>(null); + + useEffect(() => () => { + if (timer.current) window.clearTimeout(timer.current); + }, []); + + const find = async () => { + setBusy(true); + setError(null); + setDone(null); + setRun(null); + try { + const r = await fetch(`/api/report/quick-clip/strip?moment=${encodeURIComponent(text.trim())}`, { cache: "no-store" }); + const j = (await r.json().catch(() => ({}))) as Strip & { error?: string }; + if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`); + setStrip(j); + setCut({ cutStart: j.start, cutEnd: j.end }); + } catch (e) { + setStrip(null); + setCut(null); + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + + const nudge = (edge: "cutStart" | "cutEnd", d: number) => + setCut((c) => { + if (!c) return c; + const next = { ...c, [edge]: r2(Math.max(0, c[edge] + d)) }; + return next.cutEnd - next.cutStart >= 0.2 ? next : c; + }); + + const onWord = (w: { start: number; end: number | null }, shift: boolean) => + setCut((c) => { + if (!c) return c; + if (shift) { + const end = r2(w.end ?? w.start + 0.4); + return end > c.cutStart + 0.2 ? { ...c, cutEnd: end } : c; + } + const start = r2(w.start); + return start < c.cutEnd - 0.2 ? { ...c, cutStart: start } : { cutStart: start, cutEnd: r2(start + Math.max(1, c.cutEnd - c.cutStart)) }; + }); + + const spec = strip && cut ? `${strip.channel}/${strip.video}@${cut.cutStart}-${cut.cutEnd}` : null; + + const poll = (id: string) => { + timer.current = window.setTimeout(async () => { + try { + const r = await fetch(`/api/report/quick-clip?job=${encodeURIComponent(id)}`, { cache: "no-store" }); + const j = (await r.json().catch(() => ({}))) as { job?: Run; done?: Done; error?: string }; + if (j.job) setRun(j.job); + if (j.done) { + setDone(j.done); + setBusy(false); + return; + } + if (j.error || (j.job && j.job.state !== "running" && j.job.state !== "queued")) { + setError(j.error ?? `the quick clip ended ${j.job?.state ?? "badly"}`); + setBusy(false); + return; + } + } catch { + // asked again on the next tick + } + poll(id); + }, 1500); + }; + + const render = async () => { + if (!spec) return; + setBusy(true); + setError(null); + setDone(null); + try { + const r = await fetch("/api/report/quick-clip", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ spec, ...(snap ? { snap: "words" } : {}) }), + }); + const j = (await r.json().catch(() => ({}))) as { job?: Run; error?: string }; + if (!r.ok || !j.job) throw new Error(j.error ?? `HTTP ${r.status}`); + setRun(j.job); + poll(j.job.id); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + setBusy(false); + } + }; + + const state = done ? "done" : run ? run.state : strip ? "ready" : "idle"; + return ( + <section data-quick-clip={state} aria-label="Quick clip" className="rounded-[4px] border border-seam bg-panel p-3"> + <h2 className="micro mb-2">Quick clip</h2> + <form + className="flex gap-1.5" + onSubmit={(e) => { + e.preventDefault(); + if (text.trim()) void find(); + }} + > + <input + data-quick-clip-input="" + value={text} + onChange={(e) => setText(e.target.value)} + placeholder="a moment link, or channel/video@start-end" + aria-label="a moment link, or channel/video@start-end" + className="min-w-0 flex-1 rounded-[3px] border border-seam bg-bg px-2 py-1 font-mono text-[12px] text-text" + /> + <button type="submit" data-quick-clip-find="" disabled={busy || !text.trim()} className={buttonVariants({ variant: "outline", size: "sm" })}> + Find + </button> + </form> + + {strip && cut && ( + <div className="mt-2.5 space-y-2" data-quick-clip-strip={strip.spec}> + <p className="m-0 truncate text-[12px] text-text-2" title={strip.title ?? undefined}> + {/* The recording's life cycle (lane L5's rail): where it is downloaded, transcribed, cut and cited. */} + <Link href={ingredientHref(strip.channel, strip.video)} prefetch={false} data-quick-clip-ingredient="" className="font-mono text-muted no-underline hover:underline" title="its life cycle"> + {strip.channel}/{strip.video} + </Link> + {strip.title ? ` · ${strip.title}` : ""} + </p> + <WordStrip hood={{ words: strip.words, cues: strip.cues }} cut={cut} playhead={null} onSeek={() => {}} onWord={onWord} className="max-h-[7.5em] text-[12.5px]" /> + <p className="m-0 text-[11px] text-muted-2">a word: start there · shift-click: end there ({strip.wordsFrom === "cues" ? "the cues" : (strip.wordsFrom ?? "no words")})</p> + {(["cutStart", "cutEnd"] as const).map((edge) => ( + <div key={edge} className="flex items-center gap-1 text-[12px]" data-quick-clip-edge={edge === "cutStart" ? "start" : "end"}> + <span className="w-9 text-muted">{edge === "cutStart" ? "start" : "end"}</span> + {NUDGES.map((d) => ( + <button + key={d} + type="button" + data-quick-clip-nudge={`${edge === "cutStart" ? "start" : "end"}:${d}`} + onClick={() => nudge(edge, d)} + disabled={busy} + className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "px-1.5 font-mono")} + > + {d > 0 ? `+${d}` : d} + </button> + ))} + <span className="ml-auto font-mono text-text" data-quick-clip-at={cut[edge]}> + {clock(cut[edge])} + </span> + </div> + ))} + <div className="flex flex-wrap items-center gap-2"> + <button type="button" data-quick-clip-render="" disabled={busy} onClick={() => void render()} className={buttonVariants({ variant: "go", size: "sm" })}> + {busy && run ? "Rendering…" : `Render ${(cut.cutEnd - cut.cutStart).toFixed(1)} s`} + </button> + <label className="flex items-center gap-1 text-[11.5px] text-text-2" title="snap the edges to the words heard there (the editor transcribes the window)"> + <input type="checkbox" data-quick-clip-snap="" checked={snap} onChange={(e) => setSnap(e.target.checked)} disabled={busy} /> + snap to the words + </label> + </div> + <p className="m-0 break-all font-mono text-[11px] text-muted-2" data-quick-clip-spec={spec ?? ""}> + umtool clip {spec} + {snap ? " --snap words" : ""} + </p> + </div> + )} + + {run && !done && ( + <p className="m-0 mt-2 truncate font-mono text-[11px] text-text-2" data-quick-clip-progress="" title={run.log.join("\n")}> + {run.log[run.log.length - 1] ?? run.state} + </p> + )} + {done && ( + <div className="mt-2 space-y-1" data-quick-clip-done={done.project}> + <CopyShareLine project={done.project} take="clip" testid="quick-clip" /> + <Link href={takesHref(done.project)} prefetch={false} className="ink-link text-[12px]"> + the render ({done.project}) + </Link> + </div> + )} + {error && ( + <p role="alert" data-quick-clip-error="" className="m-0 mt-2 text-[12px] text-reject-text"> + {error} + </p> + )} + </section> + ); +} diff --git a/umtool/components/projects/AddClip.tsx b/umtool/components/projects/AddClip.tsx @@ -6,6 +6,7 @@ import { buttonVariants } from "@/components/ui/button"; import { newClipEntry, quoteFromCues } from "@/lib/report/clipEditorModel.mjs"; import { cn } from "@/lib/utils"; import { announceManifestChanged, refusalOf, timelineOp, type TimelineResult } from "./timelineApi"; +import { parseMomentInput, parseTime as parseTimeOf } from "@/lib/report/momentLink.mjs"; // --------------------------------------------------------------------------- // ADD A CLIP, AS ONE FLOW (lane/ui-simplify, 5 Nov; the operator: "adding new @@ -41,41 +42,17 @@ const clock = (s: number) => { return h ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`; }; -/** `1:02:32`, `62m32s`, `3752`, `1h2m32s` → seconds; null when it is not a time. */ -export function parseTime(v: string | null | undefined): number | null { - const s = String(v ?? "").trim(); - if (!s) return null; - if (/^\d+(\.\d+)?s?$/.test(s)) return Number(s.replace(/s$/, "")); - const hms = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?$/.exec(s); - if (hms && (hms[1] || hms[2] || hms[3])) return Number(hms[1] ?? 0) * 3600 + Number(hms[2] ?? 0) * 60 + Number(hms[3] ?? 0); - const parts = s.split(":").map(Number); - if (parts.length >= 2 && parts.length <= 3 && parts.every((n) => Number.isFinite(n))) return parts.reduce((a, n) => a * 60 + n, 0); - return null; -} +/** `1:02:32`, `62m32s`, `3752`, `1h2m32s` → seconds; null when it is not a time (lib/report/momentLink.mjs). */ +export const parseTime = parseTimeOf as (v: string | null | undefined) => number | null; -/** A pasted link or a short form → `{ video, t, channel? }`: a YouTube link (`v=`, youtu.be, /live/, /shorts/) with t= or start=, `<channel>/<video>@<time>`, `<video>@<time>`. */ +/** + * A pasted link or a short form → `{ video, t, channel? }` (lib/report/momentLink.mjs, home's Quick clip box's + * parser too): a YouTube link (`v=`, youtu.be, /live/, /shorts/) with t= or start=, an archive's moment link, a + * Rumble link, `<channel>/<video>@<time>` or `@<start>-<end>`, `<video>@<time>`. + */ export function parseMomentLink(raw: string): { video: string; t: number; channel: string | null } | null { - const s = raw.trim(); - const short = /^(?:([A-Za-z0-9][A-Za-z0-9._-]*)\/)?([A-Za-z0-9_-]{2,})@([0-9:hms.]+)$/.exec(s); - if (short) { - const t = parseTime(short[3]); - return t === null ? null : { channel: short[1] ?? null, video: short[2], t }; - } - let u: URL; - try { - u = new URL(/^https?:\/\//.test(s) ? s : `https://${s}`); - } catch { - return null; - } - let video: string | null = u.searchParams.get("v"); - if (!video && /youtu\.be$/.test(u.hostname)) video = u.pathname.slice(1).split("/")[0] || null; - if (!video) { - const m = /\/(?:live|shorts|embed|v)\/([A-Za-z0-9_-]{6,})/.exec(u.pathname); - video = m ? m[1] : null; - } - if (!video) return null; - const t = parseTime(u.searchParams.get("t") ?? u.searchParams.get("start") ?? (u.hash.match(/t=([0-9hms:.]+)/)?.[1] ?? "0")) ?? 0; - return { video, t, channel: null }; + const m = parseMomentInput(raw); + return m ? { video: m.video, t: m.start, channel: m.channel } : null; } /** Where a clip of `date` goes in a cut in date order: after the last dated entry on or before it; null when the cut is not in date order. */ diff --git a/umtool/components/projects/OnscreenSection.tsx b/umtool/components/projects/OnscreenSection.tsx @@ -51,7 +51,7 @@ import { deckChrome } from "@/lib/report/chain-draft.mjs"; // ---- the composition's contract, as this page reads it -------------------- export type Rect = { x: number; y: number; width: number; height: number }; -export type DeckGeometry = { W: number; H: number; footage: Rect; deck: Rect }; +export type DeckGeometry = { W: number; H: number; footage: Rect; deck: Rect; post?: Rect }; export type DeckSegment = { id: string; type: string; diff --git a/umtool/components/projects/bench/WordStrip.tsx b/umtool/components/projects/bench/WordStrip.tsx @@ -0,0 +1,62 @@ +"use client"; + +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// THE WORD STRIP: a span's words as text -- the cut's lit, the one playing +// marked, a click seeks there (`onSeek`); the clip editor's, and home's Quick +// clip box's (umtool redesign L4). Timed words when the corpus has them (a +// words sidecar, a whisper transcript, the captions' word starts), else the +// cues. `onWord` (the Quick clip box): a click on a word sets an edge instead. +// --------------------------------------------------------------------------- + +export type StripSource = { + words?: { w: string; start: number; end?: number }[] | null; + cues?: { start: number; end: number; text: string }[] | null; +} | null; + +export default function WordStrip({ + hood, + cut, + playhead, + onSeek, + onWord, + className, +}: { + hood: StripSource; + cut: { cutStart: number; cutEnd: number }; + playhead: number | null; + onSeek: (t: number) => void; + /** A click on a word, with shift held or not (the Quick clip box: start at it, shift: end after it). */ + onWord?: (w: { start: number; end: number | null }, shift: boolean) => void; + className?: string; +}) { + if (!hood) return <p className="m-0 text-[12px] text-muted">reading the words…</p>; + const list = hood.words?.length ? hood.words.map((w) => ({ text: w.w, start: w.start, end: w.end ?? null })) : (hood.cues ?? []).map((c) => ({ text: c.text, start: c.start, end: c.end as number | null })); + if (!list.length) return <p className="m-0 text-[12px] text-muted">No words or cues for this span.</p>; + return ( + <p data-editor-words={hood.words?.length ? "words" : "cues"} className={cn("m-0 max-h-[9.5em] overflow-auto text-[13px] leading-relaxed text-muted", className)}> + {list.map((w, i) => { + const end = w.end ?? list[i + 1]?.start ?? w.start; + const mid = (w.start + end) / 2; + const inCut = mid >= cut.cutStart && mid <= cut.cutEnd; + const now = playhead !== null && playhead >= w.start && playhead < end; + return ( + <span key={i}> + <button + type="button" + data-word={i} + data-word-t={w.start} + data-in-cut={inCut ? "" : undefined} + onMouseDown={(e) => e.preventDefault()} + onClick={(e) => (onWord ? onWord({ start: w.start, end: w.end }, e.shiftKey) : onSeek(w.start))} + className={cn("rounded-[2px] px-[1px] hover:bg-panel-2", inCut && "text-text", now && "bg-[color-mix(in_srgb,var(--signal)_30%,transparent)]")} + > + {w.text} + </button>{" "} + </span> + ); + })} + </p> + ); +} diff --git a/umtool/components/projects/report/DecisionSettle.tsx b/umtool/components/projects/report/DecisionSettle.tsx @@ -3,22 +3,32 @@ import { useState } from "react"; import { useRouter } from "next/navigation"; import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; import type { Decision } from "@/lib/decisions"; // The one-press settle beside a check row (lib/projects/report.mjs `settle`): // a clip patch through the window writer -- "It's deliberate: b repeats a" // (repeatOf), "Move to 12:34" (the clock and the QR back on the clip) -- or a -// link check against the sites the QRs open. The row's `fix` is the same -// thing from a terminal; nothing here needs a model. +// link check against the sites the QRs open (with `fix`: the dead links whose +// fix is known rewritten first -- a Twitch id as v<id>, a Rumble folder id as +// its embed id, "Use embed ids"), or a quote check on the durable queue (POST +// /api/cli, the registry's `quote-check` row: it transcribes through the +// editor, so it queues). The row's `fix` is the same thing from a terminal; +// nothing here needs a model. The Inbox's cards press the same buttons (L4). export default function DecisionSettle({ project, settle, token = null, + size = "sm", + className, }: { project: string; settle: NonNullable<Decision["settle"]>; token?: string | null; + /** The Inbox's card draws it as its primary action: `md`, lit. */ + size?: "sm" | "md"; + className?: string; }) { const router = useRouter(); const [busy, setBusy] = useState(false); @@ -42,6 +52,12 @@ export default function DecisionSettle({ headers: { "content-type": "application/json" }, body: JSON.stringify({ project, file: settle.file }), }) + : settle.kind === "quote-check" + ? await fetch("/api/cli", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ verb: "quote-check", values: { project, "--clips": settle.clips.join(",") } }), + }) : settle.kind === "publish-site" ? await fetch("/api/report/publish-site", { method: "POST", @@ -60,6 +76,7 @@ export default function DecisionSettle({ notes?: string[]; left?: { label: string | null; after: string }[]; jobId?: string | null; + queued?: { qid: string } | null; }; if (!r.ok) { setErr(j.error ?? `HTTP ${r.status}`); @@ -75,6 +92,10 @@ export default function DecisionSettle({ `${moved} marker${moved === 1 ? "" : "s"} moved` + (left.length ? ` · left by hand: ${left.map((l) => `${l.label ? `"${l.label}"` : "a marker"} after ${l.after}`).join(", ")}` : ""), ); + } else if (settle.kind === "quote-check") { + // The queue runs it (the editor transcribes each clip); the row goes once the check is current. + setSaid(`queued${j.queued?.qid ? ` as ${j.queued.qid}` : ""} — ${settle.clips.length} clip${settle.clips.length === 1 ? "" : "s"}; see /jobs`); + return; } else if (settle.kind === "publish-site") { // The editor's publish queue runs it; nothing here changes until the deploy lands and a check reads it. setSaid(`queued on the editor's publish queue${j.jobId ? ` (job ${j.jobId})` : ""} — Check links once it is deployed`); @@ -89,13 +110,13 @@ export default function DecisionSettle({ }; return ( - <span className="inline-flex items-center gap-2" data-settle={settle.kind}> + <span className="inline-flex flex-wrap items-center gap-x-2 gap-y-1" data-settle={settle.kind}> <button type="button" - data-settle-button={settle.kind === "patch" ? settle.clip : settle.kind === "patch-markers" ? settle.file : settle.kind === "publish-site" ? `publish-${settle.siteId}` : "links"} + data-settle-button={settle.kind === "patch" ? settle.clip : settle.kind === "patch-markers" ? settle.file : settle.kind === "publish-site" ? `publish-${settle.siteId}` : settle.kind === "quote-check" ? "quote-check" : "links"} disabled={busy} onClick={() => void run()} - className={buttonVariants({ variant: settle.kind === "patch" ? "go" : "outline", size: "sm" })} + className={cn(buttonVariants({ variant: settle.kind === "patch" ? "go" : "outline", size }), className)} title={ settle.kind === "patch" ? `writes ${Object.keys(settle.patch).join(", ")} on ${settle.clip} through the window writer` @@ -103,10 +124,14 @@ export default function DecisionSettle({ ? `each marker of ${settle.file} after a clip that is gone takes the cut's marker of the same label` : settle.kind === "publish-site" ? `asks the editor to build and deploy ${settle.siteId} (its publish queue, through the heavy slot)` - : "resolves every clip QR against the site it links (corpus.json → the shard's record), one request at a time per host" + : settle.kind === "quote-check" + ? `umtool quote-check --clips ${settle.clips.join(",")} on the durable queue: the editor transcribes what each clip plays and its quote is found in it` + : settle.fix + ? "rewrites each dead link whose fix the last check knows (a Rumble folder id → its embed id, a Twitch id → v<id>) through the window writer, then checks again" + : "resolves every clip QR against the site it links (corpus.json → the shard's record), one request at a time per host" } > - {busy ? (settle.kind === "check-links" ? "Checking…" : settle.kind === "publish-site" ? "Asking the editor…" : "Saving…") : settle.label} + {busy ? (settle.kind === "check-links" ? "Checking…" : settle.kind === "publish-site" ? "Asking the editor…" : settle.kind === "quote-check" ? "Queueing…" : "Saving…") : settle.label} </button> {said && !err && ( <span data-settle-said="" className="text-[11.5px] text-text-2"> diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx @@ -21,6 +21,7 @@ import LiveDeckPreview from "./LiveDeckPreview"; // 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"; +import WordStrip from "../bench/WordStrip"; // --------------------------------------------------------------------------- // THE CLIP EDITOR (release 35 C2): a person hops in on an assistant's clips. @@ -1263,36 +1264,8 @@ function Strip({ ); } -/** The words of the neighbourhood as text: the cut's lit, the one playing marked; a click seeks there. */ -function Words({ hood, cut, playhead, onSeek }: { hood: Neighbourhood | null; cut: Cut; playhead: number | null; onSeek: (t: number) => void }) { - if (!hood) return <p className="m-0 text-[12px] text-muted">reading the words…</p>; - const list = hood.words?.length ? hood.words.map((w) => ({ text: w.w, start: w.start, end: w.end })) : (hood.cues ?? []).map((c) => ({ text: c.text, start: c.start, end: c.end })); - if (!list.length) return <p className="m-0 text-[12px] text-muted">No words or cues for this span.</p>; - return ( - <p data-editor-words={hood.words?.length ? "words" : "cues"} className="m-0 max-h-[9.5em] overflow-auto text-[13px] leading-relaxed text-muted"> - {list.map((w, i) => { - const mid = (w.start + w.end) / 2; - const inCut = mid >= cut.cutStart && mid <= cut.cutEnd; - const now = playhead !== null && playhead >= w.start && playhead < w.end; - return ( - <span key={i}> - <button - type="button" - data-word={i} - data-word-t={w.start} - data-in-cut={inCut ? "" : undefined} - onMouseDown={(e) => e.preventDefault()} - onClick={() => onSeek(w.start)} - className={cn("rounded-[2px] px-[1px] hover:bg-panel-2", inCut && "text-text", now && "bg-[color-mix(in_srgb,var(--signal)_30%,transparent)]")} - > - {w.text} - </button>{" "} - </span> - ); - })} - </p> - ); -} +/** The words of the neighbourhood as text: the cut's lit, the one playing marked; a click seeks there (bench/WordStrip.tsx). */ +const Words = WordStrip; function EdgeControl({ edge, value, onNudge, onSet, onPlayhead }: { edge: "in" | "out"; value: number; onNudge: (d: number) => void; onSet: (v: number) => void; onPlayhead: (() => void) | null }) { const [text, setText] = useState(String(value)); diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -31,6 +31,7 @@ import type { PostPlan } from "./PostItemPlayer"; import type { VideoEntryPlay } from "@/lib/report/playVideo.mjs"; import type { ComboInfo } from "./ComboBadge"; import CopyShareLine from "../CopyShareLine"; +import VersionVerdict from "./VersionVerdict"; import { StillButton } from "../inspector/StillInspector"; // --------------------------------------------------------------------------- @@ -179,6 +180,8 @@ const L_RATES = [1, 1.5, 2, 2.5, 3]; const SKIP_S = 5; /** The player is as wide as leaves the strip and Now on screen under it (never under 480 px). */ const PLAYER_MAX_W = "max(480px, min(1100px, calc((100dvh - 430px) * 16 / 9)))"; +/** A 9:16 cut's player (the stacked vertical deck, vertical-deck.mjs): as tall as the 16:9 one would be wide allows, centred. */ +const PLAYER_MAX_W_TALL = "max(240px, min(460px, calc((100dvh - 250px) * 9 / 16)))"; const PAUSE_KEY = "umtool.play.pauseWhileWriting"; /** "on": play the clips the walk rejected too (for re-review); absent or "off": skip them. */ // The key keeps its old name: a browser that chose "show" before rejections had reasons still has. @@ -734,6 +737,8 @@ export default function PlayCut({ // ---- what is on screen (the core's) ---------------------------------------------- const { t, item, entry, tally, stamp, finaleNow, broken, postNow, videoNow } = core; + // A 9:16 cut (the stacked vertical deck): its frame is tall, and the player is sized for it. + const tall = !!core.g && core.g.H > core.g.W; // The reel strip's counter: the composed schedule's stamps when there is one, else the estimate's. const counters = useMemo<StripCounter[]>(() => { @@ -854,6 +859,8 @@ export default function PlayCut({ Watch render </a> )} + {/* Play and judge (L4): a rendered version's verdict, where it is watched. */} + {view.take.made && <VersionVerdict project={project} take={view.take.id} />} </p> ) : ( <p className="m-0 border-b border-seam px-4 py-1 text-[11.5px] text-text-2 max-md:-mx-4 max-md:-mt-3" data-play-take="" data-play-draft-note=""> @@ -874,10 +881,11 @@ export default function PlayCut({ data-play-player-pin="" data-compact={compact ? "" : undefined} className="relative w-full max-md:sticky max-md:top-0 max-md:z-30 max-md:-mx-4 max-md:w-auto max-md:bg-ground" + data-play-tall={tall ? "" : undefined} style={ compact - ? { maxWidth: PLAYER_MAX_W, width: (STRIP_H * 16) / 9, marginBottom: Math.max(0, fullH - STRIP_H) } - : { maxWidth: PLAYER_MAX_W } + ? { maxWidth: PLAYER_MAX_W, width: (STRIP_H * (tall ? 9 / 16 : 16 / 9)), marginBottom: Math.max(0, fullH - STRIP_H) } + : tall ? { maxWidth: PLAYER_MAX_W_TALL, marginInline: "auto" } : { maxWidth: PLAYER_MAX_W } } > <PlayStage core={core} basic={!!view.basic} /> diff --git a/umtool/components/projects/review/VersionVerdict.tsx b/umtool/components/projects/review/VersionVerdict.tsx @@ -0,0 +1,82 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// PLAY AND JUDGE (umtool redesign L4, "What needs you"): a rendered version +// played in Play (`?take=`) is judged where it is watched -- Like · Maybe · No, +// the Takes page's three verdicts, written through the same route (POST +// /api/report/takes/verdict, takes/verdicts.json); pressing the lit one clears +// it. The Inbox's "versions to judge" card opens here, and judging drops it. +// Its terminal twin: `umtool takes verdict <p> <take> like|maybe|no|clear`. +// --------------------------------------------------------------------------- + +const VERDICTS = [ + { id: "like", label: "Like" }, + { id: "maybe", label: "Maybe" }, + { id: "no", label: "No" }, +] as const; +type Verdict = (typeof VERDICTS)[number]["id"]; + +export default function VersionVerdict({ project, take }: { project: string; take: string }) { + const [verdict, setVerdict] = useState<Verdict | null | undefined>(undefined); + const [busy, setBusy] = useState(false); + const [err, setErr] = useState<string | null>(null); + + useEffect(() => { + let live = true; + void fetch(`/api/report/takes/verdict?project=${encodeURIComponent(project)}`, { cache: "no-store" }) + .then((r) => r.json()) + .then((j: { verdicts?: Record<string, { verdict?: Verdict | null }> }) => live && setVerdict(j.verdicts?.[take]?.verdict ?? null)) + .catch(() => live && setVerdict(null)); + return () => { + live = false; + }; + }, [project, take]); + + const judge = async (v: Verdict) => { + const next = verdict === v ? null : v; + setBusy(true); + setErr(null); + try { + const r = await fetch("/api/report/takes/verdict", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, take, verdict: next }), + }); + const j = (await r.json().catch(() => ({}))) as { error?: string }; + if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`); + setVerdict(next); + } catch (e) { + setErr(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + + return ( + <span className="inline-flex flex-wrap items-center gap-1" data-play-verdict={verdict ?? ""} role="group" aria-label={`judge ${take}`}> + {VERDICTS.map((v) => ( + <button + key={v.id} + type="button" + data-play-verdict-button={v.id} + aria-pressed={verdict === v.id} + disabled={busy || verdict === undefined} + onClick={() => void judge(v.id)} + title={verdict === v.id ? `clear the verdict on ${take}` : `${v.label}: ${take}'s verdict (takes/verdicts.json)`} + className={cn(buttonVariants({ variant: verdict === v.id ? "go" : "outline", size: "sm" }))} + > + {v.label} + </button> + ))} + {err && ( + <span data-play-verdict-error="" className="text-[11.5px] text-doubt-text"> + {err} + </span> + )} + </span> + ); +} diff --git a/umtool/components/projects/review/playCore.tsx b/umtool/components/projects/review/playCore.tsx @@ -468,12 +468,17 @@ export function PlayStage({ core, basic = false, plainClassName }: { core: PlayC <div className="absolute inset-0" style={{ background: bg }} /> {footageCanvas(rect ? { left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) } : undefined, box.width, box.height)} {videoUnder} - {postNow && rect && ( - <div className="absolute" style={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H), background: bg }}> - {postPlayer({ width: box.width, height: box.height })} - {comboBadge({ width: box.width, height: box.height })} - </div> - )} + {postNow && (g.post ?? rect) && (() => { + // The stacked vertical deck lays a post item as its hero card (deck.mjs deckGeometry `post`). + const pr = g.post ?? rect!; + const pb = g.post ?? box; + return ( + <div className="absolute" style={{ left: pct(pr.x, g.W), top: pct(pr.y, g.H), width: pct(pr.width, g.W), height: pct(pr.height, g.H), background: bg }}> + {postPlayer({ width: pb.width, height: pb.height })} + {comboBadge({ width: pb.width, height: pb.height })} + </div> + ); + })()} {teaserCard} {introCard} {placeholderCard} diff --git a/umtool/components/projects/workspace/Workspace.tsx b/umtool/components/projects/workspace/Workspace.tsx @@ -322,6 +322,8 @@ export default function Workspace({ view: served, initialBlock = null, introWrit }, [help, doUndo, doRedo, moveSelected, setPlaying, now, step, editHere]); // ---- the viewer's size: 16:9 in what the column leaves it -------------------------------- + // The frame's own shape: a 9:16 cut (the stacked vertical deck) is tall. + const aspect = core.g ? core.g.W / core.g.H : 16 / 9; const stageBox = useRef<HTMLDivElement | null>(null); const [stageW, setStageW] = useState<number | null>(null); useEffect(() => { @@ -329,13 +331,13 @@ export default function Workspace({ view: served, initialBlock = null, introWrit if (!el) return; const fit = () => { const r = el.getBoundingClientRect(); - setStageW(Math.max(160, Math.floor(Math.min(r.width, (r.height * 16) / 9)))); + setStageW(Math.max(120, Math.floor(Math.min(r.width, r.height * aspect)))); }; fit(); const ro = new ResizeObserver(fit); ro.observe(el); return () => ro.disconnect(); - }, []); + }, [aspect]); // ---- the sheet (under ~900 px): the inspector folds to its head ------------------------- const [sheetOpen, setSheetOpen] = useState(true); diff --git a/umtool/components/shell/AppRail.tsx b/umtool/components/shell/AppRail.tsx @@ -1,34 +1,27 @@ import Link from "next/link"; import { cookies } from "next/headers"; import AppNav, { placeOf } from "@/components/AppNav"; -import { initialRunning } from "@/lib/activity"; import { homeHref } from "@/lib/hrefs"; import { THEME_COOKIE, parseTheme } from "@/lib/theme"; import CreateMenu from "./CreateMenu"; import JumpButton from "./JumpButton"; import PhoneDock from "./PhoneDock"; -import RunningList from "./RunningList"; -import RecentCuts from "./RecentCuts"; import ThemeControl from "./ThemeControl"; import { Mark, Wordmark } from "./Wordmark"; // --------------------------------------------------------------------------- // The rail (canvas `.rail`): every page's left column. Top to bottom: // the mark and the wordmark (home), the places (Inbox · Research · Work · -// Tools · Settings, components/AppNav.tsx), + Create, Jump to… ⌘K, Pinned, -// and at the foot what is Running and the theme. +// Tools · Settings, components/AppNav.tsx), + Create, Jump to… ⌘K, and at +// the foot the theme. NAVIGATION ONLY (the redesign's L4): what is Running +// and the Recent cuts are on home, beside the Inbox; Pinned, which never had +// a store, is gone. // -// SERVER ONLY: it reads the theme cookie and the in-process job registries. +// SERVER ONLY: it reads the theme cookie. // A client page (the song deck) gets it from its server page instead. // // Jump (⌘K) opens the palette (JumpPalette.tsx, in the root layout). // -// What is not built yet says so plainly rather than pretending: -// - Pinned has no store until the piece page (P4a); it is empty. -// - Running (RunningList.tsx) is umtool's own jobs and the editor's live ones -// with spend (lib/activity.ts readRunning, P2b). The server draws the last -// view it has, never waiting on the editor; the browser asks after load. -// // On a phone (below md) the rail is not drawn and the PHONE DOCK, rendered // here beside it, carries the places at the foot of the screen (PhoneDock.tsx). // --------------------------------------------------------------------------- @@ -49,16 +42,7 @@ export default async function AppRail({ active }: { active: string }) { <JumpButton /> - <section data-rail-section="pins" aria-label="Pinned"> - <h2 className="micro px-5 pb-1.5 pt-4">Pinned</h2> - <p className="px-5 text-[12px] text-muted-2">Nothing pinned</p> - </section> - - <RecentCuts /> - - <RunningList initial={initialRunning()} /> - - <div data-rail-section="theme" className="px-4 pb-4 pt-3"> + <div data-rail-section="theme" className="mt-auto px-4 pb-4 pt-3"> <ThemeControl initial={theme} /> </div> </div> diff --git a/umtool/components/shell/RecentCuts.tsx b/umtool/components/shell/RecentCuts.tsx @@ -7,9 +7,10 @@ import Link from "next/link"; import { projectHref } from "@/lib/hrefs"; // --------------------------------------------------------------------------- -// THE RAIL'S RECENT CUTS (lane/ui-simplify, 5 Nov): the last report videos this +// RECENT CUTS, ON HOME (lane/ui-simplify, 5 Nov; the rail's until the +// redesign's L4 left the rail navigation only): the last report videos this // viewer opened, each with ▶ Play (the newest take) -- so Play is one click from -// any page. A per-viewer convenience, so localStorage (wrapped: a private +// home. A per-viewer convenience, so localStorage (wrapped: a private // window or blocked storage just shows nothing); <RememberCut> on a project's // page and on Play writes it. // --------------------------------------------------------------------------- @@ -58,11 +59,11 @@ export default function RecentCuts() { }, []); if (!list.length) return null; return ( - <section data-rail-section="recent-cuts" aria-label="Recent cuts"> - <h2 className="micro px-5 pb-1.5 pt-4">Recent cuts</h2> - <ul className="m-0 list-none space-y-0.5 px-4 p-0"> + <section data-home-section="recent-cuts" aria-label="Recent cuts"> + <h2 className="micro pb-1.5">Recent cuts</h2> + <ul className="m-0 list-none space-y-0.5 p-0"> {list.map((r) => ( - <li key={r.project} data-recent-cut={r.project} className="flex items-center gap-1 px-1 text-[12px]"> + <li key={r.project} data-recent-cut={r.project} className="flex items-center gap-1 text-[12px]"> <Link href={projectHref(r.project)} prefetch={false} className="min-w-0 flex-1 truncate text-text-2 no-underline hover:text-text" title={`${r.title} (${r.project})`}> {r.project.split("/").pop()} </Link> diff --git a/umtool/components/shell/RunningList.tsx b/umtool/components/shell/RunningList.tsx @@ -7,7 +7,8 @@ import { JobProgressBar, JobProgressText } from "@/components/ui/job-progress"; import { jobsHref } from "@/lib/hrefs"; // --------------------------------------------------------------------------- -// The rail's foot (canvas `.running`): what is running, umtool's own and the +// What is running, on home (canvas `.running`; it was the rail's foot until +// the redesign's L4 left the rail navigation only): umtool's own and the // editor's, with spend. The label row is "Running N" and the day's API spend // in Meter; then a row per job (lib/running.mjs chooses them) -- kind, target, // progress, queued or running, and a generation job's spend -- each linking to @@ -114,12 +115,12 @@ export default function RunningList({ initial }: { initial: RunningView }) { const state = editor.reason ?? (editor.pending ? "pending" : "ok"); return ( <section - data-rail-section="running" + data-home-section="running" aria-label="Running" data-editor-state={state} - className="mt-auto border-t border-seam pb-2 pt-3" + className="rounded-[4px] border border-seam pb-2 pt-3" > - <h2 className="micro flex justify-between px-5 pb-2"> + <h2 className="micro flex justify-between px-3 pb-2"> <span> <Link href={jobsHref()} prefetch={false} className="text-inherit no-underline hover:text-text" data-rail-jobs="" title="Jobs: the queue, every take render's record, the app's jobs"> Running @@ -139,23 +140,23 @@ export default function RunningList({ initial }: { initial: RunningView }) { )} </h2> {rows.length > 0 && ( - <ul className="grid gap-1.5 px-5" data-running-list=""> + <ul className="grid gap-1.5 px-3" data-running-list=""> {rows.map((i) => ( <Row key={`${i.source}:${i.id}`} item={i} /> ))} </ul> )} {editor.text ? ( - <p className="mt-1.5 px-5 text-[12px] text-text-2" data-running-editor={editor.reason ?? ""} title={editor.detail ?? undefined}> + <p className="mt-1.5 px-3 text-[12px] text-text-2" data-running-editor={editor.reason ?? ""} title={editor.detail ?? undefined}> {editor.text} </p> ) : rows.length === 0 ? ( - <p className="px-5 text-[12px] text-muted-2" data-running-empty={editor.pending ? "pending" : ""}> + <p className="px-3 text-[12px] text-muted-2" data-running-empty={editor.pending ? "pending" : ""}> {editor.pending ? "Asking the editor…" : "Nothing running"} </p> ) : null} {more.text && ( - <a href={editor.jobsHref} className="mt-1.5 block px-5 text-[11.5px] text-muted-2 no-underline hover:text-text" data-running-more=""> + <a href={editor.jobsHref} className="mt-1.5 block px-3 text-[11.5px] text-muted-2 no-underline hover:text-text" data-running-more=""> {rows.length ? more.text : more.text.replace(/^\+ /, "")} </a> )} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -78,10 +78,11 @@ Inbox cannot disagree about what is wrong with one. | `take status <project> [--id <take>] [--json] [--log] [--tail N]` | a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare "exited 1") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A "running" whose process is gone reads **failed** ("the render process is gone"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)); and its fast-feedback renders beside it, `preview` and `changes` (each one's state, mp4, seconds, log; a changes reel's piece count, its base and its list), a queued `--preview`/`--changes` step said as such -- never as the take's own render | | `queue add [--after <qid>\|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>` | a **step** of the durable queue: the argv of a umtool command, one word per argument (no shell), stored under `<reports root>/.umtool-queue/` and run by the **umtool app** (its systemd unit), one step at a time, in order — so it survives the session that queued it, an app restart and a ship. Prints the qid (`q<N>`) alone on stdout. `--after` waits for that step to be **done**; when it fails or is cancelled this one is **blocked** (and so is whatever waits on it). `--timeout`: the step's limit (default 720 minutes). A step does not start while the app's own job runner is busy (a Takes-page job), and a heavy step still takes the machine's heavy slot and render mode by itself | | `queue ls [--all] [--json]` · `queue status <qid> [--json]` · `queue wait <qid> [--timeout <s>]` · `queue log <qid> [--tail N]` · `queue cancel <qid>` · `queue retry <qid>` | the queue: `ls` the runner (is the app running it) and the steps not finished or finished in the last 24 h; `status` one step (**exit 0 done · 3 queued or running · 1 failed, blocked or cancelled**); `wait` the same after up to `<s>` seconds (default 90); `log` its FULL log (`logs/<qid>.log`; earlier attempts kept as `<qid>.<n>.log`); `cancel` a queued or blocked step at once, a running one stopped (its process group); `retry` a failed or cancelled step back in the queue with every step blocked behind it. A step that was running when the app died reads **failed** ("the step's process is gone"), its log kept — it is never re-run on its own | -| `jobs [--json]` | every running and recent **take render** across projects (their records), every queue step not finished or finished in the last 24 h, and the umtool app's own jobs (`GET /api/jobs` at `--url` / `UMTOOL_URL`, when it answers). The page is **/jobs** (the rail's *Running* links it) | +| `jobs [--json]` | every running and recent **take render** across projects (their records), every queue step not finished or finished in the last 24 h, and the umtool app's own jobs (`GET /api/jobs` at `--url` / `UMTOOL_URL`, when it answers). The page is **/jobs** (home's *Running* links it) | | `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed | | `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--pin \| --unpin] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway`; `--pin` keeps the pick when newer takes are built (each whole-cut take of the manifest is otherwise its group's pick once built), `--unpin` lets go ([report-video.md](report-video.md#takes-alternative-renders-judged-side-by-side)) | | `takes ls <project> [--json]` · `takes relabel <project> <take> <label…>` · `takes supersede <project> <take> [--by <take>]` · `takes supersede <project> <take> --clear` · `takes delete <project> <take> [--dry-run] [--force]` | **take housekeeping** (the Takes page's ✎, **Mark superseded**, **Delete take**): first the working cut's line (`Latest: draft-22 · 28:03 · +N edits since`, and the edits in words; `--json`: `working`), then the takes with latest / picked (pinned) / superseded / RENDERING; a label fixed in `take.json` (an undo point of the take's own); a take folded away as superseded (verdicts.json, nothing deleted); a take deleted. Relabel and delete are refused (**exit 1**) while the take renders or a live render is made from it ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) | +| `takes verdict <project> <take> like\|maybe\|no\|clear [--note "…"] [--json]` | **a take's verdict** in `takes/verdicts.json` — the Takes page's and Play's **Like · Maybe · No**; a version with a render and none is a call on home ("versions to judge", [knobs.md](knobs.md#what-needs-you-home-the-inbox-one-press-actions-quick-clip)) | | `takes save <project> [--label L] [--force] [--json]` · `takes open <project> <take> [--json]` · `takes freeze <project> [<take>… \| --all] [--apply] [--json]` | **the working draft and its saved versions** (Play's **Save version** and **Open in draft**): `save` freezes the draft (`video.manifest.json`) as the next `v<N>` — `takes/v<N>/base.manifest.json` byte for byte, `take.json` `version: true` — and names it the draft's parent (`takes/draft.json`); nothing is saved when the draft has no edits since its parent, unless `--force`. `open` copies a version into the draft — the draft saved first as the next `v<N>` when it has edits since its parent — with one undo point (`umtool timeline <p> undo` puts the draft and its parent back); a legacy take with its own timeline opens by its patch over the draft (as `take --promote`), another legacy take as the manifest it was rendered from (as `takes pick`). Neither touches the pick or its pin. `freeze` gives legacy takes a frozen base (the manifest each was rendered from, else the draft now) — a dry run unless `--apply`, each take's difference from how it resolves today said. Version ids are `v1`, `v2`, … — one above every `v<N>` directory under `takes/`, never reused ([knobs.md](knobs.md#the-working-draft-and-saved-versions)) | | `takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]` | **take housekeeping, the rest**: **Cancel render** (asked of the process rendering it, which stops its render's process group, marks the take cancelled and lets render mode go; exit 1 when it has not stopped); **Fork as variant** (a project beside this one, default `v-<take>`: the take's manifest, `variant.json`, the parent's media and assets linked, the take in it); two takes **side by side** (`<take>` or `<project>:<take>`: the facts, the cut's changes A → B, the look's differences) ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) | | `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade, intro (one rendered for the reel when the master has none, or the reel's own) and outro card (the title, the call to action, an image, the site's name; faded in from the last beat, held to the end), written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) | @@ -239,6 +240,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `takes ls <project>` | the working cut, then each take | form · *project* | | `takes relabel <project> <take> <label>` | a take's label | form · *project* | | `takes supersede <project> <take> [--by BY] [--clear]` | a take folded away in the list (or back) | form · *project* | +| `takes verdict <project> <take> like\|maybe\|no\|clear [--note NOTE]` | a take's verdict: like, maybe, no or clear (Play and judge) | form · *project* | | `takes save <project> [--label LABEL] [--force]` | the working draft frozen as the next version (v<N>) | form · *project* | | `takes open <project> <take>` | a saved version into the draft (the draft saved first) | form · *draft* | | `takes freeze <project> [<takes>…] [--all] [--apply]` | legacy takes given a frozen base (a dry run unless --apply) | form · *project* | @@ -253,7 +255,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `pool prune [--max-gb N] [--dry-run]` | the render pool pruned to its cap | form · *corpus* | | `pool verify [--sample N] [--all]` | the render pool's files checked | form · queued · *corpus* | | `trailer <project> [--take TAKE] [--reel REEL] [--beats BEATS] [--beats-json JSON] [--intro] [--finale N] [--xfade N] [--no-snap] [--out OUT] [--dry-run] [--candidates] [--vertical] [--layout reframe]` | a trailer or beat reel cut from a take's master | form · queued · *project* | -| `vertical <project> --take TAKE [--reel REEL] [--beats BEATS] [--items ITEMS] [--clip full\|framed\|quote] [--post card\|stack\|media] [--side split\|overlay] [--hook HOOK] [--captions l\|xl] [--lines 1\|2] [--loudness N] [--max N] [--name NAME] [--reframe] [--dry-run] [--intro] [--no-intro] [--no-outro]` | a vertical short (1080x1920) of a take's items | form · queued · *project* | +| `vertical <project> --take TAKE [--reel REEL] [--beats BEATS] [--items ITEMS] [--clip full\|framed\|quote] [--post card\|stack\|media] [--side split\|overlay] [--hook HOOK] [--captions l\|xl] [--lines 1\|2] [--loudness N] [--max N] [--name NAME] [--reframe] [--dry-run] [--intro] [--no-intro] [--no-outro] [--deck stacked\|bare]` | a vertical short (1080x1920) of a take's items | form · queued · *project* | | `trailer-beats <project> ls [--reel REEL]` | a reel's beats against its limit | form · *project* | | `trailer-beats <project> add <clip> [<span>] [--at N] [--label LABEL] [--take TAKE] [--reel REEL]` | a clip beat | form · *project* | | `trailer-beats <project> add-raw <at> <dur> [--at N] [--label LABEL] [--reel REEL]` | a beat of master seconds | form · *project* | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -371,7 +371,7 @@ bare footage (no deck, no cards: `data-play-bare`). | the mode | Build, **Look**: **Basic \| Deck** | `umtool look <p> mode=basic` | `PUT /api/report/render {patch: {mode}}` | | the built-in preset | Media, Video modules, Look preset | `umtool preset apply basic <p> [--replace]` | — | | a clip's **share line** — its platform page at the first second it plays (YouTube `t=<s>s`, Rumble `start=<s>`, Twitch `t=<h>h<m>m<s>s`) and its moment on the archive (`archiveMomentUrl`); a Rumble folder id (the URL slug the corpus keeps it under) goes out as the embed id the archive serves | **Copy share line**: on each take's card (its first clip) and on Play (the clip on screen); the line is shown beside the button too | `umtool share <p> [<clip>] [--take <t>] [--site <id>] [--json]` | `GET /api/report/share-line?project&clip&take` | -| **quick clip** — one moment to a shareable mp4: a basic-mode project under `quick-clips/` (its slug from `--title`, else `<channel>-<video>-<start>`), its window ASKED OF THE EDITOR (a Rumble recording fetched whole — the editor decides), `--snap words`: the edges snapped to the words heard there (the editor's transcribe op; the first word mostly after the start, the last mostly before the end, 0.15 s before and 0.3 s after, never into a neighbour), rendered as the take `clip` (the heavy slot; its record; the take panel), then the mp4's path and the share line; `--site <id>` names the archive (else the first public site carrying the channel) | — (the route) | `umtool clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json]` | `POST /api/report/quick-clip {spec, snap?, title?, site?}` → 202 `{job}`; `GET ?job=<id>` → `{job, done?: {project, output, share}}` | +| **quick clip** — one moment to a shareable mp4: a basic-mode project under `quick-clips/` (its slug from `--title`, else `<channel>-<video>-<start>`), its window ASKED OF THE EDITOR (a Rumble recording fetched whole — the editor decides), `--snap words`: the edges snapped to the words heard there (the editor's transcribe op; the first word mostly after the start, the last mostly before the end, 0.15 s before and 0.3 s after, never into a neighbour), rendered as the take `clip` (the heavy slot; its record; the take panel), then the mp4's path and the share line; `--site <id>` names the archive (else the first public site carrying the channel) | home's **Quick clip** box ([What needs you](#what-needs-you-home-the-inbox-one-press-actions-quick-clip)) | `umtool clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json]` | `POST /api/report/quick-clip {spec, snap?, title?, site?}` → 202 `{job}`; `GET ?job=<id>` → `{job, done?: {project, output, share}}` | The Rumble mapping is ONE helper (`lib/report/shareLine.mjs` `siteVideoFor`, over common `videoDir-server.mjs` `recordIdOfVideoDir`: the folder's `metadata.info.json` `id`) and it has three callers: the share line; @@ -379,6 +379,37 @@ The Rumble mapping is ONE helper (`lib/report/shareLine.mjs` `siteVideoFor`, ove `citeUrl` that was the dead link moves with it); and `umtool timeline insert <rumble-channel>/<folder>@…`, which writes the inserted clip with its `siteVideo`. A clip that pins `siteVideo` is never looked up. +## What needs you (home: the Inbox, one-press actions, Quick clip) + +Home (`/`) is the Inbox widened (umtool redesign L4): the calls waiting on the operator, grouped and ranked +(`lib/inbox/groups.mjs`), and beside them the **Quick clip** box, what is **Running** and the **Recent cuts** — which +were the rail's; the rail keeps navigation only (Pinned, which never had a store, is gone). Every row is in +`GET /api/browse/decisions` (`items[]`, one per decision) and `umtool inbox`. + +| Call | When | Its action (one press, where there is one) | From a terminal | +|---|---|---|---| +| **versions to judge** (`version-unjudged`, Review) | a version — or a legacy take — with a render on disk (its preview) and no verdict, not superseded; a quick clip's is not one; one rendered over two weeks ago is Quiet (folded: no longer waiting) | **Play and judge**: Play on the newest (`?take=`), where **Like · Maybe · No** sit in the version's line (pressing the lit one clears it) | `umtool takes verdict <p> <take> like\|maybe\|no\|clear [--note "…"]` | +| **clips not walked** (`clips-unwalked`, Review) | the draft's clips with no walk verdict, on a draft whose walk has begun or that has a render or a saved version (a cut still being assembled is not a call); a draft untouched for two weeks is Quiet | **Walk the clips**: the bench on the first in walk order | `umtool walk <p>` | +| **quote checks out of date** (`quote-check-stale`, Open) | a project with `quote-check.json` and clips its rows no longer vouch for: the cut or the quote changed since, or never checked | **Run quote-check** on those clips: a step on the durable queue (POST `/api/cli`, the registry's `quote-check` row — it transcribes through the editor) | `umtool quote-check <p> --clips a,b` | +| a quote **heard away from the cut** (`clip-quote-moved`, Blocking) | the check's row says `moved` | **Snap the cut to the words** (`window --align`'s patch, through the window writer) | `umtool window <p> <clip> --align` | +| a quote **not heard** (`clip-quote-missing`, Blocking) | the check's row says `not-found` | **Run quote-check** (after a refetch) | `umtool fetch <p> --refetch <clip> && umtool quote-check <p> --clips <clip>` | +| **QR links that don't open** (`link-dead`, Blocking) on a Rumble folder id | the recorded check knows the fix: the archive serves the recording by its embed id | **Use embed ids (N)**: the clip's `siteVideo` (a `citeUrl` that was the dead link moves with it), one undo point, then the check again (POST `/api/report/links {fix: true}`, `linksCli.mjs` applyLinkFixes — only a clip still as the check saw it) | `umtool links <p> --fix` | +| **new transcripts since the last scan** (`case-new-cues`, Review) | a research case with a pipeline, not done, whose candidate scan last finished at T, and recordings in its scope transcribed since T (the transcript index's per-video mtimes; with no index, the files) | **Scan again**: the case's pipeline page | `archilyzer case candidates <case>` | +| **X's cookies are stale and X work waits** (`x-jar-stale`, Blocking: a machine call beside a missing tool — on home and in the rail's count, no piece's, so not in `items[]`) | the editor's services (`GET /api/ops/services`, asked through umtool's editor client, a minute's memo, never waited on past 0.4 s — a late answer is the next read's) carry a stale X alert — the rule the editor's banner draws by | **Refresh X's cookies**: the editor's settings (Refresh cookies / Connect X account, then Recheck) — a human click; nothing here asks X | `pnpm ops get services` | + +A card whose rows agree on one press shows it in place of its link (`mergeSettle`: a quote check over every clip the +card lists; the same project-wide press; never two clip patches), its title still a link to where it is settled — the +same `DecisionSettle` buttons the project page's Checks list presses. + +**Quick clip.** Paste a moment — an archive's moment link (`?v=<channel>/<video>&t=`, or a `/m/…/<s>-<e>/` page), a +YouTube or Rumble link with its time (the channel is the one whose `data/` holds the recording; a Rumble embed id, the +channel whose metadata names it), or `<channel>/<video>@<start>-<end>` (`lib/report/momentLink.mjs`, the timeline's +Add clip reads the same) — and **Find** shows the recording, its span (a link's second runs to the end of its +sentence, at most 20 s) and the words around it (the corpus's words, else its cues: `GET +/api/report/quick-clip/strip?moment=`). A word starts the clip there, shift-click ends it there; **−0.5 −0.1 +0.1 ++0.5** nudge each edge; **snap to the words** asks the editor to snap them. **Render** is `umtool clip` (above: POST +`/api/report/quick-clip`), the command line shown under it; when it is done, **Copy share line**. + ## An ingredient's life cycle (the rail) `/ingredients/<channel>/<video>` is one recording of the corpus across its whole life: nine stages across the top, @@ -1648,7 +1679,7 @@ has the walk-through; in short: | one step: state, exit, error, log | `umtool queue status <qid> [--json]` (exit 0 done · 3 going · 1 failed/blocked/cancelled) · `queue wait <qid> --timeout 90` · `queue log <qid>` | **/jobs** → Queue, a step's **log** | `GET /api/queue` · `GET /api/queue/log?qid=` | | cancel / retry | `umtool queue cancel <qid>` · `umtool queue retry <qid>` (with the steps blocked behind it) | **Cancel** / **Retry** on the step | `POST /api/queue?cancel=<qid>` · `?retry=<qid>` | | a take's render record | `umtool take status <p> --id <take> [--json] [--log] [--tail N]` (exit 0 done · 3 queued/waiting/running · 1 failed) | the take's card (a render running now, or a later one that failed), **first render failed** above the takes, the project's **Queue** | `GET /api/report/takes/render?project=&take=` (`&log=1` the full log) | -| everything, across projects | `umtool jobs [--json]` | **/jobs** (the rail's *Running*) | `GET /api/queue`, `GET /api/jobs` | +| everything, across projects | `umtool jobs [--json]` | **/jobs** (home's *Running*) | `GET /api/queue`, `GET /api/jobs` | ## A take's own items (imported from other projects, edited in the take only) @@ -1695,7 +1726,8 @@ byte what it was. | Knob | Values (default) | What it does | |---|---|---| -| `render.format` | `"landscape"` · `"vertical"` (absent = landscape) | the whole cut 9:16: no header, footer, QR, rail, deck or brand intro | +| `render.format` | `"landscape"` · `"vertical"` (absent = landscape) | the whole cut 9:16, no brand intro: with its deck kept stacked (below), or bare -- no header, footer, QR, rail or deck | +| `render.vertical.deck` | `stacked` · `bare` (`stacked`) | a cut with a deck keeps it in 9:16 ([The vertical deck](#the-vertical-deck)); `bare` is the vertical as it first shipped, byte for byte. A cut with no deck is bare whatever it says | | `render.vertical.clip` | `full` · `framed` · `quote` (`full`) | T1 a 9:16 crop full-bleed, captions in the lower middle, a source tag · T2 the whole picture in the middle third over a blurred enlargement, hook above, captions below · T3 the picture in the top 40 %, the line set large below, each word lit, "— channel · date" | | `render.vertical.post` | `card` · `stack` · `media` (`card`) | P1 the card at full width, its attachment under the words · P2 the attachment over them, the thread column below · P3 the attachment large on top (60 %), the words under it | | `render.vertical.side` | `split` · `overlay` (`split`) | a clip with a side post: M1 the clip in the top half, the post rising into the bottom half for its span · M2 the clip full-bleed, the post floating over the lower third (the captions move above it) | @@ -1705,13 +1737,15 @@ byte what it was. | `render.vertical.safe` | `{top, bottom, right}` fractions (0.08, 0.2, 0.12) | kept clear of every caption, tag, card and post (the platforms' buttons) | | `render.vertical.loudness` | LUFS -30 … -8 (-14) | each clip levelled to it in its segment; the short brought to it at the end | | `render.vertical.maxSeconds` | 5 … 600 (60) | a short over it is said so (a note, never a refusal) | -| a clip's `vertical` | `{crop: [x, y, w, h], aspect?, layout?}` | its 9:16 box on the source (else centred) and its own layout over the cut's | +| a clip's `vertical` | `{crop: [x, y, w, h], aspect?, layout?, crops?}` | its 9:16 box on the source (else centred) and its own layout over the cut's; `layout: "twocrop"` with `crops: [[x, y, w, h], [x, y, w, h]]` (fractions of the source, the top one first) is the stacked deck's two-crop reframe | | a clip's `side` | `{item \| post, from, to, place?}` | a post shown BESIDE the clip while it plays: not read, the clip's sound on. `item` a post item of the cut, `post` its fields; `from`/`to` seconds into the clip; `place` `split`/`overlay` (vertical) or `right`/`left` (16:9: a panel over that side of the picture, sliding in) | | | From a terminal | |---|---| | a clip's crop, layout, side post | `umtool set <p> <clip> 'vertical.crop=[0.64,0,0.3164,1]' vertical.layout=quote side.item=<post item> side.from=1 side.to=9 side.place=overlay` (`side=` removes it; `--json`) | +| a clip's two crops (the stacked deck) | `umtool set <p> <clip> vertical.layout=twocrop 'vertical.crops=[[0.05,0.1,0.6,0.6],[0.62,0.55,0.36,0.45]]'` (`vertical.layout=` and `vertical.crops=` back) | | the cut 9:16 | `umtool look <p> format='"vertical"' vertical='{"clip":"framed","hook":"section"}'` (`format='"landscape"'` back) | +| the deck in 9:16, or none | `umtool look <p> vertical='{"deck":"stacked"}'` (the default) · `vertical='{"deck":"bare"}'` · a short: `umtool vertical <p> … --deck bare` | | a short of a take's items | `umtool vertical <p> --take <t> (--reel <r> \| --beats F \| --items a,b) [--clip …] [--post …] [--side …] [--hook …] [--json]` | | a reel 9:16 | `umtool trailer <p> --reel <r> --take <t> --vertical [--layout reframe]` | | the brand intro 9:16 first (centred in the safe area); the reel's outro card 9:16 last | `umtool vertical <p> --take <t> --reel <r> --intro` (a reel with `intro` on: by itself; `--no-intro`) · the reel's `outro` on: by itself (`--no-outro`) | @@ -1722,6 +1756,60 @@ A clip's `vertical` and `side` are read from the PROJECT's manifest over the tak made). The side card is drawn by the post card's own page with the cut's redaction and the authors' pictures; its attachments are left off. Play the cut shows the side post over the clip for its span. +### The vertical deck + +A 9:16 cut that has a deck keeps it (`render.vertical.deck: "stacked"`, the default; `report-to-video/vertical-deck.mjs`). +It is the landscape cut's deck -- the same schedule, the same pages, the same timing -- drawn in another geometry, +top to bottom inside the safe area (`render.vertical.safe`): + +| Zone | What stands there | +|---|---| +| the rail (under the top 8 %) | the section's name (the deck's markers; `deck.sectionTitle.first` before the first), its progress -- one segment per section, filled as its clips play -- and `2 / 5` | +| the picture | the clip's 16:9 footage box at the frame's full width; over it, as over the landscape footage box, the stamps, the stats, the effects, the chapters, the measure extras (the diet badge lower-left …) and the shelf (`deck.shelf`) at the picture's lower-left -- each anchored in the picture INSIDE the safe area, never in the right 12 % | +| the captions | under the picture, at most two lines (`render.vertical.captions.lines`), each word lit as it is said | +| the instruments' panel | two columns: the dial the left column's height, the odometer and the trail down the right (the promise clock in the trail's cell, as in the landscape column); an instrument the panel has no room for is left out, never squashed | +| the counters | the tally's cells, when the cut counts its claims (`render.chrome.factcheck`, `deck.counter`) | +| the source block (above the bottom 20 %) | the clip's QR, its channel, its title (the deck's own when the clip sets one), its date and the time it is from | +| the bottom 20 % | the site's name, dim (decoration only) | + +A **post item** is the hero card -- today's vertical post card (`render.vertical.post`) from under the rail to the +panel's top -- the counters under it, its big date line and who posted it in the source block; the instruments stand +down while it is up. A clip with **two crops** (`vertical.layout: "twocrop"`, `vertical.crops`) plays crop one over a +one-row strip of the instruments (what he says he weighs, what he says he has lost, NET), crop two under it with the +captions over its foot, its source line over the rail at the top and its QR small and low-left in the bottom band; a +crop drawn past 2.5× its source's pixels is said so (the lint, on a 16:9 source of `render.maxHeightSource`; the build +again, from the real one). The **finale** (`layout: "finale"`) is the instrument column over the picture's room: its +title, the dial large in a card, the odometer and NET under it (module `dial-finale`). + +Every module declares its vertical form (`vertical: {slot}` in `modules/<id>.mjs`: frame, panel, picture, shelf, +finale, inline, segment, input). One the cut sets up that has none -- the posts popups and feed, the side panel +(threads, flips), the live chat, the landscape finale's page and its diet runs (`runs-finale`), the claim checks on +the rail, the legacy chart band -- is LEFT OUT: the lint +and the build say so (`popup-posts: no vertical form -- left out of the stacked vertical deck …`); the landscape cut +keeps it. With the popups left out, a clip that carries posts is not held for them (the landscape cut's `posts.hold`: +a frozen frame with nothing over it), and nothing moves the picture; every other second is the landscape cut's. + +Play the cut plays a vertical cut's deck 9:16 (its player sized for the tall frame): the same pages, composed for +preview. Present is the landscape one. A take's `--preview` of a vertical cut is 9:16 too (720x1280, `render.preview`). + +A reel's **outro in 9:16 is the end card** (`outro.mjs`): over its title "EVERY CLIP, IN FULL", the archive's link as a +large QR (`provenance.qrLink`, else `siteOrigin`) with "Scan or search", its host and the call to action beside it, +the short's sources -- each clip's date, channel and the time it is from, three of them, then "+ N more in the +archive" -- and the site's name at the foot of the safe area. Only a short that keeps the deck ends on it. + +**720p.** A deck cut rendered 1280x720 (`render.width`/`height`) has its band scaled with the frame's height +(`deck.mjs` `deckScale`, two thirds; floored there, and only ever down) -- its default height, title, QR and pips, and +the layout's own rows and margins: the marker band, the claim row, the track, the side padding, the tally's cells, the +section title -- so `deck.footageScale` 0.82 fits as at 1080 (it was refused: "at most 0.736"), the footage box no +longer stands above the frame, and markers, a two-line subtitle, a goalpost and a tally all stay inside the band. A +size the manifest writes in pixels (`deck.height`, `deck.qr.size`, `deck.title.size`, `deck.pip`) stays those pixels. +1080 is untouched. The QR's scan lint reads a code at 720p on the frame's short side. + +A short (`umtool vertical`) of a stacked deck cut declares the stacked deck's memory floor to the heavy slot +(`render-estimate.mjs` `VERTICAL_DECK_MIN_MB`, its measured 2.6 GB peak + 25 %), and its pieces are cut from the built +cut clear of its dissolves (each piece after the dissolve in and before the one out, never past its own segment) so +none plays twice. `--deck bare` is the bare short, byte for byte -- its outro the card it always was, not the end card. + ## Takes: relabel, supersede, cancel, delete, fork as variant, compare | | In umtool | From a terminal | Route | diff --git a/umtool/e2e/fixtures/editor-stub-services.mjs b/umtool/e2e/fixtures/editor-stub-services.mjs @@ -0,0 +1,25 @@ +// The editor's cookie alerts, stubbed (umtool redesign L4, needs-you.spec.ts): `GET /api/ops/services` answers +// what a spec put there (`POST /__stub/services {alerts, x}`, the stub's own door, no token; `{}` resets to no +// alerts) -- the payload editor/app/lib/cookieAlerts.ts serves, so the Inbox's X jar row (lib/inbox/xJar.ts) +// reads the same shape it reads from the real editor. Nothing here asks X anything. +const state = { alerts: [], pending: [], x: null }; + +/** The spec's door. True when it answered. */ +export function servicesControl(req, res, url, { json, readBody }) { + if (req.method !== "POST" || url.pathname !== "/__stub/services") return false; + readBody(req, (body) => { + state.alerts = Array.isArray(body?.alerts) ? body.alerts : []; + state.pending = Array.isArray(body?.pending) ? body.pending : []; + state.x = body?.x && typeof body.x === "object" ? body.x : null; + json(res, 200, { ok: true, alerts: state.alerts.length }); + }); + return true; +} + +/** `GET /api/ops/services`, behind the token. True when it answered. */ +export function servicesRoute(req, res, url, { json }) { + if (req.method !== "GET" || url.pathname !== "/api/ops/services") return false; + req.resume(); + json(res, 200, { ok: true, alerts: state.alerts, pending: state.pending, ...(state.x ? { x: state.x } : {}) }); + return true; +} diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -16,6 +16,7 @@ // entry, ready when its own endpoint answers. import { intakeControl, intakeRoute } from "./editor-stub-intake.mjs"; +import { servicesControl, servicesRoute } from "./editor-stub-services.mjs"; import http from "node:http"; import { spawn, spawnSync } from "node:child_process"; import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; @@ -1236,6 +1237,8 @@ const server = http.createServer((req, res) => { } // The intake specs' counts (editor-stub-intake.mjs). if (intakeControl(req, res, url, { json, readBody })) return; + // The cookie alerts a spec puts up (editor-stub-services.mjs, needs-you.spec.ts). + if (servicesControl(req, res, url, { json, readBody })) return; if (req.method === "POST" && url.pathname === "/__stub/ops-jobs") { return readBody(req, (body) => { const mode = body?.mode ?? "ok"; @@ -1253,6 +1256,8 @@ const server = http.createServer((req, res) => { return json(res, 401, { error: "missing bearer token" }); } + // The editor's cookie alerts and X's jar (editor-stub-services.mjs): the Inbox's X jar row reads them. + if (servicesRoute(req, res, url, { json })) return; // UI notes items 13 and 16: a channel's counts, the focus, capture-posts (editor-stub-intake.mjs). if (intakeRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push({ ...r, authorization: auth }), record()) })) return; // Release 38 lane C: a research case's verify, leads and evidence stages (editor-stub-case-stages.mjs). diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -67,6 +67,7 @@ import { makePostComboFixture } from "./post-combo-fixture.mjs"; import { makeMediaScenesFixture } from "./media-scenes-fixture.mjs"; import { makeInstrumentsFixture } from "./instruments-fixture.mjs"; import { makeIntroPlayFixture } from "./intro-play-fixture.mjs"; +import { makeNeedsYouFixture } from "./needs-you-fixture.mjs"; import { makeInspectorFixtures } from "./inspector-fixture.mjs"; import { makeIngredientRailFixture } from "./ingredient-rail-fixture.mjs"; @@ -2110,6 +2111,16 @@ await makeMeasureExtrasFixture({ deck: { dial: true, odometer: true, trail: true, goals: false, peak: false, promise: false, diet: false, streak: false }, }); +// THE STACKED VERTICAL DECK (vertical-deck.spec.ts, lane L10): the same measured cut rendered 9:16 with its deck kept +// (render.format vertical; render.vertical.deck absent = stacked) -- the rail, the instruments' panel, the source +// line and its QR in Play the cut. READ-ONLY. +await makeMeasureExtrasFixture({ + reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), + name: "vertical-deck-fixture", title: "The Vertical Deck Fixture", + deck: { dial: true, odometer: true, trail: true, goals: false, peak: false, promise: false, diet: false, streak: false, markers: [{ after: "c02", label: "Carnivore" }], sectionTitle: { first: "Keto" } }, + render: { format: "vertical" }, +}); + // Wrong speaker in Play the cut (play-modules.spec.ts), which WRITES (removes c02, then undoes): // its own copy, so no other spec's cut moves under it. makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), name: "play-wrong-fixture", title: "The Play Wrong Speaker Fixture" }); @@ -2545,6 +2556,9 @@ makeCaseFixture({ channels: CHANNELS, reportsRoot: dest }); // R3: transparent runs -- a traced sweep, an imported turns-only one with two // run starts, and one still running. makeRunTraceFixture({ articles: ARTICLES, source: `local:${RESEARCH_PUBLIC}` }); +// WHAT NEEDS YOU (needs-you.spec.ts, redesign L4): a cut with a rendered version to judge, clips to walk and quote +// checks out of date; a Rumble QR naming its folder (Use embed ids); a live case with a transcript since its scan. +makeNeedsYouFixture({ reports, reportsRoot: dest, channels: CHANNELS, deckManifest, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), makePlayCutFixture }); console.log(`fixture at ${dest}`); console.log(` SITES_DIR=${SITES}`); diff --git a/umtool/e2e/fixtures/measure-extras-fixture.mjs b/umtool/e2e/fixtures/measure-extras-fixture.mjs @@ -48,11 +48,11 @@ export const MEASURE_LEDGER = [ ]; /** - * @param {{ reports: string, deckManifest: Function, cachedWindow: string, name?: string, title?: string, deck?: Record<string, any> }} o + * @param {{ reports: string, deckManifest: Function, cachedWindow: string, name?: string, title?: string, deck?: Record<string, any>, render?: Record<string, any> | null }} o * `name`/`title`/`deck`: another copy with more deck keys (play-instruments-fixture: the dial, the odometer and * the trail on, the extras off -- instruments.spec.ts). */ -export async function makeMeasureExtrasFixture({ reports, deckManifest, cachedWindow, name = "play-measure-fixture", title = "The Play Measure Fixture", deck = {} }) { +export async function makeMeasureExtrasFixture({ reports, deckManifest, cachedWindow, name = "play-measure-fixture", title = "The Play Measure Fixture", deck = {}, render = null }) { const { dir } = makePlayCutFixture({ reports, deckManifest, cachedWindow, name, title, chrome: { @@ -70,6 +70,8 @@ export async function makeMeasureExtrasFixture({ reports, deckManifest, cachedWi promise: { label: "scale video" }, ...deck, }; + // More render keys (vertical-deck-fixture: format vertical, the stacked deck). + if (render) m.render = { ...m.render, ...render }; writeFileSync(file, JSON.stringify(m, null, 2) + "\n"); return { dir }; } diff --git a/umtool/e2e/fixtures/needs-you-fixture.mjs b/umtool/e2e/fixtures/needs-you-fixture.mjs @@ -0,0 +1,100 @@ +// WHAT NEEDS YOU (needs-you.spec.ts, umtool redesign L4): one fixture per new Inbox call -- +// +// reports/needs-you-fixture the Play cut (play-cut-fixture.mjs) with +// c01 walked (confirmed), c02–c04 not -> clips-unwalked +// v1, a RENDERED saved version (its base frozen, a preview), no verdict; +// `short`, a rendered legacy take, no verdict -> version-unjudged (Play ?take=v1) +// quote-check.json: c02's row for a cut it no longer plays; c01, c03, c04 never +// checked -> quote-check-stale, its one press Run quote-check +// reports/needs-you-links one clip of a RUMBLE recording cited by its URL-slug folder (v6nyslug) whose +// archive record is its embed id (v6nyembd, its metadata.info.json), and a +// recorded link check calling it dead with that fix -> link-dead, Use embed ids (1) +// .umtool/research/needs-you-case a case with a pipeline (scope nychan), its candidate scan done on +// 1 Nov, and nychan/nyfresh transcribed since -> case-new-cues +// +// X's jar is the stub editor's (editor-stub-services.mjs), put up by the spec. The spec WRITES (a verdict, the +// links fix, a queued quote check): this fixture is its own. Synthetic, like every fixture. +import { copyFileSync, mkdirSync, readFileSync, utimesSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import path from "node:path"; +import { linksOf, withArchiveId } from "../../lib/report/linkCheck.mjs"; + +export const NY_PROJECT = "needs-you-fixture"; +export const NY_TITLE = "The Needs You Fixture"; +export const NY_LINKS = "needs-you-links"; +export const NY_LINKS_TITLE = "The Needs You Links"; +export const NY_CASE = "needs-you-case"; +export const NY_RUMBLE = "nyrumble"; +export const NY_FOLDER = "v6nyslug"; +export const NY_EMBED = "v6nyembd"; +/** + * A public-shaped site that never resolves (`.invalid`, RFC 6761: no resolver answers it): the re-check after + * the fix cannot verify, and says so. Not a loopback address -- that is a blocking siteOrigin of its own. + */ +export const NY_SITE = "https://ny-archive.invalid"; + +const write = (dir, name, doc) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, name), typeof doc === "string" ? doc : JSON.stringify(doc, null, 2) + "\n"); +}; + +/** + * @param {{ reports: string, reportsRoot: string, channels: string, deckManifest: Function, manifest: Function, cachedWindow: string, makePlayCutFixture: Function }} o + */ +export function makeNeedsYouFixture({ reports, reportsRoot, channels, deckManifest, manifest, cachedWindow, makePlayCutFixture }) { + // ---- the cut: versions to judge, clips not walked, quote checks out of date ---- + const { dir } = makePlayCutFixture({ reports, deckManifest, cachedWindow, name: NY_PROJECT, title: NY_TITLE }); + const file = path.join(dir, "video.manifest.json"); + const m = JSON.parse(readFileSync(file, "utf8")); + m.timeline = m.timeline.map((e) => (e.id === "c01" ? { ...e, verdict: "confirmed" } : e)); + const text = JSON.stringify(m, null, 2) + "\n"; + writeFileSync(file, text); + const v1 = path.join(dir, "takes", "v1"); + write(v1, "base.manifest.json", text); + write(v1, "take.json", { + id: "v1", group: "takes", order: 3, label: "Saved draft", kind: "reference", summary: "", changes: [], preview: "preview.mp4", + // Rendered a day before the fixture is made: a call (a render older than two weeks is Quiet, versions.mjs RECENT_DAYS). + seconds: 9, builtAt: new Date(Date.now() - 864e5).toISOString(), style: null, patch: null, window: "full", version: true, + savedAt: new Date(Date.now() - 2 * 864e5).toISOString(), baseHash: createHash("sha256").update(text).digest("hex"), + }); + copyFileSync(cachedWindow, path.join(v1, "preview.mp4")); + write(dir, "quote-check.json", { version: 1, checkedAt: "2026-11-08T11:00:00.000Z", clips: { c02: { status: "ok", cut: { from: 3, to: 5 }, quote: "And this one runs on", checkedAt: "2026-11-08T11:00:00.000Z" } } }); + + // ---- the Rumble QR that names the folder, not the record ---- + const rch = path.join(channels, NY_RUMBLE); + write(rch, "config.json", { name: "NY Rumble", platform: "rumble" }); + const rv = path.join(rch, "data", NY_FOLDER); + write(rv, "metadata.info.json", { id: NY_EMBED, title: "The NY Rumble Recording", webpage_url: `https://rumble.com/${NY_FOLDER}-the-ny-rumble-recording.html` }); + write(rv, "transcript.cues.json", { title: "The NY Rumble Recording", duration: 60, cues: [{ start: 0, end: 60, text: "a rumble." }] }); + const lm = manifest(NY_LINKS, NY_LINKS_TITLE, { siteOrigin: NY_SITE, channelSlug: NY_RUMBLE }, [{ type: "clip", id: "n01", video: NY_FOLDER, start: 10, end: 14, cite: 10, section: 0, quote: "a rumble." }]); + const ldir = path.join(reports, NY_LINKS); + write(ldir, "video.manifest.json", lm); + const [qr] = linksOf(lm); + if (!qr) throw new Error("needs-you-fixture: the Rumble clip draws no QR"); + write(path.join(ldir, "out"), "links.json", { + version: 1, + checkedAt: "2026-11-08T12:00:00.000Z", + fetched: 3, + origins: { [NY_SITE]: { state: "ok", generatedAt: "2026-11-01T00:00:00.000Z" } }, + links: [ + { + clip: "n01", url: qr.url, state: "dead", origin: NY_SITE, + why: `"${NY_FOLDER}" is the recording's folder (its Rumble URL slug), not a record on ${new URL(NY_SITE).host}; the site's record is its embed id "${NY_EMBED}"`, + fix: withArchiveId(qr.url, NY_FOLDER, NY_EMBED), fixSiteVideo: NY_EMBED, + }, + ], + }); + + // ---- a live case, scanned on 1 Nov, its channel transcribed since ---- + const now = "2026-11-01T00:00:00.000Z"; + const cdir = path.join(reportsRoot, ".umtool", "research", NY_CASE); + write(cdir, "case.json", { format: "umtool-research-case", version: 1, id: NY_CASE, title: "The Needs You Case", scope: { source: "local" }, search: null, sessions: [], sections: [], quotes: [], notes: "", handoffs: [], counters: { quote: 0, section: 0 }, createdAt: now, updatedAt: now }); + write(cdir, "pipeline.json", { format: "archilyzer-case-pipeline", version: 1, case: NY_CASE, subjects: [], scope: { channels: ["nychan"], groups: [], sites: [] }, eras: [], groups: [], privateNames: { sha256: [], note: "" }, readerPrompts: { common: "" }, status: "reading", createdAt: now, updatedAt: now }); + write(cdir, "stages.json", { candidates: { state: "done", startedAt: now, endedAt: "2026-11-01T00:05:00.000Z", by: "cli", pid: 1, log: [], counts: { windows: 0 } } }); + write(path.join(channels, "nychan"), "config.json", { name: "NY Chan", platform: "youtube" }); + const old = path.join(channels, "nychan", "data", "nyold"); + write(old, "transcript.cues.json", { title: "Before the scan", duration: 10, cues: [{ start: 0, end: 10, text: "old." }] }); + utimesSync(path.join(old, "transcript.cues.json"), new Date("2026-10-20T00:00:00Z"), new Date("2026-10-20T00:00:00Z")); + write(path.join(channels, "nychan", "data", "nyfresh"), "transcript.cues.json", { title: "After the scan", duration: 10, cues: [{ start: 0, end: 10, text: "new." }] }); + return { dir, ldir, cdir }; +} diff --git a/umtool/e2e/inbox-engine.spec.ts b/umtool/e2e/inbox-engine.spec.ts @@ -54,7 +54,8 @@ test("one row per decision, each with the inbox's fields; the counts add up", as expect(hidden).toBe(items.filter((d) => d.hidden).length); expect(groups.map((g) => g.id)).toEqual(["your-call", "review", "blocking", "notes", "open", "ready-to-finish", "quiet"]); for (const d of items) { - expect(d.piece, `${d.kind} ${d.project}`).toMatch(/^[ap]:/); + // A research case's new transcripts (L4, case-new-cues) are its case's: `c:<case>`. + expect(d.piece, `${d.kind} ${d.project}`).toMatch(d.kind === "case-new-cues" ? /^c:/ : /^[ap]:/); expect(d.group).toBeTruthy(); expect(d.category).toBeTruthy(); expect(d.lifecycle).toBeTruthy(); diff --git a/umtool/e2e/needs-you.spec.ts b/umtool/e2e/needs-you.spec.ts @@ -0,0 +1,243 @@ +import { test, expect, type APIRequestContext, type Page } from "@playwright/test"; +import { mkdirSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; +import { NY_CASE, NY_EMBED, NY_LINKS, NY_PROJECT, NY_TITLE } from "./fixtures/needs-you-fixture.mjs"; +import * as urls from "./urls"; +import { warm, WARM_TIMEOUT } from "./warm"; + +// --------------------------------------------------------------------------- +// WHAT NEEDS YOU (umtool redesign L4): home is the Inbox, widened -- +// +// each new kind from its fixture (fixtures/needs-you-fixture.mjs): versions to judge, clips not walked, quote +// checks out of date, a live case's new transcripts, X's jar (the stub editor's services, only while X work +// waits), and a dead Rumble QR with Use embed ids; +// one-press actions that change the file: Play and judge (verdicts.json), Use embed ids (the manifest's +// siteVideo), Run quote-check (a step on the durable queue); +// the Quick clip box: a moment found, its edges nudged, rendered (the stub editor's window), its share line; +// the rail keeps navigation only: Running and the Recent cuts are on home. +// +// The tests run in order: Quick clip before Run quote-check, which leaves a step on the queue (cancelled after). +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial" }); + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const P = `reports/${NY_PROJECT}`; +const L = `reports/${NY_LINKS}`; +const DIR = path.join(FIXTURE, "reports", NY_PROJECT); +const LDIR = path.join(FIXTURE, "reports", NY_LINKS); +const STUB = `http://127.0.0.1:${portFor("EDITOR_STUB_PORT")}`; +const QUICK_PROJECT = "quick-clips/basicyt-quickvid-10"; +const SHOTS = process.env.E2E_NEEDS_YOU_SHOTS ?? ""; +const shot = async (page: Page, name: string) => { + if (!SHOTS) return; + mkdirSync(SHOTS, { recursive: true }); + await page.screenshot({ path: path.join(SHOTS, `${name}.png`) }); +}; +const card = (page: Page, kind: string, piece: string | null = null) => + page.locator(`[data-card='${kind}']${piece ? `[data-piece='${piece}']` : ""}`); +const json = (file: string) => JSON.parse(readFileSync(file, "utf8")); +const X_ALERT = { + service: "x", + label: "X", + family: "x", + state: "stale", + kind: "jar-age", + since: "2026-11-09T09:00:00.000Z", + raisedAt: "2026-11-09T09:00:00.000Z", + headline: "X cookies are 3 h old (limit 60 min)", + fix: "Refresh cookies (or Connect X account) on /settings — then Recheck.", + detail: "2 X jobs are queued.", +}; +const services = (request: APIRequestContext, alerts: unknown[]) => request.post(`${STUB}/__stub/services`, { data: { alerts } }); +let queued: string | null = null; + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await warm(playwright, ["/", "/api/browse/decisions", urls.playHref(P, { take: "short" }), `/api/report/quick-clip/strip?moment=${encodeURIComponent("basicyt/quickvid@10-14")}`]); +}); + +test.afterAll(async ({ request }) => { + await services(request, []); + if (queued) await request.post(`/api/queue?cancel=${queued}`); + rmSync(path.join(FIXTURE, "quick-clips", "basicyt-quickvid-10"), { recursive: true, force: true }); + rmSync(path.join(FIXTURE, "channels", "basicyt", "data", "quickvid", "clips"), { recursive: true, force: true }); +}); + +test("each new call is on home from its fixture -- versions, clips, quote checks, the case, the Rumble QR; X's jar only while X work waits", async ({ page, request }) => { + test.setTimeout(120_000); + await page.setViewportSize({ width: 1366, height: 768 }); + await services(request, []); + await page.goto("/"); + const piece = `p:${P}`; + + const versions = card(page, "version-unjudged", piece); + await expect(versions).toBeVisible({ timeout: 60_000 }); + await expect(versions.locator("[data-card-title]")).toContainText(`${NY_TITLE} · 2 versions to judge`); + await expect(versions.locator("[data-action-link]")).toHaveText("Play and judge"); + await expect(page.locator(`[data-group=review] [data-card='version-unjudged'][data-piece='${piece}']`)).toHaveCount(1); + + const walk = card(page, "clips-unwalked", piece); + await expect(walk.locator("[data-card-title]")).toContainText("3 clips not walked"); + await expect(walk.locator("[data-action-link]")).toHaveAttribute("href", urls.clipBenchHref(P, "c02")); + + const checks = card(page, "quote-check-stale", piece); + await expect(checks.locator("[data-card-title]")).toContainText("4 quote checks out of date"); + await expect(checks.locator("[data-count]")).toHaveText("4"); + await expect(checks.locator("[data-settle-button='quote-check']")).toHaveText("Run quote-check"); + // A one-press card's title still goes where it is settled. + await expect(checks.locator("[data-card-link]")).toHaveAttribute("href", urls.projectHref(P)); + + const theCase = card(page, "case-new-cues", `c:${NY_CASE}`); + await expect(theCase.locator("[data-card-title]")).toContainText("1 new transcript since the last scan"); + await expect(theCase.locator("[data-action-link]")).toHaveAttribute("href", `/research/${NY_CASE}/pipeline`); + + const links = page.locator(`[data-group=blocking] [data-card='link-dead'][data-piece='p:${L}']`); + await expect(links.locator("[data-settle-button='links']")).toHaveText("Use embed ids (1)"); + + // X's jar: nothing while no X work waits; the editor's three lines once its alert is up. + await expect(card(page, "x-jar-stale")).toHaveCount(0); + await services(request, [X_ALERT]); + await page.reload(); + const x = page.locator("[data-group=blocking] [data-card='x-jar-stale']"); + await expect(x).toBeVisible({ timeout: 30_000 }); + await expect(x).toContainText("X cookies are 3 h old (limit 60 min)"); + await expect(x).toContainText("2 X jobs are queued."); + await expect(x.locator("[data-action-link]")).toHaveText("Refresh X's cookies"); + await expect(x.locator("[data-action-link]")).toHaveAttribute("href", `${STUB}/settings`); + await shot(page, "needs-you-home"); + + // The API keeps one row per decision. + const items = ((await (await request.get("/api/browse/decisions")).json()) as { items: { kind: string; project: string; target: string }[] }).items; + expect(items.filter((d) => d.kind === "version-unjudged" && d.project === P).map((d) => d.target).sort()).toEqual(["short", "v1"]); + expect(items.filter((d) => d.kind === "clips-unwalked" && d.project === P).map((d) => d.target)).toEqual(["c02", "c03", "c04"]); + expect(items.filter((d) => d.kind === "quote-check-stale" && d.project === P).map((d) => d.target)).toEqual(["c01", "c02", "c03", "c04"]); + // X's jar is a machine call (lib/machine.ts): on the page and the rail's count, not a piece's row. + expect(items.some((d) => d.kind === "x-jar-stale")).toBe(false); + expect(items.filter((d) => d.kind === "case-new-cues").map((d) => (d as { piece?: string }).piece)).toContain(`c:${NY_CASE}`); + + await services(request, []); + await page.reload(); + await expect(card(page, "x-jar-stale")).toHaveCount(0); +}); + +test("the rail keeps navigation only: Running and the Recent cuts are on home", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + await page.goto(urls.playHref(P, { take: "short" })); + await expect(page.locator("[data-play-take='short']")).toBeVisible({ timeout: 60_000 }); + await page.goto("/"); + const rail = page.locator("[data-app-rail]"); + await expect(rail).toBeVisible(); + await expect(rail.locator("[data-rail-section=pins], [data-home-section=running], [data-home-section=recent-cuts]")).toHaveCount(0); + await expect(rail).not.toContainText("Pinned"); + const aside = page.locator("[data-home-aside]"); + await expect(aside.locator("[data-home-section=running]")).toBeVisible(); + await expect(aside.locator("[data-quick-clip]")).toBeVisible(); + // Play remembered the cut: it is a Recent cut on home. + await expect(aside.locator(`[data-recent-cut='${P}']`)).toBeVisible(); +}); + +test("Play and judge: the card opens Play on the version; Like writes verdicts.json and the card counts one fewer", async ({ page }) => { + test.setTimeout(120_000); + await page.setViewportSize({ width: 1366, height: 768 }); + await page.goto("/"); + const versions = card(page, "version-unjudged", `p:${P}`); + await versions.locator("[data-action-link]").click(); + // Play keeps where it is in its address (clip, at): the version is the take. + await expect(page).toHaveURL(/\/play\?take=short(&|$)/); + const verdict = page.locator("[data-play-take='short'] [data-play-verdict]"); + await expect(verdict.locator("[data-play-verdict-button='like']")).toBeEnabled({ timeout: 60_000 }); + await shot(page, "needs-you-play-judge"); + await verdict.locator("[data-play-verdict-button='like']").click(); + await expect(verdict).toHaveAttribute("data-play-verdict", "like"); + await expect(verdict.locator("[data-play-verdict-button='like']")).toHaveAttribute("aria-pressed", "true"); + expect(json(path.join(DIR, "takes", "verdicts.json")).short?.verdict).toBe("like"); + + await page.goto("/"); + const left = card(page, "version-unjudged", `p:${P}`); + await expect(left.locator("[data-card-title]")).toContainText("1 version to judge"); + await expect(left.locator("[data-action-link]")).toHaveAttribute("href", urls.playHref(P, { take: "v1" })); + // The saved version too: judged where it plays (its base, frozen). + await left.locator("[data-action-link]").click(); + await page.locator("[data-play-take='v1'] [data-play-verdict-button='no']").click(); + await expect(page.locator("[data-play-take='v1'] [data-play-verdict]")).toHaveAttribute("data-play-verdict", "no"); + expect(json(path.join(DIR, "takes", "verdicts.json")).v1?.verdict).toBe("no"); + await page.goto("/"); + await expect(card(page, "version-unjudged", `p:${P}`)).toHaveCount(0); +}); + +test("Use embed ids: one press on the dead Rumble QR writes the clip's siteVideo, and the card goes", async ({ page }) => { + test.setTimeout(120_000); + await page.goto("/"); + const links = page.locator(`[data-card='link-dead'][data-piece='p:${L}']`); + await links.locator("[data-settle-button='links']").click(); + await expect(links.locator("[data-settle-said]")).toContainText("fixed n01", { timeout: 60_000 }); + const n01 = (json(path.join(LDIR, "video.manifest.json")).timeline as { id: string; siteVideo?: string }[]).find((e) => e.id === "n01"); + expect(n01?.siteVideo).toBe(NY_EMBED); + // One undo point before the rewrite, as `umtool links --fix` takes. + await page.reload(); + await expect(page.locator(`[data-card='link-dead'][data-piece='p:${L}']`)).toHaveCount(0); +}); + +test("Quick clip: a moment link found, the edges nudged on its words, rendered, the share line copied", async ({ page, context }) => { + test.setTimeout(300_000); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await page.setViewportSize({ width: 1366, height: 768 }); + await page.goto("/"); + const box = page.locator("[data-quick-clip]"); + const input = box.locator("[data-quick-clip-input]"); + + // A platform link names no channel: the one channel holding the recording is found; its span is its sentence. + await input.fill("https://www.youtube.com/watch?v=quickvid&t=10"); + await box.locator("[data-quick-clip-find]").click(); + await expect(box.locator("[data-quick-clip-strip]")).toHaveAttribute("data-quick-clip-strip", "basicyt/quickvid@10-30", { timeout: 30_000 }); + await input.fill("nothing here"); + await box.locator("[data-quick-clip-find]").click(); + await expect(box.locator("[data-quick-clip-error]")).toContainText("not a moment"); + + await input.fill("basicyt/quickvid@10-14"); + await box.locator("[data-quick-clip-find]").click(); + await expect(box.locator("[data-quick-clip-strip]")).toHaveAttribute("data-quick-clip-strip", "basicyt/quickvid@10-14", { timeout: 30_000 }); + await expect(box.locator("[data-editor-words]")).toContainText("a synthetic tone"); + await box.locator("[data-quick-clip-nudge='start:0.5']").click(); + await box.locator("[data-quick-clip-nudge='end:-0.5']").click(); + await box.locator("[data-quick-clip-nudge='end:0.5']").click(); + await expect(box.locator("[data-quick-clip-spec]")).toHaveText("umtool clip basicyt/quickvid@10.5-14"); + await shot(page, "needs-you-quick-clip"); + + await box.locator("[data-quick-clip-render]").click(); + await expect(box).toHaveAttribute("data-quick-clip", "done", { timeout: 240_000 }); + await expect(box.locator("[data-quick-clip-done]")).toHaveAttribute("data-quick-clip-done", QUICK_PROJECT); + const made = json(path.join(FIXTURE, QUICK_PROJECT, "video.manifest.json")); + expect(made.render.mode).toBe("basic"); + expect(made.timeline.map((e: { video: string; start: number }) => `${e.video}@${e.start}`)).toEqual(["quickvid@10.5"]); + const copy = box.locator('[data-share-copy="quick-clip"]'); + await copy.click(); + await expect(copy).toHaveAttribute("data-share-state", /copied|shown/, { timeout: 60_000 }); + await expect(box.locator('[data-share-line-box="quick-clip"] [data-share-line]')).toHaveText("https://www.youtube.com/watch?v=quickvid&t=10s"); + await shot(page, "needs-you-quick-clip-done"); + // A quick clip is shared, not judged or walked: no version to judge, no clips to walk. + const items = ((await (await page.request.get("/api/browse/decisions")).json()) as { items: { project: string; kind: string }[] }).items; + expect(items.filter((d) => d.project === QUICK_PROJECT && (d.kind === "version-unjudged" || d.kind === "clips-unwalked"))).toEqual([]); +}); + +test("Run quote-check: one press queues `umtool quote-check` on the card's clips", async ({ page, request }) => { + test.setTimeout(120_000); + await page.goto("/"); + const checks = card(page, "quote-check-stale", `p:${P}`); + await checks.locator("[data-settle-button='quote-check']").click(); + const said = checks.locator("[data-settle-said]"); + await expect(said).toContainText(/queued as q\d+ — 4 clips/, { timeout: 30_000 }); + queued = /queued as (q\d+)/.exec((await said.textContent()) ?? "")?.[1] ?? null; + const view = (await (await request.get(`/api/queue?project=${encodeURIComponent(P)}&all=1`)).json()) as { steps: { qid: string; argv?: string[]; label?: string }[] }; + const step = view.steps.find((s) => s.qid === queued); + expect(step, JSON.stringify(view.steps)).toBeTruthy(); + expect(JSON.stringify(step)).toContain("quote-check"); + expect(JSON.stringify(step)).toContain("c01,c02,c03,c04"); + // Off the queue again: it would hold the app's one job runner for the specs after this one. + expect((await request.post(`/api/queue?cancel=${queued}`)).ok()).toBe(true); + queued = null; +}); diff --git a/umtool/e2e/running.spec.ts b/umtool/e2e/running.spec.ts @@ -7,7 +7,8 @@ import { LIVE_ARTICLE, LIVE_JOB } from "./fixtures/run-trace-fixture.mjs"; import { runHref } from "../lib/research/runs-hrefs"; // --------------------------------------------------------------------------- -// P2b: what is running, in the rail, and drafts as decisions in the Inbox. +// P2b: what is running (on home, beside the Inbox, since the redesign's L4; +// the rail's foot before), and drafts as decisions in the Inbox. // // The Running list (components/shell/RunningList.tsx, lib/activity.ts) is // umtool's own jobs and the editor's live ones, from the editor stub's @@ -37,7 +38,8 @@ async function editorJobs(request: APIRequestContext, mode: "ok" | "editor-token expect(fresh.ok()).toBeTruthy(); } -const running = (page: Page) => page.locator("[data-app-rail] [data-rail-section=running]"); +// On home since the rail kept navigation only (redesign L4). +const running = (page: Page) => page.locator("[data-home-aside] [data-home-section=running]"); test.afterEach(async ({ request }) => { await editorJobs(request, "ok", [], true); @@ -75,9 +77,9 @@ const JOBS = [ { id: "e2e-q3", kind: "download-missing", channelSlug: "otherchan", status: "queued", queuedAt: NOW - 3000, queue: { key: "youtube", position: 3, queued: 3 } }, ]; -test("the rail lists the editor's running and queued jobs, a draft's spend, and the day's", async ({ page, request }) => { +test("home lists the editor's running and queued jobs, a draft's spend, and the day's", async ({ page, request }) => { await editorJobs(request, "ok", JOBS); - await page.goto("/tools"); + await page.goto("/"); const r = running(page); await expect(r).toHaveAttribute("data-editor-state", "ok"); await expect(r.locator("[data-running-count]")).toHaveAttribute("data-running-count", "2"); @@ -132,7 +134,7 @@ test("the rail lists the editor's running and queued jobs, a draft's spend, and test("nothing running, the editor's token unset, and an editor that does not answer are three sentences", async ({ page, request }) => { await editorJobs(request, "ok", [{ id: "e2e-lane-only", kind: "auto-publish", status: "running", queuedAt: NOW, startedAt: NOW }]); - await page.goto("/tools"); + await page.goto("/"); const r = running(page); await expect(r).toHaveAttribute("data-editor-state", "ok"); await expect(r.locator("[data-running-empty]")).toHaveText("Nothing running"); @@ -162,7 +164,7 @@ test("a report-draft row links its run page when it is a sweep (R3), its article // Placed by its log: a narration step, not a sweep. { id: "e2e-draft-narrate", kind: "report-draft", status: "running", queuedAt: NOW - 10_000, startedAt: NOW - 10_000, log: ["narrate of zeta i1 on qwen3:8b (the local model)"] }, ]); - await page.goto("/tools"); + await page.goto("/"); const r = running(page); const sweep = r.locator(`[data-running=${LIVE_JOB}]`); await expect(sweep.locator("[data-running-target]")).toContainText(`${LIVE_ARTICLE} i1`); diff --git a/umtool/e2e/vertical-deck.spec.ts b/umtool/e2e/vertical-deck.spec.ts @@ -0,0 +1,113 @@ +import { test, expect, type Page } from "@playwright/test"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// THE STACKED VERTICAL DECK (umtool/docs/knobs.md, "The vertical deck"; lane +// L10): a 9:16 cut that has a deck keeps it -- the landscape cut's schedule and +// pages laid in another geometry (report-to-video/vertical-deck.mjs). Play the +// cut plays it: the deck's own page over the whole 1080x1920 frame (the rail +// with its section and progress, each clip's source block and its QR), the +// footage at the frame's full width, the instruments' pages in their panel. +// +// Fixture: e2e/fixtures/measure-extras-fixture.mjs as vertical-deck-fixture -- +// play-measure-fixture's cut with the dial, the odometer and the trail on (the +// extras off), a marker after c02 ("Carnivore"; "Keto" before it) and +// render.format "vertical" (render.vertical.deck absent: stacked). READ-ONLY. +// --------------------------------------------------------------------------- + +const PROJECT = "reports/vertical-deck-fixture"; +const INSTRUMENTS = ["dial", "odometer", "trail"] as const; + +type Rect = { x: number; y: number; width: number; height: number }; +type Layer = { id: string; region?: string; geometry?: Rect | null; src?: string; error?: string }; + +const root = (page: Page) => page.locator("[data-play-cut]"); +const deck = (page: Page) => page.frameLocator('[data-testid="play-deck-iframe"]'); + +/** The words of the deck page's blocks that are on screen under `sel` (visible, opacity over a half). */ +const shown = (page: Page, sel: string) => + deck(page) + .locator(sel) + .evaluateAll((els) => + els + .filter((e) => { + let n: Element | null = e; + while (n && n instanceof HTMLElement) { + const cs = getComputedStyle(n); + if (cs.visibility === "hidden" || Number(cs.opacity) < 0.5 || cs.display === "none") return false; + n = n.parentElement; + } + return true; + }) + .map((e) => (e.textContent ?? "").replace(/\s+/g, " ").trim()), + ); + +test.beforeEach(() => { + test.setTimeout(150_000); +}); + +test("the chrome preview of a vertical cut is the stacked deck: 9:16, the picture at full width, the instruments in the panel", async ({ request }) => { + const res = await request.post("/api/report/chrome/preview", { data: { project: PROJECT, estimate: true } }); + expect(res.ok(), await res.text()).toBeTruthy(); + const doc = (await res.json()) as { geometry: { W: number; H: number; footage: Rect; deck: Rect }; layers: Layer[]; posts: { windows: unknown[] } }; + expect(doc.geometry.W).toBe(1080); + expect(doc.geometry.H).toBe(1920); + expect(doc.geometry.footage.width).toBe(1080); + expect(doc.geometry.deck).toEqual({ x: 0, y: 0, width: 1080, height: 1920 }); + expect(doc.posts.windows).toEqual([]); + const by = Object.fromEntries(doc.layers.map((l) => [l.id, l])); + // The safe area: the top 8 %, the bottom 20 %, the right 12 % kept clear. + for (const id of INSTRUMENTS) { + const g = by[id]?.geometry; + expect(g, `${id} is a play layer`).toBeTruthy(); + expect(by[id].src, by[id].error).toBeTruthy(); + expect(g!.y).toBeGreaterThanOrEqual(1920 * 0.08); + expect(g!.y + g!.height).toBeLessThanOrEqual(1920 * 0.8); + expect(g!.x + g!.width).toBeLessThanOrEqual(1080 * 0.88 + 1); + // Under the picture. + expect(g!.y).toBeGreaterThanOrEqual(doc.geometry.footage.y + doc.geometry.footage.height); + } + // The dial the left column's height, the odometer and the trail down the right. + expect(by.dial.geometry!.x).toBeLessThan(by.odometer.geometry!.x); + expect(by.trail.geometry!.y).toBeGreaterThan(by.odometer.geometry!.y); +}); + +test("Play the cut plays the stacked deck: the rail's section and progress, the source line and its QR, the instruments", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + await page.goto(urls.playHref(PROJECT, { clip: "c04", at: 1 })); + await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); + await expect(page.getByTestId("play-deck")).toBeVisible({ timeout: 30_000 }); + await expect(page.getByTestId("play-deck")).toHaveAttribute("data-deck-ready", "1", { timeout: 30_000 }); + await expect(page.locator("[data-play-tall]")).toHaveCount(1); + // The frame is tall: 9:16. + const box = await page.getByTestId("play-deck").boundingBox(); + expect(box).toBeTruthy(); + expect(Math.abs(box!.height / box!.width - 1920 / 1080)).toBeLessThan(0.02); + await expect(root(page)).toHaveAttribute("data-play-item", "c04"); + + // The rail: c04 is in the second section, its name up and "2 / 2" beside it. + await expect.poll(() => shown(page, ".rail .rlab"), { timeout: 10_000 }).toEqual(["Carnivore"]); + expect(await shown(page, ".rail .rcount")).toEqual(["2 / 2"]); + // The source block: the clip's QR beside its channel, title, date and time. + const src = deck(page).locator(".src").filter({ has: deck(page).locator("img.qr") }); + expect(await src.count()).toBeGreaterThan(0); + const blocks = await shown(page, ".src"); + expect(blocks.length).toBe(1); + expect(blocks[0]).toMatch(/\d+:\d{2}/); + // The tally's row (the cut counts its claims). + expect((await shown(page, ".tally")).length).toBe(1); + + // The instruments, each its page in the panel, up and ready. + for (const id of INSTRUMENTS) { + await expect(page.locator(`[data-play-layer="${id}"]`)).toHaveAttribute("data-play-layer-up", "1", { timeout: 30_000 }); + await expect(page.getByTestId(`play-layer-${id}`)).toHaveAttribute("data-feed-ready", "1", { timeout: 30_000 }); + } + await page.screenshot({ path: test.info().outputPath("vertical-deck-c04.png") }); + + // Back into the first section: its name on the rail. + await page.goto(urls.playHref(PROJECT, { clip: "c01", at: 0.5 })); + await expect(page.getByTestId("play-deck")).toHaveAttribute("data-deck-ready", "1", { timeout: 30_000 }); + await expect.poll(() => shown(page, ".rail .rlab"), { timeout: 10_000 }).toEqual(["Keto"]); + expect(await shown(page, ".rail .rcount")).toEqual(["1 / 2"]); + await page.screenshot({ path: test.info().outputPath("vertical-deck-c01.png") }); +}); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -594,7 +594,7 @@ export const GROUPS = [ ], docs: [ ["`jobs [--json]`", - "every running and recent **take render** across projects (their records), every queue step not finished or finished in the last 24 h, and the umtool app's own jobs (`GET /api/jobs` at `--url` / `UMTOOL_URL`, when it answers). The page is **/jobs** (the rail's *Running* links it)"], + "every running and recent **take render** across projects (their records), every queue step not finished or finished in the last 24 h, and the umtool app's own jobs (`GET /api/jobs` at `--url` / `UMTOOL_URL`, when it answers). The page is **/jobs** (home's *Running* links it)"], ], }, { @@ -604,6 +604,7 @@ export const GROUPS = [ " | ls <project> | relabel <project> <take> <label…> | supersede <project> <take> [--by <take>] [--clear]", " | delete <project> <take> [--dry-run] [--force] take housekeeping: a label fixed, a take folded away", " as superseded, a take deleted -- refused while a render names it", + " | verdict <project> <take> like|maybe|no|clear [--note T] a take's verdict (verdicts.json): Play and judge", ], docs: [ ["`takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \\| --full]`", @@ -612,6 +613,8 @@ export const GROUPS = [ "the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway`; `--pin` keeps the pick when newer takes are built (each whole-cut take of the manifest is otherwise its group's pick once built), `--unpin` lets go ([report-video.md](report-video.md#takes-alternative-renders-judged-side-by-side))"], ["`takes ls <project> [--json]` · `takes relabel <project> <take> <label…>` · `takes supersede <project> <take> [--by <take>]` · `takes supersede <project> <take> --clear` · `takes delete <project> <take> [--dry-run] [--force]`", "**take housekeeping** (the Takes page's ✎, **Mark superseded**, **Delete take**): first the working cut's line (`Latest: draft-22 · 28:03 · +N edits since`, and the edits in words; `--json`: `working`), then the takes with latest / picked (pinned) / superseded / RENDERING; a label fixed in `take.json` (an undo point of the take's own); a take folded away as superseded (verdicts.json, nothing deleted); a take deleted. Relabel and delete are refused (**exit 1**) while the take renders or a live render is made from it ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare))"], + ["`takes verdict <project> <take> like\\|maybe\\|no\\|clear [--note \"…\"] [--json]`", + "**a take's verdict** in `takes/verdicts.json` — the Takes page's and Play's **Like · Maybe · No**; a version with a render and none is a call on home (\"versions to judge\", [knobs.md](knobs.md#what-needs-you-home-the-inbox-one-press-actions-quick-clip))"], ["`takes save <project> [--label L] [--force] [--json]` · `takes open <project> <take> [--json]` · `takes freeze <project> [<take>… \\| --all] [--apply] [--json]`", "**the working draft and its saved versions** (Play's **Save version** and **Open in draft**): `save` freezes the draft (`video.manifest.json`) as the next `v<N>` — `takes/v<N>/base.manifest.json` byte for byte, `take.json` `version: true` — and names it the draft's parent (`takes/draft.json`); nothing is saved when the draft has no edits since its parent, unless `--force`. `open` copies a version into the draft — the draft saved first as the next `v<N>` when it has edits since its parent — with one undo point (`umtool timeline <p> undo` puts the draft and its parent back); a legacy take with its own timeline opens by its patch over the draft (as `take --promote`), another legacy take as the manifest it was rendered from (as `takes pick`). Neither touches the pick or its pin. `freeze` gives legacy takes a frozen base (the manifest each was rendered from, else the draft now) — a dry run unless `--apply`, each take's difference from how it resolves today said. Version ids are `v1`, `v2`, … — one above every `v<N>` directory under `takes/`, never reused ([knobs.md](knobs.md#the-working-draft-and-saved-versions))"], ["`takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]`", @@ -660,7 +663,8 @@ export const GROUPS = [ cmd: "vertical", usage: [ " umtool vertical <project> --take <t> (--reel R | --beats F | --items a,b) [--clip full|framed|quote]", - " [--post card|stack|media] [--side split|overlay] [--hook title|section|<copy>] [--reframe] [--json]", + " [--post card|stack|media] [--side split|overlay] [--hook title|section|<copy>] [--deck stacked|bare]", + " [--reframe] [--json]", " a vertical short (1080x1920, -14 LUFS) of the take's items: each clip cut again in its layout,", " each post drawn in a portrait box; --reframe recomposes the finished 16:9 master instead", ], diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -241,6 +241,7 @@ export const VERBS = Object.freeze([ form("takes ls", "project", "the working cut, then each take", [project()]), form("takes relabel", "project", "a take's label", [project(), takeArg(), arg("label")]), form("takes supersede", "project", "a take folded away in the list (or back)", [project(), takeArg(), name("--by"), bool("--clear")]), + form("takes verdict", "project", "a take's verdict: like, maybe, no or clear (Play and judge)", [project(), takeArg(), pick("verdict", ["like", "maybe", "no", "clear"], { required: true }), opt("--note", { help: "the verdict's note" })]), form("takes save", "project", "the working draft frozen as the next version (v<N>)", [project(), opt("--label"), bool("--force", "save even with no edits since its parent")]), form("takes open", "draft", "a saved version into the draft (the draft saved first)", [project(), takeArg({ help: "the version (or take) to open" })]), form("takes freeze", "project", "legacy takes given a frozen base (a dry run unless --apply)", [project(), many("takes", { item: "name", help: "take ids, one per line (none: --all)" }), bool("--all"), bool("--apply", "write them (else a dry run)")], { confirm: { what: "write each legacy take's frozen base (how it resolves can change)", when: ["--apply"] } }), @@ -262,6 +263,7 @@ export const VERBS = Object.freeze([ project(), takeOpt({ required: true, help: "the take" }), reel(), file("--beats", { help: "a beats file of the project" }), opt("--items", { help: "id,id" }), pick("--clip", ["full", "framed", "quote"]), pick("--post", ["card", "stack", "media"]), pick("--side", ["split", "overlay"]), opt("--hook", { help: "title | section | a line of the cut's own copy" }), pick("--captions", ["l", "xl"]), pick("--lines", ["1", "2"]), num("--loudness"), num("--max"), name("--name"), bool("--reframe", "recompose the finished 16:9 master"), dry(), bool("--intro"), bool("--no-intro"), bool("--no-outro"), + pick("--deck", ["stacked", "bare"]), ], Q), // ---- the trailer's beats ---- diff --git a/umtool/lib/decisions.ts b/umtool/lib/decisions.ts @@ -90,9 +90,13 @@ export type Decision = { | { kind: "patch"; clip: string; patch: Record<string, unknown>; label: string } | { kind: "check-links"; label: string; fix?: boolean } | { kind: "patch-markers"; file: string; label: string } - | { kind: "publish-site"; siteId: string; label: string }; + | { kind: "publish-site"; siteId: string; label: string } + // Run the quote check on these clips (L4): `umtool quote-check <p> --clips …`, on the durable queue. + | { kind: "quote-check"; clips: string[]; label: string }; /** The clips a project-wide row is about (a site's dead links). */ clips?: string[]; + /** The card's own title, when the rows name one ("3 versions to judge"); else the Inbox labels it by kind. */ + what?: string; // ---- The inbox's fields (lib/inbox.ts). ADDITIVE: a row without them is // still a decision, and the reducers above never set them. ---- diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts @@ -27,6 +27,8 @@ import { readSchedules } from "./schedules"; import type { ScheduleView } from "./schedule-types"; import { refreshDecisions } from "./inbox/refresh"; import { sourceWatchDecisions } from "./inbox/sourceWatch"; +import { projectCallsAll } from "./inbox/projectCalls"; +import { caseCuesDecisions } from "./inbox/caseCues"; // --------------------------------------------------------------------------- // THE INBOX, AS DATA: every open decision (lib/projects.ts openDecisions: the @@ -66,14 +68,26 @@ import { sourceWatchDecisions } from "./inbox/sourceWatch"; // per proposal, gone once approved or rejected (or the // claim ruled by hand, or changed: a stale proposal) // unreadable-proposals that file does not read: one Blocking row +// version-unjudged a rendered version (or legacy take) with no verdict: +// Play and judge (lib/inbox/versions.mjs, umtool +// redesign L4 "What needs you") +// clips-unwalked the draft's clips nobody walked, on a draft with a +// render or a walk begun (lib/inbox/walk.mjs) +// quote-check-stale clips the quote check no longer vouches for, with +// Run quote-check in place (lib/inbox/checks.mjs) +// case-new-cues a live research case's scope has new transcripts +// since its last candidate scan (lib/inbox/caseCues.mjs) +// +// (X's login when X work waits on it -- x-jar-stale, lib/inbox/xJar.mjs -- is a +// MACHINE call, lib/machine.ts, beside a missing tool: it is no piece's.) // // -- each row given its piece, category, group, one action, lifecycle and // `hidden` (lib/inbox/groups.mjs), ranked. One row per decision, never dropped: // the MCP reads `items[]` (mcp/src/archivalTools.ts). // // No editor call anywhere here: there is no "waiting on a cap" state (the daily -// cap refuses at start, a per-job cap ends the run), and running jobs are the -// rail's (lib/activity.ts readRunning). +// cap refuses at start, a per-job cap ends the run), and running jobs are +// home's Running list (lib/activity.ts readRunning). // // SERVER ONLY. // --------------------------------------------------------------------------- @@ -90,6 +104,8 @@ export type GroupCard = { what: string | null; action: { label: string; href: string }; at: number; + /** The one-press settle the card offers in place, when its rows agree on one (groups.mjs mergeSettle). */ + settle: Decision["settle"] | null; }; export type GroupSummary = { id: string; @@ -392,7 +408,9 @@ export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Pro .catch(() => [] as Decision[]); // Re-sweep when complete (UI notes item 16): a report video's source watch that fired. const sources = await sourceWatchDecisions().catch(() => [] as Decision[]); - return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts, ...proposals, ...refresh, ...recurring, ...sources]; + // What needs you (L4): versions to judge, clips to walk, stale quote checks, a live case's new transcripts. + const [calls, cases] = await Promise.all([projectCallsAll().catch(() => [] as Decision[]), caseCuesDecisions().catch(() => [] as Decision[])]); + return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts, ...proposals, ...refresh, ...recurring, ...sources, ...calls, ...cases]; } /** diff --git a/umtool/lib/inbox/caseCues.mjs b/umtool/lib/inbox/caseCues.mjs @@ -0,0 +1,63 @@ +// NEW TRANSCRIPTS ON A LIVE CASE (umtool redesign L4, "What needs you"): a +// research case with a pipeline (`<case>/pipeline.json`, common's caseTypes.ts) +// that is not done, whose candidate scan last ran at T, and whose scope's +// channels have recordings transcribed (or their captions written) since T -- +// "14 new transcripts since the last scan". Review group; its action the case's +// pipeline page, where Scan candidates runs the scan again. +// +// "Since the last refresh" is the candidates stage's last finished run +// (stages.json): that is the read of the corpus the case's windows come from. +// A case never scanned raises nothing -- there is no "since" to count from. +// +// Pure: lib/inbox/caseCues.ts lists the cases and counts the cues (the +// transcript index's per-video mtimes; a fixture with no index, the files). + +export const CASE_NEW_CUES = "case-new-cues"; + +/** + * The case's `since`: the candidates stage's last done run's end, as ms, or null. + * @param {Record<string, any> | null | undefined} stages readStages() + */ +export function lastScanOf(stages) { + const run = stages?.candidates; + if (!run || run.state !== "done") return null; + const ms = Date.parse(run.endedAt ?? run.startedAt ?? ""); + return Number.isFinite(ms) ? ms : null; +} + +/** + * The videos with cues newer than `since`: `{ channel, id, at }[]`, newest first. + * @param {Array<{ channel: string, id: string, at: number }>} rows + * @param {number} since + */ +export function newSince(rows, since) { + return (Array.isArray(rows) ? rows : []) + .filter((r) => r && Number.isFinite(r.at) && r.at > since) + .sort((a, b) => b.at - a.at || `${a.channel}/${a.id}`.localeCompare(`${b.channel}/${b.id}`)); +} + +/** + * One case's row, or null. + * + * @param {{ id: string, title: string, since: number, fresh: Array<{ channel: string, id: string, at: number }>, href: string }} o + */ +export function caseCuesDecision({ id, title, since, fresh, href }) { + const n = fresh?.length ?? 0; + if (!n) return null; + const channels = [...new Set(fresh.map((r) => r.channel))]; + const when = new Date(since).toISOString().slice(0, 16).replace("T", " "); + return { + project: `research/${id}`, + projectTitle: title, + // The case's piece (lib/research/cases.mjs casePieceId): a case has no lifecycle or mutes yet, so the + // Inbox draws no Park or Mute on its card. + piece: `c:${id}`, + kind: CASE_NEW_CUES, + target: id, + what: `${n} new transcript${n === 1 ? "" : "s"} since the last scan`, + why: `${n} new transcript${n === 1 ? "" : "s"} since the last scan · ${when} UTC · on ${channels.slice(0, 4).join(", ")}${channels.length > 4 ? ` and ${channels.length - 4} more` : ""} — scan the candidates again`, + href, + severity: "open", + at: fresh[0].at, + }; +} diff --git a/umtool/lib/inbox/caseCues.ts b/umtool/lib/inbox/caseCues.ts @@ -0,0 +1,131 @@ +import { existsSync } from "node:fs"; +import { readdir, stat } from "node:fs/promises"; +import path from "node:path"; +import { caseChannels } from "yt-dlp-transcript-common/controller/caseCorpus"; +import { readDefinition, readStages } from "yt-dlp-transcript-common/lib/research/caseStore-server"; +import type { Decision } from "@/lib/decisions"; +import { CHANNELS_DIR, REPORTS_ROOT } from "@/lib/paths.mjs"; +import { caseDir, isCaseId, readCase, researchDir } from "@/lib/research/cases.mjs"; +import { researchCasePipelineHref } from "@/lib/research/hrefs"; +import { corpusPaths } from "@/lib/research/pipeline"; +import { caseCuesDecision, lastScanOf, newSince } from "./caseCues.mjs"; + +// --------------------------------------------------------------------------- +// New transcripts on a live case, for the Inbox (lib/inbox/caseCues.mjs says +// what counts): every research case with a pipeline, not done, scanned at +// least once; its scope's channels (common's caseChannels) and, per video, +// when its cues were last written -- +// +// the transcript index's `mtimes` (key [channel, video] -> transcriptMs / +// subsMs, build-index's own record: channelSignature.ts reads the same) when +// the index is there -- a key range per channel, no file opened; +// else (a fixture, a corpus never indexed) the video directories' cue files. +// +// Kept per case and scan for ten minutes (new transcripts land in batches; the +// rail asks every ten seconds). A case that cannot be read adds nothing; this +// never throws. SERVER ONLY. +// --------------------------------------------------------------------------- + +const MEMO_MS = 10 * 60_000; +type Row = { channel: string; id: string; at: number }; +type Memo = Map<string, { at: number; value: Decision | null }>; +const g = globalThis as typeof globalThis & { __umtoolCaseCuesMemo?: Memo }; +const memo: Memo = (g.__umtoolCaseCuesMemo ??= new Map()); + +/** A cue file's name: the transcript and its sidecars, a caption track. */ +const CUE_FILE = /^(transcript\..+|.+\.vtt)$/; + +/** Per video of `slugs`, when its cues were last written (ms), from an index already open. */ +type MtimesDb = { getRange(o: { start: unknown; end: unknown }): Iterable<{ key: unknown; value: { transcriptMs?: number | null; subsMs?: number | null } }> }; +function fromIndex(mtimes: MtimesDb, slugs: string[]): Row[] { + const out: Row[] = []; + for (const slug of slugs) { + for (const { key, value } of mtimes.getRange({ start: [slug], end: [slug, "\uffff"] })) { + const k = key as [string, string]; + if (k[0] !== slug) break; + const at = Math.max(value?.transcriptMs ?? 0, value?.subsMs ?? 0); + if (at > 0) out.push({ channel: slug, id: k[1], at }); + } + } + return out; +} + +/** The same from the files: each video directory's newest cue file. */ +async function fromFiles(channelsDir: string, slugs: string[]): Promise<Row[]> { + const out: Row[] = []; + for (const slug of slugs) { + const data = path.join(/* turbopackIgnore: true */ channelsDir, slug, "data"); + const ids = await readdir(/* turbopackIgnore: true */ data, { withFileTypes: true }).catch(() => []); + for (const d of ids) { + if (!d.isDirectory() || d.name.startsWith(".")) continue; + const names = await readdir(/* turbopackIgnore: true */ path.join(data, d.name)).catch(() => [] as string[]); + let at = 0; + for (const n of names) { + if (!CUE_FILE.test(n)) continue; + const s = await stat(/* turbopackIgnore: true */ path.join(data, d.name, n)).catch(() => null); + if (s && s.mtimeMs > at) at = s.mtimeMs; + } + if (at > 0) out.push({ channel: slug, id: d.name, at }); + } + } + return out; +} + +async function caseRow(id: string, index: () => Promise<MtimesDb | null>): Promise<Decision | null> { + const dir = caseDir(REPORTS_ROOT, id); + const def = await readDefinition(dir, id); + if (!def || def.status === "done") return null; + const since = lastScanOf(await readStages(dir)); + if (since === null) return null; + const key = `${id}:${since}`; + const hit = memo.get(key); + if (hit && Date.now() - hit.at < MEMO_MS) return hit.value; + const paths = corpusPaths(); + const { slugs } = await caseChannels(paths, def); + const mtimes = await index(); + const rows = mtimes ? fromIndex(mtimes, slugs) : await fromFiles(CHANNELS_DIR, slugs); + const title = (await readCase(REPORTS_ROOT, id).catch(() => null))?.title ?? id; + const value = caseCuesDecision({ id, title, since, fresh: newSince(rows, since), href: researchCasePipelineHref(id) }) as Decision | null; + for (const k of memo.keys()) if (k.startsWith(`${id}:`)) memo.delete(k); + memo.set(key, { at: Date.now(), value }); + return value; +} + +/** Every live case's "N new transcripts since the last scan". Never throws. */ +export async function caseCuesDecisions(): Promise<Decision[]> { + try { + const names = await readdir(/* turbopackIgnore: true */ researchDir(REPORTS_ROOT), { withFileTypes: true }).catch(() => []); + const ids = names.filter((d) => d.isDirectory() && isCaseId(d.name)).map((d) => d.name); + if (!ids.length) return []; + // The index opened ONCE for every case (lmdb-js shares an environment by path: a close per case could + // end another case's range read), and the cases read one after another. + // Opened only when a case is not answered from the memo. + const lmdbPath = corpusPaths().lmdbPath; + type Env = { openDB: (o: object) => unknown; close: () => Promise<void> }; + let root = null as Env | null; + let opened: Promise<MtimesDb | null> | null = null; + const index = () => + (opened ??= (async () => { + if (!existsSync(/* turbopackIgnore: true */ lmdbPath)) return null; + try { + const { open } = await import("lmdb"); + root = open({ path: lmdbPath, readOnly: true, maxDbs: 14 }) as unknown as Env; + return root.openDB({ name: "mtimes", encoding: "msgpack" }) as MtimesDb; + } catch { + return null; + } + })()); + try { + const out: Decision[] = []; + for (const id of ids) { + const r = await caseRow(id, index).catch(() => null); + if (r) out.push(r); + } + return out; + } finally { + await root?.close().catch(() => {}); + } + } catch { + return []; + } +} diff --git a/umtool/lib/inbox/checks.mjs b/umtool/lib/inbox/checks.mjs @@ -0,0 +1,67 @@ +// QUOTE CHECKS GONE STALE (umtool redesign L4, "What needs you"): a project +// that uses the quote check (`<p>/quote-check.json`, lib/report/quoteCheck.mjs) +// and has clips the check no longer vouches for -- the cut or the quote changed +// since its row (rowIsCurrent), or a clip with a quote that was never checked +// -- is a call: one row per clip, one card per piece, its one-press action +// **Run quote-check** on those clips (the durable queue: it transcribes through +// the editor), its terminal twin `umtool quote-check <p> --clips a,b`. +// +// The failing rows themselves (moved, not-found) are the project reducer's, +// blocking: clip-quote-moved / clip-quote-missing (lib/projects/report.mjs), +// with their own one-press settles. A project with no quote-check.json raises +// nothing here: the check is opt-in. +// +// Pure: lib/inbox/projectCalls.ts reads the manifest and the file. +import { rowIsCurrent } from "../report/quoteCheck.mjs"; + +export const QUOTE_CHECK_STALE = "quote-check-stale"; + +/** + * The clips the check does not vouch for: `{ id, why: "stale" | "unchecked" }`, timeline order. + * @param {Array<Record<string, any>>} timeline + * @param {{ clips?: Record<string, any> } | null} doc readQuoteCheck() + */ +export function staleQuoteChecks(timeline, doc) { + const rows = doc?.clips && typeof doc.clips === "object" ? doc.clips : null; + if (!rows || !Object.keys(rows).length) return []; + const out = []; + for (const e of Array.isArray(timeline) ? timeline : []) { + if (e?.type !== "clip" || e.src || e.quoteRuled || !String(e.quote ?? "").trim()) continue; + const row = rows[e.id]; + if (!row) out.push({ id: String(e.id), why: "unchecked" }); + else if (!rowIsCurrent(row, e)) out.push({ id: String(e.id), why: "stale" }); + } + return out; +} + +/** + * The `quote-check-stale` rows of one project, each with the one-press settle + * for the whole set (the card's button runs the check on every clip it lists). + * + * @param {{ project: string, projectTitle: string, projectKind?: string, timeline: any[], doc: any, href: string, at: number }} o + */ +export function quoteCheckDecisions({ project, projectTitle, projectKind, timeline, doc, href, at }) { + const stale = staleQuoteChecks(timeline, doc); + if (!stale.length) return []; + const n = stale.length; + const what = `${n} quote check${n === 1 ? "" : "s"} out of date`; + const moved = stale.filter((s) => s.why === "stale").map((s) => s.id); + const never = stale.filter((s) => s.why === "unchecked").map((s) => s.id); + const list = (ids) => `${ids.slice(0, 6).join(", ")}${ids.length > 6 ? ` and ${ids.length - 6} more` : ""}`; + const why = [what, moved.length ? `cut or quote changed since: ${list(moved)}` : null, never.length ? `never checked: ${list(never)}` : null].filter(Boolean).join(" · "); + const clips = stale.map((s) => s.id); + return stale.map((s) => ({ + project, + projectTitle, + ...(projectKind ? { projectKind } : {}), + kind: QUOTE_CHECK_STALE, + target: s.id, + what, + why, + href, + severity: "open", + at, + fix: `umtool quote-check ${project} --clips ${clips.join(",")}`, + settle: { kind: "quote-check", clips: [s.id], label: "Run quote-check" }, + })); +} diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -71,6 +71,14 @@ const KIND_CATEGORY = { // claims, each waiting on the operator's approve or reject. "verdict-proposed": "review", "unreadable-proposals": "fix", + // The redesign's "What needs you" (L4): a rendered version nobody judged, + // the draft's clips nobody walked, a research case's new transcripts since + // its last scan -- each something to look at; X's login when X work waits + // on it -- a fix, like a missing tool. A stale quote check is an open call. + "version-unjudged": "review", + "clips-unwalked": "review", + "case-new-cues": "review", + "x-jar-stale": "fix", }; const CATEGORY_GROUP = { @@ -99,7 +107,7 @@ export function groupOf(d) { // Within a group: the brief's order first (proposals before failed runs), then // everything else as equals. -const KIND_RANK = { "worth-researching": 0, "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "tick-partial": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "verdict-proposed": 1, "unreadable-notes": 0, "unreadable-proposals": 0, "refresh-held": 2, "refresh-available": 2, "sources-complete": 2 }; +const KIND_RANK = { "worth-researching": 0, "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "tick-partial": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "verdict-proposed": 1, "unreadable-notes": 0, "unreadable-proposals": 0, "refresh-held": 2, "refresh-available": 2, "sources-complete": 2, "version-unjudged": 1, "case-new-cues": 2, "clips-unwalked": 3, "x-jar-stale": 0 }; const SEVERITY_RANK = { blocking: 0, open: 1, info: 2 }; // ONE primary action per decision, its button copy naming the result. @@ -159,6 +167,11 @@ const ACTION_LABEL = { "refresh-held": "Refresh", "refresh-available": "Refresh", "sources-complete": "Re-sweep", + "version-unjudged": "Play and judge", + "clips-unwalked": "Walk the clips", + "quote-check-stale": "Run quote-check", + "case-new-cues": "Scan again", + "x-jar-stale": "Refresh X's cookies", }; const CATEGORY_LABEL = { fix: "Fix it", choose: "Decide", info: "Open", spend: "Decide", review: "Review", note: "Answer note", finish: "Mark done" }; @@ -266,13 +279,35 @@ export function summarizeGroups(items) { what: d.what ?? null, action: d.action ?? actionOf(d), at: d.at ?? 0, + // The one-press settle the card offers in place (L4), when its rows agree on one. + settle: d.settle ?? null, }; cardOf.set(key, card); group.cards.push(card); - } + } else card.settle = mergeSettle(card.settle, d.settle ?? null); card.count += 1; if ((SEVERITY_RANK[d.severity] ?? 3) < (SEVERITY_RANK[card.severity] ?? 3)) card.severity = d.severity; card.at = Math.max(card.at, d.at ?? 0); } return out; } + +/** + * The settle a CARD offers for all its rows (umtool redesign L4: one-click + * actions in the Inbox), from two rows' (lib/decisions.ts `settle`): a quote + * check runs on every clip either names; the same project-wide settle (a link + * check, a publish) is kept; anything else -- two clip patches, two different + * presses -- is no settle, and the card's link is the way. A row without one + * leaves the card without one. + * + * @param {Record<string, any> | null} a + * @param {Record<string, any> | null} b + */ +export function mergeSettle(a, b) { + if (!a || !b) return null; + if (a.kind === "quote-check" && b.kind === "quote-check") { + return { ...a, clips: [...new Set([...(a.clips ?? []), ...(b.clips ?? [])])] }; + } + if (a.kind === "patch" || b.kind === "patch") return null; + return JSON.stringify(a) === JSON.stringify(b) ? a : null; +} diff --git a/umtool/lib/inbox/needs-you.test.ts b/umtool/lib/inbox/needs-you.test.ts @@ -0,0 +1,279 @@ +// "What needs you" (umtool redesign L4): the Inbox's new decision sources -- +// versions to judge, clips not walked, stale quote checks, a live case's new +// transcripts, X's jar -- as pure rows, then read from a temporary reports tree +// and a stand-in editor; and the card's one-press settle (groups.mjs mergeSettle). +// +// Run with: pnpm --filter umtool exec tsx --test lib/inbox/needs-you.test.ts +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { mkdtempSync } from "node:fs"; +import { mkdir, rm, utimes, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// The environment BEFORE any module that reads lib/paths.mjs is loaded (checks.mjs reaches it through +// quoteCheck.mjs): a static import would be hoisted above this and read the real ~/reports. +const tmp = mkdtempSync(path.join(os.tmpdir(), "umtool-needs-you-")); +process.env.CHANNELS_DIR = path.join(tmp, "channels"); +process.env.SITES_DIR = path.join(tmp, "sites"); +process.env.REPORTS_DIR = path.join(tmp, "reports"); +process.env.UMTOOL_XJAR_MEMO_MS = "0"; +const { VERSION_UNJUDGED, versionsDecisions, versionsToJudge } = await import("./versions.mjs"); +const { CLIPS_UNWALKED, walkDecisions } = await import("./walk.mjs"); +const { QUOTE_CHECK_STALE, quoteCheckDecisions, staleQuoteChecks } = await import("./checks.mjs"); +const { X_JAR_STALE, xJarDecision } = await import("./xJar.mjs"); +const { CASE_NEW_CUES, caseCuesDecision, lastScanOf, newSince } = await import("./caseCues.mjs"); +const { annotate, groupOf, mergeSettle, summarizeGroups } = await import("./groups.mjs"); +const { whatOf } = await import("./what.mjs"); + +const take = (id: string, o: Record<string, unknown> = {}) => ({ id, label: id, previewSize: 100, previewMtimeMs: 0, builtAt: "2026-11-01T10:00:00Z", draft: false, quick: false, version: true, seconds: 95, ...o }); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Row = { kind: string; severity: string; [k: string]: any }; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Any = any; +const annotated = (rows: Any[]): Row[] => annotate(rows as never[], { pieceOf: () => "p:x", lifecycleOf: () => "active" }) as Any[]; + +test("versions to judge: rendered (its preview there, whatever `draft` says), no verdict, not superseded, not a quick render or a skipped take -- newest first", () => { + const takes = [ + take("v1", { builtAt: "2026-11-01T10:00:00Z" }), + take("v2", { builtAt: "2026-11-03T10:00:00Z" }), + take("v3", { previewSize: null }), + take("d1", { draft: true, previewSize: null }), + take("d2", { draft: true, builtAt: "2026-10-25T10:00:00Z" }), + take("q1", { quick: true }), + take("liked"), + take("gone"), + take("clip"), + ]; + const verdicts = { liked: { verdict: "like" }, gone: { verdict: null, superseded: { by: "v2" } } }; + assert.deepEqual(versionsToJudge(takes, verdicts, { skip: (t) => t.id === "clip" }).map((t) => t.id), ["v2", "v1", "d2"]); + const rows = versionsDecisions({ project: "x", projectTitle: "X", takes, verdicts, playHref: (t) => `/projects/x/play?take=${t}`, skip: (t) => t.id === "clip", now: Date.parse("2026-11-04T00:00:00Z") }); + assert.equal(rows.length, 3); + assert.ok(rows.every((r) => r.kind === VERSION_UNJUDGED && r.href === "/projects/x/play?take=v2" && r.what === "3 versions to judge" && r.severity === "open")); + assert.match(rows[0].why, /^3 versions to judge · newest version v2 · 1:35 · rendered 2026-11-03/); + const [row] = annotated(rows); + assert.equal(groupOf(row), "review"); + assert.equal(row.action.label, "Play and judge"); + // A render nobody judged for two weeks is no longer waiting: Quiet, folded. + const later = versionsDecisions({ project: "x", projectTitle: "X", takes, verdicts, playHref: () => "/", skip: (t) => t.id === "clip", now: Date.parse("2026-11-16T12:00:00Z") }); + assert.deepEqual(later.map((r) => [r.target, r.severity, r.what]), [["v2", "open", "1 version to judge"], ["v1", "info", "2 versions to judge"], ["d2", "info", "2 versions to judge"]]); + assert.equal(later[1].href, "/"); + assert.equal(groupOf(later[1]), "quiet"); + assert.deepEqual(versionsDecisions({ project: "x", projectTitle: "X", takes: [], verdicts: {}, playHref: () => "/" }), []); + // Shapes it does not know are left out, never thrown on. + assert.deepEqual(versionsToJudge(null as never, null as never), []); +}); + +test("clips not walked: only on a draft going somewhere -- a walk begun or a render made; the bench on the first in walk order", () => { + const clips = [ + { id: "c03", verdict: "unreviewed" }, + { id: "c01", verdict: "confirmed" }, + { id: "c02", verdict: "unreviewed" }, + ]; + const base = { project: "x", projectTitle: "X", at: 5, now: 10, benchHref: (c: string) => `/projects/x/clip/${c}` }; + const rows = walkDecisions({ ...base, clips, rendered: false }); + assert.deepEqual(rows.map((r) => r.target), ["c03", "c02"]); + assert.ok(rows.every((r) => r.kind === CLIPS_UNWALKED && r.href === "/projects/x/clip/c03" && r.what === "2 clips not walked")); + assert.match(rows[0].why, /2 clips not walked · 1 of 3 walked · next c03 — c03, c02/); + // Never walked and never rendered: a cut in the making, not yet a call. + assert.deepEqual(walkDecisions({ ...base, clips: clips.map((c) => ({ ...c, verdict: "unreviewed" })), rendered: false }), []); + assert.equal(walkDecisions({ ...base, clips: clips.map((c) => ({ ...c, verdict: "unreviewed" })), rendered: true }).length, 3); + assert.deepEqual(walkDecisions({ ...base, clips: clips.map((c) => ({ ...c, verdict: "confirmed" })), rendered: true }), []); + const [row] = annotated(rows); + assert.deepEqual([groupOf(row), row.action.label, whatOf(CLIPS_UNWALKED)], ["review", "Walk the clips", "clips not walked"]); + // A draft untouched for two weeks: its walk is not waiting. + assert.ok(walkDecisions({ ...base, clips, rendered: false, now: 5 + 15 * 864e5 }).every((r) => r.severity === "info")); +}); + +test("stale quote checks: a clip whose cut or quote changed since its row, or never checked, on a project that uses the check", () => { + const clip = (id: string, start: number, o: Record<string, unknown> = {}) => ({ type: "clip", id, video: "v", start, end: start + 5, quote: `Line ${start}`, ...o }); + const row = (start: number, status = "ok") => ({ status, cut: { from: start, to: start + 5 }, quote: `Line ${start}` }); + const timeline = [clip("a", 10), clip("b", 20, { cutStart: 21 }), clip("c", 30), clip("d", 40, { quoteRuled: true }), clip("e", 50, { quote: "" }), { type: "card", id: "k1" }]; + const doc: Any = { version: 1, clips: { a: row(10), b: row(20, "moved"), d: row(1) } }; + assert.deepEqual(staleQuoteChecks(timeline, doc), [ + { id: "b", why: "stale" }, + { id: "c", why: "unchecked" }, + ]); + // No quote-check.json (or an empty one): the check is opt-in, nothing to say. + assert.deepEqual(staleQuoteChecks(timeline, { clips: {} }), []); + assert.deepEqual(staleQuoteChecks(timeline, null), []); + const rows = quoteCheckDecisions({ project: "x", projectTitle: "X", timeline, doc, href: "/projects/x", at: 1 }); + assert.deepEqual(rows.map((r) => [r.kind, r.target, r.settle]), [ + [QUOTE_CHECK_STALE, "b", { kind: "quote-check", clips: ["b"], label: "Run quote-check" }], + [QUOTE_CHECK_STALE, "c", { kind: "quote-check", clips: ["c"], label: "Run quote-check" }], + ]); + assert.equal(rows[0].fix, "umtool quote-check x --clips b,c"); + assert.match(rows[0].why, /2 quote checks out of date · cut or quote changed since: b · never checked: c/); + // One card, one press over every clip it lists. + const [g] = (summarizeGroups(annotated(rows)) as Any[]).filter((x) => x.cards.length); + assert.equal(g.id, "open"); + assert.deepEqual(g.cards[0].settle, { kind: "quote-check", clips: ["b", "c"], label: "Run quote-check" }); + assert.equal(g.cards[0].action.label, "Run quote-check"); +}); + +test("a card's settle: one quote check over every clip; the same project-wide press kept; two patches, or a row without one, none", () => { + const q = (c: string) => ({ kind: "quote-check", clips: [c], label: "Run quote-check" }); + const links = { kind: "check-links", fix: true, label: "Use embed ids (2)" }; + assert.deepEqual(mergeSettle(q("a"), q("b")), { kind: "quote-check", clips: ["a", "b"], label: "Run quote-check" }); + assert.deepEqual(mergeSettle(links, { ...links }), links); + assert.equal(mergeSettle({ kind: "patch", clip: "a", patch: {}, label: "x" }, { kind: "patch", clip: "b", patch: {}, label: "x" }), null); + assert.equal(mergeSettle(links, null), null); + assert.equal(mergeSettle(links, { kind: "check-links", label: "Check links" }), null); +}); + +test("X's jar: a row only when an X alert is up (X work waits) -- the editor's three lines, Blocking", () => { + const x = { source: "profile", ageMinutes: 190, maxAgeMinutes: 60, fresh: false, loggedIn: true, at: null, readAt: "", summary: "" }; + const alert = { service: "x", label: "X", family: "x", state: "stale", kind: "jar-age", raisedAt: "2026-11-09T10:00:00Z", headline: "X cookies are 3 h old (limit 60 min)", fix: "Refresh cookies (or Connect X account) on /settings — then Recheck.", detail: "2 X jobs are queued." }; + assert.equal(xJarDecision({ alerts: [], x }, { href: "/s" }), null); + assert.equal(xJarDecision({ alerts: [{ ...alert, state: "ok-again" }], x }, { href: "/s" }), null); + assert.equal(xJarDecision({ alerts: [{ ...alert, family: "ytdlp", service: "rumble" }], x }, { href: "/s" }), null); + assert.equal(xJarDecision("not a payload", { href: "/s" }), null); + const row = xJarDecision({ alerts: [alert], x }, { href: "http://editor/settings" }); + assert.ok(row); + assert.equal(row.kind, X_JAR_STALE); + assert.equal(row.severity, "blocking"); + assert.equal(row.why, "X cookies are 3 h old (limit 60 min) Refresh cookies (or Connect X account) on /settings — then Recheck. 2 X jobs are queued."); + assert.equal(row.at, Date.parse("2026-11-09T10:00:00Z")); + const [a] = annotate([row], { pieceOf: () => null, lifecycleOf: () => "active" }); + assert.deepEqual([a.group, a.action.label, a.hidden], ["blocking", "Refresh X's cookies", false]); +}); + +test("a live case's new transcripts: since its last done candidate scan; none before one ran", () => { + assert.equal(lastScanOf({}), null); + assert.equal(lastScanOf({ candidates: { state: "running", startedAt: "2026-11-01T00:00:00Z" } }), null); + const since = lastScanOf({ candidates: { state: "done", startedAt: "2026-11-01T00:00:00Z", endedAt: "2026-11-01T00:05:00Z" } }); + assert.equal(since, Date.parse("2026-11-01T00:05:00Z")); + const rows = [ + { channel: "a", id: "old", at: since! - 1 }, + { channel: "a", id: "new1", at: since! + 10 }, + { channel: "b", id: "new2", at: since! + 20 }, + ]; + const fresh = newSince(rows, since!); + assert.deepEqual(fresh.map((r) => r.id), ["new2", "new1"]); + const row = caseCuesDecision({ id: "lighthouse", title: "Lighthouse", since: since!, fresh, href: "/research/lighthouse/pipeline" }); + assert.ok(row); + assert.deepEqual([row.kind, row.target, row.what, row.at], [CASE_NEW_CUES, "lighthouse", "2 new transcripts since the last scan", since! + 20]); + assert.match(row.why, /since the last scan · 2026-11-01 00:05 UTC · on b, a — scan the candidates again/); + assert.equal(caseCuesDecision({ id: "x", title: "x", since: since!, fresh: [], href: "/" }), null); + const [a] = annotate([row], { pieceOf: () => null, lifecycleOf: () => "active" }); + assert.deepEqual([a.group, a.action.label], ["review", "Scan again"]); +}); + +// ─── read from disk and from a stand-in editor ──────────────────────────────── + +let editor: Server; +let services: unknown = { ok: true, alerts: [], pending: [] }; + +before(async () => { + editor = createServer((req, res) => { + res.setHeader("content-type", "application/json"); + if (req.url?.startsWith("/api/ops/services")) return res.end(JSON.stringify(services)); + res.statusCode = 404; + res.end(JSON.stringify({ ok: false, error: "no route" })); + }); + await new Promise<void>((r) => editor.listen(0, "127.0.0.1", r)); + process.env.ARCHILYZER_EDITOR_URL = `http://127.0.0.1:${(editor.address() as AddressInfo).port}`; + process.env.WORKER_TOKEN = "t"; + + // A report video with two rendered versions (one judged), a walk begun, and a quote check gone stale. + const p = path.join(tmp, "reports", "ny-cut"); + const clip = (id: string, start: number, o: Record<string, unknown> = {}) => ({ type: "clip", id, video: "vid", start, end: start + 4, cite: start, quote: `Line ${start}`, ...o }); + await mkdir(p, { recursive: true }); + await writeFile( + path.join(p, "video.manifest.json"), + JSON.stringify({ schemaVersion: 1, slug: "ny-cut", title: "The NY Cut", provenance: { channelSlug: "nychan" }, render: { width: 1920, height: 1080, fps: 30 }, timeline: [clip("c01", 10, { verdict: "confirmed" }), clip("c02", 20), clip("c03", 30)] }), + ); + for (const [id, order] of [["v1", 1], ["v2", 2]] as const) { + await mkdir(path.join(p, "takes", id), { recursive: true }); + await writeFile(path.join(p, "takes", id, "take.json"), JSON.stringify({ id, group: "cut", order, label: `Version ${order}`, kind: "similar", preview: "preview.mp4", version: true, window: "full", builtAt: new Date(Date.now() - (3 - order) * 864e5).toISOString() })); + await writeFile(path.join(p, "takes", id, "preview.mp4"), "mp4"); + } + await writeFile(path.join(p, "takes", "verdicts.json"), JSON.stringify({ v1: { verdict: "like", note: "", at: "2026-11-02T00:00:00Z" } })); + await writeFile(path.join(p, "quote-check.json"), JSON.stringify({ version: 1, clips: { c02: { status: "ok", cut: { from: 19, to: 24 }, quote: "Line 20" } } })); + + // A live case scanned on 1 Nov, its channel transcribed once before and twice after. + const c = path.join(tmp, "reports", ".umtool", "research", "ny-case"); + await mkdir(c, { recursive: true }); + const now = "2026-11-01T00:00:00Z"; + await writeFile(path.join(c, "case.json"), JSON.stringify({ format: "umtool-research-case", version: 1, id: "ny-case", title: "The NY Case", scope: { source: "local" }, search: null, sessions: [], sections: [], quotes: [], notes: "", handoffs: [], counters: { quote: 0, section: 0 }, createdAt: now, updatedAt: now })); + await writeFile(path.join(c, "pipeline.json"), JSON.stringify({ format: "archilyzer-case-pipeline", version: 1, case: "ny-case", subjects: [], scope: { channels: ["nychan"], groups: [], sites: [] }, eras: [], groups: [], privateNames: { sha256: [], note: "" }, readerPrompts: { common: "" }, status: "reading", createdAt: now, updatedAt: now })); + await writeFile(path.join(c, "stages.json"), JSON.stringify({ candidates: { state: "done", startedAt: now, endedAt: "2026-11-01T00:05:00Z", by: "cli", pid: 1, log: [] } })); + for (const [id, when] of [["old", "2026-10-20T00:00:00Z"], ["new1", "2026-11-03T00:00:00Z"], ["new2", "2026-11-04T00:00:00Z"]]) { + const d = path.join(tmp, "channels", "nychan", "data", id); + await mkdir(d, { recursive: true }); + await writeFile(path.join(d, "transcript.cues.json"), "{}"); + await utimes(path.join(d, "transcript.cues.json"), new Date(when), new Date(when)); + } +}); + +after(async () => { + editor?.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +test("from disk: the report video's version to judge, its clips not walked, its stale quote check -- each kind once per row", async () => { + const { projectCallsAll } = await import("./projectCalls"); + const rows = (await projectCallsAll()).filter((d) => d.project === "ny-cut"); + const of = (k: string) => rows.filter((d) => d.kind === k).map((d) => d.target); + assert.deepEqual(of(VERSION_UNJUDGED), ["v2"]); + assert.equal(rows.find((d) => d.kind === VERSION_UNJUDGED)?.href, "/projects/ny-cut/play?take=v2"); + assert.deepEqual(of(CLIPS_UNWALKED), ["c02", "c03"]); + assert.equal(rows.find((d) => d.kind === CLIPS_UNWALKED)?.href, "/projects/ny-cut/clip/c02"); + // c02's row is for a cut it no longer plays; c01 and c03 were never checked. + assert.deepEqual(of(QUOTE_CHECK_STALE), ["c01", "c02", "c03"]); + assert.ok(rows.every((d) => d.projectTitle === "The NY Cut")); + // Read again with nothing changed: the same rows (the memo), and judging v2 drops it. + assert.deepEqual((await projectCallsAll()).filter((d) => d.project === "ny-cut"), rows); + await writeFile(path.join(tmp, "reports", "ny-cut", "takes", "verdicts.json"), JSON.stringify({ v1: { verdict: "like", note: "", at: "x" }, v2: { verdict: "maybe", note: "", at: "y" } })); + assert.deepEqual((await projectCallsAll()).filter((d) => d.project === "ny-cut" && d.kind === VERSION_UNJUDGED), []); +}); + +test("from disk: the live case's two new transcripts since its scan (the files, with no index)", async () => { + const { caseCuesDecisions } = await import("./caseCues"); + const [row] = await caseCuesDecisions(); + assert.ok(row); + assert.deepEqual([row.kind, row.project, row.projectTitle, row.href, row.piece], [CASE_NEW_CUES, "research/ny-case", "The NY Case", "/research/ny-case/pipeline", "c:ny-case"]); + assert.equal(row.what, "2 new transcripts since the last scan"); +}); + +test("from the editor: no row while no X work waits; the row once the jar's alert is up; none when the editor is gone", async () => { + const { xJarDecisions } = await import("./xJar"); + assert.deepEqual(await xJarDecisions(), []); + services = { ok: true, alerts: [{ service: "x", label: "X", family: "x", state: "stale", kind: "jar-age", raisedAt: "2026-11-09T10:00:00Z", headline: "X cookies are 3 h old", fix: "Refresh cookies on /settings — then Recheck.", detail: "" }], pending: [] }; + const [row] = await xJarDecisions(); + assert.equal(row?.kind, X_JAR_STALE); + assert.equal(row?.href, `${process.env.ARCHILYZER_EDITOR_URL}/settings`); + await new Promise<void>((r) => editor.close(() => r())); + assert.deepEqual(await xJarDecisions(), []); +}); + +test("the one-press routes refuse another site's write (sameOrigin.mjs) and still take this app's own", async () => { + const routes = [ + { mod: await import("../../app/api/report/links/route"), method: "POST" as const, body: { project: "ny-cut", fix: true } }, + { mod: await import("../../app/api/report/takes/verdict/route"), method: "POST" as const, body: { project: "ny-cut", take: "v2", verdict: "like" } }, + { mod: await import("../../app/api/report/window/route"), method: "PUT" as const, body: { project: "ny-cut", clip: "c02", lockCut: true } }, + // Home's Quick clip render (it starts a job) and the timeline's writes (Add clip). + { mod: await import("../../app/api/report/quick-clip/route"), method: "POST" as const, body: { spec: "nychan/nyfresh@1-2" } }, + { mod: await import("../../app/api/report/timeline/route"), method: "POST" as const, body: { project: "ny-cut", op: "remove", id: "c03" } }, + ]; + for (const { mod, method, body } of routes) { + const handler = (mod as unknown as Record<string, (r: Request) => Promise<Response>>)[method]; + // A text/plain form post from evil.example to this app: no preflight, refused before the body is read. + const cross = await handler( + new Request("http://localhost:3050/api/x", { method, headers: { host: "localhost:3050", origin: "https://evil.example", "sec-fetch-site": "cross-site", "content-type": "text/plain" }, body: JSON.stringify(body) }), + ); + assert.equal(cross.status, 403, method); + assert.match(((await cross.json()) as { error: string }).error, /refused/); + // A rebinding page (Host: evil.example) is refused too. + const rebound = await handler(new Request("http://evil.example/api/x", { method, headers: { host: "evil.example:3050" }, body: JSON.stringify(body) })); + assert.equal(rebound.status, 403); + } + // This app's own page (same-origin) gets past the guard: the verdict is written. + const verdict = (await import("../../app/api/report/takes/verdict/route")) as unknown as { POST: (r: Request) => Promise<Response> }; + const own = await verdict.POST( + new Request("http://localhost:3050/api/report/takes/verdict", { method: "POST", headers: { host: "localhost:3050", origin: "http://localhost:3050", "sec-fetch-site": "same-origin", "content-type": "application/json" }, body: JSON.stringify({ project: "ny-cut", take: "v2", verdict: "no" }) }), + ); + assert.equal(own.status, 200, await own.clone().text()); +}); diff --git a/umtool/lib/inbox/projectCalls.ts b/umtool/lib/inbox/projectCalls.ts @@ -0,0 +1,124 @@ +import { stat, readdir } from "node:fs/promises"; +import path from "node:path"; +import type { Decision } from "@/lib/decisions"; +import { clipBenchHref, playHref, projectHref } from "@/lib/hrefs"; +import { projectRefs } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { readManifest, reviewOf, walkOrder } from "@/lib/projects/report.mjs"; +import type { ProjectRef } from "@/lib/project-types"; +import { QUOTE_CHECK_FILE, readQuoteCheck } from "@/lib/report/quoteCheck.mjs"; +import { QUICK_CLIP_FOLDER, QUICK_CLIP_TAKE } from "@/lib/report/quickClip.mjs"; +import { listTakes, readVerdicts, takesDirOf, verdictsFileOf } from "@/lib/report/takes.mjs"; +import { quoteCheckDecisions } from "./checks.mjs"; +import { versionsDecisions } from "./versions.mjs"; +import { walkDecisions } from "./walk.mjs"; + +// --------------------------------------------------------------------------- +// A REPORT VIDEO'S CALLS THE REDUCER DOES NOT MAKE (umtool redesign L4, "What +// needs you"), read from its disk for the Inbox: +// +// version-unjudged a rendered version (or legacy take) with no verdict +// (lib/inbox/versions.mjs) -- Play and judge +// clips-unwalked the draft's clips with no walk verdict, on a draft that +// is going somewhere (lib/inbox/walk.mjs) -- Walk +// quote-check-stale clips the quote check no longer vouches for +// (lib/inbox/checks.mjs) -- Run quote-check +// +// One project that cannot be read adds nothing; nothing here throws. Each +// project's rows are kept against a signature of the files they come from +// (the manifest, quote-check.json, takes/ and each take's directory, the +// verdicts), on globalThis: one cache per process, not per Next bundle. +// SERVER ONLY. +// --------------------------------------------------------------------------- + +type Memo = Map<string, { sig: string; value: Decision[] }>; +const g = globalThis as typeof globalThis & { __umtoolProjectCallsMemo?: Memo }; +const memo: Memo = (g.__umtoolProjectCallsMemo ??= new Map()); + +const stamp = async (file: string) => { + const s = await stat(/* turbopackIgnore: true */ file).catch(() => null); + return s ? `${Math.round(s.mtimeMs)}.${s.size}` : "-"; +}; + +async function signatureOf(dir: string): Promise<string> { + const takes = takesDirOf(dir); + const entries = await readdir(/* turbopackIgnore: true */ takes).catch(() => [] as string[]); + const per = await Promise.all(entries.filter((n) => !n.startsWith(".")).sort().map(async (n) => `${n}@${await stamp(path.join(takes, n))}`)); + const [man, qc, verdicts] = await Promise.all([stamp(path.join(dir, "video.manifest.json")), stamp(path.join(dir, QUOTE_CHECK_FILE)), stamp(verdictsFileOf(dir))]); + // A coarse clock too: versions.mjs and walk.mjs age rows into Quiet at RECENT_DAYS, which no file says. + const bucket = Math.floor(Date.now() / (6 * 3600_000)); + return [man, qc, verdicts, per.join(","), bucket].join("|"); +} + +/** A quick clip's project (lib/report/quickClip.mjs: `<reports>/quick-clips/<slug>`): a share, not a piece in the making. */ +const isQuickClip = (ref: ProjectRef) => ref.id.startsWith(`${QUICK_CLIP_FOLDER}/`); +/** A take a quick clip made: a share, not a version to judge. */ +const isQuickClipTake = (ref: ProjectRef, take: { id: string }) => take.id === QUICK_CLIP_TAKE && isQuickClip(ref); + +async function callsOf(ref: ProjectRef): Promise<Decision[]> { + // A quick clip is shared, not judged or walked: no calls. + if (isQuickClip(ref)) return []; + const manifest = (await readManifest(ref.dir)) as Record<string, unknown> | null; + const title = typeof manifest?.title === "string" && manifest.title ? manifest.title : ref.name; + const base = { project: ref.id, projectTitle: title, projectKind: ref.kind }; + const [{ takes }, verdicts] = await Promise.all([listTakes(ref.dir), readVerdicts(ref.dir)]); + const out: Decision[] = []; + + out.push( + ...(versionsDecisions({ + ...base, + takes, + verdicts, + playHref: (take: string) => playHref(ref.id, { take }), + skip: (t: Record<string, unknown>) => isQuickClipTake(ref, { id: String(t.id) }), + }) as Decision[]), + ); + + if (manifest) { + const timeline = (manifest.timeline ?? []) as Record<string, unknown>[]; + const review = reviewOf(manifest); + const verdictOf = new Map(review.clips.map((c: { id: string; verdict: string }) => [c.id, c.verdict])); + const clips = walkOrder(timeline).map((e: { id: string }) => ({ id: String(e.id), verdict: verdictOf.get(e.id) ?? "unreviewed" })); + const rendered = takes.some((t: { previewSize: number | null; version: boolean }) => t.previewSize != null || t.version); + const at = await stat(/* turbopackIgnore: true */ path.join(ref.dir, "video.manifest.json")).then((s) => s.mtimeMs, () => 0); + out.push(...(walkDecisions({ ...base, clips, rendered, at, benchHref: (clip: string) => clipBenchHref(ref.id, clip) }) as Decision[])); + const doc = await readQuoteCheck(ref.dir); + const checkedAt = Date.parse(String((doc as { checkedAt?: string }).checkedAt ?? "")) || at; + out.push(...(quoteCheckDecisions({ ...base, timeline, doc, href: projectHref(ref.id), at: checkedAt }) as Decision[])); + } + return out; +} + +async function projectCalls(ref: ProjectRef): Promise<Decision[]> { + const sig = await signatureOf(ref.dir); + const hit = memo.get(ref.id); + if (hit && hit.sig === sig) return hit.value; + const value = await callsOf(ref).catch(() => [] as Decision[]); + memo.set(ref.id, { sig, value }); + return value; +} + +// One read at a time: the page and the rail's count ask together, and share it. +const gi = globalThis as typeof globalThis & { __umtoolProjectCallsInflight?: Promise<Decision[]> | null }; + +/** Every report video's versions to judge, clips not walked and stale quote checks. Never throws. */ +export function projectCallsAll(): Promise<Decision[]> { + if (gi.__umtoolProjectCallsInflight) return gi.__umtoolProjectCallsInflight; + const p = readAll().finally(() => { + if (gi.__umtoolProjectCallsInflight === p) gi.__umtoolProjectCallsInflight = null; + }); + gi.__umtoolProjectCallsInflight = p; + return p; +} + +async function readAll(): Promise<Decision[]> { + try { + const refs = (await projectRefs()).filter((r) => kindMakesTakes(r.kind)); + const live = new Set(refs.map((r) => r.id)); + for (const id of memo.keys()) if (!live.has(id)) memo.delete(id); + const per = await Promise.all(refs.map((r) => projectCalls(r).catch(() => [] as Decision[]))); + return per.flat(); + } catch { + return []; + } +} diff --git a/umtool/lib/inbox/versions.mjs b/umtool/lib/inbox/versions.mjs @@ -0,0 +1,94 @@ +// VERSIONS TO JUDGE (umtool redesign L4, "What needs you"): a saved version +// (lib/report/versions.mjs) -- or a legacy take -- that has a RENDER and no +// verdict is a call in the Inbox's Review group. One row per version (the API +// keeps one row per decision), one card per piece ("3 versions to judge"), its +// action Play and judge: Play on the newest of them (`?take=`), where the +// verdict buttons are. +// +// Not a version to judge: one with no render on disk (a saved version not yet +// rendered, a draft take -- `previewSize` null), a quick draft-quality +// render, a superseded take (folded away by a person), and a quick clip's one +// take (a share, not a version -- lib/report/quickClip.mjs). "Rendered" is the +// preview file being there, whatever take.json's `draft` says. +// +// Pure: lib/inbox/projectCalls.ts reads the takes and verdicts and hands them +// here. Never throws on a shape it does not know: it is left out. + +export const VERSION_UNJUDGED = "version-unjudged"; +/** + * A render older than this that nobody judged is no longer waiting: its rows are `info` (the Quiet group, + * folded) rather than Review -- on the real tree (9 Nov) 46 projects had a render with no verdict, 18 of them + * from the last two weeks. + */ +export const RECENT_DAYS = 14; + +const timeOf = (t) => { + const ms = Date.parse(t?.builtAt ?? t?.savedAt ?? ""); + if (Number.isFinite(ms)) return ms; + return Number.isFinite(t?.previewMtimeMs) ? t.previewMtimeMs : 0; +}; + +/** + * The takes that wait on a verdict, newest first. + * + * @param {Array<Record<string, any>>} takes listTakes()'s takes + * @param {Record<string, { verdict?: string | null, superseded?: unknown }>} verdicts readVerdicts() + * @param {{ skip?: (take: Record<string, any>) => boolean }} [o] + */ +export function versionsToJudge(takes, verdicts, { skip = () => false } = {}) { + const v = verdicts && typeof verdicts === "object" ? verdicts : {}; + return (Array.isArray(takes) ? takes : []) + .filter((t) => t && typeof t.id === "string") + .filter((t) => t.previewSize != null && t.quick !== true) + .filter((t) => !v[t.id]?.verdict && !v[t.id]?.superseded) + .filter((t) => !skip(t)) + .sort((a, b) => timeOf(b) - timeOf(a) || String(a.id).localeCompare(String(b.id))); +} + +/** The card's title: how many wait. */ +export function versionsWhat(waiting) { + const n = waiting.length; + return `${n} version${n === 1 ? "" : "s"} to judge`; +} + +const day = (ms) => (ms ? new Date(ms).toISOString().slice(0, 10) : null); +const mins = (s) => (Number.isFinite(s) && s > 0 ? `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, "0")}` : null); + +/** + * The `version-unjudged` rows of one project. + * + * @param {{ + * project: string, projectTitle: string, projectKind?: string, + * takes: Array<Record<string, any>>, verdicts: Record<string, any>, + * playHref: (take: string) => string, + * skip?: (take: Record<string, any>) => boolean, + * now?: number, + * }} o + */ +export function versionsDecisions({ project, projectTitle, projectKind, takes, verdicts, playHref, skip, now = Date.now() }) { + const waiting = versionsToJudge(takes, verdicts, { skip }); + if (!waiting.length) return []; + const old = (t) => now - timeOf(t) > RECENT_DAYS * 864e5; + // Two cards at most: the recent renders (Review) and the older ones (Quiet), each counted and named by its own. + return [waiting.filter((t) => !old(t)), waiting.filter(old)].flatMap((rows) => { + if (!rows.length) return []; + const what = versionsWhat(rows); + // The card's sentence is its newest row's (summarizeGroups keeps the first, ranked newest first). + const newest = rows[0]; + const href = playHref(newest.id); + const facts = [`${newest.version ? "version" : "take"} ${newest.id}`, newest.label && newest.label !== newest.id ? `“${newest.label}”` : null, mins(newest.seconds), day(timeOf(newest)) ? `rendered ${day(timeOf(newest))}` : null]; + const why = `${what} · newest ${facts.filter(Boolean).join(" · ")} — play it and say like, maybe or no`; + return rows.map((t) => ({ + project, + projectTitle, + ...(projectKind ? { projectKind } : {}), + kind: VERSION_UNJUDGED, + target: t.id, + what, + why, + href, + severity: old(t) ? "info" : "open", + at: timeOf(t), + })); + }); +} diff --git a/umtool/lib/inbox/walk.mjs b/umtool/lib/inbox/walk.mjs @@ -0,0 +1,70 @@ +// CLIPS NOT WALKED (umtool redesign L4, "What needs you"): the working draft's +// clips with no walk verdict (lib/projects/report.mjs reviewOf: "unreviewed") +// are a call in the Review group -- one row per clip, one card per piece +// ("12 clips not walked"), its action the clip bench on the first of them in +// walk order (by source, then start: report.mjs walkOrder), the one that is +// fetched first when any is. +// +// Only a draft that is GOING somewhere is waiting on a walk: one whose walk has +// begun (a clip has a verdict), or that has a rendered take or a saved version. +// A cut still being assembled, never walked and never rendered, is not yet a +// call -- 78 of the 91 real report projects have unwalked clips (9 Nov), and an +// Inbox that lists every cut in the making is one nobody reads. And a draft +// nobody has edited for RECENT_DAYS is not waiting either: its rows are `info` +// (the Quiet group, folded), 43 projects down to 12 on the real tree. +// +// Pure: lib/inbox/projectCalls.ts reads the manifest and the takes and hands +// the walk's rows here. + +export const CLIPS_UNWALKED = "clips-unwalked"; +/** A draft not edited for this long is no longer waiting on its walk: `info` (Quiet, folded) -- versions.mjs's rule. */ +export { RECENT_DAYS } from "./versions.mjs"; +import { RECENT_DAYS } from "./versions.mjs"; + +/** The card's title. */ +export function walkWhat(n) { + return `${n} clip${n === 1 ? "" : "s"} not walked`; +} + +/** + * The `clips-unwalked` rows of one project. + * + * `clips` in WALK order (reviewOf's rows, walkOrder); `rendered`: the project + * has a rendered take or a saved version. + * + * @param {{ + * project: string, projectTitle: string, projectKind?: string, + * clips: Array<{ id: string, verdict: string, fetched?: boolean }>, + * rendered: boolean, + * at: number, + * benchHref: (clip: string) => string, + * now?: number, + * }} o + */ +export function walkDecisions({ project, projectTitle, projectKind, clips, rendered, at, benchHref, now = Date.now() }) { + const rows = (Array.isArray(clips) ? clips : []).filter((c) => c && typeof c.id === "string"); + const waiting = rows.filter((c) => c.verdict === "unreviewed"); + if (!waiting.length) return []; + const walked = rows.length - waiting.length; + if (!walked && !rendered) return []; + const first = waiting.find((c) => c.fetched) ?? waiting[0]; + const what = walkWhat(waiting.length); + const ids = waiting.map((c) => c.id); + const why = + `${what} · ${walked} of ${rows.length} walked · next ${first.id}` + + `${first.fetched === false && !waiting.some((c) => c.fetched) ? " (not fetched yet)" : ""}` + + ` — ${ids.slice(0, 6).join(", ")}${ids.length > 6 ? ` and ${ids.length - 6} more` : ""}`; + const href = benchHref(first.id); + return waiting.map((c) => ({ + project, + projectTitle, + ...(projectKind ? { projectKind } : {}), + kind: CLIPS_UNWALKED, + target: c.id, + what, + why, + href, + severity: now - at > RECENT_DAYS * 864e5 ? "info" : "open", + at, + })); +} diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -61,6 +61,13 @@ export const WHAT = { "ambiguous-project": "two kinds match", "machine-tool": "a required tool is missing", "machine-disk": "disk nearly full", + "version-unjudged": "versions to judge", + "clips-unwalked": "clips not walked", + "quote-check-stale": "quote checks out of date", + "case-new-cues": "new transcripts since the last scan", + "x-jar-stale": "X's cookies are stale and X work waits", + "clip-quote-moved": "quotes heard away from the cut", + "clip-quote-missing": "quotes not heard in the cut", }; /** A kind's words; an unknown kind reads as its id with spaces. */ diff --git a/umtool/lib/inbox/xJar.mjs b/umtool/lib/inbox/xJar.mjs @@ -0,0 +1,41 @@ +// X'S LOGIN, WHEN X WORK WAITS (umtool redesign L4, "What needs you"): the +// editor's cookie alerts (`GET /api/ops/services`, editor/app/lib/cookieAlerts.ts +// over common/lib/serviceCookies.ts) carry X's jar age always, and an ALERT only +// when the jar refused an X job or X jobs are queued behind it -- the rule the +// editor's own banner draws by. So the Inbox shows the jar only when there is a +// stale alert of X's family: one Blocking card (a MACHINE call, lib/machine.ts: +// no piece's), the editor's three short lines +// (how old, the one thing to do, what it refused), its action the editor's +// settings, where Refresh cookies / Connect X account and Recheck are. +// +// Nothing here asks X anything, and nothing refreshes the jar: a refresh is a +// human click in the editor. Pure: lib/inbox/xJar.ts asks the editor. + +export const X_JAR_STALE = "x-jar-stale"; + +/** + * The row, or null when no X work waits (or the payload is not one). + * + * @param {unknown} payload the services route's answer + * @param {{ href: string, now?: number }} o + */ +export function xJarDecision(payload, { href, now = Date.now() }) { + const p = /** @type {Record<string, any> | null} */ (payload && typeof payload === "object" ? payload : null); + const alerts = Array.isArray(p?.alerts) ? p.alerts : []; + const x = alerts.find((a) => a && a.family === "x" && a.state === "stale"); + if (!x) return null; + const jar = p?.x && typeof p.x === "object" ? p.x : null; + const lines = [x.headline, x.fix, x.detail].map((s) => (typeof s === "string" ? s.trim() : "")).filter(Boolean); + const at = Date.parse(x.raisedAt ?? x.since ?? "") || now; + return { + project: "editor", + projectTitle: x.label ? `${x.label} login` : "X login", + kind: X_JAR_STALE, + target: x.service ?? "x", + why: lines.length ? lines.join(" ") : "X's cookies are past their age limit — refresh them on the editor's settings", + href, + severity: "blocking", + at, + ...(jar && Number.isFinite(jar.ageMinutes) ? { ageMinutes: jar.ageMinutes } : {}), + }; +} diff --git a/umtool/lib/inbox/xJar.ts b/umtool/lib/inbox/xJar.ts @@ -0,0 +1,46 @@ +import type { Decision } from "@/lib/decisions"; +import { askEditor, editorUrl } from "@/lib/articles/generation"; +import { xJarDecision } from "./xJar.mjs"; + +// --------------------------------------------------------------------------- +// X's jar, for the Inbox (lib/inbox/xJar.mjs says when it is a call): the +// editor's services route asked through umtool's editor client (askEditor, +// its WORKER_TOKEN), answered from a minute's memo, and never waited on for +// more than WAIT_MS (0.4 s) -- the Inbox and the rail's count read it, and an editor +// that is slow or down must not slow them. Any failure is no row. SERVER ONLY. +// --------------------------------------------------------------------------- + +/** UMTOOL_XJAR_MEMO_MS (the e2e suite's 0: each read asks the stub), else a minute. */ +const memoMs = () => { + const v = Number(process.env.UMTOOL_XJAR_MEMO_MS); + return Number.isFinite(v) && v >= 0 ? v : 60_000; +}; +/** The editor's services answer from a stat: a late answer still lands in the memo for the next read. */ +const WAIT_MS = 400; + +type Memo = { at: number; value: Promise<Decision | null> } | null; +const g = globalThis as typeof globalThis & { __umtoolXJarMemo?: Memo }; + +/** Forget the memo (a spec that changed the stub's services; a Recheck). */ +export function clearXJarMemo(): void { + g.__umtoolXJarMemo = null; +} + +async function ask(): Promise<Decision | null> { + const payload = await askEditor("/api/ops/services", { fresh: true }); + return xJarDecision(payload, { href: `${editorUrl()}/settings` }) as Decision | null; +} + +/** The X jar's row when X work waits on it, else none. Never throws. */ +export async function xJarDecisions({ fresh = false }: { fresh?: boolean } = {}): Promise<Decision[]> { + const m = g.__umtoolXJarMemo; + let value: Promise<Decision | null>; + if (m && !fresh && Date.now() - m.at < memoMs()) value = m.value; + else { + value = ask().catch(() => null); + g.__umtoolXJarMemo = { at: Date.now(), value }; + } + const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), WAIT_MS).unref?.()); + const row = await Promise.race([value, timeout]).catch(() => null); + return row ? [row] : []; +} diff --git a/umtool/lib/machine.ts b/umtool/lib/machine.ts @@ -1,13 +1,23 @@ import { statfs } from "node:fs/promises"; import { toolsCache } from "./doctor"; import { REPORTS_ROOT } from "./paths"; +import { xJarDecisions } from "./inbox/xJar"; // The machine's own calls for the Inbox: a tool a report build needs that the // last doctor check found absent, and a reports root nearly out of space. Read // from the doctor's CACHE and one statfs -- never a probe (the probe is the -// button on /settings/system). SERVER ONLY. +// button on /settings/system). And X's login when X work waits on it (umtool +// redesign L4, lib/inbox/xJar.ts: the editor's services, memoised, never +// waited on long) -- its card names the editor's settings. SERVER ONLY. -export type MachineCall = { kind: "machine-tool" | "machine-disk"; why: string; count: number }; +export type MachineCall = { + kind: "machine-tool" | "machine-disk" | "x-jar-stale"; + why: string; + count: number; + /** The card's title and its one action, when not umtool's own (X's login: the editor's settings). */ + title?: string; + action?: { label: string; href: string }; +}; /** Below this a render or a fetch would fail part-way. */ export const LOW_DISK_BYTES = 5e9; @@ -35,5 +45,8 @@ export async function machineCalls(): Promise<MachineCall[]> { if (free !== null && free < LOW_DISK_BYTES) { out.push({ kind: "machine-disk", why: `${(free / 1e9).toFixed(1)} GB free under the reports root`, count: 1 }); } + for (const x of await xJarDecisions().catch(() => [])) { + out.push({ kind: "x-jar-stale", why: x.why, count: 1, title: x.projectTitle ?? "X login", action: { label: "Refresh X's cookies", href: x.href } }); + } return out; } diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -1434,14 +1434,26 @@ export async function reportDecisions(ctx, summary) { // there are any; a stale row -- the cut or the quote changed since -- says // nothing). { - const { quoteGate, readQuoteCheck } = await import("../report/quoteCheck.mjs"); - for (const g of quoteGate(clips, await readQuoteCheck(dir))) { + const { alignPatch, quoteGate, readQuoteCheck } = await import("../report/quoteCheck.mjs"); + const qdoc = await readQuoteCheck(dir); + for (const g of quoteGate(clips, qdoc)) { const moved = g.status === "moved"; + // The one press (L4, the Inbox's and the Checks list's): a moved quote's cut snapped to the words as heard + // (`window --align`'s patch, through the window writer); a quote not heard, checked again once refetched. + let settle = { kind: "quote-check", clips: [g.id], label: "Run quote-check" }; + if (moved) { + try { + settle = { kind: "patch", clip: g.id, patch: alignPatch(clips.find((e) => e.id === g.id), qdoc.clips[g.id]), label: "Snap the cut to the words" }; + } catch { + settle = null; + } + } add(moved ? "clip-quote-moved" : "clip-quote-missing", g.id, g.why.replace("<p>", id), "blocking", { href: clipHref(g.id), fix: moved ? `umtool window ${id} ${g.id} --align # or --quote-ruled, having heard it` : `umtool fetch ${id} --refetch ${g.id} && umtool quote-check ${id} --clips ${g.id} # or --quote-ruled, having heard it`, + ...(settle ? { settle } : {}), }); } } @@ -1664,8 +1676,11 @@ export async function reportDecisions(ctx, summary) { { fix: rows.some((r) => r.fix) ? `umtool links ${id} --fix` : checkFix, // The links whose fix is known (a Twitch id the site serves as v<id>) are rewritten in one press. + // A Rumble folder id the archive serves by its EMBED id (linkCheck.mjs fixSiteVideo, L1's mapping): Use embed ids. settle: rows.some((r) => r.fix) - ? { kind: "check-links", fix: true, label: `Fix ${rows.filter((r) => r.fix).length} link${rows.filter((r) => r.fix).length === 1 ? "" : "s"} (the site's v<id>)` } + ? rows.filter((r) => r.fix).every((r) => r.fixSiteVideo) + ? { kind: "check-links", fix: true, label: `Use embed ids (${rows.filter((r) => r.fix).length})` } + : { kind: "check-links", fix: true, label: `Fix ${rows.filter((r) => r.fix).length} link${rows.filter((r) => r.fix).length === 1 ? "" : "s"} (the site's v<id>)` } : checkSettle, clips: ids, }, diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs @@ -55,7 +55,7 @@ const REVIEW_KEYS = ["verdict", "reason", "rejectNote", "correction"]; const FX_KEYS = ["fx", ...FX_ENTRY_FIELDS.map((k) => `fx.${k}`)]; /** Seconds taken out of the clip's middle (gaps.mjs): the whole list, one added, one removed. */ const GAP_KEYS = ["gaps", "gap.add", "gap.remove"]; -export const VERTICAL_SET_KEYS = Object.freeze(["vertical", "vertical.crop", "vertical.layout", "vertical.aspect"]); +export const VERTICAL_SET_KEYS = Object.freeze(["vertical", "vertical.crop", "vertical.layout", "vertical.aspect", "vertical.crops"]); export const SIDE_SET_KEYS = Object.freeze(["side", "side.item", "side.post", "side.from", "side.to", "side.place"]); const SET_KEYS = [ "claim", ...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS, @@ -108,7 +108,8 @@ export const SET_USAGE = [ " --take <t>: the entry knobs (not claim.* or marks) land in takes/<t>/take.json's patch, an undo point first", " (`umtool timeline <p> --take <t> undo`); the project's manifest is untouched.", " vertical.crop='[x,y,w,h]' (fractions of the source: the 9:16 box a vertical render cuts; vertical.aspect the", - " source's w/h when not 16:9); vertical.layout=full|framed|quote (this clip's layout in a vertical cut).", + " source's w/h when not 16:9); vertical.layout=full|framed|quote (this clip's layout in a vertical cut), or", + " twocrop with vertical.crops='[[x,y,w,h],[x,y,w,h]]' (the stacked vertical deck's two crops, the top one first).", " side.item=<post item id> | side.post='{\"author\",\"handle\",\"date\",\"text\",…}' -- a post shown BESIDE the", " clip while it plays, never read, the clip's sound running; side.from / side.to seconds into the clip;", " side.place=split|overlay (vertical) | right|left (16:9). `side=` removes it (docs/knobs.md \"Vertical\").", diff --git a/umtool/lib/report/linksCli.mjs b/umtool/lib/report/linksCli.mjs @@ -87,22 +87,9 @@ export async function linksCommand(args, { root = REPORTS_ROOT, out = (s) => con const fixed = []; let undo = null; if (flags.has("--fix")) { - // ONE undo point before the rewrites (revisions/<stamp>-auto-before-links-fix): `umtool timeline <p> undo` takes them all back. - if (doc.links.some((l) => l.state === "dead" && l.fix)) undo = await createSnapshot(project.dir, { label: `${AUTO_SNAPSHOT_PREFIX}links-fix` }); - for (const l of doc.links) { - if (l.state !== "dead" || !l.fix) continue; - // A Rumble folder id (linkCheck.mjs siteIdOf): the clip names the embed id the archive serves (`siteVideo`), - // and a citeUrl that was the dead link moves with it; a QR built from the moment needs nothing else. - if (l.fixSiteVideo) { - const e = (m.timeline ?? []).find((x) => x?.id === l.clip); - const patch = { siteVideo: l.fixSiteVideo, ...(e?.citeUrl === l.url ? { citeUrl: l.fix } : {}) }; - await withEditNotes(project, () => updateClip(project.dir, l.clip, patch)); - fixed.push({ clip: l.clip, from: l.url, to: l.fix, siteVideo: l.fixSiteVideo }); - continue; - } - await withEditNotes(project, () => updateClip(project.dir, l.clip, { citeUrl: l.fix })); - fixed.push({ clip: l.clip, from: l.url, to: l.fix }); - } + const r = await applyLinkFixes(project, m, doc); + fixed.push(...r.fixed); + undo = r.undo; if (fixed.length) { m = await readManifest(project.dir); doc = await runLinkCheck(project.dir, m, opts); @@ -288,3 +275,48 @@ export async function linkPolicyCommand(args, { root = REPORTS_ROOT, out = (s) = return e instanceof CliError ? 2 : 1; } } + +/** + * Rewrite every dead link `doc` knows the fix for, through the window writer, + * after ONE undo point (revisions/<stamp>-auto-before-links-fix: `umtool + * timeline <p> undo` takes them all back). The CLI's `--fix` over a check it + * just ran, and the page's (POST /api/report/links `fix`: the Checks list's + * and the Inbox's "Use embed ids") over the RECORDED one -- `guard`: only a + * clip still as that check saw it (its citeUrl the dead link, or no siteVideo + * yet for a Rumble folder id); an edit since is somebody's decision. + * + * A Rumble folder id (linkCheck.mjs siteIdOf, L1's mapping): the clip names the + * embed id the archive serves (`siteVideo`), and a citeUrl that was the dead + * link moves with it; a QR built from the moment needs nothing else. Any other + * fix (a Twitch id as v<id>) is the clip's citeUrl. + * + * @param {{ id: string, dir: string }} project + * @param {Record<string, any>} m the manifest the check read + * @param {{ links?: Array<Record<string, any>> } | null} doc + * @param {{ guard?: boolean }} [o] + */ +export async function applyLinkFixes(project, m, doc, { guard = false } = {}) { + const byId = new Map((m?.timeline ?? []).map((e) => [e?.id, e])); + const todo = (doc?.links ?? []).filter((l) => { + if (l.state !== "dead" || !l.fix) return false; + if (!guard) return true; + const e = byId.get(l.clip); + if (!e) return false; + return l.fixSiteVideo ? !e.siteVideo : e.citeUrl === l.url; + }); + const fixed = []; + if (!todo.length) return { fixed, undo: null }; + const undo = await createSnapshot(project.dir, { label: `${AUTO_SNAPSHOT_PREFIX}links-fix` }); + for (const l of todo) { + if (l.fixSiteVideo) { + const e = byId.get(l.clip); + const patch = { siteVideo: l.fixSiteVideo, ...(e?.citeUrl === l.url ? { citeUrl: l.fix } : {}) }; + await withEditNotes(project, () => updateClip(project.dir, l.clip, patch)); + fixed.push({ clip: l.clip, from: l.url, to: l.fix, siteVideo: l.fixSiteVideo }); + continue; + } + await withEditNotes(project, () => updateClip(project.dir, l.clip, { citeUrl: l.fix })); + fixed.push({ clip: l.clip, from: l.url, to: l.fix }); + } + return { fixed, undo }; +} diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -840,12 +840,14 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n const errors = verticalErrors(v, "vertical"); if (errors.length) throw new Error(errors.join("; ")); const r4 = (n) => Number(Number(n).toFixed(4)); - const vv = /** @type {{ crop?: number[], aspect?: number, layout?: string }} */ (v); + const vv = /** @type {{ crop?: number[], aspect?: number, layout?: string, crops?: number[][] }} */ (v); // `layout` (lane vertical): the clip's own layout in a vertical cut; a layout alone keeps the centred crop. entry.vertical = { ...(Array.isArray(vv.crop) ? { crop: vv.crop.map(r4) } : {}), ...(vv.aspect !== undefined ? { aspect: r4(vv.aspect) } : {}), ...(vv.layout !== undefined ? { layout: vv.layout } : {}), + // The stacked deck's two crops (layout "twocrop"), the top one first. + ...(Array.isArray(vv.crops) ? { crops: vv.crops.map((c) => c.map(r4)) } : {}), }; } } diff --git a/umtool/lib/report/momentLink.mjs b/umtool/lib/report/momentLink.mjs @@ -0,0 +1,121 @@ +// A MOMENT, AS PASTED (umtool redesign L4, home's Quick clip box; the timeline's +// Add clip): the one parser for what a person pastes to name a second of a +// recording -- +// +// <channel>/<video>@<start>-<end> a span (`umtool clip`'s spec) +// <channel>/<video>@<time>, <video>@<time> +// an archive's moment link `<site>/?v=<channel>/<video>&t=<s>` (site-links.mjs +// archiveMomentUrl; `%2F` too, `#t=` too), or a moment +// page `<site>/m/<channel>/<video>/<s>-<e>/` +// a YouTube link watch?v=, youtu.be/, /live/, /shorts/, /embed/; t= / start= / #t= +// a Rumble link rumble.com/<id>-<title>.html (the URL slug's id: the +// corpus's folder) or /embed/<id>/ (the embed id); start= / t= +// +// -> `{ channel | null, video, start, end | null, via }`, or null for anything +// that is not one. A time is seconds, `1:02:32`, `62m32s` or `1h2m32s`. The +// channel of a platform link is found on the disk by the caller +// (quickClipStrip.mjs). Pure, browser-safe: no imports. + +/** `1:02:32`, `62m32s`, `3752`, `1h2m32s` → seconds; null when it is not a time. */ +export function parseTime(v) { + const s = String(v ?? "").trim(); + if (!s) return null; + if (/^\d+(\.\d+)?s?$/.test(s)) return Number(s.replace(/s$/, "")); + const hms = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?$/.exec(s); + if (hms && (hms[1] || hms[2] || hms[3])) return Number(hms[1] ?? 0) * 3600 + Number(hms[2] ?? 0) * 60 + Number(hms[3] ?? 0); + const raw = s.split(":"); + // `:` alone, or an empty part (`1:`, `:30`), is not a time. + if (raw.some((p) => !/^\d+(\.\d+)?$/.test(p))) return null; + const parts = raw.map(Number); + if (parts.length >= 2 && parts.length <= 3 && parts.every((n) => Number.isFinite(n))) return parts.reduce((a, n) => a * 60 + n, 0); + return null; +} + +const ID = /^[A-Za-z0-9_-]{2,}$/; +const CHANNEL = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +/** + * The ids of a moment. TYPED forms (`<channel>/<video>@…`, `<video>@…`) refuse a video starting with `-`: typed, + * it is likelier a slip than an id. A LINK's video id is the platform's, and a YouTube id may start with `-` or `_` + * (about 1 in 64): accepted -- it reaches a child's argv only inside the `<channel>/<video>@…` word, after `--`. + */ +const ok = (channel, video, { typed = false } = {}) => + (channel === null || (CHANNEL.test(channel) && !/^\.+$/.test(channel))) && ID.test(video) && !(typed && video.startsWith("-")); + +/** The time a link names: `t=` / `start=` in its query, else `t=` in its hash; 0 when none. */ +function linkTime(u) { + const raw = u.searchParams.get("t") ?? u.searchParams.get("start") ?? (/(?:^#|&)t=([0-9hms:.]+)/.exec(u.hash)?.[1] ?? null); + return raw === null ? 0 : parseTime(raw); +} + +/** + * @param {unknown} raw + * @returns {{ channel: string | null, video: string, start: number, end: number | null, via: "spec" | "short" | "archive" | "youtube" | "rumble" } | null} + */ +export function parseMomentInput(raw) { + const s = String(raw ?? "").trim(); + if (!s || s.length > 2000) return null; + + // <channel>/<video>@<start>-<end>: a span. + const span = /^([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9_-]{2,})@(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(s); + if (span) { + const [, channel, video, a, b] = span; + const start = Number(a); + const end = Number(b); + return ok(channel, video, { typed: true }) && end > start ? { channel, video, start, end, via: "spec" } : null; + } + // [<channel>/]<video>@<time> + const short = /^(?:([A-Za-z0-9][A-Za-z0-9._-]*)\/)?([A-Za-z0-9_-]{2,})@([0-9:hms.]+)$/.exec(s); + if (short) { + const t = parseTime(short[3]); + const channel = short[1] ?? null; + return t === null || !ok(channel, short[2], { typed: true }) ? null : { channel, video: short[2], start: t, end: null, via: "short" }; + } + + let u; + try { + u = new URL(/^https?:\/\//i.test(s) ? s : `https://${s}`); + } catch { + return null; + } + const host = u.hostname.toLowerCase().replace(/^(www|m)\./, ""); + + // An archive's moment page: /m/<channel>/<video>/<s>-<e>/ + const page = /\/m\/([^/]+)\/([^/]+)\/(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)\/?$/.exec(u.pathname); + if (page) { + const channel = decodeURIComponent(page[1]); + const video = decodeURIComponent(page[2]); + const start = Number(page[3]); + const end = Number(page[4]); + return ok(channel, video) && end > start ? { channel, video, start, end, via: "archive" } : null; + } + // An archive's moment link: ?v=<channel>/<video>&t=<s> (a YouTube v= never holds a slash). + const v = u.searchParams.get("v"); + if (v && v.includes("/")) { + const [channel, video, ...more] = v.split("/"); + const t = linkTime(u); + return !more.length && t !== null && ok(channel, video) ? { channel, video, start: t, end: null, via: "archive" } : null; + } + + if (host === "rumble.com") { + const embed = /^\/embed\/([A-Za-z0-9]+)\/?/.exec(u.pathname); + const slug = /^\/(v[A-Za-z0-9]+)(?:-[^/]*)?(?:\.html)?\/?$/.exec(u.pathname); + const video = embed?.[1] ?? slug?.[1] ?? null; + const t = linkTime(u); + return video && t !== null && ok(null, video) ? { channel: null, video, start: t, end: null, via: "rumble" } : null; + } + + if (host === "youtube.com" || host === "youtu.be" || host === "music.youtube.com") { + let video = v; + if (!video && host === "youtu.be") video = u.pathname.slice(1).split("/")[0] || null; + if (!video) video = /\/(?:live|shorts|embed|v)\/([A-Za-z0-9_-]{6,})/.exec(u.pathname)?.[1] ?? null; + const t = linkTime(u); + return video && t !== null && ok(null, video) ? { channel: null, video, start: t, end: null, via: "youtube" } : null; + } + + // Any other link with a v= and a time: a YouTube-shaped one (the timeline's Add clip always took it). + if (v && ok(null, v)) { + const t = linkTime(u); + return t === null ? null : { channel: null, video: v, start: t, end: null, via: "youtube" }; + } + return null; +} diff --git a/umtool/lib/report/momentLink.test.mjs b/umtool/lib/report/momentLink.test.mjs @@ -0,0 +1,53 @@ +// The moment parser (umtool redesign L4): every form home's Quick clip box and +// the timeline's Add clip take, and what they refuse. +import assert from "node:assert/strict"; +import test from "node:test"; +import { parseMomentInput, parseTime } from "./momentLink.mjs"; + +test("times: seconds, h:m:s, 62m32s, 1h2m32s; nothing else", () => { + assert.equal(parseTime("3752"), 3752); + assert.equal(parseTime("12.5s"), 12.5); + assert.equal(parseTime("1:02:32"), 3752); + assert.equal(parseTime("62m32s"), 3752); + assert.equal(parseTime("1h2m32s"), 3752); + assert.equal(parseTime("soon"), null); + for (const bad of [":", "1:", ":30", "1::2"]) assert.equal(parseTime(bad), null, bad); + assert.equal(parseTime(""), null); +}); + +test("the spec and the short forms", () => { + assert.deepEqual(parseMomentInput("basicyt/quickvid@10-14.5"), { channel: "basicyt", video: "quickvid", start: 10, end: 14.5, via: "spec" }); + assert.equal(parseMomentInput("basicyt/quickvid@14-10"), null); + assert.deepEqual(parseMomentInput("basicyt/quickvid@1:02"), { channel: "basicyt", video: "quickvid", start: 62, end: null, via: "short" }); + assert.deepEqual(parseMomentInput("quickvid@62"), { channel: null, video: "quickvid", start: 62, end: null, via: "short" }); + for (const bad of ["../quickvid@10-14", "..@1-2", "-rf/quickvid@10-14", "basicyt/-x@10-14", "basicyt/quickvid", "", "nothing here"]) { + assert.equal(parseMomentInput(bad), null, bad); + } +}); + +test("an archive's moment link and moment page", () => { + assert.deepEqual(parseMomentInput("https://jeralyzer.pages.dev/?v=sitechan%2Fsv1&t=754"), { channel: "sitechan", video: "sv1", start: 754, end: null, via: "archive" }); + assert.deepEqual(parseMomentInput("https://jeralyzer.pages.dev/?v=sitechan/sv1#t=12"), { channel: "sitechan", video: "sv1", start: 12, end: null, via: "archive" }); + assert.deepEqual(parseMomentInput("https://jeralyzer.pages.dev/m/sitechan/sv1/754.00-761.50/"), { channel: "sitechan", video: "sv1", start: 754, end: 761.5, via: "archive" }); + assert.equal(parseMomentInput("https://jeralyzer.pages.dev/?v=a/b/c&t=1"), null); +}); + +test("YouTube and Rumble links: the video and the second; the channel is the disk's to find", () => { + assert.deepEqual(parseMomentInput("https://www.youtube.com/watch?v=n8G_ysDV2bA&t=4132s"), { channel: null, video: "n8G_ysDV2bA", start: 4132, end: null, via: "youtube" }); + assert.deepEqual(parseMomentInput("youtu.be/n8G_ysDV2bA?t=1h2m"), { channel: null, video: "n8G_ysDV2bA", start: 3720, end: null, via: "youtube" }); + assert.deepEqual(parseMomentInput("https://www.youtube.com/live/n8G_ysDV2bA?start=90"), { channel: null, video: "n8G_ysDV2bA", start: 90, end: null, via: "youtube" }); + assert.deepEqual(parseMomentInput("https://youtube.com/shorts/n8G_ysDV2bA"), { channel: null, video: "n8G_ysDV2bA", start: 0, end: null, via: "youtube" }); + assert.deepEqual(parseMomentInput("https://rumble.com/v6w2hyk-candace-owens-x-nick-fuentes-interview-full-71125.html?start=754"), { channel: null, video: "v6w2hyk", start: 754, end: null, via: "rumble" }); + assert.deepEqual(parseMomentInput("https://rumble.com/embed/v6tvlpq/?start=12"), { channel: null, video: "v6tvlpq", start: 12, end: null, via: "rumble" }); + assert.equal(parseMomentInput("https://rumble.com/c/SomeChannel"), null); + assert.equal(parseMomentInput("https://example.com/watch?v=abcdef&t=nope"), null); +}); + +test("a link's YouTube id may start with - or _ (about 1 in 64); a typed one may not start with -", () => { + assert.deepEqual(parseMomentInput("https://www.youtube.com/watch?v=-abcDEF1234&t=5"), { channel: null, video: "-abcDEF1234", start: 5, end: null, via: "youtube" }); + assert.deepEqual(parseMomentInput("https://youtu.be/_abcDEF1234?t=7"), { channel: null, video: "_abcDEF1234", start: 7, end: null, via: "youtube" }); + assert.deepEqual(parseMomentInput("https://jeralyzer.pages.dev/?v=chan%2F-abcDEF1234&t=9"), { channel: "chan", video: "-abcDEF1234", start: 9, end: null, via: "archive" }); + assert.deepEqual(parseMomentInput("chan/_abcDEF1234@1-2"), { channel: "chan", video: "_abcDEF1234", start: 1, end: 2, via: "spec" }); + assert.equal(parseMomentInput("chan/-abcDEF1234@1-2"), null); + assert.equal(parseMomentInput("-abcDEF1234@12"), null); +}); diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs @@ -19,6 +19,10 @@ import { readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { composeChrome } from "umtool-report-to-video/compose-chrome"; import { selectVariant } from "umtool-report-to-video/build-video"; +// The stacked vertical deck (vertical-deck.mjs): a 9:16 cut that keeps its deck previews at the render its build +// makes (vertical.mjs verticalRender), and only the modules with a vertical form. +import { stackedDeckWanted, verticalRender } from "umtool-report-to-video/vertical"; +import { stackedOn } from "umtool-report-to-video/vertical-deck"; import { createPostChannelResolver, resolvePostLinks } from "umtool-report-to-video/post-links"; import { attachPosts, @@ -446,7 +450,9 @@ export async function scheduleForPreview( project, manifest, variant, draft = new Map(), postsDraft = {}, { resolver = previewPostResolver(), claimsDraft = new Map(), estimate = false } = {}, ) { - const selected = selectVariant(manifest, variant); + const picked = selectVariant(manifest, variant); + // A stacked vertical deck is previewed at its build's render: the 9:16 frame, its geometry (vertical-deck.mjs). + const selected = stackedDeckWanted(picked.render) ? { ...picked, render: verticalRender(picked.render) } : picked; const entries = selected.timeline ?? []; const posts = Array.isArray(selected.posts) ? selected.posts : []; const [built, metas, linked] = await Promise.all([ @@ -988,8 +994,10 @@ const pick = (g) => (g ? { x: g.x, y: g.y, width: g.width, height: g.height } : * @returns {Promise<Array<Record<string, any>>>} */ export async function composePlayLayers(project, variant, schedule, render, { srcOf, compose = composeChrome }) { - const { playModules } = await import("umtool-report-to-video/modules"); - const mods = playModules().filter((m) => m.on(schedule, render)); + const { playModules, verticalFormOf } = await import("umtool-report-to-video/modules"); + // The stacked vertical deck draws only the modules with a vertical form (vertical-deck.mjs), as its build does. + const stacked = stackedOn(render); + const mods = playModules().filter((m) => m.on(schedule, render) && (!stacked || verticalFormOf(m))); if (!mods.length) return []; const total = Number(schedule.total) || 0; const rows = await composeLayerPreviews(project, variant, schedule, mods.map((m) => m.id), render, { compose }); diff --git a/umtool/lib/report/quickClip.mjs b/umtool/lib/report/quickClip.mjs @@ -63,17 +63,25 @@ const fin = (v) => typeof v === "number" && Number.isFinite(v); /** * A quick clip's spec, parsed and checked: `<channel>/<video>@<start>-<end>`, the end after the start, and - * neither id a path trick -- not all dots (`..`) and not starting with `-` (an argv flag) -- so the names - * that reach the disk and a child's argv are ids. Null when it is not one. Pure. + * neither id a path trick -- not all dots (`..`); the channel not starting with `-` (an argv flag), the video + * only when it is a YouTube id (redesign L4: those can start with `-`) -- so the names that reach the disk and a + * child's argv are ids. Null when it is not one. Pure. * @param {unknown} spec */ export function quickClipSpec(spec) { const c = parseClipSpec(spec); if (!c || !(c.end > c.start)) return null; - for (const id of [c.channel, c.video]) if (/^\.+$/.test(id) || id.startsWith("-")) return null; + for (const id of [c.channel, c.video]) if (/^\.+$/.test(id)) return null; + // The channel heads the argv word, so it never starts with `-`. A video id may only when it is YouTube-shaped + // (11 of [A-Za-z0-9_-]: about 1 id in 64 starts with `-`): the app's job passes the spec after `--` anyway. + if (c.channel.startsWith("-")) return null; + if (c.video.startsWith("-") && !YOUTUBE_ID.test(c.video)) return null; return c; } +/** A YouTube video id: 11 characters of the URL-safe base64 alphabet. */ +const YOUTUBE_ID = /^[A-Za-z0-9_-]{11}$/; + /** A project slug from words: lower-case letters, digits and dashes, at most 48, never `share-…` (a deliverables link's name). */ export function quickClipSlug({ title = null, channel, video, start }) { const clean = (words) => String(words).toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48).replace(/-+$/, ""); @@ -278,6 +286,11 @@ export async function quickClipCommand(args, { root = REPORTS_ROOT, log = consol try { for (let i = 0; i < args.length; i += 1) { const a = args[i]; + // `--`: every word after it is the spec, never a flag (the app's job passes it so). + if (a === "--") { + words.push(...args.slice(i + 1)); + break; + } if (!a.startsWith("--")) words.push(a); else if (valued.has(a)) { if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); diff --git a/umtool/lib/report/quickClipStrip.mjs b/umtool/lib/report/quickClipStrip.mjs @@ -0,0 +1,121 @@ +// HOME'S QUICK CLIP BOX, BEFORE THE RENDER (umtool redesign L4): a pasted +// moment (momentLink.mjs) found in the corpus and read -- which channel holds +// the recording (a platform link names none: the channel whose data/ holds +// it; a Rumble embed id, the channel whose metadata names it), the span (the +// link's own, else from the cue it lands in to the end of its sentence, at +// most three cues on, as the timeline's Add clip picks), and the words around +// it to cut by: the corpus's words (report-to-video/clip-words.mjs -- a words +// sidecar, a whisper transcript, the en-orig captions' word starts), else its +// cues. Nothing is fetched; the render is `umtool clip` (quickClip.mjs, POST +// /api/report/quick-clip), which asks the editor for the window. +// +// Reads only. Plain ESM. +import { readdir, stat } from "node:fs/promises"; +import path from "node:path"; +import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { clipWords } from "umtool-report-to-video/clip-words"; +import { CHANNELS_DIR } from "../paths.mjs"; +import { ENDS_SENTENCE, IS_FILLER, cuePathFor, readCues } from "../projects/report.mjs"; +import { parseMomentInput } from "./momentLink.mjs"; +import { quickClipSpec } from "./quickClip.mjs"; + +/** Seconds of words shown either side of the span. */ +export const STRIP_PAD_S = 12; +/** A moment with no end: its sentence, at most this long. */ +export const DEFAULT_SPAN_S = 20; + +const r2 = (x) => Math.round(Number(x) * 100) / 100; +const isDir = (p) => stat(p).then((s) => s.isDirectory(), () => false); +export class MomentError extends Error {} + +/** + * The channel (and the folder id) a recording is under: the named one, else every channel whose data/ holds it + * (a Rumble embed id: by the channel's metadata). Several: refused, naming them. + * @param {{ channel: string | null, video: string }} m + */ +export async function findRecording(m, { channelsDir = CHANNELS_DIR } = {}) { + const at = async (slug) => { + const dir = await resolveVideoDirId(channelsDir, slug, m.video).catch(() => m.video); + return (await isDir(path.join(channelsDir, slug, "data", dir))) ? { channel: slug, video: dir } : null; + }; + if (m.channel) { + const got = await at(m.channel); + if (!got) throw new MomentError(`this corpus has no ${m.channel}/${m.video}`); + return got; + } + const slugs = (await readdir(channelsDir, { withFileTypes: true }).catch(() => [])) + .filter((d) => (d.isDirectory() || d.isSymbolicLink()) && !d.name.startsWith(".")) + .map((d) => d.name) + .sort(); + const found = []; + for (const slug of slugs) { + if (await isDir(path.join(channelsDir, slug, "data", m.video))) found.push({ channel: slug, video: m.video }); + } + // A Rumble embed id has no folder of its own: the channel whose metadata names it (resolveVideoDirId). + if (!found.length && /^v[a-z0-9]{4,}$/i.test(m.video)) { + for (const slug of slugs) { + const got = await at(slug); + if (got) found.push(got); + } + } + if (!found.length) throw new MomentError(`no channel in this corpus holds ${m.video} — download it first, or write <channel>/${m.video}@<start>-<end>`); + if (found.length > 1) throw new MomentError(`${found.length} channels hold ${m.video} (${found.map((f) => f.channel).join(", ")}): write <channel>/${m.video}@<start>-<end>`); + return found[0]; +} + +/** + * The moment's span, from its cues when the link named only a second. + * @param {{ start: number, end: number | null }} m + * @param {Array<{ start: number, end: number, text: string }>} cues + */ +export function spanOf(m, cues) { + if (m.end !== null && m.end > m.start) return { start: r2(m.start), end: r2(m.end) }; + const list = (cues ?? []).filter((c) => Number.isFinite(c?.start) && Number.isFinite(c?.end)).sort((a, b) => a.start - b.start); + const i = list.findIndex((c) => c.end > m.start); + if (i < 0) return { start: r2(m.start), end: r2(m.start + DEFAULT_SPAN_S) }; + const from = list[i]; + const closes = (c) => ENDS_SENTENCE.test(c.text ?? "") && !IS_FILLER.test(c.text ?? ""); + const close = list.slice(i).find((c, k) => closes(c) || k >= 2) ?? from; + const start = Math.max(m.start, from.start); + const end = Math.min(close.end, start + DEFAULT_SPAN_S); + return { start: r2(start), end: r2(end > start + 0.5 ? end : start + DEFAULT_SPAN_S) }; +} + +/** + * A pasted moment, read: `{ spec, channel, video, start, end, from, to, words | null, cues | null, wordsFrom, title, duration }`. + * Throws MomentError with the sentence to show. + * @param {string} text + */ +export async function quickClipStrip(text, { channelsDir = CHANNELS_DIR } = {}) { + const m = parseMomentInput(text); + if (!m) throw new MomentError("not a moment: paste an archive, YouTube or Rumble link with its time, or <channel>/<video>@<start>-<end>"); + const rec = await findRecording(m, { channelsDir }); + const provenance = { channelSlug: rec.channel }; + const entry = { type: "clip", channel: rec.channel, video: rec.video }; + const file = cuePathFor({ provenance }, entry, channelsDir, null); + const doc = file ? await readCues(file) : null; + const allCues = doc?.cues ?? []; + const { start, end } = spanOf(m, allCues); + const duration = Number.isFinite(doc?.duration) ? doc.duration : null; + const from = r2(Math.max(0, start - STRIP_PAD_S)); + const to = r2(duration ? Math.min(duration, end + STRIP_PAD_S) : end + STRIP_PAD_S); + const got = await clipWords(entry, provenance, from, to, { channelsDir }).catch(() => null); + const cues = got?.words?.length ? null : allCues.filter((c) => c.end >= from && c.start <= to).map((c) => ({ start: c.start, end: c.end, text: c.text })); + const spec = `${rec.channel}/${rec.video}@${start}-${end}`; + if (!quickClipSpec(spec)) throw new MomentError(`${spec} is not a clip (the end after the start)`); + return { + spec, + channel: rec.channel, + video: rec.video, + start, + end, + from, + to, + words: got?.words?.length ? got.words.map((w) => ({ w: w.text, start: w.start, ...(Number.isFinite(w.end) ? { end: w.end } : {}) })) : null, + wordsFrom: got?.from ?? (cues?.length ? "cues" : null), + cues: cues?.length ? cues : null, + title: typeof doc?.title === "string" ? doc.title : null, + duration, + via: m.via, + }; +} diff --git a/umtool/lib/report/quickClipStrip.test.mjs b/umtool/lib/report/quickClipStrip.test.mjs @@ -0,0 +1,72 @@ +// Home's Quick clip box before the render (umtool redesign L4): a pasted moment +// found in a corpus, its span from the cues, and the words to cut by. +import assert from "node:assert/strict"; +import test from "node:test"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { MomentError, findRecording, quickClipStrip, spanOf } from "./quickClipStrip.mjs"; +import { quickClipCommand, quickClipSpec } from "./quickClip.mjs"; + +const cues = [ + { start: 0, end: 4, text: "first we go" }, + { start: 4, end: 8, text: "and then we stop." }, + { start: 8, end: 12, text: "a new thought" }, + { start: 12, end: 16, text: "runs on" }, + { start: 16, end: 20, text: "and on" }, + { start: 20, end: 24, text: "and ends." }, +]; + +test("a span: the link's own; else from the cue it lands in to its sentence's end, at most three cues on", () => { + assert.deepEqual(spanOf({ start: 3, end: 9 }, cues), { start: 3, end: 9 }); + assert.deepEqual(spanOf({ start: 1, end: null }, cues), { start: 1, end: 8 }); + assert.deepEqual(spanOf({ start: 9, end: null }, cues), { start: 9, end: 20 }); + assert.deepEqual(spanOf({ start: 30, end: null }, cues), { start: 30, end: 50 }); + assert.deepEqual(spanOf({ start: 5, end: null }, []), { start: 5, end: 25 }); +}); + +test("the recording found on the disk: by its channel, by the one channel holding it, refused when none or two do", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "quick-clip-strip-")); + try { + const rec = async (slug, id, doc) => { + const d = path.join(root, slug, "data", id); + await mkdir(d, { recursive: true }); + await writeFile(path.join(root, slug, "config.json"), JSON.stringify({ platform: "youtube" })); + if (doc) await writeFile(path.join(d, "transcript.cues.json"), JSON.stringify(doc)); + }; + await rec("chan", "vid1", { title: "A fixture", duration: 30, cues }); + await rec("chan", "both"); + await rec("other", "both"); + assert.deepEqual(await findRecording({ channel: null, video: "vid1" }, { channelsDir: root }), { channel: "chan", video: "vid1" }); + assert.deepEqual(await findRecording({ channel: "chan", video: "vid1" }, { channelsDir: root }), { channel: "chan", video: "vid1" }); + await assert.rejects(findRecording({ channel: null, video: "nope" }, { channelsDir: root }), /no channel in this corpus holds nope/); + await assert.rejects(findRecording({ channel: null, video: "both" }, { channelsDir: root }), /2 channels hold both \(chan, other\)/); + await assert.rejects(findRecording({ channel: "other", video: "vid1" }, { channelsDir: root }), MomentError); + + const s = await quickClipStrip("https://www.youtube.com/watch?v=vid1&t=1", { channelsDir: root }); + assert.equal(s.spec, "chan/vid1@1-8"); + assert.deepEqual([s.from, s.to, s.title, s.duration, s.via], [0, 20, "A fixture", 30, "youtube"]); + // No words sidecar here: the cues around the span. + assert.equal(s.words, null); + assert.equal(s.wordsFrom, "cues"); + assert.deepEqual(s.cues.map((c) => c.text), ["first we go", "and then we stop.", "a new thought", "runs on", "and on", "and ends."]); + await assert.rejects(quickClipStrip("not a moment", { channelsDir: root }), /not a moment/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a quick clip's spec: a YouTube id starting with - is one (the job passes the spec after --); `-x`, a dash channel or dots are not", () => { + assert.deepEqual(quickClipSpec("chan/-abcDEF1234@1-2"), { channel: "chan", video: "-abcDEF1234", start: 1, end: 2 }); + assert.ok(quickClipSpec("chan/_abcDEF1234@1-2")); + for (const bad of ["chan/-x@1-2", "-rf/vid@1-2", "../vid@1-2", "chan/..@1-2", "chan/vid@2-1"]) assert.equal(quickClipSpec(bad), null, bad); +}); + +test("umtool clip -- <spec>: the word after -- is the spec, never a flag", async () => { + const out = []; + const err = []; + // A spec that parses but names no recording here: the command reaches the spec check, not "unknown flag". + const code = await quickClipCommand(["--json", "--", "nochan/-abcDEF1234@1-2"], { root: "/nonexistent-umtool-root", log: (s) => out.push(s), err: (s) => err.push(s), channelsDir: "/nonexistent-umtool-channels" }); + assert.notEqual(code, 0); + assert.doesNotMatch(err.join("\n"), /unknown flag/); +}); diff --git a/umtool/lib/report/quoteCheck.test.mjs b/umtool/lib/report/quoteCheck.test.mjs @@ -162,6 +162,10 @@ test("umtool check: a moved quote and a missing one are blocking, with the fix; assert.match(ds[0].why, /a: its quote is heard \+13\.06 s from its cut — umtool window cut a --align/); assert.equal(ds[0].fix, "umtool window cut a --align # or --quote-ruled, having heard it"); assert.match(ds[1].fix, /umtool fetch cut --refetch b/); + // The one press (L4): a moved quote's cut snapped to the words as heard (alignPatch); a missing one checked again. + assert.deepEqual(ds[0].settle, { kind: "patch", clip: "a", patch: alignPatch({ ...clip("a", 10), type: "clip" }, { ...row(10, "moved", { heard: { from: 23.06, to: 25 } }) }), label: "Snap the cut to the words" }); + assert.equal(ds[0].settle.patch.lockCut, true); + assert.deepEqual(ds[1].settle, { kind: "quote-check", clips: ["b"], label: "Run quote-check" }); } finally { await rm(root, { recursive: true, force: true }); } diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -101,6 +101,9 @@ export const TAKE_USAGE = [ "records which cut it is (censored | uncensored).", ].join("\n"); +/** What `umtool takes verdict` says: a verdict, or `clear`. */ +const TAKE_VERDICT_WORDS = new Set(["like", "maybe", "no", "clear"]); + export const TAKES_USAGE = [ "usage: umtool takes make <project> [--recipe FILE] [--only ID,ID] [--force] [--progress ndjson]", ` the recipe's takes, one at a time (default: takes/${RECIPE_FILE}); a take that`, @@ -118,6 +121,8 @@ export const TAKES_USAGE = [ " umtool takes relabel <project> <take> <label…> take.json's label (an undo point of the take's own;", " refused while it renders)", " umtool takes supersede <project> <take> [--by <take>] | --clear folded away in the takes list (verdicts.json)", + " umtool takes verdict <project> <take> like|maybe|no|clear [--note \"…\"] [--json] the take's verdict (verdicts.json):", + " the Takes page's and Play's Like / Maybe / No; a version with a render and none is a call in the Inbox", " umtool takes delete <project> <take> [--dry-run] [--force] takes/<take>/ whole (refused while it renders or a", " render is made from it; --force only past the take the project's manifest is)", " umtool takes cancel <project> <take> [--json] stop the take's render (it renders now: its build lock is live", @@ -148,7 +153,7 @@ function parse(args) { const valued = new Set([ "--id", "--label", "--group", "--kind", "--summary", "--style", "--patch", "--patch-json", "--set", "--effect", "--at", "--dur", "--recipe", "--only", "--progress", "--from", "--by", "--name", "--tail", - "--import-item", "--after", "--before", "--as", "--pad", + "--import-item", "--after", "--before", "--as", "--pad", "--note", ]); /** @type {Record<string, string[]>} */ const flags = {}; @@ -602,6 +607,20 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con else log(r.revision ? `${take}: "${r.label}" (was "${r.was}"; undo point takes/${take}/${r.revision.rel})` : `${take} is already "${r.label}"`); return 0; } + if (sub === "verdict") { + // Play and judge's twin (L4): a take's verdict in takes/verdicts.json, the Takes page's and Play's buttons. + const project = await pickProject(rest[0], reportsRoot); + const take = rest[1]; + const said = rest[2]; + if (!take || !said || ![...TAKE_VERDICT_WORDS].includes(said)) throw new CliError("umtool takes verdict <project> <take> like|maybe|no|clear [--note \"…\"]"); + const { listTakes, setTakeVerdict } = await import("./takes.mjs"); + if (!(await listTakes(project.dir)).takes.some((t) => t.id === take)) throw new CliError(`${project.id} has no take ${take}`); + const note = p.one("--note"); + const r = await setTakeVerdict(project.dir, take, { verdict: said === "clear" ? null : said, ...(note !== undefined && note !== null ? { note } : {}) }); + if (p.has("--json")) log(JSON.stringify({ ok: true, take, entry: r.entry }, null, 2)); + else log(r.entry?.verdict ? `${take}: ${r.entry.verdict}${r.entry.note ? ` — ${r.entry.note}` : ""}` : `${take}: no verdict`); + return 0; + } if (sub === "supersede") { const project = await pickProject(rest[0], reportsRoot); const take = rest[1]; diff --git a/umtool/lib/report/takePreview.mjs b/umtool/lib/report/takePreview.mjs @@ -68,9 +68,12 @@ const X264_PRESETS = ["ultrafast", "superfast", "veryfast", "faster", "fast", "m export function previewKnobs(render = {}) { const raw = render?.preview; if (raw !== undefined && raw !== null && !isObj(raw)) throw new Error("render.preview is an object: { width, height, preset, crf, segments }"); - const k = { ...PREVIEW_DEFAULTS, ...(isObj(raw) ? raw : {}) }; - const W = Number(render?.width ?? 1920); - const H = Number(render?.height ?? 1080); + // A 9:16 cut (`render.format: "vertical"`, built 1080x1920 whatever its width and height say) previews 9:16: + // the defaults turned on their side, never squashed into a 16:9 tier (lane vertical-deck). + const vertical = render?.format === "vertical"; + const k = { ...PREVIEW_DEFAULTS, ...(vertical ? { width: PREVIEW_DEFAULTS.height, height: PREVIEW_DEFAULTS.width } : {}), ...(isObj(raw) ? raw : {}) }; + const W = vertical ? 1080 : Number(render?.width ?? 1920); + const H = vertical ? 1920 : Number(render?.height ?? 1080); let width = Math.round(Number(k.width)); let height = Math.round(Number(k.height)); if (!Number.isFinite(width) || width < 16 || !Number.isFinite(height) || height < 16) throw new Error(`render.preview: width and height are pixels (≥ 16), got ${JSON.stringify(raw)}`); diff --git a/umtool/lib/report/takePreview.test.mjs b/umtool/lib/report/takePreview.test.mjs @@ -16,6 +16,8 @@ test("previewKnobs: the defaults, a knob over them, never larger than the cut, c assert.deepEqual(previewKnobs({ ...R, preview: { width: 960, height: 540, crf: 30 } }), { width: 960, height: 540, preset: "veryfast", crf: 30, segments: "shared" }); // A 640x360 cut previews at its own size. assert.deepEqual(previewKnobs({ ...R, width: 640, height: 360 }).width, 640); + // A 9:16 cut previews 9:16 (lane vertical-deck): built 1080x1920 whatever its width and height say. + assert.deepEqual(previewKnobs({ ...R, format: "vertical" }), { ...PREVIEW_DEFAULTS, width: 720, height: 1280 }); assert.deepEqual(previewKnobs({ ...R, width: 640, height: 360 }).height, 360); assert.throws(() => previewKnobs({ ...R, preview: { preset: "warp" } }), /x264 preset/); assert.throws(() => previewKnobs({ ...R, preview: { crf: 99 } }), /0–51/); diff --git a/umtool/lib/report/versions.test.mjs b/umtool/lib/report/versions.test.mjs @@ -260,6 +260,26 @@ test("umtool takes save | open | freeze, with --json", async () => { } }); +test("umtool takes verdict: Play and judge's twin -- like | maybe | no | clear, with a note; an unknown take or word refused", async () => { + const { root, dir, reportsRoot } = await project(); + try { + const out = []; + const err = []; + const run = (args) => takesCommand(args, { reportsRoot, log: (s) => out.push(s), err: (s) => err.push(s) }); + assert.equal(await run(["save", "proj"]), 0); + assert.equal(await run(["verdict", "proj", "v1", "maybe", "--note", "the cold open drags"]), 0); + assert.equal(out.pop(), "v1: maybe — the cold open drags"); + const { readVerdicts } = await import("./takes.mjs"); + assert.deepEqual([(await readVerdicts(dir)).v1.verdict, (await readVerdicts(dir)).v1.note], ["maybe", "the cold open drags"]); + assert.equal(await run(["verdict", "proj", "v1", "clear", "--json"]), 0); + assert.equal(JSON.parse(out.pop()).entry?.verdict ?? null, null); + assert.equal(await run(["verdict", "proj", "v9", "like"]), 2); + assert.equal(await run(["verdict", "proj", "v1", "great"]), 2); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + test("one undo stack: in the app (setUndoEveryMs(0)) two trims a moment apart are two undo points, undone one by one; the terminal -- and a step the app spawns -- keeps the throttle", async () => { const { root, dir } = await project(); const { setUndoEveryMs } = await import("./manifest.mjs"); diff --git a/umtool/lib/report/verticalCli.mjs b/umtool/lib/report/verticalCli.mjs @@ -28,7 +28,7 @@ export const VERTICAL_USAGE = [ " [--clip full|framed|quote] [--post card|stack|media] [--side split|overlay]", " [--hook title|section|\"<a line of the cut's own copy>\"] [--captions l|xl] [--lines 1|2]", " [--loudness -14] [--max 60] [--name N] [--out FILE] [--reframe] [--dry-run] [--json]", - " [--intro | --no-intro] [--no-outro]", + " [--intro | --no-intro] [--no-outro] [--deck stacked|bare]", "", "A vertical short (1080x1920, the take's fps) of a take's items: a reel's beats (promo/<r>-beats.json, as", "`umtool trailer --reel` reads them), a beats file, or whole items. Built natively: each clip cut again in", @@ -50,11 +50,14 @@ export const VERTICAL_USAGE = [ "else boot-dark with the mark on the chime); a reel whose `intro` is on opens on it too (its own intro when it", "has one; --no-intro: not). A reel whose `outro` is on ends on its card, laid out 9:16 inside the safe area", "(--no-outro: not). Both are counted in the length the --max note reads.", + "--deck stacked (the default for a cut with a deck: render.vertical.deck) keeps the deck in 9:16 -- the rail", + "under the top band, the picture at full width, the captions under it, the instruments in two columns, the", + "source line and its QR above the bottom band; --deck bare is the vertical with no deck, as it first shipped.", ].join("\n"); class CliError extends Error {} -const VALUED = new Set(["--take", "--reel", "--beats", "--items", "--clip", "--post", "--side", "--hook", "--captions", "--lines", "--loudness", "--max", "--name", "--out"]); +const VALUED = new Set(["--take", "--reel", "--beats", "--items", "--clip", "--post", "--side", "--hook", "--captions", "--lines", "--loudness", "--max", "--name", "--out", "--deck"]); const BOOL = new Set(["--reframe", "--landscape", "--dry-run", "--json", "--help", "--intro", "--no-intro", "--no-outro"]); function parse(args) { @@ -78,6 +81,7 @@ function parse(args) { export function knobsOfFlags(flags) { /** @type {Record<string, any>} */ const k = {}; + if (flags["--deck"]) k.deck = flags["--deck"]; if (flags["--clip"]) k.clip = flags["--clip"]; if (flags["--post"]) k.post = flags["--post"]; if (flags["--side"]) k.side = flags["--side"]; @@ -94,6 +98,18 @@ export function knobsOfFlags(flags) { const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +/** + * A short's 9:16 end card (outro.mjs) -- the archive's link as a QR and the short's sources, each clip's date, channel + * and time from the stacked deck's schedule -- or null: a short that keeps no deck (`--deck bare`, a cut without one) + * ends on the outro card it always did. + */ +export async function endCardOf({ render, knobs = {}, provenance = {}, timeline = [], schedule = null }) { + const V = await import("umtool-report-to-video/vertical"); + if (!V.stackedDeckWanted({ ...render, format: "vertical", vertical: { ...(render?.vertical ?? {}), ...knobs } })) return null; + const { endCardSources } = await import("umtool-report-to-video/outro"); + return { qrUrl: provenance.qrLink ?? provenance.siteOrigin ?? null, sources: endCardSources(timeline, schedule) }; +} + /** The heavy slot (report-to-video/heavy-gate.mjs), loaded at run time: `(cmd, fn) => …` with a declared estimate. */ async function heavySlot() { const gate = new URL("./heavy-gate.mjs", import.meta.resolve("umtool-report-to-video/package.json")).href; @@ -242,6 +258,10 @@ export async function verticalCommand(args, { reportsRoot = REPORTS_ROOT, log = const RF = await import("umtool-report-to-video/reframe"); made = await RF.assembleShort({ pieces: plan.pieces, segmentsDir: path.join(outDir, work, "segments"), built, outFile, + // A stacked vertical deck's pieces are cut from the built cut (its deck laid over it), at the build's places. + schedule: V.stackedDeckWanted({ ...(takeManifest.render ?? {}), format: "vertical", vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } }) + ? await readJson(path.join(outDir, work, "schedule.json")) + : null, render: { ...takeManifest.render, vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } }, log: say, }); } @@ -251,9 +271,14 @@ export async function verticalCommand(args, { reportsRoot = REPORTS_ROOT, log = const { wrapShort } = await import("umtool-report-to-video/reel-intro"); const RF = await import("umtool-report-to-video/reframe"); const slot = await heavySlot(); + // The 9:16 end card (outro.mjs) -- the stacked deck's only: a bare short's outro is the card it always was. + const endCard = await endCardOf({ + render: takeManifest.render ?? {}, knobs, provenance: takeManifest.provenance ?? {}, timeline: plan.timeline, + schedule: reframe || landscape ? null : await readJson(path.join(outDir, `vertical-${name}-${tag}`, "schedule.json")), + }); wrapped = await slot(["umtool", "vertical", r.project.id, "--take", take, ...(reel ? ["--reel", reel] : []), "(intro/outro)"], () => wrapShort({ file: outFile, takeDir, render: takeManifest.render ?? {}, manifest: takeManifest, introSpec, outro, - xfade: typeof reelSettings.xfade === "number" ? reelSettings.xfade : 0.3, log: say, + xfade: typeof reelSettings.xfade === "number" ? reelSettings.xfade : 0.3, log: say, endCard, })); made = { ...made, seconds: await RF.probeSeconds(outFile) }; } diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -251,6 +251,8 @@ export default defineConfig({ // would otherwise enumerate every fixture article's corpus and add cards // other specs count. refresh.spec runs the check itself, through its route. `UMTOOL_REFRESH_CHECK=0 ` + + // The Inbox's X jar row (lib/inbox/xJar.ts) asks the stub's services on every read, not from a minute's memo. + `UMTOOL_XJAR_MEMO_MS=0 ` + // The voice match's engine (release 34): the test kit's fake embedder, // run by this node, in the place of scripts/speaker-embed.py and the // TitaNet venv -- the same command line and JSON, no python, no model. diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -229,6 +229,10 @@ import { verticalPostBox, verticalPostEntry, verticalRender, } from "./vertical.mjs"; import { renderSideCard, sideFitFilter } from "./side-card.mjs"; +// THE STACKED VERTICAL DECK (vertical-deck.mjs): a 9:16 cut that keeps its deck -- the picture at full width, the +// captions under it, a clip's two crops, a post item's hero card -- and the modules it leaves out. +import { ENLARGE_WARN, clipTwoCrop, leftOutWords, stackedCaptionGeo, stackedGeometry, stackedOn, twoCropEnlargement, twoCropGraph } from "./vertical-deck.mjs"; +import { verticalFormOf } from "./modules/index.mjs"; import { TRAILER_AUDIO, trailerHitsGraph } from "./trailer-hits.mjs"; import { planContext, planContextOf } from "./post-conversation.mjs"; @@ -476,6 +480,22 @@ export function deckFraming(render, { feed = false, picture = [] } = {}) { }; } +/** + * A post item's box in the stacked vertical deck (vertical-deck.mjs layout 4): + * its card from under the rail down to the panel's top, the frame's ground + * round it -- the rail, the counters under it and the date line are the + * deck's page. `{ box, place }` as verticalPostBox gives them. + */ +export function stackedPostFraming(render) { + const g = stackedGeometry(render); + const c = g.post.card; + const bg = String(render?.palette?.bg ?? "#12100c"); + return { + box: { x: c.x, y: c.y, width: c.width, height: c.height }, + place: [`pad=${g.W}:${g.H}:${c.x}:${c.y}:color=${bg}`, "setsar=1", `fps=${render.fps ?? 30}`], + }; +} + /** `deckFraming`'s two runs joined: a whole picture into the box, then the frame. */ export function deckFramingFilter(render, opts = {}) { const { fit, place } = deckFraming(render, opts); @@ -1783,7 +1803,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // A VERTICAL cut (vertical.mjs): the clip in its layout -- full, framed or quote, or split / overlay when it // carries a side post -- its captions lit word by word, its tag and hook, as one ASS file. A source with no // picture keeps the plain path's poster. - if (dirs.vertical && media.hasVideo) { + if (dirs.vertical && !dirs.vertical.stacked && media.hasVideo) { const layout = clipVerticalLayout(entry, render); const geo = clipGeometry(layout, render, width, height); const [sw, sh] = await probeDims(raw); @@ -1830,6 +1850,51 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, return seg; } + // THE STACKED VERTICAL DECK (vertical-deck.mjs): a clip with two crops (`vertical.layout: "twocrop"`) is the + // frame's ground with crop one over the strip and crop two under it; its captions over crop two's foot. Its + // side post and its poster are the plain deck's (a source with no picture plays there). + const twoCrop = dirs.vertical?.stacked && media.hasVideo ? clipTwoCrop(entry) : null; + if (twoCrop) { + const [sw, sh] = await probeDims(raw); + const fr = framing ?? segmentFraming(render); + const inputs = cutArgs(raw, segA, segB); + let ain = "[0:a]"; + if (soundInput) { + ain = "[1:a]"; + inputs.push(...soundInput); + } + const g = gapped(ain); + const grow = twoCropEnlargement(twoCrop, sw, sh, render); + grow.forEach((x, i) => { + if (x > ENLARGE_WARN) EMIT("note", { message: `${entry.id}: its crop ${i + 1} is drawn ${x}× its source's pixels (past ${ENLARGE_WARN}×: it will look soft) -- a wider crop, or a sharper source` }); + }); + const graph = twoCropGraph({ crops: twoCrop, srcW: sw, srcH: sh, render, blur: await blurPicture(sw, sh), fps: render.fps }); + const cap = dirs.look + ? await segmentCaptions({ + entry, provenance, look: dirs.look, render, outDir, from: cutRecord.start, seconds: segSeconds, bottom: 0, gaps: cutRecord.gaps ?? [], + vertical: { geo: stackedCaptionGeo(render, { twocrop: true }), tag: null, hook: null, side: null }, + }) + : null; + cutRecord.vertical = { layout: "twocrop", crops: twoCrop, width, height, enlarged: grow, ...(cap ? { captions: cap.lines } : {}) }; + await encodeClipSegment({ + seg, outDir, render, opts, id: entry.id, record: { ...cutRecord, framing: fr }, + argv: [ + "-nostdin", "-v", "error", "-y", + ...inputs, + "-filter_complex", [ + ...g.parts, + ...levelParts(null, g.a), + `${g.v}${graph}[vp]`, + cap ? `[vp]${cap.filter}[v]` : "[vp]null[v]", + ].join(";"), + "-map", "[v]", "-map", audioMap, + ...encodeArgs(render), + seg, + ], + }); + return seg; + } + if (deckOn(render)) { const fr = framing ?? segmentFraming(render); const pst = await poster(fr.box, 1); @@ -1840,6 +1905,15 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const sideInput = sideGeo ? await sideCard(sideGeo.w, sideGeo.h) : []; const sideIdx = 1 + (pst ? 1 : 0) + (soundInput ? 1 : 0); const framed = `${pst ? "[pic]" : g.v}${deckFramingFilter(render, { feed: fr.layout === "feed", picture })}`; + // The stacked vertical deck's captions (vertical-deck.mjs): under the picture, each word lit, over the frame. + const vcap = dirs.vertical?.stacked && dirs.look + ? await segmentCaptions({ + entry, provenance, look: dirs.look, render, outDir, from: cutRecord.start, seconds: segSeconds, bottom: 0, gaps: cutRecord.gaps ?? [], + vertical: { geo: stackedCaptionGeo(render), tag: null, hook: null, side: null }, + }) + : null; + if (vcap) cutRecord.vertical = { layout: "stacked", width, height, captions: vcap.lines }; + const capped = (label) => (vcap ? [`${label}[vcx]`, `[vcx]${vcap.filter}[v]`] : null); // The box it was framed into, so --chrome-only can refuse another layout's. await encodeClipSegment({ seg, outDir, render, opts, id: entry.id, record: { ...cutRecord, framing: fr }, @@ -1853,8 +1927,8 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, ...g.parts, ...levelParts(pst ? pst.parts : null, g.a), ...(sideGeo - ? [`${framed}[vb]`, `[${sideIdx}:v]${sideFitFilter(sideGeo.w, sideGeo.h)}[vsc]`, `[vb][vsc]${landscapeSideOverlay(sideGeo, sideUp, render.width)}[v]`] - : [`${framed}[v]`]), + ? [`${framed}[vb]`, `[${sideIdx}:v]${sideFitFilter(sideGeo.w, sideGeo.h)}[vsc]`, ...(capped(`[vb][vsc]${landscapeSideOverlay(sideGeo, sideUp, render.width)}`) ?? [`[vb][vsc]${landscapeSideOverlay(sideGeo, sideUp, render.width)}[v]`])] + : capped(framed) ?? [`${framed}[v]`]), ].join(";"), "-map", "[v]", "-map", audioMap, ...encodeArgs(render), @@ -5835,8 +5909,16 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro // will capture -- the overlay order is the jobs' order, whatever order // they finish in. const jobs = []; + // THE STACKED VERTICAL DECK (vertical-deck.mjs): each page composed at the build's own render (a `--vertical` + // build of a landscape manifest is not the manifest's), and a module with no vertical form left out, said so. + const stacked = stackedOn(render); + const own = verticalOn(render) ? { render } : {}; for (const mod of deckOverlays()) { if (!mod.on(schedule, render)) continue; + if (stacked && !verticalFormOf(mod)) { + if (duration == null) EMIT("note", { message: leftOutWords(mod.id) }); + continue; + } // The shell's events name no region (the deck's, as they always have). const named = mod.region === "deck" ? {} : { region: mod.region }; if (mod.kind === "overlay-whole") { @@ -5844,7 +5926,7 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro EMIT("chrome", { phase: "compose", ...named, ...win }); const t1 = Date.now(); const r = await composeChrome({ - manifestPath, outDir, variant, region: mod.region, doRender: true, + manifestPath, outDir, variant, region: mod.region, doRender: true, ...own, fps: render.fps, workers: CHROME_WORKERS, lease, quality: "high", format: "png-sequence", ...win, // The deck's frames the chunked encode will read, and only those (deckWant). ...(mod.region === "deck" && drawOnly && duration == null ? { want: drawOnly } : {}), @@ -5873,7 +5955,7 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro EMIT("chrome", { phase: "compose", region: mod.region, ...(pr.segment !== undefined ? { segment: pr.segment } : {}) }); const t1 = Date.now(); const p = await composeChrome({ - manifestPath, outDir, variant, region: mod.region, ...(pr.segment !== undefined ? { window: pr.window } : {}), doRender: true, + manifestPath, outDir, variant, region: mod.region, ...(pr.segment !== undefined ? { window: pr.window } : {}), doRender: true, ...own, fps: render.fps, workers: CHROME_WORKERS, lease, quality: "high", format: "png-sequence", }); if (p.frames !== pr.frames || p.frameCount !== pr.frameCount) { @@ -6697,7 +6779,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly if (opts.short) dirs.short = { id: opts.short }; // A vertical cut's hooks may name a clip's section: the deck's markers, read from the cut as written. // A short of a take's items (umtool vertical) passes the WHOLE take's sections: its own timeline is a part of it. - if (vertical) dirs.vertical = { on: true, sections: opts.verticalSections ? new Map(Object.entries(opts.verticalSections)) : sectionTitlesOf(whole) }; + if (vertical) dirs.vertical = { on: true, sections: opts.verticalSections ? new Map(Object.entries(opts.verticalSections)) : sectionTitlesOf(whole), stacked: stackedOn(render) }; // A project's out/ first, through ensureOutDir: with UMTOOL_MEDIA_DIR set it // is a link to the media root, and the recursive mkdirs below would @@ -6993,7 +7075,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // A post item (post-render.mjs): its card drawn from the archived post, its attachments laid in. EMIT("card", { id: entry.id, i, n: entries.length }); const fr = deck ? framing ?? segmentFraming(render) : null; - const df = fr ? deckFraming(render, { feed: fr.layout === "feed" }) : vertical ? verticalPostBox(render) : null; + // The stacked vertical deck (vertical-deck.mjs): the hero card, from under the rail to the panel's top. + const df = dirs.vertical?.stacked ? stackedPostFraming(render) : fr ? deckFraming(render, { feed: fr.layout === "feed" }) : vertical ? verticalPostBox(render) : null; const seg = await buildPostSegment(entry, { render, outDir, manifestDir, box: df ? { width: df.box.width, height: df.box.height } : { width: render.width, height: render.height }, @@ -7646,6 +7729,8 @@ export async function cliEstimateMb(manifestPath, opts = {}, env = process.env) xfade: !opts.noXfade, single: Boolean(opts.clipPreview || opts.short), batch, + // A `--vertical` build of a landscape manifest (`umtool vertical`), its knobs: a stacked deck's floor. + ...(opts.vertical ? { vertical: opts.verticalKnobs && typeof opts.verticalKnobs === "object" ? opts.verticalKnobs : true } : {}), }); } diff --git a/umtool/report-to-video/chrome-deck.mjs b/umtool/report-to-video/chrome-deck.mjs @@ -853,7 +853,10 @@ export function deckHtml(schedule, render, opts = {}) { // As written in two lines, the count gives the second line its room. const countSize = tb ? Math.round(tb.height * (labelLines > 1 ? 0.36 : 0.42)) : 0; const countBox = Math.round(countSize * 1.12); - const labelSize = written ? TALLY_WRITTEN.size : 13; + // A band off 1080 (deckLayout `scale`, a 720p frame's): its fixed sizes scaled with it; at 1080 the numbers as ever. + const ks = lay.scale ?? 1; + const zs = ks === 1 ? (v) => v : (v) => Math.round(v * ks); + const labelSize = zs(written ? TALLY_WRITTEN.size : 13); const labelBox = written ? TALLY_WRITTEN.lineBox : 17; const labelBlock = labelBox * labelLines; const cellTop = tb ? Math.round((tb.height - (countBox + 8 + labelBlock)) / 2) + 2 : 0; @@ -1058,21 +1061,21 @@ export function deckHtml(schedule, render, opts = {}) { .mstick { position: absolute; left: -1.5px; top: -14px; width: 3px; height: 20px; border-radius: 1.5px; background: var(--mc); } .mhead { position: absolute; left: 1.5px; top: -14px; width: 12px; height: 10px; background: var(--mc); clip-path: polygon(0% 0%, 100% 50%, 0% 100%); } - .mlabel { position: absolute; top: ${(band?.y ?? 3) + (staggered ? MARKER_ROW : 0) - tr.y}px; height: 20px; text-align: center; white-space: nowrap; - overflow: hidden; text-overflow: ellipsis; font-family: 'DeckSansBold', sans-serif; font-size: ${MARKER_LABEL_SIZE}px; - line-height: 20px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--mc); + .mlabel { position: absolute; top: ${(band?.y ?? 3) + (staggered ? zs(MARKER_ROW) : 0) - tr.y}px; height: ${zs(20)}px; text-align: center; white-space: nowrap; + overflow: hidden; text-overflow: ellipsis; font-family: 'DeckSansBold', sans-serif; font-size: ${zs(MARKER_LABEL_SIZE)}px; + line-height: ${zs(20)}px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--mc); text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); }` : ""}${markers.some((mk) => mk.level === 2 && mk.label && !mk.hide) ? ` /* A subsection's flag: shorter, its head smaller, its words smaller and quieter. */ .mflag.sub .mstick { top: -8px; height: 14px; width: 2px; left: -1px; } .mflag.sub .mhead { top: -8px; left: 1px; width: 8px; height: 7px; } - .mflag.sub .mlabel { font-size: ${MARKER_SUB_LABEL_SIZE}px; opacity: 0.72; }` : ""}${markers.some((mk) => !mk.label || mk.hide) ? ` + .mflag.sub .mlabel { font-size: ${zs(MARKER_SUB_LABEL_SIZE)}px; opacity: 0.72; }` : ""}${markers.some((mk) => !mk.label || mk.hide) ? ` /* An unlabelled marker: a short tick across the track, no words. */ .mtick { position: absolute; left: -1px; top: -6px; width: 2px; height: 12px; border-radius: 1px; background: var(--mc); opacity: 0.85; }` : ""}${markers.some((mk) => (!mk.label || mk.hide) && mk.level === 2) ? ` /* A subsection's tick: half as tall. */ .mflag.sub .mtick { top: -3px; height: 6px; opacity: 0.7; }` : ""}${staggered ? ` /* Staggered labels: row 1 a row above, its flag's stick up to it. */ .mflag.up .mlabel { top: ${band.y - tr.y}px; } - .mflag.up .mstick { top: ${band.y + 20 - tr.y}px; height: ${tr.y + 6 - (band.y + 20)}px; }` : ""}${stRow ? ` + .mflag.up .mstick { top: ${band.y + zs(20) - tr.y}px; height: ${tr.y + 6 - (band.y + zs(20))}px; }` : ""}${stRow ? ` /* The section title: the current section's name, one quiet line centred under the track; ellipsized, never wrapped. */ .stitle { position: absolute; left: ${stRow.x}px; top: ${stRow.y}px; width: ${stRow.width}px; height: ${stRow.height}px; diff --git a/umtool/report-to-video/chrome-instruments.mjs b/umtool/report-to-video/chrome-instruments.mjs @@ -14,6 +14,7 @@ // frame whose values did not move keys as the frame before it -- the needle at // rest between two weights is captured once, not once a frame. import { cueTime, deckChoreography, even, instrumentsGeometry, railGap } from "./deck.mjs"; +import { stackedGeometry, stackedOn, stackedStandDowns } from "./vertical-deck.mjs"; import { mix, rgba } from "./chrome-deck.mjs"; import { finaleLayout } from "./chrome-finale.mjs"; import { FINALE_MOTION } from "./finale.mjs"; @@ -82,13 +83,47 @@ function windowOf(schedule, opts, what) { function withDeck(L, schedule, render, k) { L.set(k, { autoAlpha: 1 }); const fin = Number.isFinite(schedule?.finale?.from) ? schedule.finale.from : null; + const stacked = stackedOn(render); + const shown = []; for (const v of deckChoreography(schedule, render).visibility) { const [a, b] = v.at; // Going under the finale: over its grow, as the dial's finale comes in (dialFinaleHtml) -- a crossfade. const intoFinale = v.hide && fin !== null && Math.abs(a - fin) < 0.6; const dur = intoFinale ? Math.max(b - a, FINALE_MOTION.grow) : Math.max(INSTANT, b - a); - L.add(k, a, dur, { autoAlpha: v.hide ? 0 : 1 }, v.hide ? "power1.in" : "power2.out"); + if (!stacked) L.add(k, a, dur, { autoAlpha: v.hide ? 0 : 1 }, v.hide ? "power1.in" : "power2.out"); + else shown.push({ at: a, dur, hide: v.hide }); } + if (!stacked) return; + // THE STACKED VERTICAL DECK (vertical-deck.mjs): the panel stands down over a post item (its card takes the + // room) and a twocrop clip (its strip carries the numbers) -- out over the join into it, back over the join out. + const D = Number(schedule.transition) || 0; + const m = Math.max(D, 0.3); + for (const sd of mergedSpans(stackedStandDowns(schedule))) { + shown.push({ at: Math.max(0, sd.from), dur: m, hide: true }); + if (sd.to < (schedule.total ?? Infinity) - 0.05) shown.push({ at: sd.to, dur: m, hide: false }); + } + // Each change once, in time: a stand-down inside a span the deck is already away for adds nothing. + shown.sort((p, q) => p.at - q.at); + let hidden = false; + let depth = 0; + for (const v of shown) { + depth += v.hide ? 1 : -1; + const want = depth > 0; + if (want === hidden) continue; + hidden = want; + L.add(k, v.at, v.dur, { autoAlpha: want ? 0 : 1 }, want ? "power1.in" : "power2.out"); + } +} + +/** Spans that touch or overlap, as one. */ +function mergedSpans(spans) { + const out = []; + for (const sp of [...spans].sort((a, b) => a.from - b.from)) { + const last = out[out.length - 1]; + if (last && sp.from <= last.to + 0.05) last.to = Math.max(last.to, sp.to); + else out.push({ ...sp }); + } + return out; } /** Blocks shown one at a time: block j from `list[j].t` to the next one's. */ @@ -784,6 +819,12 @@ export function trailYields(schedule, render) { */ export function dialFinaleGeometry(schedule, render) { if (!schedule?.finale) return null; + // THE STACKED VERTICAL DECK (vertical-deck.mjs): the instrument column over the picture's room, its title where + // the rail stands -- the landscape finale's page is not drawn there, so this one is opaque. + if (stackedOn(render)) { + const f = stackedGeometry(render).finale; + return { x: f.title.x, y: f.title.y, width: f.column.width, height: 2 * Math.floor((f.column.y + f.column.height - f.title.y) / 2) }; + } const g = finaleLayout(schedule, render).geo; if (g.stats) return null; const kh = g.H / 1080; @@ -883,13 +924,24 @@ export function dialFinaleHtml(schedule, render, window, opts = {}) { // The claim ghosts STAY: the finale is the summary, and the residue of every number he gave is the point of it -- // each tick at its count at the cut's end, in with the finale's grow under the needle's drop, no pulses. const ghosts = ghostsOf(M, render, colors); - const size = even(Math.min(H, Math.round(W * 0.56))); + // Portrait (the stacked vertical deck): its title on top, the dial large in a card under it, the odometer and + // NET under that, all on an opaque ground (no landscape finale page under it). Landscape: the dial beside the wheels. + const portrait = stackedOn(render); + const u = W / 912; + const titleH = portrait ? Math.round(64 * u) : 0; + const cardH = portrait ? even(Math.round(H * 0.46)) : 0; + const size = portrait ? even(Math.min(W * 0.62, cardH - Math.round(36 * u))) : even(Math.min(H, Math.round(W * 0.56))); const k = size / 524; - const dial = dialParts({ size, ox: 0, oy: Math.floor((H - size) / 2), scale: M.scale, cfg, colors, fonts, track, marks, lines, ghosts, prefix: "f", preState: false }); - const rw = W - size - Math.round(40 * k); + const dial = dialParts({ + size, ox: portrait ? Math.floor((W - size) / 2) : 0, oy: portrait ? titleH + Math.round(18 * u) + Math.floor((cardH - size) / 2) : Math.floor((H - size) / 2), + scale: M.scale, cfg, colors, fonts, track, marks, lines, ghosts, prefix: "f", preState: false, + }); + const rw = portrait ? W - Math.round(48 * u) : W - size - Math.round(40 * k); const top = Math.max(Number(M.totals?.lost) || 0, nums.lost); const wheels = wheelCount(top); - const ob = { x: size + Math.round(40 * k), y: Math.floor((H - size) / 2) + Math.round(24 * k), width: rw }; + const ob = portrait + ? { x: Math.round(24 * u), y: titleH + Math.round(18 * u) + cardH + Math.round(34 * u), width: rw } + : { x: size + Math.round(40 * k), y: Math.floor((H - size) / 2) + Math.round(24 * k), width: rw }; const odo = odometerParts({ W: rw, H: H - ob.y, u: Math.min(1, rw / 420), cfg: { ...ocfg, runs: true }, colors, fonts, track: { lost: [{ t: from, total: 0, runs: 0 }, { t: A + 0.6, total: nums.lost, runs: nums.runs }] }, wheels, @@ -920,12 +972,19 @@ export function dialFinaleHtml(schedule, render, window, opts = {}) { L.set("onet", { autoAlpha: 0 }); L.add("onet", A + 3.2, 0.5, { autoAlpha: 1 }, "power1.out"); const { init, cues } = L.build(); + const ground = portrait ? ` + .fg { position: absolute; inset: 0; background: ${colors.bg}; } + .ftitle { position: absolute; left: 0; top: 0; height: ${titleH}px; line-height: ${titleH}px; font-family: ${fontStack(fonts, "display")}; + font-size: ${Math.round(40 * u)}px; letter-spacing: 0.06em; color: ${colors.accent}; white-space: nowrap; } + .fcard { position: absolute; left: 0; top: ${titleH + Math.round(18 * u)}px; width: ${W}px; height: ${cardH}px; border-radius: ${Math.round(24 * u)}px; + background: ${colors.card}; box-shadow: inset 0 0 0 1px ${colors.rule}; }` : ""; + const groundHtml = portrait ? `<div class="fg"></div><div class="ftitle">${esc(opts.title ?? "THE RECORD SO FAR")}</div><div class="fcard"></div>` : ""; return pageHtml({ id: "dial-finale", W, H, fps, fonts, gsap: opts.gsap, data: { from, dur, init, cues }, - css: `#rt { position: absolute; inset: 0; }${dial.css} + css: `#rt { position: absolute; inset: 0; }${ground}${dial.css} .ob { position: absolute; left: ${ob.x}px; top: ${ob.y}px; width: ${ob.width}px; height: ${H - ob.y}px; }${odo.css}`, - body: `<div id="rt" data-k="rt">${dial.html}<div class="ob">${odo.html}</div></div>`, + body: `<div id="rt" data-k="rt">${groundHtml}${dial.html}<div class="ob">${odo.html}</div></div>`, }); } diff --git a/umtool/report-to-video/chrome-story.mjs b/umtool/report-to-video/chrome-story.mjs @@ -15,7 +15,7 @@ // that fills as the cut plays: a row comes in on its first clip, its // outcome on the outcome's clip (else the end of its last evidence clip). // Each STATE of the ledger is its own block, shown over exactly its span. -import { deckGeometry, feedGeometry } from "./deck.mjs"; +import { deckGeometry, feedGeometry, overlayBox, pictureK } from "./deck.mjs"; import { rgba } from "./chrome-deck.mjs"; import { compileCues, cuePageHtml, dateText, esc, joinSpans, r4, segmentSpans, spanEvents, INSTANT } from "./chrome-cues.mjs"; import { CHAPTER_DEFAULTS, PAIR_DEFAULTS, STATUS_DEFAULTS } from "./modules/story-settings.mjs"; @@ -24,11 +24,13 @@ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); /** The footage box this cut's clips play in (the feed's when it is one). */ export function footageBox(render, { feed = false } = {}) { - const f = feed ? feedGeometry(render).footage : deckGeometry(render).footage; + // The stacked vertical deck's picture inside the safe area (overlayBox); the footage box otherwise. + const f = overlayBox(render, { feed }); return { x: f.x, y: f.y, width: f.width, height: f.height }; } -const scaleOf = (render) => (render?.width ?? 1920) / 1920; +// Over the footage at the frame's share of its 1920 design (pictureK: the stacked vertical deck's own size). +const scaleOf = (render) => pictureK(render, render?.width ?? 1920); const pxOf = (render) => (v) => Math.max(1, Math.round(v * scaleOf(render))); const even = (v) => 2 * Math.round(v / 2); diff --git a/umtool/report-to-video/chrome-vdeck.mjs b/umtool/report-to-video/chrome-vdeck.mjs @@ -0,0 +1,358 @@ +// THE STACKED VERTICAL DECK'S PAGE (vertical-deck.mjs): the deck's shell, in +// 9:16. One HyperFrames page over the whole frame, transparent but for what it +// draws -- the rail under the top band (the section's name, its progress +// segments, "2 / 5"), each segment's source block above the bottom band (the +// QR, channel · title · date · time; a post item's big date line and who +// posted it), the tally's cells when the cut counts, the site's wordmark dim in +// the bottom band -- and, for a twocrop clip, the source line over the rail at +// the top, the one-row strip of the instruments between its crops and the QR +// small and low-left. +// +// The schedule is the landscape deck's (deck.mjs deckSchedule: the same +// segments, the same handovers, the same stamps); only where things stand is +// this page's. The pictures (the footage, the crops, a post's card) are the +// segments' own; the instruments are their own pages in the panel. +// +// PURE, as the other pages: a schedule and a render block in, an HTML string +// out (measure-draw.mjs pageHtml, its cue interpreter -- every state a block +// shown over exactly its span, so a frame whose words did not move keys as the +// frame before it). + +import { deckChoreography, pipSegments, resolveDeck, resolveSectionTitle, stackedCounterOn } from "./deck.mjs"; +import { mix, rgba } from "./chrome-deck.mjs"; +import { resolveCounter } from "./counter.mjs"; +import { tallyLabelOf, tallyOf, tallySteps } from "./factcheck.mjs"; +import { resolveDial, resolveOdometer } from "./instruments.mjs"; +import { cueList, esc, fmtSigned, fmtWeight, INSTANT, measureTrack, pageHtml, r4 } from "./measure-draw.mjs"; +import { stackedGeometry } from "./vertical-deck.mjs"; + +const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/; + +/** The deck's text motion in the stacked deck: a block out, the next in (the landscape deck's `motion`). */ +const swap = (deck) => ({ out: deck.motion?.out ?? 0.3, in: deck.motion?.in ?? 0.45 }); + +/** + * The rail's sections: the markers (`deck.markers`, each after a pip's clip) + * split the pipped segments; the first is `sectionTitle.first`'s. Each + * `{ label, color, pips: [segment index…] }`, and `of` the section of each + * pipped segment. One section (no markers): the clips' count is the rail. + */ +export function stackedSections(schedule, render) { + const d = resolveDeck(render); + const pal = render?.palette ?? {}; + const st = resolveSectionTitle(render); + const pipped = pipSegments(schedule); + const byColor = d.pip?.color === "section"; + const hexOf = (key, fallback) => (typeof key === "string" && HEX_RE.test(key) ? key : (key && pal[key]) || fallback); + const after = new Map((Array.isArray(d.markers) ? d.markers : []) + .filter((m) => m && typeof m.after === "string" && m.level !== 2) + .map((m) => [m.after, m])); + const sections = [{ label: st?.first ?? "", color: byColor ? hexOf(d.pip?.sectionColor0, pal.accent ?? "#22AB83") : pal.accent ?? "#22AB83", pips: [] }]; + pipped.forEach((s, j) => { + sections[sections.length - 1].pips.push(j); + const m = after.get(s.id); + if (m && j < pipped.length - 1) { + sections.push({ label: String(m.label ?? "").trim(), color: byColor ? hexOf(m.color, pal.fg ?? "#ffffff") : pal.accent ?? "#22AB83", pips: [] }); + } + }); + const of = []; + sections.forEach((sec, i) => sec.pips.forEach((j) => { of[j] = i; })); + return { sections, of, pipped }; +} + +/** When each pipped segment takes the rail: the first at 0, each after it at its handover (its start plus half the join). */ +function railTimes(schedule) { + const D = Number(schedule.transition) || 0; + return pipSegments(schedule).map((s, j) => (j === 0 ? 0 : r4(s.start + D / 2))); +} + +/** The site's name the bottom band's wordmark says: its host's first label ("jeralyzer.pages.dev" → "JERALYZER"). */ +export function wordmarkOf(provenance) { + const o = String(provenance?.siteOrigin ?? "").trim(); + if (!o) return ""; + try { + return new URL(o).hostname.split(".")[0].toUpperCase(); + } catch { + return ""; + } +} + +/** The values a twocrop clip's strip shows at `t`: what he says he weighs, what he says he has lost, NET. */ +function stripCells(M, render) { + if (!M) return []; + const track = measureTrack(M); + const dial = resolveDial(render); + const odo = resolveOdometer(render); + const at = (list, t) => [...list].reverse().find((x) => x.t <= t + 1e-6) ?? list[0] ?? null; + const cells = []; + if (dial) cells.push({ label: dial.label, value: (t) => { const c = at(track.current, t); return Number.isFinite(c?.value) ? `${c.qualifier ?? ""}${fmtWeight(c.value)}` : "NOT YET"; } }); + if (odo) cells.push({ label: odo.label.replace(/^POUNDS /, ""), value: (t) => fmtWeight(at(track.lost, t)?.total ?? 0) }); + if (odo?.net) { + cells.push({ label: "NET", value: (t) => { + const n = at(track.net, t)?.net; + const f = typeof n?.from === "number" ? n.from : n?.from?.value; + const to = typeof n?.to === "number" ? n.to : n?.to?.value; + return Number.isFinite(f) && Number.isFinite(to) ? fmtSigned(to - f) : "—"; + } }); + } + const times = [...new Set([0, ...track.current.map((x) => x.t), ...track.lost.map((x) => x.t), ...track.net.map((x) => x.t)])].sort((a, b) => a - b); + return cells.map((c) => ({ label: c.label, runs: times.map((t) => ({ t, text: c.value(t) })).filter((r, i, all) => i === 0 || r.text !== all[i - 1].text) })); +} + +/** + * The stacked deck's page for the whole cut (or a window of it). `qrSrcs` = + * `{ <segment id>: "assets/qrNN.png" }`; `fonts` the deck's faces by name + * (DeckSans, DeckSansBold, MeasureDisplay, MeasureCond); `site` the + * wordmark's words. + */ +export function stackedDeckHtml(schedule, render, opts = {}) { + const deck = resolveDeck(render); + const pal = { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F", ...(render?.palette ?? {}) }; + const tally = tallyOf(schedule, render); + const g = stackedGeometry(render, { counter: stackedCounterOn(render) }); + const W = g.W, H = g.H; + const u = W / 1080; + const px = (v) => Math.round(v * u); + const fps = schedule.fps ?? render.fps ?? 30; + const fonts = opts.fonts ?? {}; + const qrSrcs = opts.qrSrcs ?? {}; + const from = Number(opts.from ?? 0); + const total = schedule.total; + const dur = opts.duration != null ? Number(opts.duration) : r4(total - from); + if (!(dur > 0)) throw new Error(`deck: nothing to render from ${from}s of a ${total}s cut`); + const windowed = from > 0 || Math.abs(dur - total) > 1e-6; + const D = Number(schedule.transition) || 0; + const m = swap(deck); + const segs = schedule.segments ?? []; + const display = fonts.MeasureDisplay ? "'MeasureDisplay', 'DeckSansBold', sans-serif" : "'DeckSansBold', sans-serif"; + const cond = fonts.MeasureCond ? "'MeasureCond', 'DeckSans', sans-serif" : "'DeckSans', sans-serif"; + const card = mix(pal.bg, pal.fg, 0.06); + const rule = mix(pal.bg, pal.fg, 0.16); + const L = cueList(fps); + + // ---- the page's visibility: the deck's own (away over a card, a teaser, the finale) ---- + L.set("rt", { autoAlpha: 1 }); + for (const v of deckChoreography(schedule, render).visibility) { + const [a, b] = v.at; + L.add("rt", a, Math.max(INSTANT, b - a), { autoAlpha: v.hide ? 0 : 1 }, v.hide ? "power1.in" : "power2.out"); + } + + // ---- each segment's span on the deck: from its handover in to the next one's ---- + const handIn = (i) => (i === 0 ? 0 : r4(segs[i].start + D / 2)); + const handOut = (i) => (i + 1 < segs.length ? r4(segs[i + 1].start + D / 2) : total); + const twocrop = (s) => s?.vlayout === "twocrop"; + const show = (k, i, { fade = true } = {}) => { + const a = handIn(i); + const b = handOut(i); + L.set(k, { autoAlpha: a <= 0 ? 1 : 0 }); + if (a > 0) L.add(k, a, fade ? m.in : INSTANT, { autoAlpha: 1 }, "power2.out"); + if (b < total - 1e-6) L.add(k, Math.max(a + INSTANT, b - (fade ? m.out : 0)), fade ? m.out : INSTANT, { autoAlpha: 0 }, "power1.in"); + }; + + // ---- the rail: the section's name, its progress, "2 / 5" -- and a twocrop clip's own over its source line ---- + const { sections, of, pipped } = stackedSections(schedule, render); + const times = railTimes(schedule); + const many = sections.length > 1; + const railBars = (pre) => sections.map((sec, i) => `<div class="bar" style="flex:${Math.max(1, sec.pips.length)}; background:${rgba(sec.color, 0.22)}"><div class="fill" data-k="${pre}f${i}" style="background:${sec.color}"></div></div>`).join(""); + const railLabels = (pre, cls) => sections.map((sec, i) => `<div class="${cls}" data-k="${pre}l${i}" style="color:${sec.color}">${esc(sec.label)}</div>`).join(""); + const counts = many + ? sections.map((_, i) => `<div class="rcount" data-k="rc${i}">${i + 1} / ${sections.length}</div>`).join("") + : pipped.map((_, j) => `<div class="rcount" data-k="rc${j}">${j + 1} / ${pipped.length}</div>`).join(""); + // The fills and the labels: a section filled to its share as each of its clips takes the rail, the ones before full. + for (const pre of ["r", "t"]) { + sections.forEach((_, i) => { + L.set(`${pre}f${i}`, { scaleX: 0, transformOrigin: "0% 50%" }); + L.set(`${pre}l${i}`, { autoAlpha: 0 }); + }); + } + (many ? sections : pipped).forEach((_, i) => L.set(`rc${i}`, { autoAlpha: 0 })); + let curSec = null; + pipped.forEach((_, j) => { + const s = of[j]; + const sec = sections[s]; + const share = (sec.pips.indexOf(j) + 1) / sec.pips.length; + const t = times[j]; + for (const pre of ["r", "t"]) { + if (curSec !== null && curSec !== s) { + L.add(`${pre}f${curSec}`, t, 0.35, { scaleX: 1 }, "power2.out"); + L.add(`${pre}l${curSec}`, t, 0.25, { autoAlpha: 0 }, "power1.in"); + } + L.add(`${pre}f${s}`, t, t <= 0 ? INSTANT : 0.5, { scaleX: r4(share) }, "power2.inOut"); + if (curSec !== s) L.add(`${pre}l${s}`, t, t <= 0 ? INSTANT : 0.3, { autoAlpha: 1 }, "power2.out"); + } + const ck = many ? s : j; + const prevCk = many ? curSec : j - 1; + if (prevCk !== null && prevCk >= 0 && prevCk !== ck) L.add(`rc${prevCk}`, t, INSTANT, { autoAlpha: 0 }); + if (prevCk !== ck) L.add(`rc${ck}`, t, INSTANT, { autoAlpha: 1 }); + curSec = s; + }); + // The rail itself: up but over a twocrop clip, whose own stands over its source line. + L.set("rail", { autoAlpha: 1 }); + L.set("top2", { autoAlpha: 0 }); + segs.forEach((s, i) => { + if (!twocrop(s)) return; + L.add("rail", handIn(i) - m.out, m.out, { autoAlpha: 0 }, "power1.in"); + L.add("top2", handIn(i), m.in, { autoAlpha: 1 }, "power2.out"); + if (handOut(i) < total - 1e-6) { + L.add("top2", handOut(i) - m.out, m.out, { autoAlpha: 0 }, "power1.in"); + L.add("rail", handOut(i), m.in, { autoAlpha: 1 }, "power2.out"); + } + }); + + // ---- each segment's source block ---- + const blocks = []; + const tops = []; + const strips = []; + const smallQrs = []; + const M = schedule.measure && Array.isArray(schedule.measure.state) ? schedule.measure : null; + const cellsAll = stripCells(M, render); + segs.forEach((s, i) => { + if (s.hideDeck) return; + const qr = qrSrcs[s.id] ?? null; + const k = `s${i}`; + if (twocrop(s)) { + // The source line over the rail at the top; the QR small and low-left; the instruments' strip between the crops. + const v = s.vsource ?? {}; + tops.push(`<div class="tline" data-k="${k}t"><span class="tch">${esc(v.channel || s.title || "")}</span><span class="tdt">${esc([v.date, v.clock].filter(Boolean).join(" · "))}</span></div>`); + show(`${k}t`, i); + if (qr) { + smallQrs.push(`<img class="qrs" data-k="${k}q" src="${esc(qr)}" alt="" />`); + show(`${k}q`, i); + } + if (cellsAll.length) { + const cells = cellsAll.map((c, ci) => { + const runs = c.runs.map((r, ri) => `<div class="sv" data-k="${k}c${ci}r${ri}">${esc(r.text)}</div>`).join(""); + c.runs.forEach((r, ri) => { + const a = r.t; + const b = c.runs[ri + 1]?.t ?? Infinity; + L.set(`${k}c${ci}r${ri}`, { autoAlpha: a <= 0 && b > 0 ? 1 : 0 }); + if (a > 0) L.add(`${k}c${ci}r${ri}`, a, INSTANT, { autoAlpha: 1 }); + if (Number.isFinite(b)) L.add(`${k}c${ci}r${ri}`, b, INSTANT, { autoAlpha: 0 }); + }); + return `<div class="scell"><div class="sl">${esc(c.label)}</div><div class="svs">${runs}</div></div>`; + }).join(""); + strips.push(`<div class="strip" data-k="${k}x" style="grid-template-columns: repeat(${cellsAll.length}, minmax(0, 1fr))">${cells}</div>`); + show(`${k}x`, i); + } + return; + } + let words; + if (s.type === "post") { + words = `<div class="pdate">${esc(s.title ?? "")}</div><div class="pwho">${esc(s.subtitle ?? "")}</div>`; + } else if (s.vsource) { + const v = s.vsource; + words = `<div class="ch">${esc(v.channel)}</div><div class="ti">${esc(v.title)}</div><div class="dt">${esc([v.date, v.clock].filter(Boolean).join(" · "))}</div>`; + } else { + words = `<div class="ch">${esc(s.title ?? "")}</div><div class="ti">${esc(s.subtitle ?? "")}</div>`; + } + const html = `<div class="src" data-k="${k}">${qr ? `<img class="qr" src="${esc(qr)}" alt="" />` : ""}<div class="words${qr ? "" : " noqr"}">${words}</div></div>`; + blocks.push(html); + show(k, i); + }); + + // ---- the tally: a cell per verdict the cut counts, its count over its label; under a post item's card ---- + let tallyHtml = ""; + if (tally?.length) { + const byId = resolveCounter(render).byId ?? {}; + const steps = tallySteps(schedule.factcheck?.stamps ?? [], tally); + const cells = tally.map((v, ci) => { + const vr = byId[v] ?? {}; + const color = HEX_RE.test(vr.color ?? "") ? vr.color : pal.accent; + const runs = [{ at: 0, n: 0 }, ...steps.filter((x) => x.verdict === v).map((x) => ({ at: x.at, n: x.count }))]; + const nums = runs.map((r, ri) => { + const kk = `tn${ci}r${ri}`; + const b = runs[ri + 1]?.at ?? Infinity; + L.set(kk, { autoAlpha: r.at <= 0 && b > 0 ? 1 : 0 }); + if (r.at > 0) L.add(kk, r.at, INSTANT, { autoAlpha: 1 }); + if (Number.isFinite(b)) L.add(kk, b, INSTANT, { autoAlpha: 0 }); + return `<div class="tnum" data-k="${kk}" style="color:${color}">${r.n}</div>`; + }).join(""); + const label = tallyLabelOf(vr) ?? vr.label ?? v; + return `<div class="tcell" style="border-color:${rgba(color, 0.5)}"><div class="tlab">${esc(label)}</div><div class="tnums">${nums}</div></div>`; + }).join(""); + tallyHtml = `<div class="talv" data-k="talv"><div class="tally" data-k="tal">${cells}</div></div>`; + // Under a post item's card while it is up; over the source block otherwise. + const dy = g.post.counters.y - (g.counters?.y ?? g.post.counters.y); + L.set("tal", { y: 0 }); + segs.forEach((s, i) => { + if (s.type !== "post" || !dy) return; + L.add("tal", handIn(i) - m.out, m.out + m.in, { y: dy }, "power2.inOut"); + if (handOut(i) < total - 1e-6) L.add("tal", handOut(i) - m.out, m.out + m.in, { y: 0 }, "power2.inOut"); + }); + // Over a twocrop clip its row would stand on crop two: it stands down (its strip carries the numbers). + L.set("talv", { autoAlpha: 1 }); + segs.forEach((s, i) => { + if (!twocrop(s)) return; + L.add("talv", handIn(i) - m.out, m.out, { autoAlpha: 0 }, "power1.in"); + if (handOut(i) < total - 1e-6) L.add("talv", handOut(i), m.in, { autoAlpha: 1 }, "power2.out"); + }); + } + + const site = typeof opts.site === "string" ? opts.site : ""; + const { init, cues } = L.build(); + const sq = g.source.qr; + const st = g.source.text; + const tq = g.twocrop.qr; + const t2 = g.twocrop.top; + const strip = g.twocrop.strip; + const ct = g.counters ?? { x: g.safe.x0, y: g.source.y - px(100), width: g.safe.x1 - g.safe.x0, height: px(80) }; + const css = ` + #rt { position: absolute; inset: 0; } + .rail, .top2 { position: absolute; left: ${g.rail.x}px; top: ${g.rail.y}px; width: ${g.rail.width}px; height: ${g.rail.height}px; } + .top2 { top: ${t2.y}px; height: ${t2.height}px; } + .rlab, .rcount, .tlab2 { position: absolute; top: 0; height: ${g.rail.label}px; line-height: ${g.rail.label}px; white-space: nowrap; overflow: hidden; } + .rlab { left: 0; right: ${px(130)}px; font-family: ${display}; font-size: ${px(40)}px; letter-spacing: 0.06em; text-transform: uppercase; text-overflow: ellipsis; } + .rcount { right: 0; font-family: 'DeckSans', sans-serif; font-size: ${px(24)}px; color: ${pal.muted}; font-variant-numeric: tabular-nums; } + .bars { position: absolute; left: 0; right: 0; bottom: 0; height: ${g.rail.bar}px; display: flex; gap: ${px(8)}px; } + .bar { position: relative; height: 100%; border-radius: ${px(2)}px; overflow: hidden; } + .fill { position: absolute; inset: 0; } + .top2 .bars { bottom: ${px(4)}px; right: ${px(260)}px; } + .tlab2 { top: auto; bottom: ${px(-8)}px; right: 0; width: ${px(250)}px; text-align: right; font-family: ${display}; font-size: ${px(30)}px; letter-spacing: 0.06em; text-transform: uppercase; text-overflow: ellipsis; } + .tline { position: absolute; left: 0; top: 0; right: 0; height: ${px(44)}px; line-height: ${px(44)}px; white-space: nowrap; overflow: hidden; } + .tch { font-family: 'DeckSansBold', sans-serif; font-size: ${px(30)}px; color: ${pal.fg}; margin-right: ${px(16)}px; } + .tdt { font-family: 'DeckSans', sans-serif; font-size: ${px(27)}px; color: ${pal.accent}; font-variant-numeric: tabular-nums; } + .src { position: absolute; left: ${g.source.x}px; top: ${g.source.y}px; width: ${g.source.width}px; height: ${g.source.height}px; + border-top: ${Math.max(1, px(2))}px solid ${rule}; } + .src .qr { position: absolute; left: 0; top: ${sq.y - g.source.y}px; width: ${sq.size}px; height: ${sq.size}px; border-radius: ${px(8)}px; + image-rendering: pixelated; box-shadow: 0 0 0 1px ${rgba(pal.fg, 0.25)}; } + .src .words { position: absolute; left: ${st.x - g.source.x}px; top: ${st.y - g.source.y}px; width: ${st.width}px; height: ${st.height}px; + display: flex; flex-direction: column; justify-content: center; gap: ${px(6)}px; } + .src .words.noqr { left: 0; width: ${g.source.width}px; } + .src .ch { font-family: 'DeckSansBold', sans-serif; font-size: ${px(32)}px; color: ${pal.fg}; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .src .ti { font-family: 'DeckSans', sans-serif; font-size: ${px(28)}px; color: ${mix(pal.muted, pal.fg, 0.45)}; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .src .dt { font-family: 'DeckSans', sans-serif; font-size: ${px(28)}px; color: ${pal.accent}; font-variant-numeric: tabular-nums; white-space: nowrap; } + .src .pdate { font-family: ${display}; font-size: ${px(56)}px; line-height: 1; color: ${pal.fg}; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .src .pwho { font-family: 'DeckSans', sans-serif; font-size: ${px(28)}px; color: ${mix(pal.muted, pal.fg, 0.45)}; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .qrs { position: absolute; left: ${tq.x}px; top: ${tq.y}px; width: ${tq.size}px; height: ${tq.size}px; border-radius: ${px(6)}px; opacity: 0.9; image-rendering: pixelated; } + .strip { position: absolute; left: 0; top: ${strip.y}px; width: ${W}px; height: ${strip.height}px; background: ${card}; + border-top: 1px solid ${rule}; border-bottom: 1px solid ${rule}; display: grid; padding: 0 ${W - g.safe.x1}px 0 ${g.safe.x0}px; } + .scell { position: relative; display: flex; flex-direction: column; justify-content: center; gap: ${px(4)}px; padding-left: ${px(20)}px; border-left: 1px solid ${rule}; } + .scell:first-child { padding-left: 0; border-left: 0; } + .scell .sl { font-family: ${cond}; font-size: ${px(21)}px; letter-spacing: 0.08em; color: ${pal.muted}; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .scell .svs { position: relative; height: ${px(42)}px; } + .scell .sv { position: absolute; left: 0; top: 0; font-family: ${display}; font-size: ${px(38)}px; line-height: ${px(42)}px; color: ${pal.fg}; white-space: nowrap; } + .talv { position: absolute; inset: 0; } + .tally { position: absolute; left: ${ct.x}px; top: ${ct.y}px; width: ${ct.width}px; height: ${ct.height}px; display: flex; gap: ${px(12)}px; } + .tcell { position: relative; flex: 0 1 ${px(230)}px; border: 1px solid; border-radius: ${px(10)}px; background: ${rgba(pal.bg, 0.85)}; + display: flex; flex-direction: column; justify-content: center; padding: 0 ${px(16)}px; } + .tlab { font-family: ${cond}; font-size: ${px(20)}px; letter-spacing: 0.08em; color: ${pal.muted}; text-transform: uppercase; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .tnums { position: relative; height: ${px(40)}px; } + .tnum { position: absolute; left: 0; top: 0; font-family: ${display}; font-size: ${px(36)}px; line-height: ${px(40)}px; font-variant-numeric: tabular-nums; } + .mark { position: absolute; left: ${g.wordmark.x}px; top: ${g.wordmark.y}px; font-family: ${display}; font-size: ${g.wordmark.size}px; + letter-spacing: 0.12em; color: ${mix(pal.bg, pal.fg, 0.24)}; white-space: nowrap; }`; + const body = `<div id="rt" data-k="rt"> + <div class="rail" data-k="rail">${railLabels("r", "rlab")}${counts}<div class="bars">${railBars("r")}</div></div> + <div class="top2" data-k="top2">${tops.join("")}<div class="bars">${railBars("t")}</div>${railLabels("t", "tlab2")}</div> + ${blocks.join("")} + ${strips.join("")} + ${smallQrs.join("")} + ${tallyHtml} + ${site ? `<div class="mark">${esc(site)}</div>` : ""} + </div>`; + return pageHtml({ + id: "deck", W, H, fps, fonts, gsap: opts.gsap, + data: { total: r4(total), window: windowed ? { from: r4(from), dur: r4(dur) } : null, init, cues }, + css, + body, + }); +} diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -47,6 +47,7 @@ import { FRAME_KEY_REGIONS, frameKeys } from "./frame-keys.mjs"; import { FRAME_KEYS_FILE, SPARSE_FILE } from "./chunked-encode.mjs"; import { poolFor, poolFrame, poolFrameEvents, poolPutFrames } from "./render-pool.mjs"; import { regionCaching, regionModule } from "./modules/index.mjs"; +import { stackedDeckWanted, verticalRender } from "./vertical.mjs"; const run = promisify(execFile); @@ -869,12 +870,17 @@ export async function composeChrome({ schedule = null, preview = false, doRender = false, fps = null, workers = null, quality = "high", format = "png-sequence", still = null, png = null, from = 0, duration = null, window = null, segment = null, transition = null, - lease = null, want = null, + lease = null, want = null, render: renderOverride = null, }) { // The variant's view, and its own out directory. Handed the whole manifest // the band would draw claims this cut never makes, and the deck would name // clips it does not play. const manifest = selectVariant(JSON.parse(await readFile(manifestPath, "utf8")), variant); + // THE STACKED VERTICAL DECK (vertical-deck.mjs): a 9:16 cut that keeps its deck is composed at the render the + // build makes it with (vertical.mjs verticalRender) -- the build passes its own (`render`: a `--vertical` + // build of a landscape manifest, its knobs); Play the cut and the previews read the manifest's. + if (renderOverride) manifest.render = renderOverride; + else if (stackedDeckWanted(manifest.render)) manifest.render = verticalRender(manifest.render); // Absolute: the still is a file:// URL, and a relative one is no page at all. const base = path.resolve(outDir ?? path.join(path.dirname(path.resolve(manifestPath)), "out", variant)); // The project's out/ through ensureOutDir before anything lands under it: a diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -22,7 +22,7 @@ import { measureOn, measureSlice } from "./measure-slice.mjs"; import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs"; -import { attributionParts, deckSubtitle, deckSubtitleLines, deckSubtitleLinesParts, deckSubtitleParts, formatDeckDate } from "./attribution.mjs"; +import { attributionParts, deckSubtitle, deckSubtitleLines, deckSubtitleLinesParts, deckSubtitleParts, formatDeckDate, hms } from "./attribution.mjs"; import { panelEntry, postDeckText, postItemSeconds, postLayout } from "./post-item.mjs"; import { videoDip, videoEnter, videoHidesChrome, videoSeconds } from "./video-entry.mjs"; import { @@ -33,6 +33,9 @@ import { INSTRUMENT_COLUMN, instrumentsOn, instrumentsPlacement, instrumentsWant import { TRAILER_HIT_TIERS, TRAILER_SWELL } from "./trailer-hits.mjs"; import { DECK_PAD_X, counterCell } from "./modules/design.mjs"; import { parseShelfNote, resolveShelf, SHELF_MIN } from "./modules/shelf-settings.mjs"; +// THE STACKED VERTICAL DECK (vertical-deck.mjs, a leaf): a 9:16 render that keeps its deck answers every +// geometry below with the stacked deck's boxes. A landscape render never is one: everything below is as it was. +import { STACKED_PICTURE_K, clipTwoCrop, panelCells, stackedGeometry, stackedOn } from "./vertical-deck.mjs"; // An entry's note on the shelf, as written (`umtool set <p> <entry> shelfNote=…`; manifest.mjs checks it here). export { parseShelfNote }; @@ -124,6 +127,24 @@ export function resolveDeck(render) { // The instruments' column (instruments.mjs) takes the frame's right side: // the posts stay in the footage box, and nothing moves them over it. if (instrumentsOn(render)) merged.posts = { ...merged.posts, shift: false }; + // The stacked deck (vertical-deck.mjs): the posts' popups have no vertical form -- not drawn, so no clip holds + // for them (a frozen frame with nothing over it) and nothing moves the picture; there is no feed's column. + if (stackedOn(render)) merged.posts = { ...merged.posts, show: false, shift: false, layout: "popup" }; + // A frame shorter than 1080 (a 720p render): the band's DEFAULT sizes scaled with it -- its height, the title, + // the QR, the pips -- so the footage fits above it as at 1080 (deckScale; deckLayout scales its own rows and + // margins likewise). A size the manifest writes in pixels stays those pixels. 1080 is untouched. + const k = deckScale(render); + if (k !== 1) { + const own = (key, sub = null) => (sub ? d?.[key]?.[sub] !== undefined : d?.[key] !== undefined); + if (!own("height")) merged.height = Math.round(merged.height * k); + if (!own("title", "size")) merged.title = { ...merged.title, size: Math.max(12, Math.round(merged.title.size * k)) }; + if (!own("qr", "size")) merged.qr = { ...merged.qr, size: Math.round(merged.qr.size * k) }; + merged.pip = { + ...merged.pip, + ...(own("pip", "size") ? {} : { size: Math.max(2, Math.round(merged.pip.size * k)) }), + ...(own("pip", "activeSize") ? {} : { activeSize: Math.max(4, Math.round(merged.pip.activeSize * k)) }), + }; + } return merged; } @@ -197,8 +218,9 @@ export function validateChrome(chrome, render = {}) { } // The footage has to fit above the deck. Clamping the scale instead would - // make the setting lie about what was drawn. - if (!errors.length) { + // make the setting lie about what was drawn. (The stacked vertical deck lays + // its own frame -- vertical-deck.mjs: nothing of the landscape fit applies.) + if (!errors.length && !stackedOn({ ...render, chrome })) { const g = deckGeometry({ ...render, chrome }); // Only a deck that sets `posts` and draws them is held to the column's fit // here; one with posts on the defaults is checked by validatePosts, which @@ -467,9 +489,25 @@ export const even = (v) => Math.round(v / 2) * 2; export function deckGeometry(render) { const W = render?.width ?? 1920; const H = render?.height ?? 1080; + // THE STACKED VERTICAL DECK (vertical-deck.mjs): the picture at the frame's full width under the rail, and the + // deck's one page over the whole frame -- the rail, the source block, the wordmark are all in it. + if (stackedOn(render)) { + const g = stackedGeometry(render); + return { + W, H, + footage: { ...g.picture }, + deck: { x: 0, y: 0, width: W, height: H }, + ...(resolveShelf(render) ? { shelf: { ...g.shelf } } : {}), + // A post item's hero card (the build frames it there: stackedPostFraming), for Play the cut to lay it in. + post: { ...g.post.card }, + stacked: true, + }; + } const deck = resolveDeck(render); // A two-line subtitle grows the band by its head line (subtitleBoxes): - // the footage box stands on the band's top edge wherever that is. + // the footage box stands on the band's top edge wherever that is. (A frame + // of another height than 1080 -- a 720p render -- has its band scaled with + // it: resolveDeck, deckScale.) const dh = deck.height + subtitleBoxes(deck).extra; // The instruments' column (instruments.mjs) takes the right: the footage // gives it room and stands at the left edge, `railGap` in. @@ -504,6 +542,20 @@ export function deckGeometry(render) { }; } +/** The smallest the deck band is scaled to: a 720p frame's (a smaller one is refused as it always was). */ +export const DECK_SCALE_MIN = 2 / 3; + +/** + * The deck band's scale against its 1080 design size: a frame SHORTER than + * 1080 takes its height over 1080 -- a 720p render's band two thirds as tall -- + * down to DECK_SCALE_MIN; 1080 and taller are 1, the deck as it always was. The + * stacked vertical deck lays its own frame and is not scaled. + */ +export const deckScale = (render) => { + const H = render?.height ?? 1080; + return stackedOn(render) || !(H > 0) || H >= 1080 ? 1 : Math.max(DECK_SCALE_MIN, H / 1080); +}; + /** The air between the frame's edges, the thread rail and the footage. */ export const railGap = (render) => Math.round(24 * ((render?.width ?? 1920) / 1920)); @@ -540,6 +592,7 @@ export function threadsGeometry(render) { * trail: {x:number,y:number,width:number,height:number}|null }} */ export function instrumentsGeometry(render) { + if (stackedOn(render)) return stackedInstruments(render); const { W, deck, footage } = deckGeometry(render); const k = W / 1920; const gap = railGap(render); @@ -560,6 +613,36 @@ export function instrumentsGeometry(render) { return out; } +/** The instruments' design boxes (w / h): what each cell of the stacked deck's panel is cut to. */ +export const INSTRUMENT_ASPECTS = Object.freeze({ odometer: 600 / 140, trail: 600 / 138 }); + +/** + * The instruments in the STACKED vertical deck's panel (vertical-deck.mjs + * panelCells): the dial the left column's whole height, the odometer and the + * trail down the right -- each its column's width and its design box's + * aspect; one that does not fit is left out (null, its name in `out`), never + * squashed. `column` is the panel. Wherever the dial is placed in landscape, + * the stacked deck stands it in its panel. + */ +export function stackedInstruments(render) { + const g = stackedGeometry(render, { counter: stackedCounterOn(render) }); + const on = instrumentsWanted(render); + const items = on.map((n) => (n === "dial" ? { id: n, tall: true, aspect: 1 } : { id: n, aspect: INSTRUMENT_ASPECTS[n] })); + const { cells, out } = panelCells(g.panel, items, g.gap); + return { + column: { ...g.panel }, + dial: cells.dial ?? null, odometer: cells.odometer ?? null, trail: cells.trail ?? null, + stacked: true, out, + }; +} + +/** Does the stacked deck keep a row for the tally (the fact-check counter, when the cut counts its claims)? */ +export function stackedCounterOn(render) { + const fc = render?.chrome?.factcheck; + const asked = (!!fc && typeof fc === "object") || isObj(render?.chrome?.deck?.counter); + return asked && resolveFactcheck(render).tally?.show !== false && resolveCounter(render).show !== false; +} + /** * The instruments in the CORNER (`deck.dial.placement: "corner"`): over the * footage box where the deck puts it, `inset` in from its edges -- the dial a @@ -615,49 +698,55 @@ export const BAND_TEXT_RESERVE = 0.36; export function deckLayout(render, { tally = null, schedule = null } = {}) { const { W, deck: rect } = deckGeometry(render); const d = resolveDeck(render); - const padX = DECK_PAD_X; + // Its rows and margins at the band's scale (deckScale: a 720p frame's two thirds; 1080 is 1 and every + // number below is the one it always was). + const k = deckScale(render); + const z = k === 1 ? (v) => v : (v) => Math.round(v * k); + const padX = z(DECK_PAD_X); // The markers' labels (`deck.markers`) stand in a band above the track: the // track moves down by it, and only when there is a marker to label, so a // deck without them lays out as it always did -- nor one whose markers are // all unlabelled (or `rail.labels: false`): ticks need no band. const marked = labelledMarkers(d).length > 0; const rows = marked && schedule ? markerRowsOf(schedule, render) : 1; - const markerBand = marked ? MARKER_BAND + (rows > 1 ? MARKER_ROW : 0) : 0; + const markerBand = marked ? z(MARKER_BAND) + (rows > 1 ? z(MARKER_ROW) : 0) : 0; // A goalpost's words (`deck.claims`, claims.mjs) stand in a row of their // own above the markers'; only with one, likewise. - const claimRow = hasGoalpost(d) ? CLAIM_ROW : 0; - const trackY = 16 + claimRow + markerBand; + const claimRow = hasGoalpost(d) ? z(CLAIM_ROW) : 0; + const trackY = z(16) + claimRow + markerBand; // The body is everything under the pip track: the text block and the QR are // both centred in it, so the title's optical centre and the code's agree // whatever the deck's height. 14 px clears the active pip's halo. - const bodyTop = trackY + 14; - const bodyH = rect.height - bodyTop - 8; + const bodyTop = trackY + z(14); + const bodyH = rect.height - bodyTop - z(8); // Under a marker band the code keeps clear of the active pip's halo and // inside the deck: it shrinks to the room left under the track if it must. const banded = markerBand + claimRow; - const qrSize = banded ? Math.min(d.qr.size, rect.height - (trackY + 12) - 2) : d.qr.size; + const qrSize = banded ? Math.min(d.qr.size, rect.height - (trackY + z(12)) - 2) : d.qr.size; let qrY = Math.round(bodyTop + (bodyH - qrSize) / 2); - if (banded) qrY = Math.min(rect.height - qrSize - 2, Math.max(qrY, trackY + 12)); + if (banded) qrY = Math.min(rect.height - qrSize - 2, Math.max(qrY, trackY + z(12))); const qr = d.qr.show ? { x: W - padX - qrSize, y: qrY, size: qrSize } : null; let textX = padX; - let textRight = qr ? qr.x - 48 : W - padX; + let textRight = qr ? qr.x - z(48) : W - padX; let tallyBox = null; if (tally?.length) { // A cell per verdict the cut uses: its count over its label. Beside the // QR's cell (whose plate starts 46 px before the code) on the right, or // ahead of the title on the left; 40 px of air to the text either way. // Past 8 series the cells narrow into one row's budget (design.mjs counterCell). - const { cell, gap } = counterCell(tally.length); + const cc = counterCell(tally.length); + const cell = z(cc.cell); + const gap = z(cc.gap); const width = tally.length * cell + (tally.length - 1) * gap; - const height = Math.min(bodyH - 8, 118); + const height = Math.min(bodyH - z(8), z(118)); const y = Math.round(bodyTop + (bodyH - height) / 2); if (resolveFactcheck(render).tally.position === "left") { tallyBox = { x: padX, y, width, height, cell, gap }; - textX = padX + width + 40; + textX = padX + width + z(40); } else { - const right = qr ? qr.x - 46 - 24 : W - padX; + const right = qr ? qr.x - z(46) - z(24) : W - padX; tallyBox = { x: right - width, y, width, height, cell, gap }; - textRight = tallyBox.x - 40; + textRight = tallyBox.x - z(40); } } // Line boxes, not font sizes: the title's box holds its descenders inside the @@ -680,14 +769,15 @@ export function deckLayout(render, { tally = null, schedule = null } = {}) { const st = resolveSectionTitle(render); let sectionTitle = null; if (st) { - const y = trackY + Math.ceil(d.pip.activeSize / 2) + 6; - const height = Math.round(st.size * 1.3); + const y = trackY + Math.ceil(d.pip.activeSize / 2) + z(6); + const stSize = z(st.size); + const height = Math.round(stSize * 1.3); let lo = padX; let hi = W - padX; - if (qr) hi = Math.min(hi, qr.x - 46 - 24); + if (qr) hi = Math.min(hi, qr.x - z(46) - z(24)); if (tallyBox) { - if (tallyBox.x < W / 2) lo = Math.max(lo, tallyBox.x + tallyBox.width + 24); - else hi = Math.min(hi, tallyBox.x - 24); + if (tallyBox.x < W / 2) lo = Math.max(lo, tallyBox.x + tallyBox.width + z(24)); + else hi = Math.min(hi, tallyBox.x - z(24)); } let half = Math.max(0, Math.floor(Math.min(W / 2 - lo, hi - W / 2))); titleY = Math.max(titleY, y + height + 2); @@ -699,16 +789,18 @@ export function deckLayout(render, { tally = null, schedule = null } = {}) { // width), so the two never meet. const over = titleY + block + BAND_FOOT - rect.height; if (over > 0) { - titleY = Math.max(trackY + Math.ceil(d.pip.activeSize / 2) + 4, titleY - over); + titleY = Math.max(trackY + Math.ceil(d.pip.activeSize / 2) + z(4), titleY - over); const reserve = Math.min(textRight - textX, Math.round(W * BAND_TEXT_RESERVE)); - lo = Math.max(lo, textX + reserve + 24); + lo = Math.max(lo, textX + reserve + z(24)); half = Math.max(0, Math.floor(Math.min(W / 2 - lo, hi - W / 2))); } - sectionTitle = { x: Math.round(W / 2 - half), y, width: 2 * half, height, size: st.size }; + sectionTitle = { x: Math.round(W / 2 - half), y, width: 2 * half, height, size: stSize }; } return { width: W, height: rect.height, + // Only off 1080 (a 720p band, deckScale): the page scales its own fixed sizes by it. + ...(k !== 1 ? { scale: k } : {}), pipTrack: { x0: padX, x1: W - padX, y: trackY }, text: { x: textX, @@ -728,9 +820,9 @@ export function deckLayout(render, { tally = null, schedule = null } = {}) { // Only with a tally, so a deck without claims lays out as it always did. ...(tallyBox ? { tally: tallyBox } : {}), // Only with markers, likewise: where their labels stand (deckMarkers). - ...(markerBand ? { markerBand: { y: 3 + claimRow, height: markerBand + 6, ...(rows > 1 ? { rows } : {}) } } : {}), + ...(markerBand ? { markerBand: { y: z(3) + claimRow, height: markerBand + z(6), ...(rows > 1 ? { rows } : {}) } } : {}), // Only with a goalpost: where its words stand (claimsLayout). - ...(claimRow ? { claimBand: { y: 3, height: claimRow } } : {}), + ...(claimRow ? { claimBand: { y: z(3), height: claimRow } } : {}), // Only with the section title on: its line under the track. ...(sectionTitle ? { sectionTitle } : {}), }; @@ -1369,7 +1461,9 @@ export function deckSchedule({ // window is an output the counter reads (`finale.window`), and the finale // reads the counter's totals -- neither writes the other's slice. const stamps = stampsWithFinale(stamped, finale ? { start: finale.start, segments: finIds } : null); - const allMoves = finale ? [...moves, ...finale.moves] : moves; + // The stacked vertical deck never moves its picture: the finale's column stands over it (vertical-deck.mjs). + const stacked = stackedOn(render); + const allMoves = stacked ? [] : finale ? [...moves, ...finale.moves] : moves; const threads = threadsOn(render) ? threadSchedule({ segments: segs.map((s, i) => ({ ...s, thread: threadOf(entries[i]) })), D, total, render, moves }) : null; @@ -1464,6 +1558,9 @@ export function deckSchedule({ ...(finIds.has(e.id) ? { finale: true } : {}), // And off the rail, when the finale says so (finale.pips: false). ...(finIds.has(e.id) && resolveFinale(render).pips === false ? { noPip: true } : {}), + // Only in the stacked vertical deck (vertical-deck.mjs): a clip's source line in its parts (channel, + // title, date, the clock at its start), and a twocrop clip's layout -- its strip and its small QR. + ...(stacked ? stackedSegmentFields(e, metas[i] ?? null, provenance, deck) : {}), }; }), // The finale: present only when the cut has one. @@ -1531,6 +1628,27 @@ export function deckSchedule({ } /** + * A segment's fields only the stacked vertical deck's page reads: a clip's + * source line in its four parts (`vsource`: channel, title -- the deck's own + * title when the entry sets one --, date, the clock at its start) and a + * twocrop clip's layout (`vlayout`). + */ +export function stackedSegmentFields(entry, meta, provenance, deck) { + if (entry?.type !== "clip") return {}; + const p = attributionParts(entry, meta ?? {}, provenance); + const title = String(entry.onscreen?.title ?? "").trim() || String(p.title ?? "").trim(); + return { + vsource: { + channel: String(p.channel ?? "").trim(), + title, + date: formatDeckDate(p.date ?? "", deck.subtitle?.dateFormat ?? "long"), + clock: p.at === null || p.at === undefined ? "" : hms(p.at), + }, + ...(clipTwoCrop(entry) ? { vlayout: "twocrop" } : {}), + }; +} + +/** * The notes an entry puts on the shelf (`entry.shelfNote`, one line): `[{ segment, * from, to, text }]` -- `from`/`to` its segment's span in the cut. The shelf * module (modules/shelf.mjs) shows each over its span, fading with the entry. @@ -1612,6 +1730,11 @@ export function postCovers(entries, segments, render, { feed = false } = {}) { entries.forEach((e, i) => { const seg = segments[i]; if (e?.type !== "post" || !seg || seg.id !== e.id) return; + // The stacked vertical deck lays a post item as its hero card (stackedPostFraming): the card covers that box. + if (stackedOn(render)) { + out.push({ segment: e.id, from: seg.start, to: Math.round((seg.start + seg.duration) * 1000) / 1000, rects: [{ ...stackedGeometry(render).post.card }] }); + return; + } const L = postLayout(panelEntry(e, render), { width: box.width, height: box.height }); const rects = [L.card, L.slot, L.strip] .filter((b) => b && [b.x, b.y, b.width, b.height].every(Number.isFinite)) @@ -2773,8 +2896,8 @@ export function feedGeometry(render) { */ export function stampGeometry(render, { feed = false } = {}) { const { W } = deckGeometry(render); - const f = feed ? feedGeometry(render).footage : deckGeometry(render).footage; - const k = W / 1920; + const f = overlayBox(render, { feed }); + const k = pictureK(render, W); // `stamp.scale` sizes the region (the stamp is drawn to it), still inside the footage. const { position: pos, scale = 1 } = resolveFactcheck(render).stamp; const width = Math.min(even(560 * k * scale), even(f.width)); @@ -2787,6 +2910,26 @@ export function stampGeometry(render, { feed = false } = {}) { } /** + * The scale of what stands over the footage (the stamps, the stats, the + * measure extras) against its 1920-wide design: the frame's width over 1920 -- + * or, in the stacked vertical deck, STACKED_PICTURE_K (its picture is the + * frame's whole width, so the landscape share would draw them a size small). + */ +export const pictureK = (render, W = render?.width ?? 1920) => (stackedOn(render) ? STACKED_PICTURE_K : W / 1920); + +/** + * The box what stands over the footage is anchored in: the footage box (the feed's when `feed`) -- or, in the + * stacked vertical deck, its picture inside the safe area (the picture is the frame's whole width; the right 12 % + * is the platform's buttons). + */ +export function overlayBox(render, { feed = false } = {}) { + const f = feed ? feedGeometry(render).footage : deckGeometry(render).footage; + if (!stackedOn(render)) return f; + const a = stackedGeometry(render).safe; + return { x: a.x0, y: f.y, width: a.x1 - a.x0, height: f.height }; +} + +/** * Where the stats region sits in the frame (chrome-stats.mjs, stats.mjs): a * panel in the footage box -- the feed's when `feed`, else the deck's -- at * `stats.position`, `inset` clear of its edges: 48 px plus 150 a field wide @@ -2799,8 +2942,8 @@ export function stampGeometry(render, { feed = false } = {}) { */ export function statsGeometry(render, { feed = false } = {}) { const { W } = deckGeometry(render); - const f = feed ? feedGeometry(render).footage : deckGeometry(render).footage; - const k = W / 1920; + const f = overlayBox(render, { feed }); + const k = pictureK(render, W); const cfg = resolveStats(render); const width = Math.min(even((48 + 150 * cfg.fields.length) * k), even(f.width)); const height = Math.min(even((cfg.name ? 150 : 112) * k), even(f.height)); @@ -2834,6 +2977,8 @@ export function fxGeometry(render, { feed = false } = {}) { * `layout: "feed"` exactly then -- a feed with nothing to draw is the deck alone. */ export function feedOn({ render, posts = [], entries = [] }) { + // The stacked vertical deck has no column for a feed: its posts stay popups (resolveDeck). + if (stackedOn(render)) return false; if (!deckOn(render)) return false; const p = resolveDeck(render).posts; return p.show && p.layout === "feed" && attachPosts({ posts: posts ?? [], entries }).length > 0; diff --git a/umtool/report-to-video/instruments.mjs b/umtool/report-to-video/instruments.mjs @@ -24,7 +24,8 @@ // in the finale's lower column (module `dial-finale`). // // A LEAF, like modules/settings.mjs: deck.mjs and settings.mjs import it, so it -// imports neither. +// imports neither (vertical-deck.mjs, the stacked deck's geometry, is a leaf too). +import { stackedOn } from "./vertical-deck.mjs"; /** The column's width at 1920 wide (scaled with the frame): what the footage gives up. */ export const INSTRUMENT_COLUMN = 600; @@ -126,8 +127,8 @@ export function instrumentsWanted(render) { return out; } -/** Where the instruments stand: the dial's `placement` ("column" without a dial). */ -export const instrumentsPlacement = (render) => resolveDial(render)?.placement ?? "column"; +/** Where the instruments stand: the dial's `placement` ("column" without a dial) -- always the panel's column in the stacked vertical deck. */ +export const instrumentsPlacement = (render) => (stackedOn(render) ? "column" : resolveDial(render)?.placement ?? "column"); /** * Is the instrument COLUMN on: any of the three asked for, placed in the column. diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -101,6 +101,10 @@ import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; import { validateFxEntries } from "./fx.mjs"; import { validateTransitionStyle } from "./transition.mjs"; import { validateLook } from "./look.mjs"; +// The stacked vertical deck (vertical-deck.mjs): what it leaves out, and a twocrop band drawn past its source's pixels. +import { stackedLeftOut } from "./modules/index.mjs"; +import { verticalOn, verticalRender } from "./vertical.mjs"; +import { ENLARGE_WARN, STACKED_QR_SHARE, STACKED_QR_SMALL_SHARE, clipTwoCrop, stackedOn, twoCropEnlargement } from "./vertical-deck.mjs"; import { roomWindowWarnings } from "./room.mjs"; import { qrUrlFor } from "./render-cards.mjs"; import { archiveMomentUrl } from "./site-links.mjs"; @@ -177,7 +181,9 @@ export function qrsOf(manifest, { only = null, metaOf = null } = {}) { if (d.qr?.show) { for (const e of timeline) { const url = deckQrUrl(e, provenance, { links: d.qr.links, meta: metaOf?.(e) ?? null }); - if (url) out.push({ where: `timeline ${e.id} (the deck's QR)`, id: e.id, source: "entry", url, px: Number(d.qr.size) }); + // The stacked vertical deck draws its own (vertical-deck.mjs): the source block's, a twocrop clip's small one. + const px = stackedOn(render) ? Math.round(render.width * (clipTwoCrop(e) ? STACKED_QR_SMALL_SHARE : STACKED_QR_SHARE)) : Number(d.qr.size); + if (url) out.push({ where: `timeline ${e.id} (the deck's QR)`, id: e.id, source: "entry", url, px }); } } // `posts.qr: false` draws no code on any post card. @@ -396,6 +402,28 @@ export function narrationLengthErrors(manifest, secondsById, { only = null } = { * `draftsUnreviewed` / `narrationUnreviewed` let the unapproved through. * @returns {{ errors: string[], warnings: string[] }} */ +/** A twocrop clip's warnings: past ENLARGE_WARN on a 16:9 source, or in a cut that does not play the stacked deck. */ +export function stackedLintWarnings(manifest, { only = null } = {}) { + const out = []; + const render = manifest?.render ?? {}; + const vr = verticalOn(render) ? verticalRender(render) : null; + const sh = Number(render.maxHeightSource) || 1080; + const sw = Math.round((sh * 16) / 9); + for (const e of manifest?.timeline ?? []) { + if (e?.type !== "clip" || (only && e.id !== only)) continue; + const crops = clipTwoCrop(e); + if (!crops) continue; + if (!vr || !stackedOn(vr)) { + if (vr) out.push(`timeline ${e.id}.vertical.layout "twocrop" is the stacked deck's: this vertical cut has none (render.vertical.deck "bare", or no deck), so it plays in the cut's clip layout`); + continue; + } + twoCropEnlargement(crops, sw, sh, vr).forEach((x, i) => { + if (x > ENLARGE_WARN) out.push(`timeline ${e.id}.vertical.crops[${i}] is drawn ${x}× its source's pixels at ${sw}x${sh} (past ${ENLARGE_WARN}×: it will look soft) -- a wider crop`); + }); + } + return out; +} + export function lintManifest(manifest, { manifestDir, whole = manifest, exists = existsSync, only = null, validators = true, narrationSeconds = null, narrationReview = null, narrationUnreviewed = false, draftsReview = null, final = false, draftsUnreviewed = false, @@ -403,7 +431,9 @@ export function lintManifest(manifest, { const errors = []; const warnings = []; const render = manifest.render ?? {}; - const height = Number(render.height) || 1080; + // A code's size at 720p is read off the frame's SHORT side: a 9:16 frame's width (a vertical cut plays 720 wide + // at 720p), a landscape frame's height as it always was. + const height = Math.min(Number(render.height) || 1080, Number(render.width) || Infinity); // The social posts and the video's URL are not the video's: a problem there // is said, never a refusal (release 29 G2's review). warnings.push(...publishWarnings(whole)); @@ -413,6 +443,11 @@ export function lintManifest(manifest, { warnings.push(...roomWindowWarnings(only ? { ...manifest, timeline: (manifest.timeline ?? []).filter((e) => e?.id === only) } : manifest)); // A narrated post's read that says a link aloud (post-thread.mjs threadReadWarnings), with its fix. warnings.push(...validateThreadReadWarnings(only ? { ...manifest, timeline: (manifest.timeline ?? []).filter((e) => e?.id === only) } : manifest)); + // THE STACKED VERTICAL DECK: each module the cut sets up that has no vertical form, left out (a note, never a + // refusal); a twocrop clip's band drawn past ENLARGE_WARN times its source's pixels (a 16:9 source of the cut's + // `maxHeightSource`, 1080 by default: the build says it again from the real one); a twocrop where no stacked deck plays it. + if (!only) warnings.push(...stackedLeftOut(manifest)); + warnings.push(...stackedLintWarnings(manifest, { only })); for (const { where, src } of imageSrcsOf(manifest, { only })) { if (path.isAbsolute(src) || src.startsWith("~")) { diff --git a/umtool/report-to-video/measure-extras.mjs b/umtool/report-to-video/measure-extras.mjs @@ -25,10 +25,11 @@ // - DIET: the state's diet, re-stamped at each change of regime or diet // number; a null diet after one is "NO DIET" (the producer has applied the // off-scope rule: this only draws state.diet). -import { deckGeometry, feedGeometry, instrumentsGeometry } from "./deck.mjs"; +import { deckGeometry, feedGeometry, instrumentsGeometry, overlayBox, pictureK } from "./deck.mjs"; import { chapterCover, chapterWindows } from "./chrome-story.mjs"; import { dietTagWidth, MEASURE_EXTRAS, MEASURE_POSITIONS, resolveMeasureExtra, SHELF_POSITION } from "./modules/measure-extras-settings.mjs"; import { resolveShelf } from "./modules/shelf-settings.mjs"; +import { stackedOn, stackedStandDowns } from "./vertical-deck.mjs"; const r4 = (v) => Math.round(v * 10000) / 10000; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); @@ -882,8 +883,10 @@ export function measureExtraGeometry(id, render, { feed = false } = {}) { if (slot) return { ...slot }; } const g = deckGeometry(render); - const f = feed ? feedGeometry(render).footage : g.footage; - const k = (g.W / 1920) * (cfg.scale ?? 1); + const f = overlayBox(render, { feed }); + // Over the footage at its design size scaled with the frame (pictureK: the stacked vertical deck's own). + const pk = pictureK(render, g.W); + const k = pk * (cfg.scale ?? 1); const box = measureBox(id, render); const width = Math.min(even(box.width * k), even(g.W)); const height = Math.min(even(box.height * k), even(g.H)); @@ -893,7 +896,7 @@ export function measureExtraGeometry(id, render, { feed = false } = {}) { x = cfg.x * (g.W / 1920); y = cfg.y * (g.W / 1920); } else { - const inset = Math.round(24 * (g.W / 1920)); + const inset = Math.round(24 * pk); const [v, h] = cfg.position.split("-"); x = h === "left" ? f.x + inset : h === "right" ? f.x + f.width - inset - width : f.x + (f.width - width) / 2; y = v === "top" ? f.y + inset : f.y + f.height - inset - height; @@ -934,12 +937,13 @@ const overlapsSpan = (spans, from, to) => spans.some((sp) => sp.in < to - 1e-6 & export function anchorRect(id, render, anchor, size = 1, { feed = false } = {}) { const cfg = resolveMeasureExtra(id, render) ?? resolveMeasureExtra(id, { chrome: { deck: {} } }); const g = deckGeometry(render); - const f = feed ? feedGeometry(render).footage : g.footage; - const k = (g.W / 1920) * (cfg.scale ?? 1) * size; + const f = overlayBox(render, { feed }); + const pk = pictureK(render, g.W); + const k = pk * (cfg.scale ?? 1) * size; const box = measureBox(id, render); const width = Math.min(even(box.width * k), even(f.width)); const height = Math.min(even(box.height * k), even(f.height)); - const inset = Math.round(24 * (g.W / 1920)); + const inset = Math.round(24 * pk); const [v, h] = anchor.split("-"); const x = h === "left" ? f.x + inset : h === "right" ? f.x + f.width - inset - width : f.x + (f.width - width) / 2; const y = v === "top" ? f.y + inset : f.y + f.height - inset - height; @@ -1099,6 +1103,18 @@ export function measurePlacements(schedule, render, { finaleSlot = null } = {}) out.promise.moves.push({ from: finaleSlot.at, to: Number(schedule.total) || fin.to, rect: finaleSlot.rect, size: finaleSlot.size }); } else if (inColumn) out.promise.moves.push({ from: fin.from, to: Number(schedule.total) || fin.to, rect: null, size: 1 }); } + // THE STACKED VERTICAL DECK (vertical-deck.mjs): over a post item (its card takes the picture's room) and a + // twocrop clip (its strip carries the numbers) every extra stands down, as an entry's hideModules hides it. + if (stackedOn(render)) { + for (const sd of stackedStandDowns(schedule)) { + for (const id of MEASURE_EXTRAS) { + if (!resolveMeasureExtra(id, render)) continue; + out[id].moves = carveSpans(out[id].moves, sd.from, sd.to); + out[id].moves.push({ from: sd.from, to: sd.to, rect: null, size: 1 }); + if (id === "promise") out.promise.strips = carveSpans(out.promise.strips, sd.from, sd.to); + } + } + } // An entry that hides modules over its span (`hideModules`, deck.mjs entryHides -- text in the footage no // dodge can know of, rev 9: the refund email in v02): each named module hidden there with its own fade, whatever // it would otherwise have done in that span. diff --git a/umtool/report-to-video/modules/blur.mjs b/umtool/report-to-video/modules/blur.mjs @@ -13,6 +13,8 @@ export default defineModule({ z: 2, kind: "input", slot: "footage", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "input" }, title: "Blur", summary: "A clip's picture blurred at its encode, a caption on it, the sound as recorded.", configKey: "render.blur", diff --git a/umtool/report-to-video/modules/chapter.mjs b/umtool/report-to-video/modules/chapter.mjs @@ -17,6 +17,8 @@ export default defineModule({ z: 85, kind: "overlay-window", slot: "footage", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "picture" }, title: "Chapters", summary: "A section bumper over the first seconds of the clip it opens: title, subtitle, date.", configKey: "render.chrome.chapter", diff --git a/umtool/report-to-video/modules/contract.mjs b/umtool/report-to-video/modules/contract.mjs @@ -63,6 +63,15 @@ export const MODULE_SLOTS = Object.freeze(["footer", "column", "popup", "stamp", */ export const PLAY_CLOCKS = Object.freeze(["cut"]); +/** + * Where a module stands in the STACKED vertical deck (vertical-deck.mjs): the + * whole frame (the shell's page), a cell of the instruments' panel, over the + * picture (as it stands over the footage box), on the picture's lower-left + * shelf, the finale's instrument column, inside its host's page (a part), a + * segment of the cut (its own frame), or a filter on the footage itself. + */ +export const VERTICAL_SLOTS = Object.freeze(["frame", "panel", "picture", "shelf", "finale", "inline", "segment", "input"]); + /** How a region is laid over the cut: a whole-cut sequence from frame 1, or a window at its own second. */ export const REGION_PLACEMENTS = Object.freeze(["whole", "window"]); @@ -100,6 +109,7 @@ const SPEC = Object.freeze({ play: "its live-preview contract: { clock: \"cut\", ready: \"<region>:ready\" } -- its page seeked in an iframe by Play the cut and the live preview", docs: "its knobs.md section: { heading, intro?, rows: [[knob, range, terminal]], after? }", workers: "\"wide\" or \"narrow\": how many renderer workers its page takes", + vertical: "its form in the stacked vertical deck (vertical-deck.mjs): { slot: one of VERTICAL_SLOTS }; absent, it has none and is left out of one", noun: "how a message names its sequence (\"the stamps'\")", cached: "false for a page the render cache does not key (the legacy chart band)", check: "a function (schedule, render) => the sentence why this schedule cannot draw it, or null", @@ -173,6 +183,7 @@ export function defineModule(def) { } } if (def.docs !== undefined && !(isObj(def.docs) && typeof def.docs.heading === "string")) throw new Error(`${where}: docs must be ${SPEC.docs}`); + if (def.vertical !== undefined && !(isObj(def.vertical) && VERTICAL_SLOTS.includes(def.vertical.slot))) throw new Error(`${where}: vertical must be ${SPEC.vertical}`); if (def.workers !== undefined && !["wide", "narrow"].includes(def.workers)) throw new Error(`${where}: workers must be ${SPEC.workers}`); return Object.freeze({ ...def }); } diff --git a/umtool/report-to-video/modules/counter.mjs b/umtool/report-to-video/modules/counter.mjs @@ -14,6 +14,8 @@ export default defineModule({ kind: "part", host: "shell", slot: "inline", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "inline" }, title: "Counter", summary: "A running tally of named series in the deck, each cell stepping as a mark's stamp lands.", configKey: "render.chrome.deck.counter", diff --git a/umtool/report-to-video/modules/dial-finale.mjs b/umtool/report-to-video/modules/dial-finale.mjs @@ -23,6 +23,8 @@ export default defineModule({ z: 95, kind: "overlay-window", slot: "full", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "finale" }, title: "Dial finale", summary: "The finale with the dial and the odometer large: the needle drops to his last stated weight, the wheels roll to the total, NET holds.", docs: { diff --git a/umtool/report-to-video/modules/dial.mjs b/umtool/report-to-video/modules/dial.mjs @@ -24,6 +24,8 @@ export default defineModule({ z: 74, kind: "overlay-whole", slot: "instruments", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "panel" }, title: "Scale dial", summary: "A bathroom-scale face: the needle swings to each weight he states, his remembered weights as ghosts, every goal in force on the bezel (the closest headlined), and -- with deck.measure.ghosts -- a faint tick for every weight he has claimed.", configKey: "render.chrome.deck.dial", diff --git a/umtool/report-to-video/modules/fx.mjs b/umtool/report-to-video/modules/fx.mjs @@ -13,6 +13,8 @@ export default defineModule({ z: 60, kind: "overlay-whole", slot: "footage", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "picture" }, title: "Effects", summary: "Overlays on the picture: receipts, a zoom, a scrubber, captions.", validate: settingsOf("fx").validate, diff --git a/umtool/report-to-video/modules/index.mjs b/umtool/report-to-video/modules/index.mjs @@ -7,6 +7,12 @@ // Pure: the module files are, and so is this. import { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, PLAY_CLOCKS, REGION_PLACEMENTS } from "./contract.mjs"; import { settingsOf, settingValue } from "./settings.mjs"; +// The stacked vertical deck's rules (vertical-deck.mjs) and the render a vertical cut is built with (vertical.mjs). +import { instrumentsGeometry } from "../deck.mjs"; +import { verticalOn, verticalRender } from "../vertical.mjs"; +import { leftOutWords, stackedOn } from "../vertical-deck.mjs"; +import { resolveDial } from "../instruments.mjs"; +import { runsFinaleWanted } from "../chrome-runs-finale.mjs"; import chart from "./chart.mjs"; import shell from "./shell.mjs"; @@ -174,3 +180,61 @@ export function moduleProblems(manifest) { } return out; } + +// --------------------------------------------------------------------------- +// THE STACKED VERTICAL DECK (vertical-deck.mjs): a module stands in it by its +// `vertical` form (contract.mjs VERTICAL_SLOTS); one with none is left out -- +// said so in the lint and the build's notes, never squashed into the frame. +// --------------------------------------------------------------------------- + +/** A module's form in the stacked vertical deck (`{ slot }`), or null: it has none. */ +export const verticalFormOf = (m) => (m && m.vertical) || null; + +/** Is this module's setting written on the render (its configKey, or its SETTINGS entry) and not `false`? */ +function configured(m, render) { + const chrome = render?.chrome ?? {}; + const entry = settingsOf(m.id); + const value = entry + ? settingValue(chrome, entry) + : m.configKey + ? m.configKey.split(".").slice(1).reduce((o, k) => (o && typeof o === "object" ? o[k] : undefined), render) + : undefined; + if (value === undefined || value === null || value === false) return false; + if (value && typeof value === "object" && value.show === false) return false; + return true; +} + +/** + * What the stacked vertical deck leaves out of a manifest, as sentences: each + * module the cut sets up that has no vertical form (the posts popups and + * feed, the side panel, the finale's landscape page …), and an instrument + * the panel has no room for. Empty for any other cut. `manifest.render` is the + * cut's as written (the vertical one is derived here, as the build derives it). + */ +export function stackedLeftOut(manifest) { + const render = verticalRender(manifest?.render ?? {}); + if (!verticalOn(manifest?.render) || !stackedOn(render)) return []; + const out = []; + const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + for (const m of MODULES) { + if (verticalFormOf(m)) continue; + let on = configured(m, render); + // The finale's diet runs: on with `deck.finale.dietRuns` and a finale to draw them in. + if (m.id === "runs-finale") on = !!runsFinaleWanted(render) && tl.some((e) => e?.layout === "finale"); + // The legacy chart band (`render.chart` under `render.chromeEngine`): drawn only without the deck, so a stacked + // deck says so only when the cut asks for it. + if (m.id === "chart") on = manifest?.render?.chromeEngine === "hyperframes" && !!manifest?.render?.chart; + if (m.id === "popup-posts") on = Array.isArray(manifest?.posts) && manifest.posts.length > 0 && render?.chrome?.deck?.posts?.show !== false; + if (m.id === "finale") on = tl.some((e) => e?.layout === "finale"); + if (m.id === "feed") on = render?.chrome?.deck?.posts?.layout === "feed"; + if (!on) continue; + // The finale's landscape page: the stacked deck stands the dial's instrument column in its window, when the dial draws one. + if (m.id === "finale" && resolveDial(render)?.finale) { + out.push(leftOutWords("finale", "its landscape page has no vertical form (the instrument column, module dial-finale, stands in its window)")); + continue; + } + out.push(leftOutWords(m.id)); + } + for (const id of instrumentsGeometry(render).out ?? []) out.push(leftOutWords(id, "no room left in the instruments' panel")); + return out; +} diff --git a/umtool/report-to-video/modules/intro.mjs b/umtool/report-to-video/modules/intro.mjs @@ -32,6 +32,8 @@ export default defineModule({ z: 1, kind: "segment", slot: "full", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "segment" }, title: "Intro", summary: "The brand sting the cut opens with, a site's name swapped in on the chime.", configKey: "render.intro", diff --git a/umtool/report-to-video/modules/measure-extras-module.mjs b/umtool/report-to-video/modules/measure-extras-module.mjs @@ -46,6 +46,8 @@ export function measureExtraModule(spec) { z: spec.z, kind: "overlay-whole", slot: "footage", + // Its form in the stacked vertical deck (vertical-deck.mjs): over the picture, at its anchor there. + vertical: { slot: "picture" }, title: spec.title, summary: spec.summary, configKey: `render.chrome.deck.${id}`, diff --git a/umtool/report-to-video/modules/odometer.mjs b/umtool/report-to-video/modules/odometer.mjs @@ -19,6 +19,8 @@ export default defineModule({ z: 75, kind: "overlay-whole", slot: "instruments", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "panel" }, title: "Lost odometer", summary: "Rolling digits of the pounds he says he has lost (only ever up), NET beside them.", configKey: "render.chrome.deck.odometer", diff --git a/umtool/report-to-video/modules/pair.mjs b/umtool/report-to-video/modules/pair.mjs @@ -16,6 +16,8 @@ export default defineModule({ z: 52, kind: "overlay-whole", slot: "footage", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "picture" }, title: "Then and now", summary: "Two clips on one subject, each with its date: a then | now strip (or a then→now card) with the pair's caption.", configKey: "render.chrome.pair", diff --git a/umtool/report-to-video/modules/qr.mjs b/umtool/report-to-video/modules/qr.mjs @@ -12,6 +12,8 @@ export default defineModule({ kind: "part", host: "shell", slot: "inline", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "inline" }, title: "QR", summary: "Each clip's code in the deck, to the archive at the clip or to the record itself.", configKey: "render.chrome.deck.qr", diff --git a/umtool/report-to-video/modules/rail.mjs b/umtool/report-to-video/modules/rail.mjs @@ -32,6 +32,8 @@ export default defineModule({ kind: "part", host: "shell", slot: "inline", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "inline" }, title: "Rail", summary: "The deck's pip track: a pip per clip, the marker, the fuse, and the markers' flags.", configKey: "render.chrome.deck.pip", diff --git a/umtool/report-to-video/modules/section-title.mjs b/umtool/report-to-video/modules/section-title.mjs @@ -26,6 +26,8 @@ export default defineModule({ kind: "part", host: "shell", slot: "inline", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "inline" }, title: "Section title", summary: "The current section's name (the marker that opened it) on one quiet line under the rail.", configKey: "render.chrome.deck.sectionTitle", diff --git a/umtool/report-to-video/modules/shelf.mjs b/umtool/report-to-video/modules/shelf.mjs @@ -20,6 +20,8 @@ export default defineModule({ z: 64, kind: "overlay-whole", slot: "shelf", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "shelf" }, title: "Shelf", summary: "A strip cleared under (or over) the footage for the diet's dated tags, the streak chain, a goal stack or an entry's note -- nothing on it stands on the picture.", configKey: "render.chrome.deck.shelf", diff --git a/umtool/report-to-video/modules/shell.mjs b/umtool/report-to-video/modules/shell.mjs @@ -8,6 +8,9 @@ import path from "node:path"; import { deckGeometry, deckLayout } from "../deck.mjs"; import { deckHtml } from "../chrome-deck.mjs"; +import { stackedDeckHtml, wordmarkOf } from "../chrome-vdeck.mjs"; +import { STACKED_QR_SHARE, stackedOn } from "../vertical-deck.mjs"; +import { instrumentFonts } from "./instruments-shared.mjs"; import { assertRegion, defineModule } from "./contract.mjs"; import { DECK_DEFAULTS, settingsOf } from "./settings.mjs"; @@ -17,6 +20,8 @@ export default defineModule({ z: 10, kind: "overlay-whole", slot: "footer", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "frame" }, title: "Deck", summary: "The panel at the foot of the frame: each clip's title, and the band the subtitle, QR, rail and counter draw in.", configKey: "render.chrome.deck", @@ -54,6 +59,15 @@ export default defineModule({ on: () => true, async page(ctx) { const { render, schedule } = ctx; + // THE STACKED VERTICAL DECK (vertical-deck.mjs): the same schedule, drawn over the 9:16 frame -- the rail, + // each segment's source block and its QR, the tally, the wordmark (chrome-vdeck.mjs). + if (stackedOn(render)) { + const fonts = await instrumentFonts(ctx); + const qrSrcs = {}; + const byUrl = await ctx.qrs(schedule.segments.map((s) => s.qrUrl), Math.round(render.width * STACKED_QR_SHARE)); + for (const s of schedule.segments) if (s.qrUrl) qrSrcs[s.id] = byUrl.get(s.qrUrl); + return stackedDeckHtml(schedule, render, { fonts, qrSrcs, from: ctx.from, duration: ctx.duration, site: wordmarkOf(ctx.manifest?.provenance) }); + } const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); // With the schedule: a staggered marker band moves the QR down and may shrink it. const lay = deckLayout(render, { schedule }); diff --git a/umtool/report-to-video/modules/stamp.mjs b/umtool/report-to-video/modules/stamp.mjs @@ -16,6 +16,8 @@ export default defineModule({ z: 40, kind: "overlay-whole", slot: "stamp", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "picture" }, title: "Stamps", summary: "Each counted mark's word, stamped over the footage as it lands.", configKey: "render.chrome.factcheck.stamp", diff --git a/umtool/report-to-video/modules/stats.mjs b/umtool/report-to-video/modules/stats.mjs @@ -14,6 +14,8 @@ export default defineModule({ z: 50, kind: "overlay-whole", slot: "panel", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "picture" }, title: "Stats", summary: "A frame scan's running numbers over the clips that declare them.", validate: settingsOf("stats").validate, diff --git a/umtool/report-to-video/modules/status.mjs b/umtool/report-to-video/modules/status.mjs @@ -15,6 +15,8 @@ export default defineModule({ z: 55, kind: "overlay-whole", slot: "footage", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "picture" }, title: "Status ledger", summary: "A row per item -- announced, then followed up or not -- filling a column as the cut plays.", configKey: "render.chrome.status", diff --git a/umtool/report-to-video/modules/subtitle.mjs b/umtool/report-to-video/modules/subtitle.mjs @@ -15,6 +15,8 @@ export default defineModule({ kind: "part", host: "shell", slot: "inline", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "inline" }, title: "Subtitle", summary: "Each clip's source line under its title: the channel, the source's title, the date, the clock.", configKey: "render.chrome.deck.subtitle", diff --git a/umtool/report-to-video/modules/teaser.mjs b/umtool/report-to-video/modules/teaser.mjs @@ -12,6 +12,8 @@ export default defineModule({ z: 0, kind: "segment", slot: "full", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "segment" }, title: "Teaser", summary: "A full-frame card of lines popping in on the beat, inserted as its own segment.", validate: (_value, { manifest }) => validateTeasers(manifest), diff --git a/umtool/report-to-video/modules/trail.mjs b/umtool/report-to-video/modules/trail.mjs @@ -18,6 +18,8 @@ export default defineModule({ z: 76, kind: "overlay-whole", slot: "instruments", + // Its form in the stacked vertical deck (vertical-deck.mjs). + vertical: { slot: "panel" }, title: "Weight trail", summary: "His stated weights by date, drawn up to the playhead, the 300 lb line and the times he says he is under it.", configKey: "render.chrome.deck.trail", diff --git a/umtool/report-to-video/outro.mjs b/umtool/report-to-video/outro.mjs @@ -170,10 +170,10 @@ const span = (text, { px, color, face }) => `<span font_desc="${face}" size="${M const magickOpts = { maxBuffer: 1 << 24, env: { ...process.env, FONTCONFIG_FILE } }; /** Pango markup -> a transparent PNG centred lines wrapped at `width`; its size. */ -async function textPng(markup, file, width) { +async function textPng(markup, file, width, align = "center") { const markupPath = file.replace(/\.png$/, ".pango"); await writeFile(markupPath, markup, "utf8"); - const args = ["-background", "none", "-define", "pango:align=center"]; + const args = ["-background", "none", "-define", `pango:align=${align}`]; if (width) args.push("-size", `${Math.round(width)}x`, "-define", "pango:wrap=word"); args.push(`pango:@${markupPath}`, "-trim", "+repage", file); await execFileP("magick", args, magickOpts); @@ -186,11 +186,105 @@ async function textPng(markup, file, width) { export const OUTRO_COLOURS = Object.freeze({ ground: "#151b20", ink: "#f6f1e6", muted: "#a9b4bc" }); /** - * The card's key: everything drawn (the words, the size, the image's bytes, the brand). + * The card's key: everything drawn (the words, the size, the image's bytes, the brand; a 9:16 end card's QR, + * host and sources). * @param {object} o */ -export function outroKey({ width, height, title, text, imageSha = null, brand }) { - return createHash("sha256").update(JSON.stringify({ v: 1, width, height, title, text, imageSha, brand })).digest("hex").slice(0, 20); +export function outroKey({ width, height, title, text, imageSha = null, brand, end = null }) { + return createHash("sha256").update(JSON.stringify({ v: 1, width, height, title, text, imageSha, brand, ...(end ? { end } : {}) })).digest("hex").slice(0, 20); +} + +// --------------------------------------------------------------------------- +// THE 9:16 END CARD (lane vertical-deck, out/vertical-design EndCard): a vertical outro with somewhere to go -- +// its QR large, "scan or search" and the archive's host beside it, the cut's sources listed (each its date, its +// channel and the time it is from; the rest counted), the site's name at the foot. The same card, more on it. +// --------------------------------------------------------------------------- + +/** How many sources the end card lists before it counts the rest. */ +export const END_CARD_SOURCES = 3; + +/** The end card's words over its title. */ +export const END_CARD_KICKER = "EVERY CLIP, IN FULL"; + +const MONTHS_SHORT = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +/** "2026-01-12" or "Jan 12, 2026" as the list's date ("Jan 12"); anything else as it is. */ +export function endCardDate(d) { + const s = String(d ?? "").trim(); + const iso = /^(\d{4})-(\d{2})-(\d{2})/.exec(s); + if (iso) return `${MONTHS_SHORT[Number(iso[2]) - 1]} ${Number(iso[3])}`; + const long = /^([A-Z][a-z]{2}) (\d{1,2}), \d{4}$/.exec(s); + return long ? `${long[1]} ${long[2]}` : s; +} + +/** + * The sources an end card lists: each clip of `timeline` once (by video), in order -- its date, its channel and + * the time it is from, from the build's schedule (a stacked deck's `vsource`) else what the entry says of itself. + * Pure. + * + * @param {Array<Record<string, any>>} timeline + * @param {{ segments?: Array<Record<string, any>> } | null} [schedule] + * @returns {Array<{ date: string, label: string }>} + */ +export function endCardSources(timeline, schedule = null) { + const bySeg = new Map((Array.isArray(schedule?.segments) ? schedule.segments : []).map((x) => [x.id, x])); + const seen = new Set(); + const out = []; + for (const e of Array.isArray(timeline) ? timeline : []) { + if (e?.type !== "clip") continue; + const key = String(e.video ?? e.id); + if (seen.has(key)) continue; + seen.add(key); + const v = bySeg.get(e.id)?.vsource ?? bySeg.get(String(e.id).replace(/~\d+$/, ""))?.vsource ?? null; + const channel = String(v?.channel ?? e.channelTitle ?? "").trim(); + const at = Number(e.cite ?? e.start); + const clock = v?.clock ?? (Number.isFinite(at) ? hmsOf(at) : ""); + const label = [channel, clock].filter(Boolean).join(" · "); + if (!label) continue; + out.push({ date: endCardDate(v?.date ?? e.date ?? ""), label }); + } + return out; +} + +function hmsOf(total) { + const s = Math.floor(Math.max(0, total)); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const x = s % 60; + return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(x).padStart(2, "0")}` : `${m}:${String(x).padStart(2, "0")}`; +} + +/** The archive's host as the card says it ("https://jeralyzer.pages.dev/x" → "jeralyzer.pages.dev"), or "". */ +export function endCardHost(url) { + try { + return new URL(String(url ?? "")).hostname; + } catch { + return ""; + } +} + +/** + * Where the 9:16 end card's parts go, px (the mockup's at 1080x1920): inside the safe area, top to bottom -- the + * kicker and the title, the QR and its words beside it, the sources, the wordmark. Pure. + * + * @param {{ width: number, height: number }} size + */ +export function endCardLayout({ width: W, height: H }) { + const u = W / 1080; + const box = { + x0: Math.round(W * 0.05), x1: Math.round(W * (1 - VERTICAL_SAFE.right)), + y0: Math.round(H * VERTICAL_SAFE.top), y1: Math.round(H * (1 - VERTICAL_SAFE.bottom)), + }; + const qr = Math.round(450 * u); + return { + box, u, + kicker: { px: Math.round(34 * u), y: box.y0 + Math.round(34 * u) }, + title: { px: [64, 58, 52, 46].map((p) => Math.round(p * u)), lines: 3, gap: Math.round(18 * u) }, + qr: { size: qr, pad: Math.round(28 * u), radius: Math.round(26 * u) }, + side: { gap: Math.round(32 * u), headPx: Math.round(36 * u), hostPx: Math.round(30 * u), textPx: Math.round(28 * u) }, + list: { px: Math.round(32 * u), row: Math.round(54 * u), dateW: Math.round(140 * u), gap: Math.round(40 * u) }, + brandPx: Math.round(46 * u), + }; } /** @@ -202,12 +296,14 @@ export function outroKey({ width, height, title, text, imageSha = null, brand }) * brand: { name: string, lead?: string, ink: string }, dir: string }} o * @returns {Promise<{ file: string, key: string, cached: boolean, layout: ReturnType<typeof outroLayout>, placed: Record<string, { x: number, y: number, w: number, h: number }> }>} */ -export async function renderOutroCard({ width: W, height: H, title, text, imageFile = null, brand, dir }) { +export async function renderOutroCard({ width: W, height: H, title, text, imageFile = null, brand, dir, qrUrl = null, sources = null }) { const L = outroLayout({ width: W, height: H }); const imageBytes = imageFile ? await readFile(imageFile).catch(() => null) : null; if (imageFile && !imageBytes) throw new Error(`outro.image ${imageFile}: not there`); const imageSha = imageBytes ? createHash("sha256").update(imageBytes).digest("hex") : null; - const key = outroKey({ width: W, height: H, title, text, imageSha, brand }); + // A 9:16 card with somewhere to go (a QR, or the sources to list) is the END CARD: the same card, more on it. + const end = L.vertical && (qrUrl || sources?.length) ? { qrUrl: qrUrl ?? null, host: endCardHost(qrUrl), sources: sources ?? [] } : null; + const key = outroKey({ width: W, height: H, title, text, imageSha, brand, end }); await mkdir(dir, { recursive: true }); const file = path.join(dir, `outro-${key}.png`); const placedFile = `${file}.json`; @@ -241,6 +337,12 @@ export async function renderOutroCard({ width: W, height: H, title, text, imageF await execFileP("magick", ["-size", `${W}x${H}`, `xc:${OUTRO_COLOURS.ground}`, ground], magickOpts); } + if (end) { + const placed = await drawEndCard({ W, H, title, text, brand, end, ground, mark, work, file: path.join(work, "card.png") }); + await writeFile(placedFile, JSON.stringify(placed) + "\n"); + await rename(path.join(work, "card.png"), file); + return { file, key, cached: false, layout: L, placed }; + } // The column: title, the accent rule, the call to action, centred in the box above the brand's room. const colH = t.height + L.gap + L.rule.h + L.gap + cta.height; const areaTop = L.box.y0; @@ -274,6 +376,85 @@ export async function renderOutroCard({ width: W, height: H, title, text, imageF } /** + * The 9:16 end card on `ground` (endCardLayout): the kicker and the title, the QR large with "Scan or search", the + * host and the call to action beside it, the sources (END_CARD_SOURCES, then "+ N more in the archive"), the + * brand's mark at the foot of the safe area. Returns where each part went. + */ +async function drawEndCard({ W, H, title, text, brand, end, ground, mark, work, file }) { + const E = endCardLayout({ width: W, height: H }); + const boxW = E.box.x1 - E.box.x0; + const placed = {}; + const comps = []; + const at = (png, x, y) => comps.push(png, "-geometry", `+${Math.round(x)}+${Math.round(y)}`, "-composite"); + let y = E.kicker.y; + const kick = await textPng(span(END_CARD_KICKER, { px: E.kicker.px, color: brand.ink, face: "Archivo @wght=800,wdth=108" }), path.join(work, "kicker.png"), null); + at(kick.file, E.box.x0, y); + placed.kicker = { x: E.box.x0, y, w: kick.width, h: kick.height }; + y += kick.height + E.title.gap; + let t = null; + for (const px of E.title.px) { + t = await textPng(span(title, { px, color: OUTRO_COLOURS.ink, face: "Archivo @wght=800,wdth=108" }), path.join(work, "etitle.png"), boxW, "left"); + if (t.height <= px * 1.25 * E.title.lines) break; + } + at(t.file, E.box.x0, y); + placed.title = { x: E.box.x0, y, w: t.width, h: t.height }; + y += t.height + Math.round(48 * E.u); + // The QR on a white plate, its words beside it. + if (end.qrUrl) { + const raw = path.join(work, "qr-raw.png"); + const qr = path.join(work, "qr.png"); + const inner = E.qr.size - 2 * E.qr.pad; + await execFileP(process.env.QRENCODE_BIN ?? "qrencode", ["-o", raw, "-s", "8", "-m", "0", "-l", "M", "--", end.qrUrl]); + await execFileP("magick", [ + "-size", `${E.qr.size}x${E.qr.size}`, "xc:none", "-fill", "#ffffff", "-draw", `roundrectangle 0,0 ${E.qr.size - 1},${E.qr.size - 1} ${E.qr.radius},${E.qr.radius}`, + "(", raw, "-filter", "point", "-resize", `${inner}x${inner}!`, ")", "-geometry", `+${E.qr.pad}+${E.qr.pad}`, "-composite", qr, + ], magickOpts); + at(qr, E.box.x0, y); + placed.qr = { x: E.box.x0, y, w: E.qr.size, h: E.qr.size }; + const sx = E.box.x0 + E.qr.size + E.side.gap; + const sw = E.box.x1 - sx; + let sy = y + Math.round(10 * E.u); + const head = await textPng(span("Scan or search", { px: E.side.headPx, color: OUTRO_COLOURS.ink, face: "IBM Plex Sans @wght=700" }), path.join(work, "scan.png"), null); + at(head.file, sx, sy); + sy += head.height + Math.round(18 * E.u); + if (end.host) { + const host = await textPng(span(end.host, { px: E.side.hostPx, color: brand.ink, face: "IBM Plex Sans @wght=600" }), path.join(work, "host.png"), sw, "left"); + at(host.file, sx, sy); + placed.host = { x: sx, y: sy, w: host.width, h: host.height }; + sy += host.height + Math.round(18 * E.u); + } + if (text) { + const cta = await textPng(span(text, { px: E.side.textPx, color: OUTRO_COLOURS.muted, face: "IBM Plex Sans @wght=500" }), path.join(work, "ecta.png"), sw, "left"); + at(cta.file, sx, sy); + placed.cta = { x: sx, y: sy, w: cta.width, h: cta.height }; + } + y += E.qr.size + E.list.gap; + } + // The sources: each its date, then its channel and time; the rest counted. + const list = end.sources.slice(0, END_CARD_SOURCES); + const more = end.sources.length - list.length; + placed.sources = []; + for (const [i, s] of list.entries()) { + const d = await textPng(span(s.date || "—", { px: E.list.px, color: OUTRO_COLOURS.muted, face: "IBM Plex Sans @wght=500" }), path.join(work, `sd${i}.png`), null); + const l = await textPng(span(s.label, { px: E.list.px, color: OUTRO_COLOURS.ink, face: "IBM Plex Sans @wght=500" }), path.join(work, `sl${i}.png`), E.box.x1 - E.box.x0 - E.list.dateW, "left"); + at(d.file, E.box.x0, y); + at(l.file, E.box.x0 + E.list.dateW, y); + placed.sources.push({ x: E.box.x0, y, w: E.list.dateW + l.width, h: Math.max(d.height, l.height) }); + y += Math.max(E.list.row, l.height + Math.round(14 * E.u)); + } + if (more > 0) { + const m = await textPng(span(`+ ${more} more in the archive`, { px: E.list.px, color: OUTRO_COLOURS.muted, face: "IBM Plex Sans @wght=500" }), path.join(work, "more.png"), null); + at(m.file, E.box.x0, y); + placed.more = { x: E.box.x0, y, w: m.width, h: m.height }; + } + // The brand at the foot of the safe area, left. + placed.brand = { x: E.box.x0, y: E.box.y1 - mark.height, w: mark.width, h: mark.height }; + at(mark.file, placed.brand.x, placed.brand.y); + await execFileP("magick", [ground, ...comps, "-alpha", "off", "-depth", "8", file], magickOpts); + return placed; +} + +/** * The filtergraph fragment that appends the card to a cut's `[vIn]`/`[aIn]` * (`seconds` long, its `fade` overlapping the cut's last seconds): the card * looped to its frames, the cut's sound faded out over the fade and silence diff --git a/umtool/report-to-video/outro.test.mjs b/umtool/report-to-video/outro.test.mjs @@ -236,3 +236,66 @@ test("wrapShortArgs: the intro crossfaded into the short, the card after it; a h const onlyOutro = wrapShortArgs({ ...base, outro: { png: "/c.png", seconds: 3.5, fade: 0.5 } }); assert.match(onlyOutro[onlyOutro.indexOf("-filter_complex") + 1], /offset=39\.500000\[ov\]/); }); + +// ---- the 9:16 end card (lane vertical-deck) ----------------------------------------------------------------- + +test("the end card's sources: each clip once, its date, channel and time; the schedule's source parts first", async () => { + const { endCardSources, endCardDate, endCardHost } = await import("./outro.mjs"); + const timeline = [ + { type: "clip", id: "a", video: "v1", start: 5104.2, channelTitle: "TheQuartering (Rumble)", date: "2026-01-12" }, + { type: "clip", id: "b", video: "v1", start: 20 }, + { type: "post", id: "p" }, + { type: "clip", id: "c~1", video: "v2", start: 61 }, + ]; + const schedule = { segments: [{ id: "c", vsource: { channel: "Chan", date: "Feb 3, 2026", clock: "1:01" } }] }; + assert.deepEqual(endCardSources(timeline, schedule), [ + { date: "Jan 12", label: "TheQuartering (Rumble) · 1:25:04" }, + { date: "Feb 3", label: "Chan · 1:01" }, + ]); + assert.equal(endCardDate("whenever"), "whenever"); + assert.equal(endCardHost("https://jeralyzer.pages.dev/?q=1"), "jeralyzer.pages.dev"); + assert.equal(endCardHost(null), ""); +}); + +test("the end card's layout keeps inside the safe area; a landscape outro is not one", async () => { + const { endCardLayout } = await import("./outro.mjs"); + const E = endCardLayout({ width: 1080, height: 1920 }); + assert.ok(E.box.x0 >= 0 && E.box.x1 <= 1080 * (1 - VERTICAL_SAFE.right)); + assert.ok(E.box.y0 >= 1920 * VERTICAL_SAFE.top && E.box.y1 <= 1920 * (1 - VERTICAL_SAFE.bottom)); + assert.ok(E.qr.size <= E.box.x1 - E.box.x0); +}); + +test("the end card drawn: the QR, the sources and the brand inside the safe area", async (t) => { + const { execFile } = await import("node:child_process"); + const { promisify } = await import("node:util"); + const run = promisify(execFile); + const have = await run("magick", ["-version"]).then(() => run("qrencode", ["-V"]).then(() => true)).catch(() => false); + if (!have) return t.skip("needs ImageMagick and qrencode"); + const { renderOutroCard } = await import("./outro.mjs"); + const dir = await mkdtemp(path.join(tmpdir(), "endcard-")); + try { + const sources = Array.from({ length: 5 }, (_, i) => ({ date: `Jan ${i + 1}`, label: `Channel ${i} · 1:0${i}:00` })); + const r = await renderOutroCard({ + width: 1080, height: 1920, title: "Every weight he said, in his own words", text: "Full video on the channel", + brand: { name: "Jeralyzer", lead: "Jer", ink: "#5fc4a6" }, dir, qrUrl: "https://jeralyzer.pages.dev/?q=diet", sources, + }); + const { stdout } = await run("magick", [r.file, "-format", "%w %h", "info:"]); + assert.equal(stdout.trim(), "1080 1920"); + for (const k of ["kicker", "title", "qr", "host", "cta", "more", "brand"]) assert.ok(r.placed[k], k); + assert.equal(r.placed.sources.length, 3); + const boxes = [r.placed.kicker, r.placed.title, r.placed.qr, r.placed.host, r.placed.cta, r.placed.more, r.placed.brand, ...r.placed.sources]; + for (const b of boxes) { + assert.ok(b.y >= 1920 * VERTICAL_SAFE.top - 1 && b.y + b.h <= 1920 * (1 - VERTICAL_SAFE.bottom) + 1, JSON.stringify(b)); + assert.ok(b.x + b.w <= 1080 * (1 - VERTICAL_SAFE.right) + 1, JSON.stringify(b)); + } + // Drawn again: the same key, kept. + const again = await renderOutroCard({ + width: 1080, height: 1920, title: "Every weight he said, in his own words", text: "Full video on the channel", + brand: { name: "Jeralyzer", lead: "Jer", ink: "#5fc4a6" }, dir, qrUrl: "https://jeralyzer.pages.dev/?q=diet", sources, + }); + assert.equal(again.cached, true); + if (process.env.END_CARD_OUT) await writeFile(process.env.END_CARD_OUT, await readFile(r.file)); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -25,6 +25,7 @@ "./build-video": "./build-video.mjs", "./basic": "./basic.mjs", "./vertical": "./vertical.mjs", + "./vertical-deck": "./vertical-deck.mjs", "./vertical-plan": "./vertical-plan.mjs", "./reframe": "./reframe.mjs", "./side-card": "./side-card.mjs", diff --git a/umtool/report-to-video/reel-intro.mjs b/umtool/report-to-video/reel-intro.mjs @@ -167,9 +167,9 @@ export function wrapShortArgs({ short, shortSeconds, intro = null, outro = null, * * @param {{ file: string, takeDir: string, render: Record<string, any>, manifest?: any, introSpec?: unknown, * outro?: { title: string, text: string, image?: string | null, imageFile?: string | null, seconds: number } | null, - * xfade?: number, sitesDir?: string, log?: (s: string) => void }} o + * xfade?: number, sitesDir?: string, log?: (s: string) => void, endCard?: { qrUrl?: string | null, sources?: Array<{ date: string, label: string }> } | null }} o */ -export async function wrapShort({ file, takeDir, render, manifest = null, introSpec = null, outro = null, xfade = 0.3, sitesDir = undefined, log = () => {} }) { +export async function wrapShort({ file, takeDir, render, manifest = null, introSpec = null, outro = null, xfade = 0.3, sitesDir = undefined, log = () => {}, endCard = null }) { if (!introSpec && !outro) return { intro: null, outro: null }; const { execFile } = await import("node:child_process"); const { promisify } = await import("node:util"); @@ -198,7 +198,11 @@ export async function wrapShort({ file, takeDir, render, manifest = null, introS let card = null; if (outro) { const brand = await outroBrand(ri?.entry ?? null, { provenance: manifest?.provenance ?? null, sitesDir }); - const r = await renderOutroCard({ width: W, height: H, title: outro.title, text: outro.text, imageFile: outro.imageFile ?? null, brand, dir: path.join(takeDir, "out", "sourced", "outro") }); + // A 9:16 card with somewhere to go is the end card (outro.mjs): the QR, the host, the short's sources. + const r = await renderOutroCard({ + width: W, height: H, title: outro.title, text: outro.text, imageFile: outro.imageFile ?? null, brand, dir: path.join(takeDir, "out", "sourced", "outro"), + ...(endCard && H > W ? { qrUrl: endCard.qrUrl ?? null, sources: endCard.sources ?? null } : {}), + }); card = { png: r.file, seconds: outro.seconds, fade: OUTRO_FADE }; log(`vertical: outro card ${r.cached ? "(drawn before)" : "drawn"} -- "${outro.title}"`); } diff --git a/umtool/report-to-video/reframe.mjs b/umtool/report-to-video/reframe.mjs @@ -68,7 +68,35 @@ export async function normalizeLoudness(input, output, target, { log = () => {} * piece plays whole, else each segment's part cut and joined; then the * short's loudness. `{seconds, loudness}`. */ -export async function assembleShort({ pieces, segmentsDir, built, outFile, render, log = () => {} }) { +/** + * Where each piece is cut from a stacked deck's BUILT cut (the build's schedule), or null when a piece is not in it. + * A segment overlaps its neighbours by the crossfade (deck.mjs scheduleFrom), so a piece keeps out of them -- the + * dissolve in, after its start + D, and the one out, before its end − D -- or every dissolve would play twice once + * the pieces are joined; and its `to` never runs past its own segment. Pure. + * + * @param {Array<{ id: string, from: number, to: number | null }>} pieces + * @param {{ segments?: Array<{ id: string, start: number, duration: number }>, transition?: number } | null} schedule + * @returns {Array<{ from: number, to: number }> | null} + */ +export function builtSpans(pieces, schedule) { + const segs = Array.isArray(schedule?.segments) ? schedule.segments : []; + const index = new Map(segs.map((s, i) => [s.id, i])); + if (!segs.length || !pieces.every((p) => index.has(p.id))) return null; + const D = Math.max(0, Number(schedule.transition) || 0); + return pieces.map((p) => { + const i = index.get(p.id); + const s = segs[i]; + const start = Number(s.start); + const dur = Number(s.duration); + const lo = i > 0 ? D : 0; + const hi = i < segs.length - 1 ? dur - D : dur; + const from = Math.min(Math.max(lo, Number(p.from) || 0), hi); + const to = Math.max(from, Math.min(hi, p.to === null || p.to === undefined ? hi : Number(p.to))); + return { from: Math.round((start + from) * 1000) / 1000, to: Math.round((start + to) * 1000) / 1000 }; + }); +} + +export async function assembleShort({ pieces, segmentsDir, built, outFile, render, schedule = null, log = () => {} }) { const target = verticalKnobs(render).loudness; const whole = pieces.every((p) => !p.from && p.to === null); let src = built; @@ -76,10 +104,16 @@ export async function assembleShort({ pieces, segmentsDir, built, outFile, rende src = `${outFile}.joined-${process.pid}.mp4`; const inputs = []; const parts = []; + // THE STACKED VERTICAL DECK (vertical-deck.mjs): its segments are the picture alone -- the deck is laid over the + // built cut -- so a piece is cut from the built cut at its segment's place (the build's schedule), deck and all. + const span = builtSpans(pieces, schedule); pieces.forEach((p, i) => { - inputs.push("-i", path.join(segmentsDir, `${p.id}.mp4`)); - const trim = p.to === null ? `trim=start=${f3(p.from)}` : `trim=start=${f3(p.from)}:end=${f3(p.to)}`; - const atrim = p.to === null ? `atrim=start=${f3(p.from)}` : `atrim=start=${f3(p.from)}:end=${f3(p.to)}`; + const b = span ? span[i] : null; + const a0 = b ? b.from : p.from; + const end = b ? b.to : p.to; + inputs.push("-i", b ? built : path.join(segmentsDir, `${p.id}.mp4`)); + const trim = end === null ? `trim=start=${f3(a0)}` : `trim=start=${f3(a0)}:end=${f3(end)}`; + const atrim = end === null ? `atrim=start=${f3(a0)}` : `atrim=start=${f3(a0)}:end=${f3(end)}`; parts.push(`[${i}:v]${trim},setpts=PTS-STARTPTS,fps=${render?.fps ?? 30},format=yuv420p,setsar=1[v${i}]`, `[${i}:a]${atrim},asetpts=PTS-STARTPTS,afade=t=in:d=0.08,areverse,afade=t=in:d=0.12,areverse[a${i}]`); }); parts.push(`${pieces.map((_, i) => `[v${i}][a${i}]`).join("")}concat=n=${pieces.length}:v=1:a=1[v][a]`); diff --git a/umtool/report-to-video/render-estimate.mjs b/umtool/report-to-video/render-estimate.mjs @@ -21,6 +21,12 @@ // a window's capture, 4 / 7 workers 0.8 / 1.15 GB // the ladder's re-encode (x264 medium, one rung at a time) 0.76 GB // +// The STACKED VERTICAL DECK (vertical-deck.mjs; 2026-11-10, the heavy scope's MemoryPeak, the quartering-diet +// take's 3 entries -- a twocrop clip, a clip, a post item -- 1080x1920, the deck's full-frame page and the +// dial/odometer/trail/extras layers, a preview): 2.6 GB +// A 9:16 frame is a 16:9 frame's pixels on its side, so the formula below holds for it; its full-frame deck page +// is one more 1080x1920 layer, which VERTICAL_DECK_MIN_MB (the measured peak + 25 %) floors. +// // So a render's peak is its widest ffmpeg -- the crossfade pass holds every // segment of a batch open, about 200 MB each (build-video's xfadeBatches: // REPORT_VIDEO_XFADE_BATCH / render.xfadeBatch, default 24) -- or its chrome @@ -45,6 +51,9 @@ // Pure and dependency-free: the umtool app bundles takeRender.mjs, which // imports this, and build-video.mjs imports it too (no cycle). +// The vertical format's rules (common, pure and dependency-free as this file is). +import { stackedDeckWanted } from "yt-dlp-transcript-common/lib/report/vertical.mjs"; + /** The crossfade / overlay pass's own memory, with no segment open. */ export const RENDER_ENCODE_BASE_MB = 1700; /** Each segment the pass holds open (a decoder and its frames). */ @@ -62,6 +71,8 @@ export const LADDER_ESTIMATE_MB = 1000; * a 1080p60 source decodes twice the frames, so this carries about 40 % over it. */ export const BASIC_ESTIMATE_MB = 1200; +/** A stacked vertical deck's render declares at least this (its measured peak, 2.6 GB, + 25 %). */ +export const VERTICAL_DECK_MIN_MB = 3300; /** build-video's XFADE_BATCH_DEFAULT: the segments one crossfade pass opens. */ export const XFADE_BATCH = 24; @@ -191,10 +202,16 @@ export function manifestSegments(manifest) { * @param {{ xfade?: boolean, single?: boolean, batch?: number }} [o] * @returns {number | null} */ -export function manifestEstimateMb(manifest, env = process.env, { xfade = true, single = false, batch = XFADE_BATCH } = {}) { +export function manifestEstimateMb(manifest, env = process.env, { xfade = true, single = false, batch = XFADE_BATCH, vertical = null } = {}) { // A basic cut (render.mode, as resolved: a take's render manifest carries its preset laid) is one encode at a time. if (manifest?.render?.mode === "basic") return renderEstimateMb("basic", env); const crossfades = xfade && (manifest?.render?.transition ?? 0.5) !== 0; const segments = single || (manifest && !crossfades) ? 1 : manifestSegments(manifest); - return renderEstimateMb("render", env, { segments, batch }); + const mb = renderEstimateMb("render", env, { segments, batch }); + // A 9:16 cut that keeps its deck (stackedDeckWanted: the manifest's render.format vertical, or a `--vertical` build + // of it -- `vertical`: true or its knobs, as `umtool vertical` asks): floored at its measured peak + margin -- + // unless an override says otherwise (0: declare nothing). + const own = manifest?.render ?? {}; + const r = vertical ? { ...own, format: "vertical", vertical: { ...(own.vertical ?? {}), ...(typeof vertical === "object" ? vertical : {}) } } : own; + return stackedDeckWanted(r) && mb > 0 && env.UMTOOL_RENDER_ESTIMATE_MB === undefined ? Math.max(mb, VERTICAL_DECK_MIN_MB) : mb; } diff --git a/umtool/report-to-video/subtitle-lines.test.mjs b/umtool/report-to-video/subtitle-lines.test.mjs @@ -73,11 +73,14 @@ test("two lines at 1920×1080: the band grows by the head line and every slot mo assert.equal(reservedFooterHeight(renderOf({ overCards: "show" })), 190); }); -test("two lines at 1280×720: the same band, and the footage still above it", () => { +// Lane vertical-deck (9 Nov): a frame shorter than 1080 has its band scaled with its height (deck.mjs deckScale) -- +// at 720 two thirds of the 1080 band, its head line too (title 36: a 28 px head box) -- where it was the 1080 band +// unscaled (229 px), which refused the default footageScale. footageScale 0.6 fits either way. +test("two lines at 1280×720: the band scaled with the frame, and the footage still above it", () => { const render = renderOf({ ...TWO, footageScale: 0.6 }, { width: 1280, height: 720 }); assert.deepEqual(validateChrome(render.chrome, render), []); const g = deckGeometry(render); - assert.deepEqual(g.deck, { x: 0, y: 720 - 229, width: 1280, height: 229 }); + assert.deepEqual(g.deck, { x: 0, y: 720 - 155, width: 1280, height: 155 }); assert.ok(g.footage.y + g.footage.height <= g.deck.y); const lay = deckLayout(render); assert.ok(lay.text.subtitleY + lay.text.headBox + lay.text.subtitleBox <= lay.height - 8); diff --git a/umtool/report-to-video/vertical-deck.mjs b/umtool/report-to-video/vertical-deck.mjs @@ -0,0 +1,282 @@ +// THE VERTICAL DECK (lane vertical-deck, 9 Nov): a cut that has a deck keeps it +// in 9:16. The operator's pick from the layouts (out/vertical-design): the +// STACKED deck as the default (`render.vertical.deck: "stacked"`; "bare" is the +// vertical format as it first shipped, no deck), a clip's TWO-CROP reframe as +// its own option (`vertical.layout: "twocrop"`, `vertical.crops`), and a post +// item as the hero card with the deck kept round it. +// +// ONE composition, two geometries: the deck's schedule, its pages and its +// timing are the landscape cut's; only where things stand changes. This file +// says where, top to bottom, inside the platforms' safe area +// (render.vertical.safe: the top 8 %, the bottom 20 %, the right 12 %): +// +// rail the section's name and its progress segments, "2 / 5" under the top band +// picture the clip's 16:9 footage box at the frame's full width +// shelf over the picture's lower-left (the stamps, a shelf's notes) +// captions under the picture, at most two lines, each word lit +// panel the instruments in two columns (the dial tall at the left) +// counters the tally's cells, when the cut counts +// source channel · title · date · time, the QR beside it above the bottom band +// wordmark the site's name, dim, in the bottom band (decoration only) +// +// A post item: its card in the picture's and the captions' room, the counters +// under it, the big date line and the QR in the source block. A twocrop clip: +// the source line and the rail together on top, crop one, a one-row strip of +// the instruments, crop two with the captions over its foot, the QR small and +// low-left in the bottom band. The finale: the instrument column over the +// picture's room. +// +// A LEAF and PURE: no fs, no ffmpeg, and it imports nothing of the deck's -- +// deck.mjs, the pages and the build read it. + +import { VERTICAL_HEIGHT, VERTICAL_WIDTH, clipTwoCrop, stackedDeckWanted, verticalKnobs } from "yt-dlp-transcript-common/lib/report/vertical.mjs"; + +export { clipTwoCrop, stackedDeckWanted }; + +const even = (n) => 2 * Math.round(n / 2); +const evenDown = (n) => 2 * Math.floor(n / 2); + +/** + * Is this render the stacked deck: a 9:16 render (`format: "vertical"`, the + * build's 1080x1920) that keeps its deck. The geometry functions of deck.mjs + * (deckGeometry, instrumentsGeometry …) ask this and answer with the stacked + * deck's boxes; a landscape render is never one. + */ +export const stackedOn = (render) => stackedDeckWanted(render) && (render?.height ?? 0) > (render?.width ?? 0); + +/** How large the picture's own overlays (the stamps, the stats, the measure extras) are drawn, against the landscape deck's 1920 design px. */ +export const STACKED_PICTURE_K = 0.75; + +/** The caption face's size in the stacked deck, a share of the frame's width (under the picture: two lines fit their band). */ +export const STACKED_CAPTION_SHARE = 0.046; + +/** The QR's size (a share of the width) in the source block, and the twocrop's small one in the bottom band. */ +export const STACKED_QR_SHARE = 0.13; +export const STACKED_QR_SMALL_SHARE = 0.1; + +/** The smallest a panel cell is drawn against its column's width (its aspect kept) before it is left out. */ +export const PANEL_SHRINK = 0.8; + +/** The panel's gap between its two columns and between its cells, a share of the width. */ +export const STACKED_GAP_SHARE = 0.02; + +/** + * The safe area in px: everything that must be read keeps inside x0..x1, + * y0..y1 (render.vertical.safe). The left margin is the stacked deck's own + * (the mockups' 14 of 405). + */ +export function stackedSafe(render, W = render?.width ?? VERTICAL_WIDTH, H = render?.height ?? VERTICAL_HEIGHT) { + const s = verticalKnobs(render).safe; + return { x0: Math.round(W * 0.035), x1: Math.round(W * (1 - s.right)), y0: Math.round(H * s.top), y1: Math.round(H * (1 - s.bottom)) }; +} + +/** + * Where everything of the stacked deck stands, frame px. `counter`: the cut + * draws the tally's cells (they take a row over the source block). + * + * @returns {{ W: number, H: number, safe: {x0:number,x1:number,y0:number,y1:number}, + * rail: Rect & { label: number, bar: number }, picture: Rect, shelf: Rect, captions: Rect & { size: number, lines: number }, + * panel: Rect, gap: number, counters: Rect | null, source: Rect & { qr: {x:number,y:number,size:number}, text: Rect }, + * wordmark: { x: number, y: number, size: number }, post: { card: Rect, counters: Rect }, + * twocrop: { top: Rect, crop1: Rect, strip: Rect, crop2: Rect, captions: { bottom: number }, qr: {x:number,y:number,size:number} }, + * finale: { title: Rect, column: Rect } }} + */ +export function stackedGeometry(render, { counter = false } = {}) { + const W = render?.width ?? VERTICAL_WIDTH; + const H = render?.height ?? VERTICAL_HEIGHT; + const a = stackedSafe(render, W, H); + const u = W / 1080; + const gap = Math.round(W * STACKED_GAP_SHARE); + const k = verticalKnobs(render); + // The rail: the section's name over its progress segments, just under the top band. + const label = Math.round(40 * u); + const bar = Math.max(4, Math.round(8 * u)); + const rail = { x: a.x0, y: a.y0 + Math.round(12 * u), width: a.x1 - a.x0, height: label + Math.round(17 * u) + bar, label, bar }; + // The picture: the frame's full width, 16:9, under the rail. + const ph = even((W * 9) / 16); + const picture = { x: 0, y: even(rail.y + rail.height + Math.round(31 * u)), width: W, height: ph }; + // The shelf: over the picture's lower-left. + const shelf = { x: a.x0 - Math.round(11 * u), y: picture.y + ph - Math.round(16 * u) - Math.round(110 * u), width: evenDown((a.x1 - a.x0) * 0.62), height: Math.round(110 * u) }; + // The captions: at most two lines under the picture. + const size = Math.round(W * STACKED_CAPTION_SHARE); + const lines = k.captions.lines; + const captions = { x: a.x0, y: picture.y + ph + Math.round(22 * u), width: a.x1 - a.x0, height: Math.round(size * 1.24 * 2), size, lines }; + // The source block, standing on the bottom band: its rule, the QR, the words. + const qrSize = even(W * STACKED_QR_SHARE); + const padTop = Math.round(22 * u); + const sourceH = padTop + qrSize; + const source = { x: a.x0, y: a.y1 - Math.round(12 * u) - sourceH, width: a.x1 - a.x0, height: sourceH }; + const sq = { x: a.x0, y: source.y + padTop, size: qrSize }; + const sourceBlock = { ...source, qr: sq, text: { x: sq.x + qrSize + Math.round(27 * u), y: sq.y, width: a.x1 - (sq.x + qrSize + Math.round(27 * u)), height: qrSize } }; + // The tally's row, over the source block. + const counters = counter ? { x: a.x0, y: source.y - gap - Math.round(72 * u), width: a.x1 - a.x0, height: Math.round(72 * u) } : null; + // The panel: what is left between the captions and the counters (or the source block). + const panelTop = captions.y + captions.height + Math.round(15 * u); + const panelBottom = (counters ? counters.y : source.y) - gap; + const panel = { x: a.x0, y: panelTop, width: a.x1 - a.x0, height: Math.max(0, panelBottom - panelTop) }; + // The wordmark: dim, low in the bottom band. + const wordmark = { x: a.x0, y: H - Math.round(38 * u) - Math.round(28 * u), size: Math.round(28 * u) }; + // A post item (layout 4): its card from under the rail to the panel's top, the counters under it. + const card = { x: a.x0, y: even(rail.y + rail.height + Math.round(76 * u)), width: evenDown(a.x1 - a.x0), height: 0 }; + card.height = evenDown(panelTop - card.y); + const postCounters = { x: a.x0, y: card.y + card.height + Math.round(26 * u), width: a.x1 - a.x0, height: Math.round(80 * u) }; + // Two crops (layout 3): the source line over the rail at the top, crop one, the strip, crop two to the bottom band. + const top = { x: a.x0, y: a.y0 + Math.round(6 * u), width: a.x1 - a.x0, height: picture.y - (a.y0 + Math.round(6 * u)) - Math.round(10 * u) }; + const crop1 = { x: 0, y: picture.y, width: W, height: even(H * 0.3275) }; + const strip = { x: 0, y: crop1.y + crop1.height, width: W, height: even(144 * u) }; + const crop2 = { x: 0, y: strip.y + strip.height, width: W, height: evenDown(a.y1 - (strip.y + strip.height)) }; + const qs = even(W * STACKED_QR_SMALL_SHARE); + const twocrop = { + top, crop1, strip, crop2, + captions: { bottom: crop2.y + crop2.height - Math.round(18 * u) }, + qr: { x: a.x0, y: a.y1 + Math.round((H - a.y1 - qs) / 2), size: qs }, + }; + // The finale: its title in the rail's place, the instrument column over the picture's room. + const finale = { + title: { x: a.x0, y: rail.y, width: a.x1 - a.x0, height: label }, + column: { x: a.x0, y: even(rail.y + label + Math.round(30 * u)), width: evenDown(a.x1 - a.x0), height: 0 }, + }; + finale.column.height = evenDown(a.y1 - Math.round(10 * u) - finale.column.y); + return { + W, H, safe: a, gap, rail, picture, shelf, captions, panel, counters, source: sourceBlock, wordmark, + post: { card, counters: postCounters }, twocrop, finale, + }; +} + +/** + * The panel's cells: `items` in order, each `{ id, tall?, aspect }` (its + * design box's width / height). A TALL item (the dial) takes the left column's + * whole height and the rest stack down the right; without one they fill the + * two columns, the shorter first. Each cell is its column's width and its + * aspect's height (at most what is left). An item that does not fit is left + * out (`out`), never squashed. + * + * @param {{x:number,y:number,width:number,height:number}} panel + * @param {Array<{ id: string, tall?: boolean, aspect: number }>} items + * @param {number} gap + * @returns {{ cells: Record<string, {x:number,y:number,width:number,height:number}>, out: string[] }} + */ +export function panelCells(panel, items, gap) { + const colW = evenDown((panel.width - gap) / 2); + const cols = [ + { x: panel.x, y: panel.y }, + { x: panel.x + panel.width - colW, y: panel.y }, + ]; + const bottom = panel.y + panel.height; + const cells = {}; + const out = []; + let tallDone = false; + for (const it of items) { + if (it.tall && !tallDone && cols[0].y === panel.y) { + cells[it.id] = { x: cols[0].x, y: panel.y, width: colW, height: evenDown(panel.height) }; + cols[0].y = bottom + gap; + tallDone = true; + continue; + } + // At its column's width, else a size down (to PANEL_SHRINK of it, its aspect kept) where that fits. + let placed = null; + for (const k of [1, 0.95, 0.9, 0.85, PANEL_SHRINK]) { + const w = evenDown(colW * k); + const h = evenDown(w / Math.max(0.2, it.aspect)); + // The column with the most room left that holds it. + const fits = cols.filter((c) => c.y + h <= bottom + 0.5).sort((p, q) => p.y - q.y || p.x - q.x); + if (fits.length && h >= 24) { + placed = { c: fits[0], w, h }; + break; + } + } + if (!placed) { + out.push(it.id); + continue; + } + const { c, w, h } = placed; + cells[it.id] = { x: c.x, y: c.y, width: w, height: h }; + c.y += h + gap; + } + return { cells, out }; +} + +/** + * The caption geometry the vertical captions (vertical.mjs verticalAss) are + * drawn with in the stacked deck: under the picture, centred, the stacked + * deck's size -- or, for a twocrop clip, over crop two's foot. + */ +export function stackedCaptionGeo(render, { twocrop = false } = {}) { + const g = stackedGeometry(render); + const marginL = g.safe.x0 + Math.round(10 * (g.W / 1080)); + const marginR = g.W - g.safe.x1 + Math.round(10 * (g.W / 1080)); + if (twocrop) { + return { layout: "stacked", size: Math.round(g.captions.size * 1.08), tag: null, captions: { align: 2, marginL, marginR, marginV: g.H - g.twocrop.captions.bottom } }; + } + return { layout: "stacked", size: g.captions.size, tag: null, captions: { align: 8, marginL, marginR, marginV: g.captions.y } }; +} + +/** + * A crop of the source (`[x, y, w, h]` fractions) cut to a box's aspect about + * its centre, in source px (even): what a twocrop band shows. + */ +export function cropToBox(crop, srcW, srcH, box) { + const [fx, fy, fw, fh] = crop; + let w = fw * srcW; + let h = fh * srcH; + const want = box.width / box.height; + if (w / h > want) w = h * want; + else h = w / want; + w = Math.max(2, Math.min(evenDown(w), srcW - (srcW % 2))); + h = Math.max(2, Math.min(evenDown(h), srcH - (srcH % 2))); + const cx = (fx + fw / 2) * srcW; + const cy = (fy + fh / 2) * srcH; + return { w, h, x: Math.round(Math.max(0, Math.min(srcW - w, cx - w / 2))), y: Math.round(Math.max(0, Math.min(srcH - h, cy - h / 2))) }; +} + +/** How far a band enlarges the source's own pixels, each crop (its band's width over the crop's): past ENLARGE_WARN it softens. */ +export function twoCropEnlargement(crops, srcW, srcH, render) { + const g = stackedGeometry(render).twocrop; + return [g.crop1, g.crop2].map((box, i) => { + const c = cropToBox(crops[i], srcW, srcH, box); + return Math.round((box.width / c.w) * 100) / 100; + }); +} + +/** A band enlarged past this many times its source pixels is said to soften (a lint warning, never a refusal). */ +export const ENLARGE_WARN = 2.5; + +/** + * The twocrop picture as ONE filtergraph from the build's picture pad to its + * last filter: the frame's ground, crop one in its band, crop two in its band. + * `blur` the clip's own blur on the source first. + */ +export function twoCropGraph({ crops, srcW, srcH, render, blur = [], fps = 30, id = "tc" }) { + const g = stackedGeometry(render); + const W = g.W; + const H = g.H; + const p = (s) => `${id}${s}`; + const bg = String(render?.palette?.bg ?? "#12100c").replace("#", "0x"); + const t = g.twocrop; + const a = cropToBox(crops[0], srcW, srcH, t.crop1); + const b = cropToBox(crops[1], srcW, srcH, t.crop2); + const lead = [...blur, "setsar=1"].join(","); + // The ground is crop one PADDED to the frame -- never an endless colour source under an overlay, which the + // filtergraph fills faster than the picture drains it (the real-data preview was OOM-killed at 8 GB, 9 Nov). + return [ + `${lead},split=2[${p("a")}][${p("b")}]`, + `[${p("a")}]crop=${a.w}:${a.h}:${a.x}:${a.y},scale=${t.crop1.width}:${t.crop1.height}:flags=lanczos,setsar=1,pad=${W}:${H}:0:${t.crop1.y}:color=${bg}[${p("g1")}]`, + `[${p("b")}]crop=${b.w}:${b.h}:${b.x}:${b.y},scale=${t.crop2.width}:${t.crop2.height}:flags=lanczos,setsar=1[${p("2")}]`, + `[${p("g1")}][${p("2")}]overlay=x=0:y=${t.crop2.y}:format=auto,setsar=1,fps=${fps}`, + ].join(";"); +} + +/** + * The spans the panel's instruments stand down for in the stacked deck: a post + * item (its card takes the room) and a twocrop clip (its strip carries them). + * `[{ from, to }]` in cut seconds, from the schedule's segments. + */ +export function stackedStandDowns(schedule) { + return (schedule?.segments ?? []) + .filter((s) => s.type === "post" || s.vlayout === "twocrop") + .map((s) => ({ from: s.start, to: s.end ?? s.start + s.duration, why: s.type === "post" ? "post" : "twocrop" })); +} + +/** The words a module left out of the stacked deck is said with (the lint, the build's note). */ +export const leftOutWords = (id, why = "no vertical form") => + `${id}: ${why} -- left out of the stacked vertical deck (render.vertical.deck "bare" drops the deck; landscape keeps it)`; diff --git a/umtool/report-to-video/vertical-deck.test.mjs b/umtool/report-to-video/vertical-deck.test.mjs @@ -0,0 +1,415 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + ENLARGE_WARN, STACKED_PICTURE_K, cropToBox, panelCells, stackedCaptionGeo, stackedGeometry, stackedOn, stackedSafe, stackedStandDowns, + twoCropEnlargement, twoCropGraph, +} from "./vertical-deck.mjs"; +import { verticalRender } from "./vertical.mjs"; +import { + deckGeometry, deckLayout, deckSchedule, instrumentsGeometry, pictureK, resolveDeck, stampGeometry, statsGeometry, validateChrome, +} from "./deck.mjs"; +import { verticalKnobs, validateVerticalRender } from "yt-dlp-transcript-common/lib/report/vertical.mjs"; +import { validateLook } from "yt-dlp-transcript-common/lib/report/look.mjs"; +import { measureExtraGeometry } from "./measure-extras.mjs"; +import { stackedLeftOut, MODULES, verticalFormOf } from "./modules/index.mjs"; +import { stackedLintWarnings } from "./lint.mjs"; +import { stackedDeckHtml, stackedSections, wordmarkOf } from "./chrome-vdeck.mjs"; +import { dialFinaleGeometry } from "./chrome-instruments.mjs"; + +const DECK = { engine: "hyperframes", layout: "deck", deck: {} }; +const landscape = (deck = {}) => ({ width: 1920, height: 1080, fps: 30, chrome: { ...DECK, deck }, palette: { bg: "#0F1312", fg: "#EDF0EC", accent: "#22AB83" } }); +const stacked = (deck = {}, vertical = {}) => verticalRender({ ...landscape(deck), format: "vertical", vertical }); + +const inside = (r, a) => r.x >= a.x0 - 1e-9 && r.x + r.width <= a.x1 + 1e-9 && r.y >= a.y0 - 1e-9 && r.y + r.height <= a.y1 + 1e-9; + +test("the knob: absent is stacked; bare and stacked validate; anything else is refused", () => { + assert.equal(verticalKnobs({}).deck, "stacked"); + assert.equal(verticalKnobs({ vertical: { deck: "bare" } }).deck, "bare"); + assert.deepEqual(validateVerticalRender({ render: { format: "vertical", vertical: { deck: "stacked" } } }), []); + assert.ok(validateVerticalRender({ render: { vertical: { deck: "tall" } } })[0].includes("render.vertical.deck")); +}); + +test("stacked only where a vertical cut keeps a deck; bare and landscape never", () => { + assert.equal(stackedOn(stacked()), true); + assert.equal(stackedOn(stacked({}, { deck: "bare" })), false); + assert.equal(stackedOn(landscape()), false); + // A vertical cut with no deck is the bare vertical whatever it says. + assert.equal(stackedOn(verticalRender({ width: 1920, height: 1080, format: "vertical" })), false); + // verticalRender keeps the chrome only for the stacked deck. + assert.ok(stacked().chrome); + assert.equal(stacked({}, { deck: "bare" }).chrome, undefined); +}); + +test("bare is the vertical as it shipped, byte for byte: the same render, whatever the deck", () => { + const withDeck = verticalRender({ ...landscape(), format: "vertical", vertical: { deck: "bare" } }); + const noDeck = verticalRender({ ...landscape(), chrome: undefined, format: "vertical", vertical: { deck: "bare" } }); + assert.equal(JSON.stringify(withDeck), JSON.stringify(noDeck)); + // And a deck-less vertical cut is unchanged by the default. + const plain = verticalRender({ width: 1920, height: 1080, fps: 30, format: "vertical" }); + assert.equal(plain.chrome, undefined); + assert.equal(plain.width, 1080); +}); + +test("every zone of the stacked deck keeps inside the safe area; the picture is the frame's width", () => { + for (const safe of [{}, { top: 0.1, bottom: 0.22, right: 0.14 }]) { + const r = stacked({ measure: {} }, { safe }); + const g = stackedGeometry(r, { counter: true }); + const a = stackedSafe(r); + for (const [name, box] of [["rail", g.rail], ["captions", g.captions], ["panel", g.panel], ["counters", g.counters], ["source", g.source], ["card", g.post.card], ["post counters", g.post.counters], ["finale", g.finale.column]]) { + assert.ok(inside(box, a), `${name} ${JSON.stringify(box)} inside ${JSON.stringify(a)}`); + } + // What stands over the picture -- the stamps and the stats at every corner, the measure extras at every anchor -- + // keeps inside the safe area too (the picture itself is the frame's whole width). + for (const position of ["top-left", "top-right", "bottom-left", "bottom-right"]) { + const rr = stacked({ measure: {} }, { safe }); + const fc = { ...rr, chrome: { ...rr.chrome, factcheck: { stamp: { position } }, stats: { position } } }; + assert.ok(inside(stampGeometry(fc), a), `stamp ${position} ${JSON.stringify(stampGeometry(fc))}`); + assert.ok(inside(statsGeometry(fc), a), `stats ${position} ${JSON.stringify(statsGeometry(fc))}`); + } + for (const id of ["goals", "peak", "diet", "streak"]) { + for (const position of ["top-left", "top-right", "bottom-left", "bottom-right", "top-center", "bottom-center"]) { + const rr = { ...r, chrome: { ...r.chrome, deck: { ...r.chrome.deck, [id]: { position } } } }; + const box = measureExtraGeometry(id, rr); + assert.ok(inside(box, a), `${id} ${position} ${JSON.stringify(box)}`); + } + } + // Nothing that must be read in the right band or the bottom band. + for (const box of [g.rail, g.captions, g.panel, g.source, g.counters]) { + assert.ok(box.x + box.width <= a.x1); + assert.ok(box.y + box.height <= a.y1); + } + // The picture: the frame's full width, 16:9, under the rail and over the captions. + assert.equal(g.picture.width, g.W); + assert.equal(g.picture.height, Math.round((g.W * 9) / 16 / 2) * 2); + assert.ok(g.picture.y >= g.rail.y + g.rail.height); + assert.ok(g.captions.y >= g.picture.y + g.picture.height); + // The zones stack top to bottom without meeting. + assert.ok(g.panel.y >= g.captions.y + g.captions.height); + assert.ok(g.counters.y >= g.panel.y + g.panel.height); + assert.ok(g.source.y >= g.counters.y + g.counters.height); + // Only the wordmark and the twocrop's small QR stand in the bottom band. + assert.ok(g.wordmark.y >= a.y1); + assert.ok(g.twocrop.qr.y >= a.y1 && g.twocrop.qr.x + g.twocrop.qr.size <= a.x1); + } +}); + +test("the twocrop bands: crop one, the strip, crop two to the bottom band; its captions over crop two's foot", () => { + const r = stacked(); + const g = stackedGeometry(r); + const t = g.twocrop; + assert.equal(t.crop1.y + t.crop1.height, t.strip.y); + assert.equal(t.strip.y + t.strip.height, t.crop2.y); + assert.ok(t.crop2.y + t.crop2.height <= g.safe.y1); + assert.ok(t.top.y >= g.safe.y0 && t.top.y + t.top.height <= t.crop1.y); + const cap = stackedCaptionGeo(r, { twocrop: true }); + assert.equal(cap.captions.align, 2); + assert.ok(g.H - cap.captions.marginV <= t.crop2.y + t.crop2.height && g.H - cap.captions.marginV > t.crop2.y); + // Under the picture otherwise, top-aligned, inside the safe edges. + const c = stackedCaptionGeo(r); + assert.equal(c.captions.align, 8); + assert.equal(c.captions.marginV, g.captions.y); + assert.ok(c.captions.marginR >= g.W - g.safe.x1); +}); + +test("a crop is cut to its band's aspect about its centre; the enlargement is said past 2.5x", () => { + const box = { width: 1080, height: 629 }; + const c = cropToBox([0, 0, 0.5, 0.5], 1920, 1080, box); + assert.ok(Math.abs(c.w / c.h - box.width / box.height) < 0.01); + assert.ok(c.x >= 0 && c.x + c.w <= 1920 && c.y >= 0 && c.y + c.h <= 1080); + const r = stacked(); + const [a, b] = twoCropEnlargement([[0, 0, 0.9, 0.9], [0.8, 0.8, 0.2, 0.2]], 1920, 1080, r); + assert.ok(a < ENLARGE_WARN); + assert.ok(b > ENLARGE_WARN); + const graph = twoCropGraph({ crops: [[0, 0, 0.6, 0.6], [0.6, 0.6, 0.4, 0.4]], srcW: 1920, srcH: 1080, render: r, fps: 30 }); + assert.ok(graph.includes(`pad=1080:1920:0:${stackedGeometry(r).twocrop.crop1.y}`)); + assert.ok(!graph.includes("color=c="), "no endless colour source under an overlay"); + assert.ok(graph.includes(`overlay=x=0:y=${stackedGeometry(r).twocrop.crop2.y}`)); + assert.ok(graph.startsWith("setsar=1,split=2")); +}); + +test("a clip's twocrop: its crops required, two boxes inside the picture; the lint says a soft band", () => { + const ok = { render: {}, timeline: [{ type: "clip", id: "a", vertical: { layout: "twocrop", crops: [[0, 0, 0.5, 0.5], [0.5, 0.5, 0.5, 0.5]] } }] }; + assert.deepEqual(validateLook(ok), []); + assert.ok(validateLook({ render: {}, timeline: [{ type: "clip", id: "a", vertical: { layout: "twocrop" } }] })[0].includes("needs")); + assert.ok(validateLook({ render: {}, timeline: [{ type: "clip", id: "a", vertical: { layout: "twocrop", crops: [[0, 0, 1.5, 0.5], [0, 0, 0.5, 0.5]] } }] }).some((x) => x.includes("inside"))); + assert.ok(validateLook({ render: {}, timeline: [{ type: "clip", id: "a", vertical: { layout: "full", crops: [[0, 0, 0.5, 0.5], [0, 0, 0.5, 0.5]] } }] }).some((x) => x.includes("twocrop"))); + const m = { render: { ...landscape(), format: "vertical" }, timeline: [{ type: "clip", id: "a", vertical: { layout: "twocrop", crops: [[0, 0, 0.9, 0.9], [0.9, 0.9, 0.1, 0.1]] } }] }; + assert.equal(stackedLintWarnings(m).length, 1); + assert.ok(stackedLintWarnings(m)[0].includes("crops[1]")); + assert.ok(stackedLintWarnings({ ...m, render: { ...m.render, vertical: { deck: "bare" } } })[0].includes("stacked deck's")); +}); + +test("the panel: the dial tall at the left, the odometer and the trail down the right; what does not fit is left out", () => { + const p = { x: 0, y: 0, width: 900, height: 300 }; + const { cells, out } = panelCells(p, [{ id: "dial", tall: true, aspect: 1 }, { id: "odometer", aspect: 600 / 140 }, { id: "trail", aspect: 600 / 138 }], 20); + assert.deepEqual(out, []); + assert.equal(cells.dial.x, 0); + assert.equal(cells.dial.height, 300); + assert.ok(cells.odometer.x > cells.dial.x + cells.dial.width); + assert.ok(cells.trail.y >= cells.odometer.y + cells.odometer.height); + // Too many for the room: the last is left out, never squashed. + const crowd = panelCells(p, [{ id: "a", aspect: 2 }, { id: "b", aspect: 2 }, { id: "c", aspect: 2 }, { id: "d", aspect: 2 }, { id: "e", aspect: 2 }], 20); + assert.ok(crowd.out.length >= 1); + for (const c of Object.values(crowd.cells)) assert.ok(c.y + c.height <= p.height); +}); + +test("the stacked geometry answers deck.mjs's: the footage the picture, the instruments in the panel, the shell the frame", () => { + const r = stacked({ measure: {} }); + const d = deckGeometry(r); + const g = stackedGeometry(r); + assert.deepEqual(d.footage, g.picture); + assert.deepEqual(d.deck, { x: 0, y: 0, width: 1080, height: 1920 }); + const ig = instrumentsGeometry(r); + for (const n of ["dial", "odometer", "trail"]) assert.ok(inside(ig[n], stackedSafe(r)), n); + assert.equal(pictureK(r), STACKED_PICTURE_K); + // The posts stay popups that never move the picture. + assert.equal(resolveDeck(r).posts.shift, false); + assert.equal(resolveDeck(r).posts.layout, "popup"); + assert.equal(resolveDeck(r).posts.show, false); + // The landscape fit checks do not apply. + assert.deepEqual(validateChrome(r.chrome, r), []); + // As the chrome preview route asks it: the render without its chrome beside the chrome. + const { chrome: _c, ...rest } = r; + assert.deepEqual(validateChrome(r.chrome, rest), []); + // The stamp over the picture's lower-left by default, inside it. + const st = stampGeometry(r); + assert.ok(st.x >= d.footage.x && st.y + st.height <= d.footage.y + d.footage.height); + // A measure extra over the picture. + const diet = measureExtraGeometry("diet", r); + assert.ok(diet.y >= d.footage.y && diet.y + diet.height <= d.footage.y + d.footage.height); + // The dial's finale: the column over the picture's room, inside the safe area. + assert.ok(inside(dialFinaleGeometry({ finale: { from: 0, to: 5 } }, r), stackedSafe(r))); +}); + +test("landscape at 1080 is the deck as it always was; 720p fits instead of standing at y < 0", () => { + const r = landscape(); + assert.deepEqual(deckGeometry(r), { W: 1920, H: 1080, footage: { x: 173, y: 2, width: 1574, height: 886 }, deck: { x: 0, y: 890, width: 1920, height: 190 } }); + assert.deepEqual(resolveDeck(r).title, { size: 54, maxChars: 48 }); + assert.equal(resolveDeck(r).height, 190); + const lay = deckLayout(r); + assert.equal(lay.text.titleSize, 54); + assert.equal(lay.qr.size, 150); + const r720 = { ...r, width: 1280, height: 720 }; + const g = deckGeometry(r720); + assert.ok(g.footage.y >= 0, `footage y ${g.footage.y}`); + assert.ok(g.footage.y + g.footage.height <= g.deck.y); + assert.equal(g.deck.y + g.deck.height, 720); + assert.deepEqual(validateChrome(r720.chrome, r720), []); + // Its band scaled with the height: two thirds of the 1080 deck. + assert.equal(g.deck.height, Math.round(190 * (720 / 1080))); + assert.equal(deckLayout(r720).text.titleSize, 36); +}); + +test("the schedule: a stacked deck's clips carry their source parts and a twocrop its layout; landscape does not", () => { + const entries = [ + { id: "c1", type: "clip", video: "v1", start: 125, end: 130, title: "First", channelTitle: "Chan", date: "2026-01-12" }, + { id: "c2", type: "clip", video: "v2", start: 5, end: 9, title: "Second", vertical: { layout: "twocrop", crops: [[0, 0, 0.5, 0.5], [0.5, 0.5, 0.5, 0.5]] } }, + { id: "p1", type: "post", platform: "x", author: "A", handle: "a", date: "2026-11-04", text: "hi" }, + ]; + const args = { entries, durs: [5, 4, 6], D: 0.4, provenance: {}, metas: [null, null, null] }; + const v = deckSchedule({ ...args, render: stacked() }); + assert.equal(v.segments[0].vsource.clock, "2:05"); + assert.equal(v.segments[0].vsource.channel, "Chan"); + assert.equal(v.segments[1].vlayout, "twocrop"); + assert.equal(v.segments[2].vsource, undefined); + assert.deepEqual(stackedStandDowns(v).map((x) => x.why), ["twocrop", "post"]); + const l = deckSchedule({ ...args, render: landscape() }); + assert.equal(l.segments[0].vsource, undefined); + assert.equal(l.segments[1].vlayout, undefined); +}); + +test("the shell's page in 9:16: the rail's sections, each segment's source block and its QR, the wordmark", () => { + const r = stacked({ markers: [{ after: "c1", label: "Carnivore", color: "#C9534B" }], sectionTitle: { first: "The first diets" }, pip: { color: "section" } }); + const entries = [ + { id: "c1", type: "clip", video: "v1", start: 5, end: 9, title: "First", channelTitle: "Chan", date: "2026-01-12" }, + { id: "c2", type: "clip", video: "v2", start: 5, end: 9, title: "Second", channelTitle: "Chan", date: "2026-01-13" }, + ]; + const sched = deckSchedule({ entries, durs: [4, 4], D: 0.4, render: r, provenance: {}, metas: [null, null] }); + const sec = stackedSections(sched, r); + assert.deepEqual(sec.sections.map((s) => s.label), ["The first diets", "Carnivore"]); + const html = stackedDeckHtml(sched, r, { qrSrcs: { c1: "assets/qr00.png" }, site: wordmarkOf({ siteOrigin: "https://jeralyzer.pages.dev" }) }); + assert.ok(html.includes('data-width="1080" data-height="1920"')); + assert.ok(html.includes("JERALYZER")); + assert.ok(html.includes("Carnivore") && html.includes("The first diets")); + assert.ok(html.includes("assets/qr00.png")); + assert.ok(html.includes('id="deck-data"')); + assert.ok(html.includes("1 / 2") && html.includes("2 / 2")); +}); + +test("what the stacked deck leaves out is said; every module that stands in it declares where", () => { + const forms = new Map(MODULES.map((m) => [m.id, verticalFormOf(m)?.slot ?? null])); + assert.equal(forms.get("shell"), "frame"); + assert.equal(forms.get("dial"), "panel"); + assert.equal(forms.get("dial-finale"), "finale"); + assert.equal(forms.get("popup-posts"), null); + const m = { render: { ...landscape({ measure: {} }), format: "vertical", chrome: { ...DECK, deck: { measure: {} }, flips: { items: [] } } }, posts: [{ id: "p" }], timeline: [] }; + const words = stackedLeftOut(m); + assert.ok(words.some((w) => w.startsWith("popup-posts:"))); + assert.ok(words.some((w) => w.startsWith("flips:"))); + assert.deepEqual(stackedLeftOut({ ...m, render: { ...m.render, vertical: { deck: "bare" } } }), []); + // The finale's diet runs, with a finale to draw them in. + const runs = { ...m, render: { ...m.render, chrome: { ...m.render.chrome, deck: { finale: { dietRuns: true } } } }, timeline: [{ type: "clip", id: "n", layout: "finale" }] }; + assert.ok(stackedLeftOut(runs).some((w) => w.startsWith("runs-finale:"))); + assert.ok(!stackedLeftOut(m).some((w) => w.startsWith("chart:")), "the chart band only under its own legacy engine"); + assert.deepEqual(stackedLeftOut({ ...m, render: landscape() }), []); +}); + +// ---- landscape and the bare vertical: byte for byte what main drew ----------------------------- +// +// md5s taken from main (7f7767a0) with the same fixture -- the measure-dial cut of instruments.test.mjs with +// markers and a section title: the estimate's schedule, the deck's page, the dial's, the odometer's, the trail's, +// the dial finale's and the deck's geometry; and the bare vertical's render, each clip layout's geometry, picture +// graph and words, and a post's box. +const MAIN = { + schedule: "4ebd0afd1cddb975b6d20ce934df2158", + deck: "546848c82d65e45e4d1a4ac4c7a9c3c8", + dial: "f7e21e4a3622703975f746d39cbcb738", + odometer: "8425983d217408dddcb6ee794881c6c4", + trail: "3512192be69f8b9bc33aec6e7b41a088", + dialFinale: "52866e4d87e15bd55afe8c1a703414a3", + geometry: "182959796c281f769766df3d02962904", + bare: "7ce1f7a66452adec21575bcdbba900f1", +}; + +test("a landscape cut and a bare vertical draw what main drew, byte for byte", async () => { + const { createHash } = await import("node:crypto"); + const { readFileSync } = await import("node:fs"); + const path = await import("node:path"); + const { fileURLToPath } = await import("node:url"); + const deck = await import("./deck.mjs"); + const ci = await import("./chrome-instruments.mjs"); + const cd = await import("./chrome-deck.mjs"); + const v = await import("./vertical.mjs"); + const here = path.dirname(fileURLToPath(import.meta.url)); + const md5 = (s) => createHash("md5").update(typeof s === "string" ? s : JSON.stringify(s)).digest("hex"); + const MEASURE = JSON.parse(readFileSync(path.join(here, "fixtures/measure-dial/measure.json"), "utf8")); + const RENDER = { + width: 1920, height: 1080, fps: 30, transition: 0.4, + palette: { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" }, + chrome: { ...DECK, deck: { dial: true, odometer: true, trail: true, qr: { show: false }, finale: { video: "side", totals: false }, markers: [{ after: "c3", label: "Two" }], sectionTitle: { first: "One" } } }, + }; + const timeline = Array.from({ length: 9 }, (_, i) => ({ + type: "clip", id: `c${i + 1}`, video: "vidx", start: 10 * i, end: 10 * i + (i === 8 ? 14 : 8), cite: 1, section: 0, + quote: "q", onscreen: { title: `Clip ${i + 1}` }, ...(i === 8 ? { layout: "finale" } : {}), + })); + const s = { ...deck.estimateSchedule({ slug: "m", title: "M", provenance: {}, render: RENDER, timeline }), measure: MEASURE }; + const fonts = { DeckSans: "assets/r.ttf", DeckSansBold: "assets/b.ttf" }; + assert.equal(md5(s), MAIN.schedule); + assert.equal(md5(cd.deckHtml(s, RENDER, { fonts: { regular: "r.ttf", bold: "b.ttf" } })), MAIN.deck); + assert.equal(md5(ci.dialHtml(s, RENDER, { fonts })), MAIN.dial); + assert.equal(md5(ci.odometerHtml(s, RENDER, { fonts })), MAIN.odometer); + assert.equal(md5(ci.trailHtml(s, RENDER, { fonts })), MAIN.trail); + const win = deck.snapWindow({ segment: "dial-finale", from: s.finale.from, to: s.finale.to }, { fps: 30, total: s.total }); + assert.equal(md5(ci.dialFinaleHtml(s, RENDER, win, { fonts })), MAIN.dialFinale); + assert.equal(md5([deck.deckGeometry(RENDER), deck.instrumentsGeometry(RENDER), deck.deckLayout(RENDER, { schedule: s }), deck.stampGeometry(RENDER), deck.statsGeometry({ ...RENDER, chrome: { ...RENDER.chrome, stats: {} } })]), MAIN.geometry); + const vr = v.verticalRender({ ...RENDER, format: "vertical", vertical: { deck: "bare", clip: "framed", hook: "section" } }); + const words = [{ text: "so", start: 0.2, end: 0.4 }, { text: "the", start: 0.45, end: 0.6 }, { text: "scale", start: 0.62, end: 1 }, { text: "says", start: 1.1, end: 1.4 }]; + const bare = { render: vr, layouts: {} }; + for (const layout of ["full", "framed", "quote", "split", "overlay"]) { + const geo = v.clipGeometry(layout, vr); + bare.layouts[layout] = { geo, graph: v.verticalClipGraph({ geo, srcW: 1920, srcH: 1080, crop: null, fps: 30 }), ass: v.verticalAss({ geo, render: vr, words, seconds: 3, tag: "Chan · 12 Jan 2026", hook: "One" }) }; + } + bare.post = v.verticalPostBox(vr); + assert.equal(md5(bare), MAIN.bare); +}); + +test("the lint reads a vertical cut's QR at 720p on its short side, at the size the stacked deck draws it", async () => { + const { lintManifest, qrsOf } = await import("./lint.mjs"); + const render = stacked(); + const timeline = [ + { type: "clip", id: "a", video: "v7eqa6e", channel: "the-quartering-rumble", start: 633.42, end: 644.16, citeUrl: "https://jeralyzer.pages.dev/channel/the-quartering-rumble/v7eqa6e?t=633" }, + { type: "clip", id: "b", video: "v7eqa6e", start: 1, end: 5, citeUrl: "https://jeralyzer.pages.dev/channel/the-quartering-rumble/v7eqa6e?t=1", vertical: { layout: "twocrop", crops: [[0, 0, 0.6, 0.6], [0.6, 0.4, 0.4, 0.6]] } }, + ]; + const m = { slug: "s", render, provenance: { siteOrigin: "https://jeralyzer.pages.dev" }, timeline }; + const qrs = qrsOf(m); + assert.deepEqual(qrs.map((q) => q.px), [140, 108]); + const l = lintManifest(m, { validators: false }); + assert.ok(!l.errors.some((e) => e.includes("too small to scan")), l.errors.join("; ")); +}); + +test("a stacked vertical deck's render declares at least its measured peak + margin; a bare one what it did", async () => { + const { VERTICAL_DECK_MIN_MB, manifestEstimateMb } = await import("./render-estimate.mjs"); + const one = (render) => manifestEstimateMb({ render, timeline: [{ type: "clip", id: "a" }] }, {}, { single: true }); + const v = { format: "vertical", chrome: { engine: "hyperframes", layout: "deck", deck: {} } }; + assert.ok(one(v) >= VERTICAL_DECK_MIN_MB); + assert.equal(one({ ...v, vertical: { deck: "bare" } }), one({ chrome: v.chrome })); +}); + +test("with the tally's row the dial, the odometer and the trail still stand in the panel (a cell a size down, never squashed)", () => { + const r = verticalRender({ ...landscape({ dial: true, odometer: true, trail: true }), format: "vertical", chrome: { ...DECK, deck: { dial: true, odometer: true, trail: true }, factcheck: {} } }); + const ig = instrumentsGeometry(r); + assert.deepEqual(ig.out, []); + for (const n of ["dial", "odometer", "trail"]) assert.ok(ig[n], n); + assert.ok(Math.abs(ig.trail.width / ig.trail.height - 600 / 138) < 0.1); + assert.ok(ig.trail.y + ig.trail.height <= ig.column.y + ig.column.height); +}); + +test("720p: markers (two rows), a two-line subtitle, a goalpost and a tally all fit inside the scaled band", () => { + const deck = { + footageScale: 0.7, subtitle: { lines: 2 }, sectionTitle: { first: "Opening" }, + markers: [{ after: "c1", label: "A long first section" }, { after: "c2", label: "Another long section" }, { after: "c3", label: "And a third one" }], + claims: [{ kind: "goalpost", label: "Pill test results", steps: [{ at: "c2", t: 1, said: "“3–5 weeks”", from: "2026-09-23", due: ["P3W", "P5W"] }] }], + }; + const r = { width: 1280, height: 720, fps: 30, chrome: { ...DECK, deck }, palette: { bg: "#0F1312", fg: "#EDF0EC" } }; + assert.deepEqual(validateChrome(r.chrome, r), []); + const g = deckGeometry(r); + assert.ok(g.footage.y >= 0 && g.footage.y + g.footage.height <= g.deck.y); + const lay = deckLayout(r, { tally: ["CORROBORATED", "CONTRADICTED", "UNVERIFIED"] }); + assert.equal(lay.scale, 2 / 3); + const t = lay.text; + const textBottom = t.subtitleY + (t.headBox ?? 0) + t.subtitleBox; + assert.ok(textBottom <= lay.height, `text bottom ${textBottom} in a ${lay.height} px band`); + assert.ok(lay.tally.y >= 0 && lay.tally.y + lay.tally.height <= lay.height, JSON.stringify(lay.tally)); + assert.ok(lay.tally.cell >= 80, "the tally's cells scaled, not squashed"); + assert.ok(lay.qr.y + lay.qr.size <= lay.height); + // A size written in pixels stays those pixels at 720. + assert.equal(resolveDeck({ ...r, chrome: { ...DECK, deck: { ...deck, height: 200, qr: { size: 120 } } } }).height, 200); + assert.equal(resolveDeck({ ...r, chrome: { ...DECK, deck: { ...deck, qr: { size: 120 } } } }).qr.size, 120); +}); + +test("a --vertical build of a landscape deck cut (umtool vertical) declares the stacked floor too; --deck bare does not", async () => { + const { mkdtemp, writeFile, rm } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const path = await import("node:path"); + const { VERTICAL_DECK_MIN_MB, manifestEstimateMb } = await import("./render-estimate.mjs"); + const { cliEstimateMb } = await import("./build-video.mjs"); + const m = { render: { width: 1920, height: 1080, chrome: { engine: "hyperframes", layout: "deck", deck: {} } }, timeline: [{ type: "clip", id: "a" }] }; + assert.ok(manifestEstimateMb(m, {}, { single: true, vertical: true }) >= VERTICAL_DECK_MIN_MB); + assert.equal(manifestEstimateMb(m, {}, { single: true, vertical: { deck: "bare" } }), manifestEstimateMb(m, {}, { single: true })); + const dir = await mkdtemp(path.join(tmpdir(), "vdeck-est-")); + try { + const file = path.join(dir, "m.json"); + await writeFile(file, JSON.stringify(m)); + assert.ok((await cliEstimateMb(file, { vertical: true, verticalKnobs: {}, short: false, clipPreview: false }, {})) >= VERTICAL_DECK_MIN_MB); + assert.ok((await cliEstimateMb(file, { vertical: true, verticalKnobs: { deck: "bare" } }, {})) < VERTICAL_DECK_MIN_MB || manifestEstimateMb(m, {}) >= VERTICAL_DECK_MIN_MB); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a stacked short's pieces are cut from the built cut clear of its dissolves, never past their own segment", async () => { + const { builtSpans } = await import("./reframe.mjs"); + const schedule = { transition: 0.5, segments: [{ id: "a", start: 0, duration: 6 }, { id: "b", start: 5.5, duration: 8 }, { id: "c", start: 13, duration: 4 }] }; + assert.deepEqual(builtSpans([{ id: "a", from: 0, to: null }, { id: "b", from: 1, to: 20 }, { id: "c", from: 0, to: null }], schedule), [ + { from: 0, to: 5.5 }, { from: 6.5, to: 13 }, { from: 13.5, to: 17 }, + ]); + // A piece the build does not have: joined from the segments as before. + assert.equal(builtSpans([{ id: "z", from: 0, to: null }], schedule), null); + assert.equal(builtSpans([{ id: "a", from: 0, to: null }], null), null); +}); + +test("a bare short's outro is the card it always was: no end card, the same key", async () => { + const { endCardOf } = await import("../lib/report/verticalCli.mjs"); + const { outroKey } = await import("./outro.mjs"); + const render = { width: 1920, height: 1080, chrome: { engine: "hyperframes", layout: "deck", deck: {} } }; + const timeline = [{ type: "clip", id: "a", video: "v", start: 61, channelTitle: "Chan", date: "2026-01-12" }]; + const provenance = { siteOrigin: "https://jeralyzer.pages.dev" }; + assert.equal(await endCardOf({ render, knobs: { deck: "bare" }, provenance, timeline }), null); + assert.equal(await endCardOf({ render: { width: 1920, height: 1080 }, knobs: {}, provenance, timeline }), null); + assert.deepEqual(await endCardOf({ render, knobs: {}, provenance, timeline }), { qrUrl: "https://jeralyzer.pages.dev", sources: [{ date: "Jan 12", label: "Chan · 1:01" }] }); + // The card's key without an end card is the one it always was (v1, no `end`): pinned. + const brand = { name: "Jeralyzer", lead: "Jer", ink: "#5fc4a6" }; + assert.equal(outroKey({ width: 1080, height: 1920, title: "T", text: "X", brand }), outroKey({ width: 1080, height: 1920, title: "T", text: "X", brand, end: null })); + assert.equal(outroKey({ width: 1080, height: 1920, title: "T", text: "X", brand }), "ccb58d2be90ba1171c1e"); // main 195bd7d8 +}); diff --git a/umtool/report-to-video/vertical.mjs b/umtool/report-to-video/vertical.mjs @@ -22,11 +22,12 @@ // command (lib/report/verticalCli.mjs) call it. import { - VERTICAL_HEIGHT, VERTICAL_WIDTH, clipLayoutOf, sidePostOf, sideSpan, verticalKnobs, verticalOn, + VERTICAL_HEIGHT, VERTICAL_WIDTH, clipLayoutOf, sidePostOf, sideSpan, stackedDeckWanted, verticalKnobs, verticalOn, } from "yt-dlp-transcript-common/lib/report/vertical.mjs"; import { assColour, assTime, captionText, cropPixels } from "./look.mjs"; export { + CLIP_OWN_LAYOUTS, VERTICAL_DECKS, clipTwoCrop, stackedDeckWanted, LANDSCAPE_SIDE_PLACES, RENDER_FORMATS, SIDE_MIN_SECONDS, SIDE_PLACES, VERTICAL_CAPTION_SIZES, VERTICAL_CLIP_LAYOUTS, VERTICAL_DEFAULTS, VERTICAL_HEIGHT, VERTICAL_HOOKS, VERTICAL_KEYS, VERTICAL_POST_LAYOUTS, VERTICAL_SIDE_LAYOUTS, VERTICAL_WIDTH, clipLayoutOf, sideErrors, sidePostOf, sideSpan, validateClipSides, validateVerticalFormat, @@ -54,13 +55,17 @@ export const SIDE_MOTION = 0.35; /** * The render a vertical cut is built with: 1080x1920 at the cut's fps, no * header, footer, QR, rail, deck or montage; the cut's posts, narration, - * palette and fonts kept; the loudness the short is brought to. + * palette and fonts kept; the loudness the short is brought to. A cut that + * keeps its deck (`render.vertical.deck` "stacked", the default, on a cut with + * one: vertical-deck.mjs) keeps `chrome` -- the deck's geometry answers for + * 9:16 -- and nothing else changes; "bare" is the format as it first shipped. */ export function verticalRender(render = {}) { - const { chrome: _c, rail: _r, chromeEngine: _e, brand: _b, montage: _m, intro: _i, room: _ro, ...rest } = render; + const { chrome, rail: _r, chromeEngine: _e, brand: _b, montage: _m, intro: _i, room: _ro, ...rest } = render; const k = verticalKnobs(render); return { ...rest, + ...(stackedDeckWanted(render) ? { chrome } : {}), format: "vertical", width: VERTICAL_WIDTH, height: VERTICAL_HEIGHT,