commit f286e52076b3179ff70ea74b88e38309072f6bbc
parent 280211755350c4d7f98cc486cbb4164f93786cae
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 03:19:33 -0500
umtool: Add post in Play the cut (UI notes item 13) -- search, capture, the card on its clip, a crop, the warning
The chain capture-posts → `umtool posts add` → `umtool look deck.posts` in one panel
(components/projects/review/AddPost.tsx, /api/report/post-cards, lib/report/postCards.mjs):
search a channel's posts archive (channels/<slug>/posts/*.jsonl: every word, newest first;
the channels the cut's posts come from first, then <cited>-x); Capture a post with no
screenshot through the EDITOR's capture-posts (paced there, on the platform's queue), the job
followed until it ends; Add it to the clip on screen through `posts add`'s own write, now
`addPostFromArchive` in postsCli.mjs (the capture copied into the project, upsertPost, an undo
point), the playhead sent to the clip's end and the deck recomposed so the card shows on it.
A per-post crop: `posts[].shotMaxHeight` (120–1080 px, needs a shot; deck.mjs validatePosts),
the post's top that tall and NEVER panned (chrome-posts.mjs data-crop) -- unlike the deck-wide
deck.posts.shotMaxHeight, whose taller shots pan -- so a quoted post or a thumbnail under the
words stays off the screen. Written by updatePosts/normalizePostPatches and upsertPost, previewed
through the posts draft, `umtool posts set <p> <post> crop=<px>|off`, `posts add … --crop <px>`.
The warning is the post's own data, never the picture: `quoted`, `repostOf`, `mediaCount` (a
forum's `media`) -- on every hit, on every post in the cut, and as `WARNING:` lines from
`umtool posts add` (`--json`: warnings). The e2e stub takes capture-posts (a job that writes the
shot), and the fixture carries a social channel with a plain, a quoting and a media post.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
21 files changed, 1073 insertions(+), 77 deletions(-)
diff --git a/umtool/app/api/report/post-cards/route.ts b/umtool/app/api/report/post-cards/route.ts
@@ -0,0 +1,124 @@
+import { askEditor, EditorError, readDraftJob } from "@/lib/articles/generation";
+import { channelsDirFor } from "@/lib/projects/report.mjs";
+import { PostsRefused, StaleToken, manifestToken, updatePosts } from "@/lib/report/manifest.mjs";
+import { postChannels, postWarnings, searchPostArchive } from "@/lib/report/postCards.mjs";
+import { addPostFromArchive, findPostId, findPostRow } from "@/lib/report/postsCli.mjs";
+import { citedChannels } from "@/lib/report/sourceBacklog.mjs";
+import { withEditNotes } from "@/lib/report/guard";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+
+export const dynamic = "force-dynamic";
+
+// ADD POST, from Play the cut (UI notes item 13; lib/report/postCards.mjs,
+// postsCli.mjs addPostFromArchive). The chain it replaces -- `pnpm ops
+// capture-posts` → `umtool posts add` → `umtool look deck.posts` -- in one panel:
+//
+// GET ?project=<id> { channels, posts: [the cut's posts, each with its warnings], token }
+// GET ?project=<id>&channel=<slug>&q=<words> { hits: [{ id, date, text, warnings, captured, inCut, … }], total }
+// GET ?project=<id>&job=<jobId> a capture's job (the editor's)
+// POST { project, op: "capture", channel, ids } the editor's capture-posts (paced there, on the
+// platform's own queue) → { jobId }
+// POST { project, op: "add", channel, id, attach?, crop? } the card, through `posts add`'s write
+// POST { project, op: "crop", post, crop, token? } the post's own crop (shotMaxHeight; null: none)
+const headers = { "cache-control": "no-store" };
+const SLUG_RE = /^[A-Za-z0-9._-]+$/;
+const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
+
+/** The archive channel and native id a manifest post came from, when it says. */
+function sourceOf(p: Record<string, unknown>): { slug: string; id: string } | null {
+ const shot = typeof p.shot === "string" ? /^posts-media\/([^/]+)\/([^/]+)\//.exec(p.shot) : null;
+ const slug = typeof p.siteChannel === "string" ? p.siteChannel : shot?.[1];
+ const id = typeof p.postId === "string" ? p.postId : shot?.[2] ?? (typeof p.id === "string" ? p.id.replace(/^(x|bsky|post)-/, "") : null);
+ return slug && id && SLUG_RE.test(slug) && ID_RE.test(id) ? { slug, id } : null;
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await resolveReport(url.searchParams.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers });
+ const m = r.manifest as Record<string, unknown>;
+ const channelsDir = channelsDirFor(r.project.dir, m) as string | null;
+ if (!channelsDir) return Response.json({ error: "this project reads no corpus (no channels directory)" }, { status: 400, headers });
+ const job = url.searchParams.get("job");
+ try {
+ if (job) {
+ const j = await readDraftJob(job, 6);
+ return Response.json({ ...j, ended: ["done", "failed", "cancelled", "error"].includes(j.status) }, { headers });
+ }
+ const channel = url.searchParams.get("channel");
+ if (channel) {
+ if (!SLUG_RE.test(channel)) return Response.json({ error: "not a channel slug" }, { status: 400, headers });
+ return Response.json(await searchPostArchive(channelsDir, channel, url.searchParams.get("q") ?? "", { manifest: m }), { headers });
+ }
+ const cited = (citedChannels(m) as { slug: string }[]).map((c) => c.slug);
+ const posts = await Promise.all(
+ ((Array.isArray(m.posts) ? m.posts : []) as Record<string, unknown>[]).map(async (p) => {
+ const src = sourceOf(p);
+ const row = src ? (await findPostRow(channelsDir, src.slug, src.id).catch(() => null))?.row ?? null : null;
+ return {
+ id: String(p.id ?? ""),
+ date: typeof p.date === "string" ? p.date : null,
+ text: typeof p.text === "string" ? p.text : "",
+ attachTo: typeof p.attachTo === "string" ? p.attachTo : null,
+ shot: typeof p.shot === "string" ? p.shot : null,
+ shotMaxHeight: Number.isInteger(p.shotMaxHeight) ? (p.shotMaxHeight as number) : null,
+ hide: p.hide === true,
+ source: src,
+ warnings: postWarnings(row),
+ };
+ }),
+ );
+ return Response.json({ channels: await postChannels(channelsDir, m, cited), posts, token: await manifestToken(r.project.dir) }, { headers });
+ } catch (e) {
+ const status = e instanceof EditorError ? e.status : 400;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+ }
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/post-cards");
+ if (refused) return refused;
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers });
+ try {
+ if (body.op === "capture") {
+ const slug = String(body.channel ?? "");
+ const ids = Array.isArray(body.ids) ? body.ids.map(String).filter((x) => ID_RE.test(x)) : [];
+ if (!SLUG_RE.test(slug) || !ids.length) return Response.json({ error: "a capture names a channel and its post ids" }, { status: 400, headers });
+ // The editor's own capture: paced there (a pause before every contact
+ // after the first), on the platform's download queue, refused for an id
+ // not in the channel's archive.
+ const answer = await askEditor<{ jobId?: string }>("/api/ops/capture-posts", { method: "POST", body: { slug, ids } });
+ return Response.json({ ok: true, jobId: answer.jobId ?? null }, { headers });
+ }
+ if (body.op === "add") {
+ const crop = body.crop === undefined || body.crop === null || body.crop === "" ? null : Number(body.crop);
+ if (crop !== null && !Number.isInteger(crop)) return Response.json({ error: "crop is a whole number of pixels" }, { status: 400, headers });
+ const out = await addPostFromArchive(r.project, {
+ slug: String(body.channel ?? ""),
+ postId: String(body.id ?? ""),
+ attach: typeof body.attach === "string" && body.attach ? body.attach : null,
+ crop,
+ });
+ return Response.json({ ok: true, post: out.result.post, created: out.result.created, warnings: out.warnings, copied: out.copied, editNotes: out.editNotes, token: await manifestToken(r.project.dir) }, { headers });
+ }
+ if (body.op === "crop") {
+ const found = findPostId(r.manifest, String(body.post ?? ""));
+ const id = found === null ? null : String(found);
+ if (!id) return Response.json({ error: `no post ${String(body.post ?? "")} in the cut` }, { status: 404, headers });
+ const crop = body.crop === undefined || body.crop === null || body.crop === "" ? null : Number(body.crop);
+ const token = typeof body.token === "string" ? body.token : await manifestToken(r.project.dir);
+ const { result, editNotes } = await withEditNotes(r.project, () => updatePosts(r.project.dir, { [id]: { shotMaxHeight: crop } }, { token }));
+ return Response.json({ ok: true, id, post: (result as { posts: Record<string, unknown> }).posts[id], token: (result as { token: string }).token, editNotes }, { headers });
+ }
+ return Response.json({ error: 'op is "capture", "add" or "crop"' }, { status: 400, headers });
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers });
+ if (e instanceof PostsRefused) return Response.json({ error: e.message, errors: (e as PostsRefused & { errors: string[] }).errors }, { status: 400, headers });
+ const status = e instanceof EditorError ? e.status : 400;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+ }
+}
diff --git a/umtool/components/projects/review/AddPost.tsx b/umtool/components/projects/review/AddPost.tsx
@@ -0,0 +1,288 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+// ---------------------------------------------------------------------------
+// ADD POST in Play the cut (UI notes item 13): the chain `pnpm ops
+// capture-posts` → `umtool posts add` → `umtool look deck.posts` in one
+// panel (/api/report/post-cards). Search a channel's posts archive; Capture
+// one through the EDITOR's capture-posts (paced there); Add it to the clip on
+// screen (`posts add`'s own write) and see its card on that clip as the cut
+// plays. Each post's WARNING comes from its own data -- a quoted post, a
+// repost, media -- since its screenshot shows them; the cure is a CROP (the
+// post's own shotMaxHeight: its top that tall, never panned).
+// ---------------------------------------------------------------------------
+
+type Hit = {
+ id: string;
+ date: string | null;
+ author: string | null;
+ text: string;
+ url: string | null;
+ warnings: string[];
+ captured: boolean;
+ inCut: boolean;
+};
+type CutPost = { id: string; date: string | null; text: string; attachTo: string | null; shotMaxHeight: number | null; hide: boolean; warnings: string[] };
+type Base = { channels: { slug: string; suggested: boolean }[]; posts: CutPost[]; token: string | null };
+
+async function postJson(body: Record<string, unknown>) {
+ const r = await fetch("/api/report/post-cards", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown>;
+ return { ok: r.ok, status: r.status, json: j };
+}
+
+export default function AddPost({
+ project,
+ clip,
+ onAdded,
+}: {
+ project: string;
+ /** The clip on screen: what Add attaches the post to (null: a card is on screen). */
+ clip: string | null;
+ /** A post was added or cropped: the view is read again, the deck recomposed, the card shown on its clip. */
+ onAdded: (post: { id: string; attachTo: string | null }) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [base, setBase] = useState<Base | null>(null);
+ const [channel, setChannel] = useState("");
+ const [q, setQ] = useState("");
+ const [hits, setHits] = useState<Hit[] | null>(null);
+ const [total, setTotal] = useState(0);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [said, setSaid] = useState<string | null>(null);
+ const [crop, setCrop] = useState<Record<string, string>>({});
+ const [capturing, setCapturing] = useState<{ jobId: string; id: string; line: string } | null>(null);
+
+ const loadBase = useCallback(async () => {
+ const r = await fetch(`/api/report/post-cards?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null);
+ const j = r ? ((await r.json().catch(() => null)) as (Base & { error?: string }) | null) : null;
+ if (!r?.ok || !j) {
+ setError(j?.error ?? "the posts could not be read");
+ return;
+ }
+ setBase(j);
+ setChannel((c) => c || j.channels[0]?.slug || "");
+ }, [project]);
+ useEffect(() => {
+ if (open && !base) void loadBase();
+ }, [open, base, loadBase]);
+
+ const search = useCallback(async () => {
+ if (!channel) return;
+ setBusy("search");
+ setError(null);
+ try {
+ const r = await fetch(`/api/report/post-cards?project=${encodeURIComponent(project)}&channel=${encodeURIComponent(channel)}&q=${encodeURIComponent(q)}`, { cache: "no-store" });
+ const j = (await r.json().catch(() => ({}))) as { hits?: Hit[]; total?: number; archive?: boolean; error?: string };
+ if (!r.ok) setError(j.error ?? `HTTP ${r.status}`);
+ else if (j.archive === false) setError(`${channel} has no posts archive`);
+ setHits(j.hits ?? []);
+ setTotal(j.total ?? 0);
+ } finally {
+ setBusy(null);
+ }
+ }, [channel, project, q]);
+
+ // A capture in flight: the editor's job, followed until it ends; then the search again (its shot is there).
+ useEffect(() => {
+ if (!capturing) return;
+ const t = setInterval(async () => {
+ const r = await fetch(`/api/report/post-cards?project=${encodeURIComponent(project)}&job=${encodeURIComponent(capturing.jobId)}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as { status: string; ended: boolean; tail: string[] };
+ setCapturing((c) => (c ? { ...c, line: `${j.status}${j.tail.length ? ` — ${j.tail[j.tail.length - 1]}` : ""}` } : c));
+ if (j.ended) {
+ setSaid(`capture of ${capturing.id}: ${j.status}${j.tail.length ? ` — ${j.tail[j.tail.length - 1]}` : ""}`);
+ setCapturing(null);
+ await search();
+ }
+ }, 1000);
+ return () => clearInterval(t);
+ }, [capturing, project, search]);
+
+ const capture = async (id: string) => {
+ setBusy(id);
+ setError(null);
+ try {
+ const r = await postJson({ project, op: "capture", channel, ids: [id] });
+ if (!r.ok || !r.json.jobId) setError(String(r.json.error ?? `HTTP ${r.status}`));
+ else setCapturing({ jobId: String(r.json.jobId), id, line: "queued" });
+ } finally {
+ setBusy(null);
+ }
+ };
+ const add = async (h: Hit) => {
+ setBusy(h.id);
+ setError(null);
+ setSaid(null);
+ try {
+ const c = crop[h.id]?.trim();
+ const r = await postJson({ project, op: "add", channel, id: h.id, ...(clip ? { attach: clip } : {}), ...(c ? { crop: Number(c) } : {}) });
+ if (!r.ok) {
+ setError(String(r.json.error ?? `HTTP ${r.status}`));
+ return;
+ }
+ const post = r.json.post as { id: string; attachTo?: string };
+ setSaid(`${r.json.created ? "added" : "replaced"} ${post.id}${post.attachTo ? ` on ${post.attachTo}` : ""} — its card plays at the clip's end`);
+ await loadBase();
+ await search();
+ onAdded({ id: post.id, attachTo: post.attachTo ?? null });
+ } finally {
+ setBusy(null);
+ }
+ };
+ const saveCrop = async (p: CutPost) => {
+ setBusy(p.id);
+ setError(null);
+ try {
+ const v = (crop[`cut:${p.id}`] ?? (p.shotMaxHeight ? String(p.shotMaxHeight) : "")).trim();
+ const r = await postJson({ project, op: "crop", post: p.id, crop: v ? Number(v) : null, token: base?.token ?? null });
+ if (!r.ok) {
+ setError(String(r.json.error ?? `HTTP ${r.status}`));
+ return;
+ }
+ setSaid(v ? `${p.id} cropped to its top ${v} px` : `${p.id} uncropped`);
+ await loadBase();
+ onAdded({ id: p.id, attachTo: p.attachTo });
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ return (
+ <div data-play-add-post="" className="text-[12px]">
+ <button type="button" data-play-add-post-open="" onClick={() => setOpen((v) => !v)} className={buttonVariants({ variant: open ? "outline" : "quiet", size: "sm" })} title="a post card from the channel's posts archive, on the clip on screen">
+ {open ? "Close Add post" : "Add post"}
+ </button>
+ {open && (
+ <div data-testid="add-post" className="mt-1.5 space-y-1.5 rounded border border-seam bg-panel px-3 py-2">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <select data-add-post-channel="" aria-label="posts channel" value={channel} onChange={(e) => setChannel(e.target.value)} className="rounded border border-seam-2 bg-ground px-1 py-0.5 text-[11.5px] text-text">
+ {!base?.channels.length && <option value="">no posts archive</option>}
+ {base?.channels.map((c) => (
+ <option key={c.slug} value={c.slug}>
+ {c.slug}
+ </option>
+ ))}
+ </select>
+ <input
+ data-add-post-q=""
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") void search();
+ }}
+ placeholder="words in the post (empty: the newest)"
+ className="min-w-48 flex-1 rounded border border-seam-2 bg-ground px-1.5 py-0.5 text-[11.5px] text-text"
+ />
+ <button type="button" data-add-post-search="" disabled={!channel || busy !== null} onClick={() => void search()} className={buttonVariants({ size: "sm" })}>
+ Search
+ </button>
+ <span className="text-[11px] text-muted">{clip ? `adds to ${clip}, the clip on screen` : "a card is on screen: the post rides on the clip its date picks"}</span>
+ </div>
+ {error && (
+ <p role="alert" data-add-post-error="" className="m-0 text-[11.5px] text-reject-text">
+ {error}
+ </p>
+ )}
+ {said && <p data-add-post-said="" className="m-0 text-[11.5px] text-text-2">{said}</p>}
+ {capturing && <p data-add-post-capturing={capturing.id} className="m-0 text-[11.5px] text-muted">capturing {capturing.id} through the editor (paced): {capturing.line}</p>}
+ {hits && (
+ <>
+ <p className="m-0 text-[11px] text-muted">
+ {total} post{total === 1 ? "" : "s"} in {channel}
+ {total > hits.length ? `, the newest ${hits.length} shown` : ""}
+ </p>
+ <ul className="m-0 max-h-80 list-none space-y-1 overflow-y-auto p-0">
+ {hits.map((h) => (
+ <li key={h.id} data-add-post-hit={h.id} data-add-post-captured={h.captured ? "1" : "0"} className="rounded border border-seam px-2 py-1">
+ <div className="flex flex-wrap items-baseline gap-1.5">
+ <span className="font-mono text-[11px] text-muted">{h.date?.slice(0, 10)}</span>
+ {h.author && <span className="text-text-2">@{h.author.replace(/^@/, "")}</span>}
+ {h.inCut && <span className={badgeVariants({ variant: "on", size: "sm" })}>in the cut</span>}
+ <span className={badgeVariants({ variant: h.captured ? "info" : "state", size: "sm" })}>{h.captured ? "captured" : "no screenshot yet"}</span>
+ {h.url && (
+ <a href={h.url} target="_blank" rel="noreferrer" className="ink-link text-[11px]">
+ the post ↗
+ </a>
+ )}
+ </div>
+ <p className="m-0 mt-0.5 line-clamp-3 text-[12px] leading-snug text-text">{h.text}</p>
+ {h.warnings.map((w, i) => (
+ <p key={i} role="note" data-add-post-warning={h.id} className="m-0 mt-0.5 text-[11.5px] text-reject-text">
+ ⚠ {w}
+ </p>
+ ))}
+ <div className="mt-1 flex flex-wrap items-center gap-1.5">
+ {!h.captured ? (
+ <button type="button" data-add-post-capture={h.id} disabled={busy !== null || !!capturing} onClick={() => void capture(h.id)} className={buttonVariants({ variant: "outline", size: "sm" })} title="the editor's capture-posts: a screenshot of the post, paced">
+ Capture
+ </button>
+ ) : (
+ <>
+ <label className="flex items-center gap-1 text-[11px] text-muted">
+ crop
+ <input
+ data-add-post-crop={h.id}
+ inputMode="numeric"
+ value={crop[h.id] ?? ""}
+ onChange={(e) => setCrop((c) => ({ ...c, [h.id]: e.target.value }))}
+ placeholder={h.warnings.length ? "px — keep its top" : "px"}
+ className="w-20 rounded border border-seam-2 bg-ground px-1 py-0.5 font-mono text-[11px] text-text"
+ />
+ </label>
+ <button type="button" data-add-post-add={h.id} disabled={busy !== null} onClick={() => void add(h)} className={buttonVariants({ variant: "go", size: "sm" })}>
+ {h.inCut ? "Replace in the cut" : clip ? `Add to ${clip}` : "Add"}
+ </button>
+ </>
+ )}
+ </div>
+ </li>
+ ))}
+ </ul>
+ </>
+ )}
+ {base && base.posts.length > 0 && (
+ <div data-add-post-cut="" className="space-y-1 border-t border-seam pt-1.5">
+ <p className="micro m-0">posts in the cut — {base.posts.length}</p>
+ <ul className="m-0 list-none space-y-1 p-0">
+ {base.posts.map((p) => (
+ <li key={p.id} data-add-post-in-cut={p.id} className={cn("flex flex-wrap items-baseline gap-1.5", p.hide && "opacity-60")}>
+ <span className="font-mono text-[11px] text-text">{p.id}</span>
+ <span className="text-[11px] text-muted">{p.attachTo ? `on ${p.attachTo}` : "on the clip its date picks"}</span>
+ <span className="min-w-0 max-w-[24rem] truncate text-[11.5px] text-text-2">{p.text}</span>
+ <label className="flex items-center gap-1 text-[11px] text-muted">
+ crop
+ <input
+ data-add-post-cut-crop={p.id}
+ inputMode="numeric"
+ value={crop[`cut:${p.id}`] ?? (p.shotMaxHeight ? String(p.shotMaxHeight) : "")}
+ onChange={(e) => setCrop((c) => ({ ...c, [`cut:${p.id}`]: e.target.value }))}
+ placeholder="px"
+ className="w-20 rounded border border-seam-2 bg-ground px-1 py-0.5 font-mono text-[11px] text-text"
+ />
+ </label>
+ <button type="button" data-add-post-cut-crop-save={p.id} disabled={busy !== null} onClick={() => void saveCrop(p)} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Save crop
+ </button>
+ {p.warnings.map((w, i) => (
+ <span key={i} role="note" data-add-post-cut-warning={p.id} className="basis-full pl-4 text-[11px] text-reject-text">
+ ⚠ {w}
+ {p.shotMaxHeight ? ` (cropped to ${p.shotMaxHeight} px)` : ""}
+ </span>
+ ))}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -26,6 +26,7 @@ import RejectClip from "./RejectClip";
import WhatPlays, { type WorkingCut } from "./WhatPlays";
import { useCutApp } from "../cutApp/CutApp";
import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport";
+import AddPost from "./AddPost";
// ---------------------------------------------------------------------------
// THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The
@@ -1060,6 +1061,20 @@ export default function PlayCut({
/>
<ClipExportStatus exp={clipExport} />
</div>
+ {/* Add post (UI notes item 13): a card from the channel's posts archive, captured through the editor, on the clip on screen. */}
+ {editable && (
+ <AddPost
+ project={project}
+ clip={item?.clip ? item.id : null}
+ onAdded={(p) => {
+ setPlaying(false);
+ // Its card plays at the end of the clip it rides on: the playhead goes there, the deck recomposed.
+ const it = planRef.current.items.find((x) => x.id === (p.attachTo ?? item?.id));
+ void reloadView();
+ if (it) seekTo(Math.max(it.from, it.to - 1));
+ }}
+ />
+ )}
{/* Reject ▾ (x): the clip on screen out of the cut for a reason, on record, with an undo (the project's cut: not on a take). */}
{editable && (
<RejectClip
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -74,8 +74,8 @@ Inbox cannot disagree about what is wrong with one.
| `timeline <project> --take <take> [ls \| move <id> --to <index> \| remove <id> \| undo]` | a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it |
| `timeline <project> sections [--json]` · `section-move <id>… --to-section N [--start]` · `section-add --after <id> [--label L] [--color C]` · `section-boundary <marker> --after <id>` · `section-remove <marker>` · `section-set <marker> [--label L] [--color C]` · `split <id> <second>` · `flash-forward <id> <from>-<to> (--after <id\|-> \| --to-section N [--start]) [--move] [--quote Q] [--id ID]` | **sections as sections** (the deck's markers; the Cut tab's section bars and row menus): clips moved to a section with every marker following, a section opened, a boundary moved, relabelled, removed — no section emptied, no boundary crossed (**exit 1**) — and every take patch in step synced; **split** (each half's quote from the words, the second half's cite and QR at its second, a marker after the clip following its second half); **flash-forward** a tight copy of a span elsewhere with the clip's attribution and locks, as `repeatOf` the clip (`--move`: out of the clip) ([knobs.md](knobs.md#sections-split-and-flash-forward-editing-the-cut)) |
| `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) |
-| `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key. Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** |
-| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run) |
+| `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** |
+| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) |
| `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) |
| `preset list [--json]` · `preset show <name> [--json]` · `preset save <name> --from <project> [--description D] [--force]` · `preset apply <name\|none> <project>` | the **look presets** (`umtool/presets/<name>.json`, or `UMTOOL_PRESETS_DIR`): a render block a manifest stands on (`"preset": "<name>"`), laid under it — preset → manifest → style → take patch. `save` keeps a project's look and leaves its content out; `apply` names the preset on the cut through `updatePreset` (nothing copied in), refused when the cut over it would not build ([knobs.md](knobs.md#look-presets)) |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -234,6 +234,7 @@ that mentions the seizure in question and one before it. The Marks box is on eve
| `render.chrome.deck.markerLayout` — `stagger` or `truncate` when labels crowd (default: stagger only when a label would truncate) | markers, **layout** | `deck.markerLayout=truncate` | `PUT /api/report/chrome {project, token, markerLayout}` |
| `render.chrome.deck.claims[]` — his explicit claims drawn against the record on the rail, at most 6: a `count` or a `goalpost` ([below](#claim-checks-on-the-rail)) | On-screen, **claim checks**: add a count / a goalpost, the clip picker, **use the playhead**, his words, the window's dates, the record's verdict, per, the claim; a goalpost's steps (**add a step**), each its from date and due durations; remove — the build's validator under each as it is typed | `umtool look <p> deck.claims='[…]'` (`deck.claims=` none) | `PUT /api/report/chrome {project, token, claims}` |
| `posts[].thread` — `true`: a reply drawn with the post it answers above it — the capture's `shot-thread.png` beside the post's `shot` (taken by `pnpm ops capture-posts --json '{"slug":…,"ids":[…],"thread":true}'`, the replied-to author's avatar, name and handle blurred unless gold- or grey-checked or the reply's own; `"threadRedact": false` takes it unblurred), the post's own shot while there is none; needs a `shot`. In the feed a thread shot is drawn whole: the card under it leaves rather than the reply being squeezed, and one taller than the column is scaled to fit, never cut; the popup posts pan through it as through any tall shot | Media, On-screen **Posts** table: **thread** (shown once a thread shot is on disk) | `umtool posts set <p> <post> thread=on` (`thread=off` clears it) · on add: `umtool posts add <p> <channel>/<postId> --thread` | `PUT /api/report/posts {project, token, posts: {<id>: {thread}}}` |
+| `posts[].shotMaxHeight` — the post's OWN **crop** of its screenshot, 120–1080 px: its top that tall, the rest cut off and **never panned to** (the deck-wide `deck.posts.shotMaxHeight` caps the viewport and a taller shot pans through it; this one does not) — what keeps a quoted post or a media thumbnail under the post's words off the screen; needs a `shot` | Play the cut, **Add post**: a hit's **crop** before Add, or a post in the cut's **crop** + **Save crop** (empty: none) | `umtool posts set <p> <post> crop=420` (`crop=off` clears it) · on add: `umtool posts add <p> <channel>/<postId> --crop 420` | `POST /api/report/post-cards {project, op: "crop", post, crop}` · `PUT /api/report/posts {…, posts: {<id>: {shotMaxHeight}}}` |
| `render.blur` — `off`: every clip's picture as recorded, no caption (the uncensored variant); `on` (the default) blurs the clips that ask | Build, **Look**: **Blurred clips** | `umtool look <p> blur=off` · a take: `umtool take <p> --id uncensored --set render.blur=off` | `PUT /api/report/render {project, token, patch: {blur}}` |
| `render.intro` — the brand sting the cut opens with: a style (`boot` `boot-wipe` `boot-dark` `boot-cascade` `boot-mark`) or `{style, ground?, mark?, sound?, seconds?, site?, swap?, url?, urlPlace?}`; absent is none ([report-video.md](report-video.md#the-brand-intro-renderintro)) | Build, **Look**: **Intro** | `umtool look <p> intro=boot-dark` (`intro=` none) · a take: `umtool take <p> --id intro-wipe --set render.intro=boot-wipe` | `PUT /api/report/render {project, token, patch: {intro}}` |
| `render.intro.site` — on the chime, "Archi" becomes the cited site's name ("Jera"), "lyzer" stays, the colours go to its accent: `auto` (the site whose `siteUrl` is `provenance.siteOrigin`; none found, no swap), a site id, `{name, lead?, accent?, url?}`, or `none`/absent (the plain intro, byte for byte). `render.intro.swap` `swipe-down` (default) \| `roll` \| `wipe`; `render.intro.url` `both` (default: the site's, then archilyzer.pages.dev) \| `site` \| `project` \| `false`; `render.intro.urlPlace` `under` (default: one row under MEDIA) \| `replace` (MEDIA's place) | — (manifest or a take) | a take: `umtool take <p> --id intro-jera --set render.intro.style=boot-dark --set render.intro.mark=chime --set render.intro.site=auto` (`--set render.intro.swap=roll`, `--set render.intro.url=false`, `--set render.intro.urlPlace=replace`) · standalone: `node umtool/report-to-video/intro.mjs render --style boot-dark --mark chime --site auto --site-origin https://jeralyzer.pages.dev --swap wipe --out x.mp4` | `PUT /api/report/render {project, token, patch: {intro: {…, site}}}` |
@@ -559,6 +560,19 @@ it replies on the note as the agent; with no route the button says why, and the
Then the cut: the Build tab's **final** preset (a full build, about an hour for a 36-clip cut), and Deliver's
**Make variants**.
+## Add post (a post card from Play the cut)
+
+The chain `pnpm ops capture-posts` → `umtool posts add` → `umtool look deck.posts` in one panel: Play the cut's **Add
+post** (`components/projects/review/AddPost.tsx`, `/api/report/post-cards`, `lib/report/postCards.mjs`).
+
+| | In umtool | From a terminal | Route |
+|---|---|---|---|
+| the archive | **Add post** → a posts channel (those the cut's posts come from first, then those named like a cited channel, `<channel>-x`) and words: every word in the post's text or handle, any case, newest first (40 shown); empty, the newest | — (the archive is `channels/<slug>/posts/*.jsonl`) | `GET /api/report/post-cards?project&channel&q` |
+| the WARNING | each hit, and each post in the cut: **⚠** when the post's OWN data says its screenshot shows more than its words — it quotes a post (`quoted`), it is a repost (`repostOf`), it carries media (`mediaCount`, a forum's `media`): somebody else's words or video, or a thumbnail. Decided from the record, never from the picture | `umtool posts add` prints `WARNING: …` (`--json`: `warnings`) | the hits' `warnings` |
+| capture | a hit with no screenshot: **Capture** — the EDITOR's capture-posts (paced there: a pause before every contact after the first; the platform's own queue; an id not in the channel's archive refused), followed until it ends, then the search again | `pnpm ops capture-posts --json '{"slug":…,"ids":[…]}'` | `POST {op: "capture", channel, ids}` → `{jobId}` · `GET ?job=` |
+| add | a captured hit: **crop** (optional, px) and **Add to <clip>** — the clip on screen (a card on screen: the clip its date picks) — through `posts add`'s own write (`addPostFromArchive`: the capture copied into `posts-media/<slug>/<postId>/`, `upsertPost`, an undo point); the playhead goes to the clip's end and the deck is composed again, so the card shows on its clip | `umtool posts add <p> <slug>/<postId> --attach <clip> [--crop <px>]` | `POST {op: "add", channel, id, attach?, crop?}` |
+| crop a post in the cut | **posts in the cut**: **crop** + **Save crop** (`posts[].shotMaxHeight`, above) | `umtool posts set <p> <post> crop=<px>\|off` | `POST {op: "crop", post, crop}` |
+
## The source backlog (Sources · Prioritize · Re-sweep when complete)
The Overview tab's **sources** line (`components/projects/report/SourceBacklog.tsx`, `lib/report/sourceBacklog.*`): for each
diff --git a/umtool/e2e/add-post.spec.ts b/umtool/e2e/add-post.spec.ts
@@ -0,0 +1,133 @@
+import { test, expect, type Page } from "@playwright/test";
+import { copyFileSync, existsSync, readFileSync, rmSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+import { POST_IDS } from "./fixtures/intake-fixture.mjs";
+
+// ---------------------------------------------------------------------------
+// Add post in Play the cut (UI notes item 13; lib/report/postCards.mjs,
+// postsCli.mjs addPostFromArchive, /api/report/post-cards):
+//
+// add-post-fixture play-cut-fixture's cut, no posts; the corpus's testchan-x
+// posts archive: a plain post (captured), one QUOTING
+// another account (not captured) and one with a picture
+// (captured). WRITES its manifest, posts-media/ and the
+// corpus's testchan-x/posts-media/<quoting>/ (the stub's
+// capture); every test starts from the fixture's.
+//
+// The archive searched from Play; each post's warning from its own data;
+// Capture through the editor's capture-posts (the stub's job); Add to the clip
+// on screen with a crop -- the card on that clip in the live preview, its shot
+// cropped (data-crop, never panned) -- and the crop changed on a post in the cut.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, ".e2e-song");
+const DIR = path.join(FIXTURE, "reports", "add-post-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const PROJECT = "reports/add-post-fixture";
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+const QUOTING_SHOT = path.join(FIXTURE, "channels", "testchan-x", "posts-media", POST_IDS.quoting);
+const SHOTS = process.env.U4_SHOTS ?? null;
+
+type Post = { id: string; attachTo?: string; shot?: string; shotMaxHeight?: number };
+const posts = () => ((JSON.parse(readFileSync(MANIFEST, "utf8")) as { posts?: Post[] }).posts ?? []);
+const stubLog = () => {
+ try {
+ return JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route: string; slug?: string; ids?: string[] }[];
+ } catch {
+ return [];
+ }
+};
+
+test.beforeAll(() => {
+ if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
+});
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+ copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
+ rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
+ rmSync(path.join(DIR, "posts-media"), { recursive: true, force: true });
+ rmSync(QUOTING_SHOT, { recursive: true, force: true });
+});
+
+const root = (page: Page) => page.locator("[data-play-cut]");
+async function open(page: Page) {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.playHref(PROJECT));
+ await expect(root(page)).toHaveAttribute("data-play-state", "paused");
+ await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 });
+ await page.locator("[data-play-add-post-open]").click();
+ await expect(page.getByTestId("add-post")).toBeVisible();
+ await expect(page.locator("[data-add-post-channel]")).toHaveValue("testchan-x");
+}
+async function search(page: Page, q: string) {
+ await page.locator("[data-add-post-q]").fill(q);
+ await page.locator("[data-add-post-search]").click();
+ await expect(page.locator("[data-add-post-hit]").first()).toBeVisible();
+}
+const hit = (page: Page, id: string) => page.locator(`[data-add-post-hit='${id}']`);
+
+test("the archive searched from Play; each post's warning from its own data: a quoted post, a picture, none", async ({ page }) => {
+ await open(page);
+ await search(page, "voice");
+ await expect(page.locator("[data-add-post-hit]")).toHaveCount(3);
+ await expect(hit(page, POST_IDS.quoting).locator("[data-add-post-warning]")).toContainText("quotes a post by @someoneelse");
+ await expect(hit(page, POST_IDS.media).locator("[data-add-post-warning]")).toContainText("a picture or video");
+ await expect(hit(page, POST_IDS.plain).locator("[data-add-post-warning]")).toHaveCount(0);
+ await expect(hit(page, POST_IDS.quoting)).toHaveAttribute("data-add-post-captured", "0");
+ await expect(hit(page, POST_IDS.plain)).toHaveAttribute("data-add-post-captured", "1");
+ await search(page, "pictured");
+ await expect(page.locator("[data-add-post-hit]")).toHaveCount(1);
+});
+
+test("Capture through the editor, Add to the clip on screen with a crop: the card on that clip in the preview, cropped", async ({ page }) => {
+ await open(page);
+ await search(page, "voice");
+ const before = stubLog().length;
+ await page.locator(`[data-add-post-capture='${POST_IDS.quoting}']`).click();
+ await expect(page.locator("[data-add-post-said]")).toContainText(`capture of ${POST_IDS.quoting}: done`, { timeout: 20_000 });
+ const asked = stubLog().slice(before).filter((r) => r.route === "capture-posts");
+ expect(asked).toEqual([expect.objectContaining({ slug: "testchan-x", ids: [POST_IDS.quoting] })]);
+ await expect(hit(page, POST_IDS.quoting)).toHaveAttribute("data-add-post-captured", "1");
+ // The clip on screen is c01: the post goes on it, cropped to its own words.
+ await expect(page.locator(`[data-add-post-add='${POST_IDS.quoting}']`)).toHaveText("Add to c01");
+ await page.locator(`[data-add-post-crop='${POST_IDS.quoting}']`).fill("300");
+ await page.locator(`[data-add-post-add='${POST_IDS.quoting}']`).click();
+ await expect(page.locator("[data-add-post-said]")).toContainText(`added x-${POST_IDS.quoting} on c01`);
+ await expect.poll(() => posts().map((p) => `${p.id}:${p.attachTo}:${p.shotMaxHeight}`)).toEqual([`x-${POST_IDS.quoting}:c01:300`]);
+ expect(existsSync(path.join(DIR, "posts-media", "testchan-x", POST_IDS.quoting, "shot.png"))).toBe(true);
+ // The card on c01, in the live preview: its shot cropped (data-crop), never panned.
+ const preview = page.locator("[data-testid=onscreen-posts-preview][data-segment='c01']");
+ await expect(preview).toHaveAttribute("data-posts-ready", "1", { timeout: 60_000 });
+ const frame = page.frameLocator("[data-testid=onscreen-posts-preview-iframe]");
+ await expect(frame.locator(".shot-view[data-crop='300']")).toHaveCount(1);
+ // In the cut, the post still says what its screenshot carries.
+ await expect(page.locator(`[data-add-post-cut-warning='x-${POST_IDS.quoting}']`)).toContainText("cropped to 300 px");
+ if (SHOTS) {
+ await page.waitForTimeout(800);
+ await page.screenshot({ path: path.join(SHOTS, "13-add-post-card-on-clip.png") });
+ }
+});
+
+test("a post in the cut: Save crop changes its own shotMaxHeight; empty takes the crop off", async ({ page }) => {
+ await open(page);
+ await search(page, "pictured");
+ await page.locator(`[data-add-post-add='${POST_IDS.media}']`).click();
+ await expect.poll(() => posts().map((p) => p.id)).toEqual([`x-${POST_IDS.media}`]);
+ const crop = page.locator(`[data-add-post-cut-crop='x-${POST_IDS.media}']`);
+ await crop.fill("420");
+ await page.locator(`[data-add-post-cut-crop-save='x-${POST_IDS.media}']`).click();
+ await expect.poll(() => posts()[0].shotMaxHeight).toBe(420);
+ if (SHOTS) {
+ await page.getByTestId("add-post").screenshot({ path: path.join(SHOTS, "13-add-post-panel-warnings.png") });
+ }
+ await crop.fill("");
+ await page.locator(`[data-add-post-cut-crop-save='x-${POST_IDS.media}']`).click();
+ await expect.poll(() => "shotMaxHeight" in posts()[0]).toBe(false);
+ // A crop out of range is refused in the build's words.
+ await crop.fill("50");
+ await page.locator(`[data-add-post-cut-crop-save='x-${POST_IDS.media}']`).click();
+ await expect(page.locator("[data-add-post-error]")).toContainText("from 120 to 1080");
+});
diff --git a/umtool/e2e/fixtures/editor-stub-intake.mjs b/umtool/e2e/fixtures/editor-stub-intake.mjs
@@ -1,13 +1,19 @@
-// The editor's doors the intake specs knock on (UI notes 2026-10-30, item 16),
-// stubbed beside editor-stub.mjs:
+// The editor's doors the intake specs knock on (UI notes 2026-10-30, items 13
+// and 16), stubbed beside editor-stub.mjs:
//
// GET /api/ops/channel/<slug> a channel's snapshot counts (testchan: a backlog,
// 1,454/2,798 transcribed; backlog-done: nothing left;
// any other: 404 "Channel … not found")
// GET /api/ops/settings?key=channelPriority { value: { focus, channels } }
// POST /api/ops/channel-priority {focus} the focus replaced, recorded
+// POST /api/ops/capture-posts {slug, ids} job cp-<n>: running at once, done after ~1 s, when it
+// has written posts-media/<id>/shot.png + capture.json
+// GET /api/ops/job/cp-<n> that job
// POST /__stub/channel-counts {slug, totals?, undownloaded?, untranscribed?} (no token) a spec's
// counts for a channel; {} resets
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { postShotPng } from "./intake-fixture.mjs";
const DEFAULT_COUNTS = () => ({
testchan: { totals: { videos: 2751, transcribed: 1454, downloaded: 2700 }, undownloaded: 47, untranscribed: 1297 },
@@ -15,6 +21,8 @@ const DEFAULT_COUNTS = () => ({
});
let counts = DEFAULT_COUNTS();
const priority = { focus: { kind: "none" }, channels: {} };
+const jobs = new Map();
+let nextJob = 1;
/** The control door (before the token check). Answers true when it handled the request. */
export function intakeControl(req, res, url, { json, readBody }) {
@@ -32,7 +40,7 @@ export function intakeControl(req, res, url, { json, readBody }) {
}
/** The token-gated doors. Answers true when it handled the request. */
-export function intakeRoute(req, res, url, { json, readBody, push }) {
+export function intakeRoute(req, res, url, { json, readBody, push, channels }) {
const ch = /^\/api\/ops\/channel\/([^/]+)$/.exec(url.pathname);
if (req.method === "GET" && ch) {
req.resume();
@@ -67,5 +75,36 @@ export function intakeRoute(req, res, url, { json, readBody, push }) {
});
return true;
}
+ if (req.method === "POST" && url.pathname === "/api/ops/capture-posts") {
+ readBody(req, (body) => {
+ push({ route: "capture-posts", ...(body ?? {}) });
+ const slug = String(body?.slug ?? "");
+ const ids = Array.isArray(body?.ids) ? body.ids.map(String) : [];
+ if (!/^[A-Za-z0-9._-]+$/.test(slug) || !ids.length) return json(res, 400, { ok: false, error: '"slug" and "ids"' });
+ const id = `cp-${nextJob++}`;
+ const job = { id, kind: "capture-posts", status: "running", tail: [`capturing ${ids.length} post(s) of ${slug}`] };
+ jobs.set(id, job);
+ setTimeout(() => {
+ for (const pid of ids) {
+ const d = path.join(channels, slug, "posts-media", pid);
+ mkdirSync(d, { recursive: true });
+ writeFileSync(path.join(d, "shot.png"), postShotPng());
+ writeFileSync(path.join(d, "capture.json"), JSON.stringify({ version: 1, id: pid, url: `https://x.com/i/status/${pid}`, capturedAt: new Date().toISOString(), state: "captured", mediaState: "skipped", media: [] }) + "\n");
+ }
+ job.status = "done";
+ job.tail.push(`Done: ${ids.length} captured, 0 deleted, 0 unavailable, 0 failed.`);
+ }, 1000);
+ json(res, 200, { ok: true, jobId: id });
+ });
+ return true;
+ }
+ const jm = /^\/api\/ops\/job\/(cp-\d+)$/.exec(url.pathname);
+ if (req.method === "GET" && jm) {
+ req.resume();
+ const job = jobs.get(jm[1]);
+ if (!job) json(res, 404, { ok: false, error: "no such job" });
+ else json(res, 200, { ok: true, job: { id: job.id, kind: job.kind, status: job.status }, tail: job.tail });
+ return true;
+ }
return false;
}
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -1241,7 +1241,7 @@ const server = http.createServer((req, res) => {
return json(res, 401, { error: "missing bearer token" });
}
- // UI notes item 16: a channel's counts and the focus (editor-stub-intake.mjs).
+ // 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 37 S4: Import this capture (editor-stub-import-page.mjs).
if (importPageRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push(r), record()) })) return;
diff --git a/umtool/e2e/fixtures/intake-fixture.mjs b/umtool/e2e/fixtures/intake-fixture.mjs
@@ -11,10 +11,71 @@
// stub answers it with a backlog: 1,454/2,798 transcribed)
// and backlog-done (the stub's: nothing left), and a third
// the stub does not archive (source-backlog.spec.ts)
+// add-post-fixture play-cut-fixture's cut (play-cut-fixture.mjs) with no posts;
+// the social channel testchan-x beside it in the corpus:
+// posts/2026-10.jsonl -- 1910000000000000001 plain words,
+// captured; ...002 QUOTING another account, not captured
+// (the stub's capture-posts takes it); ...003 with a picture,
+// captured -- each captured shot a tall 500x900 png
+// (add-post.spec.ts)
//
// Synthetic, like every fixture.
import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
+import { deflateSync } from "node:zlib";
+import { makePlayCutFixture } from "./play-cut-fixture.mjs";
+
+const CRC = (() => {
+ const t = new Uint32Array(256);
+ for (let n = 0; n < 256; n += 1) {
+ let c = n;
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ t[n] = c >>> 0;
+ }
+ return t;
+})();
+const crc32 = (buf) => {
+ let c = 0xffffffff;
+ for (const b of buf) c = CRC[(c ^ b) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+};
+const chunk = (type, data) => {
+ const len = Buffer.alloc(4);
+ len.writeUInt32BE(data.length);
+ const td = Buffer.concat([Buffer.from(type, "ascii"), data]);
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(crc32(td));
+ return Buffer.concat([len, td, crc]);
+};
+/**
+ * A post's screenshot, drawn: a light card -- the post's own words as dark bars
+ * in its top 300 px -- and, below, a grey box standing for a quoted post or a
+ * media thumbnail (what a crop keeps off the screen).
+ */
+export function postShotPng(w = 500, h = 900) {
+ const raw = Buffer.alloc((w * 3 + 1) * h);
+ for (let y = 0; y < h; y += 1) {
+ const row = y * (w * 3 + 1);
+ raw[row] = 0;
+ for (let x = 0; x < w; x += 1) {
+ let v = 245;
+ if (y < 300 && y % 40 > 24 && x > 24 && x < w - 24 - (y % 80 > 40 ? 120 : 0)) v = 40; // the words
+ if (y >= 340 && y < h - 30 && x > 24 && x < w - 24) v = y % 60 < 4 || x < 30 || x > w - 30 ? 120 : 190; // the quoted box
+ const i = row + 1 + x * 3;
+ raw[i] = v;
+ raw[i + 1] = v;
+ raw[i + 2] = v + (y >= 340 ? 10 : 0) > 255 ? 255 : v + (y >= 340 ? 10 : 0);
+ }
+ }
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(w, 0);
+ ihdr.writeUInt32BE(h, 4);
+ ihdr[8] = 8;
+ ihdr[9] = 2;
+ return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
+}
+
+export const POST_IDS = { plain: "1910000000000000001", quoting: "1910000000000000002", media: "1910000000000000003" };
const json = (doc) => JSON.stringify(doc, null, 2) + "\n";
const write = (dir, name, text) => {
@@ -63,7 +124,7 @@ export const CANDIDATES_SWEEP = `# Re-sweep: newer transcripts against the cut
/**
* @param {{ reports: string, deckManifest: Function, cachedWindow: string }} o
*/
-export function makeIntakeFixture({ reports, deckManifest, cachedWindow }) {
+export function makeIntakeFixture({ reports, channels, deckManifest, cachedWindow }) {
const cands = path.join(reports, "candidates-fixture");
const m = deckManifest("candidates-fixture", "The Candidates Fixture", clips(["c01", "c02", "c03", "c04", "c05", "c06"]));
m.render.chrome.deck.markers = [
@@ -86,5 +147,27 @@ export function makeIntakeFixture({ reports, deckManifest, cachedWindow }) {
]);
write(backlog, "video.manifest.json", json(bm));
+ // ---- Add post (item 13) -----------------------------------------------------------
+ makePlayCutFixture({ reports, deckManifest, cachedWindow, name: "add-post-fixture", title: "The Add Post Fixture" });
+ const x = path.join(channels, "testchan-x");
+ const row = (id, date, text, extra = {}) =>
+ JSON.stringify({ id, slug: "testchan-x", channelSlug: "testchan-x", author: "teststreamer", authorName: "Test Streamer", createdAt: `${date}T15:00:00.000Z`, uploadDate: date.replace(/-/g, ""), text, url: `https://x.com/teststreamer/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [], ...extra });
+ write(x, "config.json", json({ name: "Test Streamer (X)", kind: "social", platform: "x" }));
+ write(
+ x,
+ "posts/2026-10.jsonl",
+ [
+ row(POST_IDS.plain, "2026-10-20", "The voice is a setting, nothing more."),
+ row(POST_IDS.quoting, "2026-10-21", "About that voice clip going round:", { quoted: { platform: "twitter", id: "1900000000000000009", author: "someoneelse", url: "https://x.com/someoneelse/status/1900000000000000009" } }),
+ row(POST_IDS.media, "2026-10-22", "The voice setup, pictured.", { mediaCount: 1 }),
+ ].join("\n") + "\n",
+ );
+ write(x, "posts-archive", Object.values(POST_IDS).map((id) => `twitter ${id}`).join("\n") + "\n");
+ for (const id of [POST_IDS.plain, POST_IDS.media]) {
+ const d = path.join(x, "posts-media", id);
+ mkdirSync(d, { recursive: true });
+ writeFileSync(path.join(d, "shot.png"), postShotPng());
+ writeFileSync(path.join(d, "capture.json"), json({ version: 1, id, url: `https://x.com/teststreamer/status/${id}`, capturedAt: "2026-10-30T00:00:00.000Z", state: "captured", mediaState: "skipped", media: [] }));
+ }
return { cands, backlog };
}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -1876,7 +1876,7 @@ makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out
// (cut-sections, cut-flash, trailer-beats and take-housekeeping specs).
makeCutEditingFixture({ reports, manifest, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
// The intake (UI notes 2026-10-30, items 13, 14, 16): the candidates inbox, the source backlog, Add post (intake specs).
-makeIntakeFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
+makeIntakeFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Gaps inside a clip and the bench waveform's zoom (gaps-zoom.spec.ts), which WRITES (gaps cut,
// undone, put back): its own project on gapvid, a recording id of its own (the fixture's vid1
// window -- tone, silences at 2.9-3.1 and 5.9-6.1 -- so nothing another spec fetches moves it).
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -1555,7 +1555,7 @@ export async function updateRender(dir, patch, { token = null } = {}) {
// into the manifest, and this writer refuses to be a second way to do that.
// ---------------------------------------------------------------------------
-const POST_PATCH_KEYS = ["attachTo", "hide", "thread"];
+const POST_PATCH_KEYS = ["attachTo", "hide", "thread", "shotMaxHeight"];
/**
* A batch of post patches, checked for shape before anything is read: post id
@@ -1563,7 +1563,7 @@ const POST_PATCH_KEYS = ["attachTo", "hide", "thread"];
* `attachTo: ""` is the same as null (a select's "auto").
*
* @param {unknown} posts
- * @returns {Record<string, { attachTo?: string | null, hide?: boolean, thread?: boolean }>}
+ * @returns {Record<string, { attachTo?: string | null, hide?: boolean, thread?: boolean, shotMaxHeight?: number | null }>}
*/
export function normalizePostPatches(posts) {
if (!posts || typeof posts !== "object" || Array.isArray(posts)) {
@@ -1571,7 +1571,7 @@ export function normalizePostPatches(posts) {
}
const ids = Object.keys(posts);
if (!ids.length) throw new Error("nothing to change");
- /** @type {Record<string, { attachTo?: string | null, hide?: boolean, thread?: boolean }>} */
+ /** @type {Record<string, { attachTo?: string | null, hide?: boolean, thread?: boolean, shotMaxHeight?: number | null }>} */
const out = {};
for (const id of ids) {
const v = /** @type {Record<string, unknown>} */ (posts)[id];
@@ -1580,10 +1580,10 @@ export function normalizePostPatches(posts) {
}
for (const k of Object.keys(v)) {
if (!POST_PATCH_KEYS.includes(k)) {
- throw new Error(`${id}: ${k} is not something this writer changes (only attachTo, hide and thread)`);
+ throw new Error(`${id}: ${k} is not something this writer changes (only attachTo, hide, thread and shotMaxHeight)`);
}
}
- /** @type {{ attachTo?: string | null, hide?: boolean, thread?: boolean }} */
+ /** @type {{ attachTo?: string | null, hide?: boolean, thread?: boolean, shotMaxHeight?: number | null }} */
const p = {};
if ("attachTo" in v) {
const a = /** @type {Record<string, unknown>} */ (v).attachTo;
@@ -1601,6 +1601,13 @@ export function normalizePostPatches(posts) {
if (typeof t !== "boolean") throw new Error(`${id}: thread must be true or false`);
p.thread = t;
}
+ // The post's own crop of its screenshot (UI notes item 13): px, or null for none.
+ if ("shotMaxHeight" in v) {
+ const c = /** @type {Record<string, unknown>} */ (v).shotMaxHeight;
+ if (c === null || c === "" || c === undefined) p.shotMaxHeight = null;
+ else if (typeof c === "number" && Number.isInteger(c)) p.shotMaxHeight = c;
+ else throw new Error(`${id}: shotMaxHeight must be a whole number of pixels, or null for no crop`);
+ }
out[id] = p;
}
return out;
@@ -1620,9 +1627,9 @@ export function normalizePostPatches(posts) {
* build's own check, so a manifest this accepts is one the build accepts.
*
* @param {string} dir
- * @param {Record<string, { attachTo?: string | null, hide?: boolean }>} posts
+ * @param {Record<string, { attachTo?: string | null, hide?: boolean, thread?: boolean, shotMaxHeight?: number | null }>} posts
* @param {{ token?: string | null }} [opts]
- * @returns {Promise<{ posts: Record<string, { attachTo: string | null, hide: boolean }>, token: string | null }>}
+ * @returns {Promise<{ posts: Record<string, { attachTo: string | null, hide: boolean, thread: boolean, shotMaxHeight: number | null }>, token: string | null }>}
*/
export async function updatePosts(dir, posts, { token = null } = {}) {
const next = normalizePostPatches(posts);
@@ -1655,16 +1662,20 @@ export async function updatePosts(dir, posts, { token = null } = {}) {
if (p.thread) post.thread = true;
else delete post.thread;
}
+ if ("shotMaxHeight" in p) {
+ if (p.shotMaxHeight !== null && p.shotMaxHeight !== undefined) post.shotMaxHeight = p.shotMaxHeight;
+ else delete post.shotMaxHeight;
+ }
}
const errors = validatePosts(manifest.posts, manifest.timeline ?? [], manifest.render);
if (errors.length) throw new PostsRefused(errors);
const nextToken = await writeManifestAtomic(dir, manifest);
- /** @type {Record<string, { attachTo: string | null, hide: boolean, thread: boolean }>} */
+ /** @type {Record<string, { attachTo: string | null, hide: boolean, thread: boolean, shotMaxHeight: number | null }>} */
const saved = {};
for (const id of ids) {
const post = byId.get(id);
- saved[id] = { attachTo: post.attachTo ?? null, hide: post.hide === true, thread: post.thread === true };
+ saved[id] = { attachTo: post.attachTo ?? null, hide: post.hide === true, thread: post.thread === true, shotMaxHeight: Number.isInteger(post.shotMaxHeight) ? post.shotMaxHeight : null };
}
return { posts: saved, token: nextToken };
});
@@ -2895,7 +2906,7 @@ export async function writeDraftedField(dir, { entry = null, field, value }, { t
});
}
-const POST_TEXT_KEYS = ["platform", "author", "handle", "date", "text", "url", "shot", "flag", "accent", "logo", "siteChannel", "siteUrl", "postId", "variant"];
+const POST_TEXT_KEYS = ["platform", "author", "handle", "date", "text", "url", "shot", "flag", "accent", "logo", "siteChannel", "siteUrl", "postId", "variant", "shotMaxHeight"];
/**
* Add a post, or replace the one with its id. The value is the post as it
diff --git a/umtool/lib/report/manifest.test.mjs b/umtool/lib/report/manifest.test.mjs
@@ -400,7 +400,7 @@ test("updatePosts: attachTo and hide round trip; null and false delete the key;
try {
const token = await manifestToken(dir);
const res = await updatePosts(dir, { p1: { attachTo: "c02", hide: true }, p2: { attachTo: null, hide: false } }, { token });
- assert.deepEqual(res.posts, { p1: { attachTo: "c02", hide: true, thread: false }, p2: { attachTo: null, hide: false, thread: false } });
+ assert.deepEqual(res.posts, { p1: { attachTo: "c02", hide: true, thread: false, shotMaxHeight: null }, p2: { attachTo: null, hide: false, thread: false, shotMaxHeight: null } });
assert.equal(res.token, await manifestToken(dir));
const raw = await readRaw(dir);
assert.ok(raw.startsWith('{\n "slug"') && raw.endsWith("}\n"), "the CLI's formatting kept");
@@ -429,7 +429,7 @@ test("updatePosts: thread round trips on a post with a shot (false deletes it);
const dir = await project(m0);
try {
const res = await updatePosts(dir, { p1: { thread: true } });
- assert.deepEqual(res.posts.p1, { attachTo: null, hide: false, thread: true });
+ assert.deepEqual(res.posts.p1, { attachTo: null, hide: false, thread: true, shotMaxHeight: null });
assert.equal(post(await read(dir), "p1").thread, true);
// Replaced by a writer that does not name it: kept, as attachTo is.
await upsertPost(dir, { ...m0.posts[0], text: "one, again" });
diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs
@@ -312,6 +312,11 @@ export function applyPostsDraft(posts, draft = {}) {
if (d.thread) out.thread = true;
else delete out.thread;
}
+ // A crop being tried (the Add post panel's), previewed before it is saved.
+ if ("shotMaxHeight" in d) {
+ if (Number.isInteger(d.shotMaxHeight)) out.shotMaxHeight = d.shotMaxHeight;
+ else delete out.shotMaxHeight;
+ }
return out;
});
}
diff --git a/umtool/lib/report/onscreen.test.mjs b/umtool/lib/report/onscreen.test.mjs
@@ -229,7 +229,7 @@ test("applyPostsDraft: the writer's rule, on a copy", () => {
assert.equal(applyPostsDraft(posts, {}), posts);
assert.deepEqual(normalizePostsDraft(undefined), {});
assert.deepEqual(normalizePostsDraft({}), {});
- assert.throws(() => normalizePostsDraft({ p1: { text: "x" } }), /only attachTo, hide and thread/);
+ assert.throws(() => normalizePostsDraft({ p1: { text: "x" } }), /only attachTo, hide, thread and shotMaxHeight/);
});
test("postRows: the automatic clip, the effective one, and the slot in the schedule", () => {
diff --git a/umtool/lib/report/postCards.mjs b/umtool/lib/report/postCards.mjs
@@ -0,0 +1,141 @@
+// POST CARDS FROM PLAY THE CUT (UI notes 2026-10-30, item 13): what the Add
+// post panel reads -- a channel's posts archive searched, each post's
+// warnings from its OWN data -- beside postsCli.mjs's addPostFromArchive (the
+// one write) and the editor's capture-posts (the one capture, paced there).
+//
+// The archive is `channels/<slug>/posts/YYYY-MM.jsonl` (common/lib/posts-server.ts,
+// read only here) and its captures `channels/<slug>/posts-media/<id>/`.
+//
+// THE WARNING is decided from the post's record, never from the picture: a
+// post that QUOTES another (`quoted`), REPOSTS one (`repostOf`) or carries
+// MEDIA (`mediaCount`, a forum's `media`) has a screenshot that shows them --
+// somebody else's words or footage, or a thumbnail -- below its own words.
+// The cure is a crop (`shotMaxHeight` on the post) or another post.
+//
+// Plain ESM.
+import { readFile, readdir, stat } from "node:fs/promises";
+import path from "node:path";
+
+const SLUG_RE = /^[A-Za-z0-9._-]+$/;
+const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
+export const POST_SEARCH_MAX = 40;
+
+const who = (ref) => (ref && typeof ref.author === "string" && ref.author ? `@${ref.author.replace(/^@/, "")}` : "another account");
+
+/**
+ * What the post's screenshot carries besides its own words, as sentences
+ * (empty: nothing). From the record only.
+ *
+ * @param {Record<string, any> | null} row an archive row (common/lib/posts.ts Post)
+ * @returns {string[]}
+ */
+export function postWarnings(row) {
+ if (!row || typeof row !== "object") return [];
+ const out = [];
+ if (row.quoted && typeof row.quoted === "object") {
+ out.push(`it quotes a post by ${who(row.quoted)}: the screenshot carries that post (someone else's words, or their video) — crop it to the post's own words, or pick another`);
+ }
+ if (row.repostOf && typeof row.repostOf === "object") {
+ out.push(`it is a repost of ${who(row.repostOf)}: the screenshot is someone else's post`);
+ }
+ const media = Number.isInteger(row.mediaCount) && row.mediaCount > 0 ? row.mediaCount : Array.isArray(row.media) ? row.media.filter((m) => m && m.kind !== "link-card").length : 0;
+ if (media > 0) out.push(`it carries ${media === 1 ? "a picture or video" : `${media} pictures or videos`}: the screenshot shows ${media === 1 ? "its thumbnail" : "their thumbnails"} — crop it if they are not the point`);
+ return out;
+}
+
+/** The date a row was posted, `YYYY-MM-DD…`, or null. */
+const dateOf = (row) =>
+ typeof row?.createdAt === "string" && row.createdAt
+ ? row.createdAt
+ : /^\d{8}$/.test(String(row?.uploadDate ?? ""))
+ ? `${row.uploadDate.slice(0, 4)}-${row.uploadDate.slice(4, 6)}-${row.uploadDate.slice(6, 8)}`
+ : null;
+
+/**
+ * Search channel `slug`'s posts archive: every word of `q` in the post's words
+ * or handle (any case), newest first, at most `limit`; an empty `q` is the
+ * newest posts. Each hit with its warnings, whether its screenshot is captured,
+ * and whether the cut carries it already.
+ *
+ * @param {string} channelsDir
+ * @param {string} slug
+ * @param {string} q
+ * @param {{ limit?: number, manifest?: Record<string, any> | null }} [o]
+ */
+export async function searchPostArchive(channelsDir, slug, q, { limit = POST_SEARCH_MAX, manifest = null } = {}) {
+ if (!SLUG_RE.test(slug)) throw new Error(`not a channel slug: ${slug}`);
+ const dir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "posts");
+ const names = (await readdir(dir).catch(() => null))?.filter((n) => /^\d{4}-\d{2}\.jsonl$/.test(n)).sort().reverse() ?? null;
+ if (names === null) return { slug, archive: false, hits: [], total: 0 };
+ const words = String(q ?? "").toLowerCase().split(/\s+/).filter(Boolean);
+ const byId = new Map();
+ for (const name of names) {
+ const text = await readFile(path.join(dir, name), "utf8").catch(() => "");
+ for (const line of text.split("\n")) {
+ if (!line.trim()) continue;
+ let row;
+ try {
+ row = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (!row || !POST_ID_RE.test(String(row.id ?? ""))) continue;
+ byId.set(String(row.id), row); // a re-fetch appends: the last line wins
+ }
+ }
+ const hay = (row) => `${row.text ?? ""} ${row.author ?? ""} ${row.authorName ?? ""}`.toLowerCase();
+ const matched = [...byId.values()].filter((row) => !row.isDeleted && words.every((w) => hay(row).includes(w)));
+ matched.sort((a, b) => String(dateOf(b) ?? "").localeCompare(String(dateOf(a) ?? "")));
+ const inCut = new Set(
+ (Array.isArray(manifest?.posts) ? manifest.posts : []).flatMap((p) => [p?.postId, typeof p?.id === "string" ? p.id.replace(/^(x|bsky|post)-/, "") : null]).filter(Boolean),
+ );
+ const media = path.join(/* turbopackIgnore: true */ channelsDir, slug, "posts-media");
+ const hits = await Promise.all(
+ matched.slice(0, limit).map(async (row) => {
+ const id = String(row.id);
+ const shot = await stat(path.join(media, id, "shot.png")).then(() => true, () => false);
+ return {
+ id,
+ date: dateOf(row),
+ author: typeof row.author === "string" ? row.author : null,
+ authorName: typeof row.authorName === "string" ? row.authorName : null,
+ text: typeof row.text === "string" ? row.text : "",
+ url: typeof row.url === "string" ? row.url : null,
+ platform: typeof row.platform === "string" ? row.platform : null,
+ quoted: row.quoted && typeof row.quoted === "object" ? { author: row.quoted.author ?? null, url: row.quoted.url ?? null } : null,
+ mediaCount: Number.isInteger(row.mediaCount) ? row.mediaCount : Array.isArray(row.media) ? row.media.length : 0,
+ warnings: postWarnings(row),
+ captured: shot,
+ inCut: inCut.has(id),
+ };
+ }),
+ );
+ return { slug, archive: true, hits, total: matched.length };
+}
+
+/**
+ * The channels with a posts archive, the ones this cut is likeliest to want
+ * first: those its posts already come from (`siteChannel`, a shot's
+ * `posts-media/<slug>/`), then those named like a channel it cites
+ * (`emberparadox-x` for `emberparadox`), then the rest by name.
+ *
+ * @param {string} channelsDir
+ * @param {Record<string, any> | null} manifest
+ * @param {string[]} cited the channels the cut's clips cite
+ */
+export async function postChannels(channelsDir, manifest, cited = []) {
+ const dirs = await readdir(/* turbopackIgnore: true */ channelsDir, { withFileTypes: true }).catch(() => []);
+ const have = [];
+ for (const d of dirs) {
+ if (!d.isDirectory() || !SLUG_RE.test(d.name)) continue;
+ if (await stat(path.join(/* turbopackIgnore: true */ channelsDir, d.name, "posts")).then((s) => s.isDirectory(), () => false)) have.push(d.name);
+ }
+ const used = new Set(
+ (Array.isArray(manifest?.posts) ? manifest.posts : []).flatMap((p) => [
+ typeof p?.siteChannel === "string" ? p.siteChannel : null,
+ typeof p?.shot === "string" ? (/^posts-media\/([^/]+)\//.exec(p.shot)?.[1] ?? null) : null,
+ ]),
+ );
+ const rank = (s) => (used.has(s) ? 0 : cited.some((c) => s.startsWith(`${c}-`) || s === c) ? 1 : 2);
+ return have.sort((a, b) => rank(a) - rank(b) || a.localeCompare(b)).map((slug) => ({ slug, suggested: rank(slug) < 2 }));
+}
diff --git a/umtool/lib/report/postCards.test.mjs b/umtool/lib/report/postCards.test.mjs
@@ -0,0 +1,78 @@
+// Post cards from Play the cut (UI notes item 13): the WARNING from a post's
+// own data (a quoted post, a repost, media), the archive searched (every word,
+// newest first, the last line of a re-fetch winning, captured and in-the-cut
+// said), the channels offered, and a post's own crop -- `posts set crop=`, the
+// writer, the build's check and the card's drawing (its top, never panned).
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { validatePosts } from "umtool-report-to-video/deck";
+import { postChannels, postWarnings, searchPostArchive } from "./postCards.mjs";
+import { postPatchOf } from "./postsCli.mjs";
+import { MANIFEST_NAME, normalizePostPatches, updatePosts } from "./manifest.mjs";
+import { readFile } from "node:fs/promises";
+
+const row = (id, text, extra = {}) => ({ id, slug: "chan-x", channelSlug: "chan-x", author: "somebody", createdAt: `2026-10-${String(10 + Number(id.slice(-1))).padStart(2, "0")}T12:00:00Z`, text, url: `https://x.com/somebody/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [], ...extra });
+
+test("the warning is the post's own data: a quoted post, a repost, media; none for words alone", () => {
+ assert.deepEqual(postWarnings(row("1001", "just words")), []);
+ const q = postWarnings(row("1002", "look at this", { quoted: { platform: "twitter", id: "9", author: "other" } }));
+ assert.equal(q.length, 1);
+ assert.match(q[0], /quotes a post by @other/);
+ assert.match(postWarnings(row("1003", "pic", { mediaCount: 2 }))[0], /2 pictures or videos/);
+ assert.match(postWarnings(row("1004", "rt", { repostOf: { platform: "twitter", id: "8", author: "x" } }))[0], /repost of @x/);
+ assert.deepEqual(postWarnings(null), []);
+});
+
+async function corpus() {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-posts-"));
+ const posts = path.join(dir, "chan-x", "posts");
+ await mkdir(posts, { recursive: true });
+ await writeFile(
+ path.join(posts, "2026-10.jsonl"),
+ [row("1001", "the voice changer again"), row("1002", "Voice reveal soon", { quoted: { platform: "twitter", id: "9", author: "other" } }), row("1003", "pictures", { mediaCount: 1 }), row("1001", "the voice changer again (edited)")].map((r) => JSON.stringify(r)).join("\n") + "\n{torn",
+ );
+ await mkdir(path.join(dir, "chan-x", "posts-media", "1002"), { recursive: true });
+ await writeFile(path.join(dir, "chan-x", "posts-media", "1002", "shot.png"), "png");
+ await mkdir(path.join(dir, "chan"), { recursive: true });
+ await mkdir(path.join(dir, "zeta-x", "posts"), { recursive: true });
+ return dir;
+}
+
+test("the archive searched: every word, any case, newest first; captured and in-the-cut said; the last line wins", async () => {
+ const dir = await corpus();
+ const r = await searchPostArchive(dir, "chan-x", "VOICE", { manifest: { posts: [{ id: "x-1002" }] } });
+ assert.deepEqual(r.hits.map((h) => h.id), ["1002", "1001"]);
+ assert.equal(r.hits[0].captured, true);
+ assert.equal(r.hits[0].inCut, true);
+ assert.equal(r.hits[0].warnings.length, 1);
+ assert.equal(r.hits[1].text, "the voice changer again (edited)");
+ assert.equal(r.hits[1].captured, false);
+ assert.equal((await searchPostArchive(dir, "chan-x", "")).total, 3);
+ assert.equal((await searchPostArchive(dir, "chan", "")).archive, false);
+ assert.deepEqual(await postChannels(dir, { posts: [] }, ["chan"]), [{ slug: "chan-x", suggested: true }, { slug: "zeta-x", suggested: false }]);
+});
+
+test("a post's own crop: posts set crop=, the patch writer, the build's check (a shot needed, 120–1080)", async () => {
+ assert.deepEqual(postPatchOf(["crop=420"]), { shotMaxHeight: 420 });
+ assert.deepEqual(postPatchOf(["crop=off"]), { shotMaxHeight: null });
+ assert.throws(() => postPatchOf(["crop=big"]), /whole number/);
+ assert.deepEqual(normalizePostPatches({ a: { shotMaxHeight: 300 } }), { a: { shotMaxHeight: 300 } });
+ assert.throws(() => normalizePostPatches({ a: { shotMaxHeight: "300" } }), /whole number/);
+ const post = { id: "x-1", platform: "x", date: "2026-10-01", text: "t", url: "https://x.com/a/status/1", shot: "posts-media/c/1/shot.png" };
+ assert.deepEqual(validatePosts([{ ...post, shotMaxHeight: 400 }], []), []);
+ assert.match(validatePosts([{ ...post, shotMaxHeight: 50 }], []).join(), /120 to 1080/);
+ assert.match(validatePosts([{ ...post, shot: undefined, shotMaxHeight: 400 }], []).join(), /has no shot/);
+
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-crop-"));
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify({ slug: "s", timeline: [{ type: "clip", id: "c1", video: "v", start: 0, end: 2 }], posts: [post] }));
+ const r = await updatePosts(dir, { "x-1": { shotMaxHeight: 360 } });
+ assert.equal(r.posts["x-1"].shotMaxHeight, 360);
+ assert.equal(JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")).posts[0].shotMaxHeight, 360);
+ await updatePosts(dir, { "x-1": { shotMaxHeight: null } });
+ assert.equal("shotMaxHeight" in JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")).posts[0], false, "null removes the key");
+});
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -34,11 +34,12 @@ import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { channelsDirFor, readManifest } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { PostsRefused, StaleToken, StructureRefused, manifestToken, updatePosts, upsertPost } from "./manifest.mjs";
+import { postWarnings } from "./postCards.mjs";
export const POSTS_USAGE = [
"usage: umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID]",
- " [--thread] [--dry-run] [--json]",
- " umtool posts set <project> <post> thread=on|off [hide=on|off] [attach=<clipId>|auto] [--json]",
+ " [--thread] [--crop <px>] [--dry-run] [--json]",
+ " umtool posts set <project> <post> thread=on|off [hide=on|off] [attach=<clipId>|auto] [crop=<px>|off] [--json]",
" a post card from the corpus's posts archive (channels/<slug>/posts/*.jsonl): its words, date, link and handle,",
" and its screenshot (channels/<slug>/posts-media/<postId>/shot.png) copied into the project's posts-media/.",
" The id is x-<postId> (bsky-, post-) unless --id; --attach pins it to a clip; --author overrides the name",
@@ -47,9 +48,11 @@ export const POSTS_USAGE = [
" --thread (or `set … thread=on`): a reply drawn with the post it answers above it -- the capture's",
" shot-thread.png beside shot.png (capture-posts with \"thread\": true takes it); its own shot while there is none.",
" set: <post> is the manifest's post id (x-<postId>) or the bare <postId>; the Posts table's writer.",
+ " --crop / crop=<px>: the post's own crop of its screenshot (shotMaxHeight, 120-1080): its top that tall, never panned.",
+ " A post that quotes another or carries media is added with a WARNING: its screenshot shows them (the post's own data says so).",
].join("\n");
-const VALUED = new Set(["--attach", "--flag", "--author", "--id"]);
+const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
@@ -144,10 +147,10 @@ const OFF = new Set(["off", "false", "no", "0"]);
* `hide=on|off`, `attach=<clipId>|auto`. Throws on anything else.
*
* @param {string[]} pairs
- * @returns {{ attachTo?: string | null, hide?: boolean, thread?: boolean }}
+ * @returns {{ attachTo?: string | null, hide?: boolean, thread?: boolean, shotMaxHeight?: number | null }}
*/
export function postPatchOf(pairs) {
- /** @type {{ attachTo?: string | null, hide?: boolean, thread?: boolean }} */
+ /** @type {{ attachTo?: string | null, hide?: boolean, thread?: boolean, shotMaxHeight?: number | null }} */
const out = {};
for (const pair of pairs) {
const eq = pair.indexOf("=");
@@ -157,12 +160,17 @@ export function postPatchOf(pairs) {
if (ON.has(v)) out[k] = true;
else if (OFF.has(v)) out[k] = false;
else throw new CliError(`${k}= takes on or off, not ${JSON.stringify(v)}`);
+ } else if (k === "crop") {
+ // The post's own crop of its screenshot: its top that many px, never panned.
+ if (OFF.has(v) || v === "none") out.shotMaxHeight = null;
+ else if (/^\d+$/.test(v)) out.shotMaxHeight = Number(v);
+ else throw new CliError(`crop= takes a whole number of pixels, or off (got ${JSON.stringify(v)})`);
} else if (k === "attach") {
if (!v) throw new CliError("attach= takes a clip id, or auto");
out.attachTo = v === "auto" ? null : pair.slice(eq + 1);
- } else throw new CliError(`${pair}: not a post knob (thread=, hide=, attach=)`);
+ } else throw new CliError(`${pair}: not a post knob (thread=, hide=, attach=, crop=)`);
}
- if (!Object.keys(out).length) throw new CliError("nothing to set: thread=on|off, hide=on|off or attach=<clipId>|auto");
+ if (!Object.keys(out).length) throw new CliError("nothing to set: thread=on|off, hide=on|off, attach=<clipId>|auto or crop=<px>|off");
return out;
}
@@ -229,6 +237,63 @@ const sameFile = async (a, b) => {
};
/**
+ * ADD A POST CARD from the archive -- `posts add`'s whole write, which the
+ * Add post panel (Play the cut, /api/report/post-cards) runs too: the archive's
+ * row, its screenshot required, the entry (postEntryOf, `crop` its
+ * shotMaxHeight), the capture copied into the project (never through a link
+ * out of it), then upsertPost under the generated-manifest guard. Answers what
+ * was written and the WARNINGS the post's own data gives (postWarnings: a
+ * quoted post, a media thumbnail in the screenshot). `dryRun`: nothing written.
+ *
+ * @param {{ id: string, dir: string, kind?: string }} project
+ * @param {{ slug: string, postId: string, attach?: string | null, flag?: string | null, author?: string | null, id?: string | null, thread?: boolean, crop?: number | null, dryRun?: boolean }} o
+ */
+export async function addPostFromArchive(project, { slug, postId, attach = null, flag = null, author = null, id = null, thread = false, crop = null, dryRun = false }) {
+ if (!SLUG_RE.test(slug) || !POST_ID_RE.test(postId)) throw new CliError(`not <archive-channel>/<postId>: ${slug}/${postId}`);
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CliError(`${project.id} has no manifest`);
+ // The corpus the project reads (provenance.channelsDir), else the global one.
+ const channelsDir = channelsDirFor(project.dir, manifest);
+ const found = await findPostRow(channelsDir, slug, postId);
+ if (!found.row) {
+ throw new Error(
+ found.shards
+ ? `${slug} has no post ${postId} in its archive (${found.shards} shard(s) read under ${path.join(channelsDir, slug, "posts")})`
+ : `${slug} has no posts archive under ${channelsDir} — is it a social channel?`,
+ );
+ }
+ const shotFrom = path.join(channelsDir, slug, "posts-media", postId, "shot.png");
+ if (!(await stat(shotFrom).catch(() => null))) {
+ throw new Error(
+ `${slug}/${postId} has no screenshot (${shotFrom}) — capture it first:\n` +
+ ` pnpm ops capture-posts --json '${JSON.stringify({ slug, ids: [postId] })}'`,
+ );
+ }
+ if (attach && !(manifest.timeline ?? []).some((e) => e?.type === "clip" && e.id === attach)) {
+ throw new CliError(`--attach ${attach}: no clip with that id in ${project.id}`);
+ }
+ const post = postEntryOf(found.row, { slug, postId, manifest, attach, flag, author, id, thread });
+ if (crop !== null && crop !== undefined) post.shotMaxHeight = crop;
+ const warnings = postWarnings(found.row);
+ // A thread shot asked for and not taken: the card draws its own shot until a capture takes one.
+ const threadFrom = path.join(path.dirname(shotFrom), "shot-thread.png");
+ const threadMissing = thread && !(await stat(threadFrom).catch(() => null));
+ const shotTo = path.join(project.dir, ...post.shot.split("/"));
+ if (dryRun) return { post, shard: found.shard, shotFrom, shotTo, warnings, found };
+ // The pictures first: a post whose `shot` names a file not there would build a broken card.
+ // Never THROUGH a link out of the project: a cut whose posts-media/<slug> links the
+ // channel's own captures (the Huck cut's do) already has them, and a link anywhere
+ // else would make this copy a write into somebody else's tree.
+ const where = await shotHome(project.dir, path.dirname(shotTo), path.dirname(path.dirname(shotFrom)));
+ if (where === "elsewhere") {
+ throw new Error(`${path.relative(project.dir, path.dirname(shotTo))} leads out of ${project.id} (a link) — not copying through it`);
+ }
+ const copied = where === "linked" ? [] : await copyCapture(path.dirname(shotFrom), path.dirname(shotTo));
+ const { result, editNotes } = await withEditNotes(project, async () => upsertPost(project.dir, post, { token: await manifestToken(project.dir) }));
+ return { post, result, editNotes, found, shotFrom, shotTo, where, copied, threadMissing, warnings };
+}
+
+/**
* @param {string[]} args the words after `posts`
* @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
* @returns {Promise<number>} the exit code
@@ -267,58 +332,35 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
if (!r.project) throw new CliError(`no project matches "${projectArg}"`);
const project = r.project;
- const manifest = await readManifest(project.dir);
- if (!manifest) throw new CliError(`${project.id} has no manifest`);
- // The corpus the project reads (provenance.channelsDir), else the global one.
- const channelsDir = channelsDirFor(project.dir, manifest);
- const found = await findPostRow(channelsDir, slug, postId);
- if (!found.row) {
- throw new Error(
- found.shards
- ? `${slug} has no post ${postId} in its archive (${found.shards} shard(s) read under ${path.join(channelsDir, slug, "posts")})`
- : `${slug} has no posts archive under ${channelsDir} — is it a social channel?`,
- );
- }
- const shotFrom = path.join(channelsDir, slug, "posts-media", postId, "shot.png");
- if (!(await stat(shotFrom).catch(() => null))) {
- throw new Error(
- `${slug}/${postId} has no screenshot (${shotFrom}) — capture it first:\n` +
- ` pnpm ops capture-posts --json '${JSON.stringify({ slug, ids: [postId] })}'`,
- );
- }
- const attach = str("--attach");
- if (attach && !(manifest.timeline ?? []).some((e) => e?.type === "clip" && e.id === attach)) {
- throw new CliError(`--attach ${attach}: no clip with that id in ${project.id}`);
- }
const thread = flags.has("--thread");
- const post = postEntryOf(found.row, { slug, postId, manifest, attach, flag: str("--flag"), author: str("--author"), id: str("--id"), thread });
- // A thread shot asked for and not taken: the card draws its own shot until a capture takes one.
- const threadFrom = path.join(path.dirname(shotFrom), "shot-thread.png");
- const threadMissing = thread && !(await stat(threadFrom).catch(() => null));
- const shotTo = path.join(project.dir, ...post.shot.split("/"));
+ const cropRaw = str("--crop");
+ const crop = cropRaw === null ? null : Number(cropRaw);
+ if (cropRaw !== null && !Number.isInteger(crop)) throw new CliError(`--crop takes a whole number of pixels (got ${cropRaw})`);
+ const added = await addPostFromArchive(project, {
+ slug,
+ postId,
+ attach: str("--attach"),
+ flag: str("--flag"),
+ author: str("--author"),
+ id: str("--id"),
+ thread,
+ crop,
+ dryRun,
+ });
if (dryRun) {
- out(json ? JSON.stringify({ ok: true, dryRun: true, post, shard: found.shard, shotFrom, shotTo }, null, 2) : `would add ${post.id} (${found.shard}):\n${JSON.stringify(post, null, 2)}\n shot ${shotFrom} -> ${shotTo}`);
+ const { post, shard, shotFrom, shotTo } = added;
+ out(json ? JSON.stringify({ ok: true, dryRun: true, post, shard, shotFrom, shotTo, warnings: added.warnings }, null, 2) : `would add ${post.id} (${shard}):\n${JSON.stringify(post, null, 2)}\n shot ${shotFrom} -> ${shotTo}${added.warnings.map((w) => `\n WARNING: ${w}`).join("")}`);
return 0;
}
- // The pictures first: a post whose `shot` names a file not there would build a broken card.
- // Never THROUGH a link out of the project: a cut whose posts-media/<slug> links the
- // channel's own captures (the Huck cut's do) already has them, and a link anywhere
- // else would make this copy a write into somebody else's tree.
- const where = await shotHome(project.dir, path.dirname(shotTo), path.dirname(path.dirname(shotFrom)));
- if (where === "elsewhere") {
- throw new Error(`${path.relative(project.dir, path.dirname(shotTo))} leads out of ${project.id} (a link) — not copying through it`);
- }
- const copied = where === "linked" ? [] : await copyCapture(path.dirname(shotFrom), path.dirname(shotTo));
- const { result, editNotes } = await withEditNotes(project, async () =>
- upsertPost(project.dir, post, { token: await manifestToken(project.dir) }),
- );
+ const { result, editNotes, found, shotFrom, shotTo, where, copied, threadMissing, warnings } = added;
if (json) {
- out(JSON.stringify({ ok: true, ...result, shard: found.shard, shot: { from: shotFrom, to: shotTo, via: where }, copied, ...(thread ? { threadShot: !threadMissing } : {}), editNotes }, null, 2));
+ out(JSON.stringify({ ok: true, ...result, shard: found.shard, shot: { from: shotFrom, to: shotTo, via: where }, copied, ...(thread ? { threadShot: !threadMissing } : {}), warnings, editNotes }, null, 2));
return 0;
}
out(`${result.created ? "added" : "replaced"} post ${result.post.id}${result.post.attachTo ? ` -> ${result.post.attachTo}` : ""} ${result.post.date}`);
out(` ${result.post.author ?? ""}${result.post.handle ? ` @${result.post.handle}` : ""}: ${result.post.text.split("\n")[0].slice(0, 100)}`);
- out(` shot ${result.post.shot}${where === "linked" ? " (posts-media links the channel's captures)" : copied.length ? ` (copied: ${copied.join(", ")})` : " (already there)"}`);
+ out(` shot ${result.post.shot}${where === "linked" ? " (posts-media links the channel's captures)" : copied.length ? ` (copied: ${copied.join(", ")})` : " (already there)"}${result.post.shotMaxHeight ? `, cropped to its top ${result.post.shotMaxHeight} px` : ""}`);
+ for (const w of warnings) out(` WARNING: ${w}`);
if (threadMissing) {
out(
` thread: no shot-thread.png yet -- its own shot is drawn until one is taken:\n` +
@@ -377,7 +419,7 @@ async function setCommand(projectArg, ref, pairs, { root, json, out }) {
out(JSON.stringify({ ok: true, id, post: saved, ...(threadThere === null ? {} : { threadShot: threadThere }), token: result.token, editNotes }, null, 2));
return 0;
}
- out(`set ${id}: thread ${saved.thread ? "on" : "off"}, ${saved.hide ? "hidden" : "shown"}, rides on ${saved.attachTo ?? "auto"}`);
+ out(`set ${id}: thread ${saved.thread ? "on" : "off"}, ${saved.hide ? "hidden" : "shown"}, rides on ${saved.attachTo ?? "auto"}${saved.shotMaxHeight ? `, cropped to its top ${saved.shotMaxHeight} px` : ""}`);
if (threadThere === false) out(" no shot-thread.png beside its shot yet -- its own shot is drawn (capture-posts with \"thread\": true)");
if (editNotes) out(` edit noted for ${editNotes.generatedBy}`);
return 0;
diff --git a/umtool/lib/report/postsCli.test.mjs b/umtool/lib/report/postsCli.test.mjs
@@ -207,7 +207,7 @@ test("posts set: the Posts table's writer -- thread on/off by the post's id or i
assert.equal(await run("set", "set", XID, "thread=on", "--json"), 0);
const on = JSON.parse(lines.at(-1));
assert.equal(on.id, `x-${XID}`);
- assert.deepEqual(on.post, { attachTo: null, hide: false, thread: true });
+ assert.deepEqual(on.post, { attachTo: null, hide: false, thread: true, shotMaxHeight: null });
assert.equal(on.threadShot, false, "no thread shot beside its shot: its own is drawn");
assert.equal((await read(dir)).posts.find((p) => p.id === `x-${XID}`).thread, true);
assert.equal(await run("set", "set", `x-${XID}`, "thread=off", "hide=on", "attach=c01"), 0);
diff --git a/umtool/report-to-video/chrome-posts.mjs b/umtool/report-to-video/chrome-posts.mjs
@@ -282,7 +282,7 @@ export function postsHtml(schedule, render, window, opts = {}) {
return (
`<article class="post${shot ? " has-shot" : ""}${logo ? " has-logo" : ""}${plate ? "" : " no-plate"}" data-post="${esc(p.id)}" data-k="c${j}"${style}>` +
(shot
- ? `<div class="body shot-body">${flag}<div class="shot-view"><img class="shot" data-k="s${j}" src="${esc(shot)}" alt=""></div></div>`
+ ? `<div class="body shot-body">${flag}<div class="shot-view"${Number.isInteger(p.crop) ? ` data-crop="${p.crop}" style="max-height: ${p.crop}px"` : ""}><img class="shot" data-k="s${j}" src="${esc(shot)}" alt=""></div></div>`
: `<div class="body">${flag}` +
`<div class="meta">` +
(platform ? `<span class="platform">${esc(platform)}</span>` : "") +
@@ -396,7 +396,8 @@ export function postsHtml(schedule, render, window, opts = {}) {
/* A post's screenshot in place of its words: always as wide as the words
would be, so it reads; its viewport is no taller than a full card of
them -- or than \`shotMaxHeight\` -- and a taller one pans up through
- it (postsCues \`pans\`). */
+ it (postsCues \`pans\`). A post's OWN shotMaxHeight is a crop
+ (data-crop): its top that tall, never panned. */
.shot-body { padding: ${pad - 6}px; }
.shot-view { position: relative; overflow: hidden; border-radius: 6px;
max-height: ${set.shotMaxHeight ?? Math.round(metaSize * 1.3) + 8 + set.maxLines * lineH + 2 * pad}px; }
@@ -473,7 +474,8 @@ export function postsHtml(schedule, render, window, opts = {}) {
const pans = cards.map((c) => {
const view = c.querySelector(".shot-view");
const img = view && view.querySelector("img.shot");
- return img ? Math.max(0, Math.round(img.offsetHeight - view.clientHeight)) : 0;
+ // A post's own crop (data-crop) shows its top and never pans to the rest.
+ return img && !view.hasAttribute("data-crop") ? Math.max(0, Math.round(img.offsetHeight - view.clientHeight)) : 0;
});
document.documentElement.dataset.pans = pans.join(",");
const plan = postsCues({ posts: P.posts, heights, pans, column: P.column, gap: P.gap,
diff --git a/umtool/report-to-video/chrome-posts.test.mjs b/umtool/report-to-video/chrome-posts.test.mjs
@@ -518,6 +518,15 @@ test("shotMaxHeight caps a screenshot's viewport in px; unset, a full card of wo
assert.notEqual(cap(RENDER), "820");
});
+test("a post's OWN shotMaxHeight is a crop: its viewport that tall, marked so the page never pans it", () => {
+ const sched = schedule([POST("a", "2024-10-19T17:01:17.640Z", { shot: "shots/a.png", shotMaxHeight: 300 }), POST("b", "2024-10-19T17:01:18.640Z", { shot: "shots/b.png" })]);
+ const win = snapWindow(postWindows(sched)[0], { fps: 30, total: sched.total });
+ const html = postsHtml(sched, RENDER, win, { fonts: FONTS, shotSrcs: { a: "assets/shot00.png", b: "assets/shot01.png" } });
+ assert.match(html, /<div class="shot-view" data-crop="300" style="max-height: 300px"><img class="shot" data-k="s\d+" src="assets\/shot00\.png"/);
+ assert.match(html, /<div class="shot-view"><img class="shot" data-k="s\d+" src="assets\/shot01\.png"/, "a post with no crop is drawn as before");
+ assert.match(html, /!view\.hasAttribute\("data-crop"\)/, "a cropped shot is not panned");
+});
+
test("postsCues: a tall screenshot holds on its top, pans to its bottom, and holds before it leaves", () => {
const posts = [{ id: "p0", appear: 10, out: [30, 30.5] }, { id: "p1", appear: 12, out: [30, 30.5] }];
const plan = postsCues({ posts, heights: [800, 200], pans: [600, 0], column: 2000, enter: 0.5, panHold: 1.2 });
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -1886,7 +1886,10 @@ export function pipSegments(schedule) {
export const POST_PLATFORMS = Object.freeze(["bluesky", "x", "web"]);
/** The cuts a post may be limited to (`posts[].variant`) -- build-video's VARIANTS. */
const POST_VARIANTS = Object.freeze(["sourced", "full"]);
-const POST_KEYS = ["id", "platform", "author", "handle", "date", "text", "url", "attachTo", "hide", "siteChannel", "siteUrl", "postId", "shot", "thread", "variant", "accent", "logo", "flag"];
+const POST_KEYS = ["id", "platform", "author", "handle", "date", "text", "url", "attachTo", "hide", "siteChannel", "siteUrl", "postId", "shot", "thread", "variant", "accent", "logo", "flag", "shotMaxHeight"];
+/** A post's own crop of its screenshot (`posts[].shotMaxHeight`), in px: its top that tall, never panned. */
+export const POST_CROP_MIN = 120;
+export const POST_CROP_MAX = 1080;
/** A post's `flag`: at most this many characters. */
export const POST_FLAG_MAX = 60;
@@ -1996,6 +1999,14 @@ export function validatePosts(posts, timeline = [], render = null) {
if (p.flag != null && (typeof p.flag !== "string" || !p.flag.trim() || p.flag.length > POST_FLAG_MAX)) {
errors.push(`${w}.flag must be a short label (1 to ${POST_FLAG_MAX} characters)`);
}
+ // A CROP of this post's screenshot (UI notes item 13): the top that many px
+ // of it, the rest cut off and never panned to -- what keeps a quoted post or a
+ // media thumbnail below the post's own words off the screen.
+ if (p.shotMaxHeight != null) {
+ if (!(Number.isInteger(p.shotMaxHeight) && p.shotMaxHeight >= POST_CROP_MIN && p.shotMaxHeight <= POST_CROP_MAX)) {
+ errors.push(`${w}.shotMaxHeight must be a whole number of pixels from ${POST_CROP_MIN} to ${POST_CROP_MAX}`);
+ } else if (typeof p.shot !== "string" || !p.shot) errors.push(`${w}.shotMaxHeight crops the post's screenshot, and the post has no shot`);
+ }
});
// Posts that will be drawn need a column that fits the footage box.
if (render && deckOn(render) && resolveDeck(render).posts.show && posts.some((p) => isObj(p) && !p.hide)) {
@@ -2245,6 +2256,7 @@ function postFieldsOf(p, provenance, links) {
...(typeof p.accent === "string" && p.accent ? { accent: p.accent } : {}),
...(typeof p.logo === "string" && p.logo ? { logo: p.logo } : {}),
...(typeof p.flag === "string" && p.flag.trim() ? { flag: p.flag.trim() } : {}),
+ ...(typeof p.shot === "string" && p.shot && Number.isInteger(p.shotMaxHeight) ? { crop: p.shotMaxHeight } : {}),
};
}