Skip to content
Shaken UI
Sign in

Queue

Save

An agent's todo list split into collapsible To do and Done sections with counts, where items glide to their new place when their status changes.

Category
AI elements
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Queue preview

Fix duplicate charges

  • Reproduce the duplicate charge, in progress

    Replay event evt_3Pq from staging

  • Find where events are deduplicated, to do

  • Add an idempotency key to the handler, to do

  • Write tests for duplicate events, to do

  • Update the runbook, to do

    Installation

    npx @shakenui/cli add queue

    Review the plan first. A dry run lists every file and package without changing anything:

    npx @shakenui/cli add queue --dry-run

    Usage

    queue-example.tsx
    import { Queue } from "@/components/shaken/agent/queue";
    
    export default function QueueExample() {
      return (
        <Queue
          className="max-w-sm"
          title="Tasks"
          items={[
            { id: "1", label: "Add a retry to the payment webhook", status: "active", detail: "api/webhooks/payment.ts" },
            { id: "2", label: "Write tests for duplicate events", status: "pending" },
            { id: "3", label: "Update the runbook", status: "pending" },
            { id: "4", label: "Reproduce the duplicate charge", status: "done", meta: "2m 10s" },
            { id: "5", label: "Find where events are deduplicated", status: "done", meta: "48s" },
          ]}
        />
      );
    }

    API

    PropTypeDefaultDescription
    items{ id, label, status, detail?, meta?, activity? }[]—status is pending, active (being worked on, shown with a live mark), or done.
    onStatusChange(id, done) => void—Renders a checkbox on each row so the reader can tick items off or reopen them. Without it only the agent moves items.
    titleReactNode—Heading above both sections.
    todoLabel / doneLabelReactNode"To do" / "Done"Section names.
    defaultOpen("todo" | "done")[]["todo", "done"]Sections that start open.
    emptyLabelReactNode"Nothing left to do"Shown in an empty To do section.

    Accessibility

    • Each section header is a Base UI Collapsible trigger with aria-expanded, showing its name and count in text.
    • Checkboxes are Base UI Checkbox (role="checkbox", Space toggles) labeled by the row text. When a ticked row moves to the other section, keyboard focus moves with it to its checkbox.
    • Without checkboxes, each row has a screen-reader status (to do, in progress, done); glyphs and marks are decorative.
    • Rows move with a transform only (FLIP via the Web Animations API), measured relative to the list; with reduced motion they jump to their new place.

    Files

    Installed into src/components/shaken, or components/shaken when the project has no src directory.

    • src/components/shaken/agent/queue.tsxqueue
    • Also installs agent-state@0.1.0registry dependency
    • Also installs step-list@0.3.0registry dependency
    • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

    Source

    The exact source the CLI installs, from /r/items/react/queue/0.1.0.json.

    agent/queue.tsxShow
    agent/queue.tsx
    "use client";
    
    import { Checkbox } from "@base-ui/react/checkbox";
    import { Collapsible } from "@base-ui/react/collapsible";
    import { type ComponentProps, type ReactNode, useId, useLayoutEffect, useRef } from "react";
    import { type AgentActivity, AgentMark } from "./agent-state";
    import { StatusGlyph } from "./step-list";
    
    function cx(...classes: Array<string | false | null | undefined>) {
      return classes.filter(Boolean).join(" ");
    }
    
    const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
    
    export type QueueItemStatus = "pending" | "active" | "done";
    
    export interface QueueItem {
      id: string;
      label: ReactNode;
      /** pending waits in "To do", active is being worked on now, done moves to "Done". */
      status: QueueItemStatus;
      /** A secondary line, such as the file or the result. */
      detail?: ReactNode;
      /** Right-aligned metadata, for example a duration. */
      meta?: ReactNode;
      /** Which Agent State mark moves while the item is active. @default "working" */
      activity?: AgentActivity;
    }
    
    export interface QueueProps extends Omit<ComponentProps<"section">, "children" | "title"> {
      items: QueueItem[];
      /** Heading above both sections. Leave it out when the surrounding panel already names the list. */
      title?: ReactNode;
      /**
       * Renders a checkbox on each row so the reader can tick items off or reopen them. Without it
       * the rows show status glyphs and only the agent moves items.
       */
      onStatusChange?: (id: string, done: boolean) => void;
      /** @default "To do" */
      todoLabel?: ReactNode;
      /** @default "Done" */
      doneLabel?: ReactNode;
      /** Which sections start open. @default ["todo", "done"] */
      defaultOpen?: Array<"todo" | "done">;
      /** Shown in an empty "To do" section. @default "Nothing left to do" */
      emptyLabel?: ReactNode;
    }
    
    /**
     * The agent's todo list in two collapsible sections, "To do" and "Done", each with a count.
     * When an item changes status it glides from its old row to its new one, and the rows around
     * it close the gap, so the eye can follow what moved. Instant with reduced motion.
     */
    export function Queue({
      items,
      title,
      onStatusChange,
      todoLabel = "To do",
      doneLabel = "Done",
      defaultOpen = ["todo", "done"],
      emptyLabel = "Nothing left to do",
      className,
      ...props
    }: QueueProps) {
      const todo = items.filter((item) => item.status !== "done");
      const done = items.filter((item) => item.status === "done");
      const root = useRef<HTMLElement>(null);
      const rows = useRef(new Map<string, HTMLElement>());
      const titleId = useId();
    
      useFlip(root, rows, items);
    
      // A ticked row remounts in the other section; keep keyboard focus on its checkbox there.
      const refocus = useRef<string | null>(null);
      useLayoutEffect(() => {
        const id = refocus.current;
        refocus.current = null;
        if (!id) return;
        rows.current.get(id)?.querySelector<HTMLElement>("[role=checkbox]")?.focus({ preventScroll: true });
      }, [items]);
      const handleStatusChange = onStatusChange
        ? (id: string, done: boolean) => {
            if (rows.current.get(id)?.contains(document.activeElement)) refocus.current = id;
            onStatusChange(id, done);
          }
        : undefined;
    
      const register = (id: string) => (node: HTMLElement | null) => {
        if (node) rows.current.set(id, node);
        else rows.current.delete(id);
      };
    
      return (
        <section
          ref={root}
          aria-labelledby={title != null ? titleId : undefined}
          aria-label={title == null ? "Queue" : undefined}
          className={cx(
            "w-full overflow-hidden rounded-xl border border-zinc-950/10 bg-white text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
            "dark:border-white/10 dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
            className,
          )}
          {...props}
        >
          {title != null ? (
            <h3 id={titleId} className="border-b border-zinc-950/[0.07] px-4 py-3 text-sm font-semibold dark:border-white/[0.08]">
              {title}
            </h3>
          ) : null}
          <QueueSection label={todoLabel} count={todo.length} defaultOpen={defaultOpen.includes("todo")}>
            {todo.length ? (
              todo.map((item) => <QueueRow key={item.id} ref={register(item.id)} item={item} onStatusChange={handleStatusChange} />)
            ) : (
              <li className="px-2.5 py-2 text-sm text-zinc-500">{emptyLabel}</li>
            )}
          </QueueSection>
          <QueueSection label={doneLabel} count={done.length} defaultOpen={defaultOpen.includes("done")} divided>
            {done.map((item) => (
              <QueueRow key={item.id} ref={register(item.id)} item={item} onStatusChange={handleStatusChange} />
            ))}
          </QueueSection>
        </section>
      );
    }
    
    function QueueSection({
      label,
      count,
      defaultOpen,
      divided = false,
      children,
    }: {
      label: ReactNode;
      count: number;
      defaultOpen: boolean;
      divided?: boolean;
      children: ReactNode;
    }) {
      return (
        <Collapsible.Root defaultOpen={defaultOpen} className={divided ? "border-t border-zinc-950/[0.07] dark:border-white/[0.08]" : undefined}>
          <Collapsible.Trigger
            className={cx(
              "group flex h-10 w-full cursor-pointer items-center gap-1.5 px-2.5 text-left text-xs font-medium select-none",
              "text-zinc-500 transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
              "hover:bg-zinc-950/[0.03] hover:text-zinc-950 dark:hover:bg-white/[0.04] dark:hover:text-white",
              "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
            )}
          >
            <svg
              aria-hidden="true"
              viewBox="0 0 16 16"
              fill="none"
              className={`size-4 shrink-0 text-zinc-400 transition-[rotate,color] duration-220 ${ease} group-hover:text-current group-data-[panel-open]:rotate-90 motion-reduce:transition-none dark:text-zinc-500`}
            >
              <path d="m6.25 4.5 3.5 3.5-3.5 3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            <span className="text-zinc-950 dark:text-white">{label}</span>
            <span
              key={count}
              className={`font-mono tabular-nums transition-[opacity,translate] duration-200 ${ease} starting:-translate-y-0.5 starting:opacity-0 motion-reduce:transition-none`}
            >
              {count}
            </span>
          </Collapsible.Trigger>
          <Collapsible.Panel
            data-queue-panel=""
            className={cx(
              "h-(--collapsible-panel-height) overflow-hidden",
              `transition-[height,opacity] duration-220 ${ease} motion-reduce:transition-none`,
              "data-[starting-style]:h-0 data-[starting-style]:opacity-0",
              "data-[ending-style]:h-0 data-[ending-style]:opacity-0 data-[ending-style]:duration-180",
            )}
          >
            <ul className="grid px-1.5 pb-1.5">{children}</ul>
          </Collapsible.Panel>
        </Collapsible.Root>
      );
    }
    
    function QueueRow({
      ref,
      item,
      onStatusChange,
    }: {
      ref: (node: HTMLElement | null) => void;
      item: QueueItem;
      onStatusChange?: (id: string, done: boolean) => void;
    }) {
      const done = item.status === "done";
      const active = item.status === "active";
      const labelId = useId();
    
      return (
        <li
          ref={ref}
          data-status={item.status}
          className={cx(
            "relative grid grid-cols-[1rem_minmax(0,1fr)_auto] items-start gap-x-2.5 rounded-lg px-2.5 py-2",
            "transition-[background-color] duration-200 motion-reduce:transition-none",
            active ? "bg-zinc-950/[0.04] dark:bg-white/[0.06]" : "",
          )}
        >
          <span className="flex h-5 items-center justify-center">
            {onStatusChange ? (
              <Checkbox.Root
                checked={done}
                onCheckedChange={(checked) => onStatusChange(item.id, checked)}
                aria-labelledby={labelId}
                className={cx(
                  "flex size-4 cursor-pointer items-center justify-center rounded-[5px] border",
                  "border-zinc-950/25 bg-white text-white transition-[background-color,border-color] duration-150 ease-out motion-reduce:transition-none",
                  "hover:border-zinc-950/40 data-[checked]:border-zinc-950 data-[checked]:bg-zinc-950",
                  "dark:border-white/25 dark:bg-black dark:text-black dark:hover:border-white/40 dark:data-[checked]:border-white dark:data-[checked]:bg-white",
                  "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
                )}
              >
                <Checkbox.Indicator keepMounted className="flex data-[unchecked]:hidden">
                  <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className="size-3">
                    <path
                      d="m3.75 8.25 2.75 2.75 5.75-6"
                      pathLength={1}
                      strokeDasharray="1"
                      className={`[stroke-dashoffset:0] transition-[stroke-dashoffset] duration-200 ${ease} starting:[stroke-dashoffset:1] motion-reduce:transition-none`}
                    />
                  </svg>
                </Checkbox.Indicator>
              </Checkbox.Root>
            ) : active ? (
              <AgentMark aria-hidden="true" activity={item.activity ?? "working"} size={16} className="text-zinc-950 dark:text-white" />
            ) : (
              <StatusGlyph key={item.status} kind={done ? "success" : "queued"} />
            )}
          </span>
          <div className="min-w-0">
            <p
              id={labelId}
              className={cx(
                "text-sm leading-5 break-words transition-colors duration-200 motion-reduce:transition-none",
                done ? "text-zinc-500 line-through decoration-zinc-500/50" : active ? "font-medium text-zinc-950 dark:text-white" : "text-zinc-950 dark:text-white",
              )}
            >
              {item.label}
              {!onStatusChange || active ? <span className="sr-only">, {done ? "done" : active ? "in progress" : "to do"}</span> : null}
            </p>
            {item.detail != null ? <p className="mt-0.5 text-xs text-zinc-500">{item.detail}</p> : null}
          </div>
          {item.meta != null ? <span className="pt-0.5 font-mono text-[11px] leading-5 text-zinc-500 tabular-nums">{item.meta}</span> : <span />}
        </li>
      );
    }
    
    /**
     * Moves each row from where it was to where it is now with a transform, after React has
     * placed it. Positions are measured relative to the list itself, so scrolling the page between
     * updates does not cause a jump. Rows that were hidden in a closed section simply appear.
     */
    function useFlip(root: { current: HTMLElement | null }, rows: { current: Map<string, HTMLElement> }, items: QueueItem[]) {
      const last = useRef(new Map<string, { x: number; y: number }>());
      const previousItems = useRef(items);
    
      // Snapshot where every row is before React applies the new order.
      if (previousItems.current !== items && root.current) {
        last.current = measure(root.current, rows.current);
      }
      previousItems.current = items;
    
      useLayoutEffect(() => {
        const container = root.current;
        if (!container) return;
        const next = measure(container, rows.current);
        const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
        if (!reduce) {
          for (const [id, to] of next) {
            const from = last.current.get(id);
            const node = rows.current.get(id);
            if (!from || !node) continue;
            const dx = from.x - to.x;
            const dy = from.y - to.y;
            if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;
            // A row crossing from one section to the other must not be clipped by its panel on the way.
            const panel = node.closest<HTMLElement>("[data-queue-panel]");
            if (panel) {
              lifted.set(panel, (lifted.get(panel) ?? 0) + 1);
              panel.style.overflow = "visible";
            }
            const animation = node.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: "translate(0, 0)" }], {
              duration: Math.min(480, 260 + Math.abs(dy) * 0.4),
              easing: "cubic-bezier(0.23, 1, 0.32, 1)",
            });
            const settle = () => {
              if (!panel) return;
              const left = (lifted.get(panel) ?? 1) - 1;
              lifted.set(panel, left);
              if (left <= 0) panel.style.overflow = "";
            };
            animation.addEventListener("finish", settle, { once: true });
            animation.addEventListener("cancel", settle, { once: true });
          }
        }
        last.current = next;
      }, [items, root, rows]);
    }
    
    /** Panels whose clipping is lifted, with the number of row animations still running in each. */
    const lifted = new WeakMap<HTMLElement, number>();
    
    function measure(container: HTMLElement, rows: Map<string, HTMLElement>) {
      const origin = container.getBoundingClientRect();
      const positions = new Map<string, { x: number; y: number }>();
      for (const [id, node] of rows) {
        const rect = node.getBoundingClientRect();
        // Rows inside a closed or closing section have no box; they should not fly in from it.
        if (!rect.height || (node.checkVisibility && !node.checkVisibility({ visibilityProperty: true }))) continue;
        positions.set(id, { x: rect.left - origin.left, y: rect.top - origin.top });
      }
      return positions;
    }