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

@ -119,11 +119,7 @@ export function DataSection() {
<span className="min-w-0">
<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)]">
{persistence === "persistent"
? t("settings.storagePersistent")
: persistence === "unsupported"
? t("settings.storageBestEffort")
: t("settings.storageBestEffort")}
{persistence === "persistent" ? t("settings.storagePersistent") : t("settings.storageBestEffort")}
</span>
</span>
{persistence === "best-effort" ? (

View file

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

View file

@ -4,8 +4,9 @@ import { motion } from "framer-motion";
import Link from "next/link";
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 { homeworkModeLabelKey } from "@/lib/homework";
import { useI18n } from "@/lib/i18n";
import { springGentle } from "@/lib/motion";
import type { HomeworkRecord } from "@/lib/schemas";
@ -70,8 +71,14 @@ export function HomeworkCard({
</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)]">
<span className="inline-flex items-center gap-1">
{record.mode === "make" ? <BoltIcon className="size-3.5" /> : <PlayIcon className="size-3.5" />}
{t(record.mode === "make" ? "homework.history.made" : "homework.history.guide")}
{record.mode === "make" ? (
<BoltIcon className="size-3.5" />
) : record.mode === "check" ? (
<CheckCircleIcon className="size-3.5" />
) : (
<PlayIcon className="size-3.5" />
)}
{t(homeworkModeLabelKey(record.mode))}
</span>
<span aria-hidden>·</span>
{formatDate(record.updatedAt)}

View file

@ -16,7 +16,8 @@ import { createFolder, folderStore, renameFolder } from "@/lib/folders";
import { deleteHomework, homeworkStore, sortHomework } from "@/lib/homework";
import { learningStore } from "@/lib/history";
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 { ALL_FOLDERS, folderSelection, useSelectedFolder } from "@/lib/nav";
import { springGentle, springSheet } from "@/lib/motion";
@ -110,17 +111,30 @@ export function LibraryScreen({ initialTab = "decks" }: { initialTab?: "decks" |
() => settingsStore.getSnapshot().dailyGoal,
() => 20,
);
/* Smart-review counts resolve against the live deck list: deleting a deck
must drop its due schedules and its mistakes right away. `dueCount` is not
used directly because it counts raw schedules, including decks that no
longer exist. */
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 reports = useSyncExternalStore(
reportStore.subscribe,
reportStore.getSnapshot,
reportStore.getServerSnapshot,
);
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 sorted = useMemo(() => sortDecks(decks), [decks]);
@ -512,6 +526,7 @@ export function LibraryScreen({ initialTab = "decks" }: { initialTab?: "decks" |
<DeckCard
key={deck.id}
deck={deck}
folders={folderList}
index={index}
onMove={(folderId) => {
upsertDeck({ ...deck, folderId });

View file

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

View file

@ -138,7 +138,7 @@ export function SessionFeed({
);
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. */
const attemptedTotal = Math.max(0, total - skipped.length);
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 { clearApiKey, saveSettings, settingsStore } from "@/lib/settings";
import { useBackClose } from "@/lib/use-back-close";
import { useIsPhone } from "@/lib/use-phone";
import { cn } from "@/lib/utils";
import { openInstallSheet, useInstallAvailable } from "@/lib/install";
import { useHealth } from "@/lib/use-health";
@ -84,21 +85,13 @@ export function SettingsDialog({
const [saved, setSaved] = useState(false);
const [confirmRemove, setConfirmRemove] = 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 reduceMotion = useReducedMotion();
const scrollRef = 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(() => {
if (!open) return;
setKeyDraft(apiKey);

View file

@ -113,19 +113,25 @@ export function StudyFeed({ deck }: { deck: Deck }) {
if (!retryMode && !recordedRef.current) {
recordedRef.current = true;
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 score = attempted > 0 ? (correct / attempted) * 100 : 0;
// 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
// 0% attempt before the feed had snapped back to the first slide.
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");
void celebrate("big");
}
}
}, [finished, results, total, skipped.length, currentDeck.id, retryMode]);
}, [finished, queue, results, total, skipped, currentDeck.id, retryMode]);
const handleAnswered = useCallback(
(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 correctCount = useMemo(
() => queue.filter((activity) => results[activity.id]?.correct).length,
[queue, results],
() => queue.filter((activity) => !skipped.includes(activity.id) && results[activity.id]?.correct).length,
[queue, results, skipped],
);
const restart = useCallback(

View file

@ -11,6 +11,7 @@ import {
DOCUMENT_ACCEPT_ATTR,
KIND_LABELS,
describeDocumentError,
describeExtraction,
documentKindOf,
documentsToText,
extractDocument,
@ -71,20 +72,6 @@ const MAX_IMAGES_TO_SEND = 12;
/** Cap for the merged text sent to the API. */
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 }> = [
{ value: "easy", labelKey: "upload.easy", icon: <SunIcon className="size-5" />, blurbKey: "upload.easyBlurb" },
{
@ -1106,7 +1093,8 @@ export function UploadScreen() {
onDrop={(event) => {
event.preventDefault();
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(
"card relative overflow-hidden p-4 transition-all sm:p-5",

View file

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

View file

@ -20,7 +20,13 @@ type OrderingActivity = Extract<Activity, { type: "ordering" }>;
export function Ordering({ activity, onAnswered, onNext, isLast, nextLabel }: ActivityComponentProps<OrderingActivity>) {
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 [checked, setChecked] = useState(false);
const [correct, setCorrect] = useState(false);

View file

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

View file

@ -1,6 +1,7 @@
"use client";
import Link from "next/link";
import { memo } from "react";
import { CopyIconButton } from "./CopyIconButton";
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
* (no bubble) with the Thinking row, sources, actions and error recovery.
*/
export function MessageRow({
export const MessageRow = memo(function MessageRow({
message,
streaming,
isLastAssistant,
@ -35,8 +36,8 @@ export function MessageRow({
onRegenerate?: () => void;
onEdit?: () => void;
onRetry?: () => void;
onToFlashcards?: () => void;
onSaveNotes?: () => void;
onToFlashcards?: (message: ChatMessage) => void;
onSaveNotes?: (message: ChatMessage) => void;
}) {
const { t } = useI18n();
@ -117,7 +118,7 @@ export function MessageRow({
{onToFlashcards ? (
<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)]"
>
<SparklesIcon className="size-3.5" />
@ -127,7 +128,7 @@ export function MessageRow({
{onSaveNotes ? (
<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)]"
>
<PlusIcon className="size-3.5" />
@ -155,4 +156,4 @@ export function MessageRow({
) : null}
</div>
);
}
});

View file

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

View file

@ -11,8 +11,8 @@ import { Button } from "@/components/ui";
import { WizardActionBar } from "@/components/WizardActionBar";
import {
DOCUMENT_ACCEPT_ATTR,
describeExtraction,
documentsToText,
type ExtractedDocument,
} from "@/lib/documents";
import type { HomeworkMode, HomeworkRecord } from "@/lib/schemas";
import { ACCEPTED_TYPES, formatBytes, imageFilesFromDataTransfer } from "@/lib/image";
@ -31,21 +31,6 @@ import { cn, truncate } from "@/lib/utils";
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 }> = [
{ 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" },
@ -95,6 +80,7 @@ export function HomeworkInput({
const [pasteOpen, setPasteOpen] = useState(false);
/** Phones: the check card reveals the solution field instead of starting. */
const [checkOpen, setCheckOpen] = useState(false);
const [dragging, setDragging] = useState(false);
const isPhone = useIsPhone();
const reduceMotion = useReducedMotion();
const online = useOnline();
@ -130,10 +116,9 @@ export function HomeworkInput({
/* Persist the typed assignment while the user works (debounced). */
useEffect(() => {
if (!isPhone) return;
const timer = window.setTimeout(() => saveWizardDraft("homework", { text }), 400);
return () => window.clearTimeout(timer);
}, [text, isPhone]);
}, [text]);
// Clipboard: screenshots become photos, long copied text becomes the assignment.
useEffect(() => {
@ -744,7 +729,23 @@ export function HomeworkInput({
{errorCard}
{/* ------------------------------------------------ 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>
<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") {
const recordKey = `${view.record.id}-${view.record.updatedAt}`;
return (
<div className="space-y-5">
{view.record.mode === "make" ? (
<HomeworkResult
key={recordKey}
record={view.record}
onAgain={() => again(view.record)}
onNew={newAssignment}
@ -271,6 +273,7 @@ export function HomeworkScreen({ initialRecordId }: { initialRecordId?: string }
/>
) : view.record.mode === "check" ? (
<HomeworkCheckResult
key={recordKey}
record={view.record}
onAgain={() => again(view.record)}
onNew={newAssignment}
@ -279,6 +282,7 @@ export function HomeworkScreen({ initialRecordId }: { initialRecordId?: string }
/>
) : (
<HomeworkGuide
key={recordKey}
record={view.record}
onClose={() => setView({ kind: "start" })}
onAgain={() => again(view.record)}