Skip to content
Shaken UI
Sign in

Agent Screen

Save

A live thumbnail of a computer-use agent's screen with its status, the current step and the agent's cursor and clicks, which grows into a larger view with Take over and Stop.

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

Preview

Agent Screen preview
ConnectingBrowser agent

Waiting for the first frame

Installation

npx @shakenui/cli add agent-screen

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

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

Usage

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

import { useEffect, useRef, useState } from "react";
import { type AgentCursor, AgentScreen, type AgentScreenStatus } from "@/components/shaken/agent/agent-screen";

/*
 * The agent's screen here is a small invoicing app drawn in code at 1280 x 800. In your app,
 * pass the latest frame from your computer-use session instead, for example
 * <img src={frameUrl} alt="" className="size-full object-cover" />.
 */

type ScreenState = { filter: boolean; selected: string | null; exported: boolean };

const invoices = [
  { id: "INV-2051", customer: "Northwind Freight", amount: "$12,400.00", due: "Nov 30", status: "Open" },
  { id: "INV-2049", customer: "Halcyon Dental", amount: "$3,180.00", due: "Nov 2", status: "Overdue" },
  { id: "INV-2048", customer: "Kestrel Robotics", amount: "$28,000.00", due: "Dec 4", status: "Open" },
  { id: "INV-2047", customer: "Bramble & Rye", amount: "$6,450.00", due: "Oct 28", status: "Overdue" },
  { id: "INV-2045", customer: "Osprey Health", amount: "$2,975.00", due: "Oct 30", status: "Overdue" },
  { id: "INV-2044", customer: "Marlow Studio", amount: "$1,240.00", due: "Oct 12", status: "Paid" },
  { id: "INV-2042", customer: "Fennick Labs", amount: "$9,800.00", due: "Oct 19", status: "Overdue" },
];

const nav = ["Overview", "Invoices", "Customers", "Payouts", "Reports"];
const filters = ["All", "Overdue", "Drafts", "Paid"];

export function LedgerScreen({ filter, selected, exported }: ScreenState) {
  const rows = filter ? invoices.filter((invoice) => invoice.status === "Overdue") : invoices;
  return (
    <div className="flex h-[800px] w-[1280px] flex-col bg-white font-sans text-[14px] text-zinc-900">
      <div className="flex h-[44px] shrink-0 items-center gap-3 border-b border-zinc-200 bg-zinc-100 px-4">
        <span className="flex gap-1.5">
          <span className="size-3 rounded-full bg-zinc-300" />
          <span className="size-3 rounded-full bg-zinc-300" />
          <span className="size-3 rounded-full bg-zinc-300" />
        </span>
        <span className="ml-24 w-[420px] rounded-md bg-white px-3 py-1 text-[13px] text-zinc-500">ledgerline.app/invoices{filter ? "?status=overdue" : ""}</span>
      </div>
      <div className="flex min-h-0 flex-1">
        <aside className="w-[232px] shrink-0 border-r border-zinc-200 bg-zinc-50 px-4">
          <div className="flex h-[76px] items-center gap-2 text-[15px] font-semibold">
            <span className="size-6 rounded-md bg-emerald-600" />
            Ledgerline
          </div>
          <ul>
            {nav.map((item) => (
              <li key={item} className={`flex h-[36px] items-center rounded-md px-3 ${item === "Invoices" ? "bg-zinc-200/70 font-medium" : "text-zinc-600"}`}>
                {item}
              </li>
            ))}
          </ul>
        </aside>
        <main className="relative min-w-0 flex-1 px-8">
          <div className="flex h-[84px] items-end pb-2">
            <h1 className="text-[24px] font-semibold">Invoices</h1>
          </div>
          <div className="flex h-[36px] items-center gap-2">
            {filters.map((item) => {
              const active = (item === "Overdue" && filter) || (item === "All" && !filter);
              return (
                <span key={item} className={`flex h-[32px] items-center rounded-full border px-4 text-[13px] ${active ? "border-zinc-900 bg-zinc-900 text-white" : "border-zinc-300 text-zinc-600"}`}>
                  {item}
                </span>
              );
            })}
            <span className="ml-auto flex h-[36px] w-[124px] items-center justify-center rounded-md bg-emerald-600 text-[13px] font-medium text-white">Export CSV</span>
          </div>
          <div className="mt-6">
            <div className="grid h-[36px] grid-cols-[140px_1fr_160px_120px_110px] items-center border-b border-zinc-200 text-[12px] font-medium text-zinc-500">
              <span>Invoice</span>
              <span>Customer</span>
              <span className="text-right">Amount</span>
              <span className="pl-8">Due</span>
              <span>Status</span>
            </div>
            {rows.map((invoice) => (
              <div
                key={invoice.id}
                className={`grid h-[48px] grid-cols-[140px_1fr_160px_120px_110px] items-center border-b border-zinc-100 ${selected === invoice.id ? "bg-sky-50" : ""}`}
              >
                <span className="font-mono text-[13px] text-zinc-600">{invoice.id}</span>
                <span className="font-medium">{invoice.customer}</span>
                <span className="text-right font-mono text-[13px]">{invoice.amount}</span>
                <span className="pl-8 text-zinc-600">{invoice.due}</span>
                <span className={invoice.status === "Overdue" ? "text-red-600" : invoice.status === "Paid" ? "text-emerald-700" : "text-zinc-600"}>{invoice.status}</span>
              </div>
            ))}
          </div>
          {exported ? (
            <div className="absolute right-8 bottom-8 rounded-lg bg-zinc-900 px-4 py-3 text-[13px] text-white shadow-lg">Exported overdue-invoices.csv (4 rows)</div>
          ) : null}
        </main>
      </div>
    </div>
  );
}

// Positions in the 1280 x 800 screen, as fractions.
const script: { caption: string; cursor: { x: number; y: number }; apply: (state: ScreenState) => ScreenState }[] = [
  { caption: "Opening Invoices", cursor: { x: 0.07, y: 0.2175 }, apply: () => ({ filter: false, selected: null, exported: false }) },
  { caption: "Filtering to overdue invoices", cursor: { x: 0.272, y: 0.183 }, apply: (s) => ({ ...s, filter: true }) },
  { caption: "Opening INV-2047 for Bramble & Rye", cursor: { x: 0.36, y: 0.37 }, apply: (s) => ({ ...s, selected: "INV-2047" }) },
  { caption: "Exporting 4 overdue invoices to CSV", cursor: { x: 0.928, y: 0.183 }, apply: (s) => ({ ...s, exported: true }) },
];

export default function AgentScreenExample() {
  const [status, setStatus] = useState<AgentScreenStatus>("connecting");
  const [startedAt] = useState(() => Date.now() - 154_000);
  const [step, setStep] = useState(0);
  const [cursor, setCursor] = useState<AgentCursor>({ x: 0.5, y: 0.6 });
  const [screen, setScreen] = useState<ScreenState>({ filter: false, selected: null, exported: false });
  const clicks = useRef(0);

  // Connect, then play the script while the agent has control.
  useEffect(() => {
    if (status !== "connecting") return;
    const id = setTimeout(() => setStatus("live"), 1600);
    return () => clearTimeout(id);
  }, [status]);

  useEffect(() => {
    if (status !== "live") return;
    const current = script[step % script.length]!;
    clicks.current += 1;
    setCursor({ ...current.cursor, click: clicks.current });
    // The screen reacts once the cursor lands and clicks.
    const land = setTimeout(() => setScreen((s) => current.apply(s)), 560);
    const next = setTimeout(() => setStep((n) => n + 1), 2400);
    return () => {
      clearTimeout(land);
      clearTimeout(next);
    };
  }, [status, step]);

  return (
    <AgentScreen
      className="max-w-sm"
      agentName="Browser agent"
      status={status}
      startedAt={startedAt}
      caption={script[step % script.length]!.caption}
      cursor={cursor}
      frame={<LedgerScreen {...screen} />}
      onTakeOver={() => setStatus("takeover")}
      onHandBack={() => setStatus("live")}
      onStop={() => setStatus("ended")}
    />
  );
}

States

Every state, rendered from local fixture data.

Agent Screen states
ConnectingBrowser agent

Waiting for the first frame

LiveBrowser agent

Filtering to overdue invoices

You have controlBrowser agent

Paused while you work

Session endedBrowser agent

Exported 4 overdue invoices

API

PropTypeDefaultDescription
frameReactNode—What is on the agent's screen: an image of the latest frame, a video, or any element.
status"connecting" | "live" | "takeover" | "ended"—Connecting shows a loading frame; takeover outlines the screen in amber; ended dims it.
agentNameReactNode"Agent"Who is driving.
captionReactNode—The current step, under the thumbnail and in the larger view.
cursor{ x, y, click? }—The agent's cursor in 0 to 1 coordinates. Change click to play a ripple once the cursor arrives.
aspectRationumber16 / 10Width over height of the agent's screen.
screenWidthnumber1280Width the frame is laid out at before it is scaled to fit, so element frames look the same at every size.
startedAtnumber | Date—Shows the session clock.
onTakeOver / onHandBack / onStop() => void—Buttons in the larger view.
expanded / defaultExpanded / onExpandedChangebooleanfalseWhether the larger view is open.

Accessibility

  • The thumbnail is a button labelled "Expand screen" with aria-haspopup="dialog"; the larger view is a Base UI Dialog labelled by the agent's name, with focus trapped inside and returned to the thumbnail on close.
  • Escape or the Collapse button closes it. Take over, Hand back and Stop are buttons; Stop is disabled once the session has ended.
  • The current step is a polite live region; the clock and cursor are aria-hidden. Status is written in text (Live, You have control, Session ended), not only shown by color.
  • Under reduced motion the cursor jumps instead of gliding, the click ripple only fades, and the larger view fades in without growing from the thumbnail.

Files

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

  • src/components/shaken/agent/agent-screen.tsxagent-screen
  • Also installs dot-loader@0.1.0registry dependency
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

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

agent/agent-screen.tsxShow
agent/agent-screen.tsx
"use client";

import { Dialog as BaseDialog } from "@base-ui/react/dialog";
import {
  type ComponentProps,
  type CSSProperties,
  type ReactNode,
  useCallback,
  useEffect,
  useId,
  useLayoutEffect,
  useRef,
  useState,
} from "react";
import { DotGrid } from "./dot-loader";

/*
 * Agent screen: a live thumbnail of a computer-use agent's screen with its status, the current
 * step, and the agent's cursor (which glides between targets and leaves a ripple where it clicks).
 *
 * Expanding moves the screen itself: the dialog is laid out at its full size, then starts scaled
 * down exactly over the thumbnail and grows into place while the dialog chrome fades in around it.
 * Collapsing runs the same path back. The frame is rendered at a fixed virtual resolution and
 * scaled to fit, so it looks identical at both sizes. Under reduced motion the cursor jumps,
 * ripples only fade, and the dialog fades without travel.
 */

export type AgentScreenStatus = "connecting" | "live" | "takeover" | "ended";

export interface AgentCursor {
  /** 0 to 1 across the screen. */
  x: number;
  /** 0 to 1 down the screen. */
  y: number;
  /** Change this value to play a click ripple at the cursor. */
  click?: number | string;
}

export interface AgentScreenProps extends Omit<ComponentProps<"section">, "children"> {
  /** What is on the agent's screen: an image of the latest frame, a video, or any element. */
  frame?: ReactNode;
  status: AgentScreenStatus;
  /** Who is driving, for example "Browser agent". */
  agentName?: ReactNode;
  /** The current step, for example "Clicking Export CSV". */
  caption?: ReactNode;
  cursor?: AgentCursor;
  /** Width over height of the agent's screen. */
  aspectRatio?: number;
  /**
   * Width in CSS pixels the frame is laid out at before it is scaled to fit. Set it to the agent's
   * screen width for element frames; images and video simply fill the box.
   */
  screenWidth?: number;
  /** When the session started, as epoch milliseconds or a Date. */
  startedAt?: number | Date;
  onTakeOver?: () => void;
  onHandBack?: () => void;
  onStop?: () => void;
  expanded?: boolean;
  defaultExpanded?: boolean;
  onExpandedChange?: (expanded: boolean) => void;
}

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

const quint = "cubic-bezier(0.23, 1, 0.32, 1)";

const statusMeta: Record<AgentScreenStatus, { label: string; tone: string }> = {
  connecting: { label: "Connecting", tone: "text-zinc-500" },
  live: { label: "Live", tone: "text-sky-600 dark:text-sky-400" },
  takeover: { label: "You have control", tone: "text-amber-600 dark:text-amber-400" },
  ended: { label: "Session ended", tone: "text-zinc-500" },
};

function usePrefersReducedMotion() {
  const [reduce, setReduce] = useState(false);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduce(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  return reduce;
}

function StatusGlyph({ status }: { status: AgentScreenStatus }) {
  if (status === "live" || status === "connecting") {
    return <DotGrid pattern={status === "live" ? "orbit" : "scan"} grid={3} size={14} status="running" tone="inherit" />;
  }
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="size-3.5">
      <circle cx="8" cy="8" r="6.25" />
      {status === "takeover" ? <path d="M6.5 5.75v4.5M9.5 5.75v4.5" /> : <path d="m4 12 8-8" />}
    </svg>
  );
}

function Clock({ startedAt, running }: { startedAt?: number; running: boolean }) {
  const ref = useRef<HTMLSpanElement>(null);
  useEffect(() => {
    const el = ref.current;
    if (!el || startedAt == null) return;
    const write = () => {
      const s = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));
      el.textContent = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
    };
    write();
    if (!running) return;
    const id = setInterval(write, 1000);
    return () => clearInterval(id);
  }, [startedAt, running]);
  if (startedAt == null) return null;
  return <span ref={ref} aria-hidden="true" className="font-mono text-xs text-zinc-500 tabular-nums" />;
}

// ---------------------------------------------------------------------------
// The screen: a fixed-resolution frame scaled into its box, with the cursor on top.

function Screen({
  frame,
  status,
  cursor,
  aspectRatio,
  screenWidth,
  reduce,
  large = false,
  agentName,
}: {
  frame: ReactNode;
  status: AgentScreenStatus;
  cursor?: AgentCursor;
  aspectRatio: number;
  screenWidth: number;
  reduce: boolean;
  large?: boolean;
  agentName?: ReactNode;
}) {
  const boxRef = useRef<HTMLDivElement>(null);
  const [box, setBox] = useState({ w: 0, h: 0 });

  useLayoutEffect(() => {
    const el = boxRef.current;
    if (!el) return;
    const read = () => setBox({ w: el.clientWidth, h: el.clientHeight });
    read();
    if (typeof ResizeObserver === "undefined") return;
    const observer = new ResizeObserver(read);
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  const screenHeight = screenWidth / aspectRatio;
  const scale = box.w ? box.w / screenWidth : 0;
  const showCursor = cursor && status === "live" && box.w > 0;

  return (
    <div
      ref={boxRef}
      className={cx(
        "relative w-full overflow-hidden bg-zinc-950 transition-[outline-color] duration-200 motion-reduce:transition-none",
        large ? "rounded-xl" : "rounded-lg",
        "outline-2 -outline-offset-2 outline-solid",
        status === "takeover" ? "outline-amber-500" : "outline-transparent",
      )}
      style={{ aspectRatio: String(aspectRatio) }}
    >
      {status === "connecting" ? (
        <div className="absolute inset-0 grid place-content-center justify-items-center gap-3 text-white">
          <DotGrid pattern="scan" grid={4} size={large ? 40 : 24} status="running" tone="inherit" />
          <p className={cx("text-white/60", large ? "text-sm" : "text-xs")}>Connecting to the agent&apos;s screen</p>
        </div>
      ) : (
        <div
          className={cx("absolute top-0 left-0 origin-top-left transition-[opacity,filter] duration-300 motion-reduce:transition-none", status === "ended" && "opacity-40 grayscale")}
          style={{ width: screenWidth, height: screenHeight, transform: `scale(${scale})`, visibility: scale ? "visible" : "hidden" }}
        >
          {frame}
        </div>
      )}

      {showCursor ? <Cursor cursor={cursor} box={box} reduce={reduce} large={large} agentName={agentName} /> : null}

      {status === "takeover" ? (
        <span className="absolute top-2 left-2 rounded-md bg-amber-500 px-1.5 py-0.5 text-[11px] font-medium text-black">You have control</span>
      ) : null}
      {status === "ended" ? (
        <span className="absolute inset-0 grid place-items-center">
          <span className="rounded-md bg-black/75 px-2 py-1 text-xs font-medium text-white">Session ended</span>
        </span>
      ) : null}
    </div>
  );
}

function Cursor({ cursor, box, reduce, large, agentName }: { cursor: AgentCursor; box: { w: number; h: number }; reduce: boolean; large: boolean; agentName?: ReactNode }) {
  const rippleRef = useRef<HTMLSpanElement>(null);
  const arrowRef = useRef<SVGSVGElement>(null);
  const lastClick = useRef(cursor.click);
  const x = Math.max(0, Math.min(1, cursor.x)) * box.w;
  const y = Math.max(0, Math.min(1, cursor.y)) * box.h;

  // A click plays once the cursor has arrived: the arrow dips and a ring spreads from its tip.
  useEffect(() => {
    if (cursor.click === undefined || cursor.click === lastClick.current) return;
    lastClick.current = cursor.click;
    const ring = rippleRef.current;
    const arrow = arrowRef.current;
    if (!ring || typeof ring.animate !== "function") return;
    const travel = reduce ? 0 : 520;
    if (reduce) {
      ring.animate([{ opacity: 0.6, transform: "translate(-50%, -50%) scale(1)" }, { opacity: 0, transform: "translate(-50%, -50%) scale(1)" }], { duration: 360, easing: "ease-out" });
      return;
    }
    ring.animate(
      [
        { opacity: 0.7, transform: "translate(-50%, -50%) scale(0.3)" },
        { opacity: 0, transform: "translate(-50%, -50%) scale(1.5)" },
      ],
      { duration: 520, delay: travel, easing: quint, fill: "backwards" },
    );
    arrow?.animate([{ transform: "scale(1)" }, { transform: "scale(0.86)" }, { transform: "scale(1)" }], { duration: 220, delay: travel, easing: "ease-out" });
  }, [cursor.click, reduce]);

  const size = large ? 22 : 15;
  return (
    <span
      aria-hidden="true"
      className="pointer-events-none absolute top-0 left-0"
      style={{
        transform: `translate(${x}px, ${y}px)`,
        transition: reduce ? "none" : "transform 520ms cubic-bezier(0.65, 0, 0.35, 1)",
      }}
    >
      <span ref={rippleRef} className={cx("absolute top-0 left-0 rounded-full border-2 border-sky-400 opacity-0", large ? "size-11" : "size-7")} style={{ transform: "translate(-50%, -50%)" }} />
      <svg ref={arrowRef} viewBox="0 0 16 16" className="absolute -top-px -left-px origin-top-left drop-shadow-[0_1px_2px_rgb(0_0_0/0.45)]" style={{ width: size, height: size }}>
        <path d="M2 1.5 13.5 7.6l-5 1.2-2.4 4.7z" fill="#0ea5e9" stroke="#fff" strokeWidth="1.25" strokeLinejoin="round" />
      </svg>
      {large && agentName ? (
        <span className="absolute top-5 left-4 rounded-md bg-sky-500 px-1.5 py-0.5 text-[11px] font-medium whitespace-nowrap text-white">{agentName}</span>
      ) : null}
    </span>
  );
}

// ---------------------------------------------------------------------------

const iconButton = cx(
  "inline-flex size-8 items-center justify-center rounded-lg text-zinc-500",
  "transition-[background-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.94] motion-reduce:transition-none",
  "hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white",
  "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
);

const button = {
  base: "inline-flex h-8 items-center justify-center rounded-lg px-3 text-sm font-medium whitespace-nowrap select-none transition-[background-color,border-color,scale] duration-150 ease-out motion-safe:active:scale-[0.97] motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
  secondary: "border border-zinc-950/12 bg-white text-zinc-950 hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] dark:border-white/15 dark:bg-black dark:text-white dark:hover:border-white/25 dark:hover:bg-white/[0.06]",
  danger: "bg-red-600 text-white hover:bg-red-700",
};

function ExpandIcon() {
  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">
      <path d="M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9" />
    </svg>
  );
}

function CollapseIcon() {
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4">
      <path d="M13.5 6.5h-4v-4M2.5 9.5h4v4M9.5 6.5l4-4M6.5 9.5l-4 4" />
    </svg>
  );
}

/**
 * A live thumbnail of a computer-use agent's screen. Expanding grows the screen into a dialog with
 * Take over and Stop; Escape or Collapse sends it back to the thumbnail.
 */
export function AgentScreen({
  frame,
  status,
  agentName = "Agent",
  caption,
  cursor,
  aspectRatio = 16 / 10,
  screenWidth = 1280,
  startedAt,
  onTakeOver,
  onHandBack,
  onStop,
  expanded: expandedProp,
  defaultExpanded = false,
  onExpandedChange,
  className,
  ...props
}: AgentScreenProps) {
  const reduce = usePrefersReducedMotion();
  const [uncontrolled, setUncontrolled] = useState(defaultExpanded);
  const expanded = expandedProp ?? uncontrolled;
  // `mounted` keeps the dialog open while it animates back to the thumbnail.
  const [mounted, setMounted] = useState(expanded);
  const [closing, setClosing] = useState(false);
  const thumbRef = useRef<HTMLDivElement>(null);
  const popupRef = useRef<HTMLDivElement>(null);
  const bigRef = useRef<HTMLDivElement>(null);
  const expandRef = useRef<HTMLButtonElement>(null);
  const titleId = useId();
  const start = startedAt instanceof Date ? startedAt.getTime() : startedAt;
  const meta = statusMeta[status];

  const setExpanded = useCallback(
    (next: boolean) => {
      if (expandedProp === undefined) setUncontrolled(next);
      onExpandedChange?.(next);
    },
    [expandedProp, onExpandedChange],
  );

  /** The transform that puts the dialog's screen exactly over the thumbnail's screen. */
  const flipFrom = useCallback(() => {
    const thumb = thumbRef.current?.getBoundingClientRect();
    const big = bigRef.current?.getBoundingClientRect();
    const popup = popupRef.current?.getBoundingClientRect();
    if (!thumb || !big || !popup || !big.width) return null;
    const s = thumb.width / big.width;
    const originX = big.left - popup.left + big.width / 2;
    const originY = big.top - popup.top + big.height / 2;
    const dx = thumb.left + thumb.width / 2 - (big.left + big.width / 2);
    const dy = thumb.top + thumb.height / 2 - (big.top + big.height / 2);
    return { origin: `${originX}px ${originY}px`, transform: `translate(${dx}px, ${dy}px) scale(${s})` };
  }, []);

  // Open: mount, then grow from the thumbnail.
  useEffect(() => {
    if (expanded) {
      setClosing(false);
      setMounted(true);
    } else if (mounted && !closing) {
      // Close: travel back, then unmount.
      const popup = popupRef.current;
      const from = flipFrom();
      if (!popup || !from || reduce || typeof popup.animate !== "function") {
        setMounted(false);
        return;
      }
      setClosing(true);
      popup.style.transformOrigin = from.origin;
      for (const el of popup.querySelectorAll<HTMLElement>("[data-chrome]")) {
        el.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 160, easing: "ease-out", fill: "forwards" });
      }
      const animation = popup.animate([{ transform: "none" }, { transform: from.transform }], { duration: 300, easing: "cubic-bezier(0.32, 0.72, 0, 1)", fill: "forwards" });
      animation.onfinish = () => {
        setMounted(false);
        setClosing(false);
      };
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [expanded]);

  // Runs once the popup is in the DOM after opening.
  const onPopupMounted = useCallback(() => {
    const popup = popupRef.current;
    if (!popup || typeof popup.animate !== "function") return;
    if (reduce) {
      popup.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 160, easing: "ease-out" });
      return;
    }
    const from = flipFrom();
    if (!from) return;
    popup.style.transformOrigin = from.origin;
    popup.animate([{ transform: from.transform }, { transform: "none" }], { duration: 440, easing: quint });
    // The chrome waits for the screen to get going, then fades in around it.
    for (const el of popup.querySelectorAll<HTMLElement>("[data-chrome]")) {
      el.animate([{ opacity: 0 }, { opacity: 0, offset: 0.25 }, { opacity: 1 }], { duration: 400, easing: "ease-out" });
    }
  }, [flipFrom, reduce]);

  // Base UI renders the portal after this component commits, so the grow starts when the popup attaches.
  const grown = useRef(false);
  const attachPopup = useCallback(
    (el: HTMLDivElement | null) => {
      popupRef.current = el;
      // Once per open: a re-attached ref must not restart (or flatten) the grow.
      if (el && !grown.current) {
        grown.current = true;
        onPopupMounted();
      }
    },
    [onPopupMounted],
  );
  useEffect(() => {
    if (!mounted) grown.current = false;
  }, [mounted]);

  const screenProps = { frame, status, cursor, aspectRatio, screenWidth, reduce, agentName };
  const live = status === "live" || status === "connecting";

  return (
    <section
      aria-label={typeof agentName === "string" ? `${agentName} screen` : "Agent screen"}
      data-status={status}
      className={cx(
        "w-full rounded-xl border border-zinc-950/10 bg-white p-2 text-left text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
        "dark:border-white/10 dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
        className,
      )}
      {...props}
    >
      <div ref={thumbRef} className="group/thumb relative">
        {/* The button stays mounted while the screen is in the dialog, so focus can come back to it. */}
        <button
          ref={expandRef}
          type="button"
          onClick={() => setExpanded(true)}
          aria-label="Expand screen"
          aria-haspopup="dialog"
          aria-expanded={mounted}
          className="block w-full rounded-lg outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500"
        >
          {mounted ? (
            // The screen is in the dialog; the thumbnail keeps its place.
            <span className="grid w-full place-items-center rounded-lg border border-dashed border-zinc-950/15 dark:border-white/15" style={{ aspectRatio: String(aspectRatio) }}>
              <span className="text-xs text-zinc-500">Open in a larger view</span>
            </span>
          ) : (
            <>
              <Screen {...screenProps} />
              <span
                aria-hidden="true"
                className={cx(
                  "absolute top-2 right-2 inline-flex size-7 items-center justify-center rounded-md bg-zinc-950/80 text-white",
                  "transition-[background-color] duration-150 ease-out group-hover/thumb:bg-zinc-950 motion-reduce:transition-none",
                )}
              >
                <ExpandIcon />
              </span>
            </>
          )}
        </button>
      </div>

      <div className="grid gap-0.5 px-1.5 pt-2.5 pb-1">
        <div className="flex items-center gap-2 text-xs">
          <span className={cx("flex items-center gap-1.5 font-medium", meta.tone)}>
            <StatusGlyph status={status} />
            {meta.label}
          </span>
          <span className="truncate text-zinc-500">{agentName}</span>
          <span className="ml-auto">
            <Clock startedAt={start} running={live} />
          </span>
        </div>
        <p role="status" className="min-h-5 truncate text-sm text-zinc-600 dark:text-zinc-400">
          <span
            key={typeof caption === "string" ? caption : undefined}
            className="inline-block transition-[opacity,translate] duration-300 ease-[cubic-bezier(0.23,1,0.32,1)] starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none"
          >
            {status === "connecting" ? "Waiting for the first frame" : caption}
          </span>
        </p>
      </div>

      <BaseDialog.Root
        open={mounted}
        onOpenChange={(open) => {
          if (!open) setExpanded(false);
        }}
      >
        <BaseDialog.Portal>
          <BaseDialog.Backdrop
            className={cx(
              "fixed inset-0 z-50 bg-black/40 transition-opacity duration-200 ease-out motion-reduce:transition-none dark:bg-black/70",
              "data-[starting-style]:opacity-0 data-[ending-style]:opacity-0",
              closing && "opacity-0",
            )}
          />
          <BaseDialog.Popup
            ref={attachPopup}
            aria-labelledby={titleId}
            finalFocus={expandRef}
            className={cx(
              "fixed inset-0 z-50 m-auto flex h-fit max-h-[calc(100dvh-2rem)] w-[min(960px,calc(100vw-2rem))] flex-col text-zinc-950 dark:text-white",
              "outline-none",
            )}
          >
            {/* The chrome fades around the screen, which travels on its own. */}
            <div
              data-chrome
              aria-hidden="true"
              className="absolute inset-0 rounded-2xl border border-zinc-950/10 bg-white shadow-[0_24px_64px_-16px_rgb(0_0_0/0.28)] dark:border-white/15 dark:bg-black dark:shadow-[0_24px_64px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]"
            />
            <div data-chrome className="relative flex items-center gap-3 px-4 pt-3 pb-2.5">
                <span className={cx("flex items-center gap-1.5 text-xs font-medium", meta.tone)}>
                  <StatusGlyph status={status} />
                  {meta.label}
                </span>
                <BaseDialog.Title id={titleId} className="min-w-0 truncate text-sm font-semibold">
                  {agentName}
                </BaseDialog.Title>
                <span className="ml-auto flex items-center gap-2">
                  <Clock startedAt={start} running={live} />
                  <BaseDialog.Close aria-label="Collapse" className={iconButton}>
                    <CollapseIcon />
                  </BaseDialog.Close>
                </span>
            </div>
            <div className="relative px-2">
              <div ref={bigRef} className="mx-auto w-full" style={{ maxWidth: `calc((100dvh - 9.5rem) * ${aspectRatio})` } as CSSProperties}>
                {mounted ? <Screen {...screenProps} large /> : null}
              </div>
            </div>
            <div data-chrome className="relative flex flex-wrap items-center gap-x-4 gap-y-2 px-4 pt-2.5 pb-3">
                <p className="min-w-0 flex-1 truncate text-sm text-zinc-600 dark:text-zinc-400">{status === "connecting" ? "Waiting for the first frame" : caption}</p>
                <div className="ml-auto flex items-center gap-2">
                  {status === "takeover" ? (
                    <button type="button" onClick={onHandBack} className={cx(button.base, button.secondary)}>
                      Hand back
                    </button>
                  ) : (
                    <button type="button" disabled={status !== "live"} onClick={onTakeOver} className={cx(button.base, button.secondary, "disabled:pointer-events-none disabled:opacity-40")}>
                      Take over
                    </button>
                  )}
                  <button type="button" disabled={status === "ended"} onClick={onStop} className={cx(button.base, button.danger, "disabled:pointer-events-none disabled:opacity-40")}>
                    Stop
                  </button>
                </div>
            </div>
          </BaseDialog.Popup>
        </BaseDialog.Portal>
      </BaseDialog.Root>
    </section>
  );
}