Phase 2: learning engine — history, SRS review, mistakes, stats, exam, reminders

Answer history and schedules
- Every answer is recorded (deck, activity, topic, correct/wrong, time)
  in a versioned IndexedDB log (freezmo-learning v1, stores answers +
  srs), mirrored in memory for synchronous React reads and capped at
  20k answers (oldest pruned). StudyFeed records as it grades.
- Light SM-2 schedule per activity: 1 day, 3 days, then interval x
  ease; wrong answers return in ten minutes with the ease nudged down.

Review, mistakes, stats
- Library 'Smart review' card: due count, mistakes count (latest
  answer wrong — clears itself when answered correctly), today's goal
  progress. Review sessions freeze their item list at start.
- New /review (due across decks, ?mistakes=1 global or ?deck= per
  deck) built on a shared SessionFeed with the study feed's snap/keyboard
  mechanics, wake lock and a results slide.
- New /stats: day streak, five-week calendar, accuracy per subject and
  per deck, weakest topics (>=3 answers), daily-goal progress.
- Daily goal configurable in Settings (10/20/30/50).

Exam mode
- New /exam: pick decks, question count, optional timer; no hints
  (a NoHints context hides hint rows and the self-check escape);
  results with score, per-deck and per-topic breakdown; wrong answers
  land in the mistakes set through the normal history.

Reminders (conditional)
- VAPID-gated: GET/POST/DELETE /api/push and POST /api/push/test with
  the standard route pattern, RATE_LIMIT_PUSH, zod, auth before body.
  Subscriptions stored server-side as endpoint + keys only (PUSH_DIR).
  UI hidden entirely without keys; iOS install note; service worker
  push/notificationclick handlers; scripts/send-reminders.mjs for a
  cron/systemd timer; web-push added as the one server dependency.

Verified: new phase-2 suite 42/42 (history/SRS shapes from a real study
run, mistakes clearing, review session, stats math, exam timer and
breakdowns, VAPID-less hidden state plus the configured
subscribe/validate/test/delete path against a second instance) plus
regression 74/74, mobile 52/52, wizard 80/80, declutter 116/116,
animation 8/8, native 35/35, phase1 38/38, i18n 25/25. Key parity
709/709. Lint + build clean. SW freezmo-v26.
This commit is contained in:
Martin Dvořák 2026-10-10 14:15:21 +00:00
commit e4a8e0ba01
33 changed files with 2504 additions and 47 deletions

131
app/api/push/route.ts Normal file
View file

@ -0,0 +1,131 @@
import { z } from "zod";
import { authErrorKind, authErrorMessage, getServerConfig, resolveAuth } from "@/lib/config";
import { rejectCrossOrigin, rejectOversizedBody, requestLocale } from "@/lib/http-guard";
import { translate } from "@/lib/i18n-dict";
import { addSubscription, removeSubscription } from "@/lib/push-store";
import { clientKey, rateLimit, rateLimitResponse } from "@/lib/rate-limit";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
/**
* Push reminder subscriptions. GET reports whether reminders are available
* (VAPID configured) and hands out the public key; POST/DELETE manage this
* browser's subscription. The feature is hidden client-side when `enabled`
* is false — no half-configured UI ever shows.
*/
const subscriptionSchema = z.object({
endpoint: z.string().url().max(2000),
keys: z.object({
p256dh: z.string().min(16).max(400),
auth: z.string().min(8).max(200),
}),
});
export async function GET(request: Request) {
const locale = requestLocale(request);
const crossOrigin = rejectCrossOrigin(request);
if (crossOrigin) return crossOrigin;
const config = getServerConfig();
const limit = rateLimit(`push:${clientKey(request)}`, config.rateLimits.push, config.rateLimits.windowMs);
if (!limit.allowed) return rateLimitResponse(limit, locale);
const auth = resolveAuth(config, request);
if ("error" in auth) {
return Response.json(
{ error: authErrorMessage(locale, auth.error), kind: authErrorKind(auth.error) },
{ status: 401 },
);
}
const enabled = Boolean(config.push.publicKey && config.push.privateKey);
return Response.json(
{ enabled, publicKey: enabled ? config.push.publicKey : undefined },
{ headers: { "Cache-Control": "no-store" } },
);
}
export async function POST(request: Request) {
const locale = requestLocale(request);
const crossOrigin = rejectCrossOrigin(request);
if (crossOrigin) return crossOrigin;
const config = getServerConfig();
const oversized = rejectOversizedBody(request, 64 * 1024);
if (oversized) return oversized;
const limit = rateLimit(`push:${clientKey(request)}`, config.rateLimits.push, config.rateLimits.windowMs);
if (!limit.allowed) return rateLimitResponse(limit, locale);
const auth = resolveAuth(config, request);
if ("error" in auth) {
return Response.json(
{ error: authErrorMessage(locale, auth.error), kind: authErrorKind(auth.error) },
{ status: 401 },
);
}
if (!config.push.publicKey || !config.push.privateKey) {
return Response.json(
{ error: translate(locale, "server.pushDisabled"), kind: "push_disabled" },
{ status: 404 },
);
}
let payload: unknown;
try {
payload = await request.json();
} catch {
return Response.json({ error: translate(locale, "server.bodyNotJson") }, { status: 400 });
}
const parsed = subscriptionSchema.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 },
);
}
const count = await addSubscription(config.push.dir, parsed.data);
return Response.json({ ok: true, count }, { headers: { "Cache-Control": "no-store" } });
}
export async function DELETE(request: Request) {
const locale = requestLocale(request);
const crossOrigin = rejectCrossOrigin(request);
if (crossOrigin) return crossOrigin;
const config = getServerConfig();
const limit = rateLimit(`push:${clientKey(request)}`, config.rateLimits.push, config.rateLimits.windowMs);
if (!limit.allowed) return rateLimitResponse(limit, locale);
const auth = resolveAuth(config, request);
if ("error" in auth) {
return Response.json(
{ error: authErrorMessage(locale, auth.error), kind: authErrorKind(auth.error) },
{ status: 401 },
);
}
const endpoint = new URL(request.url).searchParams.get("endpoint") ?? "";
if (!endpoint) {
return Response.json(
{ error: translate(locale, "server.invalidRequest", { detail: "endpoint" }) },
{ status: 400 },
);
}
const count = await removeSubscription(config.push.dir, endpoint);
return Response.json({ ok: true, count }, { headers: { "Cache-Control": "no-store" } });
}

View file

@ -0,0 +1,89 @@
import webpush from "web-push";
import { z } from "zod";
import { authErrorKind, authErrorMessage, getServerConfig, resolveAuth } from "@/lib/config";
import { rejectCrossOrigin, rejectOversizedBody, requestLocale } from "@/lib/http-guard";
import { translate } from "@/lib/i18n-dict";
import { readSubscriptions, removeSubscription } from "@/lib/push-store";
import { clientKey, rateLimit, rateLimitResponse } from "@/lib/rate-limit";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
const bodySchema = z.object({ endpoint: z.string().url().max(2000) });
/** Sends one test notification to this browser's subscription. */
export async function POST(request: Request) {
const locale = requestLocale(request);
const crossOrigin = rejectCrossOrigin(request);
if (crossOrigin) return crossOrigin;
const config = getServerConfig();
const oversized = rejectOversizedBody(request, 16 * 1024);
if (oversized) return oversized;
const limit = rateLimit(`push:${clientKey(request)}`, config.rateLimits.push, config.rateLimits.windowMs);
if (!limit.allowed) return rateLimitResponse(limit, locale);
const auth = resolveAuth(config, request);
if ("error" in auth) {
return Response.json(
{ error: authErrorMessage(locale, auth.error), kind: authErrorKind(auth.error) },
{ status: 401 },
);
}
if (!config.push.publicKey || !config.push.privateKey) {
return Response.json(
{ error: translate(locale, "server.pushDisabled"), kind: "push_disabled" },
{ status: 404 },
);
}
let payload: unknown;
try {
payload = await request.json();
} catch {
return Response.json({ error: translate(locale, "server.bodyNotJson") }, { status: 400 });
}
const parsed = bodySchema.safeParse(payload);
if (!parsed.success) {
return Response.json({ error: translate(locale, "server.invalidRequest", { detail: "endpoint" }) }, { status: 400 });
}
const subscriptions = await readSubscriptions(config.push.dir);
const target = subscriptions.find((entry) => entry.endpoint === parsed.data.endpoint);
if (!target) {
return Response.json(
{ error: translate(locale, "server.pushNotSubscribed"), kind: "not_subscribed" },
{ status: 404 },
);
}
webpush.setVapidDetails(config.push.subject, config.push.publicKey, config.push.privateKey);
try {
await webpush.sendNotification(
{ endpoint: target.endpoint, keys: target.keys },
JSON.stringify({
title: translate(locale, "server.pushReminderTitle"),
body: translate(locale, "server.pushReminderBody"),
url: "/",
}),
);
} catch (error) {
const status = (error as { statusCode?: number }).statusCode;
if (status === 404 || status === 410) {
await removeSubscription(config.push.dir, target.endpoint);
return Response.json(
{ error: translate(locale, "server.pushGone"), kind: "gone" },
{ status: 410 },
);
}
return Response.json(
{ error: translate(locale, "server.pushSendFailed"), kind: "push_failed" },
{ status: 502 },
);
}
return Response.json({ ok: true }, { headers: { "Cache-Control": "no-store" } });
}

26
app/exam/page.tsx Normal file
View file

@ -0,0 +1,26 @@
import { ApiKeyGate } from "@/components/ApiKeyGate";
import { AppHeader } from "@/components/AppHeader";
import { ExamScreen } from "@/components/exam/ExamScreen";
import { MobileSidebar, Sidebar, SidebarOffset } from "@/components/Sidebar";
export const metadata = {
title: "Exam mode",
};
export default function ExamPage() {
return (
<ApiKeyGate>
<div className="flex min-h-dvh">
<Sidebar />
<SidebarOffset />
<MobileSidebar />
<main className="flex min-h-dvh min-w-0 flex-1 flex-col">
<AppHeader />
<div className="mx-auto w-full max-w-3xl flex-1 px-4 pb-tabbar lg:px-10 lg:pb-16 lg:pt-10">
<ExamScreen />
</div>
</main>
</div>
</ApiKeyGate>
);
}

22
app/review/page.tsx Normal file
View file

@ -0,0 +1,22 @@
import { ApiKeyGate } from "@/components/ApiKeyGate";
import { ReviewClient } from "@/components/ReviewClient";
export const metadata = {
title: "Review",
};
export default async function ReviewPage({
searchParams,
}: {
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
const params = await searchParams;
return (
<ApiKeyGate>
<ReviewClient
mistakes={params.mistakes === "1"}
deckId={typeof params.deck === "string" ? params.deck : undefined}
/>
</ApiKeyGate>
);
}

26
app/stats/page.tsx Normal file
View file

@ -0,0 +1,26 @@
import { ApiKeyGate } from "@/components/ApiKeyGate";
import { AppHeader } from "@/components/AppHeader";
import { MobileSidebar, Sidebar, SidebarOffset } from "@/components/Sidebar";
import { StatsScreen } from "@/components/StatsScreen";
export const metadata = {
title: "Progress",
};
export default function StatsPage() {
return (
<ApiKeyGate>
<div className="flex min-h-dvh">
<Sidebar />
<SidebarOffset />
<MobileSidebar />
<main className="flex min-h-dvh min-w-0 flex-1 flex-col">
<AppHeader />
<div className="mx-auto w-full max-w-3xl flex-1 px-4 pb-tabbar lg:px-10 lg:pb-16 lg:pt-10">
<StatsScreen />
</div>
</main>
</div>
</ApiKeyGate>
);
}