Skip to content

The Open Standard for Generative UI

Build the OpenUI Cloud chat demo (#924)

Zahle Khand9e9026a2716
diff --git a/docs/app/(home)/cloud/CloudFeatureMarquee.tsx b/docs/app/(home)/cloud/CloudFeatureMarquee.tsx
index 87c979cfb..be5810296 100644
--- a/docs/app/(home)/cloud/CloudFeatureMarquee.tsx
+++ b/docs/app/(home)/cloud/CloudFeatureMarquee.tsx
@@ -21,7 +21,7 @@ const FEATURES: CloudFeature[] = [
darkImage: "/cloud-features/reports-dark.webp",
},
{
- title: "Presentation generation",
+ title: "Slides generation",
lightImage: "/cloud-features/slides-light.webp",
darkImage: "/cloud-features/slides-dark.webp",
},
@@ -36,17 +36,17 @@ const FEATURES: CloudFeature[] = [
darkImage: "/cloud-features/ui-component-library-dark.webp",
},
{
- title: "Error detection and correction",
+ title: "Error correction",
lightImage: "/cloud-features/error-correction-light.webp",
darkImage: "/cloud-features/error-correction-dark.webp",
},
{
- title: "Managed model access and fallbacks",
+ title: "Provider fallback",
lightImage: "/cloud-features/model-fallbacks-light.webp",
darkImage: "/cloud-features/model-fallbacks-dark.webp",
},
{
- title: "Built-in conversation persistence",
+ title: "Conversation Persistence",
lightImage: "/cloud-features/conversation-history-light.webp",
darkImage: "/cloud-features/conversation-history-dark.webp",
},
diff --git a/docs/app/_components/build-for-free-menu.tsx b/docs/app/_components/build-for-free-menu.tsx
index b2c7bad1d..6b77dea11 100644
--- a/docs/app/_components/build-for-free-menu.tsx
+++ b/docs/app/_components/build-for-free-menu.tsx
@@ -3,6 +3,7 @@
import { ClipboardCommandButton } from "@/app/(home)/components/Button/Button";
import { captureCreateCliCommandCopied } from "@/lib/analytics";
import { ArrowRight } from "lucide-react";
+import { useEffect, useRef } from "react";
import styles from "./build-for-free-menu.module.css";
import { useHeaderDropdown } from "./use-header-dropdown";
@@ -16,11 +17,29 @@ export const CLI_COMMANDS = [
interface BuildForFreeMenuProps {
analyticsSource: "chat_navbar" | "compare_navbar";
className?: string;
+ dataAttributeElement?: string;
+ onOpen?: () => void;
}
-export function BuildForFreeMenu({ analyticsSource, className }: BuildForFreeMenuProps) {
+export function BuildForFreeMenu({
+ analyticsSource,
+ className,
+ dataAttributeElement,
+ onOpen,
+}: BuildForFreeMenuProps) {
const { open, setOpen, wrapRef, triggerRef, handleHoverOpen, handleHoverClose } =
useHeaderDropdown();
+ const onOpenRef = useRef(onOpen);
+ const wasOpenRef = useRef(open);
+
+ useEffect(() => {
+ onOpenRef.current = onOpen;
+ }, [onOpen]);
+
+ useEffect(() => {
+ if (open && !wasOpenRef.current) onOpenRef.current?.();
+ wasOpenRef.current = open;
+ }, [open]);
return (
<div
@@ -35,7 +54,8 @@ export function BuildForFreeMenu({ analyticsSource, className }: BuildForFreeMen
className={styles.button}
aria-haspopup="menu"
aria-expanded={open}
- onClick={() => setOpen((value) => !value)}
+ data-attribute-element={dataAttributeElement}
+ onClick={() => setOpen(!open)}
>
<span>Build for free</span>
<ArrowRight
diff --git a/docs/app/api/openui-cloud/chat/route.ts b/docs/app/api/openui-cloud/chat/route.ts
index b24d53836..e4e8797f6 100644
--- a/docs/app/api/openui-cloud/chat/route.ts
+++ b/docs/app/api/openui-cloud/chat/route.ts
@@ -2,12 +2,14 @@ import { readOpenuiCloudConfig } from "@/lib/openui-cloud/config";
import { unavailableResponse } from "@/lib/openui-cloud/errors";
import { resolveRequestedModel } from "@/lib/openui-cloud/models";
import { hasAllowedOrigin, hasJsonContentType, readLimitedJson } from "@/lib/openui-cloud/request";
-import { artifactTool, createResponsesInstructions } from "@openuidev/thesys-server";
+import { artifactTool, generateSystemPrompt } from "@openuidev/thesys-server";
import OpenAI from "openai";
import type { ResponseInputItem } from "openai/resources/responses/responses";
const MAX_INPUT_ITEMS = 16;
const MAX_THREAD_ID_LENGTH = 256;
+const SLIDES_ARTIFACT_INSTRUCTION = `Create a premium 5–7 slide visual story, not a text document split into slides. Use a strong cover, varied editorial layouts, concise copy, and image_search-sourced absolute image URLs. Every image must depict the exact film, product, person, or location named beside it—never use a metaphorical substitute or generic filler. Do not reuse one image for distinct entities. Include a chart when supplied quantitative data supports one, never invent factual data, avoid repetitive card grids, and finish with a decisive visual takeaway.`;
+const REPORT_ARTIFACT_INSTRUCTION = `Create a premium executive report with a visual cover, clear hierarchy, and a deliberate mix of metrics, charts, tables, imagery, and concise analysis. Use image_search-sourced absolute image URLs only when each image accurately matches its label; never use metaphorical substitutes, unrelated stock photos, or one repeated image for distinct entities. Visualize supplied quantitative data when useful without fabricating facts, vary page composition, and end with specific decisions or next steps.`;
interface CloudChatRequest {
threadId: string;
@@ -44,11 +46,19 @@ export async function POST(request: Request): Promise<Response> {
stream: true,
store: true,
tools: [
- artifactTool({ artifacts: ["slides", "report"] }),
+ artifactTool({
+ artifacts: [
+ { type: "slides", instruction: SLIDES_ARTIFACT_INSTRUCTION },
+ { type: "report", instruction: REPORT_ARTIFACT_INSTRUCTION },
+ ],
+ }),
{ type: "web_search" },
{ type: "image_search" },
],
- instructions: createResponsesInstructions(),
+ instructions: generateSystemPrompt({
+ instructions:
+ "When creating an artifact, actively use the available web and image search tools to ground its content and visual choices.",
+ }),
// The Cloud Responses endpoint extends the stock OpenAI tool union.
} as any,
{ signal: request.signal },
diff --git a/docs/app/chat/_components/agent-surfaces/cloud-agent-surface.tsx b/docs/app/chat/_components/agent-surfaces/cloud-agent-surface.tsx
index 16125deb7..7d5b8c674 100644
--- a/docs/app/chat/_components/agent-surfaces/cloud-agent-surface.tsx
+++ b/docs/app/chat/_components/agent-surfaces/cloud-agent-surface.tsx
@@ -1,44 +1,85 @@
"use client";
+import {
+ captureChatDemoEvent,
+ CHAT_DEMO_EVENTS,
+ getChatDemoArtifactAnalytics,
+ getChatDemoId,
+} from "@/lib/chat-demo-analytics";
+import {
+ OPENUI_CLOUD_LOGO_URL,
+ OPENUI_CLOUD_PROMPT_TEMPLATES,
+ OPENUI_CLOUD_STARTERS,
+} from "@/lib/openui-cloud/chat-constants";
import { createCloudChatLLM } from "@/lib/openui-cloud/chat-llm";
-import { DEFAULT_MODEL } from "@/lib/openui-cloud/models";
import { CLOUD_USER_ID_HEADER, getOrCreateCloudUserId } from "@/lib/openui-cloud/user-id";
-import { defineArtifactCategories } from "@openuidev/react-headless";
-import { AgentInterface } from "@openuidev/react-ui";
+import { useThreadList } from "@openuidev/react-headless";
+import { AgentInterface, defineArtifactCategories, IconButton } from "@openuidev/react-ui";
import {
chatLibrary,
presentationArtifactRenderer,
reportArtifactRenderer,
useOpenuiCloudStorage,
} from "@openuidev/thesys";
+import { FileText, Presentation, SquarePen } from "lucide-react";
+import { useTheme } from "next-themes";
import { useCallback, useEffect, useMemo, useState } from "react";
import styles from "../../chat-page.module.css";
-import { CloudModelSwitcher } from "./cloud-model-switcher";
+import {
+ DemoAwareComposer,
+ DemoAwareModelSwitcher,
+ DemoPathSynchronizer,
+ DemoResponseInteractionGuard,
+ DemoRouteSynchronizer,
+} from "../demo-aware-chat-controls";
+import { DemoConversationList } from "../demo-conversation-list";
+import { createDemoConversationStorage } from "../demo-conversation-storage";
+import { DemoForkRegistry } from "../demo-fork-registry";
+import { SidebarUpgradeFooter } from "../sidebar-upgrade-sheet";
+import { getPersistedCloudModel, usePersistedCloudModel } from "../use-persisted-cloud-model";
-const { artifactRenderers, artifactCategories } = defineArtifactCategories([
- { name: "Presentations", renderers: [presentationArtifactRenderer] },
- { name: "Reports", renderers: [reportArtifactRenderer] },
-]);
+// Blue-to-pink spectrum colors for the stock-comparison demo's line chart,
+// matching the OpenUI Cloud default chart look while keeping every series
+// clearly distinguishable. In series order: META light periwinkle, MSFT dark
+// indigo, NFLX saturated pink, GOOGL deep raspberry, S&P 500 gray.
+// The chart distributes palette colors starting from the middle of the array
+// (see getDistributedColors in @openuidev/react-ui); with five series and five
+// colors the slots resolve back to identity order.
+const STOCK_LINE_PALETTE = ["#91A7FF", "#364FC7", "#F06595", "#A61E4D", "#868E96"];
-const CLOUD_STARTERS = [
- {
- displayText: "Pricing strategy tips",
- prompt: "List five quick tips for pricing a new electric vehicle competitively.",
- },
+const { artifactRenderers, artifactCategories } = defineArtifactCategories([
{
- displayText: "Quarterly deck",
- prompt: "Create a short presentation about our Q2 results with three slides.",
+ name: "Presentations",
+ renderers: [presentationArtifactRenderer],
+ icon: <Presentation size="1em" />,
},
{
- displayText: "Market report",
- prompt: "Write a brief market-analysis report on the EV sector.",
+ name: "Reports",
+ renderers: [reportArtifactRenderer],
+ icon: <FileText size="1em" />,
},
-];
+]);
export function CloudAgentSurface() {
- const [selectedModel, setSelectedModel] = useState(DEFAULT_MODEL);
+ const { resolvedTheme } = useTheme();
+ const mode = resolvedTheme === "dark" ? "dark" : "light";
+ const [selectedModel, setSelectedModel] = usePersistedCloudModel();
const [userId] = useState(getOrCreateCloudUserId);
- const [llm] = useState(createCloudChatLLM);
+ const [forkRegistry] = useState(() => new DemoForkRegistry(userId));
+ const [llm] = useState(() =>
+ createCloudChatLLM({
+ initialModel: getPersistedCloudModel(),
+ shouldSendFullHistory: (threadId) => forkRegistry.shouldSeed(threadId),
+ onFullHistoryAccepted: (threadId) => forkRegistry.markSeeded(threadId),
+ onPromptSubmitted: ({ threadId, model }) => {
+ captureChatDemoEvent(
+ CHAT_DEMO_EVENTS.promptSubmit,
+ getGenerationAnalyticsContext(forkRegistry, threadId, model),
+ );
+ },
+ }),
+ );
+ const [path, setPath] = useState<string>();
const cloudFetch = useMemo<typeof fetch>(() => {
return async (input, init) => {
if (typeof input !== "string" || input !== "/api/openui-cloud/frontend-token") {
@@ -56,48 +97,143 @@ export function CloudAgentSurface() {
features: { artifact: true },
fetch: cloudFetch,
});
+ const storage = useMemo(
+ () => createDemoConversationStorage(cloudStorage, forkRegistry),
+ [cloudStorage, forkRegistry],
+ );
useEffect(() => {
llm.setSelectedModel(selectedModel);
}, [llm, selectedModel]);
+ useEffect(() => {
+ const artifactId = getArtifactIdFromPath(path);
+ const artifact = getChatDemoArtifactAnalytics(artifactId);
+ if (!artifact) return;
+
+ captureChatDemoEvent(CHAT_DEMO_EVENTS.artifactView, {
+ artifact_id: artifact.artifactId,
+ artifact_type: artifact.artifactType,
+ ...(artifact.demoId ? { demo_id: artifact.demoId } : {}),
+ });
+ }, [path]);
+
const handleModelChange = useCallback(
(model: string) => {
llm.setSelectedModel(model);
setSelectedModel(model);
},
- [llm],
+ [llm, setSelectedModel],
);
return (
<div className="chat-agent-surface" data-chat-mode="cloud">
<AgentInterface
- storage={cloudStorage}
+ storage={storage}
llm={llm}
componentLibrary={chatLibrary}
artifactRenderers={artifactRenderers}
artifactCategories={artifactCategories}
- agentName="OpenUI Cloud"
- scrollVariant="always"
- scrollOnLoad={false}
- starterVariant="short"
- starters={CLOUD_STARTERS}
+ logoUrl={OPENUI_CLOUD_LOGO_URL}
+ theme={{ mode, lightTheme: { lineChartPalette: STOCK_LINE_PALETTE } }}
+ starters={OPENUI_CLOUD_STARTERS}
+ path={path}
+ onNavigate={setPath}
>
+ <AgentInterface.Sidebar>
+ <div className="openui-agent-sidebar-actions">
+ <AgentInterface.SidebarHeader />
+ <div className="openui-agent-sidebar-primary-actions">
+ <div className={styles.analyticsContents} data-attribute-element="new-chat">
+ <AgentInterface.NewChatButton />
+ </div>
+ <AgentInterface.ArtifactNav className="openui-agent-sidebar-artifact-nav" />
+ </div>
+ </div>
+ <AgentInterface.SidebarContent>
+ <DemoConversationList onNavigate={setPath} />
+ <AgentInterface.SidebarSeparator />
+ <AgentInterface.ThreadList />
+ </AgentInterface.SidebarContent>
+ <SidebarUpgradeFooter forkRegistry={forkRegistry} />
+ </AgentInterface.Sidebar>
<AgentInterface.MobileHeader
className={styles.cloudMobileHeader}
agentName=""
+ newChatButton={<AnalyticsMobileNewChatButton onNavigate={setPath} />}
actions={
- <CloudModelSwitcher selectedModel={selectedModel} onModelChange={handleModelChange} />
+ <DemoAwareModelSwitcher
+ selectedModel={selectedModel}
+ onModelChange={handleModelChange}
+ />
}
/>
<AgentInterface.ThreadHeader className={styles.cloudThreadHeader}>
- <CloudModelSwitcher selectedModel={selectedModel} onModelChange={handleModelChange} />
+ <DemoAwareModelSwitcher selectedModel={selectedModel} onModelChange={handleModelChange} />
</AgentInterface.ThreadHeader>
<AgentInterface.Welcome
- title="Build with OpenUI Cloud"
- description="Create managed generative interfaces, reports, and presentations."
+ title="Good to see you"
+ description="What's on your mind today?"
+ promptTemplates={OPENUI_CLOUD_PROMPT_TEMPLATES}
+ glowAnimation
/>
+ <AgentInterface.Composer>
+ <div className={styles.analyticsContents} data-attribute-element="composer-submit">
+ <DemoAwareComposer forkRegistry={forkRegistry} onNavigate={setPath} />
+ </div>
+ </AgentInterface.Composer>
+ <DemoPathSynchronizer path={path} onNavigate={setPath} />
+ <DemoRouteSynchronizer onNavigate={setPath} />
+ <DemoResponseInteractionGuard />
</AgentInterface>
</div>
);
}
+
+function AnalyticsMobileNewChatButton({
+ onNavigate,
+}: {
+ onNavigate: (path: string | undefined) => void;
+}) {
+ const switchToNewThread = useThreadList((state) => state.switchToNewThread);
+
+ return (
+ <div className={styles.analyticsContents} data-attribute-element="new-chat">
+ <IconButton
+ size="medium"
+ icon={<SquarePen size="1em" />}
+ onClick={() => {
+ switchToNewThread();
+ onNavigate(undefined);
+ }}
+ variant="secondary"
+ aria-label="New chat"
+ />
+ </div>
+ );
+}
+
+function getGenerationAnalyticsContext(
+ forkRegistry: DemoForkRegistry,
+ threadId: string,
+ model: string,
+) {
+ const demoId = getChatDemoId(forkRegistry.getDemoId(threadId));
+ return {
+ conversation_origin: demoId ? ("demo_continuation" as const) : ("new_chat" as const),
+ model,
+ ...(demoId ? { demo_id: demoId } : {}),
+ };
+}
+
+function getArtifactIdFromPath(path: string | undefined): string | undefined {
+ if (!path?.startsWith("artifacts/")) return undefined;
+ const segments = path.split("/");
+ if (segments.length !== 3 || !segments[2]) return undefined;
+
+ try {
+ return decodeURIComponent(segments[2]);
+ } catch {
+ return undefined;
+ }
+}
diff --git a/docs/app/chat/_components/agent-surfaces/cloud-model-switcher.tsx b/docs/app/chat/_components/agent-surfaces/cloud-model-switcher.tsx
index 8014f7e27..20b4fba55 100644
--- a/docs/app/chat/_components/agent-surfaces/cloud-model-switcher.tsx
+++ b/docs/app/chat/_components/agent-surfaces/cloud-model-switcher.tsx
@@ -1,67 +1,57 @@
"use client";
-import { MODEL_OPTIONS, type ModelOption } from "@/lib/openui-cloud/models";
-import {
- Select,
- SelectContent,
- SelectGroup,
- SelectItem,
- SelectLabel,
- SelectTrigger,
-} from "@openuidev/react-ui";
+import { MODEL_OPTIONS, type ModelOption as CloudModelOption } from "@/lib/openui-cloud/models";
+import { ModelSwitcher, type ModelOption } from "@openuidev/react-ui";
import { useMemo } from "react";
import styles from "../../chat-page.module.css";
+const PROVIDER_ORDER: CloudModelOption["provider"][] = ["Anthropic", "OpenAI", "Google"];
+
interface CloudModelSwitcherProps {
selectedModel: string;
onModelChange: (model: string) => void;
+ disabled?: boolean;
+ disabledReason?: string;
}
-export function CloudModelSwitcher({ selectedModel, onModelChange }: CloudModelSwitcherProps) {
- const selectedOption =
- MODEL_OPTIONS.find((model) => model.id === selectedModel) ?? MODEL_OPTIONS[0];
- const groupedModels = useMemo(() => groupByProvider(MODEL_OPTIONS), []);
+export function CloudModelSwitcher({
+ selectedModel,
+ onModelChange,
+ disabled = false,
+ disabledReason,
+}: CloudModelSwitcherProps) {
+ const models = useMemo(() => createModelOptions(MODEL_OPTIONS), []);
return (
<div className={styles.modelSwitcher}>
- <Select value={selectedModel} onValueChange={onModelChange} size="sm">
- <SelectTrigger
- aria-label="Select model"
- className={styles.modelSwitcherTrigger}
- title={selectedOption?.id ?? selectedModel}
- >
- <span className={styles.modelSwitcherValue}>{selectedOption?.name ?? selectedModel}</span>
- </SelectTrigger>
- <SelectContent align="start" className={styles.modelSwitcherContent}>
- {groupedModels.map(([provider, providerModels]) => (
- <SelectGroup key={provider}>
- <SelectLabel>{provider}</SelectLabel>
- {providerModels.map((model) => (
- <SelectItem key={model.id} value={model.id}>
- <span className={styles.modelOption}>
- <span className={styles.modelOptionHeading}>
- <span className={styles.modelOptionName}>{model.name}</span>
- </span>
- <span className={styles.modelOptionId}>{model.id}</span>
- </span>
- </SelectItem>
- ))}
- </SelectGroup>
- ))}
- </SelectContent>
- </Select>
+ <fieldset
+ className={styles.modelSwitcherFieldset}
+ disabled={disabled}
+ title={disabled ? disabledReason : undefined}
+ >
+ <ModelSwitcher models={models} value={selectedModel} onValueChange={onModelChange} />
+ </fieldset>
</div>
);
}
-function groupByProvider(models: readonly ModelOption[]): [string, ModelOption[]][] {
- const grouped = new Map<string, ModelOption[]>();
-
- for (const model of models) {
- const group = grouped.get(model.provider) ?? [];
- group.push(model);
- grouped.set(model.provider, group);
- }
+function createModelOptions(models: readonly CloudModelOption[]): ModelOption[] {
+ return PROVIDER_ORDER.flatMap((provider) =>
+ models.filter((model) => model.provider === provider),
+ ).map((model) => ({
+ id: model.id,
+ name: model.name,
+ group: model.provider,
+ logo: <ProviderLogo provider={model.provider} />,
+ }));
+}
- return [...grouped.entries()];
+function ProviderLogo({ provider }: { provider: CloudModelOption["provider"] }) {
+ return (
+ <span
+ className={styles.modelProviderLogo}
+ data-provider={provider.toLowerCase()}
+ aria-hidden="true"
+ />
+ );
}
diff --git a/docs/app/chat/_components/chat-page-client.tsx b/docs/app/chat/_components/chat-page-client.tsx
index 64d711e5a..a2ef9ca60 100644
--- a/docs/app/chat/_components/chat-page-client.tsx
+++ b/docs/app/chat/_components/chat-page-client.tsx
@@ -1,13 +1,83 @@
"use client";
-import { DemoCreditsDialog } from "@/components/DemoCreditsDialog";
+import {
+ CHAT_DEMO_EVENTS,
+ captureChatDemoEvent,
+ type ChatDemoHostBreakpoint,
+} from "@/lib/chat-demo-analytics";
import { OPENUI_CLOUD_UNAVAILABLE_MESSAGE } from "@/lib/openui-cloud/errors";
import dynamic from "next/dynamic";
-import { Component, useCallback, useState, type ReactNode } from "react";
+import {
+ Component,
+ useCallback,
+ useEffect,
+ useRef,
+ useSyncExternalStore,
+ type ReactNode,
+} from "react";
import styles from "../chat-page.module.css";
-import { OssAgentSurface } from "./agent-surfaces/oss-agent-surface";
import { ChatPageHeader } from "./chat-page-header";
-import type { ChatMode } from "./chat-types";
+import {
+ getCurrentUrlFormFactor,
+ getServerUrlFormFactor,
+ setCurrentUrlFormFactor,
+ subscribeToCurrentUrlFormFactor,
+ type ViewportPreset,
+} from "./viewport-presets";
+
+type HostViewport = "mobile" | "tablet" | "desktop";
+
+const HOST_VIEWPORT_PRESETS: Record<HostViewport, readonly ViewportPreset[]> = {
+ mobile: ["mobile"],
+ tablet: ["mobile", "tablet"],
+ desktop: ["mobile", "tablet", "desktop"],
+};
+
+const HOST_BREAKPOINTS: Record<HostViewport, ChatDemoHostBreakpoint> = {
+ mobile: "mobile_host",
+ tablet: "tablet_host",
+ desktop: "desktop_host",
+};
+
+function getHostViewport(): HostViewport {
+ if (window.matchMedia("(max-width: 767px)").matches) return "mobile";
+ if (window.matchMedia("(max-width: 1023px)").matches) return "tablet";
+ return "desktop";
+}
+
+function getServerHostViewport(): HostViewport {
+ return "desktop";
+}
+
+function subscribeToHostViewport(onStoreChange: () => void) {
+ const mediaQueries = [
+ window.matchMedia("(max-width: 767px)"),
+ window.matchMedia("(max-width: 1023px)"),
+ ];
+
+ mediaQueries.forEach((mediaQuery) => mediaQuery.addEventListener("change", onStoreChange));
+ return () => {
+ mediaQueries.forEach((mediaQuery) => mediaQuery.removeEventListener("change", onStoreChange));
+ };
+}
+
+function subscribeToBrowserState() {
+ return () => undefined;
+}
+
+function getBrowserState() {
+ return true;
+}
+
+function getServerBrowserState() {
+ return false;
+}
+
+function constrainViewport(viewport: ViewportPreset, hostViewport: HostViewport): ViewportPreset {
+ if (hostViewport === "mobile") return "mobile";
+ if (hostViewport === "tablet" && viewport === "desktop") return "tablet";
+ return viewport;
+}
const CloudAgentSurface = dynamic(
() => import("./agent-surfaces/cloud-agent-surface").then((module) => module.CloudAgentSurface),
@@ -38,49 +108,76 @@ class CloudSurfaceErrorBoundary extends Component<
}
export function ChatPageClient() {
- const [mode, setMode] = useState<ChatMode>("oss");
- const [announcement, setAnnouncement] = useState("");
- const [creditsDialogOpen, setCreditsDialogOpen] = useState(false);
-
- const handleCreditsExhausted = useCallback(() => {
- setCreditsDialogOpen(true);
- }, []);
-
- const requestModeChange = useCallback(
- (nextMode: ChatMode) => {
- if (nextMode === mode) return;
-
- setMode(nextMode);
- setAnnouncement(
- `${nextMode === "oss" ? "OpenUI OSS" : "OpenUI Cloud"} mode selected. New chat started.`,
- );
+ const hasCapturedExperience = useRef(false);
+ const isBrowserStateReady = useSyncExternalStore(
+ subscribeToBrowserState,
+ getBrowserState,
+ getServerBrowserState,
+ );
+ const preferredViewport =
+ useSyncExternalStore(
+ subscribeToCurrentUrlFormFactor,
+ getCurrentUrlFormFactor,
+ getServerUrlFormFactor,
+ ) ?? "desktop";
+ const hostViewport = useSyncExternalStore(
+ subscribeToHostViewport,
+ getHostViewport,
+ getServerHostViewport,
+ );
+ const availableViewports = HOST_VIEWPORT_PRESETS[hostViewport];
+ const viewport = constrainViewport(preferredViewport, hostViewport);
+
+ useEffect(() => {
+ if (!isBrowserStateReady) return;
+ setCurrentUrlFormFactor(viewport);
+ }, [isBrowserStateReady, viewport]);
+
+ useEffect(() => {
+ if (!isBrowserStateReady || hasCapturedExperience.current) return;
+ hasCapturedExperience.current = true;
+
+ captureChatDemoEvent(CHAT_DEMO_EVENTS.experienceView, {
+ host_breakpoint: HOST_BREAKPOINTS[hostViewport],
+ available_preview_count: availableViewports.length as 1 | 2 | 3,
+ initial_preview: viewport,
+ });
+ }, [availableViewports.length, hostViewport, isBrowserStateReady, viewport]);
+
+ const handleViewportChange = useCallback(
+ (nextViewport: ViewportPreset) => {
+ if (nextViewport === viewport) return;
+
+ setCurrentUrlFormFactor(nextViewport);
+ captureChatDemoEvent(CHAT_DEMO_EVENTS.previewChange, {
+ from_preview: viewport,
+ to_preview: nextViewport,
+ host_breakpoint: HOST_BREAKPOINTS[hostViewport],
+ });
},
- [mode],
+ [hostViewport, viewport],
);
return (
<main className={styles.page}>
- <h1 className={styles.srOnly}>OpenUI Chat</h1>
- <ChatPageHeader mode={mode} onModeChange={requestModeChange} />
+ <h1 className={styles.srOnly}>OpenUI Cloud Chat</h1>
+ <ChatPageHeader
+ viewport={viewport}
+ availableViewports={availableViewports}
+ onViewportChange={handleViewportChange}
+ />
<section
className={styles.agentViewport}
- aria-label={`${mode === "oss" ? "OpenUI OSS" : "OpenUI Cloud"} chat`}
+ data-viewport={viewport}
+ aria-label="OpenUI Cloud chat"
>
- {mode === "oss" ? (
- <OssAgentSurface onCreditsExhausted={handleCreditsExhausted} />
- ) : (
+ <div className={styles.agentFrame} data-viewport={viewport}>
<CloudSurfaceErrorBoundary>
<CloudAgentSurface />
</CloudSurfaceErrorBoundary>
- )}
+ </div>
</section>
-
- <p className={styles.srOnly} aria-live="polite">
- {announcement}
- </p>
-
- <DemoCreditsDialog open={creditsDialogOpen} onClose={() => setCreditsDialogOpen(false)} />
</main>
);
}
diff --git a/docs/app/chat/_components/chat-page-header.tsx b/docs/app/chat/_components/chat-page-header.tsx
index bc14a37ef..f83953c11 100644
--- a/docs/app/chat/_components/chat-page-header.tsx
+++ b/docs/app/chat/_components/chat-page-header.tsx
@@ -1,19 +1,31 @@
"use client";
import { BuildForFreeMenu } from "@/app/_components/build-for-free-menu";
+import { CHAT_DEMO_EVENTS, captureChatDemoEvent } from "@/lib/chat-demo-analytics";
import { ToggleGroup } from "@openuidev/react-ui/ToggleGroup";
import { ToggleItem } from "@openuidev/react-ui/ToggleItem";
-import { ArrowLeft } from "lucide-react";
+import { ArrowLeft, Monitor, Smartphone, Tablet } from "lucide-react";
import Link from "next/link";
import styles from "../chat-page.module.css";
-import type { ChatMode } from "./chat-types";
+import { isViewportPreset, type ViewportPreset } from "./viewport-presets";
+
+const VIEWPORT_OPTIONS = [
+ { id: "mobile", label: "Mobile", icon: Smartphone },
+ { id: "tablet", label: "Tablet", icon: Tablet },
+ { id: "desktop", label: "Desktop", icon: Monitor },
+] as const;
interface ChatPageHeaderProps {
- mode: ChatMode;
- onModeChange: (mode: ChatMode) => void;
+ viewport: ViewportPreset;
+ availableViewports: readonly ViewportPreset[];
+ onViewportChange: (viewport: ViewportPreset) => void;
}
-export function ChatPageHeader({ mode, onModeChange }: ChatPageHeaderProps) {
+export function ChatPageHeader({
+ viewport,
+ availableViewports,
+ onViewportChange,
+}: ChatPageHeaderProps) {
return (
<header className={styles.header} aria-label="OpenUI chat controls">
<div className={styles.headerRow}>
@@ -21,26 +33,49 @@ export function ChatPageHeader({ mode, onModeChange }: ChatPageHeaderProps) {
<ArrowLeft aria-hidden="true" size={15} strokeWidth={2} />
</Link>
- <div className={styles.modeControl}>
- <ToggleGroup
- type="single"
- value={mode}
- aria-label="OpenUI implementation"
- className={styles.modeGroup}
- onValueChange={(value) => {
- if (value === "oss" || value === "cloud") onModeChange(value);
- }}
- >
- <ToggleItem id="chat-mode-oss" value="oss" className={styles.modeItem}>
- OpenUI OSS
- </ToggleItem>
- <ToggleItem id="chat-mode-cloud" value="cloud" className={styles.modeItem}>
- OpenUI Cloud
- </ToggleItem>
- </ToggleGroup>
+ <div className={styles.viewportControl}>
+ {availableViewports.length > 1 ? (
+ <ToggleGroup
+ type="single"
+ value={viewport}
+ aria-label="Preview width"
+ className={styles.viewportGroup}
+ onValueChange={(value) => {
+ if (isViewportPreset(value) && availableViewports.includes(value)) {
+ onViewportChange(value);
+ }
+ }}
+ >
+ {VIEWPORT_OPTIONS.filter((option) => availableViewports.includes(option.id)).map(
+ ({ id, label, icon: Icon }) => (
+ <ToggleItem
+ key={id}
+ id={`chat-viewport-${id}`}
+ value={id}
+ data-attribute-element="preview-option"
+ className={
+ id === "desktop"
+ ? `${styles.viewportItem} ${styles.desktopViewportItem}`
+ : styles.viewportItem
+ }
+ aria-label={`Preview ${id} width`}
+ title={`${label} preview`}
+ >
+ <Icon aria-hidden="true" size={15} />
+ <span className={styles.viewportItemLabel}>{label}</span>
+ </ToggleItem>
+ ),
+ )}
+ </ToggleGroup>
+ ) : null}
</div>
- <BuildForFreeMenu analyticsSource="chat_navbar" className={styles.buildForFreeMenu} />
+ <BuildForFreeMenu
+ analyticsSource="chat_navbar"
+ className={styles.buildForFreeMenu}
+ dataAttributeElement="build-for-free"
+ onOpen={() => captureChatDemoEvent(CHAT_DEMO_EVENTS.buildMenuOpen, {})}
+ />
</div>
</header>
);
diff --git a/docs/app/chat/_components/demo-aware-chat-controls.tsx b/docs/app/chat/_components/demo-aware-chat-controls.tsx
new file mode 100644
index 000000000..2e48cab40
--- /dev/null
+++ b/docs/app/chat/_components/demo-aware-chat-controls.tsx
@@ -0,0 +1,289 @@
+"use client";
+
+import { CHAT_DEMO_EVENTS, captureChatDemoEvent, getChatDemoId } from "@/lib/chat-demo-analytics";
+import { useThreadList } from "@openuidev/react-headless";
+import { AgentInterface } from "@openuidev/react-ui";
+import { usePathname, useRouter } from "next/navigation";
+import { useEffect, useRef, useState } from "react";
+import styles from "../chat-page.module.css";
+import { CloudModelSwitcher } from "./agent-surfaces/cloud-model-switcher";
+import {
+ getDemoConversation,
+ getDemoConversationBySlug,
+ getDemoConversationPath,
+ getDemoFirstUserMessage,
+ type DemoConversation,
+} from "./demo-conversations";
+import type { DemoForkRegistry } from "./demo-fork-registry";
+import { preserveCurrentUrlSearch } from "./viewport-presets";
+
+interface DemoAwareModelSwitcherProps {
+ selectedModel: string;
+ onModelChange: (model: string) => void;
+}
+
+export function DemoAwareModelSwitcher({
+ selectedModel,
+ onModelChange,
+}: DemoAwareModelSwitcherProps) {
+ const selectedThreadId = useThreadList((state) => state.selectedThreadId);
+ const demo = getDemoConversation(selectedThreadId);
+ const disabledReason = demo ? "This read-only demo uses a fixed recorded model." : undefined;
+
+ return (
+ <CloudModelSwitcher
+ selectedModel={demo?.recordedModel ?? selectedModel}
+ onModelChange={onModelChange}
+ disabled={disabledReason !== undefined}
+ disabledReason={disabledReason}
+ />
+ );
+}
+
+interface DemoAwareComposerProps {
+ forkRegistry: DemoForkRegistry;
+ onNavigate: (path: string | undefined) => void;
+}
+
+export function DemoAwareComposer({ forkRegistry, onNavigate }: DemoAwareComposerProps) {
+ const selectedThreadId = useThreadList((state) => state.selectedThreadId);
+ const demo = getDemoConversation(selectedThreadId);
+
+ if (!demo) return <AgentInterface.Composer />;
+
+ return (
+ <ReadOnlyDemoComposer
+ key={demo.id}
+ demo={demo}
+ forkRegistry={forkRegistry}
+ onNavigate={onNavigate}
+ />
+ );
+}
+
+/**
+ * Keep recorded GenUI responses inert without disabling artifact previews or
+ * the explicit continuation CTA. The published renderer does not expose a
+ * read-only prop, so mark only its direct response roots while a fixture thread
+ * is selected. Private continuations immediately regain normal interactivity.
+ */
+export function DemoResponseInteractionGuard() {
+ const selectedThreadId = useThreadList((state) => state.selectedThreadId);
+ const isDemo = getDemoConversation(selectedThreadId) !== undefined;
+ const markerRef = useRef<HTMLSpanElement>(null);
+
+ useEffect(() => {
+ const surface = markerRef.current?.closest(".chat-agent-surface");
+ if (!(surface instanceof HTMLElement)) return;
+
+ const markedRoots = new Set<HTMLElement>();
+ const markedControls = new Map<
+ HTMLElement,
+ { ariaDisabled: string | null; inert: string | null; tabIndex: string | null }
+ >();
+ const clearMarkedRoots = () => {
+ for (const [control, previous] of markedControls) {
+ restoreAttribute(control, "aria-disabled", previous.ariaDisabled);
+ restoreAttribute(control, "inert", previous.inert);
+ restoreAttribute(control, "tabindex", previous.tabIndex);
+ }
+ markedControls.clear();
+
+ for (const root of markedRoots) {
+ root.removeAttribute("data-openui-demo-readonly-renderer");
+ }
+ markedRoots.clear();
+ };
+ const markResponseRoots = () => {
+ clearMarkedRoots();
+ if (!isDemo) return;
+
+ for (const content of surface.querySelectorAll(
+ ".openui-shell-thread-message-assistant__content",
+ )) {
+ const root = content.lastElementChild;
+ if (!(root instanceof HTMLElement) || root.style.position !== "relative") continue;
+
+ root.setAttribute("data-openui-demo-readonly-renderer", "true");
+ markedRoots.add(root);
+
+ for (const control of root.querySelectorAll<HTMLElement>(READ_ONLY_CONTROL_SELECTOR)) {
+ markedControls.set(control, {
+ ariaDisabled: control.getAttribute("aria-disabled"),
+ inert: control.getAttribute("inert"),
+ tabIndex: control.getAttribute("tabindex"),
+ });
+ control.setAttribute("aria-disabled", "true");
+ control.setAttribute("inert", "");
+ control.setAttribute("tabindex", "-1");
+ }
+ }
+ };
+
+ markResponseRoots();
+ const observer = new MutationObserver(markResponseRoots);
+ observer.observe(surface, { childList: true, subtree: true });
+
+ return () => {
+ observer.disconnect();
+ clearMarkedRoots();
+ };
+ }, [isDemo]);
+
+ return <span ref={markerRef} className={styles.demoReadOnlyMarker} aria-hidden="true" />;
+}
+
+const READ_ONLY_CONTROL_SELECTOR =
+ 'a[href], button, input, textarea, select, [contenteditable="true"], [role="button"], [role="checkbox"], [role="combobox"], [role="link"], [role="menuitem"], [role="option"], [role="radio"], [role="slider"], [role="spinbutton"], [role="switch"], [role="tab"]';
+
+function restoreAttribute(element: HTMLElement, name: string, value: string | null) {
+ if (value === null) element.removeAttribute(name);
+ else element.setAttribute(name, value);
+}
+
+interface ReadOnlyDemoComposerProps {
+ demo: DemoConversation;
+ forkRegistry: DemoForkRegistry;
+ onNavigate: (path: string | undefined) => void;
+}
+
+function ReadOnlyDemoComposer({ demo, forkRegistry, onNavigate }: ReadOnlyDemoComposerProps) {
+ const createThread = useThreadList((state) => state.createThread);
+ const updateThread = useThreadList((state) => state.updateThread);
+ const selectThread = useThreadList((state) => state.selectThread);
+ const [isCreating, setIsCreating] = useState(false);
+ const [error, setError] = useState("");
+
+ const continueInNewChat = async () => {
+ if (isCreating) return;
+ setIsCreating(true);
+ setError("");
+
+ try {
+ const firstMessage = getDemoFirstUserMessage(demo);
+ const thread = await createThread({ ...firstMessage, id: crypto.randomUUID() });
+ const continuation = { ...thread, title: `${demo.title} continuation` };
+ forkRegistry.register(thread.id, demo.id);
+ updateThread(continuation);
+ selectThread(thread.id);
+ onNavigate(undefined);
+ const demoId = getChatDemoId(demo.id);
+ if (demoId) {
+ captureChatDemoEvent(CHAT_DEMO_EVENTS.continuationCreate, { demo_id: demoId });
+ }
+ } catch {
+ setError("Could not create a continuation. Please try again.");
+ setIsCreating(false);
+ }
+ };
+
+ return (
+ <div className={styles.demoComposerState}>
+ <button
+ type="button"
+ className={styles.demoComposerCta}
+ data-attribute-element="continue-conversation"
+ onClick={continueInNewChat}
+ disabled={isCreating}
+ >
+ {isCreating ? "Creating chat…" : "Continue conversation"}
+ </button>
+ {error && (
+ <p className={styles.demoComposerError} role="alert">
+ {error}
+ </p>
+ )}
+ </div>
+ );
+}
+
+interface DemoPathSynchronizerProps {
+ path: string | undefined;
+ onNavigate: (path: string | undefined) => void;
+}
+
+export function DemoPathSynchronizer({ path, onNavigate }: DemoPathSynchronizerProps) {
+ const selectedThreadId = useThreadList((state) => state.selectedThreadId);
+
+ useEffect(() => {
+ if (path?.startsWith("demo/") && !getDemoConversation(selectedThreadId)) {
+ onNavigate(undefined);
+ }
+ }, [onNavigate, path, selectedThreadId]);
+
+ return null;
+}
+
+/**
+ * Keep public demo URLs and the selected fixture thread in sync. Browser
+ * navigation wins when the pathname changes; otherwise thread selection owns
+ * the URL. Private continuations and ordinary chats intentionally use /chat.
+ */
+export function DemoRouteSynchronizer({
+ onNavigate,
+}: {
+ onNavigate: (path: string | undefined) => void;
+}) {
+ const pathname = usePathname();
+ const router = useRouter();
+ const selectedThreadId = useThreadList((state) => state.selectedThreadId);
+ const selectThread = useThreadList((state) => state.selectThread);
+ const switchToNewThread = useThreadList((state) => state.switchToNewThread);
+ const previousPathname = useRef(pathname);
+ const previousThreadId = useRef(selectedThreadId);
+ const isInitialized = useRef(false);
+ const selectionDrivenPathnames = useRef(new Set<string>());
+ const lastCapturedDemoId = useRef<string | undefined>(undefined);
+
+ useEffect(() => {
+ const pathnameChanged = previousPathname.current !== pathname;
+ const threadChanged = previousThreadId.current !== selectedThreadId;
+ previousPathname.current = pathname;
+ previousThreadId.current = selectedThreadId;
+
+ if (pathnameChanged && selectionDrivenPathnames.current.delete(pathname)) {
+ return;
+ }
+
+ if (!isInitialized.current || pathnameChanged) {
+ isInitialized.current = true;
+ const routeDemo = getDemoConversationFromPathname(pathname);
+
+ if (routeDemo && selectedThreadId !== routeDemo.id) {
+ onNavigate(undefined);
+ selectThread(routeDemo.id);
+ } else if (pathname === "/chat" && selectedThreadId !== null) {
+ switchToNewThread();
+ }
+ return;
+ }
+
+ if (!threadChanged) return;
+
+ const selectedDemo = getDemoConversation(selectedThreadId);
+ const nextPathname = selectedDemo ? getDemoConversationPath(selectedDemo) : "/chat";
+ if (pathname !== nextPathname) {
+ selectionDrivenPathnames.current.add(nextPathname);
+ router.push(preserveCurrentUrlSearch(nextPathname));
+ }
+ }, [onNavigate, pathname, router, selectThread, selectedThreadId, switchToNewThread]);
+
+ useEffect(() => {
+ const demoId = getChatDemoId(getDemoConversation(selectedThreadId)?.id);
+ if (!demoId) {
+ lastCapturedDemoId.current = undefined;
+ return;
+ }
+ if (lastCapturedDemoId.current === demoId) return;
+
+ lastCapturedDemoId.current = demoId;
+ captureChatDemoEvent(CHAT_DEMO_EVENTS.threadView, { demo_id: demoId });
+ }, [selectedThreadId]);
+
+ return null;
+}
+
+function getDemoConversationFromPathname(pathname: string): DemoConversation | undefined {
+ const match = /^\/chat\/demo\/([^/]+)$/.exec(pathname);
+ return match ? getDemoConversationBySlug(match[1]) : undefined;
+}
diff --git a/docs/app/chat/_components/demo-conversation-list.tsx b/docs/app/chat/_components/demo-conversation-list.tsx
new file mode 100644
index 000000000..f2cc2723e
--- /dev/null
+++ b/docs/app/chat/_components/demo-conversation-list.tsx
@@ -0,0 +1,45 @@
+"use client";
+
+import type { ReactNode } from "react";
+
+import { useThreadList } from "@openuidev/react-headless";
+import { AgentInterface } from "@openuidev/react-ui";
+import { ChartNoAxesCombined, Film, Flower } from "lucide-react";
+import styles from "../chat-page.module.css";
+import { DEMO_CONVERSATIONS, type DemoConversationIcon } from "./demo-conversations";
+
+const ICONS: Record<DemoConversationIcon, ReactNode> = {
+ analytics: <ChartNoAxesCombined aria-hidden="true" size={15} />,
+ travel: <Flower aria-hidden="true" size={15} />,
+ compare: <Film aria-hidden="true" size={15} />,
+};
+
+interface DemoConversationListProps {
+ onNavigate: (path: string | undefined) => void;
+}
+
+export function DemoConversationList({ onNavigate }: DemoConversationListProps) {
+ const selectThread = useThreadList((state) => state.selectThread);
+ const selectedThreadId = useThreadList((state) => state.selectedThreadId);
+
+ return (
+ <div className={styles.demoThreadGroup} aria-label="Demo threads">
+ <div className={styles.demoThreadGroupLabel}>Featured demos</div>
+ {DEMO_CONVERSATIONS.map((conversation) => (
+ <AgentInterface.SidebarItem
+ key={conversation.id}
+ selected={selectedThreadId === conversation.id}
+ icon={ICONS[conversation.icon]}
+ data-attribute-element="featured-demo"
+ aria-label={`${conversation.title}, ${conversation.description}, read-only demo thread`}
+ onClick={() => {
+ onNavigate(undefined);
+ selectThread(conversation.id);
+ }}
+ >
+ {conversation.title}
+ </AgentInterface.SidebarItem>
+ ))}
+ </div>
+ );
+}
diff --git a/docs/app/chat/_components/demo-conversation-storage.ts b/docs/app/chat/_components/demo-conversation-storage.ts
new file mode 100644
index 000000000..2f9f89650
--- /dev/null
+++ b/docs/app/chat/_components/demo-conversation-storage.ts
@@ -0,0 +1,91 @@
+import type { ChatStorage } from "@openuidev/react-headless";
+import {
+ cloneDemoMessages,
+ DEMO_ARTIFACTS,
+ getDemoArtifact,
+ getDemoConversation,
+} from "./demo-conversations";
+import type { DemoForkRegistry } from "./demo-fork-registry";
+
+export function createDemoConversationStorage(
+ cloudStorage: ChatStorage,
+ forkRegistry: DemoForkRegistry,
+): ChatStorage {
+ const cloudArtifactStorage = cloudStorage.artifact;
+
+ return {
+ ...cloudStorage,
+ thread: {
+ ...cloudStorage.thread,
+ async getMessages(threadId) {
+ const directDemo = getDemoConversation(threadId);
+ if (directDemo) return cloneDemoMessages(directDemo);
+
+ const forkedDemoId = forkRegistry.getDemoId(threadId);
+ const forkedDemo = getDemoConversation(forkedDemoId);
+ if (forkedDemo) {
+ try {
+ const persistedMessages = await cloudStorage.thread.getMessages(threadId);
+ if (persistedMessages.length > 0) return persistedMessages;
+ } catch {
+ // A newly-created continuation has no stored messages until its first response.
+ }
+ return cloneDemoMessages(forkedDemo);
+ }
+
+ return cloudStorage.thread.getMessages(threadId);
+ },
+ async deleteThread(threadId) {
+ try {
+ await cloudStorage.thread.deleteThread(threadId);
+ } finally {
+ forkRegistry.remove(threadId);
+ }
+ },
+ },
+ ...(cloudArtifactStorage
+ ? {
+ artifact: {
+ async list(params) {
+ let cloudResult: Awaited<ReturnType<typeof cloudArtifactStorage.list>> = {
+ artifacts: [],
+ };
+ try {
+ cloudResult = await cloudArtifactStorage.list(params);
+ } catch {
+ // Keep the built-in examples available when Cloud storage is unavailable.
+ }
+ if (params?.cursor) return cloudResult;
+
+ const query = params?.name?.trim().toLowerCase();
+ const demoArtifacts = DEMO_ARTIFACTS.filter(
+ (artifact) =>
+ (!query || artifact.title.toLowerCase().includes(query)) &&
+ (!params?.type || params.type.includes(artifact.type)),
+ ).map(({ content: _content, program: _program, ...artifact }) => artifact);
+ const demoIds = new Set<string>(demoArtifacts.map((artifact) => artifact.id));
+
+ return {
+ artifacts: [
+ ...demoArtifacts,
+ ...cloudResult.artifacts.filter((artifact) => !demoIds.has(artifact.id)),
+ ],
+ nextCursor: cloudResult.nextCursor,
+ };
+ },
+ async get(id) {
+ const demoArtifact = getDemoArtifact(id);
+ if (demoArtifact) return structuredClone(demoArtifact);
+ return cloudArtifactStorage.get(id);
+ },
+ async update(patch) {
+ if (getDemoArtifact(patch.id)) {
+ throw new Error("Demo artifacts are read-only.");
+ }
+ return cloudArtifactStorage.update(patch);
+ },
+ },
+ }
+ : {}),
+ };
+}
diff --git a/docs/app/chat/_components/demo-conversations.ts b/docs/app/chat/_components/demo-conversations.ts
new file mode 100644
index 000000000..19638cbb8
--- /dev/null
+++ b/docs/app/chat/_components/demo-conversations.ts
@@ -0,0 +1,849 @@
+import { DEFAULT_MODEL } from "@/lib/openui-cloud/models";
+import type { Artifact, Message, UserMessage } from "@openuidev/react-headless";
+import { STOCK_REPORT_PROGRAM } from "./stock-report-program";
+
+export type DemoConversationIcon = "analytics" | "travel" | "compare";
+export type DemoArtifactKind = "report" | "slides";
+
+export interface DemoArtifact extends Artifact {
+ id: `demo_artifact_${string}`;
+ type: DemoArtifactKind;
+ content: string;
+ program: string;
+}
+
+export interface DemoConversation {
+ id: `demo_${string}`;
+ slug: string;
+ title: string;
+ description: string;
+ icon: DemoConversationIcon;
+ sourcePrompt: string;
+ recordedModel: string;
+ linkedArtifactId?: DemoArtifact["id"];
+ messages: Message[];
+}
+
+const DEMO_IMAGES = {
+ ai: "https://images.unsplash.com/photo-1620712943543-bcc4688e7485?auto=format&fit=crop&w=1600&q=82",
+ cinema:
+ "https://images.unsplash.com/photo-1489599849927-2ee91cede3ba?auto=format&fit=crop&w=1600&q=82",
+ cinemaAudience:
+ "https://images.unsplash.com/photo-1517604931442-7e0c8ed2963c?auto=format&fit=crop&w=1600&q=82",
+ cinemaProjector:
+ "https://images.unsplash.com/photo-1478720568477-152d9b164e26?auto=format&fit=crop&w=1600&q=82",
+ coffee:
+ "https://images.unsplash.com/photo-1495474472287-4d71bcdd2085?auto=format&fit=crop&w=1600&q=82",
+ coffeeBeans:
+ "https://images.unsplash.com/photo-1447933601403-0c6688de566e?auto=format&fit=crop&w=1600&q=82",
+ collaboration:
+ "https://images.unsplash.com/photo-1522071820081-009f0129c71c?auto=format&fit=crop&w=1600&q=82",
+ dashboard:
+ "https://images.unsplash.com/photo-1551288049-bebda4e38f71?auto=format&fit=crop&w=1600&q=82",
+ japan:
+ "https://images.unsplash.com/photo-1493976040374-85c8e12f0c0e?auto=format&fit=crop&w=1600&q=82",
+ japanLandscape:
+ "https://images.unsplash.com/photo-1509023464722-18d996393ca8?auto=format&fit=crop&w=1600&q=82",
+ japanStreet:
+ "https://images.unsplash.com/photo-1624253321171-1be53e12f5f4?auto=format&fit=crop&w=1600&q=82",
+ office:
+ "https://images.unsplash.com/photo-1497366754035-f200968a6e72?auto=format&fit=crop&w=1600&q=82",
+ planning:
+ "https://images.unsplash.com/photo-1552664730-d307ca884978?auto=format&fit=crop&w=1600&q=82",
+ posterAvatar: "https://image.tmdb.org/t/p/w1280/kyeqWdyUXW608qlYkRqosgbbJyK.jpg",
+ posterEndgame: "https://image.tmdb.org/t/p/w1280/or06FN3Dka5tukK1e9sl16pB3iy.jpg",
+ posterWayOfWater: "https://image.tmdb.org/t/p/w1280/t6HIqrRAclMCA60NsSmeqe9RmNV.jpg",
+ stadium:
+ "https://images.unsplash.com/photo-1522778119026-d647f0596c20?auto=format&fit=crop&w=1600&q=82",
+ stock:
+ "https://images.unsplash.com/photo-1611974789855-9c2a0a7236a3?auto=format&fit=crop&w=1600&q=82",
+ technology:
+ "https://images.unsplash.com/photo-1518770660439-4636190af475?auto=format&fit=crop&w=1600&q=82",
+} as const;
+
+const TRAVEL_DECK_PROGRAM = `root = SlideShow("Must-See Japan", "A first-timer's highlight tour", [cover, contrast, cities, route, rhythm, closing])
+cover = Slide("cover", DramaticTitle("Must-See Japan", "Cities, temples, mountains, and food", "An eight-day first-timer's route", null, "title-bottom", "${DEMO_IMAGES.japanLandscape}"))
+contrast = Slide("contrast", ContentWithImage("Old meets new", ["${DEMO_IMAGES.japan}", "${DEMO_IMAGES.japanStreet}"], "Move from neon districts to quiet shrines in a single afternoon, then connect the trip by fast, reliable rail.", "image-center"))
+cities = Slide("cities", VisualCards("Three essential bases", [{title: "Tokyo", body: "Energy, design, food, and late-night neighborhoods.", imageSrc: "${DEMO_IMAGES.japanStreet}"}, {title: "Kyoto", body: "Temples, gardens, craft, and early-morning calm.", imageSrc: "${DEMO_IMAGES.japan}"}, {title: "Osaka", body: "A relaxed base for street food and Kansai day trips.", imageSrc: "${DEMO_IMAGES.japanLandscape}"}]))
+route = Slide("route", ChartWithContext("Eight-day route", BarChartV2({data: {labels: ["Tokyo", "Hakone", "Kyoto", "Osaka"], series: [{category: "Nights", values: [3, 1, 3, 1]}]}}, "City", "Nights"), "Keep transfers light and give Kyoto enough unhurried mornings.", "title-body-top"))
+rhythm = Slide("rhythm", MetricsWithImage("A trip with room to breathe", [{metric: "8 days", description: "Enough for four bases"}, {metric: "3 cities", description: "The cultural spine"}, {metric: "1 bag", description: "Use luggage forwarding"}], ["${DEMO_IMAGES.japan}", "${DEMO_IMAGES.japanLandscape}"]))
+closing = Slide("closing", HeroMetric("Tokyo → Osaka", "Fly into Tokyo, out of Osaka, and let the route unfold in one direction.", "vertical", "${DEMO_IMAGES.japanStreet}"))`;
+
+const BLOCKBUSTER_DECK_PROGRAM = `root = SlideShow("Blockbuster Box Office", "The Economics of Event Cinema", slides)
+slides = [slide1, slide2, slide3, slide4, slide5, slide6, slide7]
+
+slide1 = Slide("slide-1", content1)
+content1 = DramaticTitle("Blockbuster Box Office", "What the three highest-grossing films reveal about event cinema", "WORLDWIDE BOX OFFICE · $8.06B across three films", null, "title-center", "https://cdn.celluloidjunkie.com/wp-content/uploads/2025/12/10015609/UAE-Vox-Mall-of-Emirates-IMAX-Oma-Cinema-Ferco-Seating.jpg")
+
+slide2 = Slide("slide-2", content2)
+content2 = VisualCards("Meet the All-Time Podium", cards2)
+cards2 = [card2a, card2b, card2c]
+card2a = {
+ title: "#1 · Avatar (2009) — $2.92B",
+ body: "#1 All-Time Record. Theatrical spectacle with extraordinary international reach.",
+ imageSrc: "https://m.media-amazon.com/images/M/MV5BMDEzMmQwZjctZWU2My00MWNlLWE0NjItMDJlYTRlNGJiZjcyXkEyXkFqcGc@._V1_FMjpg_UX1000_.jpg"
+}
+card2b = {
+ title: "#2 · Avengers: Endgame (2019) — $2.80B",
+ body: "#2 MCU Peak. The payoff to an unprecedented connected-film narrative.",
+ imageSrc: "https://m.media-amazon.com/images/M/MV5BMTc5MDE2ODcwNV5BMl5BanBnXkFtZTgwMzI2NzQ2NzM@._V1_FMjpg_UX1000_.jpg"
+}
+card2c = {
+ title: "#3 · Avatar: The Way of Water (2022) — $2.33B",
+ body: "#3 Cameron Returns. Premium formats and a sustained long theatrical run.",
+ imageSrc: "https://m.media-amazon.com/images/M/MV5BNWI0Y2NkOWEtMmM2OC00MjQ3LWI1YzItZGQxYzQ3NzI4NWZmXkEyXkFqcGc@._V1_.jpg"
+}
+
+slide3 = Slide("slide-3", content3)
+content3 = ChartWithMetrics("Three Films. $8.06 Billion.", metrics3, chart3)
+metrics3 = [metric3a, metric3b, metric3c, metric3d]
+metric3a = {
+ metric: "$8.06B",
+ description: "Combined gross across top 3 films"
+}
+metric3b = {
+ metric: "$2.69B",
+ description: "Average gross per film"
+}
+metric3c = {
+ metric: "3 Films",
+ description: "Holding the all-time podium"
+}
+metric3d = {
+ metric: "13 Years",
+ description: "2009 to 2022 timeline span"
+}
+
+chart3 = BarChartV2(chartData3, "Film", "USD Billions")
+chartData3 = {
+ data: {
+ labels: ["Avatar", "Avengers: Endgame", "Avatar: Way of Water"],
+ series: [series3]
+ },
+ unit: "b"
+}
+series3 = {
+ category: "Worldwide Gross",
+ values: [2.92, 2.80, 2.33]
+}
+
+slide4 = Slide("slide-4", content4)
+content4 = ChartWithContext("Domestic Is Not the Story", chart4, "Global theatrical reach separates these films from ordinary blockbusters. ~71% of revenue came from international markets, earning more abroad than any domestic release in the same year.", "title-body-left")
+
+chart4 = BarChartV2(chartData4, "Film", "USD Billions")
+chartData4 = {
+ data: {
+ labels: ["Avatar", "Avengers: Endgame", "Avatar: Way of Water"],
+ series: [series4a, series4b]
+ },
+ unit: "b"
+}
+series4a = {
+ category: "Domestic",
+ values: [0.79, 0.86, 0.69]
+}
+series4b = {
+ category: "International",
+ values: [2.14, 1.94, 1.65]
+}
+
+slide5 = Slide("slide-5", content5)
+content5 = KeyInfoWithTitle("One Director. Two Records.", infoItems5, "horizontal-grid")
+infoItems5 = [item5a, item5b, item5c, item5d]
+item5a = {
+ title: "2 of Top 3",
+ description: "James Cameron holds two positions on the all-time worldwide podium."
+}
+item5b = {
+ title: "$5.25 Billion",
+ description: "Combined gross of the Avatar franchise from just two releases."
+}
+item5c = {
+ title: "≈ 65% Share",
+ description: "Cameron's portion of total revenue generated by the top three films."
+}
+item5d = {
+ title: "13 Years Gap",
+ description: "Between Avatar releases, proving long-term brand equity and anticipation."
+}
+
+slide6 = Slide("slide-6", content6)
+content6 = ChartWithMetrics("Volume vs. Efficiency", metrics6, chart6)
+metrics6 = [metric6a, metric6b]
+metric6a = {
+ metric: "$2.63B / film",
+ description: "Avatar average efficiency"
+}
+metric6b = {
+ metric: "3.0x",
+ description: "Efficiency vs next closest franchise"
+}
+
+chart6 = BarChartV2(chartData6, "Franchise", "USD Billions")
+chartData6 = {
+ data: {
+ labels: ["MCU (~38 films)", "Star Wars (~12 films)", "Wizarding World (~10)", "James Bond (~25)", "Avatar (2 films)"],
+ series: [series6]
+ },
+ unit: "b"
+}
+series6 = {
+ category: "Total Franchise Gross",
+ values: [33.4, 10.3, 8.8, 7.9, 5.25]
+}
+
+slide7 = Slide("slide-7", content7)
+content7 = SectionBreakDramatic("Make It Unmissable", "Spectacle creates a reason to choose the largest screen. Global releases turn opening weekend into a shared cultural event, while premium formats extend lifetime value.", "vertical", "https://www.nseled.com/wp-content/uploads/2026/02/Immersive-cinema-experience-with-ultra-wide-curved-LED-display.jpg")`;
+
+const BUSINESS_HEALTH_REPORT_PROGRAM = `root = ReportView("Q2 Business Health", "Executive operating review · Illustrative data", [cover, executive, performance, customers, actions])
+cover = Page("cover", StandardFrontPage("Q2 Business Health", "${DEMO_IMAGES.dashboard}", coverCopy, "April–June 2026", "title-left"))
+coverCopy = TextContent("A decision-ready view of growth, efficiency, customer health, and the priorities leadership should carry into Q3.")
+executive = Page("executive", ContentPage([executiveHeader, metrics, executiveStatement]))
+executiveHeader = InlineHeader("Executive summary", "Growth finished ahead of plan without weakening retention or gross margin.")
+metrics = KeyMetrics("row", [{title: "Revenue", text: "$1.40M"}, {title: "Gross margin", text: "72%"}, {title: "Retention", text: "94%"}, {title: "Pipeline", text: "3.2×"}])
+executiveStatement = HeadlineStatement("The quarter closed 6% above plan", "Expansion revenue offset a slower enterprise sales cycle while the company preserved pricing discipline.", "default")
+performance = Page("performance", ContentPage([performanceHeader, revenueChart]))
+performanceHeader = InlineHeader("Revenue versus target", "Actual monthly revenue accelerated through the quarter.")
+revenueChart = BarChartV2({data: {labels: ["April", "May", "June"], series: [{category: "Actual", values: [420, 468, 515]}, {category: "Target", values: [400, 445, 490]}]}, unit: "k"}, "grouped", false, "Month", "Revenue")
+customers = Page("customers", ContentPage([customerHeader, customerMix, customerImage]))
+customerHeader = InlineHeader("A durable revenue base", "Existing customers still contribute most of the quarter's recurring revenue.")
+customerMix = PieChartV2({data: [{category: "Renewal", value: 58}, {category: "Expansion", value: 24}, {category: "New logo", value: 18}]})
+customerImage = Image("${DEMO_IMAGES.collaboration}", "Team reviewing business performance")
+actions = Page("actions", ContentPage([actionsHeader, actionPoints]))
+actionsHeader = InlineHeader("Decisions for Q3", "Three actions protect the plan while preserving efficient growth.")
+actionPoints = NumberedKeyPoint("column", [{title: "Shorten enterprise cycles", body: "Add executive sponsorship to the largest late-stage opportunities."}, {title: "Protect pricing", body: "Review discounts above the operating threshold."}, {title: "Expand healthy accounts", body: "Prioritize strong adoption and near-term renewals."}])`;
+
+const PRODUCT_DECISION_REPORT_PROGRAM = `root = ReportView("Project Platform Decision Brief", "Recommendation for a 25-person product organization", [cover, recommendation, comparison, scoring, rollout])
+cover = Page("cover", StandardFrontPage("Project Platform Decision Brief", "${DEMO_IMAGES.planning}", coverCopy, "Prepared for product and engineering leadership", "title-left"))
+coverCopy = TextContent("A concise comparison of Starter, Growth, and Enterprise plans using collaboration, governance, automation, and operating-cost criteria.")
+recommendation = Page("recommendation", ContentPage([recommendationHeader, recommendationMetric, recommendationStatement]))
+recommendationHeader = InlineHeader("Recommendation", "Choose Growth now and define explicit triggers for a future Enterprise migration.")
+recommendationMetric = HeroMetric("Growth", "Best balance of cross-team planning, automation, and manageable administration", "row", "${DEMO_IMAGES.office}")
+recommendationStatement = KeyStatement("Enterprise controls are valuable, but the current team size does not justify the added cost and governance overhead.")
+comparison = Page("comparison", ContentPage([comparisonHeader, comparisonTable]))
+comparisonHeader = InlineHeader("Plan comparison", "Scored against the needs of five collaborating product squads.")
+comparisonTable = Table([Column("Capability"), Column("Starter"), Column("Growth"), Column("Enterprise")], [["Roadmaps", "Basic", "Advanced", "Advanced"], ["Automation", "5 rules", "Unlimited", "Unlimited"], ["Permissions", "Workspace", "Team", "Organization"], ["Audit history", "None", "90 days", "1 year"], ["Relative cost", "Low", "Medium", "High"]])
+scoring = Page("scoring", ContentPage([scoringHeader, scoreChart]))
+scoringHeader = InlineHeader("Weighted decision score", "Illustrative score across fit, governance, automation, and cost.")
+scoreChart = BarChartV2({data: {labels: ["Starter", "Growth", "Enterprise"], series: [{category: "Score", values: [62, 86, 78]}]}}, "grouped", true, "Plan", "Score")
+rollout = Page("rollout", ContentPage([rolloutHeader, rolloutCards]))
+rolloutHeader = InlineHeader("30-day rollout", "Adopt the plan without importing process debt.")
+rolloutCards = VisualCards([{title: "Define", body: "Agree on issue types, ownership, and required fields.", imageSrc: "${DEMO_IMAGES.planning}"}, {title: "Pilot", body: "Test the workflow with two squads before scaling.", imageSrc: "${DEMO_IMAGES.collaboration}"}, {title: "Measure", body: "Review cycle time, automation, and reporting completeness.", imageSrc: "${DEMO_IMAGES.dashboard}"}])`;
+
+const COFFEE_TRENDS_REPORT_PROGRAM = `root = ReportView("Global Coffee Trends", "Consumer behavior and category opportunities · Illustrative 2026 outlook", [cover, signals, growth, occasions, actions])
+cover = Page("cover", StandardFrontPage("Global Coffee Trends", "${DEMO_IMAGES.coffee}", coverCopy, "Illustrative market outlook", "title-left"))
+coverCopy = TextContent("Four demand shifts shaping the next wave of café, retail, and ready-to-drink growth.")
+signals = Page("signals", ContentPage([signalsHeader, signalMetrics, signalImage]))
+signalsHeader = InlineHeader("Category signals", "Convenience is growing without displacing premium experiences.")
+signalMetrics = KeyMetrics("row", [{title: "Cold formats", text: "+18%"}, {title: "At-home premium", text: "+12%"}, {title: "Functional blends", text: "+9%"}, {title: "Traceability", text: "Top 3"}])
+signalImage = Image("${DEMO_IMAGES.coffeeBeans}", "Roasted coffee beans")
+growth = Page("growth", ContentPage([growthHeader, growthChart]))
+growthHeader = InlineHeader("Cold coffee is the growth engine", "Illustrative category index, 2023 baseline = 100.")
+growthChart = LineChartV2({data: {labels: ["2023", "2024", "2025", "2026"], series: [{category: "Cold coffee", values: [100, 118, 139, 160]}, {category: "Total coffee", values: [100, 105, 111, 117]}]}}, "Year", "Category index")
+occasions = Page("occasions", ContentPage([occasionHeader, occasionMix, occasionCards]))
+occasionHeader = InlineHeader("Demand is organized by occasion", "Formats win when they have a clear job to do.")
+occasionMix = PieChartV2({data: [{category: "Morning utility", value: 38}, {category: "Home ritual", value: 27}, {category: "Afternoon reset", value: 21}, {category: "Social discovery", value: 14}]})
+occasionCards = VisualCards([{title: "Cold and portable", body: "Speed and refreshment lead the commuting occasion.", imageSrc: "${DEMO_IMAGES.coffee}"}, {title: "Craft at home", body: "Whole bean and equipment turn preparation into ritual.", imageSrc: "${DEMO_IMAGES.coffeeBeans}"}, {title: "Signature café", body: "Distinctive drinks make social visits feel discoverable.", imageSrc: "${DEMO_IMAGES.coffee}"}])
+actions = Page("actions", ContentPage([actionsHeader, actionsList]))
+actionsHeader = InlineHeader("Three moves for operators", "Translate the signals into a focused portfolio.")
+actionsList = NumberedKeyPoint("column", [{title: "Design by occasion", body: "Give each format a clear job."}, {title: "Make sourcing visible", body: "Use concise origin proof at the point of choice."}, {title: "Prototype cold and functional", body: "Test before adding permanent complexity."}])`;
+
+const WORLD_CUP_DECK_PROGRAM = `root = SlideShow("World Cup 2026 Viewing Guide", "A host-city-first way to experience the tournament", [cover, scale, bases, matchday, itinerary, close])
+cover = Slide("cover", DramaticTitle("World Cup 2026", "A host-city-first viewing guide", "Three countries. Sixteen cities. One summer.", null, "title-bottom", "${DEMO_IMAGES.stadium}"))
+scale = Slide("scale", ChartWithContext("Sixteen host cities", BarChartV2({data: {labels: ["United States", "Mexico", "Canada"], series: [{category: "Host cities", values: [11, 3, 2]}]}}, "Country", "Host cities"), "Most routes work best as one regional cluster rather than a cross-continent sprint.", "title-body-top"))
+bases = Slide("bases", VisualCards("Choose a tournament base", [{title: "Northeast", body: "Dense connections and several nearby venues.", imageSrc: "${DEMO_IMAGES.stadium}"}, {title: "West Coast", body: "Iconic cities paired with longer travel distances.", imageSrc: "${DEMO_IMAGES.stadium}"}, {title: "Mexico", body: "Historic football culture and high-energy hosts.", imageSrc: "${DEMO_IMAGES.stadium}"}]))
+matchday = Slide("matchday", ListWithImage("Build a resilient matchday", [{iconName: "Train", primaryText: "Stay on rapid transit", body: "Optimize for the full day, not stadium proximity alone."}, {iconName: "Calendar", primaryText: "Protect recovery time", body: "Leave a buffer between cities."}, {iconName: "Ticket", primaryText: "Use official sources", body: "Keep ticketing as the single source of truth."}], ["${DEMO_IMAGES.stadium}"]))
+itinerary = Slide("itinerary", MetricsWithImage("A balanced seven-day shape", [{metric: "2 cities", description: "One regional cluster"}, {metric: "2 matches", description: "With recovery time"}, {metric: "3 open days", description: "For the host cities"}], ["${DEMO_IMAGES.stadium}"]))
+close = Slide("close", HeroMetric("Plan the route", "The best tournament trip leaves room for the cities around the football.", "vertical", "${DEMO_IMAGES.stadium}"))`;
+
+const PRODUCT_LAUNCH_DECK_PROGRAM = `root = SlideShow("AI Product Launch Plan", "From beta signal to repeatable adoption", [cover, audiences, sequence, scorecard, proof, close])
+cover = Slide("cover", DramaticTitle("AI Product Launch", "From beta signal to repeatable adoption", "A focused six-week go-to-market motion", null, "title-bottom", "${DEMO_IMAGES.ai}"))
+audiences = Slide("audiences", VisualCards("Three launch audiences", [{title: "Design partners", body: "Validate workflows and produce credible proof.", imageSrc: "${DEMO_IMAGES.collaboration}"}, {title: "Power users", body: "Create repeatable templates and community momentum.", imageSrc: "${DEMO_IMAGES.technology}"}, {title: "Team leads", body: "Convert individual use into team adoption.", imageSrc: "${DEMO_IMAGES.office}"}]))
+sequence = Slide("sequence", ListWithImage("The six-week sequence", [{iconName: "Sparkles", primaryText: "Weeks 1–2 · Prove", body: "Onboarding and reference stories."}, {iconName: "Megaphone", primaryText: "Weeks 3–4 · Launch", body: "Public release and guided templates."}, {iconName: "Users", primaryText: "Weeks 5–6 · Expand", body: "Team adoption and lifecycle automation."}], ["${DEMO_IMAGES.ai}", "${DEMO_IMAGES.planning}"]))
+scorecard = Slide("scorecard", ChartWithMetrics("Activation path", [{metric: "1,000", description: "Activated-team goal"}, {metric: "35%", description: "Week-two retention"}], LineChartV2({data: {labels: ["Week 1", "Week 2", "Week 4", "Week 6"], series: [{category: "Activated teams", values: [180, 420, 730, 1000]}]}}, "Launch week", "Teams")))
+proof = Slide("proof", ContentWithImage("Build proof loops", ["${DEMO_IMAGES.dashboard}", "${DEMO_IMAGES.collaboration}"], "Turn design-partner outcomes into templates, stories, and onboarding guidance that shorten time to first value.", "image-right"))
+close = Slide("close", HeroMetric("Earn the second session", "Reach creates awareness; a repeatable workflow creates adoption.", "vertical", "${DEMO_IMAGES.technology}"))`;
+
+const STOCK_ARTIFACT = createDemoArtifact({
+ id: "demo_artifact_big_tech_2025",
+ title: "Big Tech 2025 Report Card",
+ type: "report",
+ threadId: "demo_stock_comparison",
+ updatedAt: "2026-01-02T12:00:00.000Z",
+ program: STOCK_REPORT_PROGRAM,
+});
+
+const TRAVEL_ARTIFACT = createDemoArtifact({
+ id: "demo_artifact_japan_highlights",
+ title: "Must-See Japan",
+ type: "slides",
+ threadId: "demo_catalog_japan_highlights",
+ updatedAt: "2026-06-28T12:00:00.000Z",
+ program: TRAVEL_DECK_PROGRAM,
+});
+
+const BLOCKBUSTER_ARTIFACT = createDemoArtifact({
+ id: "demo_artifact_blockbuster_box_office",
+ title: "Blockbuster Box Office: Event Cinema Economics",
+ type: "slides",
+ threadId: "demo_blockbusters",
+ updatedAt: "2026-08-07T12:00:00.000Z",
+ program: BLOCKBUSTER_DECK_PROGRAM,
+});
+
+const BUSINESS_HEALTH_ARTIFACT = createDemoArtifact({
+ id: "demo_artifact_q2_business_health",
+ title: "Q2 Business Health",
+ type: "report",
+ threadId: "demo_catalog_q2_business_health",
+ updatedAt: "2026-06-30T12:00:00.000Z",
+ program: BUSINESS_HEALTH_REPORT_PROGRAM,
+});
+
+const PRODUCT_DECISION_ARTIFACT = createDemoArtifact({
+ id: "demo_artifact_project_platform_brief",
+ title: "Project Platform Decision Brief",
+ type: "report",
+ threadId: "demo_catalog_project_platform_brief",
+ updatedAt: "2026-06-29T12:00:00.000Z",
+ program: PRODUCT_DECISION_REPORT_PROGRAM,
+});
+
+const COFFEE_TRENDS_ARTIFACT = createDemoArtifact({
+ id: "demo_artifact_global_coffee_trends",
+ title: "Global Coffee Trends",
+ type: "report",
+ threadId: "demo_catalog_global_coffee_trends",
+ updatedAt: "2026-06-27T12:00:00.000Z",
+ program: COFFEE_TRENDS_REPORT_PROGRAM,
+});
+
+const WORLD_CUP_ARTIFACT = createDemoArtifact({
+ id: "demo_artifact_world_cup_2026_guide",
+ title: "World Cup 2026 Viewing Guide",
+ type: "slides",
+ threadId: "demo_catalog_world_cup_2026_guide",
+ updatedAt: "2026-06-25T12:00:00.000Z",
+ program: WORLD_CUP_DECK_PROGRAM,
+});
+
+const PRODUCT_LAUNCH_ARTIFACT = createDemoArtifact({
+ id: "demo_artifact_ai_product_launch",
+ title: "AI Product Launch Plan",
+ type: "slides",
+ threadId: "demo_catalog_ai_product_launch",
+ updatedAt: "2026-06-24T12:00:00.000Z",
+ program: PRODUCT_LAUNCH_DECK_PROGRAM,
+});
+
+export const DEMO_ARTIFACTS: readonly DemoArtifact[] = [
+ STOCK_ARTIFACT,
+ BUSINESS_HEALTH_ARTIFACT,
+ PRODUCT_DECISION_ARTIFACT,
+ COFFEE_TRENDS_ARTIFACT,
+ BLOCKBUSTER_ARTIFACT,
+ TRAVEL_ARTIFACT,
+ WORLD_CUP_ARTIFACT,
+ PRODUCT_LAUNCH_ARTIFACT,
+];
+
+export const DEMO_CONVERSATIONS: readonly DemoConversation[] = [
+ {
+ id: "demo_stock_comparison",
+ slug: "stock-comparison",
+ title: "Stock comparison",
+ description: "Meta, Microsoft, Netflix, and Google versus the S&P 500 in 2025",
+ icon: "analytics",
+ sourcePrompt:
+ "Compare Meta, Microsoft, Netflix, and Google for 2025. How did they do against the S&P 500?",
+ recordedModel: DEFAULT_MODEL,
+ linkedArtifactId: STOCK_ARTIFACT.id,
+ messages: [
+ {
+ id: "demo_stock_comparison_user_1",
+ role: "user",
+ content:
+ "Compare Meta, Microsoft, Netflix, and Google for 2025. How did they do against the S&P 500?",
+ },
+ {
+ id: "demo_stock_comparison_assistant_1",
+ role: "assistant",
+ content: `root = Card([header, stockCards, trendChart, ytdBars, snapshotTable, sourcesLabel, sources, note])
+sourcesLabel = TextContent("Sources", "small-heavy")
+sources = SnippetCardBlock([nasdaqSource, reutersSource, ibdSource], "grid")
+nasdaqSource = SnippetCardItem("src-nasdaq", ImageText("https://www.google.com/s2/favicons?domain=nasdaq.com&sz=64", "Nasdaq logo", "Nasdaq / Zacks", "How Big Tech Stocks Performed in 2025"))
+reutersSource = SnippetCardItem("src-reuters", ImageText("https://www.google.com/s2/favicons?domain=reuters.com&sz=64", "Reuters logo", "Reuters", "Alphabet Leads Big Tech's 2025 Rally"))
+ibdSource = SnippetCardItem("src-ibd", ImageText("https://www.google.com/s2/favicons?domain=investors.com&sz=64", "Investor's Business Daily logo", "Investor's Business Daily", "Magnificent Seven Report Card: 2025"))
+header = Header("Meta, Microsoft, Netflix, Google in 2025", "Full-year returns vs. the S&P 500 · Data as of Dec 31, 2025")
+stockCards = SnippetCardBlock([metaCard, msftCard, nflxCard, googCard, spyCard], "grid")
+metaCard = SnippetCardItem("meta", IconText(metaIcon, "success", "md", "Meta (META)", "Social & AI"), BoldText("number", "+9%", "2025 Full Year", "text", "md"))
+msftCard = SnippetCardItem("msft", IconText(msftIcon, "success", "md", "Microsoft (MSFT)", "Software & Cloud"), BoldText("number", "+21%", "2025 Full Year", "text", "md"))
+nflxCard = SnippetCardItem("nflx", IconText(nflxIcon, "success", "md", "Netflix (NFLX)", "Streaming"), BoldText("number", "+14%", "2025 Full Year", "text", "md"))
+googCard = SnippetCardItem("goog", IconText(googIcon, "success", "md", "Google (GOOGL)", "Search & AI"), BoldText("number", "+66%", "2025 Full Year", "text", "md"))
+spyCard = SnippetCardItem("spy", IconText(spyIcon, "neutral", "md", "S&P 500 (SPY)", "Benchmark"), BoldText("number", "+17%", "2025 Full Year", "text", "md"))
+metaIcon = Icon("users")
+msftIcon = Icon("cloud")
+nflxIcon = Icon("tv")
+googIcon = Icon("search")
+spyIcon = Icon("activity")
+trendChart = LineChart(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], [{category: "META", values: [10, 14, 8, 12, 18, 22, 25, 28, 22, 12, 5, 9]}, {category: "MSFT", values: [4, 6, 2, 8, 14, 18, 22, 24, 20, 18, 19, 21]}, {category: "NFLX", values: [8, 12, 15, 18, 22, 20, 16, 12, 8, 6, 10, 14]}, {category: "GOOGL", values: [3, 0, -8, -6, 2, 8, 14, 22, 32, 42, 55, 66]}, {category: "S&P 500", values: [2, 0, -5, -2, 4, 7, 10, 12, 13, 15, 16, 17]}], "default", "natural", "Monthly Cumulative Return: 2025 Trendlines", "Indexed to 0% at Jan 1, 2025 · Each line shows cumulative % gain relative to year start", "Month (2025)", "Cumulative Return (%)", "%")
+ytdBars = HorizontalBarChart(["Meta (META)", "Microsoft (MSFT)", "Netflix (NFLX)", "Google (GOOGL)", "S&P 500 (Benchmark)"], [{category: "2025 Return (%)", values: [9, 21, 14, 66, 17]}], "Full-Year 2025 Return vs. S&P 500", "Final year-end total return for each stock", "Return (%)", "Stock", "%", "grouped")
+snapshotTable = Table([stockCol, tickerCol, ytdCol, sectorCol, driverCol], [["Meta Platforms", "META", "+9%", commTag1, metaDriver], ["Microsoft", "MSFT", "+21%", techTag, msftDriver], ["Netflix", "NFLX", "+14%", commTag2, nflxDriver], ["Alphabet (Google)", "GOOGL", "+66%", commTag3, googDriver]])
+commTag1 = Tag("Comm. Services", "neutral")
+commTag2 = Tag("Comm. Services", "neutral")
+commTag3 = Tag("Comm. Services", "neutral")
+techTag = Tag("Technology", "info")
+metaDriver = Tag("AI-Powered Ads", "success")
+msftDriver = Tag("Azure & Copilot", "success")
+nflxDriver = Tag("Ads Tier Momentum", "success")
+googDriver = Tag("Gemini & Cloud", "success")
+stockCol = Col("Stock")
+tickerCol = Col("Ticker")
+ytdCol = Col("2025 Return")
+sectorCol = Col("Sector")
+driverCol = Col("Key Driver")
+note = CalloutV2("neutral", "For demonstration only", "Full-year 2025 figures are for demonstration, not investment advice.")`,
+ },
+ {
+ id: "demo_stock_comparison_user_2",
+ role: "user",
+ content: "Can you deep dive into Netflix?",
+ },
+ {
+ id: "demo_stock_comparison_assistant_2",
+ role: "assistant",
+ content: `root = Card([header, metricCards, chartTabs, driversHeading, driverCards, risksHeading, riskCards, disclaimer])
+disclaimer = CalloutV2("neutral", "Illustrative data only", "Figures and events in this deep dive are illustrative, for demonstration and not investment advice.")
+header = Header("Netflix (NFLX) 2025 Deep Dive", "Full-year financial & stock performance · Fiscal Year 2025")
+metricCards = SnippetCardBlock([revCard, marginCard, memberCard, stockCard], "grid")
+revCard = SnippetCardItem("rev", IconText(revIcon, "neutral", "md", "Full-Year Revenue", "FY 2025"), BoldText("number", "$45.2B", "+16% YoY", "metric", "md"))
+marginCard = SnippetCardItem("margin", IconText(marginIcon, "neutral", "md", "Operating Margin", "FY 2025"), BoldText("number", "29.5%", "+3 pts YoY", "metric", "md"))
+memberCard = SnippetCardItem("members", IconText(memberIcon, "neutral", "md", "Paid Memberships", "End of Q4 2025"), BoldText("number", "325M+", "Milestone", "text", "md"))
+stockCard = SnippetCardItem("stock", IconText(stockIcon, "success", "md", "Stock Return", "Full-Year 2025"), BoldText("number", "+14%", "vs. S&P +17%", "metric", "md"))
+revIcon = Icon("dollar-sign")
+marginIcon = Icon("trending-up")
+memberIcon = Icon("users")
+stockIcon = Icon("arrow-up-right")
+chartTabs = Tabs([priceTab, subsTab, revSpendTab])
+priceTab = TabItem("price", "Stock Price", [priceChart])
+priceChart = AreaChart(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], [{category: "NFLX close", values: [961, 997, 1024, 1050, 1086, 1068, 1032, 997, 961, 943, 979, 1015]}], "default", "natural", "NFLX share price, 2025", "Monthly close in US dollars", "Month (2025)", "Price ($)", "$")
+subsTab = TabItem("subs", "Subscribers", [subsChart])
+subsChart = BarChart(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], [{category: "Paid memberships", values: [303, 305, 307, 309, 310, 313, 315, 317, 320, 321, 323, 325]}], "default", "grouped", "Paid memberships", "Millions, end of month", "Month (2025)", "Members (M)", "M")
+revSpendTab = TabItem("revspend", "Revenue vs Spend", [revSpendChart])
+revSpendChart = BarChart(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], [{category: "Revenue", values: [3.4, 3.5, 3.6, 3.6, 3.7, 3.8, 3.8, 3.85, 3.9, 3.95, 4.0, 4.1]}, {category: "Content spend", values: [1.2, 1.3, 1.4, 1.4, 1.4, 1.5, 1.5, 1.5, 1.6, 1.7, 1.7, 1.8]}], "default", "grouped", "Revenue vs. content spend", "US dollars in billions per month", "Month (2025)", "USD (B)", "B")
+driversHeading = InlineHeader("Key Growth Drivers", "What powered the 2025 results")
+driverCards = CompositeCardBlock([pricingCard, adsBizCard, contentCard, wbCard], "grid")
+pricingCard = CompositeCardItem("pricing", IconText(pricingIcon, "success", "md", "Pricing Power", "Higher ARPU across regions"), [pricingBody])
+pricingBody = TextContent("Multiple price increases in the US and globally contributed to higher average revenue per membership, complementing subscriber growth.")
+pricingIcon = Icon("dollar-sign")
+adsBizCard = CompositeCardItem("ads-biz", IconText(adsBizIcon, "info", "md", "Ads Business", "Scaled ad platform & 2.5x revenue growth"), [adsBizBody])
+adsBizBody = TextContent("Ad revenue surpassed $1.5B, more than 2.5x the 2024 level. Netflix Ads Suite, its proprietary first-party ad tech platform, completed global rollout in Q2 2025.")
+adsBizIcon = Icon("megaphone")
+contentCard = CompositeCardItem("content", IconText(contentIcon, "warning", "md", "Content Slate", "Blockbuster originals & live events"), [contentBody])
+contentBody = TextContent("Hit titles including Squid Game S3, Wednesday S2, the Stranger Things finale, Happy Gilmore 2, and the Canelo-Crawford live boxing match drove outsized engagement.")
+contentIcon = Icon("clapperboard")
+wbCard = CompositeCardItem("wb", IconText(wbIcon, "neutral", "md", "Warner Bros. Acquisition", "Major strategic expansion announced Q4 2025"), [wbBody])
+wbBody = TextContent("Netflix announced an all-cash acquisition of Warner Bros. at $27.75 per share, expanding its content library and accelerating its push into major studio properties.")
+wbIcon = Icon("film")
+risksHeading = InlineHeader("Risks & Headwinds", "What could challenge the story")
+riskCards = CompositeCardBlock([compCard, perfCard], "grid")
+compCard = CompositeCardItem("comp", IconText(compIcon, "warning", "md", "Streaming Competition", "Disney+, Max, Apple TV+, YouTube"), [compBody])
+compBody = TextContent("Intensifying competition from Disney+, Max, Apple TV+, and YouTube continues to pressure churn and content spend, especially in the mature US market.")
+compIcon = Icon("swords")
+perfCard = CompositeCardItem("perf", IconText(perfIcon, "danger", "md", "Relative Performance", "NFLX +14% vs. S&P 500 +17%"), [perfBody])
+perfBody = TextContent("Despite strong fundamentals, NFLX stock trailed the S&P 500 in 2025 (+14% vs. +17%), reflecting peak-multiple concerns and Warner Bros. deal uncertainty.")
+perfIcon = Icon("trending-down")`,
+ },
+ {
+ id: "demo_stock_comparison_user_3",
+ role: "user",
+ content: "Package this into a shareable report.",
+ },
+ ...createArtifactTurn(
+ "demo_stock_comparison",
+ STOCK_ARTIFACT,
+ "I turned the four-stock comparison into a nine-page report covering benchmark-relative returns, company drivers, a Netflix deep dive, risks, and the 2026 watchlist.",
+ ),
+ ],
+ },
+ {
+ id: "demo_travel_planner",
+ slug: "japan-travel-guide",
+ title: "Japan travel guide",
+ description: "Must-see places in Japan with photos, highlights, and tips",
+ icon: "travel",
+ sourcePrompt: "Suggest must-see places in Japan.",
+ recordedModel: DEFAULT_MODEL,
+ messages: [
+ {
+ id: "demo_travel_planner_user_1",
+ role: "user",
+ content: "Suggest must-see places in Japan.",
+ },
+ {
+ id: "demo_travel_planner_assistant_1",
+ role: "assistant",
+ content: `root = Card([header, intro, placeCards, highlightsHeader, highlightTabs, followUps])
+followUps = ButtonGroup([planChipButton, seasonChipButton, foodChipButton], "row")
+planChipButton = Button("Help me plan a trip", {type: "continue_conversation"}, "secondary", "normal", "small")
+seasonChipButton = Button("What's the best season to visit?", {type: "continue_conversation"}, "secondary", "normal", "small")
+foodChipButton = Button("Where should I eat in Tokyo?", {type: "continue_conversation"}, "secondary", "normal", "small")
+header = Header("Must-See Places in Japan", "Iconic destinations from buzzing cities to serene temples")
+intro = TextContent("Japan offers an unmatched blend of ancient tradition, modern innovation, and breathtaking nature. Here are the top destinations every traveller should experience.")
+placeCards = VisualCardBlock([tokyoCard, fujiCard, kyotoCard], "grid")
+tokyoCard = VisualCardItem(tokyoCardBody, "tokyo", "https://images.unsplash.com/photo-1540959733332-eab4deabeeaf?w=1200&q=80&auto=format&fit=crop", mustSeeTag, "Neon streets of Tokyo at night")
+mustSeeTag = Tag("Must-See", "neutral")
+tokyoCardBody = BoldText("text", "Tokyo", "Japan's futuristic capital", "text", "md")
+fujiCard = VisualCardItem(fujiCardBody, "fuji", "https://images.unsplash.com/photo-1490806843957-31f4c9a91c65?w=1200&q=80&auto=format&fit=crop", wonderTag, "Mount Fuji rising over the countryside")
+wonderTag = Tag("Natural Wonder", "neutral")
+fujiCardBody = BoldText("text", "Mount Fuji", "Japan's iconic sacred peak", "text", "md")
+kyotoCard = VisualCardItem(kyotoCardBody, "kyoto", "https://images.unsplash.com/photo-1478436127897-769e1b3f0f36?w=1200&q=80&auto=format&fit=crop", culturalTag, "Historic streets and temples of Kyoto")
+culturalTag = Tag("Cultural", "neutral")
+kyotoCardBody = BoldText("text", "Kyoto", "Thousands of shrines & temples", "text", "md")
+highlightsHeader = InlineHeader("What to Do in Japan", "Food, shopping, and entertainment picks")
+highlightTabs = Tabs([foodTab, shoppingTab, entertainmentTab])
+foodTab = TabItem("food", "Food", [foodCards])
+foodCards = CompositeCardBlock([streetFood, sushiCard], "grid")
+streetFood = CompositeCardItem("street-food", ImageTextLarge("https://images.unsplash.com/photo-1590559899731-a382839e5549?w=1200&q=80&auto=format&fit=crop", "Dotonbori street food district in Osaka", "Street Food", "Takoyaki, ramen & market snacks"), [streetFoodCopy, streetFoodList, streetFoodTags])
+streetFoodCopy = TextContent("Japan's street food is a destination in itself. Osaka's Dotonbori and covered markets serve some of the country's most loved quick bites.")
+streetFoodList = List([streetSpot1, streetSpot2, streetSpot3])
+streetSpot1 = ListItem("Takoyaki in Dotonbori", "Octopus balls from the original stalls")
+streetSpot2 = ListItem("Kuromon Market", "Grilled seafood and wagyu skewers")
+streetSpot3 = ListItem("Standing ramen bars", "Quick, cheap, and unforgettable")
+streetFoodTags = TagBlock([cheapEatsTag, localTag])
+cheapEatsTag = Tag("Cheap Eats", "success")
+localTag = Tag("Local Favorite", "info")
+sushiCard = CompositeCardItem("sushi", ImageTextLarge("https://images.unsplash.com/photo-1579871494447-9811cf80d66c?w=1200&q=80&auto=format&fit=crop", "Fresh sushi platter", "Sushi & Izakaya", "From market breakfasts to late-night alleys"), [sushiCopy, sushiList, sushiTags])
+sushiCopy = TextContent("Eat sushi where it was perfected. Start with a market breakfast, then spend an evening hopping izakaya alleys in Shinjuku.")
+sushiList = List([sushiSpot1, sushiSpot2, sushiSpot3])
+sushiSpot1 = ListItem("Toyosu & Tsukiji outer market", "The freshest breakfast in Tokyo")
+sushiSpot2 = ListItem("Conveyor-belt sushi", "Fun, fast, and budget-friendly")
+sushiSpot3 = ListItem("Omoide Yokocho", "Tiny izakaya under the rail tracks")
+sushiTags = TagBlock([mustTryTag, freshTag])
+mustTryTag = Tag("Must-Try", "warning")
+freshTag = Tag("Fresh Daily", "success")
+shoppingTab = TabItem("shopping", "Shopping", [shoppingCards])
+shoppingCards = CompositeCardBlock([tokyoShopping, marketShopping], "grid")
+tokyoShopping = CompositeCardItem("tokyo-shopping", ImageTextLarge("https://images.unsplash.com/photo-1542051841857-5f90071e7989?w=1200&q=80&auto=format&fit=crop", "Busy shopping street in Tokyo", "Tokyo Shopping", "Fashion, gadgets & flagship stores"), [tokyoShopCopy, tokyoShopList, tokyoShopTags])
+tokyoShopCopy = TextContent("From Shibuya fashion floors to Ginza flagships and 24-hour discount stores, Tokyo covers every kind of shopping trip.")
+tokyoShopList = List([shopSpot1, shopSpot2, shopSpot3])
+shopSpot1 = ListItem("Shibuya & Harajuku", "Streetwear and youth fashion")
+shopSpot2 = ListItem("Ginza flagships", "Luxury brands and department stores")
+shopSpot3 = ListItem("Don Quijote", "Late-night souvenir and snack runs")
+tokyoShopTags = TagBlock([fashionTag, taxFreeTag])
+fashionTag = Tag("Fashion", "info")
+taxFreeTag = Tag("Tax-Free", "success")
+marketShopping = CompositeCardItem("market-shopping", ImageTextLarge("https://images.unsplash.com/photo-1493976040374-85c8e12f0c0e?w=1200&q=80&auto=format&fit=crop", "Traditional shopping street in Japan", "Markets & Crafts", "Souvenirs with a story"), [marketCopy, marketList, marketTags])
+marketCopy = TextContent("For gifts worth keeping, skip the airport shop. Japan's craft markets sell ceramics, knives, and tea you will actually use.")
+marketList = List([marketSpot1, marketSpot2, marketSpot3])
+marketSpot1 = ListItem("Nishiki Market, Kyoto", "Four hundred years of food stalls")
+marketSpot2 = ListItem("Nakamise-dori, Asakusa", "Classic souvenirs by Senso-ji")
+marketSpot3 = ListItem("Kappabashi Street", "Chef knives and kitchenware")
+marketTags = TagBlock([souvenirTag, traditionalTag])
+souvenirTag = Tag("Souvenirs", "neutral")
+traditionalTag = Tag("Traditional", "warning")
+entertainmentTab = TabItem("entertainment", "Entertainment", [entertainmentCards])
+entertainmentCards = CompositeCardBlock([arcadeCard, showsCard], "grid")
+arcadeCard = CompositeCardItem("arcades", ImageTextLarge("https://images.unsplash.com/photo-1511512578047-dfb367046420?w=1200&q=80&auto=format&fit=crop", "Neon arcade machines", "Arcades & Karaoke", "Japan's night out, perfected"), [arcadeCopy, arcadeList, arcadeTags])
+arcadeCopy = TextContent("Multi-floor arcades, claw machines, and private karaoke rooms make Japanese nights out unlike anywhere else.")
+arcadeList = List([arcadeSpot1, arcadeSpot2, arcadeSpot3])
+arcadeSpot1 = ListItem("Round1 arcades", "Rhythm games and crane machines")
+arcadeSpot2 = ListItem("Karaoke boxes", "Private rooms, all-night sessions")
+arcadeSpot3 = ListItem("Akihabara", "Retro game floors and electronics")
+arcadeTags = TagBlock([nightOutTag, groupFunTag])
+nightOutTag = Tag("Nightlife", "info")
+groupFunTag = Tag("Group Fun", "success")
+showsCard = CompositeCardItem("shows", ImageTextLarge("https://images.unsplash.com/photo-1545569341-9eb8b30979d9?w=1200&q=80&auto=format&fit=crop", "Traditional Japanese scene", "Shows & Experiences", "Only-in-Japan moments"), [showsCopy, showsList, showsTags])
+showsCopy = TextContent("Round out the trip with experiences you cannot get anywhere else, from digital art museums to a sumo tournament afternoon.")
+showsList = List([showSpot1, showSpot2, showSpot3])
+showSpot1 = ListItem("teamLab digital art", "Immersive light installations")
+showSpot2 = ListItem("Sumo tournaments", "Six grand tournaments a year")
+showSpot3 = ListItem("Baseball at Tokyo Dome", "Japan's loudest fan culture")
+showsTags = TagBlock([uniqueTag, bookAheadTag])
+uniqueTag = Tag("Only in Japan", "warning")
+bookAheadTag = Tag("Book Ahead", "danger")`,
+ },
+ {
+ id: "demo_travel_planner_user_2",
+ role: "user",
+ content: "Help me plan a trip.",
+ },
+ {
+ id: "demo_travel_planner_assistant_2",
+ role: "assistant",
+ content: `root = Card([header, intro, planForm])
+header = Header("Plan Your Trip to Japan", "Tell us your preferences and we'll craft the perfect itinerary")
+intro = TextContent("Fill in the details below and we'll tailor a Japan travel plan just for you.")
+planForm = Form("japan_trip_planner", formButtons, [departureField, datesField, durationField, travellersField, styleField, destinationsField])
+formButtons = ButtonGroup([submitButton])
+submitButton = Button("Create My Itinerary")
+departureField = FormControl("Departure City", departureInput, "Where are you flying from?")
+departureInput = Input("departure_city", {required: true}, "e.g. New York, London, Sydney", "text")
+datesField = FormControl("Travel Dates", datesInput, "Select your preferred travel window")
+datesInput = DatePicker("travel_dates", "range", {required: true})
+durationField = FormControl("Trip Duration", durationInput, "How long is your trip?")
+durationInput = Select("trip_duration", [durationA, durationB, durationC, durationD], {required: true}, "Select duration")
+durationA = SelectItem("5-7", "5 to 7 days")
+durationB = SelectItem("8-10", "8 to 10 days")
+durationC = SelectItem("11-14", "11 to 14 days")
+durationD = SelectItem("15plus", "15 days or more")
+travellersField = FormControl("Number of Travellers", travellersInput, "How many people are travelling?")
+travellersInput = Select("travellers", [soloItem, coupleItem, smallGroupItem, bigGroupItem], {required: true}, "Select number of travellers")
+soloItem = SelectItem("1", "Just me")
+coupleItem = SelectItem("2", "2 travellers")
+smallGroupItem = SelectItem("3-4", "3 to 4 travellers")
+bigGroupItem = SelectItem("5plus", "5 or more")
+styleField = FormControl("Trip Style", styleInput, "What kind of experience are you looking for?")
+styleInput = OptionCards("trip_style", "single", [culturalCard, natureCard, foodCard, cityCard, relaxCard, mixCard], {required: true})
+culturalCard = OptionCard("cultural", "Cultural & Historical", "Temples, shrines & ancient traditions", culturalIcon)
+culturalIcon = Icon("landmark")
+natureCard = OptionCard("nature", "Nature & Outdoors", "Mountains, forests & scenic landscapes", natureIcon)
+natureIcon = Icon("mountain")
+foodCard = OptionCard("food", "Food & Culinary", "Ramen, sushi & local street food", foodIcon)
+foodIcon = Icon("utensils")
+cityCard = OptionCard("city", "City & Modern Japan", "Anime, tech, nightlife & fashion", cityIcon)
+cityIcon = Icon("building-2")
+relaxCard = OptionCard("relax", "Relaxation & Wellness", "Onsen ryokans & peaceful retreats", relaxIcon)
+relaxIcon = Icon("bath")
+mixCard = OptionCard("mix", "Mix of Everything", "A balanced all-round experience", mixIcon)
+mixIcon = Icon("sparkles")
+destinationsField = FormControl("Destinations of Interest", destinationsInput, "Select all the places you'd like to visit")
+destinationsInput = Chips("destinations", "multiple", [tokyoChip, kyotoChip, osakaChip, hiroshimaChip, naraChip, hakoneChip, okinawaChip, sapporoChip])
+tokyoChip = ChipItem("tokyo", "Tokyo", tokyoChipIcon)
+tokyoChipIcon = Icon("zap")
+kyotoChip = ChipItem("kyoto", "Kyoto", kyotoChipIcon)
+kyotoChipIcon = Icon("landmark")
+osakaChip = ChipItem("osaka", "Osaka", osakaChipIcon)
+osakaChipIcon = Icon("utensils")
+hiroshimaChip = ChipItem("hiroshima", "Hiroshima", hiroshimaChipIcon)
+hiroshimaChipIcon = Icon("heart")
+naraChip = ChipItem("nara", "Nara", naraChipIcon)
+naraChipIcon = Icon("leaf")
+hakoneChip = ChipItem("hakone", "Hakone", hakoneChipIcon)
+hakoneChipIcon = Icon("thermometer")
+okinawaChip = ChipItem("okinawa", "Okinawa", okinawaChipIcon)
+okinawaChipIcon = Icon("waves")
+sapporoChip = ChipItem("sapporo", "Sapporo", sapporoChipIcon)
+sapporoChipIcon = Icon("snowflake")`,
+ },
+ ],
+ },
+ {
+ id: "demo_blockbusters",
+ slug: "blockbuster-report",
+ title: "Blockbuster report",
+ description: "The three highest-grossing films of all time, visualized",
+ icon: "compare",
+ sourcePrompt: "What are the top 3 highest-grossing movies of all time?",
+ recordedModel: "anthropic/claude-sonnet-4.6",
+ linkedArtifactId: BLOCKBUSTER_ARTIFACT.id,
+ messages: [
+ {
+ id: "demo_blockbusters_user_1",
+ role: "user",
+ content: "What are the top 3 highest-grossing movies of all time?",
+ },
+ {
+ id: "demo_blockbusters_assistant_1",
+ role: "assistant",
+ content: `root = Card([header, spotlightsHeader, filmCards, statCards, splitHeader, splitChart, franchiseChart, franchiseNote, sourcesLabel, sources])
+franchiseChart = PieChart([{category: "Marvel Cinematic Universe", value: 31.9}, {category: "Star Wars", value: 10.3}, {category: "Wizarding World", value: 9.7}, {category: "James Bond", value: 7.9}, {category: "Avatar", value: 5.2}], "donut", "Franchise Comparison", "Total worldwide gross by film franchise, in USD billions", "")
+franchiseNote = CalloutV2("info", "Avatar earns the most per film", "Two Avatar films have averaged about $2.6B each, the highest per-film gross of any franchise. The MCU leads on volume with 30+ releases.")
+sourcesLabel = TextContent("Sources", "small-heavy")
+sources = SnippetCardBlock([mojoSource, numbersSource, varietySource], "grid")
+mojoSource = SnippetCardItem("src-mojo", ImageText("https://www.google.com/s2/favicons?domain=boxofficemojo.com&sz=64", "Box Office Mojo logo", "Box Office Mojo", "All Time Worldwide Box Office"))
+numbersSource = SnippetCardItem("src-numbers", ImageText("https://www.google.com/s2/favicons?domain=the-numbers.com&sz=64", "The Numbers logo", "The Numbers", "Top Grossing Movies of All Time"))
+varietySource = SnippetCardItem("src-variety", ImageText("https://www.google.com/s2/favicons?domain=variety.com&sz=64", "Variety logo", "Variety", "Avatar Retakes the All-Time Box Office Crown"))
+header = Header("Top 3 Highest-Grossing Movies of All Time", "Worldwide Box Office · James Cameron dominates the #1 & #3 spots")
+statCards = SnippetCardBlock([grossCard, cameronCard, intlCard, eraCard], "grid")
+grossCard = SnippetCardItem("gross", IconText(grossIcon, "success", "md", "Combined Gross", "Top 3 films total"), BoldText("number", "$8.05B", "across 3 films", "text", "md"))
+grossIcon = Icon("dollar-sign")
+cameronCard = SnippetCardItem("cameron", IconText(cameronIcon, "info", "md", "James Cameron", "Director of #1 & #3"), BoldText("number", "2 of 3", "top spots held", "text", "md"))
+cameronIcon = Icon("clapperboard")
+intlCard = SnippetCardItem("intl", IconText(intlIcon, "neutral", "md", "Avg. International Share", "Foreign box office"), BoldText("number", "71%", "of total gross", "text", "md"))
+intlIcon = Icon("globe")
+eraCard = SnippetCardItem("era", IconText(eraIcon, "warning", "md", "Era Span", "Oldest to newest"), BoldText("number", "13 Years", "2009 to 2022", "text", "md"))
+eraIcon = Icon("calendar")
+splitHeader = InlineHeader("Domestic vs. International Breakdown", "How each film's gross splits between US and international markets")
+splitChart = HorizontalBarChart(["Avatar (2009)", "Avengers: Endgame (2019)", "Avatar: Way of Water (2022)"], [{category: "Domestic (US)", values: [0.79, 0.86, 0.68]}, {category: "International", values: [2.13, 1.94, 1.65]}], "Revenue Split by Market", "Worldwide gross in USD billions", "Gross (USD Billions)", "Film", "B", "grouped")
+spotlightsHeader = InlineHeader("Film Spotlights", "The three films that define modern event cinema")
+filmCards = VisualCardBlock([avatarCard, endgameCard, wowCard], "grid")
+avatarCard = VisualCardItem(avatarBody, "avatar", "${DEMO_IMAGES.posterAvatar}", avatarTag, "Avatar (2009) poster")
+avatarBody = BoldText("text", "Avatar", "$2.92B · 2009", "text", "md")
+avatarTag = Tag("#1 All-Time Record", "neutral")
+endgameCard = VisualCardItem(endgameBody, "endgame", "${DEMO_IMAGES.posterEndgame}", endgameTag, "Avengers: Endgame (2019) poster")
+endgameBody = BoldText("text", "Avengers: Endgame", "$2.80B · 2019", "text", "md")
+endgameTag = Tag("#2 · MCU Peak", "neutral")
+wowCard = VisualCardItem(wowBody, "wow", "${DEMO_IMAGES.posterWayOfWater}", wowTag, "Avatar: The Way of Water (2022) poster")
+wowBody = BoldText("text", "Avatar: The Way of Water", "$2.33B · 2022", "text", "md")
+wowTag = Tag("#3 · Most Expensive Ever", "neutral")`,
+ },
+ {
+ id: "demo_blockbusters_user_2",
+ role: "user",
+ content: "Package this into a shareable slide deck.",
+ },
+ ...createArtifactTurn(
+ "demo_blockbusters",
+ BLOCKBUSTER_ARTIFACT,
+ "I turned the box-office breakdown into a seven-slide deck covering the films, podium, global appeal, and the event-cinema playbook.",
+ ),
+ ],
+ },
+];
+
+const DEMO_CONVERSATIONS_BY_ID = new Map(
+ DEMO_CONVERSATIONS.map((conversation) => [conversation.id, conversation]),
+);
+const DEMO_CONVERSATIONS_BY_SLUG = new Map(
+ DEMO_CONVERSATIONS.map((conversation) => [conversation.slug, conversation]),
+);
+const DEMO_ARTIFACTS_BY_ID = new Map(DEMO_ARTIFACTS.map((artifact) => [artifact.id, artifact]));
+
+if (process.env.NODE_ENV !== "production") validateDemoContent();
+
+export function getDemoConversation(id: string | null | undefined): DemoConversation | undefined {
+ if (!id) return undefined;
+ return DEMO_CONVERSATIONS_BY_ID.get(id as DemoConversation["id"]);
+}
+
+export function getDemoConversationBySlug(slug: string): DemoConversation | undefined {
+ return DEMO_CONVERSATIONS_BY_SLUG.get(slug);
+}
+
+export function getDemoConversationPath(conversation: DemoConversation): string {
+ return `/chat/demo/${conversation.slug}`;
+}
+
+export function getDemoArtifact(id: string): DemoArtifact | undefined {
+ return DEMO_ARTIFACTS_BY_ID.get(id as DemoArtifact["id"]);
+}
+
+export function getDemoTurnCount(conversation: DemoConversation): number {
+ return conversation.messages.filter((message) => message.role === "user").length;
+}
+
+export function getDemoFirstUserMessage(conversation: DemoConversation): UserMessage {
+ const message = conversation.messages.find((candidate) => candidate.role === "user");
+ if (!message || message.role !== "user") {
+ throw new Error(`Demo conversation ${conversation.id} is missing its first user message.`);
+ }
+ return message;
+}
+
+export function cloneDemoMessages(conversation: DemoConversation): Message[] {
+ return structuredClone(conversation.messages);
+}
+
+function validateDemoContent() {
+ const artifactIds = new Set<string>();
+ const conversationSlugs = new Set<string>();
+ const counts: Record<DemoArtifactKind, number> = { report: 0, slides: 0 };
+
+ for (const artifact of DEMO_ARTIFACTS) {
+ if (artifactIds.has(artifact.id)) {
+ throw new Error(`Duplicate demo artifact ID: ${artifact.id}`);
+ }
+ artifactIds.add(artifact.id);
+ counts[artifact.type] += 1;
+ }
+
+ if (counts.report !== 4 || counts.slides !== 4) {
+ throw new Error(
+ `Expected four reports and four slide decks; found ${counts.report} reports and ${counts.slides} slide decks.`,
+ );
+ }
+
+ const expectedLinks = new Map<DemoConversation["id"], DemoArtifact["id"]>([
+ ["demo_stock_comparison", STOCK_ARTIFACT.id],
+ ["demo_blockbusters", BLOCKBUSTER_ARTIFACT.id],
+ ]);
+ const linkedConversations = DEMO_CONVERSATIONS.filter(
+ (conversation) => conversation.linkedArtifactId !== undefined,
+ );
+
+ if (linkedConversations.length !== expectedLinks.size) {
+ throw new Error("Only Stock comparison and Blockbuster report may link thread artifacts.");
+ }
+
+ for (const conversation of DEMO_CONVERSATIONS) {
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(conversation.slug)) {
+ throw new Error(`Invalid demo conversation slug: ${conversation.slug}`);
+ }
+ if (conversationSlugs.has(conversation.slug)) {
+ throw new Error(`Duplicate demo conversation slug: ${conversation.slug}`);
+ }
+ conversationSlugs.add(conversation.slug);
+
+ const expectedArtifactId = expectedLinks.get(conversation.id);
+ if (conversation.linkedArtifactId !== expectedArtifactId) {
+ throw new Error(`Unexpected demo artifact link for ${conversation.id}.`);
+ }
+ if (!expectedArtifactId) continue;
+
+ const artifact = DEMO_ARTIFACTS_BY_ID.get(expectedArtifactId);
+ if (!artifact || artifact.threadId !== conversation.id) {
+ throw new Error(`Invalid demo artifact thread link for ${conversation.id}.`);
+ }
+ if (!JSON.stringify(conversation.messages).includes(expectedArtifactId)) {
+ throw new Error(`Demo thread ${conversation.id} is missing its artifact turn.`);
+ }
+ }
+}
+
+function createDemoArtifact(artifact: Omit<DemoArtifact, "content">): DemoArtifact {
+ const carrierHeader = JSON.stringify({
+ artifact_id: artifact.id,
+ type: artifact.type,
+ name: artifact.title,
+ version: "1",
+ });
+
+ return {
+ ...artifact,
+ content: `]]>openui:artifact ${carrierHeader}\n${artifact.program}`,
+ };
+}
+
+function createArtifactTurn(idPrefix: string, artifact: DemoArtifact, summary: string): Message[] {
+ const toolCallId = `${idPrefix}_artifact_call`;
+ const toolName = artifact.type === "slides" ? "thesys_generate_slides" : "thesys_generate_report";
+ const artifactLabel = artifact.type === "slides" ? "Presentation" : "Report";
+ const toolArguments = JSON.stringify({
+ artifact_id: artifact.id,
+ artifact_type: artifact.type,
+ type: artifact.type,
+ name: artifact.title,
+ version: "1",
+ artifact_content: artifact.program,
+ });
+ const carrierHeader = JSON.stringify({
+ artifact_id: artifact.id,
+ type: artifact.type,
+ name: artifact.title,
+ version: "1",
+ });
+
+ return [
+ {
+ id: `${idPrefix}_artifact_assistant`,
+ role: "assistant",
+ content: `root = Card([ready, summary])
+ready = CalloutV2("success", "${artifactLabel} ready", "Open the artifact to explore the complete, presentation-ready output.")
+summary = TextContent(${JSON.stringify(summary)}, "small")`,
+ toolCalls: [
+ {
+ id: toolCallId,
+ type: "function",
+ function: { name: toolName, arguments: toolArguments },
+ },
+ ],
+ },
+ {
+ id: `${idPrefix}_artifact_tool`,
+ role: "tool",
+ toolCallId,
+ content: `]]>openui:artifact ${carrierHeader}\n${artifact.program}`,
+ },
+ ];
+}
diff --git a/docs/app/chat/_components/demo-fork-registry.ts b/docs/app/chat/_components/demo-fork-registry.ts
new file mode 100644
index 000000000..610a029f0
--- /dev/null
+++ b/docs/app/chat/_components/demo-fork-registry.ts
@@ -0,0 +1,103 @@
+import { getDemoConversation } from "./demo-conversations";
+
+const STORAGE_KEY_PREFIX = "openui-chat-demo-forks";
+
+export class DemoForkRegistry {
+ private readonly storageKey: string;
+ private readonly demoOrigins = new Map<string, string>();
+ private readonly unseededForks = new Set<string>();
+
+ constructor(userId: string) {
+ this.storageKey = `${STORAGE_KEY_PREFIX}:${userId}`;
+ this.restore();
+ }
+
+ register(threadId: string, demoId: string) {
+ if (!getDemoConversation(demoId)) return;
+ this.demoOrigins.set(threadId, demoId);
+ this.unseededForks.add(threadId);
+ this.persist();
+ }
+
+ getDemoId(threadId: string): string | undefined {
+ return this.demoOrigins.get(threadId);
+ }
+
+ shouldSeed(threadId: string): boolean {
+ return this.unseededForks.has(threadId);
+ }
+
+ markSeeded(threadId: string) {
+ if (!this.unseededForks.delete(threadId)) return;
+ this.persist();
+ }
+
+ remove(threadId: string) {
+ const removedOrigin = this.demoOrigins.delete(threadId);
+ const removedSeed = this.unseededForks.delete(threadId);
+ if (!removedOrigin && !removedSeed) return;
+ this.persist();
+ }
+
+ private restore() {
+ if (typeof window === "undefined") return;
+
+ try {
+ const raw = window.localStorage.getItem(this.storageKey);
+ if (!raw) return;
+ const stored = JSON.parse(raw) as Record<string, unknown>;
+ if (stored.version === 2) {
+ const origins = stored.origins;
+ const unseeded = stored.unseeded;
+ if (origins && typeof origins === "object") {
+ for (const [threadId, demoId] of Object.entries(origins)) {
+ if (typeof demoId === "string" && getDemoConversation(demoId)) {
+ this.demoOrigins.set(threadId, demoId);
+ }
+ }
+ }
+ if (Array.isArray(unseeded)) {
+ for (const threadId of unseeded) {
+ if (typeof threadId === "string" && this.demoOrigins.has(threadId)) {
+ this.unseededForks.add(threadId);
+ }
+ }
+ }
+ return;
+ }
+
+ // Migrate the original threadId -> demoId map. Every legacy entry was
+ // both a demo continuation and still awaiting its first full-history send.
+ for (const [threadId, demoId] of Object.entries(stored)) {
+ if (typeof demoId === "string" && getDemoConversation(demoId)) {
+ this.demoOrigins.set(threadId, demoId);
+ this.unseededForks.add(threadId);
+ }
+ }
+ } catch {
+ // A stale or unavailable local store should not prevent Cloud chat from loading.
+ }
+ }
+
+ private persist() {
+ if (typeof window === "undefined") return;
+
+ try {
+ if (this.demoOrigins.size === 0) {
+ window.localStorage.removeItem(this.storageKey);
+ return;
+ }
+
+ window.localStorage.setItem(
+ this.storageKey,
+ JSON.stringify({
+ version: 2,
+ origins: Object.fromEntries(this.demoOrigins),
+ unseeded: [...this.unseededForks],
+ }),
+ );
+ } catch {
+ // Persistence is a refresh convenience; the in-memory fork remains usable.
+ }
+ }
+}
diff --git a/docs/app/chat/_components/sidebar-upgrade-sheet.tsx b/docs/app/chat/_components/sidebar-upgrade-sheet.tsx
new file mode 100644
index 000000000..acac7b8ac
--- /dev/null
+++ b/docs/app/chat/_components/sidebar-upgrade-sheet.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import { CloudFeatureMarquee } from "@/app/(home)/cloud/CloudFeatureMarquee";
+import { CHAT_DEMO_EVENTS, captureChatDemoEvent, getChatDemoId } from "@/lib/chat-demo-analytics";
+import { useThreadList } from "@openuidev/react-headless";
+import { ArrowRight, X } from "lucide-react";
+import Link from "next/link";
+import { useEffect, useRef, useState } from "react";
+import styles from "../chat-page.module.css";
+import { getDemoConversation } from "./demo-conversations";
+import type { DemoForkRegistry } from "./demo-fork-registry";
+
+// Sidebar footer: "Demo powered by OpenUI Cloud" label plus a "Why upgrade?"
+// button that opens a bottom sheet with the Cloud page's 12-reasons marquee.
+interface SidebarUpgradeFooterProps {
+ forkRegistry: DemoForkRegistry;
+}
+
+export function SidebarUpgradeFooter({ forkRegistry }: SidebarUpgradeFooterProps) {
+ const [open, setOpen] = useState(false);
+ const selectedThreadId = useThreadList((state) => state.selectedThreadId);
+ const buttonRef = useRef<HTMLButtonElement>(null);
+ const hasCapturedPromptView = useRef(false);
+
+ const sourceDemoId =
+ getDemoConversation(selectedThreadId)?.id ??
+ (selectedThreadId ? forkRegistry.getDemoId(selectedThreadId) : undefined);
+ const demoId = getChatDemoId(sourceDemoId);
+
+ useEffect(() => {
+ const button = buttonRef.current;
+ if (!button || hasCapturedPromptView.current) return;
+
+ const observer = new IntersectionObserver(
+ ([entry]) => {
+ if (!entry?.isIntersecting || entry.intersectionRatio < 0.5) return;
+ hasCapturedPromptView.current = true;
+ captureChatDemoEvent(CHAT_DEMO_EVENTS.upgradePromptView, {});
+ observer.disconnect();
+ },
+ { threshold: 0.5 },
+ );
+ observer.observe(button);
+ return () => observer.disconnect();
+ }, []);
+
+ useEffect(() => {
+ if (!open) return;
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") setOpen(false);
+ };
+ document.addEventListener("keydown", handleKeyDown);
+ return () => document.removeEventListener("keydown", handleKeyDown);
+ }, [open]);
+
+ return (
+ <>
+ <div className={styles.sidebarUpgradeFooter}>
+ <div className={styles.sidebarBuiltWith}>
+ Demo powered by OpenUI
+ <span className={styles.sidebarCloudChip}>Cloud</span>
+ </div>
+ <button
+ ref={buttonRef}
+ type="button"
+ className={styles.sidebarUpgradeButton}
+ data-attribute-element="why-upgrade"
+ onClick={() => {
+ captureChatDemoEvent(CHAT_DEMO_EVENTS.upgradePromptClick, {
+ ...(demoId ? { demo_id: demoId } : {}),
+ });
+ setOpen(true);
+ }}
+ >
+ Why upgrade?
+ </button>
+ </div>
+ {open && (
+ <div
+ className={styles.upgradeSheetOverlay}
+ role="presentation"
+ onClick={() => setOpen(false)}
+ >
+ <div
+ className={styles.upgradeSheet}
+ role="dialog"
+ aria-modal="true"
+ aria-label="12 reasons to switch to Cloud"
+ onClick={(event) => event.stopPropagation()}
+ >
+ <div className={styles.upgradeSheetHeader}>
+ <h2 className={styles.upgradeSheetTitle}>12 reasons to switch to Cloud</h2>
+ <div className={styles.upgradeSheetActions}>
+ <Link
+ href="/docs/agent/getting-started/openui-cloud"
+ prefetch={false}
+ className={`${styles.upgradeSheetCta} ${styles.upgradeSheetCtaDesktop}`}
+ data-attribute-element="upgrade-cta"
+ onClick={() =>
+ captureChatDemoEvent(CHAT_DEMO_EVENTS.upgradeCtaClick, {
+ placement: "desktop",
+ destination: "getting_started_docs",
+ ...(demoId ? { demo_id: demoId } : {}),
+ })
+ }
+ >
+ Build for free
+ <ArrowRight size={15} strokeWidth={2} aria-hidden="true" />
+ </Link>
+ <button
+ type="button"
+ className={styles.upgradeSheetClose}
+ onClick={() => setOpen(false)}
+ aria-label="Close"
+ >
+ <X size={15} strokeWidth={2} aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+ <CloudFeatureMarquee />
+ <Link
+ href="/docs/agent/getting-started/openui-cloud"
+ prefetch={false}
+ className={`${styles.upgradeSheetCta} ${styles.upgradeSheetCtaMobile}`}
+ data-attribute-element="upgrade-cta"
+ onClick={() =>
+ captureChatDemoEvent(CHAT_DEMO_EVENTS.upgradeCtaClick, {
+ placement: "mobile",
+ destination: "getting_started_docs",
+ ...(demoId ? { demo_id: demoId } : {}),
+ })
+ }
+ >
+ Build for free
+ <ArrowRight size={15} strokeWidth={2} aria-hidden="true" />
+ </Link>
+ </div>
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/docs/app/chat/_components/stock-report-program.ts b/docs/app/chat/_components/stock-report-program.ts
new file mode 100644
index 000000000..0751a4ac0
--- /dev/null
+++ b/docs/app/chat/_components/stock-report-program.ts
@@ -0,0 +1,186 @@
+export const STOCK_REPORT_PROGRAM = String.raw`
+root = ReportView("Big Tech 2025 Report Card", "Meta, Microsoft, Netflix, and Google versus the S&P 500", pages)
+pages = [p1, p2, p3, p4, p5, p6, p7, p8, p9]
+
+coverImg = "https://www.bostonherald.com/wp-content/uploads/2025/12/Financial_Markets_Wall_Street_37501.jpg"
+coverBody = TextContent("An executive comparison of four technology and media leaders, the forces behind their 2025 returns, and the signals that could shape their relative position in 2026.\n\nFull-year price return review · Data as of Dec. 31, 2025\n\nFor demonstration only · Not investment advice · Returns are price returns unless stated")
+coverContent = StandardFrontPage("Big Tech 2025 Report Card", coverImg, coverBody, "Meta, Microsoft, Netflix, and Google versus the S&P 500", "title-top")
+p1 = Page("cover", coverContent)
+
+p2Header = InlineHeader("The Year in One View", "Google dominated. Microsoft roughly matched the index. Meta and Netflix trailed the benchmark.")
+p2Metrics = KeyMetrics("row", [
+ { "title": "+65%", "text": "Alphabet 2025 Price Return" },
+ { "title": "+16%", "text": "S&P 500 Price Return (Benchmark)" },
+ { "title": "+14.5%", "text": "Microsoft 2025 Price Return" },
+ { "title": "+10%", "text": "Meta 2025 Price Return" },
+ { "title": "+5%", "text": "Netflix 2025 Price Return" }
+])
+p2Statement = HeadlineStatement("Only Google decisively beat the benchmark", "On a verified price-return basis, Alphabet gained approximately 65% — roughly 49 percentage points above the S&P 500's 16% price return. Microsoft and Meta roughly tracked the index on a price basis, while Netflix lagged materially at approximately 5%. Total returns (with dividends reinvested) shift Microsoft marginally positive versus the benchmark. Note: Illustrative figures circulating in research decks (GOOGL +66%, MSFT +21%, NFLX +14%, META +9%) are rounded estimates; the verified price return data used here derives from market close prices.", "default")
+p2Points = NumberedKeyPoint("column", [
+ { "title": "Performance Leader", "body": "Google captured the strongest combination of AI enthusiasm, Cloud momentum, and earnings expectations, finishing best year since 2009." },
+ { "title": "Near-Benchmark Performer", "body": "Microsoft's Azure and Copilot narrative supported a return close to the index on a price-return basis; total return including dividends places it marginally ahead." },
+ { "title": "Operational Strength vs. Returns", "body": "Netflix expanded revenue +16% and margin to 29.5% yet delivered a price return of approximately 5% — well below the benchmark." }
+])
+p2Content = ContentPage([p2Header, p2Metrics, p2Statement, p2Points])
+p2 = Page("executive-scoreboard", p2Content)
+
+p3Header = InlineHeader("2025 Price Returns versus the Benchmark", "Full-year price return for each company compared with the S&P 500 (Jan 2–Dec 31, 2025). SPY ETF used as investable benchmark proxy.")
+p3ChartData = {
+ "data": {
+ "labels": ["Alphabet (GOOGL)", "S&P 500 (Benchmark)", "Microsoft (MSFT)", "Meta (META)", "Netflix (NFLX)"],
+ "series": [
+ { "category": "Price Return (%)", "values": [65, 16, 14.5, 10, 5] }
+ ]
+ }
+}
+p3Chart = BarChartV2(p3ChartData, "grouped", true, "2025 Price Return (%)", "Company / Index")
+p3Annotations = SummaryGrid([
+ { "type": "cyan", "label": "Alphabet (GOOGL)", "description": "+49 pts vs. benchmark" },
+ { "type": "gray", "label": "Microsoft (MSFT)", "description": "−1.5 pts (price); +0.4 pts total return" },
+ { "type": "gray", "label": "Meta (META)", "description": "−6 pts vs. benchmark" },
+ { "type": "gray", "label": "Netflix (NFLX)", "description": "−11 pts vs. benchmark" }
+])
+p3Statement = KeyStatement("The performance spread was unusually wide: 60 percentage points separated Alphabet from Netflix. Google delivered its best annual return since 2009.")
+p3Methodology = TextContent("Methodology Note: Price returns calculated Jan 2 open to Dec 31 close. SPY total return 2025: +17.7%. Total-return basis shifts Microsoft marginally above the benchmark. Sources: StatMuse Money, averageannualreturn.com, CNBC, SlickCharts, SPY Yahoo Finance.")
+p3Content = ContentPage([p3Header, p3Chart, p3Annotations, p3Statement, p3Methodology])
+p3 = Page("full-year-returns", p3Content)
+
+p4Header = InlineHeader("The Path Mattered as Much as the Destination", "Key turning points in each company's 2025 trajectory.")
+p4Col1 = Column("Quarter", "text")
+p4Col2 = Column("Key Event", "text")
+p4Col3 = Column("Market Reaction", "text")
+p4Col4 = Column("Cumulative Leaders", "text")
+p4Table = Table([p4Col1, p4Col2, p4Col3, p4Col4], [
+ ["Q1 2025", "Trump tariff shock; S&P 500 dropped ~16% from peak; GOOGL hit year low in April", "Broad tech sell-off; all five names declined", "All negative from start of year"],
+ ["Q2 2025", "Tariff pause and trade deals; AI earnings beats; Gemini momentum builds", "GOOGL begins strong recovery, up >100% from April low by year-end", "GOOGL breaks out"],
+ ["Q3 2025", "Netflix Q2 earnings: 325M members crossed; Meta ad revenue solid", "NFLX and META stabilize; MSFT steady on Azure growth", "GOOGL, MSFT near benchmark"],
+ ["Q4 2025", "GOOGL Q3 AI-led earnings beat; Netflix WBD acquisition announced Dec 5", "GOOGL surges to +65% for year; NFLX and META lag", "GOOGL clear leader"]
+])
+p4Narrative = TextContent("Google's outperformance was concentrated in H2 after AI product announcements and strong Cloud earnings drove a rerating. Netflix's strong operating results in late 2025 — revenue $45.2B, margin 29.5% — did not translate into benchmark-beating stock performance. Microsoft tracked close to the index throughout the year. Meta recovered from the tariff lows but finished below the benchmark.\n\nNote: A full monthly return chart would require verified adjusted-close price series for all five instruments. Readers are directed to Bloomberg, Refinitiv, or Yahoo Finance for verified monthly data.")
+p4Content = ContentPage([p4Header, p4Table, p4Narrative])
+p4 = Page("performance-evolution", p4Content)
+
+p5Header = InlineHeader("Four Companies, Four Different Return Stories", "Price return, benchmark spread, sector, and principal 2025 driver. Returns are price returns, Jan 2–Dec 31, 2025.")
+p5Col1 = Column("Company", "text")
+p5Col2 = Column("Ticker", "text")
+p5Col3 = Column("2025 Price Return", "number")
+p5Col4 = Column("Spread vs. S&P 500", "text")
+p5Col5 = Column("Sector", "text")
+p5Col6 = Column("Principal Driver", "text")
+p5Col7 = Column("Outcome", "text")
+
+p5TagOutperformed = TagBlock([{ "text": "Outperformed", "variant": "success" }])
+p5TagNear = TagBlock([{ "text": "Near-benchmark", "variant": "neutral" }])
+p5TagUnder1 = TagBlock([{ "text": "Underperformed", "variant": "warning" }])
+p5TagUnder2 = TagBlock([{ "text": "Underperformed", "variant": "warning" }])
+
+p5Table = Table([p5Col1, p5Col2, p5Col3, p5Col4, p5Col5, p5Col6, p5Col7], [
+ ["Alphabet", "GOOGL", "+65%", "+49 pts", "Communication Services", "Gemini AI + Google Cloud", p5TagOutperformed],
+ ["Microsoft", "MSFT", "+14.5%", "−1.5 pts (price); +0.4 pts total", "Technology", "Azure + Copilot adoption", p5TagNear],
+ ["Meta Platforms", "META", "+10%", "−6 pts", "Communication Services", "AI-powered advertising", p5TagUnder1],
+ ["Netflix", "NFLX", "+5%", "−11 pts", "Communication Services", "Advertising tier + pricing", p5TagUnder2]
+])
+p5Takeaway = TextContent("The market rewarded visible AI and Cloud monetization far more strongly than advertising improvements, content momentum, or subscriber economics. Alphabet's 65% gain reflects genuine investor re-rating of its AI product suite and Cloud trajectory.")
+p5Content = ContentPage([p5Header, p5Table, p5Takeaway])
+p5 = Page("company-scorecards", p5Content)
+
+p6Header = InlineHeader("What Drove the Performance Spread", "Each company entered 2025 with a different earnings narrative and investor expectation level.")
+p6Cards = VisualCards([
+ {
+ "title": "Google: AI and Cloud Re-rating (+65%)",
+ "body": "Gemini AI adoption, Cloud acceleration, and search resilience produced a 65% gain — its best year since 2009 — driven by a H2 surge.",
+ "imageSrc": "https://media.gettyimages.com/id/2259952847/photo/mountain-view-california-the-google-logo-is-displayed-on-a-building-at-google-headquarters-on.jpg?s=612x612&w=gi&k=20&c=__iNp8om936I1ZsY6XYoffwztAubslSOlNa3IQkT60w="
+ },
+ {
+ "title": "Microsoft: Steady AI Monetization (+14.5%)",
+ "body": "Azure cloud growth and enterprise Copilot adoption kept Microsoft close to the index. Total return (+16.4%) sat marginally above the benchmark.",
+ "imageSrc": "https://aufaittechnologies.com/wp-content/uploads/2025/07/MICROSOFT-COPILOT-1.jpg"
+ },
+ {
+ "title": "Netflix: Stronger Business, Softer Stock (+5%)",
+ "body": "Revenue grew 16% to $45.2B and margin expanded to 29.5%. Ad revenue surged >2.5x to >$1.5B, yet valuation and M&A noise weighed on returns.",
+ "imageSrc": "https://cdn.prod.website-files.com/6724d53a912f28c1861d34c5/692ebf0330edb0279b3ebca5_Netflix%20Advertising_%20The%20Future%20of%20Streaming%20TV%20Ads%20and%20How%20to%20Use%20It%20for%20Marketing.webp"
+ },
+ {
+ "title": "Meta: Ad Strength vs. Capex Intensity (+10%)",
+ "body": "AI advertising drove solid engagement, but very large capital expenditure commitments for AI infrastructure created near-term return concerns.",
+ "imageSrc": "https://engineering.fb.com/wp-content/uploads/2024/03/Meta-24K-GenAi-Clusters-hero.png"
+ }
+])
+p6Content = ContentPage([p6Header, p6Cards])
+p6 = Page("performance-drivers", p6Content)
+
+p7Header = InlineHeader("Netflix Deep Dive: Financial Engine", "Operating momentum strengthened even as the stock trailed the benchmark.")
+p7Metrics = KeyMetrics("row", [
+ { "title": "$45.2B", "text": "Revenue FY2025 (+16% YoY)" },
+ { "title": "29.5%", "text": "Operating Margin (+3 pts YoY)" },
+ { "title": ">$1.5B", "text": "Ad Revenue FY2025 (>2.5x YoY)" },
+ { "title": "325M+", "text": "Paid Memberships (Q4 Milestone)" },
+ { "title": "$11.0B", "text": "Net Income FY2025 (+26% YoY)" },
+ { "title": "~+5%", "text": "2025 Price Return (vs. S&P 500 +16%)" }
+])
+p7Statement = HeadlineStatement("Netflix's operating story was materially stronger than its relative stock performance", "Pricing, advertising, content engagement, and margin expansion all improved in 2025. Revenue grew 16% to $45.2B and operating margin reached 29.5% — the highest in company history. The stock nevertheless returned approximately 5% — roughly 11 percentage points behind the S&P 500 price return — indicating that valuation levels, strategic uncertainty, and the December 2025 Warner Bros. acquisition announcement (which Netflix subsequently walked away from in February 2026) may have weighed on the share price.", "default")
+
+p7Col1 = Column("Metric", "text")
+p7Col2 = Column("FY 2024", "text")
+p7Col3 = Column("FY 2025", "text")
+p7Col4 = Column("YoY Change", "text")
+p7Table = Table([p7Col1, p7Col2, p7Col3, p7Col4], [
+ ["Revenue", "$38.9B", "$45.2B", "+16%"],
+ ["Operating Income", "~$7.0B (est.)", "~$13.3B", "+30% (FY est.)"],
+ ["Operating Margin", "26.7%", "29.5%", "+2.8 pts"],
+ ["Net Income", "$8.7B", "$11.0B", "+26%"],
+ ["Ad Revenue", "~$0.6B (est.)", ">$1.5B", ">2.5x"],
+ ["Paid Memberships", "~301M (est.)", "325M+", "~8% growth"]
+])
+p7Footnote = TextContent("Footnote: FY2024 operating income and ad revenue are estimates; Netflix does not separately report all line items annually. Sources: Netflix Q4 2025 Shareholder Letter (Jan 20, 2026); Netflix 10-K (Dec 31, 2025).")
+p7Content = ContentPage([p7Header, p7Metrics, p7Statement, p7Table, p7Footnote])
+p7 = Page("netflix-financials", p7Content)
+
+p8Header = InlineHeader("Netflix: What Could Sustain — or Weaken — the Story", "The growth opportunity is broad, but execution complexity is increasing.")
+p8Drivers = VisualCards([
+ {
+ "title": "Pricing Power",
+ "body": "Higher average revenue per membership and selective price increases across markets. Balancing monetization against membership churn remains key.",
+ "imageSrc": "https://www.munro.agency/wp-content/uploads/2025/06/Does-Netflix-Have-Ads-banner-1.jpg"
+ },
+ {
+ "title": "Advertising Momentum",
+ "body": "Ad revenue surpassed $1.5B (>2.5x YoY). First-party ad technology build-out aims to double ad revenue again in 2026.",
+ "imageSrc": "https://cdn.prod.website-files.com/6724d53a912f28c1861d34c5/6a4e1c17e3bf6b88ced9af17_netflix%20ad%20business%20momentum.webp"
+ },
+ {
+ "title": "Content & Live Events",
+ "body": "Returning franchise series and live events drove a 9% rise in original viewing hours. Live sports and entertainment scale acquisition in 2026.",
+ "imageSrc": "https://static-www.adweek.com/wp-content/uploads/2024/08/netflix-upfront-squidgame.jpeg?w=1200"
+ }
+])
+
+p8RiskCol1 = Column("Risk", "text")
+p8RiskCol2 = Column("Why It Matters", "text")
+p8RiskCol3 = Column("Evidence to Monitor", "text")
+p8RisksTable = Table([p8RiskCol1, p8RiskCol2, p8RiskCol3], [
+ ["Streaming Competition", "Disney+, Amazon Prime, Apple TV+ and Max compete for wallet share", "Subscriber churn rates; content spending trends"],
+ ["Valuation Expectations", "NFLX trades at a premium; strong operating results did not prevent 2025 underperformance", "Forward P/E vs. earnings growth; analyst target revisions"],
+ ["Content Economics", "Rising production costs and talent fees compress margins", "Content amortization rates; operating margin guidance"],
+ ["Advertising Execution", "Ad-tech build-out requires investment before scale returns materialize", "Ad revenue growth rate; CPM trends; ad-tier membership mix"],
+ ["Pricing-Related Churn", "Repeated price increases may eventually accelerate cancellations", "Net membership adds by quarter; churn disclosure"],
+ ["Warner Bros. Acquisition", "Announced WBD acquisition in Dec 2025; walked away in Feb 2026 (Paramount acquired). Deal did NOT close.", "Monitor future M&A capital allocation strategy"]
+])
+p8Summary = KeyStatement("Netflix's central challenge is converting a broader entertainment platform — spanning streaming, advertising, live events, and gaming — into durable per-member economics without sacrificing engagement quality or operating discipline.")
+p8Content = ContentPage([p8Header, p8Drivers, p8RisksTable, p8Summary])
+p8 = Page("netflix-drivers-risks", p8Content)
+
+p9Header = InlineHeader("What to Watch Next", "The 2026 comparison will depend on monetization discipline, capital allocation, and the durability of AI-led earnings growth.")
+p9Watchlist = NumberedKeyPoint("column", [
+ { "title": "Google AI Monetization", "body": "Gemini usage trends, Google Cloud growth rate, and search advertising economics will determine whether the 2025 re-rating proves durable or mean-reverts." },
+ { "title": "Microsoft Copilot Economics", "body": "Paid enterprise adoption, Azure acceleration, and the return on AI infrastructure investment are the key variables for Microsoft's benchmark-relative performance." },
+ { "title": "Meta Capital Intensity", "body": "Very large AI infrastructure capex commitments create execution risk. The critical question: does spending produce proportional revenue and earnings growth?" },
+ { "title": "Netflix Advertising & Engagement", "body": "Ad-tier economics, pricing strategy, churn management, and the performance of major content franchises will drive whether Netflix closes the gap to the benchmark." },
+ { "title": "Benchmark-Relative Returns", "body": "All four companies underperformed or roughly matched the S&P 500 on a verified 2025 price-return basis except Alphabet. Sustained outperformance requires measurable earnings growth beyond AI narrative." }
+])
+p9Statement = HeadlineStatement("Google won 2025, but the next leadership position is not guaranteed", "Verified price returns show a clear performance hierarchy: Alphabet far ahead (+65%), Microsoft and the S&P 500 closely matched (~14.5% vs. ~16%), and Netflix and Meta below the benchmark. The 2026 outcome will depend less on AI or streaming narratives alone and more on measurable monetization, disciplined investment, and durable earnings growth. For all four companies, 2025 demonstrated that operational progress is necessary — but not sufficient — for market outperformance.", "default")
+p9Sources = TextContent("Sources & References:\n- Netflix Q4 2025 Shareholder Letter, Netflix Investor Relations (January 20, 2026)\n- Netflix 10-K Annual Report FY2025, SEC EDGAR (January 2026)\n- \"Google stock wraps best year since 2009,\" CNBC (December 31, 2025)\n- StatMuse Money — GOOGL, MSFT, NFLX price returns 2025\n- averageannualreturn.com — META, GOOG total return 2025\n- SlickCharts — MSFT, NFLX, META annual returns\n- S&P 500 2025 Return, DQYDJ (December 31, 2025)\n- SPY Performance History, Yahoo Finance / State Street\n- Netflix and Warner Bros. Discovery acquisition announcement (December 5, 2025) / Reuters WBD updates (February 2026)\n\nFor demonstration only. Figures are based on publicly available market data and company disclosures and are not verified investment research or investment advice. Price returns calculated Jan 2 open to Dec 31 close unless stated. Dividends not included in price returns.")
+p9Content = ContentPage([p9Header, p9Watchlist, p9Statement, p9Sources])
+p9 = Page("conclusions-watchlist", p9Content)
+`;
diff --git a/docs/app/chat/_components/use-persisted-cloud-model.ts b/docs/app/chat/_components/use-persisted-cloud-model.ts
new file mode 100644
index 000000000..6837e4ec2
--- /dev/null
+++ b/docs/app/chat/_components/use-persisted-cloud-model.ts
@@ -0,0 +1,51 @@
+"use client";
+
+import { DEFAULT_MODEL, MODEL_OPTIONS } from "@/lib/openui-cloud/models";
+import { useCallback, useSyncExternalStore } from "react";
+
+const MODEL_STORAGE_KEY = "openui-cloud:selected-model";
+const listeners = new Set<() => void>();
+
+function subscribe(listener: () => void) {
+ listeners.add(listener);
+ window.addEventListener("storage", listener);
+
+ return () => {
+ listeners.delete(listener);
+ window.removeEventListener("storage", listener);
+ };
+}
+
+export function getPersistedCloudModel(): string {
+ if (typeof window === "undefined") return DEFAULT_MODEL;
+
+ try {
+ const savedModel = window.localStorage.getItem(MODEL_STORAGE_KEY);
+ if (savedModel && MODEL_OPTIONS.some((model) => model.id === savedModel)) {
+ return savedModel;
+ }
+ } catch {
+ // Storage can be unavailable in private or restricted browser contexts.
+ }
+
+ return DEFAULT_MODEL;
+}
+
+export function usePersistedCloudModel(): readonly [string, (model: string) => void] {
+ const selectedModel = useSyncExternalStore(
+ subscribe,
+ getPersistedCloudModel,
+ () => DEFAULT_MODEL,
+ );
+ const setSelectedModel = useCallback((model: string) => {
+ try {
+ window.localStorage.setItem(MODEL_STORAGE_KEY, model);
+ } catch {
+ // Keep the in-page selection working even if persistence is unavailable.
+ }
+
+ listeners.forEach((listener) => listener());
+ }, []);
+
+ return [selectedModel, setSelectedModel] as const;
+}
diff --git a/docs/app/chat/_components/viewport-presets.ts b/docs/app/chat/_components/viewport-presets.ts
new file mode 100644
index 000000000..935bc5842
--- /dev/null
+++ b/docs/app/chat/_components/viewport-presets.ts
@@ -0,0 +1,50 @@
+export const VIEWPORT_PRESETS = [
+ { id: "mobile", label: "Mobile" },
+ { id: "tablet", label: "Tablet" },
+ { id: "desktop", label: "Desktop" },
+] as const;
+
+export type ViewportPreset = (typeof VIEWPORT_PRESETS)[number]["id"];
+
+export const FORM_FACTOR_QUERY_PARAM = "form_factor";
+const FORM_FACTOR_CHANGE_EVENT = "openui:form-factor-change";
+
+export function isViewportPreset(value: string): value is ViewportPreset {
+ return VIEWPORT_PRESETS.some((preset) => preset.id === value);
+}
+
+export function getFormFactorFromUrl(url: URL): ViewportPreset | undefined {
+ const value = url.searchParams.get(FORM_FACTOR_QUERY_PARAM);
+ return value && isViewportPreset(value) ? value : undefined;
+}
+
+export function setCurrentUrlFormFactor(viewport: ViewportPreset): void {
+ const url = new URL(window.location.href);
+ if (getFormFactorFromUrl(url) === viewport) return;
+
+ url.searchParams.set(FORM_FACTOR_QUERY_PARAM, viewport);
+ window.history.replaceState(window.history.state, "", url);
+ window.dispatchEvent(new Event(FORM_FACTOR_CHANGE_EVENT));
+}
+
+export function getCurrentUrlFormFactor(): ViewportPreset | undefined {
+ return getFormFactorFromUrl(new URL(window.location.href));
+}
+
+export function getServerUrlFormFactor(): undefined {
+ return undefined;
+}
+
+export function subscribeToCurrentUrlFormFactor(onStoreChange: () => void): () => void {
+ window.addEventListener("popstate", onStoreChange);
+ window.addEventListener(FORM_FACTOR_CHANGE_EVENT, onStoreChange);
+
+ return () => {
+ window.removeEventListener("popstate", onStoreChange);
+ window.removeEventListener(FORM_FACTOR_CHANGE_EVENT, onStoreChange);
+ };
+}
+
+export function preserveCurrentUrlSearch(pathname: string): string {
+ return `${pathname}${window.location.search}`;
+}
diff --git a/docs/app/chat/chat-page.module.css b/docs/app/chat/chat-page.module.css
index 1409c2466..19610d479 100644
--- a/docs/app/chat/chat-page.module.css
+++ b/docs/app/chat/chat-page.module.css
@@ -52,25 +52,28 @@
outline-offset: 2px;
}
-.modeControl {
+.viewportControl {
min-width: 0;
justify-self: center;
}
-.modeGroup {
+.viewportGroup {
display: inline-flex !important;
width: auto !important;
min-width: 0;
flex-wrap: nowrap !important;
- gap: 4px !important;
+ gap: 2px !important;
border: 0;
border-radius: 0;
background: transparent;
padding: 0;
}
-.modeItem {
+.viewportItem {
+ display: inline-flex;
min-height: 2.25rem !important;
+ align-items: center;
+ gap: 6px;
border: 0 !important;
border-radius: 10px !important;
background: transparent !important;
@@ -83,18 +86,18 @@
background-color 120ms ease;
}
-.modeItem:hover:not(:disabled) {
+.viewportItem:hover:not(:disabled) {
color: var(--openui-text-neutral-primary) !important;
background: var(--openui-highlight) !important;
}
-.modeItem[data-state="on"] {
+.viewportItem[data-state="on"] {
color: var(--openui-text-neutral-primary) !important;
background: var(--openui-sunk) !important;
box-shadow: none;
}
-.modeItem:focus-visible {
+.viewportItem:focus-visible {
position: relative;
z-index: 1;
outline: 2px solid var(--openui-border-accent-emphasis);
@@ -113,11 +116,49 @@
min-width: 0;
min-height: 0;
flex: 1;
+ align-items: stretch;
+ justify-content: center;
+ overflow: hidden;
+ background: var(--openui-background);
+ padding: 12px;
+}
+
+.agentViewport[data-viewport="desktop"] {
+ padding: 0;
+}
+
+.agentFrame {
+ position: relative;
+ height: 100%;
+ min-width: 0;
+ min-height: 0;
overflow: hidden;
background: var(--openui-foreground);
+ transition:
+ width 180ms ease,
+ border-radius 180ms ease,
+ box-shadow 180ms ease;
}
-.agentViewport > * {
+.agentFrame[data-viewport="desktop"] {
+ width: 100%;
+}
+
+.agentFrame[data-viewport="mobile"] {
+ width: min(390px, 100%);
+ border: 1px solid var(--openui-border-default);
+ border-radius: 14px;
+ box-shadow: var(--openui-shadow-m);
+}
+
+.agentFrame[data-viewport="tablet"] {
+ width: min(820px, 100%);
+ border: 1px solid var(--openui-border-default);
+ border-radius: 14px;
+ box-shadow: var(--openui-shadow-m);
+}
+
+.agentFrame > * {
width: 100%;
height: 100%;
min-width: 0;
@@ -135,15 +176,14 @@
.agentViewport :global(.openui-agent-container) {
width: 100% !important;
height: 100% !important;
+ overflow: clip !important;
}
-/* AgentInterface normally swaps a collapsed sidebar logo for this control on
- hover. The chat surfaces have no logo, so keep the only expand affordance
- visible at rest. */
-.agentViewport
- :global(.openui-agent-sidebar-header--collapsed .openui-agent-sidebar-header__toggle-button) {
- opacity: 1;
- pointer-events: auto;
+.agentViewport :global(.openui-agent-sidebar-header__logo) {
+ border-radius: 7px;
+ background: var(--openui-border-default);
+ padding: 3px;
+ object-fit: contain;
}
.agentViewport :global([data-chat-mode="cloud"] .openui-agent-thread-error) {
@@ -162,6 +202,55 @@
flex: 1 1 0% !important;
}
+.agentViewport :global(.openui-detailed-view-panel .c1-slide-scaled-container) {
+ border: 0;
+}
+
+/* Source citation cards: compact equal-width tiles in a single row, with a
+ small logo beside the title and the article name below. Scoped to snippet
+ cards that contain an image (the demo's source cards); icon-based stock
+ cards are unaffected. The library wraps items in row divs, so the rows are
+ flattened with display: contents to let all cards share one flex line. */
+.agentViewport :global(.c1-small-card-block__grid:has(.c1-image-text__image)) {
+ display: flex;
+ flex-direction: row !important;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.agentViewport :global(.c1-small-card-block__row:has(.c1-image-text__image)) {
+ display: contents;
+}
+
+.agentViewport :global(.c1-small-card-block__item:has(.c1-image-text__image)) {
+ width: 260px;
+ flex: 0 0 auto;
+}
+
+.agentViewport :global(.c1-value-card:has(.c1-image-text__image)) {
+ padding: 10px 12px;
+}
+
+.agentViewport :global(.c1-value-card .c1-image-text__image-container) {
+ width: 24px !important;
+ height: 24px !important;
+}
+
+.agentViewport :global(.c1-value-card__rhs:empty) {
+ display: none;
+}
+
+.sidebarBuiltWith {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ gap: 6px;
+ margin-bottom: 10px;
+ color: var(--openui-text-neutral-primary);
+ font: var(--openui-text-label-xs);
+ white-space: nowrap;
+}
+
.centeredState {
display: flex;
width: 100%;
@@ -212,61 +301,53 @@
flex: 0 1 auto;
}
-.modelSwitcherTrigger {
- width: auto !important;
- min-width: 0 !important;
- max-width: min(240px, calc(100vw - 32px));
- height: 32px !important;
- justify-content: flex-start !important;
- gap: 6px !important;
- border: 1px solid var(--openui-border-default) !important;
- border-radius: var(--openui-radius-m) !important;
- background: var(--openui-foreground) !important;
- padding-inline: 10px !important;
- color: var(--openui-text-neutral-primary) !important;
- box-shadow: var(--openui-shadow-s);
- font: var(--openui-text-body-sm) !important;
+.modelSwitcherFieldset {
+ min-width: 0;
+ margin: 0;
+ border: 0;
+ padding: 0;
}
-.modelSwitcherValue {
- min-width: 0;
- flex: 0 1 auto;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
+.modelSwitcherFieldset:disabled {
+ opacity: 0.58;
}
-.modelSwitcherContent {
- width: min(360px, calc(100vw - 32px));
- max-height: 360px;
- overflow: auto;
+.modelSwitcherFieldset:disabled :global(.openui-model-switcher-trigger) {
+ cursor: not-allowed;
+ box-shadow: none;
}
-.modelOption {
- display: flex;
- min-width: 0;
- flex-direction: column;
- gap: 2px;
+.modelProviderLogo {
+ display: block;
+ width: 14px;
+ height: 14px;
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: contain;
}
-.modelOptionHeading {
- display: flex;
- min-width: 0;
- align-items: center;
- gap: 6px;
+.modelProviderLogo[data-provider="google"] {
+ background-image: url("../../../packages/openui-cli/src/templates/openui-cloud/public/logos/google-light.svg");
}
-.modelOptionName,
-.modelOptionId {
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
+.modelProviderLogo[data-provider="openai"] {
+ background-image: url("../../../packages/openui-cli/src/templates/openui-cloud/public/logos/openai-light.svg");
}
-.modelOptionId {
- color: var(--openui-text-neutral-tertiary);
- font-size: 12px;
+.modelProviderLogo[data-provider="anthropic"] {
+ background-image: url("../../../packages/openui-cli/src/templates/openui-cloud/public/logos/anthropic-light.svg");
+}
+
+:global(.dark) .modelProviderLogo[data-provider="google"] {
+ background-image: url("../../../packages/openui-cli/src/templates/openui-cloud/public/logos/google-dark.svg");
+}
+
+:global(.dark) .modelProviderLogo[data-provider="openai"] {
+ background-image: url("../../../packages/openui-cli/src/templates/openui-cloud/public/logos/openai-dark.svg");
+}
+
+:global(.dark) .modelProviderLogo[data-provider="anthropic"] {
+ background-image: url("../../../packages/openui-cli/src/templates/openui-cloud/public/logos/anthropic-dark.svg");
}
.cloudMobileHeader :global(.openui-agent-mobile-header-logo-container) {
@@ -285,10 +366,125 @@
flex: 0 1 auto;
}
-.cloudMobileHeader .modelSwitcherTrigger {
+.cloudMobileHeader .modelSwitcher :global(.openui-model-switcher-trigger) {
width: min(220px, 100%) !important;
}
+.analyticsContents {
+ display: contents;
+}
+
+.demoThreadGroup {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding-block: 6px 12px;
+}
+
+.demoThreadGroupLabel {
+ padding: 4px 12px 7px;
+ color: var(--openui-text-neutral-tertiary);
+ font: var(--openui-text-label-xs);
+ letter-spacing: 0.01em;
+}
+
+.agentViewport :global(.openui-agent-sidebar-container--collapsed) .demoThreadGroupLabel {
+ display: none;
+}
+
+.demoReadOnlyMarker {
+ display: none;
+}
+
+.agentViewport
+ :global([data-openui-demo-readonly-renderer])
+ :is(
+ a[href],
+ button,
+ input,
+ textarea,
+ select,
+ [contenteditable="true"],
+ [role="button"],
+ [role="checkbox"],
+ [role="combobox"],
+ [role="link"],
+ [role="menuitem"],
+ [role="option"],
+ [role="radio"],
+ [role="slider"],
+ [role="spinbutton"],
+ [role="switch"],
+ [role="tab"]
+ ) {
+ cursor: not-allowed !important;
+}
+
+.agentViewport :global([data-openui-demo-readonly-renderer]) {
+ user-select: text;
+}
+
+.demoComposerState {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ background: var(--openui-foreground);
+ padding: 6px 16px 18px;
+}
+
+.demoComposerState::before {
+ content: "";
+ position: absolute;
+ bottom: 100%;
+ left: 0;
+ right: 0;
+ height: 56px;
+ background: linear-gradient(to top, var(--openui-foreground), transparent);
+ pointer-events: none;
+}
+
+.demoComposerCta {
+ display: inline-flex;
+ height: 2.25rem;
+ align-items: center;
+ justify-content: center;
+ border: 0;
+ border-radius: 10px;
+ background: var(--openui-inverted-background);
+ box-shadow:
+ inset 0 2px 1px -0.5px color-mix(in srgb, var(--openui-inverted-background) 84%, white),
+ inset 0 -3px 6px -1px color-mix(in srgb, var(--openui-inverted-background) 90%, black);
+ padding-inline: 1rem;
+ color: var(--openui-background);
+ font-family: "Inter", "Segoe UI", sans-serif;
+ font-size: 0.9375rem;
+ font-weight: 500;
+ cursor: pointer;
+ transition: opacity 120ms ease;
+}
+
+.demoComposerCta:hover:not(:disabled) {
+ opacity: 0.9;
+}
+
+.demoComposerCta:disabled {
+ opacity: 0.65;
+ cursor: default;
+}
+
+.demoComposerError {
+ grid-column: 1 / -1;
+ margin: 0;
+ color: var(--openui-text-danger-primary);
+ font: var(--openui-text-body-sm);
+}
+
+.agentFrame[data-viewport="mobile"] .demoComposerState {
+ padding: 6px 12px 14px;
+}
+
.srOnly {
position: absolute;
width: 1px;
@@ -301,7 +497,7 @@
border: 0;
}
-@media (max-width: 760px) {
+@media (max-width: 767px) {
.header {
padding: 8px 12px;
}
@@ -311,35 +507,78 @@
gap: 6px;
}
- .modeControl {
- width: min(100%, 15rem) !important;
+ .viewportControl {
+ display: none;
}
- .modeGroup {
+ .viewportGroup {
width: 100% !important;
}
- .modeItem {
+ .viewportItem {
min-width: 0;
flex: 1;
justify-content: center;
padding-inline: 4px !important;
- font-size: 0.6875rem !important;
+ }
+
+ .viewportItemLabel {
+ display: none;
}
.buildForFreeMenu {
display: none;
}
+
+ .agentViewport {
+ padding: 0;
+ }
+
+ .agentFrame:is([data-viewport="mobile"], [data-viewport="tablet"]) {
+ border: 0;
+ border-radius: 0;
+ box-shadow: none;
+ }
+
+ .demoComposerState {
+ grid-template-columns: 1fr;
+ padding: 10px 12px 12px;
+ }
+
+ .demoComposerNotice,
+ .demoComposerError {
+ grid-column: 1;
+ }
+
+ .demoComposerNotice {
+ align-items: flex-start;
+ }
+
+ .demoComposerNoticeCopy {
+ flex-direction: column;
+ gap: 2px;
+ }
+
+ .demoComposerNoticeCopy span {
+ display: none;
+ }
+}
+
+@media (min-width: 768px) and (max-width: 1023px) {
+ .desktopViewportItem {
+ display: none;
+ }
}
@media (max-width: 380px) {
- .cloudMobileHeader .modelSwitcherTrigger {
+ .cloudMobileHeader .modelSwitcher :global(.openui-model-switcher-trigger) {
width: min(190px, 100%) !important;
}
}
@media (prefers-reduced-motion: reduce) {
- .modeItem {
+ .viewportItem,
+ .agentFrame {
transition: none;
}
@@ -347,3 +586,276 @@
animation: none;
}
}
+
+/* Sidebar footer: powered-by label plus the "Why upgrade?" trigger for the
+ 12-reasons bottom sheet. */
+.sidebarUpgradeFooter {
+ /* The sidebar container pads 16px 12px; these negative offsets even the
+ visible gap out to about 10px on every side. */
+ margin: auto -2px -6px;
+ border: 1px solid var(--openui-border-default);
+ border-radius: 12px;
+ background: var(--openui-foreground);
+ box-shadow: 0 4px 14px -6px rgba(0, 0, 0, 0.1);
+ padding: 12px;
+}
+
+.agentViewport :global(.openui-agent-sidebar-container--collapsed) .sidebarUpgradeFooter,
+.agentViewport
+ :global(.openui-agent-sidebar-container[data-sidebar-visual-state="collapsing"])
+ .sidebarUpgradeFooter {
+ display: none;
+}
+
+.sidebarBuiltWith {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ gap: 6px;
+ margin-bottom: 10px;
+ color: var(--openui-text-neutral-primary);
+ font: var(--openui-text-label-xs);
+ white-space: nowrap;
+}
+
+.sidebarCloudChip {
+ display: inline-flex;
+ align-items: center;
+ border: 1px solid var(--openui-inverted-background);
+ border-radius: 6px;
+ background: transparent;
+ padding: 1px 7px;
+ color: var(--openui-text-neutral-primary);
+ font: var(--openui-text-label-xs);
+}
+
+.sidebarUpgradeButton {
+ display: flex;
+ width: 100%;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid var(--openui-inverted-background);
+ border-radius: 9px;
+ background: var(--openui-inverted-background);
+ padding: 8px 14px;
+ color: var(--openui-background);
+ font: var(--openui-text-label-xs);
+ cursor: pointer;
+ transition: background-color 120ms ease;
+}
+
+.sidebarUpgradeButton:hover {
+ background: color-mix(in srgb, var(--openui-inverted-background) 88%, var(--openui-background));
+}
+
+.sidebarUpgradeButton:focus-visible {
+ outline: 2px solid var(--openui-border-accent-emphasis);
+ outline-offset: -2px;
+}
+
+/* Bottom sheet with the Cloud page's 12-reasons feature marquee. */
+.upgradeSheetOverlay {
+ position: fixed;
+ inset: 0;
+ z-index: 90;
+ display: flex;
+ align-items: flex-end;
+ background: rgba(0, 0, 0, 0.42);
+ animation: upgradeSheetFade 160ms ease;
+}
+
+.upgradeSheet {
+ width: 100%;
+ max-height: 85dvh;
+ overflow-y: auto;
+ border-radius: 18px 18px 0 0;
+ background: var(--openui-foreground);
+ padding: 16px 24px 20px;
+ animation: upgradeSheetRise 260ms ease;
+}
+
+.upgradeSheetHeader {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin-bottom: 22px;
+}
+
+.upgradeSheetTitle {
+ margin: 0;
+ color: var(--openui-text-neutral-primary);
+ font-size: 1.25rem;
+ font-weight: 600;
+}
+
+.upgradeSheetActions {
+ display: flex;
+ flex: none;
+ align-items: center;
+ gap: 8px;
+}
+
+.upgradeSheetCta {
+ display: inline-flex;
+ height: 2.25rem;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ border-radius: 10px;
+ background: var(--openui-inverted-background);
+ padding-inline: 1rem;
+ color: var(--openui-background);
+ font: var(--openui-text-label-sm);
+ text-decoration: none;
+ transition: opacity 120ms ease;
+}
+
+.upgradeSheetCta:hover {
+ opacity: 0.9;
+}
+
+.upgradeSheetCtaMobile {
+ display: none;
+}
+
+.upgradeSheetClose {
+ display: inline-flex;
+ width: 2.25rem;
+ height: 2.25rem;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid var(--openui-border-default);
+ border-radius: 10px;
+ background: var(--openui-foreground);
+ color: var(--openui-text-neutral-primary);
+ cursor: pointer;
+ transition: background-color 120ms ease;
+}
+
+.upgradeSheetClose:hover {
+ background: var(--openui-highlight);
+}
+
+@keyframes upgradeSheetFade {
+ from {
+ opacity: 0;
+ }
+}
+
+@keyframes upgradeSheetRise {
+ from {
+ transform: translateY(24px);
+ opacity: 0;
+ }
+}
+
+/* The marquee section ships with the marketing page's tall vertical padding
+ and card size; flatten and shrink it about 15% inside the sheet. */
+.upgradeSheet > :global(section) {
+ --card-w: clamp(11rem, 17vw, 15.3rem);
+
+ padding-block: 0 !important;
+}
+
+/* The scroller centers itself to the marketing page's 75rem container, which
+ leaves a large leading gap inside the sheet; keep just a small inset. */
+.upgradeSheet :global(div[role="group"]) {
+ padding-inline: 0.5rem !important;
+}
+
+/* On mobile the drawer's floating New Chat button overlaps the sidebar
+ footer, so the powered-by banner moves to the top of the drawer, above
+ the Presentations nav, with wider side insets. The sidebar container is a
+ flex column, so ordering the header before the banner slots it in place. */
+.agentFrame[data-viewport="mobile"] :global(.openui-agent-sidebar-header) {
+ order: -2;
+}
+
+.agentFrame[data-viewport="mobile"] .sidebarUpgradeFooter {
+ order: -1;
+ margin: 4px 12px 10px;
+}
+
+@media (max-width: 767px) {
+ .agentViewport :global(.openui-agent-sidebar-header) {
+ order: -2;
+ }
+
+ .agentViewport .sidebarUpgradeFooter {
+ order: -1;
+ margin: 4px 12px 10px;
+ }
+}
+
+/* Mobile-only refinements: tighter sidebar section rhythm, a stacked sheet
+ header with a smaller title, and a more compact marquee. */
+@media (max-width: 767px) {
+ .agentViewport :global(.openui-agent-sidebar-container) {
+ gap: 14px;
+ }
+
+ .upgradeSheet {
+ position: relative;
+ }
+
+ .upgradeSheetHeader {
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 10px;
+ }
+
+ .upgradeSheetTitle {
+ padding-right: 3rem;
+ font-size: 1.05rem;
+ }
+
+ .upgradeSheetCtaDesktop {
+ display: none;
+ }
+
+ .upgradeSheetCtaMobile {
+ display: flex;
+ width: 100%;
+ justify-content: space-between;
+ margin-top: 28px;
+ }
+
+ .upgradeSheetClose {
+ position: absolute;
+ top: 12px;
+ right: 12px;
+ }
+
+ .upgradeSheet > :global(section) {
+ --card-w: 9rem;
+ }
+
+ .upgradeSheet :global(h3) {
+ font-size: 0.875rem !important;
+ font-weight: 400 !important;
+ }
+
+ .upgradeSheet :global(button[aria-label="Show previous features"]),
+ .upgradeSheet :global(button[aria-label="Show next features"]) {
+ display: none !important;
+ }
+
+ .upgradeSheet :global(div[role="group"]) {
+ -webkit-mask-image: linear-gradient(
+ to right,
+ transparent 0,
+ #000 2%,
+ #000 98%,
+ transparent 100%
+ ) !important;
+ mask-image: linear-gradient(
+ to right,
+ transparent 0,
+ #000 2%,
+ #000 98%,
+ transparent 100%
+ ) !important;
+ }
+}
diff --git a/docs/app/chat/demo/[demoSlug]/page.tsx b/docs/app/chat/demo/[demoSlug]/page.tsx
new file mode 100644
index 000000000..7518160ed
--- /dev/null
+++ b/docs/app/chat/demo/[demoSlug]/page.tsx
@@ -0,0 +1,36 @@
+import { createPageMetadata } from "@/lib/page-metadata";
+import { redirect } from "next/navigation";
+import {
+ DEMO_CONVERSATIONS,
+ getDemoConversationBySlug,
+ getDemoConversationPath,
+} from "../../_components/demo-conversations";
+
+interface DemoChatPageProps {
+ params: Promise<{ demoSlug: string }>;
+}
+
+export function generateStaticParams() {
+ return DEMO_CONVERSATIONS.map((conversation) => ({ demoSlug: conversation.slug }));
+}
+
+export async function generateMetadata({ params }: DemoChatPageProps) {
+ const { demoSlug } = await params;
+ const conversation = getDemoConversationBySlug(demoSlug);
+ if (!conversation) return {};
+
+ return createPageMetadata({
+ pathname: getDemoConversationPath(conversation),
+ title: `${conversation.title} | OpenUI Cloud Chat`,
+ description: conversation.description,
+ image: "/nav/chat-light.webp",
+ imageAlt: `${conversation.title} demo preview`,
+ });
+}
+
+export default async function DemoChatPage({ params }: DemoChatPageProps) {
+ const { demoSlug } = await params;
+ if (!getDemoConversationBySlug(demoSlug)) redirect("/chat");
+
+ return null;
+}
diff --git a/docs/app/chat/layout.tsx b/docs/app/chat/layout.tsx
index 87e87c6a8..f59a30650 100644
--- a/docs/app/chat/layout.tsx
+++ b/docs/app/chat/layout.tsx
@@ -1,6 +1,12 @@
import { WebsiteThemeProvider } from "@/components/website-theme-provider";
import type { ReactNode } from "react";
+import { ChatPageClient } from "./_components/chat-page-client";
export default function ChatLayout({ children }: { children: ReactNode }) {
- return <WebsiteThemeProvider>{children}</WebsiteThemeProvider>;
+ return (
+ <WebsiteThemeProvider>
+ <ChatPageClient />
+ {children}
+ </WebsiteThemeProvider>
+ );
}
diff --git a/docs/app/chat/page.tsx b/docs/app/chat/page.tsx
index b5fe75302..8a0a119ce 100644
--- a/docs/app/chat/page.tsx
+++ b/docs/app/chat/page.tsx
@@ -1,14 +1,13 @@
import { createPageMetadata } from "@/lib/page-metadata";
-import { ChatPageClient } from "./_components/chat-page-client";
export const metadata = createPageMetadata({
pathname: "/chat",
- title: "OpenUI Chat",
- description: "Try OpenUI OSS and OpenUI Cloud in a live generative UI chat.",
+ title: "OpenUI Cloud Chat",
+ description: "Explore OpenUI Cloud through live and curated generative UI conversations.",
image: "/nav/chat-light.webp",
imageAlt: "OpenUI Chat preview",
});
export default function ChatPage() {
- return <ChatPageClient />;
+ return null;
}
diff --git a/docs/lib/chat-demo-analytics.ts b/docs/lib/chat-demo-analytics.ts
new file mode 100644
index 000000000..429a172d9
--- /dev/null
+++ b/docs/lib/chat-demo-analytics.ts
@@ -0,0 +1,154 @@
+import { analytics } from "./analytics";
+
+export const CHAT_DEMO_EVENTS = {
+ experienceView: "chat_demo:experience_view",
+ threadView: "chat_demo:thread_view",
+ artifactView: "chat_demo:artifact_view",
+ previewChange: "chat_demo:preview_change",
+ upgradePromptView: "chat_demo:upgrade_prompt_view",
+ upgradePromptClick: "chat_demo:upgrade_prompt_click",
+ upgradeCtaClick: "chat_demo:upgrade_cta_click",
+ buildMenuOpen: "chat_demo:build_menu_open",
+ continuationCreate: "chat_demo:continuation_create",
+ promptSubmit: "chat_demo:prompt_submit",
+} as const;
+
+export type ChatDemoId = "stock_comparison" | "japan_travel_guide" | "blockbuster_report";
+export type ChatDemoPreview = "mobile" | "tablet" | "desktop";
+export type ChatDemoHostBreakpoint = "mobile_host" | "tablet_host" | "desktop_host";
+export type ChatDemoConversationOrigin = "new_chat" | "demo_continuation";
+export type ChatDemoArtifactType = "report" | "slides";
+
+type ChatDemoEventName = (typeof CHAT_DEMO_EVENTS)[keyof typeof CHAT_DEMO_EVENTS];
+
+interface ChatDemoEventProperties {
+ [CHAT_DEMO_EVENTS.experienceView]: {
+ host_breakpoint: ChatDemoHostBreakpoint;
+ available_preview_count: 1 | 2 | 3;
+ initial_preview: ChatDemoPreview;
+ };
+ [CHAT_DEMO_EVENTS.threadView]: {
+ demo_id: ChatDemoId;
+ };
+ [CHAT_DEMO_EVENTS.artifactView]: {
+ artifact_id: ChatDemoArtifactId;
+ artifact_type: ChatDemoArtifactType;
+ demo_id?: ChatDemoId;
+ };
+ [CHAT_DEMO_EVENTS.previewChange]: {
+ from_preview: ChatDemoPreview;
+ to_preview: ChatDemoPreview;
+ host_breakpoint: ChatDemoHostBreakpoint;
+ };
+ [CHAT_DEMO_EVENTS.upgradePromptView]: Record<string, never>;
+ [CHAT_DEMO_EVENTS.upgradePromptClick]: {
+ demo_id?: ChatDemoId;
+ };
+ [CHAT_DEMO_EVENTS.upgradeCtaClick]: {
+ placement: "desktop" | "mobile";
+ destination: "getting_started_docs";
+ demo_id?: ChatDemoId;
+ };
+ [CHAT_DEMO_EVENTS.buildMenuOpen]: Record<string, never>;
+ [CHAT_DEMO_EVENTS.continuationCreate]: {
+ demo_id: ChatDemoId;
+ };
+ [CHAT_DEMO_EVENTS.promptSubmit]: ChatDemoGenerationContext;
+}
+
+export interface ChatDemoGenerationContext {
+ conversation_origin: ChatDemoConversationOrigin;
+ model: string;
+ demo_id?: ChatDemoId;
+}
+
+export type ChatDemoArtifactId =
+ | "big_tech_2025"
+ | "japan_highlights"
+ | "blockbuster_box_office"
+ | "q2_business_health"
+ | "project_platform_brief"
+ | "global_coffee_trends"
+ | "world_cup_2026_guide"
+ | "ai_product_launch";
+
+export interface ChatDemoArtifactAnalytics {
+ artifactId: ChatDemoArtifactId;
+ artifactType: ChatDemoArtifactType;
+ demoId?: ChatDemoId;
+}
+
+const DEMO_IDS: Readonly<Record<string, ChatDemoId>> = {
+ demo_stock_comparison: "stock_comparison",
+ demo_travel_planner: "japan_travel_guide",
+ demo_blockbusters: "blockbuster_report",
+};
+
+const ARTIFACTS: Readonly<Record<string, ChatDemoArtifactAnalytics>> = {
+ demo_artifact_big_tech_2025: {
+ artifactId: "big_tech_2025",
+ artifactType: "report",
+ demoId: "stock_comparison",
+ },
+ demo_artifact_japan_highlights: {
+ artifactId: "japan_highlights",
+ artifactType: "slides",
+ demoId: "japan_travel_guide",
+ },
+ demo_artifact_blockbuster_box_office: {
+ artifactId: "blockbuster_box_office",
+ artifactType: "slides",
+ demoId: "blockbuster_report",
+ },
+ demo_artifact_q2_business_health: {
+ artifactId: "q2_business_health",
+ artifactType: "report",
+ },
+ demo_artifact_project_platform_brief: {
+ artifactId: "project_platform_brief",
+ artifactType: "report",
+ },
+ demo_artifact_global_coffee_trends: {
+ artifactId: "global_coffee_trends",
+ artifactType: "report",
+ },
+ demo_artifact_world_cup_2026_guide: {
+ artifactId: "world_cup_2026_guide",
+ artifactType: "slides",
+ },
+ demo_artifact_ai_product_launch: {
+ artifactId: "ai_product_launch",
+ artifactType: "slides",
+ },
+};
+
+export function getChatDemoId(sourceId: string | undefined): ChatDemoId | undefined {
+ return sourceId ? DEMO_IDS[sourceId] : undefined;
+}
+
+export function getChatDemoArtifactAnalytics(
+ sourceId: string | undefined,
+): ChatDemoArtifactAnalytics | undefined {
+ return sourceId ? ARTIFACTS[sourceId] : undefined;
+}
+
+export function captureChatDemoEvent<EventName extends ChatDemoEventName>(
+ eventName: EventName,
+ properties: ChatDemoEventProperties[EventName],
+): void {
+ if (typeof window === "undefined" || isLocalAnalyticsHost(window.location.hostname)) return;
+
+ analytics.capture(eventName, {
+ instrumentation_version: 1,
+ analytics_environment: getAnalyticsEnvironment(window.location.hostname),
+ ...properties,
+ });
+}
+
+function isLocalAnalyticsHost(hostname: string): boolean {
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
+}
+
+function getAnalyticsEnvironment(hostname: string): "production" | "preview" {
+ return hostname.endsWith(".vercel.app") ? "preview" : "production";
+}
diff --git a/docs/lib/openui-cloud/chat-constants.tsx b/docs/lib/openui-cloud/chat-constants.tsx
new file mode 100644
index 000000000..67b037171
--- /dev/null
+++ b/docs/lib/openui-cloud/chat-constants.tsx
@@ -0,0 +1,69 @@
+import type { PromptTemplate } from "@openuidev/react-ui";
+import { FileText, Presentation } from "lucide-react";
+
+export const OPENUI_CLOUD_LOGO_URL = "/shiro-logo.svg";
+
+export const OPENUI_CLOUD_PROMPT_TEMPLATES: PromptTemplate[] = [
+ {
+ displayText: "Create a presentation",
+ prompt: "Create a presentation about ",
+ icon: <Presentation size={16} />,
+ completions: [
+ {
+ displayText: "The rise of reusable rockets and commercial spaceflight",
+ prompt: "the rise of reusable rockets and commercial spaceflight",
+ icon: <></>,
+ },
+ {
+ displayText: "How Formula 1 became a global business",
+ prompt: "how Formula 1 became a global business",
+ icon: <></>,
+ },
+ {
+ displayText: "Why electric vehicles are changing transportation",
+ prompt: "why electric vehicles are changing transportation",
+ icon: <></>,
+ },
+ ],
+ },
+ {
+ displayText: "Write a report",
+ prompt: "Write a report on ",
+ icon: <FileText size={16} />,
+ completions: [
+ {
+ displayText: "Global coffee market trends and consumer preferences",
+ prompt: "global coffee market trends and consumer preferences",
+ icon: <></>,
+ },
+ {
+ displayText: "The state of the electric vehicle market in 2026",
+ prompt: "the state of the electric vehicle market in 2026",
+ icon: <></>,
+ },
+ {
+ displayText: "Global travel trends and emerging destinations",
+ prompt: "global travel trends and emerging destinations",
+ icon: <></>,
+ },
+ ],
+ },
+];
+
+export const OPENUI_CLOUD_STARTERS = [
+ {
+ displayText: "Relive the FIFA World Cup 2026",
+ prompt: "Relive the FIFA World Cup 2026.",
+ icon: <></>,
+ },
+ {
+ displayText: "Create a report on global coffee trends",
+ prompt: "Create a report on global coffee trends.",
+ icon: <></>,
+ },
+ {
+ displayText: "Help me plan my next vacation",
+ prompt: "Help me plan my next vacation.",
+ icon: <></>,
+ },
+];
diff --git a/docs/lib/openui-cloud/chat-llm.ts b/docs/lib/openui-cloud/chat-llm.ts
index 490b24f0c..cad9fb85a 100644
--- a/docs/lib/openui-cloud/chat-llm.ts
+++ b/docs/lib/openui-cloud/chat-llm.ts
@@ -1,33 +1,72 @@
import { DEFAULT_MODEL } from "@/lib/openui-cloud/models";
+import type { ChatLLM } from "@openuidev/react-headless";
import {
+ fetchLLM,
openAIConversationMessageFormat,
openAIResponsesAdapter,
- type ChatLLM,
-} from "@openuidev/react-headless";
+} from "@openuidev/react-ui";
interface CloudChatLLM extends ChatLLM {
setSelectedModel: (model: string) => void;
}
-export function createCloudChatLLM(): CloudChatLLM {
- let selectedModel = DEFAULT_MODEL;
+interface CloudChatLLMOptions {
+ initialModel?: string;
+ shouldSendFullHistory?: (threadId: string) => boolean;
+ onFullHistoryAccepted?: (threadId: string) => void;
+ onPromptSubmitted?: (observation: CloudChatObservation) => void;
+}
+
+export interface CloudChatObservation {
+ threadId: string;
+ model: string;
+}
+
+export function createCloudChatLLM(options: CloudChatLLMOptions = {}): CloudChatLLM {
+ let selectedModel = options.initialModel ?? DEFAULT_MODEL;
+ const llm = fetchLLM({
+ url: "/api/openui-cloud/chat",
+ streamAdapter: openAIResponsesAdapter(),
+ messageFormat: openAIConversationMessageFormat,
+ fetch: async (input, init) => {
+ const payload = JSON.parse(String(init?.body)) as {
+ threadId: string;
+ messages: unknown[];
+ };
+ const shouldSendFullHistory = options.shouldSendFullHistory?.(payload.threadId) ?? false;
+ const observation = { threadId: payload.threadId, model: selectedModel };
+ options.onPromptSubmitted?.(observation);
+
+ let response: Response;
+ try {
+ response = await fetch(input, {
+ ...init,
+ body: JSON.stringify({
+ threadId: payload.threadId,
+ input: shouldSendFullHistory ? payload.messages : payload.messages.slice(-1),
+ model: selectedModel,
+ }),
+ });
+ } catch (error) {
+ throw error;
+ }
+
+ if (!response.ok) {
+ return response;
+ }
+
+ if (shouldSendFullHistory) {
+ options.onFullHistoryAccepted?.(payload.threadId);
+ }
+
+ return response;
+ },
+ });
return {
+ ...llm,
setSelectedModel(model) {
selectedModel = model;
},
- async send({ threadId, messages, signal }) {
- return fetch("/api/openui-cloud/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- threadId,
- input: openAIConversationMessageFormat.toApi(messages.slice(-1)),
- model: selectedModel,
- }),
- signal,
- });
- },
- streamProtocol: openAIResponsesAdapter(),
};
}