Add “Make my homework”, and finish the mobile polish pass
Homework (/homework — entry points in the drawer and on the create screen) - Assignment intake reuses the study pipeline: pasted text, photos (camera/picker, compressed in the browser) and documents (PDF/DOCX/PPTX/ ODT/text) through lib/image + lib/documents, the same vision step and the same language guard. Raw files never leave the device — only text and JPEG data URLs reach the server. - Two large choice cards: “Just make it” returns the finished homework (answer only, plain text, copy + make it again); “Explain how to make this homework” builds an interactive guide. - The guide is one step per screen in the study-feed snap layout: explanation, three progressive hints (nudge -> hint -> the answer) and an optional checkpoint rendered by the existing activity components (graded through /api/grade). The last screen assembles the solution from the step answers, with a copy button. Checkpoints carry xp 0 so the guide stays free of XP/streak chrome. - Results live in freezmo.homework.v1 with a small history (open/delete); “Make it again” re-runs from the stored assignment text (the vision transcription when photos were used) — no original files are stored. - The answer and the guide are written in the assignment's language, never translated into the UI language. Server - POST /api/homework: NDJSON stage events like /api/generate, the same http-guard, auth checked before parsing, and its own RATE_LIMIT_HOMEWORK (documented in .env.example + the README table). - New prompts in lib/prompts.ts and zod schemas in lib/schemas.ts with the same single repair retry; TEXT_MODEL for content, VISION_MODEL only for photos. New shared client pieces: useNotesIntake, lib/homework store, lib/clipboard, and a shared NDJSON reader in lib/client-api. Also finishing the mobile polish pass from the previous request - Phone ice scene: the top-left orb moved behind the glass header (it sat behind the page heading/subtitle). The settings sheet's scroll cue is now a bare chevron inside a content fade (mask) instead of a chip over the status banner, and the API key card's note/disclosure/actions are tightened. - theme-color now follows the in-app theme (SSR metas still fall back to the OS preference); apple-mobile-web-app-status-bar-style stays “default” because iOS fixes the status-bar text colour at launch. Verified: 78/78 homework checks (text/photo/PDF, both modes, EN+CS, dark+light, 360/390px, copy, history persistence, storage privacy, API language, axe), plus the existing suites re-run (mobile 47/47, pixel contrast 0 below AA, i18n 27/27, desktop regression 72/72). Lint + build clean; service worker freezmo-v6.
This commit is contained in:
parent
9fb728d735
commit
ef2a6a3589
35 changed files with 2334 additions and 100 deletions
|
|
@ -1,7 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import { localeHeader, t } from "./i18n";
|
||||
import type { Activity, Difficulty } from "./schemas";
|
||||
import type { Activity, Difficulty, HomeworkMode, HomeworkStep } from "./schemas";
|
||||
import { API_KEY_HEADER, authHeaders } from "./settings";
|
||||
|
||||
export type GenerateInput = {
|
||||
|
|
@ -44,6 +44,41 @@ export class ApiError extends Error {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads an NDJSON response line by line and hands each parsed event to the
|
||||
* callback. Malformed lines are skipped (a half-written line must never break
|
||||
* the stream), and the trailing buffer is flushed at the end.
|
||||
*/
|
||||
async function consumeNdjson(
|
||||
response: Response,
|
||||
handleEvent: (event: unknown) => void,
|
||||
): Promise<void> {
|
||||
if (!response.body) throw new ApiError(t("api.empty"), "bad_response");
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
const flush = (line: string) => {
|
||||
if (!line.trim()) return;
|
||||
try {
|
||||
handleEvent(JSON.parse(line));
|
||||
} catch {
|
||||
/* ignore malformed lines */
|
||||
}
|
||||
};
|
||||
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) {
|
||||
flush(buffer.slice(0, newline));
|
||||
buffer = buffer.slice(newline + 1);
|
||||
newline = buffer.indexOf("\n");
|
||||
}
|
||||
}
|
||||
flush(buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls POST /api/generate and consumes the NDJSON progress stream.
|
||||
* Progress events arrive between the vision and generation steps.
|
||||
|
|
@ -71,55 +106,30 @@ export async function generateDeck(
|
|||
const body = (await response.json().catch(() => null)) as { error?: string; kind?: string } | null;
|
||||
throw new ApiError(body?.error ?? t("api.httpError", { status: response.status }), body?.kind);
|
||||
}
|
||||
if (!response.body) {
|
||||
throw new ApiError(t("api.empty"), "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;
|
||||
let sawDeck = false;
|
||||
|
||||
const handleLine = (line: string) => {
|
||||
if (!line.trim()) return;
|
||||
let event: StreamEvent;
|
||||
try {
|
||||
event = JSON.parse(line) as StreamEvent;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
await consumeNdjson(response, (raw) => {
|
||||
const event = raw as StreamEvent;
|
||||
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;
|
||||
sawDeck = true;
|
||||
options.onProgress?.({ stage: "done", message: t("api.almost") });
|
||||
} 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
|
||||
sawDeck
|
||||
? t("api.incomplete")
|
||||
: t("api.noDeck"),
|
||||
"bad_response",
|
||||
|
|
@ -136,6 +146,102 @@ export async function generateDeck(
|
|||
return { deck: { ...(deck as StreamedDeck), activities: valid }, meta };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Make my homework */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export type HomeworkInput = {
|
||||
mode: HomeworkMode;
|
||||
images?: string[];
|
||||
text?: string;
|
||||
language?: string;
|
||||
};
|
||||
|
||||
export type HomeworkProgress = {
|
||||
stage: "vision" | "generation" | "done";
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type StreamedHomework =
|
||||
| { mode: "make"; title: string; language?: string; answer: string; sourceText?: string }
|
||||
| { mode: "guide"; title: string; language?: string; steps: HomeworkStep[]; sourceText?: string };
|
||||
|
||||
type HomeworkStreamEvent =
|
||||
| { type: "stage"; stage: "vision" | "generation" | "done"; message: string }
|
||||
| { type: "homework"; homework: StreamedHomework; meta: Record<string, unknown> }
|
||||
| { type: "error"; error: string; kind?: string };
|
||||
|
||||
/**
|
||||
* Calls POST /api/homework and consumes the NDJSON progress stream. Same shape
|
||||
* as generateDeck: stage events first, then one final payload.
|
||||
*/
|
||||
export async function generateHomework(
|
||||
input: HomeworkInput,
|
||||
options: { onProgress?: (progress: HomeworkProgress) => void; signal?: AbortSignal } = {},
|
||||
): Promise<{ homework: StreamedHomework; meta: Record<string, unknown> }> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch("/api/homework", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...authHeaders(), ...localeHeader() },
|
||||
body: JSON.stringify(input),
|
||||
signal: options.signal,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
throw new ApiError(t("api.cancelled"), "aborted");
|
||||
}
|
||||
throw new ApiError(t("api.unreachable"), "network");
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const body = (await response.json().catch(() => null)) as { error?: string; kind?: string } | null;
|
||||
throw new ApiError(body?.error ?? t("api.httpError", { status: response.status }), body?.kind);
|
||||
}
|
||||
|
||||
let homework: StreamedHomework | null = null;
|
||||
let meta: Record<string, unknown> = {};
|
||||
let streamError: ApiError | null = null;
|
||||
|
||||
await consumeNdjson(response, (raw) => {
|
||||
const event = raw as HomeworkStreamEvent;
|
||||
if (event.type === "stage") {
|
||||
options.onProgress?.({ stage: event.stage, message: event.message });
|
||||
} else if (event.type === "homework") {
|
||||
homework = event.homework;
|
||||
meta = event.meta ?? {};
|
||||
options.onProgress?.({ stage: "done", message: t("api.almost") });
|
||||
} else if (event.type === "error") {
|
||||
streamError = new ApiError(event.error, event.kind);
|
||||
}
|
||||
});
|
||||
|
||||
if (streamError) throw streamError;
|
||||
if (!homework) {
|
||||
throw new ApiError(t("api.noHomework"), "bad_response");
|
||||
}
|
||||
|
||||
const result = homework as StreamedHomework;
|
||||
if (result.mode === "make") {
|
||||
if (!result.answer?.trim()) throw new ApiError(t("api.noHomework"), "bad_response");
|
||||
} else {
|
||||
const steps = result.steps?.filter((step) => step && typeof step.title === "string");
|
||||
if (!steps || steps.length < 2) throw new ApiError(t("api.noHomework"), "bad_response");
|
||||
// Checkpoints must look like real activities; drop anything malformed
|
||||
// rather than crash the guide.
|
||||
const cleaned = steps.map((step) => ({
|
||||
...step,
|
||||
checkpoint:
|
||||
step.checkpoint && typeof step.checkpoint.type === "string" && typeof step.checkpoint.id === "string"
|
||||
? step.checkpoint
|
||||
: undefined,
|
||||
}));
|
||||
return { homework: { ...result, steps: cleaned }, meta };
|
||||
}
|
||||
|
||||
return { homework: result, meta };
|
||||
}
|
||||
|
||||
export async function gradeAnswer(input: {
|
||||
question: string;
|
||||
referenceAnswer: string;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue