Spaces:
Runtime error
Runtime error
| import type { UIMessage } from "ai"; | |
| export function chatStorageKey(userName: string, scope: string): string { | |
| return `chat:${userName}:${scope}`; | |
| } | |
| export function loadMessages(userName: string, scope: string): UIMessage[] | undefined { | |
| try { | |
| const raw = localStorage.getItem(chatStorageKey(userName, scope)); | |
| if (!raw) return undefined; | |
| const parsed = JSON.parse(raw); | |
| if (!Array.isArray(parsed) || parsed.length === 0) return undefined; | |
| return parsed.map((m: any) => ({ | |
| ...m, | |
| createdAt: m.createdAt ? new Date(m.createdAt) : undefined, | |
| })); | |
| } catch { | |
| return undefined; | |
| } | |
| } | |
| export function saveMessages(userName: string, scope: string, messages: UIMessage[]): void { | |
| try { | |
| if (messages.length === 0) { | |
| localStorage.removeItem(chatStorageKey(userName, scope)); | |
| } else { | |
| const serializable = messages.map((m) => { | |
| const anyMsg = m as any; | |
| return { | |
| id: m.id, | |
| role: m.role, | |
| content: anyMsg.content ?? "", | |
| parts: m.parts, | |
| createdAt: anyMsg.createdAt?.toISOString?.() ?? anyMsg.createdAt, | |
| }; | |
| }); | |
| localStorage.setItem(chatStorageKey(userName, scope), JSON.stringify(serializable)); | |
| } | |
| } catch (e) { | |
| console.warn("[chat-persist] save failed:", e); | |
| } | |
| } | |
| export function getStableAnonId(): string { | |
| const key = "collab-editor:anon-id"; | |
| const stored = localStorage.getItem(key); | |
| if (stored) return stored; | |
| const id = `anon-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; | |
| localStorage.setItem(key, id); | |
| return id; | |
| } | |