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.
This commit is contained in:
Martin Dvořák 2026-10-14 19:00:17 +00:00
commit 982391ca45
57 changed files with 714 additions and 497 deletions

View file

@ -1423,6 +1423,35 @@ Things I chose while building, with the reasoning:
(measured: 268..1280 at a 1280 window) — a flat pane floating 40px inside the scene read as (measured: 268..1280 at a 1280 window) — a flat pane floating 40px inside the scene read as
"cut off next to the sidebar". "cut off next to the sidebar".
89. **Codebase-wide audit (bugs, performance, dead code, edge cases).**
- *Bugs fixed:* Backup schema now accepts `theme: "aero"` (backups exported under Frutiger Aero
used to fail `parseBackup` on import), and `applyImport` in `"replace"` mode now replaces SRS
schedules, answer history and chats instead of merging into existing SRS or skipping empty
arrays; typed `FillBlank` cards (without word-bank options) now bind the `<input>` to the live
typed state (`chosen ?? value` instead of `chosen ?? ""`) and preserve non-ASCII Unicode
letters (`\p{L}\p{N}`) when checking answers; OpenAI-compatible vision calls (`contentFor` in
`lib/openai-compat.ts`) now prefix `data:image/jpeg;base64,` when routes pass stripped base64;
streaming calls (`ollamaChatStream`, `providerChatStream`) keep their `AbortController`
attached for 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 show "Checked" instead of "Step-by-step guide";
desktop dropzones on `/create` and `/homework` accept dropped documents as well as images;
`LibraryScreen` excludes reported questions from its due and mistake counts (matching
`ReviewClient`); clearing a provider key resets `generation` if it pointed at that provider,
chat conversations persist and restore `provider`, and `ModelPicker` keys items by
`provider:name`; `RouteTransition` no longer mutates module-level `lastPath` during render;
`public/sw.js` falls back to `Response.error()` when an uncached asset fetch fails offline;
confetti and `.ice-orb`/`.ice-bubble` respect the in-app `reduce-motion` class.
- *Performance & cleanup:* The six `localStorage` stores now attach a single `storage` listener
while subscribed instead of one per subscriber (avoiding $N^2$ notifications and $N\times$ JSON
parses); `LibraryScreen` uses `todayAnswerCount` instead of building the full 35-day stats
object on every render and passes sorted `folders` down to `DeckCard`; `MessageRow` is wrapped
in `React.memo` with stable callbacks so streaming tokens only re-render the active message;
`prepareImageFromBlob` closes its `ImageBitmap` and `extractPdf` destroys the `pdf.js`
document proxy in `finally`; `POST /api/sync` no longer re-parses the serialized sync blob;
`lib/share.ts` reuses `copyText` from `lib/clipboard.ts` (including its HTTP LAN fallback);
and unused helpers and `create-next-app` SVG placeholders in `public/` were removed.
88. **A custom 404, Frutiger Aero style.** Unknown URLs used to fall through to Next's default 88. **A custom 404, Frutiger Aero style.** Unknown URLs used to fall through to Next's default
"This page could not be found". `app/not-found.tsx` now renders a standalone screen — the root "This page could not be found". `app/not-found.tsx` now renders a standalone screen — the root
layout's ice scene is the backdrop, and the glass card, the rim and the rising bubbles come from layout's ice scene is the backdrop, and the glass card, the rim and the rising bubbles come from

View file

@ -87,6 +87,9 @@ export async function POST(request: Request) {
if ("response" in gate) return gate.response; if ("response" in gate) return gate.response;
const abort = new AbortController(); const abort = new AbortController();
const timer = setTimeout(() => abort.abort(), config.timeoutMs); const timer = setTimeout(() => abort.abort(), config.timeoutMs);
const onRequestAbort = () => abort.abort();
if (request.signal.aborted) abort.abort();
else request.signal.addEventListener("abort", onRequestAbort, { once: true });
try { try {
if (images.length === 0) { if (images.length === 0) {
// Plain text needs no model call at all. // Plain text needs no model call at all.
@ -117,6 +120,7 @@ export async function POST(request: Request) {
); );
} finally { } finally {
clearTimeout(timer); clearTimeout(timer);
request.signal.removeEventListener("abort", onRequestAbort);
gate.gate.release(); gate.gate.release();
} }
} }

View file

@ -158,6 +158,9 @@ export async function POST(request: Request) {
const encode = encoder(); const encode = encoder();
const abort = new AbortController(); const abort = new AbortController();
const globalTimer = setTimeout(() => abort.abort(), config.timeoutMs); const globalTimer = setTimeout(() => abort.abort(), config.timeoutMs);
const onRequestAbort = () => abort.abort();
if (request.signal.aborted) abort.abort();
else request.signal.addEventListener("abort", onRequestAbort, { once: true });
const stream = new ReadableStream<Uint8Array>({ const stream = new ReadableStream<Uint8Array>({
async start(controller) { async start(controller) {
@ -208,6 +211,7 @@ export async function POST(request: Request) {
} }
} finally { } finally {
clearTimeout(globalTimer); clearTimeout(globalTimer);
request.signal.removeEventListener("abort", onRequestAbort);
gate.gate.release(); gate.gate.release();
try { try {
controller.close(); controller.close();
@ -218,6 +222,7 @@ export async function POST(request: Request) {
}, },
cancel() { cancel() {
clearTimeout(globalTimer); clearTimeout(globalTimer);
request.signal.removeEventListener("abort", onRequestAbort);
gate.gate.release(); gate.gate.release();
abort.abort(); abort.abort();
}, },

View file

@ -131,6 +131,9 @@ export async function POST(request: Request) {
const abort = new AbortController(); const abort = new AbortController();
// A single hard deadline for the whole pipeline (two sequential model calls). // A single hard deadline for the whole pipeline (two sequential model calls).
const globalTimer = setTimeout(() => abort.abort(), config.timeoutMs * 2); const globalTimer = setTimeout(() => abort.abort(), config.timeoutMs * 2);
const onRequestAbort = () => abort.abort();
if (request.signal.aborted) abort.abort();
else request.signal.addEventListener("abort", onRequestAbort, { once: true });
// Heartbeats: one quiet model call can run for minutes, and the client's // Heartbeats: one quiet model call can run for minutes, and the client's
// stall guard needs to tell "slow" from "dead" — a silent stream is how the // stall guard needs to tell "slow" from "dead" — a silent stream is how the
// wizard ended up loading forever. Cleared with the stream either way. // wizard ended up loading forever. Cleared with the stream either way.
@ -234,6 +237,7 @@ export async function POST(request: Request) {
} finally { } finally {
if (heartbeat) clearInterval(heartbeat); if (heartbeat) clearInterval(heartbeat);
clearTimeout(globalTimer); clearTimeout(globalTimer);
request.signal.removeEventListener("abort", onRequestAbort);
gate.gate.release(); gate.gate.release();
try { try {
controller.close(); controller.close();
@ -245,6 +249,7 @@ export async function POST(request: Request) {
cancel() { cancel() {
if (heartbeat) clearInterval(heartbeat); if (heartbeat) clearInterval(heartbeat);
clearTimeout(globalTimer); clearTimeout(globalTimer);
request.signal.removeEventListener("abort", onRequestAbort);
gate.gate.release(); gate.gate.release();
abort.abort(); abort.abort();
}, },

View file

@ -81,6 +81,11 @@ export async function POST(request: Request) {
const gate = acquireModelGate(request, config, locale); const gate = acquireModelGate(request, config, locale);
if ("response" in gate) return gate.response; if ("response" in gate) return gate.response;
const abort = new AbortController();
const timer = setTimeout(() => abort.abort(), Math.min(config.timeoutMs, 180_000));
const onRequestAbort = () => abort.abort();
if (request.signal.aborted) abort.abort();
else request.signal.addEventListener("abort", onRequestAbort, { once: true });
try { try {
const text = await refineHomeworkText({ const text = await refineHomeworkText({
model: textModel, model: textModel,
@ -89,6 +94,7 @@ export async function POST(request: Request) {
instruction: parsed.data.instruction, instruction: parsed.data.instruction,
text: parsed.data.text, text: parsed.data.text,
context: parsed.data.context, context: parsed.data.context,
signal: abort.signal,
}); });
return Response.json( return Response.json(
{ text, model: provider ? textModel : resolveModelName(config.textModel, baseAuth.directCloud) }, { text, model: provider ? textModel : resolveModelName(config.textModel, baseAuth.directCloud) },
@ -105,6 +111,8 @@ export async function POST(request: Request) {
{ status: 502 }, { status: 502 },
); );
} finally { } finally {
clearTimeout(timer);
request.signal.removeEventListener("abort", onRequestAbort);
gate.gate.release(); gate.gate.release();
} }
} }

View file

@ -124,6 +124,9 @@ export async function POST(request: Request) {
const abort = new AbortController(); const abort = new AbortController();
// A single hard deadline for the whole pipeline (two sequential model calls). // A single hard deadline for the whole pipeline (two sequential model calls).
const globalTimer = setTimeout(() => abort.abort(), config.timeoutMs * 2); const globalTimer = setTimeout(() => abort.abort(), config.timeoutMs * 2);
const onRequestAbort = () => abort.abort();
if (request.signal.aborted) abort.abort();
else request.signal.addEventListener("abort", onRequestAbort, { once: true });
// Heartbeats so the client's stall guard can tell "slow" from "dead". // Heartbeats so the client's stall guard can tell "slow" from "dead".
let heartbeat: ReturnType<typeof setInterval> | null = null; let heartbeat: ReturnType<typeof setInterval> | null = null;
@ -291,6 +294,7 @@ export async function POST(request: Request) {
} finally { } finally {
if (heartbeat) clearInterval(heartbeat); if (heartbeat) clearInterval(heartbeat);
clearTimeout(globalTimer); clearTimeout(globalTimer);
request.signal.removeEventListener("abort", onRequestAbort);
gate.gate.release(); gate.gate.release();
try { try {
controller.close(); controller.close();
@ -302,6 +306,7 @@ export async function POST(request: Request) {
cancel() { cancel() {
if (heartbeat) clearInterval(heartbeat); if (heartbeat) clearInterval(heartbeat);
clearTimeout(globalTimer); clearTimeout(globalTimer);
request.signal.removeEventListener("abort", onRequestAbort);
gate.gate.release(); gate.gate.release();
abort.abort(); abort.abort();
}, },

View file

@ -144,7 +144,8 @@ export async function POST(request: Request) {
} }
const file = fileFor(config.sync.dir, parsed.data.id); const file = fileFor(config.sync.dir, parsed.data.id);
const serialised = JSON.stringify({ updatedAt: Date.now(), envelope: parsed.data.envelope }); const updatedAt = Date.now();
const serialised = JSON.stringify({ updatedAt, envelope: parsed.data.envelope });
// Total storage cap, checked only when a new blob is created. // Total storage cap, checked only when a new blob is created.
const exists = await fs const exists = await fs
@ -162,7 +163,6 @@ export async function POST(request: Request) {
} }
await writeAtomic(file, serialised); await writeAtomic(file, serialised);
const updatedAt = (JSON.parse(serialised) as { updatedAt: number }).updatedAt;
return Response.json({ updatedAt }, { headers: { "Cache-Control": "no-store" } }); return Response.json({ updatedAt }, { headers: { "Cache-Control": "no-store" } });
} }

View file

@ -1597,10 +1597,6 @@ body:has(.overlay-open) :is(.app-header, .segmented, .tabbar, .cookie-notice) {
.fade-in-mobile { animation: none; } .fade-in-mobile { animation: none; }
} }
@media (display-mode: standalone) {
.standalone-hide { display: none }
}
/* Phones: Apple's 44px minimum for touch targets. The class is a no-op on /* Phones: Apple's 44px minimum for touch targets. The class is a no-op on
desktop (and on tablets), so components can carry it unconditionally. */ desktop (and on tablets), so components can carry it unconditionally. */
@media (max-width: 639px) { @media (max-width: 639px) {
@ -1657,7 +1653,17 @@ html.reduce-motion .ice-blob,
html.reduce-motion .ice-orb, html.reduce-motion .ice-orb,
html.reduce-motion .ice-bubble { html.reduce-motion .ice-bubble {
animation: none !important; animation: none !important;
will-change: auto;
} }
html.reduce-motion.aero .ice-bubble {
opacity: 0.55;
transform: translate3d(0, -60vh, 0);
}
html.reduce-motion .ice-orb-1 { top: 14%; left: 12%; }
html.reduce-motion .ice-orb-2 { top: 58%; left: 4%; }
html.reduce-motion .ice-orb-3 { top: auto; bottom: -70px; right: 10%; }
html.reduce-motion .ice-orb-4 { top: 24%; right: 28%; }
html.reduce-motion .ice-orb-5 { top: auto; bottom: 16%; left: 38%; }
html.reduce-motion *, html.reduce-motion *,
html.reduce-motion *::before, html.reduce-motion *::before,
html.reduce-motion *::after { html.reduce-motion *::after {

View file

@ -119,11 +119,7 @@ export function DataSection() {
<span className="min-w-0"> <span className="min-w-0">
<span className="block text-[12px] font-semibold text-[var(--text)]">{t("settings.storage")}</span> <span className="block text-[12px] font-semibold text-[var(--text)]">{t("settings.storage")}</span>
<span className="block text-[11px] leading-snug text-[var(--text-subtle)]"> <span className="block text-[11px] leading-snug text-[var(--text-subtle)]">
{persistence === "persistent" {persistence === "persistent" ? t("settings.storagePersistent") : t("settings.storageBestEffort")}
? t("settings.storagePersistent")
: persistence === "unsupported"
? t("settings.storageBestEffort")
: t("settings.storageBestEffort")}
</span> </span>
</span> </span>
{persistence === "best-effort" ? ( {persistence === "best-effort" ? (

View file

@ -10,7 +10,7 @@ import { createFolder as makeFolder, listFolders } from "@/lib/folders";
import { haptic } from "@/lib/haptics"; import { haptic } from "@/lib/haptics";
import { useI18n } from "@/lib/i18n"; import { useI18n } from "@/lib/i18n";
import { springGentle } from "@/lib/motion"; import { springGentle } from "@/lib/motion";
import { UNORGANIZED_ID, type Deck } from "@/lib/schemas"; import { UNORGANIZED_ID, type Deck, type Folder } from "@/lib/schemas";
import { shareDeck } from "@/lib/share"; import { shareDeck } from "@/lib/share";
import { appendActivities, deleteDeck, deleteNotesText, downloadDeck, renameDeck, upsertDeck } from "@/lib/storage"; import { appendActivities, deleteDeck, deleteNotesText, downloadDeck, renameDeck, upsertDeck } from "@/lib/storage";
import { showToast } from "@/lib/toast"; import { showToast } from "@/lib/toast";
@ -30,17 +30,19 @@ const ADD_OPTIONS = [3, 5, 8];
*/ */
export function DeckCard({ export function DeckCard({
deck, deck,
folders: foldersProp,
onMove, onMove,
index = 0, index = 0,
}: { }: {
deck: Deck; deck: Deck;
folders?: Folder[];
onMove?: (folderId: string | undefined) => void; onMove?: (folderId: string | undefined) => void;
/** Position in the list — used for the capped first-load stagger. */ /** Position in the list — used for the capped first-load stagger. */
index?: number; index?: number;
}) { }) {
const { t, plural } = useI18n(); const { t, plural } = useI18n();
const isPhone = useIsPhone(); const isPhone = useIsPhone();
const folders = listFolders(); const folders = foldersProp ?? listFolders();
const [busy, setBusy] = useState<Busy>(null); const [busy, setBusy] = useState<Busy>(null);
const [menuOpen, setMenuOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false);
const [renaming, setRenaming] = useState(false); const [renaming, setRenaming] = useState(false);

View file

@ -5,10 +5,11 @@ import { useRef, useState } from "react";
import { FolderIcon, PlusIcon } from "@/components/icons"; import { FolderIcon, PlusIcon } from "@/components/icons";
import { createFolder } from "@/lib/folders"; import { createFolder } from "@/lib/folders";
import { useI18n } from "@/lib/i18n"; import { useI18n } from "@/lib/i18n";
import { ALL_FOLDERS } from "@/lib/nav";
import type { Folder } from "@/lib/schemas"; import type { Folder } from "@/lib/schemas";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
export const ALL_FOLDERS = "all"; export { ALL_FOLDERS };
/** /**
* Folder switcher. Reads like a row of quiet pills (ChatGPT sidebar items): * Folder switcher. Reads like a row of quiet pills (ChatGPT sidebar items):

View file

@ -4,8 +4,9 @@ import { motion } from "framer-motion";
import Link from "next/link"; import Link from "next/link";
import { useState } from "react"; import { useState } from "react";
import { BoltIcon, ChevronDownIcon, PlayIcon, XIcon } from "@/components/icons"; import { BoltIcon, CheckCircleIcon, ChevronDownIcon, PlayIcon, XIcon } from "@/components/icons";
import { Button } from "@/components/ui"; import { Button } from "@/components/ui";
import { homeworkModeLabelKey } from "@/lib/homework";
import { useI18n } from "@/lib/i18n"; import { useI18n } from "@/lib/i18n";
import { springGentle } from "@/lib/motion"; import { springGentle } from "@/lib/motion";
import type { HomeworkRecord } from "@/lib/schemas"; import type { HomeworkRecord } from "@/lib/schemas";
@ -70,8 +71,14 @@ export function HomeworkCard({
</h2> </h2>
<p className="mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[12.5px] text-[var(--text-subtle)]"> <p className="mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[12.5px] text-[var(--text-subtle)]">
<span className="inline-flex items-center gap-1"> <span className="inline-flex items-center gap-1">
{record.mode === "make" ? <BoltIcon className="size-3.5" /> : <PlayIcon className="size-3.5" />} {record.mode === "make" ? (
{t(record.mode === "make" ? "homework.history.made" : "homework.history.guide")} <BoltIcon className="size-3.5" />
) : record.mode === "check" ? (
<CheckCircleIcon className="size-3.5" />
) : (
<PlayIcon className="size-3.5" />
)}
{t(homeworkModeLabelKey(record.mode))}
</span> </span>
<span aria-hidden>·</span> <span aria-hidden>·</span>
{formatDate(record.updatedAt)} {formatDate(record.updatedAt)}

View file

@ -16,7 +16,8 @@ import { createFolder, folderStore, renameFolder } from "@/lib/folders";
import { deleteHomework, homeworkStore, sortHomework } from "@/lib/homework"; import { deleteHomework, homeworkStore, sortHomework } from "@/lib/homework";
import { learningStore } from "@/lib/history"; import { learningStore } from "@/lib/history";
import { useI18n } from "@/lib/i18n"; import { useI18n } from "@/lib/i18n";
import { computeStats, dueItems, mistakeItems } from "@/lib/learning"; import { dueItems, mistakeItems, todayAnswerCount } from "@/lib/learning";
import { isReported, reportStore } from "@/lib/question-reports";
import { settingsStore } from "@/lib/settings"; import { settingsStore } from "@/lib/settings";
import { ALL_FOLDERS, folderSelection, useSelectedFolder } from "@/lib/nav"; import { ALL_FOLDERS, folderSelection, useSelectedFolder } from "@/lib/nav";
import { springGentle, springSheet } from "@/lib/motion"; import { springGentle, springSheet } from "@/lib/motion";
@ -110,17 +111,30 @@ export function LibraryScreen({ initialTab = "decks" }: { initialTab?: "decks" |
() => settingsStore.getSnapshot().dailyGoal, () => settingsStore.getSnapshot().dailyGoal,
() => 20, () => 20,
); );
/* Smart-review counts resolve against the live deck list: deleting a deck const reports = useSyncExternalStore(
must drop its due schedules and its mistakes right away. `dueCount` is not reportStore.subscribe,
used directly because it counts raw schedules, including decks that no reportStore.getSnapshot,
longer exist. */ reportStore.getServerSnapshot,
const deckIds = useMemo(() => new Set(decks.map((deck) => deck.id)), [decks]);
const due = useMemo(() => dueItems(srs).filter((item) => deckIds.has(item.deck.id)).length, [srs, deckIds]);
const mistakes = useMemo(
() => mistakeItems(answers).filter((item) => deckIds.has(item.deck.id)).length,
[answers, deckIds],
); );
const todayCount = useMemo(() => computeStats(answers).todayCount, [answers]); /* Smart-review counts resolve against the live deck list and reported set:
deleting a deck or reporting a question must drop its due schedules and
its mistakes right away, matching ReviewClient. */
const deckIds = useMemo(() => new Set(decks.map((deck) => deck.id)), [decks]);
const due = useMemo(
() => {
void reports;
return dueItems(srs).filter((item) => deckIds.has(item.deck.id) && !isReported(item.deck.id, item.activity.id)).length;
},
[srs, deckIds, reports],
);
const mistakes = useMemo(
() => {
void reports;
return mistakeItems(answers).filter((item) => deckIds.has(item.deck.id) && !isReported(item.deck.id, item.activity.id)).length;
},
[answers, deckIds, reports],
);
const todayCount = useMemo(() => todayAnswerCount(answers), [answers]);
const importRef = useRef<HTMLInputElement>(null); const importRef = useRef<HTMLInputElement>(null);
const sorted = useMemo(() => sortDecks(decks), [decks]); const sorted = useMemo(() => sortDecks(decks), [decks]);
@ -512,6 +526,7 @@ export function LibraryScreen({ initialTab = "decks" }: { initialTab?: "decks" |
<DeckCard <DeckCard
key={deck.id} key={deck.id}
deck={deck} deck={deck}
folders={folderList}
index={index} index={index}
onMove={(folderId) => { onMove={(folderId) => {
upsertDeck({ ...deck, folderId }); upsertDeck({ ...deck, folderId });

View file

@ -3,6 +3,7 @@
import { motion } from "framer-motion"; import { motion } from "framer-motion";
import { useAppReducedMotion as useReducedMotion } from "@/lib/motion-pref"; import { useAppReducedMotion as useReducedMotion } from "@/lib/motion-pref";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { screenVariants, tabVariants } from "@/lib/motion"; import { screenVariants, tabVariants } from "@/lib/motion";
@ -31,12 +32,18 @@ export function RouteTransition({ children }: { children: React.ReactNode }) {
const pathname = usePathname(); const pathname = usePathname();
const reduceMotion = useReducedMotion(); const reduceMotion = useReducedMotion();
const previous = lastPath; const [{ isTabSwitch, direction }] = useState(() => {
lastPath = pathname; const previous = typeof window === "undefined" ? null : lastPath;
return {
isTabSwitch: previous !== null && depth(previous) === depth(pathname) && previous !== pathname,
direction: (previous === null || depth(pathname) >= depth(previous) ? 1 : -1) as 1 | -1,
};
});
useEffect(() => {
lastPath = pathname;
}, [pathname]);
const isTabSwitch = previous !== null && depth(previous) === depth(pathname) && previous !== pathname;
const direction: 1 | -1 =
previous === null || depth(pathname) >= depth(previous) ? 1 : -1;
const variants = isTabSwitch ? tabVariants(!!reduceMotion) : screenVariants(direction, !!reduceMotion); const variants = isTabSwitch ? tabVariants(!!reduceMotion) : screenVariants(direction, !!reduceMotion);
return ( return (

View file

@ -138,7 +138,7 @@ export function SessionFeed({
); );
const finished = index >= total; const finished = index >= total;
const correct = items.filter((item) => results[item.activity.id]?.correct).length; const correct = items.filter((item) => !skipped.includes(item.activity.id) && results[item.activity.id]?.correct).length;
/** What the results slide counts: reported cards were never attempted. */ /** What the results slide counts: reported cards were never attempted. */
const attemptedTotal = Math.max(0, total - skipped.length); const attemptedTotal = Math.max(0, total - skipped.length);
const score = attemptedTotal > 0 ? Math.round((correct / attemptedTotal) * 100) : 0; const score = attemptedTotal > 0 ? Math.round((correct / attemptedTotal) * 100) : 0;

View file

@ -19,6 +19,7 @@ import { ProvidersSection } from "@/components/ProvidersSection";
import { SyncSection } from "@/components/SyncSection"; import { SyncSection } from "@/components/SyncSection";
import { clearApiKey, saveSettings, settingsStore } from "@/lib/settings"; import { clearApiKey, saveSettings, settingsStore } from "@/lib/settings";
import { useBackClose } from "@/lib/use-back-close"; import { useBackClose } from "@/lib/use-back-close";
import { useIsPhone } from "@/lib/use-phone";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { openInstallSheet, useInstallAvailable } from "@/lib/install"; import { openInstallSheet, useInstallAvailable } from "@/lib/install";
import { useHealth } from "@/lib/use-health"; import { useHealth } from "@/lib/use-health";
@ -84,21 +85,13 @@ export function SettingsDialog({
const [saved, setSaved] = useState(false); const [saved, setSaved] = useState(false);
const [confirmRemove, setConfirmRemove] = useState(false); const [confirmRemove, setConfirmRemove] = useState(false);
const [canScroll, setCanScroll] = useState(false); const [canScroll, setCanScroll] = useState(false);
const [phone, setPhone] = useState(false); // Swipe-to-dismiss is a phone gesture; the desktop dialog is unchanged.
const phone = useIsPhone();
const dragControls = useDragControls(); const dragControls = useDragControls();
const reduceMotion = useReducedMotion(); const reduceMotion = useReducedMotion();
const scrollRef = useRef<HTMLDivElement>(null); const scrollRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null); const contentRef = useRef<HTMLDivElement>(null);
// Swipe-to-dismiss is a phone gesture; the desktop dialog is unchanged.
useEffect(() => {
const query = window.matchMedia("(max-width: 639px)");
const sync = () => setPhone(query.matches);
sync();
query.addEventListener("change", sync);
return () => query.removeEventListener("change", sync);
}, []);
useEffect(() => { useEffect(() => {
if (!open) return; if (!open) return;
setKeyDraft(apiKey); setKeyDraft(apiKey);

View file

@ -113,19 +113,25 @@ export function StudyFeed({ deck }: { deck: Deck }) {
if (!retryMode && !recordedRef.current) { if (!retryMode && !recordedRef.current) {
recordedRef.current = true; recordedRef.current = true;
const answered = Object.values(results); const answered = Object.values(results);
const correct = answered.filter((entry) => entry.correct).length; const correct = queue.filter((activity) => !skipped.includes(activity.id) && results[activity.id]?.correct).length;
const attempted = Math.max(0, total - skipped.length); const attempted = Math.max(0, total - skipped.length);
const score = attempted > 0 ? (correct / attempted) * 100 : 0; const score = attempted > 0 ? (correct / attempted) * 100 : 0;
// Only a run with at least one answer counts. Without this, the scroll // Only a run with at least one answer counts. Without this, the scroll
// anchoring shift when a regenerated deck swaps in could fire a bogus // anchoring shift when a regenerated deck swaps in could fire a bogus
// 0% attempt before the feed had snapped back to the first slide. // 0% attempt before the feed had snapped back to the first slide.
if (answered.length > 0) { if (answered.length > 0) {
recordAttempt(currentDeck.id, { scorePercent: score, correct, total }); recordAttempt(currentDeck.id, { scorePercent: score, correct, total: attempted });
setCurrentDeck((prev) => ({
...prev,
attempts: prev.attempts + 1,
bestScore: Math.max(prev.bestScore ?? 0, Math.round(score)),
updatedAt: Date.now(),
}));
haptic("celebrate"); haptic("celebrate");
void celebrate("big"); void celebrate("big");
} }
} }
}, [finished, results, total, skipped.length, currentDeck.id, retryMode]); }, [finished, queue, results, total, skipped, currentDeck.id, retryMode]);
const handleAnswered = useCallback( const handleAnswered = useCallback(
(activity: Activity, correct: boolean, meta?: { userAnswer?: string }) => { (activity: Activity, correct: boolean, meta?: { userAnswer?: string }) => {
@ -166,8 +172,8 @@ export function StudyFeed({ deck }: { deck: Deck }) {
const attemptedTotal = Math.max(0, total - skipped.length); const attemptedTotal = Math.max(0, total - skipped.length);
const correctCount = useMemo( const correctCount = useMemo(
() => queue.filter((activity) => results[activity.id]?.correct).length, () => queue.filter((activity) => !skipped.includes(activity.id) && results[activity.id]?.correct).length,
[queue, results], [queue, results, skipped],
); );
const restart = useCallback( const restart = useCallback(

View file

@ -11,6 +11,7 @@ import {
DOCUMENT_ACCEPT_ATTR, DOCUMENT_ACCEPT_ATTR,
KIND_LABELS, KIND_LABELS,
describeDocumentError, describeDocumentError,
describeExtraction,
documentKindOf, documentKindOf,
documentsToText, documentsToText,
extractDocument, extractDocument,
@ -71,20 +72,6 @@ const MAX_IMAGES_TO_SEND = 12;
/** Cap for the merged text sent to the API. */ /** Cap for the merged text sent to the API. */
const MAX_TEXT_TO_SEND = 100_000; const MAX_TEXT_TO_SEND = 100_000;
function describeExtraction(
document: ExtractedDocument,
tr: (key: string, vars?: Record<string, string | number>) => string,
pl: (n: number, base: string, vars?: Record<string, string | number>) => string,
): string {
const parts = [
pl(document.words, "upload.words", { n: document.words.toLocaleString() }),
document.pages ? pl(document.pages, "upload.pages") : "",
document.images.length ? pl(document.images.length, "upload.pageImages") : "",
document.truncated ? tr("upload.truncated") : "",
];
return parts.filter(Boolean).join(" · ");
}
const DIFFICULTIES: Array<{ value: Difficulty; labelKey: string; icon: React.ReactNode; blurbKey: string }> = [ const DIFFICULTIES: Array<{ value: Difficulty; labelKey: string; icon: React.ReactNode; blurbKey: string }> = [
{ value: "easy", labelKey: "upload.easy", icon: <SunIcon className="size-5" />, blurbKey: "upload.easyBlurb" }, { value: "easy", labelKey: "upload.easy", icon: <SunIcon className="size-5" />, blurbKey: "upload.easyBlurb" },
{ {
@ -1106,7 +1093,8 @@ export function UploadScreen() {
onDrop={(event) => { onDrop={(event) => {
event.preventDefault(); event.preventDefault();
setDragging(false); setDragging(false);
void addFiles(imageFilesFromDataTransfer(event.dataTransfer)); const dropped = Array.from(event.dataTransfer?.files ?? []);
void addFiles(dropped.length > 0 ? dropped : imageFilesFromDataTransfer(event.dataTransfer));
}} }}
className={cn( className={cn(
"card relative overflow-hidden p-4 transition-all sm:p-5", "card relative overflow-hidden p-4 transition-all sm:p-5",

View file

@ -25,7 +25,7 @@ function normalise(value: string): string {
.toLowerCase() .toLowerCase()
.normalize("NFKD") .normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "") .replace(/[\u0300-\u036f]/g, "")
.replace(/[^a-z0-9\s]/g, " ") .replace(/[^\p{L}\p{N}\s]/gu, " ")
.replace(/\s+/g, " ") .replace(/\s+/g, " ")
.trim(); .trim();
} }
@ -89,7 +89,7 @@ export function FillBlank({ activity, active, onAnswered, onNext, isLast, nextLa
onAnswered(correct, { userAnswer: answerValue }); onAnswered(correct, { userAnswer: answerValue });
}; };
const displayAnswer = chosen ?? ""; const displayAnswer = chosen ?? value;
return ( return (
<> <>

View file

@ -20,7 +20,13 @@ type OrderingActivity = Extract<Activity, { type: "ordering" }>;
export function Ordering({ activity, onAnswered, onNext, isLast, nextLabel }: ActivityComponentProps<OrderingActivity>) { export function Ordering({ activity, onAnswered, onNext, isLast, nextLabel }: ActivityComponentProps<OrderingActivity>) {
const { t } = useI18n(); const { t } = useI18n();
const initial = useMemo(() => shuffle(activity.items), [activity]); const initial = useMemo(() => {
const out = shuffle(activity.items);
if (out.length > 1 && out.every((item, index) => item === activity.items[index])) {
[out[0], out[1]] = [out[1], out[0]];
}
return out;
}, [activity]);
const [items, setItems] = useState<string[]>(initial); const [items, setItems] = useState<string[]>(initial);
const [checked, setChecked] = useState(false); const [checked, setChecked] = useState(false);
const [correct, setCorrect] = useState(false); const [correct, setCorrect] = useState(false);

View file

@ -116,6 +116,10 @@ export function ChatScreen() {
/* History: hydrate once, then open ?c=<id> conversations. */ /* History: hydrate once, then open ?c=<id> conversations. */
useEffect(() => { useEffect(() => {
void ensureChatsHydrated(); void ensureChatsHydrated();
return () => {
abortRef.current?.abort();
chatActive.set(null);
};
}, []); }, []);
const loadedRef = useRef<string | null>(null); const loadedRef = useRef<string | null>(null);
@ -129,7 +133,7 @@ export function ChatScreen() {
setDraft(""); setDraft("");
setError(null); setError(null);
if (found.model) setModel(found.model); if (found.model) setModel(found.model);
if ((found as { provider?: string }).provider) setProvider((found as { provider?: string }).provider ?? "ollama"); if (found.provider) setProvider(found.provider);
loadedRef.current = found.id; loadedRef.current = found.id;
chatActive.set(found.id); chatActive.set(found.id);
}, []); }, []);
@ -188,15 +192,23 @@ export function ChatScreen() {
return [...ollama, ...cloud]; return [...ollama, ...cloud];
}, [health, providerState]); }, [health, providerState]);
const activeProvider = provider !== "ollama" && !providerState.keys[provider] ? "ollama" : provider;
const activeModel = useMemo(() => { const activeModel = useMemo(() => {
if (model && chatModels.some((entry) => entry.name === model && (entry.provider ?? "ollama") === provider)) return model; if (model && chatModels.some((entry) => entry.name === model && (entry.provider ?? "ollama") === activeProvider)) {
const sameProvider = chatModels.find((entry) => (entry.provider ?? "ollama") === provider && entry.available !== false); return model;
if (model && sameProvider?.name === model) return model; }
// The server puts the default first, but a different server may not have // The server puts the default first, but a different server may not have
// it — fall back to the first model that is actually available. // it — fall back to the first model that is actually available.
const firstAvailable = chatModels.find((entry) => (entry.provider ?? "ollama") === provider && entry.available !== false); const firstAvailable = chatModels.find(
return (firstAvailable ?? chatModels.find((entry) => (entry.provider ?? "ollama") === provider) ?? chatModels[0])?.name ?? model; (entry) => (entry.provider ?? "ollama") === activeProvider && entry.available !== false,
}, [model, chatModels, provider]); );
return (
firstAvailable ??
chatModels.find((entry) => (entry.provider ?? "ollama") === activeProvider) ??
chatModels[0]
)?.name ?? model;
}, [model, chatModels, activeProvider]);
const scopeText = useMemo(() => { const scopeText = useMemo(() => {
if (scope.kind === "all") return t("chat.scope.all"); if (scope.kind === "all") return t("chat.scope.all");
@ -266,7 +278,10 @@ export function ChatScreen() {
}; };
const persist = useCallback( const persist = useCallback(
(nextMessages: ChatMessage[], options: { title?: string; model?: string; scope?: ChatScope } = {}) => { (
nextMessages: ChatMessage[],
options: { title?: string; model?: string; provider?: string; scope?: ChatScope } = {},
) => {
const id = conversationId ?? chatMessageId("chat"); const id = conversationId ?? chatMessageId("chat");
if (!conversationId) { if (!conversationId) {
setConversationId(id); setConversationId(id);
@ -285,12 +300,13 @@ export function ChatScreen() {
messages: nextMessages, messages: nextMessages,
scope: options.scope ?? scope, scope: options.scope ?? scope,
model: options.model ?? (activeModel || undefined), model: options.model ?? (activeModel || undefined),
provider: options.provider ?? activeProvider,
createdAt: existing?.createdAt ?? Date.now(), createdAt: existing?.createdAt ?? Date.now(),
updatedAt: Date.now(), updatedAt: Date.now(),
}); });
if (nextTitle && nextTitle !== title) setTitle(nextTitle); if (nextTitle && nextTitle !== title) setTitle(nextTitle);
}, },
[conversationId, title, scope, activeModel], [conversationId, title, scope, activeModel, activeProvider],
); );
const run = async (history: ChatMessage[], extraChunks: ExtraChunk[]) => { const run = async (history: ChatMessage[], extraChunks: ExtraChunk[]) => {
@ -321,7 +337,7 @@ export function ChatScreen() {
try { try {
await streamChat({ await streamChat({
model: activeModel || undefined, model: activeModel || undefined,
provider, provider: activeProvider,
messages: history.map((message) => ({ role: message.role, content: message.content })), messages: history.map((message) => ({ role: message.role, content: message.content })),
context: context.chunks.map(({ deckId, deckTitle, section, text }) => ({ deckId, deckTitle, section, text })), context: context.chunks.map(({ deckId, deckTitle, section, text }) => ({ deckId, deckTitle, section, text })),
signal: controller.signal, signal: controller.signal,
@ -412,28 +428,24 @@ export function ChatScreen() {
void run(history, extras); void run(history, extras);
}; };
const retryLast = () => { const retryLast = useCallback(() => {
if (busy) return;
const lastUserIndex = messages.map((message) => message.role).lastIndexOf("user"); const lastUserIndex = messages.map((message) => message.role).lastIndexOf("user");
if (lastUserIndex < 0) return; if (lastUserIndex < 0) return;
const history = messages.slice(0, lastUserIndex + 1); const history = messages.slice(0, lastUserIndex + 1);
setError(null);
setMessages(history); setMessages(history);
void run(history, extrasRef.current[history[lastUserIndex].id] ?? []); void run(history, extrasRef.current[history[lastUserIndex].id] ?? []);
}; // eslint-disable-next-line react-hooks/exhaustive-deps
}, [busy, messages]);
const regenerate = () => { const editLast = useCallback(() => {
const lastUserIndex = messages.map((message) => message.role).lastIndexOf("user"); if (busy) return;
if (lastUserIndex < 0) return;
const history = messages.slice(0, lastUserIndex + 1);
setMessages(history);
void run(history, extrasRef.current[history[lastUserIndex].id] ?? []);
};
const editLast = () => {
const lastUserIndex = messages.map((message) => message.role).lastIndexOf("user"); const lastUserIndex = messages.map((message) => message.role).lastIndexOf("user");
if (lastUserIndex < 0) return; if (lastUserIndex < 0) return;
setDraft(messages[lastUserIndex].content); setDraft(messages[lastUserIndex].content);
setMessages(messages.slice(0, lastUserIndex)); setMessages(messages.slice(0, lastUserIndex));
}; }, [busy, messages]);
const resetView = useCallback(() => { const resetView = useCallback(() => {
abortRef.current?.abort(); abortRef.current?.abort();
@ -498,28 +510,34 @@ export function ChatScreen() {
return undefined; return undefined;
}, [scope, seed, decks]); }, [scope, seed, decks]);
const saveToNotes = (message: ChatMessage) => { const saveToNotes = useCallback(
if (!noteTargetDeck) return; (message: ChatMessage) => {
const current = noteTargetDeck.sourceText?.trim() ?? ""; if (!noteTargetDeck) return;
const addition = `\n\n— ${t("chat.savedFromChat")} —\n${message.content.trim()}`; const current = noteTargetDeck.sourceText?.trim() ?? "";
let next = `${current}${addition}`; const addition = `\n\n— ${t("chat.savedFromChat")} —\n${message.content.trim()}`;
let trimmed = false; let next = `${current}${addition}`;
if (next.length > 40_000) { let trimmed = false;
next = next.slice(-40_000); if (next.length > 40_000) {
trimmed = true; next = next.slice(-40_000);
} trimmed = true;
upsertDeck({ ...noteTargetDeck, sourceText: next, updatedAt: Date.now() }); }
showToast({ upsertDeck({ ...noteTargetDeck, sourceText: next, updatedAt: Date.now() });
message: trimmed showToast({
? t("chat.savedToNotesTrimmed", { deck: noteTargetDeck.title }) message: trimmed
: t("chat.savedToNotes", { deck: noteTargetDeck.title }), ? t("chat.savedToNotesTrimmed", { deck: noteTargetDeck.title })
}); : t("chat.savedToNotes", { deck: noteTargetDeck.title }),
}; });
},
[noteTargetDeck, t],
);
const toFlashcards = (message: ChatMessage) => { const toFlashcards = useCallback(
setDeckSeed({ text: message.content.slice(0, 40_000), step: 2 }); (message: ChatMessage) => {
router.push("/create"); setDeckSeed({ text: message.content.slice(0, 40_000), step: 2 });
}; router.push("/create");
},
[router],
);
const handleAttach = async (file: File) => { const handleAttach = async (file: File) => {
setAttachBusy(true); setAttachBusy(true);
@ -545,9 +563,19 @@ export function ChatScreen() {
} }
}; };
const lastAssistantId = [...messages].reverse().find((message) => message.role === "assistant")?.id; let lastAssistantId: string | undefined;
const lastUserId = [...messages].reverse().find((message) => message.role === "user")?.id; let lastUserId: string | undefined;
const lastFailedAssistant = [...messages].reverse().find((message) => message.role === "assistant" && message.error)?.id; let lastFailedAssistant: string | undefined;
for (let i = messages.length - 1; i >= 0; i -= 1) {
const message = messages[i];
if (message.role === "assistant") {
if (!lastAssistantId) lastAssistantId = message.id;
if (!lastFailedAssistant && message.error) lastFailedAssistant = message.id;
} else if (!lastUserId) {
lastUserId = message.id;
}
if (lastAssistantId && lastUserId && lastFailedAssistant) break;
}
return ( return (
<div className="flex h-full min-h-0 w-full"> <div className="flex h-full min-h-0 w-full">
@ -659,11 +687,11 @@ export function ChatScreen() {
isLastAssistant={message.id === lastAssistantId} isLastAssistant={message.id === lastAssistantId}
isLastUser={message.id === lastUserId} isLastUser={message.id === lastUserId}
busy={busy} busy={busy}
onRegenerate={regenerate} onRegenerate={retryLast}
onEdit={editLast} onEdit={editLast}
onRetry={message.id === lastFailedAssistant ? retryLast : undefined} onRetry={message.id === lastFailedAssistant ? retryLast : undefined}
onToFlashcards={() => toFlashcards(message)} onToFlashcards={toFlashcards}
onSaveNotes={noteTargetDeck ? () => saveToNotes(message) : undefined} onSaveNotes={noteTargetDeck ? saveToNotes : undefined}
/> />
</motion.div> </motion.div>
))} ))}
@ -718,12 +746,12 @@ export function ChatScreen() {
scopeLabel={scopeText} scopeLabel={scopeText}
modelLabel={ modelLabel={
activeModel activeModel
? provider !== "ollama" ? activeProvider !== "ollama"
? `${providerInfo(provider)?.label ?? provider} · ${prettyModelName(activeModel)}` ? `${providerInfo(activeProvider)?.label ?? activeProvider} · ${prettyModelName(activeModel)}`
: prettyModelName(activeModel) : prettyModelName(activeModel)
: t("chat.modelTitle") : t("chat.modelTitle")
} }
modelTitle={activeModel ? `${activeModel} · ${providerInfo(provider)?.label ?? provider}` : undefined} modelTitle={activeModel ? `${activeModel} · ${providerInfo(activeProvider)?.label ?? activeProvider}` : undefined}
scopeOpen={scopeOpen} scopeOpen={scopeOpen}
modelOpen={modelOpen} modelOpen={modelOpen}
// The chips toggle their own popover (and open one at a time), so a // The chips toggle their own popover (and open one at a time), so a
@ -746,13 +774,14 @@ export function ChatScreen() {
onClose={() => setModelOpen(false)} onClose={() => setModelOpen(false)}
models={chatModels} models={chatModels}
value={activeModel} value={activeModel}
valueProvider={provider} valueProvider={activeProvider}
onChange={(next, nextProvider) => { onChange={(next, nextProvider) => {
setProvider(nextProvider ?? "ollama"); const chosenProvider = nextProvider ?? "ollama";
storeChatProvider(nextProvider ?? "ollama"); setProvider(chosenProvider);
storeChatProvider(chosenProvider);
setModel(next); setModel(next);
storeChatModel(next); storeChatModel(next);
if (messages.length > 0) persist(messages, { model: next }); if (messages.length > 0) persist(messages, { model: next, provider: chosenProvider });
}} }}
/> />
<ContextPicker <ContextPicker

View file

@ -1,6 +1,7 @@
"use client"; "use client";
import Link from "next/link"; import Link from "next/link";
import { memo } from "react";
import { CopyIconButton } from "./CopyIconButton"; import { CopyIconButton } from "./CopyIconButton";
import { Markdown } from "./Markdown"; import { Markdown } from "./Markdown";
@ -15,7 +16,7 @@ import type { ChatMessage } from "@/lib/chat";
* One turn: user bubbles on the right, assistant answers as full-width text * One turn: user bubbles on the right, assistant answers as full-width text
* (no bubble) with the Thinking row, sources, actions and error recovery. * (no bubble) with the Thinking row, sources, actions and error recovery.
*/ */
export function MessageRow({ export const MessageRow = memo(function MessageRow({
message, message,
streaming, streaming,
isLastAssistant, isLastAssistant,
@ -35,8 +36,8 @@ export function MessageRow({
onRegenerate?: () => void; onRegenerate?: () => void;
onEdit?: () => void; onEdit?: () => void;
onRetry?: () => void; onRetry?: () => void;
onToFlashcards?: () => void; onToFlashcards?: (message: ChatMessage) => void;
onSaveNotes?: () => void; onSaveNotes?: (message: ChatMessage) => void;
}) { }) {
const { t } = useI18n(); const { t } = useI18n();
@ -117,7 +118,7 @@ export function MessageRow({
{onToFlashcards ? ( {onToFlashcards ? (
<button <button
type="button" type="button"
onClick={onToFlashcards} onClick={() => onToFlashcards(message)}
className="flex items-center gap-1.5 rounded-xl border border-[var(--glass-border)] bg-[var(--surface-strong)] px-2.5 py-2 text-[12px] font-medium text-[var(--text-muted)] transition hover:bg-[var(--hover)] hover:text-[var(--text)]" className="flex items-center gap-1.5 rounded-xl border border-[var(--glass-border)] bg-[var(--surface-strong)] px-2.5 py-2 text-[12px] font-medium text-[var(--text-muted)] transition hover:bg-[var(--hover)] hover:text-[var(--text)]"
> >
<SparklesIcon className="size-3.5" /> <SparklesIcon className="size-3.5" />
@ -127,7 +128,7 @@ export function MessageRow({
{onSaveNotes ? ( {onSaveNotes ? (
<button <button
type="button" type="button"
onClick={onSaveNotes} onClick={() => onSaveNotes(message)}
className="flex items-center gap-1.5 rounded-xl border border-[var(--glass-border)] bg-[var(--surface-strong)] px-2.5 py-2 text-[12px] font-medium text-[var(--text-muted)] transition hover:bg-[var(--hover)] hover:text-[var(--text)]" className="flex items-center gap-1.5 rounded-xl border border-[var(--glass-border)] bg-[var(--surface-strong)] px-2.5 py-2 text-[12px] font-medium text-[var(--text-muted)] transition hover:bg-[var(--hover)] hover:text-[var(--text)]"
> >
<PlusIcon className="size-3.5" /> <PlusIcon className="size-3.5" />
@ -155,4 +156,4 @@ export function MessageRow({
) : null} ) : null}
</div> </div>
); );
} });

View file

@ -97,7 +97,7 @@ export function ModelPicker({
const selected = model.name === value && (model.provider ?? "ollama") === (valueProvider ?? "ollama"); const selected = model.name === value && (model.provider ?? "ollama") === (valueProvider ?? "ollama");
const unavailable = model.available === false; const unavailable = model.available === false;
return ( return (
<li key={model.name}> <li key={`${model.provider ?? "ollama"}:${model.name}`}>
<button <button
type="button" type="button"
disabled={unavailable} disabled={unavailable}

View file

@ -11,8 +11,8 @@ import { Button } from "@/components/ui";
import { WizardActionBar } from "@/components/WizardActionBar"; import { WizardActionBar } from "@/components/WizardActionBar";
import { import {
DOCUMENT_ACCEPT_ATTR, DOCUMENT_ACCEPT_ATTR,
describeExtraction,
documentsToText, documentsToText,
type ExtractedDocument,
} from "@/lib/documents"; } from "@/lib/documents";
import type { HomeworkMode, HomeworkRecord } from "@/lib/schemas"; import type { HomeworkMode, HomeworkRecord } from "@/lib/schemas";
import { ACCEPTED_TYPES, formatBytes, imageFilesFromDataTransfer } from "@/lib/image"; import { ACCEPTED_TYPES, formatBytes, imageFilesFromDataTransfer } from "@/lib/image";
@ -31,21 +31,6 @@ import { cn, truncate } from "@/lib/utils";
import { HomeworkHistory } from "./HomeworkHistory"; import { HomeworkHistory } from "./HomeworkHistory";
/** Same wording the create screen uses for an extracted document. */
function describeExtraction(
document: ExtractedDocument,
tr: (key: string, vars?: Record<string, string | number>) => string,
pl: (n: number, base: string, vars?: Record<string, string | number>) => string,
): string {
const parts = [
pl(document.words, "upload.words", { n: document.words.toLocaleString() }),
document.pages ? pl(document.pages, "upload.pages") : "",
document.images.length ? pl(document.images.length, "upload.pageImages") : "",
document.truncated ? tr("upload.truncated") : "",
];
return parts.filter(Boolean).join(" · ");
}
const MODES: Array<{ id: HomeworkMode; icon: React.ReactNode; titleKey: string; subtitleKey: string }> = [ const MODES: Array<{ id: HomeworkMode; icon: React.ReactNode; titleKey: string; subtitleKey: string }> = [
{ id: "make", icon: <SparklesIcon className="size-5" />, titleKey: "homework.mode.make.title", subtitleKey: "homework.mode.make.subtitle" }, { id: "make", icon: <SparklesIcon className="size-5" />, titleKey: "homework.mode.make.title", subtitleKey: "homework.mode.make.subtitle" },
{ id: "guide", icon: <PlayIcon className="size-5" />, titleKey: "homework.mode.guide.title", subtitleKey: "homework.mode.guide.subtitle" }, { id: "guide", icon: <PlayIcon className="size-5" />, titleKey: "homework.mode.guide.title", subtitleKey: "homework.mode.guide.subtitle" },
@ -95,6 +80,7 @@ export function HomeworkInput({
const [pasteOpen, setPasteOpen] = useState(false); const [pasteOpen, setPasteOpen] = useState(false);
/** Phones: the check card reveals the solution field instead of starting. */ /** Phones: the check card reveals the solution field instead of starting. */
const [checkOpen, setCheckOpen] = useState(false); const [checkOpen, setCheckOpen] = useState(false);
const [dragging, setDragging] = useState(false);
const isPhone = useIsPhone(); const isPhone = useIsPhone();
const reduceMotion = useReducedMotion(); const reduceMotion = useReducedMotion();
const online = useOnline(); const online = useOnline();
@ -130,10 +116,9 @@ export function HomeworkInput({
/* Persist the typed assignment while the user works (debounced). */ /* Persist the typed assignment while the user works (debounced). */
useEffect(() => { useEffect(() => {
if (!isPhone) return;
const timer = window.setTimeout(() => saveWizardDraft("homework", { text }), 400); const timer = window.setTimeout(() => saveWizardDraft("homework", { text }), 400);
return () => window.clearTimeout(timer); return () => window.clearTimeout(timer);
}, [text, isPhone]); }, [text]);
// Clipboard: screenshots become photos, long copied text becomes the assignment. // Clipboard: screenshots become photos, long copied text becomes the assignment.
useEffect(() => { useEffect(() => {
@ -744,7 +729,23 @@ export function HomeworkInput({
{errorCard} {errorCard}
{/* ------------------------------------------------ the assignment */} {/* ------------------------------------------------ the assignment */}
<section className="card p-4 sm:p-5"> <section
onDragOver={(event) => {
event.preventDefault();
setDragging(true);
}}
onDragLeave={() => setDragging(false)}
onDrop={(event) => {
event.preventDefault();
setDragging(false);
const dropped = Array.from(event.dataTransfer?.files ?? []);
void intake.addFiles(dropped.length > 0 ? dropped : imageFilesFromDataTransfer(event.dataTransfer));
}}
className={cn(
"card p-4 transition-all sm:p-5",
dragging && "border-frost-400 bg-frost-50 ring-4 ring-frost-200 dark:bg-frost-500/10 dark:ring-frost-500/30",
)}
>
<div className="flex flex-wrap items-center justify-between gap-3"> <div className="flex flex-wrap items-center justify-between gap-3">
<div> <div>
<h2 className="text-[15px] font-semibold tracking-[-0.01em] text-[var(--text)]"> <h2 className="text-[15px] font-semibold tracking-[-0.01em] text-[var(--text)]">

View file

@ -259,10 +259,12 @@ export function HomeworkScreen({ initialRecordId }: { initialRecordId?: string }
} }
if (view.kind === "record") { if (view.kind === "record") {
const recordKey = `${view.record.id}-${view.record.updatedAt}`;
return ( return (
<div className="space-y-5"> <div className="space-y-5">
{view.record.mode === "make" ? ( {view.record.mode === "make" ? (
<HomeworkResult <HomeworkResult
key={recordKey}
record={view.record} record={view.record}
onAgain={() => again(view.record)} onAgain={() => again(view.record)}
onNew={newAssignment} onNew={newAssignment}
@ -271,6 +273,7 @@ export function HomeworkScreen({ initialRecordId }: { initialRecordId?: string }
/> />
) : view.record.mode === "check" ? ( ) : view.record.mode === "check" ? (
<HomeworkCheckResult <HomeworkCheckResult
key={recordKey}
record={view.record} record={view.record}
onAgain={() => again(view.record)} onAgain={() => again(view.record)}
onNew={newAssignment} onNew={newAssignment}
@ -279,6 +282,7 @@ export function HomeworkScreen({ initialRecordId }: { initialRecordId?: string }
/> />
) : ( ) : (
<HomeworkGuide <HomeworkGuide
key={recordKey}
record={view.record} record={view.record}
onClose={() => setView({ kind: "start" })} onClose={() => setView({ kind: "start" })}
onAgain={() => again(view.record)} onAgain={() => again(view.record)}

View file

@ -11,7 +11,7 @@
import { z } from "zod"; import { z } from "zod";
import { applyTheme } from "./theme"; import { applyTheme, type Theme } from "./theme";
import { chatHistoryStore, ensureChatsHydrated, replaceChats } from "./chat-store"; import { chatHistoryStore, ensureChatsHydrated, replaceChats } from "./chat-store";
import { replaceFolders, folderStore } from "./folders"; import { replaceFolders, folderStore } from "./folders";
import { homeworkStore, replaceHomework } from "./homework"; import { homeworkStore, replaceHomework } from "./homework";
@ -26,7 +26,7 @@ export const BACKUP_VERSION = 1;
const settingsSchema = z.object({ const settingsSchema = z.object({
haptics: z.boolean().optional(), haptics: z.boolean().optional(),
locale: z.enum(["en", "cs"]).optional(), locale: z.enum(["en", "cs"]).optional(),
theme: z.enum(["light", "dark"]).optional(), theme: z.enum(["light", "dark", "aero"]).optional(),
dailyGoal: z.number().int().min(1).max(500).optional(), dailyGoal: z.number().int().min(1).max(500).optional(),
}); });
@ -74,7 +74,7 @@ export async function buildBackup(): Promise<BackupFile> {
haptics: settingsStore.getSnapshot().haptics, haptics: settingsStore.getSnapshot().haptics,
dailyGoal: settingsStore.getSnapshot().dailyGoal, dailyGoal: settingsStore.getSnapshot().dailyGoal,
locale: (window.localStorage.getItem("freezmo.locale.v1") as "en" | "cs" | null) ?? undefined, locale: (window.localStorage.getItem("freezmo.locale.v1") as "en" | "cs" | null) ?? undefined,
theme: (window.localStorage.getItem("freezmo.theme") as "light" | "dark" | null) ?? undefined, theme: (window.localStorage.getItem("freezmo.theme") as Theme | null) ?? undefined,
}, },
}, },
}; };
@ -174,15 +174,18 @@ export async function applyImport(
replaceDecks(decks); replaceDecks(decks);
replaceHomework(homework); replaceHomework(homework);
// Answer log + schedule: merge by id (answers) and by key (schedules). // Answer log + schedule: merge by id (answers) and by key (schedules), or
// replace wholesale when mode === "replace".
await ensureLearningHydrated(); await ensureLearningHydrated();
const incomingAnswers = data.history ?? []; const incomingAnswers = data.history ?? [];
const incomingSrs = data.srs ?? []; const incomingSrs = data.srs ?? [];
if (incomingAnswers.length > 0 || incomingSrs.length > 0) { if (mode === "replace") {
const srsByKey = new Map(incomingSrs.map((entry) => [entry.key, entry]));
await replaceLearning(incomingAnswers, [...srsByKey.values()]);
} else if (incomingAnswers.length > 0 || incomingSrs.length > 0) {
const currentAnswers = learningStore.getAnswersSnapshot(); const currentAnswers = learningStore.getAnswersSnapshot();
const currentSrs = learningStore.getSrsSnapshot(); const currentSrs = learningStore.getSrsSnapshot();
const answers = const answers = mergeById(currentAnswers, incomingAnswers);
mode === "replace" ? incomingAnswers : mergeById(currentAnswers, incomingAnswers);
const srsByKey = new Map(currentSrs.map((entry) => [entry.key, entry])); const srsByKey = new Map(currentSrs.map((entry) => [entry.key, entry]));
for (const entry of incomingSrs) { for (const entry of incomingSrs) {
const current = srsByKey.get(entry.key); const current = srsByKey.get(entry.key);
@ -194,8 +197,10 @@ export async function applyImport(
// Chat conversations: merge by id (newest wins) or replace wholesale. // Chat conversations: merge by id (newest wins) or replace wholesale.
await ensureChatsHydrated(); await ensureChatsHydrated();
const incomingChats = data.chats ?? []; const incomingChats = data.chats ?? [];
if (incomingChats.length > 0) { if (mode === "replace") {
replaceChats(mode === "replace" ? incomingChats : mergeById(chatHistoryStore.getSnapshot(), incomingChats)); replaceChats(incomingChats);
} else if (incomingChats.length > 0) {
replaceChats(mergeById(chatHistoryStore.getSnapshot(), incomingChats));
} }
const settings = data.settings; const settings = data.settings;

View file

@ -56,10 +56,10 @@ function openDb(): Promise<IDBDatabase> {
}); });
} }
async function withDb<T>(mode: IDBTransactionMode, run: (db: IDBDatabase) => T): Promise<T> { async function withDb<T>(_mode: IDBTransactionMode, run: (db: IDBDatabase) => T | Promise<T>): Promise<T> {
const db = await openDb(); const db = await openDb();
try { try {
return run(db); return await run(db);
} finally { } finally {
window.setTimeout(() => db.close(), 1000); window.setTimeout(() => db.close(), 1000);
} }

View file

@ -7,6 +7,7 @@
*/ */
import type { ChatAttachment, ChatMessage, ChatScope, ChatSource } from "./schemas"; import type { ChatAttachment, ChatMessage, ChatScope, ChatSource } from "./schemas";
import { uid } from "./utils";
export type { ChatAttachment, ChatMessage, ChatScope, ChatSource }; export type { ChatAttachment, ChatMessage, ChatScope, ChatSource };
@ -59,11 +60,7 @@ export function storeChatProvider(provider: string): void {
} }
export function chatMessageId(prefix: string): string { export function chatMessageId(prefix: string): string {
const rand = return uid(prefix);
typeof crypto !== "undefined" && "randomUUID" in crypto
? crypto.randomUUID().slice(0, 8)
: Math.random().toString(36).slice(2, 10);
return `${prefix}_${Date.now().toString(36)}_${rand}`;
} }
/** Auto title from the first user turn (markdown stripped, one line). */ /** Auto title from the first user turn (markdown stripped, one line). */

View file

@ -1,9 +1,11 @@
"use client"; "use client";
/** Confetti helper that respects prefers-reduced-motion. */ /** Confetti helper that respects prefers-reduced-motion and the in-app toggle. */
export function prefersReducedMotion(): boolean { export function prefersReducedMotion(): boolean {
if (typeof window === "undefined" || !window.matchMedia) return false; if (typeof window === "undefined") return false;
if (document.documentElement.classList.contains("reduce-motion")) return true;
if (!window.matchMedia) return false;
return window.matchMedia("(prefers-reduced-motion: reduce)").matches; return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
} }
@ -35,22 +37,3 @@ export async function celebrate(intensity: "normal" | "big" = "normal"): Promise
/* confetti is a nice-to-have */ /* confetti is a nice-to-have */
} }
} }
export function burstAt(x: number, y: number): void {
if (prefersReducedMotion()) return;
void (async () => {
try {
const confetti = (await import("canvas-confetti")).default;
confetti({
particleCount: 40,
spread: 55,
startVelocity: 26,
origin: { x: x / window.innerWidth, y: y / window.innerHeight },
colors: ["#7ea6c2", "#aac6da", "#cfd8e3", "#ffffff"],
disableForReducedMotion: true,
});
} catch {
/* ignore */
}
})();
}

View file

@ -217,58 +217,65 @@ async function extractPdf(
const images: PreparedImage[] = []; const images: PreparedImage[] = [];
const warnings: string[] = []; const warnings: string[] = [];
let imagesTruncated = false; let imagesTruncated = false;
const numPages = document.numPages;
const totalPages = Math.min(document.numPages, 80); try {
if (document.numPages > totalPages) { const totalPages = Math.min(numPages, 80);
warnings.push(`Only the first ${totalPages} of ${document.numPages} pages were read.`); if (numPages > totalPages) {
} warnings.push(`Only the first ${totalPages} of ${numPages} pages were read.`);
for (let pageNumber = 1; pageNumber <= totalPages; pageNumber++) {
onProgress?.({
message: t("doc.readingPage", { n: pageNumber, total: totalPages }),
progress: pageNumber / totalPages,
});
const page = (await document.getPage(pageNumber)) as unknown as PdfPage;
let pageText = "";
try {
const content = await page.getTextContent();
pageText = textFromPdfItems(content.items);
} catch {
warnings.push(`Page ${pageNumber} text could not be extracted.`);
} }
if (pageText.trim().length >= SCANNED_PAGE_CHAR_THRESHOLD) { for (let pageNumber = 1; pageNumber <= totalPages; pageNumber++) {
pages.push(`--- page ${pageNumber} ---\n${pageText.trim()}`); onProgress?.({
} else if (images.length < MAX_DOCUMENT_IMAGES) { message: t("doc.readingPage", { n: pageNumber, total: totalPages }),
// Scanned or image-only page: render it so the vision model can read it. progress: pageNumber / totalPages,
});
const page = (await document.getPage(pageNumber)) as unknown as PdfPage;
let pageText = "";
try { try {
const viewport = page.getViewport({ scale: PDF_RENDER_SCALE }); const content = await page.getTextContent();
const canvas = window.document.createElement("canvas"); pageText = textFromPdfItems(content.items);
canvas.width = Math.floor(viewport.width);
canvas.height = Math.floor(viewport.height);
const context = canvas.getContext("2d");
if (!context) throw new Error("no 2d context");
context.fillStyle = "#ffffff";
context.fillRect(0, 0, canvas.width, canvas.height);
await page.render({ canvasContext: context, viewport }).promise;
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.9));
if (blob) {
images.push(await prepareImageFromBlob(blob, `${file.name} p${pageNumber}`));
}
} catch { } catch {
warnings.push(`Page ${pageNumber} looks scanned but could not be rendered.`); warnings.push(`Page ${pageNumber} text could not be extracted.`);
} }
} else {
imagesTruncated = true;
}
if (pageText.trim().length < SCANNED_PAGE_CHAR_THRESHOLD) { if (pageText.trim().length >= SCANNED_PAGE_CHAR_THRESHOLD) {
// Nothing to add to the text; the image carries the content. pages.push(`--- page ${pageNumber} ---\n${pageText.trim()}`);
imagesTruncated = images.length >= MAX_DOCUMENT_IMAGES; } else if (images.length < MAX_DOCUMENT_IMAGES) {
} // Scanned or image-only page: render it so the vision model can read it.
try {
const viewport = page.getViewport({ scale: PDF_RENDER_SCALE });
const canvas = window.document.createElement("canvas");
canvas.width = Math.floor(viewport.width);
canvas.height = Math.floor(viewport.height);
const context = canvas.getContext("2d");
if (!context) throw new Error("no 2d context");
context.fillStyle = "#ffffff";
context.fillRect(0, 0, canvas.width, canvas.height);
await page.render({ canvasContext: context, viewport }).promise;
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.9));
canvas.width = 0;
canvas.height = 0;
if (blob) {
images.push(await prepareImageFromBlob(blob, `${file.name} p${pageNumber}`));
}
} catch {
warnings.push(`Page ${pageNumber} looks scanned but could not be rendered.`);
}
} else {
imagesTruncated = true;
}
page.cleanup?.(); if (pageText.trim().length < SCANNED_PAGE_CHAR_THRESHOLD) {
// Nothing to add to the text; the image carries the content.
imagesTruncated = images.length >= MAX_DOCUMENT_IMAGES;
}
page.cleanup?.();
}
} finally {
await (document as { destroy?: () => Promise<void> }).destroy?.().catch(() => {});
} }
if (images.length > 0) { if (images.length > 0) {
@ -280,7 +287,7 @@ async function extractPdf(
} }
return withLimits(file.name, "pdf", pages.join("\n\n"), images, { return withLimits(file.name, "pdf", pages.join("\n\n"), images, {
pages: document.numPages, pages: numPages,
warnings, warnings,
imagesTruncated, imagesTruncated,
}); });
@ -342,14 +349,18 @@ async function extractDocx(file: File): Promise<ExtractedDocument> {
const XML_TEXT_RUN = /<a:t[^>]*>([\s\S]*?)<\/a:t>/g; const XML_TEXT_RUN = /<a:t[^>]*>([\s\S]*?)<\/a:t>/g;
const XML_PARAGRAPH = /<\/a:p>/g; const XML_PARAGRAPH = /<\/a:p>/g;
function safeCodePoint(cp: number): string {
return Number.isFinite(cp) && cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : "";
}
function decodeXmlEntities(value: string): string { function decodeXmlEntities(value: string): string {
return value return value
.replace(/&lt;/g, "<") .replace(/&lt;/g, "<")
.replace(/&gt;/g, ">") .replace(/&gt;/g, ">")
.replace(/&quot;/g, '"') .replace(/&quot;/g, '"')
.replace(/&apos;/g, "'") .replace(/&apos;/g, "'")
.replace(/&#(\d+);/g, (_, code: string) => String.fromCodePoint(Number(code))) .replace(/&#(\d+);/g, (_, code: string) => safeCodePoint(Number(code)))
.replace(/&#x([0-9a-f]+);/gi, (_, code: string) => String.fromCodePoint(Number.parseInt(code, 16))) .replace(/&#x([0-9a-f]+);/gi, (_, code: string) => safeCodePoint(Number.parseInt(code, 16)))
.replace(/&amp;/g, "&"); .replace(/&amp;/g, "&");
} }
@ -475,3 +486,18 @@ export function documentsToText(documents: ExtractedDocument[]): string {
.join("\n\n") .join("\n\n")
.slice(0, MAX_DOCUMENT_CHARS * 2); .slice(0, MAX_DOCUMENT_CHARS * 2);
} }
/** Human-readable summary line for an extracted document (words · pages · images). */
export function describeExtraction(
document: ExtractedDocument,
tr: (key: string, vars?: Record<string, string | number>) => string,
pl: (n: number, base: string, vars?: Record<string, string | number>) => string,
): string {
const parts = [
pl(document.words, "upload.words", { n: document.words.toLocaleString() }),
document.pages ? pl(document.pages, "upload.pages") : "",
document.images.length ? pl(document.images.length, "upload.pageImages") : "",
document.truncated ? tr("upload.truncated") : "",
];
return parts.filter(Boolean).join(" · ");
}

View file

@ -71,21 +71,22 @@ export function replaceFolders(next: Folder[]): void {
write(valid); write(valid);
} }
function onStorage(event: StorageEvent): void {
if (event.key === STORAGE_KEY) {
folders = null;
ensureLoaded();
listeners.forEach((l) => l());
}
}
export const folderStore = { export const folderStore = {
subscribe(listener: Listener): () => void { subscribe(listener: Listener): () => void {
ensureLoaded(); ensureLoaded();
if (listeners.size === 0) window.addEventListener("storage", onStorage);
listeners.add(listener); listeners.add(listener);
const onStorage = (event: StorageEvent) => {
if (event.key === STORAGE_KEY) {
folders = null;
ensureLoaded();
listeners.forEach((l) => l());
}
};
window.addEventListener("storage", onStorage);
return () => { return () => {
listeners.delete(listener); listeners.delete(listener);
window.removeEventListener("storage", onStorage); if (listeners.size === 0) window.removeEventListener("storage", onStorage);
}; };
}, },
getSnapshot(): Folder[] { getSnapshot(): Folder[] {
@ -155,13 +156,3 @@ export function removeFolder(id: string): void {
ensureLoaded(); ensureLoaded();
write(folderStore.getSnapshot().filter((folder) => folder.id !== id)); write(folderStore.getSnapshot().filter((folder) => folder.id !== id));
} }
/** Deleting a folder must never delete decks: callers pair this with unfileDecks(). */
export function hasFolder(id: string): boolean {
return Boolean(getFolder(id));
}
export function emptyFolder(): void {
ensureLoaded();
write([]);
}

View file

@ -64,10 +64,10 @@ function openDb(): Promise<IDBDatabase> {
}); });
} }
async function withDb<T>(mode: IDBTransactionMode, run: (db: IDBDatabase) => T): Promise<T> { async function withDb<T>(_mode: IDBTransactionMode, run: (db: IDBDatabase) => T | Promise<T>): Promise<T> {
const db = await openDb(); const db = await openDb();
try { try {
return run(db); return await run(db);
} finally { } finally {
// Transactions keep the connection alive until they settle; close on the // Transactions keep the connection alive until they settle; close on the
// next task so pending requests finish first. // next task so pending requests finish first.

View file

@ -80,21 +80,22 @@ export function replaceHomework(next: HomeworkRecord[]): void {
write(valid); write(valid);
} }
function onStorage(event: StorageEvent): void {
if (event.key === STORAGE_KEY) {
records = null;
ensureLoaded();
listeners.forEach((l) => l());
}
}
export const homeworkStore = { export const homeworkStore = {
subscribe(listener: Listener): () => void { subscribe(listener: Listener): () => void {
ensureLoaded(); ensureLoaded();
if (listeners.size === 0) window.addEventListener("storage", onStorage);
listeners.add(listener); listeners.add(listener);
const onStorage = (event: StorageEvent) => {
if (event.key === STORAGE_KEY) {
records = null;
ensureLoaded();
listeners.forEach((l) => l());
}
};
window.addEventListener("storage", onStorage);
return () => { return () => {
listeners.delete(listener); listeners.delete(listener);
window.removeEventListener("storage", onStorage); if (listeners.size === 0) window.removeEventListener("storage", onStorage);
}; };
}, },
getSnapshot(): HomeworkRecord[] { getSnapshot(): HomeworkRecord[] {

View file

@ -45,19 +45,20 @@ function emit(): void {
listeners.forEach((listener) => listener()); listeners.forEach((listener) => listener());
} }
function onStorage(event: StorageEvent): void {
if (event.key === STORAGE_KEY) {
cached = read();
emit();
}
}
export const localeStore = { export const localeStore = {
subscribe(listener: () => void): () => void { subscribe(listener: () => void): () => void {
if (listeners.size === 0) window.addEventListener("storage", onStorage);
listeners.add(listener); listeners.add(listener);
const onStorage = (event: StorageEvent) => {
if (event.key === STORAGE_KEY) {
cached = read();
emit();
}
};
window.addEventListener("storage", onStorage);
return () => { return () => {
listeners.delete(listener); listeners.delete(listener);
window.removeEventListener("storage", onStorage); if (listeners.size === 0) window.removeEventListener("storage", onStorage);
}; };
}, },
getSnapshot(): Locale { getSnapshot(): Locale {

View file

@ -45,7 +45,10 @@ async function loadBitmap(blob: Blob, fallbackName: string): Promise<{ width: nu
return { return {
width: bitmap.width, width: bitmap.width,
height: bitmap.height, height: bitmap.height,
draw: (ctx, w, h) => ctx.drawImage(bitmap, 0, 0, w, h), draw: (ctx, w, h) => {
ctx.drawImage(bitmap, 0, 0, w, h);
bitmap.close();
},
}; };
} catch { } catch {
/* fall through to the <img> path (Safari/HEIC edge cases) */ /* fall through to the <img> path (Safari/HEIC edge cases) */
@ -91,6 +94,8 @@ export async function prepareImageFromBlob(blob: Blob, name = "image.jpg"): Prom
bitmap.draw(ctx, width, height); bitmap.draw(ctx, width, height);
const dataUrl = canvas.toDataURL("image/jpeg", JPEG_QUALITY); const dataUrl = canvas.toDataURL("image/jpeg", JPEG_QUALITY);
canvas.width = 0;
canvas.height = 0;
return { return {
id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`, id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,

View file

@ -94,6 +94,16 @@ export function dayKey(at: number): string {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
} }
/** Fast count of answers recorded today (avoids building the full stats buckets). */
export function todayAnswerCount(answers: AnswerRecord[], now = Date.now()): number {
const today = dayKey(now);
let count = 0;
for (const answer of answers) {
if (dayKey(answer.at) === today) count += 1;
}
return count;
}
export function computeStats(answers: AnswerRecord[], now = Date.now()): LearningStats { export function computeStats(answers: AnswerRecord[], now = Date.now()): LearningStats {
const total = answers.length; const total = answers.length;
const correct = answers.filter((entry) => entry.correct).length; const correct = answers.filter((entry) => entry.correct).length;

View file

@ -36,14 +36,6 @@ export const fade: Transition = { duration: 0.18, ease: "easeOut" };
/** Plain ease for fades and progress bars. */ /** Plain ease for fades and progress bars. */
export const EASE_OUT = [0.22, 1, 0.36, 1] as const; export const EASE_OUT = [0.22, 1, 0.36, 1] as const;
/** Durations (seconds) used across the pass. */
export const DURATION = {
press: 0.1,
small: 0.2,
screen: 0.3,
sheet: 0.34,
} as const;
/** A screen entering from the right (drill-in) or left (back). */ /** A screen entering from the right (drill-in) or left (back). */
export function screenVariants(direction: 1 | -1, reduceMotion: boolean): Variants { export function screenVariants(direction: 1 | -1, reduceMotion: boolean): Variants {
if (reduceMotion) { if (reduceMotion) {
@ -83,17 +75,6 @@ export function stepVariants(direction: 1 | -1, reduceMotion: boolean): Variants
}; };
} }
/** Capped stagger for a list's first paint. */
export const listContainer: Variants = {
hidden: {},
show: { transition: { staggerChildren: 0.045, delayChildren: 0.02 } },
};
export const listItem: Variants = {
hidden: { opacity: 0, y: 12 },
show: { opacity: 1, y: 0, transition: springGentle },
};
/** /**
* Counts a number up over ~600ms with an ease-out curve (score, XP). Pass * Counts a number up over ~600ms with an ease-out curve (score, XP). Pass
* `disabled` (desktop, reduced motion) to jump straight to the value. * `disabled` (desktop, reduced motion) to jump straight to the value.

View file

@ -120,7 +120,10 @@ async function fetchWithTimeout(
const controller = new AbortController(); const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs); const timer = setTimeout(() => controller.abort(), timeoutMs);
const onAbort = () => controller.abort(); const onAbort = () => controller.abort();
external?.addEventListener("abort", onAbort); if (external) {
if (external.aborted) controller.abort();
else external.addEventListener("abort", onAbort, { once: true });
}
try { try {
return await fetch(url, { ...init, signal: controller.signal }); return await fetch(url, { ...init, signal: controller.signal });
@ -273,89 +276,104 @@ export async function ollamaChatStream(options: StreamOptions): Promise<ChatStre
} }
if (config.think !== null) body.think = config.think; if (config.think !== null) body.think = config.think;
let response: Response; const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? config.timeoutMs);
const onAbort = () => controller.abort();
if (options.signal) {
if (options.signal.aborted) controller.abort();
else options.signal.addEventListener("abort", onAbort, { once: true });
}
try { try {
response = await fetchWithTimeout( let response: Response;
`${baseUrl}/api/chat`,
{ method: "POST", headers, body: JSON.stringify(body), cache: "no-store" },
options.timeoutMs ?? config.timeoutMs,
options.signal,
);
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
throw new OllamaError("timeout", "The request to Ollama timed out.");
}
throw new OllamaError("unreachable", `Could not connect to Ollama at ${baseUrl}.`, {
detail: error instanceof Error ? error.message : String(error),
});
}
if (!response.ok) {
const text = await response.text().catch(() => "");
throwForStatus(response.status, text, model);
}
if (!response.body) {
throw new OllamaError("bad_response", "Ollama sent an empty stream.");
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let content = "";
let thinking = "";
const handleLine = (line: string) => {
const trimmed = line.trim();
if (!trimmed) return;
let event: unknown;
try { try {
event = JSON.parse(trimmed); response = await fetch(`${baseUrl}/api/chat`, {
} catch { method: "POST",
return; // a half-written line must never break the stream headers,
} body: JSON.stringify(body),
if (!event || typeof event !== "object") return; cache: "no-store",
const record = event as Record<string, unknown>; signal: controller.signal,
if (typeof record.error === "string" && record.error) { });
throw new OllamaError("http", record.error.slice(0, 300)); } catch (error) {
} if (error instanceof Error && error.name === "AbortError") {
const message = record.message as Record<string, unknown> | undefined; throw new OllamaError("timeout", "The request to Ollama timed out.");
const delta = typeof message?.content === "string" ? message.content : "";
const reason = typeof message?.thinking === "string" ? message.thinking : "";
if (reason) {
thinking += reason;
options.onThinking?.(reason);
}
if (delta) {
content += delta;
options.onToken?.(delta);
}
};
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let newline = buffer.indexOf("\n");
while (newline !== -1) {
handleLine(buffer.slice(0, newline));
buffer = buffer.slice(newline + 1);
newline = buffer.indexOf("\n");
} }
throw new OllamaError("unreachable", `Could not connect to Ollama at ${baseUrl}.`, {
detail: error instanceof Error ? error.message : String(error),
});
} }
handleLine(buffer);
} catch (error) { if (!response.ok) {
if (error instanceof Error && error.name === "AbortError") { const text = await response.text().catch(() => "");
throw new OllamaError("timeout", "The request to Ollama timed out."); throwForStatus(response.status, text, model);
}
if (!response.body) {
throw new OllamaError("bad_response", "Ollama sent an empty stream.");
} }
throw error;
}
if (!content.trim()) { const reader = response.body.getReader();
throw new OllamaError("bad_response", "Ollama finished the stream without any answer text."); const decoder = new TextDecoder();
} let buffer = "";
let content = "";
let thinking = "";
return { content, thinking, model }; const handleLine = (line: string) => {
const trimmed = line.trim();
if (!trimmed) return;
let event: unknown;
try {
event = JSON.parse(trimmed);
} catch {
return; // a half-written line must never break the stream
}
if (!event || typeof event !== "object") return;
const record = event as Record<string, unknown>;
if (typeof record.error === "string" && record.error) {
throw new OllamaError("http", record.error.slice(0, 300));
}
const message = record.message as Record<string, unknown> | undefined;
const delta = typeof message?.content === "string" ? message.content : "";
const reason = typeof message?.thinking === "string" ? message.thinking : "";
if (reason) {
thinking += reason;
options.onThinking?.(reason);
}
if (delta) {
content += delta;
options.onToken?.(delta);
}
};
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let newline = buffer.indexOf("\n");
while (newline !== -1) {
handleLine(buffer.slice(0, newline));
buffer = buffer.slice(newline + 1);
newline = buffer.indexOf("\n");
}
}
handleLine(buffer);
} catch (error) {
void reader.cancel().catch(() => {});
if (error instanceof Error && error.name === "AbortError") {
throw new OllamaError("timeout", "The request to Ollama timed out.");
}
throw error;
}
if (!content.trim()) {
throw new OllamaError("bad_response", "Ollama finished the stream without any answer text.");
}
return { content, thinking, model };
} finally {
clearTimeout(timer);
options.signal?.removeEventListener("abort", onAbort);
}
} }
function extractContent(payload: unknown): string | null { function extractContent(payload: unknown): string | null {
@ -493,6 +511,16 @@ export async function ollamaVerifyKey(auth: OllamaAuth, model: string, timeoutMs
: { valid: null, reason: "throttled", detail }; : { valid: null, reason: "throttled", detail };
} else probe = { valid: null, detail: `HTTP ${response.status}` }; } else probe = { valid: null, detail: `HTTP ${response.status}` };
if (probeCache.size >= 500) {
const now = Date.now();
for (const [k, entry] of probeCache) {
if (now - entry.at >= PROBE_TTL_MS) probeCache.delete(k);
}
if (probeCache.size >= 500) {
const oldest = probeCache.keys().next().value;
if (oldest) probeCache.delete(oldest);
}
}
probeCache.set(cacheKey, { ...probe, at: Date.now() }); probeCache.set(cacheKey, { ...probe, at: Date.now() });
return probe; return probe;
} }

View file

@ -125,7 +125,8 @@ function contentFor(user: string, images?: string[]): string | ChatPart[] {
if (!images || images.length === 0) return user; if (!images || images.length === 0) return user;
const parts: ChatPart[] = [{ type: "text", text: user }]; const parts: ChatPart[] = [{ type: "text", text: user }];
for (const image of images.slice(0, 8)) { for (const image of images.slice(0, 8)) {
parts.push({ type: "image_url", image_url: { url: image } }); const url = image.startsWith("data:") || /^https?:\/\//i.test(image) ? image : `data:image/jpeg;base64,${image}`;
parts.push({ type: "image_url", image_url: { url } });
} }
return parts; return parts;
} }
@ -188,72 +189,103 @@ export async function providerChatStream(input: {
})), })),
stream: true, stream: true,
}; };
const response = await runFetch( const controller = new AbortController();
`${trimBase(input.target.baseUrl)}/chat/completions`, const timer = setTimeout(() => controller.abort(), 300_000);
{ method: "POST", headers: requestHeaders(input.target), body: JSON.stringify(body), signal: input.signal, cache: "no-store" }, const onAbort = () => controller.abort();
input.model, if (input.signal) {
input.target, if (input.signal.aborted) controller.abort();
300_000, else input.signal.addEventListener("abort", onAbort, { once: true });
);
if (!response.ok) {
const text = await response.text().catch(() => "");
throw failure(response.status, text, input.model, input.target);
}
if (!response.body) {
throw new ProviderError("http", `${input.target.label} sent an empty stream.`, input.target.label);
} }
const reader = response.body.getReader(); try {
const decoder = new TextDecoder(); let response: Response;
let buffer = "";
let model = input.model;
let sawDone = false;
const handleLine = (line: string) => {
const trimmed = line.trim();
if (!trimmed.startsWith("data:")) return;
const data = trimmed.slice(5).trim();
if (!data || data === "[DONE]") {
if (data === "[DONE]") sawDone = true;
return;
}
let event: {
model?: string;
choices?: Array<{ delta?: { content?: unknown; reasoning?: unknown; reasoning_content?: unknown } }>;
error?: { message?: string };
};
try { try {
event = JSON.parse(data); response = await fetch(`${trimBase(input.target.baseUrl)}/chat/completions`, {
} catch { method: "POST",
return; headers: requestHeaders(input.target),
body: JSON.stringify(body),
signal: controller.signal,
cache: "no-store",
});
} catch (error) {
if (input.signal?.aborted) throw error;
if (error instanceof Error && error.name === "AbortError") {
throw new ProviderError("timeout", `${input.target.label} took too long to answer.`, input.target.label);
}
throw new ProviderError("unreachable", `Could not reach ${input.target.label}. Check your connection.`, input.target.label);
}
if (!response.ok) {
const text = await response.text().catch(() => "");
throw failure(response.status, text, input.model, input.target);
}
if (!response.body) {
throw new ProviderError("http", `${input.target.label} sent an empty stream.`, input.target.label);
} }
if (event.error?.message) throw new ProviderError("http", `${input.target.label}: ${event.error.message}`, input.target.label);
if (event.model) model = event.model;
const delta = event.choices?.[0]?.delta;
if (!delta) return;
const thinking = delta.reasoning_content ?? delta.reasoning;
if (typeof thinking === "string" && thinking) input.onThinking?.(thinking);
if (typeof delta.content === "string" && delta.content) input.onToken?.(delta.content);
};
while (true) { const reader = response.body.getReader();
const { done, value } = await reader.read(); const decoder = new TextDecoder();
if (done) break; let buffer = "";
buffer += decoder.decode(value, { stream: true }); let model = input.model;
let newline = buffer.indexOf("\n"); let sawDone = false;
while (newline !== -1) {
handleLine(buffer.slice(0, newline)); const handleLine = (line: string) => {
buffer = buffer.slice(newline + 1); const trimmed = line.trim();
newline = buffer.indexOf("\n"); if (!trimmed.startsWith("data:")) return;
const data = trimmed.slice(5).trim();
if (!data || data === "[DONE]") {
if (data === "[DONE]") sawDone = true;
return;
}
let event: {
model?: string;
choices?: Array<{ delta?: { content?: unknown; reasoning?: unknown; reasoning_content?: unknown } }>;
error?: { message?: string };
};
try {
event = JSON.parse(data);
} catch {
return;
}
if (event.error?.message) throw new ProviderError("http", `${input.target.label}: ${event.error.message}`, input.target.label);
if (event.model) model = event.model;
const delta = event.choices?.[0]?.delta;
if (!delta) return;
const thinking = delta.reasoning_content ?? delta.reasoning;
if (typeof thinking === "string" && thinking) input.onThinking?.(thinking);
if (typeof delta.content === "string" && delta.content) input.onToken?.(delta.content);
};
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let newline = buffer.indexOf("\n");
while (newline !== -1) {
handleLine(buffer.slice(0, newline));
buffer = buffer.slice(newline + 1);
newline = buffer.indexOf("\n");
}
}
handleLine(buffer);
} catch (error) {
void reader.cancel().catch(() => {});
if (input.signal?.aborted) throw error;
if (error instanceof Error && error.name === "AbortError") {
throw new ProviderError("timeout", `${input.target.label} took too long to answer.`, input.target.label);
}
throw error;
} }
if (!sawDone) {
// Some gateways close the stream without [DONE]; tokens already arrived,
// so this is only worth a debug note.
console.warn(`[freezmo] ${input.target.label} stream ended without [DONE]`);
}
return { model };
} finally {
clearTimeout(timer);
input.signal?.removeEventListener("abort", onAbort);
} }
handleLine(buffer);
if (!sawDone) {
// Some gateways close the stream without [DONE]; tokens already arrived,
// so this is only worth a debug note.
console.warn(`[freezmo] ${input.target.label} stream ended without [DONE]`);
}
return { model };
} }

View file

@ -117,11 +117,13 @@ export function saveProviderKey(id: string, key: string) {
} }
export function clearProviderKey(id: string) { export function clearProviderKey(id: string) {
const keys = { ...providersStore.getSnapshot().keys }; const current = providersStore.getSnapshot();
const keys = { ...current.keys };
delete keys[id]; delete keys[id];
const models = { ...providersStore.getSnapshot().models }; const models = { ...current.models };
delete models[id]; delete models[id];
update({ keys, models }); const generation = current.generation?.provider === id ? null : current.generation;
update({ keys, models, generation });
} }
export function setProviderModels(id: string, models: string[]) { export function setProviderModels(id: string, models: string[]) {

View file

@ -72,21 +72,22 @@ function write(next: QuestionReport[]): void {
listeners.forEach((listener) => listener()); listeners.forEach((listener) => listener());
} }
function onStorage(event: StorageEvent): void {
if (event.key === STORAGE_KEY) {
reports = null;
ensureLoaded();
listeners.forEach((l) => l());
}
}
export const reportStore = { export const reportStore = {
subscribe(listener: Listener): () => void { subscribe(listener: Listener): () => void {
ensureLoaded(); ensureLoaded();
if (listeners.size === 0) window.addEventListener("storage", onStorage);
listeners.add(listener); listeners.add(listener);
const onStorage = (event: StorageEvent) => {
if (event.key === STORAGE_KEY) {
reports = null;
ensureLoaded();
listeners.forEach((l) => l());
}
};
window.addEventListener("storage", onStorage);
return () => { return () => {
listeners.delete(listener); listeners.delete(listener);
window.removeEventListener("storage", onStorage); if (listeners.size === 0) window.removeEventListener("storage", onStorage);
}; };
}, },
getSnapshot(): QuestionReport[] { getSnapshot(): QuestionReport[] {

View file

@ -105,16 +105,6 @@ export const generatedActivitySchema = z.discriminatedUnion("type", [
]); ]);
export type GeneratedActivity = z.infer<typeof generatedActivitySchema>; export type GeneratedActivity = z.infer<typeof generatedActivitySchema>;
export const generatedDeckSchema = z.object({
title: z.string().min(1).max(120),
subject: z.string().max(80).optional(),
summary: z.string().max(400).optional(),
/** Language of the generated content, e.g. "Czech" or "cs". */
language: z.string().max(60).optional(),
activities: z.array(generatedActivitySchema).min(4).max(20),
});
export type GeneratedDeck = z.infer<typeof generatedDeckSchema>;
/** What the vision step must return. */ /** What the vision step must return. */
export const extractedNotesSchema = z.object({ export const extractedNotesSchema = z.object({
title: z.string().min(1).max(120), title: z.string().min(1).max(120),
@ -197,12 +187,11 @@ export const homeworkStepSchema = z.object({
checkpoint: generatedActivitySchema.optional(), checkpoint: generatedActivitySchema.optional(),
}); });
export const homeworkGuideSchema = z.object({ export type HomeworkGuide = {
title: z.string().min(1).max(200), title: string;
language: z.string().max(60).optional(), language?: string;
steps: z.array(homeworkStepSchema).min(2).max(10), steps: z.infer<typeof homeworkStepSchema>[];
}); };
export type HomeworkGuide = z.infer<typeof homeworkGuideSchema>;
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/* Client-side homework types (checkpoints carry id/xp, plus storage) */ /* Client-side homework types (checkpoints carry id/xp, plus storage) */
@ -397,6 +386,7 @@ export const chatConversationSchema = z.object({
messages: z.array(chatMessageSchema).max(300), messages: z.array(chatMessageSchema).max(300),
scope: chatScopeSchema, scope: chatScopeSchema,
model: z.string().max(120).optional(), model: z.string().max(120).optional(),
provider: z.string().max(60).optional(),
createdAt: z.number(), createdAt: z.number(),
updatedAt: z.number(), updatedAt: z.number(),
}); });

View file

@ -1,5 +1,6 @@
"use client"; "use client";
import { copyText } from "./clipboard";
import { exportDeck } from "./storage"; import { exportDeck } from "./storage";
import { showToast } from "./toast"; import { showToast } from "./toast";
import type { Deck, HomeworkRecord } from "./schemas"; import type { Deck, HomeworkRecord } from "./schemas";
@ -21,18 +22,6 @@ function deckFile(deck: Deck): File {
}); });
} }
async function copyText(text: string): Promise<boolean> {
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
return true;
}
} catch {
/* fall through */
}
return false;
}
export async function shareDeck(deck: Deck): Promise<void> { export async function shareDeck(deck: Deck): Promise<void> {
const nav = navigator as ShareNavigator; const nav = navigator as ShareNavigator;
const file = deckFile(deck); const file = deckFile(deck);

View file

@ -70,22 +70,22 @@ export function replaceDecks(next: Deck[]): void {
write(valid); write(valid);
} }
function onStorage(event: StorageEvent): void {
if (event.key === STORAGE_KEY) {
decks = null;
ensureLoaded();
listeners.forEach((l) => l());
}
}
export const deckStore = { export const deckStore = {
subscribe(listener: Listener): () => void { subscribe(listener: Listener): () => void {
ensureLoaded(); ensureLoaded();
if (listeners.size === 0) window.addEventListener("storage", onStorage);
listeners.add(listener); listeners.add(listener);
// Another tab may have changed the library.
const onStorage = (event: StorageEvent) => {
if (event.key === STORAGE_KEY) {
decks = null;
ensureLoaded();
listeners.forEach((l) => l());
}
};
window.addEventListener("storage", onStorage);
return () => { return () => {
listeners.delete(listener); listeners.delete(listener);
window.removeEventListener("storage", onStorage); if (listeners.size === 0) window.removeEventListener("storage", onStorage);
}; };
}, },
getSnapshot(): Deck[] { getSnapshot(): Deck[] {

View file

@ -78,21 +78,22 @@ function write(next: SyncRecord): void {
listeners.forEach((listener) => listener()); listeners.forEach((listener) => listener());
} }
function onStorage(event: StorageEvent): void {
if (event.key === STORAGE_KEY) {
record = null;
ensureLoaded();
listeners.forEach((l) => l());
}
}
export const syncStore = { export const syncStore = {
subscribe(listener: Listener): () => void { subscribe(listener: Listener): () => void {
ensureLoaded(); ensureLoaded();
if (listeners.size === 0) window.addEventListener("storage", onStorage);
listeners.add(listener); listeners.add(listener);
const onStorage = (event: StorageEvent) => {
if (event.key === STORAGE_KEY) {
record = null;
ensureLoaded();
listeners.forEach((l) => l());
}
};
window.addEventListener("storage", onStorage);
return () => { return () => {
listeners.delete(listener); listeners.delete(listener);
window.removeEventListener("storage", onStorage); if (listeners.size === 0) window.removeEventListener("storage", onStorage);
}; };
}, },
getSnapshot(): SyncRecord { getSnapshot(): SyncRecord {

View file

@ -55,15 +55,20 @@ export function useHealth() {
const run = useCallback(async (force: boolean) => { const run = useCallback(async (force: boolean) => {
setLoading(true); setLoading(true);
setError(null); setError(null);
const key = settingsStore.getSnapshot().apiKey;
try { try {
const key = settingsStore.getSnapshot().apiKey; const result = await loadHealth(key, force);
setHealth(await loadHealth(key, force)); if (settingsStore.getSnapshot().apiKey !== key) return;
setHealth(result);
} catch (loadError) { } catch (loadError) {
if (settingsStore.getSnapshot().apiKey !== key) return;
setError(loadError instanceof Error ? loadError.message : t("api.unreachableShort")); setError(loadError instanceof Error ? loadError.message : t("api.unreachableShort"));
} finally { } finally {
// Even a failed check is a check: the panel can say when it last ran. if (settingsStore.getSnapshot().apiKey === key) {
setCheckedAt(Date.now()); // Even a failed check is a check: the panel can say when it last ran.
setLoading(false); setCheckedAt(Date.now());
setLoading(false);
}
} }
}, []); }, []);

View file

@ -27,9 +27,14 @@ export function useWakeLock(active = true): void {
const acquire = async () => { const acquire = async () => {
try { try {
sentinel = await wakeLock.request("screen"); const acquired = await wakeLock.request("screen");
sentinel.addEventListener("release", () => { if (disposed) {
sentinel = null; void acquired.release().catch(() => {});
return;
}
sentinel = acquired;
acquired.addEventListener("release", () => {
if (sentinel === acquired) sentinel = null;
}); });
} catch { } catch {
/* denied or not allowed without a gesture — fine */ /* denied or not allowed without a gesture — fine */

View file

@ -37,7 +37,9 @@ export function stripFences(text: string): string {
let value = text.trim(); let value = text.trim();
const fence = value.match(/```(?:json)?\s*([\s\S]*?)```/i); const fence = value.match(/```(?:json)?\s*([\s\S]*?)```/i);
if (fence) value = fence[1].trim(); if (fence) value = fence[1].trim();
if (value.startsWith("{") || value.startsWith("[")) return value; if ((value.startsWith("{") && value.endsWith("}")) || (value.startsWith("[") && value.endsWith("]"))) {
return value;
}
const start = value.indexOf("{"); const start = value.indexOf("{");
const end = value.lastIndexOf("}"); const end = value.lastIndexOf("}");
if (start !== -1 && end > start) return value.slice(start, end + 1); if (start !== -1 && end > start) return value.slice(start, end + 1);

View file

@ -27,7 +27,7 @@ function keyFor(scope: "deck" | "homework"): string {
export function saveWizardDraft(scope: "deck" | "homework", draft: Omit<WizardDraft, "v" | "savedAt">): void { export function saveWizardDraft(scope: "deck" | "homework", draft: Omit<WizardDraft, "v" | "savedAt">): void {
try { try {
const images = (draft.images ?? []).filter(() => true); const images = draft.images ?? [];
const size = images.reduce((sum, image) => sum + image.dataUrl.length, 0); const size = images.reduce((sum, image) => sum + image.dataUrl.length, 0);
const payload: WizardDraft = { const payload: WizardDraft = {
v: 1, v: 1,

View file

@ -1,6 +1,6 @@
{ {
"name": "freezmo", "name": "freezmo",
"version": "0.5.7", "version": "0.5.8",
"private": true, "private": true,
"license": "GPL-3.0-only", "license": "GPL-3.0-only",
"scripts": { "scripts": {

View file

@ -1 +0,0 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

Before

Width:  |  Height:  |  Size: 391 B

View file

@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

Before

Width:  |  Height:  |  Size: 1 KiB

View file

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

View file

@ -9,7 +9,7 @@
* *
* Bumping CACHE_VERSION is how a new deploy invalidates old assets. * Bumping CACHE_VERSION is how a new deploy invalidates old assets.
*/ */
const CACHE_VERSION = "freezmo-v79"; const CACHE_VERSION = "freezmo-v80";
const SHELL_CACHE = `${CACHE_VERSION}-shell`; const SHELL_CACHE = `${CACHE_VERSION}-shell`;
const ASSET_CACHE = `${CACHE_VERSION}-assets`; const ASSET_CACHE = `${CACHE_VERSION}-assets`;
@ -131,7 +131,7 @@ self.addEventListener("fetch", (event) => {
if (response.ok) cache.put(request, response.clone()).catch(() => {}); if (response.ok) cache.put(request, response.clone()).catch(() => {});
return response; return response;
}) })
.catch(() => cached); .catch(() => cached ?? Response.error());
return cached ?? network; return cached ?? network;
})(), })(),
); );

View file

@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

Before

Width:  |  Height:  |  Size: 128 B

View file

@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

Before

Width:  |  Height:  |  Size: 385 B

View file

@ -160,5 +160,54 @@ const browser = await launchBrowser();
await cs.context.close(); await cs.context.close();
} }
/* 7. typed fill-blank + checked homework card ------------------------ */
{
const typedDeck = {
...DECK,
id: "typed_fill_deck",
activities: [
{
id: "act_typed_fill",
type: "fill_blank",
topic: "Optics",
sentence: "Short wavelengths scatter ____ than long ones.",
answer: "more",
explanation: "Blue light scatters more strongly.",
xp: 15,
},
],
};
const { context, page } = await makePage(browser);
await seed(page, {
decks: [typedDeck],
extra: {
"freezmo.homework.v1": JSON.stringify([
{
id: "hw_check_1",
mode: "check",
title: "Linear equations check",
sourceText: "2x + 2 = 6",
verdict: "One sign error.",
correct: ["Good setup"],
wrong: [],
corrected: "x = 2",
createdAt: 1,
updatedAt: 2,
},
]),
},
});
await page.goto(`${BASE}/deck/typed_fill_deck`, { waitUntil: "networkidle" });
await page.waitForTimeout(700);
const input = page.getByLabel("Type the missing word");
await input.fill("more");
check("fill-blank: typed input displays the value", (await input.inputValue()) === "more");
await page.goto(`${BASE}/?tab=homework`, { waitUntil: "networkidle" });
await page.waitForTimeout(700);
check("homework card: check mode shows Checked badge", await page.getByText("Checked").first().isVisible());
await context.close();
}
await browser.close(); await browser.close();
finish(); finish();