Freezmo: self-hosted notes-to-activities study app

Next.js 15 app that turns photos, PDFs, DOCX/PPTX and text into a swipeable
feed of AI-generated activities (flashcards, multiple choice, true/false,
fill-in-the-blank, matching, ordering, short answer) using the user's own
Ollama models.

Highlights:
- All AI calls run in server route handlers; the browser never talks to Ollama.
- Bring-your-own-key mode (default): the key lives only in the browser and is
  sent per-request; server, local-daemon and shared-key modes also supported.
- Client-side document extraction (pdf.js, mammoth, jszip) with scanned-PDF
  page rendering for the vision model; notes stay in their original language.
- ChatGPT-style shell: collapsible sidebar / mobile drawer, neutral token-based
  light + dark themes, folder organisation, PWA (manifest, SW, offline page).
- Strict JSON validation with zod + auto-repair, rate limiting, and request
  guards (cross-origin, body-size, API-key sanitising).
- setup.sh bootstraps deps, .env.local and a production build.

Gitignore excludes .env*, the generated pdf.js worker and local scratch files.
This commit is contained in:
Martin Dvořák 2026-10-06 20:56:55 +00:00
commit 3ea2cea100
83 changed files with 10909 additions and 165 deletions

209
lib/client-api.ts Normal file
View file

@ -0,0 +1,209 @@
"use client";
import type { Activity, Difficulty } from "./schemas";
import { authHeaders } from "./settings";
export type GenerateInput = {
images?: string[];
text?: string;
difficulty: Difficulty;
count?: number;
focus?: string;
language?: string;
mode?: "create" | "more";
existing?: { title: string; types: string[]; count: number };
};
export type StreamedDeck = {
title: string;
subject?: string;
summary?: string;
language?: string;
sourceText: string;
difficulty: Difficulty;
activities: Activity[];
};
export type GenerateProgress = {
stage: "vision" | "generation" | "done";
message: string;
};
type StreamEvent =
| { type: "stage"; stage: "vision" | "generation" | "done"; message: string }
| { type: "deck"; deck: StreamedDeck; meta: Record<string, unknown> }
| { type: "error"; error: string; kind?: string };
export class ApiError extends Error {
kind: string;
constructor(message: string, kind = "unknown") {
super(message);
this.name = "ApiError";
this.kind = kind;
}
}
/**
* Calls POST /api/generate and consumes the NDJSON progress stream.
* Progress events arrive between the vision and generation steps.
*/
export async function generateDeck(
input: GenerateInput,
options: { onProgress?: (progress: GenerateProgress) => void; signal?: AbortSignal } = {},
): Promise<{ deck: StreamedDeck; meta: Record<string, unknown> }> {
let response: Response;
try {
response = await fetch("/api/generate", {
method: "POST",
headers: { "Content-Type": "application/json", ...authHeaders() },
body: JSON.stringify(input),
signal: options.signal,
});
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
throw new ApiError("Generation was cancelled.", "aborted");
}
throw new ApiError("Could not reach the Freezmo server. Is it still running?", "network");
}
if (!response.ok) {
const body = (await response.json().catch(() => null)) as { error?: string; kind?: string } | null;
throw new ApiError(body?.error ?? `The server returned HTTP ${response.status}.`, body?.kind);
}
if (!response.body) {
throw new ApiError("The server sent an empty response.", "bad_response");
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let deck: StreamedDeck | null = null;
let meta: Record<string, unknown> = {};
let streamError: ApiError | null = null;
let sawActivity = false;
const handleLine = (line: string) => {
if (!line.trim()) return;
let event: StreamEvent;
try {
event = JSON.parse(line) as StreamEvent;
} catch {
return;
}
if (event.type === "stage") {
options.onProgress?.({ stage: event.stage, message: event.message });
} else if (event.type === "deck") {
deck = event.deck;
meta = event.meta ?? {};
sawActivity = true;
options.onProgress?.({ stage: "done", message: "Almost there…" });
} else if (event.type === "error") {
streamError = new ApiError(event.error, event.kind);
}
};
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);
if (streamError) throw streamError;
if (!deck) {
throw new ApiError(
sawActivity
? "The server finished without sending a deck."
: "No deck came back from the server. Check your Ollama settings and try again.",
"bad_response",
);
}
const valid = (deck as StreamedDeck).activities?.filter(
(activity) => activity && typeof activity.type === "string" && typeof activity.id === "string",
);
if (!valid || valid.length === 0) {
throw new ApiError("The generated deck had no usable activities. Try again.", "bad_response");
}
return { deck: { ...(deck as StreamedDeck), activities: valid }, meta };
}
export async function gradeAnswer(input: {
question: string;
referenceAnswer: string;
keyPoints: string[];
userAnswer: string;
language?: string;
signal?: AbortSignal;
}): Promise<{ correct: boolean; score: number; feedback: string; missing: string[] }> {
let response: Response;
try {
response = await fetch("/api/grade", {
method: "POST",
headers: { "Content-Type": "application/json", ...authHeaders() },
body: JSON.stringify(input),
signal: input.signal,
});
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
throw new ApiError("Grading was cancelled.", "aborted");
}
throw new ApiError("Could not reach the Freezmo server.", "network");
}
const body = (await response.json().catch(() => null)) as
| { correct: boolean; score: number; feedback: string; missing?: string[]; error?: string; kind?: string }
| null;
if (!response.ok || !body || body.error) {
throw new ApiError(body?.error ?? `Grading failed with HTTP ${response.status}.`, body?.kind);
}
return {
correct: Boolean(body.correct),
score: Math.max(0, Math.min(100, Math.round(body.score))),
feedback: body.feedback,
missing: body.missing ?? [],
};
}
export type HealthModel = {
configured: string;
resolved: string;
available: boolean | null;
note?: string;
};
export type Health = {
ok: boolean;
reachable: boolean;
mode: "local-daemon" | "direct-cloud";
authMode: "user-key" | "server" | "local";
needsKey: boolean;
keyAccepted: boolean | null;
baseUrl: string;
hasApiKey: boolean;
vision: HealthModel;
text: HealthModel;
latencyMs: number | null;
modelCount: number | null;
error: string | null;
kind?: string;
checkedAt: string;
};
export async function fetchHealth(): Promise<Health> {
try {
const response = await fetch("/api/health", { cache: "no-store", headers: authHeaders() });
return (await response.json()) as Health;
} catch {
throw new ApiError("Could not reach the Freezmo server.", "network");
}
}