"use client"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { benchHref, digestContextHref, postsLibraryHref, createHref, facesHref, findHref, generationPolicyHref, homeHref, mixHref, pileHref, projectsHref, researchHref, songToolsHref, sourcesHref, systemHref, toolsHref, workHref, phraseFinderHref, } from "@/lib/hrefs"; import { MODES } from "@/lib/types"; import { announceManifestChanged } from "@/components/projects/timelineApi"; import { cn } from "@/lib/utils"; import CommandForm, { type CliContext, type CliRun, type CliVerb, type Value } from "./CommandForm"; // --------------------------------------------------------------------------- // ⌘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 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`. // // COMMANDS (lane palette, L8a): every umtool verb the registry offers as a // form (lib/cli/verbs.mjs, GET /api/cli), matched on its verb and summary once // something is typed (`>` first: commands only, all of them with nothing // after it). Choosing one opens its form in place (CommandForm), the page's // project and selection filled in -- GET /api/cli?path= says what the page is // about, asked each time the palette opens (and reset first, so a quick pick never // gets the last page's project: the form is keyed on the context and remounts when // it arrives). What a form's Run started stays under Runs (nothing typed) for // the page's life, so an Escape mid-run loses nothing. // // A WORKSPACE BLOCK'S MENU (lane block-menus L8b) opens a verb's form here, the // same form, with `umtool:command` ({ row, values }: the row and what the // block filled in) -- one form component, one Runs list, one POST /api/cli. // // EVERY RUN IS WATCHED TO ITS END here, open or closed (the palette is mounted // once, for the page's life): a run that ends done and names a project // announces a write to it (MANIFEST_CHANGED, by the id the server resolved), // whatever its target -- `links --embed-ids` writes the draft too -- and a // queued one that ends after an Escape still does. A re-read is cheap. // --------------------------------------------------------------------------- export const JUMP_EVENT = "umtool:jump"; export const COMMAND_EVENT = "umtool:command"; /** `umtool:command`'s detail: the row's form opened with these values over the page's context. */ export type CommandRequest = { row: CliVerb; values: Record }; /** Open one verb's form in the palette, pre-filled (a block's menu). */ export function openCommand(req: CommandRequest) { window.dispatchEvent(new CustomEvent(COMMAND_EVENT, { detail: req })); } type Item = { id: string; section: "Runs" | "Places" | "Tools" | "Create" | "Pieces" | "Commands"; label: string; hint: string; href: string; verb?: string; run?: CliRun }; const NO_CONTEXT: CliContext = { project: null, clip: null, post: null, take: null }; const clock = (ms: number) => new Date(ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); 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, phrases, song piles, faces, sources", href: toolsHref() }, { id: "system", section: "Places", label: "Settings · system", hint: "tools, disk, index, sources, recent jobs", href: systemHref() }, { id: "create", section: "Places", label: "Create", hint: "what are you making?", href: createHref() }, { id: "policy", section: "Places", label: "Settings · generation", hint: "routes, models, caps, the key, today's spend", href: generationPolicyHref() }, { id: "find", section: "Tools", label: "Find", hint: "every occurrence of a word", href: findHref() }, { id: "mix", section: "Tools", label: "Mix", hint: "the mix bench", href: mixHref() }, { id: "phrases", section: "Tools", label: "Phrases", hint: "how often a phrase was said, by year; a montage from it", href: phraseFinderHref() }, { 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: "bench", section: "Tools", label: "Verdict bench", hint: "could a model propose a verdict", href: benchHref() }, { id: "context", section: "Tools", label: "Channel context notes", hint: "each suggested digest note, its evidence, Yes or No", href: digestContextHref() }, { id: "library", section: "Tools", label: "Posts library", hint: "a private trending library: keep, drop, later, watch", href: postsLibraryHref() }, // Each opens one line of /create (P5), its form open. { id: "new-research", section: "Create", label: "Research a question", hint: "opens a case", href: createHref({ make: "research" }) }, { id: "new-article", section: "Create", label: "New article", hint: "from a question: a sweep", href: createHref({ make: "article" }) }, { id: "new-article-board", section: "Create", label: "New article from a board", hint: "a seeded sweep, planned first", href: createHref({ make: "article-board" }) }, { id: "new-recurring", section: "Create", label: "New recurring report", hint: "a living report or a dated series", href: createHref({ make: "recurring" }) }, { id: "new-video-article", section: "Create", label: "New video from an article", hint: "the chain over an iteration", href: createHref({ make: "video-article" }) }, { id: "new-video-board", section: "Create", label: "New video from a board", hint: "a timeline from the pinned cites", href: createHref({ make: "video-board" }) }, { id: "new-video-recording", section: "Create", label: "New video from a recording", hint: "a URL or channel/id", href: createHref({ make: "video-recording" }) }, { id: "new-video-report", section: "Create", label: "New video from a sweep report", hint: "a cited report on disk", href: createHref({ make: "video-report" }) }, { id: "new-song", section: "Create", label: "New song", hint: "a song cut", href: createHref({ make: "song" }) }, ]; const words = (q: string) => q.toLowerCase().split(/\s+/).filter(Boolean); /** Each letter of `w` in `s`, in order: "tlins" finds "timeline insert". */ const subsequence = (w: string, s: string) => { let i = 0; for (const ch of s) if (ch === w[i]) i += 1; return i === w.length; }; /** How well a verb answers the words typed: 0 is not at all. */ function commandScore(v: CliVerb, w: string[]): number { const verb = v.verb.toLowerCase(); const hay = `${verb} ${v.summary.toLowerCase()}`; let score = 0; for (const x of w) { if (verb.startsWith(x)) score += 4; else if (verb.split(" ").some((part) => part.startsWith(x))) score += 3; else if (verb.includes(x)) score += 2; else if (hay.includes(x)) score += 1; else if (x.length >= 3 && subsequence(x, verb.replace(/[ -]/g, ""))) score += 0.5; else return 0; } return score; } export default function JumpPalette() { const router = useRouter(); const dialog = useRef(null); const input = useRef(null); const list = useRef(null); const [open, setOpen] = useState(false); const [q, setQ] = useState(""); const [at, setAt] = useState(0); const [pieces, setPieces] = useState(null); const [error, setError] = useState(null); // Set once the chord is listened for, so a test (or a script) can wait for it. const [ready, setReady] = useState(false); const [verbs, setVerbs] = useState(null); const [ctx, setCtx] = useState(NO_CONTEXT); const [form, setForm] = useState(null); const [resume, setResume] = useState(null); const [runs, setRuns] = useState([]); const [prefill, setPrefill] = useState | null>(null); // The runs' ends: each told once (the form tells it at once; the watcher below for the rest). const ended = useRef(new Set()); const runsRef = useRef(runs); runsRef.current = runs; const endRun = useCallback((id: string, state: string) => { if (ended.current.has(id)) return; ended.current.add(id); const r = runsRef.current.find((x) => x.id === id); if (state === "done" && r?.project) announceManifestChanged(r.project); }, []); const anyRunning = runs.some((r) => !ended.current.has(r.id)); useEffect(() => { if (!anyRunning) return; let live = true; const t = setInterval(async () => { for (const r of runsRef.current) { if (ended.current.has(r.id)) continue; try { const url = r.kind === "job" ? `/api/cli?job=${encodeURIComponent(r.id)}&since=1000000` : `/api/cli?qid=${encodeURIComponent(r.id)}`; const res = await fetch(url, { cache: "no-store" }); if (!live) return; if (res.status === 404) { endRun(r.id, "gone"); continue; } const j = (await res.json()) as { job?: { state: string }; step?: { state: string } }; const state = j.job?.state ?? j.step?.state ?? ""; if (["done", "failed", "cancelled", "blocked"].includes(state)) endRun(r.id, state); } catch { /* the next turn asks again */ } } }, 1500); return () => { live = false; clearInterval(t); }; }, [anyRunning, runs, endRun]); const show = useCallback(() => { setQ(""); setAt(0); setForm(null); setResume(null); setPrefill(null); setCtx(NO_CONTEXT); 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(); const onCommand = (e: Event) => { const req = (e as CustomEvent).detail; if (!req?.row?.verb) return; show(); setForm(req.row); setPrefill(req.values ?? {}); }; document.addEventListener("keydown", onKey); window.addEventListener(JUMP_EVENT, onJump); window.addEventListener(COMMAND_EVENT, onCommand); setReady(true); return () => { document.removeEventListener("keydown", onKey); window.removeEventListener(JUMP_EVENT, onJump); window.removeEventListener(COMMAND_EVENT, onCommand); }; }, [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]); // The verbs, and what this page is about, each time it opens (the page may have changed). useEffect(() => { if (!open) return; let live = true; const path = `${window.location.pathname}${window.location.search}`; fetch(`/api/cli?path=${encodeURIComponent(path)}`, { cache: "no-store" }) .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))) .then((j: { verbs: CliVerb[]; context: CliContext }) => { if (!live) return; setVerbs(j.verbs); setCtx(j.context); }) .catch(() => live && setVerbs((v) => v ?? [])); return () => { live = false; }; }, [open]); const items = useMemo(() => { const commandsOnly = q.trimStart().startsWith(">"); const cw = words(commandsOnly ? q.trimStart().slice(1) : q); const commands = (verbs ?? []) .map((v) => ({ v, s: cw.length ? commandScore(v, cw) : 1 })) .filter((x) => x.s > 0) .sort((a, b) => b.s - a.s || a.v.verb.localeCompare(b.v.verb)) .map(({ v }): Item => ({ id: `cmd:${v.verb}`, section: "Commands", label: v.verb, hint: v.summary, href: "", verb: v.verb })); if (commandsOnly) return commands.slice(0, 80); 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); const recent = runs.map( (r): Item => ({ id: `run:${r.id}`, section: "Runs", label: r.verb, hint: `${r.kind === "queued" ? "queued " : ""}${r.id} · ${clock(r.at)}`, href: "", verb: r.verb, run: r }), ); if (!w.length) return [...recent, ...all.filter((it) => it.section !== "Pieces"), ...all.filter((it) => it.section === "Pieces").slice(0, 8)]; const cmds = commands.slice(0, 12); 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) .concat(cmds); }, [q, pieces, verbs, runs]); useEffect(() => { list.current?.querySelector(`[data-jump-index="${at}"]`)?.scrollIntoView({ block: "nearest" }); }, [at]); const go = (it: Item | undefined) => { if (!it) return; if (it.verb) { const v = verbs?.find((x) => x.verb === it.verb); if (v) { setResume(it.run ?? null); setPrefill(null); setForm(v); } return; } setOpen(false); router.push(it.href); }; return ( setOpen(false)} className={cn( "ui-dialog mx-auto mb-auto mt-[12vh] rounded-[3px] border border-seam-2 bg-panel p-0 text-text shadow-2xl", form ? "w-[min(780px,calc(100vw-32px))]" : "w-[min(640px,calc(100vw-32px))]", )} > {open && form && (
{ runsRef.current = [r, ...runsRef.current.filter((x) => x.id !== r.id)].slice(0, 8); setRuns(runsRef.current); }} onEnded={endRun} onBack={() => { setForm(null); setResume(null); setPrefill(null); setTimeout(() => input.current?.focus(), 0); }} />
)} {open && !form && (
{ 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" /> esc
    {items.map((it, i) => (
  • {(i === 0 || items[i - 1].section !== it.section) && (
    {it.section}
    )}
    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-['']", )} > {it.verb ? `umtool ${it.label}` : it.label} {it.hint}
  • ))} {items.length === 0 &&
  • Nothing matches “{q}”
  • }
↑ ↓ move enter open > commands {pieces === null && reading pieces…} {error && {error}}
)}
); }