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
|
|
@ -125,7 +125,8 @@ function contentFor(user: string, images?: string[]): string | ChatPart[] {
|
|||
if (!images || images.length === 0) return user;
|
||||
const parts: ChatPart[] = [{ type: "text", text: user }];
|
||||
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;
|
||||
}
|
||||
|
|
@ -188,72 +189,103 @@ export async function providerChatStream(input: {
|
|||
})),
|
||||
stream: true,
|
||||
};
|
||||
const response = await runFetch(
|
||||
`${trimBase(input.target.baseUrl)}/chat/completions`,
|
||||
{ method: "POST", headers: requestHeaders(input.target), body: JSON.stringify(body), signal: input.signal, cache: "no-store" },
|
||||
input.model,
|
||||
input.target,
|
||||
300_000,
|
||||
);
|
||||
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 controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), 300_000);
|
||||
const onAbort = () => controller.abort();
|
||||
if (input.signal) {
|
||||
if (input.signal.aborted) controller.abort();
|
||||
else input.signal.addEventListener("abort", onAbort, { once: true });
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
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 {
|
||||
let response: Response;
|
||||
try {
|
||||
event = JSON.parse(data);
|
||||
} catch {
|
||||
return;
|
||||
response = await fetch(`${trimBase(input.target.baseUrl)}/chat/completions`, {
|
||||
method: "POST",
|
||||
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 { 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");
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
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 {
|
||||
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 };
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue