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:
parent
303e73f555
commit
982391ca45
57 changed files with 714 additions and 497 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue