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

@ -120,7 +120,10 @@ async function fetchWithTimeout(
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
const onAbort = () => controller.abort();
external?.addEventListener("abort", onAbort);
if (external) {
if (external.aborted) controller.abort();
else external.addEventListener("abort", onAbort, { once: true });
}
try {
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;
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 {
response = await fetchWithTimeout(
`${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;
let response: Response;
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");
response = await fetch(`${baseUrl}/api/chat`, {
method: "POST",
headers,
body: JSON.stringify(body),
cache: "no-store",
signal: controller.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),
});
}
handleLine(buffer);
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
throw new OllamaError("timeout", "The request to Ollama timed out.");
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.");
}
throw error;
}
if (!content.trim()) {
throw new OllamaError("bad_response", "Ollama finished the stream without any answer text.");
}
const reader = response.body.getReader();
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 {
@ -493,6 +511,16 @@ export async function ollamaVerifyKey(auth: OllamaAuth, model: string, timeoutMs
: { valid: null, reason: "throttled", detail };
} 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() });
return probe;
}