Archilyzer · Source

archilyzer

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

commit a6ad73ab8f4f050406933a1f81cc8182388a8f9b
parent 574104c815afb7ab8768bc099d80b28ca42c6ffa
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 07:01:53 -0400

umtool: Create and Settings (P5) — /create over the existing writers, /settings/generation, system actions behind plans

- /create, "What are you making?": one lit list (Research · Article | Video ·
  Song), each line's form inline under it — a case (R2), a sweep with its
  estimate (NewArticleForm), a board's hand-off (R2's plan-then-confirm), the
  chain over an article's iteration, a recording or a sweep report
  (scaffoldReportVideo), a song. The policy is a chip linking Settings.
- /?from=<slug>/<id> → /create?from=… (a `has` row) and /articles/new →
  /create?make=article; the rail's + Create is a link; ⌘K's create actions
  open a line; Work has one + Create.
- /settings/generation: PolicyPanel (moved off the new-article form) and the
  day's spend, job by job, from the ledger.
- /settings/system: the doctor's roots, the index (rebuild as a job, prune in
  process) and storage moves (CLI jobs), each a plan first (ActionPlan).

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

Diffstat:
Mumtool/app/api/doctor/route.ts | 15++++++++++-----
Aumtool/app/api/system/_respond.ts | 17+++++++++++++++++
Aumtool/app/api/system/index/route.ts | 22++++++++++++++++++++++
Aumtool/app/api/system/storage/route.ts | 23+++++++++++++++++++++++
Dumtool/app/articles/new/page.tsx | 30------------------------------
Aumtool/app/create/page.tsx | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/drafts/page.tsx | 8+++++---
Mumtool/app/page.tsx | 21+++++----------------
Aumtool/app/settings/generation/page.tsx | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/settings/page.tsx | 7+++----
Mumtool/app/settings/system/page.tsx | 30++++++++++++++++++++++--------
Mumtool/app/work/page.tsx | 14+++++---------
Mumtool/bin/umtool.mjs | 28++++------------------------
Mumtool/components/AppNav.tsx | 5++++-
Mumtool/components/NewProjectMenu.tsx | 291+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Mumtool/components/articles/NewArticleForm.tsx | 63++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Aumtool/components/create/CreateView.tsx | 223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/create/forms.tsx | 325+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/shell/AppRail.tsx | 2+-
Mumtool/components/shell/CreateMenu.tsx | 63++++++++++++++++-----------------------------------------------
Mumtool/components/shell/JumpPalette.tsx | 16++++++++++++----
Aumtool/components/system/ActionPlan.tsx | 174+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/system/Maintenance.tsx | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/ui/lit-list.tsx | 10+++++++++-
Mumtool/e2e/inbox.spec.ts | 13+++++++++----
Aumtool/lib/create.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/create/create.test.mjs | 47+++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/create/estimate.mjs | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/create/policy.mjs | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.test.mjs | 15++++++++++++---
Mumtool/lib/hrefs.ts | 46++++++++++++++++++++++++++++++++++++++--------
Mumtool/lib/projects.ts | 16++++++++++++++++
Aumtool/lib/projects/create.mjs | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/settings/settings.test.mjs | 31+++++++++++++++++++++++++++++++
Aumtool/lib/settings/spend.mjs | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/system/actions.ts | 246+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/system/plan-types.ts | 27+++++++++++++++++++++++++++
Aumtool/lib/system/roots.mjs | 27+++++++++++++++++++++++++++
Aumtool/lib/system/storage-rows.ts | 36++++++++++++++++++++++++++++++++++++
Mumtool/redirects.mjs | 13++++++++++---
40 files changed, 2301 insertions(+), 291 deletions(-)

diff --git a/umtool/app/api/doctor/route.ts b/umtool/app/api/doctor/route.ts @@ -1,19 +1,24 @@ import { probeNow, toolsCache } from "@/lib/doctor"; +import { rootsReport } from "@/lib/system/roots.mjs"; export const dynamic = "force-dynamic"; // GET is the cache, and only the cache: `{ checked: false }` when nothing has // been probed in the last ten minutes. POST probes. The split is the rule that // the index and the pages never shell out -- a probe is an action somebody took. +// +// Both carry `roots` (P5, lib/system/roots.mjs -- `umtool doctor`'s): where +// projects are read, where out/ goes and whether that drive is there, the +// cache and the index, and a cache left at its old place. Stats only; POST +// also sizes the old cache. export async function GET() { const c = toolsCache(); - return Response.json( - c ? { checked: true, ...c } : { checked: false }, - { headers: { "cache-control": "no-store" } }, - ); + const roots = await rootsReport({ measureOld: false }); + return Response.json(c ? { checked: true, ...c, roots } : { checked: false, roots }, { headers: { "cache-control": "no-store" } }); } export async function POST() { const r = await probeNow(); - return Response.json({ checked: true, ...r }, { headers: { "cache-control": "no-store" } }); + const roots = await rootsReport(); + return Response.json({ checked: true, ...r, roots }, { headers: { "cache-control": "no-store" } }); } diff --git a/umtool/app/api/system/_respond.ts b/umtool/app/api/system/_respond.ts @@ -0,0 +1,17 @@ +import { ActionError } from "@/lib/system/actions"; + +// The system actions' answers: JSON, never cached; an error in words with its +// status, and the plan when the confirm was refused by it. +export const ok = (v: unknown) => Response.json(v, { headers: { "cache-control": "no-store" } }); + +export function fail(e: unknown) { + const status = e instanceof ActionError ? e.status : 500; + const plan = e instanceof ActionError ? e.plan : null; + return Response.json({ error: e instanceof Error ? e.message : String(e), ...(plan ? { plan } : {}) }, { status, headers: { "cache-control": "no-store" } }); +} + +export async function bodyOf(request: Request): Promise<Record<string, unknown>> { + const b = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!b || typeof b !== "object" || Array.isArray(b)) throw new ActionError("expected a JSON object"); + return b; +} diff --git a/umtool/app/api/system/index/route.ts b/umtool/app/api/system/index/route.ts @@ -0,0 +1,22 @@ +import { ActionError, applyIndex, isIndexAction, planIndex } from "@/lib/system/actions"; +import { bodyOf, fail, ok } from "../_respond"; + +export const dynamic = "force-dynamic"; + +// THE PROJECT INDEX, from Settings · system (P5): `umtool index --rebuild | +// --prune` behind a plan (lib/system/actions.ts). +// +// POST { action: "rebuild" | "prune", dryRun: true } -> { plan } writes nothing +// POST { action: "rebuild" | "prune" } -> { applied, message, job? } +// rebuild runs as a umtool job (the CLI); prune drops the records in +// process. A confirm the plan now refuses is 409 with the plan. +export async function POST(request: Request) { + try { + const b = await bodyOf(request); + if (!isIndexAction(b.action)) throw new ActionError('action is "rebuild" or "prune"'); + if (b.dryRun === true) return ok({ plan: await planIndex(b.action) }); + return ok({ applied: true, ...(await applyIndex(b.action)) }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/system/storage/route.ts b/umtool/app/api/system/storage/route.ts @@ -0,0 +1,23 @@ +import { applyStorage, parseStorage, planStorage } from "@/lib/system/actions"; +import { bodyOf, fail, ok } from "../_respond"; + +export const dynamic = "force-dynamic"; + +// STORAGE MOVES, from Settings · system (P5): `umtool storage move-out | +// move-back | deliverables` behind a plan (lib/system/actions.ts). The body +// names a project id (or all), never a path. +// +// POST { action: "move-out" | "move-back", project | all: true, dryRun: true } -> { plan } +// POST { action: "deliverables", project, to: "media" | "local", dryRun: true } -> { plan } +// the same without dryRun -> { applied, message, job }: a umtool job running +// the CLI; a confirm the plan now refuses is 409 with the plan. +export async function POST(request: Request) { + try { + const b = await bodyOf(request); + const input = parseStorage(b); + if (b.dryRun === true) return ok({ plan: await planStorage(input) }); + return ok({ applied: true, ...(await applyStorage(input)) }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/articles/new/page.tsx b/umtool/app/articles/new/page.tsx @@ -1,30 +0,0 @@ -import BrowseHeader from "@/components/BrowseHeader"; -import NewArticleForm from "@/components/articles/NewArticleForm"; -import { listArticleDirs, listPendingArticles } from "yt-dlp-transcript-common/lib/report/registry"; -import { readPolicy, readToday, type PolicyView } from "@/lib/articles/generation"; -import { sitesPaths } from "@/lib/articles/sites"; - -export const dynamic = "force-dynamic"; - -// A NEW ARTICLE (release 27 S8): its first iteration, a sweep the editor runs -// (`report-draft`), and the generation policy it starts from. The article is -// in the making — on /articles as generating — until an iteration is used. -export default async function NewArticlePage() { - let policy: PolicyView | null = null; - try { - policy = await readPolicy(); - } catch { - policy = null; - } - const today = policy ? await readToday(policy.generation.caps.daily).catch(() => null) : null; - const paths = sitesPaths(); - const taken = [...(await listArticleDirs(paths)), ...(await listPendingArticles(paths))]; - return ( - <div className="flex h-full flex-col"> - <BrowseHeader active="articles" crumbs={[{ label: "articles", href: "/work?kind=article" }, { label: "new" }]} /> - <main className="deck-main flex-1 p-4"> - <NewArticleForm initialPolicy={policy} today={today} taken={taken} /> - </main> - </div> - ); -} diff --git a/umtool/app/create/page.tsx b/umtool/app/create/page.tsx @@ -0,0 +1,58 @@ +import Link from "next/link"; +import CreateView from "@/components/create/CreateView"; +import AppShell from "@/components/shell/AppShell"; +import { readCreate } from "@/lib/create"; +import { policyChip } from "@/lib/create/policy.mjs"; +import { generationPolicyHref, isMake, type Make } from "@/lib/hrefs"; + +export const dynamic = "force-dynamic"; + +// --------------------------------------------------------------------------- +// /create (plans/umtool-redesign.md, P5; canvas "Create"): "What are you +// making?" -- one shell over the writers that already exist. Research a +// question (a case, R2) · an article from a question (a sweep, r27/r28) or a +// board (R2's hand-off) · a video from an article (the chain), a board, a +// recording or a sweep report (scaffoldReportVideo) · a song. The policy is a +// chip (the Meter dot and where each task runs) linking /settings/generation. +// +// ?make=<make> opens that line's form (lib/hrefs.ts MAKES) +// ?from=<c>/<id> the editor's "make a video" (/?from= redirects here): +// "Video from a recording", prefilled +// ?case=<id> preselects a board; ?article=<id> an article +// --------------------------------------------------------------------------- + +export default async function CreatePage({ + searchParams, +}: { + searchParams: Promise<{ make?: string; from?: string; case?: string; article?: string }>; +}) { + const sp = await searchParams; + const from = typeof sp.from === "string" && sp.from.trim() ? sp.from.trim() : null; + const initial: Make | null = from ? "video-recording" : isMake(sp.make) ? sp.make : null; + const data = await readCreate(); + const chip = policyChip(data.policy?.generation ?? null, data.policy?.tasks); + + return ( + <div className="flex h-full flex-col"> + <AppShell + active="create" + crumbs={[{ label: "What are you making?" }]} + actions={ + <Link + href={generationPolicyHref()} + prefetch={false} + data-policy-chip={data.policy?.generation.preset ?? "unknown"} + title={data.policyError ?? "Where each task runs, the models, the caps: Settings · generation"} + className="inline-flex max-w-[640px] items-center gap-1.5 truncate rounded-[3px] border border-seam-2 px-2 py-[3px] text-[12px] text-text-2 no-underline hover:border-muted hover:text-text" + > + <i aria-hidden="true" className={`size-1.5 shrink-0 rounded-full ${data.policy ? "bg-meter" : "bg-reject"}`} /> + <span className="truncate">{chip}</span> + </Link> + } + /> + <main className="deck-main flex-1 px-4 pb-6 pt-4"> + <CreateView data={data} initial={initial} from={from} initialCase={sp.case ?? null} initialArticle={sp.article ?? null} /> + </main> + </div> + ); +} diff --git a/umtool/app/drafts/page.tsx b/umtool/app/drafts/page.tsx @@ -1,10 +1,12 @@ import { redirect } from "next/navigation"; +import { newArticleHref } from "@/lib/hrefs"; export const dynamic = "force-dynamic"; // The proof of concept's page (2026-10-12) is the application's now: a new -// article on /articles/new, its iterations on the article's Iterations tab -// (release 27 S8). +// article on Create (/create?make=article, P5; it was /articles/new), its +// iterations on the article's Iterations tab (release 27 S8). P6 deletes this +// page and redirects /drafts to the Inbox. export default function DraftsPage() { - redirect("/articles/new"); + redirect(newArticleHref()); } diff --git a/umtool/app/page.tsx b/umtool/app/page.tsx @@ -2,16 +2,13 @@ import Link from "next/link"; import InboxList, { type InboxCard, type InboxGroup } from "@/components/dashboard/InboxList"; import { UndoBar } from "@/components/dashboard/Lifecycle"; import ResumeChip from "@/components/dashboard/ResumeChip"; -import NewProjectMenu from "@/components/NewProjectMenu"; import AppShell from "@/components/shell/AppShell"; import { buttonVariants } from "@/components/ui/button"; -import { Panel } from "@/components/ui/panel"; import { machineCalls } from "@/lib/machine"; import { homeHref, systemHref } from "@/lib/hrefs"; import { readInbox, type GroupCard, type GroupSummary } from "@/lib/inbox"; import { summarizeGroups } from "@/lib/inbox/groups.mjs"; import { headlineNote, inboxHeadline } from "@/lib/inbox/headline.mjs"; -import { KINDS } from "@/lib/projects"; import type { Decision } from "@/lib/decisions"; import type { LifecycleState } from "@/lib/lifecycle"; @@ -29,10 +26,9 @@ export const dynamic = "force-dynamic"; // /settings/system. What is running is in the rail. // // `?from=<slug>/<id>` is the editor's "make a video" hand-off (VideoPanel, -// VideoNavStrip). Until /create (P5) it opens the new-project form here, -// prefilled, as the dashboard did. `?hidden=1` lists the calls on parked and -// done pieces, each with Reactivate; `?muted=1` the muted ones (lib/mutes.ts), -// each with Unmute. +// VideoNavStrip): redirects.mjs sends it to /create?from=… (P5) before this +// page is reached. `?hidden=1` lists the calls on parked and done pieces, each +// with Reactivate; `?muted=1` the muted ones (lib/mutes.ts), each with Unmute. // --------------------------------------------------------------------------- /** What a decision kind is, in a few words after the piece's title. */ @@ -128,9 +124,9 @@ function hiddenCards(items: Decision[], keep: (d: Decision) => boolean, lifeOf: export default async function Inbox({ searchParams, }: { - searchParams: Promise<{ from?: string; hidden?: string; muted?: string }>; + searchParams: Promise<{ hidden?: string; muted?: string }>; }) { - const { from, hidden: showHidden, muted: showMuted } = await searchParams; + const { hidden: showHidden, muted: showMuted } = await searchParams; const inbox = await readInbox(); const lifeOf = new Map<string, LifecycleState>(); for (const d of inbox.items) if (d.piece && d.lifecycle) lifeOf.set(d.piece, d.lifecycle as LifecycleState); @@ -165,8 +161,6 @@ export default async function Inbox({ extra.push({ id: "hidden", label: "Hidden", note: "on parked and done pieces", collapsed: false, decisions: parkedN, hidden: 0, cards }); } - const kinds = KINDS.map((k) => ({ id: k.id, label: k.label, scaffold: k.scaffold })); - return ( <div className="flex h-full flex-col"> <AppShell @@ -202,11 +196,6 @@ export default async function Inbox({ /> <main className="deck-main flex-1 px-4 pb-6 pt-4"> - {from && ( - <Panel title="Make a video" className="mb-4" data-handoff={from}> - <NewProjectMenu kinds={kinds} from={from} /> - </Panel> - )} {inbox.lifecycleError && ( <p role="alert" className="mb-3 text-[12.5px] text-reject-text"> {inbox.lifecycleError} — every piece reads as active until it is fixed. diff --git a/umtool/app/settings/generation/page.tsx b/umtool/app/settings/generation/page.tsx @@ -0,0 +1,118 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import PolicyPanel from "@/components/articles/PolicyPanel"; +import AppShell from "@/components/shell/AppShell"; +import { Panel } from "@/components/ui/panel"; +import { readPolicy, type PolicyView } from "@/lib/articles/generation"; +import { policyChip } from "@/lib/create/policy.mjs"; +import { articleHref, settingsHref } from "@/lib/hrefs"; +import { daySpend, recentDays } from "@/lib/settings/spend.mjs"; +import Link from "next/link"; + +export const dynamic = "force-dynamic"; + +// --------------------------------------------------------------------------- +// SETTINGS · GENERATION (plans/umtool-redesign.md, P5): the generation policy +// -- where each task runs (Claude Code, the API, the local model), the presets, +// the models (the extractor an API sweep reads its batches with among them), +// the caps, and whether the API key's FILE is there (its path; never the key) +// -- written through the editor's settings action (PolicyPanel, release 27 +// S8, moved here from the new-article form). Under it, the day's spend, job by +// job, from the editor's usage ledger (the total P2b's rail says). +// +// Read from the editor; an editor that does not answer is said, and the +// ledger is still read (it is a file). +// --------------------------------------------------------------------------- + +const usd = (v: number) => `$${v.toFixed(2)}`; +const hhmm = (iso: string) => iso.slice(11, 16); + +export default async function GenerationPage() { + let policy: PolicyView | null = null; + let policyError: string | null = null; + try { + policy = await readPolicy(); + } catch (e) { + policyError = e instanceof Error ? e.message : String(e); + } + const rows = await readGenerationUsage(getPaths().generationUsageFile).catch(() => []); + const day = utcDay(); + const spend = daySpend(rows, day); + const daily = policy?.generation.caps.daily ?? 0; + const today = { day, usd: spend.usd, jobs: spend.jobs.length, daily }; + const week = recentDays(rows, day, 7); + const weekMax = Math.max(...week.map((d) => d.usd), 0.01); + + return ( + <div className="flex h-full flex-col"> + <AppShell + active="generation" + crumbs={[{ href: settingsHref(), label: "Settings" }, { label: "Generation" }]} + meta={<span data-policy-summary="">{policyChip(policy?.generation ?? null, policy?.tasks)}</span>} + /> + <main className="deck-main flex-1 p-4"> + <div className="grid items-start gap-3 xl:grid-cols-[minmax(0,1fr)_360px]"> + {policy ? ( + <PolicyPanel initial={policy} today={today} /> + ) : ( + <Panel title="Policy"> + <p role="alert" className="m-0 text-[12.5px] text-reject-text" data-policy-error=""> + The editor did not answer ({policyError}), so the policy is unknown. Start it, then reload. + </p> + </Panel> + )} + + <Panel + title="Spend today" + aside={ + <span className="text-muted-2"> + {day} UTC · the editor&apos;s ledger + </span> + } + data-spend-today={spend.usd.toFixed(2)} + > + <p className="m-0 flex items-baseline gap-2"> + <span className="num text-[22px] font-semibold text-meter">{usd(spend.usd)}</span> + <span className="text-[12.5px] text-text-2"> + {daily > 0 ? `of the ${usd(daily)} daily cap` : "no daily cap"} · {spend.jobs.length} {spend.jobs.length === 1 ? "job" : "jobs"} + </span> + </p> + {spend.jobs.length > 0 ? ( + <ul className="mt-2 grid list-none gap-0 p-0 text-[12px]" aria-label="today's jobs"> + {spend.jobs.map((j) => ( + <li key={j.jobId} data-spend-job={j.jobId} className="grid grid-cols-[3.2em_minmax(0,1fr)_auto] gap-x-2 border-t border-seam py-1.5"> + <span className="num text-muted-2">{hhmm(j.at)}</span> + <span className="min-w-0 truncate"> + {j.task} ·{" "} + <Link href={articleHref({ site: "articles", id: j.article }, { tab: "iterations" })} prefetch={false} className="ink-link"> + {j.article} i{j.iteration} + </Link> + <span className="block truncate font-mono text-[11px] text-muted-2">{j.models.join(", ")}</span> + </span> + <span className="num text-meter">{usd(j.usd)}</span> + </li> + ))} + </ul> + ) : ( + <p className="mt-2 text-[12px] text-muted">Nothing spent on the API today.</p> + )} + <div className="mt-3 border-t border-seam pt-2"> + <h3 className="micro mb-1.5">Last 7 days</h3> + <ul className="grid list-none gap-1 p-0 text-[11.5px]" aria-label="last 7 days"> + {week.map((d) => ( + <li key={d.day} data-spend-day={d.day} className="grid grid-cols-[6.5em_minmax(0,1fr)_4.5em] items-center gap-x-2"> + <span className="num text-muted-2">{d.day}</span> + <span className="h-1.5 rounded-[1px] bg-seam"> + <i className="block h-full rounded-[1px] bg-meter" style={{ width: `${Math.round((d.usd / weekMax) * 100)}%` }} /> + </span> + <span className="num text-right text-text-2">{usd(d.usd)}</span> + </li> + ))} + </ul> + </div> + </Panel> + </div> + </main> + </div> + ); +} diff --git a/umtool/app/settings/page.tsx b/umtool/app/settings/page.tsx @@ -4,8 +4,7 @@ import { generationPolicyHref, systemHref } from "@/lib/hrefs"; export const dynamic = "force-dynamic"; -// SETTINGS: the two pages. /settings/generation arrives with P5; until then -// the generation policy is set on the new-article form, its current home. +// SETTINGS: the two pages (P5): the generation policy, and the machine. export default function SettingsPage() { return ( <div className="flex h-full flex-col"> @@ -16,8 +15,8 @@ export default function SettingsPage() { { title: "Settings", tools: [ - { href: systemHref(), name: "system", what: "Tools, disk, index, sources, deliverables, recent jobs", testid: "system" }, - { href: generationPolicyHref(), name: "generation policy", what: "Routes, models and caps — on the new-article form until P5", testid: "generation" }, + { href: generationPolicyHref(), name: "generation", what: "Routes, models, caps, the API key's file, today's spend", testid: "generation" }, + { href: systemHref(), name: "system", what: "Doctor, the index, storage moves, disk, sources, deliverables, recent jobs", testid: "system" }, ], }, ]} diff --git a/umtool/app/settings/system/page.tsx b/umtool/app/settings/system/page.tsx @@ -5,13 +5,17 @@ import SourcesPanel from "@/components/dashboard/SourcesPanel"; import StateStrip from "@/components/dashboard/StateStrip"; import ToolsPanel from "@/components/dashboard/ToolsPanel"; import AppShell from "@/components/shell/AppShell"; +import { IndexPanel, RootsPanel, StoragePanel } from "@/components/system/Maintenance"; import { listActivity, runningActivity } from "@/lib/activity"; import { projectsNote, sourceBuckets, stateRows } from "@/lib/dashboard"; import { toolsCache } from "@/lib/doctor"; -import { generationPolicyHref } from "@/lib/hrefs"; +import { generationPolicyHref, settingsHref } from "@/lib/hrefs"; import { freeBytesUnder } from "@/lib/machine"; import { REPORTS_ROOT } from "@/lib/paths"; -import { KINDS, decisionCounts, indexHealth, listProjects } from "@/lib/projects"; +import { KINDS, decisionCounts, indexHealth, indexPrunePlan, listProjects } from "@/lib/projects"; +import { MEDIA_ROOT, MEDIA_TIERED } from "@/lib/paths"; +import { rootsReport } from "@/lib/system/roots.mjs"; +import { storageRows } from "@/lib/system/storage-rows"; export const dynamic = "force-dynamic"; @@ -21,9 +25,15 @@ export const dynamic = "force-dynamic"; // build at all. These were the dashboard's panels; what in them is a CALL // (a required tool missing, a disk nearly full) is an Inbox card instead. // -// Everything is read from the index and the job registries; nothing here -// shells out -- the tools panel shows a cache or "not checked", and probing is -// its button. P5 adds the doctor, index and storage actions. +// Everything is read from the index, the job registries and a few stats; +// nothing here shells out -- the tools panel shows a cache or "not checked", +// and probing is its button. +// +// P5: the maintenance a terminal did -- the doctor's roots, `umtool index +// --rebuild | --prune`, `umtool storage move-out | move-back | deliverables` +// (lib/system/actions.ts) -- each one that changes or moves anything a plan +// first, then Confirm or Keep it (components/system/ActionPlan.tsx); the long +// ones run as umtool jobs, in the rail's Running list. export default async function SystemPage() { const projects = await listProjects(); @@ -33,6 +43,7 @@ export default async function SystemPage() { const tools = toolsCache(); const ix = indexHealth(); const free = await freeBytesUnder(REPORTS_ROOT); + const [roots, prune, storage] = await Promise.all([rootsReport({ measureOld: false }), indexPrunePlan(), storageRows()]); const blocking = [...counts.values()].reduce((n, c) => n + c.blocking, 0); const openN = [...counts.values()].reduce((n, c) => n + c.open, 0); @@ -42,16 +53,19 @@ export default async function SystemPage() { <div className="flex h-full flex-col"> <AppShell active="system" - crumbs={[{ href: "/settings", label: "settings" }, { label: "system" }]} + crumbs={[{ href: settingsHref(), label: "Settings" }, { label: "System" }]} actions={ - <Link href={generationPolicyHref()} data-policy-link="" className="ink-link text-[12.5px]"> - Generation policy → + <Link href={generationPolicyHref()} data-policy-link="" prefetch={false} className="ink-link text-[12.5px]"> + Generation → </Link> } /> <main className="deck-main flex-1 p-4"> <div className="grid gap-3 lg:grid-cols-2 2xl:grid-cols-3"> <ToolsPanel initial={tools} freeBytes={free} index={ix} /> + <RootsPanel roots={roots} /> + <IndexPanel index={{ ok: prune.ok, records: prune.records, path: prune.path, builtAt: prune.builtAt, stale: prune.stale.length }} /> + <StoragePanel rows={storage} tiered={MEDIA_TIERED} mediaRoot={MEDIA_ROOT} /> <NowPanel running={running} recent={recent} /> <StateStrip rows={stateRows(KINDS, projects)} note={projectsNote(projects.length, blocking, openN)} /> <SourcesPanel never={buckets.never} old={buckets.old} bad={buckets.bad} /> diff --git a/umtool/app/work/page.tsx b/umtool/app/work/page.tsx @@ -9,7 +9,7 @@ import { Input } from "@/components/ui/field"; import { LitList } from "@/components/ui/lit-list"; import { LitActions, LitGroup, LitLine } from "@/components/ui/lit-line"; import { Toolbar, ToolbarGroup } from "@/components/ui/toolbar"; -import { newArticleHref, projectsHref, siteHref, workHref, type WorkQuery } from "@/lib/hrefs"; +import { createHref, siteHref, workHref, type WorkQuery } from "@/lib/hrefs"; import { ARTICLES_KEY } from "@/lib/articles/key.mjs"; import { KINDS } from "@/lib/projects"; import { readWork, type WorkRow } from "@/lib/work"; @@ -77,14 +77,10 @@ export default async function WorkPage({ searchParams }: { searchParams: Promise </span> } actions={ - <> - <Link href={newArticleHref()} className={buttonVariants({ variant: "quiet", size: "md" })}> - + New article - </Link> - <Link href={projectsHref({ new: true })} className={buttonVariants({ variant: "quiet", size: "md" })}> - + New project - </Link> - </> + // One way in to everything that can be made (canvas "Work"): /create. + <Link href={createHref()} prefetch={false} data-work-create="" className={buttonVariants({ variant: "outline", size: "md" })}> + + Create + </Link> } /> <SlashFocus target="[data-work-search]" /> diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -79,16 +79,14 @@ import { pipelineProcessesFor } from "../lib/report/busy.mjs"; import { probeTools } from "../lib/tools.mjs"; import { notesCommand } from "../lib/annotations/cli.mjs"; import { scaffoldReportVideo } from "../lib/projects/scaffold.mjs"; -import { ARTICLES_DIR, CACHE_DIR, INDEX_DIR, MEDIA_ROOT, MEDIA_TIERED, OLD_CACHE_DIR } from "../lib/paths.mjs"; +import { rootsReport } from "../lib/system/roots.mjs"; +import { ARTICLES_DIR, MEDIA_ROOT, MEDIA_TIERED } from "../lib/paths.mjs"; import { deliverablesState, - measureTree, - mediaRootProblem, moveDeliverables, moveDirToLocal, moveDirToMedia, outDirState, - pathState, } from "../lib/report/storage.mjs"; const argv = process.argv.slice(2); @@ -368,26 +366,8 @@ function cmdKinds() { } } -/** - * The roots, as the doctor reports them: where projects are read, where their - * out/ goes, where the cache is -- and a cache left where it used to live - * (under SONG_DATA, before release 17), which is derived and safe to delete - * once `umtool index` has rebuilt the new one. - */ -async function rootsReport() { - const isDir = async (p) => (await pathState(p)).kind === "dir"; - const problem = await mediaRootProblem(); - const oldPresent = OLD_CACHE_DIR !== CACHE_DIR && (await isDir(OLD_CACHE_DIR)); - return { - ok: !problem, - reports: { path: REPORTS_ROOT, present: await isDir(REPORTS_ROOT) }, - media: { path: MEDIA_ROOT, tiered: MEDIA_TIERED, present: await isDir(MEDIA_ROOT), problem }, - cache: { path: CACHE_DIR, present: await isDir(CACHE_DIR), index: await isDir(INDEX_DIR) }, - oldCache: oldPresent - ? { path: OLD_CACHE_DIR, present: true, bytes: (await measureTree(OLD_CACHE_DIR)).bytes } - : { path: OLD_CACHE_DIR, present: false }, - }; -} +// The roots, as the doctor reports them: lib/system/roots.mjs (shared with +// the app's /settings/system). const mb = (n) => `${(n / 1024 ** 2).toFixed(1)} MB`; diff --git a/umtool/components/AppNav.tsx b/umtool/components/AppNav.tsx @@ -60,6 +60,9 @@ const PLACE_OF: Record<string, string> = { bench: "tools", settings: "settings", system: "settings", + generation: "settings", + // Create is the rail's + Create, not a place: no place is lit on it. + create: "create", ...Object.fromEntries([...TOOL_ITEMS, ...SONG_ITEMS].map((t) => [t.label, "tools"])), }; @@ -102,7 +105,7 @@ export default function AppNav({ active }: { active: string }) { ))} </div> )} - <Link href={systemHref()} prefetch={false} data-place="settings" aria-current={current("settings", ["settings", "system"])}> + <Link href={systemHref()} prefetch={false} data-place="settings" aria-current={current("settings", ["settings", "system", "generation"])}> Settings </Link> </nav> diff --git a/umtool/components/NewProjectMenu.tsx b/umtool/components/NewProjectMenu.tsx @@ -2,35 +2,80 @@ import { useState } from "react"; import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { Field, Input, Select } from "@/components/ui/field"; +import { useHydrated } from "@/components/ui/use-hydrated"; // Start a project that is not there yet -- of any kind the registry says can be -// scaffolded. The kind select comes first; the fields under it are the ones -// that kind DECLARES (`scaffold.fields` in the registry), so this file renders -// from data and never branches on a kind id. `from` prefills the source field -// when the dashboard was opened with ?from=<channel>/<id>. +// scaffolded. The fields are the ones the kind DECLARES (`scaffold.fields` in +// the registry), so this file renders from data and never branches on a kind +// id. It writes through POST /api/projects/new (lib/projects/scaffold.ts). +// +// Two ways in: +// - the projects index's "+ new project": a kind select, then that kind's +// fields (opened by the button, or by ?new=1); +// - Create's lines (/create, P5): ONE kind, fixed (`kind`), always open +// (`inline`), and `from` prefilled when the editor handed a recording over +// (/?from=<channel>/<id> → /create?from=…). A sweep report's line offers +// the reports on disk (`reports`) before a path typed by hand. // // It creates no cut files and no clip windows it cannot know. What it writes is // a shape to fill in, which is the whole reason it exists: the five songs and // six report videos made by hand each came out slightly different. +// +// Contracts (projects.spec.ts, create.spec.ts): the toggle is +// [data-new-project]; the form [data-new-project-form] with [data-new-kind], +// [data-new-slug], [data-new-title], [data-new-from], [data-new-origin], +// [data-new-seed], [data-new-brand], [data-new-create] and [data-new-error]. type Brand = { id: string; label: string }; type Kind = { id: string; label: string; scaffold?: { fields: string[]; brands?: Brand[] } | null }; +type Report = { project: string; path: string; title: string }; -const FIELD_LABEL: Record<string, string> = { - from: "from — a sweep-report .md, a viewer share URL, or <channel>/<videoId>", - siteOrigin: "site origin — the archive every QR resolves to (e.g. https://jeralyzer.pages.dev)", +const FIELD_HINT: Record<string, string> = { + from: "a sweep-report .md, a viewer share URL, or <channel>/<videoId>", + siteOrigin: "the archive every QR resolves to (e.g. https://jeralyzer.pages.dev)", seed: "seed the timeline from the video's digest chapters (review each)", - brand: "brand — a report-to-video preset: its palette and faces, the title lockup, the header mark, an end card", + brand: "a report-to-video preset: its palette and faces, the title lockup, the header mark, an end card", }; -export default function NewProjectMenu({ kinds, from = null, open: startOpen = false }: { kinds: Kind[]; from?: string | null; open?: boolean }) { +export default function NewProjectMenu({ + kinds, + kind: fixedKind, + from = null, + open: startOpen = false, + inline = false, + fromLabel = "From", + fromHint = FIELD_HINT.from, + fromPlaceholder = "report.md, share URL, or channel/videoId", + reports, + submitLabel = "Create", + onCancel, +}: { + kinds: Kind[]; + /** One kind, fixed: no kind select (Create's lines). */ + kind?: string; + from?: string | null; + open?: boolean; + /** Always open, no toggle; Cancel (and Escape) call `onCancel`. */ + inline?: boolean; + fromLabel?: string; + fromHint?: string; + fromPlaceholder?: string; + /** Sweep reports on disk, offered as the `from` (Create's "from a sweep report"). */ + reports?: Report[]; + submitLabel?: string; + onCancel?: () => void; +}) { const router = useRouter(); - const can = kinds.filter((k) => k.scaffold); - const [open, setOpen] = useState(!!from || startOpen); + const hydrated = useHydrated(); + const can = kinds.filter((k) => k.scaffold && (!fixedKind || k.id === fixedKind)); + const [open, setOpen] = useState(inline || !!from || startOpen); const [kind, setKind] = useState(can[0]?.id ?? ""); const [slug, setSlug] = useState(""); const [title, setTitle] = useState(""); - const [src, setSrc] = useState(from ?? ""); + const [src, setSrc] = useState(from ?? reports?.[0]?.path ?? ""); + const [byHand, setByHand] = useState(!reports?.length); const [origin, setOrigin] = useState(""); const [seed, setSeed] = useState(false); const [brand, setBrand] = useState(""); @@ -44,6 +89,7 @@ export default function NewProjectMenu({ kinds, from = null, open: startOpen = f const looksLikeVideo = /[?&]v=/.test(src) || /^[\w.-]+\/[\w.-]+$/.test(src.trim()); const create = async () => { + if (!slug.trim()) return; setBusy(true); setError(null); try { @@ -71,128 +117,139 @@ export default function NewProjectMenu({ kinds, from = null, open: startOpen = f if (!can.length) return null; if (!open) { return ( - <button - type="button" - onClick={() => setOpen(true)} - data-new-project - className="rounded border border-dashed border-[var(--color-line)] px-2.5 py-1 text-[12px] text-[var(--color-dim)] hover:border-[var(--color-sel)] hover:text-[var(--color-sel)]" - > + <Button type="button" size="sm" variant="outline" disabled={!hydrated} onClick={() => setOpen(true)} data-new-project className="border-dashed"> + new project - </button> + </Button> ); } - const input = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-1 text-[12px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]"; - const onEnter = (e: React.KeyboardEvent) => e.key === "Enter" && slug.trim() && create(); + const cancel = () => { + setError(null); + if (inline) onCancel?.(); + else setOpen(false); + }; + // The first field takes the focus: the source when it is asked and empty. + const sourceFirst = inline && fields.includes("from") && !from && byHand; return ( - <div + <form data-new-project-form - className="flex flex-wrap items-center gap-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2" + className="flex flex-wrap items-end gap-x-3 gap-y-2.5" + onSubmit={(e) => { + e.preventDefault(); + void create(); + }} + onKeyDown={(e) => { + if (e.key === "Escape") { + e.preventDefault(); + cancel(); + } + }} > - <select - value={kind} - onChange={(e) => setKind(e.target.value)} - aria-label="project kind" - data-new-kind - className="rounded border border-[var(--color-line)] bg-[var(--color-panel-2)] px-2 py-1 text-[12px]" - > - {can.map((k) => ( - <option key={k.id} value={k.id}> - {k.label} - </option> - ))} - </select> - <input - autoFocus - value={slug} - onChange={(e) => setSlug(e.target.value)} - onKeyDown={onEnter} - placeholder="directory name, e.g. donkey-kong" - aria-label="project directory name" - data-new-slug - className={`w-52 font-mono ${input}`} - /> - <input - value={title} - onChange={(e) => setTitle(e.target.value)} - onKeyDown={onEnter} - placeholder="title (optional)" - aria-label="project title" - data-new-title - className={`w-56 ${input}`} - /> - {fields.includes("from") && ( - <input - value={src} - onChange={(e) => setSrc(e.target.value)} - onKeyDown={onEnter} - placeholder="from: report.md, share URL, or channel/videoId" - aria-label={FIELD_LABEL.from} - title={FIELD_LABEL.from} - data-new-from - className={`w-72 font-mono ${input}`} - /> + {!fixedKind && ( + <Field label="Kind"> + <Select value={kind} onChange={(e) => setKind(e.target.value)} aria-label="project kind" data-new-kind> + {can.map((k) => ( + <option key={k.id} value={k.id}> + {k.label} + </option> + ))} + </Select> + </Field> )} - {fields.includes("siteOrigin") && ( - <input - value={origin} - onChange={(e) => setOrigin(e.target.value)} - onKeyDown={onEnter} - placeholder="site origin, e.g. https://…pages.dev" - aria-label={FIELD_LABEL.siteOrigin} - title={FIELD_LABEL.siteOrigin} - data-new-origin - className={`w-56 font-mono ${input}`} + {fields.includes("from") && reports && reports.length > 0 && ( + <Field label="Report" className="min-w-0 basis-full"> + <Select + aria-label="sweep report" + data-new-report + autoFocus={inline} + value={byHand ? "" : src} + onChange={(e) => { + const v = e.target.value; + setByHand(v === ""); + setSrc(v); + }} + > + {reports.map((r) => ( + <option key={r.path} value={r.path}> + {r.title} — {r.project} + </option> + ))} + <option value="">A path typed by hand…</option> + </Select> + </Field> + )} + {fields.includes("from") && byHand && ( + <Field label={fromLabel} hint={fromHint} className="min-w-0 basis-full"> + <Input + autoFocus={sourceFirst} + value={src} + onChange={(e) => setSrc(e.target.value)} + placeholder={fromPlaceholder} + aria-label={`from — ${FIELD_HINT.from}`} + data-new-from + className="font-mono" + /> + </Field> + )} + <Field label="Folder"> + <Input + autoFocus={!sourceFirst && !(inline && reports?.length)} + value={slug} + onChange={(e) => setSlug(e.target.value)} + placeholder="e.g. donkey-kong" + aria-label="project directory name" + data-new-slug + className="w-48 font-mono" /> + </Field> + <Field label="Title"> + <Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="optional" aria-label="project title" data-new-title className="w-52" /> + </Field> + {fields.includes("siteOrigin") && ( + <Field label="Site origin"> + <Input + value={origin} + onChange={(e) => setOrigin(e.target.value)} + placeholder="https://…pages.dev" + aria-label={`site origin — ${FIELD_HINT.siteOrigin}`} + title={FIELD_HINT.siteOrigin} + data-new-origin + className="w-52 font-mono" + /> + </Field> + )} + {fields.includes("brand") && brands.length > 0 && ( + <Field label="Brand"> + <Select value={brand} onChange={(e) => setBrand(e.target.value)} aria-label={`brand — ${FIELD_HINT.brand}`} title={FIELD_HINT.brand} data-new-brand> + <option value="">no brand</option> + {brands.map((b) => ( + <option key={b.id} value={b.id}> + {b.label} + </option> + ))} + </Select> + </Field> )} {fields.includes("seed") && looksLikeVideo && ( - <label className="flex items-center gap-1 text-[11px] text-[var(--color-dim)]" title={FIELD_LABEL.seed}> + <label className="flex items-center gap-1.5 pb-1.5 text-[12px] text-text-2" title={FIELD_HINT.seed}> <input type="checkbox" checked={seed} onChange={(e) => setSeed(e.target.checked)} data-new-seed /> - seed from chapters + Seed from the digest's chapters </label> )} - {fields.includes("brand") && brands.length > 0 && ( - <select - value={brand} - onChange={(e) => setBrand(e.target.value)} - aria-label={FIELD_LABEL.brand} - title={FIELD_LABEL.brand} - data-new-brand - className="rounded border border-[var(--color-line)] bg-[var(--color-panel-2)] px-2 py-1 text-[12px]" - > - <option value="">no brand</option> - {brands.map((b) => ( - <option key={b.id} value={b.id}> - {b.label} - </option> - ))} - </select> - )} - <button - type="button" - disabled={busy || !slug.trim()} - onClick={create} - data-new-create - className="rounded border border-[var(--color-sel)] px-2.5 py-1 text-[12px] text-[var(--color-sel)] disabled:opacity-40" - > - create - </button> - <button - type="button" - onClick={() => { - setOpen(false); - setError(null); - }} - className="text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]" - > - cancel - </button> + <div className="flex items-center gap-2 pb-px"> + <Button type="submit" variant={inline ? "go" : "primary"} disabled={!hydrated || busy || !slug.trim()} data-new-create> + {busy ? "Creating…" : submitLabel} + </Button> + <Button type="button" variant="quiet" disabled={!hydrated} onClick={cancel}> + Cancel + </Button> + </div> {error && ( - <span className="w-full text-[11px] text-[var(--color-bad)]" data-new-error> + <p role="alert" className="m-0 basis-full text-[12px] text-reject-text" data-new-error> {error} - </span> + </p> )} - </div> + </form> ); } diff --git a/umtool/components/articles/NewArticleForm.tsx b/umtool/components/articles/NewArticleForm.tsx @@ -5,6 +5,7 @@ import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; import PolicyPanel, { type Today } from "@/components/articles/PolicyPanel"; import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect"; +import { estimateOf, estimateText } from "@/lib/create/estimate.mjs"; import type { EditorChannel, PolicyView } from "@/lib/articles/generation"; // /articles/new (release 27 S8): a question over channels becomes an article's @@ -16,6 +17,12 @@ import type { EditorChannel, PolicyView } from "@/lib/articles/generation"; // archive lacks for the question and proposes acquisitions, under the // autonomy chosen here (propose, limits, auto); its queue is on the article's // Iterations tab, and a sweep continues it from there. +// +// It lives on Create (/create?make=article, P5) as "Article from a question": +// there the policy is a chip linking /settings/generation (`showPolicy` +// false), Escape is Cancel, and the ESTIMATE is said before Start -- what such +// runs on the chosen model have spent (the ledger, `history`), under the cap +// (lib/create/estimate.mjs). const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-2 py-1 text-[13px] text-[var(--color-text)] focus-visible:border-[var(--color-sel)] focus-visible:outline-none"; @@ -101,7 +108,26 @@ function ChannelPicker({ value, onChange }: { value: string[]; onChange: (v: str ); } -export default function NewArticleForm({ initialPolicy, today, taken }: { initialPolicy: PolicyView | null; today: Today | null; taken: string[] }) { +export default function NewArticleForm({ + initialPolicy, + today, + taken, + showPolicy = true, + framed = true, + history = {}, + onCancel, +}: { + initialPolicy: PolicyView | null; + today: Today | null; + taken: string[]; + /** The policy panel above the form (Create shows a chip instead). */ + showPolicy?: boolean; + /** Its own border (Create's line region frames it instead). */ + framed?: boolean; + /** task -> model -> per-job USD from the ledger, for the estimate. */ + history?: Record<string, Record<string, number[]>>; + onCancel?: () => void; +}) { const router = useRouter(); const [policy, setPolicy] = useState(initialPolicy); const onPolicy = useCallback((p: PolicyView) => setPolicy(p), []); @@ -136,6 +162,10 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia else setModel(task === "agent" ? (policy?.generation.models.api ?? "") : (policy?.generation.models.local ?? "")); }, [task, begin, policy, researchModel]); + const estimate = estimateText( + estimateOf(history, { task: begin, model, cap: capped ? Number(cap) || null : null, local: !model.startsWith("claude-") }), + ); + const idProblem = !id ? null : !ID_RE.test(id) ? "a lowercase slug: a-z, 0-9 and -" : taken.includes(id) ? "an article by that id exists — add an iteration on its page" : null; async function start(e: React.FormEvent) { @@ -174,14 +204,24 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia return ( <div className="flex max-w-4xl flex-col gap-4"> {policy ? ( - <PolicyPanel initial={policy} today={today} onChange={onPolicy} /> + showPolicy && <PolicyPanel initial={policy} today={today} onChange={onPolicy} /> ) : ( <p role="alert" className="text-[12px] text-[var(--color-bad)]"> The editor did not answer, so the policy and the channels are unknown. Start it, then reload. </p> )} - <form onSubmit={start} aria-label="new article" className="flex flex-col gap-3 rounded border border-[var(--color-line)] p-3"> + <form + onSubmit={start} + aria-label="new article" + className={`flex flex-col gap-3 ${framed ? "rounded border border-[var(--color-line)] p-3" : ""}`} + onKeyDown={(e) => { + if (e.key === "Escape" && onCancel) { + e.preventDefault(); + onCancel(); + } + }} + > <label className="flex flex-col gap-1"> <span className="micro">question</span> <textarea className={field} rows={2} required value={question} onChange={(e) => setQuestion(e.target.value)} aria-label="question" /> @@ -286,7 +326,24 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia <Button type="submit" variant="primary" size="lg" disabled={sending || !policy}> {sending ? "Starting…" : "Start"} </Button> + {onCancel && ( + <Button type="button" variant="quiet" size="lg" onClick={onCancel}> + Cancel + </Button> + )} </div> + {policy && ( + <p className="text-[12px] text-[var(--color-dim)]" data-estimate={begin}> + <span className="micro mr-2">estimate</span> + {estimate} + {today ? ( + <span className="ml-2"> + · today <span className="num text-[var(--color-meter)]">${today.usd.toFixed(2)}</span> + {today.daily > 0 ? ` of $${today.daily.toFixed(2)}` : ""} + </span> + ) : null} + </p> + )} {begin === "research" && policy && ( <p className="text-[12px] text-[var(--color-dim)]" data-research-limits> Limits a run: {policy.generation.research.maxItemsPerRun} items, {policy.generation.research.maxGbPerRun} GB,{" "} diff --git a/umtool/components/create/CreateView.tsx b/umtool/components/create/CreateView.tsx @@ -0,0 +1,223 @@ +"use client"; + +import { Fragment, useCallback, useEffect, useRef, useState } from "react"; +import NewArticleForm from "@/components/articles/NewArticleForm"; +import NewProjectMenu from "@/components/NewProjectMenu"; +import { Button } from "@/components/ui/button"; +import { LitList } from "@/components/ui/lit-list"; +import { LitActions, LitGroup, LitLine } from "@/components/ui/lit-line"; +import { createHref, type Make } from "@/lib/hrefs"; +import type { CreateData } from "@/lib/create"; +import { ArticleVideoForm, BoardForm, ResearchForm } from "./forms"; + +// --------------------------------------------------------------------------- +// CREATE (plans/umtool-redesign.md, P5; canvas "Create"): "What are you +// making?" as ONE lit list of lines in four groups -- Research · Article in the +// left column, Video · Song in the right -- each line a thing to make and the +// button that opens its form, inline under it. Every form is a thin shell over +// a writer that already exists (forms.tsx, NewArticleForm, NewProjectMenu); the +// result navigates to what was made. +// +// Keys: j/k (or the arrows) glide the lit line, Enter opens its form (the first +// field takes the focus), Escape closes it and puts the focus back on the line. +// The open form is in the address (`?make=`), so a reload or a link lands on +// it; `?from=<channel>/<id>` (the editor's hand-off) opens "Video from a +// recording" prefilled. +// --------------------------------------------------------------------------- + +const LIST_KEYS = new Set(["j", "k", "ArrowUp", "ArrowDown", "Home", "End"]); + +type Line = { make: Make; title: string; sub: string; action: string }; + +const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; + +function lines(d: CreateData): { group: string; lines: Line[] }[][] { + const board = d.cases.find((c) => c.quotes > 0) ?? d.cases[0]; + const boardSub = board ? `${board.title} · ${plural(board.quotes, "quote")}${d.cases.length > 1 ? ` · ${plural(d.cases.length, "board")}` : ""}` : "No boards yet"; + return [ + [ + { group: "Research", lines: [{ make: "research", title: "Research a question", sub: "Opens a case: search, read, pin quotes to a board", action: "Open a case" }] }, + { + group: "Article", + lines: [ + { make: "article", title: "From a question", sub: "A sweep writes iteration 1 · estimate shown before it runs", action: "Start sweep" }, + { make: "article-board", title: "From a board", sub: boardSub, action: "Draft article" }, + ], + }, + ], + [ + { + group: "Video", + lines: [ + { make: "video-article", title: "From an article", sub: "Chains a cut from the current report", action: "Choose article" }, + { make: "video-board", title: "From a board", sub: "A timeline scaffolded from the pinned cites", action: "Choose board" }, + { make: "video-recording", title: "From a recording", sub: "A video URL, or <channel>/<id> from the archive", action: "Choose recording" }, + { + make: "video-report", + title: "From a sweep report", + sub: d.reports.length ? `A cited markdown report on disk · ${plural(d.reports.length, "found", "found")}` : "A cited markdown report on disk", + action: "Choose report", + }, + ], + }, + { group: "Song", lines: [{ make: "song", title: "A song cut", sub: "From the song piles in Tools", action: "New song" }] }, + ], + ]; +} + +export default function CreateView({ + data, + initial, + from, + initialCase, + initialArticle, +}: { + data: CreateData; + initial: Make | null; + from: string | null; + initialCase: string | null; + initialArticle: string | null; +}) { + const [open, setOpen] = useState<Make | null>(initial); + const root = useRef<HTMLDivElement>(null); + const columns = lines(data); + + // The open form is the address, so a reload lands on it (no navigation: the + // page has everything it needs). + const show = useCallback((m: Make | null) => { + setOpen(m); + try { + window.history.replaceState(window.history.state, "", m ? createHref({ make: m }) : createHref()); + } catch { + // a browser that refuses is only a lost bookmark + } + }, []); + + // Closing puts the focus back on the line's button, so the keys go on. + const close = useCallback( + (m: Make) => { + show(null); + requestAnimationFrame(() => root.current?.querySelector<HTMLElement>(`[data-make="${m}"]`)?.focus()); + }, + [show], + ); + + // A form opened from the address is scrolled into view. + useEffect(() => { + if (initial) root.current?.querySelector(`[data-make-form="${initial}"]`)?.scrollIntoView({ block: "nearest" }); + }, [initial]); + + const form = (m: Make) => { + const cancel = () => close(m); + switch (m) { + case "research": + return <ResearchForm sources={data.sources} onCancel={cancel} />; + case "article": + return ( + <NewArticleForm initialPolicy={data.policy} today={data.today} taken={data.taken} showPolicy={false} framed={false} history={data.history} onCancel={cancel} /> + ); + case "article-board": + return <BoardForm to="article" cases={data.cases} casesError={data.casesError} initialCase={initialCase} onCancel={cancel} />; + case "video-board": + return <BoardForm to="video" cases={data.cases} casesError={data.casesError} initialCase={initialCase} onCancel={cancel} />; + case "video-article": + return <ArticleVideoForm articles={data.articles} initialArticle={initialArticle} onCancel={cancel} />; + case "video-recording": + return data.kinds.recording ? ( + <NewProjectMenu + kinds={[data.kinds.recording]} + kind={data.kinds.recording.id} + inline + from={from} + fromLabel="Recording" + fromHint="a viewer share URL (…/?v=<channel>%2F<id>&t=<s>) or <channel>/<videoId>" + fromPlaceholder="channel/videoId, or a share URL" + submitLabel="Create the project" + onCancel={cancel} + /> + ) : null; + case "video-report": + return data.kinds.report ? ( + <NewProjectMenu + kinds={[data.kinds.report]} + kind={data.kinds.report.id} + inline + reports={data.reports} + fromLabel="Report" + fromHint="the path of a cited markdown report (.md)" + fromPlaceholder="/path/to/sweep-report.md" + submitLabel="Create the project" + onCancel={cancel} + /> + ) : null; + case "song": + return data.kinds.song ? <NewProjectMenu kinds={[data.kinds.song]} kind={data.kinds.song.id} inline submitLabel="Create the song" onCancel={cancel} /> : null; + } + }; + + return ( + <div ref={root}> + <LitList label="What to make" global columns initial={0}> + <div className="grid gap-x-7 gap-y-[18px] lg:grid-cols-2"> + {columns.map((col, i) => ( + <div key={i} className="flex min-w-0 flex-col gap-[18px]"> + {col.map((g) => ( + <LitGroup key={g.group} title={g.group} className="!mt-0" data-make-group={g.group}> + {g.lines.map((l) => ( + <Fragment key={l.make}> + <LitLine + id={l.make} + initial={open === l.make} + data-make-line={l.make} + className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 py-3" + onKeyDown={(e) => { + if (e.key === "Enter" && e.target === e.currentTarget) { + e.preventDefault(); + show(open === l.make ? null : l.make); + } + }} + > + <div className="min-w-0"> + <b className="block text-[14px] font-semibold">{l.title}</b> + <small className="block truncate text-[12.5px] text-muted-2">{l.sub}</small> + </div> + <LitActions> + <Button + type="button" + className="lit-go" + data-make={l.make} + aria-expanded={open === l.make} + aria-controls={`make-${l.make}`} + onClick={() => show(open === l.make ? null : l.make)} + > + {l.action} + </Button> + </LitActions> + </LitLine> + {open === l.make && ( + <div + id={`make-${l.make}`} + data-make-form={l.make} + role="region" + aria-label={`${g.group}: ${l.title}`} + className="border-b border-seam bg-panel px-5 pb-4 pt-3" + // The list's keys belong to the lines: j/k on a button + // in a form must not move the light (⌘K still passes). + onKeyDown={(e) => { + if (!e.metaKey && !e.ctrlKey && !e.altKey && LIST_KEYS.has(e.key)) e.stopPropagation(); + }} + > + {form(l.make)} + </div> + )} + </Fragment> + ))} + </LitGroup> + ))} + </div> + ))} + </div> + </LitList> + </div> + ); +} diff --git a/umtool/components/create/forms.tsx b/umtool/components/create/forms.tsx @@ -0,0 +1,325 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import HandoffDialog from "@/components/research/HandoffDialog"; +import { Button } from "@/components/ui/button"; +import { Field, Input, Select } from "@/components/ui/field"; +import { articleHref } from "@/lib/hrefs"; +import { researchCaseHref, researchCasesApi } from "@/lib/research/hrefs"; +import type { CaseSummary } from "@/lib/research/case-types"; +import type { SourceOption } from "@/lib/research/types"; + +// --------------------------------------------------------------------------- +// Create's own forms (plans/umtool-redesign.md, P5). Each is a thin shell over +// a writer that already exists -- none writes anything itself: +// +// ResearchForm POST /api/research/cases (R2) → the case's board +// BoardForm a board, then R2's hand-off: POST …/<case>/handoff, its +// plan shown and confirmed in R2's HandoffDialog → the +// article's iterations, or the new project +// ArticleVideoForm an article and a done iteration, the chain's steps +// (GET /api/articles/chain), then POST it → the article's +// iterations, where the chain runs +// +// Keyboard first: the first field takes the focus, Enter submits, Escape is +// Cancel (CreateView puts the focus back on the line). +// --------------------------------------------------------------------------- + +async function json<T>(r: Response): Promise<T> { + const b = (await r.json().catch(() => null)) as (T & { error?: string }) | null; + if (!r.ok) throw new Error(b?.error ?? `HTTP ${r.status}`); + return b as T; +} + +const escToCancel = (onCancel: () => void) => (e: React.KeyboardEvent) => { + if (e.key === "Escape" && !e.defaultPrevented) { + e.preventDefault(); + onCancel(); + } +}; + +function Actions({ children, error }: { children: React.ReactNode; error?: string | null }) { + return ( + <> + <div className="flex items-center gap-2 pb-px">{children}</div> + {error && ( + <p role="alert" className="m-0 basis-full text-[12px] text-reject-text"> + {error} + </p> + )} + </> + ); +} + +// ── Research a question ───────────────────────────────────────────────────── + +export function ResearchForm({ sources, onCancel }: { sources: SourceOption[]; onCancel: () => void }) { + const router = useRouter(); + const [query, setQuery] = useState(""); + const [title, setTitle] = useState(""); + const [source, setSource] = useState(sources[0]?.handle ?? ""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const open = async () => { + if (!query.trim()) return; + setBusy(true); + setError(null); + try { + const r = await json<{ case: { id: string } }>( + await fetch(researchCasesApi(), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ query: query.trim(), ...(title.trim() ? { title: title.trim() } : {}), ...(source ? { scope: { source } } : {}) }), + }), + ); + router.push(researchCaseHref(r.case.id)); + } catch (e) { + setError((e as Error).message); + setBusy(false); + } + }; + return ( + <form + aria-label="research a question" + className="flex flex-wrap items-end gap-x-3 gap-y-2.5" + onKeyDown={escToCancel(onCancel)} + onSubmit={(e) => { + e.preventDefault(); + void open(); + }} + > + <Field label="Question" hint="The case's query; its board opens next" className="min-w-0 basis-full"> + <Input autoFocus required value={query} onChange={(e) => setQuery(e.target.value)} aria-label="question" placeholder="e.g. how many employees" /> + </Field> + <Field label="Title"> + <Input value={title} onChange={(e) => setTitle(e.target.value)} aria-label="case title" placeholder="the question, unless named" className="w-56" /> + </Field> + {sources.length > 0 && ( + <Field label="Corpus"> + <Select value={source} onChange={(e) => setSource(e.target.value)} aria-label="corpus"> + {sources.map((s) => ( + <option key={s.handle} value={s.handle}> + {s.label} + {s.detail ? ` — ${s.detail}` : ""} + </option> + ))} + </Select> + </Field> + )} + <Actions error={error}> + <Button type="submit" variant="go" disabled={busy || !query.trim()}> + {busy ? "Opening…" : "Open a case"} + </Button> + <Button type="button" variant="quiet" onClick={onCancel}> + Cancel + </Button> + </Actions> + </form> + ); +} + +// ── An article or a video from a board (R2's hand-off) ────────────────────── + +export function BoardForm({ + to, + cases, + casesError, + initialCase, + onCancel, +}: { + to: "article" | "video"; + cases: CaseSummary[]; + casesError: string | null; + initialCase?: string | null; + onCancel: () => void; +}) { + const router = useRouter(); + const withQuotes = cases.filter((c) => c.quotes > 0); + const [pick, setPick] = useState( + initialCase && cases.some((c) => c.id === initialCase) ? initialCase : (withQuotes[0]?.id ?? cases[0]?.id ?? ""), + ); + const [planning, setPlanning] = useState(false); + const chosen = cases.find((c) => c.id === pick); + if (!cases.length) { + return ( + <p className="m-0 text-[12.5px] text-text-2" data-no-boards=""> + {casesError ? `The boards do not read: ${casesError}` : "No boards yet. Pin quotes from Research to a board, then hand it off here."} + </p> + ); + } + return ( + <> + <form + aria-label={to === "article" ? "article from a board" : "video from a board"} + className="flex flex-wrap items-end gap-x-3 gap-y-2.5" + onKeyDown={escToCancel(onCancel)} + onSubmit={(e) => { + e.preventDefault(); + if (chosen) setPlanning(true); + }} + > + <Field label="Board" hint={chosen ? `${chosen.quotes} ${chosen.quotes === 1 ? "quote" : "quotes"} · ${chosen.sections} ${chosen.sections === 1 ? "section" : "sections"}` : undefined}> + <Select autoFocus value={pick} onChange={(e) => setPick(e.target.value)} aria-label="board" data-board-pick="" className="w-80"> + {cases.map((c) => ( + <option key={c.id} value={c.id}> + {c.title} · {c.quotes} {c.quotes === 1 ? "quote" : "quotes"} + </option> + ))} + </Select> + </Field> + <Actions> + <Button type="submit" variant="go" disabled={!chosen || chosen.quotes === 0}> + {to === "article" ? "Plan the article" : "Plan the video"} + </Button> + <Button type="button" variant="quiet" onClick={onCancel}> + Cancel + </Button> + </Actions> + {chosen && chosen.quotes === 0 && <p className="m-0 basis-full text-[12px] text-muted">That board has no quotes yet.</p>} + </form> + {/* Outside the form: the dialog carries a form of its own (method="dialog"). */} + <HandoffDialog + caseId={pick} + to={planning ? to : null} + onClose={() => setPlanning(false)} + onDone={(href) => { + setPlanning(false); + router.push(href); + }} + /> + </> + ); +} + +// ── A video from an article: the chain over a done iteration ──────────────── + +type IterRow = { n: number; label: string; status: string; hasReport: boolean; reportFrom: number | null; currentReport: boolean; kind: string }; +type ChainView = { steps: { name: string; label: string; status: string; optional: boolean }[]; resumeAt: string | null; job: { id: string; state: string } | null }; + +export function ArticleVideoForm({ + articles, + initialArticle, + onCancel, +}: { + articles: { id: string; title: string; status: string | null }[]; + initialArticle?: string | null; + onCancel: () => void; +}) { + const router = useRouter(); + const [article, setArticle] = useState(initialArticle && articles.some((a) => a.id === initialArticle) ? initialArticle : (articles[0]?.id ?? "")); + const [its, setIts] = useState<IterRow[] | null>(null); + const [n, setN] = useState<number | null>(null); + const [chain, setChain] = useState<ChainView | null>(null); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + + // The article's iterations: those with a report (done) are what a chain runs over. + useEffect(() => { + if (!article) return; + let live = true; + setIts(null); + setN(null); + setChain(null); + setError(null); + fetch(`/api/articles/iterations?article=${encodeURIComponent(article)}`, { cache: "no-store" }) + .then((r) => json<{ iterations: IterRow[] }>(r)) + .then((b) => { + if (!live) return; + const done = b.iterations.filter((it) => it.status === "done" && it.reportFrom !== null); + setIts(done); + setN((done.find((it) => it.currentReport) ?? done[0])?.n ?? null); + }) + .catch((e: Error) => live && setError(e.message)); + return () => { + live = false; + }; + }, [article]); + + // The chain's steps for that iteration, and where a start resumes. + useEffect(() => { + if (!article || n === null) return; + let live = true; + setChain(null); + fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}`, { cache: "no-store" }) + .then((r) => json<{ chain: ChainView }>(r)) + .then((b) => live && setChain(b.chain)) + .catch((e: Error) => live && setError(e.message)); + return () => { + live = false; + }; + }, [article, n]); + + const start = async () => { + if (!article || n === null) return; + setBusy(true); + setError(null); + try { + await json(await fetch("/api/articles/chain", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ article, n }) })); + router.push(articleHref({ site: "articles", id: article }, { tab: "iterations" })); + } catch (e) { + setError((e as Error).message); + setBusy(false); + } + }; + + if (!articles.length) { + return <p className="m-0 text-[12.5px] text-text-2">No article in the store yet. Start one from a question.</p>; + } + const todo = chain ? chain.steps.filter((s) => !s.optional) : []; + const from = chain?.resumeAt ? todo.findIndex((s) => s.name === chain.resumeAt) : -1; + return ( + <form + aria-label="video from an article" + className="flex flex-wrap items-end gap-x-3 gap-y-2.5" + onKeyDown={escToCancel(onCancel)} + onSubmit={(e) => { + e.preventDefault(); + void start(); + }} + > + <Field label="Article"> + <Select autoFocus value={article} onChange={(e) => setArticle(e.target.value)} aria-label="article" className="w-80"> + {articles.map((a) => ( + <option key={a.id} value={a.id}> + {a.title} — {a.id} + </option> + ))} + </Select> + </Field> + <Field label="Iteration"> + <Select value={n ?? ""} onChange={(e) => setN(Number(e.target.value))} aria-label="iteration" disabled={!its?.length}> + {!its && <option value="">reading…</option>} + {its && its.length === 0 && <option value="">none done</option>} + {its?.map((it) => ( + <option key={it.n} value={it.n}> + {it.label} · {it.kind} + {it.currentReport ? " · current" : ""} + </option> + ))} + </Select> + </Field> + <Actions error={error}> + <Button type="submit" variant="go" disabled={busy || n === null || !chain || chain.resumeAt === null || chain.job?.state === "running"}> + {busy ? "Starting…" : "Make the video"} + </Button> + <Button type="button" variant="quiet" onClick={onCancel}> + Cancel + </Button> + </Actions> + {its && its.length === 0 && <p className="m-0 basis-full text-[12px] text-muted">This article has no done iteration with a report: the chain runs over one.</p>} + {chain && ( + <p className="m-0 basis-full text-[12px] text-muted" data-chain-plan={chain.resumeAt ?? "done"}> + {chain.job?.state === "running" + ? "Its chain is running now." + : chain.resumeAt === null + ? "Every step is done; run one again from the article's Iterations tab." + : `${todo.length - Math.max(from, 0)} of ${todo.length} steps to run, from “${todo[Math.max(from, 0)]?.label}”: ${todo + .slice(Math.max(from, 0)) + .map((s) => s.label) + .join(" → ")}`} + </p> + )} + </form> + ); +} diff --git a/umtool/components/shell/AppRail.tsx b/umtool/components/shell/AppRail.tsx @@ -39,7 +39,7 @@ export default async function AppRail({ active }: { active: string }) { <AppNav active={active} /> - <CreateMenu /> + <CreateMenu active={active === "create"} /> <JumpButton /> diff --git a/umtool/components/shell/CreateMenu.tsx b/umtool/components/shell/CreateMenu.tsx @@ -1,52 +1,21 @@ -"use client"; - import Link from "next/link"; -import { useEffect, useRef, useState } from "react"; -import { newArticleHref, projectsHref } from "@/lib/hrefs"; +import { createHref } from "@/lib/hrefs"; -// + Create. Until /create exists (P5) it opens onto today's two doors: a new -// article (/articles/new) and a new project (/projects?new=1 opens the "+ new -// project" form). Inline in the rail, not a popover: the rail scrolls, and a -// popover would be clipped by it. -export default function CreateMenu() { - const [open, setOpen] = useState(false); - const ref = useRef<HTMLDivElement>(null); - useEffect(() => { - if (!open) return; - const away = (e: MouseEvent) => { - if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false); - }; - const key = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false); - document.addEventListener("mousedown", away); - document.addEventListener("keydown", key); - return () => { - document.removeEventListener("mousedown", away); - document.removeEventListener("keydown", key); - }; - }, [open]); +// + Create (canvas `.create`): the rail's one way in to /create, "What are you +// making?" (P5) -- research, an article, a video, a song, each a line there +// with its form. A link, not a menu: the page IS the menu. Its edge is Signal +// while you are on it. ⌘K's create actions open a line of it directly +// (`/create?make=…`). +export default function CreateMenu({ active = false }: { active?: boolean }) { return ( - <div ref={ref} data-rail-create="" className="mx-4 mb-1 mt-2.5"> - <button - type="button" - aria-expanded={open} - onClick={() => setOpen((v) => !v)} - className="flex w-full items-center gap-2 rounded-[3px] border border-seam-2 px-2.5 py-[6px] text-left font-medium text-text hover:border-muted" - > - + Create - <span aria-hidden="true" className="ml-auto text-muted-2"> - {open ? "▾" : "▸"} - </span> - </button> - {open && ( - <div className="mt-1 flex flex-col"> - <Link href={newArticleHref()} onClick={() => setOpen(false)} className="rounded-[3px] px-2.5 py-1 text-[12.5px] text-text-2 hover:bg-panel-2 hover:text-text"> - An article - </Link> - <Link href={projectsHref({ new: true })} onClick={() => setOpen(false)} className="rounded-[3px] px-2.5 py-1 text-[12.5px] text-text-2 hover:bg-panel-2 hover:text-text"> - A project (video, song, sweep) - </Link> - </div> - )} - </div> + <Link + href={createHref()} + prefetch={false} + data-rail-create="" + aria-current={active ? "page" : undefined} + className={`mx-4 mb-1 mt-2.5 flex items-center gap-2 rounded-[3px] border px-2.5 py-[6px] font-medium text-text no-underline hover:border-muted ${active ? "border-signal" : "border-seam-2"}`} + > + + Create + </Link> ); } diff --git a/umtool/components/shell/JumpPalette.tsx b/umtool/components/shell/JumpPalette.tsx @@ -4,12 +4,12 @@ import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { benchHref, + createHref, facesHref, findHref, generationPolicyHref, homeHref, mixHref, - newArticleHref, pileHref, projectsHref, researchHref, @@ -46,7 +46,8 @@ const FIXED: Item[] = [ { id: "projects", section: "Places", label: "Projects", hint: "every project, by folder", href: projectsHref() }, { id: "tools", section: "Places", label: "Tools", hint: "find, mix, song piles, faces, sources", href: toolsHref() }, { id: "system", section: "Places", label: "Settings · system", hint: "tools, disk, index, sources, recent jobs", href: systemHref() }, - { id: "policy", section: "Places", label: "Settings · generation policy", hint: "on the new-article form until /settings/generation", href: generationPolicyHref() }, + { id: "create", section: "Places", label: "Create", hint: "what are you making?", href: createHref() }, + { id: "policy", section: "Places", label: "Settings · generation", hint: "routes, models, caps, the key, today's spend", href: generationPolicyHref() }, { id: "find", section: "Tools", label: "Find", hint: "every occurrence of a word", href: findHref() }, { id: "mix", section: "Tools", label: "Mix", hint: "the mix bench", href: mixHref() }, { id: "song", section: "Tools", label: "Song piles", hint: "sort, salvage, verify, keeps", href: songToolsHref() }, @@ -54,8 +55,15 @@ const FIXED: Item[] = [ { id: "faces", section: "Tools", label: "Faces", hint: "the face judger", href: facesHref() }, { id: "sources", section: "Tools", label: "Sources", hint: "where the palette comes from", href: sourcesHref() }, { id: "bench", section: "Tools", label: "Verdict bench", hint: "could a model propose a verdict", href: benchHref() }, - { id: "new-article", section: "Create", label: "New article", hint: "from a question", href: newArticleHref() }, - { id: "new-project", section: "Create", label: "New project", hint: "a video, a song, a sweep", href: projectsHref({ new: true }) }, + // Each opens one line of /create (P5), its form open. + { id: "new-research", section: "Create", label: "Research a question", hint: "opens a case", href: createHref({ make: "research" }) }, + { id: "new-article", section: "Create", label: "New article", hint: "from a question: a sweep", href: createHref({ make: "article" }) }, + { id: "new-article-board", section: "Create", label: "New article from a board", hint: "a seeded sweep, planned first", href: createHref({ make: "article-board" }) }, + { id: "new-video-article", section: "Create", label: "New video from an article", hint: "the chain over an iteration", href: createHref({ make: "video-article" }) }, + { id: "new-video-board", section: "Create", label: "New video from a board", hint: "a timeline from the pinned cites", href: createHref({ make: "video-board" }) }, + { id: "new-video-recording", section: "Create", label: "New video from a recording", hint: "a URL or channel/id", href: createHref({ make: "video-recording" }) }, + { id: "new-video-report", section: "Create", label: "New video from a sweep report", hint: "a cited report on disk", href: createHref({ make: "video-report" }) }, + { id: "new-song", section: "Create", label: "New song", hint: "a song cut", href: createHref({ make: "song" }) }, ]; const words = (q: string) => q.toLowerCase().split(/\s+/).filter(Boolean); diff --git a/umtool/components/system/ActionPlan.tsx b/umtool/components/system/ActionPlan.tsx @@ -0,0 +1,174 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import type { ActionAnswer, ActionPlanView } from "@/lib/system/plan-types"; + +// --------------------------------------------------------------------------- +// PLAN, THEN CONFIRM for Settings · system's actions (P5) -- the DeletePlan +// pattern (components/DeletePlan.tsx) for a move or a prune: the button asks +// the route for the PLAN (a dry run: what it touches, with sizes, what refuses, +// what is worth knowing), shows it, and acts only on the confirm, whose words +// say what happens ("Move out", "Drop 2 records"). "Keep it" closes the plan +// and nothing was written. A long one starts a umtool job (the rail's Running +// list has it); the page re-reads when it is started. +// +// Labels are contracts (e2e/settings.spec.ts): the region is "plan <subject>" +// holding the lists "touches", "refused" and "worth knowing", and the buttons +// <confirm> (data-plan-confirm) and "Keep it". +// --------------------------------------------------------------------------- + +const fmt = (n: number) => { + if (n < 1024) return `${n} B`; + const u = ["KiB", "MiB", "GiB", "TiB"]; + let v = n / 1024; + let i = 0; + while (v >= 1024 && i < u.length - 1) { + v /= 1024; + i += 1; + } + return `${v.toFixed(v >= 100 ? 0 : 1)} ${u[i]}`; +}; + +type Phase = + | { at: "closed"; done?: string } + | { at: "asking" } + | { at: "plan"; plan: ActionPlanView; error: string | null } + | { at: "working"; plan: ActionPlanView } + | { at: "error"; error: string }; + +async function post(endpoint: string, body: Record<string, unknown>) { + const r = await fetch(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const b = (await r.json().catch(() => ({}))) as Partial<ActionAnswer> & { plan?: ActionPlanView; error?: string }; + return { ok: r.ok, status: r.status, body: b }; +} + +export default function ActionPlan({ + label, + subject, + endpoint, + body, + variant = "outline", +}: { + /** The trigger's words ("Move out", "Prune"). */ + label: string; + /** What it acts on, for the region's name ("index prune", "reports/x out"). */ + subject: string; + endpoint: string; + body: Record<string, unknown>; + variant?: "outline" | "destructive"; +}) { + const router = useRouter(); + const hydrated = useHydrated(); + const [phase, setPhase] = useState<Phase>({ at: "closed" }); + + const ask = async () => { + setPhase({ at: "asking" }); + try { + const r = await post(endpoint, { ...body, dryRun: true }); + if (r.body.plan) setPhase({ at: "plan", plan: r.body.plan, error: null }); + else setPhase({ at: "error", error: r.body.error ?? `HTTP ${r.status}` }); + } catch (e) { + setPhase({ at: "error", error: (e as Error).message }); + } + }; + + const confirm = async (plan: ActionPlanView) => { + setPhase({ at: "working", plan }); + try { + const r = await post(endpoint, body); + if (r.ok && r.body.applied) { + setPhase({ at: "closed", done: r.body.job ? `${r.body.message} — a job, in Running` : r.body.message }); + router.refresh(); + return; + } + setPhase({ at: "plan", plan: r.body.plan ?? plan, error: r.body.error ?? `HTTP ${r.status}` }); + } catch (e) { + setPhase({ at: "plan", plan, error: (e as Error).message }); + } + }; + + if (phase.at === "closed") { + return ( + <span className="inline-flex flex-wrap items-center gap-2"> + <Button size="sm" variant={variant} disabled={!hydrated} onClick={() => void ask()} data-plan-trigger={subject}> + {label} + </Button> + {phase.done && ( + <span role="status" className="text-[12px] text-text-2" data-plan-done={subject}> + {phase.done} + </span> + )} + </span> + ); + } + if (phase.at === "asking") return <span className="text-[12px] text-muted">Reading the plan…</span>; + if (phase.at === "error") { + return ( + <span role="alert" className="flex items-center gap-2 text-[12px] text-reject-text"> + {phase.error} + <Button size="sm" variant="quiet" onClick={() => setPhase({ at: "closed" })}> + Keep it + </Button> + </span> + ); + } + const plan = phase.plan; + return ( + <section + role="region" + aria-label={`plan ${subject}`} + data-plan={plan.action} + data-plan-blocked={plan.blocked ? "yes" : "no"} + className="mt-2 basis-full rounded-[3px] border border-seam-2 bg-ink p-3 text-[12px]" + > + <p className="m-0 font-semibold text-text">{plan.title}</p> + <p className="m-0 mt-0.5 text-text-2">{plan.summary}</p> + {plan.refusals.length > 0 && ( + <ul aria-label="refused" className="mt-1.5 list-disc pl-5 text-reject-text"> + {plan.refusals.map((r, i) => ( + <li key={i}>{r}</li> + ))} + </ul> + )} + {plan.warnings.length > 0 && ( + <ul aria-label="worth knowing" className="mt-1.5 list-disc pl-5 text-doubt-text"> + {plan.warnings.map((w, i) => ( + <li key={i}>{w}</li> + ))} + </ul> + )} + {plan.rows.length > 0 && ( + <ul aria-label="touches" className="mt-1.5 grid max-h-[220px] list-none gap-0.5 overflow-auto p-0"> + {plan.rows.map((r, i) => ( + <li key={`${r.label}-${i}`} data-plan-row={r.label} data-plan-state={r.state ?? ""} className="grid grid-cols-[minmax(0,1fr)_auto] gap-x-3 font-mono text-[11px]"> + <span className="min-w-0 truncate"> + <span className="text-text">{r.label}</span> <span className="text-muted-2">{r.what}</span> + </span> + <span className="num text-meter"> + {r.bytes !== undefined ? `${fmt(r.bytes)}${r.files !== undefined ? ` · ${r.files} files` : ""}` : ""} + </span> + </li> + ))} + </ul> + )} + {phase.at === "plan" && phase.error && ( + <p role="alert" className="m-0 mt-1.5 text-reject-text"> + {phase.error} + </p> + )} + <div className="mt-2.5 flex flex-wrap items-center gap-2"> + {!plan.blocked && ( + <Button size="sm" variant={variant === "destructive" ? "destructive" : "primary"} disabled={phase.at === "working"} onClick={() => void confirm(plan)} data-plan-confirm=""> + {phase.at === "working" ? "Working…" : plan.confirm} + </Button> + )} + <Button size="sm" variant="quiet" onClick={() => setPhase({ at: "closed" })}> + Keep it + </Button> + </div> + </section> + ); +} diff --git a/umtool/components/system/Maintenance.tsx b/umtool/components/system/Maintenance.tsx @@ -0,0 +1,129 @@ +import ActionPlan from "@/components/system/ActionPlan"; +import { Panel } from "@/components/ui/panel"; +import { fmtAgo } from "@/lib/format"; +import type { StorageRow } from "@/lib/system/storage-rows"; + +// --------------------------------------------------------------------------- +// Settings · system's maintenance (P5): what `umtool doctor`, `umtool index` +// and `umtool storage` say and do, on the page. Reading is free; every action +// that changes or moves anything is a plan first (ActionPlan): Confirm, or +// Keep it. Server-rendered; the plans are the client's. +// --------------------------------------------------------------------------- + +type Roots = { + ok: boolean; + reports: { path: string; present: boolean }; + media: { path: string; tiered: boolean; present: boolean; problem: string | null }; + cache: { path: string; present: boolean; index: boolean }; + oldCache: { path: string; present: boolean }; +}; + +function Row({ k, children, bad = false }: { k: string; children: React.ReactNode; bad?: boolean }) { + return ( + <> + <dt className="text-muted">{k}</dt> + <dd className={`m-0 min-w-0 break-all font-mono text-[11.5px] ${bad ? "text-reject-text" : "text-text-2"}`}>{children}</dd> + </> + ); +} + +export function RootsPanel({ roots }: { roots: Roots }) { + return ( + <Panel title="Roots" aside={<span className="text-muted-2">umtool doctor</span>} data-panel="roots" data-roots-ok={roots.ok ? "yes" : "no"}> + <dl className="m-0 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-[12px]"> + <Row k="reports" bad={!roots.reports.present}> + {roots.reports.path} + {roots.reports.present ? "" : " — not there"} + </Row> + <Row k="media" bad={!!roots.media.problem}> + {roots.media.tiered ? roots.media.path : "= reports (UMTOOL_MEDIA_DIR unset): out/ stays in each project"} + {roots.media.problem ? ` — ${roots.media.problem}` : ""} + </Row> + <Row k="cache"> + {roots.cache.path} + {roots.cache.index ? "" : " — no index yet"} + </Row> + {roots.oldCache.present && <Row k="old cache">{roots.oldCache.path} — the cache&apos;s old place, no longer read; derived, safe to delete</Row>} + </dl> + </Panel> + ); +} + +export function IndexPanel({ index }: { index: { ok: boolean; records: number; path: string | null; builtAt: number | null; stale: number } }) { + return ( + <Panel title="Index" aside={<span className="text-muted-2">umtool index</span>} data-panel="index" data-index-records={index.records} data-index-stale={index.stale}> + {index.ok ? ( + <p className="m-0 text-[12.5px] text-text-2"> + <b className="num text-meter">{index.records}</b> records + {index.stale > 0 ? ( + <> + , <b className="num text-meter">{index.stale}</b> for projects that are gone + </> + ) : null} + {index.builtAt ? ` · rebuilt ${fmtAgo(index.builtAt)}` : ""}. A cache of the walk: every read checks its own signature, so deleting it changes nothing but + latency. + </p> + ) : ( + <p className="m-0 text-[12.5px] text-text-2">No index (the lmdb store did not open): a normal state — everything works, just slower.</p> + )} + {index.path && <p className="m-0 mt-1 truncate font-mono text-[11px] text-muted-2">{index.path}</p>} + <div className="mt-2.5 flex flex-wrap items-start gap-2"> + <ActionPlan label="Rebuild…" subject="index rebuild" endpoint="/api/system/index" body={{ action: "rebuild" }} /> + <ActionPlan label="Prune…" subject="index prune" endpoint="/api/system/index" body={{ action: "prune" }} variant="destructive" /> + </div> + </Panel> + ); +} + +const WORD: Record<string, string> = { absent: "none", dir: "here", link: "on media", dangling: "DRIVE MISSING", other: "not a directory" }; + +export function StoragePanel({ rows, tiered, mediaRoot }: { rows: StorageRow[]; tiered: boolean; mediaRoot: string }) { + const outs = rows.filter((r) => r.out !== "absent"); + return ( + <Panel + title="Storage" + aside={<span className="text-muted-2">umtool storage · {tiered ? `media root ${mediaRoot}` : "no media root (UMTOOL_MEDIA_DIR unset)"}</span>} + data-panel="storage" + className="lg:col-span-2 2xl:col-span-3" + > + <div className="mb-2 flex flex-wrap items-start gap-2"> + <ActionPlan label="Move every out/ to the media root…" subject="storage move-out all" endpoint="/api/system/storage" body={{ action: "move-out", all: true }} /> + <ActionPlan label="Move every out/ back…" subject="storage move-back all" endpoint="/api/system/storage" body={{ action: "move-back", all: true }} /> + </div> + {outs.length === 0 && rows.length === 0 ? ( + <p className="m-0 text-[12px] text-muted">No projects.</p> + ) : ( + <ul aria-label="projects' storage" className="m-0 grid max-h-[420px] list-none overflow-auto p-0 text-[12px]"> + {rows.map((r) => ( + <li key={r.id} data-storage-row={r.id} data-out={r.out} className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-seam py-1.5 first:border-t-0"> + <span className="min-w-0 flex-1 truncate font-mono text-[11.5px] text-text">{r.id}</span> + <span className={`text-[11.5px] ${r.out === "dangling" ? "text-reject-text" : "text-muted-2"}`}>out/ {WORD[r.out] ?? r.out}</span> + {r.deliverables && ( + <span className={`text-[11.5px] ${r.deliverables.problem ? "text-reject-text" : "text-muted-2"}`} title={r.deliverables.problem ?? undefined}> + deliverables {r.deliverables.mode ?? "INVALID"} + {r.deliverables.dirs ? ` · ${r.deliverables.dirs}` : ""} + </span> + )} + <span className="flex flex-wrap items-start gap-1.5"> + {tiered && r.out === "dir" && ( + <ActionPlan label="Move out…" subject={`storage move-out ${r.id}`} endpoint="/api/system/storage" body={{ action: "move-out", project: r.id }} /> + )} + {(r.out === "link" || r.out === "dangling") && ( + <ActionPlan label="Move back…" subject={`storage move-back ${r.id}`} endpoint="/api/system/storage" body={{ action: "move-back", project: r.id }} /> + )} + {r.deliverables && (tiered || r.deliverables.mode === "media") && ( + <ActionPlan + label={r.deliverables.mode === "media" ? "Deliverables home…" : "Deliverables to media…"} + subject={`storage deliverables ${r.id}`} + endpoint="/api/system/storage" + body={{ action: "deliverables", project: r.id, to: r.deliverables.mode === "media" ? "local" : "media" }} + /> + )} + </span> + </li> + ))} + </ul> + )} + </Panel> + ); +} diff --git a/umtool/components/ui/lit-list.tsx b/umtool/components/ui/lit-list.tsx @@ -36,6 +36,7 @@ const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable= export function LitList({ label, initial, + columns = false, global = false, onLight, className, @@ -46,6 +47,12 @@ export function LitList({ /** The line lit on load, by index; a line marked `initial` wins over it. */ initial?: number; /** + * The lines sit in more than one column (Create's two, P5): the head follows + * the lit line's left edge as well as its top. Off, the head stays at the + * list's left edge, as every one-column list has it. + */ + columns?: boolean; + /** * `j`/`k` anywhere on the page move this list (when nothing is being typed * in), not only with focus inside it. For the ONE list a page is about. */ @@ -83,9 +90,10 @@ export function LitList({ h.removeAttribute("data-off"); h.style.top = `${r.top - base.top}px`; h.style.height = `${r.height}px`; + if (columns) h.style.left = `${r.left - base.left}px`; // The first placement must not glide in from the top of the list. if (!h.hasAttribute("data-placed")) requestAnimationFrame(() => h.setAttribute("data-placed", "")); - }, [lines]); + }, [lines, columns]); const light = useCallback( (i: number, opts: { focus?: boolean } = {}) => { diff --git a/umtool/e2e/inbox.spec.ts b/umtool/e2e/inbox.spec.ts @@ -184,10 +184,15 @@ test("POST /api/pieces/mute refuses junk", async ({ request }) => { expect((await post({ piece: "p:no-such-project", kind: "unbuilt", muted: true })).status()).toBe(404); }); -test("the Inbox opens the new-project form prefilled from ?from= (the editor's hand-off)", async ({ page }) => { - await page.goto(urls.homeHref({ from: "testchan/vid1" })); - await expect(page.locator("[data-new-from]")).toHaveValue("testchan/vid1"); - await expect(page.locator("[data-new-seed]")).toBeVisible(); +test("the editor's hand-off, /?from=, lands on Create with the recording's form prefilled (P5)", async ({ page }) => { + await page.goto("/?from=testchan%2Fvid1"); + await expect(page).toHaveURL(/\/create\?from=testchan%2Fvid1$/); + const form = page.locator("[data-make-form=video-recording]"); + await expect(form.locator("[data-new-from]")).toHaveValue("testchan/vid1"); + await expect(form.locator("[data-new-seed]")).toBeVisible(); + // The Inbox itself, with no `from`, is not redirected. + await page.goto(urls.homeHref()); + await expect(page).toHaveURL(/\/$/); }); // --------------------------------------------------------------------------- diff --git a/umtool/lib/create.ts b/umtool/lib/create.ts @@ -0,0 +1,87 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { listArticleDirs, listPendingArticles } from "yt-dlp-transcript-common/lib/report/registry"; +import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; +import { readPolicy, readToday, type PolicyView } from "@/lib/articles/generation"; +import { ARTICLES_KEY } from "@/lib/articles/key.mjs"; +import { sitesPaths } from "@/lib/articles/sites"; +import { spendHistory } from "@/lib/create/estimate.mjs"; +import { readPieceGraph } from "@/lib/pieces"; +import { projectRefs } from "@/lib/projects"; +import { makeKinds, sweepReports } from "@/lib/projects/create.mjs"; +import { listCases } from "@/lib/research/boards"; +import { listSources } from "@/lib/research/sources"; +import type { CaseSummary } from "@/lib/research/case-types"; +import type { SourceOption } from "@/lib/research/types"; + +// --------------------------------------------------------------------------- +// What Create (/create, plans/umtool-redesign.md P5) needs to draw its lines +// and open their forms: the policy (the chip, the new-article form), the day's +// spend and the ledger's history (the estimate), the article ids taken, the +// boards, the store's articles (a video from one), the sweep reports on disk, +// the corpora a case may read, and the kinds the scaffolds write. +// +// Every part is read on its own and fails on its own: an editor that does not +// answer costs the policy and the channels, never the page. +// --------------------------------------------------------------------------- + +export type Today = { day: string; usd: number; jobs: number; daily: number }; +export type ScaffoldKind = { id: string; label: string; scaffold: { fields: string[]; brands?: { id: string; label: string }[] } }; +export type StoreArticle = { id: string; title: string; status: string | null }; +export type SweepReport = { project: string; path: string; title: string }; + +export type CreateData = { + policy: PolicyView | null; + policyError: string | null; + today: Today | null; + /** task -> model -> per-job USD, oldest first (lib/create/estimate.mjs). */ + history: Record<string, Record<string, number[]>>; + taken: string[]; + cases: CaseSummary[]; + casesError: string | null; + articles: StoreArticle[]; + reports: SweepReport[]; + sources: SourceOption[]; + kinds: { recording: ScaffoldKind | null; report: ScaffoldKind | null; song: ScaffoldKind | null }; +}; + +const msg = (e: unknown) => (e instanceof Error ? e.message : String(e)); + +export async function readCreate(): Promise<CreateData> { + let policy: PolicyView | null = null; + let policyError: string | null = null; + try { + policy = await readPolicy(); + } catch (e) { + policyError = msg(e); + } + const paths = sitesPaths(); + const [today, rows, taken, cases, graph, refs, sources] = await Promise.all([ + policy ? readToday(policy.generation.caps.daily).catch(() => null) : Promise.resolve(null), + readGenerationUsage(getPaths().generationUsageFile).catch(() => []), + Promise.all([listArticleDirs(paths), listPendingArticles(paths)]).then(([a, b]) => [...a, ...b]).catch(() => [] as string[]), + listCases().then( + (c) => ({ cases: c, error: null as string | null }), + (e) => ({ cases: [] as CaseSummary[], error: msg(e) }), + ), + readPieceGraph().catch(() => null), + projectRefs().catch(() => []), + listSources().catch(() => [] as SourceOption[]), + ]); + const articles: StoreArticle[] = (graph?.pieces ?? []) + .filter((p) => p.kind === "article" && p.site === ARTICLES_KEY && p.report) + .sort((a, b) => b.newestMs - a.newestMs) + .map((p) => ({ id: p.report as string, title: p.title, status: p.status })); + return { + policy, + policyError, + today, + history: spendHistory(rows), + taken, + cases: cases.cases.filter((c) => !c.error), + casesError: cases.error, + articles, + reports: await sweepReports(refs).catch(() => []), + sources, + kinds: makeKinds() as CreateData["kinds"], + }; +} diff --git a/umtool/lib/create/create.test.mjs b/umtool/lib/create/create.test.mjs @@ -0,0 +1,47 @@ +// node --test umtool/lib/create/create.test.mjs +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { policyChip, routeGroups, routeSummary } from "./policy.mjs"; +import { estimateOf, estimateText, spendHistory } from "./estimate.mjs"; + +const TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube"]; +const media = (r) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r }); +const BALANCED = { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...media("local") }; + +test("the balanced preset in one line: grouped by route, drafts as one word", () => { + assert.equal(routeSummary(BALANCED, TASKS), "Claude Code: sweeps · API: report revisions, research · local: video revisions, drafts"); + assert.deepEqual(routeGroups(BALANCED, TASKS).map((g) => g.route), ["code", "api", "local"]); +}); + +test("one route for everything says so; agreeing revisions are one word; split drafts are named", () => { + const api = Object.fromEntries(TASKS.map((t) => [t, "api"])); + assert.equal(routeSummary(api, TASKS), "everything on the API"); + assert.equal(routeSummary(Object.fromEntries(TASKS.map((t) => [t, "local"])), TASKS), "everything local"); + const custom = { ...api, sweep: "code", narrate: "local" }; + assert.equal(routeSummary(custom, TASKS), "Claude Code: sweeps · API: revisions, research, cut drafts, on-screen drafts, teaser drafts, flips drafts, threads drafts, YouTube drafts · local: narration"); +}); + +test("the chip names the preset, or why there is none", () => { + assert.equal(policyChip({ preset: "balanced", routes: BALANCED }, TASKS), "Generation: balanced · Claude Code: sweeps · API: report revisions, research · local: video revisions, drafts"); + assert.equal(policyChip(null), "Generation: the editor did not answer"); +}); + +test("the ledger as per-job spend: rows summed per job under its main model, by task", () => { + const rows = [ + { jobId: "a", task: "sweep", model: "claude-sonnet", usd: 0.4, at: "2026-10-01T00:00:00Z" }, + { jobId: "a", task: "sweep", model: "claude-haiku", usd: 0.02, at: "2026-10-01T00:00:00Z" }, + { jobId: "b", task: "sweep", model: "claude-sonnet", usd: 1.1, at: "2026-10-02T00:00:00Z" }, + { jobId: "c", task: "narrate", model: "claude-sonnet", usd: 0.3, at: "2026-10-02T00:00:00Z" }, + { jobId: "d", task: "research", model: "claude-opus", usd: 2, at: "2026-10-03T00:00:00Z" }, + ]; + assert.deepEqual(spendHistory(rows), { sweep: { "claude-sonnet": [0.42, 1.1] }, research: { "claude-opus": [2] } }); +}); + +test("an estimate: the past runs' typical and most, under the cap; a local model spends nothing", () => { + const h = { sweep: { "claude-sonnet": [0.42, 1.1, 0.5] } }; + const e = estimateOf(h, { task: "sweep", model: "claude-sonnet", cap: 5, local: false }); + assert.deepEqual(e, { kind: "api", model: "claude-sonnet", runs: 3, typical: 0.5, most: 1.1, cap: 5 }); + assert.equal(estimateText(e), "3 earlier runs on claude-sonnet: typical $0.50, most $1.10 · stops at $5.00 (its cap)"); + assert.equal(estimateText(estimateOf(h, { task: "sweep", model: "claude-opus", cap: 3, local: false })), "No earlier run on claude-opus in the ledger · stops at $3.00 (its cap)"); + assert.equal(estimateText(estimateOf(h, { task: "sweep", model: "qwen3:8b", cap: 5, local: true })), "Runs on the local model: no API spend"); +}); diff --git a/umtool/lib/create/estimate.mjs b/umtool/lib/create/estimate.mjs @@ -0,0 +1,85 @@ +// --------------------------------------------------------------------------- +// What a new sweep (or research run) is likely to spend, shown BEFORE it runs +// (plans/umtool-redesign.md, P5: "Article from a question … with the estimate +// shown before it runs"). +// +// There is no price model of a sweep -- how much it reads depends on what the +// question matches -- so the estimate is what such runs HAVE spent: the +// editor's usage ledger (common/controller/generationUsage.ts, one row per +// model per finished API job), summed per job, for the same task and model. +// The cap is the ceiling the editor enforces; a local model spends nothing on +// the API. Said as it is: "2 earlier runs on <model>: typical $0.41, most +// $0.63 · stops at $5.00 (its cap)". +// +// Plain ESM: the server reads the ledger, the client form says the estimate. +// --------------------------------------------------------------------------- + +/** How many of a model's latest jobs an estimate reads. */ +export const HISTORY_RUNS = 20; + +/** + * The ledger as per-job spend: task -> model -> [usd per job], oldest first, + * at most HISTORY_RUNS each. A job's rows (one per model it called) are summed + * under the model of its largest row, which is the job's own model: an API + * sweep's extractor runs on a cheaper model beside it. + * @param {{ jobId: string, task: string, model: string, usd: number, at?: string }[]} rows + * @param {readonly string[]} [tasks] + * @returns {Record<string, Record<string, number[]>>} + */ +export function spendHistory(rows, tasks = ["sweep", "research"]) { + /** @type {Map<string, { task: string, at: string, usd: number, models: Map<string, number> }>} */ + const jobs = new Map(); + for (const r of rows) { + if (!r || !tasks.includes(r.task) || typeof r.usd !== "number" || !r.jobId) continue; + const j = jobs.get(r.jobId) ?? { task: r.task, at: r.at ?? "", usd: 0, models: new Map() }; + j.usd += r.usd; + j.models.set(r.model, (j.models.get(r.model) ?? 0) + r.usd); + if ((r.at ?? "") > j.at) j.at = r.at ?? j.at; + jobs.set(r.jobId, j); + } + /** @type {Record<string, Record<string, number[]>>} */ + const out = {}; + for (const j of [...jobs.values()].sort((a, b) => a.at.localeCompare(b.at))) { + const model = [...j.models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]; + if (!model) continue; + const list = ((out[j.task] ??= {})[model] ??= []); + list.push(Math.round(j.usd * 10_000) / 10_000); + if (list.length > HISTORY_RUNS) list.shift(); + } + return out; +} + +const median = (xs) => { + const s = [...xs].sort((a, b) => a - b); + const m = s.length >> 1; + return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; +}; + +/** + * The estimate for one run. + * @param {Record<string, Record<string, number[]>>} history + * @param {{ task: string, model: string, cap: number | null, local: boolean }} run + * @returns {{ kind: "local" } | { kind: "api", model: string, runs: number, typical: number | null, most: number | null, cap: number | null }} + */ +export function estimateOf(history, { task, model, cap, local }) { + if (local) return { kind: "local" }; + const past = history?.[task]?.[model] ?? []; + return { + kind: "api", + model, + runs: past.length, + typical: past.length ? Math.round(median(past) * 100) / 100 : null, + most: past.length ? Math.max(...past) : null, + cap: typeof cap === "number" && cap > 0 ? cap : null, + }; +} + +const usd = (v) => `$${v.toFixed(2)}`; + +/** The estimate in words. */ +export function estimateText(e) { + if (e.kind === "local") return "Runs on the local model: no API spend"; + const ceiling = e.cap !== null ? ` · stops at ${usd(e.cap)} (its cap)` : ""; + if (!e.runs) return `No earlier run on ${e.model} in the ledger${ceiling}`; + return `${e.runs} earlier ${e.runs === 1 ? "run" : "runs"} on ${e.model}: typical ${usd(e.typical)}, most ${usd(e.most)}${ceiling}`; +} diff --git a/umtool/lib/create/policy.mjs b/umtool/lib/create/policy.mjs @@ -0,0 +1,96 @@ +// --------------------------------------------------------------------------- +// The generation policy in one line (plans/umtool-redesign.md, P5): Create's +// policy chip and the Settings page's head say where each kind of task runs, +// grouped by route -- "Claude Code: sweeps · API: report revisions, research · +// local: video revisions, drafts" for the balanced preset. +// +// Plain ESM, no imports: a server page, a client component and `node --test` +// read the same function. +// --------------------------------------------------------------------------- + +/** How a route is said. */ +export const ROUTE_WORD = { code: "Claude Code", api: "API", local: "local" }; + +/** The media drafts (release 28) and narration: one word, "drafts", when they agree. */ +const DRAFT_TASKS = ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube"]; + +/** One task's word when it is said alone. */ +const TASK_WORD = { + sweep: "sweeps", + "revise-report": "report revisions", + "revise-video": "video revisions", + research: "research", + narrate: "narration", + cut: "cut drafts", + onscreen: "on-screen drafts", + teaser: "teaser drafts", + flips: "flips drafts", + threads: "threads drafts", + youtube: "YouTube drafts", +}; + +/** + * The routes, grouped: `[{ route, words }]` in the order code → api → local, + * each with the tasks that run there in the policy's task order. The draft + * tasks read as "drafts" when they all share a route; the two revisions as + * "revisions" when they do. + * @param {Record<string, string>} routes task -> route + * @param {readonly string[]} [tasks] the order tasks are said in + * @returns {{ route: string, words: string[] }[]} + */ +export function routeGroups(routes, tasks = Object.keys(routes)) { + const present = tasks.filter((t) => typeof routes[t] === "string"); + const drafts = DRAFT_TASKS.filter((t) => present.includes(t)); + const draftsAgree = drafts.length > 1 && drafts.every((t) => routes[t] === routes[drafts[0]]); + const revisionsAgree = present.includes("revise-report") && present.includes("revise-video") && routes["revise-report"] === routes["revise-video"]; + const said = new Set(); + /** @type {Map<string, string[]>} */ + const by = new Map(); + const add = (route, word) => { + if (!by.has(route)) by.set(route, []); + by.get(route).push(word); + }; + for (const t of present) { + if (said.has(t)) continue; + if (draftsAgree && drafts.includes(t)) { + drafts.forEach((d) => said.add(d)); + add(routes[t], "drafts"); + continue; + } + if (revisionsAgree && (t === "revise-report" || t === "revise-video")) { + said.add("revise-report"); + said.add("revise-video"); + add(routes[t], "revisions"); + continue; + } + said.add(t); + add(routes[t], TASK_WORD[t] ?? t); + } + const order = ["code", "api", "local"]; + return [...by.entries()] + .sort((a, b) => (order.indexOf(a[0]) + 99) % 99 - (order.indexOf(b[0]) + 99) % 99) + .map(([route, words]) => ({ route, words })); +} + +/** + * The policy in one line: "Claude Code: sweeps · API: report revisions, + * research · local: video revisions, drafts", or "everything on the API". + * @param {Record<string, string>} routes + * @param {readonly string[]} [tasks] + */ +export function routeSummary(routes, tasks) { + const groups = routeGroups(routes, tasks); + if (groups.length === 1) return `everything ${groups[0].route === "local" ? "local" : `on ${groups[0].route === "api" ? "the API" : "Claude Code"}`}`; + return groups.map((g) => `${ROUTE_WORD[g.route] ?? g.route}: ${g.words.join(", ")}`).join(" · "); +} + +/** + * The chip's words: "balanced · Claude Code: sweeps · …", or the reason the + * policy is unknown. + * @param {{ preset: string, routes: Record<string, string> } | null} generation + * @param {readonly string[]} [tasks] + */ +export function policyChip(generation, tasks) { + if (!generation) return "Generation: the editor did not answer"; + return `Generation: ${generation.preset} · ${routeSummary(generation.routes, tasks)}`; +} diff --git a/umtool/lib/hrefs.test.mjs b/umtool/lib/hrefs.test.mjs @@ -49,7 +49,7 @@ test("articles open in the store or on their site", () => { assert.equal(H.articleHref({ site: "jeralyzer", id: "poker" }), "/sites/jeralyzer/poker"); assert.equal(H.articleEvidenceHref({ site: "jeralyzer", id: "poker" }, { c: "3" }), "/sites/jeralyzer/poker/evidence?c=3"); assert.equal(H.articleCompareHref("poker", { a: "1", b: "2" }), "/articles/poker/compare?a=1&b=2"); - assert.equal(H.newArticleHref(), "/articles/new"); + assert.equal(H.newArticleHref(), "/create?make=article"); }); test("the places: Inbox, Work (and the lists it replaced), Settings", () => { @@ -62,7 +62,7 @@ test("the places: Inbox, Work (and the lists it replaced), Settings", () => { test("every page address the builders make is still served or redirected", async () => { const { REDIRECTS } = await import("../redirects.mjs"); - const old = ["/browse", "/browse/decisions", "/browse/find", "/browse/faces", "/browse/sources", "/browse/trim/:set", "/browse/at", "/browse/:path*", "/articles", "/sites", "/mix", "/bench"]; + const old = ["/browse", "/browse/decisions", "/browse/find", "/browse/faces", "/browse/sources", "/browse/trim/:set", "/browse/at", "/browse/:path*", "/articles", "/sites", "/mix", "/bench", "/articles/new", "/"]; for (const s of old) assert.ok(REDIRECTS.some((r) => r.source === s), s); for (const r of REDIRECTS) assert.equal(r.permanent, false, r.source); }); @@ -81,6 +81,15 @@ test("site pages, tools and piles", () => { assert.equal(H.toolsHref(), "/tools"); assert.equal(H.songToolsHref(), "/tools/song"); assert.equal(H.cutHref("yoshi", "wide", { plan: "p1" }), "/projects/yoshi/wide?plan=p1"); - assert.equal(H.homeHref({ from: "ch/vid" }), "/?from=ch%2Fvid"); assert.equal(H.homeHref(), "/"); }); + +test("Create and Settings (P5)", () => { + assert.equal(H.createHref(), "/create"); + assert.equal(H.createHref({ from: "ch/vid" }), "/create?from=ch%2Fvid"); + assert.equal(H.createHref({ make: "video-board", case: "c1" }), "/create?make=video-board&case=c1"); + for (const m of H.MAKES) assert.ok(H.isMake(m), m); + assert.equal(H.isMake("video"), false); + assert.equal(H.generationPolicyHref(), "/settings/generation"); + assert.equal(H.settingsHref(), "/settings"); +}); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -68,11 +68,12 @@ type NoteOpt = { note?: string | null }; // ── the places ────────────────────────────────────────────────────────────── /** - * The Inbox. `from` is the editor's "make a video" handoff - * (`/?from=<slug>/<id>`, editor VideoPanel/VideoNavStrip): the Inbox opens the - * new-project form prefilled until /create exists (P5). + * The Inbox. `hidden` lists the calls on parked and done pieces, `muted` the + * muted ones. The editor's "make a video" hand-off, `/?from=<slug>/<id>` + * (VideoPanel, VideoNavStrip), is answered by a redirect to Create + * (redirects.mjs, P5) -- build it with createHref({ from }). */ -export function homeHref(q: { from?: string; hidden?: boolean; muted?: boolean } = {}): string { +export function homeHref(q: { hidden?: boolean; muted?: boolean } = {}): string { return withQuery("/", q); } @@ -144,14 +145,43 @@ export function articlesHref(q: ArticlesQuery = {}): string { return workHref({ kind: "article", site: ARTICLES_KEY, ...q }); } -/** A new article (release 27). */ +/** + * What Create makes (P5): each is a line on /create, `?make=` opens its form. + * research a case for a question (R2's board) + * article an article from a question: a sweep, or research first + * article-board an article from a board (R2's hand-off) + * video-article a video from an article: the chain over an iteration + * video-board a video from a board (R2's hand-off) + * video-recording a video from a recording (`from` = <channel>/<id> or a share URL) + * video-report a video from a sweep report on disk + * song a song + */ +export const MAKES = ["research", "article", "article-board", "video-article", "video-board", "video-recording", "video-report", "song"] as const; +export type Make = (typeof MAKES)[number]; +export const isMake = (v: unknown): v is Make => typeof v === "string" && (MAKES as readonly string[]).includes(v); + +/** + * Create: "What are you making?". `make` opens one line's form; `from` is the + * editor's hand-off (a recording, `<channel>/<id>`), which opens "Video from a + * recording" prefilled. `case` preselects a board, `article` an article. + */ +export function createHref(q: { make?: Make; from?: string; case?: string; article?: string } = {}): string { + return withQuery("/create", q); +} + +/** A new article: Create's "Article from a question" (it was /articles/new). */ export function newArticleHref(): string { - return "/articles/new"; + return createHref({ make: "article" }); } -/** Where the generation policy is set today (the new-article form) until /settings/generation (P5). */ +/** Settings: the generation policy -- routes, models, caps, the key, the extractor, today's spend. */ export function generationPolicyHref(): string { - return "/articles/new"; + return "/settings/generation"; +} + +/** Settings: the two pages. */ +export function settingsHref(): string { + return "/settings"; } /** Settings: the machine -- tools, disk, index, sources, deliverables, recent jobs. */ diff --git a/umtool/lib/projects.ts b/umtool/lib/projects.ts @@ -112,6 +112,22 @@ export async function projectRefs(): Promise<ProjectRef[]> { return refs; } +/** + * What `pruneIndex` would drop, read only (Settings · system's plan, P5): the + * index's records for projects the walk no longer finds, against a fresh walk. + */ +export async function indexPrunePlan(): Promise<{ ok: boolean; records: number; path: string | null; builtAt: number | null; stale: { id: string; title: string | null }[] }> { + const ix = await indexHandle(); + const st = ix.stats() as { ok: boolean; records: number; path: string | null; builtAt?: number }; + if (!ix.ok) return { ok: false, records: 0, path: st.path ?? null, builtAt: null, stale: [] }; + CACHES.walk = null; + const live = new Set((await projectRefs()).map((p) => p.id)); + const stale = (ix.recent(10_000) as { id: string; title?: string }[]) + .filter((r) => !live.has(r.id)) + .map((r) => ({ id: r.id, title: typeof r.title === "string" ? r.title : null })); + return { ok: true, records: st.records, path: st.path ?? null, builtAt: st.builtAt || null, stale }; +} + /** Drop index records for projects the walk no longer finds. */ export async function pruneIndex(): Promise<number> { const ix = await indexHandle(); diff --git a/umtool/lib/projects/create.mjs b/umtool/lib/projects/create.mjs @@ -0,0 +1,65 @@ +// --------------------------------------------------------------------------- +// What Create (/create, plans/umtool-redesign.md P5) scaffolds, by KIND -- here +// because a kind id is a literal only lib/projects/ and components/projects/ +// may write (e2e/projects.spec.ts enforces it). The page asks for "the kind a +// video from a recording is" and never learns its name. +// +// video-recording a report video whose `from` is <channel>/<id> or a share URL +// video-report a report video whose `from` is a sweep report (.md) on disk +// song a song +// +// And the sweep reports on disk the "from a sweep report" form offers: every +// project of the sweep-report kind (a cited report, not yet a video), with +// its report's path and title. +// --------------------------------------------------------------------------- +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { kindById } from "./kinds.mjs"; + +const REPORT_VIDEO = "report-video"; +const SONG = "song"; +const SWEEP = "sweep-report"; + +/** The kind each scaffolding make writes. */ +export const MAKE_KIND = { "video-recording": REPORT_VIDEO, "video-report": REPORT_VIDEO, song: SONG }; + +/** + * The kind a make scaffolds, with what its form asks for (the registry's + * `scaffold`), or null when that kind cannot be scaffolded here. + * @param {string} make + * @returns {{ id: string, label: string, scaffold: { fields: string[], brands?: { id: string, label: string }[] } } | null} + */ +export function makeKind(make) { + const id = MAKE_KIND[make]; + const k = id ? kindById(id) : null; + if (!k?.scaffold) return null; + return { id: k.id, label: k.label, scaffold: k.scaffold }; +} + +const SWEEP_RE = /(^|[-_])sweep([-_]report)?\.md$|^sweep-report\.md$/i; + +/** + * The sweep reports a video can be made from: each sweep-report project's + * report file, newest first. + * @param {{ id: string, dir: string, kind: string }[]} refs the project walk + * @returns {Promise<{ project: string, path: string, title: string }[]>} + */ +export async function sweepReports(refs) { + const out = []; + for (const p of refs) { + if (p.kind !== SWEEP) continue; + const names = await readdir(/* turbopackIgnore: true */ p.dir).catch(() => []); + const name = names.find((n) => SWEEP_RE.test(n)); + if (!name) continue; + const file = path.join(/* turbopackIgnore: true */ p.dir, name); + const text = await readFile(/* turbopackIgnore: true */ file, "utf8").catch(() => ""); + const title = text.match(/^#\s+(.+)$/m)?.[1]?.trim() ?? p.id; + out.push({ project: p.id, path: file, title }); + } + return out; +} + +/** The three scaffolding makes' kinds, as Create's page wants them. */ +export function makeKinds() { + return { recording: makeKind("video-recording"), report: makeKind("video-report"), song: makeKind("song") }; +} diff --git a/umtool/lib/settings/settings.test.mjs b/umtool/lib/settings/settings.test.mjs @@ -0,0 +1,31 @@ +// node --test umtool/lib/settings/settings.test.mjs +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { daySpend, recentDays } from "./spend.mjs"; + +const row = (jobId, model, usd, at, day = at.slice(0, 10), task = "sweep") => ({ at, day, jobId, article: "zeta", iteration: 1, task, model, usd, inputTokens: 0, outputTokens: 0 }); + +test("a day's spend, job by job: rows summed per job, newest first, other days left out", () => { + const rows = [ + row("a", "claude-sonnet", 0.4, "2026-10-14T09:00:00Z"), + row("a", "claude-haiku", 0.02, "2026-10-14T09:00:01Z"), + row("b", "claude-opus", 1.1, "2026-10-14T12:00:00Z", undefined, "revise-report"), + row("c", "claude-opus", 3, "2026-10-13T12:00:00Z"), + ]; + const d = daySpend(rows, "2026-10-14"); + assert.equal(d.usd, 1.52); + assert.deepEqual(d.jobs.map((j) => [j.jobId, j.task, j.models, j.usd]), [ + ["b", "revise-report", ["claude-opus"], 1.1], + ["a", "sweep", ["claude-sonnet", "claude-haiku"], 0.42], + ]); + assert.deepEqual(daySpend(rows, "2026-10-01"), { day: "2026-10-01", usd: 0, jobs: [] }); +}); + +test("the last days' totals, a quiet day as 0", () => { + const rows = [row("a", "m", 0.5, "2026-10-14T09:00:00Z"), row("c", "m", 3, "2026-10-12T12:00:00Z")]; + assert.deepEqual(recentDays(rows, "2026-10-14", 3), [ + { day: "2026-10-14", usd: 0.5 }, + { day: "2026-10-13", usd: 0 }, + { day: "2026-10-12", usd: 3 }, + ]); +}); diff --git a/umtool/lib/settings/spend.mjs b/umtool/lib/settings/spend.mjs @@ -0,0 +1,50 @@ +// --------------------------------------------------------------------------- +// A day's API spend, job by job, from the editor's usage ledger +// (common/controller/generationUsage.ts: one row per model per finished Claude +// API job, the day in UTC). /settings/generation says it under the policy: the +// total against the daily cap, and each job -- when it ended, its task, the +// article and iteration, the models it called, what it cost. P2b's rail says +// only the total ("$0.42 today"). +// +// Plain ESM: `node --test` reads it with no bundler. +// --------------------------------------------------------------------------- + +/** + * @param {{ at: string, day: string, jobId: string, article: string, iteration: number, task: string, model: string, usd: number }[]} rows + * @param {string} day YYYY-MM-DD (UTC) + * @returns {{ day: string, usd: number, jobs: { jobId: string, at: string, task: string, article: string, iteration: number, models: string[], usd: number }[] }} + */ +export function daySpend(rows, day) { + /** @type {Map<string, { jobId: string, at: string, task: string, article: string, iteration: number, models: string[], usd: number }>} */ + const jobs = new Map(); + for (const r of rows) { + if (!r || r.day !== day || typeof r.usd !== "number") continue; + const j = jobs.get(r.jobId) ?? { jobId: r.jobId, at: r.at, task: r.task, article: r.article, iteration: r.iteration, models: [], usd: 0 }; + j.usd += r.usd; + if (!j.models.includes(r.model)) j.models.push(r.model); + if (r.at > j.at) j.at = r.at; + jobs.set(r.jobId, j); + } + const list = [...jobs.values()] + .map((j) => ({ ...j, usd: Math.round(j.usd * 10_000) / 10_000 })) + .sort((a, b) => b.at.localeCompare(a.at)); + return { day, usd: Math.round(list.reduce((s, j) => s + j.usd, 0) * 10_000) / 10_000, jobs: list }; +} + +/** + * The last `n` days' totals, newest first, a day with no spend included as 0. + * @param {{ day: string, usd: number }[]} rows + * @param {string} today YYYY-MM-DD + * @param {number} [n] + */ +export function recentDays(rows, today, n = 7) { + const by = new Map(); + for (const r of rows) if (r && typeof r.usd === "number") by.set(r.day, (by.get(r.day) ?? 0) + r.usd); + const out = []; + const t = Date.parse(`${today}T00:00:00Z`); + for (let i = 0; i < n; i++) { + const day = new Date(t - i * 86_400_000).toISOString().slice(0, 10); + out.push({ day, usd: Math.round((by.get(day) ?? 0) * 100) / 100 }); + } + return out; +} diff --git a/umtool/lib/system/actions.ts b/umtool/lib/system/actions.ts @@ -0,0 +1,246 @@ +import { stat } from "node:fs/promises"; +import path from "node:path"; +import { jobView, runningJob, startJob } from "@/lib/jobs"; +import { MEDIA_ROOT, MEDIA_TIERED } from "@/lib/paths"; +import { indexPrunePlan, invalidateProjects, projectRef, projectRefs, pruneIndex } from "@/lib/projects"; +import { MANIFEST_NAME } from "@/lib/projects/report.mjs"; +import { pipelineProcessesFor } from "@/lib/report/busy.mjs"; +import { UMTOOL_DIR, moveDeliverablesSteps } from "@/lib/report/driver.mjs"; +import { moveDeliverables, moveDirToLocal, moveDirToMedia } from "@/lib/report/storage.mjs"; +import type { Step } from "@/lib/trim"; +import type { ActionPlanView, PlanRow } from "./plan-types"; + +// --------------------------------------------------------------------------- +// SETTINGS · SYSTEM's actions (plans/umtool-redesign.md, P5): thin APIs over +// what `umtool` already does from a terminal -- `umtool index --rebuild | +// --prune` and `umtool storage move-out | move-back | deliverables`. Every one +// that changes or moves anything is PLAN, THEN CONFIRM (the DeletePlan +// pattern): the plan is a dry run that measures and refuses and writes +// nothing; the confirm reads the plan again, refuses if it now refuses, and +// only then acts. A long one runs as a umtool job (lib/jobs.ts: one at a time, +// cancellable, in the rail's Running list) through the same CLI a terminal +// would run, so the app and the terminal can never disagree about a move. +// +// index rebuild re-read every project, write its record back (a job) +// index prune drop the records of projects that are gone (in process: +// a few hundred deletes) +// storage move-out <project> | all out/ to the media root, a link left +// storage move-back <project> | all out/ back into the project +// storage deliverables <project> media|local clips/ and share-*/, then the switch +// +// Never against the real reports root in a test: every path here is +// REPORTS_ROOT's, which the e2e suite points at its fixture. +// --------------------------------------------------------------------------- + +export class ActionError extends Error { + constructor( + message: string, + readonly status = 400, + readonly plan: ActionPlanView | null = null, + ) { + super(message); + } +} + +const CLI = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); +const mb = (n: number) => `${(n / 1024 ** 2).toFixed(1)} MB`; + +function cliStep(label: string, args: string[], timeoutMs: number): Step { + return { cwd: UMTOOL_DIR, env: {}, label, argv: ["node", CLI(), ...args], timeoutMs }; +} + +/** Start a job, or say which one is in the way. */ +function runJob(kind: string, steps: Step[], project: string | null) { + const running = runningJob(); + if (running) throw new ActionError(`a job is already running (${running.kind}) — run this when it has finished`, 409); + try { + return jobView(startJob(kind, steps, { project })); + } catch (e) { + throw new ActionError(e instanceof Error ? e.message : String(e), 409); + } +} + +// ── the index ─────────────────────────────────────────────────────────────── + +export type IndexAction = "rebuild" | "prune"; +export const isIndexAction = (v: unknown): v is IndexAction => v === "rebuild" || v === "prune"; + +export async function planIndex(action: IndexAction): Promise<ActionPlanView> { + const ix = await indexPrunePlan(); + const refusals = ix.ok ? [] : ["There is no index (the lmdb store did not open) — nothing to do; everything works without it."]; + if (action === "prune") { + return { + action: "index prune", + title: "Prune the index", + summary: ix.stale.length + ? `Drop ${ix.stale.length} of ${ix.records} records: projects the walk no longer finds. Their folders are gone already; nothing on disk changes.` + : `Nothing to drop: all ${ix.records} records are projects that exist.`, + rows: ix.stale.map((r) => ({ label: r.id, what: r.title ?? "a record with no title", state: "drop" })), + refusals, + warnings: [], + confirm: ix.stale.length ? `Drop ${ix.stale.length} ${ix.stale.length === 1 ? "record" : "records"}` : "Nothing to drop", + job: false, + blocked: !ix.ok || ix.stale.length === 0, + }; + } + invalidateProjects(); + const n = (await projectRefs()).length; + return { + action: "index rebuild", + title: "Rebuild the index", + summary: `Re-read ${n} ${n === 1 ? "project" : "projects"} and write each record back (${ix.records} now). Never needed for correctness — every read checks its own signature — but the first load after a big change is fast instead of merely correct. Runs as a job.`, + rows: ix.path ? [{ label: "store", what: ix.path }] : [], + refusals, + warnings: runningJob() ? [`a job is running (${runningJob()!.kind}): the rebuild cannot start until it has finished`] : [], + confirm: "Rebuild the index", + job: true, + blocked: !ix.ok, + }; +} + +export async function applyIndex(action: IndexAction): Promise<{ message: string; job?: ReturnType<typeof jobView> }> { + const plan = await planIndex(action); + if (plan.blocked) throw new ActionError(plan.refusals[0] ?? plan.summary, 409, plan); + if (action === "prune") { + invalidateProjects(); + const dropped = await pruneIndex(); + return { message: `Dropped ${dropped} ${dropped === 1 ? "record" : "records"}` }; + } + const job = runJob("index rebuild", [cliStep("rebuild the project index", ["index", "--rebuild"], 30 * 60_000)], null); + return { message: "The index rebuild is running", job }; +} + +// ── storage ───────────────────────────────────────────────────────────────── + +export type StorageAction = "move-out" | "move-back" | "deliverables"; +export type StorageInput = { action: StorageAction; project: string | null; all: boolean; to: "media" | "local" | null }; + +export function parseStorage(body: Record<string, unknown>): StorageInput { + const action = body.action; + if (action !== "move-out" && action !== "move-back" && action !== "deliverables") { + throw new ActionError('action is "move-out", "move-back" or "deliverables"'); + } + const all = body.all === true; + const project = typeof body.project === "string" && body.project.trim() ? body.project.trim() : null; + if (!all && !project) throw new ActionError("which project? name one, or all: true"); + if (all && action === "deliverables") throw new ActionError("deliverables move one project at a time"); + const to = body.to === "media" || body.to === "local" ? body.to : null; + if (action === "deliverables" && !to) throw new ActionError('to is "media" or "local"'); + return { action, project: all ? null : project, all, to }; +} + +const hasManifest = (dir: string) => stat(path.join(/* turbopackIgnore: true */ dir, MANIFEST_NAME)).then((s) => s.isFile(), () => false); + +const WORD: Record<string, string> = { + "would-move": "moves", + "would-finish": "finishes a cut move", + already: "already there", + absent: "nothing to move", + busy: "busy — skipped", + failed: "refused", +}; + +export async function planStorage(input: StorageInput): Promise<ActionPlanView> { + const refusals: string[] = []; + const warnings: string[] = []; + const rows: PlanRow[] = []; + const refs = input.all ? await projectRefs() : [await projectRef(input.project as string)]; + if (refs.some((r) => !r)) throw new ActionError(`no such project: ${input.project}`, 404); + const projects = refs as NonNullable<(typeof refs)[number]>[]; + + if (input.action === "deliverables") { + const p = projects[0]; + const to = input.to as "media" | "local"; + if (!(await hasManifest(p.dir))) refusals.push(`${p.id} has no ${MANIFEST_NAME} — deliverables are a report video's`); + const busy = pipelineProcessesFor(p); + if (busy.length) refusals.push(`a pipeline process is working in ${p.id} (pid ${busy.join(", ")}) — run this when it has finished`); + if (!refusals.length) { + try { + const r = await moveDeliverables(p.dir, to, { dryRun: true, writeMode: async () => {} }); + for (const x of r.results as { name: string; state: string; bytes?: number; files?: number; error?: string }[]) { + rows.push({ label: `${x.name}/`, what: x.error ?? WORD[x.state] ?? x.state, state: x.state, bytes: x.bytes, files: x.files }); + if (x.state === "failed") refusals.push(`${x.name}/: ${x.error}`); + } + if (!r.results.length) rows.push({ label: "—", what: "no clips/ and no share-*/ yet; only the switch is set" }); + rows.push({ label: "storage.deliverables", what: `${r.before ?? "local (unset)"} → ${to}`, state: r.before === to ? "already" : "would-move" }); + } catch (e) { + refusals.push(e instanceof Error ? e.message : String(e)); + } + } + const bytes = rows.reduce((n, r) => n + (r.state === "would-move" ? (r.bytes ?? 0) : 0), 0); + return { + action: `storage deliverables ${p.id} ${to}`, + title: `Move ${p.id}'s deliverables to ${to === "media" ? "the media root" : "the project"}`, + summary: `clips/ and every share-*/ ${to === "media" ? `to ${MEDIA_ROOT}` : "back into the project"}, ${mb(bytes)}; then storage.deliverables: ${to}. Copied, mirrored and verified before the original goes. Runs as a job.`, + rows, + refusals, + warnings, + confirm: `Move to ${to}`, + job: true, + blocked: refusals.length > 0, + }; + } + + const toMedia = input.action === "move-out"; + if (toMedia && !MEDIA_TIERED) { + refusals.push("UMTOOL_MEDIA_DIR is not set: there is no media root to move out/ to. Set it to a directory on the media drive (outside the reports root), then restart umtool."); + } + let moving = 0; + let bytes = 0; + if (!refusals.length) { + for (const p of projects) { + const busy = pipelineProcessesFor(p); + if (busy.length) { + rows.push({ label: p.id, what: `a pipeline process is writing it (pid ${busy.join(", ")})`, state: "busy" }); + (input.all ? warnings : refusals).push(`${p.id} is busy (pid ${busy.join(", ")}) — ${input.all ? "it is skipped" : "run this when it has finished"}`); + continue; + } + try { + const r = (await (toMedia ? moveDirToMedia : moveDirToLocal)(p.dir, "out", { dryRun: true })) as { state: string; bytes?: number; files?: number }; + if (input.all && (r.state === "absent" || r.state === "already")) continue; + if (r.state === "would-move" || r.state === "would-finish") { + moving += 1; + bytes += r.bytes ?? 0; + } + rows.push({ label: p.id, what: WORD[r.state] ?? r.state, state: r.state, bytes: r.bytes, files: r.files }); + } catch (e) { + const m = e instanceof Error ? e.message : String(e); + rows.push({ label: p.id, what: m, state: "failed" }); + (input.all ? warnings : refusals).push(`${p.id}: ${m}`); + } + } + } + const subject = input.all ? "every project's out/" : `${projects[0].id}'s out/`; + return { + action: `storage ${input.action} ${input.all ? "--all" : projects[0].id}`, + title: toMedia ? `Move ${subject} to the media root` : `Move ${subject} back into the project`, + summary: refusals.length + ? "Nothing can move." + : moving + ? `${moving} ${moving === 1 ? "project" : "projects"}, ${mb(bytes)}: copied, mirrored and verified ${toMedia ? `under ${MEDIA_ROOT}, then a link left in its place` : "into the project, then the link removed"}. Runs as a job.` + : "Nothing to move: every out/ is already where it should be.", + rows, + refusals, + warnings, + confirm: toMedia ? "Move out" : "Move back", + job: true, + blocked: refusals.length > 0 || moving === 0, + }; +} + +export async function applyStorage(input: StorageInput): Promise<{ message: string; job: ReturnType<typeof jobView> }> { + const plan = await planStorage(input); + if (plan.blocked) throw new ActionError(plan.refusals[0] ?? plan.summary, 409, plan); + if (input.action === "deliverables") { + const p = (await projectRef(input.project as string))!; + const job = runJob(`move deliverables ${p.id} to ${input.to}`, moveDeliverablesSteps(p, input.to as "media" | "local"), p.id); + return { message: `Moving ${p.id}'s deliverables to ${input.to}`, job }; + } + const target = input.all ? "--all" : (input.project as string); + const job = runJob( + `storage ${input.action} ${input.all ? "all" : target}`, + [cliStep(`${input.action} ${input.all ? "every project" : target}`, ["storage", input.action, target], 60 * 60_000)], + input.all ? null : target, + ); + return { message: `${input.action === "move-out" ? "Moving out" : "Moving back"} ${input.all ? "every project" : target}`, job }; +} diff --git a/umtool/lib/system/plan-types.ts b/umtool/lib/system/plan-types.ts @@ -0,0 +1,27 @@ +// The shape of a Settings · system action's plan (lib/system/actions.ts), shared +// with the client's ActionPlan. Types only: safe for a client component. + +/** One thing the action touches: a project, a directory, an index record. */ +export type PlanRow = { label: string; what?: string; state?: string; bytes?: number; files?: number }; + +export type ActionPlanView = { + /** The action as the CLI would say it (`storage move-out reports/x`). */ + action: string; + title: string; + /** One or two sentences: what happens, how big, that it is a job. */ + summary: string; + rows: PlanRow[]; + /** Why it cannot run now. Any refusal blocks the confirm. */ + refusals: string[]; + /** Worth knowing; does not block. */ + warnings: string[]; + /** The confirm button's words ("Move out", "Drop 2 records"). */ + confirm: string; + /** It runs as a umtool job (in the rail's Running list). */ + job: boolean; + /** Nothing to do, or refused: the confirm is not offered. */ + blocked: boolean; +}; + +/** A confirm's answer. */ +export type ActionAnswer = { applied: true; message: string; job?: { id: string; kind: string; state: string } }; diff --git a/umtool/lib/system/roots.mjs b/umtool/lib/system/roots.mjs @@ -0,0 +1,27 @@ +// The roots, as the doctor reports them (`umtool doctor`, /settings/system): +// where projects are read, where their out/ goes, where the cache is -- and a +// cache left where it used to live (under SONG_DATA, before release 17), which +// is derived and safe to delete once `umtool index` has rebuilt the new one. +// +// Shared by the CLI and the app (P5 moved it out of bin/umtool.mjs). +import { CACHE_DIR, INDEX_DIR, MEDIA_ROOT, MEDIA_TIERED, OLD_CACHE_DIR, REPORTS_ROOT } from "../paths.mjs"; +import { measureTree, mediaRootProblem, pathState } from "../report/storage.mjs"; + +/** + * @param {{ measureOld?: boolean }} [opts] `measureOld` false skips sizing the + * old cache (a page render does not walk a tree) + */ +export async function rootsReport({ measureOld = true } = {}) { + const isDir = async (p) => (await pathState(p)).kind === "dir"; + const problem = await mediaRootProblem(); + const oldPresent = OLD_CACHE_DIR !== CACHE_DIR && (await isDir(OLD_CACHE_DIR)); + return { + ok: !problem, + reports: { path: REPORTS_ROOT, present: await isDir(REPORTS_ROOT) }, + media: { path: MEDIA_ROOT, tiered: MEDIA_TIERED, present: await isDir(MEDIA_ROOT), problem }, + cache: { path: CACHE_DIR, present: await isDir(CACHE_DIR), index: await isDir(INDEX_DIR) }, + oldCache: oldPresent + ? { path: OLD_CACHE_DIR, present: true, ...(measureOld ? { bytes: (await measureTree(OLD_CACHE_DIR)).bytes } : {}) } + : { path: OLD_CACHE_DIR, present: false }, + }; +} diff --git a/umtool/lib/system/storage-rows.ts b/umtool/lib/system/storage-rows.ts @@ -0,0 +1,36 @@ +import { stat } from "node:fs/promises"; +import path from "node:path"; +import { projectRefs } from "@/lib/projects"; +import { MANIFEST_NAME } from "@/lib/projects/report.mjs"; +import { deliverablesProblems, deliverablesState, outDirState } from "@/lib/report/storage.mjs"; + +// Where every project's bulk is, for Settings · system's Storage panel (P5): +// `umtool storage`'s table. out/ for every project; the deliverables (clips/, +// share-*/ and the switch) for one with a manifest. One lstat per name. + +export type StorageRow = { + id: string; + out: "absent" | "dir" | "link" | "dangling" | "other"; + deliverables: { mode: "local" | "media" | null; dirs: string; problem: string | null } | null; +}; + +const isFile = (p: string) => stat(p).then((s) => s.isFile(), () => false); + +export async function storageRows(): Promise<StorageRow[]> { + const refs = await projectRefs(); + return Promise.all( + refs.map(async (p) => { + const out = (await outDirState(p.dir)).state as StorageRow["out"]; + let deliverables: StorageRow["deliverables"] = null; + if (await isFile(path.join(/* turbopackIgnore: true */ p.dir, MANIFEST_NAME))) { + const d = await deliverablesState(p.dir); + deliverables = { + mode: d.mode, + dirs: d.dirs.map((x: { name: string; state: string }) => `${x.name}${x.state === "link" ? "→media" : x.state === "dangling" ? " MISSING" : ""}`).join(" "), + problem: deliverablesProblems(d)[0] ?? null, + }; + } + return { id: p.id, out, deliverables }; + }), + ); +} diff --git a/umtool/redirects.mjs b/umtool/redirects.mjs @@ -39,14 +39,21 @@ * }} RedirectRow */ -// Not here yet, by phase: `/?from=` → `/create?from=` and `/articles/new` → -// `/create?make=article` (P5, when /create exists -- until then the Inbox -// answers `?from=` itself); `/drafts` → `/` (P6 deletes the page). +// Not here yet, by phase: `/drafts` → `/` (P6 deletes the page; until then +// it redirects to Create's new article by itself). const p3 = (source, destination) => ({ source, destination, permanent: false, phase: "P3" }); +const p5 = (source, destination, extra = {}) => ({ source, destination, permanent: false, ...extra, phase: "P5" }); /** @type {RedirectRow[]} */ export const REDIRECTS = [ + // The editor's "make a video" hand-off (VideoPanel, VideoNavStrip link + // `<umtool>/?from=<slug>/<id>`): only when the query HAS `from`, so the Inbox + // itself is untouched. The query is passed through, so it lands on + // /create?from=<slug>/<id>, which opens "Video from a recording" prefilled. + p5("/", "/create", { has: [{ type: "query", key: "from" }] }), + // The new-article form is Create's "Article from a question". + p5("/articles/new", "/create?make=article"), // The project list became Work; the decision list became the Inbox. p3("/browse", "/work"), p3("/browse/decisions", "/"),