Archilyzer · Source

archilyzer

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

commit ee19da711b740b48e70228781f90df2575ca83cb
parent cb8ba813156c6e35de9314ea5919519a35ffedb9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 02:22:29 -0400

umtool: P3 URLs, Inbox, rail places and the ⌘K palette

/browse/<path> moves to /projects/<path>, its tools to /tools/{find,faces,
sources,trim}, /mix to /tools/mix, the song piles to /tools/song/<mode>; the
redirect table answers every old address (307). lib/hrefs.ts builders emit the
new addresses; RESERVED_BROWSE is ["at"]. / is the Inbox over readInbox();
the rail is Inbox · Research · Work · Tools · Settings with counts, and ⌘K
jumps to any piece, place, tool or create action.

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

Diffstat:
Dumtool/app/[mode]/page.tsx | 44--------------------------------------------
Aumtool/app/api/jump/route.ts | 24++++++++++++++++++++++++
Mumtool/app/api/pieces/lifecycle/route.ts | 2++
Aumtool/app/api/rail/route.ts | 12++++++++++++
Mumtool/app/articles/[report]/evidence/page.tsx | 2+-
Mumtool/app/articles/[report]/page.tsx | 4++--
Mumtool/app/articles/new/page.tsx | 2+-
Dumtool/app/browse/[...path]/page.tsx | 88-------------------------------------------------------------------------------
Dumtool/app/browse/at/page.tsx | 53-----------------------------------------------------
Dumtool/app/browse/decisions/page.tsx | 199-------------------------------------------------------------------------------
Dumtool/app/browse/faces/page.tsx | 85-------------------------------------------------------------------------------
Dumtool/app/browse/find/page.tsx | 261-------------------------------------------------------------------------------
Dumtool/app/browse/page.tsx | 249-------------------------------------------------------------------------------
Dumtool/app/browse/sources/page.tsx | 135-------------------------------------------------------------------------------
Dumtool/app/browse/trim/[set]/page.tsx | 48------------------------------------------------
Mumtool/app/globals.css | 59++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/app/layout.tsx | 3+++
Mumtool/app/page.tsx | 239+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Aumtool/app/projects/[...path]/page.tsx | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/projects/at/page.tsx | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/projects/page.tsx | 256+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/sites/[site]/[report]/evidence/page.tsx | 2+-
Mumtool/app/sites/[site]/[report]/page.tsx | 2+-
Mumtool/app/sites/[site]/page.tsx | 6+++---
Aumtool/app/tools/faces/page.tsx | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/tools/find/page.tsx | 261+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Rumtool/app/mix/page.tsx -> umtool/app/tools/mix/page.tsx | 0
Aumtool/app/tools/song/[mode]/page.tsx | 44++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/tools/sources/page.tsx | 135+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/tools/trim/[set]/page.tsx | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/AppNav.tsx | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------
Mumtool/components/NewProjectMenu.tsx | 4++--
Mumtool/components/ProvenancePanel.tsx | 4++--
Mumtool/components/ShortlistBar.tsx | 2+-
Mumtool/components/ThumbBench.tsx | 2+-
Mumtool/components/articles/AddToVideo.tsx | 2+-
Mumtool/components/articles/ArticlePage.tsx | 4++--
Mumtool/components/articles/ArticleTable.tsx | 4++--
Aumtool/components/dashboard/InboxList.tsx | 204+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/dashboard/Lifecycle.tsx | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/dashboard/ResumeChip.tsx | 23++++++++++++++---------
Mumtool/components/projects/ClaimBench.tsx | 4++--
Mumtool/components/projects/ClipBench.tsx | 12++++++------
Mumtool/components/projects/ClipBenchPage.tsx | 2+-
Mumtool/components/projects/CutPage.tsx | 6+++---
Mumtool/components/projects/DeleteProject.tsx | 2+-
Mumtool/components/projects/DeliverSection.tsx | 6+++---
Mumtool/components/projects/ProjectGrid.tsx | 2+-
Mumtool/components/projects/SongProject.tsx | 4++--
Mumtool/components/projects/SweepProject.tsx | 4++--
Mumtool/components/projects/TakesPage.tsx | 2+-
Mumtool/components/shell/AppRail.tsx | 20+++++++-------------
Mumtool/components/shell/CreateMenu.tsx | 6+++---
Aumtool/components/shell/JumpButton.tsx | 19+++++++++++++++++++
Aumtool/components/shell/JumpPalette.tsx | 244+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/shell/RailCount.tsx | 40++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/activity.ts | 4++--
Mumtool/lib/context.ts | 2+-
Mumtool/lib/dashboard.ts | 2+-
Mumtool/lib/decisions.ts | 6+++---
Mumtool/lib/hrefs.ts | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Aumtool/lib/inbox/headline.mjs | 41+++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/inbox/headline.test.mjs | 31+++++++++++++++++++++++++++++++
Mumtool/lib/last-page.ts | 12++++++------
Aumtool/lib/machine.ts | 39+++++++++++++++++++++++++++++++++++++++
Mumtool/lib/mix-preset.ts | 2+-
Mumtool/lib/pieces.ts | 11+++++++++--
Mumtool/lib/projects.ts | 11++++++-----
Mumtool/lib/projects/core.mjs | 2+-
Mumtool/lib/projects/kinds.mjs | 13++++++++-----
Mumtool/lib/projects/report.mjs | 6+++---
Mumtool/lib/projects/scaffold-song.ts | 2+-
Mumtool/lib/projects/scaffold.ts | 2+-
Aumtool/lib/rail.ts | 40++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/spec.ts | 2+-
Aumtool/lib/work.ts | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/work/facets.mjs | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/work/facets.test.mjs | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/next.config.ts | 2+-
Mumtool/redirects.mjs | 32++++++++++++++++++++++++++++++--
80 files changed, 2649 insertions(+), 1403 deletions(-)

diff --git a/umtool/app/[mode]/page.tsx b/umtool/app/[mode]/page.tsx @@ -1,44 +0,0 @@ -import { notFound } from "next/navigation"; -import { loadClipList } from "@/lib/clips"; -import { isMode } from "@/lib/types"; -import { CURATED, COMPOUNDS, readVocab } from "@/lib/vocab"; -import { REASONS, OTHER_CODE } from "../../song/reasons.mjs"; -import Deck from "@/components/Deck"; -import AppRail from "@/components/shell/AppRail"; - -export const dynamic = "force-dynamic"; - -export default async function ModePage({ - params, - searchParams, -}: { - params: Promise<{ mode: string }>; - searchParams: Promise<{ limit?: string; only?: string }>; -}) { - const { mode } = await params; - if (!isMode(mode)) notFound(); - const { limit, only } = await searchParams; - - const page = await loadClipList({ - mode, - limit: Math.max(1, Number(limit ?? 200)), - // ?only=key,key -- look at named clips whatever pile they are in, including - // rejected ones. Six clips in the last pass were rejected for the window - // rather than for the clip, and nothing would otherwise offer them again. - only: only?.split(",").map((s) => s.trim()).filter(Boolean), - }); - const custom = await readVocab(); - - // The deck is a client component and the rail reads the server, so the rail - // is rendered here and the deck draws only its own head (AppHeader). - return ( - <> - <AppRail active={mode} /> - <Deck - page={page} - vocab={{ curated: CURATED, compounds: COMPOUNDS, custom }} - reasons={{ bad: REASONS.bad, dirty: REASONS.dirty, other: OTHER_CODE }} - /> - </> - ); -} diff --git a/umtool/app/api/jump/route.ts b/umtool/app/api/jump/route.ts @@ -0,0 +1,24 @@ +import { listPieces } from "@/lib/pieces"; + +export const dynamic = "force-dynamic"; + +// What the ⌘K palette can jump to that is not a fixed place: every piece, as +// { id, title, href, kind, stage, lifecycle }. The places, tools and create +// actions are the palette's own (components/shell/JumpPalette.tsx). +export async function GET() { + const pieces = await listPieces(); + return Response.json( + { + pieces: pieces.map((p) => ({ + id: p.id, + title: p.title, + href: p.href, + kind: p.kind, + site: p.site, + stage: p.stage, + lifecycle: p.lifecycle, + })), + }, + { headers: { "cache-control": "no-store" } }, + ); +} diff --git a/umtool/app/api/pieces/lifecycle/route.ts b/umtool/app/api/pieces/lifecycle/route.ts @@ -1,5 +1,6 @@ import { isLifecycleState, LifecycleError, setLifecycle } from "@/lib/lifecycle"; import { parsePieceId, readPieceGraph } from "@/lib/pieces"; +import { clearRailCounts } from "@/lib/rail"; export const dynamic = "force-dynamic"; @@ -30,6 +31,7 @@ export async function POST(request: Request) { } try { const entry = await setLifecycle(body.piece as string, body.state, "operator"); + clearRailCounts(); return Response.json({ piece: entry.id, state: entry.state, at: entry.at, by: entry.by ?? null }, { headers: NO_STORE }); } catch (err) { if (err instanceof LifecycleError) return fail((err as LifecycleError & { status: number }).status, err.message); diff --git a/umtool/app/api/rail/route.ts b/umtool/app/api/rail/route.ts @@ -0,0 +1,12 @@ +import { railCounts } from "@/lib/rail"; + +export const dynamic = "force-dynamic"; + +// The rail's counts: { inbox, work } (lib/rail.ts). Memoised a few seconds. +export async function GET() { + try { + return Response.json(await railCounts(), { headers: { "cache-control": "no-store" } }); + } catch (err) { + return Response.json({ error: (err as Error).message }, { status: 500, headers: { "cache-control": "no-store" } }); + } +} diff --git a/umtool/app/articles/[report]/evidence/page.tsx b/umtool/app/articles/[report]/evidence/page.tsx @@ -14,5 +14,5 @@ export default async function StoreEvidencePage({ }) { const { report: reportId } = await params; const { c } = await searchParams; - return <EvidencePage site={ARTICLES_KEY} reportId={reportId} c={c} crumbs={[{ href: "/articles", label: "articles" }]} />; + return <EvidencePage site={ARTICLES_KEY} reportId={reportId} c={c} crumbs={[{ href: "/work?kind=article", label: "articles" }]} />; } diff --git a/umtool/app/articles/[report]/page.tsx b/umtool/app/articles/[report]/page.tsx @@ -24,8 +24,8 @@ export default async function StoreArticlePage({ site={ARTICLES_KEY} reportId={reportId} sp={sp} - home={{ href: "/articles", label: "articles" }} - crumbs={[{ href: "/articles", label: "articles" }]} + home={{ href: "/work?kind=article", label: "articles" }} + crumbs={[{ href: "/work?kind=article", label: "articles" }]} published={published} /> ); diff --git a/umtool/app/articles/new/page.tsx b/umtool/app/articles/new/page.tsx @@ -21,7 +21,7 @@ export default async function NewArticlePage() { const taken = [...(await listArticleDirs(paths)), ...(await listPendingArticles(paths))]; return ( <div className="flex h-full flex-col"> - <BrowseHeader active="articles" crumbs={[{ label: "articles", href: "/articles" }, { label: "new" }]} /> + <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> diff --git a/umtool/app/browse/[...path]/page.tsx b/umtool/app/browse/[...path]/page.tsx @@ -1,88 +0,0 @@ -import Link from "next/link"; -import { notFound } from "next/navigation"; -import BrowseHeader from "@/components/BrowseHeader"; -import ProjectView from "@/components/projects/ProjectView"; -import ProjectGrid from "@/components/projects/ProjectGrid"; -import { listProjects, resolveProjectPath } from "@/lib/projects"; - -export const dynamic = "force-dynamic"; - -// --------------------------------------------------------------------------- -// Everything below /browse that is not a tool page. -// -// This replaced app/browse/[song]/ rather than joining it: two dynamic segments -// at the same level is a Next routing conflict, so it is a delete-and-move. The -// song pages themselves are unchanged -- they moved to components/projects/ and -// are handed an id instead of awaiting params. /browse/yoshi/wide is still the -// same URL and still renders the same page. -// -// Resolution is LONGEST-PREFIX: a project id is a path, so `a/b` being a project -// must not stop `a/b/c` from being one too. Whatever is left over is a VIEW, and -// which views exist is the kind's business, not this file's. -// --------------------------------------------------------------------------- - -export default async function BrowsePathPage({ - params, - searchParams, -}: { - params: Promise<{ path?: string[] }>; - searchParams: Promise<Record<string, string | undefined>>; -}) { - const { path: segments = [] } = await params; - const search = await searchParams; - const resolved = await resolveProjectPath(segments); - if (!resolved) notFound(); - - if (resolved.project) { - return <ProjectView project={resolved.project} rest={resolved.rest} search={search} />; - } - - // Two projects answer to the same bare name. Which one you meant is not - // guessable, and guessing is how a link quietly starts pointing at the wrong - // thing -- so the page says so and offers both canonical paths. - if ("ambiguous" in resolved && resolved.ambiguous) { - return ( - <div className="flex h-full flex-col"> - <BrowseHeader - crumbs={[{ href: "/browse", label: "projects" }, { label: segments.join("/") }]} - note={`${resolved.ambiguous.length} projects answer to that name`} - /> - <main className="deck-main flex-1 p-4"> - <p className="mb-2 text-[12px] text-[var(--color-dim)]"> - <code className="font-mono">{segments[0]}</code> is the name of more than one project, - so it cannot be a shortcut to any of them. Use a full path: - </p> - <ul className="space-y-1"> - {resolved.ambiguous.map((p) => ( - <li key={p.id}> - <Link - href={`/browse/${p.id}${segments.slice(1).map((s) => `/${s}`).join("")}`} - className="font-mono text-[12px] ink-link" - > - /browse/{p.id} - </Link> - </li> - ))} - </ul> - </main> - </div> - ); - } - - // A folder: the same grid, filtered to what is under it. - const folder = resolved.folder; - if (!folder) notFound(); - const all = await listProjects(); - const mine = all.filter((p) => p.id.startsWith(`${folder.path}/`)); - return ( - <div className="flex h-full flex-col"> - <BrowseHeader - crumbs={[{ href: "/browse", label: "projects" }, { label: folder.label }]} - note={`${mine.length} project${mine.length === 1 ? "" : "s"}`} - /> - <main className="deck-main flex-1 p-4"> - <ProjectGrid projects={mine} /> - </main> - </div> - ); -} diff --git a/umtool/app/browse/at/page.tsx b/umtool/app/browse/at/page.tsx @@ -1,53 +0,0 @@ -import Link from "next/link"; -import { notFound } from "next/navigation"; -import ProjectView from "@/components/projects/ProjectView"; -import { projectRefs } from "@/lib/projects"; - -export const dynamic = "force-dynamic"; - -// --------------------------------------------------------------------------- -// The escape hatch for a project that cannot be reached at its own URL. -// -// Two ways that happens, and both used to fail silently. A project whose first -// path segment is a tool page name -- `find`, `trim`, `decisions` -- can never -// win the route, because a static segment beats a dynamic one; it was listed, -// linked, and the link rendered the phrase console. And a project whose name -// isSegment() dislikes (a space is enough) simply vanished from the listing. -// -// `?path=` is validated by MEMBERSHIP of the current scan, not by inspecting the -// string: it either is one of the projects the walk found or it is a 404. That -// is the same rule every other name that crosses the wire in this app follows, -// and it is why this page cannot be turned into a file reader. -// --------------------------------------------------------------------------- - -export default async function AtPage({ - searchParams, -}: { - searchParams: Promise<Record<string, string | undefined>>; -}) { - const search = await searchParams; - const wanted = search.path; - const project = wanted ? (await projectRefs()).find((p) => p.id === wanted) : null; - if (!project) notFound(); - - const why = - project.routing === "shadowed" - ? `/browse/${project.id.split("/")[0]} is a tool page, so this project can never be opened at its own URL. Rename the directory, or work here.` - : project.routing === "unroutable" - ? "This directory's name cannot be a URL segment, so it has no address of its own. Rename it to letters, digits, dots, dashes and underscores to give it one." - : null; - - return ( - <> - {why && ( - <div className="border-b border-[var(--color-bad)] bg-[color-mix(in_srgb,var(--color-bad)_10%,transparent)] px-4 py-2 text-[12px] text-[var(--color-bad)]"> - {why}{" "} - <Link href="/browse" className="underline"> - every project - </Link> - </div> - )} - <ProjectView project={project} rest={[]} search={search} /> - </> - ); -} diff --git a/umtool/app/browse/decisions/page.tsx b/umtool/app/browse/decisions/page.tsx @@ -1,199 +0,0 @@ -import Link from "next/link"; -import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; -import BrowseHeader from "@/components/BrowseHeader"; -import CopyButton from "@/components/CopyButton"; -import { - SEVERITIES, - countBySeverity, - openCount, - type Decision, - type Severity, -} from "@/lib/decisions"; -import { openDecisions } from "@/lib/projects"; -import { fmtAgo } from "@/lib/format"; -import { decisionsHref } from "@/lib/hrefs"; -import { LitList } from "@/components/ui/lit-list"; -import { LitGroup, LitLine } from "@/components/ui/lit-line"; -import { Toolbar, ToolbarGroup } from "@/components/ui/toolbar"; -import { EmptyState } from "@/components/ui/empty-state"; - -export const dynamic = "force-dynamic"; - -// A STATIC segment under app/browse/, so it wins over app/browse/[song]/ -- -// which would otherwise catch /browse/decisions, fail readSong() and 404. Same -// trick /browse itself plays against app/[mode]/. The e2e suite asserts it, -// because when this regresses the page still renders perfectly in isolation and -// only the URL stops working. -// -// The filters are links that change searchParams; nothing here changes -// without a navigation. The list is the page's one LIT LIST (components/ui/ -// lit-list.tsx): one line per decision, grouped by project, `j`/`k` from -// anywhere on the page -- the shape the Inbox takes in P3. - -// The three severities ARE three badge variants, one for one, on the filter -// chips. That is not a coincidence to be tidied away: the palette reserves its -// hues for verdicts, and a severity is the closest thing this list has to one. -// On a line it is said the verdict way, glyph and word (Severity below). -const TONE: Record<Severity, BadgeVariants["variant"]> = { - blocking: "blocking", - open: "open", - info: "info", -}; - -export default async function DecisionsPage({ - searchParams, -}: { - searchParams: Promise<{ severity?: string; kind?: string; project?: string }>; -}) { - const { severity, kind, project } = await searchParams; - const all = await openDecisions(); - - const items = all.filter( - (d) => - (!severity || d.severity === severity) && - (!kind || d.kind === kind) && - (!project || d.project === project), - ); - - const counts = countBySeverity(all); - const kinds = [...new Set(all.map((d) => d.kind))].sort(); - const projects = [...new Set(all.map((d) => d.project))].sort(); - const byProject = new Map<string, Decision[]>(); - for (const d of items) { - const list = byProject.get(d.project); - if (list) list.push(d); - else byProject.set(d.project, [d]); - } - - const q = (next: Partial<{ severity: string; kind: string; project: string }>) => - decisionsHref({ severity, kind, project, ...next }); - - return ( - <div className="flex h-full flex-col"> - <BrowseHeader - active="decisions" - crumbs={[{ href: "/browse", label: "projects" }, { label: "decisions" }]} - note={`${openCount(all)} waiting · ${all.length - openCount(all)} for information`} - /> - - <Toolbar aria-label="Filters"> - <ToolbarGroup label="Severity"> - <Chip href={q({ severity: "" })} on={!severity} label={`all ${all.length}`} /> - {SEVERITIES.map((s) => ( - <Chip - key={s} - href={q({ severity: s })} - on={severity === s} - label={`${s} ${counts[s]}`} - tone={TONE[s]} - /> - ))} - </ToolbarGroup> - <div className="ml-auto"> - <CopyButton - label="copy the whole picture" - title="every project as markdown — including this list" - url="/api/browse/context" - /> - </div> - <ToolbarGroup label="Kind" className="basis-full"> - <Chip href={q({ kind: "" })} on={!kind} label="all" /> - {kinds.map((k) => ( - <Chip key={k} href={q({ kind: k })} on={kind === k} label={k} /> - ))} - </ToolbarGroup> - <ToolbarGroup label="Project" className="basis-full"> - <Chip href={q({ project: "" })} on={!project} label="all" /> - {projects.map((p) => ( - <Chip key={p} href={q({ project: p })} on={project === p} label={p} /> - ))} - </ToolbarGroup> - </Toolbar> - - <main className="deck-main flex-1 p-4"> - {items.length === 0 ? ( - <EmptyState - title={all.length === 0 ? "Nothing undecided" : "Nothing matches that filter"} - > - {all.length === 0 - ? "Every cut ships, every live variant is judged, every recipe still describes its file." - : null} - </EmptyState> - ) : ( - <LitList label="Decisions" global> - {[...byProject.entries()].map(([id, list]) => ( - <LitGroup - key={id} - data-project={id} - title={ - <Link - // An article's notes are listed under its page's path - // (lib/decisions.ts noteDecisions), not a project's. - href={id.startsWith("sites/") ? `/${id}` : `/browse/${id}`} - className="font-mono text-[13px] normal-case tracking-normal text-text hover:underline" - > - {id} - </Link> - } - count={list.filter((d) => d.severity !== "info").length} - note={`waiting of ${list.length}`} - > - {list.map((d, i) => ( - <LitLine - key={`${d.kind}-${d.target}-${i}`} - id={`${d.project}:${d.kind}:${d.target}`} - data-decision={d.kind} - data-severity={d.severity} - data-target={d.target} - className="grid grid-cols-[86px_minmax(0,1fr)_auto_auto] items-baseline gap-x-3.5" - > - <Severity s={d.severity} /> - <span className="min-w-0 truncate"> - <Link href={d.href} className="font-mono text-[12px] text-inherit underline-offset-2 hover:underline"> - {d.target} - </Link> - <span className="ml-2 text-[12.5px]">{d.why}</span> - </span> - <span className="font-mono text-[11px] text-muted-2">{d.kind}</span> - <span className="num text-[11px] text-muted-2">{fmtAgo(d.at)}</span> - </LitLine> - ))} - </LitGroup> - ))} - </LitList> - )} - </main> - </div> - ); -} - -/** A severity the verdict way: glyph and word, the glyph in the colour. */ -function Severity({ s }: { s: Severity }) { - if (s === "info") return <span className="verdict text-muted">· info</span>; - return <span className="verdict" data-verdict={s === "blocking" ? "reject" : "doubt"}>{s}</span>; -} - -function Chip({ - href, - on, - label, - tone, -}: { - href: string; - on: boolean; - label: string; - tone?: BadgeVariants["variant"]; -}) { - return ( - <Link - href={href} - // Set by hand, not by the variant. It is what the e2e suite asserts on, - // and it is the actual accessibility statement -- the colour is only the - // visible half of it. - aria-current={on ? "true" : undefined} - className={badgeVariants({ variant: on ? "on" : (tone ?? "neutral") })} - > - {label} - </Link> - ); -} diff --git a/umtool/app/browse/faces/page.tsx b/umtool/app/browse/faces/page.tsx @@ -1,85 +0,0 @@ -import BrowseHeader from "@/components/BrowseHeader"; -import FaceDeck from "@/components/FaceDeck"; -import { faceQueue, readFaceVerdicts, rejectedVideos } from "@/lib/faces"; - -export const dynamic = "force-dynamic"; - -// THE FACE JUDGER: every corner that has ever been cut into a cover, one at a -// time, with the crop as something you can see and move. -// -// A STATIC segment under app/browse/, so it wins over app/browse/[song]/ -- -// which would otherwise catch /browse/faces, fail readSong() and 404. The same -// trap /browse/decisions and /browse/find both document, and the suite asserts -// it here too, because when this regresses the page still renders perfectly in -// isolation and only the URL stops working. -// -// It is NOT a tenth nav item. AppNav is at nine and says why: a tenth wraps the -// header on a laptop, and a nav that wraps stops reading as one row of places. -// This is reached from the cover-art bench on a song page -- which is where -// somebody is looking at the four faces when they notice one is wrong. -// -// The page reads the queue directly rather than fetching its own API, like -// /browse/find does: a render that waited on a round trip to itself would be -// serialising for nothing. /api/face exists so the suite and a script can ask -// the same question of the same function. - -type Params = Record<string, string | string[] | undefined>; -const one = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v) ?? null; - -export default async function FacesPage({ searchParams }: { searchParams: Promise<Params> }) { - const params = await searchParams; - const [queue, verdicts, rejected] = await Promise.all([ - faceQueue(), - readFaceVerdicts(), - rejectedVideos(), - ]); - - // Two ways in, because the two callers know different things. The bench knows - // a COVER and wants its four faces; a link written in a note knows the exact - // corner. Neither is made to learn the other's identifier. - const wantKey = one(params.key); - const wantCover = one(params.cover); - const start = - (wantKey && queue.find((e) => e.key === wantKey)?.key) ?? - (wantCover && queue.find((e) => e.covers.includes(wantCover))?.key) ?? - null; - - const onAccepted = queue.filter((e) => e.onAccepted).length; - const unrecorded = queue.filter((e) => !e.crop).length; - - return ( - <div className="flex h-full flex-col"> - <BrowseHeader - crumbs={[{ href: "/browse", label: "songs" }, { label: "faces" }]} - note={`${queue.length} corners · ${onAccepted} on accepted covers · ${Object.keys(verdicts.faces).length} judged`} - /> - - <main className="deck-main flex-1 space-y-3 p-4"> - <p className="text-[12px] text-[var(--color-dim)]"> - Every corner on record, deduped by episode and moment, with the ones that ship - first. The dashed amber box is what <span className="num">facecrop.py</span> would - cut; the solid one is yours. Judging writes{" "} - <span className="num">face-verdicts.json</span>, which{" "} - <span className="num">make-thumb.mjs</span> reads — this page never touches the - thumb manifests. - {unrecorded > 0 && ( - <> - {" "} - <span className="text-[var(--color-dirty)]" data-unrecorded={unrecorded}> - {unrecorded} of them have no box recorded at all, so what they were cut from - is not known — only what they were cut near. - </span> - </> - )} - </p> - - <FaceDeck - queue={queue} - initial={verdicts.faces} - rejected={rejected} - start={start} - /> - </main> - </div> - ); -} diff --git a/umtool/app/browse/find/page.tsx b/umtool/app/browse/find/page.tsx @@ -1,261 +0,0 @@ -import Link from "next/link"; -import BrowseHeader from "@/components/BrowseHeader"; -import PhraseConsole from "@/components/PhraseConsole"; -import ShortlistBar from "@/components/ShortlistBar"; -import { - episodeIds, - isEpisode, - isFillerQuery, - parsePhraseQuery, - searchPhrases, - MAX_TERMS, - PAGE_SIZE, - type PhraseResult, -} from "@/lib/phrases"; -import { listShortlists, readShortlist } from "@/lib/shortlist"; - -export const dynamic = "force-dynamic"; - -// THE PHRASE CONSOLE: every occurrence of a word or phrase across 300 episodes -// of word-level ASR, with the timestamp that addresses both the sound and the -// picture. -// -// A STATIC segment under app/browse/, so it wins over app/browse/[song]/ -- -// which would otherwise catch /browse/find, fail readSong() and 404. The same -// trap /browse/decisions documents, and the e2e suite asserts it here too, -// because when this regresses the page still renders perfectly in isolation -// and only the URL stops working. -// -// SEARCH IS `?q=` AND SERVER-RENDERED, over a plain <form method="get">. -// Not live-as-you-type: nothing else in this codebase fetches a list from the -// client, and a URL that can be pasted into a note and still mean the same -// thing six weeks later is worth more than saving a keypress. The filters are -// links for the same reason. - -type Params = Record<string, string | string[] | undefined>; - -const toSearchParams = (p: Params): URLSearchParams => { - const sp = new URLSearchParams(); - for (const [k, v] of Object.entries(p)) { - const one = Array.isArray(v) ? v[0] : v; - if (one != null) sp.set(k, one); - } - return sp; -}; - -export default async function FindPage({ searchParams }: { searchParams: Promise<Params> }) { - const raw = toSearchParams(await searchParams); - const { query, errors } = parsePhraseQuery(raw); - - // NO `q` MEANS NO INDEX. Building 105 MB of blob to draw an empty search box - // would be the entire cost of the feature paid for nothing -- the same - // restraint listSongs() shows by never probing. A bare readdir is enough to - // say how big the corpus is. - const episodes = await episodeIds(); - const unknownVideo = query.video !== null && !(await isEpisode(query.video)); - - let result: PhraseResult | null = null; - if (query.terms.length && !unknownVideo) result = await searchPhrases(query); - - // The shortlists are small JSON and are read on every render, like every - // other pile in this tool -- the CLI and a second tab write the same file, - // and a cached copy would be a stale copy the moment either did. - const slug = raw.get("list"); - const [lists, active] = await Promise.all([ - listShortlists(), - slug ? readShortlist(slug) : Promise.resolve(null), - ]); - const starred = new Set(active?.picks.map((p) => p.id) ?? []); - - const notes = [ - ...errors.map((e) => e.message), - ...(unknownVideo ? [`no episode called ${query.video}`] : []), - ...(slug && !active ? [`no shortlist called ${slug}`] : []), - ...(result?.notes ?? []), - ]; - - // Every filter is a link that changes searchParams. `page` resets on any - // change but its own: page 7 of a different filter is a different list. - const href = (next: Partial<Record<string, string>>) => { - const p = new URLSearchParams(raw); - for (const [k, v] of Object.entries(next)) { - if (v) p.set(k, v); - else p.delete(k); - } - if (!("page" in next)) p.delete("page"); - const s = p.toString(); - return `/browse/find${s ? `?${s}` : ""}`; - }; - - const pages = result ? Math.max(1, Math.ceil(result.total / query.per)) : 1; - const shown = result?.hits.length ?? 0; - // Ask the predicate, never the prose. Matching a word out of a note this file - // does not own is a link that disappears the next time the note is reworded. - const filler = isFillerQuery(query.terms); - - return ( - <div className="flex h-full flex-col"> - <BrowseHeader - active="find" - crumbs={[{ href: "/browse", label: "songs" }, { label: "find" }]} - note={`${episodes.length} episodes${result ? ` · ${result.corpus.words.toLocaleString()} words · ${result.ms}ms` : ""}`} - /> - - <main className="deck-main flex-1 p-4"> - <form method="get" action="/browse/find" className="mb-3 flex flex-wrap items-center gap-2"> - <input - id="phrase-q" - name="q" - defaultValue={query.q} - autoFocus - placeholder="a word or a phrase, as it was said" - aria-label="phrase" - className="w-[26rem] max-w-full rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-2 py-1 font-mono text-[13px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]" - /> - {/* Carried so submitting the box does not silently drop the filters - already applied. A GET form sends only its own fields. */} - {(["video", "conf", "clean", "dupes", "order", "per", "list"] as const).map((k) => - raw.get(k) ? <input key={k} type="hidden" name={k} value={raw.get(k) as string} /> : null, - )} - <button - type="submit" - className="rounded border border-[var(--color-sel)] px-2.5 py-1 font-mono text-[12px] text-[var(--color-sel)]" - > - find - </button> - <span className="micro"> - strictly adjacent · up to {MAX_TERMS} terms · <kbd>/</kbd> to focus - </span> - </form> - - <ShortlistBar lists={lists} active={active} qs={raw.toString()} /> - - {notes.length > 0 && ( - <div className="mb-3 space-y-1.5 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> - {notes.map((n, i) => ( - <p key={i} className="text-[12px] text-[var(--color-dim)]" data-note> - {n} - </p> - ))} - {/* Trap 1, said out loud and with somewhere to go. Without this the - first search anyone runs returns two rows and the console reads - as broken. */} - {filler && ( - <p className="text-[12px]"> - <Link href="/sort" className="ink-link"> - The fillers are in /sort - </Link> - <span className="text-[var(--color-dim)]"> - {" "} - — mined from the audio, not from the transcript. - </span> - </p> - )} - </div> - )} - - {result && ( - <> - <div className="mb-3 flex flex-wrap items-center gap-1.5"> - <Chip href={href({ dupes: query.dupes ? "0" : undefined })} on={query.dupes} - label={`fold chunk twins${result.collapsed ? ` ${result.collapsed}` : ""}`} /> - <Chip href={href({ clean: query.clean ? undefined : "1" })} on={query.clean} - label="hide flagged sources" /> - - <span className="micro ml-2">conf</span> - <Chip href={href({ conf: undefined })} on={query.minConf === null} label="any" /> - {[0.4, 0.9].map((c) => ( - <Chip key={c} href={href({ conf: String(c) })} on={query.minConf === c} label={`≥ ${c}`} /> - ))} - - <span className="micro ml-2">order</span> - <Chip href={href({ order: undefined })} on={query.order === "time"} label="corpus" /> - <Chip href={href({ order: "conf" })} on={query.order === "conf"} label="least certain first" /> - - {query.video && ( - <Chip href={href({ video: undefined })} on={false} label={`${query.video} ✕`} /> - )} - </div> - - <section - data-find - data-total={result.total} - data-shown={shown} - data-collapsed={result.collapsed} - data-suppressed={result.suppressed} - data-videos={result.videos} - data-corpus-built={result.corpus.videos} - data-page={query.page} - > - <p className="mb-2 text-[12px] text-[var(--color-dim)]"> - <span className="num text-[var(--color-text)]">{result.total.toLocaleString()}</span>{" "} - {result.total === 1 ? "hit" : "hits"} across{" "} - <span className="num">{result.videos}</span>{" "} - {result.videos === 1 ? "episode" : "episodes"} · showing{" "} - <span className="num">{shown}</span> · page{" "} - <span className="num">{query.page}</span> of <span className="num">{pages}</span> - </p> - - <PhraseConsole - hits={result.hits} - q={query.q} - list={active?.slug ?? null} - starred={result.hits.filter((h) => starred.has(h.id)).map((h) => h.id)} - /> - - {result.total === 0 && ( - <p className="text-[12px] text-[var(--color-dim)]"> - Nothing said that, strictly adjacent, anywhere in the corpus. - </p> - )} - - {pages > 1 && ( - <nav className="mt-3 flex items-center gap-2" aria-label="pages"> - {query.page > 1 && ( - <Link href={href({ page: String(query.page - 1) })} - className="rounded border border-[var(--color-line)] px-2 py-0.5 font-mono text-[11px] text-[var(--color-sel)]"> - ← previous - </Link> - )} - {query.page < pages && ( - <Link href={href({ page: String(query.page + 1) })} data-next - className="rounded border border-[var(--color-line)] px-2 py-0.5 font-mono text-[11px] text-[var(--color-sel)]"> - next → - </Link> - )} - <span className="micro">{PAGE_SIZE} to a page</span> - </nav> - )} - </section> - </> - )} - - {!result && ( - <section data-find data-total="0" data-shown="0" data-collapsed="0" data-corpus-built="0"> - <p className="text-[12px] text-[var(--color-dim)]"> - {episodes.length} episodes of word-level ASR, unindexed until something is asked of - them. Type a phrase: every occurrence comes back with the second it was said at, and - that second addresses the sound and the picture alike. - </p> - </section> - )} - </main> - </div> - ); -} - -function Chip({ href, on, label }: { href: string; on: boolean; label: string }) { - return ( - <Link - href={href} - aria-current={on ? "true" : undefined} - className={`rounded border px-1.5 py-0.5 font-mono text-[11px] ${ - on - ? "border-[var(--color-sel)] text-[var(--color-sel)]" - : "border-[var(--color-line)] text-[var(--color-dim)] hover:text-[var(--color-text)]" - }`} - > - {label} - </Link> - ); -} diff --git a/umtool/app/browse/page.tsx b/umtool/app/browse/page.tsx @@ -1,249 +0,0 @@ -import Link from "next/link"; -import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; -import { buttonVariants } from "@/components/ui/button"; -import { EmptyState } from "@/components/ui/empty-state"; -import { Input } from "@/components/ui/field"; -import { Toolbar, ToolbarGroup } from "@/components/ui/toolbar"; -import { browseHref, decisionsHref } from "@/lib/hrefs"; -import BrowseHeader from "@/components/BrowseHeader"; -import NewProjectMenu from "@/components/NewProjectMenu"; -import CopyButton from "@/components/CopyButton"; -import ProjectGrid from "@/components/projects/ProjectGrid"; -import { KINDS, decisionCounts, indexHealth, listFolders, listProjects } from "@/lib/projects"; -import { PROJECT_STATES } from "@/lib/project-types"; -import { projectsNote } from "@/lib/dashboard"; - -export const dynamic = "force-dynamic"; - -// A STATIC segment, so it wins over app/[mode]/page.tsx -- which would -// otherwise catch /browse, fail isMode(), and 404. Same trick as /mix. -// -// ZERO CLIENT JS, still. The four filters are links that change searchParams, -// exactly as /browse/decisions does it, and `?q=` is a plain GET form carrying -// the others as hidden inputs -- the /browse/find idiom -- so any filtered view -// is one pasteable URL. Nothing here hydrates. -// -// Counts on the chips come from the UNFILTERED set on purpose. A chip whose -// number changes when you click a different chip moves under the cursor, and -// the whole point of a filter row is to say how much is behind each one. - -type Search = { - kind?: string; - template?: string; - state?: string; - open?: string; - q?: string; - sort?: string; - // A project just deleted (components/projects/DeleteProject.tsx). - deleted?: string; -}; - -export default async function BrowsePage({ - searchParams, -}: { - searchParams: Promise<Search>; -}) { - const sp = await searchParams; - const { kind, template, state, open, q, sort } = sp; - - const all = await listProjects(); - const counts = await decisionCounts(); - const folders = await listFolders(); - - const needle = (q ?? "").trim().toLowerCase(); - const match = (p: (typeof all)[number]) => { - const c = counts.get(p.id); - return ( - (!kind || p.kind === kind) && - (!template || p.template === template) && - (!state || p.state === state) && - (!open || - (open === "blocking" ? (c?.blocking ?? 0) > 0 : (c?.blocking ?? 0) + (c?.open ?? 0) > 0)) && - (!needle || p.haystack.includes(needle)) - ); - }; - - const items = all.filter(match); - const sorted = - sort === "name" ? [...items].sort((a, b) => a.id.localeCompare(b.id)) : items; - - const nOf = (pred: (p: (typeof all)[number]) => boolean) => all.filter(pred).length; - - const qs = (next: Partial<Search>) => browseHref({ ...sp, deleted: undefined, ...next }); - - // Group by folder, using the COLLAPSED labels but never collapsed URLs. - const groups = new Map<string, typeof sorted>(); - for (const p of sorted) { - // Which displayed folder owns this project: the deepest collapsed node - // whose path is a prefix of the project's id. - let owner = ""; - for (const f of folders.keys()) { - if (f && (p.id === f || p.id.startsWith(`${f}/`)) && f.length > owner.length) owner = f; - } - const list = groups.get(owner); - if (list) list.push(p); - else groups.set(owner, [p]); - } - - const blocking = [...counts.values()].reduce((n, c) => n + c.blocking, 0); - const openN = [...counts.values()].reduce((n, c) => n + c.open, 0); - - // The index's only visible surface. It self-heals silently, so its health has - // to be said deliberately or it cannot be observed at all. - const ix = indexHealth(); - - return ( - <div className="flex h-full flex-col"> - <BrowseHeader - crumbs={[{ label: "projects" }]} - note={projectsNote(all.length, blocking, openN)} - /> - <main className="deck-main flex-1 p-4"> - {sp.deleted && ( - <p role="status" data-deleted={sp.deleted} className="mb-2 text-[12px] text-[var(--color-dim)]"> - Deleted {sp.deleted}. - </p> - )} - {/* --- filters, as links ---------------------------------------- */} - <Toolbar aria-label="Filters" className="-mx-4 -mt-4 mb-4"> - <ToolbarGroup label="Kind"> - <Chip href={qs({ kind: "", template: "" })} on={!kind && !template} label={`all ${all.length}`} /> - {KINDS.map((k) => ( - <Chip - key={k.id} - href={qs({ kind: k.id, template: "" })} - on={kind === k.id && !template} - label={`${k.label} ${nOf((p) => p.kind === k.id)}`} - /> - ))} - </ToolbarGroup> - - <ToolbarGroup label="State"> - <Chip href={qs({ state: "" })} on={!state} label="any" /> - {PROJECT_STATES.filter((s) => nOf((p) => p.state === s) > 0).map((s) => ( - <Chip - key={s} - href={qs({ state: s })} - on={state === s} - label={`${s} ${nOf((p) => p.state === s)}`} - /> - ))} - </ToolbarGroup> - - <ToolbarGroup label="Decisions"> - <Chip href={qs({ open: "" })} on={!open} label="any" /> - <Chip - href={qs({ open: "blocking" })} - on={open === "blocking"} - label={`blocking ${nOf((p) => (counts.get(p.id)?.blocking ?? 0) > 0)}`} - tone="blocking" - /> - <Chip - href={qs({ open: "1" })} - on={open === "1"} - label={`waiting ${nOf( - (p) => (counts.get(p.id)?.blocking ?? 0) + (counts.get(p.id)?.open ?? 0) > 0, - )}`} - /> - </ToolbarGroup> - - <ToolbarGroup label="Sort"> - <Chip href={qs({ sort: "" })} on={sort !== "name"} label="recent" /> - <Chip href={qs({ sort: "name" })} on={sort === "name"} label="name" /> - </ToolbarGroup> - - <div className="flex basis-full flex-wrap items-center gap-2"> - {/* A GET form so the result is a pasteable URL, and hidden inputs so - searching does not throw away the filters you already set. */} - <form method="get" action="/browse" className="flex items-center gap-1.5"> - {(["kind", "template", "state", "open", "sort"] as const).map((k) => - sp[k] ? <input key={k} type="hidden" name={k} value={sp[k]} /> : null, - )} - <Input - type="search" - name="q" - defaultValue={q ?? ""} - placeholder="title, id, source…" - aria-label="filter projects" - className="w-60 font-mono text-[12.5px]" - /> - <button type="submit" className={buttonVariants({ size: "md" })}> - filter - </button> - {q && ( - <Link href={qs({ q: "" })} className="ink-link text-[12px]"> - clear - </Link> - )} - </form> - - <NewProjectMenu kinds={KINDS.map((k) => ({ id: k.id, label: k.label, scaffold: k.scaffold }))} /> - <div className="ml-auto flex items-center gap-2"> - <Link href={decisionsHref()} className={buttonVariants({ size: "md" })}> - decisions - </Link> - <CopyButton - label="copy the whole picture" - title="every project as markdown — spec, cuts, verdicts, notes and resolved marks" - url="/api/browse/context" - className={buttonVariants({ size: "md" })} - /> - </div> - </div> - </Toolbar> - - {all.length === 0 ? ( - <EmptyState title={<>No projects under <code className="font-mono">REPORTS_DIR</code></>}> - A directory becomes one by holding a <code className="font-mono">video.manifest.json</code>, a{" "} - <code className="font-mono">spec.json</code>, or a sweep report. - </EmptyState> - ) : ( - <div className="space-y-5"> - {[...groups.entries()].map(([folderPath, list]) => ( - <section key={folderPath || "_root"} data-folder={folderPath}> - {folderPath && ( - <h2 className="micro mb-1.5"> - {folders.get(folderPath)?.label ?? folderPath} - </h2> - )} - <ProjectGrid projects={list} counts={counts} /> - </section> - ))} - </div> - )} - - {ix.ok && ix.total > 0 && ( - <p className="micro mt-6" data-index={`${ix.fresh}/${ix.total}`}> - index: {ix.fresh}/{ix.total} fresh — the filesystem is the model; this only - caches what it said - </p> - )} - </main> - </div> - ); -} - -function Chip({ - href, - on, - label, - tone, -}: { - href: string; - on: boolean; - label: string; - tone?: BadgeVariants["variant"]; -}) { - return ( - <Link - href={href} - // Set by hand, not by the variant. It is what the e2e suite asserts on, - // and it is the actual accessibility statement -- the colour is only the - // visible half of it. - aria-current={on ? "true" : undefined} - className={badgeVariants({ variant: on ? "on" : (tone ?? "neutral") })} - > - {label} - </Link> - ); -} diff --git a/umtool/app/browse/sources/page.tsx b/umtool/app/browse/sources/page.tsx @@ -1,135 +0,0 @@ -import Link from "next/link"; -import BrowseHeader from "@/components/BrowseHeader"; -import { corpusConcentration } from "@/lib/concentration"; - -export const dynamic = "force-dynamic"; - -// Which episodes the palette actually comes from, across every song. -// -// A STATIC segment under app/browse/, like /browse/decisions -- see that file. -// -// This exists because the claim "drawn from a corpus of 300 episodes" was never -// checked against the plans. It is answered here in two units at once, because -// they answer different questions: placements say how much of the RUNTIME an -// episode supplies, clips say how much of the PALETTE it does. - -const pc = (v: number) => `${(v * 100).toFixed(1)}%`; - -export default async function SourcesPage() { - const c = await corpusConcentration(); - - return ( - <div className="flex h-full flex-col"> - <BrowseHeader - active="sources" - crumbs={[{ href: "/browse", label: "songs" }, { label: "sources" }]} - note={`${c.videos.length} episodes · ${c.builds} plans`} - /> - <main className="deck-main flex-1 p-4"> - {c.videos.length === 0 ? ( - <p className="text-[12px] text-[var(--color-dim)]"> - No plans under <code className="font-mono">videos/</code>, so nothing to roll up. - </p> - ) : ( - <> - <dl className="mb-4 grid grid-cols-2 gap-x-6 gap-y-1 text-[12px] sm:grid-cols-4"> - <Stat - label="episodes" - value={String(c.placements.distinct)} - note={`over ${c.builds} plans`} - /> - <Stat - label="top episode" - value={pc(c.placements.top1)} - note="of every note placement" - /> - <Stat label="top five" value={pc(c.placements.top5)} note="of every note placement" /> - <Stat - label="cover half" - value={String(c.placements.half)} - note={`episodes · HHI ${c.placements.hhi}`} - /> - </dl> - - <p className="mb-3 max-w-3xl text-[12px] text-[var(--color-dim)]"> - Placements are how much of the finished runtime an episode supplies; clips are how - much of the palette. One beloved clip used ninety times and ninety clips used once are - the same placement count and a very different corpus — so both are here, and neither - is summed with the other. - </p> - - <table className="w-full border-collapse text-[12px]"> - <thead> - <tr className="micro"> - <th className="border-b border-[var(--color-line)] px-2 py-1 text-left">episode</th> - <th className="border-b border-[var(--color-line)] px-2 py-1 text-right">placements</th> - <th className="border-b border-[var(--color-line)] px-2 py-1 text-right">share</th> - <th className="border-b border-[var(--color-line)] px-2 py-1 text-right">clips</th> - <th className="border-b border-[var(--color-line)] px-2 py-1 text-left">songs</th> - <th className="border-b border-[var(--color-line)] px-2 py-1 text-left">date</th> - </tr> - </thead> - <tbody> - {c.videos.map((v) => ( - <tr key={v.video} data-source={v.video}> - <td className="border-b border-[var(--color-line)] px-2 py-1"> - {v.link ? ( - <a - href={v.link} - target="_blank" - rel="noreferrer" - className="ink-link" - > - {v.title || v.video} - </a> - ) : ( - <span className="text-[var(--color-text)]">{v.title || v.video}</span> - )} - <span className="num ml-2 text-[11px] text-[var(--color-line)]">{v.video}</span> - </td> - <td - className="num border-b border-[var(--color-line)] px-2 py-1 text-right text-[var(--color-meter)]" - data-placements={v.placements} - > - {v.placements} - </td> - <td className="num border-b border-[var(--color-line)] px-2 py-1 text-right text-[var(--color-dim)]"> - {pc(v.placements / (c.placements.total || 1))} - </td> - <td className="num border-b border-[var(--color-line)] px-2 py-1 text-right text-[var(--color-dim)]"> - {v.clips} - </td> - <td className="border-b border-[var(--color-line)] px-2 py-1 text-[var(--color-dim)]"> - {v.songs.map((s, i) => ( - <span key={s}> - {i > 0 && ", "} - <Link href={`/browse/${s}`} className="hover:text-[var(--color-text)]"> - {s} - </Link> - </span> - ))} - </td> - <td className="num border-b border-[var(--color-line)] px-2 py-1 text-[var(--color-dim)]"> - {v.date} - </td> - </tr> - ))} - </tbody> - </table> - </> - )} - </main> - </div> - ); -} - -function Stat({ label, value, note }: { label: string; value: string; note: string }) { - return ( - <div> - <dt className="micro">{label}</dt> - <dd className="num text-[18px] text-[var(--color-meter)]"> - {value} <span className="text-[11px] text-[var(--color-dim)]">{note}</span> - </dd> - </div> - ); -} diff --git a/umtool/app/browse/trim/[set]/page.tsx b/umtool/app/browse/trim/[set]/page.tsx @@ -1,48 +0,0 @@ -import { notFound } from "next/navigation"; -import BrowseHeader from "@/components/BrowseHeader"; -import TrimBench from "@/components/TrimBench"; -import BuildChain from "@/components/BuildChain"; -import { TRIM_SETS, readCatalogue, readTrims } from "@/lib/trim"; -import { readTrimNotes } from "@/lib/notes"; - -export const dynamic = "force-dynamic"; - -// `trim` is a STATIC segment, so it wins over /browse/[song] the same way -// /browse wins over /[mode]. -// -// The trimmer is NOT scoped to a cut, and that is deliberate: source clips are -// shared across every cut of every song, so putting the editor under one cut -// would imply per-cut trim state that does not exist. - -export default async function TrimPage({ params }: { params: Promise<{ set: string }> }) { - const { set: id } = await params; - const set = TRIM_SETS[id]; - if (!set) notFound(); - - const [catalogue, trims, hookNotes] = await Promise.all([ - readCatalogue(set), - readTrims(set), - readTrimNotes(), - ]); - - return ( - <div className="flex h-full flex-col"> - <BrowseHeader - crumbs={[{ href: "/browse", label: "songs" }, { label: `trim: ${set.id}` }]} - note={`${catalogue.hooks.length} hooks · ${trims.length} trimmed`} - /> - <main className="deck-main flex-1"> - <TrimBench - setId={set.id} - label={set.label} - hooks={catalogue.hooks} - initialTrims={trims} - hookNotes={hookNotes} - /> - <div className="px-4 pb-4"> - <BuildChain setId={set.id} /> - </div> - </main> - </div> - ); -} diff --git a/umtool/app/globals.css b/umtool/app/globals.css @@ -470,13 +470,14 @@ canvas.grabbable { color: var(--text); background: var(--panel-2); } - .app-places > a[aria-current="page"], + .app-places > a[aria-current], .app-places > [data-nav-group] > button[aria-current="page"] { color: var(--text); background: var(--panel-2); } - /* The Signal edge on the place you are in: the lit line, at rest. */ - .app-places > a[aria-current="page"]::before, + /* The Signal edge on the place you are in: the lit line, at rest. A place + is `aria-current="page"` on its own page and `"true"` on a page under it. */ + .app-places > a[aria-current]::before, .app-places > [data-nav-group] > button[aria-current="page"]::before { content: ""; position: absolute; @@ -487,6 +488,44 @@ canvas.grabbable { background: var(--signal); } + /* A place's sub-list (Tools when you are in it): smaller, indented under it, + the same lit edge on the one you are on. */ + .app-sub { + display: grid; + gap: 1px; + margin: 1px 0 3px 12px; + padding-left: 6px; + border-left: 1px solid var(--seam-2); + } + .app-sub > a, + .app-sub > [data-nav-group] > button { + position: relative; + display: flex; + width: 100%; + align-items: center; + gap: 8px; + padding: 3px 10px; + border-radius: 3px; + font-size: 12.5px; + color: var(--muted-2); + text-decoration: none; + text-align: left; + } + .app-sub > a:hover, + .app-sub > [data-nav-group] > button:hover, + .app-sub > a[aria-current="page"], + .app-sub > [data-nav-group] > button[aria-current="page"] { + color: var(--text); + background: var(--panel-2); + } + /* A count beside a place: Meter, never Signal (a number you can't click + doesn't wear the click colour). */ + .app-places .rail-n { + margin-left: auto; + font: 500 11.5px var(--f-mono); + color: var(--meter); + } + /* A link in running text or a row: ink, with a quiet underline that wakes on hover. Signal is not a link colour -- it is kept for the lit line and the one primary action (canvas critique, "Signal only on the lit line"). */ @@ -760,6 +799,20 @@ canvas.grabbable { class says. In the utilities layer, element + attribute, so it beats the bare border utility and loses to every hover/focus/state variant. */ @layer utilities { + /* The ONE primary action of a list line (canvas `.ln .act .btn.go`): an + outline at rest, filled Signal on the lit line only -- Signal is the lit + line's and the one primary action's, never every row's. In the utilities + layer so it wins over the outline variant it starts as. */ + .lit-line[data-lit] .lit-go { + border-color: var(--signal); + background: var(--signal); + color: var(--on-signal); + font-weight: 600; + } + .lit-line[data-lit] .lit-go:hover { + background: color-mix(in srgb, var(--signal) 86%, var(--text)); + } + button[class*="border-[var(--color-line)]"], select[class*="border-[var(--color-line)]"], input[class*="border-[var(--color-line)]"], diff --git a/umtool/app/layout.tsx b/umtool/app/layout.tsx @@ -3,6 +3,7 @@ import { cookies } from "next/headers"; import "./globals.css"; import { fontVariables } from "./fonts"; import { LastPageRecorder } from "@/components/LastPage"; +import JumpPalette from "@/components/shell/JumpPalette"; import { THEME_COOKIE, parseTheme, themeAttr } from "@/lib/theme"; export const metadata: Metadata = { @@ -27,6 +28,8 @@ export default async function RootLayout({ children }: { children: React.ReactNo and needs no Suspense boundary -- see components/LastPage.tsx. */} <LastPageRecorder /> {children} + {/* ⌘K, on every page -- a bench with no rail included. */} + <JumpPalette /> </body> </html> ); diff --git a/umtool/app/page.tsx b/umtool/app/page.tsx @@ -1,93 +1,212 @@ -import { statfs } from "node:fs/promises"; -import DecisionsPanel from "@/components/dashboard/DecisionsPanel"; -import DeliverablesPanel from "@/components/dashboard/DeliverablesPanel"; -import NowPanel from "@/components/dashboard/NowPanel"; -import Panel from "@/components/dashboard/Panel"; +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 SourcesPanel from "@/components/dashboard/SourcesPanel"; -import StateStrip from "@/components/dashboard/StateStrip"; -import ToolsPanel from "@/components/dashboard/ToolsPanel"; import NewProjectMenu from "@/components/NewProjectMenu"; import AppShell from "@/components/shell/AppShell"; -import ProjectGrid from "@/components/projects/ProjectGrid"; -import { listActivity, runningActivity } from "@/lib/activity"; -import { projectsNote, sourceBuckets, stateRows } from "@/lib/dashboard"; -import { toolsCache } from "@/lib/doctor"; -import { REPORTS_ROOT } from "@/lib/paths"; -import { KINDS, decisionCounts, indexHealth, listProjects, openDecisions } from "@/lib/projects"; +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 } 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"; export const dynamic = "force-dynamic"; // --------------------------------------------------------------------------- -// The front door. +// THE INBOX (plans/umtool-redesign.md, P3; canvas "Inbox"): the calls waiting +// on the operator, grouped and ranked by lib/inbox (P2a) -- Your call, Review, +// Blocking, Notes, Open, Ready to finish, and Quiet collapsed. One big number, +// the sentence under it, then the cards as one lit list. // -// It used to be a doorway that put you back in the song pile you last judged. -// It is a page now: what is running, what is waiting on you, where every -// project stands, which sources nobody has checked, what has been built, and -// whether the machine can build at all. Everything on it is read from the -// index and the two job registries; NOTHING on it shells out -- the tools -// panel shows a cache or "not checked", and probing is a button. +// What the dashboard's panels were: a call became a card here (a tool the +// pipeline needs that is missing, a disk nearly full); the rest -- recent +// jobs, project states, sources, deliverables, tools and disk -- is on +// /settings/system. What is running is in the rail. +// +// `?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. // --------------------------------------------------------------------------- -async function freeBytesUnder(dir: string): Promise<number | null> { - try { - const s = await statfs(dir); - return Number(s.bavail) * Number(s.bsize); - } catch { - return null; - } +/** What a decision kind is, in a few words after the piece's title. */ +const WHAT: Record<string, string> = { + "research-proposal": "research proposal", + "iteration-failed": "run failed", + "iteration-ready": "iteration ready", + "open-note": "open notes", + "unreadable-notes": "notes.json does not read", + "link-ambiguous": "video not linked", + "looks-done": "looks done", + "claim-unadjudicated": "claims never ruled", + "claim-incoherent": "claims that don't hold together", + "clip-no-cues": "clips with no cues", + "clip-unfetchable": "clips can't be fetched", + "clip-mid-sentence": "clips end mid-sentence", + "clip-cue-gap": "clips over a cue gap", + "clip-cut-outside": "cuts outside the window", + "window-overlap": "windows overlap", + "no-punctuation": "windows without punctuation", + "manifest-invalid": "manifest invalid", + "stale-build": "video out of date", + unbuilt: "never built", + "storage-unreachable": "media drive unreachable", + "storage-mismatch": "storage disagrees", + "unjudged-variant": "variants not judged", + "missing-cut": "cuts missing", + "stale-recipe": "recipes out of date", + "no-recipe": "no recipe", + "spec-problem": "spec problem", + "no-plan": "plans unnamed", + unattributed: "variants unattributed", + "thumb-unaccepted": "no cover accepted", + loudness: "loudness off target", + "shadowed-name": "no address of its own", + "unroutable-name": "no address of its own", + "ambiguous-project": "two kinds match", + "machine-tool": "a required tool is missing", + "machine-disk": "disk nearly full", +}; +const whatOf = (kind: string) => WHAT[kind] ?? kind.replace(/-/g, " "); + +const GROUP_NOTE: Record<string, string> = { + "your-call": "spend or failed runs", + blocking: "active pieces only", + "ready-to-finish": "suggested, never automatic", +}; + +/** The machine's calls (lib/machine.ts) as Blocking cards; /settings/system is where they are settled. */ +async function machineCards(): Promise<InboxCard[]> { + return (await machineCalls()).map((m) => ({ + key: `machine:${m.kind}`, + piece: null, + title: "umtool", + kind: m.kind, + what: whatOf(m.kind), + why: m.why, + count: m.count, + severity: "blocking", + action: { label: m.kind === "machine-tool" ? "Check tools" : "Open system", href: systemHref() }, + lifecycle: "active" as const, + })); +} + +function toCard(group: string, c: GroupCard, lifecycle: LifecycleState): InboxCard { + return { + key: `${group}:${c.piece ?? c.project}:${c.kind}`, + piece: c.piece, + title: c.title, + kind: c.kind, + what: whatOf(c.kind), + why: c.why, + count: c.count, + severity: c.severity, + action: c.action, + lifecycle, + finish: c.kind === "looks-done", + }; } -export default async function Home({ +export default async function Inbox({ searchParams, }: { - searchParams: Promise<{ from?: string }>; + searchParams: Promise<{ from?: string; hidden?: string }>; }) { - const { from } = await searchParams; - const projects = await listProjects(); - const counts = await decisionCounts(); - const decisions = await openDecisions(); - const running = runningActivity(); - const recent = listActivity(8); - const tools = toolsCache(); - const ix = indexHealth(); - const free = await freeBytesUnder(REPORTS_ROOT); + const { from, hidden: showHidden } = 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); - const blocking = [...counts.values()].reduce((n, c) => n + c.blocking, 0); - const openN = [...counts.values()].reduce((n, c) => n + c.open, 0); - const buckets = sourceBuckets(projects); - const newest = [...projects].sort((a, b) => b.newestMtimeMs - a.newestMtimeMs).slice(0, 6); + const machine = await machineCards(); + const groups: InboxGroup[] = inbox.groups.map((g) => ({ + id: g.id, + label: g.label, + note: g.id === "quiet" ? `${g.cards.length} cards, facts rather than calls` : GROUP_NOTE[g.id], + collapsed: g.collapsed, + decisions: g.decisions, + hidden: g.hidden, + cards: [ + ...(g.id === "blocking" ? machine : []), + ...g.cards.map((c) => toCard(g.id, c, c.piece ? (lifeOf.get(c.piece) ?? "active") : "active")), + ], + })); + const head = inboxHeadline( + groups.map((g) => ({ ...g, decisions: g.decisions + (g.id === "blocking" ? machine.reduce((n, c) => n + c.count, 0) : 0) })), + ); + + // The calls on parked and done pieces, as cards of their own: grouped the + // same way, every one with Reactivate. + let hiddenGroup: InboxGroup | null = null; + if (showHidden) { + const rows = inbox.items.filter((d) => d.hidden).map((d) => ({ ...d, hidden: false })) as Decision[]; + const cards = (summarizeGroups(rows) as typeof inbox.groups).flatMap((g) => + g.cards.map((c) => toCard(`hidden-${g.id}`, c, c.piece ? (lifeOf.get(c.piece) ?? "parked") : "parked")), + ); + hiddenGroup = { + id: "hidden", + label: "Hidden", + note: "on parked and done pieces", + collapsed: false, + decisions: rows.length, + 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 - active="home" - crumbs={[{ label: "home" }]} + active="inbox" + crumbs={[{ label: "Inbox" }]} actions={ <> <ResumeChip /> - <NewProjectMenu kinds={KINDS.map((k) => ({ id: k.id, label: k.label, scaffold: k.scaffold }))} from={from ?? null} /> + {inbox.hidden > 0 && ( + <Link + href={homeHref({ hidden: !showHidden })} + data-show-hidden={showHidden ? "1" : "0"} + aria-pressed={!!showHidden} + className={buttonVariants({ variant: "quiet", size: "md" })} + > + {showHidden ? "Hide hidden" : `Show hidden ${inbox.hidden}`} + </Link> + )} </> } /> - <main className="deck-main flex-1 p-4"> - <div className="grid gap-3 lg:grid-cols-2 2xl:grid-cols-3"> - <NowPanel running={running} recent={recent} /> - <DecisionsPanel decisions={decisions} /> - <StateStrip - rows={stateRows(KINDS, projects)} - note={projectsNote(projects.length, blocking, openN)} - /> - <SourcesPanel never={buckets.never} old={buckets.old} bad={buckets.bad} /> - <DeliverablesPanel projects={projects} /> - <ToolsPanel initial={tools} freeBytes={free} index={ix} /> + <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. + </p> + )} + + <div className="mb-1 mt-1 flex items-end gap-3.5" data-inbox-count={head.calls}> + <span className="display text-[72px] font-[850] leading-[0.8]">{head.calls}</span> + <span className="pb-0.5 text-[13px] text-text-2"> + {head.calls === 1 ? "call waiting on you" : "calls waiting on you"} + <small className="block text-[12px] text-muted" data-inbox-note=""> + {headlineNote(head)} + </small> + </span> </div> - <Panel title="recent" testid="recent" more={{ href: "/browse", label: "every project →" }} className="mt-3"> - <ProjectGrid projects={newest} counts={counts} /> - </Panel> + <InboxList groups={hiddenGroup ? [...groups, hiddenGroup] : groups} /> </main> + <UndoBar /> </div> ); } diff --git a/umtool/app/projects/[...path]/page.tsx b/umtool/app/projects/[...path]/page.tsx @@ -0,0 +1,88 @@ +import Link from "next/link"; +import { notFound } from "next/navigation"; +import BrowseHeader from "@/components/BrowseHeader"; +import ProjectView from "@/components/projects/ProjectView"; +import ProjectGrid from "@/components/projects/ProjectGrid"; +import { listProjects, resolveProjectPath } from "@/lib/projects"; + +export const dynamic = "force-dynamic"; + +// --------------------------------------------------------------------------- +// Everything below /browse that is not a tool page. +// +// This replaced app/browse/[song]/ rather than joining it: two dynamic segments +// at the same level is a Next routing conflict, so it is a delete-and-move. The +// song pages themselves are unchanged -- they moved to components/projects/ and +// are handed an id instead of awaiting params. /browse/yoshi/wide is still the +// same URL and still renders the same page. +// +// Resolution is LONGEST-PREFIX: a project id is a path, so `a/b` being a project +// must not stop `a/b/c` from being one too. Whatever is left over is a VIEW, and +// which views exist is the kind's business, not this file's. +// --------------------------------------------------------------------------- + +export default async function BrowsePathPage({ + params, + searchParams, +}: { + params: Promise<{ path?: string[] }>; + searchParams: Promise<Record<string, string | undefined>>; +}) { + const { path: segments = [] } = await params; + const search = await searchParams; + const resolved = await resolveProjectPath(segments); + if (!resolved) notFound(); + + if (resolved.project) { + return <ProjectView project={resolved.project} rest={resolved.rest} search={search} />; + } + + // Two projects answer to the same bare name. Which one you meant is not + // guessable, and guessing is how a link quietly starts pointing at the wrong + // thing -- so the page says so and offers both canonical paths. + if ("ambiguous" in resolved && resolved.ambiguous) { + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + crumbs={[{ href: "/projects", label: "projects" }, { label: segments.join("/") }]} + note={`${resolved.ambiguous.length} projects answer to that name`} + /> + <main className="deck-main flex-1 p-4"> + <p className="mb-2 text-[12px] text-[var(--color-dim)]"> + <code className="font-mono">{segments[0]}</code> is the name of more than one project, + so it cannot be a shortcut to any of them. Use a full path: + </p> + <ul className="space-y-1"> + {resolved.ambiguous.map((p) => ( + <li key={p.id}> + <Link + href={`/projects/${p.id}${segments.slice(1).map((s) => `/${s}`).join("")}`} + className="font-mono text-[12px] ink-link" + > + /projects/{p.id} + </Link> + </li> + ))} + </ul> + </main> + </div> + ); + } + + // A folder: the same grid, filtered to what is under it. + const folder = resolved.folder; + if (!folder) notFound(); + const all = await listProjects(); + const mine = all.filter((p) => p.id.startsWith(`${folder.path}/`)); + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + crumbs={[{ href: "/projects", label: "projects" }, { label: folder.label }]} + note={`${mine.length} project${mine.length === 1 ? "" : "s"}`} + /> + <main className="deck-main flex-1 p-4"> + <ProjectGrid projects={mine} /> + </main> + </div> + ); +} diff --git a/umtool/app/projects/at/page.tsx b/umtool/app/projects/at/page.tsx @@ -0,0 +1,55 @@ +import Link from "next/link"; +import { notFound } from "next/navigation"; +import ProjectView from "@/components/projects/ProjectView"; +import { projectRefs } from "@/lib/projects"; + +export const dynamic = "force-dynamic"; + +// --------------------------------------------------------------------------- +// The escape hatch for a project that cannot be reached at its own URL. +// +// Two ways that happens, and both used to fail silently. A project whose first +// path segment is a static page's name can never win the route, because a +// static segment beats a dynamic one. Under /browse that was every tool +// (`find`, `trim`, `decisions` …); the tools moved to /tools in P3, and under +// /projects the one static name left is `at`, this page. And a project whose +// name isSegment() dislikes (a space is enough) simply vanished from the +// listing -- that is what keeps this page: such a name has no URL of its own. +// +// `?path=` is validated by MEMBERSHIP of the current scan, not by inspecting the +// string: it either is one of the projects the walk found or it is a 404. That +// is the same rule every other name that crosses the wire in this app follows, +// and it is why this page cannot be turned into a file reader. +// --------------------------------------------------------------------------- + +export default async function AtPage({ + searchParams, +}: { + searchParams: Promise<Record<string, string | undefined>>; +}) { + const search = await searchParams; + const wanted = search.path; + const project = wanted ? (await projectRefs()).find((p) => p.id === wanted) : null; + if (!project) notFound(); + + const why = + project.routing === "shadowed" + ? `/projects/${project.id.split("/")[0]} is a page of its own, so this project can never be opened at its own URL. Rename the directory, or work here.` + : project.routing === "unroutable" + ? "This directory's name cannot be a URL segment, so it has no address of its own. Rename it to letters, digits, dots, dashes and underscores to give it one." + : null; + + return ( + <> + {why && ( + <div className="border-b border-[var(--color-bad)] bg-[color-mix(in_srgb,var(--color-bad)_10%,transparent)] px-4 py-2 text-[12px] text-[var(--color-bad)]"> + {why}{" "} + <Link href="/projects" className="underline"> + every project + </Link> + </div> + )} + <ProjectView project={project} rest={[]} search={search} /> + </> + ); +} diff --git a/umtool/app/projects/page.tsx b/umtool/app/projects/page.tsx @@ -0,0 +1,256 @@ +import Link from "next/link"; +import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; +import { EmptyState } from "@/components/ui/empty-state"; +import { Input } from "@/components/ui/field"; +import { Toolbar, ToolbarGroup } from "@/components/ui/toolbar"; +import { homeHref, projectsHref, workHref } from "@/lib/hrefs"; +import BrowseHeader from "@/components/BrowseHeader"; +import NewProjectMenu from "@/components/NewProjectMenu"; +import CopyButton from "@/components/CopyButton"; +import ProjectGrid from "@/components/projects/ProjectGrid"; +import { KINDS, decisionCounts, indexHealth, listFolders, listProjects } from "@/lib/projects"; +import { PROJECT_STATES } from "@/lib/project-types"; +import { projectsNote } from "@/lib/dashboard"; + +export const dynamic = "force-dynamic"; + +// THE PROJECTS INDEX (/projects; /browse until P3, which made Work the list of +// every piece): every project as a card, grouped by folder. It is where a +// project URL's parent walk lands (lib/last-page.ts), and where + Create's +// "A project" opens the form (`?new=1`). +// +// ZERO CLIENT JS, still. The four filters are links that change searchParams, +// exactly as /browse/decisions does it, and `?q=` is a plain GET form carrying +// the others as hidden inputs -- the /browse/find idiom -- so any filtered view +// is one pasteable URL. Nothing here hydrates. +// +// Counts on the chips come from the UNFILTERED set on purpose. A chip whose +// number changes when you click a different chip moves under the cursor, and +// the whole point of a filter row is to say how much is behind each one. + +type Search = { + kind?: string; + template?: string; + state?: string; + open?: string; + q?: string; + sort?: string; + // A project just deleted (components/projects/DeleteProject.tsx). + deleted?: string; + // Open the new-project form (+ Create → A project). + new?: string; +}; + +export default async function BrowsePage({ + searchParams, +}: { + searchParams: Promise<Search>; +}) { + const sp = await searchParams; + const { kind, template, state, open, q, sort } = sp; + + const all = await listProjects(); + const counts = await decisionCounts(); + const folders = await listFolders(); + + const needle = (q ?? "").trim().toLowerCase(); + const match = (p: (typeof all)[number]) => { + const c = counts.get(p.id); + return ( + (!kind || p.kind === kind) && + (!template || p.template === template) && + (!state || p.state === state) && + (!open || + (open === "blocking" ? (c?.blocking ?? 0) > 0 : (c?.blocking ?? 0) + (c?.open ?? 0) > 0)) && + (!needle || p.haystack.includes(needle)) + ); + }; + + const items = all.filter(match); + const sorted = + sort === "name" ? [...items].sort((a, b) => a.id.localeCompare(b.id)) : items; + + const nOf = (pred: (p: (typeof all)[number]) => boolean) => all.filter(pred).length; + + const qs = (next: Partial<Search>) => projectsHref({ ...sp, deleted: undefined, ...next, new: false }); + + // Group by folder, using the COLLAPSED labels but never collapsed URLs. + const groups = new Map<string, typeof sorted>(); + for (const p of sorted) { + // Which displayed folder owns this project: the deepest collapsed node + // whose path is a prefix of the project's id. + let owner = ""; + for (const f of folders.keys()) { + if (f && (p.id === f || p.id.startsWith(`${f}/`)) && f.length > owner.length) owner = f; + } + const list = groups.get(owner); + if (list) list.push(p); + else groups.set(owner, [p]); + } + + const blocking = [...counts.values()].reduce((n, c) => n + c.blocking, 0); + const openN = [...counts.values()].reduce((n, c) => n + c.open, 0); + + // The index's only visible surface. It self-heals silently, so its health has + // to be said deliberately or it cannot be observed at all. + const ix = indexHealth(); + + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + crumbs={[{ label: "projects" }]} + note={projectsNote(all.length, blocking, openN)} + /> + <main className="deck-main flex-1 p-4"> + {sp.deleted && ( + <p role="status" data-deleted={sp.deleted} className="mb-2 text-[12px] text-[var(--color-dim)]"> + Deleted {sp.deleted}. + </p> + )} + {/* --- filters, as links ---------------------------------------- */} + <Toolbar aria-label="Filters" className="-mx-4 -mt-4 mb-4"> + <ToolbarGroup label="Kind"> + <Chip href={qs({ kind: "", template: "" })} on={!kind && !template} label={`all ${all.length}`} /> + {KINDS.map((k) => ( + <Chip + key={k.id} + href={qs({ kind: k.id, template: "" })} + on={kind === k.id && !template} + label={`${k.label} ${nOf((p) => p.kind === k.id)}`} + /> + ))} + </ToolbarGroup> + + <ToolbarGroup label="State"> + <Chip href={qs({ state: "" })} on={!state} label="any" /> + {PROJECT_STATES.filter((s) => nOf((p) => p.state === s) > 0).map((s) => ( + <Chip + key={s} + href={qs({ state: s })} + on={state === s} + label={`${s} ${nOf((p) => p.state === s)}`} + /> + ))} + </ToolbarGroup> + + <ToolbarGroup label="Decisions"> + <Chip href={qs({ open: "" })} on={!open} label="any" /> + <Chip + href={qs({ open: "blocking" })} + on={open === "blocking"} + label={`blocking ${nOf((p) => (counts.get(p.id)?.blocking ?? 0) > 0)}`} + tone="blocking" + /> + <Chip + href={qs({ open: "1" })} + on={open === "1"} + label={`waiting ${nOf( + (p) => (counts.get(p.id)?.blocking ?? 0) + (counts.get(p.id)?.open ?? 0) > 0, + )}`} + /> + </ToolbarGroup> + + <ToolbarGroup label="Sort"> + <Chip href={qs({ sort: "" })} on={sort !== "name"} label="recent" /> + <Chip href={qs({ sort: "name" })} on={sort === "name"} label="name" /> + </ToolbarGroup> + + <div className="flex basis-full flex-wrap items-center gap-2"> + {/* A GET form so the result is a pasteable URL, and hidden inputs so + searching does not throw away the filters you already set. */} + <form method="get" action="/projects" className="flex items-center gap-1.5"> + {(["kind", "template", "state", "open", "sort"] as const).map((k) => + sp[k] ? <input key={k} type="hidden" name={k} value={sp[k]} /> : null, + )} + <Input + type="search" + name="q" + defaultValue={q ?? ""} + placeholder="title, id, source…" + aria-label="filter projects" + className="w-60 font-mono text-[12.5px]" + /> + <button type="submit" className={buttonVariants({ size: "md" })}> + filter + </button> + {q && ( + <Link href={qs({ q: "" })} className="ink-link text-[12px]"> + clear + </Link> + )} + </form> + + <NewProjectMenu kinds={KINDS.map((k) => ({ id: k.id, label: k.label, scaffold: k.scaffold }))} open={!!sp.new} /> + <div className="ml-auto flex items-center gap-2"> + <Link href={workHref()} className={buttonVariants({ size: "md" })}> + work + </Link> + <Link href={homeHref()} className={buttonVariants({ size: "md" })}> + inbox + </Link> + <CopyButton + label="copy the whole picture" + title="every project as markdown — spec, cuts, verdicts, notes and resolved marks" + url="/api/browse/context" + className={buttonVariants({ size: "md" })} + /> + </div> + </div> + </Toolbar> + + {all.length === 0 ? ( + <EmptyState title={<>No projects under <code className="font-mono">REPORTS_DIR</code></>}> + A directory becomes one by holding a <code className="font-mono">video.manifest.json</code>, a{" "} + <code className="font-mono">spec.json</code>, or a sweep report. + </EmptyState> + ) : ( + <div className="space-y-5"> + {[...groups.entries()].map(([folderPath, list]) => ( + <section key={folderPath || "_root"} data-folder={folderPath}> + {folderPath && ( + <h2 className="micro mb-1.5"> + {folders.get(folderPath)?.label ?? folderPath} + </h2> + )} + <ProjectGrid projects={list} counts={counts} /> + </section> + ))} + </div> + )} + + {ix.ok && ix.total > 0 && ( + <p className="micro mt-6" data-index={`${ix.fresh}/${ix.total}`}> + index: {ix.fresh}/{ix.total} fresh — the filesystem is the model; this only + caches what it said + </p> + )} + </main> + </div> + ); +} + +function Chip({ + href, + on, + label, + tone, +}: { + href: string; + on: boolean; + label: string; + tone?: BadgeVariants["variant"]; +}) { + return ( + <Link + href={href} + // Set by hand, not by the variant. It is what the e2e suite asserts on, + // and it is the actual accessibility statement -- the colour is only the + // visible half of it. + aria-current={on ? "true" : undefined} + className={badgeVariants({ variant: on ? "on" : (tone ?? "neutral") })} + > + {label} + </Link> + ); +} diff --git a/umtool/app/sites/[site]/[report]/evidence/page.tsx b/umtool/app/sites/[site]/[report]/evidence/page.tsx @@ -23,7 +23,7 @@ export default async function EvidenceWalkPage({ reportId={reportId} c={c} crumbs={[ - { href: "/sites", label: "articles" }, + { href: "/work?by=site", label: "articles" }, { href: `/sites/${site.siteId}`, label: site.siteId }, ]} /> diff --git a/umtool/app/sites/[site]/[report]/page.tsx b/umtool/app/sites/[site]/[report]/page.tsx @@ -24,7 +24,7 @@ export default async function SiteArticlePage({ sp={sp} home={{ href: `/sites/${site.siteId}`, label: site.siteTitle || site.siteId }} crumbs={[ - { href: "/sites", label: "articles" }, + { href: "/work?by=site", label: "articles" }, { href: `/sites/${site.siteId}`, label: site.siteId }, ]} published={(site.pages ?? []).includes(reportId)} diff --git a/umtool/app/sites/[site]/page.tsx b/umtool/app/sites/[site]/page.tsx @@ -48,7 +48,7 @@ export default async function SitePage({ <div className="flex h-full flex-col"> <BrowseHeader active="articles" - crumbs={[{ href: "/sites", label: "articles" }, { label: row.title }]} + crumbs={[{ href: "/work?by=site", label: "articles" }, { label: row.title }]} note={`${row.published} published · ${row.drafts} drafts · ${row.openNotes} open notes`} /> <main className="deck-main flex-1 space-y-6 p-4"> @@ -97,11 +97,11 @@ export default async function SitePage({ <ul className="space-y-1"> {linked.map((p) => ( <li key={p.id} data-video-project={p.id} className="flex flex-wrap items-baseline gap-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 text-[12px]"> - <Link href={`/browse/${p.id}`} className="font-mono ink-link"> + <Link href={`/projects/${p.id}`} className="font-mono ink-link"> {p.id} </Link> <span className="text-[var(--color-dim)]">{p.articles.map((a) => a.title).join(", ")}</span> - <Link href={`/browse/${p.id}/takes`} className="ml-auto text-[var(--color-dim)] hover:text-[var(--color-text)]" data-takes={p.tally.takes}> + <Link href={`/projects/${p.id}/takes`} className="ml-auto text-[var(--color-dim)] hover:text-[var(--color-text)]" data-takes={p.tally.takes}> {p.tally.takes} takes </Link> <span className={badgeVariants({ variant: "neutral", size: "sm" })}>like {p.tally.like}</span> diff --git a/umtool/app/tools/faces/page.tsx b/umtool/app/tools/faces/page.tsx @@ -0,0 +1,85 @@ +import BrowseHeader from "@/components/BrowseHeader"; +import FaceDeck from "@/components/FaceDeck"; +import { faceQueue, readFaceVerdicts, rejectedVideos } from "@/lib/faces"; + +export const dynamic = "force-dynamic"; + +// THE FACE JUDGER: every corner that has ever been cut into a cover, one at a +// time, with the crop as something you can see and move. +// +// A STATIC segment under app/browse/, so it wins over app/browse/[song]/ -- +// which would otherwise catch /browse/faces, fail readSong() and 404. The same +// trap /browse/decisions and /browse/find both document, and the suite asserts +// it here too, because when this regresses the page still renders perfectly in +// isolation and only the URL stops working. +// +// It is NOT a tenth nav item. AppNav is at nine and says why: a tenth wraps the +// header on a laptop, and a nav that wraps stops reading as one row of places. +// This is reached from the cover-art bench on a song page -- which is where +// somebody is looking at the four faces when they notice one is wrong. +// +// The page reads the queue directly rather than fetching its own API, like +// /browse/find does: a render that waited on a round trip to itself would be +// serialising for nothing. /api/face exists so the suite and a script can ask +// the same question of the same function. + +type Params = Record<string, string | string[] | undefined>; +const one = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v) ?? null; + +export default async function FacesPage({ searchParams }: { searchParams: Promise<Params> }) { + const params = await searchParams; + const [queue, verdicts, rejected] = await Promise.all([ + faceQueue(), + readFaceVerdicts(), + rejectedVideos(), + ]); + + // Two ways in, because the two callers know different things. The bench knows + // a COVER and wants its four faces; a link written in a note knows the exact + // corner. Neither is made to learn the other's identifier. + const wantKey = one(params.key); + const wantCover = one(params.cover); + const start = + (wantKey && queue.find((e) => e.key === wantKey)?.key) ?? + (wantCover && queue.find((e) => e.covers.includes(wantCover))?.key) ?? + null; + + const onAccepted = queue.filter((e) => e.onAccepted).length; + const unrecorded = queue.filter((e) => !e.crop).length; + + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + crumbs={[{ href: "/tools", label: "tools" }, { label: "faces" }]} + note={`${queue.length} corners · ${onAccepted} on accepted covers · ${Object.keys(verdicts.faces).length} judged`} + /> + + <main className="deck-main flex-1 space-y-3 p-4"> + <p className="text-[12px] text-[var(--color-dim)]"> + Every corner on record, deduped by episode and moment, with the ones that ship + first. The dashed amber box is what <span className="num">facecrop.py</span> would + cut; the solid one is yours. Judging writes{" "} + <span className="num">face-verdicts.json</span>, which{" "} + <span className="num">make-thumb.mjs</span> reads — this page never touches the + thumb manifests. + {unrecorded > 0 && ( + <> + {" "} + <span className="text-[var(--color-dirty)]" data-unrecorded={unrecorded}> + {unrecorded} of them have no box recorded at all, so what they were cut from + is not known — only what they were cut near. + </span> + </> + )} + </p> + + <FaceDeck + queue={queue} + initial={verdicts.faces} + rejected={rejected} + start={start} + /> + </main> + </div> + ); +} diff --git a/umtool/app/tools/find/page.tsx b/umtool/app/tools/find/page.tsx @@ -0,0 +1,261 @@ +import Link from "next/link"; +import BrowseHeader from "@/components/BrowseHeader"; +import PhraseConsole from "@/components/PhraseConsole"; +import ShortlistBar from "@/components/ShortlistBar"; +import { + episodeIds, + isEpisode, + isFillerQuery, + parsePhraseQuery, + searchPhrases, + MAX_TERMS, + PAGE_SIZE, + type PhraseResult, +} from "@/lib/phrases"; +import { listShortlists, readShortlist } from "@/lib/shortlist"; + +export const dynamic = "force-dynamic"; + +// THE PHRASE CONSOLE: every occurrence of a word or phrase across 300 episodes +// of word-level ASR, with the timestamp that addresses both the sound and the +// picture. +// +// A STATIC segment under app/browse/, so it wins over app/browse/[song]/ -- +// which would otherwise catch /browse/find, fail readSong() and 404. The same +// trap /browse/decisions documents, and the e2e suite asserts it here too, +// because when this regresses the page still renders perfectly in isolation +// and only the URL stops working. +// +// SEARCH IS `?q=` AND SERVER-RENDERED, over a plain <form method="get">. +// Not live-as-you-type: nothing else in this codebase fetches a list from the +// client, and a URL that can be pasted into a note and still mean the same +// thing six weeks later is worth more than saving a keypress. The filters are +// links for the same reason. + +type Params = Record<string, string | string[] | undefined>; + +const toSearchParams = (p: Params): URLSearchParams => { + const sp = new URLSearchParams(); + for (const [k, v] of Object.entries(p)) { + const one = Array.isArray(v) ? v[0] : v; + if (one != null) sp.set(k, one); + } + return sp; +}; + +export default async function FindPage({ searchParams }: { searchParams: Promise<Params> }) { + const raw = toSearchParams(await searchParams); + const { query, errors } = parsePhraseQuery(raw); + + // NO `q` MEANS NO INDEX. Building 105 MB of blob to draw an empty search box + // would be the entire cost of the feature paid for nothing -- the same + // restraint listSongs() shows by never probing. A bare readdir is enough to + // say how big the corpus is. + const episodes = await episodeIds(); + const unknownVideo = query.video !== null && !(await isEpisode(query.video)); + + let result: PhraseResult | null = null; + if (query.terms.length && !unknownVideo) result = await searchPhrases(query); + + // The shortlists are small JSON and are read on every render, like every + // other pile in this tool -- the CLI and a second tab write the same file, + // and a cached copy would be a stale copy the moment either did. + const slug = raw.get("list"); + const [lists, active] = await Promise.all([ + listShortlists(), + slug ? readShortlist(slug) : Promise.resolve(null), + ]); + const starred = new Set(active?.picks.map((p) => p.id) ?? []); + + const notes = [ + ...errors.map((e) => e.message), + ...(unknownVideo ? [`no episode called ${query.video}`] : []), + ...(slug && !active ? [`no shortlist called ${slug}`] : []), + ...(result?.notes ?? []), + ]; + + // Every filter is a link that changes searchParams. `page` resets on any + // change but its own: page 7 of a different filter is a different list. + const href = (next: Partial<Record<string, string>>) => { + const p = new URLSearchParams(raw); + for (const [k, v] of Object.entries(next)) { + if (v) p.set(k, v); + else p.delete(k); + } + if (!("page" in next)) p.delete("page"); + const s = p.toString(); + return `/tools/find${s ? `?${s}` : ""}`; + }; + + const pages = result ? Math.max(1, Math.ceil(result.total / query.per)) : 1; + const shown = result?.hits.length ?? 0; + // Ask the predicate, never the prose. Matching a word out of a note this file + // does not own is a link that disappears the next time the note is reworded. + const filler = isFillerQuery(query.terms); + + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + active="find" + crumbs={[{ href: "/tools", label: "tools" }, { label: "find" }]} + note={`${episodes.length} episodes${result ? ` · ${result.corpus.words.toLocaleString()} words · ${result.ms}ms` : ""}`} + /> + + <main className="deck-main flex-1 p-4"> + <form method="get" action="/tools/find" className="mb-3 flex flex-wrap items-center gap-2"> + <input + id="phrase-q" + name="q" + defaultValue={query.q} + autoFocus + placeholder="a word or a phrase, as it was said" + aria-label="phrase" + className="w-[26rem] max-w-full rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-2 py-1 font-mono text-[13px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]" + /> + {/* Carried so submitting the box does not silently drop the filters + already applied. A GET form sends only its own fields. */} + {(["video", "conf", "clean", "dupes", "order", "per", "list"] as const).map((k) => + raw.get(k) ? <input key={k} type="hidden" name={k} value={raw.get(k) as string} /> : null, + )} + <button + type="submit" + className="rounded border border-[var(--color-sel)] px-2.5 py-1 font-mono text-[12px] text-[var(--color-sel)]" + > + find + </button> + <span className="micro"> + strictly adjacent · up to {MAX_TERMS} terms · <kbd>/</kbd> to focus + </span> + </form> + + <ShortlistBar lists={lists} active={active} qs={raw.toString()} /> + + {notes.length > 0 && ( + <div className="mb-3 space-y-1.5 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> + {notes.map((n, i) => ( + <p key={i} className="text-[12px] text-[var(--color-dim)]" data-note> + {n} + </p> + ))} + {/* Trap 1, said out loud and with somewhere to go. Without this the + first search anyone runs returns two rows and the console reads + as broken. */} + {filler && ( + <p className="text-[12px]"> + <Link href="/tools/song/sort" className="ink-link"> + The fillers are in /sort + </Link> + <span className="text-[var(--color-dim)]"> + {" "} + — mined from the audio, not from the transcript. + </span> + </p> + )} + </div> + )} + + {result && ( + <> + <div className="mb-3 flex flex-wrap items-center gap-1.5"> + <Chip href={href({ dupes: query.dupes ? "0" : undefined })} on={query.dupes} + label={`fold chunk twins${result.collapsed ? ` ${result.collapsed}` : ""}`} /> + <Chip href={href({ clean: query.clean ? undefined : "1" })} on={query.clean} + label="hide flagged sources" /> + + <span className="micro ml-2">conf</span> + <Chip href={href({ conf: undefined })} on={query.minConf === null} label="any" /> + {[0.4, 0.9].map((c) => ( + <Chip key={c} href={href({ conf: String(c) })} on={query.minConf === c} label={`≥ ${c}`} /> + ))} + + <span className="micro ml-2">order</span> + <Chip href={href({ order: undefined })} on={query.order === "time"} label="corpus" /> + <Chip href={href({ order: "conf" })} on={query.order === "conf"} label="least certain first" /> + + {query.video && ( + <Chip href={href({ video: undefined })} on={false} label={`${query.video} ✕`} /> + )} + </div> + + <section + data-find + data-total={result.total} + data-shown={shown} + data-collapsed={result.collapsed} + data-suppressed={result.suppressed} + data-videos={result.videos} + data-corpus-built={result.corpus.videos} + data-page={query.page} + > + <p className="mb-2 text-[12px] text-[var(--color-dim)]"> + <span className="num text-[var(--color-text)]">{result.total.toLocaleString()}</span>{" "} + {result.total === 1 ? "hit" : "hits"} across{" "} + <span className="num">{result.videos}</span>{" "} + {result.videos === 1 ? "episode" : "episodes"} · showing{" "} + <span className="num">{shown}</span> · page{" "} + <span className="num">{query.page}</span> of <span className="num">{pages}</span> + </p> + + <PhraseConsole + hits={result.hits} + q={query.q} + list={active?.slug ?? null} + starred={result.hits.filter((h) => starred.has(h.id)).map((h) => h.id)} + /> + + {result.total === 0 && ( + <p className="text-[12px] text-[var(--color-dim)]"> + Nothing said that, strictly adjacent, anywhere in the corpus. + </p> + )} + + {pages > 1 && ( + <nav className="mt-3 flex items-center gap-2" aria-label="pages"> + {query.page > 1 && ( + <Link href={href({ page: String(query.page - 1) })} + className="rounded border border-[var(--color-line)] px-2 py-0.5 font-mono text-[11px] text-[var(--color-sel)]"> + ← previous + </Link> + )} + {query.page < pages && ( + <Link href={href({ page: String(query.page + 1) })} data-next + className="rounded border border-[var(--color-line)] px-2 py-0.5 font-mono text-[11px] text-[var(--color-sel)]"> + next → + </Link> + )} + <span className="micro">{PAGE_SIZE} to a page</span> + </nav> + )} + </section> + </> + )} + + {!result && ( + <section data-find data-total="0" data-shown="0" data-collapsed="0" data-corpus-built="0"> + <p className="text-[12px] text-[var(--color-dim)]"> + {episodes.length} episodes of word-level ASR, unindexed until something is asked of + them. Type a phrase: every occurrence comes back with the second it was said at, and + that second addresses the sound and the picture alike. + </p> + </section> + )} + </main> + </div> + ); +} + +function Chip({ href, on, label }: { href: string; on: boolean; label: string }) { + return ( + <Link + href={href} + aria-current={on ? "true" : undefined} + className={`rounded border px-1.5 py-0.5 font-mono text-[11px] ${ + on + ? "border-[var(--color-sel)] text-[var(--color-sel)]" + : "border-[var(--color-line)] text-[var(--color-dim)] hover:text-[var(--color-text)]" + }`} + > + {label} + </Link> + ); +} diff --git a/umtool/app/mix/page.tsx b/umtool/app/tools/mix/page.tsx diff --git a/umtool/app/tools/song/[mode]/page.tsx b/umtool/app/tools/song/[mode]/page.tsx @@ -0,0 +1,44 @@ +import { notFound } from "next/navigation"; +import { loadClipList } from "@/lib/clips"; +import { isMode } from "@/lib/types"; +import { CURATED, COMPOUNDS, readVocab } from "@/lib/vocab"; +import { REASONS, OTHER_CODE } from "../../../../song/reasons.mjs"; +import Deck from "@/components/Deck"; +import AppRail from "@/components/shell/AppRail"; + +export const dynamic = "force-dynamic"; + +export default async function ModePage({ + params, + searchParams, +}: { + params: Promise<{ mode: string }>; + searchParams: Promise<{ limit?: string; only?: string }>; +}) { + const { mode } = await params; + if (!isMode(mode)) notFound(); + const { limit, only } = await searchParams; + + const page = await loadClipList({ + mode, + limit: Math.max(1, Number(limit ?? 200)), + // ?only=key,key -- look at named clips whatever pile they are in, including + // rejected ones. Six clips in the last pass were rejected for the window + // rather than for the clip, and nothing would otherwise offer them again. + only: only?.split(",").map((s) => s.trim()).filter(Boolean), + }); + const custom = await readVocab(); + + // The deck is a client component and the rail reads the server, so the rail + // is rendered here and the deck draws only its own head (AppHeader). + return ( + <> + <AppRail active={mode} /> + <Deck + page={page} + vocab={{ curated: CURATED, compounds: COMPOUNDS, custom }} + reasons={{ bad: REASONS.bad, dirty: REASONS.dirty, other: OTHER_CODE }} + /> + </> + ); +} diff --git a/umtool/app/tools/sources/page.tsx b/umtool/app/tools/sources/page.tsx @@ -0,0 +1,135 @@ +import Link from "next/link"; +import BrowseHeader from "@/components/BrowseHeader"; +import { corpusConcentration } from "@/lib/concentration"; + +export const dynamic = "force-dynamic"; + +// Which episodes the palette actually comes from, across every song. +// +// A STATIC segment under app/browse/, like /browse/decisions -- see that file. +// +// This exists because the claim "drawn from a corpus of 300 episodes" was never +// checked against the plans. It is answered here in two units at once, because +// they answer different questions: placements say how much of the RUNTIME an +// episode supplies, clips say how much of the PALETTE it does. + +const pc = (v: number) => `${(v * 100).toFixed(1)}%`; + +export default async function SourcesPage() { + const c = await corpusConcentration(); + + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + active="sources" + crumbs={[{ href: "/tools", label: "tools" }, { label: "sources" }]} + note={`${c.videos.length} episodes · ${c.builds} plans`} + /> + <main className="deck-main flex-1 p-4"> + {c.videos.length === 0 ? ( + <p className="text-[12px] text-[var(--color-dim)]"> + No plans under <code className="font-mono">videos/</code>, so nothing to roll up. + </p> + ) : ( + <> + <dl className="mb-4 grid grid-cols-2 gap-x-6 gap-y-1 text-[12px] sm:grid-cols-4"> + <Stat + label="episodes" + value={String(c.placements.distinct)} + note={`over ${c.builds} plans`} + /> + <Stat + label="top episode" + value={pc(c.placements.top1)} + note="of every note placement" + /> + <Stat label="top five" value={pc(c.placements.top5)} note="of every note placement" /> + <Stat + label="cover half" + value={String(c.placements.half)} + note={`episodes · HHI ${c.placements.hhi}`} + /> + </dl> + + <p className="mb-3 max-w-3xl text-[12px] text-[var(--color-dim)]"> + Placements are how much of the finished runtime an episode supplies; clips are how + much of the palette. One beloved clip used ninety times and ninety clips used once are + the same placement count and a very different corpus — so both are here, and neither + is summed with the other. + </p> + + <table className="w-full border-collapse text-[12px]"> + <thead> + <tr className="micro"> + <th className="border-b border-[var(--color-line)] px-2 py-1 text-left">episode</th> + <th className="border-b border-[var(--color-line)] px-2 py-1 text-right">placements</th> + <th className="border-b border-[var(--color-line)] px-2 py-1 text-right">share</th> + <th className="border-b border-[var(--color-line)] px-2 py-1 text-right">clips</th> + <th className="border-b border-[var(--color-line)] px-2 py-1 text-left">songs</th> + <th className="border-b border-[var(--color-line)] px-2 py-1 text-left">date</th> + </tr> + </thead> + <tbody> + {c.videos.map((v) => ( + <tr key={v.video} data-source={v.video}> + <td className="border-b border-[var(--color-line)] px-2 py-1"> + {v.link ? ( + <a + href={v.link} + target="_blank" + rel="noreferrer" + className="ink-link" + > + {v.title || v.video} + </a> + ) : ( + <span className="text-[var(--color-text)]">{v.title || v.video}</span> + )} + <span className="num ml-2 text-[11px] text-[var(--color-line)]">{v.video}</span> + </td> + <td + className="num border-b border-[var(--color-line)] px-2 py-1 text-right text-[var(--color-meter)]" + data-placements={v.placements} + > + {v.placements} + </td> + <td className="num border-b border-[var(--color-line)] px-2 py-1 text-right text-[var(--color-dim)]"> + {pc(v.placements / (c.placements.total || 1))} + </td> + <td className="num border-b border-[var(--color-line)] px-2 py-1 text-right text-[var(--color-dim)]"> + {v.clips} + </td> + <td className="border-b border-[var(--color-line)] px-2 py-1 text-[var(--color-dim)]"> + {v.songs.map((s, i) => ( + <span key={s}> + {i > 0 && ", "} + <Link href={`/projects/${s}`} className="hover:text-[var(--color-text)]"> + {s} + </Link> + </span> + ))} + </td> + <td className="num border-b border-[var(--color-line)] px-2 py-1 text-[var(--color-dim)]"> + {v.date} + </td> + </tr> + ))} + </tbody> + </table> + </> + )} + </main> + </div> + ); +} + +function Stat({ label, value, note }: { label: string; value: string; note: string }) { + return ( + <div> + <dt className="micro">{label}</dt> + <dd className="num text-[18px] text-[var(--color-meter)]"> + {value} <span className="text-[11px] text-[var(--color-dim)]">{note}</span> + </dd> + </div> + ); +} diff --git a/umtool/app/tools/trim/[set]/page.tsx b/umtool/app/tools/trim/[set]/page.tsx @@ -0,0 +1,48 @@ +import { notFound } from "next/navigation"; +import BrowseHeader from "@/components/BrowseHeader"; +import TrimBench from "@/components/TrimBench"; +import BuildChain from "@/components/BuildChain"; +import { TRIM_SETS, readCatalogue, readTrims } from "@/lib/trim"; +import { readTrimNotes } from "@/lib/notes"; + +export const dynamic = "force-dynamic"; + +// `trim` is a STATIC segment, so it wins over /browse/[song] the same way +// /browse wins over /[mode]. +// +// The trimmer is NOT scoped to a cut, and that is deliberate: source clips are +// shared across every cut of every song, so putting the editor under one cut +// would imply per-cut trim state that does not exist. + +export default async function TrimPage({ params }: { params: Promise<{ set: string }> }) { + const { set: id } = await params; + const set = TRIM_SETS[id]; + if (!set) notFound(); + + const [catalogue, trims, hookNotes] = await Promise.all([ + readCatalogue(set), + readTrims(set), + readTrimNotes(), + ]); + + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + crumbs={[{ href: "/tools", label: "tools" }, { label: `trim: ${set.id}` }]} + note={`${catalogue.hooks.length} hooks · ${trims.length} trimmed`} + /> + <main className="deck-main flex-1"> + <TrimBench + setId={set.id} + label={set.label} + hooks={catalogue.hooks} + initialTrims={trims} + hookNotes={hookNotes} + /> + <div className="px-4 pb-4"> + <BuildChain setId={set.id} /> + </div> + </main> + </div> + ); +} diff --git a/umtool/components/AppNav.tsx b/umtool/components/AppNav.tsx @@ -1,58 +1,104 @@ import Link from "next/link"; import { MODES } from "@/lib/types"; -import { articlesHref, browseHref, decisionsHref, findHref, homeHref, mixHref, pileHref, sourcesHref } from "@/lib/hrefs"; +import { + findHref, + facesHref, + homeHref, + mixHref, + pileHref, + researchHref, + sourcesHref, + systemHref, + toolsHref, + workHref, +} from "@/lib/hrefs"; import NavGroup from "./NavGroup"; +import RailCount from "./shell/RailCount"; -// The places, in the order somebody works: the dashboard, every project, what -// is waiting, the articles, the two benches that are not a project (mix, find), -// and the song piles folded under one entry. They are the rail's list now -// (components/shell/AppRail.tsx), one place per line. +// The places (plans/umtool-redesign.md, "Target information architecture"): +// Inbox · Research · Work · Tools · Settings, one line each, every function two +// clicks away. The place you are in carries `aria-current` and the Signal edge +// (the lit line, at rest; app/globals.css `.app-places`): "page" on the place's +// own page, "true" on a page under it. // -// These are TODAY's places, kept as they were -- labels included, since the -// specs name them -- until P3 (plans/umtool-redesign.md) makes the rail Inbox · -// Research · Work · Tools · Settings. The next tool goes UNDER one of these, not -// beside them: the four judging piles and the sources page are the `song ▸` -// group, at the same URLs they always had, so `/sort`, `/keeps` and every -// bookmark still land where they did. +// Tools opens into its tools while you are in one -- find, mix, the song piles +// (the `song ▸` group, at /tools/song/<pile>), faces, sources -- so moving +// between tools is one click; /tools lists them all from anywhere. // -// The place you are in carries `aria-current="page"` and the Signal edge (the -// lit line, at rest; app/globals.css `.app-places`). It used to be -// `--color-accent`, a second green two inches from a verdict button -- a -// NAVIGATION state wearing a VERDICT's colour -- and accent is gone rather than -// retuned. -const SONG_ITEMS = [ - ...MODES.map((m) => ({ href: pileHref(m), label: m as string })), - // Where the palette comes from, across every song at once. +// `active` is the key a page passes. The old keys still light the right place, +// so a page nobody has touched yet (release 28's among them) is not unlit: +// `home` and `decisions` are the Inbox; `browse`, `articles` and every project +// and article page are Work; a tool's own key is Tools. + +const SONG_ITEMS = MODES.map((m) => ({ href: pileHref(m), label: m as string })); +const TOOL_ITEMS = [ + { href: findHref(), label: "find" }, + { href: mixHref(), label: "mix" }, + { href: facesHref(), label: "faces" }, { href: sourcesHref(), label: "sources" }, ]; +const PLACE_OF: Record<string, string> = { + inbox: "inbox", + home: "inbox", + decisions: "inbox", + research: "research", + work: "work", + browse: "work", + articles: "work", + sites: "work", + projects: "work", + tools: "tools", + song: "tools", + trim: "tools", + bench: "tools", + settings: "settings", + system: "settings", + ...Object.fromEntries([...TOOL_ITEMS, ...SONG_ITEMS].map((t) => [t.label, "tools"])), +}; + +/** The place a page's `active` key lights. */ +export const placeOf = (active: string): string => PLACE_OF[active] ?? "work"; + export default function AppNav({ active }: { active: string }) { - const items = [ - { href: homeHref(), label: "home" }, - { href: browseHref(), label: "browse" }, - // The worklist across every project, not a sixth pile. It sits beside - // browse because that is where every decision it names gets settled. - { href: decisionsHref(), label: "decisions" }, - // The articles -- the homepage's (/articles, release 26) and every site's - // own pages (/sites, linked from it) -- published and drafts, with their - // notes, their evidence and the workspace they were written in. Both pages - // mark this entry: the editor's /sites is the sites themselves, and two - // "sites" a tab apart were two places with one name. - { href: articlesHref(), label: "articles" }, - { href: mixHref(), label: "mix" }, - // Every occurrence of a word across the corpus. It sits with browse because - // what it retrieves is raw material for a build, not a pile to judge. - { href: findHref(), label: "find" }, - ]; - const songActive = SONG_ITEMS.some((it) => it.label === active); + const place = placeOf(active); + const current = (id: string, own: string[]) => + place !== id ? undefined : own.includes(active) ? ("page" as const) : ("true" as const); + const songActive = SONG_ITEMS.some((it) => it.label === active) || active === "song"; return ( <nav className="app-places grid gap-px px-2 py-1 text-[13.5px]" aria-label="Main"> - {items.map((it) => ( - <Link key={it.href} href={it.href} aria-current={it.label === active ? "page" : undefined}> - {it.label} - </Link> - ))} - <NavGroup label="song" items={SONG_ITEMS} active={active} on={songActive} /> + <Link href={homeHref()} data-place="inbox" aria-current={current("inbox", ["inbox", "home"])}> + <span>Inbox</span> + <RailCount which="inbox" /> + </Link> + <Link href={researchHref()} data-place="research" aria-current={current("research", ["research"])}> + Research + </Link> + <Link href={workHref()} data-place="work" aria-current={current("work", ["work"])}> + <span>Work</span> + <RailCount which="work" /> + </Link> + <Link href={toolsHref()} data-place="tools" aria-current={current("tools", ["tools"])}> + Tools + </Link> + {place === "tools" && ( + <div className="app-sub" data-rail-sub="tools"> + {TOOL_ITEMS.slice(0, 2).map((it) => ( + <Link key={it.href} href={it.href} aria-current={it.label === active ? "page" : undefined}> + {it.label} + </Link> + ))} + <NavGroup label="song" items={SONG_ITEMS} active={active} on={songActive} /> + {TOOL_ITEMS.slice(2).map((it) => ( + <Link key={it.href} href={it.href} aria-current={it.label === active ? "page" : undefined}> + {it.label} + </Link> + ))} + </div> + )} + <Link href={systemHref()} data-place="settings" aria-current={current("settings", ["settings", "system"])}> + Settings + </Link> </nav> ); } diff --git a/umtool/components/NewProjectMenu.tsx b/umtool/components/NewProjectMenu.tsx @@ -23,10 +23,10 @@ const FIELD_LABEL: Record<string, string> = { brand: "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 }: { kinds: Kind[]; from?: string | null }) { +export default function NewProjectMenu({ kinds, from = null, open: startOpen = false }: { kinds: Kind[]; from?: string | null; open?: boolean }) { const router = useRouter(); const can = kinds.filter((k) => k.scaffold); - const [open, setOpen] = useState(!!from); + const [open, setOpen] = useState(!!from || startOpen); const [kind, setKind] = useState(can[0]?.id ?? ""); const [slug, setSlug] = useState(""); const [title, setTitle] = useState(""); diff --git a/umtool/components/ProvenancePanel.tsx b/umtool/components/ProvenancePanel.tsx @@ -45,7 +45,7 @@ export default function ProvenancePanel({ allNotes?: boolean; }) { const href = (plan: string | null) => - `/browse/${song}/${cut}${plan ? `?plan=${encodeURIComponent(plan)}` : ""}`; + `/projects/${song}/${cut}${plan ? `?plan=${encodeURIComponent(plan)}` : ""}`; const shown = allNotes ? prov.rows : prov.rows.slice(0, ROW_LIMIT); const hidden = prov.rows.length - shown.length; @@ -144,7 +144,7 @@ export default function ProvenancePanel({ {prov.videos.length > 0 && ( <p className="num mt-1 text-[11px] text-[var(--color-dim)]" data-concentration> {concentrationLine(shares(prov.videos.map((v) => v.clips)))} ·{" "} - <Link href="/browse/sources" className="ink-link"> + <Link href="/tools/sources" className="ink-link"> across every song </Link> </p> diff --git a/umtool/components/ShortlistBar.tsx b/umtool/components/ShortlistBar.tsx @@ -87,7 +87,7 @@ export default function ShortlistBar({ if (slug) p.set("list", slug); else p.delete("list"); const s = p.toString(); - return `/browse/find${s ? `?${s}` : ""}`; + return `/tools/find${s ? `?${s}` : ""}`; }; const move = async (i: number, d: number) => { diff --git a/umtool/components/ThumbBench.tsx b/umtool/components/ThumbBench.tsx @@ -153,7 +153,7 @@ export default function ThumbBench({ {c.corners.length > 0 && ( <li> <Link - href={`/browse/faces?cover=${encodeURIComponent(c.name)}`} + href={`/tools/faces?cover=${encodeURIComponent(c.name)}`} data-judge-faces={c.name} className="text-[11px] ink-link" > diff --git a/umtool/components/articles/AddToVideo.tsx b/umtool/components/articles/AddToVideo.tsx @@ -67,7 +67,7 @@ export default function AddToVideo({ ev, projects }: { ev: Evidence; projects: V {state.done && ( <span role="status" className="text-[11px]"> added <span className="font-mono">{state.done.id}</span> —{" "} - <Link href={`/browse/${state.done.project}`} className="underline"> + <Link href={`/projects/${state.done.project}`} className="underline"> open </Link> </span> diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx @@ -85,12 +85,12 @@ export default async function ArticlePage({ {r?.updated && <span>updated {r.updated}</span>} {head && <span data-revisions={head.revision}>{head.revision} revision{head.revision === 1 ? "" : "s"}</span>} {links.linked.map((p: { id: string }) => ( - <Link key={p.id} href={`/browse/${p.id}`} data-project-link={p.id} className="font-mono ink-link"> + <Link key={p.id} href={`/projects/${p.id}`} data-project-link={p.id} className="font-mono ink-link"> {p.id} </Link> ))} {links.possible.map((p: { id: string }) => ( - <Link key={p.id} href={`/browse/${p.id}`} className="font-mono hover:underline" title="shares the slug; not linked"> + <Link key={p.id} href={`/projects/${p.id}`} className="font-mono hover:underline" title="shares the slug; not linked"> {p.id} (possible) </Link> ))} diff --git a/umtool/components/articles/ArticleTable.tsx b/umtool/components/articles/ArticleTable.tsx @@ -85,12 +85,12 @@ export default function ArticleTable({ articles }: { articles: ArticleRow[] }) { </td> <td className="py-1.5 pl-3 pr-3"> {a.projects.linked.map((p) => ( - <Link key={p.id} href={`/browse/${p.id}`} data-project-link={p.id} className="block font-mono text-[11px] ink-link"> + <Link key={p.id} href={`/projects/${p.id}`} data-project-link={p.id} className="block font-mono text-[11px] ink-link"> {p.id} </Link> ))} {a.projects.possible.map((p) => ( - <Link key={p.id} href={`/browse/${p.id}`} title="shares the slug; not linked" className="block font-mono text-[11px] text-[var(--color-dim)] hover:underline"> + <Link key={p.id} href={`/projects/${p.id}`} title="shares the slug; not linked" className="block font-mono text-[11px] text-[var(--color-dim)] hover:underline"> {p.id} (possible) </Link> ))} diff --git a/umtool/components/dashboard/InboxList.tsx b/umtool/components/dashboard/InboxList.tsx @@ -0,0 +1,204 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useMemo, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { LitList } from "@/components/ui/lit-list"; +import { LitActions, LitGroup, LitLine } from "@/components/ui/lit-line"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { cn } from "@/lib/utils"; +import { LifecycleButton, type LifecycleState } from "./Lifecycle"; + +// --------------------------------------------------------------------------- +// The Inbox's cards as ONE lit list (canvas "Inbox"): a group head, then a +// line per card -- piece · what, why under it, the count in Meter, the ONE +// primary action (filled Signal on the lit line only, app/globals.css +// `.lit-go`), then Park and Mute. +// +// Mute is this browser's: a card muted here (`umtool:inbox-muted`, piece and +// kind) is left out until it is unmuted from "Muted N". It is a way to stop +// looking at something, not a ruling -- the decision stays in the API and in +// every count but the big one's cards. Park and Mark done are the piece's +// lifecycle (lib/lifecycle.ts), which everything reads. +// --------------------------------------------------------------------------- + +export type InboxCard = { + key: string; + piece: string | null; + title: string; + kind: string; + what: string; + why: string; + count: number; + severity: string; + action: { label: string; href: string }; + /** The piece's lifecycle (a hidden card's is parked or done). */ + lifecycle: LifecycleState; + /** Mark done is the action (POST), not a link. */ + finish?: boolean; +}; + +export type InboxGroup = { + id: string; + label: string; + note?: string; + collapsed: boolean; + decisions: number; + hidden: number; + cards: InboxCard[]; +}; + +const MUTE_KEY = "umtool:inbox-muted"; + +function readMuted(): string[] { + try { + const raw = JSON.parse(localStorage.getItem(MUTE_KEY) ?? "[]"); + return Array.isArray(raw) ? raw.filter((x): x is string => typeof x === "string") : []; + } catch { + return []; + } +} +function writeMuted(keys: string[]) { + try { + localStorage.setItem(MUTE_KEY, JSON.stringify(keys)); + } catch { + /* not remembering a mute is not an error */ + } +} + +/** A card's mute key: the piece (or project) and the kind, not the group. */ +export const muteKey = (c: Pick<InboxCard, "piece" | "kind" | "key">) => `${c.piece ?? c.key}\u0000${c.kind}`; + +export default function InboxList({ groups }: { groups: InboxGroup[] }) { + const hydrated = useHydrated(); + const [muted, setMuted] = useState<string[]>([]); + const [showMuted, setShowMuted] = useState(false); + const [open, setOpen] = useState<Record<string, boolean>>({}); + useEffect(() => setMuted(readMuted()), []); + + const all = useMemo(() => groups.flatMap((g) => g.cards), [groups]); + const mutedHere = all.filter((c) => muted.includes(muteKey(c))); + const toggleMute = (c: InboxCard) => { + const k = muteKey(c); + const next = muted.includes(k) ? muted.filter((x) => x !== k) : [...muted, k]; + setMuted(next); + writeMuted(next); + }; + + const shown = groups + .map((g) => ({ + ...g, + cards: g.cards.filter((c) => showMuted === muted.includes(muteKey(c))), + })) + .filter((g) => g.cards.length > 0); + + return ( + <> + <div className="mb-2 flex items-center justify-end gap-2"> + {(mutedHere.length > 0 || showMuted) && ( + <button + type="button" + disabled={!hydrated} + aria-pressed={showMuted} + data-show-muted={showMuted ? "1" : "0"} + onClick={() => setShowMuted((v) => !v)} + className={buttonVariants({ variant: "quiet", size: "sm" })} + > + {showMuted ? "Back to the inbox" : `Muted ${mutedHere.length}`} + </button> + )} + </div> + {shown.length === 0 ? ( + <p data-empty="" className="py-6 text-[12.5px] text-text-2"> + {showMuted ? "Nothing muted" : "Nothing waiting on you"} + </p> + ) : ( + <LitList label="Inbox" global> + {shown.map((g) => + g.collapsed && !open[g.id] && !showMuted ? ( + <button + key={g.id} + type="button" + data-group={g.id} + data-collapsed="" + aria-expanded={false} + onClick={() => setOpen((o) => ({ ...o, [g.id]: true }))} + className="mt-[18px] flex w-full items-center gap-2.5 border-b border-seam py-2 pl-5 pr-3 text-left text-[12.5px] text-muted-2 hover:text-text" + > + <span className="micro">{g.label}</span> + <span className="font-mono text-[12px] text-meter">{g.decisions}</span> + <span className="truncate">{g.note}</span> + <span aria-hidden="true" className="ml-auto"> + ▸ + </span> + </button> + ) : ( + <LitGroup + key={g.id} + data-group={g.id} + className="mt-[18px]" + title={g.label} + count={g.cards.length} + note={ + g.collapsed && !showMuted ? ( + <button type="button" onClick={() => setOpen((o) => ({ ...o, [g.id]: false }))} className="hover:text-text"> + collapse ▾ + </button> + ) : ( + g.note + ) + } + > + {g.cards.map((c) => ( + <Card key={c.key} card={c} muted={muted.includes(muteKey(c))} onMute={() => toggleMute(c)} /> + ))} + </LitGroup> + ), + )} + </LitList> + )} + </> + ); +} + +function Card({ card: c, muted, onMute }: { card: InboxCard; muted: boolean; onMute: () => void }) { + const hidden = c.lifecycle !== "active"; + return ( + <LitLine + id={c.key} + data-card={c.kind} + data-piece={c.piece ?? undefined} + data-severity={c.severity} + className="grid grid-cols-[minmax(0,1fr)_64px_auto_auto] items-center gap-x-3.5" + > + <div className="min-w-0"> + <b className="block truncate font-medium text-inherit" data-card-title=""> + {c.title} <span className="font-normal text-muted-2">·</span> {c.what} + </b> + <small className="block truncate text-[12px] text-muted-2">{c.why}</small> + </div> + <span className="text-right font-mono text-[12.5px] font-medium text-meter" data-count={c.count}> + {c.count} + </span> + <span> + {hidden && c.piece ? ( + <LifecycleButton piece={c.piece} title={c.title} from={c.lifecycle} to="active" label="Reactivate" variant="outline" size="md" className="lit-go" /> + ) : c.finish && c.piece ? ( + <LifecycleButton piece={c.piece} title={c.title} from={c.lifecycle} to="done" label="Mark done" variant="outline" size="md" className="lit-go" /> + ) : ( + <Link href={c.action.href} data-action-link="" className={cn(buttonVariants({ variant: "outline", size: "md" }), "lit-go")}> + {c.action.label} + </Link> + )} + </span> + <LitActions className="gap-0.5"> + {!hidden && c.piece && ( + <LifecycleButton piece={c.piece} title={c.title} from={c.lifecycle} to="parked" label="Park" /> + )} + <button type="button" data-mute="" aria-pressed={muted} onClick={onMute} className={buttonVariants({ variant: "quiet", size: "sm" })}> + {muted ? "Unmute" : c.finish ? "Not yet" : "Mute"} + </button> + </LitActions> + </LitLine> + ); +} diff --git a/umtool/components/dashboard/Lifecycle.tsx b/umtool/components/dashboard/Lifecycle.tsx @@ -0,0 +1,148 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect, useState } from "react"; +import { buttonVariants, type ButtonVariants } from "@/components/ui/button"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// A piece's lifecycle, from a list: Park, Mark done, Reactivate +// (POST /api/pieces/lifecycle). Reversible, so no plan-then-confirm: the page's +// <UndoBar> offers the way back for a few seconds instead. +// +// The button says what it did by an event the bar hears (`umtool:lifecycle`), +// because the line it sat on is gone after the refresh -- a parked piece's +// calls are hidden. +// --------------------------------------------------------------------------- + +export type LifecycleState = "active" | "parked" | "done"; +type Change = { piece: string; title: string; from: LifecycleState; to: LifecycleState }; + +const EVENT = "umtool:lifecycle"; +const DONE_WORD: Record<LifecycleState, string> = { active: "Reactivated", parked: "Parked", done: "Marked done" }; + +async function post(piece: string, state: LifecycleState): Promise<string | null> { + try { + const res = await fetch("/api/pieces/lifecycle", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ piece, state }), + cache: "no-store", + }); + if (res.ok) return null; + const j = (await res.json().catch(() => null)) as { error?: string } | null; + return j?.error ?? `HTTP ${res.status}`; + } catch (err) { + return (err as Error).message; + } +} + +export function LifecycleButton({ + piece, + title, + from, + to, + label, + variant = "quiet", + size = "sm", + className, +}: { + piece: string; + title: string; + from: LifecycleState; + to: LifecycleState; + label: string; + variant?: ButtonVariants["variant"]; + size?: ButtonVariants["size"]; + className?: string; +}) { + const hydrated = useHydrated(); + const router = useRouter(); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + return ( + <> + <button + type="button" + disabled={!hydrated || busy} + data-lifecycle-to={to} + data-piece={piece} + title={error ?? undefined} + className={cn(buttonVariants({ variant, size }), error && "text-reject-text", className)} + onClick={async () => { + setBusy(true); + setError(null); + const err = await post(piece, to); + setBusy(false); + if (err) { + setError(err); + return; + } + window.dispatchEvent(new CustomEvent<Change>(EVENT, { detail: { piece, title, from, to } })); + router.refresh(); + }} + > + {busy ? "…" : label} + </button> + {error && ( + <span role="alert" className="text-[11.5px] text-reject-text"> + {error} + </span> + )} + </> + ); +} + +/** "Parked Quartering diet · Undo", for eight seconds after a change. */ +export function UndoBar() { + const router = useRouter(); + const [last, setLast] = useState<Change | null>(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + useEffect(() => { + const on = (e: Event) => { + setError(null); + setLast((e as CustomEvent<Change>).detail); + }; + window.addEventListener(EVENT, on); + return () => window.removeEventListener(EVENT, on); + }, []); + useEffect(() => { + if (!last || busy) return; + const t = setTimeout(() => setLast(null), 8000); + return () => clearTimeout(t); + }, [last, busy]); + if (!last) return null; + return ( + <div + role="status" + data-undo={last.piece} + data-undo-to={last.from} + className="fixed bottom-4 left-1/2 z-30 flex -translate-x-1/2 items-center gap-3 rounded-[3px] border border-seam-2 bg-panel-2 px-3.5 py-2 text-[12.5px] text-text shadow-lg" + > + <span> + {DONE_WORD[last.to]} <b className="font-medium">{last.title}</b> + </span> + <button + type="button" + disabled={busy} + className={buttonVariants({ variant: "outline", size: "sm" })} + onClick={async () => { + setBusy(true); + const err = await post(last.piece, last.from); + setBusy(false); + if (err) { + setError(err); + return; + } + setLast(null); + router.refresh(); + }} + > + Undo + </button> + {error && <span className="text-reject-text">{error}</span>} + </div> + ); +} diff --git a/umtool/components/dashboard/ResumeChip.tsx b/umtool/components/dashboard/ResumeChip.tsx @@ -4,9 +4,9 @@ import Link from "next/link"; import { useEffect, useState } from "react"; import { LAST_PAGE_KEY, isRecordable, restoreCandidates } from "@/lib/last-page"; -// Where you were, as a LINK rather than a redirect. The dashboard is a page in -// its own right now, so / no longer replaces itself with your last URL -- it -// offers it. Same storage, same guard, same HEAD-probed walk-up as the old +// Where you were, as a LINK rather than a redirect. The Inbox is a page in +// its own right, so / never replaces itself with your last URL -- it offers +// it. Same storage, same guard, same HEAD-probed walk-up as the old // restore, so a stale URL degrades to its parent instead of to a 404. export default function ResumeChip() { const [target, setTarget] = useState<string | null>(null); @@ -23,15 +23,20 @@ export default function ResumeChip() { if (!stored || !isRecordable(stored)) return; for (const url of restoreCandidates(stored)) { if (done) return; - let alive = false; + // The address it ANSWERS at: an old URL (/browse/…, /sort) rides a + // redirect (redirects.mjs), and the chip offers where it landed. + let landed: string | null = null; try { const res = await fetch(url, { method: "HEAD", cache: "no-store" }); - alive = res.status !== 404; + if (res.status !== 404) { + const u = new URL(res.url || url, window.location.origin); + landed = u.origin === window.location.origin ? u.pathname + u.search : url; + } } catch { - alive = false; + landed = null; } - if (alive) { - setTarget(url); + if (landed && isRecordable(landed)) { + setTarget(landed); return; } } @@ -53,7 +58,7 @@ export default function ResumeChip() { <Link href={target} data-resume={target} - className="rounded border border-[var(--color-line)] px-2 py-0.5 text-[11px] text-[var(--color-dim)] hover:border-[var(--color-sel)] hover:text-[var(--color-sel)]" + className="rounded-[3px] border border-seam-2 px-2 py-[3px] font-mono text-[11.5px] text-muted-2 hover:border-muted hover:text-text" > resume {target} → </Link> diff --git a/umtool/components/projects/ClaimBench.tsx b/umtool/components/projects/ClaimBench.tsx @@ -300,12 +300,12 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) { </div> <div className="flex-1" /> {data.prev ? ( - <Link className="text-[11px] ink-link" href={`/browse/${data.project}/claim/${data.prev}`}> + <Link className="text-[11px] ink-link" href={`/projects/${data.project}/claim/${data.prev}`}> ← {data.prev} </Link> ) : null} {data.next ? ( - <Link className="text-[11px] ink-link" href={`/browse/${data.project}/claim/${data.next}`}> + <Link className="text-[11px] ink-link" href={`/projects/${data.project}/claim/${data.next}`}> {data.next} → </Link> ) : null} diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -1259,7 +1259,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { ? "saved — the window moved with it, and the cut no longer fitted and was cleared" : "saved — the window you moved was saved with it", ); - if (ok && data.next) router.push(`/browse/${data.project}/clip/${data.next}`); + if (ok && data.next) router.push(`/projects/${data.project}/clip/${data.next}`); }, [save, router, data.project, data.next, windowMoved, muteMoved, windowPatch]); const rejectClip = useCallback(() => { @@ -1397,11 +1397,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { // trips to re-find where you were. case "n": case "N": - if (data.next) router.push(`/browse/${data.project}/clip/${data.next}`); + if (data.next) router.push(`/projects/${data.project}/clip/${data.next}`); break; case "p": case "P": - if (data.prev) router.push(`/browse/${data.project}/clip/${data.prev}`); + if (data.prev) router.push(`/projects/${data.project}/clip/${data.prev}`); break; // The two answers to "is this accurate". `y` also advances, so a cut // that is mostly right is walked with one finger. @@ -1882,7 +1882,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { {data.prev ? ( <Link data-clip-nav="prev" - href={`/browse/${data.project}/clip/${data.prev}`} + href={`/projects/${data.project}/clip/${data.prev}`} className="ink-link" > ← {data.prev} @@ -1893,7 +1893,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { {data.next ? ( <Link data-clip-nav="next" - href={`/browse/${data.project}/clip/${data.next}`} + href={`/projects/${data.project}/clip/${data.next}`} className="ink-link" > {data.next} → @@ -2793,7 +2793,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { {siblings.map((sb) => ( <li key={sb.id} data-sibling={sb.id} className="leading-snug"> <Link - href={`/browse/${data.project}/clip/${sb.id}`} + href={`/projects/${data.project}/clip/${sb.id}`} className="font-mono ink-link" > {sb.id} diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx @@ -152,7 +152,7 @@ export default async function ClipBenchPage({ // once. start/end are the window minus the file's own start, because a mix // spec is relative to the file it names. mixHref: widest - ? `/mix?${new URLSearchParams({ + ? `/tools/mix?${new URLSearchParams({ // The window's own path; see ReportProject — a window may live in // the corpus rather than under out/clips-raw. body: widest.path, diff --git a/umtool/components/projects/CutPage.tsx b/umtool/components/projects/CutPage.tsx @@ -72,8 +72,8 @@ export default async function CutPage({ <div className="flex h-full flex-col"> <BrowseHeader crumbs={[ - { href: "/browse", label: "songs" }, - { href: `/browse/${song.id}`, label: song.id }, + { href: "/projects", label: "songs" }, + { href: `/projects/${song.id}`, label: song.id }, { label: cutName }, ]} note={ @@ -87,7 +87,7 @@ export default async function CutPage({ <div className="p-4 text-[12px] text-[var(--color-dim)]"> Nothing here yet — no <code className="font-mono">{cutName}.mp4</code> and no variants named for it.{" "} - <Link href={`/browse/${song.id}`} className="ink-link"> + <Link href={`/projects/${song.id}`} className="ink-link"> back to {song.id} </Link> </div> diff --git a/umtool/components/projects/DeleteProject.tsx b/umtool/components/projects/DeleteProject.tsx @@ -13,7 +13,7 @@ export default function DeleteProject({ project }: { project: string }) { subject={`the project ${project}`} endpoint="/api/projects/delete" body={{ project }} - onDone={() => router.push(`/browse?deleted=${encodeURIComponent(project)}`)} + onDone={() => router.push(`/work?deleted=${encodeURIComponent(project)}`)} /> ); } diff --git a/umtool/components/projects/DeliverSection.tsx b/umtool/components/projects/DeliverSection.tsx @@ -220,7 +220,7 @@ export default async function DeliverSection({ <span key={c.id}> {i > 0 && " "} <Link - href={`/browse/${project.id}/clip/${c.id}`} + href={`/projects/${project.id}/clip/${c.id}`} data-need-cut-id={c.id} className="font-mono ink-link" > @@ -246,7 +246,7 @@ export default async function DeliverSection({ <span key={id}> {i > 0 && " "} <Link - href={`/browse/${project.id}/clip/${id}`} + href={`/projects/${project.id}/clip/${id}`} data-not-fetched-id={id} className="font-mono text-[var(--color-dirty)] hover:underline" > @@ -269,7 +269,7 @@ export default async function DeliverSection({ {state.incorrect.map((c) => ( <div key={c.id} data-incorrect={c.id} className="text-[11px] leading-snug"> <Link - href={`/browse/${project.id}/clip/${c.id}`} + href={`/projects/${project.id}/clip/${c.id}`} className="font-mono ink-link" > {c.id} diff --git a/umtool/components/projects/ProjectGrid.tsx b/umtool/components/projects/ProjectGrid.tsx @@ -31,7 +31,7 @@ export default function ProjectGrid({ // An unroutable or shadowed project keeps its card and its link -- the // link just goes to the escape hatch instead of to an address that // renders something else. - const href = p.routing === "ok" ? `/browse/${p.id}` : `/browse/at?path=${encodeURIComponent(p.id)}`; + const href = p.routing === "ok" ? `/projects/${p.id}` : `/projects/at?path=${encodeURIComponent(p.id)}`; return ( <li key={p.id}> <Link diff --git a/umtool/components/projects/SongProject.tsx b/umtool/components/projects/SongProject.tsx @@ -40,7 +40,7 @@ export default async function SongProject({ id }: { id: string }) { return ( <div className="flex h-full flex-col"> <BrowseHeader - crumbs={[{ href: "/browse", label: "songs" }, { label: song.id }]} + crumbs={[{ href: "/projects", label: "songs" }, { label: song.id }]} note={`${song.present}/${song.cuts.length} cuts · ${song.variantCount} variants`} /> <div className="flex flex-wrap items-start gap-3 border-b border-[var(--color-line)] px-4 py-2"> @@ -166,7 +166,7 @@ function CutCard({ <div className="min-w-0 flex-1 space-y-1"> <div className="flex flex-wrap items-baseline gap-2"> <Link - href={`/browse/${song.id}/${cut.name}`} + href={`/projects/${song.id}/${cut.name}`} className="font-mono text-[13px] text-[var(--color-text)] hover:text-[var(--color-sel)]" > {cut.name} diff --git a/umtool/components/projects/SweepProject.tsx b/umtool/components/projects/SweepProject.tsx @@ -25,7 +25,7 @@ export default async function SweepProject({ project }: { project: ProjectRef }) return ( <div className="flex h-full flex-col"> <BrowseHeader - crumbs={[{ href: "/browse", label: "projects" }, { label: project.id }]} + crumbs={[{ href: "/projects", label: "projects" }, { label: project.id }]} note={`${citations} citation${citations === 1 ? "" : "s"} · no manifest`} /> <main className="deck-main flex-1 space-y-4 p-4"> @@ -64,7 +64,7 @@ export default async function SweepProject({ project }: { project: ProjectRef }) </p> )} - <Link href="/browse" className="text-[12px] ink-link"> + <Link href="/projects" className="text-[12px] ink-link"> ← every project </Link> </main> diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx @@ -33,7 +33,7 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { {takes.length === 0 ? ( <p data-takes-empty="" className="text-[12px] text-[var(--color-dim)]"> No takes yet.{" "} - <Link href={`/browse/${project.id}`} className="ink-link"> + <Link href={`/projects/${project.id}`} className="ink-link"> back to {project.id} </Link> </p> diff --git a/umtool/components/shell/AppRail.tsx b/umtool/components/shell/AppRail.tsx @@ -5,20 +5,22 @@ import { runningActivity } from "@/lib/activity"; import { homeHref } from "@/lib/hrefs"; import { THEME_COOKIE, parseTheme } from "@/lib/theme"; import CreateMenu from "./CreateMenu"; +import JumpButton from "./JumpButton"; import ThemeControl from "./ThemeControl"; import { Mark, Wordmark } from "./Wordmark"; // --------------------------------------------------------------------------- // The rail (canvas `.rail`): every page's left column. Top to bottom: -// the mark and the wordmark (home), the places, + Create, the jump hint, -// Pinned, and at the foot what is Running and the theme. +// the mark and the wordmark (home), the places (Inbox · Research · Work · +// Tools · Settings, components/AppNav.tsx), + Create, Jump to… ⌘K, Pinned, +// and at the foot what is Running and the theme. // // SERVER ONLY: it reads the theme cookie and the in-process job registries. // A client page (the song deck) gets it from its server page instead. // +// Jump (⌘K) opens the palette (JumpPalette.tsx, in the root layout). +// // What is not built yet says so plainly rather than pretending: -// - Jump (⌘K) is P3's palette; the hint is here, inert, so the rail has its -// final shape. // - Pinned has no store until the piece page (P4a); it is empty. // - Running lists umtool's own job (a build, a fetch, a render). The editor's // jobs and their spend join it in P2b. @@ -38,15 +40,7 @@ export default async function AppRail({ active }: { active: string }) { <CreateMenu /> - <div - data-rail-section="jump" - aria-disabled="true" - title="Not built yet" - className="mx-4 mb-2 mt-0.5 flex items-center gap-2 px-0.5 py-1 text-[12.5px] text-muted-2" - > - Jump to… - <kbd className="ml-auto">⌘K</kbd> - </div> + <JumpButton /> <section data-rail-section="pins" aria-label="Pinned"> <h2 className="micro px-5 pb-1.5 pt-4">Pinned</h2> diff --git a/umtool/components/shell/CreateMenu.tsx b/umtool/components/shell/CreateMenu.tsx @@ -2,10 +2,10 @@ import Link from "next/link"; import { useEffect, useRef, useState } from "react"; -import { browseHref, newArticleHref } from "@/lib/hrefs"; +import { newArticleHref, projectsHref } from "@/lib/hrefs"; // + Create. Until /create exists (P5) it opens onto today's two doors: a new -// article (/articles/new) and a new project (/browse carries the "+ 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() { @@ -42,7 +42,7 @@ export default function CreateMenu() { <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={browseHref()} onClick={() => setOpen(false)} className="rounded-[3px] px-2.5 py-1 text-[12.5px] text-text-2 hover:bg-panel-2 hover:text-text"> + <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> diff --git a/umtool/components/shell/JumpButton.tsx b/umtool/components/shell/JumpButton.tsx @@ -0,0 +1,19 @@ +"use client"; + +import { JUMP_EVENT } from "./JumpPalette"; + +// The rail's "Jump to… ⌘K": opens the palette (components/shell/JumpPalette.tsx, +// mounted once in the root layout) the way the chord does. +export default function JumpButton() { + return ( + <button + type="button" + data-rail-section="jump" + onClick={() => window.dispatchEvent(new Event(JUMP_EVENT))} + className="mx-4 mb-2 mt-0.5 flex items-center gap-2 rounded-[3px] px-0.5 py-1 text-left text-[12.5px] text-muted-2 hover:text-text" + > + Jump to… + <kbd className="ml-auto">⌘K</kbd> + </button> + ); +} diff --git a/umtool/components/shell/JumpPalette.tsx b/umtool/components/shell/JumpPalette.tsx @@ -0,0 +1,244 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + facesHref, + findHref, + generationPolicyHref, + homeHref, + mixHref, + newArticleHref, + pileHref, + projectsHref, + researchHref, + songToolsHref, + sourcesHref, + systemHref, + toolsHref, + workHref, +} from "@/lib/hrefs"; +import { MODES } from "@/lib/types"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// ⌘K: jump to any piece, place, tool or create action (plans/umtool-redesign.md, +// P3). Keyboard first: ⌘K or Ctrl+K from anywhere (a bench included -- it is +// mounted once, in the root layout), type, ↑/↓ (or Ctrl+N/P), Enter; Escape +// closes. It fits 1366×768: a native <dialog> near the top, its list scrolling +// inside 70% of the window. +// +// The places, tools and create actions are fixed and listed here. The pieces +// are fetched the first time it opens (GET /api/jump) and kept for the page. +// The rail's "Jump to…" opens it with an event, `umtool:jump`. +// --------------------------------------------------------------------------- + +export const JUMP_EVENT = "umtool:jump"; + +type Item = { id: string; section: "Places" | "Tools" | "Create" | "Pieces"; label: string; hint: string; href: string }; +type PieceRow = { id: string; title: string; href: string; kind: string; site: string | null; stage: string; lifecycle: string }; + +const FIXED: Item[] = [ + { id: "inbox", section: "Places", label: "Inbox", hint: "the calls waiting on you", href: homeHref() }, + { id: "research", section: "Places", label: "Research", hint: "search the archive", href: researchHref() }, + { id: "work", section: "Places", label: "Work", hint: "every piece", href: workHref() }, + { 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: "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() }, + ...MODES.map((m): Item => ({ id: `pile-${m}`, section: "Tools", label: `Song · ${m}`, hint: "judging pile", href: pileHref(m) })), + { 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: "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 }) }, +]; + +const words = (q: string) => q.toLowerCase().split(/\s+/).filter(Boolean); + +export default function JumpPalette() { + const router = useRouter(); + const dialog = useRef<HTMLDialogElement>(null); + const input = useRef<HTMLInputElement>(null); + const list = useRef<HTMLUListElement>(null); + const [open, setOpen] = useState(false); + const [q, setQ] = useState(""); + const [at, setAt] = useState(0); + const [pieces, setPieces] = useState<PieceRow[] | null>(null); + const [error, setError] = useState<string | null>(null); + + const show = useCallback(() => { + setQ(""); + setAt(0); + setOpen(true); + }, []); + + // ⌘K / Ctrl+K from anywhere, typing included: it is the one chord that is + // never text. + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "k") { + e.preventDefault(); + if (dialog.current?.open) dialog.current.close(); + else show(); + } + }; + const onJump = () => show(); + document.addEventListener("keydown", onKey); + window.addEventListener(JUMP_EVENT, onJump); + return () => { + document.removeEventListener("keydown", onKey); + window.removeEventListener(JUMP_EVENT, onJump); + }; + }, [show]); + + useEffect(() => { + const d = dialog.current; + if (!d) return; + if (open && !d.open) { + d.showModal(); + input.current?.focus(); + } + if (!open && d.open) d.close(); + }, [open]); + + // The pieces, once per page, the first time it opens. + useEffect(() => { + if (!open || pieces !== null) return; + let live = true; + fetch("/api/jump", { cache: "no-store" }) + .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))) + .then((j: { pieces: PieceRow[] }) => live && setPieces(j.pieces)) + .catch((err: Error) => { + if (!live) return; + setPieces([]); + setError(`pieces could not be read: ${err.message}`); + }); + return () => { + live = false; + }; + }, [open, pieces]); + + const items = useMemo(() => { + const all: Item[] = [ + ...FIXED, + ...(pieces ?? []).map( + (p): Item => ({ + id: p.id, + section: "Pieces", + label: p.title, + hint: `${p.id} · ${p.stage}${p.lifecycle !== "active" ? ` · ${p.lifecycle}` : ""}`, + href: p.href, + }), + ), + ]; + const w = words(q); + if (!w.length) return all.filter((it) => it.section !== "Pieces").concat(all.filter((it) => it.section === "Pieces").slice(0, 8)); + const hay = (it: Item) => `${it.label} ${it.hint}`.toLowerCase(); + const hits = all.filter((it) => w.every((x) => hay(it).includes(x))); + // A label that starts with what was typed first, then the rest, each in + // its section's order. + const first = w[0]; + return [ + ...hits.filter((it) => it.label.toLowerCase().startsWith(first)), + ...hits.filter((it) => !it.label.toLowerCase().startsWith(first)), + ].slice(0, 60); + }, [q, pieces]); + + useEffect(() => { + list.current?.querySelector<HTMLElement>(`[data-jump-index="${at}"]`)?.scrollIntoView({ block: "nearest" }); + }, [at]); + + const go = (it: Item | undefined) => { + if (!it) return; + setOpen(false); + router.push(it.href); + }; + + return ( + <dialog + ref={dialog} + data-jump="" + aria-label="Jump to" + onClose={() => setOpen(false)} + className="ui-dialog mx-auto mb-auto mt-[12vh] w-[min(640px,calc(100vw-32px))] rounded-[3px] border border-seam-2 bg-panel p-0 text-text shadow-2xl" + > + {open && ( + <div className="flex max-h-[70vh] flex-col"> + <div className="flex items-center gap-2 border-b border-seam px-3.5 py-2.5"> + <span aria-hidden="true" className="font-mono text-muted-2"> + ⌕ + </span> + <input + ref={input} + data-jump-input="" + value={q} + role="combobox" + aria-expanded="true" + aria-controls="jump-list" + aria-activedescendant={items[at] ? `jump-${at}` : undefined} + aria-label="Jump to a piece, place, tool or create action" + placeholder="Jump to a piece, place, tool…" + onChange={(e) => { + setQ(e.target.value); + setAt(0); + }} + onKeyDown={(e) => { + const down = e.key === "ArrowDown" || (e.ctrlKey && e.key === "n"); + const up = e.key === "ArrowUp" || (e.ctrlKey && e.key === "p"); + if (down || up) { + e.preventDefault(); + setAt((i) => (items.length ? (i + (down ? 1 : -1) + items.length) % items.length : 0)); + } else if (e.key === "Enter") { + e.preventDefault(); + go(items[at]); + } + }} + className="min-w-0 flex-1 border-0 bg-transparent text-[15px] text-text outline-none placeholder:text-muted-2" + /> + <kbd>esc</kbd> + </div> + <ul ref={list} id="jump-list" role="listbox" aria-label="Results" className="m-0 min-h-0 flex-1 list-none overflow-y-auto p-1.5"> + {items.map((it, i) => ( + <li key={`${it.section}:${it.id}`} role="presentation"> + {(i === 0 || items[i - 1].section !== it.section) && ( + <div className="micro px-2.5 pb-1 pt-2.5">{it.section}</div> + )} + <div + id={`jump-${i}`} + role="option" + aria-selected={i === at} + data-jump-item={it.id} + data-jump-index={i} + data-href={it.href} + onMouseMove={() => i !== at && setAt(i)} + onClick={() => go(it)} + className={cn( + "relative flex cursor-pointer items-baseline gap-3 rounded-[3px] px-2.5 py-1.5 text-[13px] text-muted", + i === at && "bg-panel-2 text-text before:absolute before:inset-y-1 before:left-0 before:w-[3px] before:bg-signal before:content-['']", + )} + > + <span className="min-w-0 truncate">{it.label}</span> + <span className="ml-auto min-w-0 shrink truncate font-mono text-[11px] text-muted-2">{it.hint}</span> + </div> + </li> + ))} + {items.length === 0 && <li className="px-2.5 py-3 text-[12.5px] text-text-2">Nothing matches “{q}”</li>} + </ul> + <div className="flex items-center gap-3 border-t border-seam px-3.5 py-1.5 text-[11.5px] text-muted-2"> + <span> + <kbd>↑</kbd> <kbd>↓</kbd> move + </span> + <span> + <kbd>enter</kbd> open + </span> + {pieces === null && <span>reading pieces…</span>} + {error && <span className="text-reject-text">{error}</span>} + </div> + </div> + )} + </dialog> + ); +} diff --git a/umtool/components/shell/RailCount.tsx b/umtool/components/shell/RailCount.tsx @@ -0,0 +1,40 @@ +"use client"; + +import { useEffect, useState } from "react"; + +// A count beside a rail place (canvas rail: "Inbox 7", "Work 14"), in Meter. +// Fetched after the page is up (GET /api/rail, memoised server-side), so no +// page waits on the inbox to render its rail. The two places share one request +// per page load. Nothing is shown until it answers, and nothing on a failure: +// a missing count is better than a wrong one. + +type Counts = { inbox: number; work: number }; +let inflight: { at: number; p: Promise<Counts | null> } | null = null; + +function counts(): Promise<Counts | null> { + if (inflight && Date.now() - inflight.at < 2000) return inflight.p; + const p = fetch("/api/rail", { cache: "no-store" }) + .then((r) => (r.ok ? (r.json() as Promise<Counts>) : null)) + .catch(() => null); + inflight = { at: Date.now(), p }; + return p; +} + +export default function RailCount({ which }: { which: keyof Counts }) { + const [n, setN] = useState<number | null>(null); + useEffect(() => { + let live = true; + void counts().then((c) => { + if (live && c && typeof c[which] === "number") setN(c[which]); + }); + return () => { + live = false; + }; + }, [which]); + if (n === null) return null; + return ( + <span className="rail-n" data-rail-count={which} aria-hidden="true"> + {n} + </span> + ); +} diff --git a/umtool/lib/activity.ts b/umtool/lib/activity.ts @@ -78,7 +78,7 @@ function fromChain(j: Job): ActivityItem { ...(clipsOf !== undefined ? { clipsOf, clipsDone } : {}), entries, }, - href: j.project ? `/browse/${j.project}` : "/browse", + href: j.project ? `/projects/${j.project}` : "/work", }; } @@ -91,7 +91,7 @@ function fromRender(r: RenderJob): ActivityItem { startedAt: r.startedAt, endedAt: r.endedAt, error: r.error, - href: "/mix", + href: "/tools/mix", }; } diff --git a/umtool/lib/context.ts b/umtool/lib/context.ts @@ -300,7 +300,7 @@ export async function songContext(id: string): Promise<string> { const undecided = Object.values(song.verdicts).length; out.push( `_${built}/${song.cuts.length} cuts built · ${song.variantCount} live variants · ` + - `${undecided} judged · ${Object.keys(notes).length} notes · generated by umtool /browse._`, + `${undecided} judged · ${Object.keys(notes).length} notes · generated by umtool /projects._`, ); return out.join("\n") + "\n"; diff --git a/umtool/lib/dashboard.ts b/umtool/lib/dashboard.ts @@ -30,7 +30,7 @@ export function stateRows( segments: PROJECT_STATES.map((state) => ({ state, n: mine.filter((p) => p.state === state).length, - href: `/browse?kind=${encodeURIComponent(k.id)}&state=${state}`, + href: `/work?kind=${encodeURIComponent(k.id)}&state=${state}`, })), }; }); diff --git a/umtool/lib/decisions.ts b/umtool/lib/decisions.ts @@ -131,8 +131,8 @@ export async function decisionsForSong(id: string): Promise<Decision[]> { ]); const out: Decision[] = []; - const songHref = `/browse/${id}`; - const cutHref = (cut: string) => `/browse/${id}/${cut}`; + const songHref = `/projects/${id}`; + const cutHref = (cut: string) => `/projects/${id}/${cut}`; const target = { lufs: spec.loudness?.targetLufs ?? DEFAULT_TARGET.lufs, truePeak: spec.loudness?.truePeak ?? DEFAULT_TARGET.truePeak, @@ -359,7 +359,7 @@ export async function noteDecisions(): Promise<Decision[]> { for (const f of files) { const article = f.kind === "article"; const project = article ? `sites/${f.id}` : f.id; - const page = article ? articleHrefOf(f.id) : `/browse/${f.id}`; + const page = article ? articleHrefOf(f.id) : `/projects/${f.id}`; if (f.error || !f.doc) { out.push({ kind: "unreadable-notes", diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -1,11 +1,10 @@ // --------------------------------------------------------------------------- // Every page address umtool links to, one builder per URL shape. // -// The URLs are about to move (plans/umtool-redesign.md, P3: /browse becomes -// /work and /projects, the song tools go under /tools). When they do, the -// change is a body here and a row in redirects.mjs, not a grep across ~70 call -// sites with template literals in them. A link written as a literal from now on -// is a link P3 has to find by hand. +// The URLs moved in P3 (plans/umtool-redesign.md): /browse became Work (/work) +// and the projects (/projects/<id>), the decisions the Inbox (/), and the tools +// went under /tools. Each move was a body here and a row in redirects.mjs. A +// link written as a literal is a link the next move has to find by hand. // // Two contracts: // - `?note=<id>` is ALWAYS the last parameter. The MCP's notes tool reads a @@ -66,13 +65,54 @@ export function withNote(href: string, note: string): string { type NoteOpt = { note?: string | null }; -// ── home and the lists ────────────────────────────────────────────────────── +// ── the places ────────────────────────────────────────────────────────────── -/** The dashboard. `from` is the editor's "make a video" handoff (`/?from=<slug>/<id>`). */ -export function homeHref(q: { from?: string } = {}): string { +/** + * 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). + */ +export function homeHref(q: { from?: string; hidden?: boolean } = {}): string { return withQuery("/", q); } +/** The Inbox (an alias of homeHref, by the place's name). */ +export const inboxHref = homeHref; + +/** Research (R1). */ +export function researchHref(): string { + return "/research"; +} + +/** + * Work: every piece, faceted. It also reads the old lists' keys -- /browse's + * (kind = a project kind, template, state, open, sort), /articles' (status, + * notes, audience) and /sites' (site) -- so an old link lands on the same set. + */ +export type WorkQuery = { + q?: string; + stage?: string; + /** `article`, or a project kind id. */ + kind?: string; + site?: string; + /** active (the default) | parked | done | all. */ + life?: string; + /** `site`: grouped by site. */ + by?: string; + template?: string; + state?: string; + open?: string; + status?: string; + notes?: string; + audience?: string; + sort?: string; + deleted?: string; + freed?: string; +}; +export function workHref(q: WorkQuery = {}): string { + return withQuery("/work", q); +} + export type BrowseQuery = { kind?: string; template?: string; @@ -82,21 +122,26 @@ export type BrowseQuery = { sort?: string; deleted?: string; }; -/** Every project, filtered. */ +/** Every project, filtered -- /browse became Work, which reads these keys. */ export function browseHref(q: BrowseQuery = {}): string { - return withQuery("/browse", q); + return workHref(q); +} + +/** The projects index: every project as a grid, by folder (the old /browse page). `new` opens the new-project form. */ +export function projectsHref(q: BrowseQuery & { new?: boolean } = {}): string { + return withQuery("/projects", q); } export type DecisionsQuery = { severity?: string; kind?: string; project?: string }; -/** The decision list across every project. */ -export function decisionsHref(q: DecisionsQuery = {}): string { - return withQuery("/browse/decisions", q); +/** The decision list became the Inbox. */ +export function decisionsHref(_q: DecisionsQuery = {}): string { + return "/"; } export type ArticlesQuery = { status?: string; notes?: string; audience?: string; deleted?: string; freed?: string }; -/** The article store's list (release 26). */ +/** The article store's articles: Work, kind article. */ export function articlesHref(q: ArticlesQuery = {}): string { - return withQuery("/articles", q); + return workHref({ kind: "article", ...q }); } /** A new article (release 27). */ @@ -104,10 +149,20 @@ export function newArticleHref(): string { return "/articles/new"; } +/** Where the generation policy is set today (the new-article form) until /settings/generation (P5). */ +export function generationPolicyHref(): string { + return "/articles/new"; +} + +/** Settings: the machine -- tools, disk, index, sources, deliverables, recent jobs. */ +export function systemHref(): string { + return "/settings/system"; +} + export type SitesQuery = { site?: string; status?: string; notes?: string }; -/** Every site's articles. */ +/** Every site's articles: Work, grouped by site. */ export function sitesHref(q: SitesQuery = {}): string { - return withQuery("/sites", q); + return workHref({ by: "site", ...q }); } /** One site's page; `ws`+`rel` open a workspace file, `#files` scrolls to it. */ @@ -148,73 +203,83 @@ export function articleCompareHref(id: string, q: { a?: string; b?: string } = { /** A project's page. `all` shows every row of a long list. */ export function projectHref(id: string, q: { all?: boolean } & NoteOpt = {}): string { const { note, ...rest } = q; - return withQuery(`/browse/${encodePath(id)}`, rest, note); + return withQuery(`/projects/${encodePath(id)}`, rest, note); } /** A project by its path, for an id that a tool page shadows at its own URL. */ export function projectAtHref(id: string, q: NoteOpt = {}): string { - return withQuery("/browse/at", { path: id }, q.note); + return withQuery("/projects/at", { path: id }, q.note); } /** The clip bench, one timeline entry. */ export function clipBenchHref(project: string, clip: string, q: NoteOpt = {}): string { - return withQuery(`/browse/${encodePath(project)}/clip/${encodeURIComponent(clip)}`, {}, q.note); + return withQuery(`/projects/${encodePath(project)}/clip/${encodeURIComponent(clip)}`, {}, q.note); } /** The claim bench, one ledger entry. */ export function claimBenchHref(project: string, claim: string, q: NoteOpt = {}): string { - return withQuery(`/browse/${encodePath(project)}/claim/${encodeURIComponent(claim)}`, {}, q.note); + return withQuery(`/projects/${encodePath(project)}/claim/${encodeURIComponent(claim)}`, {}, q.note); } /** Alternative renders of one part of a cut. */ export function takesHref(project: string, q: NoteOpt = {}): string { - return withQuery(`/browse/${encodePath(project)}/takes`, {}, q.note); + return withQuery(`/projects/${encodePath(project)}/takes`, {}, q.note); } /** The narration script, card by card. */ export function narrationHref(project: string, q: NoteOpt = {}): string { - return withQuery(`/browse/${encodePath(project)}/narration`, {}, q.note); + return withQuery(`/projects/${encodePath(project)}/narration`, {}, q.note); } /** The drafts review (release 28). */ export function reviewHref(project: string, q: NoteOpt = {}): string { - return withQuery(`/browse/${encodePath(project)}/review`, {}, q.note); + return withQuery(`/projects/${encodePath(project)}/review`, {}, q.note); } /** One cut of a song; `plan` opens a plan of it, `v` a variant row. */ export function cutHref(song: string, cut: string, q: { plan?: string; v?: string } = {}): string { - return withQuery(`/browse/${encodePath(song)}/${encodeURIComponent(cut)}`, q); + return withQuery(`/projects/${encodePath(song)}/${encodeURIComponent(cut)}`, q); } // ── tools ─────────────────────────────────────────────────────────────────── /** Every occurrence of a word across the corpus. */ export function findHref(q: Query = {}): string { - return withQuery("/browse/find", q); + return withQuery("/tools/find", q); } /** The face judger; `cover` opens on one cover's corners. */ export function facesHref(q: { cover?: string } = {}): string { - return withQuery("/browse/faces", q); + return withQuery("/tools/faces", q); } /** Where the palette comes from, across every song. */ export function sourcesHref(): string { - return "/browse/sources"; + return "/tools/sources"; } /** A trim set's bench. */ export function trimHref(set: string): string { - return `/browse/trim/${encodeURIComponent(set)}`; + return `/tools/trim/${encodeURIComponent(set)}`; } export type MixQuery = { body?: string; start?: string | number; end?: string | number; from?: string; clip?: string }; /** The mix bench; the deep link is resolved server-side (lib/mix-preset.ts). */ export function mixHref(q: MixQuery = {}): string { - return withQuery("/mix", q); + return withQuery("/tools/mix", q); } -/** A song judging pile (`/sort`, `/salvage`, `/verify`, `/keeps`). */ +/** A song judging pile (`/tools/song/sort`, `…/salvage`, `…/verify`, `…/keeps`). */ export function pileHref(mode: string, q: { limit?: number; only?: string } = {}): string { - return withQuery(`/${encodeURIComponent(mode)}`, q); + return withQuery(`/tools/song/${encodeURIComponent(mode)}`, q); +} + +/** Every tool. */ +export function toolsHref(): string { + return "/tools"; +} + +/** The song tools: the four judging piles. */ +export function songToolsHref(): string { + return "/tools/song"; } diff --git a/umtool/lib/inbox/headline.mjs b/umtool/lib/inbox/headline.mjs @@ -0,0 +1,41 @@ +// THE INBOX'S ONE NUMBER (plans/umtool-redesign.md, P3; canvas "Inbox"): the +// calls waiting on the operator, and the sentence under it. Pure, over the +// grouped summary lib/inbox/groups.mjs `summarizeGroups` makes, so the page, +// the rail's count and the CLI say the same number. +// +// calls cards in the groups that ask for a call -- Your call, Review, +// Blocking, Notes, Open -- on ACTIVE pieces (a card is one piece and +// one kind: 483 unadjudicated claims on one video are one call) +// rows the decisions those cards hold +// ready cards in Ready to finish (a suggestion, never a call) +// quiet decisions in Quiet (facts, collapsed) +// hidden decisions on parked or done pieces, every group + +/** The groups whose cards are calls. */ +export const CALL_GROUPS = ["your-call", "review", "blocking", "notes", "open"]; + +/** + * @param {Array<{ id: string, decisions: number, hidden: number, cards: unknown[] }>} groups + * @returns {{ calls: number, rows: number, ready: number, quiet: number, hidden: number }} + */ +export function inboxHeadline(groups) { + const out = { calls: 0, rows: 0, ready: 0, quiet: 0, hidden: 0 }; + for (const g of groups) { + out.hidden += g.hidden; + if (CALL_GROUPS.includes(g.id)) { + out.calls += g.cards.length; + out.rows += g.decisions; + } else if (g.id === "ready-to-finish") out.ready += g.cards.length; + else if (g.id === "quiet") out.quiet += g.decisions; + } + return out; +} + +/** The sentence under the number: "101 rows · 1 piece ready to finish · 126 quiet". */ +export function headlineNote(h) { + const parts = [`${h.rows} row${h.rows === 1 ? "" : "s"}`]; + if (h.ready) parts.push(`${h.ready} piece${h.ready === 1 ? "" : "s"} ready to finish`); + parts.push(`${h.quiet} quiet`); + if (h.hidden) parts.push(`${h.hidden} hidden`); + return parts.join(" · "); +} diff --git a/umtool/lib/inbox/headline.test.mjs b/umtool/lib/inbox/headline.test.mjs @@ -0,0 +1,31 @@ +// The Inbox's one number, over hand-made group summaries. +import assert from "node:assert/strict"; +import test from "node:test"; +import { CALL_GROUPS, headlineNote, inboxHeadline } from "./headline.mjs"; +import { GROUP_IDS } from "./groups.mjs"; + +const g = (id, cards, decisions, hidden = 0) => ({ id, cards: Array.from({ length: cards }, () => ({})), decisions, hidden }); + +test("calls are the cards of the five call groups; ready, quiet and hidden are said apart", () => { + const h = inboxHeadline([ + g("your-call", 1, 1), + g("review", 2, 4), + g("blocking", 1, 35, 483), + g("notes", 1, 14), + g("open", 2, 70), + g("ready-to-finish", 3, 3, 1), + g("quiet", 40, 126, 2), + ]); + assert.deepEqual(h, { calls: 7, rows: 124, ready: 3, quiet: 126, hidden: 486 }); + assert.equal(headlineNote(h), "124 rows · 3 pieces ready to finish · 126 quiet · 486 hidden"); +}); + +test("nothing waiting is zero, and the note keeps its rows and quiet", () => { + const h = inboxHeadline(GROUP_IDS.map((id) => g(id, 0, 0))); + assert.equal(h.calls, 0); + assert.equal(headlineNote(h), "0 rows · 0 quiet"); +}); + +test("the call groups are the groups before Ready to finish, in order", () => { + assert.deepEqual(CALL_GROUPS, GROUP_IDS.slice(0, GROUP_IDS.indexOf("ready-to-finish"))); +}); diff --git a/umtool/lib/last-page.ts b/umtool/lib/last-page.ts @@ -5,7 +5,7 @@ // // The interesting part of "come back to where I was" is not the storage, it is // deciding WHERE to land when the remembered URL has gone stale -- a song gets -// renamed, a cut gets rebuilt away, and /browse/yoshi/wide stops existing. This +// renamed, a cut gets rebuilt away, and /projects/yoshi/wide stops existing. This // app has no app/not-found.tsx, so a stale restore would open the tool on // Next's bare 404, which has no nav on it and no way out but the back button. // So the walk-up lives here, pure and testable without a browser. @@ -15,10 +15,10 @@ export const LAST_PAGE_KEY = "umtool:last-page"; /** * The floor of the walk-up. It was /sort when / was a doorway into the song - * piles; / is the dashboard now, and the page a stale URL degrades to is the - * list of every project rather than one kind's judging pile. + * piles, then /browse; / is the Inbox now, and the page a stale URL degrades to + * is Work, the list of every piece. */ -export const DEFAULT_PAGE = "/browse"; +export const DEFAULT_PAGE = "/work"; /** Long enough for any real query string, short enough to bound a bad write. */ const URL_LIMIT = 2000; @@ -50,8 +50,8 @@ export function isRecordable(url: string): boolean { * Where to try landing, best first. * * The full URL, then the same path without its query, then each parent, then - * DEFAULT_PAGE. `/browse/yoshi/wide` gives - * `["/browse/yoshi/wide", "/browse/yoshi", "/browse"]` -- so a cut + * DEFAULT_PAGE. `/projects/yoshi/wide` gives + * `["/projects/yoshi/wide", "/projects/yoshi", "/projects", "/work"]` -- so a cut * that no longer exists degrades to its song, a song that no longer exists * degrades to the list of songs, and nothing ever lands on a 404. */ diff --git a/umtool/lib/machine.ts b/umtool/lib/machine.ts @@ -0,0 +1,39 @@ +import { statfs } from "node:fs/promises"; +import { toolsCache } from "./doctor"; +import { REPORTS_ROOT } from "./paths"; + +// The machine's own calls for the Inbox: a tool a report build needs that the +// last doctor check found absent, and a reports root nearly out of space. Read +// from the doctor's CACHE and one statfs -- never a probe (the probe is the +// button on /settings/system). SERVER ONLY. + +export type MachineCall = { kind: "machine-tool" | "machine-disk"; why: string; count: number }; + +/** Below this a render or a fetch would fail part-way. */ +export const LOW_DISK_BYTES = 5e9; + +export async function freeBytesUnder(dir: string): Promise<number | null> { + try { + const s = await statfs(dir); + return Number(s.bavail) * Number(s.bsize); + } catch { + return null; + } +} + +export async function machineCalls(): Promise<MachineCall[]> { + const out: MachineCall[] = []; + const missing = toolsCache()?.tools.filter((t) => t.required && !t.present) ?? []; + if (missing.length) { + out.push({ + kind: "machine-tool", + why: `${missing.map((t) => t.id).join(", ")} absent at the last check — a report build cannot run`, + count: missing.length, + }); + } + const free = await freeBytesUnder(REPORTS_ROOT); + if (free !== null && free < LOW_DISK_BYTES) { + out.push({ kind: "machine-disk", why: `${(free / 1e9).toFixed(1)} GB free under the reports root`, count: 1 }); + } + return out; +} diff --git a/umtool/lib/mix-preset.ts b/umtool/lib/mix-preset.ts @@ -80,7 +80,7 @@ export async function resolvePreset(params: { duration: info.duration, hasAudio: info.hasAudio, from: project?.id ?? null, - fromHref: project ? `/browse/${project.id}` : null, + fromHref: project ? `/projects/${project.id}` : null, clip: params.clip ?? null, fileFrom, fileTo: fileFrom + info.duration, diff --git a/umtool/lib/pieces.ts b/umtool/lib/pieces.ts @@ -59,6 +59,8 @@ export type Piece = { href: string; /** An article's: published, draft, or in the making (iterations, no report.json). */ status: "published" | "draft" | "in the making" | null; + /** A store article's audience (public | private); a site's report and a project have none. */ + audience: string | null; /** * Where it is. An article: research (in the making) → article (no video) → * video → deliver (looks done). A project: its own state (draft, windows, @@ -112,6 +114,7 @@ type ArticleIn = { id: string; title: string; status: Piece["status"]; + audience: string | null; hasVideo: boolean; mtimeMs: number; linked: LinkRow[]; @@ -128,6 +131,7 @@ function fromRow(a: ArticleRow): ArticleIn { id: a.id, title: a.title, status: a.status, + audience: a.audience ?? null, hasVideo: a.hasVideo, mtimeMs: a.mtimeMs ?? 0, linked: a.projects.linked, @@ -148,6 +152,7 @@ async function pendingArticles(): Promise<ArticleIn[]> { id, title: id, status: "in the making" as const, + audience: null, hasVideo: false, mtimeMs: 0, linked: links.linked as LinkRow[], @@ -214,7 +219,7 @@ async function buildGraph(): Promise<PieceGraph> { via: p.via ?? "slug", cut: p.id === a.cut, state: summaryOf.get(p.id)?.state ?? null, - href: `/browse/${p.id}`, + href: `/projects/${p.id}`, })); const looksDone: string[] = []; const currentVideo = a.site === ARTICLES_KEY && (its.get(a.id) ?? []).some((x: { current: boolean }) => x.current); @@ -234,6 +239,7 @@ async function buildGraph(): Promise<PieceGraph> { project: null, href: articleHref({ site: a.site, id: a.id }), status: a.status, + audience: a.audience, stage: a.status === "in the making" ? "research" : !projects.length ? "article" : looksDone.length ? "deliver" : "video", projects, possible: a.possible, @@ -253,8 +259,9 @@ async function buildGraph(): Promise<PieceGraph> { site: null, report: null, project: p.id, - href: `/browse/${p.id}`, + href: `/projects/${p.id}`, status: null, + audience: null, stage: p.state, projects: [], possible: [], diff --git a/umtool/lib/projects.ts b/umtool/lib/projects.ts @@ -8,6 +8,7 @@ import { BROWSE_ROOT } from "./browse"; import { decisionsForSong, noteDecisions } from "./decisions"; import { listMedia, listMediaUnder, type MediaRow } from "./media"; import type { Decision } from "./decisions"; +import { projectAtHref } from "./hrefs"; import type { FolderNode, ProjectKindMeta, @@ -193,7 +194,7 @@ export async function summariseProject(p: ProjectRef): Promise<ProjectSummary> { const flags = [...(body.flags ?? [])]; // Routing failures are kind-independent, so they are added here rather than // in any kind's summariser. - if (p.routing === "shadowed") flags.push(`/browse/${p.id.split("/")[0]} is a tool page`); + if (p.routing === "shadowed") flags.push(`/projects/${p.id.split("/")[0]} is a page of its own`); if (p.routing === "unroutable") flags.push("name will not route"); if (p.ambiguousWith) flags.push(`two kinds match: ${p.ambiguousWith.join(", ")}`); @@ -276,8 +277,8 @@ export async function decisionsForProject(p: ProjectRef): Promise<Decision[]> { kind: "shadowed-name", project: p.id, target: p.id.split("/")[0], - why: `/browse/${p.id.split("/")[0]} is a tool page and always wins the route — rename the directory, or open it from here`, - href: `/browse/at?path=${encodeURIComponent(p.id)}`, + why: `/projects/${p.id.split("/")[0]} is a page of its own and always wins the route — rename the directory, or open it from here`, + href: projectAtHref(p.id), severity: "blocking", at: Date.now(), }); @@ -288,7 +289,7 @@ export async function decisionsForProject(p: ProjectRef): Promise<Decision[]> { project: p.id, target: p.name, why: "this name cannot be a URL segment, so the project has no address of its own", - href: `/browse/at?path=${encodeURIComponent(p.id)}`, + href: projectAtHref(p.id), severity: "info", at: Date.now(), }); @@ -299,7 +300,7 @@ export async function decisionsForProject(p: ProjectRef): Promise<Decision[]> { project: p.id, target: p.ambiguousWith.join(" + "), why: "two kinds match this directory — it is read as the first, which is a bug rather than a choice", - href: `/browse/${p.id}`, + href: `/projects/${p.id}`, severity: "blocking", at: Date.now(), }); diff --git a/umtool/lib/projects/core.mjs b/umtool/lib/projects/core.mjs @@ -81,7 +81,7 @@ export async function decisionsFor(p, root = REPORTS_ROOT) { kind: "shadowed-name", project: p.id, target: p.id.split("/")[0], - why: `/browse/${p.id.split("/")[0]} is a tool page and always wins the route`, + why: `/projects/${p.id.split("/")[0]} is a page of its own and always wins the route`, severity: "blocking", at: 0, }); diff --git a/umtool/lib/projects/kinds.mjs b/umtool/lib/projects/kinds.mjs @@ -20,16 +20,19 @@ import { CUT_NAMES, songSignature, summariseSong } from "./song.mjs"; import { sweepSignature, summariseSweep } from "./sweep.mjs"; /** - * Static children of app/browse/. A project whose FIRST path segment is one of - * these can never be opened at its own URL -- a static segment beats a dynamic - * one, so `/browse/find` renders the phrase console no matter what is on disk. + * Static children of app/projects/ (named for app/browse/, where projects lived + * until P3). A project whose FIRST path segment is one of these can never be + * opened at its own URL -- a static segment beats a dynamic one, so + * `/projects/at` renders the escape hatch no matter what is on disk. * * Before this it failed SILENTLY, which is the worst available outcome: the * project is listed, the link is there, and it goes somewhere else entirely. * e2e/projects.spec.ts asserts this list equals the real directory listing, so - * a tenth tool page cannot quietly invalidate it. + * a second static page cannot quietly invalidate it. The tools moved to /tools + * in P3, so `find`, `faces`, `sources`, `trim` and `decisions` are ordinary + * project names again. */ -export const RESERVED_BROWSE = ["at", "decisions", "faces", "find", "sources", "trim"]; +export const RESERVED_BROWSE = ["at"]; /** Directory names the walk never descends into. */ export const SKIP_DIRS = new Set([ diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -764,8 +764,8 @@ export async function reportDecisions(ctx, summary) { const { id, dir } = ctx; const s = summary ?? (await summariseReport(ctx)); const m = s.manifest; - const href = `/browse/${id}`; - const clipHref = (cid) => `/browse/${id}/clip/${cid}`; + const href = `/projects/${id}`; + const clipHref = (cid) => `/projects/${id}/clip/${cid}`; const at = s.newestMtimeMs; const out = []; if (!m) return out; @@ -1018,7 +1018,7 @@ export async function reportDecisions(ctx, summary) { // claim page is opened, one claim at a time. const ledger = Array.isArray(m.ledger) ? m.ledger : []; if (ledger.length) { - const claimHref = (cid) => `/browse/${id}/claim/${cid}`; + const claimHref = (cid) => `/projects/${id}/claim/${cid}`; // One row per entry, not one collapsed row. Forty unpunctuated sources are // the same true thing said forty times; forty unadjudicated claims are diff --git a/umtool/lib/projects/scaffold-song.ts b/umtool/lib/projects/scaffold-song.ts @@ -57,5 +57,5 @@ export async function scaffoldSong({ slug, title }: { slug: string; title?: stri await mkdir(path.join(dir, "variants"), { recursive: true }); await writeFile(path.join(dir, "README.md"), README(id, finalTitle)); const spec = await writeSpec(id, { version: 1, song: id, title: finalTitle }); - return { song: id, spec, href: `/browse/${id}` }; + return { song: id, spec, href: `/projects/${id}` }; } diff --git a/umtool/lib/projects/scaffold.ts b/umtool/lib/projects/scaffold.ts @@ -42,7 +42,7 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str seed: body.seed || null, brand: body.brand || null, }); - result = { ...r, href: `/browse/${r.id}` }; + result = { ...r, href: `/projects/${r.id}` }; } catch (e) { const msg = e instanceof Error ? e.message : String(e); throw new ScaffoldError(msg, /already exists/.test(msg) ? 409 : 400); diff --git a/umtool/lib/rail.ts b/umtool/lib/rail.ts @@ -0,0 +1,40 @@ +import { readInbox } from "./inbox"; +import { inboxHeadline } from "./inbox/headline.mjs"; +import { machineCalls } from "./machine"; +import { listPieces } from "./pieces"; + +// The rail's two counts (canvas rail: "Inbox 7", "Work 14"): the calls waiting +// (lib/inbox/headline.mjs, plus the machine's) and the active pieces. Every +// page's rail asks for them after it loads (components/shell/RailCount.tsx), so +// they are memoised for a few seconds -- on globalThis, so every bundle shares +// one copy (the P2a project-cache lesson) -- and cleared by a lifecycle write. +// SERVER ONLY. + +export type RailCounts = { inbox: number; work: number }; + +const MEMO_MS = 10_000; +const KEY = Symbol.for("umtool.rail-counts"); +type Memo = { at: number; value: Promise<RailCounts> } | null; +const store = globalThis as unknown as Record<symbol, Memo>; + +export function clearRailCounts(): void { + store[KEY] = null; +} + +export function railCounts(): Promise<RailCounts> { + const m = store[KEY]; + if (m && Date.now() - m.at < MEMO_MS) return m.value; + const value = (async () => { + const [inbox, pieces, machine] = await Promise.all([readInbox(), listPieces(), machineCalls()]); + return { + inbox: inboxHeadline(inbox.groups).calls + machine.length, + work: pieces.filter((p) => p.lifecycle === "active").length, + }; + })(); + const entry = { at: Date.now(), value }; + store[KEY] = entry; + value.catch(() => { + if (store[KEY] === entry) store[KEY] = null; + }); + return value; +} diff --git a/umtool/lib/spec.ts b/umtool/lib/spec.ts @@ -239,7 +239,7 @@ export function operationsFor(spec: Spec, song: Song | null): Operation[] { id: "trim-hooks", label: "trim the vocal hooks", structure: "hooks", - href: `/browse/trim/${spec.hooks.trimSet}`, + href: `/tools/trim/${spec.hooks.trimSet}`, } : { id: "trim-hooks", diff --git a/umtool/lib/work.ts b/umtool/lib/work.ts @@ -0,0 +1,108 @@ +import { readInbox, type Inbox } from "./inbox"; +import { readLifecycle } from "./lifecycle"; +import { KINDS, listProjects } from "./projects"; +import { listPieces, type PieceWithLifecycle } from "./pieces"; +import { stageOf, stepOf } from "./work/facets.mjs"; + +// --------------------------------------------------------------------------- +// WORK, AS DATA: every piece (lib/pieces.ts) as one row for the Work list -- +// its stage on the four-step bar, what kind of thing it is, its lifecycle and +// how many calls wait on it -- plus the facts the facets filter on +// (lib/work/facets.mjs). GET /api/pieces gives the same counts. +// +// SERVER ONLY. +// --------------------------------------------------------------------------- + +export type PieceCounts = { + /** Every decision on the piece, hidden ones included. */ + total: number; + /** On a parked or done piece. */ + hidden: number; + /** Visible decisions per inbox group. */ + byGroup: Record<string, number>; + /** Visible calls (the five call groups) -- Work's "Open" column. */ + calls: number; + /** By severity over every decision, hidden or not (the old /browse `open` filter). */ + blocking: number; + open: number; + /** Open notes (the old /articles and /sites `notes=open`). */ + notes: number; +}; + +export type WorkRow = PieceWithLifecycle & { + /** research | article | video | deliver. */ + bucket: string; + step: number; + /** What the stage bar says: an article's stage, a project's own state. */ + stageLabel: string; + /** `article` and/or project kind ids. */ + kinds: string[]; + kindLabel: string; + templates: string[]; + states: string[]; + projectState: string | null; + haystack: string; + counts: PieceCounts; +}; + +const CALL_GROUPS = new Set(["your-call", "review", "blocking", "notes", "open"]); + +/** Decision counts per piece, from one inbox read. */ +export function countsByPiece(inbox: Inbox): Map<string, PieceCounts> { + const out = new Map<string, PieceCounts>(); + for (const d of inbox.items) { + if (!d.piece) continue; + let c = out.get(d.piece); + if (!c) out.set(d.piece, (c = { total: 0, hidden: 0, byGroup: {}, calls: 0, blocking: 0, open: 0, notes: 0 })); + c.total += 1; + if (d.severity === "blocking") c.blocking += 1; + else if (d.severity === "open") c.open += 1; + if (d.kind === "open-note") c.notes += 1; + if (d.hidden) c.hidden += 1; + else if (d.group) { + c.byGroup[d.group] = (c.byGroup[d.group] ?? 0) + 1; + if (CALL_GROUPS.has(d.group)) c.calls += 1; + } + } + return out; +} + +const EMPTY: PieceCounts = { total: 0, hidden: 0, byGroup: {}, calls: 0, blocking: 0, open: 0, notes: 0 }; + +export async function readWork(): Promise<{ rows: WorkRow[]; lifecycleError?: string }> { + const life = await readLifecycle(); + const [pieces, inbox, projects] = await Promise.all([listPieces(life), readInbox(), listProjects()]); + const counts = countsByPiece(inbox); + const byId = new Map(projects.map((p) => [p.id, p])); + const label = new Map(KINDS.map((k) => [k.id, k.label])); + + const rows = pieces.map((p): WorkRow => { + const own = p.project ? byId.get(p.project) : undefined; + const linked = p.projects.map((x) => byId.get(x.id)).filter((x) => x !== undefined); + const mine = own ? [own] : linked; + const projectKinds = [...new Set(mine.map((x) => x.kind))]; + const kinds = p.kind === "article" ? ["article", ...projectKinds] : projectKinds; + const kindLabel = + p.kind === "article" + ? projectKinds.length + ? `article + ${projectKinds.map((k) => label.get(k) ?? k).join(", ")}` + : "article" + : (projectKinds.map((k) => label.get(k) ?? k).join(", ") || "project"); + const projectState = own?.state ?? null; + const bucket = stageOf({ kind: p.kind, stage: p.stage, looksDone: p.looksDone, projectState }); + return { + ...p, + bucket, + step: stepOf(bucket), + stageLabel: p.kind === "article" ? p.stage : (projectState ?? p.stage), + kinds, + kindLabel, + templates: [...new Set(mine.map((x) => x.template))], + states: [...new Set(mine.map((x) => x.state))], + projectState, + haystack: [p.site, p.report, ...mine.map((x) => x.haystack)].filter(Boolean).join("\n"), + counts: counts.get(p.id) ?? EMPTY, + }; + }); + return { rows, ...(life.error ? { lifecycleError: life.error } : {}) }; +} diff --git a/umtool/lib/work/facets.mjs b/umtool/lib/work/facets.mjs @@ -0,0 +1,87 @@ +// WORK'S FACETS (plans/umtool-redesign.md, P3): which pieces a query keeps, and +// the stage a piece is at. Pure, over plain rows (lib/work.ts builds them), so +// the filtering is unit-tested and the page only renders. +// +// Work reads its own keys AND the old lists' keys, so an old link lands on the +// same set: +// +// its own q, stage, kind, site, life, by, sort +// /browse kind (a project kind id), template, state (a project state), +// open (blocking | 1), q, sort (name), deleted +// /articles kind=article (the redirect adds it), status, notes (open), +// audience, deleted, freed +// /sites by=site (the redirect adds it), site, status, notes +// +// A piece's KINDS are what it is: an article piece is `article` plus the kind +// of every project linked to it, a project piece is its project's kind. So the +// old `/browse?kind=<a video kind>` still finds the article whose video it is. + +/** The four stages a piece walks, in order (canvas "Work", the stage bar). */ +export const STAGES = ["research", "article", "video", "deliver"]; + +export const LIFECYCLES = ["active", "parked", "done"]; + +/** + * A piece's stage bucket: an article's own stage; a project's `deliver` when + * it looks done (or ships), else `video` -- its own state word is its label. + * + * @param {{ kind: string, stage: string, looksDone: string[], projectState?: string | null }} p + */ +export function stageOf(p) { + if (p.kind === "article") return STAGES.includes(p.stage) ? p.stage : "article"; + if (p.looksDone.length || p.projectState === "shipped") return "deliver"; + return "video"; +} + +/** 1-based position on the stage bar. */ +export const stepOf = (bucket) => STAGES.indexOf(bucket) + 1; + +/** `life`: one of the three, `all`, or (absent) active. */ +export function lifeFilter(life) { + if (life === "all") return null; + return LIFECYCLES.includes(life) ? life : "active"; +} + +/** + * Does a row stay under a query? + * + * @param {{ + * id: string, title: string, kinds: string[], bucket: string, site: string | null, + * lifecycle: string, templates: string[], states: string[], status: string | null, + * audience: string | null, haystack: string, + * counts: { blocking: number, open: number, notes: number }, + * }} r + * @param {Record<string, string | undefined>} q + * @param {{ ignore?: string[] }} [opts] keys to leave out (a facet's own counts) + */ +export function keepRow(r, q, { ignore = [] } = {}) { + const on = (k) => !ignore.includes(k) && q[k]; + if (on("stage") && r.bucket !== q.stage) return false; + if (on("kind") && !r.kinds.includes(q.kind)) return false; + if (on("site") && r.site !== q.site) return false; + if (!ignore.includes("life")) { + const life = lifeFilter(q.life); + if (life && r.lifecycle !== life) return false; + } + if (on("template") && !r.templates.includes(q.template)) return false; + if (on("state") && !r.states.includes(q.state)) return false; + if (on("status") && r.status !== q.status) return false; + if (on("audience") && r.audience !== q.audience) return false; + if (on("notes") && q.notes === "open" && r.counts.notes <= 0) return false; + if (on("open")) { + if (q.open === "blocking" ? r.counts.blocking <= 0 : r.counts.blocking + r.counts.open <= 0) return false; + } + if (on("q")) { + const needle = q.q.trim().toLowerCase(); + if (needle && !`${r.title}\n${r.id}\n${r.haystack}`.toLowerCase().includes(needle)) return false; + } + return true; +} + +/** Newest first, or by title (`sort=name`), id breaking ties. */ +export function sortRows(rows, sort) { + const out = [...rows]; + if (sort === "name") out.sort((a, b) => a.title.localeCompare(b.title) || a.id.localeCompare(b.id)); + else out.sort((a, b) => b.newestMs - a.newestMs || a.id.localeCompare(b.id)); + return out; +} diff --git a/umtool/lib/work/facets.test.mjs b/umtool/lib/work/facets.test.mjs @@ -0,0 +1,73 @@ +// Work's facets: pure, over hand-made rows. +import assert from "node:assert/strict"; +import test from "node:test"; +import { keepRow, lifeFilter, sortRows, stageOf, stepOf } from "./facets.mjs"; + +const row = (over = {}) => ({ + id: "a:articles/poker", + title: "Zero dollars to play", + kinds: ["article", "vid"], + bucket: "video", + site: "articles", + lifecycle: "active", + templates: ["report"], + states: ["built"], + status: "published", + audience: "public", + haystack: "poker deposit", + counts: { blocking: 0, open: 0, notes: 0 }, + newestMs: 0, + ...over, +}); + +test("a stage is an article's own, and a project's deliver or video", () => { + assert.equal(stageOf({ kind: "article", stage: "research", looksDone: [] }), "research"); + assert.equal(stageOf({ kind: "article", stage: "deliver", looksDone: ["x"] }), "deliver"); + assert.equal(stageOf({ kind: "project", stage: "built", looksDone: [] }), "video"); + assert.equal(stageOf({ kind: "project", stage: "built", looksDone: ["final video and share-1"] }), "deliver"); + assert.equal(stageOf({ kind: "project", stage: "shipped", looksDone: [], projectState: "shipped" }), "deliver"); + assert.deepEqual(["research", "article", "video", "deliver"].map(stepOf), [1, 2, 3, 4]); +}); + +test("lifecycle defaults to active; all shows every piece", () => { + assert.equal(lifeFilter(undefined), "active"); + assert.equal(lifeFilter("junk"), "active"); + assert.equal(lifeFilter("parked"), "parked"); + assert.equal(lifeFilter("all"), null); + assert.equal(keepRow(row({ lifecycle: "done" }), {}), false); + assert.equal(keepRow(row({ lifecycle: "done" }), { life: "done" }), true); + assert.equal(keepRow(row({ lifecycle: "done" }), { life: "all" }), true); +}); + +test("the old /browse keys: a project kind finds the article whose video it is; state, template, open", () => { + assert.equal(keepRow(row(), { kind: "vid" }), true); + assert.equal(keepRow(row(), { kind: "song" }), false); + assert.equal(keepRow(row(), { state: "built", template: "report" }), true); + assert.equal(keepRow(row(), { state: "draft" }), false); + assert.equal(keepRow(row(), { open: "1" }), false); + assert.equal(keepRow(row({ counts: { blocking: 0, open: 2, notes: 0 } }), { open: "1" }), true); + assert.equal(keepRow(row({ counts: { blocking: 0, open: 2, notes: 0 } }), { open: "blocking" }), false); +}); + +test("the old /articles and /sites keys: status, audience, notes, site", () => { + assert.equal(keepRow(row(), { kind: "article", status: "draft" }), false); + assert.equal(keepRow(row(), { kind: "article", status: "published", audience: "public" }), true); + assert.equal(keepRow(row(), { notes: "open" }), false); + assert.equal(keepRow(row({ counts: { blocking: 0, open: 0, notes: 3 } }), { notes: "open" }), true); + assert.equal(keepRow(row(), { site: "jeralyzer" }), false); +}); + +test("search reads the title, the id and the haystack; a facet can ignore itself", () => { + assert.equal(keepRow(row(), { q: "DEPOSIT" }), true); + assert.equal(keepRow(row(), { q: "a:articles/poker" }), true); + assert.equal(keepRow(row(), { q: "ferret" }), false); + assert.equal(keepRow(row(), { stage: "deliver" }), false); + assert.equal(keepRow(row(), { stage: "deliver" }, { ignore: ["stage"] }), true); +}); + +test("sort: newest first, or by title", () => { + const rows = [row({ id: "a", title: "B", newestMs: 1 }), row({ id: "b", title: "A", newestMs: 2 })]; + assert.deepEqual(sortRows(rows).map((r) => r.id), ["b", "a"]); + assert.deepEqual(sortRows(rows, "name").map((r) => r.id), ["b", "a"]); + assert.deepEqual(sortRows([row({ id: "x", title: "A" }), row({ id: "y", title: "B", newestMs: 9 })], "name").map((r) => r.id), ["x", "y"]); +}); diff --git a/umtool/next.config.ts b/umtool/next.config.ts @@ -24,7 +24,7 @@ const nextConfig: NextConfig = { // umtool runs `next start`, which shows no indicator.) devIndicators: { position: "bottom-right" }, // Every old page address and where it lives now: ONE table, redirects.mjs, - // which e2e/redirects.spec.ts (P3) reads too. Empty until P3 moves a page. + // which e2e/redirects.spec.ts reads too. async redirects() { return nextRedirects(); }, diff --git a/umtool/redirects.mjs b/umtool/redirects.mjs @@ -1,5 +1,5 @@ // --------------------------------------------------------------------------- -// Every old umtool page address, and where it lives now. EMPTY until P3. +// Every old umtool page address, and where it lives now. // // ONE table, read by two things (plans/umtool-redesign.md, "Redirects"): // - next.config.ts's `redirects()`, which answers them. Next checks redirects @@ -39,8 +39,36 @@ * }} 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); `/bench` → `/tools/bench` (after release 28 lands +// its verdict bench at /bench); `/drafts` → `/` (P6 deletes the page). + +const p3 = (source, destination) => ({ source, destination, permanent: false, phase: "P3" }); + /** @type {RedirectRow[]} */ -export const REDIRECTS = []; +export const REDIRECTS = [ + // The project list became Work; the decision list became the Inbox. + p3("/browse", "/work"), + p3("/browse/decisions", "/"), + // The tool pages that were static children of /browse -- BEFORE the + // catch-all, which would send them to a project of that name. + p3("/browse/find", "/tools/find"), + p3("/browse/faces", "/tools/faces"), + p3("/browse/sources", "/tools/sources"), + p3("/browse/trim/:set", "/tools/trim/:set"), + // The escape hatch for a project with no address of its own (a name that + // cannot be a URL segment, or one that is `at`). + p3("/browse/at", "/projects/at"), + // Every project, cut and bench: /browse/<id>[/<view>…] → /projects/<id>[/<view>…]. + p3("/browse/:path*", "/projects/:path*"), + // The article lists are Work's facets now. + p3("/articles", "/work?kind=article"), + p3("/sites", "/work?by=site"), + // The song tools. + p3("/mix", "/tools/mix"), + p3("/:mode(sort|salvage|verify|keeps)", "/tools/song/:mode"), +]; /** The rows in the shape next.config.ts's `redirects()` returns. */ export function nextRedirects() {