File size: 1,598 Bytes
76fc93a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | 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;
}
|