"use client"; import { useEffect, useMemo, useRef, useState } from "react"; import { buildArgv, cliLine, confirmOf } from "@/lib/cli/argv.mjs"; import { cn } from "@/lib/utils"; // --------------------------------------------------------------------------- // ONE VERB AS A FORM (⌘K Commands, lane palette L8a): a row of the verb // registry (lib/cli/verbs.mjs, served by GET /api/cli) drawn as its args, the // page's project and selection filled in; the exact command line under it // (Copy as CLI -- built by the same lib/cli/argv.mjs the server builds argv // with); Run posts { verb, values } to /api/cli and follows what it started: // the app job's live log, or the queued step's. A row with `confirm` (no undo: // it deletes, evicts or kills) asks a second press, "Yes, ", // and the server wants that confirm too. What Run started is handed up // (onStarted), so the palette lists it under Runs after an Escape. // // A workspace block's menu (lane block-menus L8b) opens this same form with // `prefill`: what the block filled in (verbs.mjs fromBlockValues), over the // page's context; the focus goes to the first arg still to give. When a run // ends the form says so (onEnded); the palette, which watches every run to its // end even after this form is gone, announces a done run's write. // --------------------------------------------------------------------------- export type CliArg = { name: string; type: string; required?: boolean; choices?: string[]; default?: unknown; help?: string; repeat?: boolean; context?: string }; export type CliVerb = { verb: string; summary: string; target: string; queue: boolean; confirm?: { what: string; when?: string[]; unless?: string[] } | null; args: CliArg[]; /** The block kinds whose menu offers it, what a block fills in, and a page it opens instead (lib/cli/verbs.mjs). */ blocks?: string[]; fromBlock?: Record; nav?: string; }; export type CliContext = { project: string | null; clip: string | null; post: string | null; take: string | null }; export type Value = string | boolean; /** A run the palette keeps: its form's values and what it started. */ export type CliRun = { verb: string; values: Record; kind: "job" | "queued"; id: string; line: string; at: number; /** The project it names, resolved by the server (its id): a done run announces a write to it. */ project: string | null; }; type Run = | { kind: "job"; id: string; state: string; log: string[]; next: number; error: string | null; exitCode: number | null } | { kind: "queued"; qid: string; state: string; log: string[]; error: string | null; exitCode: number | null; runnerUp: boolean }; const TEXTAREA = new Set(["pairs", "flagpairs", "list", "text", "json"]); const TERMINAL = new Set(["done", "failed", "cancelled", "blocked"]); /** What the page tells the form: the project for a project arg, the selection for one that asks. */ function initialValues(row: CliVerb, ctx: CliContext, prefill: Record | null): Record { const v: Record = {}; for (const a of row.args) { if (a.type === "project" && a.name === "project" && ctx.project) v[a.name] = ctx.project; else if (a.context === "clip" && ctx.clip) v[a.name] = ctx.clip; else if (a.context === "post" && ctx.post) v[a.name] = ctx.post; else if (a.context === "take" && ctx.take && a.required) v[a.name] = ctx.take; else if (a.default !== undefined) v[a.name] = typeof a.default === "boolean" ? a.default : String(a.default); } return prefill ? { ...v, ...prefill } : v; } export default function CommandForm({ row, ctx, onBack, resume = null, prefill = null, onStarted, onEnded, }: { row: CliVerb; ctx: CliContext; onBack: () => void; /** Values a block's menu filled in (over the page's context). */ prefill?: Record | null; /** A run started before (the palette's Runs): its values, and it is followed again. */ resume?: CliRun | null; onStarted?: (run: CliRun) => void; /** What Run started ended (done, failed, cancelled, blocked): its id. */ onEnded?: (id: string, state: string) => void; }) { const [values, setValues] = useState>(() => (resume ? resume.values : initialValues(row, ctx, prefill))); const [run, setRun] = useState(() => resume ? resume.kind === "job" ? { kind: "job", id: resume.id, state: "running", log: [], next: 0, error: null, exitCode: null } : { kind: "queued", qid: resume.id, state: "queued", log: [], error: null, exitCode: null, runnerUp: true } : null, ); const [asking, setAsking] = useState(null); const [posting, setPosting] = useState(false); const [refused, setRefused] = useState(null); const [copied, setCopied] = useState(false); const first = useRef(null); const logRef = useRef(null); // The field the focus starts in: the first required arg still empty when something was filled in for it, else the first. const [focusAt] = useState(() => { if (!prefill) return 0; const i = row.args.findIndex((a) => a.required && (values[a.name] === undefined || values[a.name] === "")); return i >= 0 ? i : 0; }); useEffect(() => { first.current?.focus(); // Opened with the palette in one go (a block's menu): the dialog's showModal runs after this and focuses its // first button, so the field is focused again once it has. const f = requestAnimationFrame(() => { if (first.current && document.activeElement !== first.current && first.current.closest("dialog")?.contains(document.activeElement)) first.current.focus(); }); return () => cancelAnimationFrame(f); }, []); const built = useMemo(() => buildArgv(row, values), [row, values]); const line = built.ok ? cliLine(built.argv) : null; const going = posting || (run !== null && !TERMINAL.has(run.state)); // Follow what Run started. useEffect(() => { if (!run || TERMINAL.has(run.state)) return; let live = true; const t = setTimeout(async () => { try { if (run.kind === "job") { const r = await fetch(`/api/cli?job=${encodeURIComponent(run.id)}&since=${run.next}`, { cache: "no-store" }); const j = (await r.json()) as { job?: { state: string; log: string[]; next: number; error: string | null; exitCode: number | null } }; if (!live) return; if (!j.job) { setRun((cur) => (cur ? { ...cur, state: "failed", error: "the app no longer knows this job (it restarted): see Settings · system" } : cur)); return; } const job = j.job; setRun((cur) => (cur && cur.kind === "job" ? { ...cur, state: job.state, log: [...cur.log, ...job.log].slice(-400), next: job.next, error: job.error, exitCode: job.exitCode } : cur)); } else { const r = await fetch(`/api/cli?qid=${encodeURIComponent(run.qid)}`, { cache: "no-store" }); const j = (await r.json()) as { step?: { state: string; error: string | null; exitCode: number | null }; log?: string[]; runner?: { enabled: boolean; armed: boolean } }; if (!live) return; if (!j.step) { setRun((cur) => (cur ? { ...cur, state: "failed", error: "no such step in the queue" } : cur)); return; } const step = j.step; setRun((cur) => (cur && cur.kind === "queued" ? { ...cur, state: step.state, log: j.log ?? [], error: step.error, exitCode: step.exitCode, runnerUp: !!j.runner?.armed } : cur)); } } catch { /* the next turn tries again */ } }, 700); return () => { live = false; clearTimeout(t); }; }, [run]); useEffect(() => { const el = logRef.current; if (el) el.scrollTop = el.scrollHeight; }, [run?.log.length]); // The run's end, told up at once (the palette also watches it, for after this form is gone). const runId = run ? (run.kind === "job" ? run.id : run.qid) : null; useEffect(() => { if (runId && run && TERMINAL.has(run.state)) onEnded?.(runId, run.state); // eslint-disable-next-line react-hooks/exhaustive-deps }, [runId, run?.state]); const set = (name: string, v: Value) => setValues((cur) => ({ ...cur, [name]: v })); const submit = async (confirmed = false) => { if (!built.ok || going) return; const what = confirmOf(row, values); if (what && !confirmed) { setAsking(what); return; } setAsking(null); setPosting(true); setRefused(null); try { const r = await fetch("/api/cli", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ verb: row.verb, values, ...(confirmed ? { confirm: true } : {}) }), }); const j = (await r.json().catch(() => ({}))) as { error?: string; line?: string; confirm?: string; job?: { id: string; state: string; log: string[]; next: number; error: string | null; exitCode: number | null }; queued?: { qid: string }; project?: string | null; queue?: { armed: boolean }; }; if (!r.ok) { if (j.confirm) setAsking(j.confirm); else setRefused(j.error ?? `HTTP ${r.status}`); } else if (j.job) { setRun({ kind: "job", id: j.job.id, state: j.job.state, log: j.job.log, next: j.job.next, error: j.job.error, exitCode: j.job.exitCode }); onStarted?.({ verb: row.verb, values, kind: "job", id: j.job.id, line: j.line ?? line ?? "", at: Date.now(), project: j.project ?? null }); } else if (j.queued) { setRun({ kind: "queued", qid: j.queued.qid, state: "queued", log: [], error: null, exitCode: null, runnerUp: !!j.queue?.armed }); onStarted?.({ verb: row.verb, values, kind: "queued", id: j.queued.qid, line: j.line ?? line ?? "", at: Date.now(), project: j.project ?? null }); } } catch (e) { setRefused(e instanceof Error ? e.message : String(e)); } finally { setPosting(false); } }; const copy = async () => { if (!line) return; try { await navigator.clipboard.writeText(line); setCopied(true); setTimeout(() => setCopied(false), 1500); } catch { setRefused("the clipboard refused: select the line and copy it"); } }; const field = (a: CliArg, i: number) => { const id = `cli-arg-${i}`; const v = values[a.name]; const ref = i === focusAt ? (el: HTMLElement | null) => void (first.current = el) : undefined; const bad = !built.ok && built.field === a.name; const control = a.type === "boolean" ? ( set(a.name, e.target.checked)} className="h-3.5 w-3.5 accent-[var(--color-signal)]" /> ) : a.type === "choice" ? ( ) : TEXTAREA.has(a.type) ? (