Skip to content
Shaken UI
Sign in

Conversation List

Save

The sidebar list of past chats, grouped into Pinned, Today, Yesterday, Previous 7 days, and Older, with search, pinning, inline rename, delete with undo, and a mark for chats an agent is still working on.

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

Preview

Conversation List preview

Installation

npx @shakenui/cli add conversation-list

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

npx @shakenui/cli add conversation-list --dry-run

Usage

conversation-list-example.tsx
"use client";

import { useState } from "react";
import { type Conversation, ConversationList } from "@/components/shaken/agent/conversation-list";

// A fixed clock so the groups render the same on the server and in the browser.
const now = new Date("2026-11-14T16:30:00");
const hoursAgo = (hours: number) => new Date(now.getTime() - hours * 3_600_000);

const initial: Conversation[] = [
  { id: "c1", title: "Northwind invoice off by a cent", updatedAt: hoursAgo(0.2), status: "running", activity: "working" },
  { id: "c2", title: "Migrate billing webhooks to v2", updatedAt: hoursAgo(1.5), status: "waiting" },
  { id: "c3", title: "Draft the Q4 pricing FAQ", updatedAt: hoursAgo(3), pinned: true },
  { id: "c4", title: "Why is the staging deploy slow", updatedAt: hoursAgo(5), status: "failed" },
  { id: "c5", title: "Summarize churn interviews", updatedAt: hoursAgo(20) },
  { id: "c6", title: "Rate limit headers for the public API", updatedAt: hoursAgo(26) },
  { id: "c7", title: "Postgres index for invoice search", updatedAt: hoursAgo(50) },
  { id: "c8", title: "Onboarding email sequence, second pass", updatedAt: hoursAgo(96) },
  { id: "c9", title: "Compare Stripe Tax and Avalara", updatedAt: hoursAgo(240) },
  { id: "c10", title: "Holiday on-call rotation", updatedAt: hoursAgo(600) },
];

export default function ConversationListExample() {
  const [conversations, setConversations] = useState(initial);
  const [selectedId, setSelectedId] = useState("c1");
  const update = (id: string, patch: Partial<Conversation>) =>
    setConversations((current) => current.map((item) => (item.id === id ? { ...item, ...patch } : item)));

  return (
    <div className="flex h-[30rem] w-full max-w-72 flex-col rounded-xl border border-zinc-950/10 bg-white p-2 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)]">
      <ConversationList
        className="flex-1"
        now={now}
        conversations={conversations}
        selectedId={selectedId}
        onSelect={setSelectedId}
        onPinChange={(id, pinned) => update(id, { pinned })}
        onRename={(id, title) => update(id, { title })}
        onDelete={(id) => setConversations((current) => current.filter((item) => item.id !== id))}
      />
    </div>
  );
}

API

PropTypeDefaultDescription
conversations{ id, title, updatedAt, pinned?, status?, activity?, href? }[]—The chats. updatedAt decides the group; status is running, waiting, or failed.
selectedIdstring | null—The open chat, marked with aria-current.
onSelect(id) => void—Called when a row is chosen.
onPinChange(id, pinned) => void—Shows Pin and Unpin. Update pinned in your data and the row glides to its group.
onRename(id, title) => void—Shows Rename, also on F2 or double click, as an inline field.
onDelete(id) => void—Shows Delete, also on Delete or Backspace. Called once the undo window passes.
undoMsnumber5000How long Undo stays available.
searchablebooleantrueShows the search field.
nowDate—Reference time for the groups. Pass it when rendering on the server.
labelstring"Chats"Accessible name of the navigation landmark.
emptyReactNode—Shown when there are no chats.

Accessibility

  • A navigation landmark with one labeled section per group. Rows are buttons (or links with href) with a single roving tab stop; the open chat has aria-current="page".
  • Up and Down move between rows (Up from the first row returns to search, Down from search enters the list), Home and End jump, F2 renames, and Delete or Backspace deletes.
  • Each row's More actions menu is a Base UI Menu reachable with Tab from the focused row. Rename is an inline field: Enter saves, Escape cancels, and focus returns to the row.
  • After a delete, focus moves to the next row and a status region offers Undo; pins, deletes, and restores are announced.
  • Running, waiting for approval, and failed are spoken as part of the row name; the agent mark and glyphs are decorative.
  • With reduced motion rows move to their new group without gliding, the agent mark holds a still frame, and the undo timer line stays full.

Files

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

  • src/components/shaken/agent/conversation-list.tsxconversation-list
  • Also installs agent-state@0.1.0registry dependency
  • Also installs dropdown-menu@0.2.1registry dependency
  • npm packages: @base-ui/react@^1.9.0, motion@^14.14.0React and Tailwind CSS v4 required

Source

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

agent/conversation-list.tsxShow
agent/conversation-list.tsx
"use client";

import { AnimatePresence, LayoutGroup, MotionConfig, motion, type Transition } from "motion/react";
import { type ComponentProps, type KeyboardEvent, type ReactNode, useEffect, useId, useMemo, useRef, useState } from "react";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "../ui/dropdown-menu";
import { type AgentActivity, AgentMark } from "./agent-state";

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

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
const move: Transition = { type: "spring", bounce: 0, duration: 0.35 };

/*
 * Conversation list: the sidebar of past chats.
 *
 * Rows are grouped by Pinned, Today, Yesterday, Previous 7 days, and Older. Pinning a chat
 * glides its row into the Pinned group (Motion shared layout, transform only); deleting folds
 * the row out and leaves an undo bar whose hairline runs down the time left. A chat an agent is
 * still working on carries the Agent State mark, a slow loop that pauses offscreen. With reduced
 * motion rows jump to their place and the mark holds still.
 */

export type ConversationStatus = "running" | "waiting" | "failed";
export type Timestamp = Date | string | number;

export interface Conversation {
  id: string;
  title: string;
  /** Last activity; decides the group. */
  updatedAt: Timestamp;
  pinned?: boolean;
  /** running shows the animated mark; waiting (for approval) and failed show their glyphs. */
  status?: ConversationStatus;
  /** Which Agent State mark runs while `status` is running. Defaults to thinking. */
  activity?: AgentActivity;
  /** Renders the row as a link instead of a button. */
  href?: string;
}

export interface ConversationListProps extends Omit<ComponentProps<"nav">, "onSelect"> {
  conversations: Conversation[];
  /** The open chat, marked with aria-current. */
  selectedId?: string | null;
  /** Called when a row is chosen with a click, Enter, or Space. */
  onSelect?: (id: string) => void;
  /** Shows Pin and Unpin in each row's menu. Update `pinned` in your data. */
  onPinChange?: (id: string, pinned: boolean) => void;
  /** Shows Rename (menu, F2, or double click). Update the title in your data. */
  onRename?: (id: string, title: string) => void;
  /** Shows Delete (menu, Delete, or Backspace). Called once the undo window has passed. */
  onDelete?: (id: string) => void;
  /** How long Undo stays available after a delete. */
  undoMs?: number;
  /** Shows the search field. */
  searchable?: boolean;
  /** Reference time for the date groups. Pass it when rendering on the server to avoid a mismatch. */
  now?: Date;
  /** Accessible name of the navigation landmark. */
  label?: string;
  /** Shown when there are no chats at all. */
  empty?: ReactNode;
}

type GroupName = "Pinned" | "Today" | "Yesterday" | "Previous 7 days" | "Older";
const order: GroupName[] = ["Pinned", "Today", "Yesterday", "Previous 7 days", "Older"];

function toDate(value: Timestamp): Date {
  return value instanceof Date ? value : new Date(value);
}

function groupOf(conversation: Conversation, now: Date): GroupName {
  if (conversation.pinned) return "Pinned";
  const day = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
  const at = toDate(conversation.updatedAt).getTime();
  if (at >= day) return "Today";
  if (at >= day - 86_400_000) return "Yesterday";
  if (at >= day - 7 * 86_400_000) return "Previous 7 days";
  return "Older";
}

/** A sidebar list of past chats, grouped by date, with search, pin, inline rename, delete with undo, and a running indicator. */
export function ConversationList({
  conversations,
  selectedId,
  onSelect,
  onPinChange,
  onRename,
  onDelete,
  undoMs = 5000,
  searchable = true,
  now: nowProp,
  label = "Chats",
  empty,
  className,
  ...props
}: ConversationListProps) {
  const [query, setQuery] = useState("");
  const [pending, setPending] = useState<Conversation[]>([]);
  const [renaming, setRenaming] = useState<string | null>(null);
  const [focused, setFocused] = useState<string | null>(null);
  const [announcement, setAnnouncement] = useState("");
  const [now, setNow] = useState<Date | null>(nowProp ?? null);
  const rowRefs = useRef(new Map<string, HTMLElement>());
  const searchRef = useRef<HTMLInputElement>(null);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  const pendingRef = useRef(pending);
  const onDeleteRef = useRef(onDelete);
  useEffect(() => {
    pendingRef.current = pending;
    onDeleteRef.current = onDelete;
  });
  const searchId = useId();

  // Without `now`, group against the client clock after mount, so server and client agree.
  useEffect(() => {
    if (!nowProp) setNow(new Date());
  }, [nowProp]);
  const reference = nowProp ?? now ?? new Date(0);

  // Leaving the page or unmounting commits whatever is still waiting for undo.
  useEffect(
    () => () => {
      clearTimeout(timer.current);
      for (const item of pendingRef.current) onDeleteRef.current?.(item.id);
    },
    [],
  );

  const hidden = useMemo(() => new Set(pending.map((item) => item.id)), [pending]);
  const q = query.trim().toLowerCase();
  const visible = conversations.filter((item) => !hidden.has(item.id) && (!q || item.title.toLowerCase().includes(q)));
  const groups = order
    .map((name) => ({
      name,
      items: visible
        .filter((item) => groupOf(item, reference) === name)
        .sort((a, b) => toDate(b.updatedAt).getTime() - toDate(a.updatedAt).getTime()),
    }))
    .filter((group) => group.items.length > 0);
  const flat = groups.flatMap((group) => group.items);
  const tabStop = flat.find((item) => item.id === focused)?.id ?? flat.find((item) => item.id === selectedId)?.id ?? flat[0]?.id;

  function focusRow(id: string | undefined) {
    if (!id) return;
    setFocused(id);
    rowRefs.current.get(id)?.focus();
  }

  function commitDeletes() {
    clearTimeout(timer.current);
    const items = pendingRef.current;
    pendingRef.current = [];
    setPending([]);
    for (const item of items) onDeleteRef.current?.(item.id);
  }

  function remove(item: Conversation) {
    const index = flat.findIndex((other) => other.id === item.id);
    const next = flat[index + 1] ?? flat[index - 1];
    pendingRef.current = [...pendingRef.current, item];
    setPending(pendingRef.current);
    setAnnouncement(`Deleted ${item.title}. Undo is available.`);
    clearTimeout(timer.current);
    timer.current = setTimeout(commitDeletes, undoMs);
    if (next && rowRefs.current.get(item.id) === document.activeElement) requestAnimationFrame(() => focusRow(next.id));
  }

  function undo() {
    clearTimeout(timer.current);
    const restored = pendingRef.current;
    pendingRef.current = [];
    setPending([]);
    setAnnouncement(restored.length === 1 ? `Restored ${restored[0]!.title}` : `Restored ${restored.length} chats`);
    const last = restored[restored.length - 1];
    if (last) requestAnimationFrame(() => focusRow(last.id));
  }

  function rename(id: string, title: string) {
    setRenaming(null);
    const current = conversations.find((item) => item.id === id);
    const next = title.trim();
    if (current && next && next !== current.title) onRename?.(id, next);
    requestAnimationFrame(() => focusRow(id));
  }

  function onRowKeyDown(event: KeyboardEvent<HTMLElement>, item: Conversation, index: number) {
    if (event.metaKey || event.ctrlKey || event.altKey) return;
    switch (event.key) {
      case "ArrowDown":
        focusRow(flat[index + 1]?.id);
        break;
      case "ArrowUp":
        if (index === 0 && searchable) searchRef.current?.focus();
        else focusRow(flat[index - 1]?.id);
        break;
      case "Home":
        focusRow(flat[0]?.id);
        break;
      case "End":
        focusRow(flat[flat.length - 1]?.id);
        break;
      case "F2":
        if (!onRename) return;
        setRenaming(item.id);
        break;
      case "Delete":
      case "Backspace":
        if (!onDelete) return;
        remove(item);
        break;
      default:
        return;
    }
    event.preventDefault();
  }

  const hasMenu = onPinChange !== undefined || onRename !== undefined || onDelete !== undefined;
  const searching = q.length > 0;

  return (
    <MotionConfig reducedMotion="user">
      <nav aria-label={label} className={cx("relative flex min-h-0 w-full flex-col text-left text-zinc-950 dark:text-white", className)} {...props}>
        {searchable ? (
          <div className="relative px-1 pb-2">
            <label htmlFor={searchId} className="sr-only">
              Search chats
            </label>
            <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="pointer-events-none absolute top-[15px] left-3.5 size-4 -translate-y-1/2 text-zinc-500">
              <circle cx="7" cy="7" r="4.25" />
              <path d="m10.25 10.25 3 3" />
            </svg>
            <input
              ref={searchRef}
              id={searchId}
              type="search"
              value={query}
              onChange={(event) => setQuery(event.target.value)}
              onKeyDown={(event) => {
                if (event.key === "ArrowDown") {
                  event.preventDefault();
                  focusRow(flat[0]?.id);
                } else if (event.key === "Escape" && query) {
                  event.preventDefault();
                  setQuery("");
                }
              }}
              placeholder="Search chats"
              autoComplete="off"
              className={cx(
                "h-8 w-full rounded-lg border border-zinc-950/10 bg-white pr-2.5 pl-8 text-sm text-zinc-950 placeholder:text-zinc-500 [&::-webkit-search-cancel-button]:hidden",
                "transition-[border-color] duration-150 ease-out hover:border-zinc-950/20 motion-reduce:transition-none",
                "dark:border-white/10 dark:bg-black dark:text-white dark:hover:border-white/20",
                "focus-visible:border-sky-500/60 focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500/40",
              )}
            />
          </div>
        ) : null}

        <div className="min-h-0 flex-1 overflow-y-auto px-1 pb-1">
          {groups.length === 0 ? (
            <p className="px-2 py-6 text-center text-sm text-zinc-500">
              {searching ? `No chats match "${query.trim()}"` : (empty ?? "No chats yet")}
            </p>
          ) : (
            <LayoutGroup>
              {groups.map((group) => {
                const headingId = `${searchId}-${group.name.replace(/\s+/g, "-")}`;
                return (
                  <motion.section key={group.name} layout={searching ? false : "position"} transition={move} aria-labelledby={headingId} className="mt-3 first:mt-0">
                    <motion.h3 layout={searching ? false : "position"} transition={move} id={headingId} className="px-2 pt-1 pb-1 text-xs font-medium text-zinc-500">
                      {group.name}
                    </motion.h3>
                    <ul className="flex flex-col gap-px">
                      <AnimatePresence initial={false} mode="popLayout">
                        {group.items.map((item) => {
                          const index = flat.indexOf(item);
                          return (
                            <motion.li
                              key={item.id}
                              layoutId={searching ? undefined : `conversation-${searchId}-${item.id}`}
                              layout={searching ? false : "position"}
                              transition={move}
                              initial={{ opacity: 0 }}
                              animate={{ opacity: 1 }}
                              exit={{ opacity: 0, scale: 0.98, transition: { duration: 0.15, ease: "easeOut" } }}
                            >
                              <Row
                                item={item}
                                query={q}
                                selected={item.id === selectedId}
                                tabStop={item.id === tabStop}
                                renaming={renaming === item.id}
                                hasMenu={hasMenu}
                                canPin={onPinChange !== undefined}
                                canRename={onRename !== undefined}
                                canDelete={onDelete !== undefined}
                                rowRef={(el) => {
                                  if (el) rowRefs.current.set(item.id, el);
                                  else rowRefs.current.delete(item.id);
                                }}
                                onFocus={() => setFocused(item.id)}
                                onKeyDown={(event) => onRowKeyDown(event, item, index)}
                                onSelect={() => onSelect?.(item.id)}
                                onPin={() => {
                                  onPinChange?.(item.id, !item.pinned);
                                  setAnnouncement(item.pinned ? `Unpinned ${item.title}` : `Pinned ${item.title}`);
                                }}
                                onStartRename={() => setRenaming(item.id)}
                                onRename={(title) => rename(item.id, title)}
                                onCancelRename={() => {
                                  setRenaming(null);
                                  requestAnimationFrame(() => focusRow(item.id));
                                }}
                                onDelete={() => remove(item)}
                              />
                            </motion.li>
                          );
                        })}
                      </AnimatePresence>
                    </ul>
                  </motion.section>
                );
              })}
            </LayoutGroup>
          )}
        </div>

        {pending.length > 0 ? (
          <div
            role="status"
            className={cx(
              "relative mx-1 mt-1 flex h-10 shrink-0 items-center gap-2 overflow-hidden rounded-lg border border-zinc-950/10 bg-white pr-1 pl-3 text-sm shadow-[0_8px_24px_-12px_rgb(0_0_0/0.25)]",
              "dark:border-white/15 dark:bg-black dark:shadow-[0_12px_32px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]",
              "transition-[opacity,translate] duration-[260ms] motion-reduce:transition-none",
              ease,
              "starting:translate-y-2 starting:opacity-0",
            )}
          >
            <span className="min-w-0 flex-1 truncate text-zinc-600 dark:text-zinc-400">
              {pending.length === 1 ? (
                <>
                  Deleted <span className="text-zinc-950 dark:text-white">{pending[0]!.title}</span>
                </>
              ) : (
                `Deleted ${pending.length} chats`
              )}
            </span>
            <button
              type="button"
              onClick={undo}
              className={cx(
                "inline-flex h-8 shrink-0 cursor-pointer items-center rounded-md px-2.5 text-sm font-medium text-zinc-950 select-none dark:text-white",
                "transition-[background-color,scale] duration-150 ease-out hover:bg-zinc-950/[0.05] motion-safe:active:scale-[0.97] motion-reduce:transition-none dark:hover:bg-white/[0.08]",
                "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
              )}
            >
              Undo
            </button>
            {/* Time left to undo; restarts with each delete. Still under reduced motion. */}
            <span
              key={pending.length}
              aria-hidden="true"
              style={{ transitionDuration: `${undoMs}ms` }}
              className={cx(
                "absolute inset-x-0 bottom-0 h-px origin-left bg-zinc-950/30 dark:bg-white/35",
                "scale-x-0 transition-[scale] ease-linear starting:scale-x-100 motion-reduce:scale-x-100 motion-reduce:transition-none",
              )}
            />
          </div>
        ) : null}
        <span className="sr-only" aria-live="polite">
          {announcement}
        </span>
      </nav>
    </MotionConfig>
  );
}

// ---------------------------------------------------------------------------
// Row

interface RowProps {
  item: Conversation;
  query: string;
  selected: boolean;
  tabStop: boolean;
  renaming: boolean;
  hasMenu: boolean;
  canPin: boolean;
  canRename: boolean;
  canDelete: boolean;
  rowRef: (el: HTMLElement | null) => void;
  onFocus: () => void;
  onKeyDown: (event: KeyboardEvent<HTMLElement>) => void;
  onSelect: () => void;
  onPin: () => void;
  onStartRename: () => void;
  onRename: (title: string) => void;
  onCancelRename: () => void;
  onDelete: () => void;
}

function Row({
  item,
  query,
  selected,
  tabStop,
  renaming,
  hasMenu,
  canPin,
  canRename,
  canDelete,
  rowRef,
  onFocus,
  onKeyDown,
  onSelect,
  onPin,
  onStartRename,
  onRename,
  onCancelRename,
  onDelete,
}: RowProps) {
  const [menuOpen, setMenuOpen] = useState(false);
  const rowClass = cx(
    "flex h-9 min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-lg pr-1 pl-2 text-left text-sm select-none",
    selected ? "text-zinc-950 dark:text-white" : "text-zinc-700 dark:text-zinc-300",
    "focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
  );
  const content = (
    <>
      <span className="min-w-0 flex-1 truncate">
        <Highlight text={item.title} query={query} />
      </span>
      <StatusMark item={item} />
    </>
  );
  const common = {
    ref: rowRef,
    tabIndex: tabStop ? 0 : -1,
    "aria-current": selected ? ("page" as const) : undefined,
    onFocus,
    onKeyDown,
    onDoubleClick: canRename ? onStartRename : undefined,
    className: rowClass,
  };

  return (
    <div
      data-selected={selected || undefined}
      className={cx(
        "group/row relative flex items-center rounded-lg",
        "transition-colors duration-150 ease-out motion-reduce:transition-none",
        selected ? "bg-zinc-950/[0.06] dark:bg-white/[0.09]" : "hover:bg-zinc-950/[0.04] dark:hover:bg-white/[0.06]",
        menuOpen && !selected && "bg-zinc-950/[0.04] dark:bg-white/[0.06]",
      )}
    >
      {renaming ? (
        <RenameField title={item.title} onCommit={onRename} onCancel={onCancelRename} />
      ) : item.href ? (
        <a href={item.href} onClick={onSelect} {...common}>
          {content}
        </a>
      ) : (
        <button
          type="button"
          onClick={onSelect}
          {...common}
        >
          {content}
        </button>
      )}
      {hasMenu && !renaming ? (
        <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
          <DropdownMenuTrigger
            tabIndex={tabStop ? 0 : -1}
            aria-label={`More actions for ${item.title}`}
            className={cx(
              "mr-1 inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-zinc-500",
              "opacity-0 transition-[opacity,background-color,color] duration-150 ease-out motion-reduce:transition-none",
              "group-hover/row:opacity-100 group-focus-within/row:opacity-100 data-[popup-open]:opacity-100 [@media(hover:none)]:opacity-100",
              "hover:bg-zinc-950/[0.06] hover:text-zinc-950 dark:hover:bg-white/[0.09] dark:hover:text-white",
              "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500",
            )}
          >
            <svg aria-hidden="true" viewBox="0 0 16 16" fill="currentColor" className="size-4">
              <circle cx="3.75" cy="8" r="1.1" />
              <circle cx="8" cy="8" r="1.1" />
              <circle cx="12.25" cy="8" r="1.1" />
            </svg>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="min-w-44">
            {canPin ? (
              <DropdownMenuItem onClick={onPin}>
                <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  {item.pinned ? (
                    <path d="M2.75 2.75l10.5 10.5M8 11.25v3M5.75 3.25h4.5M6.25 3.25v3.5L4.25 9.25v1.5h6.5" />
                  ) : (
                    <path d="M8 11.25v3M5.75 1.75h4.5M6.25 1.75v4.5L4.25 8.75v2.5h7.5v-2.5l-2-2.5v-4.5" />
                  )}
                </svg>
                {item.pinned ? "Unpin" : "Pin"}
              </DropdownMenuItem>
            ) : null}
            {canRename ? (
              <DropdownMenuItem onClick={onStartRename}>
                <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M10.25 3.25 12.75 5.75M3.25 12.75l.6-2.75 7.4-7.4a1.4 1.4 0 0 1 2 2l-7.4 7.4z" />
                </svg>
                Rename
              </DropdownMenuItem>
            ) : null}
            {canDelete ? (
              <>
                {canPin || canRename ? <DropdownMenuSeparator /> : null}
                <DropdownMenuItem destructive onClick={onDelete}>
                  <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M3 4.5h10M6.5 4.5V3.25c0-.28.22-.5.5-.5h2c.28 0 .5.22.5.5V4.5M4.5 4.5l.6 8.1c.04.52.47.9.99.9h3.82c.52 0 .95-.38.99-.9l.6-8.1" />
                  </svg>
                  Delete
                </DropdownMenuItem>
              </>
            ) : null}
          </DropdownMenuContent>
        </DropdownMenu>
      ) : null}
    </div>
  );
}

function StatusMark({ item }: { item: Conversation }) {
  if (item.status === "running") {
    return (
      <span className="flex shrink-0 items-center">
        <AgentMark activity={item.activity ?? "thinking"} size={14} aria-hidden="true" className="text-zinc-700 dark:text-zinc-300" />
        <span className="sr-only">, agent working</span>
      </span>
    );
  }
  if (item.status === "waiting" || item.status === "failed") {
    const waiting = item.status === "waiting";
    return (
      <span className={cx("flex shrink-0 items-center", waiting ? "text-amber-600 dark:text-amber-400" : "text-red-600 dark:text-red-400")}>
        <svg
          aria-hidden="true"
          viewBox="0 0 16 16"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          className={cx("size-3.5 transition-[opacity,scale] duration-200 motion-reduce:transition-none", ease, "starting:scale-90 starting:opacity-0")}
        >
          <circle cx="8" cy="8" r="6.25" />
          {waiting ? <path d="M6.5 5.75v4.5M9.5 5.75v4.5" /> : <path d="m6 6 4 4M10 6l-4 4" />}
        </svg>
        <span className="sr-only">{waiting ? ", waiting for approval" : ", run failed"}</span>
      </span>
    );
  }
  return null;
}

function RenameField({ title, onCommit, onCancel }: { title: string; onCommit: (title: string) => void; onCancel: () => void }) {
  const [value, setValue] = useState(title);
  const ref = useRef<HTMLInputElement>(null);
  const done = useRef(false);
  useEffect(() => {
    ref.current?.focus();
    ref.current?.select();
  }, []);
  return (
    <input
      ref={ref}
      aria-label="Chat title"
      value={value}
      onChange={(event) => setValue(event.target.value)}
      onKeyDown={(event) => {
        if (event.key === "Enter") {
          event.preventDefault();
          done.current = true;
          onCommit(value);
        } else if (event.key === "Escape") {
          event.preventDefault();
          done.current = true;
          onCancel();
        }
      }}
      onBlur={() => {
        if (!done.current) onCommit(value);
      }}
      className={cx(
        "mx-1 h-8 min-w-0 flex-1 rounded-md border border-sky-500/60 bg-white px-1.5 text-sm text-zinc-950 outline-2 outline-sky-500/30",
        "dark:bg-black dark:text-white",
      )}
    />
  );
}

function Highlight({ text, query }: { text: string; query: string }) {
  if (!query) return <>{text}</>;
  const at = text.toLowerCase().indexOf(query);
  if (at < 0) return <>{text}</>;
  return (
    <>
      {text.slice(0, at)}
      <mark className="rounded-[3px] bg-sky-500/20 text-inherit dark:bg-sky-400/25">{text.slice(at, at + query.length)}</mark>
      {text.slice(at + query.length)}
    </>
  );
}