Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

Chat template cleanup (#2995)

Kenton Quatman013d5d43c9d4
diff --git a/apps/docsite/src/components/templateComponents.ts b/apps/docsite/src/components/templateComponents.ts
index 9fc03e055f..228539bdd3 100644
--- a/apps/docsite/src/components/templateComponents.ts
+++ b/apps/docsite/src/components/templateComponents.ts
@@ -22,10 +22,6 @@ export const TEMPLATE_COMPONENTS: Record<
'ai-chat': lazy(
() => import('../../../../packages/cli/templates/pages/ai-chat/page'),
),
- 'ai-chat-artifact': lazy(
- () =>
- import('../../../../packages/cli/templates/pages/ai-chat-artifact/page'),
- ),
'ai-chat-landing': lazy(
() =>
import('../../../../packages/cli/templates/pages/ai-chat-landing/page'),
@@ -136,15 +132,11 @@ export const TEMPLATE_COMPONENTS: Record<
),
'table-page-heatmap-status': lazy(
() =>
- import(
- '../../../../packages/cli/templates/pages/table-page-heatmap-status/page'
- ),
+ import('../../../../packages/cli/templates/pages/table-page-heatmap-status/page'),
),
'table-page-shoe-store-heatmap': lazy(
() =>
- import(
- '../../../../packages/cli/templates/pages/table-page-shoe-store-heatmap/page'
- ),
+ import('../../../../packages/cli/templates/pages/table-page-shoe-store-heatmap/page'),
),
};
diff --git a/packages/cli/templates/pages/ai-chat-artifact/page.tsx b/packages/cli/templates/pages/ai-chat-artifact/page.tsx
deleted file mode 100644
index b90b1b59ca..0000000000
--- a/packages/cli/templates/pages/ai-chat-artifact/page.tsx
+++ /dev/null
@@ -1,604 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-'use client';
-
-import {useRef, useState} from 'react';
-import * as stylex from '@stylexjs/stylex';
-import {spacingVars} from '@xds/core/theme/tokens.stylex';
-
-import {
- HStack,
- VStack,
- StackItem,
- Layout,
- LayoutContent,
-} from '@xds/core/Layout';
-import {Text, Heading} from '@xds/core/Text';
-import {
- ChatComposer,
- ChatComposerInput,
- ChatLayout,
- ChatMessage,
- ChatMessageBubble,
- ChatMessageList,
- ChatMessageMetadata,
- ChatSystemMessage,
-} from '@xds/core/Chat';
-import {Avatar} from '@xds/core/Avatar';
-import {Card} from '@xds/core/Card';
-import {ClickableCard} from '@xds/core/ClickableCard';
-import {Section} from '@xds/core/Section';
-import {Markdown} from '@xds/core/Markdown';
-import {Timestamp} from '@xds/core/Timestamp';
-import {Button} from '@xds/core/Button';
-import {ToggleButton} from '@xds/core/ToggleButton';
-import {Icon} from '@xds/core/Icon';
-import {Dialog, DialogHeader} from '@xds/core/Dialog';
-import {DropdownMenu} from '@xds/core/DropdownMenu';
-import {MoreMenu} from '@xds/core/MoreMenu';
-import {Toolbar} from '@xds/core/Toolbar';
-import {useResizable, ResizeHandle} from '@xds/core/Resizable';
-
-import {
- DocumentTextIcon,
- ClipboardDocumentIcon,
- ShareIcon,
- AtSymbolIcon,
- PaperClipIcon,
- CodeBracketIcon,
- XMarkIcon,
- ChevronRightIcon,
-} from '@heroicons/react/24/outline';
-
-// Collapse the split-pane to a single chat column at/below this width. Single
-// source of truth shared by the CSS container query and the JS check in
-// openArtifact, so the two can't drift. A container query (not a viewport one)
-// so it reacts to the width the template is actually given, e.g. inside a
-// constrained preview pane.
-const MOBILE_MAX_WIDTH = 767;
-const MOBILE = `@container artifact (max-width: ${MOBILE_MAX_WIDTH}px)`;
-
-const styles = stylex.create({
- root: {
- height: '100dvh',
- width: '100%',
- containerType: 'inline-size',
- containerName: 'artifact',
- },
- artifactPanel: {
- flex: 1,
- overflow: 'hidden',
- flexDirection: 'column',
- display: {
- default: 'flex',
- [MOBILE]: 'none',
- },
- },
- resizeHandle: {
- display: {
- default: 'flex',
- [MOBILE]: 'none',
- },
- },
- // Only the top margin remains here — the width cap uses the maxWidth prop.
- artifactCard: {
- marginBlockStart: spacingVars['--spacing-2'],
- },
- artifactScroll: {
- flex: 1,
- overflowY: 'auto',
- },
- chatLayoutFill: {
- height: '100%',
- },
- articleBody: {
- maxWidth: 720,
- marginInline: 'auto',
- },
-});
-
-// Width comes from the resize handle on desktop and forces full-width on
-// mobile. A dynamic style (not inline) so the MOBILE override can win.
-const dynamicStyles = stylex.create({
- chatPanelWidth: (size: number | string) => ({
- width: {
- default: typeof size === 'number' ? `${size}px` : size,
- [MOBILE]: '100%',
- },
- flexShrink: {
- default: 0,
- [MOBILE]: 1,
- },
- }),
-});
-
-const chatFullWidth = stylex.create({
- fill: {
- flex: 1,
- width: '100%',
- minWidth: 0,
- },
-});
-
-// ============= ARTIFACT CONTENT =============
-
-const ARTIFACT_TITLE = 'Getting Started with Design Systems';
-
-const ARTIFACT_SUBTITLE = 'Document \u00b7 Updated just now';
-
-const ARTIFACT_CONTENT = `## Introduction
-
-A design system is a collection of reusable components, guided by clear standards, that can be assembled together to build any number of applications. It serves as the single source of truth for an organization\u2019s UI patterns and ensures consistency across products.
-
-## Core Principles
-
-### 1. Consistency
-
-Every component should look and behave the same way regardless of context. Users build mental models around familiar patterns \u2014 breaking those patterns creates friction.
-
-### 2. Composability
-
-Components should be designed as building blocks. A good design system provides primitives that can be composed into more complex interfaces without introducing custom overrides.
-
-### 3. Accessibility
-
-Accessibility isn\u2019t an afterthought \u2014 it\u2019s a foundational requirement. Every component must support keyboard navigation, screen readers, and sufficient color contrast ratios.
-
-## Component Architecture
-
-The foundation of any design system is its component architecture. Components should be:
-
-- **Self-contained** \u2014 encapsulating their own styles, logic, and documentation
-- **Configurable** \u2014 exposing a clear prop API for customization
-- **Themeable** \u2014 respecting design tokens for colors, spacing, and typography
-
-## Token System
-
-Design tokens are the atomic values that define visual properties:
-
-| Category | Examples |
-|----------|----------|
-| Color | Background, text, border, accent |
-| Spacing | Margins, padding, gaps |
-| Typography | Font size, weight, line height |
-| Shape | Border radius, shadows |
-
-## Next Steps
-
-1. Audit your existing UI for recurring patterns
-2. Define your token vocabulary
-3. Build foundational components (Button, Input, Card)
-4. Document usage guidelines and examples
-5. Establish a contribution workflow for your team`;
-
-// ============= ARTIFACT SUBVIEWS =============
-
-/** Toggle between the formatted document and its raw Markdown source. */
-function MarkdownToggle({
- showMarkdown,
- onToggleMarkdown,
-}: {
- showMarkdown: boolean;
- onToggleMarkdown: (next: boolean) => void;
-}) {
- return (
- <ToggleButton
- label="Toggle markdown view"
- size="sm"
- isIconOnly
- icon={<Icon icon={CodeBracketIcon} size="sm" />}
- isPressed={showMarkdown}
- onPressedChange={onToggleMarkdown}
- />
- );
-}
-
-/**
- * Artifact header actions: version menu, markdown toggle, copy, share. Pass
- * `onClose` to append a close button (desktop only; the mobile dialog has its
- * own). Returns a fragment so each control is a direct child of the toolbar's
- * endContent slot, which the toolbar relies on for gap and edge alignment.
- */
-function ArtifactActions({
- showMarkdown,
- onToggleMarkdown,
- onClose,
-}: {
- showMarkdown: boolean;
- onToggleMarkdown: (next: boolean) => void;
- onClose?: () => void;
-}) {
- return (
- <>
- <DropdownMenu
- button={{
- label: 'v2',
- variant: 'ghost',
- size: 'sm',
- }}
- items={[{label: 'v2 (current)'}, {label: 'v1'}]}
- />
- <MarkdownToggle
- showMarkdown={showMarkdown}
- onToggleMarkdown={onToggleMarkdown}
- />
- <Button
- label="Copy"
- variant="ghost"
- size="sm"
- icon={<Icon icon={ClipboardDocumentIcon} size="sm" />}
- isIconOnly
- />
- <Button
- label="Share"
- variant="ghost"
- size="sm"
- icon={<Icon icon={ShareIcon} size="sm" />}
- isIconOnly
- />
- {onClose != null && (
- <Button
- label="Close document"
- variant="ghost"
- size="sm"
- icon={<Icon icon={XMarkIcon} size="sm" />}
- isIconOnly
- onClick={onClose}
- />
- )}
- </>
- );
-}
-
-/**
- * Mobile variant of the artifact actions: the markdown toggle stays inline and
- * the secondary actions (version, copy, share) collapse into an overflow menu.
- */
-function MobileArtifactActions({
- showMarkdown,
- onToggleMarkdown,
-}: {
- showMarkdown: boolean;
- onToggleMarkdown: (next: boolean) => void;
-}) {
- return (
- <HStack gap={1} vAlign="center">
- <MarkdownToggle
- showMarkdown={showMarkdown}
- onToggleMarkdown={onToggleMarkdown}
- />
- <MoreMenu
- label="Document actions"
- size="sm"
- items={[
- {
- type: 'section',
- title: 'Version',
- items: [
- {label: 'v2 (current)', onClick: () => {}},
- {label: 'v1', onClick: () => {}},
- ],
- },
- {type: 'divider'},
- {label: 'Copy', icon: ClipboardDocumentIcon},
- {label: 'Share', icon: ShareIcon},
- ]}
- />
- </HStack>
- );
-}
-
-/** Scrollable artifact body — formatted document or raw markdown source. */
-function ArtifactBody({showMarkdown}: {showMarkdown: boolean}) {
- return (
- <Section variant="transparent" xstyle={styles.artifactScroll}>
- <VStack gap={2} xstyle={styles.articleBody}>
- {showMarkdown ? (
- <Text type="code">
- {`# ${ARTIFACT_TITLE}\n${ARTIFACT_CONTENT}`}
- </Text>
- ) : (
- <>
- <Heading level={1}>{ARTIFACT_TITLE}</Heading>
- <Markdown>{ARTIFACT_CONTENT}</Markdown>
- </>
- )}
- </VStack>
- </Section>
- );
-}
-
-/** In-message clickable card that opens the artifact panel/dialog. */
-function ArtifactCard({onOpen}: {onOpen: () => void}) {
- return (
- <ClickableCard
- label={`Open ${ARTIFACT_TITLE}`}
- onClick={onOpen}
- variant="muted"
- padding={3}
- maxWidth={360}
- xstyle={styles.artifactCard}>
- <HStack gap={3} vAlign="center" width="100%">
- <Icon icon={DocumentTextIcon} size="md" color="secondary" />
- <StackItem size="fill">
- <VStack gap={0}>
- <Text type="label" weight="semibold">
- {ARTIFACT_TITLE}
- </Text>
- <Text type="supporting" color="secondary">
- Document
- </Text>
- </VStack>
- </StackItem>
- <Icon icon={ChevronRightIcon} size="sm" color="secondary" />
- </HStack>
- </ClickableCard>
- );
-}
-
-// ============= MAIN COMPONENT =============
-
-export default function AIChatArtifactTemplate() {
- const [showMarkdown, setShowMarkdown] = useState(false);
- const [composerMode, setComposerMode] = useState('ask');
- // Mobile-only: the artifact opens as a full-screen dialog.
- const [isArtifactDialogOpen, setIsArtifactDialogOpen] = useState(false);
- // Desktop-only: whether the side panel is shown (closeable via its toolbar).
- const [isArtifactOpen, setIsArtifactOpen] = useState(true);
- const rootRef = useRef<HTMLElement>(null);
- const chatResize = useResizable({
- defaultSize: 420,
- minSizePx: 360,
- maxSizePx: 720,
- autoSaveId: 'ai-chat-artifact-panel',
- });
-
- // Pick the artifact surface at click time: the layout collapse is a container
- // query, so measure the root (same MOBILE_MAX_WIDTH) rather than the viewport
- // to stay in sync.
- const openArtifact = () => {
- const width = rootRef.current?.offsetWidth ?? Infinity;
- if (width <= MOBILE_MAX_WIDTH) {
- setIsArtifactDialogOpen(true);
- } else {
- setIsArtifactOpen(true);
- }
- };
-
- return (
- <VStack ref={rootRef} xstyle={styles.root}>
- <Layout
- height="fill"
- content={
- <LayoutContent padding={0}>
- <HStack height="100%">
- {/* Chat panel — resizable on desktop, full-width on mobile. */}
- <VStack
- height="100%"
- xstyle={
- isArtifactOpen
- ? dynamicStyles.chatPanelWidth(chatResize.size)
- : chatFullWidth.fill
- }>
- <ChatLayout
- xstyle={styles.chatLayoutFill}
- composer={
- <ChatComposer
- onSubmit={() => {}}
- placeholder={
- composerMode === 'ask'
- ? 'Ask anything...'
- : 'Describe your edit...'
- }
- input={<ChatComposerInput />}
- headerActions={
- <>
- <Button
- label="Mention"
- variant="ghost"
- size="sm"
- icon={<Icon icon={AtSymbolIcon} size="sm" />}
- isIconOnly
- />
- <Button
- label="Attach"
- variant="ghost"
- size="sm"
- icon={<Icon icon={PaperClipIcon} size="sm" />}
- isIconOnly
- />
- </>
- }
- footerActions={
- <DropdownMenu
- button={{
- label: composerMode === 'ask' ? 'Ask' : 'Edit',
- variant: 'ghost',
- size: 'sm',
- }}
- items={[
- {
- label: 'Ask',
- onClick: () => setComposerMode('ask'),
- },
- {
- label: 'Edit',
- onClick: () => setComposerMode('edit'),
- },
- ]}
- />
- }
- />
- }>
- <ChatMessageList>
- <ChatSystemMessage variant="divider">
- Today
- </ChatSystemMessage>
-
- {/* User request */}
- <ChatMessage sender="user">
- <ChatMessageBubble
- metadata={
- <ChatMessageMetadata
- timestamp={
- <Timestamp
- value="2026-05-12T14:30:00"
- format="time"
- />
- }
- />
- }>
- Write me a guide about getting started with design
- systems. Cover the core principles, component
- architecture, and token systems.
- </ChatMessageBubble>
- </ChatMessage>
-
- {/* Assistant response */}
- <ChatMessage
- sender="assistant"
- avatar={<Avatar name="AI" size="small" />}>
- <ChatMessageBubble variant="ghost">
- <Markdown density="compact">
- {`I've created a comprehensive guide on design systems. It covers the core principles of consistency, composability, and accessibility, along with sections on component architecture and the token system.\n\nOpen the document below to review it. Want me to expand any section or adjust the tone?`}
- </Markdown>
- </ChatMessageBubble>
- <ArtifactCard onOpen={openArtifact} />
- <ChatMessageMetadata
- timestamp={
- <Timestamp
- value="2026-05-12T14:30:45"
- format="time"
- />
- }
- />
- </ChatMessage>
-
- {/* User follow-up */}
- <ChatMessage sender="user">
- <ChatMessageBubble
- metadata={
- <ChatMessageMetadata
- timestamp={
- <Timestamp
- value="2026-05-12T14:32:00"
- format="time"
- />
- }
- />
- }>
- This is great. Can you add a section about next steps at
- the end?
- </ChatMessageBubble>
- </ChatMessage>
-
- {/* Assistant confirmation */}
- <ChatMessage
- sender="assistant"
- avatar={<Avatar name="AI" size="small" />}>
- <ChatMessageBubble variant="ghost">
- <Markdown density="compact">
- {`Done! I've added a "Next Steps" section with actionable items for getting started. The artifact has been updated \u2014 you can see the changes in the panel.`}
- </Markdown>
- </ChatMessageBubble>
- <ChatMessageMetadata
- timestamp={
- <Timestamp
- value="2026-05-12T14:32:30"
- format="time"
- />
- }
- />
- </ChatMessage>
- </ChatMessageList>
- </ChatLayout>
- </VStack>
-
- {/* Desktop split-pane: resize handle + artifact panel. */}
- {isArtifactOpen && (
- <>
- <ResizeHandle
- direction="horizontal"
- resizable={chatResize.props}
- hasDivider
- label="Resize chat panel"
- xstyle={styles.resizeHandle}
- />
-
- {/* Toolbar-as-card-header: the card's padding context lets the
- toolbar align with the section body below. */}
- <Card
- variant="transparent"
- height="100%"
- xstyle={styles.artifactPanel}>
- <Toolbar
- label="Artifact actions"
- dividers={['bottom']}
- startContent={
- <HStack gap={3} vAlign="center">
- <Icon
- icon={DocumentTextIcon}
- size="sm"
- color="secondary"
- />
- <VStack gap={0}>
- <Text type="label" weight="semibold">
- {ARTIFACT_TITLE}
- </Text>
- <Text type="supporting" color="secondary">
- {ARTIFACT_SUBTITLE}
- </Text>
- </VStack>
- </HStack>
- }
- endContent={
- <ArtifactActions
- showMarkdown={showMarkdown}
- onToggleMarkdown={setShowMarkdown}
- onClose={() => setIsArtifactOpen(false)}
- />
- }
- />
-
- <ArtifactBody showMarkdown={showMarkdown} />
- </Card>
- </>
- )}
- </HStack>
- </LayoutContent>
- }
- />
- {/* Mobile artifact view — full-screen takeover via Dialog's
- `fullscreen` variant. */}
- <Dialog
- isOpen={isArtifactDialogOpen}
- onOpenChange={setIsArtifactDialogOpen}
- purpose="info"
- variant="fullscreen">
- <Layout
- header={
- <DialogHeader
- title={ARTIFACT_TITLE}
- subtitle={ARTIFACT_SUBTITLE}
- hasDivider
- onOpenChange={setIsArtifactDialogOpen}
- endContent={
- <MobileArtifactActions
- showMarkdown={showMarkdown}
- onToggleMarkdown={setShowMarkdown}
- />
- }
- />
- }
- content={
- // LayoutContent establishes the bounded, scrollable region;
- // padding={0} since ArtifactBody's Section supplies the inset.
- <LayoutContent padding={0}>
- <ArtifactBody showMarkdown={showMarkdown} />
- </LayoutContent>
- }
- />
- </Dialog>
- </VStack>
- );
-}
diff --git a/packages/cli/templates/pages/ai-chat-artifact/template.doc.mjs b/packages/cli/templates/pages/ai-chat-artifact/template.doc.mjs
deleted file mode 100644
index 94d28bef92..0000000000
--- a/packages/cli/templates/pages/ai-chat-artifact/template.doc.mjs
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/** @type {import('../../../../core/src/docs-types').TemplateDoc} */
-export const doc = {
- type: 'page',
- name: 'Artifact Page',
- displayName: 'Artifact Page',
- description: 'AI chat interface with a resizable chat panel on the left and an artifact preview area on the right for content being created via the conversation',
- isReady: true,
- category: 'AI Chat - Artifact Page',
-};
diff --git a/packages/cli/templates/pages/ai-chat-landing/page.tsx b/packages/cli/templates/pages/ai-chat-landing/page.tsx
index 3484d6e4bb..46b203fb34 100644
--- a/packages/cli/templates/pages/ai-chat-landing/page.tsx
+++ b/packages/cli/templates/pages/ai-chat-landing/page.tsx
@@ -2,44 +2,31 @@
'use client';
-import {useCallback, useRef, useState} from 'react';
+import {useRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {spacingVars} from '@xds/core/theme/tokens.stylex';
-import {
- Layout,
- LayoutContent,
- VStack,
- HStack,
-} from '@xds/core/Layout';
+import {Layout, LayoutContent, VStack, HStack} from '@xds/core/Layout';
import {Text, Heading} from '@xds/core/Text';
import {
ChatComposer,
ChatComposerDrawer,
ChatComposerInput,
ChatDictationButton,
- ChatLayout,
- ChatMessage,
- ChatMessageBubble,
- ChatMessageList,
- ChatMessageMetadata,
- ChatSystemMessage,
useChatDictation,
type ChatComposerInputHandle,
type ChatComposerTrigger,
} from '@xds/core/Chat';
-import {Markdown} from '@xds/core/Markdown';
import {
createStaticSource,
TypeaheadItem,
type SearchableItem,
} from '@xds/core/Typeahead';
-import {Timestamp} from '@xds/core/Timestamp';
import {ToggleButton, ToggleButtonGroup} from '@xds/core/ToggleButton';
-import {Button} from '@xds/core/Button';
import {Token} from '@xds/core/Token';
-import {Card} from '@xds/core/Card';
+import {ClickableCard} from '@xds/core/ClickableCard';
import {Grid} from '@xds/core/Grid';
import {Icon} from '@xds/core/Icon';
-
import {DropdownMenu, DropdownMenuItem} from '@xds/core/DropdownMenu';
import {
Cog6ToothIcon,
@@ -50,16 +37,17 @@ import {
MagnifyingGlassIcon,
LockClosedIcon,
ClockIcon,
- PaperClipIcon,
LightBulbIcon,
} from '@heroicons/react/24/outline';
-const TOKEN_MODES: Record<string, string> = {
- sensitive: '/sensitive',
- deep: '/deep-mode',
-};
+const styles = stylex.create({
+ // Fill the content area so the greeting and composer stay vertically centered.
+ page: {minHeight: '100%'},
+ composerInput: {minHeight: 84},
+ categories: {paddingInline: spacingVars['--spacing-3']},
+});
-// Suggestion prompts per category
+// Suggestion cards shown once a category is selected.
const CATEGORY_SUGGESTIONS: Record<
string,
Array<{heading: string; body: string; prompt: string}>
@@ -154,7 +142,7 @@ const CATEGORY_SUGGESTIONS: Record<
],
};
-// Shared category definitions used by both toggle group and mode menu
+// Category filters, shared by the toggle group and the composer mode menu.
const CATEGORIES = [
{key: 'writing', label: 'Writing', icon: PencilSquareIcon},
{key: 'coding', label: 'Coding', icon: CodeBracketIcon},
@@ -162,7 +150,7 @@ const CATEGORIES = [
{key: 'creative', label: 'Creative', icon: LightBulbIcon},
] as const;
-// Mode options for the dropdown (categories + special modes)
+// Composer mode menu: categories plus special modes.
const MODE_OPTIONS = [
{key: 'auto', label: 'Auto', icon: SparklesIcon},
...CATEGORIES,
@@ -170,19 +158,20 @@ const MODE_OPTIONS = [
{key: 'deep', label: 'Deep Mode', icon: ClockIcon},
] as const;
-// ============= TRIGGER DATA =============
+// Modes that insert a composer token instead of switching the active category.
+const TOKEN_MODES: Record<string, string> = {
+ sensitive: '/sensitive',
+ deep: '/deep-mode',
+};
+// Composer trigger data: @ mentions and / commands.
const MENTION_ITEMS: SearchableItem<{role: string}>[] = [
{id: 'cindy', label: 'Cindy Zhang', auxiliaryData: {role: 'Design Systems'}},
{id: 'alex', label: 'Alex Johnson', auxiliaryData: {role: 'Frontend'}},
{id: 'sam', label: 'Sam Rivera', auxiliaryData: {role: 'Backend'}},
{id: 'jordan', label: 'Jordan Lee', auxiliaryData: {role: 'Product'}},
{id: 'taylor', label: 'Taylor Kim', auxiliaryData: {role: 'Design'}},
- {
- id: 'morgan',
- label: 'Morgan Chen',
- auxiliaryData: {role: 'Infrastructure'},
- },
+ {id: 'morgan', label: 'Morgan Chen', auxiliaryData: {role: 'Infrastructure'}},
];
const COMMAND_ITEMS: SearchableItem<{description: string}>[] = [
@@ -213,12 +202,9 @@ const COMMAND_ITEMS: SearchableItem<{description: string}>[] = [
},
];
-const mentionSource = createStaticSource(MENTION_ITEMS);
-const commandSource = createStaticSource(COMMAND_ITEMS);
-
const mentionTrigger: ChatComposerTrigger = {
character: '@',
- searchSource: mentionSource,
+ searchSource: createStaticSource(MENTION_ITEMS),
renderItem: item => (
<TypeaheadItem
item={item}
@@ -228,13 +214,13 @@ const mentionTrigger: ChatComposerTrigger = {
onSelect: item => ({
value: `@${item.id}`,
label: item.label,
- variant: 'blue' as const,
+ variant: 'blue',
}),
};
const commandTrigger: ChatComposerTrigger = {
character: '/',
- searchSource: commandSource,
+ searchSource: createStaticSource(COMMAND_ITEMS),
renderItem: item => (
<TypeaheadItem
item={item}
@@ -244,34 +230,15 @@ const commandTrigger: ChatComposerTrigger = {
onSelect: item => ({
value: `/${item.label}`,
label: `/${item.label}`,
- variant: 'yellow' as const,
+ variant: 'yellow',
}),
};
const composerTriggers = [mentionTrigger, commandTrigger];
-// ============= MESSAGE TYPES =============
-
-type ChatMessage =
- | {
- id: number;
- role: 'user';
- text: string;
- attachments?: string[];
- sentAt: Date;
- }
- | {id: number; role: 'assistant'; text: string; isStreaming?: boolean}
- | {id: number; role: 'system'; text: string};
-
-const SIMULATED_RESPONSE =
- 'Thanks for your message! I’m looking into this now.\n\nHere’s what I found so far:\n\n1. **First**, I reviewed the relevant context from the attached files\n2. **Next**, I cross-referenced with the latest documentation\n3. **Finally**, I have a few recommendations\n\nLet me know if you’d like me to dive deeper into any of these areas, or if you have follow-up questions.';
-
-// ============= SIDENAV =============
-
-// ============= MAIN COMPONENT =============
+// Main component
export default function AIChatTemplate() {
- const [view, setView] = useState<'landing' | 'chat'>('landing');
const [mode, setMode] = useState<string | null>('auto');
const [category, setCategory] = useState<string | null>(null);
const [attachments, setAttachments] = useState<string[]>([
@@ -281,130 +248,50 @@ export default function AIChatTemplate() {
'user_research.csv',
'brand_guidelines.pdf',
]);
- const [messages, setMessages] = useState<ChatMessage[]>([]);
- const [isStreaming, setIsStreaming] = useState(false);
const [isModeMenuOpen, setIsModeMenuOpen] = useState(false);
- const fileInputRef = useRef<HTMLInputElement>(null);
const composerInputRef = useRef<ChatComposerInputHandle>(null);
const shouldFocusComposerRef = useRef(false);
- const streamRef = useRef<ReturnType<typeof setInterval>>(undefined);
const dictation = useChatDictation({inputRef: composerInputRef});
+
const activeMode = MODE_OPTIONS.find(m => m.key === mode) ?? MODE_OPTIONS[0];
const suggestions = category ? CATEGORY_SUGGESTIONS[category] : null;
- // ---------------------------------------------------------------------------
- // Streaming
- // ---------------------------------------------------------------------------
-
- const streamResponse = useCallback((responseText: string) => {
- const msgId = Date.now();
- setIsStreaming(true);
- setMessages(prev => [
- ...prev,
- {id: msgId, role: 'assistant', text: '', isStreaming: true},
- ]);
-
- let i = 0;
- streamRef.current = setInterval(() => {
- i += 2 + Math.floor(Math.random() * 4);
- if (i >= responseText.length) {
- clearInterval(streamRef.current);
- setMessages(prev =>
- prev.map(m =>
- m.id === msgId ? {...m, text: responseText, isStreaming: false} : m,
- ),
- );
- setIsStreaming(false);
- return;
- }
- setMessages(prev =>
- prev.map(m =>
- m.id === msgId ? {...m, text: responseText.slice(0, i)} : m,
- ),
- );
- }, 30);
- }, []);
-
- const handleStop = useCallback(() => {
- clearInterval(streamRef.current);
- setIsStreaming(false);
- setMessages(prev =>
- prev.map(m =>
- m.role === 'assistant' && m.isStreaming
- ? {...m, isStreaming: false}
- : m,
- ),
- );
- }, []);
-
- // ---------------------------------------------------------------------------
- // Submit
- // ---------------------------------------------------------------------------
-
- const handleSubmit = useCallback(
- (value: string) => {
- if (!value.trim()) {
- return;
- }
-
- const userMsg: ChatMessage = {
- id: Date.now(),
- role: 'user',
- text: value,
- attachments: attachments.length > 0 ? [...attachments] : undefined,
- sentAt: new Date(),
- };
-
- if (view === 'landing') {
- setMessages([
- {id: userMsg.id - 1, role: 'system', text: 'Today'},
- userMsg,
- ]);
- setAttachments([]);
- setView('chat');
- setTimeout(() => streamResponse(SIMULATED_RESPONSE), 600);
- } else {
- setMessages(prev => [...prev, userMsg]);
- setTimeout(() => streamResponse(SIMULATED_RESPONSE), 600);
- }
- },
- [view, attachments, streamResponse],
- );
+ // The composer's imperative insert methods mutate the DOM without emitting a
+ // change, so dispatch an input event to sync its value and clear the placeholder.
+ const syncComposerValue = () => {
+ document.activeElement?.dispatchEvent(new Event('input', {bubbles: true}));
+ };
- const replaceWithSuggestion = (prompt: string) => {
+ const applySuggestion = (prompt: string) => {
const input = composerInputRef.current;
if (!input) {
return;
}
input.focus();
- // Select all existing content so insertText replaces it
- const sel = window.getSelection();
- if (sel && document.activeElement) {
- sel.selectAllChildren(document.activeElement);
+ if (document.activeElement) {
+ window.getSelection()?.selectAllChildren(document.activeElement);
}
input.insertText(prompt);
- // Dispatch input event to trigger emitChange and clear placeholder
- document.activeElement?.dispatchEvent(new Event('input', {bubbles: true}));
+ syncComposerValue();
};
- // ---------------------------------------------------------------------------
- // Composer (shared between landing and chat views)
- // ---------------------------------------------------------------------------
-
- const insertMentionToken = (item: (typeof MENTION_ITEMS)[number]) => {
- composerInputRef.current?.focus();
- // Move cursor to end so token is appended
- const sel = window.getSelection();
- if (sel && document.activeElement) {
- sel.selectAllChildren(document.activeElement);
- sel.collapseToEnd();
+ const insertMention = (item: (typeof MENTION_ITEMS)[number]) => {
+ const input = composerInputRef.current;
+ if (!input) {
+ return;
}
- composerInputRef.current?.insertToken({
+ input.focus();
+ if (document.activeElement) {
+ const sel = window.getSelection();
+ sel?.selectAllChildren(document.activeElement);
+ sel?.collapseToEnd();
+ }
+ input.insertToken({
value: `@${item.id}`,
label: item.label,
variant: 'blue',
});
- document.activeElement?.dispatchEvent(new Event('input', {bubbles: true}));
+ syncComposerValue();
};
const insertModeToken = (label: string) => {
@@ -414,215 +301,9 @@ export default function AIChatTemplate() {
label,
variant: 'orange',
});
- // Dispatch input event to trigger emitChange and clear placeholder
- document.activeElement?.dispatchEvent(new Event('input', {bubbles: true}));
+ syncComposerValue();
};
- const fileInput = (
- <input
- ref={fileInputRef}
- type="file"
- multiple
- style={{display: 'none'}}
- onChange={e => {
- const files = Array.from(e.target.files ?? []);
- setAttachments(prev => [...prev, ...files.map(f => f.name)]);
- e.target.value = '';
- }}
- />
- );
-
- const renderComposer = ({
- inputMinHeight,
- extraFooterActions = null,
- }: {
- inputMinHeight: string;
- extraFooterActions?: React.ReactNode;
- }) => (
- <ChatComposer
- onSubmit={handleSubmit}
- onStop={handleStop}
- isStopShown={isStreaming}
- placeholder="Ask anything"
- input={
- <ChatComposerInput
- handleRef={composerInputRef}
- triggers={composerTriggers}
- style={{minHeight: inputMinHeight}}
- />
- }
- drawer={
- attachments.length > 0 ? (
- <ChatComposerDrawer count={attachments.length}>
- {attachments.map(name => (
- <Token
- key={name}
- label={name}
- onRemove={() =>
- setAttachments(prev => prev.filter(n => n !== name))
- }
- />
- ))}
- </ChatComposerDrawer>
- ) : undefined
- }
- headerActions={
- <>
- <DropdownMenu
- button={{
- label: 'Reference',
- variant: 'ghost',
- size: 'sm',
- icon: <Icon icon={AtSymbolIcon} size="sm" />,
- isIconOnly: true,
- }}
- hasChevron={false}
- menuWidth={240}>
- {MENTION_ITEMS.map(item => (
- <DropdownMenuItem
- key={item.id}
- label={item.label}
- description={item.auxiliaryData?.role}
- onClick={() => insertMentionToken(item)}
- />
- ))}
- </DropdownMenu>
- <Button
- label="Attach"
- variant="ghost"
- size="sm"
- icon={<Icon icon={PaperClipIcon} size="sm" />}
- isIconOnly
- onClick={() => fileInputRef.current?.click()}
- />
- </>
- }
- footerActions={
- <>
- <DropdownMenu
- button={{
- label: activeMode.label,
- variant: 'ghost',
- size: 'md',
- icon: <Icon icon={activeMode.icon} size="sm" />,
- children: activeMode.label,
- }}
- menuWidth={200}
- isMenuOpen={isModeMenuOpen}
- onOpenChange={(isOpen: boolean) => {
- setIsModeMenuOpen(isOpen);
- if (!isOpen && shouldFocusComposerRef.current) {
- shouldFocusComposerRef.current = false;
- // Delay focus until after menu restores focus to its trigger button
- setTimeout(() => {
- composerInputRef.current?.focus();
- }, 50);
- }
- }}
- items={MODE_OPTIONS.flatMap(opt => {
- const item = {
- label: opt.label,
- icon: opt.icon,
- onClick: () => {
- const tokenLabel = TOKEN_MODES[opt.key];
- if (tokenLabel) {
- insertModeToken(tokenLabel);
- shouldFocusComposerRef.current = true;
- } else {
- setMode(opt.key);
- }
- },
- };
- return opt.key === 'sensitive'
- ? [{type: 'divider' as const}, item]
- : [item];
- })}
- />
- {extraFooterActions}
- </>
- }
- sendActions={<ChatDictationButton dictation={dictation} />}
- />
- );
-
- // ---------------------------------------------------------------------------
- // Chat view
- // ---------------------------------------------------------------------------
-
- if (view === 'chat') {
- return (
- <Layout
- height="fill"
- content={
- <LayoutContent padding={0}>
- <ChatLayout
- style={{height: '100%'}}
- composer={
- <>
- {fileInput}
- {renderComposer({inputMinHeight: '44px'})}
- </>
- }>
- <ChatMessageList>
- {messages.map(msg => {
- if (msg.role === 'system') {
- return (
- <ChatSystemMessage key={msg.id} variant="divider">
- {msg.text}
- </ChatSystemMessage>
- );
- }
- if (msg.role === 'user') {
- return (
- <ChatMessage key={msg.id} sender="user">
- {msg.attachments && msg.attachments.length > 0 && (
- <HStack gap={1} style={{flexWrap: 'wrap'}}>
- {msg.attachments.map(f => (
- <Token key={f} label={f} />
- ))}
- </HStack>
- )}
- <ChatMessageBubble
- metadata={
- <ChatMessageMetadata
- timestamp={
- <Timestamp
- value={msg.sentAt.getTime()}
- format="time"
- />
- }
- />
- }>
- {msg.text}
- </ChatMessageBubble>
- </ChatMessage>
- );
- }
- return (
- <ChatMessage key={msg.id} sender="assistant">
- <Markdown density="compact">{msg.text}</Markdown>
- {!msg.isStreaming && msg.text && (
- <ChatMessageMetadata
- timestamp={
- <Timestamp value={msg.id} format="time" />
- }
- />
- )}
- </ChatMessage>
- );
- })}
- </ChatMessageList>
- </ChatLayout>
- </LayoutContent>
- }
- />
- );
- }
-
- // ---------------------------------------------------------------------------
- // Landing view
- // ---------------------------------------------------------------------------
-
return (
<Layout
height="fill"
@@ -630,7 +311,7 @@ export default function AIChatTemplate() {
padding={6}
content={
<LayoutContent>
- <VStack gap={8} vAlign="center" style={{minHeight: '100%'}}>
+ <VStack gap={8} vAlign="center" xstyle={styles.page}>
{/* Greeting */}
<VStack gap={1}>
<HStack gap={2} vAlign="center">
@@ -645,30 +326,116 @@ export default function AIChatTemplate() {
</VStack>
{/* Composer */}
- {fileInput}
- {renderComposer({
- inputMinHeight: '84px',
- extraFooterActions: (
+ <ChatComposer
+ onSubmit={() => {}}
+ placeholder="Ask anything"
+ input={
+ <ChatComposerInput
+ handleRef={composerInputRef}
+ triggers={composerTriggers}
+ xstyle={styles.composerInput}
+ onFiles={files =>
+ setAttachments(prev => [...prev, ...files.map(f => f.name)])
+ }
+ />
+ }
+ drawer={
+ attachments.length > 0 ? (
+ <ChatComposerDrawer count={attachments.length}>
+ {attachments.map(name => (
+ <Token
+ key={name}
+ label={name}
+ onRemove={() =>
+ setAttachments(prev => prev.filter(n => n !== name))
+ }
+ />
+ ))}
+ </ChatComposerDrawer>
+ ) : undefined
+ }
+ headerActions={
<DropdownMenu
button={{
- label: 'Settings',
+ label: 'Reference',
variant: 'ghost',
- size: 'md',
- icon: <Icon icon={Cog6ToothIcon} size="sm" />,
- children: 'Settings',
+ size: 'sm',
+ icon: <Icon icon={AtSymbolIcon} size="sm" />,
+ isIconOnly: true,
}}
- menuWidth={200}
- items={[
- {label: 'Preferences', onClick: () => {}},
- {label: 'Keyboard shortcuts', onClick: () => {}},
- {label: 'About', onClick: () => {}},
- ]}
- />
- ),
- })}
+ hasChevron={false}
+ menuWidth={240}>
+ {MENTION_ITEMS.map(item => (
+ <DropdownMenuItem
+ key={item.id}
+ label={item.label}
+ description={item.auxiliaryData?.role}
+ onClick={() => insertMention(item)}
+ />
+ ))}
+ </DropdownMenu>
+ }
+ footerActions={
+ <>
+ <DropdownMenu
+ button={{
+ label: activeMode.label,
+ variant: 'ghost',
+ size: 'md',
+ icon: <Icon icon={activeMode.icon} size="sm" />,
+ children: activeMode.label,
+ }}
+ menuWidth={200}
+ isMenuOpen={isModeMenuOpen}
+ onOpenChange={isOpen => {
+ setIsModeMenuOpen(isOpen);
+ // Restore focus to the composer after inserting a mode token.
+ if (!isOpen && shouldFocusComposerRef.current) {
+ shouldFocusComposerRef.current = false;
+ setTimeout(() => composerInputRef.current?.focus(), 50);
+ }
+ }}
+ items={MODE_OPTIONS.flatMap(opt => {
+ const item = {
+ label: opt.label,
+ icon: opt.icon,
+ onClick: () => {
+ const tokenLabel = TOKEN_MODES[opt.key];
+ if (tokenLabel) {
+ insertModeToken(tokenLabel);
+ shouldFocusComposerRef.current = true;
+ } else {
+ setMode(opt.key);
+ }
+ },
+ };
+ return opt.key === 'sensitive'
+ ? [{type: 'divider' as const}, item]
+ : [item];
+ })}
+ />
+ <DropdownMenu
+ button={{
+ label: 'Settings',
+ variant: 'ghost',
+ size: 'md',
+ icon: <Icon icon={Cog6ToothIcon} size="sm" />,
+ children: 'Settings',
+ }}
+ menuWidth={200}
+ items={[
+ {label: 'Preferences', onClick: () => {}},
+ {label: 'Keyboard shortcuts', onClick: () => {}},
+ {label: 'About', onClick: () => {}},
+ ]}
+ />
+ </>
+ }
+ sendActions={<ChatDictationButton dictation={dictation} />}
+ />
- {/* Category toggle buttons */}
- <VStack gap={6} style={{paddingInline: 'var(--spacing-3)'}}>
+ {/* Category filters + suggestion cards */}
+ <VStack gap={6} xstyle={styles.categories}>
<ToggleButtonGroup
label="Category"
value={category}
@@ -684,27 +451,17 @@ export default function AIChatTemplate() {
))}
</ToggleButtonGroup>
- {/* Suggestion cards */}
{suggestions && (
<Grid columns={{minWidth: 280}} gap={3}>
{suggestions.map(suggestion => (
- <Card
- variant="muted"
+ <ClickableCard
key={suggestion.heading}
+ label={suggestion.heading}
+ variant="muted"
padding={3}
- style={{cursor: 'pointer'}}
- role="button"
- tabIndex={0}
onClick={() => {
- replaceWithSuggestion(suggestion.prompt);
+ applySuggestion(suggestion.prompt);
setMode(category);
- }}
- onKeyDown={(e: React.KeyboardEvent) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- replaceWithSuggestion(suggestion.prompt);
- setMode(category);
- }
}}>
<VStack gap={0.5}>
<Heading level={4}>{suggestion.heading}</Heading>
@@ -712,7 +469,7 @@ export default function AIChatTemplate() {
{suggestion.body}
</Text>
</VStack>
- </Card>
+ </ClickableCard>
))}
</Grid>
)}
diff --git a/packages/cli/templates/pages/ai-chat/page.tsx b/packages/cli/templates/pages/ai-chat/page.tsx
index 69623cb1e3..564354b219 100644
--- a/packages/cli/templates/pages/ai-chat/page.tsx
+++ b/packages/cli/templates/pages/ai-chat/page.tsx
@@ -2,8 +2,18 @@
'use client';
-import {HStack, Layout, LayoutContent} from '@xds/core/Layout';
-import {Text} from '@xds/core/Text';
+import {useRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {spacingVars} from '@xds/core/theme/tokens.stylex';
+
+import {
+ HStack,
+ VStack,
+ StackItem,
+ Layout,
+ LayoutContent,
+} from '@xds/core/Layout';
+import {Text, Heading} from '@xds/core/Text';
import {
ChatComposer,
ChatComposerInput,
@@ -17,125 +27,392 @@ import {
ChatToolCalls,
} from '@xds/core/Chat';
import {Avatar} from '@xds/core/Avatar';
+import {Card} from '@xds/core/Card';
+import {ClickableCard} from '@xds/core/ClickableCard';
+import {Section} from '@xds/core/Section';
import {Markdown} from '@xds/core/Markdown';
import {CodeBlock} from '@xds/core/CodeBlock';
import {Timestamp} from '@xds/core/Timestamp';
import {Token} from '@xds/core/Token';
import {Button} from '@xds/core/Button';
import {Icon} from '@xds/core/Icon';
+import {Dialog, DialogHeader} from '@xds/core/Dialog';
+import {DropdownMenu} from '@xds/core/DropdownMenu';
+import {MoreMenu} from '@xds/core/MoreMenu';
+import {Toolbar} from '@xds/core/Toolbar';
+import {useResizable, ResizeHandle} from '@xds/core/Resizable';
+
+import {
+ DocumentTextIcon,
+ ClipboardDocumentIcon,
+ ShareIcon,
+ AtSymbolIcon,
+ PaperClipIcon,
+ XMarkIcon,
+ ChevronRightIcon,
+} from '@heroicons/react/24/outline';
+
+// Below this width the split-pane collapses to a single chat column. Shared by
+// the CSS container query and the JS check in openArtifact so they can't drift.
+const MOBILE_MAX_WIDTH = 767;
+const MOBILE = `@container artifact (max-width: ${MOBILE_MAX_WIDTH}px)`;
-import {AtSymbolIcon, PaperClipIcon} from '@heroicons/react/24/outline';
+const styles = stylex.create({
+ root: {
+ height: '100dvh',
+ width: '100%',
+ containerType: 'inline-size',
+ containerName: 'artifact',
+ },
+ chatColumn: {
+ flex: 1,
+ width: '100%',
+ minWidth: 0,
+ height: '100%',
+ },
+ chatLayout: {
+ flex: 1,
+ minHeight: 0,
+ },
+ artifactPanel: {
+ overflow: 'hidden',
+ flexDirection: 'column',
+ display: {default: 'flex', [MOBILE]: 'none'},
+ },
+ resizeHandle: {
+ display: {default: 'flex', [MOBILE]: 'none'},
+ },
+ artifactCard: {
+ marginBlockStart: spacingVars['--spacing-2'],
+ },
+ artifactScroll: {
+ flex: 1,
+ overflowY: 'auto',
+ },
+ articleBody: {
+ maxWidth: 720,
+ marginInline: 'auto',
+ },
+});
-// ============= TOKENS =============
+// Runtime width for the artifact panel; the MOBILE override forces full width.
+const dynamicStyles = stylex.create({
+ artifactPanelWidth: (size: number | string) => ({
+ width: {
+ default: typeof size === 'number' ? `${size}px` : size,
+ [MOBILE]: '100%',
+ },
+ flexShrink: {default: 0, [MOBILE]: 1},
+ }),
+});
+
+// Artifact content
const MENTION_TOKENS = [
{value: '@agent', label: '@Agent', variant: 'blue' as const},
];
-// ============= SIDENAV =============
+const ARTIFACT_TITLE = 'JWT Token Refresh: Design & Rollout';
+
+const ARTIFACT_SUBTITLE = 'Document · Updated just now';
+
+const ARTIFACT_CONTENT = `## Overview
+
+Our API gateway authenticates every request with a short-lived JWT access token. Until now, an expired token meant an immediate \`401\` — even when the user still held a valid refresh token. This document describes the silent-refresh flow we just shipped and how we're rolling it out.
+
+## The Problem
+
+Token validation ran **before** any refresh logic, so the middleware rejected expired tokens outright:
+
+1. A request arrives with an expired access token
+2. \`validateToken()\` throws \`TokenExpiredError\`
+3. The catch block returns \`401\` — \`refreshToken()\` is never reached
+
+The result was users getting logged out whenever an access token lapsed mid-session.
+
+## The Fix
+
+The middleware now catches \`TokenExpiredError\` specifically and attempts a silent refresh before rejecting. On success it reissues an access token and continues the request; on failure it falls back to \`401\`.
+
+- **Transparent** — valid sessions never see an interruption
+- **Safe** — a missing or invalid refresh token still returns \`401\`
+- **Cheap** — refresh only runs on the expiry path, not on every request
+
+## Testing
+
+The refresh path is covered end to end:
-// ============= MAIN COMPONENT =============
+| Scenario | Expected |
+|----------|----------|
+| Valid token passes through | \`200\` |
+| Expired token, valid refresh | \`200\` + new access token |
+| Expired token, invalid refresh | \`401\` |
+| Malformed token | \`401\` |
+
+## Rollout & Monitoring
+
+1. Ship behind the \`silent_refresh\` flag at 5% of traffic
+2. Watch the \`auth.refresh.success\` and \`auth.refresh.failure\` counters
+3. Alert if the failure rate exceeds **2%** over any 5-minute window
+4. Ramp to 100% once metrics hold steady for 24 hours`;
+
+// Artifact subviews
+
+// Header actions: version menu, copy, share. Pass `onClose` for the desktop
+// close button. A fragment so each control is a direct child of the toolbar.
+function ArtifactActions({onClose}: {onClose?: () => void}) {
+ return (
+ <>
+ <DropdownMenu
+ button={{
+ label: 'v2',
+ variant: 'ghost',
+ size: 'sm',
+ }}
+ items={[{label: 'v2 (current)'}, {label: 'v1'}]}
+ />
+ <Button
+ label="Copy"
+ variant="ghost"
+ size="sm"
+ icon={<Icon icon={ClipboardDocumentIcon} size="sm" />}
+ isIconOnly
+ />
+ <Button
+ label="Share"
+ variant="ghost"
+ size="sm"
+ icon={<Icon icon={ShareIcon} size="sm" />}
+ isIconOnly
+ />
+ {onClose != null && (
+ <Button
+ label="Close document"
+ variant="ghost"
+ size="sm"
+ icon={<Icon icon={XMarkIcon} size="sm" />}
+ isIconOnly
+ onClick={onClose}
+ />
+ )}
+ </>
+ );
+}
+
+// Mobile variant: the actions collapse into an overflow menu.
+function MobileArtifactActions() {
+ return (
+ <MoreMenu
+ label="Document actions"
+ size="sm"
+ items={[
+ {
+ type: 'section',
+ title: 'Version',
+ items: [
+ {label: 'v2 (current)', onClick: () => {}},
+ {label: 'v1', onClick: () => {}},
+ ],
+ },
+ {type: 'divider'},
+ {label: 'Copy', icon: ClipboardDocumentIcon},
+ {label: 'Share', icon: ShareIcon},
+ ]}
+ />
+ );
+}
+
+// Scrollable artifact body — the formatted document.
+function ArtifactBody() {
+ return (
+ <Section variant="transparent" xstyle={styles.artifactScroll}>
+ <VStack gap={2} xstyle={styles.articleBody}>
+ <Heading level={1}>{ARTIFACT_TITLE}</Heading>
+ <Markdown>{ARTIFACT_CONTENT}</Markdown>
+ </VStack>
+ </Section>
+ );
+}
+
+// In-message card that opens the artifact panel/dialog.
+function ArtifactCard({onOpen}: {onOpen: () => void}) {
+ return (
+ <ClickableCard
+ label={`Open ${ARTIFACT_TITLE}`}
+ onClick={onOpen}
+ variant="muted"
+ padding={3}
+ maxWidth={360}
+ xstyle={styles.artifactCard}>
+ <HStack gap={3} vAlign="center" width="100%">
+ <Icon icon={DocumentTextIcon} size="md" color="secondary" />
+ <StackItem size="fill">
+ <VStack gap={0}>
+ <Text type="label" weight="semibold">
+ {ARTIFACT_TITLE}
+ </Text>
+ <Text type="supporting" color="secondary">
+ Document
+ </Text>
+ </VStack>
+ </StackItem>
+ <Icon icon={ChevronRightIcon} size="sm" color="secondary" />
+ </HStack>
+ </ClickableCard>
+ );
+}
+
+// Main component
export default function AIChatConversationTemplate() {
+ const [composerMode, setComposerMode] = useState('ask');
+ // Mobile shows the artifact as a full-screen dialog; desktop as a side panel.
+ const [isArtifactDialogOpen, setIsArtifactDialogOpen] = useState(false);
+ const [isArtifactOpen, setIsArtifactOpen] = useState(true);
+ const rootRef = useRef<HTMLElement>(null);
+ const artifactResize = useResizable({
+ defaultSize: 640,
+ minSizePx: 480,
+ maxSizePx: 960,
+ autoSaveId: 'ai-chat-artifact-panel',
+ });
+
+ // Match the container-query breakpoint by measuring the root, not the viewport.
+ const openArtifact = () => {
+ const width = rootRef.current?.offsetWidth ?? Infinity;
+ if (width <= MOBILE_MAX_WIDTH) {
+ setIsArtifactDialogOpen(true);
+ } else {
+ setIsArtifactOpen(true);
+ }
+ };
+
return (
- <Layout
- height="fill"
- content={
- <LayoutContent padding={0}>
- <ChatLayout
- style={{height: '100%'}}
- composer={
- <ChatComposer
- onSubmit={() => {}}
- placeholder="Ask anything"
- input={<ChatComposerInput />}
- headerActions={
- <>
- <Button
- label="Mention"
- variant="ghost"
- size="sm"
- icon={<Icon icon={AtSymbolIcon} size="sm" />}
- isIconOnly
- />
- <Button
- label="Attach"
- variant="ghost"
- size="sm"
- icon={<Icon icon={PaperClipIcon} size="sm" />}
- isIconOnly
- />
- </>
- }
- />
- }>
- <ChatMessageList>
- {/* ── System message: date divider ── */}
- <ChatSystemMessage variant="divider">
- Today
- </ChatSystemMessage>
-
- {/* ── User message with tokenized mention and file attachments ── */}
- <ChatMessage sender="user">
- <HStack gap={1} wrap="wrap">
- <Token label="auth-service.ts" />
- <Token label="middleware.ts" />
- </HStack>
- <ChatMessageBubble
- metadata={
- <ChatMessageMetadata
- timestamp={
- <Timestamp
- value="2026-04-29T10:15:00"
- format="time"
+ <VStack ref={rootRef} xstyle={styles.root}>
+ <Layout
+ height="fill"
+ content={
+ <LayoutContent padding={0}>
+ <HStack height="100%">
+ {/* Chat column — flexes to fill the space the artifact leaves */}
+ <VStack xstyle={styles.chatColumn}>
+ <ChatLayout
+ density="spacious"
+ xstyle={styles.chatLayout}
+ composer={
+ <ChatComposer
+ onSubmit={() => {}}
+ placeholder={
+ composerMode === 'ask'
+ ? 'Ask anything...'
+ : 'Describe your edit...'
+ }
+ input={<ChatComposerInput />}
+ headerActions={
+ <>
+ <Button
+ label="Mention"
+ variant="ghost"
+ size="sm"
+ icon={<Icon icon={AtSymbolIcon} size="sm" />}
+ isIconOnly
+ />
+ <Button
+ label="Attach"
+ variant="ghost"
+ size="sm"
+ icon={<Icon icon={PaperClipIcon} size="sm" />}
+ isIconOnly
+ />
+ </>
+ }
+ footerActions={
+ <DropdownMenu
+ button={{
+ label: composerMode === 'ask' ? 'Ask' : 'Edit',
+ variant: 'ghost',
+ size: 'sm',
+ }}
+ items={[
+ {
+ label: 'Ask',
+ onClick: () => setComposerMode('ask'),
+ },
+ {
+ label: 'Edit',
+ onClick: () => setComposerMode('edit'),
+ },
+ ]}
/>
}
/>
}>
- <ChatTokenizedText tokens={MENTION_TOKENS}>
- @agent Can you review these auth files? The JWT refresh
- logic seems broken — tokens expire but the middleware
- doesn't catch it.
- </ChatTokenizedText>
- </ChatMessageBubble>
- </ChatMessage>
-
- {/* ── Assistant message with tool calls ── */}
- <ChatMessage
- sender="assistant"
- avatar={<Avatar name="Agent" size="small" />}>
- <ChatMessageBubble variant="ghost" name="Agent">
- Looking into the auth files now. Let me read through the code
- and trace the token refresh flow.
- </ChatMessageBubble>
- <ChatToolCalls
- defaultIsExpanded
- calls={[
- {
- name: 'read',
- target: 'auth-service.ts',
- status: 'complete',
- duration: '45ms',
- },
- {
- name: 'read',
- target: 'middleware.ts',
- status: 'complete',
- duration: '38ms',
- },
- {
- name: 'bash',
- target: 'grep -rn "refreshToken" src/',
- status: 'complete',
- duration: '120ms',
- node: 'cli:remote-server',
- },
- ]}
- />
-
- {/* Markdown response with analysis */}
- <ChatMessageBubble variant="ghost">
- <Markdown density="compact">{`Found the issue. In \`middleware.ts\`, the token validation runs **before** the refresh check. When a token expires, the middleware rejects the request immediately instead of attempting a refresh.
+ <ChatMessageList>
+ {/* Date divider */}
+ <ChatSystemMessage variant="divider">
+ Today
+ </ChatSystemMessage>
+
+ {/* User message: mention + file attachments */}
+ <ChatMessage sender="user">
+ <HStack gap={1} wrap="wrap">
+ <Token label="auth-service.ts" />
+ <Token label="middleware.ts" />
+ </HStack>
+ <ChatMessageBubble
+ metadata={
+ <ChatMessageMetadata
+ timestamp={
+ <Timestamp
+ value="2026-04-29T10:15:00"
+ format="time"
+ />
+ }
+ />
+ }>
+ <ChatTokenizedText tokens={MENTION_TOKENS}>
+ @agent Can you review these auth files? The JWT
+ refresh logic seems broken — tokens expire but the
+ middleware doesn't catch it.
+ </ChatTokenizedText>
+ </ChatMessageBubble>
+ </ChatMessage>
+
+ {/* Assistant message: tool calls, markdown, code block */}
+ <ChatMessage
+ sender="assistant"
+ avatar={<Avatar name="Agent" size="small" />}>
+ <ChatMessageBubble variant="ghost">
+ Looking into the auth files now. Let me read through the
+ code and trace the token refresh flow.
+ </ChatMessageBubble>
+ <ChatToolCalls
+ defaultIsExpanded
+ calls={[
+ {
+ name: 'read',
+ target: 'auth-service.ts',
+ status: 'complete',
+ duration: '45ms',
+ },
+ {
+ name: 'read',
+ target: 'middleware.ts',
+ status: 'complete',
+ duration: '38ms',
+ },
+ {
+ name: 'bash',
+ target: 'grep -rn "refreshToken" src/',
+ status: 'complete',
+ duration: '120ms',
+ node: 'cli:remote-server',
+ },
+ ]}
+ />
+
+ <ChatMessageBubble variant="ghost">
+ <Markdown density="compact">{`Found the issue. In \`middleware.ts\`, the token validation runs **before** the refresh check. When a token expires, the middleware rejects the request immediately instead of attempting a refresh.
Here's the problematic sequence:
@@ -144,14 +421,13 @@ Here's the problematic sequence:
3. The catch block returns \`401\` — never reaching \`refreshToken()\`
The fix is to catch \`TokenExpiredError\` specifically and attempt a refresh before rejecting:`}</Markdown>
- </ChatMessageBubble>
-
- {/* Code block with the fix */}
- <ChatMessageBubble variant="ghost">
- <CodeBlock
- title="middleware.ts"
- language="typescript"
- code={`async function authMiddleware(req: Request) {
+ </ChatMessageBubble>
+
+ <ChatMessageBubble variant="ghost">
+ <CodeBlock
+ title="middleware.ts"
+ language="typescript"
+ code={`async function authMiddleware(req: Request) {
try {
const decoded = validateToken(req.headers.authorization);
req.user = decoded;
@@ -169,88 +445,91 @@ The fix is to catch \`TokenExpiredError\` specifically and attempt a refresh bef
}
return next(req);
}`}
- />
- </ChatMessageBubble>
-
- <ChatToolCalls
- calls={[
- {
- name: 'edit',
- target: 'middleware.ts',
- status: 'complete',
- duration: '85ms',
- additions: 8,
- deletions: 2,
- },
- ]}
- />
-
- <ChatMessageMetadata
- timestamp={
- <Timestamp value="2026-04-29T10:15:30" format="time" />
- }
- footer={
- <Text type="supporting" color="secondary">
- Agent
- </Text>
- }
- />
- </ChatMessage>
-
- {/* ── User multi-bubble follow-up ── */}
- <ChatMessage sender="user">
- <ChatMessageBubble group="first">
- Nice catch, that makes sense
- </ChatMessageBubble>
- <ChatMessageBubble
- group="last"
- metadata={
- <ChatMessageMetadata
- timestamp={
- <Timestamp
- value="2026-04-29T10:16:00"
- format="time"
/>
- }
- status="delivered"
- />
- }>
- Can you also add a test for the refresh path?
- </ChatMessageBubble>
- </ChatMessage>
-
- {/* ── Assistant response with test code ── */}
- <ChatMessage
- sender="assistant"
- avatar={<Avatar name="Agent" size="small" />}>
- <ChatToolCalls
- defaultIsExpanded
- calls={[
- {
- name: 'read',
- target: 'middleware.test.ts',
- status: 'complete',
- duration: '32ms',
- },
- {
- name: 'edit',
- target: 'middleware.test.ts',
- status: 'complete',
- duration: '110ms',
- additions: 24,
- deletions: 0,
- },
- {
- name: 'bash',
- target: 'yarn test middleware',
- status: 'complete',
- duration: '3.2s',
- node: 'cli:remote-server',
- },
- ]}
- />
- <ChatMessageBubble variant="ghost">
- <Markdown density="compact">{`Added a test for the refresh flow. All **4 tests** pass:
+ </ChatMessageBubble>
+
+ <ChatToolCalls
+ calls={[
+ {
+ name: 'edit',
+ target: 'middleware.ts',
+ status: 'complete',
+ duration: '85ms',
+ additions: 8,
+ deletions: 2,
+ },
+ ]}
+ />
+
+ <ChatMessageMetadata
+ timestamp={
+ <Timestamp
+ value="2026-04-29T10:15:30"
+ format="time"
+ />
+ }
+ footer={
+ <Text type="supporting" color="secondary">
+ Agent
+ </Text>
+ }
+ />
+ </ChatMessage>
+
+ {/* User message: multi-bubble grouping */}
+ <ChatMessage sender="user">
+ <ChatMessageBubble group="first">
+ Nice catch, that makes sense
+ </ChatMessageBubble>
+ <ChatMessageBubble
+ group="last"
+ metadata={
+ <ChatMessageMetadata
+ timestamp={
+ <Timestamp
+ value="2026-04-29T10:16:00"
+ format="time"
+ />
+ }
+ status="delivered"
+ />
+ }>
+ Can you also add a test for the refresh path?
+ </ChatMessageBubble>
+ </ChatMessage>
+
+ {/* Assistant message: test results table + code block */}
+ <ChatMessage
+ sender="assistant"
+ avatar={<Avatar name="Agent" size="small" />}>
+ <ChatToolCalls
+ defaultIsExpanded
+ calls={[
+ {
+ name: 'read',
+ target: 'middleware.test.ts',
+ status: 'complete',
+ duration: '32ms',
+ },
+ {
+ name: 'edit',
+ target: 'middleware.test.ts',
+ status: 'complete',
+ duration: '110ms',
+ additions: 24,
+ deletions: 0,
+ },
+ {
+ name: 'bash',
+ target: 'yarn test middleware',
+ status: 'complete',
+ duration: '3.2s',
+ node: 'cli:remote-server',
+ },
+ ]}
+ />
+ <ChatMessageBubble variant="ghost">
+ <Markdown density="compact">{`Added a test for the refresh flow. All **4 tests** pass:
| Test | Status |
|------|--------|
@@ -258,13 +537,13 @@ The fix is to catch \`TokenExpiredError\` specifically and attempt a refresh bef
| Expired token triggers refresh | ✅ |
| Expired token with invalid refresh returns 401 | ✅ |
| Malformed token returns 401 immediately | ✅ |`}</Markdown>
- </ChatMessageBubble>
+ </ChatMessageBubble>
- <ChatMessageBubble variant="ghost">
- <CodeBlock
- title="middleware.test.ts"
- language="typescript"
- code={`describe('authMiddleware', () => {
+ <ChatMessageBubble variant="ghost">
+ <CodeBlock
+ title="middleware.test.ts"
+ language="typescript"
+ code={`describe('authMiddleware', () => {
it('refreshes an expired token silently', async () => {
const expiredToken = createExpiredJWT(mockUser);
const validRefresh = createRefreshToken(mockUser);
@@ -281,66 +560,192 @@ The fix is to catch \`TokenExpiredError\` specifically and attempt a refresh bef
expect(req.newAccessToken).toBeDefined();
});
});`}
+ />
+ </ChatMessageBubble>
+ <ChatMessageMetadata
+ timestamp={
+ <Timestamp
+ value="2026-04-29T10:16:45"
+ format="time"
+ />
+ }
+ />
+ </ChatMessage>
+
+ {/* Status message */}
+ <ChatSystemMessage>
+ Changes saved to workspace
+ </ChatSystemMessage>
+
+ {/* User message: requests a document artifact */}
+ <ChatMessage sender="user">
+ <ChatMessageBubble
+ metadata={
+ <ChatMessageMetadata
+ timestamp={
+ <Timestamp
+ value="2026-04-29T10:18:00"
+ format="time"
+ />
+ }
+ />
+ }>
+ Looks solid. Before I open the PR, can you write up a
+ short design doc explaining the token-refresh flow for
+ the team?
+ </ChatMessageBubble>
+ </ChatMessage>
+
+ {/* Assistant message: artifact card */}
+ <ChatMessage
+ sender="assistant"
+ avatar={<Avatar name="Agent" size="small" />}>
+ <ChatMessageBubble variant="ghost">
+ <Markdown density="compact">
+ {`I've drafted a design doc covering the problem, the fix, and the test matrix — pulling straight from the changes we just made.\n\nOpen the document below to review it. Want me to expand any section?`}
+ </Markdown>
+ </ChatMessageBubble>
+ <ArtifactCard onOpen={openArtifact} />
+ <ChatMessageMetadata
+ timestamp={
+ <Timestamp
+ value="2026-04-29T10:18:40"
+ format="time"
+ />
+ }
+ />
+ </ChatMessage>
+
+ {/* User follow-up */}
+ <ChatMessage sender="user">
+ <ChatMessageBubble
+ metadata={
+ <ChatMessageMetadata
+ timestamp={
+ <Timestamp
+ value="2026-04-29T10:20:00"
+ format="time"
+ />
+ }
+ status="delivered"
+ />
+ }>
+ This is great. Can you add a section on rollout and
+ monitoring at the end?
+ </ChatMessageBubble>
+ </ChatMessage>
+
+ {/* Assistant message: in-progress tool call */}
+ <ChatMessage
+ sender="assistant"
+ avatar={<Avatar name="Agent" size="small" />}>
+ <ChatMessageBubble variant="ghost">
+ <Markdown density="compact">
+ {`On it — adding a **Rollout & Monitoring** section with a staged flag ramp and the alert thresholds. Updating the document now.`}
+ </Markdown>
+ </ChatMessageBubble>
+ <ChatToolCalls
+ calls={[
+ {
+ name: 'edit',
+ target: 'docs/token-refresh.md',
+ status: 'running',
+ node: 'cli:remote-server',
+ },
+ ]}
+ />
+ <ChatMessageMetadata
+ timestamp={
+ <Timestamp
+ value="2026-04-29T10:20:30"
+ format="time"
+ />
+ }
+ />
+ </ChatMessage>
+ </ChatMessageList>
+ </ChatLayout>
+ </VStack>
+
+ {/* Desktop split-pane: resize handle + artifact panel */}
+ {isArtifactOpen && (
+ <>
+ <ResizeHandle
+ direction="horizontal"
+ resizable={artifactResize.props}
+ isReversed
+ pillPlacement="start"
+ hasDivider
+ label="Resize artifact panel"
+ xstyle={styles.resizeHandle}
/>
- </ChatMessageBubble>
- <ChatMessageMetadata
- timestamp={
- <Timestamp value="2026-04-29T10:16:45" format="time" />
- }
- />
- </ChatMessage>
-
- {/* ── System message: status ── */}
- <ChatSystemMessage>
- Changes saved to workspace
- </ChatSystemMessage>
-
- {/* ── User follow-up ── */}
- <ChatMessage sender="user">
- <ChatMessageBubble
- metadata={
- <ChatMessageMetadata
- timestamp={
- <Timestamp
- value="2026-04-29T10:17:00"
- format="time"
+
+ {/* Toolbar as the card header, body below */}
+ <Card
+ variant="transparent"
+ height="100%"
+ xstyle={[
+ styles.artifactPanel,
+ dynamicStyles.artifactPanelWidth(artifactResize.size),
+ ]}>
+ <Toolbar
+ label="Artifact actions"
+ dividers={['bottom']}
+ startContent={
+ <HStack gap={3} vAlign="center">
+ <Icon
+ icon={DocumentTextIcon}
+ size="sm"
+ color="secondary"
+ />
+ <VStack gap={0}>
+ <Text type="label" weight="semibold">
+ {ARTIFACT_TITLE}
+ </Text>
+ <Text type="supporting" color="secondary">
+ {ARTIFACT_SUBTITLE}
+ </Text>
+ </VStack>
+ </HStack>
+ }
+ endContent={
+ <ArtifactActions
+ onClose={() => setIsArtifactOpen(false)}
/>
}
/>
- }>
- Perfect. Ship it — create a PR with these changes.
- </ChatMessageBubble>
- </ChatMessage>
-
- {/* ── Assistant with running tool call ── */}
- <ChatMessage
- sender="assistant"
- avatar={<Avatar name="Agent" size="small" />}>
- <ChatMessageBubble variant="ghost">
- On it — pushing the branch and opening a PR now.
- </ChatMessageBubble>
- <ChatToolCalls
- calls={[
- {
- name: 'bash',
- target: 'git push -u origin fix/jwt-refresh',
- status: 'complete',
- duration: '1.8s',
- node: 'cli:remote-server',
- },
- {
- name: 'bash',
- target: 'gh pr create --title "fix: handle expired JWT…"',
- status: 'running',
- node: 'cli:remote-server',
- },
- ]}
- />
- </ChatMessage>
- </ChatMessageList>
- </ChatLayout>
- </LayoutContent>
- }
- />
+
+ <ArtifactBody />
+ </Card>
+ </>
+ )}
+ </HStack>
+ </LayoutContent>
+ }
+ />
+ {/* Mobile artifact view — full-screen Dialog */}
+ <Dialog
+ isOpen={isArtifactDialogOpen}
+ onOpenChange={setIsArtifactDialogOpen}
+ purpose="info"
+ variant="fullscreen">
+ <Layout
+ header={
+ <DialogHeader
+ title={ARTIFACT_TITLE}
+ subtitle={ARTIFACT_SUBTITLE}
+ hasDivider
+ onOpenChange={setIsArtifactDialogOpen}
+ endContent={<MobileArtifactActions />}
+ />
+ }
+ content={
+ <LayoutContent padding={0}>
+ <ArtifactBody />
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </VStack>
);
}
diff --git a/packages/cli/templates/pages/ai-chat/template.doc.mjs b/packages/cli/templates/pages/ai-chat/template.doc.mjs
index 4a5ea4664a..5dcfda3fd6 100644
--- a/packages/cli/templates/pages/ai-chat/template.doc.mjs
+++ b/packages/cli/templates/pages/ai-chat/template.doc.mjs
@@ -5,7 +5,7 @@ export const doc = {
type: 'page',
name: 'AI Chat Conversation',
displayName: 'AI Chat Conversation',
- description: 'AI assistant conversation view with tool calls, system messages, markdown, code blocks, and multi-bubble grouping',
+ description: 'AI assistant conversation view with tool calls, system messages, markdown, code blocks, multi-bubble grouping, and a resizable artifact preview panel for generated documents',
isReady: true,
category: 'AI Chat - Conversation',
};