Data Displayduskmoonimplemented18 demos

Chat

Chat composes unboxed agent answers, native activity disclosures, collapsible user bubbles, controlled waiting queues, and native or controlled composers.

Import@duskmoon-dev/components/chat
46API sections
92documented props
7behavior scenarios
Key API
placementtimelinehovertargetIdcolorsize

Usage

When to use

  • Use it to clarify state, metadata, content hierarchy, or loading without creating a new workflow.
  • Pair it with semantic content so visual treatment never becomes the only source of meaning.

Implementation notes

StylesheetImport @duskmoon-dev/components/styles.css once in the app or docs shell.
StateStart with default props for static examples, then switch to controlled props when state must be shared.
ThemeThe preview inherits the active DuskMoon data-theme value from the docs layout.
Optional compact presentationBoth Composer layouts use icon buttons with accessible names and title hints. Set compact on Chat.Composer, ChatSessionComposer or RichChatComposer for Core 1.21.1's Add menu and simple ready-image thumbnails. The default layout keeps independent Stop and Send actions. Files, mixed attachments, preparation and errors retain their complete rows. Compose native popovers through children; model choices and acknowledgments remain application-owned.
Public settings menus, context and approvalsCore 1.21.5 supplies all styles for ComposerSettings variant=menu, Chat.ComposerContext and Chat.Request. Pass a context node to either composer; it renders first inside the composer and inherits the compact or ghost surface. Context items accept decorative icons and named actions; ComposerConnection announces its connection state. Put Chat.Request next to Chat.Tool inside Chat.Agent. Actions with tone primary or danger render filled; untoned actions render as outlined secondary buttons. The host controls request state and pending decisions; resolved and answer-elsewhere requests have no actions.
Choose the editor contractKeep Chat.Composer for controlled string/File inputs. ChatSessionComposer adds portable documents and host receipts. RichChatComposer is available only from @duskmoon-dev/components/chat/rich; root and /chat imports do not load the editor runtime.
Controlled updates, history and clipboardEcho editor updates unchanged to preserve selection and undo. Explicit replace, restore, scope-switch and clear updates reset rich history. Remounts restore content, not undo. Rich copy includes portable semantic data and plain text; external paste uses text. Mixed file/text paste preserves the text and applies the same file intake policy.
The host owns authority and recoveryKeep the recovery owner and optional draft adapter stable beyond editor mounts. Pending/unknown submissions retain their immutable identity; reconcile before any explicitly authorized retry. Hosts authorize references and handles, prepare files, admit prompts, execute commands, confirm queue projections and acknowledge settings. The demos simulate these transitions in memory and provide no durable delivery guarantee.

Features

Visual hierarchy

Focuses on status, metadata, empty/loading states, or content grouping without owning application state.

Theme integration

Uses DuskMoon tokens so the component follows the active docs theme.

Primary API surface

Chat is most often configured through `placement`, `timeline`, `hover`, `targetId`.

Covered behavior

Renders a start-aligned turn with structural slots

Feature Demos

Feature demos are authored for the component page, then supplemented with behavior scenarios from the component test coverage.

Preview
Assistant
I can check the changes. This command needs your approval first.
Run project tests Not executed
npm test
This preview records a decision without executing the command.
Allow the assistant to run npm test?
Awaiting approval
npm test

Working directory: /workspace/example

Apply changes to three files?
Expired

The host withdrew this request after the turn ended.

Confirm the deployment?
Answer elsewhere

Open the original terminal client to answer this request.

/workspace/exampleGoal: verify the changesLocal host connected

Timeline Approvals and Composer Context

authored

Host-owned approval requests stay next to tool calls in the agent timeline. Decisions remain pending until the demo host confirms them; expired requests and requests answered elsewhere keep their details without actions. The composer context shares the surface across compact and ghost variants and exposes a named goal action.

Source
import React, { useEffect, useRef, useState } from "react";
import { Chat, type ChatRequestState } from "@duskmoon-dev/components/chat";

/** The demo host, rather than Chat.Request, confirms each delayed decision. */
export function ChatRequestsPreview() {
  const [state, setState] = useState<ChatRequestState>("pending");
  const [pending, setPending] = useState(false);
  const [value, setValue] = useState("");
  const [sent, setSent] = useState("");
  const [goal, setGoal] = useState(true);
  const [compact, setCompact] = useState(true);
  const [ghost, setGhost] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  useEffect(() => () => clearTimeout(timer.current), []);

  function decide(next: ChatRequestState) {
    if (timer.current || state !== "pending") return;
    setPending(true);
    timer.current = setTimeout(() => {
      setState(next);
      setPending(false);
      timer.current = undefined;
    }, 650);
  }

  function reset() {
    clearTimeout(timer.current);
    timer.current = undefined;
    setPending(false);
    setState("pending");
  }

  return (
    <div
      data-chat-requests-demo
      style={{ width: "min(44rem, 100%)", display: "grid", gap: "1rem" }}
    >
      <div
        className="chat-demo-controls"
        role="group"
        aria-label="Demo controls"
      >
        <button type="button" className="btn btn-sm" onClick={reset}>
          Reset approval request
        </button>
        <label>
          <input
            type="checkbox"
            className="checkbox checkbox-sm"
            checked={compact}
            onChange={(event) => setCompact(event.currentTarget.checked)}
          />{" "}
          Compact composer
        </label>
        <label>
          <input
            type="checkbox"
            className="checkbox checkbox-sm"
            checked={ghost}
            onChange={(event) => setGhost(event.currentTarget.checked)}
          />{" "}
          Ghost composer
        </label>
      </div>
      <Chat.Agent>
        <Chat.Header>Assistant</Chat.Header>
        <Chat.Content>
          I can check the changes. This command needs your approval first.
        </Chat.Content>
        <Chat.Tool status="pending" open>
          <Chat.ToolHeader>
            Run project tests <Chat.ToolStatus>Not executed</Chat.ToolStatus>
          </Chat.ToolHeader>
          <Chat.ToolCall>
            <code>npm test</code>
          </Chat.ToolCall>
          <Chat.ToolResult>
            This preview records a decision without executing the command.
          </Chat.ToolResult>
        </Chat.Tool>
        <Chat.Request
          title="Allow the assistant to run npm test?"
          state={state}
          pending={pending}
          actions={[
            {
              id: "approve",
              label: "Approve",
              tone: "primary",
              onSelect: () => decide("approved"),
            },
            {
              id: "session",
              label: "Approve for this session",
              onSelect: () => decide("approved-for-session"),
            },
            {
              id: "decline",
              label: "Decline",
              tone: "danger",
              onSelect: () => decide("declined"),
            },
          ]}
        >
          <pre aria-label="Requested command">
            <code>npm test</code>
          </pre>
          <p>Working directory: /workspace/example</p>
        </Chat.Request>
        <Chat.Request
          title="Apply changes to three files?"
          state="expired"
          explanation={
            <p>The host withdrew this request after the turn ended.</p>
          }
        />
        <Chat.Request
          title="Confirm the deployment?"
          state="answer-elsewhere"
          explanation={
            <p>Open the original terminal client to answer this request.</p>
          }
        />
      </Chat.Agent>
      <Chat.Composer
        compact={compact}
        className={ghost ? "chat-composer-ghost" : undefined}
        value={value}
        onValueChange={setValue}
        onSubmit={(submission) => setSent(submission.value)}
        textareaProps={{
          "aria-label": "Approval demo message",
          placeholder: "Keep writing while the host confirms a decision…",
        }}
        context={
          <Chat.ComposerContext>
            <Chat.ComposerContextItem icon={<span>⌘</span>}>
              /workspace/example
            </Chat.ComposerContextItem>
            {goal ? (
              <Chat.ComposerContextItem
                action={{
                  label: "Clear active goal",
                  children: "×",
                  onClick: () => setGoal(false),
                }}
              >
                Goal: verify the changes
              </Chat.ComposerContextItem>
            ) : null}
            <Chat.ComposerContextEnd>
              <Chat.ComposerConnection
                state="connected"
                label="Local host connected"
              />
            </Chat.ComposerContextEnd>
          </Chat.ComposerContext>
        }
      />
      {sent ? (
        <p role="status" aria-label="Demo submitted message">
          Submitted: {sent}
        </p>
      ) : null}
    </div>
  );
}
Preview
demo-repositoryConnected

Loading rich editor. Your draft is preserved.

Review the latest changes.
Export preserved draft
Add

Cmd/Ctrl+Enter sends; Enter adds a line. Add files with +; images become thumbnails after preparation. Type / to choose skills or commands, or @ for repository references.

Choose a model and reasoning effort from the model menu. Switch editors from Add. Stop and follow-up submission are independent.

This in-memory demo applies model choices only after the host acknowledges them.

Approval mode
Select model
Medium
LowMax

Host: idle; model: standard; waiting messages: 0.

Compact Composer and Model Menu

authored

Core 1.21.5 composition using public ComposerSettings menus and an attached context bar with an Add menu, approval choice, model/effort menus and ready-image thumbnails. The primary action sends a draft or stops a running turn. Choices wait for the in-memory host to acknowledge them; this demo changes no real permissions.

Source
import React, { useId, useRef, useState, useSyncExternalStore } from "react";
import {
  ChatAuthoritativeQueue,
  Chat,
  ComposerSettings,
  ChatSessionComposer,
  Button,
  createComposerRecoveryOwner,
  exportComposerText,
  type ChatSessionComposerHandle,
  type ComposerAttachmentOptions,
  type ComposerCapabilities,
  type ComposerCompletionProvider,
  type ComposerDocument,
  type ComposerProviderCandidate,
  type ComposerDocumentUpdate,
  type ComposerDraft,
  type ComposerDraftAdapter,
  type ComposerQueueEditorProps,
  type ComposerQueueMutation,
  type ComposerQueueMutationResult,
  type ComposerQueueProjection,
  type ComposerReceipt,
  type ComposerRuntimeState,
  type ComposerSessionHost,
  type ComposerSettingRequest,
  type ComposerSettingResult,
  type ComposerSubmission,
} from "@duskmoon-dev/components";
import { RichChatComposer } from "@duskmoon-dev/components/chat/rich";

const scope = { contextKey: "demo-repository", conversationId: "demo-thread" };
const capabilities: ComposerCapabilities = {
  protocolVersion: 1,
  documentVersions: [1],
  intents: ["send", "follow_up", "steer"],
  commands: true,
  attachments: true,
  queue: { edit: "document", remove: true, promote: true },
  durableRecovery: false,
};
type Admission = "accept" | "reject" | "unknown";
interface DemoState {
  readonly runtime: ComposerRuntimeState;
  readonly queue: ComposerQueueProjection;
  readonly settingsRevision: number;
  readonly model: string;
  readonly effort: string;
  readonly approval: string;
  readonly events: readonly string[];
}

/** Abortable demo latency, not an upload or execution transport. */
function pause(signal: AbortSignal) {
  return new Promise<void>((resolve, reject) => {
    if (signal.aborted) {
      reject(new DOMException("Cancelled", "AbortError"));
      return;
    }
    const abort = () => {
      clearTimeout(timer);
      reject(new DOMException("Cancelled", "AbortError"));
    };
    const timer = setTimeout(() => {
      signal.removeEventListener("abort", abort);
      resolve();
    }, 400);
    signal.addEventListener("abort", abort, { once: true });
  });
}

const settingsValues: Record<string, readonly string[]> = {
  model: ["standard", "fast"],
  effort: ["low", "medium", "high", "max"],
  approval: ["ask", "auto", "full"],
};

/** Stable per-preview host: memory only, lost on page reload. */
function createDemoHost() {
  const recovery = createComposerRecoveryOwner();
  const receipts = new Map<string, ComposerReceipt>();
  const drafts = new Map<string, ComposerDraft>();
  const listeners = new Set<() => void>();
  let admission: Admission = "accept";
  let failPreparation = true;
  let turnCounter = 0;
  const preparations = new Set<string>();
  let state: DemoState = {
    runtime: { status: "idle" },
    queue: { protocolVersion: 1, scope, revision: 0, items: [] },
    settingsRevision: 0,
    model: "standard",
    effort: "medium",
    approval: "ask",
    events: [],
  };
  function publish(next: Partial<DemoState>, event?: string) {
    state = {
      ...state,
      ...next,
      events: event ? [...state.events.slice(-7), event] : state.events,
    };
    listeners.forEach((listener) => listener());
  }
  function accept(snapshot: ComposerSubmission): ComposerReceipt {
    const identity = {
      protocolVersion: 1 as const,
      clientSubmissionId: snapshot.clientSubmissionId,
      scope: snapshot.scope,
      outcome: "accepted" as const,
    };
    if (snapshot.operation === "command") {
      const result = { help: "Use /review for a prompt or @ for a reference." };
      publish({}, `Command result: ${JSON.stringify(result)}`);
      return { ...identity, operation: "command", result };
    }
    const text =
      exportComposerText(snapshot.document) || "Attachment-only prompt";
    if (snapshot.intent === "follow_up") {
      const id = `waiting-${snapshot.clientSubmissionId}`;
      const queue = {
        ...state.queue,
        revision: state.queue.revision + 1,
        items: [
          ...state.queue.items,
          {
            id,
            document: snapshot.document,
            attachments: snapshot.attachments,
            capabilities: capabilities.queue,
          },
        ],
      };
      publish({ queue }, `Follow-up admitted: ${text}`);
      return {
        ...identity,
        operation: "prompt",
        delivery: "follow_up",
        persistence: "volatile",
        queueItemId: id,
        queueRevision: queue.revision,
      };
    }
    const turnId =
      snapshot.intent === "steer"
        ? snapshot.targetTurnId
        : `demo-turn-${++turnCounter}`;
    publish(
      { runtime: { status: "running", activeTurnId: turnId } },
      `${snapshot.intent === "steer" ? "Steer" : "Prompt"} admitted: ${text}`,
    );
    return {
      ...identity,
      operation: "prompt",
      delivery: snapshot.intent === "steer" ? "steer" : "immediate",
      persistence: "volatile",
      turnId,
    };
  }
  const host: ComposerSessionHost = {
    capabilities,
    recovery,
    commandOperation: (command) =>
      command.commandId === "help" ? "command" : "prompt",
    async submit(snapshot, signal) {
      const mode = admission;
      await pause(signal);
      const existing = receipts.get(snapshot.clientSubmissionId);
      if (existing) return existing;
      if (mode === "reject") {
        const receipt: ComposerReceipt = {
          protocolVersion: 1,
          scope: snapshot.scope,
          clientSubmissionId: snapshot.clientSubmissionId,
          operation: snapshot.operation,
          outcome: "rejected",
          error: {
            code: "demo_rejection",
            message:
              "Demo host rejected this request. Edit or change the outcome and submit again.",
          },
        };
        receipts.set(snapshot.clientSubmissionId, receipt);
        publish({}, "Request rejected; draft retained.");
        return receipt;
      }
      const receipt = accept(snapshot);
      receipts.set(snapshot.clientSubmissionId, receipt);
      if (mode !== "unknown") return receipt;
      publish(
        {},
        "Demo response lost after admission. Check submission status to reconcile.",
      );
      return {
        protocolVersion: 1,
        scope: snapshot.scope,
        clientSubmissionId: snapshot.clientSubmissionId,
        operation: snapshot.operation,
        outcome: "unknown",
        error: {
          code: "demo_response_lost",
          message:
            "Admission response was lost; do not assume failure or resend as a new request.",
        },
      };
    },
    async reconcile(snapshot, signal) {
      await pause(signal);
      const receipt = receipts.get(snapshot.clientSubmissionId);
      publish(
        {},
        receipt
          ? `Reconciled: ${receipt.outcome}`
          : "No admission record found; outcome remains unresolved.",
      );
      return receipt ?? { outcome: "not_found" };
    },
    async authorizeRetry() {
      publish(
        {},
        "Demo host authorized retry using the original submission identity.",
      );
      return true;
    },
  };
  const draftAdapter: ComposerDraftAdapter = {
    async load({ scope: owner, draftKey, signal }) {
      await pause(signal);
      return drafts.get(JSON.stringify([owner, draftKey]));
    },
    async save(draft, signal) {
      await pause(signal);
      drafts.set(JSON.stringify([draft.scope, draft.draftKey]), draft);
      publish({}, `Draft revision ${draft.revision} saved in demo memory.`);
    },
  };
  const attachmentOptions: Omit<ComposerAttachmentOptions, "scope"> = {
    policy: {
      accept: "image/*,.txt,.md,.pdf",
      maxFiles: 3,
      maxFileBytes: 2 * 1024 * 1024,
    },
    async prepare(file, { entryId, signal, reportProgress }) {
      reportProgress(0.25);
      await pause(signal);
      if (failPreparation && !preparations.has(entryId)) {
        preparations.add(entryId);
        throw new Error("Demo preparation failed once. Retry this attachment.");
      }
      reportProgress(1);
      return {
        providerId: "demo-files",
        reference: { entryId, name: file.name },
      };
    },
    // Omitted canRecover: saved occurrences require reattachment after remount.
  };
  return {
    host,
    draftAdapter,
    attachmentOptions,
    getSnapshot: () => state,
    subscribe(listener: () => void) {
      listeners.add(listener);
      return () => {
        listeners.delete(listener);
      };
    },
    setAdmission(value: Admission) {
      admission = value;
    },
    setFailPreparation(value: boolean) {
      failPreparation = value;
    },
    start() {
      publish(
        {
          runtime: {
            status: "running",
            activeTurnId: `demo-turn-${++turnCounter}`,
          },
        },
        "Demo turn started; no model is executing.",
      );
    },
    stop() {
      publish(
        { runtime: { status: "idle" } },
        "Stop acknowledged by demo host; queued messages remain waiting.",
      );
    },
    invoke() {
      publish(
        {},
        "Provider invocation executed independently of prompt admission.",
      );
    },
    async mutate(
      request: ComposerQueueMutation,
      signal: AbortSignal,
    ): Promise<ComposerQueueMutationResult> {
      await pause(signal);
      const item = state.queue.items.find(
        (entry) => entry.id === request.itemId,
      );
      if (
        request.expectedRevision !== state.queue.revision ||
        !item ||
        (request.operation === "promote" &&
          request.targetTurnId !== state.runtime.activeTurnId)
      ) {
        return {
          requestId: request.requestId,
          outcome: "rejected",
          projection: state.queue,
          error: {
            code: "queue_conflict",
            message:
              "Demo queue changed; use the canonical projection and try again.",
          },
        };
      }
      const queue: ComposerQueueProjection = {
        ...state.queue,
        revision: state.queue.revision + 1,
        items:
          request.operation === "edit"
            ? state.queue.items.map((entry) =>
                entry.id === item.id
                  ? { ...entry, document: request.document }
                  : entry,
              )
            : state.queue.items.filter((entry) => entry.id !== item.id),
      };
      publish(
        { queue },
        `Queue ${request.operation} acknowledged for ${request.itemId}.`,
      );
      return {
        requestId: request.requestId,
        outcome: "accepted",
        projection: queue,
      };
    },
    applyProjection(queue: ComposerQueueProjection) {
      if (queue.revision >= state.queue.revision) publish({ queue });
    },
    async requestSetting(
      request: ComposerSettingRequest,
      signal: AbortSignal,
    ): Promise<ComposerSettingResult> {
      await pause(signal);
      const identity = {
        requestId: request.requestId,
        scopeKey: request.scopeKey,
        settingId: request.settingId,
        revision: state.settingsRevision + 1,
      };
      if (
        request.expectedRevision !== state.settingsRevision ||
        request.value === "restricted" ||
        !(settingsValues[request.settingId] ?? []).includes(request.value)
      ) {
        return {
          ...identity,
          outcome: "rejected",
          message:
            "Demo host declined this model; the current selection is retained.",
        };
      }
      return { ...identity, outcome: "accepted", value: request.value };
    },
    acknowledgeSetting(result: ComposerSettingResult) {
      publish(
        {
          settingsRevision: result.revision,
          ...(result.outcome === "accepted"
            ? { [result.settingId]: result.value }
            : {}),
        },
        `${result.settingId} change ${result.outcome}.`,
      );
    },
  };
}

const providers: readonly ComposerCompletionProvider[] = [
  {
    providerId: "demo-files",
    label: "Repository references",
    icon: <DemoIcon name="reference" />,
    sourceLabel: "Demo",
    trigger: { text: "@", position: "word" },
    async query(request, signal) {
      await pause(signal);
      return {
        request,
        candidates: (
          [
            {
              id: "readme",
              label: "README.md",
              description: "Demo reference, resolved by the host",
              action: {
                type: "insert",
                content: [
                  {
                    type: "reference",
                    nodeId: `${request.requestId}-reference`,
                    providerId: "demo-files",
                    refId: "README.md",
                    label: "README.md",
                    plainText: "@README.md",
                  },
                ],
              },
            },
            {
              id: "private",
              label: "Private document",
              disabledReason: "Host has not granted access",
              action: { type: "insert", content: [] },
            },
          ] satisfies ComposerProviderCandidate[]
        ).filter((candidate) =>
          candidate.label.toLowerCase().includes(request.query.toLowerCase()),
        ),
      };
    },
  },
  {
    providerId: "demo-commands",
    label: "Commands",
    icon: <DemoIcon name="command" />,
    sourceLabel: "Demo",
    trigger: { text: "/", position: "leading" },
    async query(request, signal) {
      await pause(signal);
      return {
        request,
        candidates: (
          [
            {
              id: "help",
              label: "/help",
              description: "Show available commands",
              action: {
                type: "insert",
                command: { providerId: "demo-commands", commandId: "help" },
                content: [{ type: "text", text: "/help " }],
              },
            },
            {
              id: "review",
              label: "/review",
              description: "Review the current changes",
              action: {
                type: "insert",
                command: { providerId: "demo-commands", commandId: "review" },
                content: [{ type: "text", text: "/review " }],
              },
            },
            {
              id: "inspect",
              label: "/inspect",
              description: "Inspect the current session",
              action: {
                type: "invoke",
                command: { providerId: "demo-commands", commandId: "inspect" },
              },
            },
          ] satisfies ComposerProviderCandidate[]
        ).filter((candidate) => candidate.label.includes(request.query)),
      };
    },
  },
  {
    providerId: "demo-skills",
    label: "Skills",
    icon: <DemoIcon name="skill" />,
    sourceLabel: "Demo",
    trigger: { text: "/", position: "leading" },
    async query(request, signal) {
      await pause(signal);
      return {
        request,
        candidates: (
          [
            {
              id: "summarize",
              label: "/summarize",
              description: "Summarize changes and completed checks",
              action: {
                type: "insert",
                content: [
                  {
                    type: "text",
                    text: "Summarize the changes and list the checks that passed. ",
                  },
                ],
              },
            },
          ] satisfies ComposerProviderCandidate[]
        ).filter((candidate) => candidate.label.includes(request.query)),
      };
    },
  },
];

const demoIcons = {
  start: "m8 5 11 7-11 7Z",
  remount: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7",
  clear: "M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7",
  reference: "M14 2H6v20h12V6ZM14 2v5h5M8 12h8M8 16h5",
  quote: "M3 6h7v7H3ZM14 6h7v7h-7ZM10 13c0 4-2 6-5 6M21 13c0 4-2 6-5 6",
  command: "m4 6 6 6-6 6M13 18h7",
  skill: "m12 3 8 4v10l-8 4-8-4V7ZM4 7l8 4 8-4M12 11v10",
  review: "m15 4 5 5-11 11H4v-5ZM13 6l5 5",
  settings: "M4 7h16M4 17h16M8 4v6M16 14v6",
  help: "M12 8h.01M12 12v5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z",
  inspect: "M4 4h16v16H4ZM7 8l3 3-3 3M12 15h5",
  save: "M5 3h12l4 4v14H3V3ZM7 3v6h10V3M7 21v-8h10v8",
  cancel: "m6 6 12 12M6 18 18 6",
};
type DemoIconName = keyof typeof demoIcons;

function DemoIcon({ name }: { name: DemoIconName }) {
  return (
    <svg
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d={demoIcons[name]} />
    </svg>
  );
}

function DemoAction({
  label,
  icon,
  ...props
}: {
  label: string;
  icon: DemoIconName;
} & React.ComponentProps<typeof Button>) {
  return (
    <Button
      type="button"
      appearance="ghost"
      color="base"
      size="sm"
      shape="circle"
      {...props}
      aria-label={label}
      title={label}
    >
      <DemoIcon name={icon} />
    </Button>
  );
}

/** Core owns menu sizing/placement; the native Popover owns dismissal and focus. */
function DemoPopover({
  label,
  icon,
  children,
}: {
  label: string;
  icon: DemoIconName;
  children: React.ReactNode;
}) {
  const id = useId();
  const anchorName = `--demo-${id.replace(/[^a-zA-Z0-9_-]/g, "")}`;
  const [open, setOpen] = useState(false);
  return (
    <>
      <button
        type="button"
        className="popover-menu-item"
        aria-label={label}
        title={label}
        popoverTarget={id}
        aria-controls={id}
        aria-expanded={open}
        style={{ anchorName } as React.CSSProperties}
      >
        <DemoIcon name={icon} />
        <span>{label}</span>
      </button>
      <div
        id={id}
        popover="auto"
        className="popover popover-menu chat-composer-menu chat-demo-popover"
        role="group"
        aria-label={label}
        style={{ positionAnchor: anchorName } as React.CSSProperties}
        onToggle={(event) =>
          setOpen(event.currentTarget.matches(":popover-open"))
        }
      >
        {children}
      </div>
    </>
  );
}

const models = [
  ["standard", "Standard demo model", "Standard"],
  ["fast", "Fast demo model", "Fast"],
  ["restricted", "Restricted model (host rejects)", "Restricted"],
] as const;
const efforts = ["low", "medium", "high", "max"];
const effortLabels = ["Low", "Medium", "High", "Max"];
const approvals = [
  ["ask", "Ask for approval", "Review each action before it runs."],
  ["auto", "Approve for me", "Request review for sensitive actions."],
  ["full", "Full access", "Allow actions without an approval prompt."],
] as const;

const menuGroups = [
  {
    id: "approval",
    label: "Approval mode",
    settingIds: ["approval"],
    appearance: "access" as const,
  },
  {
    id: "model",
    label: "Model settings",
    settingIds: ["model", "effort"],
    nestedSettingIds: ["model"],
    appearance: "model" as const,
  },
];

function QueueDocumentEditor({
  value,
  onChange,
  onSave,
  onCancel,
  pending,
}: ComposerQueueEditorProps) {
  return (
    <>
      {value.content.map((node, index) =>
        node.type === "text" ? (
          <textarea
            key={index}
            className="chat-composer-input"
            aria-label={`Queued text ${index + 1}`}
            value={node.text}
            disabled={pending}
            onChange={(event) =>
              onChange({
                ...value,
                content: value.content.map((entry, at) =>
                  at === index
                    ? { type: "text", text: event.currentTarget.value }
                    : entry,
                ),
              })
            }
          />
        ) : (
          <p key={node.nodeId}>
            {node.type === "reference" ? node.label : node.text}
          </p>
        ),
      )}
      <DemoAction
        label="Save queued document"
        icon="save"
        disabled={pending}
        onClick={onSave}
      />
      <DemoAction
        label="Cancel"
        icon="cancel"
        disabled={pending}
        onClick={onCancel}
      />
    </>
  );
}

function SessionDemo({ rich }: { rich: boolean }) {
  const [demo] = useState(createDemoHost);
  const state = useSyncExternalStore(
    demo.subscribe,
    demo.getSnapshot,
    demo.getSnapshot,
  );
  const [value, setValue] = useState<ComposerDocumentUpdate>({
    document: {
      schemaVersion: 1,
      content: [{ type: "text", text: "Review the latest changes." }],
    },
    revision: 0,
    origin: "replace",
    originId: "demo-initial",
  });
  const [mount, setMount] = useState(0);
  const [admission, setAdmission] = useState<Admission>("accept");
  const [intent, setIntent] = useState<"follow_up" | "steer">("follow_up");
  const [failPreparation, setFailPreparation] = useState(true);
  const editor = useRef<ChatSessionComposerHandle>(null);
  const occurrence = useRef(0);
  const Composer = rich ? RichChatComposer : ChatSessionComposer;
  function replace(document: ComposerDocument) {
    setValue((current) => ({
      document,
      revision: current.revision + 1,
      origin: "replace",
      originId: `demo-replace-${++occurrence.current}`,
    }));
  }
  const addMenu = (
    <>
      <DemoPopover label="Demo controls" icon="settings">
        <div className="chat-demo-controls">
          <DemoAction
            label="Start demo turn"
            icon="start"
            onClick={demo.start}
          />
        </div>
        <div className="chat-demo-fields">
          <label>
            Admission outcome{" "}
            <select
              className="select select-sm"
              value={admission}
              onChange={(event) => {
                const next = event.currentTarget.value as Admission;
                setAdmission(next);
                demo.setAdmission(next);
              }}
            >
              <option value="accept">Accept</option>
              <option value="reject">Reject</option>
              <option value="unknown">Lose response after admission</option>
            </select>
          </label>
          <label>
            Running intent{" "}
            <select
              className="select select-sm"
              value={intent}
              onChange={(event) =>
                setIntent(event.currentTarget.value as "follow_up" | "steer")
              }
            >
              <option value="follow_up">Follow-up</option>
              <option value="steer">Steer active turn</option>
            </select>
          </label>
          <label>
            <input
              type="checkbox"
              className="checkbox checkbox-sm"
              checked={failPreparation}
              onChange={(event) => {
                setFailPreparation(event.currentTarget.checked);
                demo.setFailPreparation(event.currentTarget.checked);
              }}
            />{" "}
            Fail first preparation
          </label>
        </div>
        <div className="chat-demo-controls">
          <DemoAction
            label="Remount editor"
            icon="remount"
            onClick={() => setMount((current) => current + 1)}
          />
          <DemoAction
            label="Replace with empty document"
            icon="clear"
            onClick={() =>
              replace({
                schemaVersion: 1,
                content: [{ type: "text", text: "" }],
              })
            }
          />
          {rich ? (
            <>
              <DemoAction
                label="Insert reference"
                icon="reference"
                onClick={() =>
                  editor.current?.insertReference({
                    type: "reference",
                    nodeId: `demo-ref-${++occurrence.current}`,
                    providerId: "demo-files",
                    refId: "README.md",
                    label: "README.md",
                    plainText: "@README.md",
                  })
                }
              />
              <DemoAction
                label="Insert quote"
                icon="quote"
                onClick={() =>
                  editor.current?.insertQuote({
                    type: "quote",
                    nodeId: `demo-quote-${++occurrence.current}`,
                    text: "Keep user edits while admission is pending.",
                    source: {
                      messageId: "demo-message",
                      conversationId: scope.conversationId,
                      label: "Earlier assistant reply",
                    },
                  })
                }
              />
              <DemoAction
                label="Claim /help command"
                icon="command"
                onClick={() =>
                  editor.current?.claimCommand(
                    { providerId: "demo-commands", commandId: "help" },
                    "/help",
                  )
                }
              />
              <DemoAction
                label="Claim /review prompt"
                icon="review"
                onClick={() =>
                  editor.current?.claimCommand(
                    { providerId: "demo-commands", commandId: "review" },
                    "/review",
                  )
                }
              />
            </>
          ) : null}
        </div>
      </DemoPopover>
      <DemoPopover label="Composer help" icon="help">
        <div className="popover-body">
          <p>
            Cmd/Ctrl+Enter sends; Enter adds a line. Type @ for references or /
            for commands and editable skills.
          </p>
          <p>
            Add up to three images, .txt, .md or .pdf files, each at most 2 MiB.
            If preparation fails, use Retry.
          </p>
          <p>
            Save a draft before remounting to try restoration; files then
            require reattachment. Stop is independent of sending and
            preparation.
          </p>
          <p>
            This interactive demo keeps files, drafts and recovery in memory. It
            has no backend; reloading the page discards its state.
          </p>
        </div>
      </DemoPopover>
      <DemoPopover label="Inspect demo state" icon="inspect">
        <details>
          <summary>Current portable document</summary>
          <pre aria-label="Current portable document">
            {JSON.stringify(value.document, null, 2)}
          </pre>
        </details>
        <p>
          Host: {state.runtime.status}; model: {state.model}; queue revision:{" "}
          {state.queue.revision}.
        </p>
        <div aria-label="Demo host events" role="log" aria-live="off">
          {state.events.length ? (
            state.events.map((event, index) => (
              <p key={`${index}-${event}`}>{event}</p>
            ))
          ) : (
            <p>No events yet.</p>
          )}
        </div>
      </DemoPopover>
    </>
  );
  return (
    <div
      className="chat-demo chat-session-demo"
      data-chat-session-demo={rich ? "rich" : "plain"}
    >
      <p className="sr-only" role="status">
        Host: {state.runtime.status}; model: {state.model}; queue revision:{" "}
        {state.queue.revision}.
      </p>
      <ChatAuthoritativeQueue
        projection={state.queue}
        capabilities={capabilities.queue}
        targetTurnId={state.runtime.activeTurnId}
        onMutation={demo.mutate}
        onProjection={demo.applyProjection}
        renderDocumentEditor={(props) => <QueueDocumentEditor {...props} />}
      />
      <Composer
        compact
        addMenu={addMenu}
        attachLabel="Add files and more"
        className="chat-composer-ghost"
        key={mount}
        ref={editor}
        value={value}
        onDocumentChange={setValue}
        scope={scope}
        draftKey="demo-draft"
        host={demo.host}
        runtime={state.runtime}
        policy={{ runningIntent: intent }}
        options={{
          model: state.model,
          effort: state.effort,
          approval: state.approval,
        }}
        draftAdapter={demo.draftAdapter}
        attachmentOptions={demo.attachmentOptions}
        providers={providers}
        onProviderInvoke={demo.invoke}
        onStop={demo.stop}
        context={
          <Chat.ComposerContext>
            <Chat.ComposerContextItem icon={<DemoIcon name="reference" />}>
              demo-repository
            </Chat.ComposerContextItem>
            <Chat.ComposerContextEnd>
              <Chat.ComposerConnection state="connected" />
            </Chat.ComposerContextEnd>
          </Chat.ComposerContext>
        }
        allowAttachmentOnly
        label={rich ? "Rich demo message" : "Semantic demo message"}
      >
        <ComposerSettings
          variant="menu"
          groups={menuGroups}
          scopeKey={scope.conversationId}
          revision={state.settingsRevision}
          settings={[
            {
              id: "approval",
              label: "Approval mode",
              value: state.approval,
              choices: approvals.map(([value, label, description]) => ({
                value,
                label,
                description,
                tone: value === "full" ? ("warning" as const) : undefined,
              })),
            },
            {
              id: "model",
              label: "Model",
              value: state.model,
              choices: models.map(([value, label]) => ({ value, label })),
            },
            {
              id: "effort",
              label: "Reasoning effort",
              value: state.effort,
              ordered: true,
              defaultValue: "medium",
              choices: efforts.map((value, index) => ({
                value,
                label: effortLabels[index],
              })),
            },
          ]}
          onRequest={demo.requestSetting}
          onAcknowledged={demo.acknowledgeSetting}
        />
      </Composer>
    </div>
  );
}

export function SemanticComposerPreview() {
  return <SessionDemo rich={false} />;
}
export function RichComposerPreview() {
  return <SessionDemo rich />;
}

/** Focused Core 1.21.1 composition; settings still require host acknowledgment. */
export function CompactComposerPreview() {
  const [demo] = useState(() => {
    const host = createDemoHost();
    host.setFailPreparation(false);
    return host;
  });
  const state = useSyncExternalStore(
    demo.subscribe,
    demo.getSnapshot,
    demo.getSnapshot,
  );
  const [rich, setRich] = useState(true);
  const [value, setValue] = useState<ComposerDocumentUpdate>({
    document: {
      schemaVersion: 1,
      content: [{ type: "text", text: "Review the latest changes." }],
    },
    revision: 0,
    origin: "replace",
    originId: "compact-initial",
  });
  const Composer = rich ? RichChatComposer : ChatSessionComposer;
  return (
    <div className="chat-demo chat-session-demo" data-chat-compact-demo>
      <Composer
        compact
        attachLabel="Add files and more"
        addMenu={
          <>
            <DemoPopover label="Composer help" icon="help">
              <div className="popover-body">
                <p>
                  Cmd/Ctrl+Enter sends; Enter adds a line. Add files with +;
                  images become thumbnails after preparation. Type / to choose
                  skills or commands, or @ for repository references.
                </p>
                <p>
                  Choose a model and reasoning effort from the model menu.
                  Switch editors from Add. Stop and follow-up submission are
                  independent.
                </p>
                <p>
                  This in-memory demo applies model choices only after the host
                  acknowledges them.
                </p>
              </div>
            </DemoPopover>
            <label className="chat-composer-menu-field">
              <span>
                <input
                  type="checkbox"
                  className="checkbox checkbox-sm"
                  checked={rich}
                  onChange={(event) => setRich(event.currentTarget.checked)}
                />{" "}
                Use rich editor
              </span>
            </label>
          </>
        }
        className="chat-composer-ghost"
        value={value}
        onDocumentChange={setValue}
        scope={scope}
        draftKey="compact-demo"
        host={demo.host}
        runtime={state.runtime}
        attachmentOptions={demo.attachmentOptions}
        providers={providers}
        onProviderInvoke={demo.invoke}
        options={{
          model: state.model,
          effort: state.effort,
          approval: state.approval,
        }}
        onStop={demo.stop}
        context={
          <Chat.ComposerContext>
            <Chat.ComposerContextItem icon={<DemoIcon name="reference" />}>
              demo-repository
            </Chat.ComposerContextItem>
            <Chat.ComposerContextEnd>
              <Chat.ComposerConnection state="connected" />
            </Chat.ComposerContextEnd>
          </Chat.ComposerContext>
        }
        allowAttachmentOnly
        label="Compact demo message"
      >
        <ComposerSettings
          variant="menu"
          groups={menuGroups}
          scopeKey={scope.conversationId}
          revision={state.settingsRevision}
          settings={[
            {
              id: "approval",
              label: "Approval mode",
              value: state.approval,
              choices: approvals.map(([value, label, description]) => ({
                value,
                label,
                description,
                tone: value === "full" ? ("warning" as const) : undefined,
              })),
            },
            {
              id: "model",
              label: "Model",
              value: state.model,
              choices: models.map(([value, label]) => ({ value, label })),
            },
            {
              id: "effort",
              label: "Reasoning effort",
              value: state.effort,
              ordered: true,
              defaultValue: "medium",
              choices: efforts.map((value, index) => ({
                value,
                label: effortLabels[index],
              })),
            },
          ]}
          onRequest={demo.requestSetting}
          onAcknowledged={demo.acknowledgeSetting}
        />
      </Composer>
      <p className="sr-only" role="status" aria-label="Compact host state">
        Host: {state.runtime.status}; model: {state.model}; waiting messages:{" "}
        {state.queue.items.length}.
        {state.events.at(-1) ? ` ${state.events.at(-1)}` : ""}
      </p>
    </div>
  );
}
Preview

Host: idle; model: standard; queue revision: 0.

demo-repositoryConnected
Draft storage is provided by the host.
Add

Cmd/Ctrl+Enter sends; Enter adds a line. Type @ for references or / for commands and editable skills.

Add up to three images, .txt, .md or .pdf files, each at most 2 MiB. If preparation fails, use Retry.

Save a draft before remounting to try restoration; files then require reattachment. Stop is independent of sending and preparation.

This interactive demo keeps files, drafts and recovery in memory. It has no backend; reloading the page discards its state.

Current portable document
{
  "schemaVersion": 1,
  "content": [
    {
      "type": "text",
      "text": "Review the latest changes."
    }
  ]
}

Host: idle; model: standard; queue revision: 0.

No events yet.

Approval mode
Select model
Medium
LowMax

Semantic Composer and Recovery

authored

Controlled semantic plain editor with a typed in-memory host. Use the Add menu for explicit draft save, editor remount and demo controls. Try admission recovery, attachment preparation retry and follow-ups during a running turn. The existing string-based Composer remains available below.

Source
import React, { useId, useRef, useState, useSyncExternalStore } from "react";
import {
  ChatAuthoritativeQueue,
  Chat,
  ComposerSettings,
  ChatSessionComposer,
  Button,
  createComposerRecoveryOwner,
  exportComposerText,
  type ChatSessionComposerHandle,
  type ComposerAttachmentOptions,
  type ComposerCapabilities,
  type ComposerCompletionProvider,
  type ComposerDocument,
  type ComposerProviderCandidate,
  type ComposerDocumentUpdate,
  type ComposerDraft,
  type ComposerDraftAdapter,
  type ComposerQueueEditorProps,
  type ComposerQueueMutation,
  type ComposerQueueMutationResult,
  type ComposerQueueProjection,
  type ComposerReceipt,
  type ComposerRuntimeState,
  type ComposerSessionHost,
  type ComposerSettingRequest,
  type ComposerSettingResult,
  type ComposerSubmission,
} from "@duskmoon-dev/components";
import { RichChatComposer } from "@duskmoon-dev/components/chat/rich";

const scope = { contextKey: "demo-repository", conversationId: "demo-thread" };
const capabilities: ComposerCapabilities = {
  protocolVersion: 1,
  documentVersions: [1],
  intents: ["send", "follow_up", "steer"],
  commands: true,
  attachments: true,
  queue: { edit: "document", remove: true, promote: true },
  durableRecovery: false,
};
type Admission = "accept" | "reject" | "unknown";
interface DemoState {
  readonly runtime: ComposerRuntimeState;
  readonly queue: ComposerQueueProjection;
  readonly settingsRevision: number;
  readonly model: string;
  readonly effort: string;
  readonly approval: string;
  readonly events: readonly string[];
}

/** Abortable demo latency, not an upload or execution transport. */
function pause(signal: AbortSignal) {
  return new Promise<void>((resolve, reject) => {
    if (signal.aborted) {
      reject(new DOMException("Cancelled", "AbortError"));
      return;
    }
    const abort = () => {
      clearTimeout(timer);
      reject(new DOMException("Cancelled", "AbortError"));
    };
    const timer = setTimeout(() => {
      signal.removeEventListener("abort", abort);
      resolve();
    }, 400);
    signal.addEventListener("abort", abort, { once: true });
  });
}

const settingsValues: Record<string, readonly string[]> = {
  model: ["standard", "fast"],
  effort: ["low", "medium", "high", "max"],
  approval: ["ask", "auto", "full"],
};

/** Stable per-preview host: memory only, lost on page reload. */
function createDemoHost() {
  const recovery = createComposerRecoveryOwner();
  const receipts = new Map<string, ComposerReceipt>();
  const drafts = new Map<string, ComposerDraft>();
  const listeners = new Set<() => void>();
  let admission: Admission = "accept";
  let failPreparation = true;
  let turnCounter = 0;
  const preparations = new Set<string>();
  let state: DemoState = {
    runtime: { status: "idle" },
    queue: { protocolVersion: 1, scope, revision: 0, items: [] },
    settingsRevision: 0,
    model: "standard",
    effort: "medium",
    approval: "ask",
    events: [],
  };
  function publish(next: Partial<DemoState>, event?: string) {
    state = {
      ...state,
      ...next,
      events: event ? [...state.events.slice(-7), event] : state.events,
    };
    listeners.forEach((listener) => listener());
  }
  function accept(snapshot: ComposerSubmission): ComposerReceipt {
    const identity = {
      protocolVersion: 1 as const,
      clientSubmissionId: snapshot.clientSubmissionId,
      scope: snapshot.scope,
      outcome: "accepted" as const,
    };
    if (snapshot.operation === "command") {
      const result = { help: "Use /review for a prompt or @ for a reference." };
      publish({}, `Command result: ${JSON.stringify(result)}`);
      return { ...identity, operation: "command", result };
    }
    const text =
      exportComposerText(snapshot.document) || "Attachment-only prompt";
    if (snapshot.intent === "follow_up") {
      const id = `waiting-${snapshot.clientSubmissionId}`;
      const queue = {
        ...state.queue,
        revision: state.queue.revision + 1,
        items: [
          ...state.queue.items,
          {
            id,
            document: snapshot.document,
            attachments: snapshot.attachments,
            capabilities: capabilities.queue,
          },
        ],
      };
      publish({ queue }, `Follow-up admitted: ${text}`);
      return {
        ...identity,
        operation: "prompt",
        delivery: "follow_up",
        persistence: "volatile",
        queueItemId: id,
        queueRevision: queue.revision,
      };
    }
    const turnId =
      snapshot.intent === "steer"
        ? snapshot.targetTurnId
        : `demo-turn-${++turnCounter}`;
    publish(
      { runtime: { status: "running", activeTurnId: turnId } },
      `${snapshot.intent === "steer" ? "Steer" : "Prompt"} admitted: ${text}`,
    );
    return {
      ...identity,
      operation: "prompt",
      delivery: snapshot.intent === "steer" ? "steer" : "immediate",
      persistence: "volatile",
      turnId,
    };
  }
  const host: ComposerSessionHost = {
    capabilities,
    recovery,
    commandOperation: (command) =>
      command.commandId === "help" ? "command" : "prompt",
    async submit(snapshot, signal) {
      const mode = admission;
      await pause(signal);
      const existing = receipts.get(snapshot.clientSubmissionId);
      if (existing) return existing;
      if (mode === "reject") {
        const receipt: ComposerReceipt = {
          protocolVersion: 1,
          scope: snapshot.scope,
          clientSubmissionId: snapshot.clientSubmissionId,
          operation: snapshot.operation,
          outcome: "rejected",
          error: {
            code: "demo_rejection",
            message:
              "Demo host rejected this request. Edit or change the outcome and submit again.",
          },
        };
        receipts.set(snapshot.clientSubmissionId, receipt);
        publish({}, "Request rejected; draft retained.");
        return receipt;
      }
      const receipt = accept(snapshot);
      receipts.set(snapshot.clientSubmissionId, receipt);
      if (mode !== "unknown") return receipt;
      publish(
        {},
        "Demo response lost after admission. Check submission status to reconcile.",
      );
      return {
        protocolVersion: 1,
        scope: snapshot.scope,
        clientSubmissionId: snapshot.clientSubmissionId,
        operation: snapshot.operation,
        outcome: "unknown",
        error: {
          code: "demo_response_lost",
          message:
            "Admission response was lost; do not assume failure or resend as a new request.",
        },
      };
    },
    async reconcile(snapshot, signal) {
      await pause(signal);
      const receipt = receipts.get(snapshot.clientSubmissionId);
      publish(
        {},
        receipt
          ? `Reconciled: ${receipt.outcome}`
          : "No admission record found; outcome remains unresolved.",
      );
      return receipt ?? { outcome: "not_found" };
    },
    async authorizeRetry() {
      publish(
        {},
        "Demo host authorized retry using the original submission identity.",
      );
      return true;
    },
  };
  const draftAdapter: ComposerDraftAdapter = {
    async load({ scope: owner, draftKey, signal }) {
      await pause(signal);
      return drafts.get(JSON.stringify([owner, draftKey]));
    },
    async save(draft, signal) {
      await pause(signal);
      drafts.set(JSON.stringify([draft.scope, draft.draftKey]), draft);
      publish({}, `Draft revision ${draft.revision} saved in demo memory.`);
    },
  };
  const attachmentOptions: Omit<ComposerAttachmentOptions, "scope"> = {
    policy: {
      accept: "image/*,.txt,.md,.pdf",
      maxFiles: 3,
      maxFileBytes: 2 * 1024 * 1024,
    },
    async prepare(file, { entryId, signal, reportProgress }) {
      reportProgress(0.25);
      await pause(signal);
      if (failPreparation && !preparations.has(entryId)) {
        preparations.add(entryId);
        throw new Error("Demo preparation failed once. Retry this attachment.");
      }
      reportProgress(1);
      return {
        providerId: "demo-files",
        reference: { entryId, name: file.name },
      };
    },
    // Omitted canRecover: saved occurrences require reattachment after remount.
  };
  return {
    host,
    draftAdapter,
    attachmentOptions,
    getSnapshot: () => state,
    subscribe(listener: () => void) {
      listeners.add(listener);
      return () => {
        listeners.delete(listener);
      };
    },
    setAdmission(value: Admission) {
      admission = value;
    },
    setFailPreparation(value: boolean) {
      failPreparation = value;
    },
    start() {
      publish(
        {
          runtime: {
            status: "running",
            activeTurnId: `demo-turn-${++turnCounter}`,
          },
        },
        "Demo turn started; no model is executing.",
      );
    },
    stop() {
      publish(
        { runtime: { status: "idle" } },
        "Stop acknowledged by demo host; queued messages remain waiting.",
      );
    },
    invoke() {
      publish(
        {},
        "Provider invocation executed independently of prompt admission.",
      );
    },
    async mutate(
      request: ComposerQueueMutation,
      signal: AbortSignal,
    ): Promise<ComposerQueueMutationResult> {
      await pause(signal);
      const item = state.queue.items.find(
        (entry) => entry.id === request.itemId,
      );
      if (
        request.expectedRevision !== state.queue.revision ||
        !item ||
        (request.operation === "promote" &&
          request.targetTurnId !== state.runtime.activeTurnId)
      ) {
        return {
          requestId: request.requestId,
          outcome: "rejected",
          projection: state.queue,
          error: {
            code: "queue_conflict",
            message:
              "Demo queue changed; use the canonical projection and try again.",
          },
        };
      }
      const queue: ComposerQueueProjection = {
        ...state.queue,
        revision: state.queue.revision + 1,
        items:
          request.operation === "edit"
            ? state.queue.items.map((entry) =>
                entry.id === item.id
                  ? { ...entry, document: request.document }
                  : entry,
              )
            : state.queue.items.filter((entry) => entry.id !== item.id),
      };
      publish(
        { queue },
        `Queue ${request.operation} acknowledged for ${request.itemId}.`,
      );
      return {
        requestId: request.requestId,
        outcome: "accepted",
        projection: queue,
      };
    },
    applyProjection(queue: ComposerQueueProjection) {
      if (queue.revision >= state.queue.revision) publish({ queue });
    },
    async requestSetting(
      request: ComposerSettingRequest,
      signal: AbortSignal,
    ): Promise<ComposerSettingResult> {
      await pause(signal);
      const identity = {
        requestId: request.requestId,
        scopeKey: request.scopeKey,
        settingId: request.settingId,
        revision: state.settingsRevision + 1,
      };
      if (
        request.expectedRevision !== state.settingsRevision ||
        request.value === "restricted" ||
        !(settingsValues[request.settingId] ?? []).includes(request.value)
      ) {
        return {
          ...identity,
          outcome: "rejected",
          message:
            "Demo host declined this model; the current selection is retained.",
        };
      }
      return { ...identity, outcome: "accepted", value: request.value };
    },
    acknowledgeSetting(result: ComposerSettingResult) {
      publish(
        {
          settingsRevision: result.revision,
          ...(result.outcome === "accepted"
            ? { [result.settingId]: result.value }
            : {}),
        },
        `${result.settingId} change ${result.outcome}.`,
      );
    },
  };
}

const providers: readonly ComposerCompletionProvider[] = [
  {
    providerId: "demo-files",
    label: "Repository references",
    icon: <DemoIcon name="reference" />,
    sourceLabel: "Demo",
    trigger: { text: "@", position: "word" },
    async query(request, signal) {
      await pause(signal);
      return {
        request,
        candidates: (
          [
            {
              id: "readme",
              label: "README.md",
              description: "Demo reference, resolved by the host",
              action: {
                type: "insert",
                content: [
                  {
                    type: "reference",
                    nodeId: `${request.requestId}-reference`,
                    providerId: "demo-files",
                    refId: "README.md",
                    label: "README.md",
                    plainText: "@README.md",
                  },
                ],
              },
            },
            {
              id: "private",
              label: "Private document",
              disabledReason: "Host has not granted access",
              action: { type: "insert", content: [] },
            },
          ] satisfies ComposerProviderCandidate[]
        ).filter((candidate) =>
          candidate.label.toLowerCase().includes(request.query.toLowerCase()),
        ),
      };
    },
  },
  {
    providerId: "demo-commands",
    label: "Commands",
    icon: <DemoIcon name="command" />,
    sourceLabel: "Demo",
    trigger: { text: "/", position: "leading" },
    async query(request, signal) {
      await pause(signal);
      return {
        request,
        candidates: (
          [
            {
              id: "help",
              label: "/help",
              description: "Show available commands",
              action: {
                type: "insert",
                command: { providerId: "demo-commands", commandId: "help" },
                content: [{ type: "text", text: "/help " }],
              },
            },
            {
              id: "review",
              label: "/review",
              description: "Review the current changes",
              action: {
                type: "insert",
                command: { providerId: "demo-commands", commandId: "review" },
                content: [{ type: "text", text: "/review " }],
              },
            },
            {
              id: "inspect",
              label: "/inspect",
              description: "Inspect the current session",
              action: {
                type: "invoke",
                command: { providerId: "demo-commands", commandId: "inspect" },
              },
            },
          ] satisfies ComposerProviderCandidate[]
        ).filter((candidate) => candidate.label.includes(request.query)),
      };
    },
  },
  {
    providerId: "demo-skills",
    label: "Skills",
    icon: <DemoIcon name="skill" />,
    sourceLabel: "Demo",
    trigger: { text: "/", position: "leading" },
    async query(request, signal) {
      await pause(signal);
      return {
        request,
        candidates: (
          [
            {
              id: "summarize",
              label: "/summarize",
              description: "Summarize changes and completed checks",
              action: {
                type: "insert",
                content: [
                  {
                    type: "text",
                    text: "Summarize the changes and list the checks that passed. ",
                  },
                ],
              },
            },
          ] satisfies ComposerProviderCandidate[]
        ).filter((candidate) => candidate.label.includes(request.query)),
      };
    },
  },
];

const demoIcons = {
  start: "m8 5 11 7-11 7Z",
  remount: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7",
  clear: "M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7",
  reference: "M14 2H6v20h12V6ZM14 2v5h5M8 12h8M8 16h5",
  quote: "M3 6h7v7H3ZM14 6h7v7h-7ZM10 13c0 4-2 6-5 6M21 13c0 4-2 6-5 6",
  command: "m4 6 6 6-6 6M13 18h7",
  skill: "m12 3 8 4v10l-8 4-8-4V7ZM4 7l8 4 8-4M12 11v10",
  review: "m15 4 5 5-11 11H4v-5ZM13 6l5 5",
  settings: "M4 7h16M4 17h16M8 4v6M16 14v6",
  help: "M12 8h.01M12 12v5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z",
  inspect: "M4 4h16v16H4ZM7 8l3 3-3 3M12 15h5",
  save: "M5 3h12l4 4v14H3V3ZM7 3v6h10V3M7 21v-8h10v8",
  cancel: "m6 6 12 12M6 18 18 6",
};
type DemoIconName = keyof typeof demoIcons;

function DemoIcon({ name }: { name: DemoIconName }) {
  return (
    <svg
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d={demoIcons[name]} />
    </svg>
  );
}

function DemoAction({
  label,
  icon,
  ...props
}: {
  label: string;
  icon: DemoIconName;
} & React.ComponentProps<typeof Button>) {
  return (
    <Button
      type="button"
      appearance="ghost"
      color="base"
      size="sm"
      shape="circle"
      {...props}
      aria-label={label}
      title={label}
    >
      <DemoIcon name={icon} />
    </Button>
  );
}

/** Core owns menu sizing/placement; the native Popover owns dismissal and focus. */
function DemoPopover({
  label,
  icon,
  children,
}: {
  label: string;
  icon: DemoIconName;
  children: React.ReactNode;
}) {
  const id = useId();
  const anchorName = `--demo-${id.replace(/[^a-zA-Z0-9_-]/g, "")}`;
  const [open, setOpen] = useState(false);
  return (
    <>
      <button
        type="button"
        className="popover-menu-item"
        aria-label={label}
        title={label}
        popoverTarget={id}
        aria-controls={id}
        aria-expanded={open}
        style={{ anchorName } as React.CSSProperties}
      >
        <DemoIcon name={icon} />
        <span>{label}</span>
      </button>
      <div
        id={id}
        popover="auto"
        className="popover popover-menu chat-composer-menu chat-demo-popover"
        role="group"
        aria-label={label}
        style={{ positionAnchor: anchorName } as React.CSSProperties}
        onToggle={(event) =>
          setOpen(event.currentTarget.matches(":popover-open"))
        }
      >
        {children}
      </div>
    </>
  );
}

const models = [
  ["standard", "Standard demo model", "Standard"],
  ["fast", "Fast demo model", "Fast"],
  ["restricted", "Restricted model (host rejects)", "Restricted"],
] as const;
const efforts = ["low", "medium", "high", "max"];
const effortLabels = ["Low", "Medium", "High", "Max"];
const approvals = [
  ["ask", "Ask for approval", "Review each action before it runs."],
  ["auto", "Approve for me", "Request review for sensitive actions."],
  ["full", "Full access", "Allow actions without an approval prompt."],
] as const;

const menuGroups = [
  {
    id: "approval",
    label: "Approval mode",
    settingIds: ["approval"],
    appearance: "access" as const,
  },
  {
    id: "model",
    label: "Model settings",
    settingIds: ["model", "effort"],
    nestedSettingIds: ["model"],
    appearance: "model" as const,
  },
];

function QueueDocumentEditor({
  value,
  onChange,
  onSave,
  onCancel,
  pending,
}: ComposerQueueEditorProps) {
  return (
    <>
      {value.content.map((node, index) =>
        node.type === "text" ? (
          <textarea
            key={index}
            className="chat-composer-input"
            aria-label={`Queued text ${index + 1}`}
            value={node.text}
            disabled={pending}
            onChange={(event) =>
              onChange({
                ...value,
                content: value.content.map((entry, at) =>
                  at === index
                    ? { type: "text", text: event.currentTarget.value }
                    : entry,
                ),
              })
            }
          />
        ) : (
          <p key={node.nodeId}>
            {node.type === "reference" ? node.label : node.text}
          </p>
        ),
      )}
      <DemoAction
        label="Save queued document"
        icon="save"
        disabled={pending}
        onClick={onSave}
      />
      <DemoAction
        label="Cancel"
        icon="cancel"
        disabled={pending}
        onClick={onCancel}
      />
    </>
  );
}

function SessionDemo({ rich }: { rich: boolean }) {
  const [demo] = useState(createDemoHost);
  const state = useSyncExternalStore(
    demo.subscribe,
    demo.getSnapshot,
    demo.getSnapshot,
  );
  const [value, setValue] = useState<ComposerDocumentUpdate>({
    document: {
      schemaVersion: 1,
      content: [{ type: "text", text: "Review the latest changes." }],
    },
    revision: 0,
    origin: "replace",
    originId: "demo-initial",
  });
  const [mount, setMount] = useState(0);
  const [admission, setAdmission] = useState<Admission>("accept");
  const [intent, setIntent] = useState<"follow_up" | "steer">("follow_up");
  const [failPreparation, setFailPreparation] = useState(true);
  const editor = useRef<ChatSessionComposerHandle>(null);
  const occurrence = useRef(0);
  const Composer = rich ? RichChatComposer : ChatSessionComposer;
  function replace(document: ComposerDocument) {
    setValue((current) => ({
      document,
      revision: current.revision + 1,
      origin: "replace",
      originId: `demo-replace-${++occurrence.current}`,
    }));
  }
  const addMenu = (
    <>
      <DemoPopover label="Demo controls" icon="settings">
        <div className="chat-demo-controls">
          <DemoAction
            label="Start demo turn"
            icon="start"
            onClick={demo.start}
          />
        </div>
        <div className="chat-demo-fields">
          <label>
            Admission outcome{" "}
            <select
              className="select select-sm"
              value={admission}
              onChange={(event) => {
                const next = event.currentTarget.value as Admission;
                setAdmission(next);
                demo.setAdmission(next);
              }}
            >
              <option value="accept">Accept</option>
              <option value="reject">Reject</option>
              <option value="unknown">Lose response after admission</option>
            </select>
          </label>
          <label>
            Running intent{" "}
            <select
              className="select select-sm"
              value={intent}
              onChange={(event) =>
                setIntent(event.currentTarget.value as "follow_up" | "steer")
              }
            >
              <option value="follow_up">Follow-up</option>
              <option value="steer">Steer active turn</option>
            </select>
          </label>
          <label>
            <input
              type="checkbox"
              className="checkbox checkbox-sm"
              checked={failPreparation}
              onChange={(event) => {
                setFailPreparation(event.currentTarget.checked);
                demo.setFailPreparation(event.currentTarget.checked);
              }}
            />{" "}
            Fail first preparation
          </label>
        </div>
        <div className="chat-demo-controls">
          <DemoAction
            label="Remount editor"
            icon="remount"
            onClick={() => setMount((current) => current + 1)}
          />
          <DemoAction
            label="Replace with empty document"
            icon="clear"
            onClick={() =>
              replace({
                schemaVersion: 1,
                content: [{ type: "text", text: "" }],
              })
            }
          />
          {rich ? (
            <>
              <DemoAction
                label="Insert reference"
                icon="reference"
                onClick={() =>
                  editor.current?.insertReference({
                    type: "reference",
                    nodeId: `demo-ref-${++occurrence.current}`,
                    providerId: "demo-files",
                    refId: "README.md",
                    label: "README.md",
                    plainText: "@README.md",
                  })
                }
              />
              <DemoAction
                label="Insert quote"
                icon="quote"
                onClick={() =>
                  editor.current?.insertQuote({
                    type: "quote",
                    nodeId: `demo-quote-${++occurrence.current}`,
                    text: "Keep user edits while admission is pending.",
                    source: {
                      messageId: "demo-message",
                      conversationId: scope.conversationId,
                      label: "Earlier assistant reply",
                    },
                  })
                }
              />
              <DemoAction
                label="Claim /help command"
                icon="command"
                onClick={() =>
                  editor.current?.claimCommand(
                    { providerId: "demo-commands", commandId: "help" },
                    "/help",
                  )
                }
              />
              <DemoAction
                label="Claim /review prompt"
                icon="review"
                onClick={() =>
                  editor.current?.claimCommand(
                    { providerId: "demo-commands", commandId: "review" },
                    "/review",
                  )
                }
              />
            </>
          ) : null}
        </div>
      </DemoPopover>
      <DemoPopover label="Composer help" icon="help">
        <div className="popover-body">
          <p>
            Cmd/Ctrl+Enter sends; Enter adds a line. Type @ for references or /
            for commands and editable skills.
          </p>
          <p>
            Add up to three images, .txt, .md or .pdf files, each at most 2 MiB.
            If preparation fails, use Retry.
          </p>
          <p>
            Save a draft before remounting to try restoration; files then
            require reattachment. Stop is independent of sending and
            preparation.
          </p>
          <p>
            This interactive demo keeps files, drafts and recovery in memory. It
            has no backend; reloading the page discards its state.
          </p>
        </div>
      </DemoPopover>
      <DemoPopover label="Inspect demo state" icon="inspect">
        <details>
          <summary>Current portable document</summary>
          <pre aria-label="Current portable document">
            {JSON.stringify(value.document, null, 2)}
          </pre>
        </details>
        <p>
          Host: {state.runtime.status}; model: {state.model}; queue revision:{" "}
          {state.queue.revision}.
        </p>
        <div aria-label="Demo host events" role="log" aria-live="off">
          {state.events.length ? (
            state.events.map((event, index) => (
              <p key={`${index}-${event}`}>{event}</p>
            ))
          ) : (
            <p>No events yet.</p>
          )}
        </div>
      </DemoPopover>
    </>
  );
  return (
    <div
      className="chat-demo chat-session-demo"
      data-chat-session-demo={rich ? "rich" : "plain"}
    >
      <p className="sr-only" role="status">
        Host: {state.runtime.status}; model: {state.model}; queue revision:{" "}
        {state.queue.revision}.
      </p>
      <ChatAuthoritativeQueue
        projection={state.queue}
        capabilities={capabilities.queue}
        targetTurnId={state.runtime.activeTurnId}
        onMutation={demo.mutate}
        onProjection={demo.applyProjection}
        renderDocumentEditor={(props) => <QueueDocumentEditor {...props} />}
      />
      <Composer
        compact
        addMenu={addMenu}
        attachLabel="Add files and more"
        className="chat-composer-ghost"
        key={mount}
        ref={editor}
        value={value}
        onDocumentChange={setValue}
        scope={scope}
        draftKey="demo-draft"
        host={demo.host}
        runtime={state.runtime}
        policy={{ runningIntent: intent }}
        options={{
          model: state.model,
          effort: state.effort,
          approval: state.approval,
        }}
        draftAdapter={demo.draftAdapter}
        attachmentOptions={demo.attachmentOptions}
        providers={providers}
        onProviderInvoke={demo.invoke}
        onStop={demo.stop}
        context={
          <Chat.ComposerContext>
            <Chat.ComposerContextItem icon={<DemoIcon name="reference" />}>
              demo-repository
            </Chat.ComposerContextItem>
            <Chat.ComposerContextEnd>
              <Chat.ComposerConnection state="connected" />
            </Chat.ComposerContextEnd>
          </Chat.ComposerContext>
        }
        allowAttachmentOnly
        label={rich ? "Rich demo message" : "Semantic demo message"}
      >
        <ComposerSettings
          variant="menu"
          groups={menuGroups}
          scopeKey={scope.conversationId}
          revision={state.settingsRevision}
          settings={[
            {
              id: "approval",
              label: "Approval mode",
              value: state.approval,
              choices: approvals.map(([value, label, description]) => ({
                value,
                label,
                description,
                tone: value === "full" ? ("warning" as const) : undefined,
              })),
            },
            {
              id: "model",
              label: "Model",
              value: state.model,
              choices: models.map(([value, label]) => ({ value, label })),
            },
            {
              id: "effort",
              label: "Reasoning effort",
              value: state.effort,
              ordered: true,
              defaultValue: "medium",
              choices: efforts.map((value, index) => ({
                value,
                label: effortLabels[index],
              })),
            },
          ]}
          onRequest={demo.requestSetting}
          onAcknowledged={demo.acknowledgeSetting}
        />
      </Composer>
    </div>
  );
}

export function SemanticComposerPreview() {
  return <SessionDemo rich={false} />;
}
export function RichComposerPreview() {
  return <SessionDemo rich />;
}

/** Focused Core 1.21.1 composition; settings still require host acknowledgment. */
export function CompactComposerPreview() {
  const [demo] = useState(() => {
    const host = createDemoHost();
    host.setFailPreparation(false);
    return host;
  });
  const state = useSyncExternalStore(
    demo.subscribe,
    demo.getSnapshot,
    demo.getSnapshot,
  );
  const [rich, setRich] = useState(true);
  const [value, setValue] = useState<ComposerDocumentUpdate>({
    document: {
      schemaVersion: 1,
      content: [{ type: "text", text: "Review the latest changes." }],
    },
    revision: 0,
    origin: "replace",
    originId: "compact-initial",
  });
  const Composer = rich ? RichChatComposer : ChatSessionComposer;
  return (
    <div className="chat-demo chat-session-demo" data-chat-compact-demo>
      <Composer
        compact
        attachLabel="Add files and more"
        addMenu={
          <>
            <DemoPopover label="Composer help" icon="help">
              <div className="popover-body">
                <p>
                  Cmd/Ctrl+Enter sends; Enter adds a line. Add files with +;
                  images become thumbnails after preparation. Type / to choose
                  skills or commands, or @ for repository references.
                </p>
                <p>
                  Choose a model and reasoning effort from the model menu.
                  Switch editors from Add. Stop and follow-up submission are
                  independent.
                </p>
                <p>
                  This in-memory demo applies model choices only after the host
                  acknowledges them.
                </p>
              </div>
            </DemoPopover>
            <label className="chat-composer-menu-field">
              <span>
                <input
                  type="checkbox"
                  className="checkbox checkbox-sm"
                  checked={rich}
                  onChange={(event) => setRich(event.currentTarget.checked)}
                />{" "}
                Use rich editor
              </span>
            </label>
          </>
        }
        className="chat-composer-ghost"
        value={value}
        onDocumentChange={setValue}
        scope={scope}
        draftKey="compact-demo"
        host={demo.host}
        runtime={state.runtime}
        attachmentOptions={demo.attachmentOptions}
        providers={providers}
        onProviderInvoke={demo.invoke}
        options={{
          model: state.model,
          effort: state.effort,
          approval: state.approval,
        }}
        onStop={demo.stop}
        context={
          <Chat.ComposerContext>
            <Chat.ComposerContextItem icon={<DemoIcon name="reference" />}>
              demo-repository
            </Chat.ComposerContextItem>
            <Chat.ComposerContextEnd>
              <Chat.ComposerConnection state="connected" />
            </Chat.ComposerContextEnd>
          </Chat.ComposerContext>
        }
        allowAttachmentOnly
        label="Compact demo message"
      >
        <ComposerSettings
          variant="menu"
          groups={menuGroups}
          scopeKey={scope.conversationId}
          revision={state.settingsRevision}
          settings={[
            {
              id: "approval",
              label: "Approval mode",
              value: state.approval,
              choices: approvals.map(([value, label, description]) => ({
                value,
                label,
                description,
                tone: value === "full" ? ("warning" as const) : undefined,
              })),
            },
            {
              id: "model",
              label: "Model",
              value: state.model,
              choices: models.map(([value, label]) => ({ value, label })),
            },
            {
              id: "effort",
              label: "Reasoning effort",
              value: state.effort,
              ordered: true,
              defaultValue: "medium",
              choices: efforts.map((value, index) => ({
                value,
                label: effortLabels[index],
              })),
            },
          ]}
          onRequest={demo.requestSetting}
          onAcknowledged={demo.acknowledgeSetting}
        />
      </Composer>
      <p className="sr-only" role="status" aria-label="Compact host state">
        Host: {state.runtime.status}; model: {state.model}; waiting messages:{" "}
        {state.queue.items.length}.
        {state.events.at(-1) ? ` ${state.events.at(-1)}` : ""}
      </p>
    </div>
  );
}
Preview

Host: idle; model: standard; queue revision: 0.

demo-repositoryConnected

Loading rich editor. Your draft is preserved.

Review the latest changes.
Export preserved draft
Draft storage is provided by the host.
Add

Cmd/Ctrl+Enter sends; Enter adds a line. Type @ for references or / for commands and editable skills.

Add up to three images, .txt, .md or .pdf files, each at most 2 MiB. If preparation fails, use Retry.

Save a draft before remounting to try restoration; files then require reattachment. Stop is independent of sending and preparation.

This interactive demo keeps files, drafts and recovery in memory. It has no backend; reloading the page discards its state.

Current portable document
{
  "schemaVersion": 1,
  "content": [
    {
      "type": "text",
      "text": "Review the latest changes."
    }
  ]
}

Host: idle; model: standard; queue revision: 0.

No events yet.

Approval mode
Select model
Medium
LowMax

Rich Composer and Authoritative Queue

authored

Optional /chat/rich editor with atomic references, attributed quotes, claimed prompt/action commands and editable skills. Start a demo turn, send follow-ups or steer, then edit/remove/promote confirmed queue items. Model selection changes only after host acknowledgment; the restricted choice demonstrates rejection. Copy/paste and undo stay editor-owned. The fake host stores only page-lifetime memory.

Source
import React, { useId, useRef, useState, useSyncExternalStore } from "react";
import {
  ChatAuthoritativeQueue,
  Chat,
  ComposerSettings,
  ChatSessionComposer,
  Button,
  createComposerRecoveryOwner,
  exportComposerText,
  type ChatSessionComposerHandle,
  type ComposerAttachmentOptions,
  type ComposerCapabilities,
  type ComposerCompletionProvider,
  type ComposerDocument,
  type ComposerProviderCandidate,
  type ComposerDocumentUpdate,
  type ComposerDraft,
  type ComposerDraftAdapter,
  type ComposerQueueEditorProps,
  type ComposerQueueMutation,
  type ComposerQueueMutationResult,
  type ComposerQueueProjection,
  type ComposerReceipt,
  type ComposerRuntimeState,
  type ComposerSessionHost,
  type ComposerSettingRequest,
  type ComposerSettingResult,
  type ComposerSubmission,
} from "@duskmoon-dev/components";
import { RichChatComposer } from "@duskmoon-dev/components/chat/rich";

const scope = { contextKey: "demo-repository", conversationId: "demo-thread" };
const capabilities: ComposerCapabilities = {
  protocolVersion: 1,
  documentVersions: [1],
  intents: ["send", "follow_up", "steer"],
  commands: true,
  attachments: true,
  queue: { edit: "document", remove: true, promote: true },
  durableRecovery: false,
};
type Admission = "accept" | "reject" | "unknown";
interface DemoState {
  readonly runtime: ComposerRuntimeState;
  readonly queue: ComposerQueueProjection;
  readonly settingsRevision: number;
  readonly model: string;
  readonly effort: string;
  readonly approval: string;
  readonly events: readonly string[];
}

/** Abortable demo latency, not an upload or execution transport. */
function pause(signal: AbortSignal) {
  return new Promise<void>((resolve, reject) => {
    if (signal.aborted) {
      reject(new DOMException("Cancelled", "AbortError"));
      return;
    }
    const abort = () => {
      clearTimeout(timer);
      reject(new DOMException("Cancelled", "AbortError"));
    };
    const timer = setTimeout(() => {
      signal.removeEventListener("abort", abort);
      resolve();
    }, 400);
    signal.addEventListener("abort", abort, { once: true });
  });
}

const settingsValues: Record<string, readonly string[]> = {
  model: ["standard", "fast"],
  effort: ["low", "medium", "high", "max"],
  approval: ["ask", "auto", "full"],
};

/** Stable per-preview host: memory only, lost on page reload. */
function createDemoHost() {
  const recovery = createComposerRecoveryOwner();
  const receipts = new Map<string, ComposerReceipt>();
  const drafts = new Map<string, ComposerDraft>();
  const listeners = new Set<() => void>();
  let admission: Admission = "accept";
  let failPreparation = true;
  let turnCounter = 0;
  const preparations = new Set<string>();
  let state: DemoState = {
    runtime: { status: "idle" },
    queue: { protocolVersion: 1, scope, revision: 0, items: [] },
    settingsRevision: 0,
    model: "standard",
    effort: "medium",
    approval: "ask",
    events: [],
  };
  function publish(next: Partial<DemoState>, event?: string) {
    state = {
      ...state,
      ...next,
      events: event ? [...state.events.slice(-7), event] : state.events,
    };
    listeners.forEach((listener) => listener());
  }
  function accept(snapshot: ComposerSubmission): ComposerReceipt {
    const identity = {
      protocolVersion: 1 as const,
      clientSubmissionId: snapshot.clientSubmissionId,
      scope: snapshot.scope,
      outcome: "accepted" as const,
    };
    if (snapshot.operation === "command") {
      const result = { help: "Use /review for a prompt or @ for a reference." };
      publish({}, `Command result: ${JSON.stringify(result)}`);
      return { ...identity, operation: "command", result };
    }
    const text =
      exportComposerText(snapshot.document) || "Attachment-only prompt";
    if (snapshot.intent === "follow_up") {
      const id = `waiting-${snapshot.clientSubmissionId}`;
      const queue = {
        ...state.queue,
        revision: state.queue.revision + 1,
        items: [
          ...state.queue.items,
          {
            id,
            document: snapshot.document,
            attachments: snapshot.attachments,
            capabilities: capabilities.queue,
          },
        ],
      };
      publish({ queue }, `Follow-up admitted: ${text}`);
      return {
        ...identity,
        operation: "prompt",
        delivery: "follow_up",
        persistence: "volatile",
        queueItemId: id,
        queueRevision: queue.revision,
      };
    }
    const turnId =
      snapshot.intent === "steer"
        ? snapshot.targetTurnId
        : `demo-turn-${++turnCounter}`;
    publish(
      { runtime: { status: "running", activeTurnId: turnId } },
      `${snapshot.intent === "steer" ? "Steer" : "Prompt"} admitted: ${text}`,
    );
    return {
      ...identity,
      operation: "prompt",
      delivery: snapshot.intent === "steer" ? "steer" : "immediate",
      persistence: "volatile",
      turnId,
    };
  }
  const host: ComposerSessionHost = {
    capabilities,
    recovery,
    commandOperation: (command) =>
      command.commandId === "help" ? "command" : "prompt",
    async submit(snapshot, signal) {
      const mode = admission;
      await pause(signal);
      const existing = receipts.get(snapshot.clientSubmissionId);
      if (existing) return existing;
      if (mode === "reject") {
        const receipt: ComposerReceipt = {
          protocolVersion: 1,
          scope: snapshot.scope,
          clientSubmissionId: snapshot.clientSubmissionId,
          operation: snapshot.operation,
          outcome: "rejected",
          error: {
            code: "demo_rejection",
            message:
              "Demo host rejected this request. Edit or change the outcome and submit again.",
          },
        };
        receipts.set(snapshot.clientSubmissionId, receipt);
        publish({}, "Request rejected; draft retained.");
        return receipt;
      }
      const receipt = accept(snapshot);
      receipts.set(snapshot.clientSubmissionId, receipt);
      if (mode !== "unknown") return receipt;
      publish(
        {},
        "Demo response lost after admission. Check submission status to reconcile.",
      );
      return {
        protocolVersion: 1,
        scope: snapshot.scope,
        clientSubmissionId: snapshot.clientSubmissionId,
        operation: snapshot.operation,
        outcome: "unknown",
        error: {
          code: "demo_response_lost",
          message:
            "Admission response was lost; do not assume failure or resend as a new request.",
        },
      };
    },
    async reconcile(snapshot, signal) {
      await pause(signal);
      const receipt = receipts.get(snapshot.clientSubmissionId);
      publish(
        {},
        receipt
          ? `Reconciled: ${receipt.outcome}`
          : "No admission record found; outcome remains unresolved.",
      );
      return receipt ?? { outcome: "not_found" };
    },
    async authorizeRetry() {
      publish(
        {},
        "Demo host authorized retry using the original submission identity.",
      );
      return true;
    },
  };
  const draftAdapter: ComposerDraftAdapter = {
    async load({ scope: owner, draftKey, signal }) {
      await pause(signal);
      return drafts.get(JSON.stringify([owner, draftKey]));
    },
    async save(draft, signal) {
      await pause(signal);
      drafts.set(JSON.stringify([draft.scope, draft.draftKey]), draft);
      publish({}, `Draft revision ${draft.revision} saved in demo memory.`);
    },
  };
  const attachmentOptions: Omit<ComposerAttachmentOptions, "scope"> = {
    policy: {
      accept: "image/*,.txt,.md,.pdf",
      maxFiles: 3,
      maxFileBytes: 2 * 1024 * 1024,
    },
    async prepare(file, { entryId, signal, reportProgress }) {
      reportProgress(0.25);
      await pause(signal);
      if (failPreparation && !preparations.has(entryId)) {
        preparations.add(entryId);
        throw new Error("Demo preparation failed once. Retry this attachment.");
      }
      reportProgress(1);
      return {
        providerId: "demo-files",
        reference: { entryId, name: file.name },
      };
    },
    // Omitted canRecover: saved occurrences require reattachment after remount.
  };
  return {
    host,
    draftAdapter,
    attachmentOptions,
    getSnapshot: () => state,
    subscribe(listener: () => void) {
      listeners.add(listener);
      return () => {
        listeners.delete(listener);
      };
    },
    setAdmission(value: Admission) {
      admission = value;
    },
    setFailPreparation(value: boolean) {
      failPreparation = value;
    },
    start() {
      publish(
        {
          runtime: {
            status: "running",
            activeTurnId: `demo-turn-${++turnCounter}`,
          },
        },
        "Demo turn started; no model is executing.",
      );
    },
    stop() {
      publish(
        { runtime: { status: "idle" } },
        "Stop acknowledged by demo host; queued messages remain waiting.",
      );
    },
    invoke() {
      publish(
        {},
        "Provider invocation executed independently of prompt admission.",
      );
    },
    async mutate(
      request: ComposerQueueMutation,
      signal: AbortSignal,
    ): Promise<ComposerQueueMutationResult> {
      await pause(signal);
      const item = state.queue.items.find(
        (entry) => entry.id === request.itemId,
      );
      if (
        request.expectedRevision !== state.queue.revision ||
        !item ||
        (request.operation === "promote" &&
          request.targetTurnId !== state.runtime.activeTurnId)
      ) {
        return {
          requestId: request.requestId,
          outcome: "rejected",
          projection: state.queue,
          error: {
            code: "queue_conflict",
            message:
              "Demo queue changed; use the canonical projection and try again.",
          },
        };
      }
      const queue: ComposerQueueProjection = {
        ...state.queue,
        revision: state.queue.revision + 1,
        items:
          request.operation === "edit"
            ? state.queue.items.map((entry) =>
                entry.id === item.id
                  ? { ...entry, document: request.document }
                  : entry,
              )
            : state.queue.items.filter((entry) => entry.id !== item.id),
      };
      publish(
        { queue },
        `Queue ${request.operation} acknowledged for ${request.itemId}.`,
      );
      return {
        requestId: request.requestId,
        outcome: "accepted",
        projection: queue,
      };
    },
    applyProjection(queue: ComposerQueueProjection) {
      if (queue.revision >= state.queue.revision) publish({ queue });
    },
    async requestSetting(
      request: ComposerSettingRequest,
      signal: AbortSignal,
    ): Promise<ComposerSettingResult> {
      await pause(signal);
      const identity = {
        requestId: request.requestId,
        scopeKey: request.scopeKey,
        settingId: request.settingId,
        revision: state.settingsRevision + 1,
      };
      if (
        request.expectedRevision !== state.settingsRevision ||
        request.value === "restricted" ||
        !(settingsValues[request.settingId] ?? []).includes(request.value)
      ) {
        return {
          ...identity,
          outcome: "rejected",
          message:
            "Demo host declined this model; the current selection is retained.",
        };
      }
      return { ...identity, outcome: "accepted", value: request.value };
    },
    acknowledgeSetting(result: ComposerSettingResult) {
      publish(
        {
          settingsRevision: result.revision,
          ...(result.outcome === "accepted"
            ? { [result.settingId]: result.value }
            : {}),
        },
        `${result.settingId} change ${result.outcome}.`,
      );
    },
  };
}

const providers: readonly ComposerCompletionProvider[] = [
  {
    providerId: "demo-files",
    label: "Repository references",
    icon: <DemoIcon name="reference" />,
    sourceLabel: "Demo",
    trigger: { text: "@", position: "word" },
    async query(request, signal) {
      await pause(signal);
      return {
        request,
        candidates: (
          [
            {
              id: "readme",
              label: "README.md",
              description: "Demo reference, resolved by the host",
              action: {
                type: "insert",
                content: [
                  {
                    type: "reference",
                    nodeId: `${request.requestId}-reference`,
                    providerId: "demo-files",
                    refId: "README.md",
                    label: "README.md",
                    plainText: "@README.md",
                  },
                ],
              },
            },
            {
              id: "private",
              label: "Private document",
              disabledReason: "Host has not granted access",
              action: { type: "insert", content: [] },
            },
          ] satisfies ComposerProviderCandidate[]
        ).filter((candidate) =>
          candidate.label.toLowerCase().includes(request.query.toLowerCase()),
        ),
      };
    },
  },
  {
    providerId: "demo-commands",
    label: "Commands",
    icon: <DemoIcon name="command" />,
    sourceLabel: "Demo",
    trigger: { text: "/", position: "leading" },
    async query(request, signal) {
      await pause(signal);
      return {
        request,
        candidates: (
          [
            {
              id: "help",
              label: "/help",
              description: "Show available commands",
              action: {
                type: "insert",
                command: { providerId: "demo-commands", commandId: "help" },
                content: [{ type: "text", text: "/help " }],
              },
            },
            {
              id: "review",
              label: "/review",
              description: "Review the current changes",
              action: {
                type: "insert",
                command: { providerId: "demo-commands", commandId: "review" },
                content: [{ type: "text", text: "/review " }],
              },
            },
            {
              id: "inspect",
              label: "/inspect",
              description: "Inspect the current session",
              action: {
                type: "invoke",
                command: { providerId: "demo-commands", commandId: "inspect" },
              },
            },
          ] satisfies ComposerProviderCandidate[]
        ).filter((candidate) => candidate.label.includes(request.query)),
      };
    },
  },
  {
    providerId: "demo-skills",
    label: "Skills",
    icon: <DemoIcon name="skill" />,
    sourceLabel: "Demo",
    trigger: { text: "/", position: "leading" },
    async query(request, signal) {
      await pause(signal);
      return {
        request,
        candidates: (
          [
            {
              id: "summarize",
              label: "/summarize",
              description: "Summarize changes and completed checks",
              action: {
                type: "insert",
                content: [
                  {
                    type: "text",
                    text: "Summarize the changes and list the checks that passed. ",
                  },
                ],
              },
            },
          ] satisfies ComposerProviderCandidate[]
        ).filter((candidate) => candidate.label.includes(request.query)),
      };
    },
  },
];

const demoIcons = {
  start: "m8 5 11 7-11 7Z",
  remount: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7",
  clear: "M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7",
  reference: "M14 2H6v20h12V6ZM14 2v5h5M8 12h8M8 16h5",
  quote: "M3 6h7v7H3ZM14 6h7v7h-7ZM10 13c0 4-2 6-5 6M21 13c0 4-2 6-5 6",
  command: "m4 6 6 6-6 6M13 18h7",
  skill: "m12 3 8 4v10l-8 4-8-4V7ZM4 7l8 4 8-4M12 11v10",
  review: "m15 4 5 5-11 11H4v-5ZM13 6l5 5",
  settings: "M4 7h16M4 17h16M8 4v6M16 14v6",
  help: "M12 8h.01M12 12v5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z",
  inspect: "M4 4h16v16H4ZM7 8l3 3-3 3M12 15h5",
  save: "M5 3h12l4 4v14H3V3ZM7 3v6h10V3M7 21v-8h10v8",
  cancel: "m6 6 12 12M6 18 18 6",
};
type DemoIconName = keyof typeof demoIcons;

function DemoIcon({ name }: { name: DemoIconName }) {
  return (
    <svg
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d={demoIcons[name]} />
    </svg>
  );
}

function DemoAction({
  label,
  icon,
  ...props
}: {
  label: string;
  icon: DemoIconName;
} & React.ComponentProps<typeof Button>) {
  return (
    <Button
      type="button"
      appearance="ghost"
      color="base"
      size="sm"
      shape="circle"
      {...props}
      aria-label={label}
      title={label}
    >
      <DemoIcon name={icon} />
    </Button>
  );
}

/** Core owns menu sizing/placement; the native Popover owns dismissal and focus. */
function DemoPopover({
  label,
  icon,
  children,
}: {
  label: string;
  icon: DemoIconName;
  children: React.ReactNode;
}) {
  const id = useId();
  const anchorName = `--demo-${id.replace(/[^a-zA-Z0-9_-]/g, "")}`;
  const [open, setOpen] = useState(false);
  return (
    <>
      <button
        type="button"
        className="popover-menu-item"
        aria-label={label}
        title={label}
        popoverTarget={id}
        aria-controls={id}
        aria-expanded={open}
        style={{ anchorName } as React.CSSProperties}
      >
        <DemoIcon name={icon} />
        <span>{label}</span>
      </button>
      <div
        id={id}
        popover="auto"
        className="popover popover-menu chat-composer-menu chat-demo-popover"
        role="group"
        aria-label={label}
        style={{ positionAnchor: anchorName } as React.CSSProperties}
        onToggle={(event) =>
          setOpen(event.currentTarget.matches(":popover-open"))
        }
      >
        {children}
      </div>
    </>
  );
}

const models = [
  ["standard", "Standard demo model", "Standard"],
  ["fast", "Fast demo model", "Fast"],
  ["restricted", "Restricted model (host rejects)", "Restricted"],
] as const;
const efforts = ["low", "medium", "high", "max"];
const effortLabels = ["Low", "Medium", "High", "Max"];
const approvals = [
  ["ask", "Ask for approval", "Review each action before it runs."],
  ["auto", "Approve for me", "Request review for sensitive actions."],
  ["full", "Full access", "Allow actions without an approval prompt."],
] as const;

const menuGroups = [
  {
    id: "approval",
    label: "Approval mode",
    settingIds: ["approval"],
    appearance: "access" as const,
  },
  {
    id: "model",
    label: "Model settings",
    settingIds: ["model", "effort"],
    nestedSettingIds: ["model"],
    appearance: "model" as const,
  },
];

function QueueDocumentEditor({
  value,
  onChange,
  onSave,
  onCancel,
  pending,
}: ComposerQueueEditorProps) {
  return (
    <>
      {value.content.map((node, index) =>
        node.type === "text" ? (
          <textarea
            key={index}
            className="chat-composer-input"
            aria-label={`Queued text ${index + 1}`}
            value={node.text}
            disabled={pending}
            onChange={(event) =>
              onChange({
                ...value,
                content: value.content.map((entry, at) =>
                  at === index
                    ? { type: "text", text: event.currentTarget.value }
                    : entry,
                ),
              })
            }
          />
        ) : (
          <p key={node.nodeId}>
            {node.type === "reference" ? node.label : node.text}
          </p>
        ),
      )}
      <DemoAction
        label="Save queued document"
        icon="save"
        disabled={pending}
        onClick={onSave}
      />
      <DemoAction
        label="Cancel"
        icon="cancel"
        disabled={pending}
        onClick={onCancel}
      />
    </>
  );
}

function SessionDemo({ rich }: { rich: boolean }) {
  const [demo] = useState(createDemoHost);
  const state = useSyncExternalStore(
    demo.subscribe,
    demo.getSnapshot,
    demo.getSnapshot,
  );
  const [value, setValue] = useState<ComposerDocumentUpdate>({
    document: {
      schemaVersion: 1,
      content: [{ type: "text", text: "Review the latest changes." }],
    },
    revision: 0,
    origin: "replace",
    originId: "demo-initial",
  });
  const [mount, setMount] = useState(0);
  const [admission, setAdmission] = useState<Admission>("accept");
  const [intent, setIntent] = useState<"follow_up" | "steer">("follow_up");
  const [failPreparation, setFailPreparation] = useState(true);
  const editor = useRef<ChatSessionComposerHandle>(null);
  const occurrence = useRef(0);
  const Composer = rich ? RichChatComposer : ChatSessionComposer;
  function replace(document: ComposerDocument) {
    setValue((current) => ({
      document,
      revision: current.revision + 1,
      origin: "replace",
      originId: `demo-replace-${++occurrence.current}`,
    }));
  }
  const addMenu = (
    <>
      <DemoPopover label="Demo controls" icon="settings">
        <div className="chat-demo-controls">
          <DemoAction
            label="Start demo turn"
            icon="start"
            onClick={demo.start}
          />
        </div>
        <div className="chat-demo-fields">
          <label>
            Admission outcome{" "}
            <select
              className="select select-sm"
              value={admission}
              onChange={(event) => {
                const next = event.currentTarget.value as Admission;
                setAdmission(next);
                demo.setAdmission(next);
              }}
            >
              <option value="accept">Accept</option>
              <option value="reject">Reject</option>
              <option value="unknown">Lose response after admission</option>
            </select>
          </label>
          <label>
            Running intent{" "}
            <select
              className="select select-sm"
              value={intent}
              onChange={(event) =>
                setIntent(event.currentTarget.value as "follow_up" | "steer")
              }
            >
              <option value="follow_up">Follow-up</option>
              <option value="steer">Steer active turn</option>
            </select>
          </label>
          <label>
            <input
              type="checkbox"
              className="checkbox checkbox-sm"
              checked={failPreparation}
              onChange={(event) => {
                setFailPreparation(event.currentTarget.checked);
                demo.setFailPreparation(event.currentTarget.checked);
              }}
            />{" "}
            Fail first preparation
          </label>
        </div>
        <div className="chat-demo-controls">
          <DemoAction
            label="Remount editor"
            icon="remount"
            onClick={() => setMount((current) => current + 1)}
          />
          <DemoAction
            label="Replace with empty document"
            icon="clear"
            onClick={() =>
              replace({
                schemaVersion: 1,
                content: [{ type: "text", text: "" }],
              })
            }
          />
          {rich ? (
            <>
              <DemoAction
                label="Insert reference"
                icon="reference"
                onClick={() =>
                  editor.current?.insertReference({
                    type: "reference",
                    nodeId: `demo-ref-${++occurrence.current}`,
                    providerId: "demo-files",
                    refId: "README.md",
                    label: "README.md",
                    plainText: "@README.md",
                  })
                }
              />
              <DemoAction
                label="Insert quote"
                icon="quote"
                onClick={() =>
                  editor.current?.insertQuote({
                    type: "quote",
                    nodeId: `demo-quote-${++occurrence.current}`,
                    text: "Keep user edits while admission is pending.",
                    source: {
                      messageId: "demo-message",
                      conversationId: scope.conversationId,
                      label: "Earlier assistant reply",
                    },
                  })
                }
              />
              <DemoAction
                label="Claim /help command"
                icon="command"
                onClick={() =>
                  editor.current?.claimCommand(
                    { providerId: "demo-commands", commandId: "help" },
                    "/help",
                  )
                }
              />
              <DemoAction
                label="Claim /review prompt"
                icon="review"
                onClick={() =>
                  editor.current?.claimCommand(
                    { providerId: "demo-commands", commandId: "review" },
                    "/review",
                  )
                }
              />
            </>
          ) : null}
        </div>
      </DemoPopover>
      <DemoPopover label="Composer help" icon="help">
        <div className="popover-body">
          <p>
            Cmd/Ctrl+Enter sends; Enter adds a line. Type @ for references or /
            for commands and editable skills.
          </p>
          <p>
            Add up to three images, .txt, .md or .pdf files, each at most 2 MiB.
            If preparation fails, use Retry.
          </p>
          <p>
            Save a draft before remounting to try restoration; files then
            require reattachment. Stop is independent of sending and
            preparation.
          </p>
          <p>
            This interactive demo keeps files, drafts and recovery in memory. It
            has no backend; reloading the page discards its state.
          </p>
        </div>
      </DemoPopover>
      <DemoPopover label="Inspect demo state" icon="inspect">
        <details>
          <summary>Current portable document</summary>
          <pre aria-label="Current portable document">
            {JSON.stringify(value.document, null, 2)}
          </pre>
        </details>
        <p>
          Host: {state.runtime.status}; model: {state.model}; queue revision:{" "}
          {state.queue.revision}.
        </p>
        <div aria-label="Demo host events" role="log" aria-live="off">
          {state.events.length ? (
            state.events.map((event, index) => (
              <p key={`${index}-${event}`}>{event}</p>
            ))
          ) : (
            <p>No events yet.</p>
          )}
        </div>
      </DemoPopover>
    </>
  );
  return (
    <div
      className="chat-demo chat-session-demo"
      data-chat-session-demo={rich ? "rich" : "plain"}
    >
      <p className="sr-only" role="status">
        Host: {state.runtime.status}; model: {state.model}; queue revision:{" "}
        {state.queue.revision}.
      </p>
      <ChatAuthoritativeQueue
        projection={state.queue}
        capabilities={capabilities.queue}
        targetTurnId={state.runtime.activeTurnId}
        onMutation={demo.mutate}
        onProjection={demo.applyProjection}
        renderDocumentEditor={(props) => <QueueDocumentEditor {...props} />}
      />
      <Composer
        compact
        addMenu={addMenu}
        attachLabel="Add files and more"
        className="chat-composer-ghost"
        key={mount}
        ref={editor}
        value={value}
        onDocumentChange={setValue}
        scope={scope}
        draftKey="demo-draft"
        host={demo.host}
        runtime={state.runtime}
        policy={{ runningIntent: intent }}
        options={{
          model: state.model,
          effort: state.effort,
          approval: state.approval,
        }}
        draftAdapter={demo.draftAdapter}
        attachmentOptions={demo.attachmentOptions}
        providers={providers}
        onProviderInvoke={demo.invoke}
        onStop={demo.stop}
        context={
          <Chat.ComposerContext>
            <Chat.ComposerContextItem icon={<DemoIcon name="reference" />}>
              demo-repository
            </Chat.ComposerContextItem>
            <Chat.ComposerContextEnd>
              <Chat.ComposerConnection state="connected" />
            </Chat.ComposerContextEnd>
          </Chat.ComposerContext>
        }
        allowAttachmentOnly
        label={rich ? "Rich demo message" : "Semantic demo message"}
      >
        <ComposerSettings
          variant="menu"
          groups={menuGroups}
          scopeKey={scope.conversationId}
          revision={state.settingsRevision}
          settings={[
            {
              id: "approval",
              label: "Approval mode",
              value: state.approval,
              choices: approvals.map(([value, label, description]) => ({
                value,
                label,
                description,
                tone: value === "full" ? ("warning" as const) : undefined,
              })),
            },
            {
              id: "model",
              label: "Model",
              value: state.model,
              choices: models.map(([value, label]) => ({ value, label })),
            },
            {
              id: "effort",
              label: "Reasoning effort",
              value: state.effort,
              ordered: true,
              defaultValue: "medium",
              choices: efforts.map((value, index) => ({
                value,
                label: effortLabels[index],
              })),
            },
          ]}
          onRequest={demo.requestSetting}
          onAcknowledged={demo.acknowledgeSetting}
        />
      </Composer>
    </div>
  );
}

export function SemanticComposerPreview() {
  return <SessionDemo rich={false} />;
}
export function RichComposerPreview() {
  return <SessionDemo rich />;
}

/** Focused Core 1.21.1 composition; settings still require host acknowledgment. */
export function CompactComposerPreview() {
  const [demo] = useState(() => {
    const host = createDemoHost();
    host.setFailPreparation(false);
    return host;
  });
  const state = useSyncExternalStore(
    demo.subscribe,
    demo.getSnapshot,
    demo.getSnapshot,
  );
  const [rich, setRich] = useState(true);
  const [value, setValue] = useState<ComposerDocumentUpdate>({
    document: {
      schemaVersion: 1,
      content: [{ type: "text", text: "Review the latest changes." }],
    },
    revision: 0,
    origin: "replace",
    originId: "compact-initial",
  });
  const Composer = rich ? RichChatComposer : ChatSessionComposer;
  return (
    <div className="chat-demo chat-session-demo" data-chat-compact-demo>
      <Composer
        compact
        attachLabel="Add files and more"
        addMenu={
          <>
            <DemoPopover label="Composer help" icon="help">
              <div className="popover-body">
                <p>
                  Cmd/Ctrl+Enter sends; Enter adds a line. Add files with +;
                  images become thumbnails after preparation. Type / to choose
                  skills or commands, or @ for repository references.
                </p>
                <p>
                  Choose a model and reasoning effort from the model menu.
                  Switch editors from Add. Stop and follow-up submission are
                  independent.
                </p>
                <p>
                  This in-memory demo applies model choices only after the host
                  acknowledges them.
                </p>
              </div>
            </DemoPopover>
            <label className="chat-composer-menu-field">
              <span>
                <input
                  type="checkbox"
                  className="checkbox checkbox-sm"
                  checked={rich}
                  onChange={(event) => setRich(event.currentTarget.checked)}
                />{" "}
                Use rich editor
              </span>
            </label>
          </>
        }
        className="chat-composer-ghost"
        value={value}
        onDocumentChange={setValue}
        scope={scope}
        draftKey="compact-demo"
        host={demo.host}
        runtime={state.runtime}
        attachmentOptions={demo.attachmentOptions}
        providers={providers}
        onProviderInvoke={demo.invoke}
        options={{
          model: state.model,
          effort: state.effort,
          approval: state.approval,
        }}
        onStop={demo.stop}
        context={
          <Chat.ComposerContext>
            <Chat.ComposerContextItem icon={<DemoIcon name="reference" />}>
              demo-repository
            </Chat.ComposerContextItem>
            <Chat.ComposerContextEnd>
              <Chat.ComposerConnection state="connected" />
            </Chat.ComposerContextEnd>
          </Chat.ComposerContext>
        }
        allowAttachmentOnly
        label="Compact demo message"
      >
        <ComposerSettings
          variant="menu"
          groups={menuGroups}
          scopeKey={scope.conversationId}
          revision={state.settingsRevision}
          settings={[
            {
              id: "approval",
              label: "Approval mode",
              value: state.approval,
              choices: approvals.map(([value, label, description]) => ({
                value,
                label,
                description,
                tone: value === "full" ? ("warning" as const) : undefined,
              })),
            },
            {
              id: "model",
              label: "Model",
              value: state.model,
              choices: models.map(([value, label]) => ({ value, label })),
            },
            {
              id: "effort",
              label: "Reasoning effort",
              value: state.effort,
              ordered: true,
              defaultValue: "medium",
              choices: efforts.map((value, index) => ({
                value,
                label: effortLabels[index],
              })),
            },
          ]}
          onRequest={demo.requestSetting}
          onAcknowledged={demo.acknowledgeSetting}
        />
      </Composer>
      <p className="sr-only" role="status" aria-label="Compact host state">
        Host: {state.runtime.status}; model: {state.model}; waiting messages:{" "}
        {state.queue.items.length}.
        {state.events.at(-1) ? ` ${state.events.at(-1)}` : ""}
      </p>
    </div>
  );
}
Preview
Worked · 2 tool calls · 0 failed
Reasoning
Compare the source contract before checking behavior.
Review source Done
Markup reviewed.

The answer stays visible when activity is closed.

Progress without an avatar

Agent Answers and Activity

authored

Native work disclosures leave the final agent answer visible. Tool counts are illustrative; this preview performs no external work.

Source
import React, { useId, useRef, useState } from "react";
import { Chat } from "@duskmoon-dev/components/chat";

export function AgentActivityPreview() {
  return (
    <div data-chat-agent-demo style={{ width: "min(42rem, 100%)" }}>
      <Chat.Agent>
        <Chat.Work>
          <Chat.WorkSummary>Worked · 2 tool calls · 0 failed</Chat.WorkSummary>
          <Chat.WorkBody>
            <Chat.Reasoning>
              <summary>Reasoning</summary>
              <div className="chat-reasoning-body">
                Compare the source contract before checking behavior.
              </div>
            </Chat.Reasoning>
            <Chat.Tool status="success">
              <Chat.ToolHeader>
                Review source <Chat.ToolStatus>Done</Chat.ToolStatus>
              </Chat.ToolHeader>
              <Chat.ToolResult>Markup reviewed.</Chat.ToolResult>
            </Chat.Tool>
          </Chat.WorkBody>
        </Chat.Work>
        <Chat.Content className="markdown-body">
          <p>The answer stays visible when activity is closed.</p>
        </Chat.Content>
      </Chat.Agent>
      <Chat.Agent>
        <Chat.Content streaming>Progress without an avatar</Chat.Content>
      </Chat.Agent>
    </div>
  );
}

const initialMessage =
  "Review the chat view.\nKeep the waiting queue.\nSupport immediate steer.\nPreserve message order.\nKeep multiline text.\nCheck keyboard focus.\nCheck narrow screens.\nShare the results.";

export function CollapsibleMessagePreview() {
  const [message, setMessage] = useState(initialMessage);
  const id = useId();
  return (
    <div
      data-chat-collapse-demo
      style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
    >
      <label htmlFor={id}>Sent message text (edit to remeasure)</label>
      <textarea
        id={id}
        className="textarea"
        value={message}
        rows={3}
        onChange={(event) => setMessage(event.currentTarget.value)}
      />
      <Chat placement="end">
        <Chat.Bubble color="primary" collapsible>
          {message}
        </Chat.Bubble>
      </Chat>
    </div>
  );
}

function QueueIcon({
  action,
}: {
  action: "send" | "steer" | "complete" | "reject" | "reset";
}) {
  const paths = {
    send: "m5 12 7-7 7 7M12 5v14",
    steer: "m15 4 5 5-5 5M20 9h-9a6 6 0 0 0-6 6v4",
    complete: "m5 12 4 4L19 6",
    reject: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM6 6l12 12",
    reset: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7",
  };
  return (
    <svg
      width="18"
      height="18"
      style={{ flexShrink: 0 }}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d={paths[action]} />
    </svg>
  );
}

/** Local simulation only. Applications await their transport before changing the queue. */
export function WaitingQueuePreview() {
  const inputId = useId();
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const serial = useRef(2);
  const [draft, setDraft] = useState("");
  const [active, setActive] = useState(true);
  const [turns, setTurns] = useState(1);
  const [rejectNext, setRejectNext] = useState(false);
  const [queue, setQueue] = useState([
    { id: "queued-1", text: "Also include the accessibility checks." },
    { id: "queued-2", text: "Check narrow screens too." },
  ]);
  const [sent, setSent] = useState<{ id: string; text: string }[]>([]);
  const [status, setStatus] = useState(
    "Reply in progress. 2 messages waiting.",
  );

  function accepted() {
    if (!rejectNext) return true;
    setRejectNext(false);
    setStatus(
      "Admission rejected. The draft and waiting messages are preserved; retry the action.",
    );
    return false;
  }

  function admit(steer = false) {
    if (!draft.trim() || (steer && !active) || !accepted()) return;
    const item = { id: `message-${++serial.current}`, text: draft };
    if (active && !steer) {
      setQueue((current) => [...current, item]);
      setStatus(`Message queued. ${queue.length + 1} messages waiting.`);
    } else {
      setSent((current) => [...current, item]);
      if (!steer) {
        setActive(true);
        setTurns((current) => current + 1);
      }
      setStatus(
        steer
          ? `Draft steered into the current reply. ${queue.length} messages waiting.`
          : "Message sent. Reply started.",
      );
    }
    setDraft("");
  }

  function consume(id: string, steer: boolean) {
    const item = queue.find((entry) => entry.id === id);
    if (!item || (steer && !accepted())) return;
    setQueue((current) => current.filter((entry) => entry.id !== id));
    if (steer) setSent((current) => [...current, item]);
    setStatus(
      `${steer ? "Message steered into the current reply" : "Waiting message removed"}. ${queue.length - 1} messages waiting.`,
    );
    inputRef.current?.focus();
  }

  function complete() {
    const next = queue[0];
    if (next && !accepted()) return;
    if (next) {
      setQueue((current) => current.slice(1));
      setSent((current) => [...current, next]);
      setTurns((current) => current + 1);
      setStatus(
        `Reply completed; oldest waiting message dispatched. ${queue.length - 1} messages waiting.`,
      );
    } else {
      setActive(false);
      setStatus("Reply completed. No messages waiting.");
    }
  }

  return (
    <div
      data-chat-queue-demo
      data-reply-count={turns}
      style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
    >
      {sent.map((item) => (
        <Chat key={item.id} placement="end">
          <Chat.Bubble color="primary" collapsible>
            {item.text}
          </Chat.Bubble>
        </Chat>
      ))}
      <Chat.Agent>
        <Chat.Content streaming={active}>
          {active ? "Simulated reply in progress" : "Simulated reply complete"}
        </Chat.Content>
      </Chat.Agent>
      <Chat.InputArea>
        <Chat.Queue
          items={queue}
          steerDisabled={!active}
          onSteer={(id) => consume(id, true)}
          onRemove={(id) => consume(id, false)}
        />
        <Chat.ComposerForm
          ghost
          onSubmit={(event) => {
            event.preventDefault();
            admit();
          }}
        >
          <label className="sr-only" htmlFor={inputId}>
            Queue demo message
          </label>
          <Chat.ComposerInput
            ref={inputRef}
            id={inputId}
            name="message"
            value={draft}
            rows={3}
            placeholder="Message the agent…"
            onChange={(event) => setDraft(event.currentTarget.value)}
            onKeyDown={(event) => {
              if (
                event.nativeEvent.isComposing ||
                event.keyCode === 229 ||
                event.key !== "Enter" ||
                event.shiftKey ||
                event.altKey
              )
                return;
              event.preventDefault();
              if (event.ctrlKey || event.metaKey) admit(true);
              else event.currentTarget.form?.requestSubmit();
            }}
          />
          <Chat.ComposerActions>
            <button
              className="btn btn-primary btn-sm btn-circle btn-icon btn-icon-sm"
              type="submit"
              disabled={!draft.trim()}
              aria-label={active ? "Queue message" : "Send message"}
              title={active ? "Queue message (Enter)" : "Send message (Enter)"}
              aria-keyshortcuts="Enter"
            >
              <QueueIcon action="send" />
            </button>
            <button
              className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
              type="button"
              disabled={!active || !draft.trim()}
              aria-label="Steer current message"
              title="Steer current message (Ctrl/⌘+Enter)"
              aria-keyshortcuts="Control+Enter Meta+Enter"
              onClick={() => admit(true)}
            >
              <QueueIcon action="steer" />
            </button>
          </Chat.ComposerActions>
        </Chat.ComposerForm>
      </Chat.InputArea>
      <p role="status" aria-atomic="true">
        {status}
      </p>
      <div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
        <button
          className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
          type="button"
          disabled={!active}
          aria-label="Complete response"
          title="Complete response"
          onClick={complete}
        >
          <QueueIcon action="complete" />
        </button>
        <button
          className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
          type="button"
          aria-label="Reject next admission"
          title="Reject next admission"
          aria-pressed={rejectNext}
          onClick={() => setRejectNext(!rejectNext)}
        >
          <QueueIcon action="reject" />
        </button>
        <button
          className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
          type="button"
          aria-label="Start fresh"
          title="Start fresh"
          onClick={() => {
            setActive(false);
            setQueue([]);
            setSent([]);
            setDraft("");
            setTurns(0);
            setRejectNext(false);
            setStatus("Idle. No messages waiting.");
            inputRef.current?.focus();
          }}
        >
          <QueueIcon action="reset" />
        </button>
      </div>
    </div>
  );
}
Preview
Review the chat view. Keep the waiting queue. Support immediate steer. Preserve message order. Keep multiline text. Check keyboard focus. Check narrow screens. Share the results.

Collapsible Sent Messages

authored

Messages above six rendered lines expand with an accessible native button. Edit the text or resize to remeasure; short messages need no toggle.

Source
import React, { useId, useRef, useState } from "react";
import { Chat } from "@duskmoon-dev/components/chat";

export function AgentActivityPreview() {
  return (
    <div data-chat-agent-demo style={{ width: "min(42rem, 100%)" }}>
      <Chat.Agent>
        <Chat.Work>
          <Chat.WorkSummary>Worked · 2 tool calls · 0 failed</Chat.WorkSummary>
          <Chat.WorkBody>
            <Chat.Reasoning>
              <summary>Reasoning</summary>
              <div className="chat-reasoning-body">
                Compare the source contract before checking behavior.
              </div>
            </Chat.Reasoning>
            <Chat.Tool status="success">
              <Chat.ToolHeader>
                Review source <Chat.ToolStatus>Done</Chat.ToolStatus>
              </Chat.ToolHeader>
              <Chat.ToolResult>Markup reviewed.</Chat.ToolResult>
            </Chat.Tool>
          </Chat.WorkBody>
        </Chat.Work>
        <Chat.Content className="markdown-body">
          <p>The answer stays visible when activity is closed.</p>
        </Chat.Content>
      </Chat.Agent>
      <Chat.Agent>
        <Chat.Content streaming>Progress without an avatar</Chat.Content>
      </Chat.Agent>
    </div>
  );
}

const initialMessage =
  "Review the chat view.\nKeep the waiting queue.\nSupport immediate steer.\nPreserve message order.\nKeep multiline text.\nCheck keyboard focus.\nCheck narrow screens.\nShare the results.";

export function CollapsibleMessagePreview() {
  const [message, setMessage] = useState(initialMessage);
  const id = useId();
  return (
    <div
      data-chat-collapse-demo
      style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
    >
      <label htmlFor={id}>Sent message text (edit to remeasure)</label>
      <textarea
        id={id}
        className="textarea"
        value={message}
        rows={3}
        onChange={(event) => setMessage(event.currentTarget.value)}
      />
      <Chat placement="end">
        <Chat.Bubble color="primary" collapsible>
          {message}
        </Chat.Bubble>
      </Chat>
    </div>
  );
}

function QueueIcon({
  action,
}: {
  action: "send" | "steer" | "complete" | "reject" | "reset";
}) {
  const paths = {
    send: "m5 12 7-7 7 7M12 5v14",
    steer: "m15 4 5 5-5 5M20 9h-9a6 6 0 0 0-6 6v4",
    complete: "m5 12 4 4L19 6",
    reject: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM6 6l12 12",
    reset: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7",
  };
  return (
    <svg
      width="18"
      height="18"
      style={{ flexShrink: 0 }}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d={paths[action]} />
    </svg>
  );
}

/** Local simulation only. Applications await their transport before changing the queue. */
export function WaitingQueuePreview() {
  const inputId = useId();
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const serial = useRef(2);
  const [draft, setDraft] = useState("");
  const [active, setActive] = useState(true);
  const [turns, setTurns] = useState(1);
  const [rejectNext, setRejectNext] = useState(false);
  const [queue, setQueue] = useState([
    { id: "queued-1", text: "Also include the accessibility checks." },
    { id: "queued-2", text: "Check narrow screens too." },
  ]);
  const [sent, setSent] = useState<{ id: string; text: string }[]>([]);
  const [status, setStatus] = useState(
    "Reply in progress. 2 messages waiting.",
  );

  function accepted() {
    if (!rejectNext) return true;
    setRejectNext(false);
    setStatus(
      "Admission rejected. The draft and waiting messages are preserved; retry the action.",
    );
    return false;
  }

  function admit(steer = false) {
    if (!draft.trim() || (steer && !active) || !accepted()) return;
    const item = { id: `message-${++serial.current}`, text: draft };
    if (active && !steer) {
      setQueue((current) => [...current, item]);
      setStatus(`Message queued. ${queue.length + 1} messages waiting.`);
    } else {
      setSent((current) => [...current, item]);
      if (!steer) {
        setActive(true);
        setTurns((current) => current + 1);
      }
      setStatus(
        steer
          ? `Draft steered into the current reply. ${queue.length} messages waiting.`
          : "Message sent. Reply started.",
      );
    }
    setDraft("");
  }

  function consume(id: string, steer: boolean) {
    const item = queue.find((entry) => entry.id === id);
    if (!item || (steer && !accepted())) return;
    setQueue((current) => current.filter((entry) => entry.id !== id));
    if (steer) setSent((current) => [...current, item]);
    setStatus(
      `${steer ? "Message steered into the current reply" : "Waiting message removed"}. ${queue.length - 1} messages waiting.`,
    );
    inputRef.current?.focus();
  }

  function complete() {
    const next = queue[0];
    if (next && !accepted()) return;
    if (next) {
      setQueue((current) => current.slice(1));
      setSent((current) => [...current, next]);
      setTurns((current) => current + 1);
      setStatus(
        `Reply completed; oldest waiting message dispatched. ${queue.length - 1} messages waiting.`,
      );
    } else {
      setActive(false);
      setStatus("Reply completed. No messages waiting.");
    }
  }

  return (
    <div
      data-chat-queue-demo
      data-reply-count={turns}
      style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
    >
      {sent.map((item) => (
        <Chat key={item.id} placement="end">
          <Chat.Bubble color="primary" collapsible>
            {item.text}
          </Chat.Bubble>
        </Chat>
      ))}
      <Chat.Agent>
        <Chat.Content streaming={active}>
          {active ? "Simulated reply in progress" : "Simulated reply complete"}
        </Chat.Content>
      </Chat.Agent>
      <Chat.InputArea>
        <Chat.Queue
          items={queue}
          steerDisabled={!active}
          onSteer={(id) => consume(id, true)}
          onRemove={(id) => consume(id, false)}
        />
        <Chat.ComposerForm
          ghost
          onSubmit={(event) => {
            event.preventDefault();
            admit();
          }}
        >
          <label className="sr-only" htmlFor={inputId}>
            Queue demo message
          </label>
          <Chat.ComposerInput
            ref={inputRef}
            id={inputId}
            name="message"
            value={draft}
            rows={3}
            placeholder="Message the agent…"
            onChange={(event) => setDraft(event.currentTarget.value)}
            onKeyDown={(event) => {
              if (
                event.nativeEvent.isComposing ||
                event.keyCode === 229 ||
                event.key !== "Enter" ||
                event.shiftKey ||
                event.altKey
              )
                return;
              event.preventDefault();
              if (event.ctrlKey || event.metaKey) admit(true);
              else event.currentTarget.form?.requestSubmit();
            }}
          />
          <Chat.ComposerActions>
            <button
              className="btn btn-primary btn-sm btn-circle btn-icon btn-icon-sm"
              type="submit"
              disabled={!draft.trim()}
              aria-label={active ? "Queue message" : "Send message"}
              title={active ? "Queue message (Enter)" : "Send message (Enter)"}
              aria-keyshortcuts="Enter"
            >
              <QueueIcon action="send" />
            </button>
            <button
              className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
              type="button"
              disabled={!active || !draft.trim()}
              aria-label="Steer current message"
              title="Steer current message (Ctrl/⌘+Enter)"
              aria-keyshortcuts="Control+Enter Meta+Enter"
              onClick={() => admit(true)}
            >
              <QueueIcon action="steer" />
            </button>
          </Chat.ComposerActions>
        </Chat.ComposerForm>
      </Chat.InputArea>
      <p role="status" aria-atomic="true">
        {status}
      </p>
      <div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
        <button
          className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
          type="button"
          disabled={!active}
          aria-label="Complete response"
          title="Complete response"
          onClick={complete}
        >
          <QueueIcon action="complete" />
        </button>
        <button
          className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
          type="button"
          aria-label="Reject next admission"
          title="Reject next admission"
          aria-pressed={rejectNext}
          onClick={() => setRejectNext(!rejectNext)}
        >
          <QueueIcon action="reject" />
        </button>
        <button
          className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
          type="button"
          aria-label="Start fresh"
          title="Start fresh"
          onClick={() => {
            setActive(false);
            setQueue([]);
            setSent([]);
            setDraft("");
            setTurns(0);
            setRejectNext(false);
            setStatus("Idle. No messages waiting.");
            inputRef.current?.focus();
          }}
        >
          <QueueIcon action="reset" />
        </button>
      </div>
    </div>
  );
}
Preview
Simulated reply in progress

Waiting messages

2 queued
  1. #1
    Also include the accessibility checks.
  2. #2
    Check narrow screens too.

Reply in progress. 2 messages waiting.

Waiting Queue and Steer

authored

Application-owned local simulation: Enter sends or queues, Shift+Enter adds a newline, and Ctrl/⌘+Enter steers into the current reply. Complete response dispatches the oldest waiting item; rejection preserves drafts/messages. No backend or generated answers.

Source
import React, { useId, useRef, useState } from "react";
import { Chat } from "@duskmoon-dev/components/chat";

export function AgentActivityPreview() {
  return (
    <div data-chat-agent-demo style={{ width: "min(42rem, 100%)" }}>
      <Chat.Agent>
        <Chat.Work>
          <Chat.WorkSummary>Worked · 2 tool calls · 0 failed</Chat.WorkSummary>
          <Chat.WorkBody>
            <Chat.Reasoning>
              <summary>Reasoning</summary>
              <div className="chat-reasoning-body">
                Compare the source contract before checking behavior.
              </div>
            </Chat.Reasoning>
            <Chat.Tool status="success">
              <Chat.ToolHeader>
                Review source <Chat.ToolStatus>Done</Chat.ToolStatus>
              </Chat.ToolHeader>
              <Chat.ToolResult>Markup reviewed.</Chat.ToolResult>
            </Chat.Tool>
          </Chat.WorkBody>
        </Chat.Work>
        <Chat.Content className="markdown-body">
          <p>The answer stays visible when activity is closed.</p>
        </Chat.Content>
      </Chat.Agent>
      <Chat.Agent>
        <Chat.Content streaming>Progress without an avatar</Chat.Content>
      </Chat.Agent>
    </div>
  );
}

const initialMessage =
  "Review the chat view.\nKeep the waiting queue.\nSupport immediate steer.\nPreserve message order.\nKeep multiline text.\nCheck keyboard focus.\nCheck narrow screens.\nShare the results.";

export function CollapsibleMessagePreview() {
  const [message, setMessage] = useState(initialMessage);
  const id = useId();
  return (
    <div
      data-chat-collapse-demo
      style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
    >
      <label htmlFor={id}>Sent message text (edit to remeasure)</label>
      <textarea
        id={id}
        className="textarea"
        value={message}
        rows={3}
        onChange={(event) => setMessage(event.currentTarget.value)}
      />
      <Chat placement="end">
        <Chat.Bubble color="primary" collapsible>
          {message}
        </Chat.Bubble>
      </Chat>
    </div>
  );
}

function QueueIcon({
  action,
}: {
  action: "send" | "steer" | "complete" | "reject" | "reset";
}) {
  const paths = {
    send: "m5 12 7-7 7 7M12 5v14",
    steer: "m15 4 5 5-5 5M20 9h-9a6 6 0 0 0-6 6v4",
    complete: "m5 12 4 4L19 6",
    reject: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM6 6l12 12",
    reset: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7",
  };
  return (
    <svg
      width="18"
      height="18"
      style={{ flexShrink: 0 }}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
    >
      <path d={paths[action]} />
    </svg>
  );
}

/** Local simulation only. Applications await their transport before changing the queue. */
export function WaitingQueuePreview() {
  const inputId = useId();
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const serial = useRef(2);
  const [draft, setDraft] = useState("");
  const [active, setActive] = useState(true);
  const [turns, setTurns] = useState(1);
  const [rejectNext, setRejectNext] = useState(false);
  const [queue, setQueue] = useState([
    { id: "queued-1", text: "Also include the accessibility checks." },
    { id: "queued-2", text: "Check narrow screens too." },
  ]);
  const [sent, setSent] = useState<{ id: string; text: string }[]>([]);
  const [status, setStatus] = useState(
    "Reply in progress. 2 messages waiting.",
  );

  function accepted() {
    if (!rejectNext) return true;
    setRejectNext(false);
    setStatus(
      "Admission rejected. The draft and waiting messages are preserved; retry the action.",
    );
    return false;
  }

  function admit(steer = false) {
    if (!draft.trim() || (steer && !active) || !accepted()) return;
    const item = { id: `message-${++serial.current}`, text: draft };
    if (active && !steer) {
      setQueue((current) => [...current, item]);
      setStatus(`Message queued. ${queue.length + 1} messages waiting.`);
    } else {
      setSent((current) => [...current, item]);
      if (!steer) {
        setActive(true);
        setTurns((current) => current + 1);
      }
      setStatus(
        steer
          ? `Draft steered into the current reply. ${queue.length} messages waiting.`
          : "Message sent. Reply started.",
      );
    }
    setDraft("");
  }

  function consume(id: string, steer: boolean) {
    const item = queue.find((entry) => entry.id === id);
    if (!item || (steer && !accepted())) return;
    setQueue((current) => current.filter((entry) => entry.id !== id));
    if (steer) setSent((current) => [...current, item]);
    setStatus(
      `${steer ? "Message steered into the current reply" : "Waiting message removed"}. ${queue.length - 1} messages waiting.`,
    );
    inputRef.current?.focus();
  }

  function complete() {
    const next = queue[0];
    if (next && !accepted()) return;
    if (next) {
      setQueue((current) => current.slice(1));
      setSent((current) => [...current, next]);
      setTurns((current) => current + 1);
      setStatus(
        `Reply completed; oldest waiting message dispatched. ${queue.length - 1} messages waiting.`,
      );
    } else {
      setActive(false);
      setStatus("Reply completed. No messages waiting.");
    }
  }

  return (
    <div
      data-chat-queue-demo
      data-reply-count={turns}
      style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
    >
      {sent.map((item) => (
        <Chat key={item.id} placement="end">
          <Chat.Bubble color="primary" collapsible>
            {item.text}
          </Chat.Bubble>
        </Chat>
      ))}
      <Chat.Agent>
        <Chat.Content streaming={active}>
          {active ? "Simulated reply in progress" : "Simulated reply complete"}
        </Chat.Content>
      </Chat.Agent>
      <Chat.InputArea>
        <Chat.Queue
          items={queue}
          steerDisabled={!active}
          onSteer={(id) => consume(id, true)}
          onRemove={(id) => consume(id, false)}
        />
        <Chat.ComposerForm
          ghost
          onSubmit={(event) => {
            event.preventDefault();
            admit();
          }}
        >
          <label className="sr-only" htmlFor={inputId}>
            Queue demo message
          </label>
          <Chat.ComposerInput
            ref={inputRef}
            id={inputId}
            name="message"
            value={draft}
            rows={3}
            placeholder="Message the agent…"
            onChange={(event) => setDraft(event.currentTarget.value)}
            onKeyDown={(event) => {
              if (
                event.nativeEvent.isComposing ||
                event.keyCode === 229 ||
                event.key !== "Enter" ||
                event.shiftKey ||
                event.altKey
              )
                return;
              event.preventDefault();
              if (event.ctrlKey || event.metaKey) admit(true);
              else event.currentTarget.form?.requestSubmit();
            }}
          />
          <Chat.ComposerActions>
            <button
              className="btn btn-primary btn-sm btn-circle btn-icon btn-icon-sm"
              type="submit"
              disabled={!draft.trim()}
              aria-label={active ? "Queue message" : "Send message"}
              title={active ? "Queue message (Enter)" : "Send message (Enter)"}
              aria-keyshortcuts="Enter"
            >
              <QueueIcon action="send" />
            </button>
            <button
              className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
              type="button"
              disabled={!active || !draft.trim()}
              aria-label="Steer current message"
              title="Steer current message (Ctrl/⌘+Enter)"
              aria-keyshortcuts="Control+Enter Meta+Enter"
              onClick={() => admit(true)}
            >
              <QueueIcon action="steer" />
            </button>
          </Chat.ComposerActions>
        </Chat.ComposerForm>
      </Chat.InputArea>
      <p role="status" aria-atomic="true">
        {status}
      </p>
      <div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
        <button
          className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
          type="button"
          disabled={!active}
          aria-label="Complete response"
          title="Complete response"
          onClick={complete}
        >
          <QueueIcon action="complete" />
        </button>
        <button
          className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
          type="button"
          aria-label="Reject next admission"
          title="Reject next admission"
          aria-pressed={rejectNext}
          onClick={() => setRejectNext(!rejectNext)}
        >
          <QueueIcon action="reject" />
        </button>
        <button
          className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
          type="button"
          aria-label="Start fresh"
          title="Start fresh"
          onClick={() => {
            setActive(false);
            setQueue([]);
            setSent([]);
            setDraft("");
            setTurns(0);
            setRejectNext(false);
            setStatus("Idle. No messages waiting.");
            inputRef.current?.focus();
          }}
        >
          <QueueIcon action="reset" />
        </button>
      </div>
    </div>
  );
}
Preview

Messages are queued locally in this example.

Composer, Attachments, and Completion

authored

A controlled multiline composer with image/file previews, application-supplied command and skill completion, local asynchronous admission, and independent Stop. Cmd/Ctrl+Enter sends; Enter adds a line. Draft persistence, remote candidates, file validation/upload, and follow-up policy belong to your application. This example allows attachment-only messages and follow-ups during a reply.

Source
import "@duskmoon-dev/components/styles.css";
import { useState } from "react";
import { Chat } from "@duskmoon-dev/components/chat";

export function ComposerChatPreview() {
  const [value, setValue] = useState("");
  const [files, setFiles] = useState<File[]>([]);
  const [generating, setGenerating] = useState(false);
  const [messages, setMessages] = useState<string[]>([]);
  const [error, setError] = useState("");
  const commands = [
    { id: "help", label: "/help", description: "Show available commands" },
    { id: "review", label: "/review", description: "Use the review skill" },
  ];
  const query = value.match(/\/[^\s/]*$/)?.[0];
  const items = query
    ? commands.filter((item) => item.label.startsWith(query))
    : [];

  return (
    <div
      className="chat-demo"
      data-chat-composer-demo
      style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
    >
      {messages.map((message, index) => (
        <Chat key={index} placement="end">
          <Chat.Bubble color="primary">{message}</Chat.Bubble>
        </Chat>
      ))}
      <Chat.Composer
        value={value}
        onValueChange={setValue}
        attachments={files}
        onAttachmentsChange={(next) => {
          setFiles(next);
          setError(
            next.some((file) => file.size > 2 * 1024 * 1024)
              ? "Choose files smaller than 2 MiB for this example."
              : "",
          );
        }}
        allowAttachmentOnly
        generating={generating}
        onStop={() => setGenerating(false)}
        error={error || undefined}
        onSubmit={async (submission) => {
          if (submission.files.some((file) => file.size > 2 * 1024 * 1024)) {
            setError("Choose files smaller than 2 MiB for this example.");
            return false;
          }
          await new Promise((resolve) => setTimeout(resolve, 200));
          setMessages((current) => [
            ...current,
            [
              submission.value,
              ...submission.files.map((file) => `Attached: ${file.name}`),
            ]
              .filter(Boolean)
              .join(" · "),
          ]);
          setGenerating(true);
          return true;
        }}
        completion={{
          label: "Commands and skills",
          items,
          onSelect: (item, context) => {
            const before = context.value.slice(0, context.selectionStart);
            setValue(
              before.replace(/\/[^\s/]*$/, `${item.label} `) +
                context.value.slice(context.selectionEnd),
            );
          },
        }}
        textareaProps={{
          "aria-label": "Message",
          placeholder: "Write a message or type / for commands and skills",
        }}
      />
      <p role="status">
        {generating
          ? "Reply in progress. You can send a follow-up or stop."
          : "Messages are queued locally in this example."}
      </p>
    </div>
  );
}
Preview
AI
Assistant - 2:15 PM
How can I help you today? Read the Chat guide for longer messages and links.
GA
You - 2:16 PM
Show me a compact chat transcript.

Basic Chat

authored

An unboxed agent answer and a rounded user bubble with optional avatars, headers, and footers.

Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";

const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;

function ChatAvatar({ name, color }: { name: string; color?: string }) {
  return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}

export function BasicChatPreview() {
  return (
    <div className="chat-demo" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "1rem" }}>
      <Chat.Agent>
        <ChatAvatar name="AI" color="avatar-primary" />
        <Chat.Header>Assistant - 2:15 PM</Chat.Header>
        <Chat.Content>How can I help you today? Read the <a href="/components/chat">Chat guide</a> for longer messages and links.</Chat.Content>
        <Chat.Footer>Delivered</Chat.Footer>
      </Chat.Agent>
      <Chat placement="end">
        <ChatAvatar name="GA" />
        <Chat.Header>You - 2:16 PM</Chat.Header>
        <Chat.Bubble color="primary">Show me a compact chat transcript.</Chat.Bubble>
        <Chat.Footer>Sent</Chat.Footer>
      </Chat>
    </div>
  );
}
Preview
AI
Assistant - 2:00 PM
Welcome back. The left ticks mark each assistant reply — scroll or click a tick to jump to that response.
GA
You - 2:01 PM
Can the rail follow assistant replies?
AI
Assistant - 2:01 PM
Each agent row exposes a named view timeline. The parent raises timeline scope so indicators can follow visible replies.
GA
You - 2:02 PM
Should user messages get ticks?
AI
Assistant - 2:02 PM
No. Ticks only navigate to an agent response. User turns remain in the transcript without ticks.
GA
You - 2:03 PM
What about animation range?
AI
Assistant - 2:03 PM
Indicators brighten as their paired assistant message enters the panel and fade as it leaves.
GA
You - 2:04 PM
Why avoid hash links?
AI
Assistant - 2:04 PM
Hash navigation scrolls the document. These buttons scroll only this conversation panel.
GA
You - 2:05 PM
Can ticks land on the reply start?
AI
Assistant - 2:05 PM
The handler aligns the agent row with the top of the panel, allowing for its scroll margin.
GA
You - 2:06 PM
Add one more long answer.
AI
Assistant - 2:06 PM
This longer answer gives the transcript enough height to scroll while the sticky indicator rail stays visible beside the message column. Long links, such as the DuskMoon component documentation, wrap inside a message instead of widening the panel.
GA
You - 2:07 PM
Great — take me to the last reply.
AI
Assistant - 2:07 PM
Done. Click the last dash to return to this assistant response without moving the page behind the panel.

Scroll-Driven Chat Indicators

authored

Eight assistant replies pair with in-panel navigation ticks; user turns stay in the transcript without ticks.

Source
import "@duskmoon-dev/components/styles.css";
import React, { useId } from "react";
import * as DmComponents from "@duskmoon-dev/components";

const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;

function ChatAvatar({ name, color }: { name: string; color?: string }) {
  return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}

const scrollReplies = [
  "Welcome back. The left ticks mark each assistant reply — scroll or click a tick to jump to that response.",
  "Each agent row exposes a named view timeline. The parent raises timeline scope so indicators can follow visible replies.",
  "No. Ticks only navigate to an agent response. User turns remain in the transcript without ticks.",
  "Indicators brighten as their paired assistant message enters the panel and fade as it leaves.",
  "Hash navigation scrolls the document. These buttons scroll only this conversation panel.",
  "The handler aligns the agent row with the top of the panel, allowing for its scroll margin.",
  "This longer answer gives the transcript enough height to scroll while the sticky indicator rail stays visible beside the message column. Long links, such as the DuskMoon component documentation, wrap inside a message instead of widening the panel.",
  "Done. Click the last dash to return to this assistant response without moving the page behind the panel.",
] as const;
const scrollQuestions = [
  "Can the rail follow assistant replies?",
  "Should user messages get ticks?",
  "What about animation range?",
  "Why avoid hash links?",
  "Can ticks land on the reply start?",
  "Add one more long answer.",
  "Great — take me to the last reply.",
] as const;
const scrollTimelines = [1, 2, 3, 4, 5, 6, 7, 8] as const;

export function ScrollDrivenChatPreview() {
  const transcriptId = useId();
  const replyIds = scrollTimelines.map((timeline) => `${transcriptId}-reply-${timeline}`);
  return (
    <Chat.Scroll className="chat-demo" style={{ width: "min(48rem, 100%)", height: "22rem" }} aria-label="Example chat transcript">
      <Chat.ScrollTrack aria-label="Assistant replies">
        {scrollTimelines.map((timeline, index) => <Chat.ScrollIndicator key={timeline} timeline={timeline} targetId={replyIds[index]} />)}
      </Chat.ScrollTrack>
      <Chat.ScrollBody>
        {scrollTimelines.map((timeline, index) => (
          <React.Fragment key={timeline}>
            <Chat.Agent id={replyIds[index]} timeline={timeline}>
              <ChatAvatar name="AI" color="avatar-primary" />
              <Chat.Header>Assistant - 2:{String(index).padStart(2, "0")} PM</Chat.Header>
              <Chat.Content>{scrollReplies[index]}</Chat.Content>
            </Chat.Agent>
            {index < scrollQuestions.length && (
              <Chat placement="end">
                <ChatAvatar name="GA" />
                <Chat.Header>You - 2:{String(index + 1).padStart(2, "0")} PM</Chat.Header>
                <Chat.Bubble color="primary">{scrollQuestions[index]}</Chat.Bubble>
              </Chat>
            )}
          </React.Fragment>
        ))}
      </Chat.ScrollBody>
    </Chat.Scroll>
  );
}
Preview
Default bubble
primary bubble
secondary bubble
tertiary bubble
info bubble
success bubble
warning bubble
error bubble
Filled primary bubble

Bubble Colors

authored

Default, semantic soft colors, and a filled primary bubble.

Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";

const Chat = DmComponents.Chat;

export function BubbleColorsPreview() {
  const colors = ["primary", "secondary", "tertiary", "info", "success", "warning", "error"] as const;
  return (
    <div className="chat-demo" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "0.75rem" }}>
      <Chat placement="end"><Chat.Bubble>Default bubble</Chat.Bubble></Chat>
      {colors.map((color) => <Chat placement="end" key={color}><Chat.Bubble color={color}>{color} bubble</Chat.Bubble></Chat>)}
      <Chat placement="end"><Chat.Bubble color="primary" filled>Filled primary bubble</Chat.Bubble></Chat>
    </div>
  );
}
Preview
AI
المساعد
كيف يمكنني مساعدتك اليوم؟
GA
أنت
أرني مثالاً للمحادثة.

RTL Bubble Alignment

authored

Right-to-left start and end rows with Arabic labels and bubbles.

Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";

const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;

function ChatAvatar({ name, color }: { name: string; color?: string }) {
  return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}

export function RtlBubblePreview() {
  return (
    <div className="chat-demo" dir="rtl" lang="ar" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "1rem" }}>
      <Chat.Agent><ChatAvatar name="AI" color="avatar-primary" /><Chat.Header>المساعد</Chat.Header><Chat.Content>كيف يمكنني مساعدتك اليوم؟</Chat.Content></Chat.Agent>
      <Chat placement="end"><ChatAvatar name="GA" /><Chat.Header>أنت</Chat.Header><Chat.Bubble color="primary">أرني مثالاً للمحادثة.</Chat.Bubble></Chat>
    </div>
  );
}
Preview
Extra small transcript bubble
Small dense chat bubble
Medium default chat bubble
Large accessible chat bubble

Bubble Sizes

authored

Extra small through large bubble sizes.

Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";

const Chat = DmComponents.Chat;

export function BubbleSizesPreview() {
  const sizes = [["xs", "Extra small transcript bubble"], ["sm", "Small dense chat bubble"], ["md", "Medium default chat bubble"], ["lg", "Large accessible chat bubble"]] as const;
  return (
    <div className="chat-demo" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "0.75rem" }}>
      {sizes.map(([size, label]) => <Chat placement="end" key={size}><Chat.Bubble size={size}>{label}</Chat.Bubble></Chat>)}
    </div>
  );
}
Preview
AI
Assistant - 2:18 PM
Working · 2 tool calls · 0 failed
Thinking (3s)
I should call the weather tool, then summarize the result in one sentence.
get_weatherRunning...
Calljson
{"city":"Tokyo"}
Tool returned cloudy at 18 C. Drafting the final answer.
get_weatherDone
Calljson
{"city":"Tokyo"}
Resultjson
{"temperature":"18 C","condition":"cloudy"}
It is 18 C and cloudy in Tokyo right now.

Reasoning, Tool Call, and Streaming

authored

Reasoning with a running tool, a completed call and result, and streaming final content inside one bubble.

Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";

const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;

function ChatAvatar({ name, color }: { name: string; color?: string }) {
  return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}

function CodePane({ title, children }: { title: "Call" | "Result"; children: string }) {
  return (
    <div className="code-block code-block-compact">
      <div className="code-header"><span className="code-title">{title}</span><span className="code-language">json</span></div>
      <div className="code-content"><pre tabIndex={0} aria-label={`${title} JSON payload`}><code>{children}</code></pre></div>
    </div>
  );
}

export function LlmChatPreview() {
  return (
    <div className="chat-demo" style={{ width: "min(48rem, 100%)", display: "flex", flexDirection: "column", gap: "1rem" }}>
      <Chat.Agent aria-live="polite">
        <ChatAvatar name="AI" color="avatar-info" />
        <Chat.Header>Assistant - 2:18 PM</Chat.Header>
        <Chat.Work open><Chat.WorkSummary>Working · 2 tool calls · 0 failed</Chat.WorkSummary><Chat.WorkBody>
          <Chat.Reasoning open>
            <summary>Thinking (3s)</summary>
            <div className="chat-reasoning-body">
              <div>I should call the weather tool, then summarize the result in one sentence.</div>
              <Chat.Tool status="running" open>
                <Chat.ToolHeader><span>get_weather</span><Chat.ToolStatus>Running...</Chat.ToolStatus></Chat.ToolHeader>
                <Chat.ToolCall><CodePane title="Call">{'{"city":"Tokyo"}'}</CodePane></Chat.ToolCall>
              </Chat.Tool>
              <div>Tool returned cloudy at 18 C. Drafting the final answer.</div>
            </div>
          </Chat.Reasoning>
          <Chat.Tool status="success" open>
            <Chat.ToolHeader><span>get_weather</span><Chat.ToolStatus>Done</Chat.ToolStatus></Chat.ToolHeader>
            <Chat.ToolCall><CodePane title="Call">{'{"city":"Tokyo"}'}</CodePane></Chat.ToolCall>
            <Chat.ToolResult><CodePane title="Result">{'{"temperature":"18 C","condition":"cloudy"}'}</CodePane></Chat.ToolResult>
          </Chat.Tool>
          </Chat.WorkBody></Chat.Work><Chat.Content streaming>It is 18 C and cloudy in Tokyo right now.</Chat.Content>
        
        <Chat.Footer>Streaming</Chat.Footer>
      </Chat.Agent>
    </div>
  );
}
Preview
AI
AI
Generating a response

Typing and Streaming

authored

First-token typing and an active streaming reply.

Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";

const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;

function ChatAvatar({ name, color }: { name: string; color?: string }) {
  return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}

export function LiveStatesPreview() {
  return (
    <div className="chat-demo" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "1rem" }}>
      <Chat.Agent><ChatAvatar name="AI" color="avatar-secondary" /><Chat.Content><Chat.Typing /></Chat.Content></Chat.Agent>
      <Chat.Agent><ChatAvatar name="AI" color="avatar-secondary" /><Chat.Content streaming>Generating a response</Chat.Content></Chat.Agent>
    </div>
  );
}
Preview
GA
You
Summarize the deployment checks.
Sent12 tokens
Edit your deployment question
AI
Assistant · Generating
Checking the build and smoke-test results
Generating42 token/s256 tokens
Stop generating the deployment summary
AI
Assistant · Completed
The build completed and all deployment smoke tests passed.
Completed42 token/s1,248 tokens
Retry the deployment summaryCopy the deployment summary

Token Metrics and Message Actions

authored

Edit, Stop, Retry, and Copy appear on row hover or focus; touch devices keep them visible, with local outcomes alongside status and token metrics.

Source
import "@duskmoon-dev/components/styles.css";
import React, { useId, useState } from "react";
import * as DmComponents from "@duskmoon-dev/components";

const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;
const Tooltip = DmComponents.Tooltip;

function ChatAvatar({ name, color }: { name: string; color?: string }) {
  return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}

function Action({ label, onClick, children }: {
  label: string;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <Tooltip title={label}>
      <button type="button" className="btn btn-ghost btn-xs btn-square" aria-label={label} onClick={onClick}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false">
          {children}
        </svg>
      </button>
    </Tooltip>
  );
}

export function MessageActionsPreview() {
  const editId = useId();
  const [question, setQuestion] = useState("Summarize the deployment checks.");
  const [draft, setDraft] = useState(question);
  const [editing, setEditing] = useState(false);
  const [generating, setGenerating] = useState(true);
  const [revision, setRevision] = useState(0);
  const [feedback, setFeedback] = useState("");
  const answer = revision === 0 ? "The build completed and all deployment smoke tests passed." : `Revision ${revision}: the build and smoke tests passed.`;
  async function copyAnswer() {
    try {
      await navigator.clipboard.writeText(answer);
      setFeedback("Deployment summary copied.");
    } catch {
      setFeedback("Copy failed. Select the summary to copy it.");
    }
  }
  return (
    <div className="chat-demo" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "1rem" }}>
      <Chat placement="end">
        <ChatAvatar name="GA" /><Chat.Header>You</Chat.Header>
        <Chat.Bubble color="primary">{question}</Chat.Bubble>
        <Chat.Status><Chat.StatusItem>Sent</Chat.StatusItem><Chat.StatusItem><Chat.StatusValue>12</Chat.StatusValue> tokens</Chat.StatusItem></Chat.Status>
        <Chat.Actions hover>
          <Action label="Edit your deployment question" onClick={() => { setDraft(question); setEditing(true); }}><path d="m16 3 5 5-12 12H4v-5Z" /><path d="m14 5 5 5" /></Action>
        </Chat.Actions>
        {editing && <form onSubmit={(event) => { event.preventDefault(); setQuestion(draft); setEditing(false); setFeedback("Question updated."); }}>
          <label htmlFor={editId}>Edit question</label>
          <input id={editId} className="input" value={draft} onChange={(event) => setDraft(event.target.value)} />
          <button type="submit" className="btn btn-primary btn-xs">Save</button>
        </form>}
      </Chat>
      <Chat.Agent>
        <ChatAvatar name="AI" color="avatar-secondary" /><Chat.Header>Assistant · {generating ? "Generating" : "Stopped"}</Chat.Header>
        <Chat.Content streaming={generating}>{generating ? "Checking the build and smoke-test results" : "Generation stopped."}</Chat.Content>
        <Chat.Status><Chat.StatusItem>{generating ? "Generating" : "Stopped"}</Chat.StatusItem><Chat.StatusItem><Chat.StatusValue>42</Chat.StatusValue> token/s</Chat.StatusItem><Chat.StatusItem><Chat.StatusValue>256</Chat.StatusValue> tokens</Chat.StatusItem></Chat.Status>
        {generating && <Chat.Actions hover><Action label="Stop generating the deployment summary" onClick={() => { setGenerating(false); setFeedback("Generation stopped."); }}><rect x="5" y="5" width="14" height="14" rx="2" /></Action></Chat.Actions>}
      </Chat.Agent>
      <Chat.Agent>
        <ChatAvatar name="AI" color="avatar-primary" /><Chat.Header>Assistant · Completed</Chat.Header>
        <Chat.Content>{answer}</Chat.Content>
        <Chat.Status><Chat.StatusItem>Completed</Chat.StatusItem><Chat.StatusItem><Chat.StatusValue>42</Chat.StatusValue> token/s</Chat.StatusItem><Chat.StatusItem><Chat.StatusValue>1,248</Chat.StatusValue> tokens</Chat.StatusItem></Chat.Status>
        <Chat.Actions hover>
          <Action label="Retry the deployment summary" onClick={() => { setRevision((current) => current + 1); setFeedback("Summary regenerated locally."); }}><path d="M3 11a9 9 0 1 1 2.6 7.4" /><path d="M3 4v7h7" /></Action>
          <Action label="Copy the deployment summary" onClick={() => { void copyAnswer(); }}><rect x="8" y="8" width="13" height="13" rx="2" /><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3" /></Action>
        </Chat.Actions>
      </Chat.Agent>
      <p role="status">{feedback}</p>
    </div>
  );
}
Preview
search_docsPending
run_queryRunning...
get_profileDone
deploy_previewFailed

Tool Statuses

authored

Pending, running, successful, and failed tool headers.

Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";

const Chat = DmComponents.Chat;

export function ToolStatusesPreview() {
  const tools = [["pending", "search_docs", "Pending"], ["running", "run_query", "Running..."], ["success", "get_profile", "Done"], ["error", "deploy_preview", "Failed"]] as const;
  return (
    <div className="chat-demo" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "0.75rem" }}>
      {tools.map(([status, name, label]) => <Chat.Tool key={status} status={status} open><Chat.ToolHeader><span>{name}</span><Chat.ToolStatus>{label}</Chat.ToolStatus></Chat.ToolHeader></Chat.Tool>)}
    </div>
  );
}
Preview
AI

Summary: the deployment is ready.

  • Build completed
  • Smoke test passed

Markdown Agent Content

authored

Unboxed agent answer with Markdown typography.

Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";

const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;

function ChatAvatar({ name, color }: { name: string; color?: string }) {
  return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}

export function MarkdownChatPreview() {
  return (
    <div className="chat-demo" style={{ width: "min(42rem, 100%)" }}>
      <Chat.Agent><ChatAvatar name="AI" color="avatar-tertiary" /><Chat.Content><div className="markdown-body"><p><strong>Summary:</strong> the deployment is ready.</p><ul><li>Build completed</li><li>Smoke test passed</li></ul></div></Chat.Content></Chat.Agent>
    </div>
  );
}

API

The API reference below lists every parsed exported type or interface for Chat. Start with `placement`, `timeline`, `hover`, `targetId` for common usage.

Types: packages/components/src/components/chat/Chat.types.tsScenarios: packages/components/src/components/chat/Chat.test.tsx
ChatPropsinterface extends ComponentProps<"div">
PropTypeRequiredDescription
placementChatPlacementNoPosition the turn at the start or end of the conversation row.
timelineChatTimelineNoPair an assistant row with a scroll indicator (slots 1–24).
ChatActionsPropsinterface extends ComponentProps<"div">
PropTypeRequiredDescription
hoverbooleanNoReveal actions on message hover or keyboard focus.
ChatScrollIndicatorPropsinterface extends ComponentProps<"button">
PropTypeRequiredDescription
targetIdstringYestargetId configures Chat.
timelineChatTimelineYestimeline configures Chat.
ChatBubblePropsinterface extends ComponentProps<"div">
PropTypeRequiredDescription
colorChatBubbleColorNoApply a semantic DuskMoon color to the bubble.
sizeChatBubbleSizeNoControl the bubble padding and font size. @default "md"
filledbooleanNoUse the saturated form of the selected color.
streamingbooleanNoShow the live streaming caret after the bubble content.
collapsiblebooleanNoCollapse sent user messages exceeding six rendered lines.
expandedbooleanNoexpanded configures Chat.
defaultExpandedbooleanNodefaultExpanded configures Chat.
onExpandedChange(expanded: boolean) => voidNoonExpandedChange configures Chat.
ChatContentPropsinterface extends ComponentProps<"div">
PropTypeRequiredDescription
streamingbooleanNostreaming configures Chat.
ChatComposerFormPropsinterface extends ComponentProps<"form">
PropTypeRequiredDescription
colorChatComposerColorNocolor configures Chat.
ghostbooleanNoghost configures Chat.
ChatQueueIteminterface
PropTypeRequiredDescription
idstringYesid configures Chat.
textstringYestext configures Chat.
attachment{ src: string; alt: string }Noattachment configures Chat.
ChatQueuePropsinterface extends Omit< ComponentProps<"section">, "children" >
PropTypeRequiredDescription
itemsreadonly ChatQueueItem[]Yesitems configures Chat.
activeIdstringNoStable identity of the next message; defaults to the first item.
pendingIdsreadonly string[]NoThe application owns pending state and removes messages after acknowledgment.
steerDisabledbooleanNosteerDisabled configures Chat.
renderItemActions(NoOptional authoritative controls; legacy Steer/Remove remain the default.
itemChatQueueItem,Yesitem configures Chat.
indexnumber,Yesindex configures Chat.
pendingboolean,Yespending configures Chat.
renderItemContent(item: ChatQueueItem, index: number) => ReactNodeNorenderItemContent configures Chat.
onSteer(id: string) => voidYesonSteer configures Chat.
onRemove(id: string) => voidYesonRemove configures Chat.
labelstringNoAccessible queue name. @default "Waiting messages"
ChatToolPropsinterface extends ComponentProps<"details">
PropTypeRequiredDescription
statusChatToolStateNoReflect the current tool-call state.
ChatComposerSubmissioninterface
PropTypeRequiredDescription
valuestringYesvalue configures Chat.
filesFile[]Yesfiles configures Chat.
ChatComposerCompletioninterface
PropTypeRequiredDescription
idstringYesid configures Chat.
labelstringYeslabel configures Chat.
iconReactNodeNoOptional presentation; never part of the submitted document.
sourceLabelstringNosourceLabel configures Chat.
descriptionReactNodeNodescription configures Chat.
disabledbooleanNodisabled configures Chat.
groupstringNogroup configures Chat.
ChatComposerCompletionContextinterface
PropTypeRequiredDescription
valuestringYesvalue configures Chat.
selectionStartnumberYesselectionStart configures Chat.
selectionEndnumberYesselectionEnd configures Chat.
ChatComposerCompletionConfiginterface
PropTypeRequiredDescription
itemsreadonly ChatComposerCompletion[]Yesitems configures Chat.
onSelect(YesonSelect configures Chat.
itemChatComposerCompletion,Yesitem configures Chat.
contextChatComposerCompletionContext,Yescontext configures Chat.
labelstringNolabel configures Chat.
ChatComposerActionContextinterface
PropTypeRequiredDescription
submit() => voidYessubmit configures Chat.
submittingbooleanYessubmitting configures Chat.
canSubmitbooleanYescanSubmit configures Chat.
disabledbooleanYesdisabled configures Chat.
generatingbooleanYesgenerating configures Chat.
openAttachments() => voidYesopenAttachments configures Chat.
ChatComposerAttachmentContextinterface
PropTypeRequiredDescription
remove() => voidYesremove configures Chat.
disabledbooleanYesdisabled configures Chat.
ChatComposerPropsinterface extends Omit< ComponentProps<"div">, "children" | "onSubmit" | "onChange" >
PropTypeRequiredDescription
valuestringYesvalue configures Chat.
scopeComposerScopeNoIsolate pending admission and completion state when changing contexts.
onValueChange(value: string) => voidYesonValueChange configures Chat.
onSubmit(YesReturn false to reject admission and retain the draft.
snapshotChatComposerSubmission,Yessnapshot configures Chat.
attachmentsFile[]Noattachments configures Chat.
onAttachmentsChange(files: File[]) => voidNoEnables the native file picker and attachment removal controls.
acceptstringNoaccept configures Chat.
attachmentPolicyComposerAttachmentIntakePolicyNoShared validation for picker, pasted files, and dropped files.
onAttachmentRejected(NoonAttachmentRejected configures Chat.
rejectedreadonly ComposerAttachmentRejection[],Yesrejected configures Chat.
multiplebooleanNo@default true
allowAttachmentOnlybooleanNoPermit a draft containing only files. @default false
compactbooleanNoCompact Add menu, one send/stop action and ready-image strip. @default false
addMenuReactNodeNoAdditional actions in the compact Add menu.
contextReactNodeNoAttached context bar, rendered first inside the composer.
disabledbooleanNodisabled configures Chat.
busybooleanNoGates submission while keeping the draft editable.
generatingbooleanNoShows Stop when onStop is supplied; does not prevent submission.
canSubmitbooleanNoApplication-controlled admission, including follow-ups. @default true
onStop() => voidNoonStop configures Chat.
errorReactNodeNoerror configures Chat.
onSubmitError(error: unknown) => voidNoonSubmitError configures Chat.
clearOnSubmitbooleanNoClear unchanged admitted text and only admitted file entries. @default true
completionChatComposerCompletionConfigNocompletion configures Chat.
minRowsnumberNo@default 1
maxRowsnumberNo@default 6
textareaPropsOmit<NotextareaProps configures Chat.
attachLabelstringNoattachLabel configures Chat.
sendLabelstringNosendLabel configures Chat.
stopLabelstringNostopLabel configures Chat.
renderAttachment(NorenderAttachment configures Chat.
fileFile,Yesfile configures Chat.
contextChatComposerAttachmentContext,Yescontext configures Chat.
childrenReactNode | ((context: ChatComposerActionContext) => ReactNode)NoExtra application actions rendered alongside Attach, Stop, and Send.
ChatPlacementtype
Type definition
"start" | "end"
ChatTimelinetype
Type definition
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24
ChatBubbleColortype
Type definition
| "primary" | "secondary" | "tertiary" | "accent" | "neutral" | "base" | "info" | "success" | "warning" | "error"
ChatBubbleSizetype
Type definition
"xs" | "sm" | "md" | "lg"
ChatToolStatetype
Type definition
"pending" | "running" | "success" | "error"
ChatAvatarPropstype
Type definition
ComponentProps<"div">
ChatHeaderPropstype
Type definition
ComponentProps<"div">
ChatFooterPropstype
Type definition
ComponentProps<"div">
ChatStatusPropstype
Type definition
ComponentProps<"div">
ChatStatusItemPropstype
Type definition
ComponentProps<"span">
ChatStatusValuePropstype
Type definition
ComponentProps<"span">
ChatScrollPropstype
Type definition
ComponentProps<"div">
ChatScrollBodyPropstype
Type definition
ComponentProps<"div">
ChatScrollTrackPropstype
Type definition
ComponentProps<"div">
ChatAgentPropstype
Type definition
Omit<ChatProps, "placement">
ChatWorkPropstype
Type definition
ComponentProps<"details">
ChatWorkSummaryPropstype
Type definition
ComponentProps<"summary">
ChatWorkBodyPropstype
Type definition
ComponentProps<"div">
ChatInputAreaPropstype
Type definition
ComponentProps<"div">
ChatComposerColortype
Type definition
| "primary" | "secondary" | "tertiary" | "info" | "success" | "warning" | "error"
ChatComposerInputPropstype
Type definition
ComponentProps<"textarea">
ChatComposerActionsPropstype
Type definition
ComponentProps<"div">
ChatComposerHintPropstype
Type definition
ComponentProps<"kbd">
ChatReasoningPropstype
Type definition
ComponentProps<"details">
ChatToolHeaderPropstype
Type definition
ComponentProps<"summary">
ChatToolStatusPropstype
Type definition
ComponentProps<"span">
ChatToolCallPropstype
Type definition
ComponentProps<"div">
ChatToolResultPropstype
Type definition
ComponentProps<"div">
ChatTypingPropstype
Type definition
Omit<ComponentProps<"span">, "children">
ChatComponenttype
Type definition
ChatPartComponent<HTMLDivElement, ChatProps> & { Composer: ChatPartComponent<HTMLDivElement, ChatComposerProps>