freezmo/lib/chat-store.ts
Martin Dvorak 982391ca45 Codebase audit: fix bugs, performance issues, dead code, and edge cases
1. Bugs fixed:
- Backup schema now accepts theme: "aero" so backups exported under
  Frutiger Aero pass parseBackup on import, and applyImport in "replace"
  mode replaces SRS schedules, answer history, and chats instead of
  merging into existing SRS or skipping empty arrays.
- Typed FillBlank cards bind the input value to chosen ?? value instead
  of chosen ?? "", and normalise() preserves Unicode letters (\p{L}\p{N})
  when grading non-ASCII answers.
- OpenAI-compatible vision calls (contentFor in lib/openai-compat.ts)
  prefix data:image/jpeg;base64, when routes pass stripped base64.
- Streaming calls (ollamaChatStream, providerChatStream) keep their
  AbortController active across the entire body stream and API routes
  forward request.signal so stopping a chat or cancelling a run aborts
  the upstream request immediately.
- HomeworkCard uses homeworkModeLabelKey so "check" records display the
  Checked label instead of Step-by-step guide.
- Desktop dropzones on /create and /homework accept dropped documents as
  well as images.
- LibraryScreen filters reported questions out of its due and mistake
  counts to match ReviewClient.
- Clearing a provider key resets generation if it pointed at that
  provider; chat conversations persist and restore provider; ModelPicker
  keys items by provider:name.
- RouteTransition no longer mutates module-level lastPath during render.
- Service worker asset handler falls back to Response.error() when an
  uncached asset fetch fails offline.
- Confetti and .ice-orb / .ice-bubble respect the in-app reduce-motion
  toggle.

2. Performance & cleanup:
- Deduplicate window storage listeners across all six localStorage
  stores (one listener while subscribed instead of N^2 notifications).
- Use todayAnswerCount in LibraryScreen and pass sorted folders to
  DeckCard.
- Memoize MessageRow with stable callbacks in ChatScreen and compute
  last message IDs in a single pass.
- Close ImageBitmap after drawing in lib/image.ts and destroy pdf.js
  documents in finally in lib/documents.ts.
- Avoid re-parsing serialized sync payloads in POST /api/sync.
- Deduplicate copyText (lib/share.ts -> lib/clipboard.ts), chatMessageId,
  describeExtraction, ALL_FOLDERS, useIsPhone, and remove unused helpers
  and boilerplate public/*.svg files.

Version 0.5.8, SW -> freezmo-v80.
2026-10-14 19:00:17 +00:00

195 lines
6.6 KiB
TypeScript

"use client";
/**
* Chat conversations, kept in IndexedDB so history survives reloads and the
* tab can be closed mid-conversation. The in-memory mirror makes reads
* synchronous for React (`useSyncExternalStore`); writes update the mirror
* immediately and persist asynchronously.
*
* Versioned DB `freezmo-chat` v1 with one store:
* chats keyPath id (index: updatedAt)
*
* Every stored record is validated with the shared zod schema, and the store
* is capped (oldest conversations first) so a long-lived browser can't grow
* without bound. Chats are part of the export/backup and the encrypted sync
* payload — never the API key.
*/
import { chatConversationSchema, type ChatConversation, type ChatMessage } from "./schemas";
import { markSyncDirty } from "./sync-state";
const DB_NAME = "freezmo-chat";
const DB_VERSION = 1;
const CHATS = "chats";
/** Caps: a personal app, but still bounded. */
export const MAX_CONVERSATIONS = 100;
export const MAX_MESSAGES_PER_CHAT = 300;
const EMPTY: ChatConversation[] = [];
type Listener = () => void;
let conversations: ChatConversation[] = [];
let cached: ChatConversation[] = EMPTY;
const listeners = new Set<Listener>();
let hydrated = false;
let hydration: Promise<void> | null = null;
function notify(): void {
cached = [...conversations].sort((a, b) => b.updatedAt - a.updatedAt);
listeners.forEach((listener) => listener());
}
function openDb(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onupgradeneeded = () => {
const db = request.result;
if (!db.objectStoreNames.contains(CHATS)) {
const store = db.createObjectStore(CHATS, { keyPath: "id" });
store.createIndex("updatedAt", "updatedAt");
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
async function withDb<T>(_mode: IDBTransactionMode, run: (db: IDBDatabase) => T | Promise<T>): Promise<T> {
const db = await openDb();
try {
return await run(db);
} finally {
window.setTimeout(() => db.close(), 1000);
}
}
function requestToPromise<T>(request: IDBRequest<T>): Promise<T> {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function persist(conversation: ChatConversation): void {
void withDb("readwrite", (db) => {
const transaction = db.transaction(CHATS, "readwrite");
transaction.objectStore(CHATS).put(conversation);
}).catch((error) => console.warn("[freezmo] could not save the chat", error));
}
function removeFromDb(id: string): void {
void withDb("readwrite", (db) => {
const transaction = db.transaction(CHATS, "readwrite");
transaction.objectStore(CHATS).delete(id);
}).catch((error) => console.warn("[freezmo] could not delete the chat", error));
}
/** Loads IndexedDB into the mirror exactly once. Safe to call repeatedly. */
export function ensureChatsHydrated(): Promise<void> {
if (hydrated) return Promise.resolve();
if (hydration) return hydration;
hydration = (async () => {
if (typeof indexedDB === "undefined") {
hydrated = true;
return;
}
try {
await withDb("readonly", async (db) => {
const transaction = db.transaction(CHATS, "readonly");
const loaded = await requestToPromise(transaction.objectStore(CHATS).getAll() as IDBRequest<unknown[]>);
const known = new Set(conversations.map((entry) => entry.id));
const valid: ChatConversation[] = [];
for (const raw of loaded) {
const parsed = chatConversationSchema.safeParse(raw);
if (!parsed.success) continue;
if (known.has(parsed.data.id)) continue;
valid.push(parsed.data);
}
conversations = [...conversations, ...valid]
.sort((a, b) => b.updatedAt - a.updatedAt)
.slice(0, MAX_CONVERSATIONS);
});
} catch (error) {
console.warn("[freezmo] could not read the chat history", error);
} finally {
hydrated = true;
notify();
}
})();
return hydration;
}
export const chatHistoryStore = {
subscribe(listener: Listener): () => void {
listeners.add(listener);
void ensureChatsHydrated();
return () => listeners.delete(listener);
},
getSnapshot(): ChatConversation[] {
return cached;
},
getServerSnapshot(): ChatConversation[] {
return EMPTY;
},
};
export function getConversation(id: string): ChatConversation | undefined {
return conversations.find((entry) => entry.id === id);
}
export function conversationMessages(conversation: ChatConversation): ChatMessage[] {
return conversation.messages.slice(-MAX_MESSAGES_PER_CHAT);
}
/** Creates or replaces one conversation and persists it. */
export function saveConversation(conversation: ChatConversation): void {
const parsed = chatConversationSchema.safeParse({
...conversation,
messages: conversation.messages.slice(-MAX_MESSAGES_PER_CHAT),
});
if (!parsed.success) {
console.warn("[freezmo] skipping invalid chat", parsed.error.issues[0]);
return;
}
const next = parsed.data;
conversations = [next, ...conversations.filter((entry) => entry.id !== next.id)]
.sort((a, b) => b.updatedAt - a.updatedAt)
.slice(0, MAX_CONVERSATIONS);
notify();
persist(next);
markSyncDirty();
}
export function renameConversation(id: string, title: string): void {
const trimmed = title.trim().slice(0, 200);
if (!trimmed) return;
const current = getConversation(id);
if (!current) return;
saveConversation({ ...current, title: trimmed, updatedAt: Date.now() });
}
export function deleteConversation(id: string): void {
conversations = conversations.filter((entry) => entry.id !== id);
notify();
removeFromDb(id);
markSyncDirty();
}
/** Used by backup import and sync: wholesale replacement (no dirty marking —
callers that need it wrap with withoutDirtyTracking). */
export function replaceChats(next: ChatConversation[]): void {
const valid: ChatConversation[] = [];
for (const raw of next) {
const parsed = chatConversationSchema.safeParse(raw);
if (parsed.success) valid.push(parsed.data);
}
conversations = valid.sort((a, b) => b.updatedAt - a.updatedAt).slice(0, MAX_CONVERSATIONS);
notify();
void withDb("readwrite", (db) => {
const transaction = db.transaction(CHATS, "readwrite");
transaction.objectStore(CHATS).clear();
for (const conversation of conversations) transaction.objectStore(CHATS).put(conversation);
}).catch((error) => console.warn("[freezmo] could not replace the chat history", error));
}