Steps - iOS now uses the exact flow: Safari users get 4 steps (⋯ → Share/More → Add to Home Screen → Add); non-Safari (CriOS/FxiOS/EdgiOS/in-app) get a first 'Open this page in Safari' step and 5 total. The vague 'in some browsers it's under…' wording is gone. Chips and icons - The ⋯ chip renders a single three-dot icon (icon-only pill) instead of the icon plus an '⋯' character (which showed two sets of dots). - The More chip uses a chevron-down icon instead of the rounded-square. - The accent pill uses real iOS blue: #0A84FF dark / #007AFF light, still the only coloured element. - Steps and chips share one 16px type scale; chip labels are medium weight. Typography and layout - Numbers are small muted circles in a fixed 24px column, aligned with the first text line via matching line-height. - Removed trailing periods after chips; steps tightened. - Bottom padding is calc(24px + env(safe-area-inset-bottom)) and a secondary 'Maybe later' button sits below the steps. - max-height 90dvh with inner scrolling; 36×4px low-contrast handle with real swipe-down-to-close (momentum off, spring back). - App card shows the hostname only (no port), truncated. Themes - Dark (default): layered surfaces #1c1c1e sheet / #2c2c2e card / #3a3a3c chips with 8% white borders; subtle logo tile instead of solid white; backdrop is 50% black with 4px blur. - Light only when the app theme was explicitly set to light, ignoring the system preference; borders #e0e0e0, chip fills #f2f2f2. Also fixes a crash the test pressure exposed: a 429 (rate-limited) /api/health response crashed Settings at health.vision.available. fetchHealth now rejects non-OK/malformed responses so the dialog shows its error banner instead of the app error screen. Install-sheet suite now 64 checks; pwa/final-ux/security/contrast green.
278 lines
8.3 KiB
TypeScript
278 lines
8.3 KiB
TypeScript
"use client";
|
|
|
|
import type { Activity, Difficulty } from "./schemas";
|
|
import { API_KEY_HEADER, 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> {
|
|
let response: Response;
|
|
try {
|
|
response = await fetch("/api/health", { cache: "no-store", headers: authHeaders() });
|
|
} catch {
|
|
throw new ApiError("Could not reach the Freezmo server.", "network");
|
|
}
|
|
const body = (await response.json().catch(() => null)) as (Partial<Health> & { error?: string; kind?: string }) | null;
|
|
if (!response.ok) {
|
|
throw new ApiError(
|
|
body?.error ?? `The health check failed with HTTP ${response.status}.`,
|
|
body?.kind ?? "http",
|
|
);
|
|
}
|
|
// Guard against anything that isn't a health payload (e.g. a proxy error
|
|
// page) so consumers can rely on the shape.
|
|
if (!body || typeof body !== "object" || !body.vision || !body.text) {
|
|
throw new ApiError("The Freezmo server sent an unexpected health response.", "bad_response");
|
|
}
|
|
return body as Health;
|
|
}
|
|
|
|
export type KeyCheck =
|
|
| { result: "valid" }
|
|
| { result: "invalid"; message: string }
|
|
| { result: "offline"; message: string };
|
|
|
|
/**
|
|
* Checks a *draft* key before it is saved anywhere, by asking our own
|
|
* `/api/health` route (which performs a real one-token chat probe against
|
|
* Ollama — model listings alone prove nothing). The key travels in the
|
|
* request header for this single call and is never stored server-side.
|
|
*/
|
|
export async function verifyOllamaKey(apiKey: string): Promise<KeyCheck> {
|
|
let response: Response;
|
|
try {
|
|
response = await fetch("/api/health", {
|
|
cache: "no-store",
|
|
headers: { [API_KEY_HEADER]: apiKey },
|
|
});
|
|
} catch {
|
|
return {
|
|
result: "offline",
|
|
message: "Could not reach the Freezmo server. Is it still running?",
|
|
};
|
|
}
|
|
|
|
const body = (await response.json().catch(() => null)) as Health | null;
|
|
if (!response.ok || !body) {
|
|
return {
|
|
result: "offline",
|
|
message: "The Freezmo server answered unexpectedly. Try again in a moment.",
|
|
};
|
|
}
|
|
|
|
if (body.keyAccepted === false) {
|
|
return {
|
|
result: "invalid",
|
|
message:
|
|
body.error ??
|
|
"Ollama rejected this key. Check for typos, or create a new one at ollama.com/settings/keys.",
|
|
};
|
|
}
|
|
if (body.keyAccepted === true) return { result: "valid" };
|
|
|
|
if (!body.reachable) {
|
|
return {
|
|
result: "offline",
|
|
message:
|
|
body.error ?? "Couldn't reach Ollama just now. Check your connection and try again.",
|
|
};
|
|
}
|
|
|
|
// Reachable, but the probe was inconclusive (usually a model-availability
|
|
// matter rather than a bad key). Let the user in — Settings shows details.
|
|
return { result: "valid" };
|
|
}
|