"use client"; /** * Per-instance remembrance of the last picked provider/model on the chat * homepage. The value is scoped by the active instance name so switching * credentials in the instance switcher automatically flips the defaults * back to whatever the user last used against that instance. * * Storage key shape: `tsagent.chat.lastConfig.`. When no instance * is active the suffix degrades to `__none__` so the default bucket still * has somewhere to live. */ export interface ChatLastConfig { providerId?: string; model?: string; } const KEY_PREFIX = "tsagent.chat.lastConfig."; const NONE_SUFFIX = "__none__"; function storageKey(instance: string | null | undefined): string { const suffix = instance && instance.length > 0 ? instance : NONE_SUFFIX; return `${KEY_PREFIX}${suffix}`; } /** Read the last picked provider/model for a given instance; returns `{}` * on SSR, missing entry, malformed JSON or storage failure. */ export function readLastConfig( instance: string | null | undefined, ): ChatLastConfig { if (typeof window === "undefined") return {}; try { const raw = window.localStorage.getItem(storageKey(instance)); if (!raw) return {}; const parsed = JSON.parse(raw) as unknown; if (!parsed || typeof parsed !== "object") return {}; const { providerId, model } = parsed as ChatLastConfig; return { providerId: typeof providerId === "string" ? providerId : undefined, model: typeof model === "string" ? model : undefined, }; } catch { return {}; } } /** Persist the last picked provider/model for a given instance. Empty * `providerId` short-circuits to avoid clobbering a previously saved * value with an empty one (e.g. during early hydration). */ export function writeLastConfig( instance: string | null | undefined, cfg: ChatLastConfig, ): void { if (typeof window === "undefined") return; if (!cfg.providerId) return; try { window.localStorage.setItem( storageKey(instance), JSON.stringify({ providerId: cfg.providerId, model: cfg.model ?? "" }), ); } catch { // quota exceeded / disabled storage — nothing meaningful to do. } }