freezmo/lib/homework.ts
Martin Dvorak bb1f4e2018 Phase 1: backup, encrypted sync and monthly-usage handling
Safety net and errors, mobile-first, desktop unchanged in behaviour.

Backup and persistence
- Settings -> Data & backup: 'Export all data' writes one zod-validated
  JSON (decks, folders, homework, progress, safe settings; the API key
  is not part of the shape and never appears in the file).
- 'Import backup' validates, shows a preview with added/replaced
  counts and offers merge or replace; invalid files get a friendly
  error. Storage persistence (navigator.storage.persist) is shown and
  requestable, with the result reported.
- A dismissible nudge appears after 5 new decks or 14 days without a
  backup and stays snoozed for 14 days.

Opt-in encrypted sync (off by default)
- New lib/sync.ts: PBKDF2-SHA256 (310k) -> AES-GCM-256, derived key
  kept as a non-extractable CryptoKey in IndexedDB (lib/sync-key.ts);
  the passphrase and key never leave the browser.
- New POST/GET/DELETE /api/sync following the route pattern (locale,
  cross-origin guard, body cap, rate limit RATE_LIMIT_SYNC, auth
  before body parsing, zod validation). One atomic JSON file per
  random 128-bit sync ID under SYNC_DIR; server-stamped updatedAt is
  the conflict clock; SYNC_MAX_BYTES and SYNC_TOTAL_BYTES enforced
  (413 / 507). The server only ever sees an opaque envelope.
- Settings -> Sync: enable with a passphrase, copy the sync ID, sync
  now, last-synced time, explicit keep-this-device / use-synced-copy
  conflict choice, join from another device (ID + passphrase, wrong
  passphrase rejected), unlock after the key is gone, delete the
  synced copy (works even on a locked device). Every data store marks
  sync dirty on write; pulled payloads are applied without marking
  dirty again.

Monthly usage vs short-term throttling
- lib/ollama.ts classifies the real 429 body (monthly/quota/upgrade
  vs burst) into new 'usage_limit' and 'throttled' kinds, mapped in
  every route and in the health probe.
- The client renders the same localized message in the deck flow,
  homework, grading and the Settings banner: the required
  upgrade/new-key copy with 'Open Settings' (jumps to and focuses the
  key field) and 'Open Ollama'. Input and wizard drafts are kept so
  Retry works right after swapping the key. No model fallback.

Verified: new phase-1 suite 38/38 (backup content + no key, import
preview/merge/replace, junk file, persistence row, nudge + snooze,
sync enable/upload/opaque blob/push/join/wrong passphrase/delete,
server validation 400/401, usage-limit copy and key focus, and the
real route mapping against a stub Ollama for both 429 variants) plus
regression 74/74, mobile 52/52, wizard 80/80, declutter 116/116,
animation 8/8, native 35/35, i18n 25/25. Key parity 638/638. Lint +
build clean. SW freezmo-v25.
2026-10-10 13:43:42 +00:00

173 lines
5.6 KiB
TypeScript

"use client";
/**
* Homework results backed by localStorage. Same tiny observable store as the
* deck library, but deliberately smaller: no folders, no attempts — just the
* assignment text (so “Make it again” works) and the result.
*
* Original photos/documents are never stored; they were reduced to text on the
* client before this point.
*/
import {
homeworkRecordSchema,
type HomeworkGuideRecord,
type HomeworkMode,
type HomeworkRecord,
type HomeworkStep,
} from "./schemas";
import { markSyncDirty } from "./sync-state";
import { uid } from "./utils";
const STORAGE_KEY = "freezmo.homework.v1";
const EMPTY: HomeworkRecord[] = [];
/** Enough to regenerate from, while staying well under the storage quota. */
export const MAX_STORED_SOURCE = 24_000;
type Listener = () => void;
let records: HomeworkRecord[] | null = null;
let cached: HomeworkRecord[] = EMPTY;
const listeners = new Set<Listener>();
function read(): HomeworkRecord[] {
if (typeof window === "undefined") return EMPTY;
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) return EMPTY;
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return EMPTY;
const valid: HomeworkRecord[] = [];
for (const entry of parsed) {
const result = homeworkRecordSchema.safeParse(entry);
if (result.success) valid.push(result.data as HomeworkRecord);
else console.warn("[freezmo] skipping invalid homework record", result.error.issues);
}
return valid;
} catch (error) {
console.warn("[freezmo] could not read the homework history", error);
return EMPTY;
}
}
function ensureLoaded(): void {
if (records !== null) return;
records = read();
cached = records;
}
function write(next: HomeworkRecord[]): void {
records = next;
cached = next;
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
} catch (error) {
console.warn("[freezmo] could not save the homework history (storage full?)", error);
}
markSyncDirty();
listeners.forEach((listener) => listener());
}
/** Used by backup import and sync: wholesale replacement of the history. */
export function replaceHomework(next: HomeworkRecord[]): void {
const valid: HomeworkRecord[] = [];
for (const entry of next) {
const result = homeworkRecordSchema.safeParse(entry);
if (result.success) valid.push(result.data as HomeworkRecord);
else console.warn("[freezmo] skipping invalid homework record in import", result.error.issues);
}
write(valid);
}
export const homeworkStore = {
subscribe(listener: Listener): () => void {
ensureLoaded();
listeners.add(listener);
const onStorage = (event: StorageEvent) => {
if (event.key === STORAGE_KEY) {
records = null;
ensureLoaded();
listeners.forEach((l) => l());
}
};
window.addEventListener("storage", onStorage);
return () => {
listeners.delete(listener);
window.removeEventListener("storage", onStorage);
};
},
getSnapshot(): HomeworkRecord[] {
ensureLoaded();
return cached;
},
getServerSnapshot(): HomeworkRecord[] {
return EMPTY;
},
};
/** Newest first. */
export function sortHomework(list: HomeworkRecord[]): HomeworkRecord[] {
return [...list].sort((a, b) => b.updatedAt - a.updatedAt);
}
export function getHomework(id: string): HomeworkRecord | undefined {
return homeworkStore.getSnapshot().find((record) => record.id === id);
}
/** Everything needed to store a result (the route's payload plus the source). */
export type NewHomeworkResult =
| { mode: "make"; title: string; language?: string; sourceText: string; answer: string }
| { mode: "guide"; title: string; language?: string; sourceText: string; steps: HomeworkStep[] };
function buildRecord(
base: { id: string; createdAt: number; updatedAt: number },
input: NewHomeworkResult,
): HomeworkRecord {
const shared = {
...base,
title: input.title.slice(0, 200),
language: input.language,
sourceText: input.sourceText.slice(0, MAX_STORED_SOURCE),
};
if (input.mode === "make") return { ...shared, mode: "make", answer: input.answer };
return { ...shared, mode: "guide", steps: input.steps };
}
export function saveHomework(input: NewHomeworkResult): HomeworkRecord {
ensureLoaded();
const now = Date.now();
const record = buildRecord({ id: uid("hw"), createdAt: now, updatedAt: now }, input);
write([record, ...homeworkStore.getSnapshot()]);
return record;
}
/** “Make it again” keeps the same history row. */
export function updateHomework(id: string, input: NewHomeworkResult): HomeworkRecord | undefined {
ensureLoaded();
const existing = homeworkStore.getSnapshot().find((record) => record.id === id);
if (!existing) return undefined;
const updated = buildRecord(
{ id: existing.id, createdAt: existing.createdAt, updatedAt: Date.now() },
input,
);
write(homeworkStore.getSnapshot().map((record) => (record.id === id ? updated : record)));
return updated;
}
export function deleteHomework(id: string): void {
ensureLoaded();
write(homeworkStore.getSnapshot().filter((record) => record.id !== id));
}
/** The final screen's text: the step answers assembled into one solution. */
export function assembleSolution(record: HomeworkGuideRecord): string {
const parts = record.steps.map((step, index) => `${index + 1}. ${step.title}\n${step.answer}`);
return [record.title, ...parts].join("\n\n");
}
/** Label for a row in the history list. */
export function homeworkModeLabelKey(mode: HomeworkMode): string {
return mode === "make" ? "homework.history.made" : "homework.history.guide";
}
export type { HomeworkGuideRecord };