freezmo/app/api/health/route.ts
Martin Dvorak 618ad5fb9c Add an English/Czech interface language switch
English stays the default; Czech is a full translation. Only the app chrome
is translated - notes and generated decks keep their own language, which is a
core feature, not a setting.

i18n
- lib/i18n-dict.ts: flat en/cs dictionaries (441 keys each), translate() and
  translatePlural() with real Czech plural rules (1 sada / 2-4 sady / 5+ sad).
  English is the default and the fallback for a missing key.
- lib/i18n.ts: browser store (freezmo.locale.v1), useI18n() hook, and the
  x-freezmo-locale header. The hook's t/plural are bound to the locale React
  is rendering with, so the first client render matches the server HTML and
  then re-renders in the stored language; module-level t is only for event
  handlers and non-React helpers.
- <html lang> follows the choice (inline script + setLocale).

UI
- Settings -> Language segmented control (English / Cestina), plus an EN/CS
  button on the key gate for first run.
- Every screen translated: sidebar, header, tab bar, library, deck cards,
  folder bar, create flow, all seven activities, study chrome, results,
  settings + health panel, API-key gate and help, install sheet, offline and
  the deck-not-found page.
- Plural-aware counts everywhere (decks, folders, activities, runs, photos,
  documents, pages, words, wrong attempts).

Server
- API routes and guards (generate, grade, health, http-guard, rate-limit,
  ollama error mapping) answer in the request's language, so error cards and
  the health panel never fall back to English mid-sentence.

Fixes
- A hydration mismatch when a non-default locale was stored silently dropped
  the .dark class after hydration; render-time t() is now bound to the
  hook's locale (UploadScreen.describeExtraction, ResultsScreen.answerFor,
  DeckCard's folder fallback).
- Bumped the service worker cache to freezmo-v4 for this deploy.

Tests: i18n 27/27 (gate toggle, persistence, html lang, Czech plurals,
settings switch) and a rebuilt regression suite 72/72 (English default,
library, create, all 7 activity types, results, settings, install sheet,
offline, PWA, security, Czech smoke).
2026-10-08 13:56:32 +00:00

134 lines
4.8 KiB
TypeScript

import { authErrorMessage, authErrorKind, canonicalModelName, getServerConfig, resolveAuth, resolveModelName, type AuthMode } from "@/lib/config";
import { friendlyErrorMessage, ollamaListModels, ollamaVerifyKey, OllamaError } from "@/lib/ollama";
import { clientKey, rateLimit, rateLimitResponse } from "@/lib/rate-limit";
import { requestLocale } from "@/lib/http-guard";
import { translate } from "@/lib/i18n-dict";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export type ModelHealth = {
configured: string;
resolved: string;
available: boolean | null;
note?: string;
};
export type HealthResponse = {
ok: boolean;
reachable: boolean;
mode: "local-daemon" | "direct-cloud";
authMode: AuthMode;
/** True when the browser has to provide its own key and hasn't. */
needsKey: boolean;
/** null = not checked (no key), true/false = Ollama accepted/rejected the key. */
keyAccepted: boolean | null;
baseUrl: string;
hasApiKey: boolean;
vision: ModelHealth;
text: ModelHealth;
latencyMs: number | null;
modelCount: number | null;
error: string | null;
kind?: string;
checkedAt: string;
};
export async function GET(request: Request) {
const locale = requestLocale(request);
const config = getServerConfig();
const limit = rateLimit(`health:${clientKey(request)}`, config.rateLimits.health, config.rateLimits.windowMs);
if (!limit.allowed) return rateLimitResponse(limit, locale);
const started = Date.now();
const resolvedAuth = resolveAuth(config, request);
const health: HealthResponse = {
ok: false,
reachable: false,
mode: config.directCloud ? "direct-cloud" : "local-daemon",
authMode: config.authMode,
needsKey: "error" in resolvedAuth,
keyAccepted: null,
baseUrl: config.baseUrl,
hasApiKey: !("error" in resolvedAuth) && Boolean(resolvedAuth.auth.apiKey),
vision: {
configured: config.visionModel,
resolved: resolveModelName(config.visionModel, config.directCloud),
available: null,
},
text: {
configured: config.textModel,
resolved: resolveModelName(config.textModel, config.directCloud),
available: null,
},
latencyMs: null,
modelCount: null,
error: null,
checkedAt: new Date().toISOString(),
};
if ("error" in resolvedAuth) {
health.error =
resolvedAuth.error === "missing_key"
? translate(locale, "server.healthNoKey")
: authErrorMessage(locale, resolvedAuth.error);
health.kind = authErrorKind(resolvedAuth.error);
return Response.json(health satisfies HealthResponse, { headers: { "Cache-Control": "no-store" } });
}
try {
const models = await ollamaListModels(resolvedAuth.auth);
health.reachable = true;
health.latencyMs = Date.now() - started;
health.modelCount = models.length;
// A key is only "accepted" once Ollama authenticated a real request —
// model listings are public, so an actual (tiny, cached) chat proves it.
if (resolvedAuth.auth.apiKey) {
const probe = await ollamaVerifyKey(resolvedAuth.auth, config.textModel, config.healthTimeoutMs * 3);
health.keyAccepted = probe.valid;
if (probe.valid === false) {
health.error = translate(locale, "server.healthKeyRejected");
health.kind = "auth";
return Response.json(health satisfies HealthResponse, { headers: { "Cache-Control": "no-store" } });
}
if (probe.reason === "no_credits") {
health.error = translate(locale, "server.healthNoCredits", { model: config.textModel });
health.kind = "no_credits";
}
}
const names = new Set(models.map((model) => canonicalModelName(model.name)));
for (const key of ["vision", "text"] as const) {
const entry = health[key];
const wanted = canonicalModelName(entry.resolved);
const listed = names.has(wanted);
entry.available = listed;
if (!listed) {
entry.note =
health.mode === "local-daemon"
? translate(locale, "server.healthModelNoteLocal", { model: entry.resolved })
: translate(locale, "server.healthModelNoteCloud", { url: config.baseUrl });
}
}
health.ok = Boolean(health.vision.available && health.text.available && health.keyAccepted !== false);
if (!health.ok && !health.error) {
health.error = translate(locale, "server.healthModelsMissing");
}
} catch (error) {
health.error = friendlyErrorMessage(error, config.baseUrl, locale);
health.kind = error instanceof OllamaError ? error.kind : "unknown";
if (error instanceof OllamaError && (error.kind === "auth" || error.kind === "http")) {
health.keyAccepted = false;
}
health.latencyMs = null;
}
return Response.json(health satisfies HealthResponse, {
status: 200,
headers: { "Cache-Control": "no-store" },
});
}