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.
118 lines
4.4 KiB
TypeScript
118 lines
4.4 KiB
TypeScript
import { z } from "zod";
|
|
|
|
import { refineHomeworkText } from "@/lib/ai";
|
|
import { getServerConfig, resolveModelName } from "@/lib/config";
|
|
import { INERT_OLLAMA_AUTH, resolveModelTarget } from "@/lib/providers-server";
|
|
import { friendlyErrorMessage, OllamaError } from "@/lib/ollama";
|
|
import { rejectCrossOrigin, rejectOversizedBody, requestLocale } from "@/lib/http-guard";
|
|
import { translate } from "@/lib/i18n-dict";
|
|
import { clientKey, rateLimit, rateLimitResponse } from "@/lib/rate-limit";
|
|
import { acquireModelGate } from "@/lib/model-guard";
|
|
|
|
export const runtime = "nodejs";
|
|
export const dynamic = "force-dynamic";
|
|
|
|
/**
|
|
* Homework follow-ups: rewrite one finished piece — shorter, more detail, or
|
|
* a step explained differently. One short model call, plain JSON back.
|
|
*/
|
|
|
|
const requestSchema = z.object({
|
|
|
|
model: z.string().min(1).max(200).optional(),
|
|
instruction: z.enum(["shorter", "more", "explain"]),
|
|
text: z.string().min(1).max(20_000),
|
|
/** The assignment, for context (optional). */
|
|
context: z.string().max(8_000).optional(),
|
|
language: z.string().max(60).optional(),
|
|
});
|
|
|
|
export async function POST(request: Request) {
|
|
const locale = requestLocale(request);
|
|
const crossOrigin = rejectCrossOrigin(request);
|
|
if (crossOrigin) return crossOrigin;
|
|
const oversized = rejectOversizedBody(request, 128 * 1024);
|
|
if (oversized) return oversized;
|
|
|
|
const config = getServerConfig();
|
|
const limit = rateLimit(`refine:${clientKey(request)}`, config.rateLimits.refine, config.rateLimits.windowMs);
|
|
if (!limit.allowed) return rateLimitResponse(limit, locale);
|
|
|
|
// Ollama (server-configured) or a cloud provider the browser sent a key for.
|
|
const resolved = resolveModelTarget(config, request, locale);
|
|
if ("error" in resolved) {
|
|
return Response.json({ error: resolved.error.message, kind: resolved.error.kind }, { status: resolved.error.status });
|
|
}
|
|
const target = resolved.target;
|
|
const provider = target.kind === "provider" ? target.target : undefined;
|
|
const baseAuth = target.kind === "provider" ? INERT_OLLAMA_AUTH : target.auth;
|
|
|
|
let payload: unknown;
|
|
try {
|
|
payload = await request.json();
|
|
} catch {
|
|
return Response.json({ error: translate(locale, "server.bodyNotJson") }, { status: 400 });
|
|
}
|
|
|
|
const parsed = requestSchema.safeParse(payload);
|
|
if (!parsed.success) {
|
|
return Response.json(
|
|
{
|
|
error: translate(locale, "server.invalidRequest", {
|
|
detail: parsed.error.issues
|
|
.slice(0, 3)
|
|
.map((issue) => `${issue.path.join(".") || "body"} ${issue.message}`)
|
|
.join("; "),
|
|
}),
|
|
},
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
|
|
// Provider runs carry the model the user picked in Settings → Providers.
|
|
const providerModel = provider ? parsed.data.model : undefined;
|
|
if (provider && !providerModel) {
|
|
return Response.json(
|
|
{ error: translate(locale, "server.providerModelNeeded"), kind: "bad_provider" },
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
const textModel = provider ? providerModel! : config.textModel;
|
|
|
|
const gate = acquireModelGate(request, config, locale);
|
|
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 {
|
|
const text = await refineHomeworkText({
|
|
model: textModel,
|
|
auth: baseAuth,
|
|
provider,
|
|
instruction: parsed.data.instruction,
|
|
text: parsed.data.text,
|
|
context: parsed.data.context,
|
|
signal: abort.signal,
|
|
});
|
|
return Response.json(
|
|
{ text, model: provider ? textModel : resolveModelName(config.textModel, baseAuth.directCloud) },
|
|
{ headers: { "Cache-Control": "no-store" } },
|
|
);
|
|
} catch (error) {
|
|
// Never log the text itself: it may contain the student's homework.
|
|
console.error("[api/homework/refine]", error instanceof OllamaError ? `${error.kind}: ${error.message}` : error);
|
|
return Response.json(
|
|
{
|
|
error: friendlyErrorMessage(error, baseAuth.baseUrl || provider?.baseUrl || '', locale),
|
|
kind: error instanceof OllamaError ? error.kind : "unknown",
|
|
},
|
|
{ status: 502 },
|
|
);
|
|
} finally {
|
|
clearTimeout(timer);
|
|
request.signal.removeEventListener("abort", onRequestAbort);
|
|
gate.gate.release();
|
|
}
|
|
}
|