Skip to content
Shaken UI
Sign in

Agent Workspace

Save

A complete agent workspace laid out as one document of the run: a slim status header with a progress line, one-line steps that open in place, files, inline approvals, the streamed reply, and a pinned prompt composer.

Category
Block
Version
0.3.1
Frameworks
Next.js, Vite + React, Vite + Vue
Styling
Tailwind CSS v4

Preview

Agent Workspace preview
Scenario
Applied through event 0

Update the rate-limit docs

Queued

Describe a task

The agent's steps, files, and reply build up here as one record of the run.

Enter to send, Shift+Enter for a new line.

Installation

npx @shakenui/cli add agent-workspace

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

npx @shakenui/cli add agent-workspace --dry-run

Usage

agent-workspace-example.tsx
"use client";

import { useState } from "react";
import type { AgentRun } from "@/components/shaken/agent/agent-run";
import { AgentWorkspace } from "@/components/shaken/blocks/agent-workspace";

const initialRun: AgentRun = {
  id: "run_1",
  title: "Update the rate-limit docs",
  status: "waiting-for-approval",
  createdAt: "2026-11-14T10:00:00.000Z",
  messages: [{ id: "m1", role: "user", status: "complete", content: "Update the rate limits and open a pull request." }],
  steps: [
    { id: "s1", name: "search_docs", kind: "tool", status: "succeeded", summary: "Find pages that mention rate limits", input: { query: "rate limits" }, output: "Found 3 pages.", startedAt: "2026-11-14T10:00:00.600Z", finishedAt: "2026-11-14T10:00:01.400Z" },
    { id: "s2", name: "edit_files", kind: "tool", status: "succeeded", summary: "Update the limits table", output: "Changed 1 file.", startedAt: "2026-11-14T10:00:01.600Z", finishedAt: "2026-11-14T10:00:02.600Z" },
  ],
  approvals: [{ id: "a1", title: "Open a pull request?", status: "pending", detail: "gh pr create --title \"Update rate limits\"" }],
  artifacts: [{ id: "f1", name: "rate-limits.md", type: "text/markdown", status: "ready", content: "Free: 60/min\nPro: 600/min" }],
};

export default function AgentWorkspaceExample() {
  // In your app, build the run from your backend's events with applyEvents (see agent-run).
  const [run, setRun] = useState(initialRun);
  const decide = (status: "approved" | "rejected") => async (id: string) =>
    setRun((current) => ({
      ...current,
      status: status === "approved" ? "running" : "cancelled",
      approvals: current.approvals.map((a) => (a.id === id ? { ...a, status, decidedAt: new Date().toISOString() } : a)),
    }));

  return <AgentWorkspace run={run} height="36rem" onSubmit={() => {}} onApprove={decide("approved")} onReject={decide("rejected")} />;
}

API

PropTypeDefaultDescription
runAgentRun—The run to render, normalized with agent-run's applyEvents and fromSnapshot.
onSubmit / onStop(prompt, context) => void | Promise<void> / () => void—Prompt composer actions; context carries the chosen mode, model, permission, and files.
onApprove / onReject(approvalId: string) => void | Promise<void>—Approval decisions; send them to your backend for verification.
composerStatus"idle" | "submitting" | "running"—Defaults from the run status.
composerPick<PromptComposerProps, "placeholder" | "mode" | "model" | "permissions" | "attachments" | "mentions" | "beam">—Composer options. Mode, model, and permission selectors are on by default.
outline / defaultOutlineOpenboolean / booleantrue / trueA collapsible rail beside the run on wide screens listing every step and file; choosing one scrolls the run to it.
heightCSS height"42rem"The run scrolls between the header and the pinned composer. Pass "100%" to fill a pane.
bannerReactNode—Optional notice above the run, e.g. reconnecting.

Accessibility

  • The run is a polite log: new steps, files, approvals, and reply text are announced as they arrive, and each step announces its new status (for example "search_docs, Done").
  • The header status pill is a live region whose text is exactly the run status; every status is shown as text and a shape, with color as reinforcement.
  • Steps and decided approvals open in place with native details and summary. After Approve or Reject, focus moves to the approval so keyboard and screen reader users keep their place.
  • The outline toggle reports aria-expanded; outline entries are buttons that scroll to and focus the matching step or file.
  • With reduced motion, entries appear instantly, the activity marks hold a still frame, and the composer's border light stays still.

Files

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

Source

The exact source the CLI installs, from /r/items/react/agent-workspace/0.3.1.json.

blocks/agent-workspace.tsxShow
blocks/agent-workspace.tsx
"use client";

import { type CSSProperties, type ReactNode, useEffect, useId, useRef, useState } from "react";
import type { AgentRun, RunApproval, RunArtifact, RunStatus, RunStep, StepStatus } from "../agent/agent-run";
import { type AgentActivity, type AgentPhase, AgentMark, AgentState } from "../agent/agent-state";
import { ApprovalCard } from "../agent/approval-card";
import { ArtifactPreview } from "../agent/artifact-preview";
import { type ComposerStatus, type ComposerSubmitContext, PromptComposer, type PromptComposerProps } from "../agent/prompt-composer";
import { MessageScroller, StreamingMessage } from "../agent/streaming-message";

export interface AgentWorkspaceProps {
  /** The run to show, normalized (see agent-run's applyEvents and fromSnapshot). */
  run: AgentRun;
  composerStatus?: ComposerStatus;
  onSubmit: (prompt: string, context: ComposerSubmitContext) => void | Promise<void>;
  onStop?: () => void;
  onApprove?: (approvalId: string) => void | Promise<void>;
  onReject?: (approvalId: string) => void | Promise<void>;
  /** Optional notice above the run, e.g. a connection message. */
  banner?: ReactNode;
  /** Shows a collapsible outline of steps and files beside the run on wide screens. */
  outline?: boolean;
  /** Whether the outline starts open. */
  defaultOutlineOpen?: boolean;
  /** Height of the workspace. The run scrolls between the header and the composer. Pass "100%" to fill a pane. */
  height?: CSSProperties["height"];
  /** Composer options. Mode, model, and permission selectors are on by default. */
  composer?: Pick<PromptComposerProps, "placeholder" | "mode" | "model" | "permissions" | "attachments" | "mentions" | "beam">;
  className?: string;
}

const runStatus: Record<RunStatus, { label: string; phase: AgentPhase }> = {
  queued: { label: "Queued", phase: "idle" },
  running: { label: "Running", phase: "active" },
  "waiting-for-approval": { label: "Needs approval", phase: "waiting" },
  succeeded: { label: "Succeeded", phase: "done" },
  failed: { label: "Failed", phase: "failed" },
  cancelled: { label: "Cancelled", phase: "cancelled" },
};

const stepLabel: Record<StepStatus, string> = {
  queued: "Queued",
  running: "Running",
  succeeded: "Done",
  failed: "Failed",
  skipped: "Skipped",
};

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
/** New entries settle in with a short rise; instant with reduced motion. */
const rise = `transition-[opacity,translate] duration-200 ${ease} starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none`;
const hairline = "border-zinc-950/[0.07] dark:border-white/[0.08]";

/**
 * A complete agent workspace laid out as one document of the run: a slim header with the run's
 * state and a progress hairline, then the request, each step as a one-line row that opens in
 * place, files, approvals, and the streamed reply, with the composer pinned underneath.
 * It renders whatever run you pass and reports user actions through callbacks.
 */
export function AgentWorkspace({
  run,
  composerStatus,
  onSubmit,
  onStop,
  onApprove,
  onReject,
  banner,
  outline = true,
  defaultOutlineOpen = true,
  height = "42rem",
  composer,
  className,
}: AgentWorkspaceProps) {
  const id = useId();
  const [outlineOpen, setOutlineOpen] = useState(defaultOutlineOpen);
  const items = useArrivalOrder(activityItems(run));

  const firstReply = run.messages.findIndex((message) => message.role === "assistant");
  const lead = firstReply === -1 ? run.messages : run.messages.slice(0, firstReply);
  const rest = firstReply === -1 ? [] : run.messages.slice(firstReply);
  const empty = run.messages.length === 0 && items.length === 0;

  const running = run.steps.find((step) => step.status === "running");
  const writing = run.messages.some((message) => message.role === "assistant" && message.status === "streaming");
  const activity = writing ? { activity: "thinking" as const, label: "Writing" } : activityOf(running);
  const meta = runStatus[run.status];
  const statusLabel = run.status === "running" ? activity.label : meta.label;

  const settled = run.steps.filter((step) => step.status !== "queued" && step.status !== "running").length;
  const progress = run.status === "succeeded" ? 1 : run.steps.length ? settled / run.steps.length : 0;
  const elapsed = elapsedOf(run);
  const status: ComposerStatus =
    composerStatus ?? (run.status === "running" || run.status === "waiting-for-approval" ? "running" : "idle");
  const contentKey = `${run.messages.reduce((total, message) => total + message.content.length, 0)}:${items.map((item) => item.status).join()}`;
  const failedStepShown = run.steps.some((step) => step.status === "failed" && step.error);
  const showOutline = outline && outlineOpen;

  /** Brings a step or file in the run into view and moves focus to it. */
  function reveal(key: string) {
    const target = document.getElementById(`${id}-${key}`);
    if (!target) return;
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    target.scrollIntoView({ block: "nearest", behavior: reduce ? "auto" : "smooth" });
    (target.querySelector<HTMLElement>("summary") ?? target).focus({ preventScroll: true });
  }

  return (
    <div
      data-status={run.status}
      style={{ height }}
      className={["flex min-h-0 w-full flex-col text-zinc-950 dark:text-white", className].filter(Boolean).join(" ")}
    >
      <header className="relative flex min-w-0 items-center gap-3 pb-3">
        <h3 className="min-w-0 flex-1 truncate text-sm leading-6 font-semibold">{run.title}</h3>
        {run.steps.length || elapsed ? (
          <p className="shrink-0 font-mono text-xs text-zinc-500 tabular-nums">
            {run.steps.length ? (
              <span className="hidden sm:inline">
                {settled} of {run.steps.length} {run.steps.length === 1 ? "step" : "steps"}
                {elapsed ? <span aria-hidden="true"> · </span> : null}
              </span>
            ) : null}
            {elapsed ? (
              <>
                <span className="sr-only">Elapsed </span>
                {elapsed}
              </>
            ) : null}
          </p>
        ) : null}
        {/* A live region whose text is exactly the status label; the mark is decorative. */}
        <AgentState
          status
          data-slot="run-status"
          size="sm"
          activity={activity.activity}
          phase={meta.phase}
          label={statusLabel}
          className="shrink-0"
        />
        {outline ? (
          <button
            type="button"
            aria-label="Run outline"
            aria-expanded={outlineOpen}
            aria-controls={`${id}-outline`}
            onClick={() => setOutlineOpen((open) => !open)}
            className={[
              "-mr-1 hidden size-7 shrink-0 items-center justify-center rounded-lg text-zinc-500 lg:inline-flex",
              "transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none",
              "hover:bg-zinc-950/[0.04] hover:text-zinc-950 aria-expanded:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white dark:aria-expanded:text-white",
              "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
            ].join(" ")}
          >
            <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" className="size-4">
              <rect x="2.25" y="3" width="11.5" height="10" rx="2" />
              <path d="M10 3v10" />
            </svg>
          </button>
        ) : null}
        {/* The header's bottom edge is the progress line: it fills as steps settle. */}
        <span aria-hidden="true" className="absolute inset-x-0 bottom-0 h-px overflow-hidden bg-zinc-950/[0.07] dark:bg-white/[0.08]">
          <span
            className={[
              "absolute inset-0 origin-left transition-[scale,background-color] duration-500 motion-reduce:transition-none",
              ease,
              run.status === "failed" ? "bg-red-500/70" : run.status === "waiting-for-approval" ? "bg-amber-500/70" : "bg-zinc-950/35 dark:bg-white/45",
            ].join(" ")}
            style={{ scale: `${progress} 1` }}
          />
        </span>
      </header>

      <div className={`grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)] ${showOutline ? "lg:grid-cols-[minmax(0,1fr)_15rem]" : ""}`}>
        <section aria-label="Run" className="flex min-h-0 min-w-0 flex-col">
          {banner ? (
            <div className="px-2 pt-4">
              <div className="mx-auto max-w-2xl">{banner}</div>
            </div>
          ) : null}
          <div className="min-h-0 flex-1 [&>div]:h-full">
            <MessageScroller
              contentKey={contentKey}
              className="px-2 [mask-image:linear-gradient(to_bottom,transparent,#000_1.25rem,#000_calc(100%-1.25rem),transparent)]"
            >
              <div className="mx-auto flex min-h-full w-full max-w-2xl flex-col py-6">
                {empty ? (
                  <div className="m-auto max-w-xs py-10 text-center">
                    <p className="text-sm font-medium">Describe a task</p>
                    <p className="mt-1 text-sm text-pretty text-zinc-500">
                      The agent's steps, files, and reply build up here as one record of the run.
                    </p>
                  </div>
                ) : null}

                {lead.map((message, index) => (
                  <Prompt key={message.id} content={message.content} className={index ? "mt-3" : ""} />
                ))}

                {items.length ? (
                  <ol aria-label="Activity" className={`flex flex-col ${lead.length ? "mt-5" : ""}`}>
                    {items.map((item) =>
                      item.kind === "step" ? (
                        <StepRow key={item.key} domId={`${id}-${item.key}`} step={item.step} />
                      ) : item.kind === "artifact" ? (
                        <li key={item.key} id={`${id}-${item.key}`} tabIndex={-1} className={`my-1.5 min-w-0 outline-none ${rise}`}>
                          <ArtifactPreview
                            name={item.artifact.name}
                            type={item.artifact.type}
                            status={item.artifact.status}
                            path={item.artifact.path}
                            content={item.artifact.content}
                            sizeBytes={item.artifact.sizeBytes}
                            error={item.artifact.error}
                          />
                        </li>
                      ) : (
                        <ApprovalItem key={item.key} approval={item.approval} onApprove={onApprove} onReject={onReject} />
                      ),
                    )}
                  </ol>
                ) : null}

                {rest.map((message) =>
                  message.role === "user" ? (
                    <Prompt key={message.id} content={message.content} className="mt-8" />
                  ) : (
                    <StreamingMessage
                      key={message.id}
                      role="assistant"
                      content={message.content}
                      status={message.status}
                      error={message.error}
                      className="mt-5"
                    />
                  ),
                )}

                {run.status === "failed" && run.error && !failedStepShown ? (
                  <p className={`mt-5 text-sm text-red-700 dark:text-red-400 ${rise}`}>{run.error}</p>
                ) : null}
              </div>
            </MessageScroller>
          </div>
          <div className="px-2 pt-1">
            <div className="mx-auto max-w-2xl">
              <PromptComposer mode model permissions {...composer} onSubmit={onSubmit} onStop={onStop} status={status} />
            </div>
          </div>
        </section>

        {showOutline ? (
          <aside
            id={`${id}-outline`}
            aria-label="Run outline"
            className={`hidden min-h-0 overflow-y-auto border-l py-6 pl-4 lg:block ${hairline}`}
          >
            <Outline run={run} onReveal={reveal} />
          </aside>
        ) : null}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// The run, as a list of activity

type ActivityItem =
  | { kind: "step"; key: string; status: string; step: RunStep }
  | { kind: "artifact"; key: string; status: string; artifact: RunArtifact }
  | { kind: "approval"; key: string; status: string; approval: RunApproval };

/**
 * Steps, files, and approvals in a sensible order for a run loaded all at once: steps in the
 * order they started, a decided approval before the steps that started after the decision, then
 * files, then anything still waiting for a decision.
 */
function activityItems(run: AgentRun): ActivityItem[] {
  const ordered: ActivityItem[] = run.steps.map((step) => ({ kind: "step", key: `step-${step.id}`, status: step.status, step }));
  for (const approval of run.approvals) {
    if (approval.status === "pending") continue;
    const decided = time(approval.decidedAt);
    const index = ordered.findIndex((item) => item.kind === "step" && time(item.step.startedAt) > decided);
    const entry: ActivityItem = { kind: "approval", key: `approval-${approval.id}`, status: approval.status, approval };
    if (index === -1) ordered.push(entry);
    else ordered.splice(index, 0, entry);
  }
  for (const artifact of run.artifacts) ordered.push({ kind: "artifact", key: `artifact-${artifact.id}`, status: artifact.status, artifact });
  for (const approval of run.approvals) {
    if (approval.status === "pending") ordered.push({ kind: "approval", key: `approval-${approval.id}`, status: approval.status, approval });
  }
  return ordered;
}

/**
 * Keeps entries in the order they first appeared, so a streamed run reads in the order it
 * happened and nothing jumps when an approval is decided. Entries that arrive together (a run
 * loaded from a snapshot) take the order from `activityItems`.
 */
function useArrivalOrder(items: ActivityItem[]): ActivityItem[] {
  const order = useRef(new Map<string, number>());
  const next = useRef(0);
  const present = new Set(items.map((item) => item.key));
  for (const key of order.current.keys()) if (!present.has(key)) order.current.delete(key);
  if (order.current.size === 0) next.current = 0;
  for (const item of items) if (!order.current.has(item.key)) order.current.set(item.key, next.current++);
  return [...items].sort((a, b) => order.current.get(a.key)! - order.current.get(b.key)!);
}

/** The request that starts a turn: the document's opening line, not a chat bubble. */
function Prompt({ content, className = "" }: { content: string; className?: string }) {
  return (
    <article data-role="user" className={`${rise} ${className}`}>
      <p className="sr-only">You:</p>
      <p className="text-[15px] leading-relaxed font-medium tracking-[-0.005em] break-words whitespace-pre-wrap text-pretty">{content}</p>
    </article>
  );
}

const rowClass = "-mx-2 flex min-h-9 items-center gap-3 rounded-lg px-2 py-1.5";
const summaryClass = [
  "cursor-pointer list-none select-none [&::-webkit-details-marker]:hidden",
  "transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] motion-reduce:transition-none dark:hover:bg-white/[0.06]",
  "focus-visible:outline-2 focus-visible:outline-sky-500",
].join(" ");
const disclosure = [
  "group [interpolate-size:allow-keywords]",
  // Height animates where ::details-content and interpolate-size are supported; elsewhere it simply opens.
  "[&::details-content]:h-0 [&::details-content]:overflow-clip [&::details-content]:transition-[height,content-visibility] [&::details-content]:duration-[220ms] [&::details-content]:ease-[cubic-bezier(0.23,1,0.32,1)] [&::details-content]:[transition-behavior:allow-discrete]",
  "open:[&::details-content]:h-auto motion-reduce:[&::details-content]:transition-none",
].join(" ");

/** The disclosure arrow on rows that open; it turns to point down while open. */
function Chevron() {
  return (
    <svg
      aria-hidden="true"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      className={`size-3.5 shrink-0 text-zinc-400 transition-transform duration-200 ${ease} group-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" />
    </svg>
  );
}

/** One step on one line: status, tool name, what it does, and how long it took. Opens in place. */
function StepRow({ step, domId }: { step: RunStep; domId: string }) {
  const hasInput = step.input !== undefined;
  const hasOutput = step.status === "succeeded" && step.output != null;
  const expandable = hasInput || hasOutput;
  const duration = step.startedAt && step.finishedAt ? formatDuration(step.startedAt, step.finishedAt) : "";
  const dim = step.status === "queued" || step.status === "skipped";

  const row = (
    <>
      <StepGlyph key={step.status} status={step.status} activity={activityOf(step).activity} />
      <span className="flex min-w-0 flex-1 items-baseline gap-2.5">
        <span
          aria-hidden="true"
          className={[
            "max-w-[65%] shrink-0 truncate font-mono text-[13px] transition-colors duration-200 motion-reduce:transition-none",
            dim ? "text-zinc-500" : "text-zinc-950 dark:text-white",
            step.status === "skipped" ? "line-through decoration-zinc-500/60" : "",
          ].join(" ")}
        >
          {step.name}
        </span>
        {/* Remounts with the status, so the log announces "search_docs, Done". */}
        <span key={step.status} className="sr-only">
          {step.name}, {stepLabel[step.status]}.
        </span>
        {step.summary ? <span className="min-w-0 truncate text-sm text-zinc-500">{step.summary}</span> : null}
      </span>
      <span
        aria-hidden="true"
        className={`shrink-0 font-mono text-xs tabular-nums ${step.status === "failed" ? "text-red-600 dark:text-red-400" : "text-zinc-500"}`}
      >
        {step.status === "succeeded" ? duration : step.status === "failed" && duration ? `Failed · ${duration}` : stepLabel[step.status]}
      </span>
      {expandable ? (
        <Chevron />
      ) : (
        <span aria-hidden="true" className="size-3.5 shrink-0" />
      )}
    </>
  );

  return (
    <li id={domId} tabIndex={-1} data-slot="step" data-status={step.status} className={`min-w-0 outline-none ${rise}`}>
      {expandable ? (
        <details className={disclosure}>
          <summary className={`${rowClass} ${summaryClass}`}>{row}</summary>
          <div className={`grid grid-cols-[minmax(0,1fr)] gap-3 pt-1 pb-3 pl-7 opacity-0 transition-opacity duration-200 ${ease} group-open:opacity-100 motion-reduce:transition-none`}>
            {hasInput ? <Well label={hasOutput ? "Input" : undefined}>{JSON.stringify(step.input, null, 2)}</Well> : null}
            {hasOutput ? (
              <Well label={hasInput ? "Output" : undefined} wrap>
                {step.output!}
              </Well>
            ) : null}
          </div>
        </details>
      ) : (
        <div className={rowClass}>{row}</div>
      )}
      {step.status === "failed" && step.error ? (
        <p className={`-mt-1 pb-2 pl-7 text-xs leading-relaxed text-red-700 dark:text-red-400 ${rise}`}>{step.error}</p>
      ) : null}
    </li>
  );
}

/** A preformatted value inside an opened step. `wrap` soft-wraps tool output; JSON keeps its layout. */
function Well({ label, wrap = false, children }: { label?: string; wrap?: boolean; children: string }) {
  return (
    <div>
      {label ? <p className="mb-1.5 text-xs font-medium text-zinc-500">{label}</p> : null}
      <pre
        className={[
          wrap ? "break-words whitespace-pre-wrap" : "overflow-x-auto",
          "rounded-lg border border-zinc-950/[0.07] bg-zinc-950/[0.02] px-3 py-2.5 font-mono text-xs leading-relaxed text-zinc-800 dark:border-white/[0.08] dark:bg-transparent dark:text-zinc-300",
        ].join(" ")}
      >
        {children}
      </pre>
    </div>
  );
}

/**
 * An approval inline in the run. When the decision lands and its buttons go away, focus moves
 * to the approval itself so keyboard and screen reader users stay where they were.
 */
function ApprovalItem({
  approval,
  onApprove,
  onReject,
}: {
  approval: RunApproval;
  onApprove?: (approvalId: string) => void | Promise<void>;
  onReject?: (approvalId: string) => void | Promise<void>;
}) {
  const ref = useRef<HTMLLIElement>(null);
  const previous = useRef(approval.status);

  useEffect(() => {
    const was = previous.current;
    previous.current = approval.status;
    const element = ref.current;
    if (was !== "pending" || approval.status === "pending" || !element) return;
    const active = document.activeElement;
    if (!active || active === document.body || element.contains(active)) element.focus({ preventScroll: true });
  }, [approval.status]);

  if (approval.status === "pending") {
    return (
      <li ref={ref} tabIndex={-1} className={`my-2 min-w-0 outline-none ${rise}`}>
        <ApprovalCard
          title={approval.title}
          description={approval.description}
          detail={approval.detail}
          status={approval.status}
          onApprove={onApprove ? () => onApprove(approval.id) : undefined}
          onReject={onReject ? () => onReject(approval.id) : undefined}
        />
      </li>
    );
  }

  // Once decided, the approval settles into a row like the steps; what it covered opens in place.
  const decision = decisions[approval.status];
  const row = (
    <>
      <span aria-hidden="true" className={`flex h-5 w-4 shrink-0 items-center justify-center ${decision.tone}`}>
        <DecisionGlyph status={approval.status} />
      </span>
      <span className="flex min-w-0 flex-1 items-baseline gap-2.5">
        <span className={`shrink-0 text-sm font-medium ${decision.tone}`}>{decision.label}</span>
        <span className="min-w-0 truncate text-sm text-zinc-600 dark:text-zinc-400">{approval.title}</span>
      </span>
      <span aria-hidden="true" className="hidden shrink-0 text-xs text-zinc-500 sm:inline">
        {decision.outcome}
      </span>
      <span className="sr-only">{decision.outcome}</span>
    </>
  );

  return (
    <li ref={ref} tabIndex={-1} data-slot="approval" data-status={approval.status} className={`min-w-0 outline-none ${rise}`}>
      {approval.detail || approval.description ? (
        <details className={disclosure}>
          <summary className={`${rowClass} ${summaryClass}`}>
            {row}
            <Chevron />
          </summary>
          <div className={`grid grid-cols-[minmax(0,1fr)] gap-2 pt-1 pb-3 pl-7 opacity-0 transition-opacity duration-200 ${ease} group-open:opacity-100 motion-reduce:transition-none`}>
            {approval.description ? <p className="text-sm text-pretty text-zinc-600 dark:text-zinc-400">{approval.description}</p> : null}
            {approval.detail ? <Well wrap>{approval.detail}</Well> : null}
          </div>
        </details>
      ) : (
        <div className={rowClass}>
          {row}
          <span aria-hidden="true" className="size-3.5 shrink-0" />
        </div>
      )}
    </li>
  );
}

const decisions: Record<Exclude<RunApproval["status"], "pending">, { label: string; outcome: string; tone: string }> = {
  approved: { label: "Approved", outcome: "The agent continued.", tone: "text-emerald-700 dark:text-emerald-400" },
  rejected: { label: "Rejected", outcome: "Nothing ran.", tone: "text-red-700 dark:text-red-400" },
  expired: { label: "Expired", outcome: "Nothing ran.", tone: "text-zinc-500" },
};

/** The approval glyphs from Approval Card: check, x, or slash in a circle. */
function DecisionGlyph({ status }: { status: RunApproval["status"] }) {
  return (
    <svg
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth={1.5}
      strokeLinecap="round"
      strokeLinejoin="round"
      className={`size-4 transition-[opacity,scale] duration-200 ${ease} starting:scale-90 starting:opacity-0 motion-reduce:transition-none`}
    >
      <circle cx="8" cy="8" r="6.25" />
      {status === "approved" ? (
        <path d="m5.35 8.25 1.75 1.75 3.55-3.75" />
      ) : status === "rejected" ? (
        <path d="m6.1 6.1 3.8 3.8m0-3.8-3.8 3.8" />
      ) : (
        <path d="m5.6 10.4 4.8-4.8" />
      )}
    </svg>
  );
}

/** The outline rail: every step and file at a glance; choosing one scrolls the run to it. */
function Outline({ run, onReveal }: { run: AgentRun; onReveal: (key: string) => void }) {
  const button = [
    "flex w-full min-w-0 items-center gap-2.5 rounded-md px-2 py-1.5 text-left",
    "transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] motion-reduce:transition-none dark:hover:bg-white/[0.06]",
    "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
  ].join(" ");

  return (
    <div className="grid gap-6">
      <div>
        <p className="px-2 text-xs font-medium text-zinc-500">Steps</p>
        {run.steps.length ? (
          <ol className="mt-1.5 grid">
            {run.steps.map((step) => (
              <li key={step.id} data-slot="outline-step" data-status={step.status}>
                <button type="button" onClick={() => onReveal(`step-${step.id}`)} className={button}>
                  <OutlineGlyph status={step.status} />
                  <span
                    className={[
                      "min-w-0 flex-1 truncate font-mono text-xs",
                      step.status === "queued" || step.status === "skipped" ? "text-zinc-500" : "text-zinc-800 dark:text-zinc-200",
                      step.status === "skipped" ? "line-through decoration-zinc-500/60" : "",
                    ].join(" ")}
                  >
                    {step.name}
                  </span>
                  <span className="sr-only">, {stepLabel[step.status]}</span>
                  {step.startedAt && step.finishedAt ? (
                    <span aria-hidden="true" className="shrink-0 font-mono text-[11px] text-zinc-500 tabular-nums">
                      {formatDuration(step.startedAt, step.finishedAt)}
                    </span>
                  ) : null}
                </button>
              </li>
            ))}
          </ol>
        ) : (
          <p className="mt-1.5 px-2 text-xs text-zinc-500">None yet</p>
        )}
      </div>
      {run.artifacts.length ? (
        <div>
          <p className="px-2 text-xs font-medium text-zinc-500">Files</p>
          <ul className="mt-1.5 grid">
            {run.artifacts.map((artifact) => (
              <li key={artifact.id}>
                <button type="button" onClick={() => onReveal(`artifact-${artifact.id}`)} className={button}>
                  <span className="min-w-0 flex-1 truncate text-xs text-zinc-800 dark:text-zinc-200">{artifact.name}</span>
                  <span
                    className={`shrink-0 text-[11px] ${artifact.status === "failed" ? "text-red-600 dark:text-red-400" : "text-zinc-500"}`}
                  >
                    {artifact.status === "generating" ? "Writing" : artifact.status === "failed" ? "Failed" : "Ready"}
                  </span>
                </button>
              </li>
            ))}
          </ul>
        </div>
      ) : null}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Glyphs and helpers

/**
 * The row's status: the animated mark while running, a bare check, an x, a dash, or a small
 * open dot. Remounted per status so the new shape eases in and the check draws.
 */
function StepGlyph({ status, activity }: { status: StepStatus; activity: AgentActivity }) {
  const enter = `flex h-5 w-4 shrink-0 items-center justify-center transition-[opacity,scale,filter] duration-300 ${ease} starting:scale-75 starting:opacity-0 starting:blur-[2px] motion-reduce:transition-none`;
  if (status === "running") {
    return (
      <span aria-hidden="true" className={enter}>
        <AgentMark activity={activity} size={16} className="text-zinc-950 dark:text-white" />
      </span>
    );
  }
  const tone =
    status === "succeeded"
      ? "text-emerald-600 dark:text-emerald-400"
      : status === "failed"
        ? "text-red-600 dark:text-red-400"
        : "text-zinc-400 dark:text-zinc-600";
  return (
    <span aria-hidden="true" className={enter}>
      <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" className={`size-4 ${tone}`}>
        {status === "succeeded" ? (
          <path
            d="m4.25 8.4 2.5 2.45 5-5.6"
            pathLength={1}
            strokeDasharray="1"
            className={`[stroke-dashoffset:0] transition-[stroke-dashoffset] delay-75 duration-300 ${ease} starting:[stroke-dashoffset:1] motion-reduce:transition-none`}
          />
        ) : status === "failed" ? (
          <path d="m5.25 5.25 5.5 5.5m0-5.5-5.5 5.5" />
        ) : status === "skipped" ? (
          <path d="M5.5 8h5" />
        ) : (
          <circle cx="8" cy="8" r="3" />
        )}
      </svg>
    </span>
  );
}

/** Still versions of the step glyphs for the outline; only the run itself animates. */
function OutlineGlyph({ status }: { status: StepStatus }) {
  const tone =
    status === "succeeded"
      ? "text-emerald-600 dark:text-emerald-400"
      : status === "failed"
        ? "text-red-600 dark:text-red-400"
        : status === "running"
          ? "text-zinc-950 dark:text-white"
          : "text-zinc-400 dark:text-zinc-600";
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.6} strokeLinecap="round" strokeLinejoin="round" className={`size-3.5 shrink-0 ${tone}`}>
      {status === "succeeded" ? (
        <path d="m4.25 8.4 2.5 2.45 5-5.6" />
      ) : status === "failed" ? (
        <path d="m5.25 5.25 5.5 5.5m0-5.5-5.5 5.5" />
      ) : status === "skipped" ? (
        <path d="M5.5 8h5" />
      ) : status === "running" ? (
        <circle cx="8" cy="8" r="3" fill="currentColor" stroke="none" />
      ) : (
        <circle cx="8" cy="8" r="3" />
      )}
    </svg>
  );
}

/** Picks the mark and verb for what a step is doing, from its tool name. */
function activityOf(step?: RunStep): { activity: AgentActivity; label: string } {
  if (!step) return { activity: "thinking", label: "Thinking" };
  const name = step.name.toLowerCase();
  if (/search|find|query|lookup|grep|browse/.test(name)) return { activity: "searching", label: "Searching" };
  if (/read|fetch|load|download|list/.test(name)) return { activity: "searching", label: "Reading" };
  if (/plan|think|reason/.test(name)) return { activity: "planning", label: "Planning" };
  if (/edit|write|patch|create|update|generate|draft/.test(name)) return { activity: "shaping", label: "Editing" };
  return { activity: "working", label: "Working" };
}

function time(iso?: string): number {
  const value = iso ? Date.parse(iso) : Number.NaN;
  return Number.isNaN(value) ? Number.POSITIVE_INFINITY : value;
}

/** Time from the run's start to its end, or to the latest event while it is still going. */
function elapsedOf(run: AgentRun): string {
  const start = run.createdAt ? Date.parse(run.createdAt) : Number.NaN;
  if (Number.isNaN(start)) return "";
  const stamps = [run.finishedAt, ...run.steps.flatMap((step) => [step.startedAt, step.finishedAt]), ...run.approvals.map((approval) => approval.decidedAt)]
    .map((value) => (value ? Date.parse(value) : Number.NaN))
    .filter((value) => !Number.isNaN(value));
  const end = run.finishedAt ? Date.parse(run.finishedAt) : Math.max(...stamps);
  const ms = end - start;
  if (!Number.isFinite(ms) || ms <= 0) return "";
  if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`;
  return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;
}

function formatDuration(start: string, end: string): string {
  const ms = new Date(end).getTime() - new Date(start).getTime();
  if (!Number.isFinite(ms) || ms < 0) return "";
  return ms < 1000 ? `${ms} ms` : `${(ms / 1000).toFixed(1)} s`;
}

Vue

A native Vue 3 implementation ships in the Vue pilot. Run the same command in a Vite + Vue project; the CLI detects Vue and installs these files instead. The live preview above is the React version; the Vue example below is built in a clean Vite + Vue app by CI.

agent-workspace-example.vue
<script setup lang="ts">
import { ref } from "vue";
import type { AgentRun } from "@/components/shaken/agent/agent-run";
import AgentWorkspace from "@/components/shaken/blocks/AgentWorkspace.vue";

// In your app, build the run from your backend's events with applyEvents (see agent-run).
const run = ref<AgentRun>({
  id: "run_1",
  title: "Update the rate-limit docs",
  status: "waiting-for-approval",
  createdAt: "2026-11-14T10:00:00.000Z",
  messages: [{ id: "m1", role: "user", status: "complete", content: "Update the rate limits and open a pull request." }],
  steps: [
    { id: "s1", name: "search_docs", kind: "tool", status: "succeeded", summary: "Find pages that mention rate limits", input: { query: "rate limits" }, output: "Found 3 pages.", startedAt: "2026-11-14T10:00:00.600Z", finishedAt: "2026-11-14T10:00:01.400Z" },
    { id: "s2", name: "edit_files", kind: "tool", status: "succeeded", summary: "Update the limits table", output: "Changed 1 file.", startedAt: "2026-11-14T10:00:01.600Z", finishedAt: "2026-11-14T10:00:02.600Z" },
  ],
  approvals: [{ id: "a1", title: "Open a pull request?", status: "pending", detail: 'gh pr create --title "Update rate limits"' }],
  artifacts: [{ id: "f1", name: "rate-limits.md", type: "text/markdown", status: "ready", content: "Free: 60/min\nPro: 600/min" }],
});

async function decide(id: string, status: "approved" | "rejected") {
  await new Promise((resolve) => setTimeout(resolve, 500)); // your API call
  run.value = {
    ...run.value,
    status: status === "approved" ? "running" : "cancelled",
    approvals: run.value.approvals.map((a) => (a.id === id ? { ...a, status, decidedAt: new Date().toISOString() } : a)),
  };
}
</script>

<template>
  <AgentWorkspace :run="run" height="36rem" :on-approve="(id) => decide(id, 'approved')" :on-reject="(id) => decide(id, 'rejected')" />
</template>
  • src/components/shaken/blocks/AgentWorkspace.vuevue/agent-workspace@0.3.0
blocks/AgentWorkspace.vueShow
blocks/AgentWorkspace.vue
<script setup lang="ts">
import { computed, nextTick, onMounted, ref, useId, watch } from "vue";
import type { AgentRun, RunApproval, RunArtifact, RunStatus, RunStep, StepStatus } from "../agent/agent-run";
import AgentMark from "../agent/AgentMark.vue";
import AgentState from "../agent/AgentState.vue";
import type { AgentActivity, AgentPhase } from "../agent/agent-marks";
import Button from "../ui/Button.vue";

/**
 * A compact agent workspace for Vue, laid out as one document of the run: a slim header with
 * the run's state and a progress hairline, then the request, each step as a one-line row that
 * opens in place, files, approvals, and the streamed reply, with the prompt box pinned
 * underneath. It renders the run you pass (see agent-run's applyEvents) and reports actions.
 */
const props = withDefaults(
  defineProps<{
    run: AgentRun;
    /** Receives the trimmed prompt. */
    onSubmit?: (prompt: string) => void | Promise<void>;
    /** Shows a Stop button while the run is working. */
    onStop?: () => void;
    /** Called once per decision; buttons ignore clicks until it settles. Verify on your backend. */
    onApprove?: (approvalId: string) => void | Promise<void>;
    onReject?: (approvalId: string) => void | Promise<void>;
    /** Height of the workspace. The run scrolls between the header and the prompt box. Pass "100%" to fill a pane. */
    height?: string;
    placeholder?: string;
  }>(),
  { height: "36rem", placeholder: "Ask the agent to do something…" },
);

defineSlots<{
  /** Optional notice above the run, e.g. a connection message. */
  banner?: () => unknown;
}>();

const runStatus: Record<RunStatus, { label: string; phase: AgentPhase }> = {
  queued: { label: "Queued", phase: "idle" },
  running: { label: "Running", phase: "active" },
  "waiting-for-approval": { label: "Needs approval", phase: "waiting" },
  succeeded: { label: "Succeeded", phase: "done" },
  failed: { label: "Failed", phase: "failed" },
  cancelled: { label: "Cancelled", phase: "cancelled" },
};

const stepLabel: Record<StepStatus, string> = {
  queued: "Queued",
  running: "Running",
  succeeded: "Done",
  failed: "Failed",
  skipped: "Skipped",
};

const decisions: Record<Exclude<RunApproval["status"], "pending">, { label: string; outcome: string; tone: string }> = {
  approved: { label: "Approved", outcome: "The agent continued.", tone: "text-emerald-700 dark:text-emerald-400" },
  rejected: { label: "Rejected", outcome: "Nothing ran.", tone: "text-red-700 dark:text-red-400" },
  expired: { label: "Expired", outcome: "Nothing ran.", tone: "text-zinc-500" },
};

const id = useId();
const prompt = ref("");
const deciding = ref<string | null>(null);
const decisionError = ref<string | null>(null);
const scroller = ref<HTMLElement | null>(null);

// ---------------------------------------------------------------------------
// The run, as a list of activity

type ActivityItem =
  | { kind: "step"; key: string; status: string; step: RunStep }
  | { kind: "artifact"; key: string; status: string; artifact: RunArtifact }
  | { kind: "approval"; key: string; status: string; approval: RunApproval };

/**
 * Steps, files, and approvals in a sensible order for a run loaded all at once: steps in the
 * order they started, a decided approval before the steps that started after the decision,
 * then files, then anything still waiting for a decision.
 */
function activityItems(run: AgentRun): ActivityItem[] {
  const ordered: ActivityItem[] = run.steps.map((step) => ({ kind: "step", key: `step-${step.id}`, status: step.status, step }));
  for (const approval of run.approvals) {
    if (approval.status === "pending") continue;
    const decided = time(approval.decidedAt);
    const index = ordered.findIndex((item) => item.kind === "step" && time(item.step.startedAt) > decided);
    const entry: ActivityItem = { kind: "approval", key: `approval-${approval.id}`, status: approval.status, approval };
    if (index === -1) ordered.push(entry);
    else ordered.splice(index, 0, entry);
  }
  for (const artifact of run.artifacts) ordered.push({ kind: "artifact", key: `artifact-${artifact.id}`, status: artifact.status, artifact });
  for (const approval of run.approvals) {
    if (approval.status === "pending") ordered.push({ kind: "approval", key: `approval-${approval.id}`, status: approval.status, approval });
  }
  return ordered;
}

// Entries keep the order they first appeared, so a streamed run reads in the order it happened
// and nothing jumps when an approval is decided. Entries that arrive together take the order above.
const arrival = new Map<string, number>();
let nextArrival = 0;
const items = computed(() => {
  const list = activityItems(props.run);
  const present = new Set(list.map((item) => item.key));
  for (const key of arrival.keys()) if (!present.has(key)) arrival.delete(key);
  if (arrival.size === 0) nextArrival = 0;
  for (const item of list) if (!arrival.has(item.key)) arrival.set(item.key, nextArrival++);
  return list.sort((a, b) => arrival.get(a.key)! - arrival.get(b.key)!);
});

const firstReply = computed(() => props.run.messages.findIndex((message) => message.role === "assistant"));
const lead = computed(() => (firstReply.value === -1 ? props.run.messages : props.run.messages.slice(0, firstReply.value)));
const rest = computed(() => (firstReply.value === -1 ? [] : props.run.messages.slice(firstReply.value)));
const empty = computed(() => props.run.messages.length === 0 && items.value.length === 0);

const writing = computed(() => props.run.messages.some((message) => message.role === "assistant" && message.status === "streaming"));
const activity = computed(() => (writing.value ? { activity: "thinking" as const, label: "Writing" } : activityOf(props.run.steps.find((step) => step.status === "running"))));
const meta = computed(() => runStatus[props.run.status]);
const statusLabel = computed(() => (props.run.status === "running" ? activity.value.label : meta.value.label));

const settled = computed(() => props.run.steps.filter((step) => step.status !== "queued" && step.status !== "running").length);
const progress = computed(() => (props.run.status === "succeeded" ? 1 : props.run.steps.length ? settled.value / props.run.steps.length : 0));
const elapsed = computed(() => elapsedOf(props.run));
const busy = computed(() => props.run.status === "running" || props.run.status === "waiting-for-approval");
const failedStepShown = computed(() => props.run.steps.some((step) => step.status === "failed" && step.error));
const contentKey = computed(() => `${props.run.messages.reduce((total, message) => total + message.content.length, 0)}:${items.value.map((item) => item.status).join()}`);

// ---------------------------------------------------------------------------
// Scrolling, focus, and actions

const following = ref(true);
function onScroll() {
  const element = scroller.value;
  if (element) following.value = element.scrollHeight - element.scrollTop - element.clientHeight < 32;
}
function toBottom() {
  const element = scroller.value;
  if (element) element.scrollTop = element.scrollHeight;
}
// Follow new content only while the reader is at the bottom.
watch(contentKey, async () => {
  if (!following.value) return;
  await nextTick();
  toBottom();
});
onMounted(toBottom);

// When a decision lands and its buttons go away, focus moves to the approval itself so keyboard
// and screen reader users stay where they were.
watch(
  () => props.run.approvals.map((approval) => `${approval.id}:${approval.status}`),
  async (now, before) => {
    const was = new Map(before.map((entry) => [entry.slice(0, entry.lastIndexOf(":")), entry.slice(entry.lastIndexOf(":") + 1)]));
    const decided = props.run.approvals.find((approval) => approval.status !== "pending" && was.get(approval.id) === "pending");
    if (!decided) return;
    const holder = document.getElementById(`${id}-approval-${decided.id}`);
    const active = document.activeElement;
    const kept = !active || active === document.body || (holder?.contains(active) ?? false);
    await nextTick();
    if (kept) document.getElementById(`${id}-approval-${decided.id}`)?.focus({ preventScroll: true });
  },
);

async function send() {
  const text = prompt.value.trim();
  if (!text || busy.value) return;
  await props.onSubmit?.(text);
  prompt.value = "";
}

function onKeydown(event: KeyboardEvent) {
  if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
    event.preventDefault();
    void send();
  }
}

async function decide(approvalId: string, approved: boolean) {
  // A plain guard (not just the disabled state) ignores double clicks that land before a re-render.
  if (deciding.value) return;
  deciding.value = `${approvalId}:${approved ? "approve" : "reject"}`;
  decisionError.value = null;
  try {
    await (approved ? props.onApprove : props.onReject)?.(approvalId);
  } catch {
    decisionError.value = approvalId;
  } finally {
    deciding.value = null;
  }
}

// ---------------------------------------------------------------------------
// Helpers

/** Picks the mark and verb for what a step is doing, from its tool name. */
function activityOf(step?: RunStep): { activity: AgentActivity; label: string } {
  if (!step) return { activity: "thinking", label: "Thinking" };
  const name = step.name.toLowerCase();
  if (/search|find|query|lookup|grep|browse/.test(name)) return { activity: "searching", label: "Searching" };
  if (/read|fetch|load|download|list/.test(name)) return { activity: "searching", label: "Reading" };
  if (/plan|think|reason/.test(name)) return { activity: "planning", label: "Planning" };
  if (/edit|write|patch|create|update|generate|draft/.test(name)) return { activity: "shaping", label: "Editing" };
  return { activity: "working", label: "Working" };
}

function time(iso?: string): number {
  const value = iso ? Date.parse(iso) : Number.NaN;
  return Number.isNaN(value) ? Number.POSITIVE_INFINITY : value;
}

/** Time from the run's start to its end, or to the latest event while it is still going. */
function elapsedOf(run: AgentRun): string {
  const start = run.createdAt ? Date.parse(run.createdAt) : Number.NaN;
  if (Number.isNaN(start)) return "";
  const stamps = [run.finishedAt, ...run.steps.flatMap((step) => [step.startedAt, step.finishedAt]), ...run.approvals.map((approval) => approval.decidedAt)]
    .map((value) => (value ? Date.parse(value) : Number.NaN))
    .filter((value) => !Number.isNaN(value));
  const end = run.finishedAt ? Date.parse(run.finishedAt) : Math.max(...stamps);
  const ms = end - start;
  if (!Number.isFinite(ms) || ms <= 0) return "";
  if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`;
  return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;
}

function duration(step: RunStep): string {
  if (!step.startedAt || !step.finishedAt) return "";
  const ms = new Date(step.finishedAt).getTime() - new Date(step.startedAt).getTime();
  if (!Number.isFinite(ms) || ms < 0) return "";
  return ms < 1000 ? `${ms} ms` : `${(ms / 1000).toFixed(1)} s`;
}

function stepMeta(step: RunStep): string {
  const took = duration(step);
  return step.status === "succeeded" ? took : step.status === "failed" && took ? `Failed · ${took}` : stepLabel[step.status];
}

const glyphTone: Record<Exclude<StepStatus, "running">, string> = {
  succeeded: "text-emerald-600 dark:text-emerald-400",
  failed: "text-red-600 dark:text-red-400",
  queued: "text-zinc-400 dark:text-zinc-600",
  skipped: "text-zinc-400 dark:text-zinc-600",
};

function fileState(artifact: RunArtifact): string {
  return artifact.status === "generating" ? "Writing" : artifact.status === "failed" ? "Failed" : "Ready";
}

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
/** New entries settle in with a short rise; instant with reduced motion. */
const rise = `transition-[opacity,translate] duration-200 ${ease} starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none`;
const enterGlyph = `flex h-5 w-4 shrink-0 items-center justify-center transition-[opacity,scale,filter] duration-300 ${ease} starting:scale-75 starting:opacity-0 starting:blur-[2px] motion-reduce:transition-none`;
const rowClass = "-mx-2 flex min-h-9 items-center gap-3 rounded-lg px-2 py-1.5";
const summaryClass = [
  "cursor-pointer list-none select-none [&::-webkit-details-marker]:hidden",
  "transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] motion-reduce:transition-none dark:hover:bg-white/[0.06]",
  "focus-visible:outline-2 focus-visible:outline-sky-500",
].join(" ");
const disclosure = [
  "group [interpolate-size:allow-keywords]",
  // Height animates where ::details-content and interpolate-size are supported; elsewhere it simply opens.
  "[&::details-content]:h-0 [&::details-content]:overflow-clip [&::details-content]:transition-[height,content-visibility] [&::details-content]:duration-[220ms] [&::details-content]:ease-[cubic-bezier(0.23,1,0.32,1)] [&::details-content]:[transition-behavior:allow-discrete]",
  "open:[&::details-content]:h-auto motion-reduce:[&::details-content]:transition-none",
].join(" ");
const opened = `grid grid-cols-[minmax(0,1fr)] gap-3 pt-1 pb-3 pl-7 opacity-0 transition-opacity duration-200 ${ease} group-open:opacity-100 motion-reduce:transition-none`;
const chevron = `size-3.5 shrink-0 text-zinc-400 transition-transform duration-200 ${ease} group-open:rotate-90 motion-reduce:transition-none dark:text-zinc-500`;
const well =
  "rounded-lg border border-zinc-950/[0.07] bg-zinc-950/[0.02] px-3 py-2.5 font-mono text-xs leading-relaxed text-zinc-800 dark:border-white/[0.08] dark:bg-transparent dark:text-zinc-300";
</script>

<template>
  <div :data-status="props.run.status" :style="{ height: props.height }" class="flex min-h-0 w-full flex-col text-zinc-950 dark:text-white">
    <header class="relative flex min-w-0 items-center gap-3 pb-3">
      <h3 class="min-w-0 flex-1 truncate text-sm leading-6 font-semibold">{{ props.run.title }}</h3>
      <p v-if="props.run.steps.length || elapsed" class="shrink-0 font-mono text-xs text-zinc-500 tabular-nums">
        <span v-if="props.run.steps.length" class="hidden sm:inline"
          >{{ settled }} of {{ props.run.steps.length }} {{ props.run.steps.length === 1 ? "step" : "steps"
          }}<span v-if="elapsed" aria-hidden="true"> · </span></span
        >
        <template v-if="elapsed"><span class="sr-only">Elapsed </span>{{ elapsed }}</template>
      </p>
      <!-- A live region whose text is exactly the status label; the mark is decorative. -->
      <AgentState
        status
        data-slot="run-status"
        size="sm"
        class="shrink-0"
        :activity="activity.activity"
        :phase="meta.phase"
        :label="statusLabel"
      />
      <!-- The header's bottom edge is the progress line: it fills as steps settle. -->
      <span aria-hidden="true" class="absolute inset-x-0 bottom-0 h-px overflow-hidden bg-zinc-950/[0.07] dark:bg-white/[0.08]">
        <span
          :class="[
            'absolute inset-0 origin-left transition-[scale,background-color] duration-500 motion-reduce:transition-none',
            ease,
            props.run.status === 'failed'
              ? 'bg-red-500/70'
              : props.run.status === 'waiting-for-approval'
                ? 'bg-amber-500/70'
                : 'bg-zinc-950/35 dark:bg-white/45',
          ]"
          :style="{ scale: `${progress} 1` }"
        />
      </span>
    </header>

    <section aria-label="Run" class="flex min-h-0 min-w-0 flex-1 flex-col">
      <div v-if="$slots.banner" class="px-2 pt-4">
        <div class="mx-auto max-w-2xl"><slot name="banner" /></div>
      </div>
      <div
        ref="scroller"
        role="log"
        aria-live="polite"
        aria-relevant="additions text"
        tabindex="0"
        aria-label="Run activity"
        class="min-h-0 flex-1 overflow-y-auto overscroll-contain px-2 [mask-image:linear-gradient(to_bottom,transparent,#000_1.25rem,#000_calc(100%-1.25rem),transparent)] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500"
        @scroll.passive="onScroll"
      >
        <div class="mx-auto flex min-h-full w-full max-w-2xl flex-col py-6">
          <div v-if="empty" class="m-auto max-w-xs py-10 text-center">
            <p class="text-sm font-medium">Describe a task</p>
            <p class="mt-1 text-sm text-pretty text-zinc-500">The agent's steps, files, and reply build up here as one record of the run.</p>
          </div>

          <!-- The request that starts a turn: the document's opening line, not a chat bubble. -->
          <article v-for="(message, index) in lead" :key="message.id" data-role="user" :class="[rise, index ? 'mt-3' : '']">
            <p class="sr-only">You:</p>
            <p class="text-[15px] leading-relaxed font-medium tracking-[-0.005em] break-words whitespace-pre-wrap text-pretty">{{ message.content }}</p>
          </article>

          <ol v-if="items.length" aria-label="Activity" :class="['flex flex-col', lead.length ? 'mt-5' : '']">
            <template v-for="item in items" :key="item.key">
              <!-- One step on one line: status, tool name, what it does, and how long it took. Opens in place. -->
              <li
                v-if="item.kind === 'step'"
                :id="`${id}-${item.key}`"
                tabindex="-1"
                data-slot="step"
                :data-status="item.step.status"
                :class="['min-w-0 outline-none', rise]"
              >
                <component
                  :is="item.step.input !== undefined || (item.step.status === 'succeeded' && item.step.output != null) ? 'details' : 'div'"
                  :class="item.step.input !== undefined || (item.step.status === 'succeeded' && item.step.output != null) ? disclosure : undefined"
                >
                  <component
                    :is="item.step.input !== undefined || (item.step.status === 'succeeded' && item.step.output != null) ? 'summary' : 'div'"
                    :class="[rowClass, item.step.input !== undefined || (item.step.status === 'succeeded' && item.step.output != null) ? summaryClass : '']"
                  >
                    <!-- Remounted per status so the new shape eases in and the check draws. -->
                    <span :key="item.step.status" aria-hidden="true" :class="enterGlyph">
                      <AgentMark v-if="item.step.status === 'running'" :activity="activityOf(item.step).activity" :size="16" class="text-zinc-950 dark:text-white" />
                      <svg
                        v-else
                        viewBox="0 0 16 16"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="1.5"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        :class="['size-4', glyphTone[item.step.status]]"
                      >
                        <path
                          v-if="item.step.status === 'succeeded'"
                          d="m4.25 8.4 2.5 2.45 5-5.6"
                          path-length="1"
                          stroke-dasharray="1"
                          :class="`[stroke-dashoffset:0] transition-[stroke-dashoffset] delay-75 duration-300 ${ease} starting:[stroke-dashoffset:1] motion-reduce:transition-none`"
                        />
                        <path v-else-if="item.step.status === 'failed'" d="m5.25 5.25 5.5 5.5m0-5.5-5.5 5.5" />
                        <path v-else-if="item.step.status === 'skipped'" d="M5.5 8h5" />
                        <circle v-else cx="8" cy="8" r="3" />
                      </svg>
                    </span>
                    <span class="flex min-w-0 flex-1 items-baseline gap-2.5">
                      <span
                        aria-hidden="true"
                        :class="[
                          'max-w-[65%] shrink-0 truncate font-mono text-[13px] transition-colors duration-200 motion-reduce:transition-none',
                          item.step.status === 'queued' || item.step.status === 'skipped' ? 'text-zinc-500' : 'text-zinc-950 dark:text-white',
                          item.step.status === 'skipped' ? 'line-through decoration-zinc-500/60' : '',
                        ]"
                        >{{ item.step.name }}</span
                      >
                      <!-- Remounts with the status, so the log announces "search_docs, Done". -->
                      <span :key="item.step.status" class="sr-only">{{ item.step.name }}, {{ stepLabel[item.step.status] }}.</span>
                      <span v-if="item.step.summary" class="min-w-0 truncate text-sm text-zinc-500">{{ item.step.summary }}</span>
                    </span>
                    <span
                      aria-hidden="true"
                      :class="['shrink-0 font-mono text-xs tabular-nums', item.step.status === 'failed' ? 'text-red-600 dark:text-red-400' : 'text-zinc-500']"
                      >{{ stepMeta(item.step) }}</span
                    >
                    <svg
                      v-if="item.step.input !== undefined || (item.step.status === 'succeeded' && item.step.output != null)"
                      aria-hidden="true"
                      viewBox="0 0 16 16"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="1.5"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      :class="chevron"
                    >
                      <path d="m6.25 4.5 3.5 3.5-3.5 3.5" />
                    </svg>
                    <span v-else aria-hidden="true" class="size-3.5 shrink-0" />
                  </component>
                  <div v-if="item.step.input !== undefined || (item.step.status === 'succeeded' && item.step.output != null)" :class="opened">
                    <div v-if="item.step.input !== undefined">
                      <p v-if="item.step.status === 'succeeded' && item.step.output != null" class="mb-1.5 text-xs font-medium text-zinc-500">Input</p>
                      <pre :class="['overflow-x-auto', well]">{{ JSON.stringify(item.step.input, null, 2) }}</pre>
                    </div>
                    <div v-if="item.step.status === 'succeeded' && item.step.output != null">
                      <p v-if="item.step.input !== undefined" class="mb-1.5 text-xs font-medium text-zinc-500">Output</p>
                      <pre :class="['break-words whitespace-pre-wrap', well]">{{ item.step.output }}</pre>
                    </div>
                  </div>
                </component>
                <p v-if="item.step.status === 'failed' && item.step.error" :class="['-mt-1 pb-2 pl-7 text-xs leading-relaxed text-red-700 dark:text-red-400', rise]">
                  {{ item.step.error }}
                </p>
              </li>

              <!-- A file the run produced: name, path, and whether it is ready. Text files open in place. -->
              <li
                v-else-if="item.kind === 'artifact'"
                :id="`${id}-${item.key}`"
                tabindex="-1"
                data-slot="artifact"
                :data-status="item.artifact.status"
                :class="['min-w-0 outline-none', rise]"
              >
                <component :is="item.artifact.content ? 'details' : 'div'" :class="item.artifact.content ? disclosure : undefined">
                  <component :is="item.artifact.content ? 'summary' : 'div'" :class="[rowClass, item.artifact.content ? summaryClass : '']">
                    <span aria-hidden="true" class="flex h-5 w-4 shrink-0 items-center justify-center text-zinc-500">
                      <AgentMark v-if="item.artifact.status === 'generating'" activity="shaping" :size="16" class="text-zinc-950 dark:text-white" />
                      <svg v-else viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" class="size-4">
                        <path d="M4 2.75h5.25L12 5.5v7.75H4z" />
                        <path d="M9 2.75V5.75h3" />
                      </svg>
                    </span>
                    <span class="flex min-w-0 flex-1 items-baseline gap-2.5">
                      <span class="max-w-[65%] shrink-0 truncate text-sm font-medium">{{ item.artifact.name }}</span>
                      <span v-if="item.artifact.path" class="min-w-0 truncate font-mono text-xs text-zinc-500">{{ item.artifact.path }}</span>
                    </span>
                    <span :class="['shrink-0 text-xs', item.artifact.status === 'failed' ? 'text-red-600 dark:text-red-400' : 'text-zinc-500']">{{
                      fileState(item.artifact)
                    }}</span>
                    <svg
                      v-if="item.artifact.content"
                      aria-hidden="true"
                      viewBox="0 0 16 16"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="1.5"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      :class="chevron"
                    >
                      <path d="m6.25 4.5 3.5 3.5-3.5 3.5" />
                    </svg>
                    <span v-else aria-hidden="true" class="size-3.5 shrink-0" />
                  </component>
                  <div v-if="item.artifact.content" :class="opened">
                    <pre :class="['max-h-64 overflow-auto break-words whitespace-pre-wrap', well]">{{ item.artifact.content }}</pre>
                  </div>
                </component>
                <p v-if="item.artifact.status === 'failed' && item.artifact.error" class="-mt-1 pb-2 pl-7 text-xs text-red-700 dark:text-red-400">
                  {{ item.artifact.error }}
                </p>
              </li>

              <!-- An approval waiting for a decision: the question, what will run, then two decisions. -->
              <li
                v-else-if="item.approval.status === 'pending'"
                :id="`${id}-${item.key}`"
                tabindex="-1"
                data-slot="approval"
                data-status="pending"
                :class="['my-2 min-w-0 outline-none', rise]"
              >
                <section
                  :aria-label="`Approval: ${item.approval.title}`"
                  class="rounded-xl border border-zinc-950/10 bg-white p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]"
                >
                  <p role="status" class="flex items-center gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-400">
                    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" class="size-3.5 shrink-0">
                      <circle cx="8" cy="8" r="6.25" />
                      <path d="M6.6 5.9v4.2M9.4 5.9v4.2" />
                    </svg>
                    Needs your approval
                  </p>
                  <h4 class="mt-2 text-[15px] leading-snug font-semibold tracking-[-0.01em] text-pretty">{{ item.approval.title }}</h4>
                  <p v-if="item.approval.description" class="mt-1 text-sm leading-relaxed text-pretty text-zinc-600 dark:text-zinc-400">
                    {{ item.approval.description }}
                  </p>
                  <figure v-if="item.approval.detail" class="mt-3">
                    <figcaption class="sr-only">What will run</figcaption>
                    <pre :class="['overflow-x-auto', well]">{{ item.approval.detail }}</pre>
                  </figure>
                  <div class="mt-4 grid grid-cols-2 gap-2 sm:flex sm:justify-end">
                    <Button
                      size="sm"
                      variant="ghost"
                      class="border border-zinc-950/10 sm:border-transparent dark:border-white/10 sm:dark:border-transparent"
                      :loading="deciding === `${item.approval.id}:reject`"
                      :disabled="deciding === `${item.approval.id}:approve`"
                      @click="decide(item.approval.id, false)"
                      >Reject</Button
                    >
                    <Button
                      size="sm"
                      :loading="deciding === `${item.approval.id}:approve`"
                      :disabled="deciding === `${item.approval.id}:reject`"
                      @click="decide(item.approval.id, true)"
                      >Approve</Button
                    >
                  </div>
                  <p v-if="decisionError === item.approval.id" role="alert" :class="['mt-3 text-sm text-red-600 dark:text-red-400', rise]">
                    Your decision was not saved. Try again.
                  </p>
                </section>
              </li>

              <!-- Once decided, the approval settles into a row like the steps; what it covered opens in place. -->
              <li
                v-else
                :id="`${id}-${item.key}`"
                tabindex="-1"
                data-slot="approval"
                :data-status="item.approval.status"
                :class="['min-w-0 outline-none', rise]"
              >
                <component
                  :is="item.approval.detail || item.approval.description ? 'details' : 'div'"
                  :class="item.approval.detail || item.approval.description ? disclosure : undefined"
                >
                  <component
                    :is="item.approval.detail || item.approval.description ? 'summary' : 'div'"
                    :class="[rowClass, item.approval.detail || item.approval.description ? summaryClass : '']"
                  >
                    <span aria-hidden="true" :class="['flex h-5 w-4 shrink-0 items-center justify-center', decisions[item.approval.status].tone]">
                      <svg
                        viewBox="0 0 16 16"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="1.5"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        :class="`size-4 transition-[opacity,scale] duration-200 ${ease} starting:scale-90 starting:opacity-0 motion-reduce:transition-none`"
                      >
                        <circle cx="8" cy="8" r="6.25" />
                        <path v-if="item.approval.status === 'approved'" d="m5.35 8.25 1.75 1.75 3.55-3.75" />
                        <path v-else-if="item.approval.status === 'rejected'" d="m6.1 6.1 3.8 3.8m0-3.8-3.8 3.8" />
                        <path v-else d="m5.6 10.4 4.8-4.8" />
                      </svg>
                    </span>
                    <span class="flex min-w-0 flex-1 items-baseline gap-2.5">
                      <span :class="['shrink-0 text-sm font-medium', decisions[item.approval.status].tone]">{{ decisions[item.approval.status].label }}</span>
                      <span class="min-w-0 truncate text-sm text-zinc-600 dark:text-zinc-400">{{ item.approval.title }}</span>
                    </span>
                    <span aria-hidden="true" class="hidden shrink-0 text-xs text-zinc-500 sm:inline">{{ decisions[item.approval.status].outcome }}</span>
                    <span class="sr-only">{{ decisions[item.approval.status].outcome }}</span>
                    <svg
                      v-if="item.approval.detail || item.approval.description"
                      aria-hidden="true"
                      viewBox="0 0 16 16"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="1.5"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      :class="chevron"
                    >
                      <path d="m6.25 4.5 3.5 3.5-3.5 3.5" />
                    </svg>
                    <span v-else aria-hidden="true" class="size-3.5 shrink-0" />
                  </component>
                  <div v-if="item.approval.detail || item.approval.description" :class="opened">
                    <p v-if="item.approval.description" class="text-sm text-pretty text-zinc-600 dark:text-zinc-400">{{ item.approval.description }}</p>
                    <pre v-if="item.approval.detail" :class="['break-words whitespace-pre-wrap', well]">{{ item.approval.detail }}</pre>
                  </div>
                </component>
              </li>
            </template>
          </ol>

          <template v-for="message in rest" :key="message.id">
            <article v-if="message.role === 'user'" data-role="user" :class="['mt-8', rise]">
              <p class="sr-only">You:</p>
              <p class="text-[15px] leading-relaxed font-medium tracking-[-0.005em] break-words whitespace-pre-wrap text-pretty">{{ message.content }}</p>
            </article>
            <article
              v-else
              data-role="assistant"
              :data-status="message.status"
              :aria-busy="message.status === 'streaming' || undefined"
              :class="['mt-5 max-w-prose text-sm leading-relaxed', rise]"
            >
              <p class="sr-only">Assistant:</p>
              <p v-if="message.content" class="break-words whitespace-pre-wrap">
                {{ message.content
                }}<span
                  v-if="message.status === 'streaming'"
                  aria-hidden="true"
                  class="ml-1.5 inline-flex align-[-2px] transition-opacity duration-300 starting:opacity-0 motion-reduce:transition-none"
                  ><AgentMark :size="14" class="text-zinc-950/80 dark:text-white/85"
                /></span>
              </p>
              <AgentState v-else-if="message.status === 'streaming'" variant="plain" label="Thinking" class="h-6" />
              <p
                v-if="message.status === 'failed'"
                role="alert"
                class="mt-3 rounded-lg border border-red-500/35 bg-red-500/[0.08] px-3 py-2 text-sm text-red-700 dark:text-red-300"
              >
                {{ message.error ?? "The response stopped before it finished." }}
              </p>
            </article>
          </template>

          <p v-if="props.run.status === 'failed' && props.run.error && !failedStepShown" :class="['mt-5 text-sm text-red-700 dark:text-red-400', rise]">
            {{ props.run.error }}
          </p>
        </div>
      </div>

      <div class="px-2 pt-1">
        <form
          class="mx-auto max-w-2xl rounded-xl border border-zinc-950/10 bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)] transition-[border-color,box-shadow] duration-150 ease-out hover:border-zinc-950/15 focus-within:border-zinc-950/25 focus-within:shadow-[0_0_0_3px_rgb(14_165_233/0.16)] motion-reduce:transition-none dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)] dark:hover:border-white/20 dark:focus-within:border-white/30 dark:focus-within:shadow-[0_0_0_3px_rgb(56_189_248/0.18),inset_0_1px_0_rgb(255_255_255/0.06)]"
          @submit.prevent="send"
        >
          <label :for="`${id}-prompt`" class="sr-only">Message the agent</label>
          <textarea
            :id="`${id}-prompt`"
            v-model="prompt"
            rows="1"
            :placeholder="props.placeholder"
            class="block max-h-48 min-h-11 w-full resize-none bg-transparent px-3.5 pt-3 pb-1 text-sm leading-relaxed text-zinc-950 [field-sizing:content] placeholder:text-zinc-500 focus:outline-none dark:text-white"
            @keydown="onKeydown"
          />
          <div class="flex min-h-11 items-center justify-between gap-3 py-2 pr-2 pl-3.5">
            <AgentState v-if="busy" variant="plain" size="sm" :activity="activity.activity" :phase="meta.phase" :label="statusLabel" />
            <span v-else class="hidden text-xs text-zinc-500 sm:block">Enter to send, Shift+Enter for a new line</span>
            <Button v-if="busy && props.onStop" size="sm" variant="secondary" class="ml-auto" @click="props.onStop()">Stop</Button>
            <Button v-else type="submit" size="sm" class="ml-auto" :disabled="!prompt.trim() || busy">Send</Button>
          </div>
        </form>
      </div>
    </section>
  </div>
</template>