Captain sidebar
A sidebar for one Captain that runs swarms. The questions that need you sit on top as a deck; answer one in place and your answer flies into its mission.
npx shadcn@latest add https://uimaxxer.com/r/captain-sidebar.jsonCaptain
Waiting on you"use client";
// uimaxxer · Captain sidebar, MIT. Idea: one Captain that runs swarms, with the questions that need you dealt as a deck on top. Delight: answer the top card in place and your answer flies into its mission, where the waiting cell turns back to work, in 260 ms.
import { AnimatePresence, motion } from "motion/react";
import { createContext, useContext, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type MutableRefObject, type ReactNode } from "react";
import { EASE, cx, useIsoLayoutEffect } from "@/registry/captain/ui/captain";
import { Icon, type IconName } from "@/registry/captain/ui/icons";
import {
AGENT_ORDER, AGENT_STATES, AUTONOMY, AUTONOMY_LONG, HANDOFF_MS, STATES, ago, count, dur, money, rovingKeyDown, search, summarize, wrap,
useAnnouncer, useCaptainSidebar, useHydrated, useMedia, useNow,
type Agent, type Autonomy, type CaptainSidebarProps, type CaptainState, type HistoryItem, type Mission, type QueueItem, type SidebarState,
} from "./captain-sidebar-core";
import { Helm, Mark, Ring, Swarm, TYPES } from "./captain-sidebar-marks";
export * from "./captain-sidebar-core";
export { Helm, Mark, Ring, Swarm, TYPES, pose, typeOf } from "./captain-sidebar-marks";
const T = { duration: 0.22, ease: EASE } as const;
const FOCUS = "outline-none focus-visible:bg-hover";
const ROW = cx("pressable relative flex w-full min-w-0 items-center gap-2.5 rounded-inner px-2 text-left hover:bg-hover", FOCUS);
const ICON_BTN = cx("pressable relative grid size-7 flex-none place-items-center rounded-inner text-ink-2 hover:bg-hover hover:text-ink before:absolute before:-inset-2 before:content-['']", FOCUS);
/* ---------- small parts ---------- */
/** A number that rolls in from below when it changes. */
function Num({ v, reduced }: { v: number | string; reduced?: boolean }) {
const hydrated = useHydrated();
return (
<motion.span key={String(v)} className="tnum inline-block" initial={hydrated ? { opacity: 0, y: reduced ? 0 : "0.45em" } : false} animate={{ opacity: 1, y: 0 }} transition={T}>
{v}
</motion.span>
);
}
/** Text that wipes in once when it changes (the Captain's line, a mission's phase). */
function Wipe({ k, children, className }: { k: string; children: ReactNode; className?: string }) {
const hydrated = useHydrated();
return (
<motion.span key={k} className={className} initial={hydrated ? { clipPath: "inset(0 100% 0 0)" } : false} animate={{ clipPath: "inset(0 0% 0 0)" }} transition={{ duration: 0.28, ease: "linear" }}>
{children}
</motion.span>
);
}
/** The original interface icons by their old names, drawn from the Captain icon set. */
const IC: Record<string, IconName> = { search: "search", panel: "sidebar", updown: "updown", chev: "chevron", more: "more", plus: "plus", check: "check", x: "x", ask: "ask", stamp: "stamp", clash: "clash", pause: "pause", play: "play", stop: "stop", warn: "warn", clock: "clock" };
export type IcName = keyof typeof IC;
export const ICONS = Object.keys(IC) as IcName[];
/** An interface icon by its original name: 24 px grid, 1.5 px stroke. */
export function Ic({ i, s = 16 }: { i: IcName; s?: number }) {
return <Icon name={IC[i] ?? "ask"} size={s} />;
}
const OUT: Record<HistoryItem["outcome"], IconName> = { merged: "check", shipped: "check", stopped: "stop", failed: "warn" };
const OUT_TONE: Record<HistoryItem["outcome"], string> = { merged: "text-success", shipped: "text-success", stopped: "text-ink-3", failed: "text-danger" };
/* ---------- context ---------- */
type MenuItem = { label: string; icon?: ReactNode; sub?: ReactNode; on?: boolean; multi?: boolean; keep?: boolean; run(): void } | null;
type MenuSpec = { label: string; x: number; y?: number; b?: number; items: MenuItem[] };
type Api = {
p: CaptainSidebarProps;
st: SidebarState;
root: MutableRefObject<HTMLDivElement | null>;
rh: number;
dark: boolean;
from: MutableRefObject<DOMRect | null>;
setMenu(m: MenuSpec | null): void;
under: boolean;
setUnder(v: boolean): void;
openPal(): void;
missionMenu(m: Mission, x: number, y: number): void;
};
export interface SidebarContext { p: CaptainSidebarProps; st: SidebarState; mode: "panel" | "rail" | "sheet"; dark: boolean; accent: string; api: Api }
const Ctx = createContext<SidebarContext | null>(null);
/** The sidebar's context: its props, the headless state, the layout mode and the theme. For parts inside Sidebar.Root. */
export function useSidebar(): SidebarContext {
const c = useContext(Ctx);
if (!c) throw new Error("captain-sidebar: parts must be inside <Sidebar.Root>.");
return c;
}
const actionsOf = (p: CaptainSidebarProps) => {
const l = p.missionActions ?? (p.onMissionAction ? ["pause", "add", "stop"] : []);
return { pause: l.includes("pause"), add: l.includes("add"), stop: l.includes("stop"), any: l.length > 0 };
};
/* ---------- header and Captain ---------- */
/** The top bar: the workspace switcher, search and collapse. */
export function SidebarHeader() {
const { p, api, mode } = useSidebar();
if (mode === "sheet") return null;
const ws = p.workspace;
return (
<div className="flex h-11 flex-none items-center gap-1 px-2.5">
<button
type="button"
data-k=""
className={cx(ROW, "h-8 w-auto flex-1 gap-2 px-1.5")}
aria-haspopup={p.workspaces ? "menu" : undefined}
onClick={(e) => {
if (!p.workspaces || !api.root.current) return;
const r = e.currentTarget.getBoundingClientRect(), R = api.root.current.getBoundingClientRect();
api.setMenu({ label: "Workspaces", x: r.left - R.left, y: r.bottom - R.top + 4, items: p.workspaces.map((w) => ({ label: w.name, icon: <span className="size-3.5 rounded-[4px]" style={{ background: w.color || "var(--captain-ink)" }} />, on: w.name === ws?.name, run: () => p.onWorkspace?.(w) })) });
}}
>
<span className="grid size-[22px] flex-none place-items-center rounded-[6px] text-[12px] font-semibold text-white shadow-[inset_0_1px_0_rgba(255,255,255,.3),0_1px_2px_rgba(17,18,20,.2)]" style={{ background: ws?.color || "var(--captain-ink)" }} aria-hidden="true">
{(ws?.name || "W").slice(0, 1).toUpperCase()}
</span>
{/* Named by its own text, so the visible name and the spoken name always match. */}
<span className="min-w-0 truncate text-[13.5px] font-medium text-ink"><span className="sr-only">Workspace: </span>{ws?.name || "Workspace"}</span>
{p.workspaces ? <span className="text-ink-3"><Icon name="updown" size={14} /></span> : null}
</button>
<button type="button" className={ICON_BTN} aria-label="Search" aria-keyshortcuts="Meta+K" title="Search ⌘K" onClick={api.openPal}>
<Icon name="search" />
</button>
<button type="button" className={ICON_BTN} aria-label="Collapse the sidebar" aria-keyshortcuts="Meta+\" title="Collapse ⌘\" onClick={() => api.st.setCollapsed(true)}>
<Icon name="sidebar" />
</button>
</div>
);
}
/** The Captain at the top: its Helm, its live state and the one line of what it is doing. */
export function SidebarCaptain() {
const { p, mode } = useSidebar();
if (mode === "sheet") return null;
const c = p.captain ?? { state: "idle" as const };
const s = c.state || "idle";
const sel = p.selected === "captain";
const line = s === "asking" ? undefined : c.line;
return (
<div className="flex-none px-2.5 pb-1">
<button
type="button"
data-k=""
data-cap=""
aria-current={sel || undefined}
className={cx(ROW, line ? "items-start" : "items-center", "gap-2.5 py-1.5", sel && "bg-hover")}
onClick={() => p.onOpen?.("captain", "captain")}
>
<span className="well grid size-8 flex-none place-items-center rounded-[8px]">
<Helm s={s} size={22} />
</span>
<span className={cx("flex min-w-0 flex-1 flex-col gap-0.5", line && "pt-px")}>
<span className="flex items-baseline gap-2">
<span className="text-[13.5px] leading-[18px] font-medium text-ink">{c.name || "Captain"}<span className="sr-only">, </span></span>
<Wipe k={s} className={cx("min-w-0 flex-1 truncate text-[12.5px]", s === "asking" ? "text-accent-ink" : "text-ink-2")}>{STATES[s] ?? s}</Wipe>
</span>
{line ? (
<span className="block truncate text-[12.5px] leading-[17px] text-ink-3" aria-hidden="true">
<Wipe k={s + line.replace(/[\d$.,]+/g, "#")}>{line}</Wipe>
</span>
) : null}
</span>
</button>
</div>
);
}
/* ---------- the deck: what needs you ---------- */
function answersFor(q: QueueItem): [label: string, answer: string, primary: boolean][] {
if (q.kind === "approval") return [["Approve", "approve", true], ["Deny", "deny", false]];
if (q.kind === "conflict") return [[`Keep ${q.from ? q.from.id : "first"}`, "a", true], [`Keep ${q.vs ? q.vs.id : "second"}`, "b", false]];
return (q.options ?? ["Yes", "No"]).map((o, i) => [o, o, i === 0]);
}
function QueueCard({ q, api }: { q: QueueItem; api: Api }) {
const { p, st } = api;
const now = useNow();
const mission = (p.missions ?? []).find((m) => m.id === q.mission);
const acts = answersFor(q);
const titleId = useId();
return (
<div role="group" aria-labelledby={titleId} className="lifted relative rounded-[10px] p-2.5">
<div className="flex items-start gap-2.5">
<span className="well relative grid size-7 flex-none place-items-center rounded-[7px]">
{q.from ? <Mark type={q.from.type} s={16} /> : <Helm s="asking" size={18} />}
{q.vs ? <span className="raised absolute -right-1.5 -bottom-1.5 grid size-[18px] place-items-center rounded-[5px]"><Mark type={q.vs.type} s={12} /></span> : null}
</span>
<span className="min-w-0 flex-1">
<span id={titleId} className="line-clamp-2 text-[13.5px] leading-[18px] font-medium text-ink">{q.title}</span>
<span className="mt-0.5 block truncate text-[12px] leading-4 text-ink-3">
{q.from ? q.from.id : "Captain"}
{q.vs ? ` and ${q.vs.id}` : ""}
{mission ? `, ${mission.title}` : ""}
</span>
</span>
{q.at && now ? <span className="tnum flex-none text-[11.5px] leading-[18px] text-ink-3">{ago(q.at, now)}</span> : null}
</div>
<div className="mt-2 flex flex-wrap items-center gap-1 pl-[38px]">
{acts.map(([label, a, primary]) => (
<button
key={a}
type="button"
data-k=""
className={cx(
"pressable relative h-7 rounded-[6px] px-2.5 text-[12.5px] font-medium outline-none before:absolute before:-inset-x-0.5 before:-inset-y-2 before:content-['']",
primary ? "bg-primary text-primary-ink shadow-[inset_0_1px_0_rgba(255,255,255,.16),0_1px_2px_rgba(17,18,20,.24)] focus-visible:bg-accent" : "text-ink-2 hover:bg-hover hover:text-ink focus-visible:bg-hover",
)}
onClick={(e) => {
api.from.current = e.currentTarget.getBoundingClientRect();
st.resolve(q, a, label);
}}
>
{label}
</button>
))}
</div>
</div>
);
}
/** What needs you: questions, approvals and conflicts as a deck, the top one answerable in place. */
export function SidebarQueue({ limit = 4 }: { limit?: number }) {
const { p, st, api } = useSidebar();
const queue = (p.queue ?? []).filter((q) => !st.leaving[q.id]);
const shown = st.queueAll ? queue : queue.slice(0, Math.max(1, limit));
const top = shown.find((q) => q.id === st.activeQueue) ?? shown[0];
const rest = shown.filter((q) => q !== top);
const behind = Math.min(2, rest.length);
const reduced = st.reduced;
const total = (p.queue ?? []).length;
const [clip, setClip] = useState(false);
return (
<AnimatePresence initial={false}>
{top ? (
<motion.section
key="queue"
aria-label="Needs you"
initial={{ height: 0, opacity: 0 }}
animate={{ height: "auto", opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={T}
onAnimationStart={() => setClip(true)}
onAnimationComplete={() => setClip(false)}
className={cx("flex-none", clip && "overflow-hidden")}
>
<div className="px-3 pt-1">
<h2 className="flex h-7 items-center gap-1.5 px-1 text-[12px] font-medium text-accent-ink">
Needs you <Num v={total} reduced={reduced} />
</h2>
<div className="relative mb-2" style={{ paddingBottom: behind * 7 }}>
{/* The cards behind: only their edges show, so you can see how many are waiting. A tap brings the next one up. */}
{Array.from({ length: behind }, (_, i) => behind - i).map((d) => (
<button
key={d}
type="button"
tabIndex={d === 1 ? 0 : -1}
aria-label={d === 1 && rest[0] ? `Next: ${rest[0].title}` : undefined}
aria-hidden={d === 1 ? undefined : true}
onClick={() => rest[0] && st.setActiveQueue(rest[0].id)}
className="lifted absolute inset-x-0 top-0 rounded-[10px] outline-none focus-visible:bg-hover"
style={{ bottom: behind * 7, transform: `translateY(${d * 7}px) scale(${1 - d * 0.04})`, transformOrigin: "50% 100%" }}
/>
))}
<AnimatePresence initial={false} mode="popLayout">
<motion.div
key={top.id}
className="relative"
initial={{ opacity: 0, y: reduced ? 0 : 6, scale: reduced ? 1 : 0.95, zIndex: 0 }}
animate={{ opacity: 1, y: 0, scale: 1, zIndex: 0, transition: { type: "spring", stiffness: 560, damping: 42, mass: 0.8, opacity: { duration: 0.16, delay: 0.09 } } }}
exit={{ opacity: 0, scale: reduced ? 1 : 0.97, zIndex: 2, transition: { duration: 0.1, ease: EASE } }}
style={{ transformOrigin: "50% 100%" }}
>
<QueueCard q={top} api={api} />
</motion.div>
</AnimatePresence>
</div>
</div>
</motion.section>
) : null}
</AnimatePresence>
);
}
/* ---------- missions ---------- */
function AgentRow({ a, y, api }: { a: Agent; y: number; api: Api }) {
const ref = useRef<HTMLButtonElement>(null);
const was = useRef(a.state);
useEffect(() => {
const el = ref.current;
if (el && was.current !== a.state && !api.st.reduced && (a.state === "done" || was.current === "needs")) {
const tone = a.state === "done" ? "var(--captain-success)" : "var(--captain-accent)";
el.animate([{ backgroundColor: `color-mix(in srgb, ${tone} 16%, transparent)` }, { backgroundColor: "transparent" }], { duration: 600, easing: "ease-out" });
}
was.current = a.state;
}, [a.state, api.st.reduced]);
const word = a.state === "working" || a.state === "needs" ? a.step || AGENT_STATES[a.state] : AGENT_STATES[a.state];
return (
<button
ref={ref}
type="button"
data-k="a"
tabIndex={-1}
className={cx("absolute inset-x-0 top-0 flex items-center gap-2 rounded-[6px] px-2 text-left text-[12.5px] hover:bg-hover", FOCUS, a.state === "done" && "opacity-60")}
style={{ height: api.rh, transform: `translateY(${y}px)`, transition: "transform .24s cubic-bezier(.23,1,.32,1)" }}
onClick={() => api.p.onSelect?.("agent", a.id)}
>
<Mark type={a.type} work={a.state === "working"} s={12} />
<span className="flex-none font-medium text-ink">{a.name || a.id}</span>
<span className={cx("min-w-0 flex-1 truncate", a.state === "needs" ? "text-accent-ink" : a.state === "failed" ? "text-danger" : "text-ink-3")}>{word}</span>
<span className="tnum flex-none text-ink-3">{a.ms != null ? dur(a.ms) : ""}</span>
</button>
);
}
function AgentList({ agents, api, label }: { agents: Agent[]; api: Api; label: string }) {
const [top, setTop] = useState(0);
const rh = api.rh, n = agents.length, win = n > 30;
const s = win ? Math.max(0, Math.floor(top / rh) - 4) : 0, e = win ? Math.min(n, s + 16) : n;
return (
<div role="group" aria-label={label} className="relative overflow-auto [scrollbar-width:none]" style={{ height: Math.min(n, 6) * rh }} onScroll={win ? (ev) => setTop(ev.currentTarget.scrollTop) : undefined}>
<div className="relative" style={{ height: n * rh }}>
{agents.slice(s, e).map((a, i) => <AgentRow key={a.id} a={a} y={(s + i) * rh} api={api} />)}
</div>
</div>
);
}
function MissionBody({ m, api }: { m: Mission; api: Api }) {
const sorted = useMemo(() => m.agents.slice().sort((a, b) => AGENT_ORDER[a.state] - AGENT_ORDER[b.state]), [m.agents]);
const can = actionsOf(api.p);
const act = (a: "pause" | "resume" | "stop") => api.p.onMissionAction?.(m.id, a);
const quiet = cx("pressable flex h-7 items-center gap-1.5 rounded-[6px] px-2 text-[12px] text-ink-2 hover:bg-hover hover:text-ink", FOCUS);
return (
<div className="pb-1.5 pl-[44px]">
{sorted.length ? <AgentList agents={sorted} api={api} label={`Agents on ${m.title}`} /> : <p className="px-2 py-1.5 text-[12.5px] text-ink-3">The Captain is still planning this one.</p>}
{can.pause || can.stop || m.cost != null ? (
<div className="mt-0.5 flex items-center gap-0.5">
{can.pause ? <button type="button" data-k="" className={quiet} onClick={() => act(m.paused ? "resume" : "pause")}><Icon name={m.paused ? "play" : "pause"} size={14} />{m.paused ? "Resume" : "Pause"}</button> : null}
{can.stop ? <button type="button" data-k="" className={quiet} onClick={() => act("stop")}><Icon name="stop" size={14} />Stop</button> : null}
{m.cost != null ? <span className="tnum ml-auto pr-2 text-[12px] text-ink-3">{money(m.cost)}</span> : null}
</div>
) : null}
</div>
);
}
function MissionRow({ m, open, sel, api, landing }: { m: Mission; open: boolean; sel: boolean; api: Api; landing: boolean }) {
const c = useMemo(() => count(m.agents), [m.agents]);
const sm = summarize(m);
const reduced = api.st.reduced;
const [shown, setShown] = useState(open);
useEffect(() => {
if (open) setShown(true);
else { const t = setTimeout(() => setShown(false), 260); return () => clearTimeout(t); }
}, [open]);
const meta =
sm.kind === "needs" ? <span className="text-accent-ink"><Num v={c.needs} reduced={reduced} /> need{c.needs > 1 ? "" : "s"} you</span>
: sm.kind === "failed" ? <><Num v={c.done} reduced={reduced} /> of {c.n} done, <span className="text-danger">{c.failed} retrying</span></>
: sm.kind === "progress" ? <><Num v={c.done} reduced={reduced} /> of {c.n} done</>
: sm.kind === "done" ? <span className="text-success">Done, {c.n} agents</span>
: <Wipe k={"state" in sm ? sm.state : sm.kind}>{sm.text}</Wipe>;
return (
<div data-mission={m.id} className="relative">
<button
type="button"
data-k=""
data-m={m.id}
aria-expanded={open}
aria-current={sel || undefined}
className={cx(ROW, "py-1.5", sel && "bg-hover")}
onClick={() => api.st.toggle(m.id)}
onContextMenu={(e) => { e.preventDefault(); api.missionMenu(m, e.clientX, e.clientY); }}
>
<span data-swarm="" className="well relative grid size-8 flex-none place-items-center overflow-hidden rounded-[8px]">
<Swarm agents={m.agents} c={c} dark={api.dark} size={24} />
{/* The handoff lands here: the tray lights for a moment as the answer arrives. */}
<AnimatePresence>
{landing ? (
<motion.span
key="land"
aria-hidden="true"
className="absolute inset-0 rounded-[8px] bg-accent-tint"
initial={{ opacity: 0 }}
animate={{ opacity: [0, 0, 1] }}
exit={{ opacity: 0, transition: { duration: 0.24, ease: EASE } }}
transition={{ duration: HANDOFF_MS / 1000, times: [0, 0.7, 1] }}
/>
) : null}
</AnimatePresence>
</span>
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-[13.5px] leading-[18px] font-medium text-ink">{m.title}</span>
<span className="truncate text-[12px] leading-4 text-ink-3">{meta}</span>
</span>
{c.needs ? (
<span className="tnum grid h-5 min-w-5 flex-none place-items-center rounded-[5px] bg-accent px-1 text-[11.5px] font-semibold text-white" aria-hidden="true">
<Num v={c.needs} reduced={reduced} />
</span>
) : m.paused ? <span className="flex-none text-ink-3"><Icon name="pause" size={14} /></span> : null}
</button>
<motion.div initial={false} animate={{ height: open ? "auto" : 0, opacity: open ? 1 : 0 }} transition={T} className="overflow-hidden" inert={!open}>
{shown ? <MissionBody m={m} api={api} /> : null}
</motion.div>
</div>
);
}
/** A titled section, for your own content in the sidebar's rhythm. */
export function SidebarSection({ title, count: n, children }: { title: ReactNode; count?: number; children?: ReactNode }) {
const id = useId();
const { st } = useSidebar();
return (
<section aria-labelledby={id} className="px-3 pt-2">
<h2 id={id} className="flex h-7 items-center gap-1.5 px-1 text-[12px] font-medium text-ink-3">
{title} {n ? <Num v={n} reduced={st.reduced} /> : null}
</h2>
{children}
</section>
);
}
/** The missions, each with its swarm; open one to see its agents. */
export function SidebarMissions() {
const { p, st, api } = useSidebar();
const missions = p.missions ?? [];
const landing = st.handoff?.mission;
return (
<SidebarSection title="Missions" count={missions.length}>
{missions.length ? (
<div className="flex flex-col gap-px">
{missions.map((m) => <MissionRow key={m.id} m={m} open={st.open.has(m.id)} sel={p.selected === m.id} api={api} landing={landing === m.id} />)}
</div>
) : <p className="px-1 py-2 text-[12.5px] text-ink-3">{p.emptyText || "No missions yet. Tell the Captain what you need."}</p>}
</SidebarSection>
);
}
function Hist({ x, api, sel, now }: { x: HistoryItem; api: Api; sel: boolean; now: number | null }) {
const sub = [x.detail || x.outcome[0]!.toUpperCase() + x.outcome.slice(1), x.agents ? x.agents + " agents" : "", x.cost != null ? money(x.cost) : ""].filter(Boolean).join(", ");
return (
<button type="button" data-k="" aria-current={sel || undefined} className={cx(ROW, "py-1.5", sel && "bg-hover")} onClick={() => api.p.onSelect?.("history", x.id)}>
<span className={cx("grid size-9 flex-none place-items-center", OUT_TONE[x.outcome])}><Icon name={OUT[x.outcome]} size={16} /></span>
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-[13px] leading-[18px] text-ink">{x.title}</span>
<span className="tnum truncate text-[12px] leading-4 text-ink-3">{sub}</span>
</span>
{now ? <span className="tnum flex-none self-start pt-0.5 text-[11.5px] text-ink-3">{ago(x.at, now)}</span> : null}
</button>
);
}
/** Finished missions, folded by default. */
export function SidebarHistory({ limit = 6 }: { limit?: number }) {
const { p, st, api } = useSidebar();
const history = p.history ?? [];
const now = useNow();
const id = useId();
if (!history.length) return null;
return (
<section aria-labelledby={id} className="px-3 pt-3 pb-2">
<h2 id={id}>
<button type="button" data-k="" aria-expanded={st.historyOpen} onClick={() => st.setHistoryOpen((v) => !v)} className={cx("pressable flex h-7 items-center gap-1.5 rounded-[6px] px-1 text-[12px] font-medium text-ink-3 hover:text-ink", FOCUS)}>
History <Num v={history.length} reduced={st.reduced} />
<motion.span animate={{ rotate: st.historyOpen ? 0 : -90 }} transition={T} className="grid place-items-center"><Icon name="chevron" size={14} /></motion.span>
</button>
</h2>
<motion.div initial={false} animate={{ height: st.historyOpen ? "auto" : 0, opacity: st.historyOpen ? 1 : 0 }} transition={T} className="overflow-hidden" inert={!st.historyOpen}>
{history.slice(0, limit).map((x) => <Hist key={x.id} x={x} api={api} sel={p.selected === x.id} now={now} />)}
{history.length > limit ? (
<button type="button" data-k="" onClick={api.openPal} className={cx(ROW, "h-8 justify-between text-[12.5px] text-ink-2")}>
Search all {history.length}<kbd className="font-sans text-[11.5px] text-ink-3">⌘K</kbd>
</button>
) : null}
</motion.div>
</section>
);
}
/** The scrolling middle. Put Queue, Missions and History (or your own sections) inside. */
export function SidebarContent({ children }: { children?: ReactNode }) {
const { api } = useSidebar();
const ref = useRef<HTMLDivElement>(null);
const check = () => { const el = ref.current; if (el) api.setUnder(el.scrollHeight - el.scrollTop - el.clientHeight > 1); };
useEffect(() => {
const el = ref.current;
if (!el) return;
check();
const ro = new ResizeObserver(check);
ro.observe(el);
if (el.firstElementChild) for (const c of el.children) ro.observe(c);
return () => ro.disconnect();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div ref={ref} data-scroll="" onScroll={check} className="relative min-h-0 flex-1 overflow-y-auto overscroll-contain pb-2 [scrollbar-width:none]">
{children ?? (<><SidebarQueue /><SidebarMissions /><SidebarHistory /></>)}
</div>
);
}
/* ---------- footer ---------- */
/** The footer: what the swarms have spent against the cap, and how much the Captain may do without you. */
export function SidebarFooter() {
const { p, api } = useSidebar();
const b = p.budget ?? { spent: 0, cap: 0 };
const pct = b.cap ? b.spent / b.cap : 0;
const on = p.roster ?? Object.keys(TYPES);
const au: Autonomy = p.autonomy ?? "ask";
const per = useMemo(() => {
const o: Record<string, number> = {};
for (const m of p.missions ?? []) for (const a of m.agents) if (a.state !== "done") o[a.type] = (o[a.type] ?? 0) + 1;
return o;
}, [p.missions]);
const showBudget = !!p.budget, showAuto = p.autonomy !== undefined || !!p.onAutonomyChange;
if (!showBudget && !showAuto && !p.showRoster && !p.simulated) return null;
const pop = (el: HTMLElement, label: string, items: MenuItem[]) => {
const R = api.root.current?.getBoundingClientRect();
if (!R) return;
const r = el.getBoundingClientRect();
api.setMenu({ label, x: Math.max(8, Math.min(r.left - R.left, R.width - 228)), b: R.bottom - r.top + 6, items });
};
const warn = pct >= 1 ? 2 : pct >= 0.8 ? 1 : 0;
return (
<div className={cx("relative z-10 flex-none bg-band px-2.5 pt-1 pb-1.5 transition-shadow duration-200", api.under && "shadow-[0_-8px_14px_-6px_var(--captain-scrim)]")}>
{p.showRoster ? (
<div className="mb-1 flex flex-wrap gap-0.5 px-1">
{Object.keys(TYPES).map((t) => (
<button
key={t}
type="button"
data-k=""
aria-haspopup="menu"
aria-label={`${TYPES[t]![0]}: ${per[t] ?? 0} working`}
className={cx("pressable flex h-7 items-center gap-1 rounded-[6px] px-1.5 text-[11.5px] text-ink-3 hover:bg-hover", FOCUS, !on.includes(t) && "opacity-40")}
onClick={(e) => pop(e.currentTarget, "Roster", Object.keys(TYPES).map((k) => ({ label: TYPES[k]![0], icon: <Mark type={k} s={12} />, sub: per[k] ?? 0, on: on.includes(k), multi: true, keep: true, run: () => p.onRosterChange?.(on.includes(k) ? on.filter((x) => x !== k) : [...on, k]) })))}
>
<Mark type={t} work={(per[t] ?? 0) > 0} s={14} />
<span className="tnum" aria-hidden="true">{per[t] || ""}</span>
</button>
))}
</div>
) : null}
{showBudget || showAuto ? (
<div className="flex items-center gap-1">
{showBudget ? (
<button
type="button"
data-k=""
aria-haspopup="menu"
className={cx(ROW, "h-8 flex-1 gap-2.5 px-2")}
onClick={(e) => pop(e.currentTarget, "Budget", [10, 25, 50, 100, 250].map((v) => ({ label: `Stop at $${v}`, on: b.cap === v, run: () => p.onBudgetChange?.(v) })))}
>
<span className="flex flex-none items-baseline gap-1 text-[12px] leading-4">
<span className="sr-only">Spent </span>
<span className="tnum font-medium text-ink">{money(b.spent)}</span>
{b.cap ? <span className="tnum text-ink-3">of ${b.cap}</span> : null}
{warn ? <span className={cx("tnum", warn === 2 ? "text-danger" : "text-warning")}>{warn === 2 ? "Paused at the cap" : `${Math.round(pct * 100)}%`}</span> : null}
</span>
<span className="well relative block h-1.5 min-w-6 flex-1 overflow-hidden rounded-[3px]" aria-hidden="true">
<span className={cx("absolute inset-y-0 left-0 w-full origin-left rounded-[3px]", warn === 2 ? "bg-danger" : warn ? "bg-warning" : "bg-ink")} style={{ transform: `scaleX(${Math.min(1, pct)})`, transition: "transform .28s cubic-bezier(.23,1,.32,1)" }} />
</span>
</button>
) : <span className="flex-1" />}
{showAuto ? (
<button
type="button"
data-k=""
aria-haspopup="menu"
aria-label={`Autonomy: ${AUTONOMY_LONG[au]}`}
className={cx("pressable flex h-8 flex-none items-center gap-1 rounded-inner px-2 text-[12.5px] font-medium text-ink-2 hover:bg-hover hover:text-ink", FOCUS)}
onClick={(e) => pop(e.currentTarget, "Autonomy", (["ask", "risk", "full"] as const).map((a) => ({ label: AUTONOMY_LONG[a], on: au === a, run: () => p.onAutonomyChange?.(a) })))}
>
{AUTONOMY[au]}
<span className="text-ink-3"><Icon name="chevron" size={14} /></span>
</button>
) : null}
</div>
) : null}
{p.simulated ? <p className="px-2 pt-1 text-[11.5px] text-ink-3">Simulated, no agents are running</p> : null}
</div>
);
}
/* ---------- the rail ---------- */
/** The collapsed rail: the Captain and every mission in 56 px. */
export function SidebarRail() {
const { p, api } = useSidebar();
const missions = p.missions ?? [], captain = p.captain ?? { state: "idle" as const }, ws = p.workspace, needs = (p.queue ?? []).length, shown = missions.slice(0, 9);
const said = (STATES[captain.state] ?? "Idle").toLowerCase();
return (
<div className="flex h-full flex-col items-center gap-1 py-2.5">
<span className="mb-1 grid size-[22px] place-items-center rounded-[6px] text-[12px] font-semibold text-white" style={{ background: ws?.color || "var(--captain-ink)" }} title={ws?.name} aria-hidden="true">{(ws?.name || "W").slice(0, 1).toUpperCase()}</span>
<button type="button" className={ICON_BTN} aria-label="Expand the sidebar" title="Expand ⌘\" onClick={() => api.st.setCollapsed(false)}><Icon name="sidebar" /></button>
<button type="button" data-k="" data-cap="" aria-label={`${captain.name || "Captain"}, ${said}`} title={`Captain, ${said}`} onClick={() => p.onOpen?.("captain", "captain")} className={cx("pressable well mt-1 grid size-10 place-items-center rounded-[10px]", FOCUS)}>
<Helm s={captain.state || "idle"} size={26} />
</button>
{needs ? (
<button type="button" data-k="" aria-label={`${needs} need${needs > 1 ? "" : "s"} you`} onClick={() => api.st.setCollapsed(false)} className={cx("pressable relative mt-1 grid size-9 place-items-center rounded-inner text-accent-ink hover:bg-hover", FOCUS)}>
<Icon name="ask" size={18} />
<span className="tnum absolute -top-0.5 -right-0.5 grid h-4 min-w-4 place-items-center rounded-[4px] bg-accent px-0.5 text-[10.5px] font-semibold text-white" aria-hidden="true">{needs}</span>
</button>
) : null}
<span className="my-1.5 h-2" />
{shown.map((m) => (
<button key={m.id} type="button" data-k="" aria-label={`${m.title}, ${summarize(m).text}`} title={m.title} onClick={() => { api.st.setCollapsed(false); api.st.toggle(m.id, true); }} className={cx("pressable grid size-9 place-items-center rounded-inner hover:bg-hover", FOCUS)}>
<Ring m={m} c={count(m.agents)} s={18} />
</button>
))}
{missions.length > 9 ? <span className="tnum text-[11.5px] text-ink-3">+{missions.length - 9}</span> : null}
<span className="flex-1" />
<button type="button" className={ICON_BTN} aria-label="Search" onClick={api.openPal}><Icon name="search" /></button>
{p.budget ? <span className={cx("tnum mt-1 text-[11.5px]", p.budget.spent >= p.budget.cap * 0.8 ? "text-warning" : "text-ink-3")} aria-label={`Spent ${money(p.budget.spent)}`}>${Math.round(p.budget.spent)}</span> : null}
</div>
);
}
/* ---------- menus and the ⌘K palette ---------- */
function Menu({ m, close }: { m: MenuSpec; close(): void }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = ref.current;
if (!el) return;
const back = document.activeElement as HTMLElement | null;
const b = () => [...el.querySelectorAll<HTMLElement>("[role^=menuitem]")];
b()[0]?.focus();
const key = (e: KeyboardEvent) => {
const l = b(), i = l.indexOf(document.activeElement as HTMLElement);
if (e.key === "Escape" || e.key === "Tab") { if (e.key === "Escape") e.preventDefault(); e.stopPropagation(); close(); }
else if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); e.stopPropagation(); l[wrap(i, l.length, e.key === "ArrowDown" ? 1 : -1)]?.focus(); }
else if (e.key === "Home" || e.key === "End") { e.preventDefault(); l[e.key === "Home" ? 0 : l.length - 1]?.focus(); }
};
const out = (e: PointerEvent) => { if (!el.contains(e.target as Node)) close(); };
el.addEventListener("keydown", key);
document.addEventListener("pointerdown", out, true);
return () => {
el.removeEventListener("keydown", key);
document.removeEventListener("pointerdown", out, true);
if (back?.focus && (el.contains(document.activeElement) || document.activeElement === document.body)) back.focus();
};
}, [close]);
return (
<motion.div
ref={ref}
role="menu"
aria-label={m.label}
initial={{ opacity: 0, scale: 0.96 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.16, ease: EASE }}
className="glass absolute z-30 w-[220px] rounded-[10px] p-1"
style={{ left: m.x, top: m.y, bottom: m.b, transformOrigin: m.b != null ? "0 100%" : "0 0" }}
>
{m.items.map((it, i) =>
it ? (
<button
key={i}
type="button"
role={it.on === undefined ? "menuitem" : it.multi ? "menuitemcheckbox" : "menuitemradio"}
aria-checked={it.on === undefined ? undefined : !!it.on}
tabIndex={-1}
className="flex h-8 w-full items-center gap-2 rounded-[6px] px-2 text-left text-[13px] text-ink outline-none hover:bg-hover focus:bg-hover"
onClick={() => { it.run(); if (!it.keep) close(); }}
>
{it.icon ? <span className="grid w-4 place-items-center text-ink-2">{it.icon}</span> : null}
<span className="min-w-0 flex-1 truncate">{it.label}</span>
{it.sub != null ? <span className="tnum text-[12px] text-ink-3">{it.sub}</span> : null}
{it.on ? <Icon name="check" size={14} /> : null}
</button>
) : <span key={i} className="mx-2 my-1 block h-px bg-rim-soft" />,
)}
</motion.div>
);
}
function Palette({ api, close, contained }: { api: Api; close(): void; contained?: boolean }) {
const [q, setQ] = useState(""), [ix, setIx] = useState(0);
const { p, st } = api;
const list = useRef<HTMLDivElement>(null);
const id = useId();
type Item = { label: string; sub?: string; icon: ReactNode; group: string; run(): void };
const items = useMemo<Item[]>(() => {
const found: Item[] = search(p, q).map((x) => ({
label: x.label, sub: x.kind === "mission" || x.kind === "history" ? undefined : x.sub, group: x.group,
icon: x.kind === "queue" ? <Icon name={x.ref.kind === "question" ? "ask" : x.ref.kind === "approval" ? "stamp" : "clash"} size={14} />
: x.kind === "mission" ? <Ring m={x.ref} c={count(x.ref.agents)} />
: x.kind === "history" ? <Icon name={OUT[x.ref.outcome]} size={14} /> : <Mark type={x.ref.type} s={12} />,
run: x.kind === "queue" ? () => { st.setActiveQueue(x.id); p.onOpen?.("queue", x.id); }
: x.kind === "mission" ? () => { st.toggle(x.id, true); p.onSelect?.("mission", x.id); }
: x.kind === "history" ? () => p.onSelect?.("history", x.id) : () => p.onSelect?.("agent", x.id),
}));
const acts: Omit<Item, "group">[] = [
{ label: "Open the Captain", sub: "⌘J", icon: <Helm size={16} />, run: () => p.onOpen?.("captain", "captain") },
{ label: "Pause every swarm", icon: <Icon name="pause" size={14} />, run: () => p.onMissionAction?.("*", "pause") },
{ label: "Resume every swarm", icon: <Icon name="play" size={14} />, run: () => p.onMissionAction?.("*", "resume") },
...(["ask", "risk", "full"] as const).map((a) => ({ label: "Autonomy: " + AUTONOMY_LONG[a], icon: <Icon name="stamp" size={14} />, run: () => p.onAutonomyChange?.(a) })),
{ label: "Collapse the sidebar", sub: "⌘\\", icon: <Icon name="sidebar" size={14} />, run: () => st.setCollapsed(true) },
];
const wl = q.trim().toLowerCase().split(/\s+/).filter(Boolean);
return [...found, ...acts.filter((a) => wl.every((x) => a.label.toLowerCase().includes(x))).slice(0, wl.length ? 4 : 3).map((a) => ({ ...a, group: "Actions" }))];
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [q, p.queue, p.missions, p.history]);
useEffect(() => setIx(0), [q]);
useEffect(() => { list.current?.querySelector("[data-a]")?.scrollIntoView({ block: "nearest" }); }, [ix]);
useEffect(() => {
const back = document.activeElement as HTMLElement | null;
return () => { if (back?.focus && back.isConnected) back.focus(); };
}, []);
const key = (e: React.KeyboardEvent) => {
if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); setIx((i) => wrap(i, items.length, e.key === "ArrowDown" ? 1 : -1)); }
else if (e.key === "Enter" && items[ix]) { e.preventDefault(); items[ix].run(); close(); }
else if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); close(); }
else if (e.key === "Tab") e.preventDefault();
};
const groups: { name: string; items: [Item, number][] }[] = [];
items.forEach((it, i) => { const g = groups[groups.length - 1]; if (g && g.name === it.group) g.items.push([it, i]); else groups.push({ name: it.group, items: [[it, i]] }); });
const lid = id + "l", oid = (i: number) => `${id}o${i}`;
return (
<motion.div
className={cx(contained ? "absolute" : "fixed", "inset-0 z-40 flex items-start justify-center bg-scrim p-3 pt-[12%]")}
initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0, transition: { duration: 0.14 } }} transition={{ duration: 0.16 }}
onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}
>
<motion.div role="dialog" aria-modal="true" aria-label="Search the sidebar" className="glass w-full max-w-[420px] overflow-hidden rounded-shell" initial={{ scale: 0.96, y: -4 }} animate={{ scale: 1, y: 0 }} exit={{ scale: 0.98 }} transition={{ duration: 0.2, ease: EASE }}>
<label className="m-2 flex h-10 items-center gap-2 rounded-inner px-3 text-ink-3 well">
<Icon name="search" size={16} />
<input
autoFocus value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={key} placeholder="Search missions, agents and history"
role="combobox" aria-label="Search" aria-expanded="true" aria-controls={lid} aria-autocomplete="list" aria-activedescendant={items[ix] ? oid(ix) : undefined}
autoComplete="off" spellCheck={false}
className="min-w-0 flex-1 bg-transparent text-[13.5px] text-ink outline-none placeholder:text-ink-3"
/>
</label>
<div ref={list} id={lid} role="listbox" aria-label="Results" className="max-h-[280px] overflow-y-auto px-1.5 pb-1.5">
{items.length ? groups.map((g) => (
<div key={g.name} role="group" aria-label={g.name}>
<div aria-hidden="true" className="px-2 pt-2 pb-1 text-[11.5px] font-medium text-ink-3">{g.name}</div>
{g.items.map(([it, i]) => (
<div key={i} id={oid(i)} role="option" aria-selected={i === ix} data-a={i === ix ? "" : undefined} onPointerMove={() => setIx(i)} onClick={() => { it.run(); close(); }}
className={cx("flex h-8 cursor-default items-center gap-2.5 rounded-[6px] px-2 text-[13px] text-ink", i === ix && "bg-hover")}>
<span aria-hidden="true" className="grid w-4 place-items-center text-ink-2">{it.icon}</span>
<span className="min-w-0 flex-1 truncate">{it.label}</span>
{it.sub ? <span className="flex-none text-[12px] text-ink-3">{it.sub}</span> : null}
</div>
))}
</div>
)) : <p className="px-2 py-3 text-[13px] text-ink-3">Nothing matches “{q}”.</p>}
</div>
</motion.div>
</motion.div>
);
}
/* ---------- the handoff: the answer itself travels into its mission ---------- */
function HandoffGhost({ api }: { api: Api }) {
const h = api.st.handoff;
const [flight, setFlight] = useState<{ id: string; label: string; x0: number; y0: number; w: number; h: number; dx: number; dy: number } | null>(null);
useIsoLayoutEffect(() => {
const root = api.root.current, src = api.from.current;
if (!h || !root || !src || api.st.reduced) { setFlight(null); return; }
const R = root.getBoundingClientRect();
const scroller = root.querySelector<HTMLElement>("[data-scroll]")?.getBoundingClientRect();
const tray = h.mission ? root.querySelector<HTMLElement>(`[data-mission="${CSS.escape(h.mission)}"] [data-swarm]`) : null;
let tgt = tray?.getBoundingClientRect() ?? null;
if (tgt && scroller && (tgt.bottom < scroller.top || tgt.top > scroller.bottom)) tgt = null;
tgt ??= root.querySelector<HTMLElement>("[data-cap]")?.getBoundingClientRect() ?? null;
if (!tgt) { setFlight(null); return; }
setFlight({
id: h.id, label: h.label, x0: src.left - R.left, y0: src.top - R.top, w: src.width, h: src.height,
dx: tgt.left + tgt.width / 2 - (src.left + src.width / 2), dy: tgt.top + tgt.height / 2 - (src.top + src.height / 2),
});
api.from.current = null;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [h?.id]);
if (!flight || !h || flight.id !== h.id) return null;
return (
<motion.span
key={flight.id}
aria-hidden="true"
className="pointer-events-none absolute z-20 grid place-items-center overflow-hidden rounded-[6px] bg-primary px-2.5 text-[12.5px] font-medium whitespace-nowrap text-primary-ink shadow-[0_6px_16px_-4px_rgba(17,18,20,.35)]"
style={{ left: flight.x0, top: flight.y0, height: flight.h, minWidth: flight.w }}
initial={{ x: 0, y: 0, scale: 1, opacity: 1 }}
animate={{ x: flight.dx, y: flight.dy, scale: 0.3, opacity: [1, 1, 0] }}
transition={{ duration: HANDOFF_MS / 1000, ease: [0.4, 0, 0.2, 1], opacity: { duration: HANDOFF_MS / 1000, times: [0, 0.72, 1] } }}
>
{flight.label}
</motion.span>
);
}
/* ---------- phones: a bottom sheet that follows the finger ---------- */
function Sheet({ api, children }: { api: Api; children: ReactNode }) {
const { p } = api;
const captain = p.captain ?? { state: "idle" as const }, needs = (p.queue ?? []).length, b = p.budget;
const el = useRef<HTMLDivElement>(null);
const d = useRef<{ y: number; t: number; v: number; ly: number; lt: number; moved: number } | null>(null);
const first = useRef(true);
const [snap, setSnap] = useState(0);
const PEEK = 68;
const pos = (s: number) => { const H = el.current?.offsetHeight ?? 0; return [H - PEEK, H * 0.42, 0][s] ?? 0; };
const put = (y: number, anim: boolean) => {
const s = el.current;
if (!s) return;
s.style.transition = anim && !api.st.reduced ? "transform .3s cubic-bezier(.32,.72,0,1)" : "none";
s.style.transform = `translateY(${y}px)`;
};
useIsoLayoutEffect(() => {
put(pos(snap), !first.current);
first.current = false;
if (!el.current) return;
const ro = new ResizeObserver(() => put(pos(snap), false));
ro.observe(el.current);
return () => ro.disconnect();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [snap]);
const down = (e: React.PointerEvent) => { if (e.button) return; d.current = { y: e.clientY, t: pos(snap), v: 0, ly: e.clientY, lt: e.timeStamp, moved: 0 }; e.currentTarget.setPointerCapture(e.pointerId); };
const move = (e: React.PointerEvent) => {
const g = d.current;
if (!g) return;
const dy = e.clientY - g.y, max = pos(0);
let y = g.t + dy;
if (y < 0) y /= 3;
if (y > max) y = max + (y - max) / 3;
g.v = (e.clientY - g.ly) / Math.max(1, e.timeStamp - g.lt); g.ly = e.clientY; g.lt = e.timeStamp; g.moved = Math.max(g.moved, Math.abs(dy));
if (g.moved > 3) put(y, false);
};
const up = (e: React.PointerEvent) => {
const g = d.current;
d.current = null;
if (!g) return;
if (g.moved <= 3) { setSnap((s) => (s ? 0 : 1)); return; }
const y = g.t + (e.clientY - g.y) + g.v * 220, pts = [0, 1, 2].map(pos);
const best = pts.reduce((bi, pt, i) => (Math.abs(pt - y) < Math.abs(pts[bi]! - y) ? i : bi), 0);
put(pos(best), true);
setSnap(best);
};
return (
<>
<div className={cx("absolute inset-0 bg-scrim transition-opacity duration-200", snap ? "opacity-100" : "pointer-events-none opacity-0")} onClick={() => setSnap(0)} />
<div ref={el} role="dialog" aria-label={p.label || "Captain"} className="glass absolute inset-x-0 bottom-0 flex h-[88%] flex-col rounded-t-[14px]">
<div className="flex-none touch-none px-3 pt-2 pb-2" onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={up}>
<span className="mx-auto mb-2 block h-1 w-9 rounded-[2px] bg-rim-strong" />
<div className="flex items-center gap-2.5">
<span className="well grid size-9 flex-none place-items-center rounded-[9px]"><Helm s={captain.state || "idle"} size={22} /></span>
<span className="flex min-w-0 flex-1 flex-col">
<span className="text-[13.5px] font-medium text-ink">{STATES[captain.state] ?? "Idle"}</span>
<span className="truncate text-[12px] text-ink-3">{captain.line ?? ""}</span>
</span>
{needs ? <span className="tnum grid h-5 min-w-5 place-items-center rounded-[5px] bg-accent px-1 text-[11.5px] font-semibold text-white">{needs}</span> : null}
{b ? <span className="tnum text-[12px] text-ink-3">{money(b.spent)}</span> : null}
<button type="button" className={ICON_BTN} aria-label="Search" onPointerDown={(e) => e.stopPropagation()} onClick={api.openPal}><Icon name="search" /></button>
</div>
</div>
<div className="flex min-h-0 flex-1 flex-col">{children}</div>
</div>
</>
);
}
/* ---------- the root ---------- */
/**
* The root. With no children it renders the whole sidebar; give it children (the Sidebar parts, or your own) to compose it.
* Collapsed, it renders the rail; on phones it wraps the children in a bottom sheet.
*/
export function SidebarRoot(props: CaptainSidebarProps) {
const { missions = [], theme = "inherit", layout = "auto", density = "regular", accent, width = 296, contained } = props;
const root = useRef<HTMLDivElement | null>(null);
const from = useRef<DOMRect | null>(null);
const st = useCaptainSidebar(props);
const sys = useMedia("(prefers-color-scheme: dark)");
const phone = useMedia("(max-width: 640px)");
const [inherited, setInherited] = useState(false);
useEffect(() => {
if (theme !== "inherit") return;
const check = () => setInherited(!!root.current?.closest(".dark, [data-theme='dark']"));
check();
const mo = new MutationObserver(check);
mo.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "data-theme"] });
return () => mo.disconnect();
}, [theme]);
const dark = theme === "dark" || (theme === "auto" && sys) || (theme === "inherit" && inherited);
const [menu, setMenu] = useState<MenuSpec | null>(null);
const [under, setUnder] = useState(false);
const mode: "panel" | "rail" | "sheet" = layout === "sheet" || (layout === "auto" && phone && !contained) ? "sheet" : st.collapsed ? "rail" : "panel";
const { log } = useAnnouncer(props, { enabled: props.announce !== false });
st.focusCaptain.current = () => root.current?.querySelector<HTMLElement>("[data-cap]")?.focus();
const api: Api = {
p: props, st, root, from, dark, setMenu, under, setUnder,
rh: { compact: 24, regular: 28, comfy: 32 }[density] ?? 28,
openPal: () => st.setSearchOpen(true),
missionMenu: (m, x, y) => {
const R = root.current?.getBoundingClientRect();
if (!R) return;
const act = (a: "pause" | "resume" | "add" | "stop") => props.onMissionAction?.(m.id, a), can = actionsOf(props);
const items: (MenuItem | false)[] = [
{ label: "Open", icon: <Icon name="chevron" size={14} />, run: () => props.onOpen?.("mission", m.id) },
can.pause && { label: m.paused ? "Resume the swarm" : "Pause the swarm", icon: <Icon name={m.paused ? "play" : "pause"} size={14} />, run: () => act(m.paused ? "resume" : "pause") },
can.add && { label: "Add agents", icon: <Icon name="plus" size={14} />, sub: m.agents.length, run: () => act("add") },
can.stop && null,
can.stop && { label: "Stop the mission", icon: <Icon name="stop" size={14} />, run: () => act("stop") },
];
setMenu({ label: m.title, x: Math.min(x - R.left, R.width - 228), y: Math.min(y - R.top, R.height - 200), items: items.filter((x): x is MenuItem => x !== false) });
},
};
const nav = (e: React.KeyboardEvent) => {
if (!root.current) return;
rovingKeyDown(e, root.current, {
onToggle: (id, v) => st.toggle(id, v),
onMenu: (id, t) => { const r = t.getBoundingClientRect(), m = missions.find((x) => x.id === id); if (m) api.missionMenu(m, r.left + 40, r.bottom); },
onEscape: (t) => { setMenu(null); t.blur(); },
});
};
const ctx: SidebarContext = { p: props, st, mode, dark, accent: accent ?? "var(--captain-accent)", api };
const kids = props.children ?? (<><SidebarHeader /><SidebarCaptain /><SidebarContent /><SidebarFooter /></>);
const style = { ...(accent ? { "--captain-accent": accent, "--captain-accent-tint": `color-mix(in srgb, ${accent} 14%, transparent)` } : null), ...props.style } as CSSProperties;
return (
<Ctx.Provider value={ctx}>
<div
ref={root}
dir={props.dir}
data-theme={theme === "inherit" ? undefined : dark ? "dark" : "light"}
data-layout={mode}
className={cx("relative isolate flex h-full min-h-0 font-sans text-ink antialiased", mode !== "sheet" && "bg-band", props.className)}
style={{ width: mode === "sheet" ? "100%" : mode === "rail" ? 56 : width, transition: "width .26s cubic-bezier(.23,1,.32,1)", ...style }}
onKeyDown={nav}
>
{mode === "sheet" ? (
<Sheet api={api}>{kids}</Sheet>
) : (
<nav aria-label={props.label || "Captain"} className="flex min-h-0 w-full flex-col overflow-hidden">
{mode === "rail" ? <SidebarRail /> : kids}
</nav>
)}
<div className="sr-only" role="log" aria-live="polite" aria-relevant="additions">{log.map((x) => <p key={x.id}>{x.text}</p>)}</div>
<HandoffGhost api={api} />
{menu ? <Menu m={menu} close={() => setMenu(null)} /> : null}
<AnimatePresence>{st.searchOpen ? <Palette key="pal" api={api} close={() => st.setSearchOpen(false)} contained={contained} /> : null}</AnimatePresence>
</div>
</Ctx.Provider>
);
}
/** The whole sidebar in one component: Sidebar.Root with the default parts. */
export function CaptainSidebar(props: CaptainSidebarProps) {
return <SidebarRoot {...props} />;
}
export default CaptainSidebar;
/** The parts: <Sidebar.Root><Sidebar.Captain /><Sidebar.Content /><Sidebar.Footer /></Sidebar.Root>. */
export const Sidebar = {
Root: SidebarRoot, Header: SidebarHeader, Captain: SidebarCaptain, Content: SidebarContent, Section: SidebarSection,
Queue: SidebarQueue, Missions: SidebarMissions, History: SidebarHistory, Footer: SidebarFooter, Rail: SidebarRail,
};
/* ---------- kept from the original API ---------- */
/** The two springs every motion used, as CSS linear() easings. */
export const SPRING = "linear(0,.009 1%,.035 2.1%,.141 4.6%,.281 7.1%,.438 10%,.592 13.2%,.723 16.6%,.83 20.4%,.907 24.5%,.959 28.9%,.99 33.6%,1.006 38.7%,1.012 44.5%,1.01 51.7%,1.003 62%,1)";
export const BOUNCE = "linear(0,.018 1.1%,.072 2.3%,.29 5.1%,.555 8.2%,.79 11.6%,.958 15.3%,1.055 19.1%,1.094 22.7%,1.093 26.3%,1.064 30.4%,1.023 35.4%,.996 40.6%,.986 45.7%,.988 51.5%,.998 61.4%,1.001 72%,1)";
/** The styles now come from the Captain theme (captain.css), so there is no private stylesheet to inject. */
const NO_STYLES = "";
export { NO_STYLES as CSS, NO_STYLES as TOKENS };
export function ensureStyles(_doc?: Document | null) {}"use client";
// uimaxxer · Captain sidebar core, MIT. The headless part: types, state, keyboard, search and announcements, with no markup.
// Ported from github.com/jawadjalal/sidebar (captain-core.js); same names and data shape, so it can go back there.
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type Dispatch, type MutableRefObject, type SetStateAction } from "react";
/* ---------- data ---------- */
/** The Captain's states. Shared with composer-kit's lead. */
export type CaptainState = "idle" | "thinking" | "planning" | "delegating" | "waiting" | "asking" | "reviewing" | "merging" | "done" | "paused" | "offline";
/** How much the Captain may do without you: ask first, ask only on risky steps, or never ask. */
export type Autonomy = "ask" | "risk" | "full";
/** Agent types with a built-in mark and colour; any other string gets a stable mark and colour from its name. */
export type AgentType = "review" | "tests" | "build" | "research" | "security" | "docs" | "design" | "ship" | (string & {});
export type AgentState = "queued" | "working" | "needs" | "failed" | "done";
export interface Captain {
name?: string;
state: CaptainState;
/** What it is doing now, in one line. */
line?: string;
/** Epoch ms when the current state started; drives the m:ss timer. */
since?: number;
}
export interface Agent {
id: string;
type: AgentType;
state: AgentState;
name?: string;
/** The step it is on or, when state is 'needs', the question. */
step?: string;
/** Time spent working, in ms. */
ms?: number;
}
export interface Mission {
id: string;
title: string;
state: CaptainState;
agents: Agent[];
paused?: boolean;
/** Dollars spent on this mission so far. */
cost?: number;
}
export interface QueueItem {
id: string;
kind: "question" | "approval" | "conflict";
title: string;
/** For questions: up to two answers. The first is the primary. */
options?: string[];
mission?: string;
from?: { id: string; type: AgentType };
/** For conflicts: the other agent. */
vs?: { id: string; type: AgentType };
/** Epoch ms. */
at?: number;
}
export interface HistoryItem {
id: string;
title: string;
outcome: "merged" | "shipped" | "stopped" | "failed";
detail?: string;
agents?: number;
cost?: number;
/** Epoch ms. */
at: number;
}
export interface Budget { spent: number; cap: number }
export type MissionAction = "pause" | "resume" | "stop" | "add" | "open";
/** For questions: the option text. For approvals: 'approve' or 'deny'. For conflicts: 'a' (keep from) or 'b' (keep vs). */
export type Answer = string;
export type Workspace = { name: string; color?: string };
export interface CaptainSidebarProps {
captain?: Captain;
missions?: Mission[];
queue?: QueueItem[];
history?: HistoryItem[];
budget?: Budget;
autonomy?: Autonomy;
/** Agent types the Captain may use. Defaults to all eight. */
roster?: AgentType[];
workspace?: Workspace;
workspaces?: Workspace[];
/** 'inherit' (default here) lets the app's .dark decide; 'light' and 'dark' force one. */
theme?: "light" | "dark" | "auto" | "inherit";
/** 'auto' (default): a panel, or a bottom sheet under 640px. 'rail' starts collapsed. */
layout?: "auto" | "panel" | "rail" | "sheet";
density?: "compact" | "regular" | "comfy";
/** The one colour: things that need you. Defaults to the theme's accent. */
accent?: string;
/** Kept for the original API. 0 turns the sheet's frosted glass off. */
glass?: number;
/** Panel width in px. Default 296. */
width?: number;
/** Keep the sheet, dim and palette inside the host instead of the viewport (previews and playgrounds). */
contained?: boolean;
/** Show a "Simulated" line in the footer. */
simulated?: boolean;
open?: string[];
defaultOpen?: string[];
onOpenChange?(open: string[]): void;
collapsed?: boolean;
defaultCollapsed?: boolean;
onCollapsedChange?(collapsed: boolean): void;
searchOpen?: boolean;
onSearchOpenChange?(open: boolean): void;
historyOpen?: boolean;
defaultHistoryOpen?: boolean;
onHistoryOpenChange?(open: boolean): void;
missionActions?: ("pause" | "add" | "stop")[];
showRoster?: boolean;
/** Announce changes in a polite live region. Default true. */
announce?: boolean;
/** Kept for the original API; the styles now come from the Captain theme, so it does nothing. */
injectStyles?: boolean;
/** The nav landmark's name. Default 'Captain'. */
label?: string;
emptyText?: string;
dir?: "ltr" | "rtl" | "auto";
className?: string;
children?: React.ReactNode;
/** Id of the selected item ('captain', a mission, a history item). */
selected?: string;
/** ⌘K search, ⌘J the Captain, ⌘\ collapse. Default true; one sidebar per page should own them. */
hotkeys?: boolean;
style?: React.CSSProperties;
onOpen?(kind: "captain" | "queue" | "mission", id: string): void;
onSelect?(kind: "mission" | "history" | "agent", id: string): void;
onResolve?(item: QueueItem, answer: Answer): void;
onMissionAction?(missionId: string | "*", action: MissionAction): void;
onAutonomyChange?(autonomy: Autonomy): void;
onBudgetChange?(cap: number): void;
onRosterChange?(roster: AgentType[]): void;
onLayoutChange?(layout: "panel" | "rail"): void;
onWorkspace?(workspace: Workspace): void;
}
/* ---------- words ---------- */
export const DOM = typeof document !== "undefined";
export const STATES: Record<CaptainState, string> = { idle: "Idle", thinking: "Thinking", planning: "Planning", delegating: "Delegating", waiting: "Waiting on agents", asking: "Waiting on you", reviewing: "Reviewing", merging: "Merging", done: "Done", paused: "Paused", offline: "Offline" };
export const AGENT_STATES: Record<AgentState, string> = { queued: "Queued", working: "Working", done: "Done", needs: "Needs you", failed: "Failed, retrying" };
export const AUTONOMY: Record<Autonomy, string> = { ask: "Ask", risk: "On risk", full: "Full" };
export const AUTONOMY_LONG: Record<Autonomy, string> = { ask: "Ask before acting", risk: "Ask on risky steps", full: "Full autonomy" };
/** Sort order inside a mission: what needs you first, what is done last. */
export const AGENT_ORDER: Record<AgentState, number> = { needs: 0, failed: 1, working: 2, queued: 3, done: 4 };
/* ---------- pure helpers ---------- */
export interface Counts { n: number; done: number; working: number; needs: number; failed: number; queued: number }
export function count(agents: readonly Agent[]): Counts {
const c: Counts = { n: agents.length, done: 0, working: 0, needs: 0, failed: 0, queued: 0 };
for (const a of agents) c[a.state] += 1;
return c;
}
export type Summary =
| { kind: "done" | "needs" | "failed" | "progress"; c: Counts; text: string }
| { kind: "state"; c: Counts; state: CaptainState; text: string };
/** The line under a mission's title, as data. */
export function summarize(m: Mission): Summary {
const c = count(m.agents);
const st: CaptainState = m.paused ? "paused" : m.state;
const early = st === "thinking" || st === "planning";
if (st === "done") return { kind: "done", c, text: `Done, ${c.n} agents` };
if (c.needs) return { kind: "needs", c, text: `${c.needs} need${c.needs > 1 ? "" : "s"} you` };
if (c.failed) return { kind: "failed", c, text: `${c.done} of ${c.n} done, ${c.failed} retrying` };
if (c.n && !early && st !== "paused") return { kind: "progress", c, text: `${c.done} of ${c.n} done` };
return { kind: "state", c, state: st, text: STATES[st] ?? "" };
}
/** Which mission opens first: the first that needs you, else the first. */
export function firstOpen(missions: readonly Mission[]): string[] {
const m = missions.find((x) => count(x.agents).needs) ?? missions[0];
return m ? [m.id] : [];
}
export type SearchResult =
| { kind: "queue"; id: string; label: string; sub: string; ref: QueueItem; group: string }
| { kind: "mission"; id: string; label: string; sub: string; ref: Mission; group: string }
| { kind: "history"; id: string; label: string; sub: string; ref: HistoryItem; group: string }
| { kind: "agent"; id: string; label: string; sub: string; ref: Agent; mission: Mission; group: string };
type Unplaced = SearchResult extends infer R ? (R extends SearchResult ? Omit<R, "group"> : never) : never;
/** ⌘K's search over the sidebar's data: every word must match. */
export function search(
data: { queue?: readonly QueueItem[]; missions?: readonly Mission[]; history?: readonly HistoryItem[] },
query: string,
options: { limits?: Partial<Record<"queue" | "missions" | "history" | "agents", number>> } = {},
): SearchResult[] {
const w = String(query || "").toLowerCase().split(/\s+/).filter(Boolean);
const hit = (s: string) => w.every((x) => s.toLowerCase().includes(x));
const L = { queue: 4, missions: w.length ? 6 : 4, history: w.length ? 6 : 3, agents: 5, ...options.limits };
const out: SearchResult[] = [];
const add = (group: string, arr: Unplaced[], lim: number) => {
let n = 0;
for (const it of arr) {
if (n >= lim) break;
if (hit(it.label + " " + (it.sub || ""))) { out.push({ ...it, group } as SearchResult); n++; }
}
};
add("Needs you", (data.queue ?? []).map((x) => ({ kind: "queue" as const, id: x.id, label: x.title, sub: x.from ? x.from.id : "", ref: x })), L.queue);
add("Missions", (data.missions ?? []).map((m) => ({ kind: "mission" as const, id: m.id, label: m.title, sub: `${m.agents.length} agents`, ref: m })), L.missions);
add("History", (data.history ?? []).map((x) => ({ kind: "history" as const, id: x.id, label: x.title, sub: x.outcome, ref: x })), L.history);
if (w.length) {
const ag: Unplaced[] = [];
for (const m of data.missions ?? []) for (const a of m.agents) {
if (ag.length >= 200) break;
ag.push({ kind: "agent", id: a.id, label: a.name || a.id, sub: `${a.type}, ${m.title}`, ref: a, mission: m });
}
add("Agents", ag, L.agents);
}
return out;
}
export interface Snapshot { captain?: Captain; queue?: readonly QueueItem[]; history?: readonly HistoryItem[]; missions?: readonly Mission[] }
/** What changed between two snapshots, in sentences for a screen reader. */
export function describeChanges(prev: Snapshot | null, next: Snapshot): string[] {
if (!prev) return [];
const out: string[] = [];
const pc = prev.captain, nc = next.captain;
if (nc && pc?.state !== nc.state && STATES[nc.state]) out.push(`${nc.name || "Captain"}: ${STATES[nc.state].toLowerCase()}`);
const had = new Set((prev.queue ?? []).map((q) => q.id));
const fresh = (next.queue ?? []).filter((q) => !had.has(q.id));
if (fresh.length > 2) out.push(`${fresh.length} new things need you`);
else for (const q of fresh) out.push(`${q.from ? q.from.id : "The Captain"} needs you: ${q.title}`);
const seen = new Set((prev.history ?? []).map((x) => x.id));
for (const x of (next.history ?? []).filter((x) => !seen.has(x.id)).slice(0, 3)) out.push(`${x.title}: ${x.outcome}`);
const pm = new Set((prev.missions ?? []).map((m) => m.id));
for (const m of (next.missions ?? []).filter((m) => !pm.has(m.id)).slice(0, 2)) out.push(`New mission: ${m.title}`);
return out;
}
/** Index of the next item for arrow keys, clamped at both ends. */
export const step = (i: number, n: number, dir: 1 | -1) => Math.max(0, Math.min(n - 1, (i < 0 ? (dir > 0 ? -1 : n) : i) + dir));
/** Wrapping version, for menus and the palette. */
export const wrap = (i: number, n: number, dir: 1 | -1) => (n ? (i + dir + n) % n : 0);
export const money = (v?: number) => "$" + (v ?? 0).toFixed(2);
export const ago = (at: number, now: number) => {
const s = (now - at) / 1e3;
return s < 45 ? "now" : s < 3600 ? Math.round(s / 60) + "m" : s < 86400 ? Math.round(s / 3600) + "h" : Math.round(s / 86400) + "d";
};
export const dur = (ms: number) => {
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}:${String(s % 60).padStart(2, "0")}`;
};
/* ---------- hooks ---------- */
/** Controlled when `value` is given, uncontrolled otherwise. */
export function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (v: T) => void): [T, Dispatch<SetStateAction<T>>] {
const [inner, setInner] = useState(defaultValue);
const controlled = value !== undefined;
const cur = controlled ? value : inner;
const ref = useRef(cur);
ref.current = cur;
const set = useCallback<Dispatch<SetStateAction<T>>>((v) => {
const nv = typeof v === "function" ? (v as (p: T) => T)(ref.current) : v;
if (Object.is(nv, ref.current)) return;
if (!controlled) setInner(nv);
onChange?.(nv);
}, [controlled, onChange]);
return [cur, set];
}
const noop = () => () => {};
/** False on the server and during hydration, true afterwards. Anything that differs between them waits for it. */
export function useHydrated() {
return useSyncExternalStore(noop, () => true, () => false);
}
/** Same result on the server and on the first client render, then follows the browser. */
export function useMedia(q: string): boolean {
return useSyncExternalStore(
useCallback((f: () => void) => {
if (!DOM) return () => {};
const l = matchMedia(q);
l.addEventListener("change", f);
return () => l.removeEventListener("change", f);
}, [q]),
() => matchMedia(q).matches,
() => false,
);
}
export const useReducedMotion = () => useMedia("(prefers-reduced-motion: reduce)");
/** The wall clock, ticking every `ms`. Null until hydrated, so relative times never mismatch the server. */
export function useNow(ms = 30000): number | null {
const hydrated = useHydrated();
const [now, setNow] = useState(() => (DOM ? Date.now() : 0));
useEffect(() => {
const t = setInterval(() => setNow(Date.now()), ms);
return () => clearInterval(t);
}, [ms]);
return hydrated ? now : null;
}
/** ⌘K, ⌘J and ⌘\ (Ctrl elsewhere). One sidebar per page should own them. */
export function useHotkeys(enabled: boolean, map: Record<string, (e: KeyboardEvent) => void>) {
const ref = useRef(map);
ref.current = map;
useEffect(() => {
if (!enabled || !DOM) return;
const k = (e: KeyboardEvent) => {
if (!(e.metaKey || e.ctrlKey) || e.altKey) return;
const f = ref.current[e.key.toLowerCase()];
if (f) { e.preventDefault(); f(e); }
};
addEventListener("keydown", k);
return () => removeEventListener("keydown", k);
}, [enabled]);
}
/** The last few announcements for a polite live region. */
export function useAnnouncer(data: Snapshot, { enabled = true, max = 4 }: { enabled?: boolean; max?: number } = {}) {
const prev = useRef<Snapshot | null>(null);
const [log, setLog] = useState<{ id: number; text: string }[]>([]);
const seq = useRef(0);
const snap: Snapshot = { captain: data.captain, queue: data.queue, history: data.history, missions: data.missions };
useEffect(() => {
if (!enabled) { prev.current = snap; return; }
const lines = describeChanges(prev.current, snap);
prev.current = snap;
if (lines.length) setLog((l) => [...l, ...lines.map((t) => ({ id: ++seq.current, text: t }))].slice(-max));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data.captain?.state, data.queue, data.history, data.missions?.length, enabled]);
const say = useCallback((text: string) => setLog((l) => [...l, { id: ++seq.current, text }].slice(-max)), [max]);
return { log, say };
}
/** Where an answered queue item is travelling: from the answer button to its mission (or the Captain). */
export interface Handoff { id: string; answer: string; label: string; mission?: string; at: number }
export interface SidebarState {
open: Set<string>;
setOpen: Dispatch<SetStateAction<string[]>>;
toggle(id: string, open?: boolean): void;
isOpen(id: string): boolean;
collapsed: boolean;
setCollapsed: Dispatch<SetStateAction<boolean>>;
searchOpen: boolean;
setSearchOpen: Dispatch<SetStateAction<boolean>>;
historyOpen: boolean;
setHistoryOpen: Dispatch<SetStateAction<boolean>>;
/** The queue item on top of the deck. */
activeQueue: string | undefined;
setActiveQueue(id: string | null): void;
queueAll: boolean;
setQueueAll: Dispatch<SetStateAction<boolean>>;
/** Queue items on their way out after an answer. */
leaving: Record<string, 1>;
/** The answer in flight to its mission, for the handoff. */
handoff: Handoff | null;
/** Answers a queue item: it folds into its mission, then onResolve runs. */
resolve(item: QueueItem, answer: Answer, label?: string): void;
reduced: boolean;
focusCaptain: MutableRefObject<(() => void) | null>;
}
/** How long an answered card takes to fold into its mission. onResolve runs at the end. */
export const HANDOFF_MS = 260;
/** The whole sidebar's state with no markup. Takes the same props as <CaptainSidebar />. */
export function useCaptainSidebar(props: CaptainSidebarProps): SidebarState {
const { missions = [], queue = [], hotkeys = true } = props;
const reduced = useReducedMotion();
const [open, setOpen] = useControllable<string[]>(props.open, props.defaultOpen ?? firstOpen(missions), props.onOpenChange);
const { onCollapsedChange, onLayoutChange } = props;
const onCollapsed = useCallback((v: boolean) => { onCollapsedChange?.(v); onLayoutChange?.(v ? "rail" : "panel"); }, [onCollapsedChange, onLayoutChange]);
const [collapsed, setCollapsed] = useControllable(props.collapsed, props.defaultCollapsed ?? props.layout === "rail", onCollapsed);
const [searchOpen, setSearchOpen] = useControllable(props.searchOpen, false, props.onSearchOpenChange);
const [historyOpen, setHistoryOpen] = useControllable(props.historyOpen, props.defaultHistoryOpen ?? false, props.onHistoryOpenChange);
const [activeQ, setActiveQ] = useState<string | null>(null);
const [queueAll, setQueueAll] = useState(false);
const [leaving, setLeaving] = useState<Record<string, 1>>({});
const [handoff, setHandoff] = useState<Handoff | null>(null);
const lastLayout = useRef(props.layout);
useEffect(() => {
if (props.layout === lastLayout.current) return;
lastLayout.current = props.layout;
if (props.layout === "rail" || props.layout === "panel") setCollapsed(props.layout === "rail");
}, [props.layout, setCollapsed]);
const openSet = useMemo(() => new Set(open ?? []), [open]);
// Until you open or close a mission yourself, the one that needs you (else the first) opens as missions arrive.
const touched = useRef(props.defaultOpen !== undefined);
const lead = firstOpen(missions)[0];
useEffect(() => {
if (!touched.current && props.open === undefined && lead && !openSet.has(lead)) setOpen((o) => [...(o ?? []), lead]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [lead]);
const toggle = useCallback((id: string, v?: boolean) => {
touched.current = true;
setOpen((o) => {
const s = new Set(o ?? []);
const on = v ?? !s.has(id);
if (on) s.add(id); else s.delete(id);
return [...s];
});
}, [setOpen]);
const { onResolve } = props;
const resolve = useCallback((q: QueueItem, a: Answer, label?: string) => {
setLeaving((o) => ({ ...o, [q.id]: 1 }));
setHandoff({ id: q.id, answer: a, label: label ?? a, mission: q.mission, at: DOM ? performance.now() : 0 });
setTimeout(() => {
onResolve?.(q, a);
setLeaving((o) => { const n = { ...o }; delete n[q.id]; return n; });
setHandoff((h) => (h && h.id === q.id ? null : h));
}, reduced ? 0 : HANDOFF_MS);
}, [onResolve, reduced]);
const top = queue.find((q) => !leaving[q.id])?.id;
const activeQueue = queue.some((q) => q.id === activeQ && !leaving[q.id]) ? activeQ! : top;
const focusCaptain = useRef<(() => void) | null>(null);
useHotkeys(hotkeys, {
k: () => setSearchOpen((v) => !v),
j: () => { focusCaptain.current?.(); props.onOpen?.("captain", "captain"); },
"\\": () => setCollapsed((v) => !v),
});
return {
open: openSet, setOpen, toggle, isOpen: (id) => openSet.has(id),
collapsed, setCollapsed, searchOpen, setSearchOpen, historyOpen, setHistoryOpen,
activeQueue, setActiveQueue: setActiveQ, queueAll, setQueueAll, leaving, handoff, resolve,
reduced, focusCaptain,
};
}
/** Arrow keys, Home and End over [data-k] items in `root`; Left and Right fold missions (mirrored in RTL). */
export function rovingKeyDown(
e: { key: string; target: EventTarget | null; shiftKey?: boolean; preventDefault(): void },
root: HTMLElement,
handlers: { selector?: string; onToggle?(id: string, open: boolean): void; onMenu?(id: string, el: HTMLElement): void; onEscape?(el: HTMLElement): void } = {},
) {
const { selector = "[data-k]", onToggle, onMenu, onEscape } = handlers;
const t = e.target as HTMLElement | null;
if (!t || t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.closest("[role=menu],[role=dialog][aria-modal=true]")) return;
const shown = (x: HTMLElement) => (typeof x.checkVisibility === "function" ? x.checkVisibility() : !x.closest("[hidden],[inert]"));
const items = () => [...root.querySelectorAll<HTMLElement>(selector)].filter((x) => (x.tabIndex >= 0 || x.dataset.k === "a") && shown(x));
const rtl = getComputedStyle(root).direction === "rtl";
const k = e.key;
if (k === "ArrowDown" || k === "ArrowUp" || k === "Home" || k === "End") {
const l = items(), i = l.indexOf(t);
e.preventDefault();
const j = k === "Home" ? 0 : k === "End" ? l.length - 1 : step(i, l.length, k === "ArrowDown" ? 1 : -1);
l[j]?.focus();
} else if (t.dataset.m && (k === "ArrowRight" || k === "ArrowLeft")) {
e.preventDefault();
onToggle?.(t.dataset.m, (k === "ArrowRight") !== rtl);
} else if (t.dataset.m && (k === "." || k === "ContextMenu" || (k === "F10" && e.shiftKey))) {
e.preventDefault();
onMenu?.(t.dataset.m, t);
} else if (k === "Escape") onEscape?.(t);
}"use client";
// uimaxxer · Captain sidebar marks, MIT. The Captain's Helm, the agents' pixel marks, a mission's swarm of cells and its ring.
// Every pose is a pure function of time on one shared clock, so many marks on a page never drift and a recording can step them.
import { memo, useMemo, useRef, useState, useEffect } from "react";
import { useIsoLayoutEffect } from "@/registry/captain/ui/captain";
import { DOM, type AgentType, type CaptainState, type Counts, type Mission, type Agent } from "./captain-sidebar-core";
const still = () => DOM && matchMedia("(prefers-reduced-motion: reduce)").matches;
/* ---------- one clock for every 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) {
subs.add(f);
if (!raf && DOM) raf = requestAnimationFrame(loop);
return () => { subs.delete(f); };
}
const clamp = (v: number, a = 0, b = 1) => Math.min(b, Math.max(a, v));
const lerp = (a: number, b: number, p: number) => a + (b - a) * p;
const eo = (p: number) => 1 - Math.pow(1 - p, 3);
const eio = (p: number) => (p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2);
const back = (p: number) => 1 + 2.7 * Math.pow(p - 1, 3) + 1.7 * Math.pow(p - 1, 2);
const bump = (p: number) => (p <= 0 || p >= 1 ? 0 : Math.sin(Math.PI * p));
/* ---------- square-pixel glyphs: '#' solid, '+' 50% dither ---------- */
const M16 = "................";
const P = (s: string) => s.split("/");
const MK: 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}`),
};
const pc = new Map<string, [string, string]>();
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 NAMES = ["eye", "nib", "flask", "bolt", "lens", "shield", "leaf", "cube"] as const;
const HUES = ["#2E5BFF", "#C98A0B", "#1E8A4C", "#0E7C86", "#6B4BD6", "#A63A9C"];
/** The eight built-in agent types: [label, mark, colour]. Shared with composer-kit. */
export const TYPES: Record<string, [string, string, string]> = {
review: ["Review", "eye", "#2E5BFF"], tests: ["Tests", "flask", "#1E8A4C"], build: ["Build", "cube", "#0E7C86"],
research: ["Research", "lens", "#6B4BD6"], security: ["Security", "shield", "#A63A9C"], docs: ["Docs", "leaf", "#8A6A12"],
design: ["Design", "nib", "#C2410C"], ship: ["Ship", "bolt", "#C98A0B"],
};
const hash = (s: string) => { let n = 0; for (const c of String(s)) n = (n * 31 + c.charCodeAt(0)) >>> 0; return n; };
export const typeOf = (t: AgentType): [string, string, string] => TYPES[t] ?? [String(t), NAMES[hash(t) % 8]!, HUES[hash(t) % 6]!];
/** An agent's mark: a 16-pixel glyph in its type's colour. While it works, the dither shimmers on the shared clock. */
export const Mark = memo(function Mark({ type, work, s = 14 }: { type: AgentType; work?: boolean; s?: number }) {
const t = typeOf(type);
const rows = MK[t[1]]!;
const [a, d0] = paths(rows, 0);
const d1 = paths(rows, 1)[1];
const ref = useRef<SVGSVGElement>(null);
useEffect(() => {
if (!work || still()) return;
let ph = -1;
return onTick((now) => {
const p = Math.floor(now / 400) % 2;
if (p === ph || !ref.current) return;
ph = p;
ref.current.dataset.ph = String(p);
});
}, [work]);
return (
<svg ref={ref} width={s} height={s} viewBox="0 0 16 16" shapeRendering="crispEdges" aria-hidden="true" className="group/mk block flex-none" style={{ color: t[2] }} data-ph="0">
<path d={a} fill="currentColor" />
<path d={d0} fill="currentColor" className="group-data-[ph=1]/mk:hidden" />
<path d={d1} fill="currentColor" className="hidden group-data-[ph=1]/mk:inline" />
</svg>
);
});
/* ---------- the Captain's Helm: one at the centre, six around it, a motion for each state ---------- */
const KN = 6, KR = 8.6, A0 = -Math.PI / 2;
/** A pose of the Helm: [core scale, then radius, scale and opacity for each of the six]. Pure, for recordings. */
export function pose(s: CaptainState, t: number, T: number): number[] {
const v = [1];
for (let i = 0; i < KN; i++) {
let r = KR, k = 1, o = 1;
if (s === "thinking") { const p = (((T / 1500 - i / KN) % 1) + 1) % 1, b = bump(p / 0.42); r -= 1.7 * b; k += 0.2 * b; }
else if (s === "planning") { const c = t % 2800, p = c - 120 - i * 150; k = p < 0 ? 0 : back(clamp(p / 420)); if (c > 2300) k *= 1 - eio(clamp((c - 2300) / 380)); }
else if (s === "delegating") { const c = t % 2200, q = clamp((c - 60 - i * 110) / 620); r = lerp(3.4, KR, back(q)); k = lerp(0.45, 1, q); o = clamp(q * 4); if (c > 1800) o *= 1 - clamp((c - 1800) / 340); }
else if (s === "waiting") { o = 0.38 + 0.62 * (0.5 + 0.5 * Math.sin(T / 540 + i * 2.25)); }
else if (s === "asking") { if (i) o = 0.32; else { const c = t % 2200; r += 1.5 * (bump(c / 280) + bump((c - 380) / 280)); k = 1.12; } }
else if (s === "reviewing") { const d = (((T / 230 - i) % KN) + KN) % KN, w = clamp(1 - d / 1.7); k = 1 + 0.42 * w; o = 0.42 + 0.58 * w; }
else if (s === "merging") { const c = t % 2000, q = eio(clamp((c - i * 55) / 820)); r = lerp(KR, 2.4, q); k = lerp(1, 0.5, q); o = 1 - clamp((q - 0.72) / 0.28); if (c > 1420) { r = KR; k = 1; o = eo(clamp((c - 1420) / 420)); } }
else if (s === "done") { k = 1 + 0.3 * bump(clamp((t - 60 - i * 40) / 380)); }
else if (s === "paused") o = 0.38;
else if (s === "offline") o = 0.26;
v.push(r, k, o);
}
if (s === "thinking") v[0] = 1 + 0.1 * Math.sin(T / 380);
else if (s === "delegating") v[0] = 1 - 0.14 * bump((t % 2200) / 320);
else if (s === "merging") v[0] = 1 + 0.3 * bump(((t % 2000) - 820) / 520);
else if (s === "done") v[0] = 1 + 0.34 * Math.exp(-t / 240) * Math.sin(Math.min(t, 1400) / 95);
else if (s === "asking") v[0] = 1.06;
return v;
}
const STILL: Partial<Record<CaptainState, 1>> = { idle: 1, paused: 1, offline: 1 };
const CORE: Partial<Record<CaptainState, string>> = { asking: "fill-accent", done: "fill-success" };
/** The Captain's mark. `at` (ms) draws a still pose. */
export const Helm = memo(function Helm({ s = "idle", size = 18, at }: { s?: CaptainState; size?: number; at?: number }) {
const ref = useRef<SVGSVGElement>(null);
const mem = useRef<number[] | null>(null);
useIsoLayoutEffect(() => {
const root = ref.current;
if (!root) return;
const els = root.querySelectorAll<SVGCircleElement>("[data-p]");
const t0 = performance.now(), fixed = at != null, from = fixed ? null : mem.current, calm = still() && !fixed;
const paint = (now: number) => {
const tg = fixed ? pose(s, at, at) : pose(s, calm ? 1e4 : now - t0, calm ? 0 : now);
const b = from && !calm ? eo(clamp((now - t0) / 320)) : 1;
const v = b < 1 && from ? tg.map((x, i) => lerp(from[i] ?? x, x, b)) : tg;
mem.current = v;
els[0]?.setAttribute("r", (3.7 * v[0]!).toFixed(2));
for (let i = 0; i < KN; i++) {
const r = v[1 + i * 3]!, k = v[2 + i * 3]!, o = v[3 + i * 3]!, a = A0 + (i * Math.PI) / 3, kn = els[1 + i];
if (!kn) continue;
kn.setAttribute("cx", (12 + Math.cos(a) * r).toFixed(2));
kn.setAttribute("cy", (12 + Math.sin(a) * r).toFixed(2));
kn.setAttribute("r", (2.05 * k).toFixed(2));
kn.setAttribute("opacity", o.toFixed(2));
}
};
paint(t0);
if (fixed || calm || (STILL[s] && !from)) return;
const off = onTick((now) => {
paint(now);
if ((STILL[s] && now - t0 > 340) || (s === "done" && now - t0 > 1500)) off();
});
return off;
}, [s, at]);
const kids = [<circle key="c" data-p="" cx={12} cy={12} r={3.7} className={CORE[s] ?? (s === "offline" ? "fill-none stroke-current" : "fill-current")} strokeWidth={1.5} />];
for (let i = 0; i < KN; i++) {
const a = A0 + (i * Math.PI) / 3;
kids.push(<circle key={i} data-p="" cx={12 + Math.cos(a) * KR} cy={12 + Math.sin(a) * KR} r={2.05} className={i === 0 && s === "asking" ? "fill-accent" : "fill-current"} />);
}
return (
<svg ref={ref} data-s={s} width={size} height={size} viewBox="0 0 24 24" aria-hidden="true" className="block flex-none overflow-visible text-ink">
{kids}
</svg>
);
});
/* ---------- a mission's progress: a ring that fills as agents finish ---------- */
const RC = 2 * Math.PI * 6;
export function Ring({ m, c, s = 14 }: { m: Pick<Mission, "state" | "paused">; c: Counts; s?: number }) {
const st = m.paused ? "paused" : m.state;
const plan = !c.n || st === "thinking" || st === "planning";
const k = st === "done" || st === "merging" ? "done" : c.needs ? "needs" : st === "paused" ? "paused" : c.failed ? "failed" : plan ? "plan" : "run";
const p = k === "done" ? 1 : c.n ? c.done / c.n : 0;
return (
<svg width={s} height={s} viewBox="0 0 16 16" aria-hidden="true" className="block flex-none overflow-visible fill-none" strokeWidth={1.6} strokeLinecap="round">
<circle cx={8} cy={8} r={6} className={k === "plan" ? "stroke-ink-3" : "stroke-rim-strong"} strokeDasharray={k === "plan" ? "2.4 2.31" : undefined} />
{plan ? null : <circle cx={8} cy={8} r={6} transform="rotate(-90 8 8)" strokeDasharray={RC} style={{ strokeDashoffset: RC * (1 - p), transition: "stroke-dashoffset .28s cubic-bezier(.23,1,.32,1)" }} className={k === "done" ? "stroke-success" : "stroke-ink"} />}
{k === "needs" || k === "failed" ? <circle cx={8} cy={8} r={2.2} className={k === "needs" ? "fill-accent stroke-none" : "fill-danger stroke-none"} />
: k === "paused" ? <path d="M6.6 6.1v3.8M9.4 6.1v3.8" className="stroke-ink-2" strokeWidth={1.5} />
: k === "done" ? <path d="M5.5 8.2 7.2 9.9 10.5 6.3" className="stroke-success" strokeWidth={1.5} strokeLinejoin="round" /> : null}
</svg>
);
}
/* ---------- the swarm: a square of cells, one per agent up to 36, then each cell is a share ----------
It sits where an avatar would. A cell that changes state pops, so you see agents finish (or get your answer) without reading a number. */
const SO: Record<Agent["state"], number> = { done: 0, working: 1, needs: 2, failed: 3, queued: 4 };
const tok = (el: Element, n: string) => getComputedStyle(el).getPropertyValue(n).trim();
export const Swarm = memo(function Swarm({ agents, c, dark, size = 32 }: { agents: Agent[]; c: Counts; dark?: boolean; size?: number }) {
const ref = useRef<HTMLCanvasElement>(null);
const mem = useRef<{ prev: string[] | null; pop: Record<number, number>; was: number }>({ prev: null, pop: {}, was: 0 });
const n = agents.length;
const k = Math.min(n, 36), cols = Math.max(3, Math.ceil(Math.sqrt(k))), rows = Math.ceil(k / cols), pitch = Math.floor(size / cols), cell = Math.max(3, Math.round(pitch * 0.74));
const ox = Math.round((size - (cols * pitch - (pitch - cell))) / 2), oy = Math.round((size - (rows * pitch - (pitch - cell))) / 2);
const key = useMemo(() => { let v = ""; for (const a of agents) v += a.state[0] + a.type; return v; }, [agents]);
const list = useMemo(() => {
const s = agents.slice().sort((a, b) => SO[a.state] - SO[b.state]);
return Array.from({ length: k }, (_, i) => s[Math.floor(((i + 0.5) * n) / k)]!);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key]);
const [hydrated, setHydrated] = useState(false);
useEffect(() => setHydrated(true), []);
useIsoLayoutEffect(() => {
const cv = ref.current;
if (!cv) return;
const g = mem.current, t0 = performance.now(), calm = still();
if (g.prev && g.prev.length === list.length && !calm) list.forEach((a, i) => { if (g.prev![i] !== a.state) g.pop[i] = t0; });
g.prev = list.map((a) => a.state);
const r = Math.min(2, window.devicePixelRatio || 1), x = cv.getContext("2d");
if (!x) return;
const col: Record<string, string> = {
done: tok(cv, "--captain-ink-3") || "#60646C", queued: tok(cv, "--captain-rim-strong") || "rgba(17,18,20,.18)",
needs: tok(cv, "--captain-accent") || "#2E5BFF", failed: tok(cv, "--captain-danger") || "#C4321F",
};
cv.width = size * r; cv.height = size * r; x.setTransform(r, 0, 0, r, 0, 0);
let ph = -1;
const live = (t: number) => { let l = 0; for (const i in g.pop) { if (t - g.pop[i]! < 280) l = 1; else delete g.pop[i]; } return l; };
const draw = (t: number) => {
const p = calm ? 0 : Math.floor(t / 200) % 2, l = live(t);
if (p === ph && !l && !g.was) return;
ph = p; g.was = l;
x.clearRect(0, 0, size, size);
list.forEach((a, i) => {
const cx = ox + (i % cols) * pitch + cell / 2, cy = oy + Math.floor(i / cols) * pitch + cell / 2, st = a.state;
const q = g.pop[i] != null ? 1 - eo(clamp((t - g.pop[i]!) / 280)) : 0, z = cell * (1 + 0.5 * q);
x.globalAlpha = st === "working" && (i + p) % 2 && !q ? 0.55 : st === "done" ? 0.5 : 1;
x.fillStyle = st === "working" ? typeOf(a.type)[2] : col[st] ?? col.queued!;
x.beginPath();
if (x.roundRect) x.roundRect(cx - z / 2, cy - z / 2, z, z, Math.min(1.5, z / 4)); else x.rect(cx - z / 2, cy - z / 2, z, z);
x.fill();
});
};
draw(t0);
if (!c.working && !live(t0)) return;
const off = onTick((t) => { draw(t); if (!c.working && !live(t) && !g.was) off(); });
return off;
}, [list, dark, size, hydrated]);
return n ? <canvas ref={ref} aria-hidden="true" className="block" style={{ width: size, height: size }} /> : <Ring m={{ state: "planning" }} c={c} s={20} />;
});Usage
import { CaptainSidebar } from "@/components/ui/captain-sidebar"
<CaptainSidebar
captain={captain}
missions={missions}
queue={queue}
budget={{ spent: 8.4, cap: 50 }}
onResolve={(item, answer) => captain.answer(item.id, answer)}
/>Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| captain | { state, line?, since?, name? } | The Captain's state and the one line it is saying. | |
| missions | Mission[] | Swarms with their agents. Each mission's agents show as a tray of cells. | |
| queue | QueueItem[] | Questions, approvals and conflicts waiting on you, dealt as a deck. | |
| onResolve | (item, answer) => void | Runs once the answer has landed in its mission, 260 ms after the tap. | |
| history | HistoryItem[] | Finished missions, folded by default. | |
| budget | { spent, cap } | Spend against the cap, with a menu to change the cap. | |
| autonomy | "ask" | "risk" | "full" | How much the Captain may do without you. | |
| selected | string | 'captain', a mission id or a history id; that row is raised. | |
| layout | "auto" | "panel" | "rail" | "sheet" | "auto" | A panel, the 56 px rail, or a bottom sheet on phones. |
| onMissionAction | (id, action) => void | Pause, resume, stop or add agents. |
Keyboard
- ⌘J
- Open the Captain
- ⌘K
- Search
- ⌘\
- Collapse
- ↑ ↓
- Move between rows
- ← →
- Fold a mission
Accessibility
- A nav landmark with labelled sections; every row is a real button.
- Arrow keys move through rows, Left and Right fold missions, and the deck's next card is a button.
- A polite live region says what changed: new questions, finished missions, the Captain's state.
- Swarms over 30 agents render only the rows in view.