Transcript
A chat thread where the agent's work is drawn: plans you edit, live swarms, diffs, previews and tests. Drag a step's crew and the swarm it will start reshapes.
npx shadcn@latest add https://uimaxxer.com/r/transcript.jsonPasskeysFix the duplicate Stripe charge
"use client";
// uimaxxer · Transcript, MIT. A chat thread where the agent's work is drawn: plans you edit, live swarms, diffs you review, previews you drag, tests as cells. Delight: drag a plan step's crew and the swarm it will start reshapes under your finger; approve, and that exact swarm runs.
import { createContext, forwardRef, memo, useCallback, useContext, useEffect, useId, useImperativeHandle, useMemo, useRef, useState } from "react";
import type { CSSProperties, KeyboardEvent as RKeyboardEvent, ReactNode } from "react";
import { motion, useReducedMotion } from "motion/react";
import type { ActionEvent, AgentRef, Block, BlockProps, CaptainMessage, EventMessage, Message, State, TranscriptHandle, TranscriptProps, YouMessage } from "@/registry/captain/ui/transcript-types";
import { BASE_BODIES, Icon, Mark, PM, Prose, StateGlyph, TranscriptContext, Ghost, type TranscriptContextValue } from "@/registry/captain/ui/transcript-blocks";
import { PlanBody, SwarmBody, swarmMeta } from "@/registry/captain/ui/transcript-plan";
import { DOM, STATES, TITLES, clock, copyText, dur, money, plural, stateWord, toText, useAnnouncements, useTranscriptList, type ListRow, type UseTranscriptList } from "@/registry/captain/ui/transcript-core";
import { EASE, cx } from "@/registry/captain/ui/captain";
import { Icon as CIcon } from "@/registry/captain/ui/icons";
export * from "@/registry/captain/ui/transcript-types";
export { Icon, Mark, StateGlyph, Since, Prose, Code, ActionButton, AgentCell, TranscriptContext, PlainTool, PlainDiff, PlainStream } from "@/registry/captain/ui/transcript-blocks";
export type { TranscriptContextValue, ActionButtonProps } from "@/registry/captain/ui/transcript-blocks";
export { useTranscriptList, useAnnouncements, toText, describe, highlight, tree, estimate, offsets, rowAt, waitingIn, copyText, STATES, BLOCKS, BLOCK_STATES, TITLES, stateWord } from "@/registry/captain/ui/transcript-core";
export type { ListRow, UseTranscriptList, TreeRow, TokenClass } from "@/registry/captain/ui/transcript-core";
export { TYPES, typeOf, hue, cells, MARKS, ICONS } from "@/registry/captain/ui/transcript-marks";
/** The built-in block bodies, by type. Pass `blocks` to the transcript to add kinds or replace these. */
export const BODIES: Record<string, React.ComponentType<BlockProps<any>>> = { ...BASE_BODIES, plan: PlanBody, swarm: SwarmBody }; // eslint-disable-line @typescript-eslint/no-explicit-any
/* text, thinking and tool calls carry their own header, so the shell draws none */
const BARE: Record<string, 1> = { text: 1, thinking: 1, tool: 1 };
/* what a finished block says about itself in its header */
function meta(b: Block): ReactNode {
switch (b.type) {
case "plan": return `${plural((b.steps || []).length, "step")} · ${plural((b.steps || []).reduce((n, s) => n + (s.agents || 1), 0), "agent")}`;
case "swarm": return swarmMeta(b);
case "diff": case "files": { const f = b.files || []; return <>{plural(f.length, "file")} <PM add={f.reduce((n, x) => n + (x.add || 0), 0)} del={f.reduce((n, x) => n + (x.del || 0), 0)} /></>; }
case "timeline": return dur(b.ms || 0);
case "preview": return b.url;
case "tests": return b.failed ? `${b.failed} failed` : null;
default: return null;
}
}
/* ---------- a block: the header every kind shares (no box; each body brings its own material) ---------- */
/** One block with its header (state, title, who made it), copy and permalink, folding, and keys: digits answer, Enter takes the main action. */
export const BlockView = memo(function BlockView({ block: b, turn }: { block: Block; turn: State }) {
const ctx = useContext(TranscriptContext);
const st: State = b.state || "done";
const [ok, setOk] = useState("");
const [fold, setFold] = useState(!!b.folded);
const ids = useId(), bodyId = "ctb" + ids.replace(/:/g, ""), titleId = bodyId + "t";
const act = useCallback((action: string, value?: unknown) => ctx.act({ block: b.id, type: b.type, action, value }), [ctx, b.id, b.type]);
const Body = (ctx.blocks && ctx.blocks[b.type]) || BODIES[b.type];
const bare = !!BARE[b.type] && !(ctx.blocks && ctx.blocks[b.type] && !BODIES[b.type]);
const t = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => () => clearTimeout(t.current), []);
const flash = (k: string) => { setOk(k); clearTimeout(t.current); t.current = setTimeout(() => setOk(""), 1200); };
if (!Body) return null;
const tool = "grid size-7 place-items-center rounded-chip text-ink-3 outline-none transition-colors hover:bg-hover hover:text-ink focus-visible:bg-hover focus-visible:text-ink";
const tools = (
<span className={cx("flex shrink-0 items-center opacity-0 transition-opacity duration-150 group-hover/blk:opacity-100 group-focus-within/blk:opacity-100 [@media(hover:none)]:opacity-100", bare && "absolute -top-1 right-0 z-10")}>
<button type="button" className={tool} title={ok === "c" ? "Copied" : "Copy"} aria-label={ok === "c" ? "Copied" : "Copy"} onClick={() => { copyText(toText(b)).then((y) => y && flash("c")); }}>
<CIcon name={ok === "c" ? "check" : "copy"} size={15} />
</button>
<button type="button" className={tool} title={ok === "l" ? "Link copied" : "Copy link"} aria-label={ok === "l" ? "Link copied" : "Copy link"}
onClick={() => { const u = location.href.split("#")[0] + "#ct-" + b.id; copyText(u).then((y) => y && flash("l")); try { history.replaceState(null, "", "#ct-" + b.id); } catch { /* sandboxed */ } ctx.onLink?.(b.id); }}>
<CIcon name={ok === "l" ? "check" : "link"} size={15} />
</button>
</span>
);
const keys = (e: RKeyboardEvent<HTMLDivElement>) => {
const tg = e.target as HTMLElement;
if (e.metaKey || e.ctrlKey || e.altKey || tg.closest("input,textarea,[role=slider]")) return;
const root = e.currentTarget;
if (/^[1-9]$/.test(e.key)) {
const btn = root.querySelectorAll<HTMLButtonElement>("[data-acts] button, [data-opt]")[+e.key - 1];
if (btn && !btn.disabled) { btn.click(); e.preventDefault(); }
} else if (e.key === "Enter" && tg === root) {
const p = root.querySelector<HTMLButtonElement>("[data-act=primary]");
if (p) { p.click(); e.preventDefault(); }
}
};
const ghost = st === "thinking" && b.type !== "thinking" && b.type !== "tool";
const word = st === "done" ? null : stateWord(b, st);
const by = b.by || (st === "delegating" ? b.to : null);
const byl: AgentRef[] = by ? (Array.isArray(by) ? by : [by]) : [];
const m = word ? null : meta(b);
return (
<div id={"ct-" + b.id} data-block={b.id} data-state={st} role={bare ? undefined : "group"} aria-labelledby={bare ? undefined : titleId}
tabIndex={st === "waiting" ? 0 : -1} onKeyDown={keys}
className="group/blk relative scroll-mt-6 rounded-inner outline-none transition-colors focus-visible:bg-hover">
{!bare && (
<div className="mb-2 flex min-h-8 items-center gap-1">
<button type="button" onClick={() => setFold(!fold)} aria-expanded={!fold} aria-controls={bodyId}
className="-ml-1.5 flex min-h-8 min-w-0 flex-1 items-center gap-2 rounded-chip px-1.5 text-left outline-none transition-colors hover:bg-hover focus-visible:bg-hover">
{word && <StateGlyph s={st} />}
<span id={titleId} className="truncate text-[13.5px] font-medium text-ink">{b.title || TITLES[b.type] || b.type.replace(/^x-/, "")}</span>
{word
? <span className={cx("tnum shrink-0 text-[13px]", st === "waiting" ? "font-medium text-accent-ink" : "text-ink-2")}>{word}</span>
: m != null && <span className="tnum min-w-0 truncate text-[13px] text-ink-3">{m}</span>}
<span className={cx("shrink-0 text-ink-3 transition-transform duration-200 ease-snap", fold && "-rotate-90")}><CIcon name="chevron" size={14} /></span>
</button>
{byl.length > 0 && (
<span className="flex shrink-0 items-center gap-1 text-[12.5px] text-ink-2">
{byl.slice(0, 4).map((a, i) => (
<motion.span key={a.id} initial={{ opacity: 0, scale: 0.8 }} animate={{ opacity: 1, scale: 1 }} transition={{ duration: 0.2, ease: EASE, delay: i * 0.08 }} className="flex items-center gap-1">
<Mark type={a.type} s={14} />{i === 0 && <span>{byl.length > 1 ? `${a.id} +${byl.length - 1}` : a.id}</span>}
</motion.span>
))}
</span>
)}
{tools}
</div>
)}
{bare && tools}
<div id={bodyId} hidden={fold} aria-busy={ghost || undefined}>
{!fold && (ghost ? <Ghost type={b.type} id={b.id} /> : <Body block={b} state={st} turn={turn} act={act} />)}
</div>
</div>
);
});
/* ---------- turns ---------- */
/** The Captain's mark: stepping while it works. */
export const CaptainMark = memo(function CaptainMark({ s = 20, work }: { s?: number; work?: boolean }) {
return <span className="grid shrink-0 place-items-center text-ink"><Mark type="captain" s={s} work={work} /></span>;
});
export function YouTurn({ message: m }: { message: YouMessage }) {
return (
<div className="flex flex-col items-end gap-1">
<div className="max-w-[min(85%,560px)] rounded-shell rounded-br-[5px] bg-band px-3.5 py-2.5 text-[15px] leading-[1.55] text-ink [text-wrap:pretty]"><Prose text={m.text} /></div>
{m.note && <div className="px-1 text-[12.5px] text-ink-3">{m.note}</div>}
</div>
);
}
export function CaptainTurn({ message: m, name }: { message: CaptainMessage; name: string }) {
const st = m.state || "done", live = st !== "done";
return (
<div className="flex flex-col">
<div className="mb-2.5 flex h-7 items-center gap-2">
<CaptainMark s={18} work={live && st !== "waiting"} />
<span className="text-[14px] font-semibold text-ink">{m.name || name}</span>
{live && (
<span className={cx("tnum flex items-center gap-1.5 text-[13px]", st === "waiting" ? "font-medium text-accent-ink" : "text-ink-2")}>
<StateGlyph s={st} />{STATES[st] || st}
</span>
)}
</div>
<div className="flex flex-col gap-5">{(m.blocks || []).map((b) => <BlockView key={b.id} block={b} turn={st} />)}</div>
{!live && m.ms != null && <div className="tnum mt-4 text-[12.5px] text-ink-3">{[`Worked for ${dur(m.ms)}`, m.agents ? plural(m.agents, "agent") : "", m.cost != null ? money(m.cost) : ""].filter(Boolean).join(" · ")}</div>}
</div>
);
}
export function EventTurn({ message: m }: { message: EventMessage }) {
return <div className={cx("flex items-center justify-center gap-1.5 text-[12.5px]", m.tone === "bad" ? "text-danger" : "text-ink-3")}>{m.tone === "bad" && <Icon i="x" s={12} />}{m.text}</div>;
}
/* ---------- the list context ---------- */
interface ListContextValue { list: UseTranscriptList; messages: Message[]; name: string; label: string }
const ListContext = createContext<ListContextValue | null>(null);
/** The list state from inside a Transcript.Root: rows, scroll position, chips. For your own parts. */
export function useTranscript(): ListContextValue {
const c = useContext(ListContext);
if (!c) throw new Error("useTranscript() must be used inside <Transcript.Root>.");
return c;
}
/* ---------- Root ---------- */
export interface RootProps extends TranscriptProps { children?: ReactNode }
/** Owns the messages (controlled with `messages`, or uncontrolled with `defaultMessages` and the handle's append and update), the virtual list, theme, accent and direction. */
export const Root = forwardRef<TranscriptHandle, RootProps>(function Root(props, ref) {
const { messages: controlled, defaultMessages, onAction, theme, accent, name = "Captain", width, overscan = 800, blocks, renderers, onLink, label = "Conversation with the Captain", dir, className, style, children } = props;
const [own, setOwn] = useState<Message[]>(() => defaultMessages || []);
const messages = controlled || own;
const msgRef = useRef(messages); msgRef.current = messages;
const box = useRef<HTMLDivElement>(null);
const list = useTranscriptList(messages, overscan);
const cb = useRef(onAction); cb.current = onAction;
const ctx = useMemo<TranscriptContextValue>(() => ({ act: (e: ActionEvent) => cb.current && cb.current(e), onLink, blocks, renderers, name }), [onLink, blocks, renderers, name]);
useImperativeHandle(ref, () => ({
scrollToBlock: list.scrollToBlock,
scrollToEnd: list.scrollToEnd,
append: (...m: Message[]) => { if (controlled) warn("append"); else setOwn((x) => [...x, ...m]); },
update: (id, patch) => {
if (controlled) { warn("update"); return; }
setOwn((x) => { const i = x.findIndex((y) => y.id === id); if (i < 0) return x; const n = x.slice(); n[i] = typeof patch === "function" ? patch(x[i]!) : ({ ...x[i]!, ...patch } as Message); return n; });
},
get messages() { return msgRef.current; },
get element() { return box.current; },
}), [list.scrollToBlock, list.scrollToEnd, controlled]);
// a permalink in the address bar scrolls to its block once
useEffect(() => { if (DOM && /^#ct-/.test(location.hash)) list.scrollToBlock(decodeURIComponent(location.hash.slice(4)), false); }, []); // eslint-disable-line react-hooks/exhaustive-deps
const lc = useMemo<ListContextValue>(() => ({ list, messages, name, label }), [list, messages, name, label]);
const st: CSSProperties = { ...(accent ? { ["--captain-accent" as string]: accent } : null), ["--captain-transcript-width" as string]: (width || 760) + "px", ...style };
return (
<TranscriptContext.Provider value={ctx}>
<ListContext.Provider value={lc}>
<div ref={box} data-theme={theme === "system" ? undefined : theme} dir={dir} style={st}
className={cx("relative flex h-full min-h-0 flex-col font-sans text-ink", theme === "dark" && "dark", className)}>{children}</div>
</ListContext.Provider>
</TranscriptContext.Provider>
);
});
const warn = (f: string) => { if (typeof console !== "undefined") console.warn(`transcript: ${f}() only works without the messages prop. Change messages instead.`); };
/* ---------- Viewport: the scrolling feed ---------- */
const Row = memo(function Row({ message: m, fresh, skim, height, pos, size, name }: ListRow & { pos: number; size: number; name: string }) {
const reduce = useReducedMotion();
if (skim) return (
<div data-id={m.id} data-skim="" aria-hidden="true" style={{ height }} className="flex flex-col gap-2 py-4">
<i className="well block h-3 w-1/3 rounded-chip" /><i className="well block h-3 w-4/5 rounded-chip" /><i className="well block h-3 w-3/5 rounded-chip" />
</div>
);
const lab = m.role === "you" ? "You" : m.role === "captain" ? (m.name || name) : undefined;
const busy = m.role === "captain" && (m.state || "done") !== "done" && m.state !== "waiting";
return (
<motion.article data-role={m.role} data-id={m.id} aria-posinset={pos} aria-setsize={size} aria-label={lab} aria-busy={busy || undefined} tabIndex={-1}
initial={fresh && !reduce ? { opacity: 0, y: 8 } : false} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.24, ease: EASE }}
className="rounded-inner py-3 outline-none focus-visible:bg-hover">
{m.role === "you" ? <YouTurn message={m} /> : m.role === "captain" ? <CaptainTurn message={m} name={name} /> : <EventTurn message={m} />}
</motion.article>
);
});
export interface ViewportProps { empty?: ReactNode; className?: string }
/** The scrolling thread. Only rows near the screen are in the DOM. PageDown and PageUp move between messages. */
export function Viewport({ empty, className }: ViewportProps) {
const { list, messages, name, label } = useTranscript();
const keys = useCallback((e: RKeyboardEvent<HTMLDivElement>) => {
if (e.key !== "PageDown" && e.key !== "PageUp") return;
// fields and scrolling code keep their own paging
if ((e.target as HTMLElement).closest("input,textarea,select,[contenteditable]:not([contenteditable=false]),[data-scroll]")) return;
const art = (e.target as HTMLElement).closest("article");
if (!art || !art.parentElement) return;
let n = (e.key === "PageDown" ? art.nextElementSibling : art.previousElementSibling) as HTMLElement | null;
while (n && n.tagName !== "ARTICLE") n = (e.key === "PageDown" ? n.nextElementSibling : n.previousElementSibling) as HTMLElement | null;
if (n) { e.preventDefault(); n.focus(); n.scrollIntoView({ block: "nearest" }); }
}, []);
const last = messages[messages.length - 1] as CaptainMessage | undefined;
const busy = !!last && last.role === "captain" && (last.state || "done") !== "done" && last.state !== "waiting";
return (
<div ref={list.scrollRef} onScroll={list.onScroll} onKeyDown={keys} tabIndex={0} role="log" aria-label="Conversation" className={cx("min-h-0 flex-1 overflow-y-auto overscroll-contain [scrollbar-width:thin]", className)}>
{messages.length === 0 && (empty ?? <div className="grid h-full place-items-center content-center gap-3 text-[15px] text-ink-2"><CaptainMark s={40} /><span>Tell the {name} what to build.</span></div>)}
<div className="@container mx-auto w-full max-w-[var(--captain-transcript-width,760px)] px-4 sm:px-6" style={{ paddingTop: list.padTop + 8, paddingBottom: list.padBottom + 20 }}>
<div ref={list.rowsRef} role="feed" aria-label={label} aria-busy={busy || undefined} className="flex flex-col">
{list.rows.map((r, i) => <Row key={r.message.id} {...r} pos={list.start + i + 1} size={messages.length} name={name} />)}
</div>
</div>
</div>
);
}
/* ---------- chips that bring the reader back ---------- */
/** Holds the chips at the bottom of the transcript. */
export function Float({ children }: { children?: ReactNode }) {
return <div className="pointer-events-none absolute inset-x-0 bottom-3 flex justify-center gap-2 [&>*]:pointer-events-auto">{children}</div>;
}
const CHIP = "glass pressable flex h-9 items-center gap-2 rounded-inner px-3 text-[13px] font-medium outline-none transition-colors focus-visible:bg-hover";
/** Shows when the reader has scrolled up. Says how many messages arrived meanwhile. */
export function JumpToLatest({ children }: { children?: (unseen: number) => ReactNode }) {
const { list } = useTranscript();
if (list.atBottom) return null;
return <button type="button" className={cx(CHIP, "text-ink")} onClick={() => list.scrollToEnd(true)}><CIcon name="arrowUp" size={14} className="rotate-180" />{children ? children(list.unseen) : list.unseen > 0 ? `${list.unseen} new` : "Jump to latest"}</button>;
}
/** Shows when a block below the screen is waiting on you, and takes you to it. */
export function NeedsYou({ children }: { children?: (count: number) => ReactNode }) {
const { list } = useTranscript();
const w = list.waitingBelow;
if (!w.length) return null;
return <button type="button" className={cx(CHIP, "text-accent-ink")} onClick={() => { const [i, id] = w[w.length - 1]!; list.scrollToIndex(i, id, true); }}><StateGlyph s="waiting" />{children ? children(w.length) : `${w.length} needs you`}</button>;
}
/* ---------- Announcer ---------- */
/** A visually hidden live log for screen readers: state changes, blocks that start waiting on you, replies once they finish, test results. Never word by word. */
export function Announcer() {
const { messages, name } = useTranscript();
const log = useAnnouncements(messages, name);
return <div className="sr-only" role="log" aria-live="polite" aria-relevant="additions">{log.map((a) => <p key={a.id}>{a.text}</p>)}</div>;
}
/* ---------- the whole thing ---------- */
/** The transcript with every part in place. Use the parts under `Transcript` to arrange your own. */
export const CaptainTranscript = forwardRef<TranscriptHandle, TranscriptProps>(function CaptainTranscript({ empty, children, ...p }, ref) {
return (
<Root ref={ref} {...p}>
<Viewport empty={empty} />
<Float><NeedsYou /><JumpToLatest /></Float>
<Announcer />
{children}
</Root>
);
});
export const Transcript = { Root, Viewport, Float, JumpToLatest, NeedsYou, Announcer };
export default CaptainTranscript;"use client";
// uimaxxer · Transcript plan and swarm, MIT. The plan is drawn as the swarm it will start: every step carries its crew of agent cells. Delight: drag a crew sideways and agents split off or fold back into it, the order reshuffles under your finger, and what you approve is exactly the swarm that runs.
import { AnimatePresence, Reorder, motion, useDragControls, useReducedMotion } from "motion/react";
import { useEffect, useRef, useState, type KeyboardEvent as RKeyboardEvent, type PointerEvent as RPointerEvent, type ReactNode } from "react";
import type { BlockProps, PlanBlock, PlanStep, SwarmAgent, SwarmBlock } from "@/registry/captain/ui/transcript-types";
import { clock, plural } from "@/registry/captain/ui/transcript-core";
import { typeOf } from "@/registry/captain/ui/transcript-marks";
import { SPRING, SPRING_LAYOUT, clamp, cx } from "@/registry/captain/ui/captain";
import { Icon as CIcon } from "@/registry/captain/ui/icons";
import { ActionButton as Btn, Acts, AgentCell, Mark, type CellLook } from "@/registry/captain/ui/transcript-blocks";
const MAX = 8;
const STEP_PX = 26; // how far a crew drag travels per agent: one cell and its gap
/* ---------- a crew: the agents one step will start. Drag it, use the arrows, or tap the open cell ---------- */
function Crew({ step, live, onChange, className }: { step: PlanStep; live: boolean; onChange: (n: number) => void; className?: string }) {
const n = step.agents || 1;
const reduce = useReducedMotion();
const drag = useRef<{ x: number; n0: number } | null>(null);
const [held, setHeld] = useState(false);
const cells = Array.from({ length: n }, (_, i) => i);
const look: CellLook = live ? "ready" : "done";
const down = (e: RPointerEvent<HTMLDivElement>) => {
if (!live || e.button !== 0) return;
e.currentTarget.setPointerCapture(e.pointerId);
drag.current = { x: e.clientX, n0: n };
setHeld(true);
};
const move = (e: RPointerEvent<HTMLDivElement>) => {
const d = drag.current;
if (!d) return;
const next = clamp(d.n0 + Math.round((e.clientX - d.x) / STEP_PX), 1, MAX);
if (next !== n) onChange(next);
};
const up = () => { drag.current = null; setHeld(false); };
const key = (e: RKeyboardEvent<HTMLDivElement>) => {
const next = e.key === "ArrowRight" || e.key === "ArrowUp" ? n + 1 : e.key === "ArrowLeft" || e.key === "ArrowDown" ? n - 1 : e.key === "Home" ? 1 : e.key === "End" ? MAX : null;
if (next == null) return;
e.preventDefault(); e.stopPropagation();
onChange(clamp(next, 1, MAX));
};
const label = typeOf(step.type)[0];
const body = (
<motion.span layout={!reduce} transition={SPRING_LAYOUT} className="flex items-center gap-1">
<AnimatePresence initial={false} mode="popLayout">
{cells.map((i) => (
<motion.span key={i} layout={!reduce} transition={SPRING} initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.4, x: -14 }}
animate={{ opacity: 1, scale: 1, x: 0 }} exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.4, x: -14, transition: { duration: 0.16 } }}>
<AgentCell type={step.type} look={look} s={live ? 22 : 16} />
</motion.span>
))}
</AnimatePresence>
{live && n < MAX && (
// A pointer shortcut only, so it is not a button: the slider around it already takes the arrow keys.
<motion.span layout={!reduce} transition={SPRING_LAYOUT} aria-hidden="true" onPointerDown={(e) => e.stopPropagation()} onClick={() => onChange(n + 1)}
className="pressable well grid size-[22px] place-items-center rounded-[6px] text-ink-3 opacity-50 transition-opacity duration-150 hover:text-ink group-hover/step:opacity-100 group-focus-within/step:opacity-100 [@media(hover:none)]:opacity-100">
<CIcon name="plus" size={12} />
</motion.span>
)}
</motion.span>
);
if (!live) return <span className={cx("flex items-center", className)} aria-label={`${plural(n, "agent")}, ${label}`}>{body}</span>;
return (
<div role="slider" tabIndex={0} aria-label={`Agents on ${step.title}`} aria-valuemin={1} aria-valuemax={MAX} aria-valuenow={n} aria-valuetext={`${plural(n, label.toLowerCase() + " agent")}`}
onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={up} onKeyDown={key}
className={cx("relative -my-1 flex min-h-11 touch-pan-y select-none items-center rounded-inner px-1.5 outline-none transition-colors duration-150 focus-visible:bg-hover", className,
held ? "cursor-grabbing bg-hover" : "cursor-ew-resize hover:bg-hover")}>
{body}
</div>
);
}
/* ---------- one step ---------- */
function Step({ s, i, count, live, done, editing, setEditing, onTitle, onAgents, onRemove, onMove, onDragEnd }: {
s: PlanStep; i: number; count: number; live: boolean; done: boolean; editing: boolean; setEditing: (v: boolean) => void;
onTitle: (v: string) => void; onAgents: (n: number) => void; onRemove: () => void; onMove: (to: number) => void; onDragEnd: () => void;
}) {
const controls = useDragControls();
const reduce = useReducedMotion();
const key = (e: RKeyboardEvent) => {
const to = e.key === "ArrowUp" ? i - 1 : e.key === "ArrowDown" ? i + 1 : e.key === "Home" ? 0 : e.key === "End" ? count - 1 : null;
if (to == null) return;
e.preventDefault(); e.stopPropagation();
onMove(to);
};
const row: ReactNode = (
<>
{live
? <button type="button" onPointerDown={(e) => controls.start(e)} onKeyDown={key} aria-label={`Move ${s.title}. Step ${i + 1} of ${count}. Arrow keys move it.`}
className="grid h-11 w-6 shrink-0 cursor-grab touch-none place-items-center rounded-chip text-ink-3 outline-none transition-colors hover:text-ink focus-visible:bg-hover active:cursor-grabbing">
<svg width="8" height="14" viewBox="0 0 8 14" fill="currentColor" aria-hidden="true"><circle cx="2" cy="2" r="1.25" /><circle cx="6" cy="2" r="1.25" /><circle cx="2" cy="7" r="1.25" /><circle cx="6" cy="7" r="1.25" /><circle cx="2" cy="12" r="1.25" /><circle cx="6" cy="12" r="1.25" /></svg>
</button>
: <span aria-hidden="true" className={cx("grid w-6 shrink-0 place-items-center", done ? "text-success" : "text-ink-3")}>{done ? <CIcon name="check" size={15} /> : <i className="block size-1.5 rounded-full bg-current" />}</span>}
{editing
? <input aria-label="Step title" autoFocus defaultValue={s.title} onBlur={(e) => { onTitle(e.currentTarget.value); setEditing(false); }}
onKeyDown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); if (e.key === "Escape") setEditing(false); e.stopPropagation(); }}
className="well h-9 min-w-0 rounded-inner px-2.5 text-[14.5px] text-ink outline-none" />
: live
? <button type="button" onClick={() => setEditing(true)} aria-label={`${s.title}. Edit`}
className="min-w-0 rounded-chip py-1 text-left text-[14.5px] leading-snug text-ink outline-none transition-colors hover:text-accent-ink focus-visible:bg-hover">{s.title}</button>
: <span className={cx("min-w-0 py-1 text-[14px] leading-snug", done ? "text-ink-2" : "text-ink")}>{s.title}</span>}
<Crew step={s} live={live} onChange={onAgents} className="justify-self-end @max-[460px]:col-start-2 @max-[460px]:row-start-2 @max-[460px]:-ml-1.5 @max-[460px]:-mt-1 @max-[460px]:justify-self-start" />
{live && (
<button type="button" onClick={onRemove} aria-label={`Remove ${s.title}`}
className="grid size-7 shrink-0 place-items-center rounded-chip text-ink-3 opacity-0 @max-[460px]:col-start-3 @max-[460px]:row-start-1 outline-none transition-[opacity,color,background-color] hover:bg-hover hover:text-ink focus-visible:bg-hover focus-visible:opacity-100 group-hover/step:opacity-100 [@media(hover:none)]:opacity-100">
<CIcon name="x" size={14} />
</button>
)}
</>
);
const cls = cx("group/step relative grid items-center gap-x-2 rounded-inner px-1", live ? "min-h-11 grid-cols-[24px_minmax(0,1fr)_auto_auto] @max-[460px]:grid-cols-[24px_minmax(0,1fr)_auto] @max-[460px]:pb-1.5" : "min-h-9 grid-cols-[24px_minmax(0,1fr)_auto]");
if (!live) return <li data-step={s.id} className={cls}>{row}</li>;
return (
<Reorder.Item value={s} dragListener={false} dragControls={controls} onDragEnd={onDragEnd} layout="position" transition={SPRING_LAYOUT}
whileDrag={{ scale: 1.015, boxShadow: "var(--captain-lift)", backgroundColor: "var(--captain-surface)", zIndex: 2 }} className={cls} data-step={s.id}>
{row}
</Reorder.Item>
);
}
/* ---------- the plan ---------- */
export function PlanBody({ block: b, state: st, act }: BlockProps<PlanBlock>) {
const [steps, setSteps] = useState<PlanStep[]>(b.steps || []);
const [edit, setEdit] = useState<string | null>(null);
const [say, setSay] = useState("");
const reduce = useReducedMotion();
useEffect(() => { setSteps(b.steps || []); }, [b.steps]);
const live = st === "waiting";
// side effects stay out of state updaters: StrictMode runs updaters twice
const cur = useRef(steps); cur.current = steps;
const change = (n: PlanStep[], action: "reorder" | "edit") => { cur.current = n; setSteps(n); act(action, n); };
const move = (from: number, to: number) => {
const s = cur.current;
if (to < 0 || to >= s.length || to === from) return;
const n = s.slice(), x = n.splice(from, 1)[0]!; n.splice(to, 0, x);
change(n, "reorder"); setSay(`${x.title}, step ${to + 1} of ${n.length}`);
requestAnimationFrame(() => document.querySelector<HTMLElement>(`[data-step="${CSS.escape(x.id)}"] button`)?.focus());
};
const agents = steps.reduce((n, s) => n + (s.agents || 1), 0);
const list = live
? (
<Reorder.Group axis="y" values={steps} onReorder={(n) => { cur.current = n; setSteps(n); }} className="flex flex-col" aria-label="Steps" as="ol">
{steps.map((s, i) => (
<Step key={s.id} s={s} i={i} count={steps.length} live done={false} editing={edit === s.id} setEditing={(v) => setEdit(v ? s.id : null)}
onTitle={(v) => { v = v.trim(); if (v && v !== s.title) change(cur.current.map((y) => (y.id === s.id ? { ...y, title: v } : y)), "edit"); }}
onAgents={(n) => { change(cur.current.map((y) => (y.id === s.id ? { ...y, agents: n } : y)), "edit"); setSay(`${s.title}: ${plural(n, "agent")}`); }}
onRemove={() => change(cur.current.filter((y) => y.id !== s.id), "edit")}
onMove={(to) => move(i, to)} onDragEnd={() => act("reorder", cur.current)} />
))}
</Reorder.Group>
)
: (
<ol className="flex flex-col" aria-label="Steps">
{steps.map((s, i) => <Step key={s.id} s={s} i={i} count={steps.length} live={false} done={st === "done"} editing={false} setEditing={() => {}} onTitle={() => {}} onAgents={() => {}} onRemove={() => {}} onMove={() => {}} onDragEnd={() => {}} />)}
</ol>
);
return (
<div className={cx("@container", live && "lifted rounded-shell px-2 pb-2 pt-1.5", st === "planning" && "opacity-70")}>
{list}
<span className="sr-only" aria-live="assertive">{say}</span>
{live && (
<div className="mt-2 flex flex-wrap items-center gap-1 px-1">
<Btn kind="ink" k="↵" onClick={() => act("approve", steps)}>
<span>Approve and start{" "}
<span className="tnum relative inline-grid overflow-hidden align-bottom">
<AnimatePresence initial={false} mode="popLayout">
<motion.span key={agents} initial={reduce ? { opacity: 0 } : { y: "-70%", opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={reduce ? { opacity: 0 } : { y: "70%", opacity: 0 }} transition={{ duration: 0.2, ease: [0.23, 1, 0.32, 1] }}>
{agents}
</motion.span>
</AnimatePresence>
</span>{" "}{agents === 1 ? "agent" : "agents"}</span>
</Btn>
<Btn onClick={() => { const id = "s" + Date.now().toString(36); const n = [...cur.current, { id, title: "New step", type: "build", agents: 1 }]; change(n, "edit"); setEdit(id); }}>
<CIcon name="plus" size={14} />Add step
</Btn>
</div>
)}
</div>
);
}
/* ---------- the swarm: the same cells, now running ---------- */
const ASTATE: Record<string, string> = { queued: "Queued", working: "Working", needs: "Needs you", failed: "Failed, retrying", done: "Done" };
export function SwarmBody({ block: b, state: st, act }: BlockProps<SwarmBlock>) {
const [pick, setPick] = useState<string | null>(null);
const reduce = useReducedMotion();
const lanes = b.lanes || [];
const big = lanes.reduce((n, l) => n + l.agents.length, 0) > 120;
let k = 0;
const ask = b.ask;
return (
<div className="flex flex-col gap-1">
{lanes.map((l) => {
const sel: SwarmAgent | undefined = pick ? l.agents.find((a) => a.id === pick) : undefined;
return (
<div key={l.id} role="group" aria-label={l.title} className="flex flex-col gap-1.5 rounded-inner py-1 @min-[520px]:grid @min-[520px]:grid-cols-[minmax(0,1fr)_auto] @min-[520px]:items-center @min-[520px]:gap-4">
<span aria-hidden="true" className="truncate text-[13.5px] text-ink-2">{l.title}</span>
<div className="flex flex-wrap gap-1 @min-[520px]:justify-end">
{l.agents.map((a) => {
const d = (k++ * 0.035) % 1.4;
return (
<motion.button key={a.id} type="button" aria-pressed={pick === a.id} aria-label={`${a.id}, ${ASTATE[a.state] || a.state}`} title={big ? undefined : `${a.id} · ${ASTATE[a.state] || a.state}`}
onClick={() => setPick(pick === a.id ? null : a.id)}
initial={st === "delegating" && !reduce ? { opacity: 0, scale: 0.5, y: -6 } : false} animate={{ opacity: 1, scale: 1, y: 0 }} transition={{ ...SPRING, delay: st === "delegating" ? d : 0 }}
className={cx("pressable rounded-[6px] outline-none transition-[translate,box-shadow] duration-150 ease-snap focus-visible:brightness-110", pick === a.id && "-translate-y-[3px] shadow-lift")}>
<AgentCell type={a.type} look={a.state as CellLook} s={big ? 10 : 24} />
</motion.button>
);
})}
</div>
{sel && (
<div className="col-span-2 flex items-center gap-2 text-[13px]">
<Mark type={sel.type} s={14} /><b className="font-medium text-ink">{sel.id}</b><span className="truncate text-ink-2">{sel.step || ASTATE[sel.state]}</span>
{sel.ms != null && <span className="tnum ml-auto text-ink-3">{clock(sel.ms)}</span>}
</div>
)}
</div>
);
})}
{ask && st === "waiting" && (
<div className="raised mt-2 rounded-shell p-3">
<div className="flex items-start gap-2 text-[14px] leading-snug">
<span className="mt-0.5"><Mark type={ask.from.type} s={16} /></span>
<p><b className="font-medium text-ink">{ask.from.id}</b> <span className="text-ink-2">{ask.text}</span></p>
</div>
<Acts>{ask.options.map((o, i) => <Btn key={o} kind={i ? undefined : "ink"} k={String(i + 1)} onClick={() => act("answer", o)}>{o}</Btn>)}</Acts>
</div>
)}
</div>
);
}
export function swarmMeta(b: SwarmBlock): ReactNode {
let n = 0; const c: Record<string, number> = {};
for (const l of b.lanes || []) for (const a of l.agents) { n++; c[a.state] = (c[a.state] || 0) + 1; }
return <>{plural(n, "agent")}{c.working ? ` · ${c.working} working` : ""}{c.done && c.done !== n ? ` · ${c.done} done` : ""}{c.failed ? ` · ${c.failed} retrying` : ""}{c.needs ? <span className="text-accent-ink"> · {c.needs} needs you</span> : ""}</>;
}"use client";
// uimaxxer · Transcript blocks, MIT. Every block body, each in its own material: code sits in wells, the preview is a window, picks lift out of their tray, a cost fills its track.
import { createContext, Fragment, memo, useContext, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent as RKeyboardEvent, type PointerEvent as RPointerEvent, type ReactNode } from "react";
import { useReducedMotion } from "motion/react";
import type {
ActionEvent, Block, BlockProps, ChoiceBlock, ConflictBlock, CostBlock, DiagramBlock, DiffBlock, DiffFile, DiffHunk, DiffNote, FilesBlock,
PreviewBlock, State, TerminalBlock, TestsBlock, TextBlock, ThinkingBlock, TimelineBlock, ToolBlock, TranscriptProps,
DiffRendererProps, HunkVerdict, Renderers, ReviewHunk, StreamRendererProps, ToolRendererProps,
} from "@/registry/captain/ui/transcript-types";
import { ICONS, MARKS, cells, hue, paths, typeOf } from "@/registry/captain/ui/transcript-marks";
import { clock, dur, highlight, langOf, money, onTick, plural, reducedMotion, rnd, tree, useIsoLayoutEffect } from "@/registry/captain/ui/transcript-core";
import { cx } from "@/registry/captain/ui/captain";
import { Thinking } from "@/registry/captain/ui/thinking";
const vars = (o: Record<string, string | number | undefined>): CSSProperties => o as CSSProperties;
/* ---------- context: what every block needs from the transcript ---------- */
export interface TranscriptContextValue {
act: (e: ActionEvent) => void;
onLink?: (blockId: string) => void;
blocks?: TranscriptProps["blocks"];
renderers?: Renderers;
name: string;
}
export const TranscriptContext = createContext<TranscriptContextValue>({ act: () => {}, name: "Captain" });
/* ---------- glyphs: square pixels, shared with the composer and the sidebar ---------- */
/** A pixel icon from the shared set: copy, link, check, x, chev, grip, plus, drag, dir, file, down, term, warn, play. */
export function Icon({ i, s = 14 }: { i: string; s?: number }) {
const r = ICONS[i];
if (!r) return null;
const [a, b] = paths(r, 0);
return (
<svg className="shrink-0" width={s} height={s} viewBox={`0 0 ${r[0]!.length} ${r.length}`} shapeRendering="crispEdges" fill="currentColor" aria-hidden="true" focusable="false">
<path d={a} />{b && <path d={b} opacity={0.5} />}
</svg>
);
}
/** An agent's mark in its type colour. `work` steps the dither; `ink` draws it in the current colour. */
export const Mark = memo(function Mark({ type, work, s = 16, ink }: { type: string; work?: boolean; s?: number; ink?: boolean }) {
const cap = type === "captain", t = cap ? null : typeOf(type), r = MARKS[cap ? "captain" : t![1]]!;
const [a, d0] = paths(r, 0), d1 = paths(r, 1)[1];
const reduce = useReducedMotion();
const ref = useRef<SVGSVGElement>(null);
// the dither swaps phase on the shared clock while the agent works, so every working mark on the page steps together
useIsoLayoutEffect(() => {
const el = ref.current;
if (!el || !work || reduce) return;
let last = -1;
return onTick((now) => { const k = Math.floor(now / 260) % 2; if (k !== last) { last = k; el.dataset.ph = String(k); } });
}, [work, reduce]);
return (
<svg ref={ref} className="group/mk shrink-0" width={s} height={s} viewBox="0 0 16 16" shapeRendering="crispEdges" fill="currentColor"
style={cap || ink ? undefined : { color: t![2] }} aria-hidden="true" focusable="false" data-ph="0">
<path d={a} />
<path d={d0} className="group-data-[ph=1]/mk:opacity-0" />
<path d={d1} className="opacity-0 group-data-[ph=1]/mk:opacity-100" />
</svg>
);
});
/** Twelve pixels of motion for a state, painted outside React on the shared clock. */
export function StateGlyph({ s }: { s: State }) {
const ref = useRef<SVGPathElement>(null);
useIsoLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const t0 = performance.now(), still = reducedMotion();
let last = "", n = 0;
const paint = (now: number) => { const d = cells(s, still ? (s === "done" ? 1e4 : 0) : Math.floor((now - t0) / 100) * 100); if (d !== last) el.setAttribute("d", (last = d)); };
paint(t0);
if (still) return;
return onTick((now) => { if (s === "done" && ++n > 30) return; paint(now); });
}, [s]);
return (
<svg className={cx("shrink-0", s === "waiting" ? "text-accent-ink" : "text-ink-2")} width={12} height={12} viewBox="0 0 12 12" shapeRendering="crispEdges" fill="currentColor" aria-hidden="true" focusable="false">
<path ref={ref} />
</svg>
);
}
/** A timer that counts up from `at` without re-rendering React. */
export function Since({ at, fmt = dur }: { at: number; fmt?: (ms: number) => string }) {
const ref = useRef<HTMLSpanElement>(null);
useIsoLayoutEffect(() => {
let last = "";
const paint = () => { const v = fmt(Date.now() - at); if (v !== last && ref.current) ref.current.textContent = last = v; };
paint();
return onTick(paint);
}, [at, fmt]);
return <span ref={ref} className="tnum" />;
}
/* ---------- prose: bold, code, #refs and links ---------- */
const INL = /(\*\*[^*]+\*\*|`[^`]+`|#\d+\b|\[[^\]]+\]\([^)]+\))/g;
const SAFE = /^(https?:|mailto:|\/|#|\.)/i;
const INLINE_CODE = "rounded-chip bg-band px-[5px] py-px font-mono text-[0.86em] text-ink";
function inline(text: string): ReactNode[] {
const out: ReactNode[] = [];
text.split(INL).forEach((part, i) => {
if (!part) return;
if (!(i % 2)) { out.push(part); return; }
const k = out.length;
if (part[0] === "*") out.push(<b key={k} className="font-semibold text-ink">{part.slice(2, -2)}</b>);
else if (part[0] === "`") out.push(<code key={k} className={INLINE_CODE}>{part.slice(1, -1)}</code>);
else if (part[0] === "#") out.push(<span key={k} className="tnum font-medium text-accent-ink">{part}</span>);
else {
const m = /\[([^\]]+)\]\(([^)]+)\)/.exec(part)!;
const href = m[2]!.trim();
out.push(SAFE.test(href)
? <a key={k} className="text-accent-ink underline decoration-[color-mix(in_srgb,currentColor_35%,transparent)] underline-offset-[3px] hover:decoration-current" href={href} target="_blank" rel="noreferrer noopener">{m[1]}</a>
: <span key={k}>{m[1]}</span>);
}
});
return out;
}
/** Short-form markdown: paragraphs, **bold**, `code`, [links](https://…) and #123. Unsafe link schemes render as text. */
export function Prose({ text }: { text: string; streaming?: boolean }) {
return <>{String(text || "").split(/\n{2,}/).map((p, i) => <p key={i} className="[&+p]:mt-3">{inline(p)}</p>)}</>;
}
/** Syntax colour for ts, tsx, css, json and shell, from theme tokens. */
const TOK: Record<string, string> = { c: "text-ink-3", s: "text-success", k: "text-accent-ink", n: "text-warning", t: "text-accent-ink", f: "text-ink", p: "text-ink-2" };
export const Code = memo(function Code({ text, lang }: { text: string; lang: string }) {
return <>{highlight(text, lang).map(([k, s], i) => (k ? <span key={i} className={TOK[k]}>{s}</span> : s))}</>;
});
/* ---------- buttons: one ink block, the rest quiet ---------- */
export interface ActionButtonProps { kind?: "ink"; onClick?: () => void; children?: ReactNode; k?: string; tip?: string; disabled?: boolean }
/** The transcript's button. `ink` is the one filled primary; `k` shows its key. */
export function ActionButton({ kind, onClick, children, k, tip, disabled }: ActionButtonProps) {
return (
<button type="button" onClick={onClick} title={tip} disabled={disabled} data-act={kind === "ink" ? "primary" : "secondary"}
className={cx("pressable inline-flex h-9 items-center gap-2 rounded-inner px-3 text-[13.5px] font-medium outline-none transition-colors duration-150 disabled:opacity-50",
kind === "ink" ? "bg-primary text-primary-ink focus-visible:bg-accent" : "text-ink-2 hover:bg-hover hover:text-ink focus-visible:bg-hover")}>
{children}
{k && <kbd aria-hidden="true" className={cx("tnum font-sans text-[12px]", kind === "ink" ? "opacity-55" : "text-ink-3")}>{k}</kbd>}
</button>
);
}
const Btn = ActionButton;
export function Acts({ children }: { children: ReactNode }) {
return <div className="mt-3 flex flex-wrap items-center gap-1" data-acts="">{children}</div>;
}
/** Lines added and removed, in tabular figures. */
export const PM = ({ add, del }: { add?: number; del?: number }) => (
<span className="tnum inline-flex gap-1.5 text-[12.5px]">
{add ? <span className="text-success"><span className="sr-only">added </span>+{add}</span> : null}
{del ? <span className="text-danger"><span className="sr-only">removed </span>{"−"}{del}</span> : null}
</span>
);
/* ---------- agent cells: one per agent, in the agent type's colour. The plan's crews and the swarm's lanes are drawn from the same cell. ---------- */
export type CellLook = "queued" | "ready" | "working" | "needs" | "failed" | "done";
export const AgentCell = memo(function AgentCell({ type, look, s = 24 }: { type: string; look: CellLook; s?: number }) {
const h = hue(type);
const bg =
look === "queued" ? undefined
: look === "done" ? h
: look === "needs" ? "var(--captain-accent)"
: look === "failed" ? "color-mix(in srgb, var(--captain-danger) 16%, transparent)"
: `color-mix(in srgb, ${h} ${look === "ready" ? 15 : 20}%, transparent)`;
return (
<span className={cx("relative grid shrink-0 place-items-center rounded-[6px] transition-[background-color,box-shadow] duration-200",
look === "queued" && "well", (look === "done" || look === "needs") && "shadow-[inset_0_1px_0_rgba(255,255,255,.28),0_1px_2px_rgba(17,18,20,.18)]")}
style={{ width: s, height: s, background: bg, color: look === "done" || look === "needs" ? "#fff" : look === "failed" ? "var(--captain-danger)" : h }}>
{look === "queued" ? null : <Mark type={type} s={Math.round(s * 0.62)} work={look === "working"} ink={look === "done" || look === "needs" || look === "failed"} />}
</span>
);
});
/* ---------- ghosts: a block's shape while the Captain is still deciding it ---------- */
export function Ghost({ type, id }: { type: string; id: string }) {
const r = rnd(id + type);
const rows = type === "terminal" || type === "diff" ? 6 : type === "preview" ? 0 : 4;
if (type === "preview") return <div aria-hidden="true" className="well aspect-[16/10] w-full animate-pulse rounded-shell" />;
return (
<div aria-hidden="true" className="flex animate-pulse flex-col gap-2 py-1">
{Array.from({ length: rows }, (_, i) => <i key={i} className="well block h-2.5 rounded-chip" style={{ width: `${40 + r() * 55}%`, marginInlineStart: type === "diff" && i % 3 ? 16 : 0 }} />)}
</div>
);
}
/* ---------- default renderers: light, free, on the theme tokens. Swap any of them with the transcript's `renderers` prop. ---------- */
const json = (v: unknown): string => { try { return typeof v === "string" ? v : JSON.stringify(v, null, 2) ?? ""; } catch { return String(v); } };
/** A tool call as a one-line command and its result, the terminal look. Opens to show the arguments. */
export function PlainTool({ name, title, status, args, result, error, startedAt, duration, className }: ToolRendererProps) {
const [open, setOpen] = useState(false);
const id = useId();
const call = `${name}(${args === undefined ? "" : json(args).replace(/\s*\n\s*/g, " ")})`;
return (
<div className={className}>
<button type="button" onClick={() => setOpen(!open)} aria-expanded={open} aria-controls={id}
className="flex min-h-9 w-full items-center gap-2.5 rounded-inner px-1.5 text-left outline-none transition-colors hover:bg-hover focus-visible:bg-hover">
<span className={cx("grid w-4 shrink-0 place-items-center", status === "error" ? "text-danger" : status === "running" ? "text-ink-2" : "text-success")}>
{status === "running" ? <StateGlyph s="working" /> : <Icon i={status === "error" ? "x" : "check"} s={12} />}
</span>
<span className="min-w-0 flex-1 truncate text-[14px] text-ink">{title}</span>
<span className="tnum shrink-0 text-[12.5px] text-ink-3">{status === "running" ? (startedAt ? <Since at={startedAt} /> : "Running") : duration != null ? (duration < 6e4 ? `${(duration / 1000).toFixed(1)}s` : dur(duration)) : null}</span>
<span className={cx("shrink-0 text-ink-3 transition-transform duration-200 ease-snap", !open && "-rotate-90")}><Icon i="chev" s={12} /></span>
</button>
<div id={id} hidden={!open} className="mt-1.5 flex flex-col gap-1.5">
{open && (
<>
<pre data-scroll="" className="well max-h-[240px] overflow-auto whitespace-pre-wrap break-all rounded-inner px-3 py-2.5 font-mono text-[12.5px] leading-[1.6] text-ink"><span className="select-none text-ink-3">$ </span>{call}</pre>
{error ? <div className="well rounded-inner px-3 py-2.5 text-[13.5px] text-danger">{error}</div>
: result !== undefined && <pre data-scroll="" className="well max-h-[200px] overflow-auto rounded-inner px-3 py-2.5 font-mono text-[12.5px] leading-[1.6] text-ink-2">{json(result)}</pre>}
</>
)}
</div>
</div>
);
}
/** Streamed text with a caret while it arrives. */
export function PlainStream({ text, done, className }: StreamRendererProps) {
return <div className={className}><Prose text={text} />{!done && <span aria-hidden="true" className="ml-0.5 inline-block h-[1.05em] w-[2px] translate-y-[3px] bg-accent motion-safe:animate-pulse" />}</div>;
}
/** A plain review: every hunk in a well, with accept and reject beside it. */
export function PlainDiff({ hunks, value = {}, onValueChange, className }: DiffRendererProps) {
const set = (id: string, v: HunkVerdict) => onValueChange?.({ ...value, [id]: value[id] === v ? undefined : v });
return (
<div className={cx("flex flex-col gap-2", className)}>
{hunks.map((h) => {
const v = value[h.id];
return (
<div key={h.id} className={cx("well overflow-hidden rounded-inner transition-opacity duration-200", v === "rejected" && "opacity-50")}>
<div className="flex min-h-9 items-center gap-2 px-3 text-[13px]">
<span className="min-w-0 flex-1 truncate"><span className="font-medium text-ink">{h.file}</span> <span className="text-ink-3">{h.header}</span></span>
{(["accepted", "rejected"] as const).map((k) => (
<button key={k} type="button" aria-pressed={v === k} onClick={() => set(h.id, k)}
className={cx("pressable h-7 rounded-chip px-2 text-[12.5px] font-medium outline-none transition-colors focus-visible:bg-hover",
v === k ? (k === "accepted" ? "bg-[color-mix(in_srgb,var(--captain-success)_16%,transparent)] text-success" : "bg-[color-mix(in_srgb,var(--captain-danger)_14%,transparent)] text-danger") : "text-ink-2 hover:bg-hover")}>
{k === "accepted" ? "Accept" : "Reject"}
</button>
))}
</div>
<div data-scroll="" className="overflow-x-auto pb-2 font-mono text-[12.5px] leading-[1.7]">
{h.lines.map((l, i) => (
<div key={i} className={cx("flex pr-3", l.type === "add" && "bg-[color-mix(in_srgb,var(--captain-success)_11%,transparent)]", l.type === "del" && "bg-[color-mix(in_srgb,var(--captain-danger)_10%,transparent)]")}>
<span aria-hidden="true" className="tnum w-9 shrink-0 select-none pr-1 text-right text-ink-3">{l.n ?? ""}</span>
<span className={cx("w-5 shrink-0 select-none text-center", l.type === "add" ? "text-success" : l.type === "del" ? "text-danger" : "")}>
{l.type === "ctx" ? "" : <><span aria-hidden="true">{l.type === "del" ? "\u2212" : "+"}</span><span className="sr-only">{l.type === "del" ? "removed" : "added"}</span></>}
</span>
<code className="whitespace-pre text-ink">{l.text}</code>
</div>
))}
</div>
</div>
);
})}
</div>
);
}
/* ---------- text and thinking ---------- */
function TextBody({ block: b }: BlockProps<TextBlock>) {
// a reply that streamed here keeps the streaming view once it ends, so the last words never re-render in a different shape
const streamed = useRef(!!b.streaming);
if (b.streaming) streamed.current = true;
const Stream = useContext(TranscriptContext).renderers?.stream ?? PlainStream;
return (
<div className="text-[15px] leading-[1.6] text-ink [text-wrap:pretty]">
{streamed.current ? <Stream text={b.text} done={!b.streaming} /> : <Prose text={b.text} />}
</div>
);
}
function ThinkingBody({ block: b, state: st }: BlockProps<ThinkingBlock>) {
return <Thinking active={st !== "done"} startedAt={b.since} seconds={b.ms ? Math.round(b.ms / 1000) : undefined} openWhileActive>{b.text}</Thinking>;
}
/* ---------- a tool call, as its JSON unfolding ---------- */
function ToolBody({ block: b, state: st }: BlockProps<ToolBlock>) {
const running = st !== "done" && st !== "waiting";
const Tool = useContext(TranscriptContext).renderers?.tool ?? PlainTool;
return (
<Tool name={b.name} title={b.title || b.name} status={b.error ? "error" : running ? "running" : "success"} args={b.args} result={b.result}
error={b.error} startedAt={b.since} duration={b.ms ?? undefined} className={Tool === PlainTool ? "-mx-1.5" : "-mx-3"} />
);
}
/* ---------- files: an indented tree in a well ---------- */
export function Tree({ files, sel, onSel, by }: { files: Array<Pick<DiffFile, "path" | "add" | "del" | "by">>; sel?: number; onSel?: (i: number) => void; by?: boolean }) {
const rows = useMemo(() => tree(files), [files]);
return (
<ul className="flex flex-col py-1 text-[13px]" aria-label="Files">
{rows.map((r, j) => {
const pad = { paddingInlineStart: 10 + r.depth * 16 };
if (r.dir) return <li key={"d" + j} className="flex h-7 items-center gap-2 pr-3 text-ink-3" style={pad}><Icon i="dir" s={12} /><span className="truncate">{r.name}</span></li>;
const inner = (
<>
{by && r.by ? <Mark type={r.by.type} s={12} /> : <span className="text-ink-3"><Icon i="file" s={12} /></span>}
<span className="min-w-0 flex-1 truncate text-left">{r.name}</span>
<PM add={r.add} del={r.del} />
</>
);
return (
<li key={r.path}>
{onSel
? <button type="button" style={pad} aria-current={sel === r.i ? "true" : undefined} onClick={() => onSel(r.i!)}
className={cx("flex h-7 w-full items-center gap-2 rounded-chip pr-3 outline-none transition-colors hover:bg-hover focus-visible:bg-hover", sel === r.i ? "font-medium text-ink" : "text-ink-2")}>{inner}</button>
: <span className="flex h-7 items-center gap-2 pr-3 text-ink-2" style={pad}>{inner}</span>}
</li>
);
})}
</ul>
);
}
function FilesBody({ block: b, state: st }: BlockProps<FilesBlock>) {
return <div className="well rounded-inner px-1"><Tree files={b.files || []} by={st === "delegating"} /></div>;
}
/* ---------- diff: read in a well; when it waits on you, every hunk is a card you scrub and fling ---------- */
function HunkLines({ hk, lang, note }: { hk: DiffHunk; lang: string; note?: DiffNote | null }) {
let o = hk.at ? hk.at[0] : 1, n = hk.at ? hk.at[1] : 1;
return (
<>
{hk.skip ? <div className="flex h-7 items-center gap-2 px-3 font-sans text-[12px] text-ink-3"><Icon i="drag" s={12} />{plural(hk.skip, "unchanged line")}</div> : null}
{hk.lines.map(([s, t], i) => {
const on = s === "+" ? "" : o++, nn = s === "-" ? "" : n++;
return (
<Fragment key={i}>
<div className={cx("flex pr-3", s === "+" && "bg-[color-mix(in_srgb,var(--captain-success)_11%,transparent)]", s === "-" && "bg-[color-mix(in_srgb,var(--captain-danger)_10%,transparent)]")}>
<span aria-hidden="true" className="tnum w-9 shrink-0 select-none pr-1 text-right text-ink-3">{on}</span>
<span aria-hidden="true" className="tnum w-9 shrink-0 select-none pr-1 text-right text-ink-3">{nn}</span>
<span className={cx("w-5 shrink-0 select-none text-center", s === "+" ? "text-success" : s === "-" ? "text-danger" : "")}>
{s === " " ? "" : <><span aria-hidden="true">{s === "-" ? "−" : "+"}</span><span className="sr-only">{s === "-" ? "removed" : "added"}</span></>}
</span>
<code className="whitespace-pre"><Code text={t} lang={lang} /></code>
</div>
{note && note.line === i && (
<div role="note" className="raised mx-3 my-2 flex items-start gap-2 rounded-inner px-3 py-2 font-sans text-[13px] leading-[1.45]">
<Mark type={note.by.type} s={14} /><b className="shrink-0 font-medium">{note.by.id}</b><span className="text-ink-2">{note.text}</span>
</div>
)}
</Fragment>
);
})}
</>
);
}
const toHunks = (files: DiffFile[]): ReviewHunk[] =>
files.flatMap((f) => f.hunks.map((hk, i) => {
let o = hk.at ? hk.at[0] : 1, n = hk.at ? hk.at[1] : 1;
return {
id: `${f.path}#${i}`, file: f.path, header: hk.at ? `line ${hk.at[1]}` : "",
lines: hk.lines.map(([s, t]) => (s === "+" ? { type: "add" as const, text: t, n: n++ } : s === "-" ? { type: "del" as const, text: t, n: o++ } : { type: "ctx" as const, text: t, n: (o++, n++) })),
};
}));
function DiffBody({ block: b, state: st, act }: BlockProps<DiffBlock>) {
const files = b.files || [];
const [sel, setSel] = useState(0);
const [all, setAll] = useState(false);
const hunks = useMemo(() => toHunks(files), [files]);
const [verdicts, setVerdicts] = useState<Record<string, HunkVerdict | undefined>>({});
const Review = useContext(TranscriptContext).renderers?.diff ?? PlainDiff;
const f = files[Math.min(sel, files.length - 1)];
if (!f) return null;
if (st === "waiting") {
const rejected = Object.values(verdicts).filter((v) => v === "rejected").length;
return (
<>
<Review hunks={hunks} value={verdicts} onValueChange={setVerdicts} hint />
<Acts>
<Btn kind="ink" k="↵" onClick={() => act("accept", verdicts)}>{rejected ? `Accept the rest` : "Accept changes"}</Btn>
<Btn onClick={() => act("changes", verdicts)}>Ask for changes</Btn>
</Acts>
</>
);
}
const lang = langOf(f.path);
const total = f.hunks.reduce((n, x) => n + x.lines.length, 0);
let left = all ? 1e9 : 22;
const shown = f.hunks.map((x) => { const take = Math.max(0, Math.min(x.lines.length, left)); left -= take; return take < x.lines.length ? { ...x, lines: x.lines.slice(0, take) } : x; }).filter((x) => x.lines.length);
return (
<div className={cx("grid gap-2", files.length > 1 && "@min-[560px]:grid-cols-[200px_minmax(0,1fr)]")}>
{files.length > 1 && <div className="well max-h-[320px] overflow-y-auto rounded-inner px-1 @max-[559px]:max-h-[132px]"><Tree files={files} sel={sel} onSel={setSel} by={st === "delegating"} /></div>}
<div className="well min-w-0 overflow-hidden rounded-inner">
<div className="flex h-9 items-center gap-2 px-3 text-[13px]"><span className="min-w-0 flex-1 truncate font-medium text-ink">{f.path}</span><PM add={f.add} del={f.del} /></div>
<div dir="ltr" tabIndex={0} data-scroll="" aria-label={`Changes to ${f.path}`} className="max-h-[360px] overflow-auto pb-2 font-mono text-[12.5px] leading-[1.7] text-ink outline-none focus-visible:bg-hover">
{shown.map((x, i) => <HunkLines key={i} hk={x} lang={lang} note={st === "reviewing" && i === 0 ? b.note : null} />)}
</div>
{total > 22 && (
<button type="button" onClick={() => setAll(!all)} aria-expanded={all}
className="flex h-8 w-full items-center px-3 text-left text-[12.5px] font-medium text-ink-2 outline-none transition-colors hover:bg-hover hover:text-ink focus-visible:bg-hover">
{all ? "Show less" : `Show all ${total} lines`}
</button>
)}
</div>
</div>
);
}
/* ---------- terminal: the command, its last lines, and how it ended ---------- */
function TerminalBody({ block: b, state: st, act }: BlockProps<TerminalBlock>) {
const [open, setOpen] = useState(false);
const lines = b.lines || [];
const run = st !== "done" && st !== "waiting" && b.exit == null;
const show = open ? lines : lines.slice(-6);
return (
<>
<div dir="ltr" className="well overflow-hidden rounded-inner font-mono text-[12.5px] leading-[1.65]">
<div className="flex gap-2 px-3.5 pt-3 text-ink"><span aria-hidden="true" className="select-none text-ink-3">$</span><code className="min-w-0 break-all"><Code text={b.cmd || ""} lang="sh" /></code></div>
{lines.length > 6 && (
<button type="button" onClick={() => setOpen(!open)} aria-expanded={open}
className="mt-1 h-6 px-3.5 font-sans text-[12px] font-medium text-ink-3 outline-none transition-colors hover:text-ink focus-visible:text-ink">
{open ? "Fewer lines" : `${lines.length - 6} earlier lines`}
</button>
)}
{st !== "waiting" && lines.length > 0 && (
<pre data-scroll="" className="max-h-[260px] overflow-auto px-3.5 pt-1 text-ink-2">
{show.map((l, i) => <span key={i} className={cx("block min-h-[1lh]", /error|fail|✗/i.test(l) ? "text-danger" : /✓|pass|ok\b|ready/i.test(l) ? "text-success" : undefined)}>{l || " "}</span>)}
</pre>
)}
<div className="tnum flex h-9 items-center gap-3 px-3.5 font-sans text-[12.5px] text-ink-3">
{run ? <><span className="text-ink-2">Running</span>{b.since && <Since at={b.since} />}</>
: st === "waiting" ? <span>Not run yet</span>
: <><span className={b.exit ? "text-danger" : "text-success"}>{b.exit ? `Exit ${b.exit}` : "Exit 0"}</span>{b.ms != null && <span>{dur(b.ms)}</span>}</>}
</div>
</div>
{st === "waiting" && <Acts><Btn kind="ink" k="↵" onClick={() => act("run")}>Run it</Btn><Btn onClick={() => act("always")}>Always allow</Btn><Btn onClick={() => act("deny")}>Skip</Btn></Acts>}
</>
);
}
/* ---------- preview: the running app in a window, with a before and after you drag between ---------- */
function Shot({ v, alt }: { v: ReactNode; alt: string }) { return typeof v === "string" ? <img src={v} alt={alt} draggable={false} className="size-full object-cover object-top" /> : <>{v}</>; }
const shotRole = (v: ReactNode, alt: string) => (typeof v === "string" ? {} : { role: "img", "aria-label": alt });
function PreviewBody({ block: b, state: st, act }: BlockProps<PreviewBlock>) {
const [x, setX] = useState(b.split != null ? b.split : 0.5);
const box = useRef<HTMLDivElement>(null);
useEffect(() => { if (b.split != null) setX(b.split); }, [b.split]);
const two = b.before != null && b.after != null;
const go = (e: RPointerEvent<HTMLDivElement>) => {
const r = box.current!.getBoundingClientRect();
const set = (ev: { clientX: number }) => setX(Math.min(1, Math.max(0, (ev.clientX - r.left) / r.width)));
set(e);
try { e.currentTarget.setPointerCapture(e.pointerId); } catch { /* jsdom */ }
const up = () => { removeEventListener("pointermove", set); removeEventListener("pointerup", up); };
addEventListener("pointermove", set); addEventListener("pointerup", up);
};
const key = (e: RKeyboardEvent) => {
const step = e.shiftKey ? 0.2 : 0.05;
const v = e.key === "ArrowLeft" || e.key === "ArrowDown" ? x - step : e.key === "ArrowRight" || e.key === "ArrowUp" ? x + step : e.key === "Home" ? 0 : e.key === "End" ? 1 : null;
if (v == null) return;
e.preventDefault(); e.stopPropagation();
setX(Math.min(1, Math.max(0, v)));
};
const pct = Math.round(x * 100);
const first = two ? b.before : (b.after ?? b.before);
return (
<>
<div className="raised overflow-hidden rounded-shell">
<div className="flex h-8 items-center justify-center bg-band px-3">
<span className="truncate text-[12px] text-ink-3">{b.url || "localhost:3000"}</span>
</div>
<div ref={box} dir="ltr" className="relative select-none overflow-hidden [container-type:inline-size]" style={{ aspectRatio: b.ratio || "16 / 10" }}>
<div className="absolute inset-0" {...shotRole(first, two ? "Before" : "Preview")}><Shot v={first} alt={two ? "Before" : "Preview"} /></div>
{two && <div className="absolute inset-0" style={{ clipPath: `inset(0 0 0 ${x * 100}%)` }} {...shotRole(b.after, "After")}><Shot v={b.after} alt="After" /></div>}
{two && (
<div role="slider" tabIndex={0} onPointerDown={go} onKeyDown={key} aria-label="Before and after" aria-valuemin={0} aria-valuemax={100} aria-valuenow={pct}
aria-valuetext={pct <= 0 ? "All after" : pct >= 100 ? "All before" : `${pct}% before, ${100 - pct}% after`}
className="group/split absolute inset-y-0 z-10 -ml-[22px] flex w-11 cursor-ew-resize touch-none justify-center outline-none" style={{ left: x * 100 + "%" }}>
<span className="h-full w-[2px] bg-white shadow-[0_0_0_1px_rgba(17,18,20,.12)]" />
<span className="absolute top-1/2 grid size-8 -translate-y-1/2 place-items-center rounded-full bg-white text-[#111214] shadow-[0_1px_2px_rgba(17,18,20,.25),0_6px_16px_-4px_rgba(17,18,20,.35)] transition-transform duration-150 ease-snap group-active/split:scale-95 group-focus-visible/split:bg-[#E8EDFF]">
<Icon i="drag" s={14} />
</span>
</div>
)}
{two && <span aria-hidden="true" className="glass absolute bottom-2.5 left-2.5 rounded-chip px-2 py-0.5 text-[12px] font-medium text-ink transition-opacity" style={{ opacity: x > 0.16 ? 1 : 0 }}>Before</span>}
{two && <span aria-hidden="true" className="glass absolute bottom-2.5 right-2.5 rounded-chip px-2 py-0.5 text-[12px] font-medium text-ink transition-opacity" style={{ opacity: x < 0.84 ? 1 : 0 }}>After</span>}
</div>
</div>
{st === "waiting" && <Acts><Btn kind="ink" k="↵" onClick={() => act("ship")}>Keep the new one</Btn><Btn onClick={() => act("revert")}>Go back</Btn></Acts>}
</>
);
}
/* ---------- tests: the count, and one cell per test ---------- */
function TestsBody({ block: b, state: st, act }: BlockProps<TestsBlock>) {
const cases = b.cases || "";
const cnt = (c: string) => (cases.match(new RegExp(c, "g")) || []).length;
const p = b.passed ?? cnt("p"), f = b.failed ?? cnt("f"), s = b.skipped ?? cnt("s");
const run = st !== "done" && st !== "waiting";
return (
<>
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-baseline gap-x-2">
<b className="display tnum text-[28px] font-semibold leading-none text-ink">{p.toLocaleString("en")}</b>
<span className="text-[14px] text-ink-2">{run ? "passing so far" : "passed"}</span>
<span className="tnum ml-auto text-[13px] text-ink-3">{[f ? `${f} failed` : "", s ? `${s} skipped` : "", b.ms != null ? dur(b.ms) : ""].filter(Boolean).join(" · ")}</span>
</div>
<div aria-hidden="true" className="flex flex-wrap gap-[3px]">
{Array.from(cases, (c, i) => (
<i key={i} className={cx("block h-3 w-[6px] rounded-[1.5px] transition-colors duration-200",
c === "p" ? "bg-success" : c === "f" ? "bg-danger" : c === "s" ? "bg-[color-mix(in_srgb,var(--captain-ink)_22%,transparent)]" : "well")} />
))}
</div>
{(b.failures || []).map((x, i) => (
<div key={i} className="flex flex-col gap-1.5">
<div className="flex items-center gap-2 text-[13.5px]"><span className="text-danger"><Icon i="x" s={12} /></span><span className="font-medium text-ink">{x.name}</span>{x.at && <span className="text-ink-3">{x.at}</span>}</div>
{x.message && <code className="well block rounded-inner px-3 py-2 font-mono text-[12.5px] text-ink-2">{x.message}</code>}
</div>
))}
</div>
{st === "waiting" && f > 0 && <Acts><Btn kind="ink" k="↵" onClick={() => act("fix")}>Fix the {f === 1 ? "failing test" : f + " failing tests"}</Btn><Btn onClick={() => act("ignore")}>Ship anyway</Btn></Acts>}
</>
);
}
/* ---------- timeline: who did what, when ---------- */
function TimelineBody({ block: b, state: st }: BlockProps<TimelineBlock>) {
const T = b.ms || 1, lanes = b.lanes || [];
const ticks: number[] = [], step = T > 6e5 ? 3e5 : T > 18e4 ? 6e4 : T > 6e4 ? 3e4 : 1e4;
for (let t = 0; t <= T; t += step) ticks.push(t);
return (
<div className="flex flex-col gap-1.5 text-[12.5px]">
{lanes.map((l, i) => (
<div key={l.agent.id} className="grid grid-cols-[112px_minmax(0,1fr)] items-center gap-3">
<span className="flex min-w-0 items-center gap-1.5 text-ink-2"><Mark type={l.agent.type} s={14} /><span className="truncate">{l.agent.id}</span></span>
<span className="sr-only">{l.spans.map((s) => `${s.label || "working"} ${clock(s.t0)} to ${clock(s.t1)}`).join(", ")}</span>
<span aria-hidden="true" className="well relative h-3.5 rounded-chip">
{l.spans.map((s, j) => (
<i key={j} title={s.label} className="absolute inset-y-[2px] block rounded-[3px]"
style={vars({ left: (s.t0 / T) * 100 + "%", width: Math.max(0.8, ((s.t1 - s.t0) / T) * 100) + "%",
background: s.state === "failed" ? "var(--captain-danger)" : s.state === "waiting" ? "var(--captain-accent)" : s.state === "idle" ? "transparent" : hue(l.agent.type),
opacity: s.state === "waiting" ? 0.55 : 1, "--d": (i * 3 + j) * 60 + "ms" })} />
))}
{b.now != null && st !== "done" && <b className="absolute -inset-y-1 w-[2px] rounded-full bg-accent" style={{ left: (b.now / T) * 100 + "%" }} />}
</span>
</div>
))}
<div aria-hidden="true" className="grid grid-cols-[112px_minmax(0,1fr)] gap-3">
<span />
<span className="tnum relative h-4 text-[11.5px] text-ink-3">{ticks.map((t) => <em key={t} className="absolute not-italic [translate:-50%_0] first:[translate:0_0]" style={{ left: (t / T) * 100 + "%" }}>{clock(t)}</em>)}</span>
</div>
</div>
);
}
/* ---------- conflict: two agents, side by side; the one you pick stays lit ---------- */
function ConflictBody({ block: b, state: st, act }: BlockProps<ConflictBlock>) {
const done = st === "done" || b.picked != null;
const side = (x: ConflictBlock["a"], k: "a" | "b") => (
<div className={cx("raised flex min-w-0 flex-col gap-2 rounded-inner p-3 transition-opacity duration-200", b.picked != null && b.picked !== k && "opacity-45")}>
<div className="flex items-center gap-2 text-[13px]">
<Mark type={x.agent.type} s={14} /><b className="font-medium text-ink">{x.agent.id}</b><span className="truncate text-ink-2">{x.title}</span>
{b.picked === k && <span className="ml-auto text-success"><Icon i="check" s={12} /><span className="sr-only">(picked)</span></span>}
</div>
{x.code && <pre dir="ltr" tabIndex={0} data-scroll="" className="well overflow-x-auto rounded-chip px-2.5 py-2 font-mono text-[12px] leading-[1.6] text-ink outline-none"><Code text={x.code} lang={x.lang || "ts"} /></pre>}
</div>
);
const opts = b.options || [`Use ${b.a.agent.id}'s`, `Use ${b.b.agent.id}'s`];
return (
<>
<p className="mb-2.5 text-[15px] text-ink">{b.question}</p>
<div className="grid gap-2 @min-[520px]:grid-cols-2">{side(b.a, "a")}{side(b.b, "b")}</div>
{!done && <Acts>{opts.map((o, i) => <Btn key={o} kind={i ? undefined : "ink"} k={String(i + 1)} onClick={() => act("pick", i === 0 ? "a" : i === 1 ? "b" : o)}>{o}</Btn>)}</Acts>}
</>
);
}
/* ---------- choice: options in a tray; the one you pick lifts out of it ---------- */
function ChoiceBody({ block: b, state: st, act }: BlockProps<ChoiceBlock>) {
const [p, setP] = useState(b.picked ?? null);
useEffect(() => setP(b.picked ?? null), [b.picked]);
const open = st === "waiting" && p == null, qid = useId();
return (
<div role="radiogroup" aria-labelledby={b.question ? qid : undefined} aria-label={b.question ? undefined : "Pick one"}>
{b.question && <p id={qid} className="mb-2.5 text-[15px] text-ink">{b.question}</p>}
<div className="well flex flex-col gap-0.5 rounded-shell p-1">
{(b.options || []).map((o, i) => {
const on = p === o.id;
return (
<button key={o.id} type="button" role="radio" aria-checked={on} disabled={!open && !on} data-opt=""
onClick={() => { if (!open) return; setP(o.id); act("pick", o.id); }}
className={cx("pressable flex min-h-11 items-center gap-3 rounded-inner px-3 py-2 text-left outline-none transition-[background-color,box-shadow,opacity] duration-200",
on ? "raised" : open ? "hover:bg-hover focus-visible:bg-hover" : "opacity-45")}>
<kbd aria-hidden="true" className="tnum w-3 font-sans text-[12.5px] text-ink-3">{i + 1}</kbd>
<span className="flex min-w-0 flex-1 flex-col">
<b className="text-[14px] font-medium text-ink">{o.label}</b>
{o.detail && <span className="text-[13px] text-ink-2">{o.detail}</span>}
</span>
{o.cost && <span className="tnum text-[13px] text-ink-3">{o.cost}</span>}
{on && <span className="text-success"><Icon i="check" s={12} /></span>}
</button>
);
})}
</div>
</div>
);
}
/* ---------- cost: what it cost, filling its cap ---------- */
function CostBody({ block: b, state: st, act }: BlockProps<CostBlock>) {
const items = b.items || [], sum = items.reduce((n, x) => n + x.cost, 0) || b.spent || 1;
const cap = b.cap, spent = b.spent != null ? b.spent : sum, near = !!cap && spent / cap >= 0.8;
return (
<>
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-baseline gap-x-2">
<b className="display tnum text-[28px] font-semibold leading-none text-ink">{money(spent)}</b>
{cap ? <span className="tnum text-[14px] text-ink-2">of {money(cap)}</span> : null}
<span className="tnum ml-auto text-[13px] text-ink-3">{[b.tokens ? `${(b.tokens / 1e6).toFixed(1)}M tokens` : "", b.agents ? plural(b.agents, "agent") : ""].filter(Boolean).join(" · ")}</span>
</div>
<div aria-hidden="true" className="well h-3 overflow-hidden rounded-chip p-[2px]">
<div className="flex h-full gap-[2px]" style={{ width: cap ? Math.min(100, (spent / cap) * 100) + "%" : "100%" }}>
{items.map((x) => <i key={x.type} className="block h-full rounded-[2px]" style={{ flex: x.cost, background: hue(x.type) }} />)}
</div>
</div>
<ul className="flex flex-wrap gap-x-4 gap-y-1.5 text-[13px]">
{items.map((x) => <li key={x.type} className="flex items-center gap-1.5 text-ink-2"><Mark type={x.type} s={12} />{typeOf(x.type)[0]}<span className="tnum text-ink">{money(x.cost)}</span></li>)}
</ul>
</div>
{st === "waiting" && near && cap && <Acts><Btn kind="ink" onClick={() => act("raise", cap * 2)}>Raise the cap to {money(cap * 2)}</Btn><Btn onClick={() => act("stop")}>Stop at the cap</Btn></Acts>}
</>
);
}
/* ---------- diagram: nodes on a 0 to 100 grid; hot edges flow while the Captain works ---------- */
function DiagramBody({ block: b, state: st, act }: BlockProps<DiagramBlock>) {
const nodes = b.nodes || [], edges = b.edges || [], W = 720, H = b.h || 220, NW = 62, mid = useId().replace(/:/g, "");
const at: Record<string, [number, number]> = Object.fromEntries(nodes.map((n) => [n.id, [(n.x / 100) * W, (n.y / 100) * H]]));
const name = (id: string) => nodes.find((n) => n.id === id)?.label || id;
const label = `Diagram: ${edges.map((e) => `${name(e.from)} to ${name(e.to)}${e.label ? ` (${e.label})` : ""}`).join("; ")}`;
return (
<>
<div dir="ltr" className="well overflow-x-auto rounded-shell px-2 py-3">
<svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label={label} className="block w-full min-w-[520px]">
<defs><marker id={mid} viewBox="0 0 8 8" refX={7} refY={4} markerWidth={7} markerHeight={7} orient="auto-start-reverse"><path d="M0 0L8 4L0 8z" fill="var(--captain-ink-3)" /></marker></defs>
{edges.map((e, i) => {
const [x1, y1] = at[e.from] || [0, 0], [x2, y2] = at[e.to] || [0, 0], v = Math.abs(y2 - y1) > Math.abs(x2 - x1);
let d: string, lx: number, ly: number, anchor: "middle" | "start" | "end" = "middle";
if (v) { const sy = y2 > y1 ? 1 : -1, a1 = y1 + sy * 18, a2 = y2 - sy * 20; d = `M${x1} ${a1}C${x1} ${(a1 + a2) / 2} ${x2} ${(a1 + a2) / 2} ${x2} ${a2}`; lx = (x1 + x2) / 2 + 10; ly = (y1 + y2) / 2 + 4; anchor = "start"; }
else { const sx = x2 > x1 ? 1 : -1, a1 = x1 + sx * NW, a2 = x2 - sx * (NW + 2), flat = Math.abs(y1 - y2) < 4; d = flat ? `M${a1} ${y1}L${a2} ${y2}` : `M${a1} ${y1}C${(a1 + a2) / 2} ${y1} ${(a1 + a2) / 2} ${y2} ${a2} ${y2}`; lx = (a1 + a2) / 2 + (flat ? 0 : sx * 8); ly = flat ? y1 - 8 : (y1 + y2) / 2 + 4; anchor = flat ? "middle" : sx > 0 ? "start" : "end"; }
return (
<g key={i}>
<path d={d} fill="none" stroke={e.hot ? "var(--captain-accent)" : "var(--captain-ink-3)"} strokeWidth={e.hot ? 1.75 : 1.25} markerEnd={`url(#${mid})`}
strokeDasharray={e.hot && st !== "done" ? "5 5" : undefined} className={e.hot && st !== "done" ? "motion-safe:animate-[ct-flow_900ms_linear_infinite]" : undefined} />
{e.label && <text x={lx} y={ly} textAnchor={anchor} fontSize={12} fill="var(--captain-ink-2)">{e.label}</text>}
</g>
);
})}
{nodes.map((n) => {
const [x, y] = at[n.id]!;
const fill = n.kind === "you" ? "var(--captain-primary)" : n.kind === "new" ? "var(--captain-accent-tint)" : "var(--captain-surface)";
const ink = n.kind === "you" ? "var(--captain-primary-ink)" : n.kind === "new" ? "var(--captain-accent-ink)" : "var(--captain-ink)";
return (
<g key={n.id} transform={`translate(${x - NW} ${y - 18})`}>
<rect y={1.5} width={NW * 2} height={36} rx={6} fill="rgba(17,18,20,.10)" />
<rect width={NW * 2} height={36} rx={6} fill={fill} />
<text x={NW} y={22.5} textAnchor="middle" fontSize={13} fontWeight={500} fill={ink}>{n.label}</text>
</g>
);
})}
</svg>
<style>{"@keyframes ct-flow{to{stroke-dashoffset:-10}}"}</style>
</div>
{st === "waiting" && <Acts><Btn kind="ink" k="↵" onClick={() => act("approve")}>This is right</Btn><Btn onClick={() => act("changes")}>Change it</Btn></Acts>}
</>
);
}
/** The built-in block bodies, by type, except plan and swarm, which live in transcript-plan. */
export const BASE_BODIES: Record<string, React.ComponentType<BlockProps<any>>> = { // eslint-disable-line @typescript-eslint/no-explicit-any
text: TextBody, thinking: ThinkingBody, diff: DiffBody, files: FilesBody, terminal: TerminalBody, preview: PreviewBody,
tests: TestsBody, timeline: TimelineBody, conflict: ConflictBody, choice: ChoiceBody, cost: CostBody, diagram: DiagramBody, tool: ToolBody,
};
export type { Block };"use client";
// uimaxxer · Transcript core, MIT. The headless core: no styles and no markup decisions. Formatting, the syntax tokenizer, the file tree,
// plain-text export, the virtual list, the shared clock, and screen-reader announcements.
// Everything here is safe to import on the server; hooks only touch the DOM inside effects.
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import type { Block, DiffFile, Message, State, CaptainMessage } from "@/registry/captain/ui/transcript-types";
export const DOM = typeof document !== 'undefined';
export const useIsoLayoutEffect = DOM ? useLayoutEffect : useEffect;
export const reducedMotion = (): boolean => DOM && typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
export const cx = (...a: unknown[]): string => a.filter(Boolean).join(' ');
/* ---------- one clock for every live number and motion on the page ---------- */
const subs = new Set<(t: number) => void>();
let raf = 0;
function loop(t: number) { subs.forEach(f => f(t)); raf = subs.size ? requestAnimationFrame(loop) : 0; }
export function onTick(f: (t: number) => void): () => void {
subs.add(f);
if (!raf && DOM) raf = requestAnimationFrame(loop);
return () => { subs.delete(f); };
}
/* ---------- formatting ---------- */
export const money = (v?: number): string => '$' + (v || 0).toFixed(2);
export const dur = (ms: number): string => { const s = Math.max(0, Math.floor(ms / 1e3)), m = Math.floor(s / 60); return m >= 60 ? `${Math.floor(m / 60)}h ${m % 60}m` : m ? `${m}m ${s % 60}s` : `${s}s`; };
export const clock = (ms: number): string => { const s = Math.max(0, Math.floor(ms / 1e3)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; };
export const plural = (n: number, w: string): string => `${n.toLocaleString('en')} ${w}${n === 1 ? '' : 's'}`;
export const rnd = (seed: string): (() => number) => { let s = 0; for (const c of seed) s = (s * 31 + c.charCodeAt(0)) >>> 0; s = s % 2147483646 + 1; return () => (s = (s * 16807) % 2147483647) / 2147483647; };
/* ---------- states ---------- */
export const STATES: Record<State, string> = { thinking: 'Thinking', planning: 'Planning', delegating: 'Handing out', working: 'Agents working', waiting: 'Needs you', reviewing: 'Reviewing', done: 'Done' };
export const BLOCKS = ['text', 'thinking', 'plan', 'swarm', 'diff', 'files', 'terminal', 'preview', 'tests', 'timeline', 'conflict', 'choice', 'cost', 'diagram', 'tool'] as const;
export const BLOCK_STATES: State[] = ['thinking', 'planning', 'delegating', 'working', 'waiting', 'reviewing', 'done'];
/** Some kinds say their live state in their own words. */
export const WORDS: Partial<Record<string, Partial<Record<State, string>>>> = { terminal: { working: 'Running' }, tests: { working: 'Running' }, diff: { working: 'Writing' }, files: { working: 'Writing' }, preview: { working: 'Building', reviewing: 'Checking' }, tool: { working: 'Running', thinking: 'Writing the call' } };
export const TITLES: Record<string, string> = { plan: 'Plan', swarm: 'Swarm', diff: 'Changes', files: 'Files', terminal: 'Terminal', preview: 'Preview', tests: 'Tests', timeline: 'What each agent did', conflict: 'Two agents disagree', choice: 'Pick one', cost: 'Cost', diagram: 'Diagram', tool: 'Tool' };
export const stateWord = (b: Block, st: State): string => (WORDS[b.type] && WORDS[b.type]![st]) || STATES[st];
/* ---------- syntax colour: a small tokenizer for ts, tsx, js, css, json and shell ---------- */
export type TokenClass = 0 | 'c' | 's' | 'k' | 'n' | 't' | 'f' | 'p';
const KW = 'import|from|export|default|const|let|var|function|return|if|else|await|async|new|class|extends|type|interface|true|false|null|undefined|try|catch|throw|for|of|in|while|switch|case|break|as|void|this|typeof';
const PARTS: Array<[Exclude<TokenClass, 0>, string]> = [
['c', String.raw`\/\/.*|\/\*[^]*?\*\/`],
['s', String.raw`'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|` + '`(?:[^`\\\\]|\\\\.)*`'],
['k', String.raw`\b(?:${KW})\b`],
['n', String.raw`#[0-9a-fA-F]{3,8}\b|\b\d[\d_.]*(?:px|ms|s|%)?\b`],
['t', String.raw`<\/?[A-Za-z][\w.]*|\/?>`],
['f', String.raw`[A-Za-z_$][\w$]*(?=\()`],
['p', String.raw`[\w-]+(?=\??:\s)`],
];
const RX: Record<string, [RegExp, TokenClass[]]> = {};
function rx(lang: string): [RegExp, TokenClass[]] {
if (RX[lang]) return RX[lang];
const use = PARTS.filter(([c]) => !(lang === 'sh' && (c === 'p' || c === 't' || c === 'c')) && !(lang === 'css' && (c === 'k' || c === 't')) && !(lang === 'json' && (c === 'k' || c === 't' || c === 'f')));
if (lang === 'sh') use.unshift(['c', String.raw`(?:^|\s)#.*`], ['p', String.raw`\s--?[\w-]+`]);
return (RX[lang] = [new RegExp(use.map(([, r]) => `(${r})`).join('|'), 'g'), use.map(([c]) => c)]);
}
const hlc = new Map<string, Array<[TokenClass, string]>>();
/** Split code into coloured tokens. Cached. */
export function highlight(code: string, lang: string): Array<[TokenClass, string]> {
const key = lang + '\u0000' + code, hit = hlc.get(key);
if (hit) return hit;
const [re, cls] = rx(lang), out: Array<[TokenClass, string]> = [];
let last = 0, m: RegExpExecArray | null;
re.lastIndex = 0;
while ((m = re.exec(code))) {
if (!m[0].length) { re.lastIndex++; continue; }
let g = 1; while (m[g] === undefined) g++;
if (m.index > last) out.push([0, code.slice(last, m.index)]);
out.push([cls[g - 1]!, m[0]]);
last = m.index + m[0].length;
}
if (last < code.length) out.push([0, code.slice(last)]);
if (hlc.size > 4000) hlc.clear();
hlc.set(key, out);
return out;
}
export const langOf = (p?: string): string => ({ ts: 'ts', tsx: 'tsx', js: 'ts', jsx: 'tsx', mjs: 'ts', css: 'css', json: 'json', sh: 'sh' } as Record<string, string>)[String(p || '').split('.').pop() || ''] || 'ts';
/* ---------- the file tree ---------- */
export interface TreeRow { dir?: boolean; name: string; depth: number; i?: number; path?: string; add?: number; del?: number; by?: DiffFile['by'] }
interface TreeNode { kids: Map<string, TreeNode>; files: Array<TreeRow & { i: number }> }
/** Files as rows of a folder tree; single-child folders collapse into one row ("app/(auth)/sign-in"). */
export function tree(files: Array<Pick<DiffFile, 'path' | 'add' | 'del' | 'by'>>): TreeRow[] {
const root: TreeNode = { kids: new Map(), files: [] };
files.forEach((f, i) => {
const parts = f.path.split('/'), name = parts.pop() || f.path;
let n = root;
for (const p of parts) { if (!n.kids.has(p)) n.kids.set(p, { kids: new Map(), files: [] }); n = n.kids.get(p)!; }
n.files.push({ ...f, name, i, depth: 0 });
});
const rows: TreeRow[] = [];
const walk = (n: TreeNode, depth: number) => {
for (const [name, kid] of n.kids) {
let label = name, k = kid;
while (!k.files.length && k.kids.size === 1) { const [n2, k2] = [...k.kids][0]!; label += '/' + n2; k = k2; }
rows.push({ dir: true, name: label, depth });
walk(k, depth + 1);
}
for (const f of n.files) rows.push({ ...f, depth });
};
walk(root, 0);
return rows;
}
/* ---------- plain text, for copy ---------- */
const tc = (ms: number) => clock(ms);
/** The block as plain text: what the copy action puts on the clipboard. A diff comes out as a unified diff. */
export function toText(b: Block): string {
switch (b.type) {
case 'text': case 'thinking': return b.text || '';
case 'plan': return (b.title ? b.title + '\n' : '') + (b.steps || []).map(s => `- ${s.title} (${s.agents || 1} ${s.type})`).join('\n');
case 'swarm': return (b.lanes || []).map(l => `${l.title}\n` + l.agents.map(a => ` ${a.id}: ${a.state}${a.step ? ' · ' + a.step : ''}`).join('\n')).join('\n');
case 'diff': return (b.files || []).map(f => `--- a/${f.path}\n+++ b/${f.path}\n` + f.hunks.map(x => `@@ -${x.at ? x.at[0] : 1} +${x.at ? x.at[1] : 1} @@\n` + x.lines.map(([s, l]) => s + l).join('\n')).join('\n')).join('\n');
case 'files': return (b.files || []).map(f => `${f.path} +${f.add || 0} -${f.del || 0}`).join('\n');
case 'terminal': return `$ ${b.cmd}\n${(b.lines || []).join('\n')}`;
case 'preview': return b.url || '';
case 'tests': return `${b.passed ?? 0} passed, ${b.failed || 0} failed, ${b.skipped || 0} skipped` + (b.failures || []).map(f => `\n✗ ${f.name}: ${f.message || ''}`).join('');
case 'timeline': return (b.lanes || []).map(l => `${l.agent.id}: ` + l.spans.map(s => `${s.label || ''} ${tc(s.t0)}-${tc(s.t1)}`).join(', ')).join('\n');
case 'conflict': return `${b.question}\nA (${b.a.agent.id}): ${b.a.title}\nB (${b.b.agent.id}): ${b.b.title}`;
case 'choice': return `${b.question || ''}\n` + (b.options || []).map((o, i) => `${i + 1}. ${o.label}${o.detail ? ': ' + o.detail : ''}`).join('\n');
case 'cost': return `${money(b.spent)}${b.cap ? ' of ' + money(b.cap) : ''}\n` + (b.items || []).map(x => `${x.type}: ${money(x.cost)}`).join('\n');
case 'diagram': return (b.edges || []).map(e => `${e.from} -> ${e.to}${e.label ? ' (' + e.label + ')' : ''}`).join('\n');
case 'tool': { const j = (v: unknown) => { try { return typeof v === 'string' ? v : JSON.stringify(v, null, 2) ?? ''; } catch { return String(v); } }; return `${b.name}(${b.args === undefined ? '' : j(b.args)})` + (b.error ? `\nerror: ${b.error}` : b.result !== undefined ? `\n${j(b.result)}` : ''); }
default: return '';
}
}
/** A short sentence about a block, for screen readers. */
export function describe(b: Block, st: State, name = 'Captain'): string {
const t = b.title || TITLES[b.type] || b.type;
if (st === 'waiting') {
if (b.type === 'swarm' && b.ask) return `${b.ask.from.id} asks: ${b.ask.text} Answers: ${b.ask.options.join(', ')}.`;
if (b.type === 'conflict') return `${b.question} ${b.a.agent.id}: ${b.a.title}. ${b.b.agent.id}: ${b.b.title}.`;
if (b.type === 'choice') return `${b.question || 'Pick one'}: ${b.options.map(o => o.label).join(', ')}.`;
return `${t} needs you.`;
}
if (st === 'done') {
if (b.type === 'text') return `${name}: ${b.text.length > 280 ? b.text.slice(0, 277) + '…' : b.text}`;
if (b.type === 'tests') return `Tests: ${b.passed ?? 0} passed${b.failed ? `, ${b.failed} failed` : ''}.`;
if (b.type === 'thinking') return '';
return `${t} done.`;
}
return `${t}: ${stateWord(b, st)}.`;
}
/* ---------- the virtual list ---------- */
const ESTC = new WeakMap<Message, number>();
const BLOCK_EST: Record<string, number> = { text: 64, thinking: 36, plan: 260, swarm: 220, diff: 420, files: 180, terminal: 200, preview: 460, tests: 180, timeline: 220, conflict: 280, choice: 220, cost: 160, diagram: 300, tool: 64 };
const est0 = (m: Message) => m.role === 'you' ? 64 : m.role === 'captain' ? 72 + (m.blocks || []).reduce((n, b) => n + (BLOCK_EST[b.type] || 120), 0) : 40;
/** A first guess at a row's height, before it has been measured. Cached per message object. */
export const estimate = (m: Message): number => { let v = ESTC.get(m); if (v == null) ESTC.set(m, (v = est0(m))); return v; };
/** Offsets of every row: o[i] is the top of row i, o[n] the total height. O(n). */
export function offsets(messages: Message[], measured: Map<string, number>): Float64Array {
const n = messages.length, o = new Float64Array(n + 1);
for (let i = 0; i < n; i++) { const m = messages[i]!; o[i + 1] = o[i]! + (measured.get(m.id) || estimate(m)); }
return o;
}
/** The row at height y, by binary search. */
export function rowAt(o: Float64Array, y: number): number {
let lo = 0, hi = o.length - 1;
while (lo < hi) { const mid = (lo + hi) >> 1; if (o[mid + 1]! <= y) lo = mid + 1; else hi = mid; }
return lo;
}
/** Blocks waiting on you, newest first: [row index, block id]. Looks at live turns only. */
export function waitingIn(messages: Message[], limit = 50): Array<[number, string]> {
const w: Array<[number, string]> = [];
for (let i = messages.length - 1; i >= 0 && w.length < limit; i--) {
const m = messages[i]!;
if (m.role === 'captain' && m.state !== 'done') for (const b of m.blocks || []) if (b.state === 'waiting') w.push([i, b.id]);
}
return w;
}
export interface ListRow { message: Message; fresh: boolean; skim: boolean; height?: number }
export interface UseTranscriptList {
/** Put on the scrolling element. */
scrollRef: React.RefObject<HTMLDivElement | null>;
onScroll: () => void;
/** Put on the element whose children are the rows. */
rowsRef: React.RefObject<HTMLDivElement | null>;
padTop: number; padBottom: number;
/** Index of the first rendered row. */
start: number;
rows: ListRow[];
atBottom: boolean;
/** Messages that arrived while the reader was scrolled up. */
unseen: number;
/** Waiting blocks below the screen. */
waitingBelow: Array<[number, string]>;
scrollToIndex(i: number, blockId?: string | null, smooth?: boolean): void;
scrollToBlock(id: string, smooth?: boolean): void;
scrollToEnd(smooth?: boolean): void;
}
/**
* Virtualises a thread: only rows near the screen are rendered, heights are measured as rows render,
* the reader's place holds when something above changes height, and the list follows new messages while
* the reader is at the bottom. While flinging, rows that were not drawn yet come back as skims (cheap
* stand-ins) until scrolling settles. Rows appended at the end are marked fresh, so only they animate in.
*/
export function useTranscriptList(messages: Message[], overscan = 800): UseTranscriptList {
const scrollRef = useRef<HTMLDivElement | null>(null);
const rowsRef = useRef<HTMLDivElement | null>(null);
const measured = useRef(new Map<string, number>());
const msgs = useRef(messages); msgs.current = messages;
// rows the size observer watches; reset when it disconnects, so a remount (StrictMode, Activity) observes them again
const watched = useRef(new WeakSet<Element>());
const [ver, setVer] = useState(0);
const [vp, setVp] = useState({ top: 0, h: 800 });
const bottom = useRef(true);
// set by scrollToEnd: keep following the end until the reader scrolls themselves, even while heights settle
const pin = useRef(false);
const [away, setAway] = useState(false);
const seenN = useRef(messages.length);
const lastTop = useRef(0), skimRef = useRef(false), skimT = useRef<ReturnType<typeof setTimeout>>(undefined), full = useRef(new Set<string>());
const [skim, setSkim] = useState(false);
useEffect(() => () => clearTimeout(skimT.current), []);
// rows that arrive at the end animate in; rows that scroll into view do not
const fresh = useRef(new Set<string>()), prevM = useRef<Message[] | null>(null);
if (prevM.current !== messages) {
const p = prevM.current;
if (p && p.length && messages.length > p.length && messages[0] && p[0] && messages[0].id === p[0].id) {
for (let i = p.length; i < messages.length; i++) fresh.current.add(messages[i]!.id);
if (fresh.current.size > 400) fresh.current = new Set([...fresh.current].slice(-200));
} else if (!p || !messages[0] || !p[0] || messages[0].id !== p[0].id) fresh.current = new Set();
prevM.current = messages;
}
const off = useMemo(() => offsets(messages, measured.current), [messages, ver]);
const total = off[messages.length];
const a = Math.max(0, rowAt(off, vp.top - overscan)), z = Math.min(messages.length, rowAt(off, vp.top + vp.h + overscan) + 1);
const ro = useMemo(() => DOM && typeof ResizeObserver !== 'undefined' ? new ResizeObserver((es, obs) => {
let changed = false, above = 0;
const el = scrollRef.current; if (!el) return;
for (const e of es) {
const t = e.target as HTMLElement;
if (!t.isConnected) { obs.unobserve(t); continue; }
if (t.hasAttribute('data-skim')) continue;
const id = t.getAttribute('data-id'); if (!id) continue;
const hh = Math.round(e.borderBoxSize && e.borderBoxSize[0] ? e.borderBoxSize[0].blockSize : t.offsetHeight);
const old = measured.current.get(id);
if (old === hh) continue;
// before its first measurement a row stood in at its estimate, so that is what it grew or shrank from
const m = msgs.current[+(t.getAttribute('aria-posinset') || 0) - 1];
const was = old ?? (m && m.id === id ? estimate(m) : hh);
measured.current.set(id, hh); changed = true;
if (!bottom.current && t.offsetTop + was < el.scrollTop) above += hh - was;
}
if (changed) { if (pin.current) el.scrollTop = el.scrollHeight; else if (above) el.scrollTop += above; setVer(v => v + 1); }
}) : null, []);
useEffect(() => () => { ro && ro.disconnect(); watched.current = new WeakSet(); }, [ro]);
useIsoLayoutEffect(() => {
const box = rowsRef.current; if (!box) return;
const kids = box.children, f = new Set<string>();
for (let i = 0; i < kids.length; i++) {
const r = kids[i] as HTMLElement;
if (ro && !watched.current.has(r)) { watched.current.add(r); ro.observe(r); }
if (!r.hasAttribute('data-skim')) f.add(r.getAttribute('data-id') || '');
}
full.current = f;
});
const onScroll = useCallback(() => {
const el = scrollRef.current; if (!el) return;
const jump = Math.abs(el.scrollTop - lastTop.current) > el.clientHeight;
lastTop.current = el.scrollTop;
if (jump) {
if (!skimRef.current) { skimRef.current = true; setSkim(true); }
clearTimeout(skimT.current);
skimT.current = setTimeout(() => { skimRef.current = false; setSkim(false); }, 140);
}
let atB = el.scrollHeight - el.scrollTop - el.clientHeight < 48;
if (pin.current) { if (atB) pin.current = false; else atB = true; }
bottom.current = atB;
setAway(!atB);
if (atB) seenN.current = Infinity;
// never more than the window: an unstyled or unbounded scroller reports the whole thread's height
const h = DOM && innerHeight > 0 ? Math.min(el.clientHeight, innerHeight) : el.clientHeight;
setVp(v => (Math.abs(v.top - el.scrollTop) < 1 && v.h === h) ? v : { top: el.scrollTop, h });
}, []);
useIsoLayoutEffect(() => {
const el = scrollRef.current; if (!el) return;
const rs = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => { if (bottom.current) el.scrollTop = el.scrollHeight; onScroll(); }) : null;
rs && rs.observe(el);
// the reader taking over ends a jump to the end
const mine = () => { pin.current = false; };
el.addEventListener('wheel', mine, { passive: true }); el.addEventListener('touchstart', mine, { passive: true }); el.addEventListener('pointerdown', mine);
el.scrollTop = el.scrollHeight; onScroll();
return () => { rs && rs.disconnect(); el.removeEventListener('wheel', mine); el.removeEventListener('touchstart', mine); el.removeEventListener('pointerdown', mine); };
}, []);
useIsoLayoutEffect(() => { const el = scrollRef.current; if (el && bottom.current) el.scrollTop = el.scrollHeight; }, [messages, ver]);
if (bottom.current) seenN.current = messages.length;
const unseen = Math.max(0, messages.length - Math.min(seenN.current, messages.length));
const scrollToIndex = useCallback((i: number, blockId?: string | null, smooth?: boolean) => {
const el = scrollRef.current; if (!el) return;
el.scrollTo({ top: Math.max(0, off[i]! - 24), behavior: smooth && !reducedMotion() ? 'smooth' : 'auto' });
if (blockId) setTimeout(() => {
const n = el.querySelector<HTMLElement>(`[data-block="${CSS.escape(blockId)}"]`);
if (!n) return;
const r = n.getBoundingClientRect(), r0 = el.getBoundingClientRect();
el.scrollTop += r.top - r0.top - 24;
// a short tint on the block it took you to; no outline
if (!reducedMotion() && typeof n.animate === 'function') n.animate([{ backgroundColor: 'var(--captain-accent-tint)' }, { backgroundColor: 'transparent' }], { duration: 1100, easing: 'cubic-bezier(0.23, 1, 0.32, 1)' });
n.focus({ preventScroll: true });
}, smooth ? 420 : 60);
}, [off]);
const scrollToBlock = useCallback((id: string, smooth = true) => {
const i = messages.findIndex(m => m.id === id || (m.role === 'captain' && (m.blocks || []).some(b => b.id === id)));
if (i >= 0) scrollToIndex(i, messages[i]!.id === id ? null : id, smooth);
}, [messages, scrollToIndex]);
const scrollToEnd = useCallback((smooth = true) => {
const el = scrollRef.current; if (!el) return;
bottom.current = true; pin.current = true;
// smooth only over a short distance; across thousands of rows it would chase heights that are still settling
const far = el.scrollHeight - el.scrollTop - el.clientHeight > el.clientHeight * 3;
el.scrollTo({ top: el.scrollHeight, behavior: smooth && !far && !reducedMotion() ? 'smooth' : 'auto' });
setAway(false);
}, []);
const waits = useMemo(() => waitingIn(messages), [messages]);
const waitingBelow = waits.filter(([i]) => off[i]! > vp.top + vp.h - 80);
const rows: ListRow[] = [];
for (let i = a; i < z; i++) {
const m = messages[i]!, sk = skim && !full.current.has(m.id);
rows.push({ message: m, fresh: fresh.current.has(m.id), skim: sk, height: sk ? (measured.current.get(m.id) || estimate(m)) : undefined });
}
return { scrollRef, onScroll, rowsRef, padTop: off[a]!, padBottom: total! - off[z]!, start: a, rows, atBottom: !away, unseen, waitingBelow, scrollToIndex, scrollToBlock, scrollToEnd };
}
/* ---------- announcements for screen readers ---------- */
/**
* Watches the thread and returns the latest sentence worth announcing: the Captain's state changes,
* a block that starts waiting on you, a reply that finished streaming, and tests that finished.
* Streaming words are never announced one by one; a reply is read once, when it is complete.
*/
/** One sentence for the live log. `id` never changes, so a list keyed by it only ever adds nodes. */
export interface Announcement { id: number; text: string }
export function useAnnouncements(messages: Message[], name = 'Captain'): Announcement[] {
const seen = useRef(new Map<string, string>());
const seq = useRef(0);
const [log, setLog] = useState<Announcement[]>([]);
const first = useRef(true);
useEffect(() => {
const out: string[] = [];
// only the last few messages can change; looking at 6 keeps this O(1) on long threads
for (let i = Math.max(0, messages.length - 6); i < messages.length; i++) {
const m = messages[i]!;
if (m.role !== 'captain') continue;
const cm = m as CaptainMessage, st = cm.state || 'done', k = 'turn:' + cm.id, v = st;
if (seen.current.get(k) !== v) { seen.current.set(k, v); if (st !== 'done' && st !== 'waiting') out.push(`${cm.name || name}: ${STATES[st]}.`); }
for (const b of cm.blocks || []) {
const bst: State = b.state || 'done';
const sig = bst + (b.type === 'text' && (b as { streaming?: boolean }).streaming ? ':s' : '');
const bk = 'b:' + b.id;
if (seen.current.get(bk) === sig) continue;
seen.current.set(bk, sig);
if (b.type === 'text' && (b as { streaming?: boolean }).streaming) continue;
if (bst === 'waiting' || bst === 'done') { const d = describe(b, bst, cm.name || name); if (d) out.push(d); }
}
}
if (seen.current.size > 2000) seen.current = new Map([...seen.current].slice(-500));
if (first.current) { first.current = false; return; } // don't read the whole history on mount
if (out.length) { const add = out.map(text => ({ id: ++seq.current, text })); setLog(l => [...l, ...add].slice(-8)); }
}, [messages, name]);
return log;
}
/** Copy text to the clipboard; resolves false when the browser refuses. */
export async function copyText(s: string): Promise<boolean> {
try { await navigator.clipboard.writeText(s); return true; } catch { return false; }
}// uimaxxer · Transcript types, MIT. The message and block shapes, shared with captain-transcript (github.com/jawadjalal/transcript).
import type { CSSProperties, ReactNode } from 'react';
/** What the Captain, or one block, is doing right now. */
export type State = 'thinking' | 'planning' | 'delegating' | 'working' | 'waiting' | 'reviewing' | 'done';
/** The agent kinds shared with the composer and the sidebar. Any other string gets a stable mark and colour. */
export type AgentType = 'review' | 'tests' | 'build' | 'research' | 'security' | 'docs' | 'design' | 'ship' | (string & {});
export interface AgentRef { id: string; type: AgentType }
export type AgentState = 'queued' | 'working' | 'needs' | 'failed' | 'done';
export interface BlockBase {
id: string;
/** Leave it out, or 'done', for a finished block. */
state?: State;
/** When this state began (ms since epoch). Live states show a timer. */
since?: number;
/** A title for the block's header. Each kind has a default. */
title?: string;
/** The agent that made it, shown in the header. */
by?: AgentRef | AgentRef[] | null;
/** While delegating: who it is being handed to. */
to?: AgentRef | AgentRef[];
/** Start folded to its header. */
folded?: boolean;
}
export interface TextBlock extends BlockBase { type: 'text'; text: string; streaming?: boolean }
export interface ThinkingBlock extends BlockBase { type: 'thinking'; text: string; ms?: number }
export interface PlanStep { id: string; title: string; type: AgentType; agents?: number }
export interface PlanBlock extends BlockBase { type: 'plan'; steps: PlanStep[] }
export interface SwarmAgent extends AgentRef { state: AgentState; step?: string; ms?: number }
export interface SwarmLane { id: string; title: string; agents: SwarmAgent[] }
export interface SwarmAsk { from: AgentRef; text: string; options: string[] }
export interface SwarmBlock extends BlockBase { type: 'swarm'; lanes: SwarmLane[]; ask?: SwarmAsk | null }
export type DiffLine = [' ' | '+' | '-', string];
export interface DiffHunk { at?: [number, number]; skip?: number; lines: DiffLine[] }
export interface DiffFile { path: string; add?: number; del?: number; by?: AgentRef; hunks: DiffHunk[] }
export interface DiffNote { line: number; by: AgentRef; text: string }
export interface DiffBlock extends BlockBase { type: 'diff'; files: DiffFile[]; note?: DiffNote }
export interface FilesBlock extends BlockBase { type: 'files'; files: Array<Pick<DiffFile, 'path' | 'add' | 'del' | 'by'>> }
export interface TerminalBlock extends BlockBase { type: 'terminal'; cmd: string; lines?: string[]; exit?: number | null; ms?: number | null }
export interface PreviewBlock extends BlockBase {
type: 'preview';
url?: string;
/** An image URL or any React node. With both, a slider sits between them. */
before?: string | ReactNode;
after?: string | ReactNode;
/** 0 to 1: where the slider starts. Controlled when it changes. */
split?: number;
/** CSS aspect-ratio of the shot. Default '16 / 10'. */
ratio?: string;
}
export interface TestFailure { name: string; at?: string; message?: string }
export interface TestsBlock extends BlockBase {
type: 'tests';
passed?: number; failed?: number; skipped?: number; ms?: number | null;
/** One letter per test: p passed, f failed, s skipped, r not run yet. */
cases?: string;
failures?: TestFailure[];
}
export interface TimelineSpan { t0: number; t1: number; label?: string; state?: 'failed' | 'waiting' | 'idle' }
export interface TimelineBlock extends BlockBase { type: 'timeline'; ms: number; now?: number; lanes: Array<{ agent: AgentRef; spans: TimelineSpan[] }> }
export interface ConflictSide { agent: AgentRef; title: string; code?: string; lang?: string }
export interface ConflictBlock extends BlockBase { type: 'conflict'; question: string; a: ConflictSide; b: ConflictSide; options?: string[]; picked?: 'a' | 'b' | (string & {}) | null }
export interface ChoiceOption { id: string; label: string; detail?: string; cost?: string }
export interface ChoiceBlock extends BlockBase { type: 'choice'; question?: string; options: ChoiceOption[]; picked?: string | null }
export interface CostBlock extends BlockBase { type: 'cost'; spent?: number; cap?: number; tokens?: number; agents?: number; items: Array<{ type: AgentType; cost: number }> }
export interface DiagramNode { id: string; label: string; x: number; y: number; kind?: 'you' | 'new' }
export interface DiagramEdge { from: string; to: string; label?: string; hot?: boolean | number }
/** Nodes on a 0 to 100 grid. */
export interface DiagramBlock extends BlockBase { type: 'diagram'; h?: number; nodes: DiagramNode[]; edges: DiagramEdge[] }
/** A tool call drawn as its arguments and result, with the JSON unfolding as it streams. */
export interface ToolBlock extends BlockBase { type: 'tool'; name: string; args?: unknown; result?: unknown; error?: string; ms?: number | null }
/** Your own block kind: render it with the `blocks` prop. */
export interface CustomBlock extends BlockBase { type: `x-${string}`; [key: string]: unknown }
export type Block = TextBlock | ThinkingBlock | PlanBlock | SwarmBlock | DiffBlock | FilesBlock | TerminalBlock | PreviewBlock | TestsBlock | TimelineBlock | ConflictBlock | ChoiceBlock | CostBlock | DiagramBlock | ToolBlock | CustomBlock;
export type BlockType = Block['type'];
export type BuiltinBlockType = Exclude<BlockType, `x-${string}`>;
export interface YouMessage { id: string; role: 'you'; text: string; note?: string }
export interface CaptainMessage {
id: string; role: 'captain';
state?: State; since?: number; name?: string;
blocks: Block[];
/** For a finished turn: how long it took, how many agents, what it cost. */
ms?: number | null; agents?: number; cost?: number;
}
export interface EventMessage { id: string; role: 'event'; text: string; tone?: 'bad' }
export type Message = YouMessage | CaptainMessage | EventMessage;
export interface ActionEvent {
/** The block's id. */
block: string;
type: BlockType;
/**
* plan: approve, reorder, edit · swarm: answer · diff: accept, changes · terminal: run, always, deny ·
* preview: ship, revert, split · tests: fix, ignore · conflict: pick · choice: pick · cost: raise, stop · diagram: approve, changes · tool: none
*/
action: string;
value?: unknown;
}
/** Props every block body gets. */
export interface BlockProps<B extends Block = Block> {
block: B;
/** The block's state, resolved (never undefined). */
state: State;
/** The state of the turn it sits in. */
turn: State;
act: (action: string, value?: unknown) => void;
}
export type Theme = 'light' | 'dark' | 'system';
export interface TranscriptProps {
/** Controlled: the whole conversation. Give a message a new object only when it changes. */
messages?: Message[];
/** Uncontrolled: the first messages. Add more with the ref handle's append and update. */
defaultMessages?: Message[];
onAction?: (e: ActionEvent) => void;
/** Leave it out to follow the page (.dark or [data-theme] on an ancestor). 'system' follows the OS. */
theme?: Theme;
/** Sets --captain-accent on this transcript. */
accent?: string;
/** The Captain's name in its turns. */
name?: string;
/** Reading column in px. Default 760. */
width?: number;
/** Extra px drawn above and below the screen. Default 800. */
overscan?: number;
/** Swap the pieces inside built-in blocks: tool calls, the diff you review, and streamed replies. Each defaults to a light rendering on the theme tokens. */
renderers?: Renderers;
/** Render your own block kinds, or replace a built-in one. */
blocks?: Partial<Record<string, React.ComponentType<BlockProps<any>>>>;
/** Called when someone copies a block's permalink. */
onLink?: (blockId: string) => void;
/** What to show with no messages. */
empty?: ReactNode;
/** Label for the conversation, read by screen readers. Default 'Conversation with the Captain'. */
label?: string;
dir?: 'ltr' | 'rtl';
/** Kept for the captain-transcript package. uimaxxer styles with the theme's classes, so it does nothing here. */
injectStyles?: boolean;
children?: ReactNode;
className?: string;
style?: CSSProperties;
}
export interface TranscriptHandle {
scrollToBlock(id: string, smooth?: boolean): void;
scrollToEnd(smooth?: boolean): void;
/** Uncontrolled only: add messages at the end. */
append(...m: Message[]): void;
/** Uncontrolled only: change one message by id. */
update(id: string, patch: Partial<Message> | ((m: Message) => Message)): void;
readonly messages: Message[];
readonly element: HTMLDivElement | null;
}
/* ---------- renderers: swappable pieces inside the built-in blocks ---------- */
export type ToolStatus = 'running' | 'success' | 'error';
/** What the tool renderer gets for a `tool` block. */
export interface ToolRendererProps { name: string; title: ReactNode; status: ToolStatus; args?: unknown; result?: unknown; error?: ReactNode; startedAt?: number; duration?: number; className?: string }
export interface ReviewLine { type: 'add' | 'del' | 'ctx'; text: string; n?: number }
/** One hunk to accept or reject, flattened from a diff block's files. */
export interface ReviewHunk { id: string; file: string; header: string; lines: ReviewLine[] }
export type HunkVerdict = 'accepted' | 'rejected';
/** What the diff renderer gets while a diff waits on you. */
export interface DiffRendererProps { hunks: ReviewHunk[]; value?: Record<string, HunkVerdict | undefined>; onValueChange?: (v: Record<string, HunkVerdict | undefined>) => void; hint?: boolean; className?: string }
/** What the stream renderer gets for a reply that is streaming (and keeps once it ends). */
export interface StreamRendererProps { text: string; done?: boolean; className?: string }
export interface Renderers {
tool?: React.ComponentType<ToolRendererProps>;
diff?: React.ComponentType<DiffRendererProps>;
stream?: React.ComponentType<StreamRendererProps>;
}// uimaxxer · Transcript marks, MIT. Square-pixel glyphs, shared with the composer and the sidebar: '#' solid, '+' 50% dither.
// Pure data and pure functions, so they are safe on the server.
import type { AgentType } from "@/registry/captain/ui/transcript-types";
const P = (s: string): string[] => s.split('/');
const pc = new Map<string, [string, string]>();
export function paths(rows: string[], ph: number): [string, string] {
const k = rows.join() + ph;
const hit = pc.get(k); if (hit) return hit;
let s = '', d = '';
rows.forEach((r, y) => {
let run = -1;
for (let x = 0; x <= r.length; x++) {
const c = r[x];
if (c === '#') { if (run < 0) run = x; } else if (run >= 0) { s += `M${run} ${y}h${x - run}v1h${run - x}z`; run = -1; }
if (c === '+' && (x + y + ph) % 2 === 0) d += `M${x} ${y}h1v1h-1z`;
}
});
pc.set(k, [s, d]);
return [s, d];
}
const E = '..............';
export const ICONS: Record<string, string[]> = {
copy: P(`${E}/....########../....########../....##....##../.#######..##../.#######..##../.##...##..##../.##...######../.##...######../.##...##....../.##...##....../.#######....../.#######....../${E}`),
link: P(`${E}/....##...##.../....##...##.../.############./.############./...##...##..../...##...##..../...##...##..../.############./.############./..##...##...../..##...##...../${E}/${E}`),
chev: P(`${E}/${E}/${E}/${E}/...##....##.../....##..##..../.....####...../......##....../${E}/${E}/${E}/${E}/${E}/${E}`),
check: P(`${E}/${E}/${E}/...........##./..........###./.........###../.##.....###.../.###...###..../..###.###...../...#####....../....###......./.....#......../${E}/${E}`),
x: P(`${E}/${E}/${E}/...##....##.../...###..###.../....######..../.....####...../.....####...../....######..../...###..###.../...##....##.../${E}/${E}/${E}`),
grip: P(`${E}/${E}/....##..##..../....##..##..../${E}/${E}/....##..##..../....##..##..../${E}/${E}/....##..##..../....##..##..../${E}/${E}`),
plus: P(`${E}/${E}/......##....../......##....../......##....../......##....../..##########../..##########../......##....../......##....../......##....../......##....../${E}/${E}`),
down: P(`${E}/......##....../......##....../......##....../......##....../......##....../..##..##..##../...##.##.##.../....######..../.....####...../......##....../${E}/${E}/${E}`),
file: P(`${E}/..#######...../..##...###..../..##....###.../..##.....##.../..##.....##.../..##.....##.../..##.....##.../..##.....##.../..##.....##.../..#########.../..#########.../${E}/${E}`),
dir: P(`${E}/${E}/.#####......../.##..######.../.##.......###./.############./.##........##./.##........##./.##........##./.##........##./.############./${E}/${E}/${E}`),
term: P(`${E}/${E}/.##.........../..##........../...##........./....##......../...##........./..##........../.##....######./.......######./${E}/${E}/${E}/${E}`),
warn: P(`${E}/......##....../......##....../.....####...../....##..##..../....##..##..../...###..###.../...###..###.../..##########../..####..####../.############./.############./${E}/${E}`),
play: P(`${E}/${E}/...##........./...####......./...######...../...########.../...#########../...#########../...########.../...######...../...####......./...##........./${E}/${E}`),
drag: P(`${E}/${E}/${E}/${E}/..##......##../.##........##./##..........##/##..........##/.##........##./..##......##../${E}/${E}/${E}/${E}`),
};
/* agent marks, the same silhouettes and colours as composer and the sidebar */
const M16 = '................';
export const MARKS: Record<string, string[]> = {
eye: P(`${M16}/${M16}/${M16}/......####....../...##########.../..####....####../.####..##..####./####..####..####/####..####..####/.####..##..####./..####....####../...++++++++++.../......++++....../${M16}/${M16}/${M16}`),
nib: P(`${M16}/.......##......./......####....../.....######...../....########..../....###..###..../...####..####.../...#####.####.../...####.#####.../....###.####..../....###.###...../.....++++++...../.....++++++...../.....++++++...../${M16}/${M16}`),
flask: P(`${M16}/.....######...../......####....../......####....../......####....../.....######...../....###..###..../...###....###.../..###......###../..##++++++++##../.###++++++++###./.##++++++++++##./.##############./${M16}/${M16}/${M16}`),
bolt: P(`${M16}/.........####.../........####..../.......####...../......####....../.....####......./....##########../...##########.../........####..../.......####...../......++++....../.....+++......../....++........../${M16}/${M16}/${M16}`),
lens: P(`${M16}/....######....../...########...../..###++++###..../..##++++++##..../..##++++++##..../..##++++++##..../..###++++###..../...########...../....#######...../.........###..../..........###.../...........###../............##../${M16}/${M16}`),
shield: P(`${M16}/..############../..##++++++####../..##++++++####../..##++++++####../..##++++++####../..###+++++####../...##+++++###.../...###++++###.../....##++++##..../.....##++##...../......####....../.......##......./${M16}/${M16}/${M16}`),
leaf: P(`${M16}/............##../.........#####../......########../....##########../...###++######../..###++#######../..##++#######.../..##+#######..../..#.######....../.#..####......../#.............../${M16}/${M16}/${M16}/${M16}`),
cube: P(`${M16}/${M16}/.......++......./.....++++++...../...++++++++++.../..++++++++++++../..##++++++++##../..####++++####../..######.######./..######.######./..######.######./..######.######./...#####.#####../.....###.###..../${M16}/${M16}`),
captain: P(`.......##......./.......##......./..#....##....#../...#...##...#.../....#.####.#..../.....######...../....###++###..../#######++#######/#######++#######/....###++###..../.....######...../....#.####.#..../...#...##...#.../..#....##....#../.......##......./.......##.......`),
};
const NAMES: string[] = ['eye', 'nib', 'flask', 'bolt', 'lens', 'shield', 'leaf', 'cube'];
const HUES: string[] = ['#2E5BFF', '#C98A0B', '#1E8A4C', '#0E7C86', '#6B4BD6', '#A63A9C'];
/** The built-in agent types: label, mark, and the --captain-type-* token for its colour (with the spec's value as fallback). */
export const TYPES: Record<string, [label: string, mark: string, colour: string]> = {
review: ['Review', 'eye', 'var(--captain-type-review, #2E5BFF)'], tests: ['Tests', 'flask', 'var(--captain-type-tests, #1E8A4C)'], build: ['Build', 'cube', 'var(--captain-type-build, #0E7C86)'],
research: ['Research', 'lens', 'var(--captain-type-research, #6B4BD6)'], security: ['Security', 'shield', 'var(--captain-type-security, #A63A9C)'], docs: ['Docs', 'leaf', 'var(--captain-type-docs, #8A6A12)'],
design: ['Design', 'nib', 'var(--captain-type-design, #C2410C)'], ship: ['Ship', 'bolt', 'var(--captain-type-ship, #C98A0B)'],
};
export const hash = (s: unknown): number => { let n = 0; for (const c of String(s)) n = (n * 31 + c.charCodeAt(0)) >>> 0; return n; };
/** An agent type's label, mark and colour. Unknown types get a stable mark, and read --captain-type-<name> if the app sets it. */
export const typeOf = (t: AgentType): [string, string, string] => TYPES[t] || [String(t), NAMES[hash(t) % 8]!, `var(--captain-type-${String(t).replace(/[^\w-]/g, '')}, ${HUES[hash(t) % 6]})`];
export const hue = (t: AgentType): string => typeOf(t)[2];
/** The Captain's state as twelve pixels of motion: a pure function of state and time, returned as an SVG path. */
export function cells(s: string, t: number): string {
const c: number[] = [], sq = (x: number, y: number, w = 2, hh = 2) => { for (let i = 0; i < w; i++) for (let j = 0; j < hh; j++) c.push(x + i, y + j); };
if (s === 'thinking') [1, 5, 9].forEach((y, i) => sq(1, y, 3 + Math.round(7 * (.5 + .5 * Math.sin(t / 300 + i * 2.1))), 2));
else if (s === 'planning') { const k = (t % 2400) / 2400; [1, 5, 9].forEach((y, i) => { sq(0, y); sq(4, y, Math.round(8 * Math.min(1, Math.max(0, k * 1.7 - i * .3))), 2); }); }
else if (s === 'delegating') { sq(5, 5); const d = Math.round(5 * ((t % 900) / 900)); ([[-1, -1], [1, -1], [-1, 1], [1, 1]] as const).forEach(([x, y]) => sq(5 + x * d, 5 + y * d)); }
else if (s === 'working') { const k = Math.floor((t % 2400) / 600); ([[0, 0], [10, 0], [10, 10], [0, 10]] as const).forEach(([x, y], i) => { if (i <= k) sq(x, y); }); sq(5, 5); }
else if (s === 'reviewing') { for (let x = 1; x <= 10; x++) c.push(x, 0, x, 11); for (let y = 1; y <= 10; y++) c.push(1, y, 10, y); sq(3, 2 + Math.floor((t % 1600) / 200), 6, 1); }
else if (s === 'done') { ([[0, 6], [1, 7], [2, 8], [3, 9], [4, 8], [5, 7], [6, 6], [7, 5], [8, 4], [9, 3], [10, 2]] as const).slice(0, Math.ceil(t / 30)).forEach(([x, y]) => sq(x, y)); }
else if (s === 'waiting') { for (let x = 1; x <= 10; x++) c.push(x, 1, x, 8); for (let y = 2; y <= 7; y++) c.push(0, y, 11, y); c.push(2, 9, 3, 9, 2, 10); const k = Math.floor(t / 400) % 4; [3, 5, 7].forEach((x, i) => { if (i < k) sq(x, 4, 2, 2); }); }
else sq(5, 5);
let d = '';
for (let i = 0; i < c.length; i += 2) { const x = c[i]!, y = c[i + 1]!; if (x >= 0 && y >= 0 && x < 12 && y < 12) d += `M${x} ${y}h1v1h-1z`; }
return d;
}// uimaxxer · Transcript for the Vercel AI SDK, MIT. Vercel AI SDK adapter. Turns useChat's UIMessage[] into transcript messages, and draws tool calls as blocks.
// It has no dependency on `ai`: the types below are the structural shape of UIMessage parts (AI SDK 5 and later).
import type { ActionEvent, Block, BuiltinBlockType, CaptainMessage, Message, State } from "@/registry/captain/ui/transcript-types";
export interface UIPartLike {
type: string;
text?: string;
state?: string;
toolCallId?: string;
toolName?: string;
input?: unknown;
output?: unknown;
errorText?: string;
id?: string;
data?: unknown;
/** A streamed, not-yet-final tool output (an async generator execute). */
preliminary?: boolean;
}
export interface UIMessageLike { id: string; role: 'user' | 'assistant' | 'system' | (string & {}); parts?: UIPartLike[] }
export type ChatStatus = 'submitted' | 'streaming' | 'ready' | 'error' | (string & {});
/** A tool call, as the adapter hands it to your own mapping. */
export interface ToolCall { id: string; name: string; state: string; input: unknown; output: unknown; errorText?: string; preliminary?: boolean }
export interface FromUIMessagesOptions {
/** useChat's status, so the last turn shows Thinking, Agents working or Done. */
status?: ChatStatus;
/** The Captain's name on its turns. */
name?: string;
/**
* Draw a tool call your own way. Return a block, several, or null to hide it. Tools named after a built-in
* block (plan, swarm, diff, files, terminal, preview, tests, timeline, conflict, choice, cost, diagram)
* need no mapping: their input is the block, and their output is merged over it.
*/
tools?: Record<string, (call: ToolCall) => Block | Block[] | null>;
/** Tools that wait on a person (no execute on the server) and so read as 'waiting' until answered. Default: plan, choice, conflict. */
interactive?: string[];
/** How a tool with no mapping is drawn: 'tool' shows its arguments and result as JSON that unfolds while it streams; 'terminal' shows a one-line call and its output, as captain-transcript 1.0 did. Default 'tool'. */
generic?: 'tool' | 'terminal';
}
const BUILTIN = new Set<string>(['plan', 'swarm', 'diff', 'files', 'terminal', 'preview', 'tests', 'timeline', 'conflict', 'choice', 'cost', 'diagram']);
const obj = (v: unknown): Record<string, unknown> => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
const json = (v: unknown): string => { try { return typeof v === 'string' ? v : JSON.stringify(v, null, 2) ?? ''; } catch { return String(v); } };
function toolCall(p: UIPartLike): ToolCall | null {
if (p.type === 'dynamic-tool') return { id: p.toolCallId || '', name: p.toolName || 'tool', state: p.state || '', input: p.input, output: p.output, errorText: p.errorText, preliminary: p.preliminary };
if (p.type.startsWith('tool-')) return { id: p.toolCallId || '', name: p.type.slice(5), state: p.state || '', input: p.input, output: p.output, errorText: p.errorText, preliminary: p.preliminary };
return null;
}
/** The block state for a tool call's state. */
export function toolState(state: string, interactive: boolean, preliminary?: boolean): State {
if (preliminary) return 'working';
if (state === 'input-streaming') return 'thinking';
if (state === 'approval-responded') return 'working';
if (state === 'input-available') return interactive ? 'waiting' : 'working';
if (state === 'approval-requested') return 'waiting';
return 'done';
}
/** One tool call as blocks: your mapping, a built-in block, or a terminal-style card showing the call and its result. */
export function toolToBlocks(c: ToolCall, o: FromUIMessagesOptions = {}): Block[] {
const own = o.tools && o.tools[c.name];
if (own) { const r = own(c); return r == null ? [] : Array.isArray(r) ? r : [r]; }
const inter = (o.interactive || ['plan', 'choice', 'conflict']).includes(c.name);
const st = toolState(c.state, inter, c.preliminary);
if (BUILTIN.has(c.name)) {
const out0 = obj(c.output), { action, value, ...rest } = out0;
const b = { ...obj(c.input), ...rest, id: c.id, type: c.name as BuiltinBlockType, state: st } as Record<string, unknown>;
// an answer from toolOutputFor: fold it back into the block
if (action !== undefined) {
if (c.name === 'plan' && Array.isArray(value)) b.steps = value;
if ((c.name === 'choice' || c.name === 'conflict') && value !== undefined) b.picked = value;
}
fill(b);
const out: Block[] = [b as unknown as Block];
if (c.state === 'output-error') out.push({ id: c.id + ':err', type: 'text', text: `**${c.name} failed:** ${c.errorText || 'unknown error'}` });
return out;
}
const err = c.state === 'output-error';
if ((o.generic ?? 'tool') === 'tool') return [{
id: c.id, type: 'tool', name: c.name, title: c.name, state: st === 'thinking' ? 'working' : st,
args: c.input, result: c.state === 'output-denied' ? 'denied' : c.output, error: err ? c.errorText || 'error' : undefined,
}];
return [{
id: c.id, type: 'terminal', title: c.name, state: st === 'thinking' ? 'working' : st,
cmd: `${c.name}(${c.input === undefined ? '' : json(c.input).replace(/\s*\n\s*/g, ' ')})`,
lines: err ? [c.errorText || 'error'] : c.state === 'output-denied' ? ['denied'] : c.output === undefined ? [] : json(c.output).split('\n').slice(0, 200),
// exit 0 only once the tool has really finished; a denied call is not a success
exit: c.state === 'output-available' && !c.preliminary ? 0 : err || c.state === 'output-denied' ? 1 : null,
}];
}
/* a half-streamed tool input can miss arrays the bodies map over. It fills copies: the arrays and their items
still belong to useChat's message, which is sent back to the model and may be saved */
function fill(b: Record<string, unknown>) {
const arr = (k: string) => { b[k] = Array.isArray(b[k]) ? (b[k] as unknown[]).map(x => (x && typeof x === 'object' && !Array.isArray(x) ? { ...x } : x)) : []; };
switch (b.type) {
case 'plan': arr('steps'); (b.steps as Array<Record<string, unknown>>).forEach((s, i) => { s.id ??= 's' + i; s.type ??= 'build'; s.title ??= ''; }); break;
case 'swarm': arr('lanes'); (b.lanes as Array<Record<string, unknown>>).forEach((l, i) => { l.id ??= 'l' + i; if (!Array.isArray(l.agents)) l.agents = []; }); break;
case 'diff': arr('files'); (b.files as Array<Record<string, unknown>>).forEach(f => { if (!Array.isArray(f.hunks)) f.hunks = []; }); break;
case 'files': arr('files'); break;
case 'terminal': b.cmd ??= ''; break;
case 'timeline': arr('lanes'); b.ms ??= 1; break;
case 'choice': arr('options'); (b.options as Array<Record<string, unknown>>).forEach((x, i) => { x.id ??= String(i); x.label ??= ''; }); break;
case 'cost': arr('items'); break;
case 'diagram': arr('nodes'); arr('edges'); break;
case 'conflict': { const side = (k: string) => { const s = { ...obj(b[k]) }; s.agent = { id: '?', type: 'build', ...obj(s.agent) }; s.title ??= ''; b[k] = s; }; side('a'); side('b'); b.question ??= ''; break; }
}
}
/**
* useChat's messages as transcript messages. User messages become your turns; assistant messages become Captain
* turns: text → text, reasoning → thinking, tool calls → blocks, and data-<block type> parts → that block.
*/
const CACHE = new WeakMap<UIMessageLike, { k: string; o: FromUIMessagesOptions['tools']; m: Message | null; last: boolean | null }>();
export function fromUIMessages(ui: UIMessageLike[], o: FromUIMessagesOptions = {}): Message[] {
const out: Message[] = [];
const live = o.status === 'submitted' || o.status === 'streaming';
let lastDep = false;
ui.forEach((m, mi) => {
// useChat keeps finished messages as the same objects: map each once, so unchanged turns keep their identity
const isLast = mi === ui.length - 1;
const k = `${isLast && live}|${o.name || ''}|${(o.interactive || []).join()}|${o.generic || ''}`, hit = CACHE.get(m);
// a turn whose state hung on being last (a stopped run reads as working until another turn follows) is mapped again when that changes
if (hit && hit.k === k && hit.o === o.tools && (hit.last === null || hit.last === isLast)) { if (hit.m) out.push(hit.m); return; }
const before = out.length;
lastDep = false;
one(m, mi);
CACHE.set(m, { k, o: o.tools, m: out.length > before ? out[out.length - 1]! : null, last: lastDep ? isLast : null });
});
function one(m: UIMessageLike, mi: number) {
const parts = m.parts || [];
if (m.role === 'user') { out.push({ id: m.id, role: 'you', text: parts.filter(p => p.type === 'text').map(p => p.text || '').join('\n\n') }); return; }
if (m.role !== 'assistant') return;
const blocks: Block[] = [];
parts.forEach((p, i) => {
const id = `${m.id}:${i}`;
if (p.type === 'text') { if (p.text) blocks.push({ id, type: 'text', text: p.text, streaming: p.state === 'streaming' }); return; }
if (p.type === 'reasoning') { if (p.text) blocks.push({ id, type: 'thinking', text: p.text, state: p.state === 'streaming' ? 'working' : 'done' }); return; }
const c = toolCall(p);
if (c) { blocks.push(...toolToBlocks({ ...c, id: c.id || id }, o)); return; }
if (p.type.startsWith('data-') && BUILTIN.has(p.type.slice(5)) && p.data) {
const b = { state: 'done', ...obj(p.data), id: p.id || id, type: p.type.slice(5) } as Record<string, unknown>;
fill(b); blocks.push(b as unknown as Block);
}
});
const last = mi === ui.length - 1;
const waiting = blocks.some(b => b.state === 'waiting');
const working = blocks.some(b => b.state && b.state !== 'done' && b.state !== 'waiting');
const state: State = waiting ? 'waiting' : last && live ? (blocks.length ? 'working' : 'thinking') : working && last ? 'working' : 'done';
if (!waiting && working) lastDep = true;
const turn: CaptainMessage = { id: m.id, role: 'captain', state, blocks };
if (o.name) turn.name = o.name;
out.push(turn);
}
// sent, nothing back yet: show the Captain thinking
if (o.status === 'submitted' && (!ui.length || ui[ui.length - 1]!.role === 'user')) out.push({ id: '__captain-pending', role: 'captain', state: 'thinking', blocks: [] });
return out;
}
/** Actions that change a block while you work on it, and so answer nothing yet. */
export const DRAFT_ACTIONS = ['reorder', 'edit', 'split'];
/**
* What to hand addToolOutput (or addToolResult on AI SDK 5) when someone acts on a waiting tool block.
* Null if the block is not a tool call, or the action is a draft (reordering or editing a plan before approving it).
*/
export function toolOutputFor(e: ActionEvent, ui: UIMessageLike[]): { tool: string; toolCallId: string; output: { action: string; value?: unknown } } | null {
if (DRAFT_ACTIONS.includes(e.action)) return null;
for (let i = ui.length - 1; i >= 0; i--) for (const p of ui[i]!.parts || []) {
const c = toolCall(p);
if (c && c.id === e.block) return { tool: c.name, toolCallId: c.id, output: { action: e.action, ...(e.value !== undefined ? { value: e.value } : null) } };
}
return null;
}// uimaxxer · Transcript fixtures, MIT. Every block in every state, a scripted Captain you can watch, and a 10,000-message thread.
// Nothing here calls a model: it is seeded demo data, the passkeys story from captain-transcript.
import { createElement as h, type ComponentType } from 'react';
import type { ActionEvent, Block, BlockType, ChoiceBlock, ConflictBlock, CostBlock, DiagramBlock, DiffFile, DiffNote, Message, PlanStep, State, SwarmAsk, TerminalBlock, TestsBlock, TimelineBlock, ToolBlock } from '@/registry/captain/ui/transcript-types';
// Loose on purpose: this is demo data, shaped by the typed wrapper in captain-transcript-fixtures.ts.
/* eslint-disable @typescript-eslint/no-explicit-any */
type A = any;
/* ---------- the running app, drawn in HTML so it is sharp at any size ---------- */
const FP = ['..####..', '.#....#.', '#..##..#', '#.#..#.#', '#.#..#.#', '#.#.##.#', '..#.#..#', '.#..#.#.'];
const finger = (c: string, s: string) => h('svg', { viewBox: '0 0 8 8', width: s, height: s, shapeRendering: 'crispEdges', style: { flex: 'none' } }, FP.map((r, y) => [...r].map((ch, x) => ch === '#' ? h('rect', { key: x + '-' + y, x, y, width: 1, height: 1, fill: c }) : null)));
const field = (label: string, value: string, opts: A = {}) => h('div', { style: { display: 'flex', flexDirection: 'column', gap: '.8cqw' } },
h('span', { style: { fontSize: '1.3cqw', color: opts.dim || '#6F6F6D' } }, label),
h('div', { style: { height: '4.4cqw', borderRadius: opts.r || '.5cqw', border: '1px solid ' + (opts.line || '#D4D4D0'), padding: '0 1.4cqw', display: 'flex', alignItems: 'center', fontSize: '1.4cqw', color: '#171717', background: opts.bg || '#fff' } }, value));
function SignInImpl({ after }: { after?: boolean }) {
const base = { position: 'absolute', inset: 0, display: 'grid', gridTemplateColumns: '42% 58%', fontFamily: 'Inter, ui-sans-serif, system-ui, sans-serif', letterSpacing: '-.01em', background: '#fff' };
if (!after) return h('div', { style: base },
h('div', { style: { background: '#E7E7E4', padding: '4cqw', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' } },
h('span', { style: { fontSize: '1.8cqw', fontWeight: 600, color: '#5C5C5A' } }, 'Your app'),
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '1cqw' } }, [80, 64, 72].map((w, i) => h('i', { key: i, style: { display: 'block', width: w + '%', height: '1cqw', borderRadius: '.3cqw', background: '#D2D2CF' } })))),
h('div', { style: { background: '#fff', padding: '5cqw 6cqw', display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: '2cqw' } },
h('span', { style: { fontSize: '2.4cqw', fontWeight: 600, color: '#2B2B2A' } }, 'Sign in'),
field('Email', 'you@example.com', { r: '.3cqw' }),
field('Password', '••••••••••••', { r: '.3cqw' }),
h('div', { style: { height: '4.4cqw', borderRadius: '.3cqw', background: '#5B6B8C', color: '#fff', display: 'grid', placeItems: 'center', fontSize: '1.4cqw', fontWeight: 500 } }, 'Sign in'),
h('span', { style: { fontSize: '1.3cqw', color: '#3E63DD', textDecoration: 'underline' } }, 'Forgot your password?')));
return h('div', { style: base },
h('div', { style: { background: '#0F2A1E', padding: '4cqw', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', color: '#fff' } },
h('span', { style: { fontSize: '1.8cqw', fontWeight: 600 } }, 'Your app'),
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '1.4cqw' } },
finger('#7FD4A6', '5cqw'),
h('span', { style: { fontSize: '3.4cqw', lineHeight: 1.1, fontWeight: 600, letterSpacing: '-.03em' } }, 'Welcome back.'),
h('span', { style: { fontSize: '1.4cqw', color: 'rgba(255,255,255,.62)' } }, 'Your key is on this device.'))),
h('div', { style: { background: '#fff', padding: '5cqw 6cqw', display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: '2cqw' } },
h('span', { style: { fontSize: '2.4cqw', fontWeight: 600, color: '#171717' } }, 'Sign in'),
h('div', { style: { height: '5cqw', borderRadius: '.8cqw', background: '#171717', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '1.2cqw', fontSize: '1.5cqw', fontWeight: 500 } }, finger('#fff', '2cqw'), 'Continue with a passkey'),
h('div', { style: { display: 'flex', alignItems: 'center', gap: '1.2cqw', color: '#6F6F6D', fontSize: '1.2cqw' } }, h('i', { style: { flex: 1, height: 1, background: '#E6E6E3' } }), 'or', h('i', { style: { flex: 1, height: 1, background: '#E6E6E3' } })),
field('Email', 'you@example.com', { r: '.8cqw', bg: '#F6F6F5', line: 'transparent' }),
h('span', { style: { fontSize: '1.3cqw', color: '#6F6F6D' } }, 'Use your password instead')));
}
/* ---------- the story: add passkeys to sign-in ---------- */
export const PLAN = [
{ id: 'p1', title: 'Check passkey support on Safari, Chrome and Android', type: 'research', agents: 2 },
{ id: 'p2', title: 'Threat-model the sign-in flow', type: 'security', agents: 1 },
{ id: 'p3', title: 'WebAuthn register and verify routes', type: 'build', agents: 3 },
{ id: 'p4', title: 'Passkey button first, password behind it', type: 'design', agents: 2 },
{ id: 'p5', title: 'Tests for every path, the mobile deep link too', type: 'tests', agents: 4 },
{ id: 'p6', title: 'Review it all, then open one PR', type: 'review', agents: 2 },
];
const STEPS = {
research: ['Reading the WebAuthn level 3 spec', 'Testing conditional UI in Safari 18', 'Checking Android credential manager'],
security: ['Mapping replay and phishing paths', 'Checking origin and RP id binding'],
build: ['Writing passkey.ts', 'Adding /auth/passkey/options', 'Storing credentials beside the hash', 'Wiring verify into the session'],
design: ['Laying out the sign-in screen', 'Moving password behind a link', 'Checking the 360px layout'],
tests: ['Writing passkey.test.ts', 'Covering the iOS deep link', 'Running the auth suite', 'Covering password fallback'],
review: ['Reading the diff', 'Checking error paths'],
};
export function lanes(state = 'queued', steps: A[] = PLAN) {
return steps.map(s => ({ id: 'l-' + s.id, title: s.title, agents: Array.from({ length: s.agents }, (_, i) => ({ id: `${s.type}-${String(i + 1).padStart(2, '0')}`, type: s.type, state, step: ((STEPS as A)[s.type] || ['Working'])[i % ((STEPS as A)[s.type] || ['Working']).length], ms: 0 })) }));
}
export const ASK = { from: { id: 'tests-02', type: 'tests' }, text: 'The iOS deep link drops ?next after a passkey sign-in. Fix it here, or file it?', options: ['Fix it here', 'File it for later'] };
export const DIFF = [
{ path: 'src/auth/passkey.ts', add: 86, del: 0, by: { id: 'build-01', type: 'build' }, hunks: [{ at: [0, 1], lines: [
['+', "import { generateAuthenticationOptions, verifyAuthenticationResponse } from '@simplewebauthn/server';"],
['+', "import { db } from '../db';"],
['+', "import { createSession } from './session';"],
['+', ''],
['+', "const rpID = process.env.RP_ID ?? 'example.com';"],
['+', ''],
['+', 'export async function options(email: string) {'],
['+', ' const user = await db.user.findUnique({ where: { email }, include: { passkeys: true } });'],
['+', ' return generateAuthenticationOptions({'],
['+', ' rpID,'],
['+', " userVerification: 'preferred',"],
['+', " allowCredentials: user?.passkeys.map(k => ({ id: k.credentialId, transports: k.transports })) ?? [],"],
['+', ' });'],
['+', '}'],
['+', ''],
['+', 'export async function verify(email: string, response: AuthenticationResponseJSON, challenge: string) {'],
['+', ' const key = await db.passkey.findFirstOrThrow({ where: { credentialId: response.id } });'],
['+', ' const { verified, authenticationInfo } = await verifyAuthenticationResponse({'],
['+', ' response, expectedChallenge: challenge, expectedOrigin: `https://${rpID}`, expectedRPID: rpID,'],
['+', ' credential: { id: key.credentialId, publicKey: key.publicKey, counter: key.counter },'],
['+', ' });'],
['+', " if (!verified) throw new Error('passkey did not verify');"],
['+', ' await db.passkey.update({ where: { id: key.id }, data: { counter: authenticationInfo.newCounter } });'],
['+', ' return createSession(key.userId);'],
['+', '}'],
] }] },
{ path: 'src/auth/routes.ts', add: 24, del: 6, by: { id: 'build-02', type: 'build' }, hunks: [{ at: [12, 12], lines: [
[' ', "router.post('/auth/sign-in', rateLimit(10), async (req, res) => {"],
['-', ' const session = await signInWithPassword(req.body.email, req.body.password);'],
['-', " res.redirect('/home');"],
['+', " const session = req.body.passkey"],
['+', ' ? await passkey.verify(req.body.email, req.body.passkey, req.session.challenge)'],
['+', ' : await signInWithPassword(req.body.email, req.body.password);'],
['+', " res.redirect(safeNext(req.query.next) ?? '/home');"],
[' ', '});'],
] }, { at: [40, 44], skip: 26, lines: [
['+', "router.post('/auth/passkey/options', rateLimit(20), async (req, res) => {"],
['+', ' const opts = await passkey.options(req.body.email);'],
['+', ' req.session.challenge = opts.challenge;'],
['+', ' res.json(opts);'],
['+', '});'],
] }] },
{ path: 'app/(auth)/sign-in/page.tsx', add: 52, del: 31, by: { id: 'design-01', type: 'design' }, hunks: [{ at: [18, 18], lines: [
[' ', 'export default function SignIn() {'],
['-', ' return <PasswordForm />;'],
['+', ' const [usePassword, setUsePassword] = useState(false);'],
['+', ' return ('],
['+', ' <Stack gap={16}>'],
['+', ' <PasskeyButton onDone={next => router.replace(next)} />'],
['+', ' <Divider>or</Divider>'],
['+', ' {usePassword ? <PasswordForm /> : <EmailField autoComplete="username webauthn" />}'],
['+', ' <TextButton onClick={() => setUsePassword(true)}>Use your password instead</TextButton>'],
['+', ' </Stack>'],
['+', ' );'],
[' ', '}'],
] }] },
{ path: 'src/db/schema.ts', add: 12, del: 0, by: { id: 'build-03', type: 'build' }, hunks: [{ at: [31, 31], lines: [
['+', 'export const passkey = table({'],
['+', ' id: id(),'],
['+', ' userId: ref(user),'],
['+', ' credentialId: text().unique(),'],
['+', ' publicKey: bytes(),'],
['+', ' counter: int().default(0),'],
['+', " transports: text().array(),"],
['+', '});'],
] }] },
{ path: 'tests/auth/passkey.test.ts', add: 64, del: 0, by: { id: 'tests-01', type: 'tests' }, hunks: [{ at: [0, 1], lines: [
['+', "test('signs in with a passkey and keeps ?next', async () => {"],
['+', " const res = await signIn({ passkey: fakeAssertion(), next: '/billing' });"],
['+', " expect(res.headers.location).toBe('/billing');"],
['+', '});'],
] }] },
];
export const NOTE = { line: 21, by: { id: 'review-01', type: 'review' }, text: 'Throwing here returns a 500. Return a 401 so the button can say what happened.' };
export const TERM = { cmd: 'pnpm vitest run tests/auth --reporter=dot', lines: [
' RUN v3.2.4 /app',
'',
' ✓ tests/auth/password.test.ts (38)',
' ✓ tests/auth/session.test.ts (27)',
' ✓ tests/auth/routes.test.ts (31)',
' ✓ tests/auth/passkey.test.ts (24)',
' ✓ tests/auth/deeplink.test.ts (12)',
' ✓ tests/auth/rate-limit.test.ts (8)',
' ↓ tests/auth/legacy-sso.test.ts (3 skipped)',
'',
' Test Files 6 passed | 1 skipped (7)',
' Tests 140 passed | 3 skipped (143)',
' Duration 6.41s',
] };
const CASES = (n: number, fail: number[] = []) => Array.from({ length: n }, (_, i) => fail.includes(i) ? 'f' : i > n - 4 ? 's' : 'p').join('');
export const TESTS = { passed: 140, failed: 0, skipped: 3, ms: 6410, cases: CASES(143) };
export const TESTS_FAIL = { passed: 139, failed: 1, skipped: 3, ms: 6880, cases: CASES(143, [97]), failures: [{ name: 'keeps ?next after a passkey sign-in on iOS', at: 'deeplink.test.ts:41', message: "expected '/billing', received '/sign-in?next=%2Fbilling'" }] };
const M = 1000;
export const TIMELINE = { ms: 192 * M, lanes: [
{ agent: { id: 'research-01', type: 'research' }, spans: [{ t0: 2 * M, t1: 38 * M, label: 'WebAuthn spec' }] },
{ agent: { id: 'security-01', type: 'security' }, spans: [{ t0: 4 * M, t1: 61 * M, label: 'Threat model' }] },
{ agent: { id: 'build-01', type: 'build' }, spans: [{ t0: 40 * M, t1: 104 * M, label: 'passkey.ts' }, { t0: 150 * M, t1: 166 * M, label: 'Return 401' }] },
{ agent: { id: 'design-01', type: 'design' }, spans: [{ t0: 42 * M, t1: 121 * M, label: 'Sign-in screen' }, { t0: 121 * M, t1: 139 * M, label: 'Waited on you', state: 'waiting' }] },
{ agent: { id: 'tests-02', type: 'tests' }, spans: [{ t0: 64 * M, t1: 92 * M, label: 'Deep link' }, { t0: 92 * M, t1: 101 * M, label: 'Failed', state: 'failed' }, { t0: 101 * M, t1: 133 * M, label: 'Retried, passed' }] },
{ agent: { id: 'review-01', type: 'review' }, spans: [{ t0: 134 * M, t1: 176 * M, label: 'Review' }] },
] };
export const CONFLICT = {
question: 'Where does the password field go?',
a: { agent: { id: 'design-01', type: 'design' }, title: 'Behind a link', lang: 'tsx', code: '<PasskeyButton />\n<TextButton>Use your password instead</TextButton>' },
b: { agent: { id: 'build-02', type: 'build' }, title: 'Beside the passkey', lang: 'tsx', code: '<PasskeyButton />\n<PasswordForm compact />' },
options: ['Behind a link', 'Beside the passkey'],
};
export const CHOICE = { question: 'Who gets passkeys first?', options: [
{ id: 'all', label: 'Everyone', detail: 'Ship today' },
{ id: 'web', label: 'Web only', detail: 'Mobile next week' },
{ id: 'flag', label: 'Staff first', detail: 'Behind a flag for a week' },
] };
export const COST = { spent: 3.84, cap: 20, tokens: 1.9e6, agents: 14, items: [{ type: 'build', cost: 1.42 }, { type: 'tests', cost: .86 }, { type: 'design', cost: .58 }, { type: 'review', cost: .41 }, { type: 'research', cost: .34 }, { type: 'security', cost: .23 }] };
export const TOOL = { name: 'read_file', title: 'Read src/auth/session.ts', args: { path: 'src/auth/session.ts', lines: [1, 48] }, result: { path: 'src/auth/session.ts', lines: 48, exports: ['createSession', 'endSession', 'rotate'] }, ms: 420 };
export const COST_NEAR = { ...COST, spent: 17.2, cap: 20 };
export const DIAGRAM = { h: 220, nodes: [
{ id: 'you', label: 'You', x: 11, y: 24, kind: 'you' }, { id: 'page', label: 'Sign-in page', x: 37, y: 24 }, { id: 'opt', label: 'passkey/options', x: 63, y: 24, kind: 'new' }, { id: 'dev', label: 'This device', x: 89, y: 50 },
{ id: 'ver', label: 'passkey/verify', x: 63, y: 76, kind: 'new' }, { id: 'ses', label: 'Session', x: 37, y: 76 }, { id: 'home', label: '?next or /home', x: 11, y: 76 },
], edges: [
{ from: 'you', to: 'page' }, { from: 'page', to: 'opt', hot: 1, label: 'email' }, { from: 'opt', to: 'dev', hot: 1, label: 'challenge' },
{ from: 'dev', to: 'ver', hot: 1, label: 'signed' }, { from: 'ver', to: 'ses', hot: 1 }, { from: 'ses', to: 'home' },
] };
export const THINK = 'Passkeys touch four places: the auth routes, the sign-in screen, where credentials live, and the iOS deep link that carries ?next. The risky one is the deep link, because a passkey prompt can drop the query string on Safari. Password stays as the fallback, so nothing breaks for anyone without a passkey. I will split it six ways and keep tests on the deep link from the start.';
export const INTRO = 'Six pieces of work for 14 agents. **Password stays** as the fallback, and the iOS deep link gets its own tests from the first minute. Change anything below, then approve.';
export const OUTRO = 'Passkeys are in. #212 is open with 5 files, 143 tests and a review. Password still works for anyone without a passkey, and the deep link keeps `?next` on iOS.';
/* ---------- one block in one state ---------- */
const BASE = {
text: () => ({ text: INTRO }),
thinking: () => ({ text: THINK, ms: 12000 }),
plan: () => ({ title: 'Add passkeys to sign-in', steps: PLAN }),
swarm: () => ({ title: 'Passkeys', lanes: lanes('done') }),
diff: () => ({ files: DIFF, note: NOTE }),
files: () => ({ title: 'What changed', files: DIFF }),
terminal: () => ({ ...TERM, exit: 0, ms: 6410 }),
preview: () => ({ url: 'localhost:3000/sign-in', before: h(SignIn, { after: false }), after: h(SignIn, { after: true }), split: .5 }),
tests: () => TESTS,
timeline: () => TIMELINE,
conflict: () => CONFLICT,
choice: () => CHOICE,
cost: () => COST,
diagram: () => ({ title: 'How sign-in works now', ...DIAGRAM }),
tool: () => TOOL,
};
const SWARM_BY = { delegating: 'queued', working: 'working', reviewing: 'done', done: 'done', thinking: 'queued', planning: 'queued', waiting: 'working' };
function block_(type: string, state = 'done', id = 'fx-' + type) {
const b: A = { id, type, ...(BASE as A)[type](), state };
const now = Date.now();
if (state !== 'done' && state !== 'waiting') b.since = now - 4000;
if (type === 'thinking' && state !== 'done') b.text = THINK.slice(0, 180);
if (type === 'text' && state !== 'done') b.streaming = state !== 'waiting';
if (type === 'swarm') {
b.lanes = lanes((SWARM_BY as A)[state]);
if (state === 'working') b.lanes.forEach((l: A, i: number) => l.agents.forEach((a: A, j: number) => { a.state = (i + j) % 3 === 0 ? 'done' : 'working'; a.ms = (i * 7 + j * 11) * 1000; }));
if (state === 'waiting') { b.lanes[4].agents[1].state = 'needs'; b.ask = ASK; b.lanes[0].agents.forEach((a: A) => { a.state = 'done'; }); }
if (state === 'reviewing') b.lanes[5].agents.forEach((a: A) => { a.state = 'working'; });
}
if (type === 'tests') {
if (state === 'waiting') Object.assign(b, TESTS_FAIL);
else if (state !== 'done' && state !== 'reviewing') { const n = state === 'working' ? 96 : 40; b.cases = TESTS.cases.slice(0, n) + 'r'.repeat(143 - n); b.passed = n; b.skipped = 0; b.ms = null; }
}
if (type === 'terminal' && state !== 'done' && state !== 'reviewing') { b.exit = null; b.ms = null; b.lines = TERM.lines.slice(0, 5); }
if (type === 'cost' && state === 'waiting') Object.assign(b, COST_NEAR);
if (type === 'timeline' && state !== 'done') b.now = 140000;
if (type === 'conflict' && state === 'done') b.picked = 'a';
if (type === 'choice' && state === 'done') b.picked = 'web';
if ((type === 'diff' || type === 'files') && state === 'delegating') b.to = DIFF.slice(0, 3).map(f => f.by);
if (type === 'plan' && state === 'delegating') b.to = [{ id: 'build-01', type: 'build' }, { id: 'tests-01', type: 'tests' }, { id: 'design-01', type: 'design' }];
if (type === 'preview' && state === 'delegating') b.to = { id: 'design-01', type: 'design' };
if (type === 'diff' && state === 'working') b.by = { id: 'build-01', type: 'build' };
if (type === 'tool' && state !== 'done') { b.result = undefined; b.ms = null; if (state !== 'waiting') b.since = now - 1400; }
return b;
}
export const BLOCK_TYPES = ['text', 'thinking', 'plan', 'swarm', 'diff', 'files', 'terminal', 'preview', 'tests', 'timeline', 'conflict', 'choice', 'cost', 'diagram', 'tool'];
export const BLOCK_STATES = ['thinking', 'planning', 'delegating', 'working', 'waiting', 'reviewing', 'done'];
const ASKS = { text: 'Add passkeys to sign-in.', thinking: 'Add passkeys to sign-in.', plan: 'Plan passkeys for sign-in first.', swarm: 'Go.', diff: 'Show me the code.', files: 'What changed?', terminal: 'Run the auth tests.', preview: 'What does it look like?', tests: 'Did the tests pass?', timeline: 'Who did what?', conflict: 'Merge it.', choice: 'Ship it.', cost: 'What did that cost?', diagram: 'How does sign-in work now?', tool: 'Read the session code.' };
function fixture_(type: string, state = 'done') {
const live = state !== 'done';
return [
{ id: 'fx-you', role: 'you', text: (ASKS as A)[type] || 'Go.' },
{ id: 'fx-cap', role: 'captain', state: live ? state : 'done', since: Date.now() - 4000, ms: live ? null : 12000, blocks: [block_(type, state)] },
];
}
/* every block, done, in one turn */
function gallery_() {
return [
{ id: 'g-you', role: 'you', text: 'Add passkeys to sign-in. Keep passwords as a fallback, and don’t break the mobile app.' },
{ id: 'g-cap', role: 'captain', state: 'done', ms: 192000, agents: 14, cost: 3.84, blocks: ['thinking', 'text', ...BLOCK_TYPES.filter(t => t !== 'text' && t !== 'thinking')].map(t => block_(t, t === 'choice' ? 'waiting' : 'done', 'g-' + t)) },
];
}
/* ---------- a scripted Captain: the whole passkeys run, about 40 seconds, deterministic ---------- */
function createSim_({ auto = true, speed = 1, seed = 7, from = 'start', hold = 2600 }: { auto?: boolean; speed?: number; seed?: number; from?: 'start' | 'plan'; hold?: number } = {}) {
let msgs: A[] = [], stopped = false, queued = false, crew = 14;
const subs = new Set<(m: A[]) => void>(), timers = new Set<ReturnType<typeof setTimeout>>(), gates = new Map<string, (v: unknown) => void>();
const r = (() => { let s = seed; return () => (s = (s * 16807) % 2147483647) / 2147483647; })();
const emit = () => { if (queued) return; queued = true; Promise.resolve().then(() => { queued = false; subs.forEach(f => f(msgs)); }); };
const sleep = (ms: number) => new Promise<void>(res => { const t = setTimeout(() => { timers.delete(t); res(); }, ms / speed); timers.add(t); });
const add = (m: A) => { msgs = [...msgs, m]; emit(); };
const turn = (id: string, patch: A) => { msgs = msgs.map((m: A) => m.id === id ? { ...m, ...(typeof patch === 'function' ? patch(m) : patch) } : m); emit(); };
const put = (tid: string, b: A) => turn(tid, (m: A) => ({ blocks: [...m.blocks, b] }));
const blk = (tid: string, bid: string, patch: A) => turn(tid, (m: A) => ({ blocks: m.blocks.map((b: A) => b.id === bid ? { ...b, ...(typeof patch === 'function' ? patch(b) : patch) } : b) }));
// a gate answers itself after ms when auto is on; touching what it waits on (editing the plan) restarts that wait
const waits = new Map<string, () => void>();
const gate = (name: string, ms: number) => new Promise<unknown>(res => {
gates.set(name, res);
if (!auto) return;
let t: ReturnType<typeof setTimeout>;
const arm = () => { clearTimeout(t); timers.delete(t); t = setTimeout(() => { timers.delete(t); waits.delete(name); if (gates.has(name)) { gates.delete(name); res('auto'); } }, ms / speed); timers.add(t); };
waits.set(name, arm);
arm();
});
const stream = async (tid: string, bid: string, text: string, every = 34) => { const w = text.split(/(?<=\s)/); let s = ''; for (let i = 0; i < w.length; i++) { s += w[i]; if (i % 2 === 1 || i === w.length - 1) { blk(tid, bid, { text: s }); await sleep(every * 2); } } };
async function run() {
const T = 'cap-1', t0 = Date.now();
if (from === 'plan') {
// open on the payoff: the thinking already folded, the plan on the table with its crews
msgs = [
{ id: 'you-1', role: 'you', text: 'Add passkeys to sign-in. Keep passwords as a fallback, and don’t break the mobile app.' },
{ id: T, role: 'captain', state: 'waiting', blocks: [
{ id: 'think', type: 'thinking', state: 'done', text: THINK, ms: 12000 },
{ id: 'intro', type: 'text', text: INTRO },
{ id: 'plan', type: 'plan', state: 'waiting', title: 'Add passkeys to sign-in', steps: PLAN },
] },
];
emit();
return afterPlan(T, hold);
}
add({ id: 'you-1', role: 'you', text: 'Add passkeys to sign-in. Keep passwords as a fallback, and don’t break the mobile app.' });
await sleep(700);
add({ id: T, role: 'captain', state: 'thinking', since: Date.now(), blocks: [{ id: 'think', type: 'thinking', state: 'thinking', text: '', since: Date.now() }] });
await stream(T, 'think', THINK, 26);
blk(T, 'think', { state: 'done', ms: Date.now() - t0 - 700 });
turn(T, { state: 'planning', since: Date.now() });
put(T, { id: 'intro', type: 'text', text: '', streaming: true });
await stream(T, 'intro', INTRO, 30);
blk(T, 'intro', { streaming: false });
put(T, { id: 'plan', type: 'plan', state: 'planning', title: 'Add passkeys to sign-in', steps: PLAN, since: Date.now() });
await sleep(1400);
blk(T, 'plan', { state: 'waiting' }); turn(T, { state: 'waiting' });
return afterPlan(T, hold);
}
async function afterPlan(T: string, hold: number) {
// the plan you approve is the swarm that runs: edited counts, order and steps all carry over
const ok = await gate('plan', hold);
const steps: A[] = Array.isArray(ok) && ok.length ? ok : (msgs.find((m: A) => m.id === T)?.blocks.find((b: A) => b.id === 'plan')?.steps ?? PLAN);
crew = steps.reduce((n: number, s: A) => n + (s.agents || 1), 0);
blk(T, 'plan', { state: 'done', steps });
turn(T, { state: 'delegating', since: Date.now() });
put(T, { id: 'swarm', type: 'swarm', state: 'delegating', title: 'Passkeys', lanes: lanes('queued', steps), since: Date.now() });
await sleep(1300);
blk(T, 'swarm', { state: 'working' }); turn(T, { state: 'working', since: Date.now() });
const tick = async (n: number, rule: (a: A, l: A) => A) => {
for (let k = 0; k < n; k++) {
blk(T, 'swarm', (b: A) => ({ lanes: b.lanes.map((l: A) => ({ ...l, agents: l.agents.map((a: A) => rule(a, l) || a) })) }));
await sleep(240);
}
};
const advance = (p: number, pd: number, hold?: (a: A) => boolean) => (a: A) => {
if (hold && hold(a)) return null;
if (a.state === 'queued' && r() < p) return { ...a, state: 'working' };
if (a.state === 'working') return r() < pd ? { ...a, state: 'done' } : { ...a, ms: a.ms + 240 };
if (a.state === 'failed' && r() < .4) return { ...a, state: 'working', step: 'Retrying' };
return null;
};
await tick(6, advance(.45, .03, (a: A) => a.id === 'review-01' || a.id === 'review-02'));
blk(T, 'swarm', (b: A) => ({ lanes: b.lanes.map((l: A) => ({ ...l, agents: l.agents.map((a: A) => a.id === 'tests-02' || (a.type === 'tests' && a.id === 'tests-01' && !l.agents.some((x: A) => x.id === 'tests-02')) ? { ...a, state: 'needs' } : a.id === 'tests-03' ? { ...a, state: 'failed' } : a) })), ask: ASK, state: 'waiting' }));
turn(T, { state: 'waiting' });
await gate('ask', 2400);
blk(T, 'swarm', (b: A) => ({ state: 'working', ask: null, lanes: b.lanes.map((l: A) => ({ ...l, agents: l.agents.map((a: A) => a.state === 'needs' ? { ...a, state: 'working', step: 'Fixing ?next on iOS' } : a) })) }));
turn(T, { state: 'working' });
put(T, { id: 'diff', type: 'diff', state: 'working', files: DIFF, note: NOTE, by: { id: 'build-01', type: 'build' }, since: Date.now() });
await tick(8, advance(.6, .14, (a: A) => a.type === 'review'));
blk(T, 'diff', { state: 'reviewing', by: { id: 'review-01', type: 'review' } });
turn(T, { state: 'reviewing', since: Date.now() });
await tick(8, advance(1, .22));
blk(T, 'swarm', (b: A) => ({ state: 'done', lanes: b.lanes.map((l: A) => ({ ...l, agents: l.agents.map((a: A) => ({ ...a, state: 'done' })) })) }));
blk(T, 'diff', { state: 'done', by: null });
put(T, { id: 'term', type: 'terminal', state: 'working', cmd: TERM.cmd, lines: [], since: Date.now() });
put(T, { id: 'tests', type: 'tests', state: 'working', cases: 'r'.repeat(143), passed: 0, skipped: 0 });
for (let i = 0; i < TERM.lines.length; i++) {
blk(T, 'term', { lines: TERM.lines.slice(0, i + 1) });
const n = Math.min(143, Math.round((i + 1) / TERM.lines.length * 143));
blk(T, 'tests', { cases: TESTS.cases.slice(0, n) + 'r'.repeat(143 - n), passed: (TESTS.cases.slice(0, n).match(/p/g) || []).length });
await sleep(260);
}
blk(T, 'term', { state: 'done', exit: 0, ms: 6410 });
blk(T, 'tests', { ...TESTS, state: 'done' });
put(T, { id: 'prev', type: 'preview', state: 'reviewing', url: 'localhost:3000/sign-in', before: h(SignIn, { after: false }), after: h(SignIn, { after: true }), split: 1, since: Date.now() });
turn(T, { state: 'reviewing' });
for (let i = 0; i <= 24; i++) { blk(T, 'prev', { split: 1 - .5 * (1 - Math.pow(1 - i / 24, 3)) }); await sleep(50); }
blk(T, 'prev', { state: 'done' });
put(T, { id: 'conf', type: 'conflict', state: 'waiting', ...CONFLICT });
turn(T, { state: 'waiting' });
const pick = await gate('conf', 2600);
blk(T, 'conf', { state: 'done', picked: pick === 'b' ? 'b' : 'a' });
turn(T, { state: 'done' });
put(T, { id: 'tl', type: 'timeline', state: 'done', ...TIMELINE });
put(T, { id: 'cost', type: 'cost', state: 'done', ...COST });
put(T, { id: 'outro', type: 'text', text: '', streaming: true });
await stream(T, 'outro', OUTRO, 30);
blk(T, 'outro', { streaming: false });
turn(T, { state: 'done', ms: 192000, agents: crew, cost: 3.84 });
}
return {
get messages() { return msgs; },
subscribe(f: (m: A[]) => void) { subs.add(f); f(msgs); return () => subs.delete(f); },
start() { stopped = false; run().catch(e => { if (!stopped) console.error(e); }); return this; },
stop() { stopped = true; timers.forEach(t => clearTimeout(t)); timers.clear(); gates.clear(); },
/* answer what the Captain is waiting on: 'plan', 'ask' or 'conf' */
answer(gateName: string, value?: unknown) { const g = gates.get(gateName); if (g) { gates.delete(gateName); g(value); } },
/* map an onAction event from the transcript to the gate it answers */
act(e: A) {
if (e.type === 'plan' && (e.action === 'edit' || e.action === 'reorder') && Array.isArray(e.value)) {
msgs = msgs.map((m: A) => m.role === 'captain' ? { ...m, blocks: m.blocks.map((b: A) => b.id === e.block ? { ...b, steps: e.value } : b) } : m); emit();
waits.get('plan')?.();
return;
}
const g = ({ plan: 'plan', swarm: 'ask', conflict: 'conf' } as A)[e.type]; if (g && /approve|answer|pick/.test(e.action)) this.answer(g, e.value);
},
};
}
/* ---------- a long thread for scrolling: n messages, every block kind, deterministic ---------- */
function bigThread_(n = 10000) {
const out = [], r = (() => { let s = 42; return () => (s = (s * 16807) % 2147483647) / 2147483647; })();
const kinds = BLOCK_TYPES.filter(t => t !== 'thinking');
const asks = ['Add passkeys to sign-in.', 'Why is the build slow?', 'Make the settings page use tokens.', 'Fix the flaky checkout test.', 'Ship the billing export.', 'Who touched the session store?'];
for (let i = 0; i < n; i++) {
const k = i % 5;
if (k === 0 || k === 2) out.push({ id: 'm' + i, role: 'you', text: asks[Math.floor(r() * asks.length)] });
else if (k === 4 && r() < .4) out.push({ id: 'm' + i, role: 'event', text: `Worked for ${1 + Math.floor(r() * 9)}m ${Math.floor(r() * 60)}s` });
else {
const nb = 1 + Math.floor(r() * 3), blocks = [{ id: `m${i}-t`, type: 'thinking', state: 'done', text: THINK, ms: 2000 + Math.floor(r() * 20000) }];
for (let j = 0; j < nb; j++) { const t = kinds[Math.floor(r() * kinds.length)]!; blocks.push(block_(t, 'done', `m${i}-${j}`)); }
out.push({ id: 'm' + i, role: 'captain', state: 'done', ms: 30000 + Math.floor(r() * 300000), blocks });
}
}
return out;
}
/* ---------- typed exports ---------- */
export interface Sim {
readonly messages: Message[];
subscribe(fn: (messages: Message[]) => void): () => void;
start(): Sim;
stop(): void;
/** Answer what the Captain waits on: 'plan', 'ask' or 'conf'. */
answer(gate: 'plan' | 'ask' | 'conf', value?: unknown): void;
/** Pass the transcript's onAction events straight in. Plan edits change the swarm it will run. */
act(e: ActionEvent): void;
}
/** The demo app's sign-in screen, before and after. */
export const SignIn: ComponentType<{ after?: boolean }> = SignInImpl;
/** One block of this kind in this state, with demo data. */
export const block = block_ as (type: BlockType, state?: State, id?: string) => Block;
/** A two-message thread: you ask, the Captain answers with one block in this state. */
export const fixture = fixture_ as (type: BlockType, state?: State) => Message[];
/** Every kind of block, finished, in one Captain turn. */
export const gallery = gallery_ as () => Message[];
/** A long deterministic thread for scrolling tests. */
export const bigThread = bigThread_ as (n?: number) => Message[];
/** A scripted Captain: the whole passkeys run in about 40 seconds. With auto, it answers its own questions after a pause (`hold` ms for the plan; an edit restarts it). `from: 'plan'` opens on the plan. */
export const createSim = createSim_ as (opts?: { auto?: boolean; speed?: number; seed?: number; from?: 'start' | 'plan'; hold?: number }) => Sim;Usage
import { CaptainTranscript } from "@/components/ui/transcript"
import { fromUIMessages, toolOutputFor } from "@/components/ui/transcript-ai-sdk"
const { messages, status, addToolOutput } = useChat()
<div style={{ height: 600 }}>
<CaptainTranscript
messages={fromUIMessages(messages, { status })}
onAction={(e) => { const out = toolOutputFor(e, messages); if (out) addToolOutput(out) }}
/>
</div>Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| messages | Message[] | The thread, controlled. Give a message a new object only when it changes. | |
| defaultMessages | Message[] | Uncontrolled start; add more with the ref's append and update. | |
| onAction | (e: ActionEvent) => void | Approve, edit, answer, pick, accept, run, ship. Plan edits arrive as they happen. | |
| renderers | { tool?, diff?, stream? } | Swap the pieces inside blocks, e.g. Pro ToolCall, DiffReview and StreamingText. Defaults are plain and free. | |
| blocks | Record<string, ComponentType<BlockProps>> | Your own block kinds (x-*), or replace a built-in one. | |
| name | string | "Captain" | The agent's name on its turns. |
| width | number | 760 | Reading column in px. |
| theme | "light" | "dark" | "system" | Leave it out to follow the page. |
Keyboard
- PageDown / PageUp
- Next and previous message
- 1 to 9
- Answer a waiting block
- Enter
- Its main action
- Arrows on a crew
- Fewer or more agents
- Arrows on a grip
- Move a step
Accessibility
- role=feed of articles, virtualised, with a polite log that reads state changes and finished replies, never word by word.
- Every crew is a slider and every grip moves its step from the keyboard.
- The before and after split is a slider with its value in words.