Skip to content
Shaken UI
Sign in

Activity Pill

Save

A compact black pill for a running agent task, showing a status glyph, a short status and a live clock, that springs open into a card with the steps and actions and springs back.

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

Preview

Activity Pill preview

Installation

npx @shakenui/cli add activity-pill

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

npx @shakenui/cli add activity-pill --dry-run

Usage

activity-pill-example.tsx
"use client";

import { useState } from "react";
import { ActivityPill } from "@/components/shaken/agent/activity-pill";

export default function ActivityPillExample() {
  // Fixed once on mount so the clock reads as a run that started a while ago.
  const [startedAt] = useState(() => Date.now() - 84_000);

  return (
    <div className="grid min-h-80 w-full max-w-md content-start">
      <ActivityPill
        title="Refactoring the auth middleware"
        summary="Refactoring auth"
        status="running"
        statusText="Step 3 of 5"
        startedAt={startedAt}
        steps={[
          { id: "read", label: "Read 12 files in src/auth", status: "done", meta: "4s" },
          { id: "plan", label: "Planned the session token change", status: "done", meta: "11s" },
          { id: "edit", label: "Editing middleware.ts", status: "running" },
          { id: "test", label: "Run the auth test suite", status: "pending" },
          { id: "pr", label: "Open a pull request", status: "pending" },
        ]}
        actions={[
          { label: "Stop", variant: "danger" },
          { label: "Open run", variant: "primary" },
        ]}
      />
    </div>
  );
}

States

Every state, rendered from local fixture data.

Activity Pill states
Queued
Update the billing docs: Waiting to start
Running
Needs approval
Delete 3 stale branches: Waiting for your approval
Done
Translate the onboarding copy: Finished
Failed
Deploy preview for #482: Stopped with an error

API

PropTypeDefaultDescription
titleReactNode—What the agent is doing. Heads the open card.
status"queued" | "running" | "needs-approval" | "done" | "failed"—The task state.
summaryReactNodetitle while running, the status otherwiseShort text in the pill.
statusTextReactNodea sentence for the statusOne line under the title in the card.
startedAt / endedAtnumber | Date—Shows a live m:ss clock; endedAt freezes it.
steps{ id, label, status, meta? }[]—Steps listed in the card. Step status is pending, running, done or failed.
detailReactNode—Extra content above the actions, such as the command waiting for approval.
actions{ label, onSelect?, variant?, collapse? }[]—Buttons at the foot of the card. Variant is primary, secondary or danger; they collapse the card unless collapse is false.
open / defaultOpen / onOpenChangebooleanfalseWhether the card is open.
align"start" | "center" | "end""center"Which edge the pill and card hang from.
widthnumber340Width of the open card in pixels; never wider than the space available.

Accessibility

  • The pill is a button with aria-expanded and aria-controls; Enter or Space opens the card and moves focus to its header.
  • The open card is a labelled region. Its header is a Collapse button; Escape or a press outside also closes it, and focus returns to the pill.
  • The closed card is inert and the open pill is inert, so only the visible one is in the tab order.
  • Status changes are announced through a polite live region; the clock is aria-hidden. Each step carries its status in text for screen readers.
  • Under reduced motion the pill and card swap without the spring, the blur or any travel.

Files

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

  • src/components/shaken/agent/activity-pill.tsxactivity-pill
  • Also installs dot-loader@0.1.0registry dependency
  • npm packages: motion@^14.14.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/activity-pill/0.1.0.json.

agent/activity-pill.tsxShow
agent/activity-pill.tsx
"use client";

import { animate, motion, useMotionValue, useReducedMotion, useTransform } from "motion/react";
import {
  type ComponentProps,
  type ReactNode,
  useCallback,
  useEffect,
  useId,
  useLayoutEffect,
  useRef,
  useState,
} from "react";
import { DotGrid } from "./dot-loader";

/*
 * Activity pill: a compact black pill for one running agent task, like a live activity.
 * Pressing it springs open into a card with the steps and actions, and springs back.
 *
 * The morph is a clip: the card is laid out once at its open size and a spring drives the
 * `clip-path` from the pill's rectangle to the full card, so nothing reflows and text never
 * stretches. A second clipped layer one pixel larger draws the hairline. Contents cross-fade
 * with a short blur. Under reduced motion the pill and card swap without travel.
 */

export type ActivityStatus = "queued" | "running" | "needs-approval" | "done" | "failed";
export type ActivityStepStatus = "pending" | "running" | "done" | "failed";

export interface ActivityStep {
  id: string;
  label: ReactNode;
  status: ActivityStepStatus;
  /** Short trailing detail in mono, for example a duration or a file count. */
  meta?: ReactNode;
}

export interface ActivityAction {
  label: string;
  onSelect?: () => void;
  /** `primary` is the white button; use it once. */
  variant?: "primary" | "secondary" | "danger";
  /** Collapses the card after the action runs. Defaults to true. */
  collapse?: boolean;
}

export interface ActivityPillProps extends Omit<ComponentProps<"div">, "children" | "title"> {
  /** What the agent is doing, for example "Refactoring the auth middleware". */
  title: ReactNode;
  status: ActivityStatus;
  /** Short text in the pill. Defaults to the title while running, and to the status otherwise. */
  summary?: ReactNode;
  /** One line under the title in the card. Defaults to a sentence for the status. */
  statusText?: ReactNode;
  /** When the task started, as epoch milliseconds or a Date. Shows a live clock. */
  startedAt?: number | Date;
  /** When the task ended. Freezes the clock. */
  endedAt?: number | Date;
  steps?: ActivityStep[];
  /** Extra content in the card above the actions, such as the command waiting for approval. */
  detail?: ReactNode;
  actions?: ActivityAction[];
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  /** Which edge the pill and card hang from. */
  align?: "start" | "center" | "end";
  /** Width of the open card in pixels. It never exceeds the available width. */
  width?: number;
}

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const PILL_H = 36;
const RADIUS = 18;

const defaultSummary: Record<Exclude<ActivityStatus, "running">, string> = {
  queued: "Queued",
  "needs-approval": "Needs approval",
  done: "Done",
  failed: "Failed",
};

const defaultStatusText: Record<ActivityStatus, string> = {
  queued: "Waiting to start",
  running: "Working",
  "needs-approval": "Waiting for your approval",
  done: "Finished",
  failed: "Stopped with an error",
};

const statusTone: Record<ActivityStatus, string> = {
  queued: "text-zinc-400",
  running: "text-white",
  "needs-approval": "text-amber-400",
  done: "text-emerald-400",
  failed: "text-red-400",
};

function toMs(value: number | Date | undefined) {
  return value instanceof Date ? value.getTime() : value;
}

function clock(ms: number) {
  const s = Math.max(0, Math.floor(ms / 1000));
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  const sec = String(s % 60).padStart(2, "0");
  return h ? `${h}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`;
}

/** A clock that writes itself once a second, so the pill does not re-render while it ticks. */
function Clock({ startedAt, endedAt, className }: { startedAt?: number; endedAt?: number; className?: string }) {
  const ref = useRef<HTMLSpanElement>(null);
  useEffect(() => {
    const el = ref.current;
    if (!el || startedAt == null) return;
    const write = () => {
      el.textContent = clock((endedAt ?? Date.now()) - startedAt);
    };
    write();
    if (endedAt != null) return;
    const id = setInterval(write, 1000);
    return () => clearInterval(id);
  }, [startedAt, endedAt]);
  if (startedAt == null) return null;
  return (
    <span ref={ref} aria-hidden="true" className={cx("font-mono text-xs tabular-nums", className)}>
      {clock((endedAt ?? startedAt) - startedAt)}
    </span>
  );
}

/** The status mark. Running, done and failed share one dot grid, so finishing gathers the dots into a check. */
function StatusGlyph({ status }: { status: ActivityStatus }) {
  const approval = status === "needs-approval";
  const grid = status === "running" ? "running" : status === "done" ? "done" : status === "failed" ? "failed" : "idle";
  return (
    <span className={cx("relative grid size-4 shrink-0 place-items-center transition-colors duration-200 motion-reduce:transition-none", statusTone[status])}>
      <span
        className={cx(
          "col-start-1 row-start-1 transition-[opacity,scale] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
          approval ? "scale-90 opacity-0" : "scale-100 opacity-100",
        )}
      >
        <DotGrid pattern="orbit" grid={3} size={14} status={grid} tone="inherit" />
      </span>
      <svg
        aria-hidden="true"
        viewBox="0 0 16 16"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        className={cx(
          "col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
          approval ? "scale-100 opacity-100" : "scale-90 opacity-0",
        )}
      >
        <circle cx="8" cy="8" r="6.25" />
        <path d="M6.5 5.75v4.5M9.5 5.75v4.5" />
      </svg>
    </span>
  );
}

function StepGlyph({ status }: { status: ActivityStepStatus }) {
  if (status === "running") return <DotGrid pattern="orbit" grid={3} size={12} status="running" tone="inherit" className="text-white" />;
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className={cx("size-3", status === "done" ? "text-emerald-400" : status === "failed" ? "text-red-400" : "text-white/30")}>
      {status === "done" ? <path d="m3.5 8.5 3 3 6-7" /> : status === "failed" ? <path d="m4.5 4.5 7 7m0-7-7 7" /> : <circle cx="8" cy="8" r="5.5" strokeDasharray="2 2.4" />}
    </svg>
  );
}

const stepLabel: Record<ActivityStepStatus, string> = { pending: "Pending", running: "In progress", done: "Done", failed: "Failed" };

const actionClass: Record<NonNullable<ActivityAction["variant"]>, string> = {
  primary: "bg-white text-black hover:bg-zinc-200",
  secondary: "bg-white/[0.08] text-white hover:bg-white/[0.14]",
  danger: "bg-white/[0.08] text-red-400 hover:bg-red-500/20 hover:text-red-300",
};

/**
 * A black pill for a running agent task that springs open into a detail card with steps and
 * actions. Enter or Space opens it; Escape, the header, or a press outside closes it.
 */
export function ActivityPill({
  title,
  status,
  summary,
  statusText,
  startedAt,
  endedAt,
  steps,
  detail,
  actions,
  open: openProp,
  defaultOpen = false,
  onOpenChange,
  align = "center",
  width = 340,
  className,
  style,
  ...props
}: ActivityPillProps) {
  const [uncontrolled, setUncontrolled] = useState(defaultOpen);
  const open = openProp ?? uncontrolled;
  const reduce = useReducedMotion();
  const id = useId();
  const panelId = `${id}-panel`;
  const titleId = `${id}-title`;

  const rootRef = useRef<HTMLDivElement>(null);
  const shellRef = useRef<HTMLDivElement>(null);
  const pillRef = useRef<HTMLButtonElement>(null);
  const rowRef = useRef<HTMLSpanElement>(null);
  const panelRef = useRef<HTMLDivElement>(null);
  const headerRef = useRef<HTMLButtonElement>(null);

  // Geometry, as motion values so the clip updates without re-rendering.
  const progress = useMotionValue(open ? 1 : 0);
  const pillW = useMotionValue(160);
  const shellW = useMotionValue(width);
  const shellH = useMotionValue(PILL_H);
  const [measured, setMeasured] = useState(false);

  const setOpen = useCallback(
    (next: boolean) => {
      if (openProp === undefined) setUncontrolled(next);
      onOpenChange?.(next);
    },
    [openProp, onOpenChange],
  );

  // Measure the pill row, the shell width and the card height, and follow changes.
  useLayoutEffect(() => {
    const row = rowRef.current;
    const shell = shellRef.current;
    const panel = panelRef.current;
    if (!row || !shell || !panel) return;
    const first = { current: true };
    const read = () => {
      const w = Math.min(row.offsetWidth, shell.offsetWidth);
      const sw = shell.offsetWidth;
      const h = Math.max(PILL_H, panel.offsetHeight);
      const spring = { type: "spring" as const, duration: 0.38, bounce: 0.12 };
      if (first.current || reduce) {
        pillW.set(w);
        shellW.set(sw);
        shellH.set(h);
      } else {
        // Width changes when the pill text changes; the card height when steps arrive.
        void animate(pillW, w, spring);
        shellW.set(sw);
        void animate(shellH, h, spring);
      }
      first.current = false;
      setMeasured(true);
    };
    read();
    if (typeof ResizeObserver === "undefined") return;
    const observer = new ResizeObserver(read);
    observer.observe(row);
    observer.observe(shell);
    observer.observe(panel);
    return () => observer.disconnect();
  }, [pillW, shellW, shellH, reduce]);

  // Spring the morph whenever open changes: about 380ms to settle with a slight overshoot opening,
  // a little quicker closing.
  useEffect(() => {
    const target = open ? 1 : 0;
    if (reduce) {
      progress.set(target);
      return;
    }
    const controls = animate(progress, target, open ? { type: "spring", duration: 0.4, bounce: 0.16 } : { type: "spring", duration: 0.34, bounce: 0.1 });
    return () => controls.stop();
  }, [open, reduce, progress]);

  // Focus follows the morph: into the card on open, back to the pill on close.
  const wasOpen = useRef(open);
  useEffect(() => {
    if (open && !wasOpen.current) headerRef.current?.focus({ preventScroll: true });
    if (!open && wasOpen.current && shellRef.current?.contains(document.activeElement)) pillRef.current?.focus({ preventScroll: true });
    wasOpen.current = open;
  }, [open]);

  // Press outside closes.
  useEffect(() => {
    if (!open) return;
    const onDown = (event: PointerEvent) => {
      if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
    };
    document.addEventListener("pointerdown", onDown);
    return () => document.removeEventListener("pointerdown", onDown);
  }, [open, setOpen]);

  const clipFor = (inset: number) => (values: number[]) => {
    const [p = 0, w = 0, sw = 0, sh = 0] = values;
    // Below 0 (the closing undershoot) the pill dips slightly smaller; above 1 is handled by scale.
    const q = Math.min(1, p);
    const spare = Math.max(0, sw - w);
    const left = align === "start" ? 0 : align === "end" ? spare : spare / 2;
    const right = spare - left;
    const l = left * (1 - q) + inset;
    const r = right * (1 - q) + inset;
    const b = Math.max(0, sh - PILL_H) * (1 - q) + inset;
    return `inset(${(inset).toFixed(2)}px ${r.toFixed(2)}px ${b.toFixed(2)}px ${l.toFixed(2)}px round ${RADIUS - inset}px)`;
  };
  const outerClip = useTransform([progress, pillW, shellW, shellH], clipFor(0));
  const innerClip = useTransform([progress, pillW, shellW, shellH], clipFor(1));
  const scale = useTransform(progress, (p) => (p > 1 ? 1 + (p - 1) * 0.35 : 1));
  // Contents cross-fade around the middle of the morph.
  const pillOpacity = useTransform(progress, [0, 0.35], [1, 0]);
  const panelOpacity = useTransform(progress, [0.3, 0.85], [0, 1]);
  const panelBlur = useTransform(progress, [0.3, 0.85], ["blur(4px)", "blur(0px)"]);
  const panelY = useTransform(progress, [0.3, 1], [-6, 0]);

  const pillText = summary ?? (status === "running" ? title : defaultSummary[status]);
  const start = toMs(startedAt);
  const end = toMs(endedAt);
  const origin = align === "start" ? "0% 0%" : align === "end" ? "100% 0%" : "50% 0%";

  return (
    <div
      ref={rootRef}
      data-status={status}
      data-open={open || undefined}
      className={cx("relative flex h-9", align === "start" ? "justify-start" : align === "end" ? "justify-end" : "justify-center", className)}
      style={{ zIndex: open ? 30 : undefined, ...style }}
      onKeyDown={(event) => {
        if (event.key === "Escape" && open) {
          event.stopPropagation();
          setOpen(false);
        }
      }}
      {...props}
    >
      {/* Status changes are announced; the clock is not. */}
      <span role="status" className="sr-only">
        {status === "running" ? null : <>{typeof title === "string" ? `${title}: ` : null}{defaultStatusText[status]}</>}
      </span>

      <div
        ref={shellRef}
        className={cx("pointer-events-none absolute top-0", align === "start" ? "left-0" : align === "end" ? "right-0" : "left-1/2 -translate-x-1/2")}
        style={{ width: `min(${width}px, 100%)`, minWidth: Math.min(width, 280) }}
      >
        <motion.div
          className="relative [filter:drop-shadow(0_10px_20px_rgb(0_0_0/0.18))_drop-shadow(0_1px_2px_rgb(0_0_0/0.2))] dark:[filter:none]"
          style={{ scale, transformOrigin: origin, height: shellH, visibility: measured ? "visible" : "hidden" }}
        >
          <motion.div aria-hidden="true" className="absolute inset-0 bg-zinc-950 dark:bg-white/[0.17]" style={{ clipPath: outerClip }} />
          <motion.div className="pointer-events-auto absolute inset-0 bg-zinc-950 text-white dark:bg-black" style={{ clipPath: innerClip }}>
            {/* The pill. */}
            <motion.div
              className={cx("absolute top-0 flex h-9", align === "start" ? "left-0" : align === "end" ? "right-0" : "inset-x-0 justify-center")}
              style={{ opacity: pillOpacity }}
            >
              <button
                ref={pillRef}
                type="button"
                aria-expanded={open}
                aria-controls={panelId}
                inert={open || undefined}
                onClick={() => setOpen(true)}
                className="group/pill h-9 max-w-full rounded-full outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-400"
              >
                <span ref={rowRef} className="inline-flex h-9 max-w-full items-center gap-2 pr-3.5 pl-2.5 transition-[background-color] duration-150 motion-reduce:transition-none">
                  <StatusGlyph status={status} />
                  <span className="min-w-0 truncate text-[13px] font-medium">{pillText}</span>
                  <Clock startedAt={start} endedAt={end} className="text-white/55" />
                </span>
              </button>
            </motion.div>

            {/* The card. */}
            <motion.div
              ref={panelRef}
              id={panelId}
              role="region"
              aria-labelledby={titleId}
              inert={!open || undefined}
              className="absolute inset-x-0 top-0"
              style={{ opacity: panelOpacity, filter: panelBlur, y: panelY }}
            >
              <button
                ref={headerRef}
                type="button"
                aria-label="Collapse"
                aria-expanded={open}
                aria-controls={panelId}
                onClick={() => setOpen(false)}
                className="flex w-full items-start gap-3 rounded-t-[18px] px-4 pt-4 pb-3 text-left outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-400"
              >
                <span className="mt-0.5">
                  <StatusGlyph status={status} />
                </span>
                <span className="min-w-0 flex-1">
                  <span id={titleId} className="block text-sm leading-5 font-semibold">
                    {title}
                  </span>
                  <span className={cx("block text-xs leading-5", status === "running" || status === "queued" ? "text-white/60" : statusTone[status])}>
                    {statusText ?? defaultStatusText[status]}
                  </span>
                </span>
                <Clock startedAt={start} endedAt={end} className="mt-0.5 text-white/55" />
              </button>

              {steps?.length ? (
                <ol className="mx-4 grid gap-0.5 border-t border-white/10 py-2.5">
                  {steps.map((step) => (
                    <li key={step.id} className="flex items-center gap-2.5 py-1">
                      <span className="grid size-4 shrink-0 place-items-center">
                        <StepGlyph status={step.status} />
                      </span>
                      <span className={cx("min-w-0 flex-1 truncate text-[13px] leading-5", step.status === "pending" ? "text-white/40" : step.status === "running" ? "text-white" : step.status === "failed" ? "text-red-400" : "text-white/65")}>
                        {step.label}
                        <span className="sr-only">, {stepLabel[step.status]}</span>
                      </span>
                      {step.meta != null ? <span className="font-mono text-xs text-white/40 tabular-nums">{step.meta}</span> : null}
                    </li>
                  ))}
                </ol>
              ) : null}

              {detail != null ? <div className="mx-4 mb-3 text-[13px] leading-5 text-white/70">{detail}</div> : null}

              {actions?.length ? (
                <div className="flex flex-wrap justify-end gap-2 border-t border-white/10 px-4 py-3">
                  {actions.map((action) => (
                    <button
                      key={action.label}
                      type="button"
                      onClick={() => {
                        action.onSelect?.();
                        if (action.collapse !== false) setOpen(false);
                      }}
                      className={cx(
                        "inline-flex h-8 items-center rounded-full px-3.5 text-[13px] font-medium whitespace-nowrap select-none",
                        "transition-[background-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.97] motion-reduce:transition-none",
                        "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-400",
                        actionClass[action.variant ?? "secondary"],
                      )}
                    >
                      {action.label}
                    </button>
                  ))}
                </div>
              ) : (
                <div className="h-1" />
              )}
            </motion.div>
          </motion.div>
        </motion.div>
      </div>
    </div>
  );
}