freezmo/lib/sync-state.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

142 lines
3.8 KiB
TypeScript

"use client";
/**
* Local bookkeeping for opt-in encrypted sync: whether it is on, the random
* sync ID, when this device last synced and whether local data changed since.
* The passphrase itself is never stored here — the derived key lives in
* IndexedDB as a non-extractable CryptoKey (lib/sync-key.ts) and nowhere else.
*/
const STORAGE_KEY = "freezmo.sync.v1";
export type SyncRecord = {
v: 1;
enabled: boolean;
/** Random 128-bit id — the only handle the server ever sees. */
id: string;
/** KDF salt (not secret; travels in the envelope too). */
salt: string;
lastSyncedAt: number | null;
/** Set whenever local data changes; cleared after a successful sync. */
dirtyAt: number | null;
/** True when a sync found both sides changed (the UI asks what to keep). */
conflict: boolean;
};
const EMPTY: SyncRecord = {
v: 1,
enabled: false,
id: "",
salt: "",
lastSyncedAt: null,
dirtyAt: null,
conflict: false,
};
type Listener = () => void;
let record: SyncRecord | null = null;
let cached: SyncRecord = EMPTY;
const listeners = new Set<Listener>();
let suppressDirty = false;
function read(): SyncRecord {
if (typeof window === "undefined") return EMPTY;
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) return EMPTY;
const parsed = JSON.parse(raw) as Partial<SyncRecord>;
if (parsed.v !== 1) return EMPTY;
return {
v: 1,
enabled: parsed.enabled === true,
id: typeof parsed.id === "string" ? parsed.id : "",
salt: typeof parsed.salt === "string" ? parsed.salt : "",
lastSyncedAt: typeof parsed.lastSyncedAt === "number" ? parsed.lastSyncedAt : null,
dirtyAt: typeof parsed.dirtyAt === "number" ? parsed.dirtyAt : null,
conflict: parsed.conflict === true,
};
} catch {
return EMPTY;
}
}
function ensureLoaded(): void {
if (record !== null) return;
record = read();
cached = record;
}
function write(next: SyncRecord): void {
record = next;
cached = next;
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
} catch {
/* private mode */
}
listeners.forEach((listener) => listener());
}
function onStorage(event: StorageEvent): void {
if (event.key === STORAGE_KEY) {
record = null;
ensureLoaded();
listeners.forEach((l) => l());
}
}
export const syncStore = {
subscribe(listener: Listener): () => void {
ensureLoaded();
if (listeners.size === 0) window.addEventListener("storage", onStorage);
listeners.add(listener);
return () => {
listeners.delete(listener);
if (listeners.size === 0) window.removeEventListener("storage", onStorage);
};
},
getSnapshot(): SyncRecord {
ensureLoaded();
return cached;
},
getServerSnapshot(): SyncRecord {
return EMPTY;
},
};
export function setSyncRecord(next: Partial<SyncRecord>): void {
ensureLoaded();
write({ ...syncStore.getSnapshot(), ...next });
}
/**
* Called by every data store's write(); no-op when sync is off (or while a
* pulled payload is being applied). Returns true when the data was actually
* marked dirty, so callers can schedule an immediate sync.
*/
export function markSyncDirty(): boolean {
if (suppressDirty) return false;
ensureLoaded();
const current = syncStore.getSnapshot();
if (!current.enabled || current.dirtyAt !== null) return false;
write({ ...current, dirtyAt: Date.now() });
return true;
}
/** Applying a pulled payload must not mark the local data dirty again. */
export function withoutDirtyTracking<T>(fn: () => T): T {
suppressDirty = true;
try {
return fn();
} finally {
suppressDirty = false;
}
}
/** 16 random bytes as hex = 128 bits, unguessable. */
export function newSyncId(): string {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
}