{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"job-queue","type":"registry:component","title":"Job queue","description":"A worker pool’s jobs grouped by what needs you: reviews first, each job’s status ring doubling as its clock, approvals and retries that call your server.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency","https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/job-queue.tsx","type":"registry:component","content":"// Hairline UI · job-queue · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { Check, ChevronDown, Copy, Pause, Play, X } from \"lucide-react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\n\n/* ─────────────────────────────────────────────────────────\n * JOB QUEUE: a worker pool's jobs, grouped by what needs you\n *\n *   groups    Needs review first, then Running, Failed, Queued,\n *             Completed; each a quiet label with its count. When a\n *             job moves to another group, its row glides there\n *   the clock each job's status mark is also its clock: a running\n *             job's ring fills with its progress, a review's amber\n *             ring drains as its window runs out, a failed job's red\n *             ring fills until it retries by itself. The draining\n *             and filling are single linear animations, so nothing\n *             re-renders to move them\n *   workers   the pool's workers as hairline slots in the header,\n *             each busy one filled to its job's progress\n *   act       Approve, Reject, Retry and Cancel call your async\n *             functions and show a pending state until you update\n *             the jobs; rows you remove fold away\n *   details   a payload or a stack opens in place under its row,\n *             with Copy\n *\n * Laid out for the card's own width: on a narrow card the buttons\n * take a line of their own under the reason; on a wide one they sit\n * at the end of the row. The jobs you pass are the truth: the\n * component never changes a job's status itself.\n * ───────────────────────────────────────────────────────── */\n\nexport type JobStatus = \"running\" | \"approval\" | \"queued\" | \"failed\" | \"completed\";\n\nexport interface JobItem {\n  id: string;\n  /** What the job is, e.g. \"billing.refund-exec\". */\n  title: string;\n  queue?: string;\n  status: JobStatus;\n  /** 0 to 100, for running jobs. */\n  progress?: number;\n  /** When it started (ms since epoch), for the running clock. */\n  startedAt?: number;\n  /** How long it took, for completed jobs. */\n  durationMs?: number;\n  approval?: {\n    reason: string;\n    /** When the review window closes (ms since epoch). */\n    expiresAt?: number;\n    /** When it was asked for (ms since epoch); sets how full the draining ring starts. */\n    requestedAt?: number;\n  };\n  error?: {\n    message: string;\n    stack?: string;\n    attempt?: number;\n    maxAttempts?: number;\n    /** When it will retry by itself (ms since epoch). */\n    retryAt?: number;\n    /** How long the backoff is; with retryAt it sets how full the ring starts, alone it counts from when the job first shows as failed. */\n    backoffMs?: number;\n  };\n  payload?: Record<string, unknown> | string;\n}\n\nexport interface JobQueueProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onChange\"> {\n  /** The pool or queue's name. */\n  title?: string;\n  jobs: JobItem[];\n  /** How many workers the pool has. */\n  concurrency?: number;\n  /** Jobs finished per second. */\n  throughput?: number;\n  isPaused?: boolean;\n  onTogglePause?: (paused: boolean) => void;\n  onApprove?: (jobId: string) => Promise<unknown> | void;\n  onReject?: (jobId: string) => Promise<unknown> | void;\n  onRetry?: (jobId: string) => Promise<unknown> | void;\n  onCancel?: (jobId: string) => Promise<unknown> | void;\n}\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40\";\nconst PRESS = \"transition-[background-color,color,box-shadow,scale] duration-200 active:scale-[0.97] motion-reduce:active:scale-100\";\n/** The mark: 2px hairlines every 4px, counted up from the bottom. */\nconst RULE = \"repeating-linear-gradient(to top, #000 0 2px, transparent 2px 4px)\";\nconst ORDER: JobStatus[] = [\"approval\", \"running\", \"failed\", \"queued\", \"completed\"];\nconst GROUP: Record<JobStatus, string> = { approval: \"Needs review\", running: \"Running\", failed: \"Failed\", queued: \"Queued\", completed: \"Completed\" };\nconst R = 8;\nconst C = 2 * Math.PI * R;\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst useReducedMotion = () =>\n  React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\n// The clock starts after hydration, so the server and the first client render agree and nothing reads the time while rendering.\nconst subscribeNothing = () => () => {};\nconst useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);\n\nconst clock = (ms: number) => {\n  const s = Math.max(0, Math.floor(ms / 1000));\n  return s >= 3600 ? `${Math.floor(s / 3600)}:${String(Math.floor((s % 3600) / 60)).padStart(2, \"0\")}:${String(s % 60).padStart(2, \"0\")}` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, \"0\")}`;\n};\nconst seconds = (ms: number) => (ms < 10_000 ? `${(ms / 1000).toFixed(1)}s` : clock(ms));\n\n/** A countdown on a ring: where it is now (0–1), where it ends, and how long until then. */\ntype Countdown = { from: number; to: number; ms: number; key: string };\n\nfunction countdownOf(job: JobItem, now: number, firstSeen: number): Countdown | null {\n  if (!now) return null;\n  if (job.status === \"approval\" && job.approval?.expiresAt) {\n    const start = job.approval.requestedAt ?? firstSeen;\n    const total = Math.max(1, job.approval.expiresAt - start);\n    const left = Math.max(0, job.approval.expiresAt - now);\n    return { from: left / total, to: 0, ms: left, key: `a${job.approval.expiresAt}` };\n  }\n  if (job.status === \"failed\" && (job.error?.retryAt || job.error?.backoffMs)) {\n    const at = job.error.retryAt ?? firstSeen + (job.error.backoffMs ?? 0);\n    const start = job.error.retryAt && job.error.backoffMs ? job.error.retryAt - job.error.backoffMs : firstSeen;\n    const total = Math.max(1, at - start);\n    const left = Math.max(0, at - now);\n    return { from: 1 - left / total, to: 1, ms: left, key: `f${at}` };\n  }\n  return null;\n}\n\n/**\n * The status mark, which is also the job's clock. Running: a ring filling with progress. Review: an amber ring draining\n * as the window closes. Failed: a red ring filling until the retry. A countdown runs as one linear animation of the\n * ring's dash, started from where it is now, so the per-second re-render never touches it.\n */\nfunction Glyph({ job, paused, countdown, reduced }: { job: JobItem; paused: boolean; countdown: Countdown | null; reduced: boolean }) {\n  const ring = React.useRef<SVGCircleElement>(null);\n  const counting = !!countdown && countdown.ms > 0 && !reduced;\n  const startFrom = countdown?.from ?? 0;\n  const endAt = countdown?.to ?? 0;\n  const ms = countdown?.ms ?? 0;\n  React.useLayoutEffect(() => {\n    const el = ring.current;\n    if (!el || !counting) return;\n    const run = el.animate([{ strokeDashoffset: C * (1 - startFrom) }, { strokeDashoffset: C * (1 - endAt) }], { duration: ms, easing: \"linear\", fill: \"both\" });\n    return () => run.cancel();\n    // Restarts only when the job's own times change, not on every second's re-render.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [countdown?.key, counting]);\n\n  const s = job.status;\n  const arc =\n    s === \"running\"\n      ? Math.max(0.04, (job.progress ?? 0) / 100)\n      : countdown && !counting\n        ? countdown.from\n        : s === \"approval\" || s === \"failed\"\n          ? 1\n          : 0;\n  const tone =\n    s === \"running\" ? (paused ? \"stroke-muted-foreground\" : \"stroke-primary\") : s === \"approval\" ? \"stroke-amber-500\" : s === \"failed\" ? \"stroke-red-500\" : \"\";\n  return (\n    <svg viewBox=\"0 0 20 20\" aria-hidden=\"true\" className=\"size-5 shrink-0\">\n      {s === \"completed\" ? (\n        <>\n          <circle cx=\"10\" cy=\"10\" r={R} className=\"fill-emerald-500/12 stroke-emerald-500\" strokeWidth=\"1.5\" />\n          <path d=\"M6.8 10.2l2.2 2.2 4.2-4.6\" fill=\"none\" strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\" className=\"stroke-emerald-600 dark:stroke-emerald-400\" />\n        </>\n      ) : s === \"queued\" ? (\n        <circle cx=\"10\" cy=\"10\" r={R} fill=\"none\" strokeWidth=\"1.5\" strokeDasharray=\"2.6 2.6\" className=\"stroke-muted-foreground/60\" />\n      ) : (\n        <>\n          <circle cx=\"10\" cy=\"10\" r={R} fill=\"none\" strokeWidth=\"1.5\" className=\"stroke-border\" />\n          <circle\n            ref={ring}\n            cx=\"10\"\n            cy=\"10\"\n            r={R}\n            fill=\"none\"\n            strokeWidth=\"1.75\"\n            strokeLinecap=\"round\"\n            strokeDasharray={C}\n            strokeDashoffset={C * (1 - arc)}\n            transform=\"rotate(-90 10 10)\"\n            className={tone}\n            style={{ transition: counting || reduced ? \"none\" : `stroke-dashoffset 700ms ${EASE}, stroke 300ms` }}\n          />\n          {s === \"approval\" && (\n            <>\n              <path d=\"M10 6.4v4.2\" strokeWidth=\"1.7\" strokeLinecap=\"round\" className=\"stroke-amber-600 dark:stroke-amber-400\" />\n              <circle cx=\"10\" cy=\"13.3\" r=\"1\" className=\"fill-amber-600 dark:fill-amber-400\" />\n            </>\n          )}\n          {s === \"failed\" && <path d=\"M7.7 7.7l4.6 4.6M12.3 7.7l-4.6 4.6\" strokeWidth=\"1.6\" strokeLinecap=\"round\" className=\"stroke-red-600 dark:stroke-red-400\" />}\n        </>\n      )}\n    </svg>\n  );\n}\n\n/** A small button whose label morphs to its pending state. */\nfunction Action({ label, busyLabel, busy, tone = \"plain\", onClick }: { label: string; busyLabel: string; busy: boolean; tone?: \"plain\" | \"primary\" | \"outline\"; onClick: () => void }) {\n  const style =\n    tone === \"primary\"\n      ? \"bg-primary text-primary-foreground hover:bg-primary/90\"\n      : tone === \"outline\"\n        ? \"text-foreground shadow-[inset_0_0_0_1px_var(--border)] hover:bg-accent\"\n        : \"text-muted-foreground shadow-[inset_0_0_0_1px_var(--border)] hover:bg-accent hover:text-foreground\";\n  return (\n    <button\n      type=\"button\"\n      onClick={(e) => {\n        e.stopPropagation();\n        onClick();\n      }}\n      aria-disabled={busy || undefined}\n      className={`inline-flex h-7 shrink-0 cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-full px-3 text-[12px] font-medium aria-disabled:cursor-default ${PRESS} ${FOCUS} ${style}`}\n    >\n      {busy && <span aria-hidden=\"true\" className=\"size-3 animate-spin rounded-full border-[1.5px] border-current border-r-transparent opacity-70 motion-reduce:animate-none\" />}\n      <TextMorph>{busy ? busyLabel : label}</TextMorph>\n    </button>\n  );\n}\n\nfunction CopyText({ text }: { text: string }) {\n  const [copied, setCopied] = React.useState(false);\n  React.useEffect(() => {\n    if (!copied) return;\n    const t = window.setTimeout(() => setCopied(false), 1600);\n    return () => window.clearTimeout(t);\n  }, [copied]);\n  return (\n    <button\n      type=\"button\"\n      onClick={(e) => {\n        e.stopPropagation();\n        void navigator.clipboard?.writeText(text);\n        setCopied(true);\n      }}\n      className={`inline-flex h-6 cursor-pointer items-center gap-1 rounded-full px-2 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground ${PRESS} ${FOCUS}`}\n    >\n      <span className=\"relative size-3\">\n        <Copy aria-hidden=\"true\" className=\"absolute inset-0 size-3 transition-[opacity,scale] duration-200\" style={{ opacity: copied ? 0 : 1, scale: copied ? \"0.6\" : \"1\" }} />\n        <Check aria-hidden=\"true\" className=\"absolute inset-0 size-3 text-emerald-600 transition-[opacity,scale] duration-200 dark:text-emerald-400\" style={{ opacity: copied ? 1 : 0, scale: copied ? \"1\" : \"0.6\" }} />\n      </span>\n      <TextMorph>{copied ? \"Copied\" : \"Copy\"}</TextMorph>\n    </button>\n  );\n}\n\nexport function JobQueue({\n  title = \"dispatcher-pool\",\n  jobs,\n  concurrency = 8,\n  throughput,\n  isPaused,\n  onTogglePause,\n  onApprove,\n  onReject,\n  onRetry,\n  onCancel,\n  className = \"\",\n  ...props\n}: JobQueueProps) {\n  const reduced = useReducedMotion();\n  const hydrated = useHydrated();\n  const id = React.useId();\n  const [ownPaused, setOwnPaused] = React.useState(false);\n  const paused = isPaused ?? ownPaused;\n  const [open, setOpen] = React.useState<string | null>(null);\n  const [pending, setPending] = React.useState<Record<string, string>>({});\n\n  // One clock for every countdown and running time, ticking once a second. Each tick also notes when a job was first\n  // seen, for a backoff or review window given without a start.\n  const [now, setNow] = React.useState(0);\n  const [firstSeen, setFirstSeen] = React.useState<Record<string, number>>({});\n  const jobsRef = React.useRef(jobs);\n  React.useLayoutEffect(() => {\n    jobsRef.current = jobs;\n  });\n  React.useEffect(() => {\n    let t = 0;\n    const tick = () => {\n      const at = Date.now();\n      setNow(at);\n      setFirstSeen((f) => {\n        const fresh = jobsRef.current.filter((j) => f[j.id] === undefined);\n        return fresh.length ? { ...f, ...Object.fromEntries(fresh.map((j) => [j.id, at])) } : f;\n      });\n      t = window.setTimeout(tick, 1000 - (Date.now() % 1000) + 5);\n    };\n    tick();\n    return () => window.clearTimeout(t);\n  }, []);\n\n  // Rows that leave the list fold away in place instead of vanishing.\n  const [last, setLast] = React.useState(jobs);\n  const [leaving, setLeaving] = React.useState<JobItem[]>([]);\n  if (last !== jobs) {\n    const ids = new Set(jobs.map((j) => j.id));\n    const gone = last.filter((j) => !ids.has(j.id));\n    setLast(jobs);\n    if (gone.length && !reduced) setLeaving((l) => [...l.filter((g) => !ids.has(g.id)), ...gone]);\n  }\n  React.useEffect(() => {\n    if (!leaving.length) return;\n    const t = window.setTimeout(() => setLeaving([]), 420);\n    return () => window.clearTimeout(t);\n  }, [leaving]);\n\n  // A pending action ends when the job it was for changes or leaves.\n  const statusKey = jobs.map((j) => `${j.id}:${j.status}`).join(\"|\");\n  const [lastKey, setLastKey] = React.useState(statusKey);\n  const [pendingFor, setPendingFor] = React.useState<Record<string, string>>({});\n  if (lastKey !== statusKey) {\n    setLastKey(statusKey);\n    const still: Record<string, string> = {};\n    for (const [jid, kind] of Object.entries(pending)) {\n      const job = jobs.find((j) => j.id === jid);\n      if (job && pendingFor[jid] === job.status) still[jid] = kind;\n    }\n    setPending(still);\n  }\n\n  const rowRefs = React.useRef(new Map<string, HTMLElement>());\n  const act = async (job: JobItem, kind: \"approve\" | \"reject\" | \"retry\" | \"cancel\") => {\n    if (pending[job.id]) return;\n    const fn = { approve: onApprove, reject: onReject, retry: onRetry, cancel: onCancel }[kind];\n    setPending((p) => ({ ...p, [job.id]: kind }));\n    setPendingFor((p) => ({ ...p, [job.id]: job.status }));\n    try {\n      await fn?.(job.id);\n    } catch {\n      setPending((p) => {\n        const next = { ...p };\n        delete next[job.id];\n        return next;\n      });\n      // It didn't go through: the row gives a small shake and its buttons come back.\n      if (!reduced) rowRefs.current.get(job.id)?.animate([{ translate: \"0\" }, { translate: \"-4px\" }, { translate: \"4px\" }, { translate: \"-2px\" }, { translate: \"0\" }], { duration: 380, easing: \"ease-out\" });\n      return;\n    }\n    // It went through; if the jobs haven't moved on a moment later, stop showing it as pending anyway.\n    window.setTimeout(() => {\n      setPending((p) => {\n        if (p[job.id] !== kind) return p;\n        const next = { ...p };\n        delete next[job.id];\n        return next;\n      });\n    }, 2500);\n  };\n\n  // Rows glide to their new place only when a job moves to another group. Positions are refreshed on every render (the\n  // clock re-renders each second), so a fold opening between changes never leaves them stale; a new glide replaces any\n  // that is still running, so they never stack.\n  const tops = React.useRef(new Map<string, number>());\n  const glidedKey = React.useRef(statusKey);\n  React.useLayoutEffect(() => {\n    const moved = glidedKey.current !== statusKey;\n    glidedKey.current = statusKey;\n    const next = new Map<string, number>();\n    rowRefs.current.forEach((el, key) => {\n      const top = el.offsetTop;\n      next.set(key, top);\n      const before = tops.current.get(key);\n      if (moved && before !== undefined && Math.abs(before - top) > 1 && !reduced) {\n        el.getAnimations().forEach((a) => a.id === \"glide\" && a.cancel());\n        const glide = el.animate([{ transform: `translateY(${before - top}px)` }, { transform: \"none\" }], { duration: 460, easing: EASE });\n        glide.id = \"glide\";\n      }\n    });\n    tops.current = next;\n  });\n\n  const togglePause = () => {\n    const next = !paused;\n    if (isPaused === undefined) setOwnPaused(next);\n    onTogglePause?.(next);\n  };\n\n  const running = jobs.filter((j) => j.status === \"running\");\n  const slots = Array.from({ length: Math.max(1, concurrency) }, (_, i) => running[i]);\n  const review = jobs.filter((j) => j.status === \"approval\").length;\n  const groups = ORDER.map((status) => ({\n    status,\n    rows: [...jobs.filter((j) => j.status === status), ...leaving.filter((j) => j.status === status)],\n    count: jobs.filter((j) => j.status === status).length,\n  })).filter((g) => g.rows.length);\n  const tick = hydrated ? now : 0;\n\n  return (\n    <div className={`w-full rounded-[22px] bg-card text-card-foreground shadow-[0_0_0_1px_var(--border)] ${className}`} {...props}>\n      {/* Its natural width where the parent sizes to its content (a centred flex column), without forcing it on narrow screens. */}\n      <div aria-hidden=\"true\" data-natural-width className=\"grid h-0\" style={{ gridTemplateColumns: \"minmax(0, 720px)\" }} />\n      <div className=\"@container w-full\">\n        {/* The pool: its name and Pause, then its workers as hairline slots beside the pace. */}\n        <div className=\"grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-3 px-4 pb-3.5 pt-4 @[34rem]:px-5\">\n          <p className=\"truncate pt-1 text-[14px] font-medium text-foreground\">{title}</p>\n          <button\n            type=\"button\"\n            aria-pressed={paused}\n            onClick={togglePause}\n            className={`row-span-2 inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-full pl-2.5 pr-3 text-[12.5px] font-medium shadow-[inset_0_0_0_1px_var(--border)] hover:bg-accent ${PRESS} ${FOCUS} ${paused ? \"text-amber-700 dark:text-amber-400\" : \"text-foreground\"}`}\n          >\n            <span aria-hidden=\"true\" className=\"relative size-3.5\">\n              <Pause className=\"absolute inset-0 size-3.5 fill-current transition-[opacity,scale] duration-300\" style={{ opacity: paused ? 0 : 1, scale: paused ? \"0.6\" : \"1\" }} />\n              <Play className=\"absolute inset-0 size-3.5 fill-current transition-[opacity,scale] duration-300\" style={{ opacity: paused ? 1 : 0, scale: paused ? \"1\" : \"0.6\" }} />\n            </span>\n            <TextMorph>{paused ? \"Resume\" : \"Pause\"}</TextMorph>\n          </button>\n          <div className=\"mt-1.5 flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-muted-foreground tabular-nums\">\n            <span aria-hidden=\"true\" className=\"flex h-3.5 items-end gap-[2px]\">\n              {slots.map((job, i) => (\n                <span key={i} className=\"relative h-full w-[5px]\" style={{ maskImage: RULE, WebkitMaskImage: RULE }}>\n                  <span className=\"absolute inset-0 bg-foreground/[0.1]\" />\n                  <span\n                    className={`absolute inset-x-0 bottom-0 ${paused ? \"bg-muted-foreground/60\" : \"bg-primary\"}`}\n                    style={{ height: job ? `${Math.max(14, job.progress ?? 0)}%` : \"0%\", transition: reduced ? \"none\" : `height 600ms ${EASE}, background-color 300ms` }}\n                  />\n                </span>\n              ))}\n            </span>\n            <span className=\"whitespace-nowrap\">\n              <span className=\"font-medium text-foreground\">\n                <NumberRoll value={paused ? 0 : running.length} duration={600} />\n              </span>{\" \"}\n              of {concurrency} busy\n            </span>\n            {throughput !== undefined && (\n              <span className=\"whitespace-nowrap\">\n                <span className=\"font-medium text-foreground\">\n                  <NumberRoll value={paused ? 0 : throughput} format={{ minimumFractionDigits: 1, maximumFractionDigits: 1 }} duration={600} />\n                </span>{\" \"}\n                jobs/s\n              </span>\n            )}\n            {review > 0 && (\n              <span className=\"whitespace-nowrap text-amber-700 dark:text-amber-400\">\n                {review} to review\n              </span>\n            )}\n          </div>\n        </div>\n\n        <div className=\"border-t border-border pb-1.5\">\n          {groups.length === 0 && <p className=\"px-5 py-10 text-center text-[12.5px] text-muted-foreground\">No jobs in this pool.</p>}\n          {groups.map((group, gi) => (\n            <section key={group.status} aria-label={`${GROUP[group.status]}, ${group.count}`} className={gi > 0 ? \"border-t border-border\" : \"\"}>\n              <p className=\"flex items-center gap-1.5 px-4 pb-0.5 pt-3 text-[11.5px] font-medium text-muted-foreground @[34rem]:px-5\">\n                {GROUP[group.status]}\n                <span className=\"tabular-nums text-muted-foreground/70\">\n                  <NumberRoll value={group.count} duration={500} />\n                </span>\n              </p>\n              {group.rows.map((job) => {\n                const isLeaving = leaving.some((l) => l.id === job.id) && !jobs.some((j) => j.id === job.id);\n                const busy = pending[job.id];\n                const details = job.error?.stack ?? (job.payload ? (typeof job.payload === \"string\" ? job.payload : JSON.stringify(job.payload, null, 2)) : null);\n                const isOpen = open === job.id && !!details;\n                const seenAt = firstSeen[job.id] ?? tick;\n                const countdown = countdownOf(job, tick, seenAt);\n                const elapsed = job.status === \"running\" && job.startedAt ? clock(tick - job.startedAt) : \"\";\n                const time =\n                  job.status === \"running\"\n                    ? `${Math.round(job.progress ?? 0)}%`\n                    : job.status === \"approval\" && job.approval?.expiresAt\n                      ? `${clock(job.approval.expiresAt - tick)} left`\n                      : job.status === \"failed\" && (job.error?.retryAt || job.error?.backoffMs)\n                        ? `retry in ${clock((job.error.retryAt ?? seenAt + (job.error.backoffMs ?? 0)) - tick)}`\n                        : job.status === \"completed\" && job.durationMs !== undefined\n                          ? seconds(job.durationMs)\n                          : \"\";\n                const meta =\n                  job.status === \"approval\"\n                    ? job.approval?.reason\n                    : job.status === \"failed\"\n                      ? job.error?.message\n                      : job.status === \"queued\"\n                        ? `${jobs.filter((j) => j.status === \"queued\").findIndex((j) => j.id === job.id) + 1} in line`\n                        : undefined;\n                const buttons =\n                  (job.status === \"approval\" && (onApprove || onReject)) || (job.status === \"failed\" && onRetry) ? (\n                    <>\n                      {job.status === \"approval\" && onApprove && <Action label=\"Approve\" busyLabel=\"Approving\" busy={busy === \"approve\"} tone=\"primary\" onClick={() => act(job, \"approve\")} />}\n                      {job.status === \"approval\" && onReject && <Action label=\"Reject\" busyLabel=\"Rejecting\" busy={busy === \"reject\"} onClick={() => act(job, \"reject\")} />}\n                      {job.status === \"failed\" && onRetry && <Action label=\"Retry now\" busyLabel=\"Retrying\" busy={busy === \"retry\"} tone=\"outline\" onClick={() => act(job, \"retry\")} />}\n                    </>\n                  ) : null;\n                return (\n                  <div\n                    key={job.id}\n                    ref={(el) => {\n                      if (el) rowRefs.current.set(job.id, el);\n                      else rowRefs.current.delete(job.id);\n                    }}\n                    className=\"grid\"\n                    style={{\n                      gridTemplateRows: isLeaving ? \"0fr\" : \"1fr\",\n                      opacity: isLeaving ? 0 : 1,\n                      transition: reduced ? \"none\" : `grid-template-rows 380ms ${EASE} 60ms, opacity 200ms ${EASE}`,\n                    }}\n                  >\n                    {/* overflow: clip, not hidden: a hidden box still scrolls when a button inside it takes focus. */}\n                    <div className=\"min-h-0 overflow-clip\" inert={isLeaving || undefined}>\n                      {/* One row, laid out by the card's own width: name and time on top, the reason under the name, and\n                          the buttons on a line of their own on a narrow card or at the end of the row on a wide one. */}\n                      <div\n                        onClick={() => details && setOpen(isOpen ? null : job.id)}\n                        className={`mx-1.5 grid grid-cols-[20px_minmax(0,1fr)_auto] gap-x-3 rounded-[14px] px-2.5 py-2.5 transition-colors duration-200 @[34rem]:mx-2.5 @[34rem]:grid-cols-[20px_minmax(0,1fr)_auto_auto] ${\n                          details ? \"cursor-pointer hover:bg-muted/50\" : \"\"\n                        }`}\n                      >\n                        <span className=\"row-span-2 pt-px\">\n                          <Glyph job={job} paused={paused} countdown={countdown} reduced={reduced} />\n                        </span>\n                        <p className=\"flex min-w-0 items-baseline gap-2 pt-px\">\n                          <span className=\"truncate text-[13.5px] font-medium text-foreground\">{job.title}</span>\n                          <span className=\"hidden shrink-0 font-mono text-[11px] text-muted-foreground/70 @[34rem]:inline\">{job.id}</span>\n                        </p>\n                        <div className=\"col-start-3 row-start-1 flex items-center gap-1 self-start @[34rem]:row-span-2 @[34rem]:self-center\">\n                          {time && (\n                            <span\n                              className={`whitespace-nowrap pt-0.5 text-[12px] tabular-nums @[34rem]:pt-0 ${\n                                job.status === \"approval\" ? \"text-amber-700 dark:text-amber-400\" : job.status === \"failed\" ? \"text-red-600 dark:text-red-400\" : \"text-muted-foreground\"\n                              }`}\n                            >\n                              {hydrated ? time : \"\"}\n                              {hydrated && elapsed ? <span className=\"hidden @[24rem]:inline\"> · {elapsed}</span> : null}\n                            </span>\n                          )}\n                          {job.status === \"queued\" && onCancel && (\n                            <button\n                              type=\"button\"\n                              aria-label={`Cancel ${job.title}`}\n                              onClick={(e) => {\n                                e.stopPropagation();\n                                void act(job, \"cancel\");\n                              }}\n                              className={`-my-1 -mr-1 flex size-7 cursor-pointer items-center justify-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground ${PRESS} ${FOCUS}`}\n                            >\n                              <X aria-hidden=\"true\" className=\"size-3.5\" />\n                            </button>\n                          )}\n                          {details && (\n                            <button\n                              type=\"button\"\n                              aria-expanded={isOpen}\n                              aria-controls={`${id}-${job.id}`}\n                              aria-label={`${isOpen ? \"Hide\" : \"Show\"} details for ${job.title}`}\n                              onClick={(e) => {\n                                e.stopPropagation();\n                                setOpen(isOpen ? null : job.id);\n                              }}\n                              className={`-my-1 -mr-1 flex size-7 cursor-pointer items-center justify-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground ${PRESS} ${FOCUS}`}\n                            >\n                              <ChevronDown aria-hidden=\"true\" className=\"size-3.5\" style={{ transform: isOpen ? \"rotate(180deg)\" : \"none\", transition: reduced ? \"none\" : `transform 320ms ${EASE}` }} />\n                            </button>\n                          )}\n                          {/* Every row ends in the same 28px slot, so the times line up down the card. */}\n                          {!details && !(job.status === \"queued\" && onCancel) && <span aria-hidden=\"true\" className=\"-mr-1 size-7 shrink-0\" />}\n                        </div>\n                        <p\n                          className={`col-start-2 col-end-4 mt-0.5 text-[12px] leading-[1.45] @[34rem]:col-end-3 ${\n                            job.status === \"approval\" ? \"text-amber-700 dark:text-amber-400\" : job.status === \"failed\" ? \"text-red-600 dark:text-red-400\" : \"text-muted-foreground\"\n                          }`}\n                        >\n                          {meta ? <span>{meta}</span> : null}\n                          {job.queue ? <span className=\"text-muted-foreground\">{meta ? \" · \" : \"\"}{job.queue}</span> : null}\n                          {job.status === \"failed\" && job.error?.attempt && job.error.maxAttempts ? (\n                            <span className=\"text-muted-foreground\">\n                              {\" \"}\n                              · attempt {job.error.attempt} of {job.error.maxAttempts}\n                            </span>\n                          ) : null}\n                        </p>\n                        {buttons && (\n                          <div className=\"col-start-2 col-end-4 mt-2.5 flex flex-wrap items-center gap-2 @[34rem]:col-start-4 @[34rem]:col-end-5 @[34rem]:row-span-2 @[34rem]:row-start-1 @[34rem]:mt-0 @[34rem]:ml-1 @[34rem]:flex-row-reverse @[34rem]:self-center\">\n                            {buttons}\n                          </div>\n                        )}\n                      </div>\n\n                      {/* Details open in place, under the row, aligned with its name. */}\n                      {details && (\n                        <div\n                          id={`${id}-${job.id}`}\n                          className=\"grid\"\n                          style={{ gridTemplateRows: isOpen ? \"1fr\" : \"0fr\", transition: reduced ? \"none\" : `grid-template-rows 380ms ${EASE}` }}\n                        >\n                          <div className=\"min-h-0 min-w-0 overflow-clip\" inert={!isOpen || undefined}>\n                            <div className=\"mb-2 ml-4 mr-4 mt-0.5 rounded-[12px] bg-muted/50 shadow-[inset_0_0_0_1px_var(--border)] @[34rem]:ml-[52px] @[34rem]:mr-5\">\n                              <div className=\"flex items-center justify-between gap-2 py-1 pl-3 pr-1\">\n                                <span className=\"text-[11.5px] font-medium text-muted-foreground\">{job.error?.stack ? \"Stack trace\" : \"Payload\"}</span>\n                                <CopyText text={details} />\n                              </div>\n                              <pre className=\"max-h-48 overflow-auto whitespace-pre border-t border-border px-3 py-2.5 font-mono text-[11.5px] leading-relaxed text-foreground/85\">{details}</pre>\n                            </div>\n                          </div>\n                        </div>\n                      )}\n                    </div>\n                  </div>\n                );\n              })}\n            </section>\n          ))}\n        </div>\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {paused ? `${title} paused` : \"\"}\n      </p>\n    </div>\n  );\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/job-queue. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}