---
title: "AI Chat Conversation · UI SDK — StyleX Blocks"
description: "Transcript of alternating turns carrying mixed rich content inline (prose, code blocks, collapsible tool-call output) beside a resizable artifact panel that collapses to a full-screen dialog on narrow screens."
url: "https://stylexblocks.com/block/ui-sdk/ai-chat/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# AI Chat Conversation block

Transcript of alternating turns carrying mixed rich content inline (prose, code blocks, collapsible tool-call output) beside a resizable artifact panel that collapses to a full-screen dialog on narrow screens.

- Behavior engine: UI SDK
- Category: [AI](https://stylexblocks.com/blocks/ai.md)
- Built with: [Badge](https://stylexblocks.com/components/ui-sdk/badge.md), [Bubble](https://stylexblocks.com/components/ui-sdk/bubble.md), [Button](https://stylexblocks.com/components/ui-sdk/button.md), [Center](https://stylexblocks.com/components/ui-sdk/center.md), [Code Block](https://stylexblocks.com/components/ui-sdk/code-block.md), [Collapsible](https://stylexblocks.com/components/ui-sdk/collapsible.md), [Dialog](https://stylexblocks.com/components/ui-sdk/dialog.md), [Heading](https://stylexblocks.com/components/ui-sdk/heading.md), [Icon Button](https://stylexblocks.com/components/ui-sdk/icon-button.md), [Menu](https://stylexblocks.com/components/ui-sdk/menu.md), [Message](https://stylexblocks.com/components/ui-sdk/message.md), [Message Scroller](https://stylexblocks.com/components/ui-sdk/message-scroller.md), [Separator](https://stylexblocks.com/components/ui-sdk/separator.md), [Spinner](https://stylexblocks.com/components/ui-sdk/spinner.md), [Splitter](https://stylexblocks.com/components/ui-sdk/splitter.md), [Stack](https://stylexblocks.com/components/ui-sdk/stack.md), [Table](https://stylexblocks.com/components/ui-sdk/table.md), [Tag](https://stylexblocks.com/components/ui-sdk/tag.md), [Text](https://stylexblocks.com/components/ui-sdk/text.md), [Textarea](https://stylexblocks.com/components/ui-sdk/textarea.md), [Toast](https://stylexblocks.com/components/ui-sdk/toast.md), [Toolbar](https://stylexblocks.com/components/ui-sdk/toolbar.md), [Visually Hidden](https://stylexblocks.com/components/ui-sdk/visually-hidden.md)
- HTML page: https://stylexblocks.com/block/ui-sdk/ai-chat/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style ui-sdk
```

Then add the item as source you own:

```sh
npx stylexblocks add ai-chat
```

Equivalent: `npx shadcn add @stylexblocks/ai-chat`. Registry item JSON: https://stylexblocks.com/r/ui-sdk/ai-chat.json

## Usage

```tsx
import { AiChat } from "#components/blocks/ui-sdk/ai-chat.tsx";

export function Example() {
  return (
    <div style={{ height: "100dvh" }}>
      <AiChat defaultArtifactOpen />
    </div>
  );
}
```

## Source

`components/blocks/ui-sdk/ai-chat.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { useCallback, useMemo, useRef, useState } from "react";
import { Badge } from "#components/ui/ui-sdk/badge.tsx";
import { Bubble } from "#components/ui/ui-sdk/bubble.tsx";
import { Button } from "#components/ui/ui-sdk/button.tsx";
import { Square } from "#components/ui/ui-sdk/center.tsx";
import { CodeBlock } from "#components/ui/ui-sdk/code-block.tsx";
import { Collapsible } from "#components/ui/ui-sdk/collapsible.tsx";
import { Dialog } from "#components/ui/ui-sdk/dialog.tsx";
import { Heading } from "#components/ui/ui-sdk/heading.tsx";
import { IconButton } from "#components/ui/ui-sdk/icon-button.tsx";
import { Menu } from "#components/ui/ui-sdk/menu.tsx";
import { Message } from "#components/ui/ui-sdk/message.tsx";
import { MessageScroller } from "#components/ui/ui-sdk/message-scroller.tsx";
import { Separator } from "#components/ui/ui-sdk/separator.tsx";
import { Spinner } from "#components/ui/ui-sdk/spinner.tsx";
import { Splitter } from "#components/ui/ui-sdk/splitter.tsx";
import { HStack, VStack } from "#components/ui/ui-sdk/stack.tsx";
import { Table } from "#components/ui/ui-sdk/table.tsx";
import { Tag } from "#components/ui/ui-sdk/tag.tsx";
import { Text } from "#components/ui/ui-sdk/text.tsx";
import { Textarea } from "#components/ui/ui-sdk/textarea.tsx";
import { Toast, Toaster } from "#components/ui/ui-sdk/toast.tsx";
import { Toolbar } from "#components/ui/ui-sdk/toolbar.tsx";
import { VisuallyHidden } from "#components/ui/ui-sdk/visually-hidden.tsx";
import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";
import { semanticRadii } from "@stylexblocks/ui/semantic-tokens/radii.stylex.ts";
import { accentPalette, greenPalette } from "@stylexblocks/ui/themes/palettes.ts";
import { fontSizes } from "@stylexblocks/ui/tokens/font-sizes.stylex.ts";
import { fontWeights } from "@stylexblocks/ui/tokens/font-weights.stylex.ts";
import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";
import { lineHeights } from "@stylexblocks/ui/tokens/line-heights.stylex.ts";
import { radii } from "@stylexblocks/ui/tokens/radii.stylex.ts";
import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";
import type { StyleOverrideProps } from "#lib/recipe-props.ts";

// Below this container width the artifact opens as a fullscreen dialog instead of a side pane.
const MOBILE_MAX_WIDTH = 767;
const NARROW_CONTAINER = `@container ai-chat (max-width: ${MOBILE_MAX_WIDTH}px)`;

interface ToolCallItem {
  name: "read" | "edit" | "bash";
  target: string;
  status: "complete" | "running";
  duration?: string;
  additions?: number;
  deletions?: number;
  node?: string;
}

interface ExtraUserMessage {
  id: string;
  text: string;
  mode: "ask" | "edit";
  time: string;
}

const ARTIFACT_TITLE = "Webhook Replay Protection: RFC & Rollout";
const ARTIFACT_SUBTITLE = "Specification · Updated just now";

const ARTIFACT_MARKDOWN = `# ${ARTIFACT_TITLE}

## Context

Our billing webhook receiver verifies HMAC-SHA256 signatures, but previously ignored the signed timestamp header. A captured delivery could be replayed indefinitely and still pass verification.

## Root Cause

Signature checking compared the raw digest without checking delivery age or using constant-time equality:

1. \`verifyWebhookSignature()\` hashed the raw payload body only
2. \`X-Webhook-Timestamp\` was never bound into the signed message
3. Replayed payloads older than 5 minutes returned \`200\`

## Implementation

The verifier now signs \`\${timestamp}.\${rawBody}\`, rejects timestamps outside a **300-second** skew window, and compares digests with \`timingSafeEqual\`.

- **Replay-safe** — stale deliveries fail fast with \`401\`
- **Timing-safe** — constant-time buffer comparison avoids side-channel leaks
- **Idempotent** — delivery IDs are cached in KV for 10 minutes

## Verification Matrix

| Case | Status |
|------|--------|
| Valid signature within 5 min window | 200 |
| Valid signature older than 5 min | 401 |
| Duplicate delivery ID | 200 (no-op) |
| Tampered payload or bad digest | 401 |

## Rollout Plan

1. Enable \`webhook_replay_guard\` in dry-run logging mode for 48 hours
2. Track \`webhooks.verify.stale\` and \`webhooks.verify.invalid\` counters
3. Enforce hard rejections once clock-skew false positives stay below **0.1%**
4. Remove the legacy body-only verifier after one billing cycle`;

const VERIFIER_CODE = `export async function verifyWebhookSignature(
  rawBody: string,
  headerSig: string | null,
  timestampHeader: string | null,
  secret: string,
): Promise<boolean> {
  if (!headerSig || !timestampHeader) return false;

  const sentAt = Number(timestampHeader);
  const skewSeconds = Math.abs(Date.now() / 1000 - sentAt);
  if (!Number.isFinite(sentAt) || skewSeconds > 300) {
    return false;
  }

  const expected = await hmacSha256Hex(secret, \`\${sentAt}.\${rawBody}\`);
  return timingSafeEqualHex(headerSig, expected);
}`;

const TEST_CODE = `describe("verifyWebhookSignature", () => {
  it("rejects valid signatures outside the 5-minute replay window", async () => {
    const body = JSON.stringify({ event: "invoice.paid", id: "evt_918" });
    const staleTs = String(Math.floor(Date.now() / 1000) - 600);
    const sig = await hmacSha256Hex(TEST_SECRET, \`\${staleTs}.\${body}\`);

    const ok = await verifyWebhookSignature(body, sig, staleTs, TEST_SECRET);
    expect(ok).toBe(false);
  });

  it("accepts a fresh signed payload", async () => {
    const body = JSON.stringify({ event: "invoice.paid", id: "evt_919" });
    const nowTs = String(Math.floor(Date.now() / 1000));
    const sig = await hmacSha256Hex(TEST_SECRET, \`\${nowTs}.\${body}\`);

    const ok = await verifyWebhookSignature(body, sig, nowTs, TEST_SECRET);
    expect(ok).toBe(true);
  });
});`;

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    containerName: "ai-chat",
    containerType: "inline-size",
    fontFamily: fonts.body,
    height: "100%",
    minHeight: 0,
    overflow: "hidden",
    position: "relative",
    width: "100%",
  },
  grow: {
    flexGrow: 1,
    minWidth: 0,
  },
  shrink0: {
    flexShrink: 0,
  },
  splitter: {
    flexGrow: 1,
    height: "100%",
    minHeight: 0,
    width: "100%",
  },
  chatPanel: {
    display: "flex",
    flexDirection: "column",
    height: "100%",
    minHeight: 0,
    minWidth: 0,
  },
  desktopOnly: {
    display: {
      default: "grid",
      [NARROW_CONTAINER]: "none",
    },
  },
  artifactPanel: {
    backgroundColor: semanticColors.bgSurface,
    display: {
      default: "flex",
      [NARROW_CONTAINER]: "none",
    },
    flexDirection: "column",
    height: "100%",
    minHeight: 0,
    minWidth: 0,
    overflow: "hidden",
  },
  chatColumn: {
    flexGrow: 1,
    height: "100%",
    minHeight: 0,
  },
  scrollerWrap: {
    flexGrow: 1,
    minHeight: 0,
    position: "relative",
  },
  scrollerContent: {
    gap: spacing._5,
    marginInline: "auto",
    maxWidth: "46rem",
    paddingBlock: spacing._6,
    paddingInline: spacing._5,
    width: "100%",
  },
  dateDivider: {
    paddingBlock: spacing._1,
    width: "100%",
  },
  dividerLine: {
    flexGrow: 1,
  },
  statusBanner: {
    paddingBlock: spacing._1,
    width: "100%",
  },
  mentionChip: {
    backgroundColor: semanticColors.blueSubtle,
    borderRadius: radii.sm,
    color: semanticColors.blueFg,
    display: "inline-block",
    fontWeight: fontWeights.medium,
    marginInlineEnd: spacing._1,
    paddingBlock: "0.0625rem",
    paddingInline: spacing._1_5,
  },
  prose: {
    color: semanticColors.fg,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.md,
  },
  proseParagraph: {
    lineHeight: lineHeights.md,
  },
  proseList: {
    marginBlock: 0,
    paddingInlineStart: spacing._5,
  },
  inlineCode: {
    backgroundColor: semanticColors.bgMuted,
    borderColor: semanticColors.border,
    borderRadius: radii.sm,
    borderStyle: "solid",
    borderWidth: "1px",
    fontFamily: fonts.mono,
    fontSize: "0.85em",
    paddingBlock: "0.0625rem",
    paddingInline: spacing._1,
  },
  tableWrap: {
    borderColor: semanticColors.border,
    borderRadius: radii.lg,
    borderStyle: "solid",
    borderWidth: "1px",
    overflow: "hidden",
    width: "100%",
  },
  codeBlockWrap: {
    maxWidth: "100%",
    width: "100%",
  },
  toolCallsCard: {
    backgroundColor: semanticColors.bgSurface,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    overflow: "hidden",
    width: "100%",
  },
  toolCallsTrigger: {
    alignItems: "center",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.interactionHover,
    },
    borderStyle: "none",
    color: semanticColors.fgMuted,
    cursor: "pointer",
    display: "flex",
    fontFamily: fonts.body,
    fontSize: fontSizes.xs,
    fontWeight: fontWeights.medium,
    gap: spacing._2,
    justifyContent: "space-between",
    paddingBlock: spacing._2,
    paddingInline: spacing._3,
    textAlign: "start",
    width: "100%",
  },
  toolCallsList: {
    borderTopColor: semanticColors.border,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    paddingBlock: spacing._2,
    paddingInline: spacing._3,
  },
  toolCallRow: {
    paddingBlock: spacing._0_5,
  },
  toolCallVerb: {
    textTransform: "lowercase",
  },
  toolCallMeta: {
    flexShrink: 0,
  },
  artifactCardButton: {
    alignItems: "center",
    backgroundColor: {
      default: semanticColors.bgSurface,
      ":hover": semanticColors.bgMuted,
    },
    borderColor: {
      default: semanticColors.border,
      ":hover": semanticColors.borderEmphasized,
    },
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fg,
    cursor: "pointer",
    display: "flex",
    fontFamily: fonts.body,
    gap: spacing._3,
    maxWidth: "22.5rem",
    paddingBlock: spacing._3,
    paddingInline: spacing._3_5,
    textAlign: "start",
    transitionDuration: "140ms",
    transitionProperty: "background-color, border-color",
    width: "100%",
  },
  artifactIconBox: {
    backgroundColor: semanticColors.bgMuted,
    borderRadius: radii.md,
    color: semanticColors.fgMuted,
  },
  composerShell: {
    borderTopColor: semanticColors.border,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    flexShrink: 0,
    paddingBlock: spacing._3,
    paddingInline: spacing._4,
  },
  composerCard: {
    backgroundColor: semanticColors.bgSurface,
    borderColor: {
      default: semanticColors.border,
      ":focus-within": semanticColors.borderEmphasized,
    },
    borderRadius: radii.xl,
    borderStyle: "solid",
    borderWidth: "1px",
    marginInline: "auto",
    maxWidth: "46rem",
    paddingBlock: spacing._2,
    paddingInline: spacing._3,
    transitionDuration: "140ms",
    transitionProperty: "border-color",
  },
  composerInput: {
    backgroundColor: "transparent",
    borderWidth: 0,
    boxShadow: "none",
    flexGrow: 1,
    minHeight: "2.5rem",
    outlineStyle: "none",
    paddingBlock: spacing._1,
    paddingInline: 0,
    resize: "none",
  },
  composerFooter: {
    paddingTop: spacing._1,
  },
  artifactToolbar: {
    alignItems: "center",
    backgroundColor: semanticColors.bgSurface,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    borderLeftWidth: 0,
    borderRadius: 0,
    borderRightWidth: 0,
    borderTopWidth: 0,
    display: "flex",
    flexShrink: 0,
    gap: spacing._2,
    justifyContent: "space-between",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._4,
    width: "100%",
  },
  artifactBodyScroll: {
    flexGrow: 1,
    minHeight: 0,
    overflowY: "auto",
    paddingBlock: spacing._6,
    paddingInline: spacing._6,
  },
  article: {
    marginInline: "auto",
    maxWidth: "42rem",
  },
  articleHeading: {
    marginBlock: 0,
  },
  articleSectionHeading: {
    marginBlockEnd: 0,
    marginBlockStart: spacing._2,
  },
  dialogContent: {
    overflow: "hidden",
  },
  dialogHeaderRow: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    flexShrink: 0,
    paddingBlock: spacing._3,
    paddingInline: spacing._4,
  },
  chevronIcon: {
    transitionDuration: "160ms",
    transitionProperty: "transform",
  },
  chevronOpen: {
    transform: "rotate(90deg)",
  },
  mutedIcon: {
    color: semanticColors.fgMuted,
    flexShrink: 0,
  },
  checkIcon: {
    color: semanticColors.greenFg,
    flexShrink: 0,
  },
});

function DocumentIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <polyline points="14 2 14 8 20 8" />
      <line x1="8" y1="13" x2="16" y2="13" />
      <line x1="8" y1="17" x2="13" y2="17" />
    </svg>
  );
}

function CopyIcon() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <rect x="9" y="9" width="13" height="13" rx="2" />
      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
    </svg>
  );
}

function ShareIcon() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <circle cx="18" cy="5" r="3" />
      <circle cx="6" cy="12" r="3" />
      <circle cx="18" cy="19" r="3" />
      <line x1="8.59" y1="13.51" x2="15.42" y2="17.49" />
      <line x1="15.41" y1="6.51" x2="8.59" y2="10.49" />
    </svg>
  );
}

function CloseIcon() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <line x1="18" y1="6" x2="6" y2="18" />
      <line x1="6" y1="6" x2="18" y2="18" />
    </svg>
  );
}

function MentionIcon() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <circle cx="12" cy="12" r="4" />
      <path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-3.92 7.94" />
    </svg>
  );
}

function AttachIcon() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" />
    </svg>
  );
}

function ChevronRightIcon({ rotated }: { rotated?: boolean }) {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      {...stylex.props(styles.chevronIcon, rotated && styles.chevronOpen)}
    >
      <polyline points="9 18 15 12 9 6" />
    </svg>
  );
}

function ChevronDownIcon() {
  return (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <polyline points="6 9 12 15 18 9" />
    </svg>
  );
}

function CheckCircleIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" {...stylex.props(styles.checkIcon)}>
      <circle cx="12" cy="12" r="9" />
      <path d="m9 12 2 2 4-4" />
    </svg>
  );
}

function ArrowUpIcon() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <line x1="12" y1="19" x2="12" y2="5" />
      <polyline points="5 12 12 5 19 12" />
    </svg>
  );
}

function MoreDotsIcon() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <circle cx="5" cy="12" r="1.75" />
      <circle cx="12" cy="12" r="1.75" />
      <circle cx="19" cy="12" r="1.75" />
    </svg>
  );
}

function ToolCallsBlock({
  calls,
  defaultOpen = false,
}: {
  calls: ToolCallItem[];
  defaultOpen?: boolean;
}) {
  const [open, setOpen] = useState(defaultOpen);
  const running = calls.some((c) => c.status === "running");
  const summary = running
    ? `Running ${calls[0]?.name} on ${calls[0]?.target}`
    : `${calls.length} tool ${calls.length === 1 ? "call" : "calls"} completed`;

  return (
    <Collapsible.Root open={open} onOpenChange={setOpen}>
      <div {...stylex.props(styles.toolCallsCard)}>
        <Collapsible.Trigger
          render={<button type="button" {...stylex.props(styles.toolCallsTrigger)} />}
        >
          <HStack render={<span />} gap="2">
            {running ? <Spinner size="xs" /> : <CheckCircleIcon />}
            <span>{summary}</span>
          </HStack>
          <ChevronRightIcon rotated={open} />
        </Collapsible.Trigger>
        <Collapsible.Panel>
          <VStack gap="1" style={styles.toolCallsList}>
            {calls.map((call, idx) => (
              <HStack
                key={`${call.name}-${call.target}-${idx}`}
                gap="2"
                justify="between"
                style={styles.toolCallRow}
              >
                <HStack gap="2">
                  {call.status === "running" ? <Spinner size="xs" /> : <CheckCircleIcon />}
                  <Text
                    render={<span />}
                    variant="mono"
                    size="xs"
                    tone="muted"
                    weight="semibold"
                    style={styles.toolCallVerb}
                  >
                    {call.name}
                  </Text>
                  <Text render={<span />} variant="mono" size="xs" truncate="true">
                    {call.target}
                  </Text>
                </HStack>
                <HStack gap="1.5" style={styles.toolCallMeta}>
                  {call.additions != null ? (
                    <Text
                      render={<span />}
                      variant="mono"
                      size="2xs"
                      tone="success"
                      weight="medium"
                    >
                      +{call.additions}
                    </Text>
                  ) : null}
                  {call.deletions != null ? (
                    <Text
                      render={<span />}
                      variant="mono"
                      size="2xs"
                      tone="error"
                      weight="medium"
                    >
                      -{call.deletions}
                    </Text>
                  ) : null}
                  {call.node ? (
                    <Badge variant="subtle" size="sm">
                      {call.node}
                    </Badge>
                  ) : null}
                  {call.duration ? (
                    <Text render={<span />} variant="mono" size="2xs" tone="subtle">
                      {call.duration}
                    </Text>
                  ) : null}
                </HStack>
              </HStack>
            ))}
          </VStack>
        </Collapsible.Panel>
      </div>
    </Collapsible.Root>
  );
}

function CodeSnippet({
  title,
  code,
  onCopy,
}: {
  title: string;
  code: string;
  onCopy: (code: string, label: string) => void;
}) {
  return (
    <div {...stylex.props(styles.codeBlockWrap)}>
      <CodeBlock.Root size="sm">
        <CodeBlock.Header>
          <CodeBlock.Title>{title}</CodeBlock.Title>
          <CodeBlock.Control>
            <Button
              variant="ghost"
              size="xs"
              aria-label={`Copy ${title}`}
              onClick={() => onCopy(code, title)}
            >
              <CopyIcon />
              Copy
            </Button>
          </CodeBlock.Control>
        </CodeBlock.Header>
        <CodeBlock.Content>
          <CodeBlock.Code>
            <CodeBlock.CodeText>{code}</CodeBlock.CodeText>
          </CodeBlock.Code>
        </CodeBlock.Content>
      </CodeBlock.Root>
    </div>
  );
}

function ArtifactBody() {
  return (
    <div {...stylex.props(styles.artifactBodyScroll)}>
      <VStack render={<article />} gap="4" style={styles.article}>
        <Heading size="xl" style={styles.articleHeading}>
          {ARTIFACT_TITLE}
        </Heading>

        <VStack gap="2.5" style={styles.prose}>
          <Heading render={<h3 />} size="md" style={styles.articleSectionHeading}>
            Context
          </Heading>
          <Text style={styles.proseParagraph}>
            Our billing webhook receiver verifies HMAC-SHA256 signatures, but previously ignored the
            signed timestamp header. A captured delivery could be replayed indefinitely and still
            pass verification.
          </Text>

          <Heading render={<h3 />} size="md" style={styles.articleSectionHeading}>
            Root Cause
          </Heading>
          <Text style={styles.proseParagraph}>
            Signature checking compared the raw digest without checking delivery age or using
            constant-time equality:
          </Text>
          <VStack render={<ol />} gap="1" style={styles.proseList}>
            <li>
              <code {...stylex.props(styles.inlineCode)}>verifyWebhookSignature()</code> hashed the
              raw payload body only
            </li>
            <li>
              <code {...stylex.props(styles.inlineCode)}>X-Webhook-Timestamp</code> was never bound
              into the signed message
            </li>
            <li>
              Replayed payloads older than 5 minutes returned{" "}
              <code {...stylex.props(styles.inlineCode)}>200</code>
            </li>
          </VStack>

          <Heading render={<h3 />} size="md" style={styles.articleSectionHeading}>
            Implementation
          </Heading>
          <Text style={styles.proseParagraph}>
            The verifier now signs{" "}
            <code {...stylex.props(styles.inlineCode)}>{`\${timestamp}.\${rawBody}`}</code>, rejects
            timestamps outside a <strong>300-second</strong> skew window, and compares digests with{" "}
            <code {...stylex.props(styles.inlineCode)}>timingSafeEqual</code>.
          </Text>
          <VStack render={<ul />} gap="1.5" style={styles.proseList}>
            <li>
              <strong>Replay-safe</strong> — stale deliveries fail fast with{" "}
              <code {...stylex.props(styles.inlineCode)}>401</code>
            </li>
            <li>
              <strong>Timing-safe</strong> — constant-time buffer comparison avoids side-channel
              leaks
            </li>
            <li>
              <strong>Idempotent</strong> — delivery IDs are cached in KV for 10 minutes
            </li>
          </VStack>

          <Heading render={<h3 />} size="md" style={styles.articleSectionHeading}>
            Verification Matrix
          </Heading>
          <Text style={styles.proseParagraph}>Every replay and signature edge case is tested:</Text>
          <div {...stylex.props(styles.tableWrap)}>
            <Table.Root size="sm">
              <Table.Header>
                <Table.Row>
                  <Table.ColumnHeader>Case</Table.ColumnHeader>
                  <Table.ColumnHeader>Status</Table.ColumnHeader>
                </Table.Row>
              </Table.Header>
              <Table.Body>
                <Table.Row>
                  <Table.Cell>Valid signature within 5 min window</Table.Cell>
                  <Table.Cell>
                    <code {...stylex.props(styles.inlineCode)}>200</code>
                  </Table.Cell>
                </Table.Row>
                <Table.Row>
                  <Table.Cell>Valid signature older than 5 min</Table.Cell>
                  <Table.Cell>
                    <code {...stylex.props(styles.inlineCode)}>401</code>
                  </Table.Cell>
                </Table.Row>
                <Table.Row>
                  <Table.Cell>Duplicate delivery ID</Table.Cell>
                  <Table.Cell>
                    <code {...stylex.props(styles.inlineCode)}>200</code> (no-op)
                  </Table.Cell>
                </Table.Row>
                <Table.Row>
                  <Table.Cell>Tampered payload or bad digest</Table.Cell>
                  <Table.Cell>
                    <code {...stylex.props(styles.inlineCode)}>401</code>
                  </Table.Cell>
                </Table.Row>
              </Table.Body>
            </Table.Root>
          </div>

          <Heading render={<h3 />} size="md" style={styles.articleSectionHeading}>
            Rollout Plan
          </Heading>
          <VStack render={<ol />} gap="1" style={styles.proseList}>
            <li>
              Enable <code {...stylex.props(styles.inlineCode)}>webhook_replay_guard</code> in
              dry-run logging mode for 48 hours
            </li>
            <li>
              Track <code {...stylex.props(styles.inlineCode)}>webhooks.verify.stale</code> and{" "}
              <code {...stylex.props(styles.inlineCode)}>webhooks.verify.invalid</code> counters
            </li>
            <li>
              Enforce hard rejections once clock-skew false positives stay below{" "}
              <strong>0.1%</strong>
            </li>
            <li>Remove the legacy body-only verifier after one billing cycle</li>
          </VStack>
        </VStack>
      </VStack>
    </div>
  );
}

export interface AiChatProps extends StyleOverrideProps {
  /** Whether the desktop artifact panel starts open. */
  defaultArtifactOpen?: boolean;
}

/**
 * AiChat — split-pane AI chat conversation with mixed inline rich content
 * (prose, code blocks, collapsible tool-call logs, artifact cards) beside a
 * resizable artifact panel that falls back to a full-screen dialog on narrow
 * containers.
 */
export function AiChat({ defaultArtifactOpen = true, style }: AiChatProps) {
  const queue = useMemo(() => Toast.createToaster(), []);
  const rootRef = useRef<HTMLDivElement>(null);
  const [composerMode, setComposerMode] = useState<"ask" | "edit">("ask");
  const [draft, setDraft] = useState("");
  const [extraMessages, setExtraMessages] = useState<ExtraUserMessage[]>([]);
  const [version, setVersion] = useState<"v2" | "v1">("v2");
  const [isArtifactOpen, setIsArtifactOpen] = useState(defaultArtifactOpen);
  const [isArtifactDialogOpen, setIsArtifactDialogOpen] = useState(false);

  const notify = useCallback(
    (title: string, description?: string) => {
      queue.info(title, description ? { description } : undefined);
    },
    [queue],
  );

  const copyText = useCallback(
    (text: string, label: string) => {
      void navigator.clipboard
        ?.writeText(text)
        .then(() => queue.success(`Copied ${label}`))
        .catch(() => queue.info(`Copied ${label}`));
    },
    [queue],
  );

  const openArtifact = () => {
    const width = rootRef.current?.offsetWidth ?? Infinity;
    if (width <= MOBILE_MAX_WIDTH) {
      setIsArtifactDialogOpen(true);
    } else {
      setIsArtifactOpen(true);
    }
  };

  const handleSubmit = () => {
    const trimmed = draft.trim();
    if (!trimmed) {
      notify("Demo: your message would send here");
      return;
    }
    const now = new Date().toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
    setExtraMessages((prev) => [
      ...prev,
      { id: String(Date.now()), text: trimmed, mode: composerMode, time: now },
    ]);
    setDraft("");
    queue.success("Message sent", {
      description: `Mode: ${composerMode === "ask" ? "Ask" : "Edit"}`,
    });
  };

  const chatColumn = (
    <VStack gap="0" style={styles.chatColumn}>
      <VStack gap="0" style={styles.scrollerWrap}>
        <MessageScroller.Provider autoScroll defaultScrollPosition="start">
          <MessageScroller.Root>
            <MessageScroller.Viewport>
              <MessageScroller.Content style={styles.scrollerContent}>
                <MessageScroller.Item>
                  <HStack gap="3" justify="center" style={styles.dateDivider}>
                    <Separator style={styles.dividerLine} />
                    <Text render={<span />} size="xs" tone="subtle" weight="medium">
                      Today
                    </Text>
                    <Separator style={styles.dividerLine} />
                  </HStack>
                </MessageScroller.Item>

                {/* User message: file tokens + mention */}
                <MessageScroller.Item scrollAnchor>
                  <Message.Root align="end">
                    <Message.Content>
                      <HStack gap="1.5" wrap="wrap" justify="end">
                        <Tag.Root size="sm" variant="surface">
                          <Tag.Label>webhooks/verify.ts</Tag.Label>
                        </Tag.Root>
                        <Tag.Root size="sm" variant="surface">
                          <Tag.Label>webhooks/route.ts</Tag.Label>
                        </Tag.Root>
                      </HStack>
                      <Bubble.Root variant="subtle" align="end" palette={accentPalette}>
                        <Bubble.Content>
                          <span {...stylex.props(styles.mentionChip)}>@Agent</span>
                          Can you audit our billing webhook verification? Replayed deliveries from
                          last week still seem to pass the HMAC check.
                        </Bubble.Content>
                      </Bubble.Root>
                      <Message.Footer>2:08 PM</Message.Footer>
                    </Message.Content>
                  </Message.Root>
                </MessageScroller.Item>

                {/* Assistant message: tool calls + prose + code block */}
                <MessageScroller.Item>
                  <Message.Root align="start">
                    <Message.Content>
                      <Bubble.Root variant="ghost" align="start">
                        <Bubble.Content>
                          Checking the webhook handler and signature helper now to see how the
                          timestamp header is validated.
                        </Bubble.Content>
                      </Bubble.Root>

                      <ToolCallsBlock
                        defaultOpen
                        calls={[
                          { name: "read", target: "webhooks/verify.ts", status: "complete", duration: "29ms" },
                          { name: "read", target: "webhooks/route.ts", status: "complete", duration: "34ms" },
                          {
                            name: "bash",
                            target: 'rg "X-Webhook-Timestamp" src/',
                            status: "complete",
                            duration: "92ms",
                            node: "worker:edge-dev",
                          },
                        ]}
                      />

                      <Bubble.Root variant="ghost" align="start">
                        <Bubble.Content>
                          <VStack gap="2.5" style={styles.prose}>
                            <Text style={styles.proseParagraph}>
                              Found it. In{" "}
                              <code {...stylex.props(styles.inlineCode)}>webhooks/verify.ts</code>,
                              the HMAC digest is computed over the raw body alone, and{" "}
                              <code {...stylex.props(styles.inlineCode)}>X-Webhook-Timestamp</code>{" "}
                              is never checked for freshness.
                            </Text>
                            <Text style={styles.proseParagraph}>
                              Here&apos;s what happens on a replay:
                            </Text>
                            <VStack render={<ol />} gap="1" style={styles.proseList}>
                              <li>An old signed delivery arrives hours later</li>
                              <li>
                                <code {...stylex.props(styles.inlineCode)}>hmacSha256Hex()</code>{" "}
                                matches the body digest
                              </li>
                              <li>
                                The route returns{" "}
                                <code {...stylex.props(styles.inlineCode)}>200</code> and
                                re-processes the invoice event
                              </li>
                            </VStack>
                            <Text style={styles.proseParagraph}>
                              We should bind the timestamp into the signed payload, enforce a
                              300-second window, and compare in constant time:
                            </Text>
                          </VStack>
                        </Bubble.Content>
                      </Bubble.Root>

                      <CodeSnippet title="webhooks/verify.ts" code={VERIFIER_CODE} onCopy={copyText} />

                      <ToolCallsBlock
                        calls={[
                          {
                            name: "edit",
                            target: "webhooks/verify.ts",
                            status: "complete",
                            duration: "74ms",
                            additions: 11,
                            deletions: 3,
                          },
                        ]}
                      />

                      <Message.Footer>Assistant · 2:09 PM</Message.Footer>
                    </Message.Content>
                  </Message.Root>
                </MessageScroller.Item>

                {/* User multi-bubble group */}
                <MessageScroller.Item scrollAnchor>
                  <Message.Root align="end">
                    <Message.Content>
                      <Bubble.Group>
                        <Bubble.Root variant="subtle" align="end" palette={accentPalette}>
                          <Bubble.Content>Good catch — signing the timestamp fixes both issues.</Bubble.Content>
                        </Bubble.Root>
                        <Bubble.Root variant="subtle" align="end" palette={accentPalette}>
                          <Bubble.Content>
                            Can you add unit tests for stale timestamps and bad digests?
                          </Bubble.Content>
                        </Bubble.Root>
                      </Bubble.Group>
                      <Message.Footer>2:10 PM · Delivered</Message.Footer>
                    </Message.Content>
                  </Message.Root>
                </MessageScroller.Item>

                {/* Assistant test results + code */}
                <MessageScroller.Item>
                  <Message.Root align="start">
                    <Message.Content>
                      <ToolCallsBlock
                        defaultOpen
                        calls={[
                          { name: "read", target: "webhooks/verify.test.ts", status: "complete", duration: "24ms" },
                          {
                            name: "edit",
                            target: "webhooks/verify.test.ts",
                            status: "complete",
                            duration: "88ms",
                            additions: 22,
                            deletions: 0,
                          },
                          {
                            name: "bash",
                            target: "bun test webhooks/verify.test.ts",
                            status: "complete",
                            duration: "1.4s",
                            node: "worker:edge-dev",
                          },
                        ]}
                      />

                      <Bubble.Root variant="ghost" align="start">
                        <Bubble.Content>
                          <VStack gap="2.5" style={styles.prose}>
                            <Text style={styles.proseParagraph}>
                              Added replay and tamper coverage. All <strong>4 specs</strong> pass:
                            </Text>
                            <div {...stylex.props(styles.tableWrap)}>
                              <Table.Root size="sm">
                                <Table.Header>
                                  <Table.Row>
                                    <Table.ColumnHeader>Spec</Table.ColumnHeader>
                                    <Table.ColumnHeader>Result</Table.ColumnHeader>
                                  </Table.Row>
                                </Table.Header>
                                <Table.Body>
                                  {[
                                    "Accepts fresh signed delivery",
                                    "Rejects valid signature older than 5 min",
                                    "Deduplicates repeated delivery IDs",
                                    "Rejects tampered payload body",
                                  ].map((row) => (
                                    <Table.Row key={row}>
                                      <Table.Cell>{row}</Table.Cell>
                                      <Table.Cell>
                                        <Badge variant="subtle" size="sm" palette={greenPalette}>
                                          Pass
                                        </Badge>
                                      </Table.Cell>
                                    </Table.Row>
                                  ))}
                                </Table.Body>
                              </Table.Root>
                            </div>
                          </VStack>
                        </Bubble.Content>
                      </Bubble.Root>

                      <CodeSnippet title="webhooks/verify.test.ts" code={TEST_CODE} onCopy={copyText} />

                      <Message.Footer>2:11 PM</Message.Footer>
                    </Message.Content>
                  </Message.Root>
                </MessageScroller.Item>

                <MessageScroller.Item>
                  <Text size="xs" tone="subtle" align="center" style={styles.statusBanner}>
                    Workspace synced · 2 files updated
                  </Text>
                </MessageScroller.Item>

                {/* User asks for spec artifact */}
                <MessageScroller.Item scrollAnchor>
                  <Message.Root align="end">
                    <Message.Content>
                      <Bubble.Root variant="subtle" align="end" palette={accentPalette}>
                        <Bubble.Content>
                          Before we ship this, can you put together a short RFC with the rollout
                          plan for the billing team?
                        </Bubble.Content>
                      </Bubble.Root>
                      <Message.Footer>2:13 PM</Message.Footer>
                    </Message.Content>
                  </Message.Root>
                </MessageScroller.Item>

                {/* Assistant artifact card */}
                <MessageScroller.Item>
                  <Message.Root align="start">
                    <Message.Content>
                      <Bubble.Root variant="ghost" align="start">
                        <Bubble.Content>
                          <VStack gap="2.5" style={styles.prose}>
                            <Text style={styles.proseParagraph}>
                              Drafted an RFC covering the root cause, the timestamped signature
                              change, and the verification matrix.
                            </Text>
                            <Text style={styles.proseParagraph}>
                              Open it below to inspect or copy for the PR description.
                            </Text>
                          </VStack>
                        </Bubble.Content>
                      </Bubble.Root>

                      <button
                        type="button"
                        onClick={openArtifact}
                        aria-label={`Open ${ARTIFACT_TITLE}`}
                        {...stylex.props(styles.artifactCardButton)}
                      >
                        <Square render={<span />} size="sm" style={styles.artifactIconBox}>
                          <DocumentIcon />
                        </Square>
                        <VStack render={<span />} gap="0.5" style={styles.grow}>
                          <Text render={<span />} size="sm" weight="semibold" truncate="true">
                            {ARTIFACT_TITLE}
                          </Text>
                          <Text render={<span />} size="xs" tone="muted">
                            Specification · {version}
                          </Text>
                        </VStack>
                        <span {...stylex.props(styles.mutedIcon)}>
                          <ChevronRightIcon />
                        </span>
                      </button>
                      <Message.Footer>2:14 PM</Message.Footer>
                    </Message.Content>
                  </Message.Root>
                </MessageScroller.Item>

                {/* User follow-up */}
                <MessageScroller.Item scrollAnchor>
                  <Message.Root align="end">
                    <Message.Content>
                      <Bubble.Root variant="subtle" align="end" palette={accentPalette}>
                        <Bubble.Content>
                          Nice. Can you include a dry-run logging phase before hard rejections?
                        </Bubble.Content>
                      </Bubble.Root>
                      <Message.Footer>2:15 PM · Delivered</Message.Footer>
                    </Message.Content>
                  </Message.Root>
                </MessageScroller.Item>

                {/* Assistant in-progress edit */}
                <MessageScroller.Item>
                  <Message.Root align="start">
                    <Message.Content>
                      <Bubble.Root variant="ghost" align="start">
                        <Bubble.Content>
                          Adding a 48-hour dry-run phase under{" "}
                          <code {...stylex.props(styles.inlineCode)}>webhook_replay_guard</code> and
                          the skew alert thresholds to the RFC now.
                        </Bubble.Content>
                      </Bubble.Root>

                      <ToolCallsBlock
                        calls={[
                          {
                            name: "edit",
                            target: "docs/rfc-webhook-replay.md",
                            status: "running",
                            node: "worker:edge-dev",
                          },
                        ]}
                      />

                      <Message.Footer>2:15 PM</Message.Footer>
                    </Message.Content>
                  </Message.Root>
                </MessageScroller.Item>

                {/* Newly sent user turns */}
                {extraMessages.map((msg) => (
                  <MessageScroller.Item key={msg.id} scrollAnchor>
                    <Message.Root align="end">
                      <Message.Content>
                        <Bubble.Root variant="subtle" align="end" palette={accentPalette}>
                          <Bubble.Content>{msg.text}</Bubble.Content>
                        </Bubble.Root>
                        <Message.Footer>
                          {msg.time} · {msg.mode === "ask" ? "Ask" : "Edit"}
                        </Message.Footer>
                      </Message.Content>
                    </Message.Root>
                  </MessageScroller.Item>
                ))}
              </MessageScroller.Content>
            </MessageScroller.Viewport>
            <MessageScroller.Button direction="end" />
          </MessageScroller.Root>
        </MessageScroller.Provider>
      </VStack>

      {/* Composer */}
      <div {...stylex.props(styles.composerShell)}>
        <VStack gap="1.5" style={styles.composerCard}>
          <HStack align="start" gap="2">
            <Textarea
              aria-label="Message composer"
              rows={2}
              variant="subtle"
              size="sm"
              value={draft}
              onChange={(e) => setDraft(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  handleSubmit();
                }
              }}
              placeholder={composerMode === "ask" ? "Ask anything..." : "Describe your edit..."}
              style={styles.composerInput}
            />
            <HStack gap="0.5" style={styles.shrink0}>
              <IconButton
                variant="ghost"
                size="xs"
                aria-label="Mention"
                onClick={() => notify("Demo: mention picker would open here")}
              >
                <MentionIcon />
              </IconButton>
              <IconButton
                variant="ghost"
                size="xs"
                aria-label="Attach"
                onClick={() => notify("Demo: file picker would open here")}
              >
                <AttachIcon />
              </IconButton>
            </HStack>
          </HStack>
          <HStack justify="between" style={styles.composerFooter}>
            <Menu.Root size="sm">
              <Menu.Trigger render={<Button variant="ghost" size="xs" />}>
                {composerMode === "ask" ? "Ask" : "Edit"}
                <ChevronDownIcon />
              </Menu.Trigger>
              <Menu.Content side="top" align="start">
                <Menu.RadioGroup
                  value={composerMode}
                  onValueChange={(next) => setComposerMode(next as "ask" | "edit")}
                >
                  <Menu.RadioItem value="ask">
                    <Menu.ItemText>Ask</Menu.ItemText>
                    <Menu.ItemIndicator />
                  </Menu.RadioItem>
                  <Menu.RadioItem value="edit">
                    <Menu.ItemText>Edit</Menu.ItemText>
                    <Menu.ItemIndicator />
                  </Menu.RadioItem>
                </Menu.RadioGroup>
              </Menu.Content>
            </Menu.Root>

            <Button
              variant="solid"
              size="xs"
              palette={accentPalette}
              aria-label="Send message"
              onClick={handleSubmit}
            >
              <ArrowUpIcon />
              Send
            </Button>
          </HStack>
        </VStack>
      </div>
    </VStack>
  );

  const artifactToolbar = (
    <Toolbar.Root variant="plain" size="sm" aria-label="Artifact actions" style={styles.artifactToolbar}>
      <HStack gap="2.5">
        <span {...stylex.props(styles.mutedIcon)}>
          <DocumentIcon />
        </span>
        <VStack gap="0.5" style={styles.grow}>
          <Text render={<span />} size="sm" weight="semibold" truncate="true">
            {ARTIFACT_TITLE}
          </Text>
          <Text render={<span />} size="xs" tone="muted">
            {ARTIFACT_SUBTITLE}
          </Text>
        </VStack>
      </HStack>
      <HStack gap="1" style={styles.shrink0}>
        <Menu.Root size="sm">
          <Menu.Trigger render={<Button variant="ghost" size="xs" />}>
            {version}
            <ChevronDownIcon />
          </Menu.Trigger>
          <Menu.Content align="end">
            <Menu.RadioGroup
              value={version}
              onValueChange={(v) => {
                const next = v as "v2" | "v1";
                setVersion(next);
                notify(next === "v2" ? "Viewing v2 (current)" : "Demo: version 1 snapshot selected");
              }}
            >
              <Menu.RadioItem value="v2">
                <Menu.ItemText>v2 (current)</Menu.ItemText>
                <Menu.ItemIndicator />
              </Menu.RadioItem>
              <Menu.RadioItem value="v1">
                <Menu.ItemText>v1</Menu.ItemText>
                <Menu.ItemIndicator />
              </Menu.RadioItem>
            </Menu.RadioGroup>
          </Menu.Content>
        </Menu.Root>
        <IconButton
          variant="ghost"
          size="xs"
          aria-label="Copy document"
          onClick={() => copyText(ARTIFACT_MARKDOWN, "specification")}
        >
          <CopyIcon />
        </IconButton>
        <IconButton
          variant="ghost"
          size="xs"
          aria-label="Share document"
          onClick={() => notify("Demo: sharing would start here")}
        >
          <ShareIcon />
        </IconButton>
        <IconButton
          variant="ghost"
          size="xs"
          aria-label="Close document"
          onClick={() => setIsArtifactOpen(false)}
        >
          <CloseIcon />
        </IconButton>
      </HStack>
    </Toolbar.Root>
  );

  return (
    <VStack ref={rootRef} gap="0" style={[styles.root, style]}>
      <VisuallyHidden render={<h1 />}>Chat</VisuallyHidden>

      {isArtifactOpen ? (
        <Splitter.Root defaultSize={[52, 48]} minSize={30} style={styles.splitter}>
          <Splitter.Panel style={styles.chatPanel}>{chatColumn}</Splitter.Panel>
          <Splitter.ResizeTrigger
            aria-label="Resize artifact panel"
            style={styles.desktopOnly}
          />
          <Splitter.Panel style={styles.artifactPanel}>
            {artifactToolbar}
            <ArtifactBody />
          </Splitter.Panel>
        </Splitter.Root>
      ) : (
        chatColumn
      )}

      {/* Narrow-container artifact modal */}
      <Dialog.Root
        open={isArtifactDialogOpen}
        onOpenChange={setIsArtifactDialogOpen}
        size="full"
      >
        <Dialog.Backdrop />
        <Dialog.Content style={styles.dialogContent}>
          <HStack gap="2" justify="between" style={styles.dialogHeaderRow}>
            <VStack gap="0.5" style={styles.grow}>
              <Dialog.Title>{ARTIFACT_TITLE}</Dialog.Title>
              <Text render={<span />} size="xs" tone="muted">
                {ARTIFACT_SUBTITLE}
              </Text>
            </VStack>
            <HStack gap="1" style={styles.shrink0}>
              <Menu.Root size="sm">
                <Menu.Trigger
                  render={<IconButton variant="ghost" size="xs" aria-label="Document actions" />}
                >
                  <MoreDotsIcon />
                </Menu.Trigger>
                <Menu.Content align="end">
                  <Menu.Group>
                    <Menu.GroupLabel>Version</Menu.GroupLabel>
                    <Menu.Item onSelect={() => setVersion("v2")}>
                      <Menu.ItemText>v2 (current)</Menu.ItemText>
                    </Menu.Item>
                    <Menu.Item onSelect={() => setVersion("v1")}>
                      <Menu.ItemText>v1</Menu.ItemText>
                    </Menu.Item>
                  </Menu.Group>
                  <Menu.Separator />
                  <Menu.Item onSelect={() => copyText(ARTIFACT_MARKDOWN, "specification")}>
                    <Menu.ItemText>Copy</Menu.ItemText>
                  </Menu.Item>
                  <Menu.Item onSelect={() => notify("Demo: sharing would start here")}>
                    <Menu.ItemText>Share</Menu.ItemText>
                  </Menu.Item>
                </Menu.Content>
              </Menu.Root>
              <Dialog.Close render={<IconButton variant="ghost" size="xs" aria-label="Close" />}>
                <CloseIcon />
              </Dialog.Close>
            </HStack>
          </HStack>
          <ArtifactBody />
        </Dialog.Content>
      </Dialog.Root>

      <Toaster toaster={queue} />
    </VStack>
  );
}
```

Credit: Inspired by [AI Chat Conversation](https://astryx.atmeta.com/playground?template=ai-chat) from Astryx (MIT License · Copyright (c) 2026 Meta Platforms, Inc.)
