The Open Standard for Generative UI
Improve OpenUI Cloud model and billing UX (#735)
Zahle Khan9a2e60cffd6e
diff --git a/packages/openui-cli/src/templates/openui-cloud/README.md b/packages/openui-cli/src/templates/openui-cloud/README.mdindex 01acedbdc..c16c16c5c 100644--- a/packages/openui-cli/src/templates/openui-cloud/README.md+++ b/packages/openui-cli/src/templates/openui-cloud/README.md@@ -6,7 +6,10 @@ This is an [OpenUI](https://openui.com) Cloud project bootstrapped with [`openuicp .env.example .env.local # fill THESYS_API_KEY and point the base URLs at your API```-Required env: `THESYS_API_KEY`, `OPENUI_MODEL` (bare `provider/model`, e.g. `openai/gpt-5`), `DEMO_USER_ID`.+Required env: `THESYS_API_KEY`, `DEMO_USER_ID`.++Optional env: `OPENUI_MODEL` sets the server-side fallback model used before a user picks a model+in the app.## Getting Started@@ -29,31 +32,19 @@ by adding system prompts or tools.## Switching Models-To switch the chat model used for the app, add an `OPENUI_MODEL` env var in your .env file. Thesys Server accepts a value in the `provider/model` format compliant with [models.dev](models.dev). Some of the models supported include:--| Provider | Model | Model String |-|----------|-----------|--------------|-| Google | Gemini 3.1 Flash Lite | google/gemini-3.1-flash-lite-free |-| Google | Gemini 3.1 Pro | google/gemini-3.1-pro-free |-| Google | Gemini 3.5 Flash | google/gemini-3.5-flash-free |-| OpenAI | GPT 5.2 | openai/gpt-5.2 |-| OpenAI | GPT 5.5 | openai/gpt-5.5 |-| OpenAI | GPT 5 | openai/gpt-5.4|-| OpenAI | GPT 5 | openai/gpt-5.4-mini|-| OpenAI | GPT 5 | openai/gpt-5.1|-| OpenAI | GPT 5 | openai/gpt-5|-| OpenAI | GPT 5 | openai/gpt-5-mini|-| OpenAI | GPT 5 | openai/gpt-5-nano|-| OpenAI | GPT 5 | openai/gpt-4.1|-| OpenAI | GPT 5 | openai/gpt-4.1-mini|-| OpenAI | GPT 5 | openai/gpt-4o|-| Anthropic | Claude Sonnet | anthropic/claude-sonnet-5|-| Anthropic | Claude Opus | anthropic/claude-opus-4.7|-| Anthropic | Claude Sonnet | anthropic/claude-sonnet-4.6|-| Anthropic | Claude Sonnet | anthropic/claude-sonnet-4|-| Anthropic | Claude Haiku | anthropic/claude-haiku-4.5|+Use the model switcher in the chat header to choose a model for new messages. The starter keeps a+small curated model list in the frontend and sends the selected `provider/model` id to `/api/chat`.+The built-in list includes Gemini, GPT, Claude Sonnet, and Claude Opus options; free Gemini+variants are marked with a `Free` badge.++The built-in model ids are available on [models.dev's OpenRouter provider+list](https://models.dev/providers/openrouter/).+To set the initial server fallback, add `OPENUI_MODEL` to your `.env` file:+```bash+OPENUI_MODEL=google/gemini-3.1-pro-free+```## SDK packagesdiff --git a/packages/openui-cli/src/templates/openui-cloud/src/app/api/chat/route.ts b/packages/openui-cli/src/templates/openui-cloud/src/app/api/chat/route.tsindex 0dd3a5989..94498d4b8 100644--- a/packages/openui-cli/src/templates/openui-cloud/src/app/api/chat/route.ts+++ b/packages/openui-cli/src/templates/openui-cloud/src/app/api/chat/route.ts@@ -1,4 +1,6 @@+import { getBillingCreditsErrorMessage } from "@/lib/billing";import { envOr, requiredEnv } from "@/lib/env";+import { DEFAULT_MODEL, resolveRequestedModel } from "@/lib/models";import { artifactTool, createResponsesInstructions } from "@openuidev/thesys-server";import OpenAI from "openai";import type { ResponseInputItem } from "openai/resources/responses/responses";@@ -16,9 +18,10 @@ import type { ResponseInputItem } from "openai/resources/responses/responses";* with the fct_ token (see /api/frontend-token + the storage adapter).*/export async function POST(req: Request) {- const { threadId, input } = (await req.json()) as {+ const { threadId, input, model: requestedModel } = (await req.json()) as {threadId?: string;input?: ResponseInputItem[];+ model?: unknown;};if (!threadId) {@@ -41,9 +44,11 @@ export async function POST(req: Request) {let stream: AsyncIterable<Record<string, unknown>>;try {+ const model = resolveRequestedModel(requestedModel, envOr("OPENUI_MODEL", DEFAULT_MODEL));+stream = (await client.responses.create({- model: envOr("OPENUI_MODEL", "google/gemini-3.1-pro-free"),+ model,conversation: threadId, // store:true persists to the conversationinput,stream: true,@@ -65,6 +70,15 @@ export async function POST(req: Request) {} catch (err) {// The SDK surfaces upstream HTTP errors (e.g. 403) as APIError.const e = err as { status?: number; error?: unknown; message?: string };+ if (isRateLimitError(e)) {+ return Response.json(+ {+ error: { message: getBillingCreditsErrorMessage() },+ },+ { status: 429 },+ );+ }+return Response.json({ error: e.error ?? { message: e.message ?? "upstream error" } },{ status: e.status ?? 502 },@@ -80,7 +94,11 @@ export async function POST(req: Request) {controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));}} catch (err) {- const message = err instanceof Error ? err.message : String(err);+ const message = isRateLimitError(err)+ ? getBillingCreditsErrorMessage()+ : err instanceof Error+ ? err.message+ : String(err);controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type: "error", message })}\n\n`),);@@ -98,3 +116,7 @@ export async function POST(req: Request) {},});}++function isRateLimitError(err: unknown): boolean {+ return typeof err === "object" && err !== null && "status" in err && err.status === 429;+}diff --git a/packages/openui-cli/src/templates/openui-cloud/src/app/globals.css b/packages/openui-cli/src/templates/openui-cloud/src/app/globals.cssindex b60243d5e..de65c92f6 100644--- a/packages/openui-cli/src/templates/openui-cloud/src/app/globals.css+++ b/packages/openui-cli/src/templates/openui-cloud/src/app/globals.css@@ -10,3 +10,200 @@flex: 1 1 0% !important;min-height: 0 !important;}++.openui-cloud-thread-header .openui-agent-thread-header__title {+ display: none;+}++.openui-cloud-thread-header .openui-agent-thread-header__actions {+ flex: 1 1 auto;+ min-width: 0;+ justify-content: space-between;+}++.openui-cloud-model-switcher {+ min-width: 0;+}++.openui-cloud-thread-header .openui-cloud-model-switcher {+ flex: 0 1 auto;+}++.openui-cloud-model-switcher__trigger {+ 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;+ padding-inline: 10px !important;+ border-radius: 8px !important;+ border: 1px solid #e5e7eb !important;+ background: #ffffff !important;+ color: #111827 !important;+ box-shadow: 0 1px 2px rgba(17, 24, 39, 0.04);+ font-size: 14px !important;+}++.openui-cloud-model-switcher__trigger .openui-select-trigger-icon {+ margin-left: 2px;+ flex: 0 0 auto;+}++.openui-cloud-model-switcher__value {+ min-width: 0;+ flex: 0 1 auto;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.openui-cloud-model-switcher__model-badge {+ display: inline-flex;+ flex: 0 0 auto;+ align-items: center;+ justify-content: center;+ border-radius: 999px;+ background: #dcfce7;+ color: #15803d;+ font-size: 10px;+ font-weight: 600;+ line-height: 1;+ padding: 3px 7px;+}++.openui-agent-thread-error {+ width: min(760px, calc(100% - 32px));+ margin: 8px auto 12px;+}++.openui-agent-thread-error .openui-callout {+ display: flex;+ align-items: center;+ gap: 8px;+ border: 1px solid var(--openui-border-interactive) !important;+ border-radius: var(--openui-radius-l) !important;+ background: var(--openui-foreground) !important;+ padding: 10px 12px !important;+ box-shadow: var(--openui-shadow-m) !important;+}++.openui-agent-thread-error .openui-callout-title {+ display: none;+}++.openui-agent-thread-error .openui-callout-description {+ margin: 0 !important;+ color: var(--openui-text-neutral-secondary) !important;+ font: var(--openui-text-body-sm) !important;+ letter-spacing: var(--openui-text-body-sm-letter-spacing) !important;+}++.openui-cloud-billing-dialog__description {+ margin: 0;+ color: var(--openui-text-neutral-secondary);+ font: var(--openui-text-body-default);+ letter-spacing: var(--openui-text-body-default-letter-spacing);+}++.openui-cloud-billing-dialog__actions {+ display: flex;+ align-items: center;+ gap: var(--openui-space-s);+ margin-top: var(--openui-space-xs);+}++.openui-cloud-root--billing-credits-required .openui-agent-thread-error {+ display: none;+}++.openui-cloud-model-switcher__content {+ width: min(360px, calc(100vw - 32px));+ max-height: 360px;+ overflow: auto;+}++.openui-cloud-model-switcher__content .openui-select-item {+ align-items: flex-start;+}++.openui-cloud-model-switcher__content .openui-select-item-text {+ min-width: 0;+}++.openui-cloud-model-switcher__option {+ display: flex;+ min-width: 0;+ flex-direction: column;+ gap: 2px;+}++.openui-cloud-model-switcher__option-heading {+ display: flex;+ min-width: 0;+ align-items: center;+ gap: 6px;+}++.openui-cloud-model-switcher__option-name,+.openui-cloud-model-switcher__option-id {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.openui-cloud-model-switcher__option-id {+ color: #6b7280;+ font-size: 12px;+}++.openui-cloud-mobile-header .openui-agent-mobile-header-logo-container {+ display: none;+}++.openui-cloud-mobile-header .openui-agent-mobile-header-actions {+ flex: 1 1 auto;+ min-width: 0;+ justify-content: space-between;+}++.openui-cloud-mobile-header .openui-cloud-model-switcher {+ order: -1;+ flex: 0 1 auto;+ min-width: 0;+}++.openui-cloud-mobile-header .openui-cloud-model-switcher__trigger {+ width: min(220px, 100%) !important;+}++.openui-cloud-mobile-header .openui-cloud-model-switcher__trigger .openui-select-trigger-icon {+ margin-left: auto;+}++@media (max-width: 380px) {+ .openui-cloud-mobile-header .openui-cloud-model-switcher__trigger {+ width: min(190px, 100%) !important;+ }+}++@media (max-width: 640px) {+ .openui-agent-thread-error {+ width: calc(100% - 24px);+ }++ .openui-agent-thread-error .openui-callout {+ align-items: flex-start;+ }++ .openui-cloud-billing-dialog__actions {+ flex-direction: column;+ align-items: stretch;+ }++ .openui-cloud-billing-dialog__actions .openui-button-base {+ width: 100%;+ justify-content: center;+ }+}diff --git a/packages/openui-cli/src/templates/openui-cloud/src/app/page.tsx b/packages/openui-cli/src/templates/openui-cloud/src/app/page.tsxindex 2892fca23..d75fb021e 100644--- a/packages/openui-cli/src/templates/openui-cloud/src/app/page.tsx+++ b/packages/openui-cli/src/templates/openui-cloud/src/app/page.tsx@@ -1,79 +1,10 @@-"use client";import "@openuidev/react-ui/components.css";import "@openuidev/thesys/styles.css";-import { useTheme } from "@/hooks/use-system-theme";-import {- defineArtifactCategories,- openAIConversationMessageFormat,- openAIResponsesAdapter,- type ChatLLM,-} from "@openuidev/react-headless";-import { AgentInterface } from "@openuidev/react-ui";-import {- chatLibrary,- presentationArtifactRenderer,- reportArtifactRenderer,- useOpenuiCloudStorage,-} from "@openuidev/thesys";+import { CloudChat } from "@/components/cloud-chat";-const { artifactRenderers, artifactCategories } = defineArtifactCategories([- { name: "Presentations", renderers: [presentationArtifactRenderer] },- { name: "Reports", renderers: [reportArtifactRenderer] },-]);--const llm: ChatLLM = {- send: async ({ threadId, messages, signal }) => {- const latest = messages.slice(-1);- return fetch("/api/chat", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ threadId, input: openAIConversationMessageFormat.toApi(latest) }),- signal,- });- },- streamProtocol: openAIResponsesAdapter(),-};+export const dynamic = "force-dynamic";export default function Page() {- const mode = useTheme();- const storage = useOpenuiCloudStorage({- token: "/api/frontend-token",- apiBaseUrl: "https://api.thesys.dev",- features: { artifact: true },- });-- return (- <div className="h-screen w-screen overflow-hidden relative">- <AgentInterface- storage={storage}- llm={llm}- componentLibrary={chatLibrary}- artifactRenderers={artifactRenderers}- artifactCategories={artifactCategories}- agentName="OpenUI Cloud"- scrollVariant="always"- scrollOnLoad={false}- theme={{ mode }}- starters={[- {- displayText: "Summarize EV trends",- prompt: "In a few sentences, summarize the biggest EV market trends this quarter.",- },- {- displayText: "Pricing strategy tips",- prompt: "List five quick tips for pricing a new electric vehicle competitively.",- },- {- displayText: "Quarterly deck",- prompt: "Create a short presentation about our Q2 results with three slides.",- },- {- displayText: "Market report",- prompt: "Write a brief market-analysis report on the EV sector.",- },- ]}- />- </div>- );+ return <CloudChat />;}diff --git a/packages/openui-cli/src/templates/openui-cloud/src/components/billing-credits-dialog.tsx b/packages/openui-cli/src/templates/openui-cloud/src/components/billing-credits-dialog.tsxnew file mode 100644index 000000000..89fb1c7a3--- /dev/null+++ b/packages/openui-cli/src/templates/openui-cloud/src/components/billing-credits-dialog.tsx@@ -0,0 +1,37 @@+"use client";++import {+ BILLING_CREDITS_ACTION_LABEL,+ BILLING_CREDITS_ERROR_MESSAGE,+ BILLING_CREDITS_ERROR_TITLE,+ BILLING_URL,+} from "@/lib/billing";+import { Button } from "@openuidev/react-ui";+import { Modal } from "@openuidev/react-ui/Modal";+import { CreditCard } from "lucide-react";++interface BillingCreditsDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+}++export function BillingCreditsDialog({ open, onOpenChange }: BillingCreditsDialogProps) {+ return (+ <Modal open={open} onOpenChange={onOpenChange} size="sm" title={BILLING_CREDITS_ERROR_TITLE}>+ <p className="openui-cloud-billing-dialog__description">+ {BILLING_CREDITS_ERROR_MESSAGE}+ </p>+ <div className="openui-cloud-billing-dialog__actions">+ <Button+ iconLeft={<CreditCard />}+ onClick={() => window.open(BILLING_URL, "_blank", "noopener,noreferrer")}+ size="medium"+ type="button"+ variant="primary"+ >+ {BILLING_CREDITS_ACTION_LABEL}+ </Button>+ </div>+ </Modal>+ );+}diff --git a/packages/openui-cli/src/templates/openui-cloud/src/components/cloud-chat.tsx b/packages/openui-cli/src/templates/openui-cloud/src/components/cloud-chat.tsxnew file mode 100644index 000000000..4710377e4--- /dev/null+++ b/packages/openui-cli/src/templates/openui-cloud/src/components/cloud-chat.tsx@@ -0,0 +1,110 @@+"use client";++import { useTheme } from "@/hooks/use-system-theme";+import { shouldShowBillingCreditsNotice } from "@/lib/billing";+import { createCloudChatLLM } from "@/lib/cloud-chat-llm";+import { DEFAULT_MODEL } from "@/lib/models";+import { defineArtifactCategories } from "@openuidev/react-headless";+import { AgentInterface } from "@openuidev/react-ui";+import {+ chatLibrary,+ presentationArtifactRenderer,+ reportArtifactRenderer,+ useOpenuiCloudStorage,+} from "@openuidev/thesys";+import { useCallback, useEffect, useState } from "react";+import { BillingCreditsDialog } from "./billing-credits-dialog";+import { ModelSwitcher } from "./model-switcher";++const { artifactRenderers, artifactCategories } = defineArtifactCategories([+ { name: "Presentations", renderers: [presentationArtifactRenderer] },+ { name: "Reports", renderers: [reportArtifactRenderer] },+]);++const showBillingCreditsNotice = shouldShowBillingCreditsNotice();++export function CloudChat() {+ const mode = useTheme();+ const [selectedModel, setSelectedModel] = useState(DEFAULT_MODEL);+ const [billingDialogOpen, setBillingDialogOpen] = useState(false);+ const [billingCreditsRequired, setBillingCreditsRequired] = useState(false);+ const [llm] = useState(() =>+ createCloudChatLLM({+ initialModel: selectedModel,+ showBillingCreditsNotice,+ onRequestStart: () => {+ if (showBillingCreditsNotice) setBillingCreditsRequired(false);+ },+ onBillingCreditsRequired: () => {+ setBillingCreditsRequired(true);+ setBillingDialogOpen(true);+ },+ }),+ );+ const storage = useOpenuiCloudStorage({+ token: "/api/frontend-token",+ apiBaseUrl: "https://api.thesys.dev",+ features: { artifact: true },+ });++ useEffect(() => {+ llm.setSelectedModel(selectedModel);+ }, [llm, selectedModel]);++ const handleModelChange = useCallback((model: string) => {+ llm.setSelectedModel(model);+ setSelectedModel(model);+ }, [llm]);++ return (+ <div+ className={`h-screen w-screen overflow-hidden relative${+ billingCreditsRequired ? " openui-cloud-root--billing-credits-required" : ""+ }`}+ >+ <AgentInterface+ storage={storage}+ llm={llm}+ componentLibrary={chatLibrary}+ artifactRenderers={artifactRenderers}+ artifactCategories={artifactCategories}+ agentName="OpenUI Cloud"+ scrollVariant="always"+ scrollOnLoad={false}+ theme={{ mode }}+ starters={[+ {+ displayText: "Summarize EV trends",+ prompt: "In a few sentences, summarize the biggest EV market trends this quarter.",+ },+ {+ displayText: "Pricing strategy tips",+ prompt: "List five quick tips for pricing a new electric vehicle competitively.",+ },+ {+ displayText: "Quarterly deck",+ prompt: "Create a short presentation about our Q2 results with three slides.",+ },+ {+ displayText: "Market report",+ prompt: "Write a brief market-analysis report on the EV sector.",+ },+ ]}+ >+ <AgentInterface.MobileHeader+ className="openui-cloud-mobile-header"+ agentName=""+ actions={+ <ModelSwitcher selectedModel={selectedModel} onModelChange={handleModelChange} />+ }+ />+ <AgentInterface.ThreadHeader className="openui-cloud-thread-header">+ <ModelSwitcher selectedModel={selectedModel} onModelChange={handleModelChange} />+ </AgentInterface.ThreadHeader>+ </AgentInterface>+ {showBillingCreditsNotice ? (+ <BillingCreditsDialog open={billingDialogOpen} onOpenChange={setBillingDialogOpen} />+ ) : null}+ </div>+ );+}diff --git a/packages/openui-cli/src/templates/openui-cloud/src/components/model-switcher.tsx b/packages/openui-cli/src/templates/openui-cloud/src/components/model-switcher.tsxnew file mode 100644index 000000000..67ec2da89--- /dev/null+++ b/packages/openui-cli/src/templates/openui-cloud/src/components/model-switcher.tsx@@ -0,0 +1,77 @@+"use client";++import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectLabel,+ SelectTrigger,+} from "@openuidev/react-ui";+import { useMemo } from "react";++import { MODEL_OPTIONS, type ModelOption } from "@/lib/models";++interface ModelSwitcherProps {+ selectedModel: string;+ onModelChange: (model: string) => void;+}++export function ModelSwitcher({ selectedModel, onModelChange }: ModelSwitcherProps) {+ const selectedOption =+ MODEL_OPTIONS.find((model) => model.id === selectedModel) ?? MODEL_OPTIONS[0];+ const groupedModels = useMemo(() => groupByProvider(MODEL_OPTIONS), []);++ return (+ <div className="openui-cloud-model-switcher">+ <Select value={selectedModel} onValueChange={onModelChange} size="sm">+ <SelectTrigger+ aria-label="Select model"+ className="openui-cloud-model-switcher__trigger"+ title={selectedOption?.id ?? selectedModel}+ >+ <span className="openui-cloud-model-switcher__value">+ {selectedOption?.name ?? selectedModel}+ </span>+ {selectedOption?.badge ? (+ <span className="openui-cloud-model-switcher__model-badge">{selectedOption.badge}</span>+ ) : null}+ </SelectTrigger>+ <SelectContent align="start" className="openui-cloud-model-switcher__content">+ {groupedModels.map(([provider, providerModels]) => (+ <SelectGroup key={provider}>+ <SelectLabel>{provider}</SelectLabel>+ {providerModels.map((model) => (+ <SelectItem key={model.id} value={model.id}>+ <span className="openui-cloud-model-switcher__option">+ <span className="openui-cloud-model-switcher__option-heading">+ <span className="openui-cloud-model-switcher__option-name">{model.name}</span>+ {model.badge ? (+ <span className="openui-cloud-model-switcher__model-badge">+ {model.badge}+ </span>+ ) : null}+ </span>+ <span className="openui-cloud-model-switcher__option-id">{model.id}</span>+ </span>+ </SelectItem>+ ))}+ </SelectGroup>+ ))}+ </SelectContent>+ </Select>+ </div>+ );+}++function groupByProvider(models: 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);+ }++ return [...grouped.entries()];+}diff --git a/packages/openui-cli/src/templates/openui-cloud/src/lib/billing.ts b/packages/openui-cli/src/templates/openui-cloud/src/lib/billing.tsnew file mode 100644index 000000000..63a7c750c--- /dev/null+++ b/packages/openui-cli/src/templates/openui-cloud/src/lib/billing.ts@@ -0,0 +1,21 @@+export const BILLING_URL = "https://console.thesys.dev/billing";++export const BILLING_CREDITS_ERROR_TITLE = "Add credits to keep going";++export const BILLING_CREDITS_ERROR_MESSAGE =+ "Looks like this workspace is out of OpenUI Cloud credits. Purchase credits to keep testing, then try your request again. This notice is only shown in development.";++export const BILLING_CREDITS_ACTION_LABEL = "Purchase credits";++export const GENERIC_CHAT_ERROR_MESSAGE =+ "Something went wrong while sending your message. Please try again.";++export function shouldShowBillingCreditsNotice(nodeEnv = process.env.NODE_ENV): boolean {+ return nodeEnv === "development";+}++export function getBillingCreditsErrorMessage(+ showBillingCreditsNotice = shouldShowBillingCreditsNotice(),+): string {+ return showBillingCreditsNotice ? BILLING_CREDITS_ERROR_MESSAGE : GENERIC_CHAT_ERROR_MESSAGE;+}diff --git a/packages/openui-cli/src/templates/openui-cloud/src/lib/chat-error.ts b/packages/openui-cli/src/templates/openui-cloud/src/lib/chat-error.tsnew file mode 100644index 000000000..ad0ce2f9c--- /dev/null+++ b/packages/openui-cli/src/templates/openui-cloud/src/lib/chat-error.ts@@ -0,0 +1,28 @@+import {+ getBillingCreditsErrorMessage,+ shouldShowBillingCreditsNotice,+} from "./billing";++interface ChatErrorMessageOptions {+ showBillingCreditsNotice?: boolean;+}++export async function getChatErrorMessage(+ response: Response,+ { showBillingCreditsNotice = shouldShowBillingCreditsNotice() }: ChatErrorMessageOptions = {},+): Promise<string> {+ if (response.status === 429) {+ return getBillingCreditsErrorMessage(showBillingCreditsNotice);+ }++ try {+ const data = (await response.clone().json()) as { error?: { message?: unknown } };+ if (typeof data.error?.message === "string" && data.error.message.trim()) {+ return data.error.message;+ }+ } catch {+ // Fall through to a concise status-based message.+ }++ return `Request failed: ${response.status} ${response.statusText}`;+}diff --git a/packages/openui-cli/src/templates/openui-cloud/src/lib/cloud-chat-llm.test.ts b/packages/openui-cli/src/templates/openui-cloud/src/lib/cloud-chat-llm.test.tsnew file mode 100644index 000000000..7cddaef07--- /dev/null+++ b/packages/openui-cli/src/templates/openui-cloud/src/lib/cloud-chat-llm.test.ts@@ -0,0 +1,92 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import type { Message } from "@openuidev/react-headless";++import { BILLING_CREDITS_ERROR_MESSAGE, GENERIC_CHAT_ERROR_MESSAGE } from "./billing";+import { createCloudChatLLM } from "./cloud-chat-llm";++describe("createCloudChatLLM", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("reads the selected model when sending instead of closing over the initial value", async () => {+ let selectedModel = "google/gemini-3.1-pro-free";+ const fetchMock = vi.fn().mockResolvedValue(new Response("ok"));+ vi.stubGlobal("fetch", fetchMock);++ const llm = createCloudChatLLM({+ initialModel: selectedModel,+ });++ selectedModel = "openai/gpt-5.5";+ llm.setSelectedModel(selectedModel);+ await llm.send({+ threadId: "thread-1",+ messages: [userMessage("hello")],+ signal: new AbortController().signal,+ });++ const request = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string) as {+ model?: string;+ };+ expect(request.model).toBe("openai/gpt-5.5");+ });++ it("notifies the UI when billing credits are required", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 429 }));+ const onRequestStart = vi.fn();+ const onBillingCreditsRequired = vi.fn();+ vi.stubGlobal("fetch", fetchMock);++ const llm = createCloudChatLLM({+ initialModel: "google/gemini-3.1-pro-free",+ onRequestStart,+ onBillingCreditsRequired,+ showBillingCreditsNotice: true,+ });++ await expect(+ llm.send({+ threadId: "thread-1",+ messages: [userMessage("hello")],+ signal: new AbortController().signal,+ }),+ ).rejects.toThrow(BILLING_CREDITS_ERROR_MESSAGE);++ expect(onRequestStart).toHaveBeenCalledOnce();+ expect(onBillingCreditsRequired).toHaveBeenCalledOnce();+ expect(onRequestStart.mock.invocationCallOrder[0]).toBeLessThan(+ onBillingCreditsRequired.mock.invocationCallOrder[0],+ );+ });++ it("uses neutral copy for 429 responses when billing notices are disabled", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 429 }));+ const onBillingCreditsRequired = vi.fn();+ vi.stubGlobal("fetch", fetchMock);++ const llm = createCloudChatLLM({+ initialModel: "google/gemini-3.1-pro-free",+ onBillingCreditsRequired,+ showBillingCreditsNotice: false,+ });++ await expect(+ llm.send({+ threadId: "thread-1",+ messages: [userMessage("hello")],+ signal: new AbortController().signal,+ }),+ ).rejects.toThrow(GENERIC_CHAT_ERROR_MESSAGE);++ expect(onBillingCreditsRequired).not.toHaveBeenCalled();+ });+});++function userMessage(content: string): Message {+ return {+ id: "message-1",+ role: "user",+ content,+ } as Message;+}diff --git a/packages/openui-cli/src/templates/openui-cloud/src/lib/cloud-chat-llm.ts b/packages/openui-cli/src/templates/openui-cloud/src/lib/cloud-chat-llm.tsnew file mode 100644index 000000000..b8770074e--- /dev/null+++ b/packages/openui-cli/src/templates/openui-cloud/src/lib/cloud-chat-llm.ts@@ -0,0 +1,57 @@+import {+ openAIConversationMessageFormat,+ openAIResponsesAdapter,+ type ChatLLM,+} from "@openuidev/react-headless";++import { getChatErrorMessage } from "./chat-error";++interface CloudChatLLMOptions {+ initialModel: string;+ onRequestStart?: () => void;+ onBillingCreditsRequired?: () => void;+ showBillingCreditsNotice?: boolean;+}++export interface CloudChatLLM extends ChatLLM {+ setSelectedModel: (model: string) => void;+}++export function createCloudChatLLM({+ initialModel,+ onRequestStart,+ onBillingCreditsRequired,+ showBillingCreditsNotice = false,+}: CloudChatLLMOptions): CloudChatLLM {+ let selectedModel = initialModel;++ return {+ setSelectedModel: (model: string) => {+ selectedModel = model;+ },+ send: async ({ threadId, messages, signal }) => {+ onRequestStart?.();++ const latest = messages.slice(-1);+ const response = await fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ threadId,+ input: openAIConversationMessageFormat.toApi(latest),+ model: selectedModel,+ }),+ signal,+ });++ if (response.ok) return response;++ if (response.status === 429 && showBillingCreditsNotice) {+ onBillingCreditsRequired?.();+ }++ throw new Error(await getChatErrorMessage(response, { showBillingCreditsNotice }));+ },+ streamProtocol: openAIResponsesAdapter(),+ };+}diff --git a/packages/openui-cli/src/templates/openui-cloud/src/lib/models.ts b/packages/openui-cli/src/templates/openui-cloud/src/lib/models.tsnew file mode 100644index 000000000..76647bdf9--- /dev/null+++ b/packages/openui-cli/src/templates/openui-cloud/src/lib/models.ts@@ -0,0 +1,39 @@+export const DEFAULT_MODEL = "google/gemini-3.1-pro-free";++export interface ModelOption {+ id: string;+ name: string;+ provider: "Anthropic" | "Google" | "OpenAI";+ badge?: string;+}++export const MODEL_OPTIONS: ModelOption[] = [+ { provider: "Google", id: "google/gemini-3.1-pro-free", name: "Gemini 3.1 Pro", badge: "Free" },+ {+ provider: "Google",+ id: "google/gemini-3.1-flash-lite-free",+ name: "Gemini 3.1 Flash Lite",+ badge: "Free",+ },+ {+ provider: "Google",+ id: "google/gemini-3.5-flash-free",+ name: "Gemini 3.5 Flash",+ badge: "Free",+ },+ { provider: "Google", id: "google/gemini-3.5-flash", name: "Gemini 3.5 Flash" },+ { provider: "Google", id: "google/gemini-3.1-pro-preview", name: "Gemini 3.1 Pro Preview" },+ { provider: "OpenAI", id: "openai/gpt-5.5", name: "GPT-5.5" },+ { provider: "OpenAI", id: "openai/gpt-5.4", name: "GPT-5.4" },+ { provider: "OpenAI", id: "openai/gpt-5.4-mini", name: "GPT-5.4 mini" },+ { provider: "OpenAI", id: "openai/gpt-5.2", name: "GPT-5.2" },+ { provider: "OpenAI", id: "openai/gpt-5.1", name: "GPT-5.1" },+ { provider: "OpenAI", id: "openai/gpt-5", name: "GPT-5" },+ { provider: "Anthropic", id: "anthropic/claude-sonnet-5", name: "Claude Sonnet 5" },+ { provider: "Anthropic", id: "anthropic/claude-sonnet-4.6", name: "Claude Sonnet 4.6" },+ { provider: "Anthropic", id: "anthropic/claude-opus-4-7", name: "Claude Opus 4.7" },+];++export function resolveRequestedModel(model: unknown, fallback = DEFAULT_MODEL): string {+ return typeof model === "string" && model.trim() ? model : fallback;+}