Aadi

Run Inbox

Backgrounds 1

About

Every agent run in one inbox: tabs for needs input, running and done, each run with its task, repo and last step, and Respond inline for the runs waiting on a decision.

Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Run Inbox to your project and fits it to your theme.

Code

How Run Inbox is used: the demo's code. The component's own source comes with a free account.

Usage.tsx

"use client"

import * as React from "react"
import { cn } from "@/lib/utils"
import { BackgroundRunData, BackgroundRunGlyph, BackgroundRunStatus, Button, Icon, IconNode, RunInbox, StepLine, UnreadDot, createIcon, isActive, keyOf, secondaryLine, useRunTime } from "@/components/ui/run-inbox"

const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"

/**
 * 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
 * phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
 * render white on dark pages. FitFrame fills the frame exactly instead.
 *
 * - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
 * - "crop": the content stays at full size from the top and fades out at the bottom. For text
 *   that streams in, where a changing scale would make the page breathe.
 *
 * `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
 * to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
 * shrinks evenly on both sides.
 *
 * Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
 * shorter than `hideBelow`, so a profile card shows the visual alone.
 */
function FitFrame({
  children,
  mode = "scale",
  hideBelow = 360,
  minWidth,
}: {
  children: React.ReactNode
  mode?: "scale" | "crop"
  hideBelow?: number
  minWidth?: string
}) {
  const content = React.useRef<HTMLDivElement>(null)
  const [cropped, setCropped] = React.useState(false)

  React.useLayoutEffect(() => {
    const el = content.current
    if (!el) return
    const measure = () => {
      const vw = window.innerWidth
      const vh = window.innerHeight
      el.toggleAttribute("data-fit-small", vh < hideBelow)
      // Layout sizes ignore the transform, so measuring never feeds back.
      const w = Math.max(el.offsetWidth, el.scrollWidth)
      const h = Math.max(el.offsetHeight, el.scrollHeight)
      const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
      el.style.transform = scale < 1 ? `scale(${scale})` : ""
      setCropped(mode === "crop" && h > vh + 1)
    }
    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(el)
    // Content that changes inside a fixed width box (a headline that cycles words) never resizes
    // the box itself, so changes below it measure again on the next frame.
    let frame = 0
    const mutations = new MutationObserver(() => {
      cancelAnimationFrame(frame)
      frame = requestAnimationFrame(measure)
    })
    mutations.observe(el, { subtree: true, childList: true, characterData: true })
    window.addEventListener("resize", measure)
    return () => {
      observer.disconnect()
      mutations.disconnect()
      cancelAnimationFrame(frame)
      window.removeEventListener("resize", measure)
    }
  }, [mode, hideBelow])

  const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
  return (
    <div
      className="flex w-full justify-center overflow-hidden"
      style={{
        height: "100dvh",
        alignItems: mode === "crop" ? "flex-start" : "center",
        maskImage: cropped ? fade : undefined,
        WebkitMaskImage: cropped ? fade : undefined,
      }}
    >
      <style>{FIT_CSS}</style>
      <div
        ref={content}
        className="w-full shrink-0"
        style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
      >
        {children}
      </div>
    </div>
  )
}

// The demo's times count back from the moment it renders. Read through `performance`, which
// Next.js allows while it prerenders a page; `Date.now()` during render fails the build there.
const demoNow = () => performance.timeOrigin + performance.now()

function fixtures(now: number): BackgroundRunData[] {
  return [
    {
      id: "r1",
      title: "Fix flaky checkout test",
      context: "tallyline/web · fix/checkout-flake",
      status: "needs-input",
      request: "Approve pnpm db:migrate --env preview",
      steps: { done: 3, total: 7 },
      startedAt: now - 192_000,
      unread: true,
    },
    {
      id: "r2",
      title: "Upgrade to Next.js 16.4",
      context: "tallyline/web · chore/next-16-4",
      status: "needs-input",
      request: "Delete src/middleware.ts?",
      steps: { done: 5, total: 9 },
      startedAt: now - 611_000,
      unread: true,
    },
    {
      id: "r3",
      title: "Research vector databases",
      context: "Deep research",
      status: "running",
      step: "Reading pgvector benchmarks on a 10M row table",
      startedAt: now - 134_000,
    },
    {
      id: "r4",
      title: "Add CSV export to the runs table",
      context: "tallyline/web · feat/csv-export",
      status: "done",
      summary: "4 files changed, 18 tests pass. PR #482 is ready.",
      durationMs: 402_000,
      unread: true,
    },
    {
      id: "r5",
      title: "Migrate auth to the new session store",
      context: "tallyline/api · chore/sessions",
      status: "failed",
      error: "Redis refused the connection. Check REDIS_URL, then retry.",
      durationMs: 71_000,
    },
    {
      id: "r6",
      title: "Write the Q3 usage report",
      context: "Analytics",
      status: "queued",
      queuePosition: 1,
    },
    {
      id: "r7",
      title: "Translate onboarding emails to German",
      context: "tallyline/emails · main",
      status: "done",
      summary: "6 templates translated and checked for length.",
      durationMs: 248_000,
    },
  ]
}

/* -------------------------------------------------------------------------------------------------
 * BackgroundRun (card)
 * -----------------------------------------------------------------------------------------------*/

interface BackgroundRunProps
  extends Omit<React.ComponentProps<"article">, "title" | "id">,
    Omit<BackgroundRunData, "id"> {
  id?: string
  onOpen?: () => void
  onCancel?: () => void
  onRetry?: () => void
  /** Primary action for `needs-input`. Defaults to `onOpen` labelled Respond. */
  onRespond?: () => void
  /** Replace the default actions. */
  actions?: React.ReactNode
}

function progressOf(run: Pick<BackgroundRunData, "progress" | "steps">) {
  if (run.progress !== undefined) return Math.max(0, Math.min(1, run.progress))
  if (run.steps && run.steps.total > 0) return Math.min(1, run.steps.done / run.steps.total)
  return undefined
}

/* -------------------------------------------------------------------------------------------------
 * Helpers
 * -----------------------------------------------------------------------------------------------*/

const STATUS_LABEL: Record<BackgroundRunStatus, string> = {
  queued: "Queued",
  running: "Running",
  "needs-input": "Needs input",
  done: "Done",
  failed: "Failed",
  cancelled: "Cancelled",
}

const iconNode: IconNode = [
  ["path", {"d":"M5.49 17.46A8.5 8.5 0 1 0 6.54 5.49"}],
  ["path", {"d":"m8.21 8.65-2.94-.26a2 2 0 0 1-1.82-2.16l.26-2.94"}],
]

const RotateCcwIcon: Icon = /* @__PURE__ */ createIcon("rotate-ccw", iconNode)

interface RunProgressProps extends React.ComponentProps<"div"> {
  /** 0 to 1. Undefined means indeterminate. */
  value?: number
  /** Accessible name. Default "Progress". */
  label?: string
}

/**
 * 2 px progress line. Determinate fills with a scaleX transform (280 ms, so jumps between steps
 * read as progress, not teleports). Indeterminate slides a third-width segment with the Web
 * Animations API; under reduced motion the segment sits still.
 */
function RunProgress({ value, label = "Progress", className, ...props }: RunProgressProps) {
  const segment = React.useRef<HTMLSpanElement>(null)
  const indeterminate = value === undefined

  React.useEffect(() => {
    const el = segment.current
    if (!indeterminate || !el || typeof el.animate !== "function") return
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
    const rtl = getComputedStyle(el).direction === "rtl"
    const from = rtl ? "100%" : "-100%"
    const to = rtl ? "-300%" : "300%"
    const animation = el.animate(
      [{ transform: `translateX(${from})` }, { transform: `translateX(${to})` }],
      {
        duration: 1600,
        iterations: Number.POSITIVE_INFINITY,
        easing: "cubic-bezier(0.77, 0, 0.175, 1)",
      },
    )
    return () => animation.cancel()
  }, [indeterminate])

  return (
    <div
      role="progressbar"
      aria-label={label}
      aria-valuemin={0}
      aria-valuemax={100}
      aria-valuenow={indeterminate ? undefined : Math.round(value * 100)}
      data-slot="run-progress"
      data-indeterminate={indeterminate ? "" : undefined}
      className={cn("bg-(color:--chatcn-alpha-200) relative h-0.5 overflow-hidden", className)}
      {...props}
    >
      {indeterminate ? (
        <span
          ref={segment}
          className="bg-(color:--chatcn-accent) absolute inset-y-0 start-1/3 w-1/3 rounded-full motion-reduce:opacity-40"
        />
      ) : (
        <span
          className={cn(
            "bg-(color:--chatcn-accent) absolute inset-0 origin-left rtl:origin-right",
            "ease-(--chatcn-ease-out) transition-transform duration-280 motion-reduce:transition-none",
          )}
          style={{ transform: `scaleX(${value})` }}
        />
      )}
    </div>
  )
}

/**
 * Card for a detached agent task: what it is, where it runs, the latest step, a 2 px progress
 * line on the bottom edge and Open or Cancel. Queued, running, needs input, done, failed and
 * cancelled each get their own glyph, line and actions.
 */
function BackgroundRun({
  id,
  title,
  status,
  context,
  step,
  request,
  summary,
  error,
  progress,
  steps,
  queuePosition,
  startedAt,
  durationMs,
  unread,
  onOpen,
  onCancel,
  onRetry,
  onRespond,
  actions,
  className,
  ...props
}: BackgroundRunProps) {
  const run: BackgroundRunData = {
    id: id ?? "",
    title,
    status,
    context,
    step,
    request,
    summary,
    error,
    progress,
    steps,
    queuePosition,
    startedAt,
    durationMs,
  }
  const time = useRunTime(run)
  const value = progressOf(run)
  const line = secondaryLine(run)
  const titleId = React.useId()
  // One running signal per card: the spinner. The bar only shows progress it can measure, so an
  // unknown amount never adds a second, sliding motion beside the spinner.
  const showBar =
    status === "queued" ||
    ((status === "running" || status === "needs-input") && value !== undefined)

  return (
    <article
      aria-labelledby={titleId}
      data-slot="background-run"
      data-run-status={status}
      className={cn(
        "rounded-(--chatcn-radius-lg) bg-(color:--chatcn-card) shadow-(--chatcn-shadow-sm) relative flex flex-col overflow-hidden",
        "text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) forced-colors:outline-1 forced-colors:outline-solid",
        className,
      )}
      {...props}
    >
      <div className="flex flex-col gap-3 p-4 pb-3">
        <div className="flex min-w-0 items-start gap-2.5">
          <span className="mt-0.5">
            <BackgroundRunGlyph status={status} />
          </span>
          <div className="flex min-w-0 flex-1 flex-col gap-0.5">
            <div className="flex min-w-0 items-baseline gap-2">
              <h3 id={titleId} className="flex min-w-0 flex-1 items-center gap-2 font-medium">
                {/* Truncate on a span: headings can inherit text-wrap: balance, which beats nowrap. */}
                <span className="min-w-0 truncate">{title}</span>
                {unread ? (
                  <>
                    <UnreadDot />
                    <span className="sr-only">, unread</span>
                  </>
                ) : null}
              </h3>
              {time ? (
                <span className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) shrink-0 tabular-nums">
                  {time}
                </span>
              ) : null}
            </div>
            <div className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) flex min-w-0 items-center gap-1.5">
              <span
                aria-live="polite"
                className={cn(
                  "shrink-0 font-medium",
                  status === "failed"
                    ? "text-(color:--chatcn-red)"
                    : status === "needs-input"
                      ? "text-(color:--chatcn-fg)"
                      : "text-(color:--chatcn-fg-muted)",
                )}
              >
                {STATUS_LABEL[status]}
              </span>
              {steps && status !== "queued" ? (
                <>
                  <span aria-hidden="true">·</span>
                  <span className="shrink-0 tabular-nums">
                    {Math.min(steps.done, steps.total)} of {steps.total}
                  </span>
                </>
              ) : null}
              {context ? (
                <>
                  <span aria-hidden="true">·</span>
                  <span className="min-w-0 truncate font-mono">{context}</span>
                </>
              ) : null}
            </div>
          </div>
        </div>

        {line ? (
          <div
            data-slot="background-run-line"
            className={cn(
              "text-[0.8125rem]/[1.25rem] flex min-w-0 items-start gap-2 ps-6.5",
              status === "needs-input" ? "text-(color:--chatcn-fg)" : "text-(color:--chatcn-fg-muted)",
            )}
          >
            {status === "needs-input" ? (
              // Sits in the gutter, so the text still lines up with the title.
              <span
                aria-hidden="true"
                className="bg-(color:--chatcn-fg) my-[3px] -ms-2.5 w-0.5 shrink-0 self-stretch rounded-full"
              />
            ) : null}
            <StepLine
              stepKey={keyOf(line, status)}
              wrap={status !== "running" && status !== "queued"}
              className="flex-1"
            >
              {line}
            </StepLine>
          </div>
        ) : null}

        <div className="flex items-center justify-end gap-1.5 ps-6.5 empty:hidden">
          {actions ?? (
            <>
              {isActive(status) || status === "queued"
                ? onCancel && (
                    <Button size="sm" onClick={onCancel}>
                      Cancel
                    </Button>
                  )
                : null}
              {status === "failed" && onRetry ? (
                <Button size="sm" onClick={onRetry}>
                  <RotateCcwIcon />
                  Retry
                </Button>
              ) : null}
              {status === "needs-input" && (onRespond ?? onOpen) ? (
                <Button size="sm" variant="solid" onClick={onRespond ?? onOpen}>
                  Respond
                </Button>
              ) : onOpen ? (
                <Button size="sm" variant="outline" onClick={onOpen}>
                  Open
                </Button>
              ) : null}
            </>
          )}
        </div>
      </div>

      {showBar ? (
        <RunProgress
          value={status === "queued" ? 0 : value}
          label={typeof title === "string" ? `${title} progress` : "Run progress"}
          className="absolute inset-x-0 bottom-0"
        />
      ) : null}
    </article>
  )
}

function RunInboxDemo() {
  const [now] = React.useState(() => demoNow())
  const [runs, setRuns] = React.useState(() => fixtures(now))
  const [selectedId, setSelectedId] = React.useState("r1")
  const selected = runs.find((r) => r.id === selectedId)
  const markRead = (id: string) =>
    setRuns((prev) => prev.map((r) => (r.id === id ? { ...r, unread: false } : r)))

  return (
    <div className="grid w-full max-w-4xl items-start gap-4 md:grid-cols-[minmax(0,22rem)_minmax(0,1fr)]">
      <RunInbox
        runs={runs}
        selectedId={selectedId}
        onOpen={(run) => {
          setSelectedId(run.id)
          markRead(run.id)
        }}
        onMarkAllRead={() => setRuns((prev) => prev.map((r) => ({ ...r, unread: false })))}
      />
      {selected ? (
        <BackgroundRun
          key={selected.id}
          {...selected}
          unread={false}
          onOpen={() => {}}
          onCancel={() => {}}
          onRespond={() =>
            setRuns((prev) =>
              prev.map((r) =>
                r.id === selected.id
                  ? {
                      ...r,
                      status: "running",
                      step: "Running the approved step",
                      request: undefined,
                    }
                  : r,
              ),
            )
          }
          onRetry={() => {}}
          className="md:mt-[5.25rem]"
        />
      ) : null}
    </div>
  )
}

/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
  return (
    <p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
      {children}{" "}
      <a
        href={`https://chatcn.dev/docs/components/${slug}`}
        target="_blank"
        rel="noopener"
        className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
      >
        chatcn.dev
      </a>
    </p>
  )
}

/** The kit's own example, framed for the 21st preview. */
export default function RunInboxPreview() {
  return (
    <FitFrame minWidth="38rem">
      <div className="flex w-full flex-col items-center justify-center gap-4 p-6">
        <div className="flex w-full max-w-2xl justify-center">
          <RunInboxDemo />
        </div>
        <MoreOn slug="run-inbox">Every agent run in one inbox, by status. On</MoreOn>
      </div>
    </FitFrame>
  )
}

More by Aadi

View all
  • Dither Orb

    Dither Orb

    12
  • Audio Visualizer

    Audio Visualizer

    9
  • Voice Orb

    Voice Orb

    8
  • Agent Lanes

    Agent Lanes

    6
  • Computer View

    Computer View

    3
  • Waveform

    Waveform

    2
  • Reasoning

    Reasoning

    2
  • Voice Session

    Voice Session

    1

More in Backgrounds

View all
  • Elegant Dark Pattern

    Elegant Dark Pattern

    885
  • Background snippets

    Background snippets

    240
  • Light theme Tailwind CSS Background Snippet

    Light theme Tailwind CSS Background Snippet

    245
  • Tailwind CSS Background Snippet

    Tailwind CSS Background Snippet

    597
  • Gradient Backgrounds

    Gradient Backgrounds

    28
  • Background Components

    Background Components

    242
  • Jade Sky

    Jade Sky

    102
  • LivingOrigami bg

    LivingOrigami bg

    156

Explore more

Part of chatcn — browse the full library on 21st.dev.