The Open Standard for Generative UI
refactor(cloud-chat): replace localStorage model management with usePersistedModel hook (#857)
Subham Das4d65c3e712e4
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.tsxindex 56c71d0ac..590593d31 100644--- 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.tsx@@ -1,9 +1,9 @@"use client";+import { usePersistedModel, getPersistedModel } from "@/hooks/use-persisted-model";import { useTheme } from "@/hooks/use-system-theme";import { shouldShowBillingCreditsNotice } from "@/lib/billing";import { createCloudChatLLM } from "@/lib/cloud-chat-llm";-import { DEFAULT_MODEL, MODEL_OPTIONS } from "@/lib/models";import { defineArtifactCategories } from "@openuidev/react-headless";import { AgentInterface } from "@openuidev/react-ui";import {@@ -12,7 +12,7 @@ import {reportArtifactRenderer,useOpenuiCloudStorage,} from "@openuidev/thesys";-import { useCallback, useEffect, useState, useSyncExternalStore } from "react";+import { useCallback, useEffect, useState } from "react";import { BillingCreditsDialog } from "./billing-credits-dialog";import { ModelSwitcher } from "./model-switcher";@@ -23,64 +23,9 @@ const { artifactRenderers, artifactCategories } = defineArtifactCategories([const showBillingCreditsNotice = shouldShowBillingCreditsNotice();-// The chosen model is persisted in localStorage so it survives a refresh-// (TH-2365). It is read through useSyncExternalStore so the value stays-// hydration-safe (server → DEFAULT_MODEL, client → the stored value) and in-// sync across tabs, without a setState-in-effect.-const MODEL_STORAGE_KEY = "openui-cloud:selected-model";-const modelStoreListeners = new Set<() => void>();--function readStoredModel(): string | null {- if (typeof window === "undefined") return null;- try {- const saved = window.localStorage.getItem(MODEL_STORAGE_KEY);- // Ignore a stale id that is no longer in the model list.- return saved && MODEL_OPTIONS.some((option) => option.id === saved) ? saved : null;- } catch {- return null;- }-}--function getModelSnapshot(): string {- return readStoredModel() ?? DEFAULT_MODEL;-}--function getServerModelSnapshot(): string {- return DEFAULT_MODEL;-}--function subscribeModelStore(onChange: () => void): () => void {- modelStoreListeners.add(onChange);- // Cross-tab updates arrive via the storage event; same-tab updates are- // dispatched manually from storeModel.- const onStorage = (event: StorageEvent) => {- if (event.key === MODEL_STORAGE_KEY) onChange();- };- window.addEventListener("storage", onStorage);- return () => {- modelStoreListeners.delete(onChange);- window.removeEventListener("storage", onStorage);- };-}--function storeModel(model: string): void {- if (typeof window === "undefined") return;- try {- window.localStorage.setItem(MODEL_STORAGE_KEY, model);- } catch {- // Ignore storage failures (private mode, quota, disabled storage).- }- // Notify same-tab subscribers (the storage event only fires in other tabs).- modelStoreListeners.forEach((listener) => listener());-}-export function CloudChat() {const mode = useTheme();- const selectedModel = useSyncExternalStore(- subscribeModelStore,- getModelSnapshot,- getServerModelSnapshot,- );+ const [selectedModel, setSelectedModel] = usePersistedModel();const [billingDialogOpen, setBillingDialogOpen] = useState(false);const [billingCreditsRequired, setBillingCreditsRequired] = useState(false);const [llm] = useState(() =>@@ -89,7 +34,7 @@ export function CloudChat() {// selection at construction. selectedModel is still the server snapshot// (DEFAULT_MODEL) during the first client render; the effect below also// keeps it in sync afterwards.- initialModel: getModelSnapshot(),+ initialModel: getPersistedModel(),showBillingCreditsNotice,onRequestStart: () => {if (showBillingCreditsNotice) setBillingCreditsRequired(false);@@ -115,9 +60,9 @@ export function CloudChat() {(model: string) => {llm.setSelectedModel(model);// Persist + notify; useSyncExternalStore re-reads and re-renders.- storeModel(model);+ setSelectedModel(model);},- [llm],+ [llm, setSelectedModel],);return (diff --git a/packages/openui-cli/src/templates/openui-cloud/src/hooks/use-persisted-model.ts b/packages/openui-cli/src/templates/openui-cloud/src/hooks/use-persisted-model.tsnew file mode 100644index 000000000..3e773f02d--- /dev/null+++ b/packages/openui-cli/src/templates/openui-cloud/src/hooks/use-persisted-model.ts@@ -0,0 +1,45 @@+"use client";++import { useCallback, useEffect, useState } from "react";++import { DEFAULT_MODEL, MODEL_OPTIONS } from "@/lib/models";++// The chosen model is saved in localStorage so it survives a page refresh.+const MODEL_STORAGE_KEY = "openui-cloud:selected-model";++export function getPersistedModel(): string {+ if (typeof window === "undefined") return DEFAULT_MODEL;+ try {+ const saved = window.localStorage.getItem(MODEL_STORAGE_KEY);+ if (saved && MODEL_OPTIONS.some((option) => option.id === saved)) {+ return saved;+ }+ } catch {+ // Ignore storage failures (private mode, quota, disabled storage).+ }+ return DEFAULT_MODEL;+}++// Like useState, but the value is remembered across refreshes.+export function usePersistedModel(): readonly [string, (model: string) => void] {++ const [model, setModel] = useState(DEFAULT_MODEL);++ useEffect(() => {++ // eslint-disable-next-line react-hooks/set-state-in-effect+ setModel(getPersistedModel());+ }, []);++ // Update the model and save the new choice to localStorage.+ const selectModel = useCallback((next: string) => {+ setModel(next);+ try {+ window.localStorage.setItem(MODEL_STORAGE_KEY, next);+ } catch {+ // Ignore storage failures (private mode, quota, disabled storage).+ }+ }, []);++ return [model, selectModel] as const;+}