DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(quiz/book): quiz follow-up chat composer, GeoGebra viewer, book updates
Bingxi Zhao (Frank)4df05d02dab9
diff --git a/deeptutor/api/routers/quiz_judge.py b/deeptutor/api/routers/quiz_judge.pynew file mode 100644index 000000000..dc3881951--- /dev/null+++ b/deeptutor/api/routers/quiz_judge.py@@ -0,0 +1,433 @@+"""AI judge WebSocket — grades a learner's quiz answer.++Mounted on its own (without router-level HTTP auth dependencies) because+WebSocket upgrades cannot use FastAPI's HTTP dependency injection, so we+rely on ``ws_require_auth`` inside the handler — mirroring the pattern+used by ``unified_ws``.+"""++from __future__ import annotations++import base64 as _b64+import logging+from typing import Any++from fastapi import APIRouter, WebSocket, WebSocketDisconnect++from deeptutor.services.config import PROJECT_ROOT, load_config_with_main+from deeptutor.services.llm import stream as llm_stream+from deeptutor.services.settings.interface_settings import get_ui_language+from deeptutor.utils.error_utils import format_exception_message++logger = logging.getLogger(__name__)+_config = load_config_with_main("main.yaml", PROJECT_ROOT)++router = APIRouter()+++_JUDGE_SYSTEM_PROMPTS = {+ "zh": (+ "你是一名严谨且鼓励学习者的助教,正在批改一道测验题。"+ "请基于题目、参考答案与解析,对学习者的作答给出针对性的判定与反馈。\n\n"+ "回答要求:\n"+ "- 先用一行明确结论:✅ 正确 / ⚠️ 部分正确 / ❌ 不正确,并简短点明关键判定依据。\n"+ "- 然后分条列出:哪里做对了、哪里出错或缺漏、应该如何改正。\n"+ "- 若题目本身有多种合理答案,请承认学习者的合理之处。\n"+ "- 直接以学习者的作答为对象,不要泛泛而谈。\n"+ "- 全程使用中文。"+ ),+ "en": (+ "You are a rigorous yet encouraging teaching assistant grading a learner's quiz answer. "+ "Use the question, reference answer, and explanation to deliver a targeted assessment.\n\n"+ "Requirements:\n"+ "- Open with one line that states the verdict: ✅ Correct / ⚠️ Partially correct / ❌ Incorrect, "+ "and the key reason.\n"+ "- Then list: what the learner got right, what is wrong or missing, and how to fix it.\n"+ "- If multiple reasonable answers exist, acknowledge what the learner did well.\n"+ "- Speak directly to the learner's submission — do not give a generic lecture.\n"+ "- Reply in English."+ ),+}+++def _build_judge_user_prompt(+ *,+ language: str,+ question: str,+ question_type: str,+ options: dict | None,+ correct_answer: str,+ explanation: str,+ user_answer: str,+ has_image: bool,+ image_count: int = 0,+) -> str:+ options_block = ""+ if options:+ try:+ options_block = "\n".join(f" {k}. {v}" for k, v in options.items())+ except Exception:+ options_block = ""+ if language == "zh":+ parts = [+ f"题目类型:{question_type or 'unknown'}",+ f"题干:\n{question}",+ ]+ if options_block:+ parts.append(f"选项:\n{options_block}")+ if correct_answer:+ parts.append(f"参考答案:\n{correct_answer}")+ if explanation:+ parts.append(f"参考解析:\n{explanation}")+ parts.append(+ "学习者作答:\n"+ + (+ user_answer.strip()+ if user_answer and user_answer.strip()+ else "(仅提交了图片,无文字作答)"+ )+ )+ if has_image:+ count_text = (+ f"学习者另附了 {image_count} 张图片作为作答内容"+ if image_count > 1+ else "学习者另附了一张图片作为作答内容"+ )+ parts.append(+ f"{count_text},请结合图片中的文字/公式/草图一并判定。"+ )+ parts.append("请针对该学习者的具体作答给出 AI 评判。")+ else:+ parts = [+ f"Question type: {question_type or 'unknown'}",+ f"Question:\n{question}",+ ]+ if options_block:+ parts.append(f"Options:\n{options_block}")+ if correct_answer:+ parts.append(f"Reference answer:\n{correct_answer}")+ if explanation:+ parts.append(f"Reference explanation:\n{explanation}")+ parts.append(+ "Learner's answer:\n"+ + (+ user_answer.strip()+ if user_answer and user_answer.strip()+ else "(only an image was submitted, no typed answer)"+ )+ )+ if has_image:+ if image_count > 1:+ parts.append(+ f"The learner attached {image_count} images as part of the answer. "+ "Read their text/formulas/sketches and factor them into the judgment."+ )+ else:+ parts.append(+ "The learner attached an image as part of the answer. "+ "Read its text/formulas/sketches and factor it into the judgment."+ )+ parts.append("Produce an AI judgment that addresses this learner's specific answer.")+ return "\n\n".join(parts)+++async def _build_multimodal_user_content(+ *,+ text: str,+ image_records: list[dict[str, str]],+) -> list[dict[str, Any]]:+ """Compose an OpenAI-style content-parts array with text + image blocks.++ For ``url``-only records we resolve local AttachmentStore paths to+ base64 here (most providers can fetch external URLs themselves, but+ locally-hosted ``/api/attachments/...`` is only reachable from the+ browser). Falls back to passing the URL through when resolution is+ not possible.+ """+ from urllib.parse import unquote, urlparse++ from deeptutor.services.storage import get_attachment_store++ content: list[dict[str, Any]] = [{"type": "text", "text": text}]+ attachment_store = get_attachment_store()+ resolve = getattr(attachment_store, "resolve_path", None)++ for record in image_records:+ b64 = record.get("base64") or ""+ url = record.get("url") or ""+ filename = record.get("filename") or "answer.png"+ mime_type = record.get("mime_type") or _guess_image_mime(filename)++ if not b64 and url and resolve is not None:+ try:+ parsed = urlparse(url)+ parts = (parsed.path or url).strip("/").split("/")+ # Expected shape: api/attachments/{sid}/{aid}/{name}+ if len(parts) >= 5 and parts[0] == "api" and parts[1] == "attachments":+ sid = unquote(parts[2])+ aid = unquote(parts[3])+ name = unquote("/".join(parts[4:]))+ target = resolve(session_id=sid, attachment_id=aid, filename=name)+ if target is not None and target.exists():+ b64 = _b64.b64encode(target.read_bytes()).decode("ascii")+ except Exception as exc:+ logger.debug("Could not resolve %s to bytes: %s", url, exc)++ if b64:+ data_url = f"data:{mime_type};base64,{b64}"+ content.append({"type": "image_url", "image_url": {"url": data_url}})+ elif url:+ content.append({"type": "image_url", "image_url": {"url": url}})++ return content+++def _guess_image_mime(filename: str | None) -> str:+ if not filename:+ return "image/png"+ ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""+ return {+ "png": "image/png",+ "jpg": "image/jpeg",+ "jpeg": "image/jpeg",+ "gif": "image/gif",+ "webp": "image/webp",+ }.get(ext, "image/png")++[email protected]("/question/judge")+async def websocket_quiz_judge(websocket: WebSocket):+ """Stream an AI judgment for a single quiz answer.++ Auth is enforced via ``ws_require_auth`` rather than a router-level+ HTTP dependency — see module docstring.++ Client → Server (initial JSON):+ {+ "question": str,+ "question_type": str,+ "options": dict | null,+ "correct_answer": str,+ "explanation": str,+ "user_answer": str,+ # New: list of image entries. Each entry has either ``base64``+ # (no ``data:`` prefix) or ``url`` (already hosted via the+ # AttachmentStore). ``user_answer_image`` (single, base64) is+ # still accepted for backward compatibility.+ "user_answer_images": [+ {"base64": str, "url": str, "filename": str, "mime_type": str},+ ...+ ] | null,+ "user_answer_image": str | null, # legacy single-image form+ "image_filename": str | null, # legacy filename for the above+ "language": "zh" | "en",+ }++ Server → Client (streaming):+ {"type": "started"}+ {"type": "text", "content": "..."} # zero or more+ {"type": "done"}+ {"type": "error", "content": "..."}+ """+ from deeptutor.api.routers.auth import ws_auth_failed, ws_require_auth+ from deeptutor.multi_user.context import reset_current_user++ user_token = await ws_require_auth(websocket)+ if user_token is ws_auth_failed:+ return++ await websocket.accept()++ async def safe_send(payload: dict[str, Any]) -> bool:+ try:+ await websocket.send_json(payload)+ return True+ except (WebSocketDisconnect, RuntimeError, ConnectionError):+ return False++ try:+ data = await websocket.receive_json()+ except WebSocketDisconnect:+ return+ except Exception as exc:+ await safe_send({"type": "error", "content": f"Invalid request: {exc}"})+ try:+ await websocket.close()+ except Exception:+ pass+ if user_token is not None:+ try:+ reset_current_user(user_token)+ except Exception:+ pass+ return++ question_text = (data.get("question") or "").strip()+ if not question_text:+ await safe_send({"type": "error", "content": "Question is required"})+ try:+ await websocket.close()+ except Exception:+ pass+ if user_token is not None:+ try:+ reset_current_user(user_token)+ except Exception:+ pass+ return++ requested_language = (data.get("language") or "").strip().lower()+ if requested_language not in ("zh", "en"):+ requested_language = get_ui_language(+ default=_config.get("system", {}).get("language", "en")+ )+ if requested_language not in ("zh", "en"):+ requested_language = "en"++ user_answer = data.get("user_answer") or ""++ # Resolve the image set. New clients send ``user_answer_images`` (list);+ # legacy clients send the single ``user_answer_image`` + ``image_filename``+ # pair. Build a uniform list of ``{base64, url, filename, mime_type}`` so+ # the downstream multimodal-message builder doesn't care which form+ # arrived.+ raw_images = data.get("user_answer_images")+ image_records: list[dict[str, str]] = []+ if isinstance(raw_images, list):+ for entry in raw_images:+ if not isinstance(entry, dict):+ continue+ b64 = entry.get("base64") or ""+ url = entry.get("url") or ""+ if isinstance(b64, str) and b64.startswith("data:"):+ try:+ b64 = b64.split(",", 1)[1]+ except IndexError:+ b64 = ""+ if not b64 and not url:+ continue+ filename = entry.get("filename") or "answer.png"+ mime_type = entry.get("mime_type") or _guess_image_mime(filename)+ image_records.append(+ {+ "base64": b64,+ "url": url,+ "filename": filename,+ "mime_type": mime_type,+ }+ )+ else:+ legacy_b64 = data.get("user_answer_image") or ""+ if isinstance(legacy_b64, str) and legacy_b64.startswith("data:"):+ try:+ legacy_b64 = legacy_b64.split(",", 1)[1]+ except IndexError:+ legacy_b64 = ""+ if legacy_b64:+ legacy_filename = data.get("image_filename") or "answer.png"+ image_records.append(+ {+ "base64": legacy_b64,+ "url": "",+ "filename": legacy_filename,+ "mime_type": _guess_image_mime(legacy_filename),+ }+ )++ has_image = bool(image_records)++ options_value = data.get("options") if isinstance(data.get("options"), dict) else None+ system_prompt = _JUDGE_SYSTEM_PROMPTS.get(+ requested_language, _JUDGE_SYSTEM_PROMPTS["en"]+ )+ user_prompt = _build_judge_user_prompt(+ language=requested_language,+ question=question_text,+ question_type=data.get("question_type") or "",+ options=options_value,+ correct_answer=data.get("correct_answer") or "",+ explanation=data.get("explanation") or "",+ user_answer=user_answer,+ has_image=has_image,+ image_count=len(image_records),+ )++ if not (user_answer.strip() or has_image):+ await safe_send(+ {+ "type": "error",+ "content": (+ "No answer to judge — submit a typed answer or attach an image."+ ),+ }+ )+ try:+ await websocket.close()+ except Exception:+ pass+ if user_token is not None:+ try:+ reset_current_user(user_token)+ except Exception:+ pass+ return++ await safe_send({"type": "started"})++ # Build a multimodal user message when ≥1 image was attached. We pass+ # the full ``messages`` array to ``factory.stream`` so it forwards the+ # content-parts unchanged (the single-image ``image_data`` kwarg only+ # supports one image).+ stream_kwargs: dict[str, Any] = {}+ if has_image:+ from deeptutor.services.llm import config as _llm_config_mod+ from deeptutor.services.llm.capabilities import supports_vision++ llm_cfg = _llm_config_mod.get_llm_config()+ binding = getattr(llm_cfg, "binding", "openai") or "openai"+ model = getattr(llm_cfg, "model", "") or ""+ if supports_vision(binding, model):+ user_content = await _build_multimodal_user_content(+ text=user_prompt,+ image_records=image_records,+ )+ stream_kwargs["messages"] = [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": user_content},+ ]+ else:+ # Vision-incapable model — fall back to text-only judge so the+ # learner still gets feedback on their typed answer.+ logger.info(+ "Judge: %s/%s does not support vision; dropping %d image(s)",+ binding,+ model,+ len(image_records),+ )++ try:+ async for chunk in llm_stream(+ prompt=user_prompt,+ system_prompt=system_prompt,+ **stream_kwargs,+ ):+ if not chunk:+ continue+ if not await safe_send({"type": "text", "content": chunk}):+ break+ await safe_send({"type": "done"})+ except WebSocketDisconnect:+ logger.debug("AI judge client disconnected mid-stream")+ except Exception as exc:+ logger.exception("AI judge stream failed")+ await safe_send({"type": "error", "content": format_exception_message(exc)})+ finally:+ try:+ await websocket.close()+ except Exception:+ pass+ if user_token is not None:+ try:+ reset_current_user(user_token)+ except Exception:+ passdiff --git a/deeptutor/book/blocks/quiz.py b/deeptutor/book/blocks/quiz.pyindex ac05de0ed..197f1409a 100644--- a/deeptutor/book/blocks/quiz.py+++ b/deeptutor/book/blocks/quiz.py@@ -26,7 +26,12 @@ class QuizGenerator(BlockGenerator):question_type = str(params.get("question_type") or "")topic = chapter_title.strip() or ctx.book_id- preference = "; ".join(filter(None, [chapter_summary, *objectives]))+ # Fold chapter context directly into the topic so the planner sees+ # it without needing a separate "preference" channel.+ extra_context = "; ".join(filter(None, [chapter_summary, *objectives]))+ if extra_context:+ topic = f"{topic}\n\n[Chapter context: {extra_context}]"+ question_types = [question_type] if question_type else []try:from deeptutor.agents.question.coordinator import AgentCoordinator@@ -38,10 +43,9 @@ class QuizGenerator(BlockGenerator):)summary = await coordinator.generate_from_topic(user_topic=topic,- preference=preference,num_questions=num_questions,difficulty=difficulty,- question_type=question_type,+ question_types=question_types,)except Exception as exc:logger.warning(f"QuizGenerator failed: {exc}", exc_info=True)diff --git a/deeptutor/book/engine.py b/deeptutor/book/engine.pyindex 22cf9521c..18d631178 100644--- a/deeptutor/book/engine.py+++ b/deeptutor/book/engine.py@@ -1223,6 +1223,7 @@ _engines: dict[str, BookEngine] = {}def get_book_engine() -> BookEngine:from deeptutor.services.path_service import get_path_service+key = str(get_path_service().workspace_root.resolve())if key not in _engines:_engines[key] = BookEngine()diff --git a/deeptutor/book/storage.py b/deeptutor/book/storage.pyindex 50aafd09a..ba2afdfb3 100644--- a/deeptutor/book/storage.py+++ b/deeptutor/book/storage.py@@ -84,7 +84,6 @@ class BookStorage:@propertydef path_service(self):- from deeptutor.services.path_service import get_path_servicereturn get_path_service()# ── Path helpers ─────────────────────────────────────────────────────@@ -270,7 +269,6 @@ _storages: dict[str, BookStorage] = {}def get_book_storage() -> BookStorage:- from deeptutor.services.path_service import get_path_servicekey = str(get_path_service().workspace_root.resolve())if key not in _storages:_storages[key] = BookStorage()diff --git a/web/app/(workspace)/book/components/BookChatPanel.tsx b/web/app/(workspace)/book/components/BookChatPanel.tsxindex 2aedd54a8..58138523d 100644--- a/web/app/(workspace)/book/components/BookChatPanel.tsx+++ b/web/app/(workspace)/book/components/BookChatPanel.tsx@@ -121,6 +121,8 @@ export default function BookChatPanel({const raw = window.localStorage.getItem("deeptutor.bookChat.width");const parsed = Number(raw);if (Number.isFinite(parsed) && parsed >= 300 && parsed <= 720) {+ // Hydrate persisted panel width after the SSR-safe default render.+ // eslint-disable-next-line react-hooks/set-state-in-effectsetWidth(parsed);}}, []);@@ -130,9 +132,10 @@ export default function BookChatPanel({}, [width]);useEffect(() => {+ const retryTimers = retryTimersRef.current;return () => {- retryTimersRef.current.forEach((timer) => clearTimeout(timer));- retryTimersRef.current.clear();+ retryTimers.forEach((timer) => clearTimeout(timer));+ retryTimers.clear();clientRef.current?.disconnect();clientRef.current = null;};@@ -145,6 +148,8 @@ export default function BookChatPanel({clientRef.current?.disconnect();clientRef.current = null;sessionIdRef.current = initialSessionId || null;+ // Reset local chat state when the backing page/session changes.+ // eslint-disable-next-line react-hooks/set-state-in-effectsetMessages([]);setAttachments([]);setAttachmentError(null);diff --git a/web/app/(workspace)/book/components/PageOutlineNav.tsx b/web/app/(workspace)/book/components/PageOutlineNav.tsxindex 95603033b..b30e496ee 100644--- a/web/app/(workspace)/book/components/PageOutlineNav.tsx+++ b/web/app/(workspace)/book/components/PageOutlineNav.tsx@@ -90,26 +90,20 @@ export interface PageOutlineNavProps {blocks: Block[];scrollContainer?: HTMLElement | null;language?: string;- /** Stable identifier (e.g. page id) used to reset collapsed state when the page changes. */- resetKey?: string;}export default function PageOutlineNav({blocks,scrollContainer,language: _language,- resetKey,}: PageOutlineNavProps) {const { t } = useTranslation();const headerText = t("On this page");const collapseTip = t("Hide outline");const expandTip = t("Show outline");- // Default: expanded. Reset whenever the page changes.+ // Default: expanded; PageReader keys this component by page id.const [collapsed, setCollapsed] = useState(false);- useEffect(() => {- setCollapsed(false);- }, [resetKey]);// Track which block is currently in view for active highlight.const [activeId, setActiveId] = useState<string | null>(null);diff --git a/web/app/(workspace)/book/components/PageReader.tsx b/web/app/(workspace)/book/components/PageReader.tsxindex 9451e0d66..e52816e87 100644--- a/web/app/(workspace)/book/components/PageReader.tsx+++ b/web/app/(workspace)/book/components/PageReader.tsx@@ -319,10 +319,10 @@ export default function PageReader({{/* Floating outline lives outside the scroll container so it stayspinned to the viewport regardless of page scrolling. */}<PageOutlineNav+ key={page.id}blocks={page.blocks}scrollContainer={scrollContainer}language={bookLanguage}- resetKey={page.id}/></div>);diff --git a/web/app/(workspace)/book/components/blocks/FigureBlock.tsx b/web/app/(workspace)/book/components/blocks/FigureBlock.tsxindex 89be7dcd4..2b9a3f648 100644--- a/web/app/(workspace)/book/components/blocks/FigureBlock.tsx+++ b/web/app/(workspace)/book/components/blocks/FigureBlock.tsx@@ -5,15 +5,15 @@ import MarkdownRenderer from "@/components/common/MarkdownRenderer";import { useTranslation } from "react-i18next";import type { Block } from "@/lib/book-types";import type {- VisualizeRenderType,VisualizeResult,+ VisualizeTextRenderType,} from "@/lib/visualize-types";export interface FigureBlockProps {block: Block;}-const FIGURE_RENDER_TYPES: ReadonlySet<VisualizeRenderType> = new Set([+const FIGURE_RENDER_TYPES: ReadonlySet<VisualizeTextRenderType> = new Set(["svg","chartjs","mermaid",@@ -22,12 +22,12 @@ const FIGURE_RENDER_TYPES: ReadonlySet<VisualizeRenderType> = new Set([function coerceRenderType(value: unknown,language: string,-): VisualizeRenderType {+): VisualizeTextRenderType {if (typeof value === "string" &&(FIGURE_RENDER_TYPES as Set<string>).has(value)) {- return value as VisualizeRenderType;+ return value as VisualizeTextRenderType;}if (language === "javascript" || language === "js") return "chartjs";if (language === "mermaid") return "mermaid";diff --git a/web/app/(workspace)/book/components/blocks/QuizBlock.tsx b/web/app/(workspace)/book/components/blocks/QuizBlock.tsxindex fe964e004..df0c054d5 100644--- a/web/app/(workspace)/book/components/blocks/QuizBlock.tsx+++ b/web/app/(workspace)/book/components/blocks/QuizBlock.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { CheckCircle2, Eye, EyeOff, XCircle } from "lucide-react";import { useTranslation } from "react-i18next";@@ -77,26 +77,32 @@ function QuizQuestionCard({const { t } = useTranslation();const [selected, setSelected] = useState<string | null>(null);const [revealed, setRevealed] = useState(false);- const [reported, setReported] = useState(false);+ const reportedRef = useRef<string | null>(null);const normalizedType = normalizeQuizQuestionType(question.question_type);const options = question.options || {};const isChoice = isChoiceQuizQuestion(normalizedType);const correct = String(question.correct_answer || "").trim();const correctChoiceKey = resolveChoiceAnswerKey(correct, options);+ const reportKey = `${question.question_id || index}:${selected || ""}`;useEffect(() => {- if (revealed && selected && !reported && onAttempt) {+ if (+ revealed &&+ selected &&+ reportedRef.current !== reportKey &&+ onAttempt+ ) {+ reportedRef.current = reportKey;onAttempt({questionId: question.question_id,userAnswer: selected,isCorrect: selected.toUpperCase() === correctChoiceKey,});- setReported(true);}}, [+ reportKey,revealed,selected,- reported,onAttempt,question.question_id,correctChoiceKey,diff --git a/web/components/Geogebra.tsx b/web/components/Geogebra.tsxnew file mode 100644index 000000000..dac77fc39--- /dev/null+++ b/web/components/Geogebra.tsx@@ -0,0 +1,191 @@+"use client";++import React, { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";++interface GeogebraProps {+ script: string;+ title?: string;+ className?: string;+ width?: number;+ height?: number;+}++declare global {+ interface Window {+ GGBApplet?: new (params: Record<string, unknown>, html5: boolean) => {+ inject: (containerId: string) => void;+ };+ }+}++const GGB_SCRIPT_SRC = "https://www.geogebra.org/apps/deployggb.js";++// Single in-flight loader shared by every Geogebra instance on the page.+// deployggb.js is ~MB and lives on geogebra.org's CDN; fetching it once and+// reusing window.GGBApplet keeps subsequent applets snappy.+let ggbLoader: Promise<void> | null = null;++function loadGgbScript(): Promise<void> {+ if (typeof window === "undefined") {+ return Promise.reject(new Error("window unavailable"));+ }+ if (window.GGBApplet) return Promise.resolve();+ if (ggbLoader) return ggbLoader;++ ggbLoader = new Promise((resolve, reject) => {+ const existing = document.querySelector<HTMLScriptElement>(+ `script[src="${GGB_SCRIPT_SRC}"]`,+ );+ if (existing) {+ if (window.GGBApplet) {+ resolve();+ return;+ }+ existing.addEventListener("load", () => resolve());+ existing.addEventListener("error", () => {+ ggbLoader = null;+ reject(new Error("GeoGebra script failed to load"));+ });+ return;+ }+ const script = document.createElement("script");+ script.src = GGB_SCRIPT_SRC;+ script.async = true;+ script.onload = () => resolve();+ script.onerror = () => {+ ggbLoader = null;+ reject(new Error("GeoGebra script failed to load"));+ };+ document.head.appendChild(script);+ });++ return ggbLoader;+}++// The agent emits one command per line and prefixes human-readable+// descriptions with `#`. evalCommand only takes one command at a time, so we+// strip comments + empty lines and feed the rest sequentially.+function parseGgbCommands(raw: string): string[] {+ return raw+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter((line) => line.length > 0 && !line.startsWith("#"));+}++let containerCounter = 0;++const Geogebra: React.FC<GeogebraProps> = ({+ script,+ title,+ className = "",+ width = 760,+ height = 480,+}) => {+ const { t } = useTranslation();+ const containerRef = useRef<HTMLDivElement | null>(null);+ const containerIdRef = useRef<string>(+ `ggb-${++containerCounter}-${Date.now().toString(36)}`,+ );+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ let cancelled = false;+ // Snapshot the ref now so the cleanup closure sees the same node React+ // mounted with, not whatever the ref points at after a later re-render.+ const containerAtMount = containerRef.current;+ setLoading(true);+ setError(null);++ async function mount() {+ try {+ await loadGgbScript();+ if (cancelled) return;+ if (!window.GGBApplet) {+ throw new Error("GGBApplet global missing after script load");+ }++ const commands = parseGgbCommands(script);+ const container = containerRef.current;+ if (!container) return;+ container.id = containerIdRef.current;+ container.innerHTML = "";++ const applet = new window.GGBApplet(+ {+ appName: "geometry",+ width,+ height,+ showToolBar: false,+ showAlgebraInput: false,+ showMenuBar: false,+ showResetIcon: true,+ enableLabelDrags: false,+ enableShiftDragZoom: true,+ useBrowserForJS: false,+ // The api passed in here lets us drive the applet+ // imperatively without going through a global. We feed each+ // command separately so one bad line doesn't abort the rest.+ appletOnLoad: (api: { evalCommand: (cmd: string) => boolean }) => {+ if (cancelled) return;+ for (const cmd of commands) {+ try {+ api.evalCommand(cmd);+ } catch (err) {+ console.warn("[ggb] evalCommand failed", { cmd, err });+ }+ }+ setLoading(false);+ },+ },+ true,+ );++ applet.inject(containerIdRef.current);+ } catch (err) {+ if (!cancelled) {+ setError(err instanceof Error ? err.message : String(err));+ setLoading(false);+ }+ }+ }++ void mount();++ return () => {+ cancelled = true;+ if (containerAtMount) {+ containerAtMount.innerHTML = "";+ }+ };+ }, [script, width, height]);++ return (+ <div+ className={`my-4 overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--card)] ${className}`}+ >+ {title ? (+ <div className="border-b border-[var(--border)] px-3 py-2 text-sm font-medium text-[var(--foreground)]">+ {title}+ </div>+ ) : null}+ {error ? (+ <div className="p-4 text-sm text-[var(--destructive,#dc2626)]">+ {t("Failed to load GeoGebra")}: {error}+ </div>+ ) : (+ <div className="relative" style={{ minHeight: height }}>+ {loading ? (+ <div className="absolute inset-0 flex items-center justify-center text-sm text-[var(--muted-foreground)]">+ {t("Loading GeoGebra...")}+ </div>+ ) : null}+ <div ref={containerRef} className="ggb-applet-container" />+ </div>+ )}+ </div>+ );+};++export default Geogebra;diff --git a/web/components/common/GeogebraOpenCTA.tsx b/web/components/common/GeogebraOpenCTA.tsxnew file mode 100644index 000000000..69880d3a1--- /dev/null+++ b/web/components/common/GeogebraOpenCTA.tsx@@ -0,0 +1,88 @@+"use client";++import { Compass } from "lucide-react";+import { useCallback, useMemo } from "react";+import { useTranslation } from "react-i18next";+import { useGeogebraTabOpener } from "@/context/GeogebraTabContext";++interface GeogebraOpenCTAProps {+ /** Raw ggbscript body. */+ script: string;+ /** Stable id from the ```ggbscript[id;title] fence — used for tab dedupe. */+ payloadId?: string;+ /** Title to show on the CTA + the resulting tab. */+ title?: string;+ className?: string;+}++/**+ * Card-style CTA shown in-place of a ```ggbscript fence in chat answers.+ * Clicking expands the right-hand SessionViewerPanel and opens (or+ * focuses) a GeoGebra tab carrying this script.+ *+ * When no GeogebraTabProvider is mounted (e.g. preview surfaces), the+ * button is disabled with a tooltip — we don't want a click to silently+ * no-op.+ */+export default function GeogebraOpenCTA({+ script,+ payloadId,+ title,+ className = "",+}: GeogebraOpenCTAProps) {+ const { t } = useTranslation();+ const controller = useGeogebraTabOpener();++ // A stable id keyed on the script content. This makes the tab dedupe+ // robust even if the assistant doesn't bother emitting an explicit+ // page_id in the fence info (older outputs).+ const id = useMemo(() => {+ if (payloadId) return payloadId;+ let hash = 0;+ for (let i = 0; i < script.length; i += 1) {+ hash = (hash * 31 + script.charCodeAt(i)) | 0;+ }+ return `script-${(hash >>> 0).toString(36)}`;+ }, [payloadId, script]);++ const onClick = useCallback(() => {+ if (!controller) return;+ controller.openTab({ id, title: title || t("GeoGebra figure"), script });+ }, [controller, id, script, t, title]);++ const disabled = !controller;++ return (+ <div className={`my-3 ${className}`}>+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ title={+ disabled+ ? t("GeoGebra viewer is not available in this surface")+ : undefined+ }+ className={`group flex w-full items-center gap-3 rounded-xl border border-[var(--border)] bg-[var(--card)] px-4 py-3 text-left transition-colors ${+ disabled+ ? "cursor-not-allowed opacity-60"+ : "hover:border-[var(--primary)]/60 hover:bg-[var(--muted)]/30"+ }`}+ >+ <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-[var(--primary)]/10 text-[var(--primary)]">+ <Compass size={18} strokeWidth={1.9} />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-sm font-medium text-[var(--foreground)]">+ {title || t("Interactive GeoGebra figure")}+ </span>+ <span className="block text-xs text-[var(--muted-foreground)]">+ {t(+ "Click to open an interactive GeoGebra canvas in the side viewer.",+ )}+ </span>+ </span>+ </button>+ </div>+ );+}diff --git a/web/components/quiz/FollowupChatComposer.tsx b/web/components/quiz/FollowupChatComposer.tsxnew file mode 100644index 000000000..7291f8cdd--- /dev/null+++ b/web/components/quiz/FollowupChatComposer.tsx@@ -0,0 +1,767 @@+"use client";++/**+ * FollowupChatComposer — renders the SAME ``ChatComposer`` used on the+ * main chat page, but with its own local state pool and a send handler+ * that routes through ``QuizFollowupController`` instead of the unified+ * chat context. The follow-up tab uses this so the composer surface+ * (look, controls, @space popup, KB picker, attachments, LLM selector,+ * picker dialogs) matches the main chat composer exactly.+ *+ * Self-contained: loads its own KB / LLM lists, owns drag-and-drop ++ * attachment state, mounts the @space pickers internally.+ */++import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";+import dynamic from "next/dynamic";+import { MessageSquare } from "lucide-react";+import { useTranslation } from "react-i18next";+import ChatComposer from "@/components/chat/home/ChatComposer";+import {+ type QuizFollowupTabContext,+ useFollowupThread,+ useQuizFollowupController,+} from "@/context/QuizFollowupContext";+import { buildQuizFollowupConfig } from "@/lib/quiz-types";+import {+ classifyFile,+ isSvgFilename,+ MAX_ATTACHMENT_BYTES,+ MAX_TOTAL_ATTACHMENT_BYTES,+} from "@/lib/doc-attachments";+import {+ extractBase64FromDataUrl,+ readFileAsDataUrl,+} from "@/lib/file-attachments";+import { listKnowledgeBases } from "@/lib/knowledge-api";+import { listLLMOptions, type LLMOption } from "@/lib/llm-options";+import { selectedBooksToPayload } from "@/lib/book-references";+import type { SelectedBookReference } from "@/lib/book-references";+import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";+import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";+import type { SelectedRecord } from "@/lib/notebook-selection-types";+import type { SpaceMemoryFile } from "@/lib/space-items";+import type { LLMSelection } from "@/lib/unified-ws";++const NotebookRecordPicker = dynamic(+ () => import("@/components/notebook/NotebookRecordPicker"),+ { ssr: false },+);+const HistorySessionPicker = dynamic(+ () => import("@/components/chat/HistorySessionPicker"),+ { ssr: false },+);+const QuestionBankPicker = dynamic(+ () => import("@/components/chat/QuestionBankPicker"),+ { ssr: false },+);+const SkillsPicker = dynamic(() => import("@/components/chat/SkillsPicker"), {+ ssr: false,+});+const MemoryPicker = dynamic(() => import("@/components/chat/MemoryPicker"), {+ ssr: false,+});+const BookReferencePicker = dynamic(+ () => import("@/components/chat/BookReferencePicker"),+ { ssr: false },+);++interface KnowledgeBase {+ name: string;+ is_default?: boolean;+}++interface PendingAttachment {+ type: string;+ filename: string;+ base64?: string;+ previewUrl?: string;+ size?: number;+ mimeType?: string;+}++// Single-capability list — the follow-up tab is locked to "chat".+// label/description are i18n keys; resolved via t() inside the component.+const FOLLOWUP_CAPABILITIES_RAW = [+ {+ value: "",+ label: "Chat",+ description: "Flexible conversation with any tool",+ icon: MessageSquare,+ allowedTools: [],+ },+];++interface FollowupChatComposerProps {+ context: QuizFollowupTabContext;+}++function FollowupChatComposerImpl({ context }: FollowupChatComposerProps) {+ const { t } = useTranslation();+ const controller = useQuizFollowupController();+ const thread = useFollowupThread(context.questionKey);++ // ── Composer DOM refs ─────────────────────────────────────────+ const composerRef = useRef<HTMLDivElement>(null);+ const capMenuRef = useRef<HTMLDivElement>(null);+ const capBtnRef = useRef<HTMLButtonElement>(null);+ const spaceMenuRef = useRef<HTMLDivElement>(null);+ const spaceBtnRef = useRef<HTMLButtonElement>(null);+ const kbMenuRef = useRef<HTMLDivElement>(null);+ const kbBtnRef = useRef<HTMLButtonElement>(null);+ const dragCounter = useRef(0);++ // ── Composer local state ──────────────────────────────────────+ const [attachments, setAttachments] = useState<PendingAttachment[]>([]);+ const [attachmentError, setAttachmentError] = useState<string | null>(null);+ const attachmentErrorTimer = useRef<ReturnType<typeof setTimeout> | null>(+ null,+ );+ const [dragging, setDragging] = useState(false);+ const [capMenuOpen, setCapMenuOpen] = useState(false);+ const [spaceMenuOpen, setSpaceMenuOpen] = useState(false);+ const [kbMenuOpen, setKbMenuOpen] = useState(false);++ const [selectedKnowledgeBases, setSelectedKnowledgeBases] = useState<+ string[]+ >([]);+ const [selectedBookReferences, setSelectedBookReferences] = useState<+ SelectedBookReference[]+ >([]);+ const [selectedNotebookRecords, setSelectedNotebookRecords] = useState<+ SelectedRecord[]+ >([]);+ const [selectedHistorySessions, setSelectedHistorySessions] = useState<+ SelectedHistorySession[]+ >([]);+ const [selectedQuestionEntries, setSelectedQuestionEntries] = useState<+ SelectedQuestionEntry[]+ >([]);+ const [selectedSkills, setSelectedSkills] = useState<string[]>([]);+ const [skillsAutoMode, setSkillsAutoMode] = useState(false);+ const [selectedMemoryFiles, setSelectedMemoryFiles] = useState<+ SpaceMemoryFile[]+ >([]);++ // ── Picker dialog visibility ──────────────────────────────────+ const [showNotebookPicker, setShowNotebookPicker] = useState(false);+ const [showBookPicker, setShowBookPicker] = useState(false);+ const [showHistoryPicker, setShowHistoryPicker] = useState(false);+ const [showQuestionBankPicker, setShowQuestionBankPicker] = useState(false);+ const [showSkillsPicker, setShowSkillsPicker] = useState(false);+ const [showMemoryPicker, setShowMemoryPicker] = useState(false);++ // ── Shared data (KBs + LLMs) ──────────────────────────────────+ const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);+ const [llmOptions, setLLMOptions] = useState<LLMOption[]>([]);+ const [activeLLMDefault, setActiveLLMDefault] = useState<LLMSelection | null>(+ null,+ );+ const [llmSelection, setLLMSelection] = useState<LLMSelection | null>(null);+ const [llmOptionsLoading, setLLMOptionsLoading] = useState(true);+ const [llmOptionsError, setLLMOptionsError] = useState(false);++ useEffect(() => {+ let cancelled = false;+ const run = async () => {+ try {+ const list = await listKnowledgeBases({ force: false });+ if (!cancelled) setKnowledgeBases(list);+ } catch {+ if (!cancelled) setKnowledgeBases([]);+ }+ };+ void run();+ return () => {+ cancelled = true;+ };+ }, []);++ useEffect(() => {+ let cancelled = false;+ const run = async () => {+ setLLMOptionsLoading(true);+ try {+ const payload = await listLLMOptions();+ if (cancelled) return;+ setLLMOptions(payload.options);+ setActiveLLMDefault(payload.active);+ setLLMOptionsError(false);+ } catch {+ if (cancelled) return;+ setLLMOptionsError(true);+ setLLMOptions([]);+ setActiveLLMDefault(null);+ } finally {+ if (!cancelled) setLLMOptionsLoading(false);+ }+ };+ void run();+ return () => {+ cancelled = true;+ };+ }, []);++ // Default to the server-side active LLM until the user picks one.+ useEffect(() => {+ if (llmSelection || !activeLLMDefault) return;+ setLLMSelection(activeLLMDefault);+ }, [activeLLMDefault, llmSelection]);++ // Click-outside handlers for menu chrome (cap / space / KB).+ useEffect(() => {+ if (!capMenuOpen && !spaceMenuOpen && !kbMenuOpen) return;+ const handler = (event: MouseEvent) => {+ const target = event.target as Node | null;+ if (!target) return;+ if (+ capMenuOpen &&+ capMenuRef.current &&+ !capMenuRef.current.contains(target) &&+ capBtnRef.current &&+ !capBtnRef.current.contains(target)+ ) {+ setCapMenuOpen(false);+ }+ if (+ spaceMenuOpen &&+ spaceMenuRef.current &&+ !spaceMenuRef.current.contains(target) &&+ spaceBtnRef.current &&+ !spaceBtnRef.current.contains(target)+ ) {+ setSpaceMenuOpen(false);+ }+ if (+ kbMenuOpen &&+ kbMenuRef.current &&+ !kbMenuRef.current.contains(target) &&+ kbBtnRef.current &&+ !kbBtnRef.current.contains(target)+ ) {+ setKbMenuOpen(false);+ }+ };+ document.addEventListener("mousedown", handler);+ return () => document.removeEventListener("mousedown", handler);+ }, [capMenuOpen, spaceMenuOpen, kbMenuOpen]);++ // ── Attachment helpers ────────────────────────────────────────+ const showAttachmentError = useCallback((message: string) => {+ setAttachmentError(message);+ if (attachmentErrorTimer.current) {+ clearTimeout(attachmentErrorTimer.current);+ }+ attachmentErrorTimer.current = setTimeout(() => {+ setAttachmentError(null);+ attachmentErrorTimer.current = null;+ }, 4000);+ }, []);++ const fileToAttachment = useCallback(+ (f: File): Promise<PendingAttachment> =>+ new Promise((resolve, reject) => {+ readFileAsDataUrl(f)+ .then((raw) => {+ const svg = isSvgFilename(f.name) || f.type === "image/svg+xml";+ const isImage = !svg && f.type.startsWith("image/");+ const b64 = extractBase64FromDataUrl(raw);+ resolve({+ type: isImage ? "image" : "file",+ filename: f.name,+ base64: b64,+ previewUrl: isImage || svg ? raw : undefined,+ size: f.size,+ mimeType: f.type || undefined,+ });+ })+ .catch(reject);+ }),+ [],+ );++ const filterAndReportFiles = useCallback(+ (files: File[]): File[] => {+ let runningTotal = attachments.reduce((s, a) => s + (a.size ?? 0), 0);+ const accepted: File[] = [];+ const rejected: {+ name: string;+ reason: "unsupported" | "too_large" | "quota";+ }[] = [];+ for (const f of files) {+ const kind = classifyFile(f);+ if (!kind) {+ rejected.push({ name: f.name, reason: "unsupported" });+ continue;+ }+ if (f.size > MAX_ATTACHMENT_BYTES) {+ rejected.push({ name: f.name, reason: "too_large" });+ continue;+ }+ if (runningTotal + f.size > MAX_TOTAL_ATTACHMENT_BYTES) {+ rejected.push({ name: f.name, reason: "quota" });+ break;+ }+ runningTotal += f.size;+ accepted.push(f);+ }+ if (rejected.length) {+ const first = rejected[0];+ let msg: string;+ if (first.reason === "too_large") {+ msg = t("File too large: {{name}}", { name: first.name });+ } else if (first.reason === "quota") {+ msg = t("Too many files, skipped some");+ } else {+ msg = t("Unsupported file type: {{name}}", { name: first.name });+ }+ showAttachmentError(msg);+ }+ return accepted;+ },+ [attachments, showAttachmentError, t],+ );++ const handleAddFiles = useCallback(+ async (files: File[]) => {+ const accepted = filterAndReportFiles(files);+ if (!accepted.length) return;+ const next = await Promise.all(accepted.map(fileToAttachment));+ setAttachments((prev) => [...prev, ...next]);+ },+ [fileToAttachment, filterAndReportFiles],+ );++ const removeAttachment = useCallback((index: number) => {+ setAttachments((prev) => prev.filter((_, i) => i !== index));+ }, []);++ const handlePaste = useCallback(+ async (event: React.ClipboardEvent) => {+ const items = Array.from(event.clipboardData.items);+ const files = items+ .filter((item) => item.kind === "file")+ .map((item) => item.getAsFile())+ .filter((f): f is File => f !== null);+ const accepted = filterAndReportFiles(files);+ if (!accepted.length) return;+ event.preventDefault();+ const next = await Promise.all(accepted.map(fileToAttachment));+ setAttachments((prev) => [...prev, ...next]);+ },+ [fileToAttachment, filterAndReportFiles],+ );++ // ── Drag-and-drop on the composer surface ─────────────────────+ const handleDragEnter = useCallback((e: React.DragEvent) => {+ e.preventDefault();+ e.stopPropagation();+ dragCounter.current += 1;+ if (e.dataTransfer.types.includes("Files")) setDragging(true);+ }, []);+ const handleDragLeave = useCallback((e: React.DragEvent) => {+ e.preventDefault();+ e.stopPropagation();+ dragCounter.current -= 1;+ if (dragCounter.current <= 0) {+ dragCounter.current = 0;+ setDragging(false);+ }+ }, []);+ const handleDragOver = useCallback((e: React.DragEvent) => {+ e.preventDefault();+ e.stopPropagation();+ }, []);+ const handleDrop = useCallback(+ async (e: React.DragEvent) => {+ e.preventDefault();+ e.stopPropagation();+ dragCounter.current = 0;+ setDragging(false);+ const files = Array.from(e.dataTransfer.files);+ await handleAddFiles(files);+ },+ [handleAddFiles],+ );++ // ── Picker handlers ───────────────────────────────────────────+ const handleToggleKB = useCallback((name: string) => {+ setSelectedKnowledgeBases((prev) =>+ prev.includes(name) ? prev.filter((kb) => kb !== name) : [...prev, name],+ );+ }, []);++ const handleSelectNotebookPicker = useCallback(() => {+ setShowNotebookPicker(true);+ }, []);+ const handleSelectBookPicker = useCallback(() => {+ setShowBookPicker(true);+ }, []);+ const handleSelectHistoryPicker = useCallback(() => {+ setShowHistoryPicker(true);+ }, []);+ const handleSelectQuestionBankPicker = useCallback(() => {+ setShowQuestionBankPicker(true);+ }, []);+ const handleSelectSkillsPicker = useCallback(() => {+ setShowSkillsPicker(true);+ }, []);+ const handleSelectMemoryPicker = useCallback(() => {+ setShowMemoryPicker(true);+ }, []);++ const handleToggleSkill = useCallback((skill: string) => {+ setSelectedSkills((prev) =>+ prev.includes(skill) ? prev.filter((s) => s !== skill) : [...prev, skill],+ );+ }, []);+ const handleSetSkillsAuto = useCallback((auto: boolean) => {+ setSkillsAutoMode(auto);+ if (auto) setSelectedSkills([]);+ }, []);+ const handleToggleMemoryFile = useCallback((file: SpaceMemoryFile) => {+ setSelectedMemoryFiles((prev) =>+ prev.includes(file) ? prev.filter((f) => f !== file) : [...prev, file],+ );+ }, []);++ const handleRemoveHistory = useCallback((sessionId: string) => {+ setSelectedHistorySessions((prev) =>+ prev.filter((s) => s.sessionId !== sessionId),+ );+ }, []);+ const handleRemoveBookReference = useCallback((bookId: string) => {+ setSelectedBookReferences((prev) => prev.filter((b) => b.bookId !== bookId));+ }, []);+ const handleRemoveNotebook = useCallback((notebookId: string) => {+ setSelectedNotebookRecords((prev) =>+ prev.filter((r) => r.notebookId !== notebookId),+ );+ }, []);+ const handleRemoveQuestion = useCallback((entryId: number) => {+ setSelectedQuestionEntries((prev) => prev.filter((e) => e.id !== entryId));+ }, []);++ // ── References payloads ───────────────────────────────────────+ const notebookReferencesPayload = useMemo(() => {+ const grouped = new Map<string, string[]>();+ selectedNotebookRecords.forEach((record) => {+ const current = grouped.get(record.notebookId) || [];+ current.push(record.id);+ grouped.set(record.notebookId, current);+ });+ return Array.from(grouped.entries()).map(([notebook_id, record_ids]) => ({+ notebook_id,+ record_ids,+ }));+ }, [selectedNotebookRecords]);+ const bookReferencesPayload = useMemo(+ () => selectedBooksToPayload(selectedBookReferences),+ [selectedBookReferences],+ );+ const historyReferencesPayload = useMemo(+ () => selectedHistorySessions.map((s) => s.sessionId),+ [selectedHistorySessions],+ );+ const questionNotebookReferencesPayload = useMemo(+ () => selectedQuestionEntries.map((entry) => entry.id),+ [selectedQuestionEntries],+ );+ const memoryReferencesPayload = useMemo(+ () => [...selectedMemoryFiles],+ [selectedMemoryFiles],+ );+ const notebookReferenceGroups = useMemo(() => {+ return notebookReferencesPayload.map((ref) => {+ const sample = selectedNotebookRecords.find(+ (r) => r.notebookId === ref.notebook_id,+ );+ return {+ notebookId: ref.notebook_id,+ notebookName: sample?.notebookName ?? ref.notebook_id,+ count: ref.record_ids.length,+ };+ });+ }, [notebookReferencesPayload, selectedNotebookRecords]);++ // Once the user has clicked Send we wipe transient selections — the+ // follow-up chat session has captured them and later turns ride on+ // server-side memory, mirroring the main chat behavior.+ const handleSend = useCallback(+ (content: string) => {+ const hasContent = content.trim().length > 0;+ const hasReferences =+ attachments.length > 0 ||+ selectedKnowledgeBases.length > 0 ||+ selectedBookReferences.length > 0 ||+ selectedNotebookRecords.length > 0 ||+ selectedHistorySessions.length > 0 ||+ selectedQuestionEntries.length > 0 ||+ selectedSkills.length > 0 ||+ skillsAutoMode ||+ selectedMemoryFiles.length > 0;+ if (!hasContent && !hasReferences) return;+ if (thread.isStreaming) return;++ const isFirstSend =+ !thread.sessionId && thread.messages.length === 0;+ const answerImageAttachments = isFirstSend+ ? context.answerImages+ .map((image) => {+ if (image.base64) {+ return {+ type: "image",+ base64: image.base64,+ filename: image.filename,+ mime_type: image.mime,+ } as const;+ }+ if (image.url) {+ return {+ type: "image",+ url: image.url,+ filename: image.filename,+ mime_type: image.mime,+ } as const;+ }+ return null;+ })+ .filter(+ (entry): entry is NonNullable<typeof entry> => entry !== null,+ )+ : [];++ const composerAttachments = attachments.map((a) => ({+ type: a.type,+ filename: a.filename,+ base64: a.base64,+ mime_type: a.mimeType,+ }));++ const skillsPayload = skillsAutoMode+ ? ["auto"]+ : [...selectedSkills];++ const baseConfig = buildQuizFollowupConfig(+ context.question,+ context.userAnswer,+ context.isCorrect,+ context.parentQuizSessionId,+ {+ userAnswerImageFilenames: context.answerImages.map(+ (image) => image.filename,+ ),+ aiJudgment: context.aiJudgment,+ },+ );++ // Memory references ride on ``config`` — same convention as the+ // main chat sendMessage path.+ const config: Record<string, unknown> = { ...baseConfig };+ if (memoryReferencesPayload.length > 0) {+ config.memory_references = memoryReferencesPayload;+ }++ controller.sendMessage({+ questionKey: context.questionKey,+ content,+ attachments: [...answerImageAttachments, ...composerAttachments],+ config,+ language: context.language,+ knowledgeBases: selectedKnowledgeBases,+ notebookReferences: notebookReferencesPayload,+ historyReferences: historyReferencesPayload,+ bookReferences: bookReferencesPayload,+ questionNotebookReferences: questionNotebookReferencesPayload,+ skills: skillsPayload,+ llmSelection,+ });++ // Wipe transient selections — the chat session now owns them.+ setAttachments([]);+ setSelectedBookReferences([]);+ setSelectedNotebookRecords([]);+ setSelectedHistorySessions([]);+ setSelectedQuestionEntries([]);+ setSelectedSkills([]);+ setSkillsAutoMode(false);+ setSelectedMemoryFiles([]);+ },+ [+ attachments,+ bookReferencesPayload,+ context,+ controller,+ historyReferencesPayload,+ llmSelection,+ memoryReferencesPayload,+ notebookReferencesPayload,+ questionNotebookReferencesPayload,+ selectedBookReferences.length,+ selectedHistorySessions.length,+ selectedKnowledgeBases,+ selectedMemoryFiles,+ selectedNotebookRecords.length,+ selectedQuestionEntries.length,+ selectedSkills,+ skillsAutoMode,+ thread.isStreaming,+ thread.messages.length,+ thread.sessionId,+ ],+ );++ const handleCancelStreaming = useCallback(() => {+ // The follow-up runner is owned by the controller; we don't expose+ // a hard cancel from the public surface. Treat this as a no-op for+ // now — the user can refresh or close the tab to recover.+ }, []);++ // ── Active capability is always "chat" for follow-up ──────────+ const FOLLOWUP_CAPABILITIES = useMemo(+ () =>+ FOLLOWUP_CAPABILITIES_RAW.map((cap) => ({+ ...cap,+ label: t(cap.label),+ description: t(cap.description),+ })),+ [t],+ );+ const activeCap = FOLLOWUP_CAPABILITIES[0];++ return (+ <>+ <ChatComposer+ composerRef={composerRef}+ capMenuRef={capMenuRef}+ capBtnRef={capBtnRef}+ spaceMenuRef={spaceMenuRef}+ spaceBtnRef={spaceBtnRef}+ kbMenuRef={kbMenuRef}+ kbBtnRef={kbBtnRef}+ dragCounter={dragCounter}+ dragging={dragging}+ capMenuOpen={capMenuOpen}+ spaceMenuOpen={spaceMenuOpen}+ kbMenuOpen={kbMenuOpen}+ hasMessages={+ thread.messages.filter((m) => m.role !== "system").length > 0+ }+ attachments={attachments}+ attachmentError={attachmentError}+ activeCap={activeCap}+ knowledgeBases={knowledgeBases}+ llmOptions={llmOptions}+ activeLLMDefault={activeLLMDefault}+ llmSelection={llmSelection}+ llmOptionsLoading={llmOptionsLoading}+ llmOptionsError={llmOptionsError}+ selectedBookReferences={selectedBookReferences}+ selectedNotebookRecords={selectedNotebookRecords}+ selectedHistorySessions={selectedHistorySessions}+ selectedQuestionEntries={selectedQuestionEntries}+ notebookReferenceGroups={notebookReferenceGroups}+ selectedSkills={selectedSkills}+ skillsAutoMode={skillsAutoMode}+ selectedMemoryFiles={selectedMemoryFiles}+ selectedKnowledgeBases={selectedKnowledgeBases}+ isStreaming={thread.isStreaming}+ isVisualizeMode={false}+ capabilityNeedsConfig={false}+ capabilityConfigConfirmed={true}+ onRequestConfigConfirm={() => {}}+ capabilities={FOLLOWUP_CAPABILITIES}+ onSetCapMenuOpen={setCapMenuOpen}+ onSetSpaceMenuOpen={setSpaceMenuOpen}+ onSetKbMenuOpen={setKbMenuOpen}+ onToggleKB={handleToggleKB}+ onSelectLLM={setLLMSelection}+ onSelectNotebookPicker={handleSelectNotebookPicker}+ onSelectBookPicker={handleSelectBookPicker}+ onSelectHistoryPicker={handleSelectHistoryPicker}+ onSelectQuestionBankPicker={handleSelectQuestionBankPicker}+ onSelectSkillsPicker={handleSelectSkillsPicker}+ onSelectMemoryPicker={handleSelectMemoryPicker}+ onToggleSkill={handleToggleSkill}+ onSetSkillsAuto={handleSetSkillsAuto}+ onToggleMemoryFile={handleToggleMemoryFile}+ onSend={handleSend}+ onRemoveAttachment={removeAttachment}+ onRemoveHistory={handleRemoveHistory}+ onRemoveBookReference={handleRemoveBookReference}+ onRemoveNotebook={handleRemoveNotebook}+ onRemoveQuestion={handleRemoveQuestion}+ onDragEnter={handleDragEnter}+ onDragLeave={handleDragLeave}+ onDragOver={handleDragOver}+ onDrop={handleDrop}+ onPaste={handlePaste}+ onAddFiles={handleAddFiles}+ onSelectCapability={() => {}}+ onCancelStreaming={handleCancelStreaming}+ inputPlaceholder={t(+ "Ask anything about this question, your answer, or the AI judgment.",+ )}+ />++ <NotebookRecordPicker+ open={showNotebookPicker}+ onClose={() => setShowNotebookPicker(false)}+ onApply={(records: SelectedRecord[]) => {+ setSelectedNotebookRecords(records);+ setShowNotebookPicker(false);+ }}+ />+ <BookReferencePicker+ open={showBookPicker}+ initialReferences={selectedBookReferences}+ onClose={() => setShowBookPicker(false)}+ onApply={(refs: SelectedBookReference[]) => {+ setSelectedBookReferences(refs);+ setShowBookPicker(false);+ }}+ />+ <HistorySessionPicker+ open={showHistoryPicker}+ onClose={() => setShowHistoryPicker(false)}+ onApply={(sessions: SelectedHistorySession[]) => {+ setSelectedHistorySessions(sessions);+ setShowHistoryPicker(false);+ }}+ />+ <QuestionBankPicker+ open={showQuestionBankPicker}+ onClose={() => setShowQuestionBankPicker(false)}+ onApply={(entries: SelectedQuestionEntry[]) => {+ setSelectedQuestionEntries(entries);+ setShowQuestionBankPicker(false);+ }}+ />+ <SkillsPicker+ open={showSkillsPicker}+ initialAuto={skillsAutoMode}+ initialSkills={selectedSkills}+ onClose={() => setShowSkillsPicker(false)}+ onApply={(selection: { auto: boolean; skills: string[] }) => {+ setSkillsAutoMode(selection.auto);+ setSelectedSkills(selection.auto ? [] : selection.skills);+ setShowSkillsPicker(false);+ }}+ />+ <MemoryPicker+ open={showMemoryPicker}+ initialFiles={selectedMemoryFiles}+ onClose={() => setShowMemoryPicker(false)}+ onApply={(files: SpaceMemoryFile[]) => {+ setSelectedMemoryFiles(files);+ setShowMemoryPicker(false);+ }}+ />+ </>+ );+}++const FollowupChatComposer = memo(FollowupChatComposerImpl);+export default FollowupChatComposer;++export type { FollowupChatComposerProps };diff --git a/web/components/quiz/QuestionFollowupPanel.tsx b/web/components/quiz/QuestionFollowupPanel.tsxdeleted file mode 100644index 92288e7ab..000000000--- a/web/components/quiz/QuestionFollowupPanel.tsx+++ /dev/null@@ -1,185 +0,0 @@-"use client";--import {- ChevronDown,- Loader2,- MessageSquarePlus,- SendHorizonal,- Sparkles,-} from "lucide-react";-import { useTranslation } from "react-i18next";-import MarkdownRenderer from "@/components/common/MarkdownRenderer";-import type { QuizQuestion } from "@/lib/quiz-types";--export interface FollowupMessage {- role: "user" | "assistant" | "system";- content: string;-}--export interface FollowupThreadState {- isOpen: boolean;- input: string;- isStreaming: boolean;- currentStage: string;- sessionId: string | null;- activeTurnId: string | null;- messages: FollowupMessage[];- error: string | null;-}--interface QuestionFollowupPanelProps {- question: QuizQuestion;- questionNumber: number;- thread: FollowupThreadState;- onToggle: () => void;- onInputChange: (value: string) => void;- onSend: () => void;-}--function titleCase(value: string) {- return value- .replaceAll("_", " ")- .replace(/\b\w/g, (char) => char.toUpperCase());-}--export default function QuestionFollowupPanel({- question,- questionNumber,- thread,- onToggle,- onInputChange,- onSend,-}: QuestionFollowupPanelProps) {- const { t } = useTranslation();- const visibleMessages = thread.messages.filter(- (message) => message.role !== "system",- );-- return (- <div className="border-t border-[var(--border)] bg-[var(--card)]/30 px-3 py-2">- <div className="overflow-hidden rounded-lg border border-[var(--border)]/80 bg-[var(--background)]/88 shadow-[0_1px_2px_rgba(0,0,0,0.02)]">- <button- onClick={onToggle}- className="flex w-full items-center justify-between gap-3 px-3 py-2 text-left transition-colors hover:bg-[var(--muted)]/14"- >- <div className="min-w-0 flex items-center gap-2 text-[12px] font-medium text-[var(--foreground)]">- <MessageSquarePlus size={13} className="text-[var(--primary)]" />- <span>{t("Follow-up Chat")}</span>- </div>- <div className="ml-auto flex min-w-0 items-center gap-1.5">- <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] uppercase tracking-[0.08em] text-[var(--muted-foreground)]">- Q{questionNumber}- </span>- {question.question_type && (- <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] uppercase tracking-[0.08em] text-[var(--muted-foreground)]">- {question.question_type}- </span>- )}- {question.difficulty && (- <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] uppercase tracking-[0.08em] text-[var(--muted-foreground)]">- {question.difficulty}- </span>- )}- {thread.isStreaming && (- <Loader2- size={11}- className="animate-spin text-[var(--primary)]"- />- )}- <ChevronDown- size={14}- className={`shrink-0 text-[var(--muted-foreground)] transition-transform ${- thread.isOpen ? "rotate-180" : ""- }`}- />- </div>- </button>-- {thread.isOpen && (- <>- <div className="max-h-[220px] space-y-2 overflow-y-auto border-t border-[var(--border)]/60 px-3 py-2.5">- {visibleMessages.length === 0 ? (- <div className="rounded-md border border-dashed border-[var(--border)]/80 bg-[var(--muted)]/14 px-3 py-2.5 text-[12px] leading-[1.55] text-[var(--muted-foreground)]">- <div className="mb-1 flex items-center gap-1.5 font-medium text-[var(--foreground)]">- <Sparkles size={11} className="text-[var(--primary)]" />- {t("Ask anything about this question")}- </div>- <div>- {t(- "Try: why this answer is correct, where your reasoning went wrong, or ask for a cleaner explanation.",- )}- </div>- </div>- ) : (- visibleMessages.map((message, index) => (- <div- key={`${message.role}-${index}`}- className={- message.role === "user"- ? "flex justify-end"- : "flex justify-start"- }- >- <div- className={`max-w-[88%] rounded-[16px] px-3 py-2 text-[13px] leading-[1.7] ${- message.role === "user"- ? "rounded-br-md bg-[var(--primary)] text-white shadow-[0_1px_2px_rgba(0,0,0,0.04)]"- : "rounded-bl-md border border-[var(--border)]/80 bg-[var(--card)] text-[var(--foreground)]"- }`}- >- {message.role === "assistant" ? (- <MarkdownRenderer- content={message.content}- variant="compact"- />- ) : (- <div className="whitespace-pre-wrap break-words">- {message.content}- </div>- )}- </div>- </div>- ))- )}- </div>-- <div className="border-t border-[var(--border)]/70 bg-[var(--card)]/45 px-3 py-2">- {thread.currentStage && thread.isStreaming && (- <div className="mb-1 text-[10px] text-[var(--muted-foreground)]">- {titleCase(thread.currentStage)}...- </div>- )}- {thread.error && (- <div className="mb-1 rounded-md border border-red-200 bg-red-50 px-2 py-1 text-[10px] text-red-700 dark:border-red-950/50 dark:bg-red-950/20 dark:text-red-300">- {thread.error}- </div>- )}- <div className="flex items-end gap-1.5">- <textarea- value={thread.input}- onChange={(event) => onInputChange(event.target.value)}- rows={2}- disabled={thread.isStreaming}- placeholder={t("Ask a follow-up question about this item...")}- className="min-h-[56px] flex-1 resize-none rounded-md border border-[var(--border)]/80 bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors placeholder:text-[var(--muted-foreground)] focus:border-[var(--primary)]/35"- />- <button- onClick={onSend}- disabled={!thread.input.trim() || thread.isStreaming}- className="inline-flex h-9 shrink-0 items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 text-[12px] font-medium text-white transition-opacity disabled:opacity-35"- >- {thread.isStreaming ? (- <Loader2 size={11} className="animate-spin" />- ) : (- <SendHorizonal size={11} />- )}- {t("Send")}- </button>- </div>- </div>- </>- )}- </div>- </div>- );-}diff --git a/web/components/quiz/QuizConfigPanel.tsx b/web/components/quiz/QuizConfigPanel.tsxindex ddce98268..85fa56ab9 100644--- a/web/components/quiz/QuizConfigPanel.tsx+++ b/web/components/quiz/QuizConfigPanel.tsx@@ -1,13 +1,27 @@"use client";-import { memo, useRef, useState } from "react";-import { FileText, Upload, X } from "lucide-react";+import {+ memo,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { createPortal } from "react-dom";+import { Check, ChevronDown, FileText, Upload, X } from "lucide-react";import { useTranslation } from "react-i18next";import {summarizeQuizConfig,+ QUIZ_TYPE_LABEL_KEYS,type DeepQuestionFormConfig,type DeepQuestionMode,} from "@/lib/quiz-types";+import {+ QUIZ_QUESTION_TYPES,+ type NormalizedQuizQuestionType,+} from "@/lib/quiz-question-type";import {CollapsibleConfigSection,Field,@@ -29,6 +43,62 @@ interface QuizConfigPanelProps {onToggleCollapsed?: () => void;}+// Per-type accent colors. Used both for the filled segment background and+// for the legend dot. Kept inline so Tailwind's JIT picks each class up —+// do NOT compose at runtime.+const TYPE_ACCENT: Record<+ NormalizedQuizQuestionType,+ { fill: string; dot: string }+> = {+ choice: { fill: "bg-orange-500", dot: "bg-orange-500" },+ concept: { fill: "bg-emerald-500", dot: "bg-emerald-500" },+ fill_in_blank: { fill: "bg-sky-500", dot: "bg-sky-500" },+ short_answer: { fill: "bg-violet-500", dot: "bg-violet-500" },+ written: { fill: "bg-rose-500", dot: "bg-rose-500" },+ coding: { fill: "bg-slate-500", dot: "bg-slate-500" },+};++/**+ * Re-distribute the total quiz count across the selected types. Each+ * selected type gets at least 1; remainder lands on the first types in+ * ``types`` order. Existing counts in ``prev`` are preserved when their+ * sum already matches; otherwise we rebuild a clean equal split.+ */+function rebalanceCounts(+ types: NormalizedQuizQuestionType[],+ total: number,+ prev: Partial<Record<NormalizedQuizQuestionType, number>>,+): Partial<Record<NormalizedQuizQuestionType, number>> {+ if (types.length < 2) return {};+ const safeTotal = Math.max(types.length, total);+ // Try to preserve user-set counts if they still sum to safeTotal and+ // each is ≥ 1.+ const preserved: Record<string, number> = {};+ let preservedSum = 0;+ let preservedValid = true;+ for (const t of types) {+ const v = prev[t];+ if (typeof v !== "number" || !Number.isFinite(v) || v < 1) {+ preservedValid = false;+ break;+ }+ preserved[t] = Math.floor(v);+ preservedSum += preserved[t];+ }+ if (preservedValid && preservedSum === safeTotal) {+ return preserved as Partial<Record<NormalizedQuizQuestionType, number>>;+ }+ // Equal split with remainder.+ const base = Math.floor(safeTotal / types.length);+ let remainder = safeTotal - base * types.length;+ const out: Record<string, number> = {};+ for (const t of types) {+ out[t] = base + (remainder > 0 ? 1 : 0);+ if (remainder > 0) remainder -= 1;+ }+ return out as Partial<Record<NormalizedQuizQuestionType, number>>;+}+export default memo(function QuizConfigPanel({value,onChange,@@ -48,15 +118,62 @@ export default memo(function QuizConfigPanel({const setMode = (m: DeepQuestionMode) => update("mode", m);+ // Whenever the selected-type set or the total count drifts out of sync+ // with per_type_counts, auto-rebalance so the user never sees a broken+ // intermediate state.+ useEffect(() => {+ if (value.mode !== "custom") return;+ if (value.question_types.length < 2) {+ if (Object.keys(value.per_type_counts).length > 0) {+ onChange({ ...value, per_type_counts: {} });+ }+ return;+ }+ // If the user picks more types than num_questions allows, bump the+ // total so each type can get at least 1.+ let total = value.num_questions;+ if (total < value.question_types.length) {+ total = value.question_types.length;+ }+ const next = rebalanceCounts(+ value.question_types,+ total,+ value.per_type_counts,+ );+ const sameTotal = total === value.num_questions;+ const sameCounts =+ Object.keys(next).length === Object.keys(value.per_type_counts).length &&+ Object.entries(next).every(+ ([k, v]) =>+ value.per_type_counts[k as NormalizedQuizQuestionType] === v,+ );+ if (sameTotal && sameCounts) return;+ onChange({ ...value, num_questions: total, per_type_counts: next });+ }, [value, onChange]);++ const handleTypesChange = (next: NormalizedQuizQuestionType[]) =>+ onChange({ ...value, question_types: next });++ const handleCountsChange = (+ next: Partial<Record<NormalizedQuizQuestionType, number>>,+ ) => onChange({ ...value, per_type_counts: next });++ const showRatioBar =+ value.mode === "custom" && value.question_types.length >= 2;++ const totalCount = value.question_types+ .map((t_) => value.per_type_counts[t_] ?? 0)+ .reduce((sum, n) => sum + n, 0);+const body = (<>- <div className="inline-flex rounded-lg border border-[var(--border)]/25 p-0.5">+ <div className="grid w-full grid-cols-2 gap-1 rounded-lg border border-[var(--border)]/25 p-0.5">{(["custom", "mimic"] as const).map((m) => (<buttonkey={m}type="button"onClick={() => setMode(m)}- className={`rounded-md px-3 py-1 text-[11px] font-medium transition-all ${+ className={`flex h-[26px] items-center justify-center rounded-md text-[11px] font-medium transition-all ${value.mode === m? "bg-[var(--muted)] text-[var(--foreground)] shadow-sm": "text-[var(--muted-foreground)]/50 hover:text-[var(--muted-foreground)]"@@ -68,58 +185,79 @@ export default memo(function QuizConfigPanel({</div>{value.mode === "custom" ? (- <div className="flex flex-wrap items-end gap-x-3 gap-y-2">- <Field label={t("Count")} width="w-[60px]">- <input- type="number"- min={1}- max={50}- value={value.num_questions}- onChange={(e) =>- update(- "num_questions",- Math.max(1, Number(e.target.value) || 1),- )- }- className={`${INPUT_CLS} w-full`}- />- </Field>+ <div className="space-y-2.5">+ <div className="flex items-end gap-x-2">+ <Field label={t("Count")} width="w-[60px]">+ <input+ type="number"+ min={1}+ max={50}+ value={value.num_questions}+ onChange={(e) =>+ update(+ "num_questions",+ Math.max(1, Number(e.target.value) || 1),+ )+ }+ className={`${INPUT_CLS} w-full`}+ />+ </Field>- <Field label={t("Difficulty")} width="w-[100px]">- <select- value={value.difficulty}- onChange={(e) => update("difficulty", e.target.value)}- className={`${INPUT_CLS} w-full`}- >- <option value="auto">{t("Auto")}</option>- <option value="easy">{t("Easy")}</option>- <option value="medium">{t("Medium")}</option>- <option value="hard">{t("Hard")}</option>- </select>- </Field>+ <Field label={t("Difficulty")} width="flex-1">+ <select+ value={value.difficulty}+ onChange={(e) => update("difficulty", e.target.value)}+ className={`${INPUT_CLS} w-full`}+ >+ <option value="auto">{t("Auto")}</option>+ <option value="easy">{t("Easy")}</option>+ <option value="medium">{t("Medium")}</option>+ <option value="hard">{t("Hard")}</option>+ </select>+ </Field>- <Field label={t("Type")} width="w-[110px]">- <select- value={value.question_type}- onChange={(e) => update("question_type", e.target.value)}- className={`${INPUT_CLS} w-full`}- >- <option value="auto">{t("Auto")}</option>- <option value="choice">{t("Multiple Choice")}</option>- <option value="written">{t("Written")}</option>- <option value="coding">{t("Coding")}</option>- </select>- </Field>+ <Field label={t("Type")} width="flex-1">+ <TypeMultiSelect+ value={value.question_types}+ onChange={handleTypesChange}+ />+ </Field>+ </div>- <Field label={t("Preference")} width="min-w-[140px] flex-1">- <input- type="text"- value={value.preference}- onChange={(e) => update("preference", e.target.value)}- placeholder={t("Extra constraints...")}- className={`${INPUT_CLS} w-full`}- />- </Field>+ {showRatioBar && (+ <div className="rounded-lg border border-[var(--border)]/30 bg-[var(--background)]/40 p-2.5">+ <div className="mb-1.5 flex items-center justify-between text-[10px] font-medium text-[var(--muted-foreground)]/60">+ <span>{t("Type Mix")}</span>+ <span className="tabular-nums">+ {totalCount}/{value.num_questions}+ </span>+ </div>+ <DraggableRatioBar+ types={value.question_types}+ counts={value.per_type_counts}+ total={value.num_questions}+ onChange={handleCountsChange}+ />+ <div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-[var(--muted-foreground)]">+ {value.question_types.map((qt) => {+ const count = value.per_type_counts[qt] ?? 0;+ return (+ <span key={qt} className="inline-flex items-center gap-1.5">+ <span+ className={`h-2 w-2 shrink-0 rounded-full ${TYPE_ACCENT[qt].dot}`}+ />+ <span className="text-[var(--foreground)]">+ {t(QUIZ_TYPE_LABEL_KEYS[qt])}+ </span>+ <span className="font-semibold tabular-nums text-[var(--foreground)]">+ {count}+ </span>+ </span>+ );+ })}+ </div>+ </div>+ )}</div>) : (<div className="flex flex-wrap items-end gap-x-3 gap-y-2">@@ -232,3 +370,385 @@ export default memo(function QuizConfigPanel({</CollapsibleConfigSection>);});++// ---------------------------------------------------------------------------+// Type multi-select dropdown+// ---------------------------------------------------------------------------++interface TypeMultiSelectProps {+ value: NormalizedQuizQuestionType[];+ onChange: (next: NormalizedQuizQuestionType[]) => void;+}++function TypeMultiSelect({ value, onChange }: TypeMultiSelectProps) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const triggerRef = useRef<HTMLButtonElement>(null);+ const menuRef = useRef<HTMLDivElement>(null);+ // Position of the portal-rendered menu. Computed from the trigger's+ // bounding rect — the menu is rendered into document.body via portal+ // so the parent card's ``overflow-hidden`` doesn't clip it.+ // Position of the portal-rendered menu. We anchor the menu to the+ // trigger's **right** edge (so a wider menu grows leftward into the+ // panel rather than off the viewport) and flip the vertical anchor+ // up vs. down based on remaining space.+ const [menuPos, setMenuPos] = useState<{+ rightCss: number;+ triggerWidth: number;+ triggerRightX: number;+ direction: "down" | "up";+ anchorOffset: number;+ } | null>(null);++ const recomputePosition = useCallback(() => {+ const trigger = triggerRef.current;+ if (!trigger) return;+ const rect = trigger.getBoundingClientRect();+ const viewportH = window.innerHeight;+ const viewportW = window.innerWidth;+ const menuMaxH = 260;+ const spacing = 4;+ const spaceBelow = viewportH - rect.bottom - spacing;+ const spaceAbove = rect.top - spacing;+ // Flip up only when there's clearly not enough room below AND there+ // is more room above. Otherwise stay anchored down.+ const direction: "down" | "up" =+ spaceBelow >= menuMaxH || spaceBelow >= spaceAbove ? "down" : "up";+ setMenuPos({+ rightCss: Math.max(0, viewportW - rect.right),+ triggerWidth: rect.width,+ triggerRightX: rect.right,+ direction,+ anchorOffset:+ direction === "down"+ ? rect.bottom + spacing+ : viewportH - rect.top + spacing,+ });+ }, []);++ // Open/close: when the menu is open, listen for outside clicks+ // (mousedown on something outside both the trigger and the menu) and+ // for viewport changes that would move the trigger relative to the+ // page, so the portal-rendered menu follows.+ useLayoutEffect(() => {+ if (!open) {+ setMenuPos(null);+ return;+ }+ recomputePosition();+ }, [open, recomputePosition]);++ useEffect(() => {+ if (!open) return;+ function onPointer(e: MouseEvent) {+ const target = e.target as Node | null;+ if (!target) return;+ if (+ triggerRef.current?.contains(target) ||+ menuRef.current?.contains(target)+ ) {+ return;+ }+ setOpen(false);+ }+ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") setOpen(false);+ }+ function onReflow() {+ recomputePosition();+ }+ document.addEventListener("mousedown", onPointer);+ document.addEventListener("keydown", onKey);+ window.addEventListener("scroll", onReflow, true);+ window.addEventListener("resize", onReflow);+ return () => {+ document.removeEventListener("mousedown", onPointer);+ document.removeEventListener("keydown", onKey);+ window.removeEventListener("scroll", onReflow, true);+ window.removeEventListener("resize", onReflow);+ };+ }, [open, recomputePosition]);++ const summary = useMemo(() => {+ if (value.length === 0) return t("Auto");+ if (value.length === 1) return t(QUIZ_TYPE_LABEL_KEYS[value[0]]);+ return `${value.length} ${t("types")}`;+ }, [value, t]);++ // Full list of selected types — surfaced as a native title tooltip on+ // the trigger so the user can see exactly which types are picked when+ // the summary collapses to "N types" (or even just truncates a single+ // long label).+ const triggerTooltip = useMemo(() => {+ if (value.length === 0) return t("Auto");+ return value.map((qt) => t(QUIZ_TYPE_LABEL_KEYS[qt])).join(", ");+ }, [value, t]);++ const toggle = (qt: NormalizedQuizQuestionType | null) => {+ // null = the "Auto" entry — clears the selection.+ if (qt === null) {+ if (value.length === 0) return;+ onChange([]);+ return;+ }+ const has = value.includes(qt);+ onChange(has ? value.filter((x) => x !== qt) : [...value, qt]);+ };++ const menu =+ open && menuPos && typeof document !== "undefined"+ ? createPortal(+ <div+ ref={menuRef}+ style={{+ position: "fixed",+ top:+ menuPos.direction === "down" ? menuPos.anchorOffset : undefined,+ bottom:+ menuPos.direction === "up" ? menuPos.anchorOffset : undefined,+ // Anchor to the trigger's right edge — the menu grows+ // leftward into the panel so long English labels never+ // push it off the viewport.+ right: menuPos.rightCss,+ // Let the menu grow past the (narrow) trigger button so+ // long English labels like "Fill in the Blank" don't get+ // ellipsized. The leftward growth is capped to whatever+ // viewport space exists to the left of the trigger's+ // right edge (minus a small breathing margin).+ minWidth: menuPos.triggerWidth,+ maxWidth: Math.min(+ 240,+ Math.max(menuPos.triggerWidth, menuPos.triggerRightX - 8),+ ),+ maxHeight: 260,+ zIndex: 1000,+ }}+ className="overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--card)] py-1 shadow-lg"+ >+ <DropdownRow+ label={t("Auto")}+ active={value.length === 0}+ onClick={() => toggle(null)}+ />+ <div className="my-1 h-px bg-[var(--border)]/40" />+ {QUIZ_QUESTION_TYPES.map((qt) => (+ <DropdownRow+ key={qt}+ label={t(QUIZ_TYPE_LABEL_KEYS[qt])}+ active={value.includes(qt)}+ dotClass={TYPE_ACCENT[qt].dot}+ onClick={() => toggle(qt)}+ />+ ))}+ </div>,+ document.body,+ )+ : null;++ return (+ <>+ <button+ ref={triggerRef}+ type="button"+ title={triggerTooltip}+ onClick={() => setOpen((o) => !o)}+ className={`${INPUT_CLS} flex w-full items-center justify-between gap-1`}+ >+ <span className="min-w-0 truncate text-left">{summary}</span>+ <ChevronDown+ size={12}+ className={`shrink-0 text-[var(--muted-foreground)]/60 transition-transform ${+ open ? "rotate-180" : ""+ }`}+ />+ </button>+ {menu}+ </>+ );+}++function DropdownRow({+ label,+ active,+ dotClass,+ onClick,+}: {+ label: string;+ active: boolean;+ dotClass?: string;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ title={label}+ className="flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"+ >+ <span+ className={`flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-sm border ${+ active+ ? "border-[var(--primary)] bg-[var(--primary)] text-white"+ : "border-[var(--border)] bg-transparent"+ }`}+ >+ {active ? <Check size={9} strokeWidth={3} /> : null}+ </span>+ {dotClass ? (+ <span className={`h-2 w-2 shrink-0 rounded-full ${dotClass}`} />+ ) : null}+ <span className="min-w-0 flex-1 truncate">{label}</span>+ </button>+ );+}++// ---------------------------------------------------------------------------+// Draggable ratio bar+// ---------------------------------------------------------------------------++interface DraggableRatioBarProps {+ types: NormalizedQuizQuestionType[];+ counts: Partial<Record<NormalizedQuizQuestionType, number>>;+ total: number;+ onChange: (next: Partial<Record<NormalizedQuizQuestionType, number>>) => void;+}++function DraggableRatioBar({+ types,+ counts,+ total,+ onChange,+}: DraggableRatioBarProps) {+ const barRef = useRef<HTMLDivElement>(null);+ // Snapshot of the drag start: which boundary, the pointer x at start,+ // and the counts at start. We compute deltas off the snapshot rather+ // than the live counts so a drag is one atomic gesture.+ const dragRef = useRef<{+ boundaryIdx: number;+ startX: number;+ startCounts: Record<NormalizedQuizQuestionType, number>;+ } | null>(null);++ const safeTotal = Math.max(total, types.length);++ // Cumulative percentage at the right edge of each segment, used to+ // position the drag handles and segment widths.+ const widthsPct = useMemo(+ () => types.map((qt) => ((counts[qt] ?? 0) / safeTotal) * 100),+ [types, counts, safeTotal],+ );+ const cumulativePct = useMemo(() => {+ const out: number[] = [];+ let running = 0;+ for (const w of widthsPct) {+ running += w;+ out.push(running);+ }+ return out;+ }, [widthsPct]);++ const handleBoundaryPointerDown = useCallback(+ (boundaryIdx: number) => (e: React.PointerEvent) => {+ if (!barRef.current) return;+ e.preventDefault();+ e.stopPropagation();+ (e.currentTarget as Element).setPointerCapture(e.pointerId);+ const snapshot: Record<NormalizedQuizQuestionType, number> = {} as Record<+ NormalizedQuizQuestionType,+ number+ >;+ for (const qt of types) {+ snapshot[qt] = counts[qt] ?? 0;+ }+ dragRef.current = {+ boundaryIdx,+ startX: e.clientX,+ startCounts: snapshot,+ };+ },+ [counts, types],+ );++ const handlePointerMove = useCallback(+ (e: React.PointerEvent) => {+ const drag = dragRef.current;+ if (!drag || !barRef.current) return;+ const rect = barRef.current.getBoundingClientRect();+ if (rect.width <= 0) return;+ const pxPerUnit = rect.width / safeTotal;+ const rawDelta = e.clientX - drag.startX;+ let deltaUnits = Math.round(rawDelta / pxPerUnit);+ if (deltaUnits === 0) return;++ const leftType = types[drag.boundaryIdx];+ const rightType = types[drag.boundaryIdx + 1];+ const leftStart = drag.startCounts[leftType] ?? 1;+ const rightStart = drag.startCounts[rightType] ?? 1;++ // Clamp so neither side drops below 1.+ if (leftStart + deltaUnits < 1) deltaUnits = 1 - leftStart;+ if (rightStart - deltaUnits < 1) deltaUnits = rightStart - 1;+ if (deltaUnits === 0) return;++ const next: Record<string, number> = { ...drag.startCounts };+ next[leftType] = leftStart + deltaUnits;+ next[rightType] = rightStart - deltaUnits;+ onChange(next as Partial<Record<NormalizedQuizQuestionType, number>>);+ },+ [onChange, safeTotal, types],+ );++ const handlePointerUp = useCallback((e: React.PointerEvent) => {+ dragRef.current = null;+ try {+ (e.currentTarget as Element).releasePointerCapture(e.pointerId);+ } catch {+ /* pointer may already be released */+ }+ }, []);++ return (+ <div+ ref={barRef}+ className="relative flex h-9 w-full select-none overflow-hidden rounded-md bg-[var(--muted)]/30"+ >+ {types.map((qt) => {+ const count = counts[qt] ?? 0;+ const widthPct = (count / safeTotal) * 100;+ // Hide the inline count label once the segment is too narrow to+ // fit it cleanly — the legend below the bar still has it.+ const showCount = widthPct >= 12;+ return (+ <div+ key={qt}+ style={{ width: `${widthPct}%` }}+ className={`flex h-full items-center justify-center ${TYPE_ACCENT[qt].fill} text-[12px] font-semibold text-white tabular-nums transition-[width] duration-150`}+ >+ {showCount ? count : null}+ </div>+ );+ })}+ {/* Drag handles for each interior boundary. Wider hit area than+ the visible line so the cursor doesn't fall off easily. */}+ {types.slice(0, -1).map((qt, i) => {+ const leftPct = cumulativePct[i];+ return (+ <div+ key={`boundary-${qt}`}+ role="separator"+ aria-orientation="vertical"+ aria-label="Drag to adjust ratio"+ style={{ left: `${leftPct}%` }}+ onPointerDown={handleBoundaryPointerDown(i)}+ onPointerMove={handlePointerMove}+ onPointerUp={handlePointerUp}+ onPointerCancel={handlePointerUp}+ className="absolute top-0 z-10 flex h-full w-3 -translate-x-1/2 cursor-ew-resize items-center justify-center"+ >+ <span className="h-4 w-[3px] rounded-full bg-white/85 shadow-[0_0_0_1px_rgba(0,0,0,0.08)]" />+ </div>+ );+ })}+ </div>+ );+}diff --git a/web/components/quiz/QuizFollowupTabBody.tsx b/web/components/quiz/QuizFollowupTabBody.tsxnew file mode 100644index 000000000..a9daafea5--- /dev/null+++ b/web/components/quiz/QuizFollowupTabBody.tsx@@ -0,0 +1,328 @@+"use client";++/**+ * QuizFollowupTabBody — chat-page-like surface that lives inside a+ * SessionViewerPanel tab. Dedicated to one quiz question and runs the+ * full ``chat`` capability against a session pinned to that question.+ *+ * Layout: pinned context cards (question / your answer / AI judgment) →+ * scrollable chat thread → ``FollowupChatComposer`` (same chrome as the+ * main chat composer).+ *+ * State is owned by ``QuizFollowupProvider`` so closing/reopening the+ * tab — or toggling questions inside QuizViewer — keeps the thread+ * intact and is reflected in the QuizViewer follow-up badge.+ */++import { useEffect, useMemo, useRef } from "react";+import { Sparkles } from "lucide-react";+import { useTranslation } from "react-i18next";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import FollowupChatComposer from "@/components/quiz/FollowupChatComposer";+import {+ AskUserOptions,+ extractMessageSegments,+} from "@/components/chat/home/AskUserOptions";+import { TraceSurface } from "@/components/chat/home/TracePanels";+import {+ type QuizFollowupTabContext,+ useFollowupThread,+ useQuizFollowupController,+} from "@/context/QuizFollowupContext";+import { apiUrl } from "@/lib/api";+import { getSession } from "@/lib/session-api";++/** Resolve a possibly-relative AttachmentStore URL to an absolute one. */+function resolveImageSrc(url: string | null | undefined): string {+ if (!url) return "";+ if (/^(https?:|data:|blob:)/i.test(url)) return url;+ return apiUrl(url);+}++interface QuizFollowupTabBodyProps {+ context: QuizFollowupTabContext;+}++export default function QuizFollowupTabBody({+ context,+}: QuizFollowupTabBodyProps) {+ const { t } = useTranslation();+ const controller = useQuizFollowupController();+ const thread = useFollowupThread(context.questionKey);+ const threadEndRef = useRef<HTMLDivElement | null>(null);++ useEffect(() => {+ threadEndRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });+ }, [thread.messages, thread.isStreaming]);++ // Hydrate prior chat history when the tab opens and the notebook+ // entry has a persisted ``followup_session_id``. Skipped when the+ // in-memory thread is already populated (page reload while the+ // controller still holds state, or the user toggles the tab).+ useEffect(() => {+ const followupSessionId = context.followupSessionId;+ if (!followupSessionId) return;+ if (thread.messages.length > 0 || thread.sessionId) return;+ let cancelled = false;+ const run = async () => {+ try {+ const detail = await getSession(followupSessionId);+ if (cancelled || !detail) return;+ const hydrated = (detail.messages ?? []).map((m) => ({+ role: m.role,+ content: m.content || "",+ events: m.events ?? [],+ }));+ controller.hydrateThread(+ context.questionKey,+ followupSessionId,+ hydrated,+ );+ } catch {+ /* best-effort — leave the thread empty so the user can re-ask */+ }+ };+ void run();+ return () => {+ cancelled = true;+ };+ }, [+ context.followupSessionId,+ context.questionKey,+ controller,+ thread.messages.length,+ thread.sessionId,+ ]);++ const visibleMessages = thread.messages.filter((m) => m.role !== "system");+ const isCoding = context.question.question_type === "coding";++ return (+ <div className="flex h-full flex-col bg-[var(--card)]">+ {/* Header strip — mimics a chat-page title bar but with quiz crumbs. */}+ <div className="flex shrink-0 items-center gap-2 border-b border-[var(--border)]/40 bg-[var(--card)] px-4 py-2.5">+ <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-[var(--primary)]/12">+ <Sparkles+ size={14}+ strokeWidth={1.7}+ className="text-[var(--primary)]"+ />+ </div>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[12.5px] font-semibold text-[var(--foreground)]">+ {context.tabLabel}+ </div>+ <div className="truncate text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Follow-up Chat")}+ {context.question.question_type+ ? ` · ${context.question.question_type}`+ : ""}+ </div>+ </div>+ </div>++ {/* Scrollable body: pinned context + chat thread. */}+ <div className="flex-1 overflow-y-auto px-4 py-3">+ <div className="mx-auto flex max-w-[640px] flex-col gap-3">+ <div className="rounded-md border border-[var(--border)]/70 bg-[var(--background)]/70 px-3 py-2">+ <div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">+ {t("Question")}+ </div>+ <div className="text-[13px] leading-relaxed text-[var(--foreground)]">+ <MarkdownRenderer+ content={context.question.question}+ variant="compact"+ />+ </div>+ </div>++ <div className="rounded-md border border-[var(--border)]/70 bg-[var(--background)]/70 px-3 py-2">+ <div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">+ {t("Your Answer")}+ </div>+ {context.userAnswer ? (+ <div className="text-[13px] leading-relaxed text-[var(--foreground)]">+ <MarkdownRenderer+ content={+ isCoding && !context.userAnswer.trimStart().startsWith("```")+ ? `\`\`\`python\n${context.userAnswer}\n\`\`\``+ : context.userAnswer+ }+ variant="compact"+ />+ </div>+ ) : context.answerImages.length === 0 ? (+ <div className="text-[12px] italic text-[var(--muted-foreground)]">+ {t("No answer recorded.")}+ </div>+ ) : null}+ {context.answerImages.length > 0 && (+ <div className="mt-2 grid grid-cols-3 gap-2 sm:grid-cols-4 md:grid-cols-5">+ {context.answerImages.map((image) => {+ const src = image.previewUrl ?? resolveImageSrc(image.url);+ return (+ <div+ key={image.id}+ className="overflow-hidden rounded-md border border-[var(--border)] bg-[var(--card)]"+ >+ {src ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={src}+ alt={image.filename}+ className="h-16 w-full object-cover"+ />+ ) : (+ <div className="flex h-16 w-full items-center justify-center text-[10px] text-[var(--muted-foreground)]">+ {image.filename}+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>++ {context.aiJudgment && (+ <div className="rounded-md border border-[var(--primary)]/30 bg-[var(--primary)]/[0.04] px-3 py-2">+ <div className="mb-1 flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--primary)]">+ <Sparkles size={10} />+ {t("AI Judgment")}+ </div>+ <div className="text-[12.5px] leading-relaxed text-[var(--foreground)]">+ <MarkdownRenderer+ content={context.aiJudgment}+ variant="compact"+ />+ </div>+ </div>+ )}++ <div className="flex flex-col gap-3 py-1">+ {visibleMessages.length === 0 ? (+ <div className="rounded-md border border-dashed border-[var(--border)] bg-[var(--background)]/40 px-3 py-3 text-[12px] text-[var(--muted-foreground)]">+ {t(+ "Ask anything about this question, your answer, or the AI judgment.",+ )}+ </div>+ ) : (+ visibleMessages.map((message, index) => {+ if (message.role === "user") {+ return (+ <div+ key={`user-${index}`}+ className="flex justify-end"+ >+ <div className="max-w-[88%] whitespace-pre-wrap break-words rounded-[14px] rounded-br-md bg-[var(--primary)] px-3 py-2 text-[13px] leading-[1.6] text-[var(--primary-foreground)]">+ {message.content}+ </div>+ </div>+ );+ }+ // Assistant message: render the same TraceSurface the+ // main chat uses (reasoning blocks, tool-call cards,+ // streaming-status row) followed by the message body. If+ // the turn paused on ``ask_user``, splice the picker card+ // into the body in stream order — text emitted before the+ // pause sits above the card, text from the resumed+ // iteration sits below.+ const isLast = index === visibleMessages.length - 1;+ const isStreamingThis = isLast && thread.isStreaming;+ return (+ <AssistantThreadMessage+ key={`assistant-${index}`}+ message={message}+ isStreaming={isStreamingThis}+ onSubmitUserReply={(reply) =>+ controller.submitAskUserReply(+ context.questionKey,+ reply,+ )+ }+ />+ );+ })+ )}+ {thread.error && (+ <div className="rounded-md border border-red-200 bg-red-50 px-2 py-1 text-[11px] text-red-700 dark:border-red-950/50 dark:bg-red-950/20 dark:text-red-300">+ {thread.error}+ </div>+ )}+ <div ref={threadEndRef} />+ </div>+ </div>+ </div>++ {/* Composer — the same ChatComposer used on the main chat page,+ wired through FollowupChatComposer to route sends into the+ QuizFollowupController and keep its own state pool. */}+ <div className="shrink-0 border-t border-[var(--border)]/50 bg-[var(--card)] px-4 pt-3">+ <FollowupChatComposer context={context} />+ </div>+ </div>+ );+}++/**+ * Per-assistant-message renderer for the follow-up thread. Splits the+ * event stream into ordered text + ``ask_user`` segments so the picker+ * card lives inline with the surrounding narration — mirroring the+ * default chat surface's behaviour from ``ChatMessages``.+ */+function AssistantThreadMessage({+ message,+ isStreaming,+ onSubmitUserReply,+}: {+ message: {+ role: "user" | "assistant" | "system";+ content: string;+ events?: import("@/lib/unified-ws").StreamEvent[];+ };+ isStreaming: boolean;+ onSubmitUserReply: (reply: {+ text?: string;+ answers?: Array<{ questionId: string; text: string }>;+ }) => void;+}) {+ const segments = useMemo(+ () => extractMessageSegments(message.events),+ [message.events],+ );+ const hasInlineAskUser = segments.some((s) => s.kind === "ask_user");++ return (+ <div className="flex flex-col gap-1.5">+ <TraceSurface+ events={message.events ?? []}+ isStreaming={isStreaming}+ content={message.content}+ />+ {hasInlineAskUser ? (+ segments.map((seg) =>+ seg.kind === "text" ? (+ seg.text ? (+ <div+ key={seg.key}+ className="text-[13px] leading-[1.6] text-[var(--foreground)]"+ >+ <MarkdownRenderer content={seg.text} variant="compact" />+ </div>+ ) : null+ ) : (+ <AskUserOptions+ key={seg.key}+ data={seg.data}+ onSubmit={onSubmitUserReply}+ />+ ),+ )+ ) : message.content ? (+ <div className="text-[13px] leading-[1.6] text-[var(--foreground)]">+ <MarkdownRenderer content={message.content} variant="compact" />+ </div>+ ) : null}+ </div>+ );+}diff --git a/web/components/quiz/QuizViewer.tsx b/web/components/quiz/QuizViewer.tsxindex 1d824b715..08d1544ad 100644--- a/web/components/quiz/QuizViewer.tsx+++ b/web/components/quiz/QuizViewer.tsx@@ -1,6 +1,13 @@"use client";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ type ChangeEvent,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";import {Bookmark,Check,@@ -9,20 +16,33 @@ import {ChevronRight,Eye,FolderPlus,+ ImagePlus,Loader2,+ MessageSquarePlus,Plus,RotateCcw,+ Sparkles,+ X,} from "lucide-react";import { useTranslation } from "react-i18next";import MarkdownRenderer from "@/components/common/MarkdownRenderer";-import QuestionFollowupPanel, {- type FollowupThreadState,-} from "@/components/quiz/QuestionFollowupPanel";+import {+ useAllFollowupThreads,+ useQuizFollowupController,+} from "@/context/QuizFollowupContext";import {isChoiceQuizQuestion,+ isConceptQuizQuestion,+ isFillInBlankQuizQuestion,resolveChoiceAnswerKey,+ resolveConceptAnswer,} from "@/lib/quiz-question-type";-import { buildQuizFollowupConfig, type QuizQuestion } from "@/lib/quiz-types";+import {+ readFileAsBase64,+ startQuizJudge,+ type QuizJudgeHandle,+} from "@/lib/quiz-judge";+import { type QuizQuestion } from "@/lib/quiz-types";import {addEntryToCategory,createCategory,@@ -33,56 +53,117 @@ import {type NotebookCategory,} from "@/lib/notebook-api";import { recordQuizResults } from "@/lib/session-api";-import { shouldAppendEventContent } from "@/lib/stream";-import {- type StartTurnMessage,- type StreamEvent,- UnifiedWSClient,-} from "@/lib/unified-ws";+import { apiUrl } from "@/lib/api";++/** Resolve a possibly-relative AttachmentStore URL to an absolute one so+ * ``<img src>`` works regardless of the API/frontend port pairing. */+function resolveImageSrc(url: string | null | undefined): string | undefined {+ if (!url) return undefined;+ if (/^(https?:|data:|blob:)/i.test(url)) return url;+ return apiUrl(url);+}interface QuizViewerProps {questions: QuizQuestion[];sessionId?: string | null;+ /**+ * The ``turn_id`` of the assistant turn that produced this quiz. Scopes+ * notebook lookups/upserts so two quizzes generated in the same chat+ * session don't share answer state (see issue #487). When absent, the+ * component falls back to legacy session-wide scoping for backward+ * compatibility with already-persisted entries.+ */+ turnId?: string | null;language?: string;}+type AnswerImage = {+ /**+ * Local-only identifier used to key React lists and to remove a+ * specific image. When the image has been persisted server-side the+ * field is replaced with the stable AttachmentStore id.+ */+ id: string;+ /** Base64 (no ``data:`` prefix) when freshly picked client-side. */+ base64: string | null;+ /** AttachmentStore URL once the upsert response confirms persistence. */+ url: string | null;+ filename: string;+ mime: string;+ /** Blob: URL for the local <img> preview when ``base64`` is present. */+ previewUrl: string | null;+};+type AnswerState = {selected: string | null;typed: string;submitted: boolean;+ images: AnswerImage[];};const EMPTY_ANSWER: AnswerState = {selected: null,typed: "",submitted: false,+ images: [],};-function createEmptyThreadState(): FollowupThreadState {- return {- isOpen: false,- input: "",- isStreaming: false,- currentStage: "",- sessionId: null,- activeTurnId: null,- messages: [],- error: null,- };+function makeAnswerImageId(): string {+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {+ return crypto.randomUUID().replaceAll("-", "").slice(0, 12);+ }+ return Math.random().toString(36).slice(2, 14);}+type JudgmentState = {+ text: string;+ isStreaming: boolean;+ error: string | null;+};++const EMPTY_JUDGMENT: JudgmentState = {+ text: "",+ isStreaming: false,+ error: null,+};++type AnswerView = "reference" | "judgment";+function getQuestionKey(question: QuizQuestion, index: number): string {return question.question_id || `question_${index + 1}`;}-function getUserAnswer(question: QuizQuestion, answer: AnswerState): string {- if (+function isMultipleChoice(question: QuizQuestion): boolean {+ return (isChoiceQuizQuestion(question.question_type) &&- question.options &&+ !!question.options &&Object.keys(question.options).length > 0+ );+}++/**+ * Auto-gradable question types: choice, concept (T/F), fill_in_blank.+ * Open-ended types (short_answer, written, coding) are excluded — their+ * answers are graded by the learner against the reference, not by exact+ * string match.+ */+function isAutoGradable(question: QuizQuestion): boolean {+ return (+ isMultipleChoice(question) ||+ isConceptQuizQuestion(question.question_type) ||+ isFillInBlankQuizQuestion(question.question_type)+ );+}++function getUserAnswer(question: QuizQuestion, answer: AnswerState): string {+ // Choice + concept use the ``selected`` field (option key / "true" / "false").+ if (+ isMultipleChoice(question) ||+ isConceptQuizQuestion(question.question_type)) {return answer.selected ?? "";}+ // Fill-in-blank + free-text types use the typed string.return answer.typed.trim();}@@ -90,11 +171,7 @@ function isAnswerCorrect(question: QuizQuestion, answer: AnswerState): boolean {const userAnswer = getUserAnswer(question, answer);if (!userAnswer) return false;const correct = question.correct_answer.trim();- const isChoice =- isChoiceQuizQuestion(question.question_type) &&- question.options &&- Object.keys(question.options).length > 0;- if (isChoice) {+ if (isMultipleChoice(question)) {const correctChoiceKey = resolveChoiceAnswerKey(correct, question.options);return (userAnswer.toUpperCase() === correctChoiceKey ||@@ -102,28 +179,36 @@ function isAnswerCorrect(question: QuizQuestion, answer: AnswerState): boolean {userAnswer.toUpperCase() === correct.charAt(0).toUpperCase());}+ if (isConceptQuizQuestion(question.question_type)) {+ const correctTF = resolveConceptAnswer(correct);+ return userAnswer.toLowerCase() === correctTF;+ }return userAnswer.toLowerCase() === correct.toLowerCase();}export default function QuizViewer({questions,sessionId,+ turnId,language = "en",}: QuizViewerProps) {const { t } = useTranslation();+ const followupController = useQuizFollowupController();+ // Read all follow-up threads so we can light up the "N messages" badge+ // and the per-chip dot indicator. Owned by QuizFollowupProvider so+ // QuizFollowupTabBody and QuizViewer stay in sync.+ const followupThreads = useAllFollowupThreads();const [idx, setIdx] = useState(0);const [answers, setAnswers] = useState<Record<number, AnswerState>>({});- const [threads, setThreads] = useState<Record<string, FollowupThreadState>>(- {},- );const lastReportedSignatureRef = useRef("");- const threadsRef = useRef<Record<string, FollowupThreadState>>({});- const threadRunnersRef = useRef<- Map<string, { questionKey: string; client: UnifiedWSClient }>- >(new Map());const [entryIds, setEntryIds] = useState<Record<string, number>>({});const [bookmarked, setBookmarked] = useState<Record<string, boolean>>({});+ // Captured from the notebook entry on lookup so QuizFollowupTabBody+ // can hydrate prior chat history when the follow-up tab opens.+ const [followupSessionIds, setFollowupSessionIds] = useState<+ Record<string, string>+ >({});const [categories, setCategories] = useState<NotebookCategory[]>([]);const [categoryDropdownKey, setCategoryDropdownKey] = useState<string | null>(null,@@ -131,31 +216,37 @@ export default function QuizViewer({const [newCategoryName, setNewCategoryName] = useState("");const [categoryBusy, setCategoryBusy] = useState(false);+ const [judgments, setJudgments] = useState<Record<number, JudgmentState>>({});+ const [answerViews, setAnswerViews] = useState<Record<number, AnswerView>>(+ {},+ );+ // Per-question collapsed state for the Reference / Judgment review+ // block. Default: expanded. Persists per question while the QuizViewer+ // instance is alive.+ const [reviewCollapsed, setReviewCollapsed] = useState<+ Record<number, boolean>+ >({});+ const judgeHandlesRef = useRef<Map<number, QuizJudgeHandle>>(new Map());+ const fileInputRef = useRef<HTMLInputElement | null>(null);++ useEffect(+ () => () => {+ judgeHandlesRef.current.forEach((handle) => handle.close());+ judgeHandlesRef.current.clear();+ },+ [],+ );+const q = questions[idx];const ans = answers[idx] ?? EMPTY_ANSWER;const total = questions.length;const navigationProgress = total > 0 ? ((idx + 1) / total) * 100 : 0;const questionKey = q ? getQuestionKey(q, idx) : "";- const thread = questionKey- ? (threads[questionKey] ?? createEmptyThreadState())- : createEmptyThreadState();const completedCount = useMemo(() => Object.values(answers).filter((answer) => answer.submitted).length,[answers],);- useEffect(() => {- threadsRef.current = threads;- }, [threads]);-- useEffect(- () => () => {- threadRunnersRef.current.forEach(({ client }) => client.disconnect());- threadRunnersRef.current.clear();- },- [],- );-const updateAnswer = useCallback((patch: Partial<AnswerState>) =>setAnswers((prev) => ({@@ -165,47 +256,76 @@ export default function QuizViewer({[idx],);- const updateThread = useCallback(- (- key: string,- updater: (prev: FollowupThreadState) => FollowupThreadState,- ) => {- setThreads((prev) => ({- ...prev,- [key]: updater(prev[key] ?? createEmptyThreadState()),- }));- },- [],- );-// ── Notebook integration ──────────────────────────────────────const refreshEntryId = useCallback(async (qKey: string, sId: string, questionIndex?: number) => {try {- const entry = await lookupNotebookEntry(sId, qKey);+ const entry = await lookupNotebookEntry(sId, qKey, turnId);if (entry) {setEntryIds((prev) => ({ ...prev, [qKey]: entry.id }));setBookmarked((prev) => ({ ...prev, [qKey]: entry.bookmarked }));- if (questionIndex !== undefined && entry.user_answer) {+ if (entry.followup_session_id) {+ setFollowupSessionIds((prev) => ({+ ...prev,+ [qKey]: entry.followup_session_id,+ }));+ }+ const persistedImages = (entry.user_answer_images ?? []).map(+ (image) => ({+ id: image.id || makeAnswerImageId(),+ base64: null,+ url: image.url || null,+ filename: image.filename || "answer.png",+ mime: image.mime_type || "image/png",+ previewUrl: null,+ }),+ );+ if (+ questionIndex !== undefined &&+ (entry.user_answer || persistedImages.length > 0)+ ) {setAnswers((prev) => {if (prev[questionIndex]?.submitted) return prev;return {...prev,[questionIndex]: {+ ...EMPTY_ANSWER,selected: entry.user_answer || null,typed: entry.user_answer || "",+ images: persistedImages,submitted: true,},};});}+ // Rehydrate the AI judgment so the learner can keep reading+ // it across page refreshes. We only overwrite when local state+ // is still empty so an in-flight judge run isn't clobbered.+ if (+ questionIndex !== undefined &&+ entry.ai_judgment &&+ entry.ai_judgment.length > 0+ ) {+ setJudgments((prev) => {+ const current = prev[questionIndex];+ if (current?.text || current?.isStreaming) return prev;+ return {+ ...prev,+ [questionIndex]: {+ text: entry.ai_judgment ?? "",+ isStreaming: false,+ error: null,+ },+ };+ });+ }}} catch {/* entry may not exist yet */}},- [],+ [turnId],);useEffect(() => {@@ -284,158 +404,10 @@ export default function QuizViewer({setCategoryBusy(false);}, [entryIds, idx, newCategoryName, q]);- // ── Follow-up thread event handling ───────────────────────────-- const handleThreadEvent = useCallback(- (key: string, event: StreamEvent) => {- if (event.type === "session") {- const metadata = (event.metadata ?? {}) as {- session_id?: string;- turn_id?: string;- };- const nextSessionId = metadata.session_id || event.session_id || "";- const nextTurnId = metadata.turn_id || event.turn_id || null;- if (!nextSessionId) return;- updateThread(key, (prev) => ({- ...prev,- sessionId: nextSessionId,- activeTurnId: nextTurnId,- }));- const runner = threadRunnersRef.current.get(key);- if (runner) runner.questionKey = nextSessionId;- const eId = entryIds[key];- if (eId) {- void updateNotebookEntry(eId, {- followup_session_id: nextSessionId,- }).catch(() => {});- }- return;- }-- if (event.type === "done") {- updateThread(key, (prev) => ({- ...prev,- isStreaming: false,- currentStage: "",- activeTurnId: null,- }));- const runner = threadRunnersRef.current.get(key);- runner?.client.disconnect();- threadRunnersRef.current.delete(key);- return;- }-- updateThread(key, (prev) => {- const next = {- ...prev,- activeTurnId: event.turn_id || prev.activeTurnId,- };- if (event.type === "stage_start") {- next.currentStage = event.stage;- return next;- }- if (event.type === "stage_end") {- next.currentStage = "";- return next;- }- if (event.type === "error") {- next.error = event.content || prev.error;- const terminal = Boolean(- ((event.metadata ?? {}) as { turn_terminal?: boolean })- .turn_terminal,- );- if (terminal) {- next.isStreaming = false;- next.currentStage = "";- next.activeTurnId = null;- }- return next;- }- if (shouldAppendEventContent(event)) {- const messages = [...prev.messages];- const last = messages[messages.length - 1];- if (!last || last.role !== "assistant") {- messages.push({ role: "assistant", content: event.content });- } else {- messages[messages.length - 1] = {- ...last,- content: `${last.content}${event.content}`,- };- }- next.messages = messages;- }- return next;- });- },- [entryIds, updateThread],- );-- const ensureThreadRunner = useCallback(- (key: string) => {- const existing = threadRunnersRef.current.get(key);- if (existing) {- if (!existing.client.connected) existing.client.connect();- return existing;- }- const record = {- questionKey: key,- client: new UnifiedWSClient(- (event) => handleThreadEvent(key, event),- () => {- const current = threadsRef.current[key];- if (current?.isStreaming) {- updateThread(key, (prev) => ({- ...prev,- isStreaming: false,- currentStage: "",- activeTurnId: null,- error:- prev.error ||- "Follow-up chat failed because the connection closed.",- }));- }- },- ),- };- threadRunnersRef.current.set(key, record);- record.client.connect();- return record;- },- [handleThreadEvent, updateThread],- );-- const sendThroughThreadRunner = useCallback(- function sendThroughThreadRunner(- key: string,- message: StartTurnMessage,- attempt = 0,- ) {- const runner = ensureThreadRunner(key);- if (!runner.client.connected) {- if (attempt >= 10) {- updateThread(key, (prev) => ({- ...prev,- isStreaming: false,- currentStage: "",- error: "Follow-up chat failed to connect.",- }));- return;- }- window.setTimeout(- () => sendThroughThreadRunner(key, message, attempt + 1),- 200,- );- return;- }- runner.client.send(message);- },- [ensureThreadRunner, updateThread],- );-- const isChoice =- isChoiceQuizQuestion(q?.question_type) &&- q.options &&- Object.keys(q.options).length > 0;+ const isChoice = q ? isMultipleChoice(q) : false;+ const isConcept = q ? isConceptQuizQuestion(q.question_type) : false;+ const isFillBlank = q ? isFillInBlankQuizQuestion(q.question_type) : false;+ const isGradable = q ? isAutoGradable(q) : false;const currentUserAnswer = q ? getUserAnswer(q, ans) : "";const isCorrect = useMemo(() => {@@ -470,7 +442,7 @@ export default function QuizViewer({const signature = JSON.stringify(submittedResults);if (!signature || signature === lastReportedSignatureRef.current) return;lastReportedSignatureRef.current = signature;- void recordQuizResults(sessionId, submittedResults)+ void recordQuizResults(sessionId, submittedResults, turnId).then(() => {questions.forEach((question, i) => {void refreshEntryId(getQuestionKey(question, i), sessionId);@@ -489,15 +461,28 @@ export default function QuizViewer({sessionId,submittedResults,total,+ turnId,]);const upsertSingleQuestion = useCallback(- async (question: QuizQuestion, answer: AnswerState) => {+ async (+ question: QuizQuestion,+ answer: AnswerState,+ questionIndex: number,+ ) => {if (!sessionId) return;- const key = getQuestionKey(question, questions.indexOf(question));+ const key = getQuestionKey(question, questionIndex);try {+ const imagePayload = answer.images.map((image) => ({+ id: image.id,+ base64: image.base64 ?? undefined,+ url: image.url ?? undefined,+ filename: image.filename,+ mime_type: image.mime,+ }));const entry = await upsertNotebookEntry({session_id: sessionId,+ turn_id: turnId || "",question_id: question.question_id,question: question.question,question_type: question.question_type,@@ -506,86 +491,267 @@ export default function QuizViewer({explanation: question.explanation ?? "",difficulty: question.difficulty ?? "",user_answer: getUserAnswer(question, answer),+ user_answer_images: imagePayload,is_correct: isAnswerCorrect(question, answer),});setEntryIds((prev) => ({ ...prev, [key]: entry.id }));setBookmarked((prev) => ({ ...prev, [key]: entry.bookmarked }));+ // Replace freshly-uploaded ``base64`` images with the+ // AttachmentStore URLs the server hands back, so subsequent+ // upserts don't re-upload the same bytes and the previews can+ // survive a page reload by falling through to ``url``.+ const persisted = entry.user_answer_images ?? [];+ if (persisted.length > 0) {+ setAnswers((prev) => {+ const current = prev[questionIndex];+ if (!current) return prev;+ const byId = new Map(persisted.map((image) => [image.id, image]));+ const nextImages = current.images.map((image) => {+ const match = byId.get(image.id);+ if (!match) return image;+ return {+ ...image,+ url: match.url || image.url,+ // Drop base64 once the server has the bytes.+ base64: null,+ };+ });+ return {+ ...prev,+ [questionIndex]: { ...current, images: nextImages },+ };+ });+ }} catch {/* best-effort */}},- [questions, sessionId],+ [sessionId, turnId],);const handleSubmit = () => {if (ans.submitted || !q) return;const newAnswer = { ...(answers[idx] ?? EMPTY_ANSWER), submitted: true };updateAnswer({ submitted: true });- void upsertSingleQuestion(q, newAnswer);+ void upsertSingleQuestion(q, newAnswer, idx);};const handleReset = () => {+ // Reset typed/selected state but keep an attached image so the learner+ // doesn't have to re-upload it when retrying.updateAnswer({ selected: null, typed: "", submitted: false });+ setJudgments((prev) => {+ const next = { ...prev };+ delete next[idx];+ return next;+ });+ setAnswerViews((prev) => {+ const next = { ...prev };+ delete next[idx];+ return next;+ });+ const existing = judgeHandlesRef.current.get(idx);+ if (existing) {+ existing.close();+ judgeHandlesRef.current.delete(idx);+ }};- const handleToggleFollowup = useCallback(() => {- if (!q) return;- const key = getQuestionKey(q, idx);- updateThread(key, (prev) => ({ ...prev, isOpen: !prev.isOpen }));- }, [idx, q, updateThread]);+ const handlePickImageClick = useCallback(() => {+ fileInputRef.current?.click();+ }, []);- const handleFollowupInputChange = useCallback(- (value: string) => {- if (!q) return;- const key = getQuestionKey(q, idx);- updateThread(key, (prev) => ({ ...prev, input: value }));+ const handleImageChange = useCallback(+ async (event: ChangeEvent<HTMLInputElement>) => {+ const files = Array.from(event.target.files ?? []);+ // Reset the input so re-selecting the same file fires onChange again.+ event.target.value = "";+ if (files.length === 0) return;++ const newImages: AnswerImage[] = [];+ for (const file of files) {+ if (!file.type.startsWith("image/")) continue;+ try {+ const { base64, mime, name } = await readFileAsBase64(file);+ newImages.push({+ id: makeAnswerImageId(),+ base64,+ url: null,+ filename: name,+ mime,+ previewUrl: URL.createObjectURL(file),+ });+ } catch {+ /* skip this file — user can retry */+ }+ }+ if (newImages.length === 0) return;++ const prev = answers[idx] ?? EMPTY_ANSWER;+ updateAnswer({ images: [...prev.images, ...newImages] });},- [idx, q, updateThread],+ [answers, idx, updateAnswer],);- const handleSendFollowup = useCallback(() => {- if (!q) return;- const key = getQuestionKey(q, idx);- const currentThread = threadsRef.current[key] ?? createEmptyThreadState();- const content = currentThread.input.trim();- if (!content || currentThread.isStreaming) return;+ const handleRemoveImage = useCallback(+ (imageId: string) => {+ const prev = answers[idx] ?? EMPTY_ANSWER;+ const remaining: AnswerImage[] = [];+ for (const image of prev.images) {+ if (image.id === imageId) {+ if (image.previewUrl) {+ try {+ URL.revokeObjectURL(image.previewUrl);+ } catch {+ /* ignore */+ }+ }+ continue;+ }+ remaining.push(image);+ }+ updateAnswer({ images: remaining });+ },+ [answers, idx, updateAnswer],+ );+ const handleAiJudge = useCallback(() => {+ if (!q) return;const answer = answers[idx] ?? EMPTY_ANSWER;- const followupConfig = buildQuizFollowupConfig(- q,- getUserAnswer(q, answer),- isAnswerCorrect(q, answer),- sessionId,- );+ const userAnswer = getUserAnswer(q, answer);+ if (!userAnswer && answer.images.length === 0) return;- updateThread(key, (prev) => ({+ // Cancel any in-flight judge for this question before starting a new run.+ const existing = judgeHandlesRef.current.get(idx);+ if (existing) {+ existing.close();+ judgeHandlesRef.current.delete(idx);+ }++ setJudgments((prev) => ({...prev,- isOpen: true,- input: "",- isStreaming: true,- error: null,- messages: [...prev.messages, { role: "user", content }],+ [idx]: { text: "", isStreaming: true, error: null },}));+ setAnswerViews((prev) => ({ ...prev, [idx]: "judgment" }));++ const judgeLanguage: "zh" | "en" = language === "zh" ? "zh" : "en";++ const handle = startQuizJudge(+ {+ question: q.question,+ question_type: q.question_type ?? "",+ options: q.options ?? null,+ correct_answer: q.correct_answer ?? "",+ explanation: q.explanation ?? "",+ user_answer: userAnswer,+ user_answer_images: answer.images.map((image) => ({+ base64: image.base64,+ url: image.url,+ filename: image.filename,+ mime_type: image.mime,+ })),+ language: judgeLanguage,+ },+ {+ onChunk: (chunk) => {+ setJudgments((prev) => {+ const current = prev[idx] ?? EMPTY_JUDGMENT;+ return {+ ...prev,+ [idx]: { ...current, text: current.text + chunk },+ };+ });+ },+ onDone: () => {+ let finalText = "";+ setJudgments((prev) => {+ const current = prev[idx] ?? EMPTY_JUDGMENT;+ finalText = current.text;+ return {+ ...prev,+ [idx]: { ...current, isStreaming: false },+ };+ });+ judgeHandlesRef.current.delete(idx);+ // Persist the AI judgment text on the notebook entry so it+ // survives a page refresh. Best-effort — a failed write just+ // means the next reload won't have the judgment cached.+ const key = q ? getQuestionKey(q, idx) : "";+ const eId = key ? entryIds[key] : undefined;+ if (eId && finalText.trim().length > 0) {+ void updateNotebookEntry(eId, { ai_judgment: finalText }).catch(+ () => {},+ );+ }+ },+ onError: (message) => {+ setJudgments((prev) => {+ const current = prev[idx] ?? EMPTY_JUDGMENT;+ return {+ ...prev,+ [idx]: { ...current, isStreaming: false, error: message },+ };+ });+ judgeHandlesRef.current.delete(idx);+ },+ },+ );+ judgeHandlesRef.current.set(idx, handle);+ }, [answers, entryIds, idx, language, q]);++ const handleToggleAnswerView = useCallback(+ (view: AnswerView) => {+ setAnswerViews((prev) => ({ ...prev, [idx]: view }));+ },+ [idx],+ );++ // ── Follow-up (right-side viewer tab) ─────────────────────────+ //+ // Clicking "Follow-up" no longer expands an in-place panel — it opens+ // a dedicated tab in the SessionViewerPanel on the right, where a+ // chat-page-style UI runs the full ``chat`` capability against a+ // session that pins this question + answer + judgment as fixed+ // context. State for that chat lives in ``QuizFollowupProvider`` so+ // it survives tab toggles and is also reflected in this card's+ // message-count badge.- sendThroughThreadRunner(key, {- type: "start_turn",- content,- tools: [],- capability: "deep_question",- knowledge_bases: [],- session_id: currentThread.sessionId,- attachments: [],+ const handleOpenFollowup = useCallback(() => {+ if (!q) return;+ const key = getQuestionKey(q, idx);+ const answer = answers[idx] ?? EMPTY_ANSWER;+ const judgment = judgments[idx] ?? EMPTY_JUDGMENT;+ followupController.openFollowupTab({+ questionKey: key,+ question: q,+ userAnswer: getUserAnswer(q, answer),+ isCorrect: isAutoGradable(q) ? isAnswerCorrect(q, answer) : null,+ answerImages: answer.images.map((image) => ({+ id: image.id,+ base64: image.base64,+ url: image.url,+ filename: image.filename,+ mime: image.mime,+ previewUrl: image.previewUrl,+ })),+ aiJudgment: judgment.text,+ parentQuizSessionId: sessionId ?? null,+ notebookEntryId: entryIds[key] ?? null,+ followupSessionId: followupSessionIds[key] ?? null,language,- config: followupConfig,+ tabLabel: `Q${idx + 1} · ${t("Follow-up")}`,});}, [answers,+ entryIds,+ followupController,+ followupSessionIds,idx,+ judgments,language,q,- sendThroughThreadRunner,sessionId,- updateThread,+ t,]);if (!q) return null;@@ -596,36 +762,71 @@ export default function QuizViewer({return (<div className="overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--card)]">- <div className="flex items-center gap-1 border-b border-[var(--border)] px-3 py-2">- <span className="mr-2 text-[11px] font-semibold text-[var(--muted-foreground)]">+ <div className="flex items-center gap-2 border-b border-[var(--border)] px-3 py-2">+ <button+ type="button"+ onClick={() => setIdx((value) => Math.max(0, value - 1))}+ disabled={idx === 0}+ title={t("Previous")}+ aria-label={t("Previous")}+ className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--border)] bg-[var(--muted)]/60 text-[var(--foreground)] shadow-sm transition-colors hover:border-[var(--primary)] hover:bg-[var(--primary)]/10 hover:text-[var(--primary)] disabled:cursor-not-allowed disabled:border-[var(--border)] disabled:bg-transparent disabled:text-[var(--muted-foreground)] disabled:opacity-40 disabled:hover:bg-transparent"+ >+ <ChevronLeft size={18} strokeWidth={2.5} />+ </button>+ <span className="text-[11px] font-semibold text-[var(--muted-foreground)]">{completedCount}/{total}</span>- <div className="flex flex-wrap gap-1">+ <div className="flex flex-1 flex-wrap gap-1">{questions.map((question, questionIndex) => {const answer = answers[questionIndex];const isCurrent = questionIndex === idx;const done = answer?.submitted;const hasThread =Boolean(- threads[getQuestionKey(question, questionIndex)]?.sessionId,+ followupThreads[getQuestionKey(question, questionIndex)]+ ?.sessionId,) ||Boolean(- threads[getQuestionKey(question, questionIndex)]?.messages- .length,+ followupThreads[getQuestionKey(question, questionIndex)]+ ?.messages.length,);+ // Color the chip by correctness for auto-gradable types+ // (choice, concept, fill_in_blank). For open-ended types+ // (short_answer / written / coding) we'd be guessing — keep+ // the neutral "completed" tint so we don't mark a thoughtful+ // answer red just because it doesn't match the reference+ // string verbatim.+ const autoGradable = isAutoGradable(question);+ const correctness: "correct" | "incorrect" | null =+ done && answer && autoGradable+ ? isAnswerCorrect(question, answer)+ ? "correct"+ : "incorrect"+ : null;+ const baseChip =+ "flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-semibold transition-all";+ const chipClass = isCurrent+ ? `${baseChip} bg-[var(--primary)] text-white shadow-sm`+ : correctness === "correct"+ ? `${baseChip} bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/40 dark:text-green-300`+ : correctness === "incorrect"+ ? `${baseChip} bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900/40 dark:text-red-300`+ : done+ ? `${baseChip} bg-[var(--primary)]/15 text-[var(--primary)]`+ : `${baseChip} bg-[var(--muted)] text-[var(--muted-foreground)] hover:bg-[var(--border)]`;return (<buttonkey={question.question_id || questionIndex}onClick={() => setIdx(questionIndex)}- className={`flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-semibold transition-all ${- isCurrent- ? "bg-[var(--primary)] text-white shadow-sm"- : done- ? "bg-[var(--primary)]/15 text-[var(--primary)]"- : "bg-[var(--muted)] text-[var(--muted-foreground)] hover:bg-[var(--border)]"- }`}+ className={chipClass}>- {done && !isCurrent ? (+ {/* For graded auto-gradable questions we *replace* the ✓+ with the sequence number — the color is the+ completion signal, and the digit lets the learner+ navigate to a specific question by index. The+ followup-thread dot still rides along when the+ learner asked a follow-up about this question. */}+ {done && !isCurrent && !autoGradable ? (hasThread ? (<span className="relative inline-flex"><Check size={10} />@@ -634,6 +835,11 @@ export default function QuizViewer({) : (<Check size={10} />)+ ) : hasThread && done && !isCurrent ? (+ <span className="relative inline-flex">+ {questionIndex + 1}+ <span className="absolute -right-1 -top-1 h-1.5 w-1.5 rounded-full bg-[var(--primary)]" />+ </span>) : (questionIndex + 1)}@@ -641,6 +847,22 @@ export default function QuizViewer({);})}</div>+ <button+ type="button"+ onClick={() => setIdx((value) => Math.min(total - 1, value + 1))}+ disabled={idx === total - 1}+ title={t("Next")}+ aria-label={t("Next")}+ className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--border)] bg-[var(--muted)]/60 text-[var(--foreground)] shadow-sm transition-colors hover:border-[var(--primary)] hover:bg-[var(--primary)]/10 hover:text-[var(--primary)] disabled:cursor-not-allowed disabled:border-[var(--border)] disabled:bg-transparent disabled:text-[var(--muted-foreground)] disabled:opacity-40 disabled:hover:bg-transparent"+ >+ <ChevronRight size={18} strokeWidth={2.5} />+ </button>+ </div>+ <div className="h-0.5 bg-[var(--muted)]">+ <div+ className="h-full bg-[var(--primary)] transition-all duration-300"+ style={{ width: `${navigationProgress}%` }}+ /></div><div className="px-4 py-3">@@ -693,6 +915,25 @@ export default function QuizViewer({><FolderPlus size={16} /></button>+ <button+ onClick={handleOpenFollowup}+ title={t("Follow-up Chat")}+ className="ml-1 inline-flex items-center gap-1 rounded-lg border border-[var(--primary)]/60 bg-[var(--primary)]/10 px-2 py-1 text-[12px] font-medium text-[var(--primary)] transition-colors hover:bg-[var(--primary)]/15"+ >+ <MessageSquarePlus size={13} />+ {t("Follow-up")}+ {(() => {+ const tcount =+ followupThreads[questionKey]?.messages.filter(+ (m) => m.role !== "system",+ ).length ?? 0;+ return tcount > 0 ? (+ <span className="rounded-full bg-[var(--primary)]/25 px-1.5 py-0 text-[10px]">+ {tcount}+ </span>+ ) : null;+ })()}+ </button>{showCategoryDropdown && (<div className="absolute right-0 top-8 z-20 w-48 rounded-lg border border-[var(--border)] bg-[var(--card)] py-1 shadow-lg">@@ -802,13 +1043,83 @@ export default function QuizViewer({);})}</div>+ ) : isConcept ? (+ // Concept (true/false) — two large buttons.+ (() => {+ const correctTF = resolveConceptAnswer(q.correct_answer);+ const showFeedback = ans.submitted;+ const renderTFButton = (key: "true" | "false", label: string) => {+ const isSelected = ans.selected === key;+ const isCorrect = correctTF === key;+ let cls =+ "border-[var(--border)] bg-[var(--background)] text-[var(--foreground)] hover:border-[var(--primary)]/30";+ if (isSelected && !showFeedback) {+ cls =+ "border-[var(--primary)] bg-[var(--primary)]/[0.08] text-[var(--foreground)] ring-1 ring-[var(--primary)]/25";+ } else if (showFeedback && isCorrect) {+ cls =+ "border-green-500 bg-green-50 text-green-800 dark:bg-green-950/20 dark:text-green-300 dark:border-green-700";+ } else if (showFeedback && isSelected && !isCorrect) {+ cls =+ "border-red-400 bg-red-50 text-red-700 dark:bg-red-950/20 dark:text-red-300 dark:border-red-700";+ }+ return (+ <button+ key={key}+ type="button"+ disabled={ans.submitted}+ onClick={() => updateAnswer({ selected: key })}+ className={`flex flex-1 items-center justify-center gap-2 rounded-lg border px-3 py-3 text-[14px] font-semibold transition-all ${cls}`}+ >+ {label}+ </button>+ );+ };+ return (+ <div className="flex gap-2">+ {renderTFButton("true", t("True"))}+ {renderTFButton("false", t("False"))}+ </div>+ );+ })()+ ) : isFillBlank ? (+ // Fill-in-the-blank — single-line input. The question text+ // already contains the literal ``____`` placeholder which the+ // learner sees in the rendered question above; this is just+ // where they type the missing word/phrase.+ <div>+ <div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]/70">+ {t("Fill in the Blank")}+ </div>+ <input+ type="text"+ value={ans.typed}+ onChange={(event) => updateAnswer({ typed: event.target.value })}+ disabled={ans.submitted}+ placeholder={t("Type your answer...")}+ className={`w-full rounded-lg border px-3 py-2 text-[13px] outline-none transition-colors placeholder:text-[var(--muted-foreground)] ${+ ans.submitted+ ? "border-[var(--border)] bg-[var(--muted)] text-[var(--foreground)]"+ : "border-[var(--border)] bg-[var(--background)] text-[var(--foreground)] focus:border-[var(--primary)]/40"+ }`}+ />+ </div>) : (+ // Free-text branches: short_answer / written / coding.+ // Different default heights so essay-style "written" has more+ // room than a concept-style short answer.<div><textareavalue={ans.typed}onChange={(event) => updateAnswer({ typed: event.target.value })}disabled={ans.submitted}- rows={3}+ rows={+ q.question_type === "coding"+ ? 6+ : q.question_type === "written"+ ? 5+ : 3+ }placeholder={q.question_type === "coding"? t("Write your code here...")@@ -823,11 +1134,87 @@ export default function QuizViewer({</div>)}- <div className="mt-3 flex items-center gap-2">+ {/* Image-as-answer attachment — only offered for question types+ without an auto-gradable answer (short_answer / written /+ coding). These are also the types that benefit most from a+ multimodal AI judgment over handwritten work. */}+ {!isGradable && (+ <div className="mt-2 space-y-2">+ <input+ ref={fileInputRef}+ type="file"+ accept="image/*"+ multiple+ onChange={(event) => void handleImageChange(event)}+ className="hidden"+ />+ {ans.images.length > 0 && (+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 md:grid-cols-4">+ {ans.images.map((image) => {+ const previewSrc =+ image.previewUrl ?? resolveImageSrc(image.url);+ return (+ <div+ key={image.id}+ className="group relative overflow-hidden rounded-md border border-[var(--border)] bg-[var(--background)]"+ >+ {previewSrc ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={previewSrc}+ alt={image.filename}+ className="h-24 w-full object-cover"+ />+ ) : (+ <div className="flex h-24 w-full items-center justify-center text-[10px] text-[var(--muted-foreground)]">+ {image.filename}+ </div>+ )}+ <div className="absolute inset-x-0 bottom-0 truncate bg-black/45 px-1.5 py-0.5 text-[10px] text-white">+ {image.filename}+ </div>+ {!ans.submitted && (+ <button+ type="button"+ onClick={() => handleRemoveImage(image.id)}+ title={t("Remove image")}+ className="absolute right-1 top-1 inline-flex h-5 w-5 items-center justify-center rounded-full bg-black/55 text-white opacity-0 transition-opacity group-hover:opacity-100"+ >+ <X size={11} />+ </button>+ )}+ </div>+ );+ })}+ </div>+ )}+ {!ans.submitted && (+ <button+ type="button"+ onClick={handlePickImageClick}+ className="inline-flex items-center gap-1.5 rounded-md border border-dashed border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)] hover:text-[var(--primary)]"+ >+ <ImagePlus size={13} />+ {ans.images.length === 0+ ? t("Attach an image as your answer")+ : t("Add another image")}+ </button>+ )}+ </div>+ )}++ <div className="mt-3 flex flex-wrap items-center gap-2">{!ans.submitted ? (<buttononClick={handleSubmit}- disabled={isChoice ? !ans.selected : !ans.typed.trim()}+ disabled={(() => {+ if (isChoice || isConcept) return !ans.selected;+ // For free-text / fill-blank, require a typed answer; for+ // non-auto-gradable types, an image attachment also counts.+ if (ans.typed.trim()) return false;+ if (!isGradable && ans.images.length > 0) return false;+ return true;+ })()}className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-white transition-opacity disabled:opacity-30"><Eye size={13} />@@ -835,7 +1222,7 @@ export default function QuizViewer({</button>) : (<>- {isChoice && isCorrect !== null && (+ {isGradable && isCorrect !== null && (<spanclassName={`rounded-md px-2 py-0.5 text-[11px] font-semibold ${isCorrect@@ -853,81 +1240,186 @@ export default function QuizViewer({<RotateCcw size={11} />{t("Retry")}</button>+ {(() => {+ const j = judgments[idx] ?? EMPTY_JUDGMENT;+ const hasJudgment = j.text.length > 0 || j.error !== null;+ return (+ <button+ onClick={handleAiJudge}+ disabled={j.isStreaming}+ className="inline-flex items-center gap-1 rounded-lg border border-[var(--primary)]/60 bg-[var(--primary)]/10 px-2.5 py-1.5 text-[12px] font-medium text-[var(--primary)] transition-colors hover:bg-[var(--primary)]/15 disabled:opacity-50"+ >+ {j.isStreaming ? (+ <Loader2 size={11} className="animate-spin" />+ ) : (+ <Sparkles size={11} />+ )}+ {j.isStreaming+ ? t("Judging...")+ : hasJudgment+ ? t("Re-judge")+ : t("AI Judge")}+ </button>+ );+ })()}</>)}</div>- {ans.submitted && (- <div className="mt-3 space-y-2 rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2.5">- {!isChoice && q.correct_answer && (- <div>- <div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">- {t("Reference Answer")}- </div>- <div className="text-[13px] leading-relaxed text-[var(--foreground)]">- <MarkdownRenderer- content={- q.question_type === "coding" &&- !q.correct_answer.trimStart().startsWith("```")- ? `\`\`\`python\n${q.correct_answer}\n\`\`\``- : q.correct_answer- }- variant="prose"- />- </div>- </div>- )}- {q.explanation && (- <div>- <div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">- {t("Explanation")}- </div>- <div className="text-[13px] leading-relaxed text-[var(--muted-foreground)]">- <MarkdownRenderer content={q.explanation} variant="prose" />- </div>- </div>- )}- </div>- )}- </div>+ {ans.submitted &&+ (() => {+ const judgment = judgments[idx] ?? EMPTY_JUDGMENT;+ const hasJudgment =+ judgment.text.length > 0 ||+ judgment.error !== null ||+ judgment.isStreaming;+ // Default to the reference tab; flip to the judgment tab when+ // the learner first triggers a judge run (set in handleAiJudge).+ const view: AnswerView =+ answerViews[idx] ?? (hasJudgment ? "judgment" : "reference");+ const showReferenceAnswer =+ !isChoice && !isConcept && !!q.correct_answer;+ const showAnyReference = showReferenceAnswer || !!q.explanation;+ if (!showAnyReference && !hasJudgment) return null;- <div className="flex items-center justify-between border-t border-[var(--border)] px-3 py-2">- <button- onClick={() => setIdx((value) => Math.max(0, value - 1))}- disabled={idx === 0}- className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-30"- >- <ChevronLeft size={13} />- {t("Previous")}- </button>+ const collapsed = reviewCollapsed[idx] === true;+ const toggleCollapsed = () =>+ setReviewCollapsed((prev) => ({ ...prev, [idx]: !collapsed }));- <div className="mx-3 h-1 flex-1 overflow-hidden rounded-full bg-[var(--muted)]">- <div- className="h-full rounded-full bg-[var(--primary)] transition-all duration-300"- style={{ width: `${navigationProgress}%` }}- />- </div>+ return (+ <div className="mt-3 space-y-2 rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2.5">+ {/* Header bar — when there's no tab strip (only one of+ reference/judgment is showing) we still render this so+ the collapse chevron has a home. */}+ {hasJudgment && showAnyReference ? (+ <div className="flex items-center gap-1 border-b border-[var(--border)]/70 pb-1.5">+ <button+ type="button"+ onClick={() => handleToggleAnswerView("reference")}+ className={`rounded-md px-2 py-0.5 text-[11px] font-medium transition-colors ${+ view === "reference"+ ? "bg-[var(--primary)]/12 text-[var(--primary)]"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {t("Reference Answer")}+ </button>+ <button+ type="button"+ onClick={() => handleToggleAnswerView("judgment")}+ className={`inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-[11px] font-medium transition-colors ${+ view === "judgment"+ ? "bg-[var(--primary)]/12 text-[var(--primary)]"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ <Sparkles size={10} />+ {t("AI Judgment")}+ {judgment.isStreaming && (+ <Loader2 size={10} className="animate-spin" />+ )}+ </button>+ <button+ type="button"+ onClick={toggleCollapsed}+ aria-label={collapsed ? t("Expand") : t("Collapse")}+ title={collapsed ? t("Expand") : t("Collapse")}+ className="ml-auto inline-flex h-5 w-5 items-center justify-center rounded-md text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <ChevronDown+ size={13}+ className={`transition-transform ${+ collapsed ? "-rotate-90" : ""+ }`}+ />+ </button>+ </div>+ ) : (+ <button+ type="button"+ onClick={toggleCollapsed}+ className="flex w-full items-center gap-1 pb-1.5 text-left"+ >+ <span className="text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">+ {hasJudgment ? t("AI Judgment") : t("Reference Answer")}+ </span>+ <ChevronDown+ size={13}+ className={`ml-auto text-[var(--muted-foreground)] transition-transform ${+ collapsed ? "-rotate-90" : ""+ }`}+ />+ </button>+ )}- <button- onClick={() => setIdx((value) => Math.min(total - 1, value + 1))}- disabled={idx === total - 1}- className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-30"- >- {t("Next")}- <ChevronRight size={13} />- </button>+ {collapsed ? null : hasJudgment && view === "judgment" ? (+ <div>+ <div className="mb-1 flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">+ <Sparkles size={10} />+ {t("AI Judgment")}+ {judgment.isStreaming && (+ <Loader2+ size={10}+ className="animate-spin text-[var(--primary)]"+ />+ )}+ </div>+ {judgment.error ? (+ <div className="rounded-md border border-red-200 bg-red-50 px-2 py-1 text-[12px] text-red-700 dark:border-red-950/50 dark:bg-red-950/20 dark:text-red-300">+ {judgment.error}+ </div>+ ) : judgment.text ? (+ <div className="text-[13px] leading-relaxed text-[var(--foreground)]">+ <MarkdownRenderer+ content={judgment.text}+ variant="prose"+ />+ </div>+ ) : (+ <div className="text-[12px] text-[var(--muted-foreground)]">+ {t("Judging...")}+ </div>+ )}+ </div>+ ) : (+ <>+ {showReferenceAnswer && (+ <div>+ <div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">+ {t("Reference Answer")}+ </div>+ <div className="text-[13px] leading-relaxed text-[var(--foreground)]">+ <MarkdownRenderer+ content={+ q.question_type === "coding" &&+ !q.correct_answer.trimStart().startsWith("```")+ ? `\`\`\`python\n${q.correct_answer}\n\`\`\``+ : q.correct_answer+ }+ variant="prose"+ />+ </div>+ </div>+ )}+ {q.explanation && (+ <div>+ <div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">+ {t("Explanation")}+ </div>+ <div className="text-[13px] leading-relaxed text-[var(--muted-foreground)]">+ <MarkdownRenderer+ content={q.explanation}+ variant="prose"+ />+ </div>+ </div>+ )}+ </>+ )}+ </div>+ );+ })()}</div>-- {ans.submitted && (- <QuestionFollowupPanel- question={q}- questionNumber={idx + 1}- thread={thread}- onToggle={handleToggleFollowup}- onInputChange={handleFollowupInputChange}- onSend={handleSendFollowup}- />- )}</div>);}diff --git a/web/context/GeogebraTabContext.tsx b/web/context/GeogebraTabContext.tsxnew file mode 100644index 000000000..774ad9a0a--- /dev/null+++ b/web/context/GeogebraTabContext.tsx@@ -0,0 +1,89 @@+"use client";++/**+ * GeogebraTabContext — bridges in-message "open in viewer" CTAs to the+ * SessionViewerPanel's imperative ``openGeogebraTab``.+ *+ * Pattern mirrors QuizFollowupContext (but much smaller — no persistent+ * thread state). A CTA inside the markdown renderer calls+ * ``useGeogebraTabOpener()`` and dispatches; the chat page wires the+ * controller's open-handler to the viewer panel ref via+ * ``setOpenHandler``.+ */++import {+ createContext,+ type ReactNode,+ useCallback,+ useContext,+ useMemo,+ useRef,+} from "react";++export interface GeogebraTabPayload {+ /** Stable id for tab dedupe — same script + title should map to same tab. */+ id: string;+ /** Display label on the tab strip. */+ title: string;+ /** Raw ggbscript body (GeoGebra commands, one per line, with optional `#` comments). */+ script: string;+}++export interface GeogebraTabController {+ /** Open or focus a GeoGebra tab in the side viewer. */+ openTab(payload: GeogebraTabPayload): void;+ /** The chat page registers the viewer-panel's ``openGeogebraTab`` here. */+ setOpenHandler(handler: ((payload: GeogebraTabPayload) => void) | null): void;+}++const GeogebraTabCtx = createContext<GeogebraTabController | null>(null);++export function GeogebraTabProvider({ children }: { children: ReactNode }) {+ // The handler is mutable — the chat page can swap it via setOpenHandler+ // without forcing every consumer to re-render. Stored in a ref so the+ // controller object itself stays stable across renders.+ const handlerRef = useRef<((payload: GeogebraTabPayload) => void) | null>(+ null,+ );++ const openTab = useCallback((payload: GeogebraTabPayload) => {+ const handler = handlerRef.current;+ if (handler) {+ handler(payload);+ } else {+ // No viewer registered yet (or page hasn't mounted the bridge). The+ // CTA click is a no-op rather than throwing; the user can retry once+ // the viewer is available.+ console.warn(+ "[GeogebraTabContext] No open handler registered; ignoring openTab()",+ );+ }+ }, []);++ const setOpenHandler = useCallback(+ (handler: ((payload: GeogebraTabPayload) => void) | null) => {+ handlerRef.current = handler;+ },+ [],+ );++ const controller = useMemo<GeogebraTabController>(+ () => ({ openTab, setOpenHandler }),+ [openTab, setOpenHandler],+ );++ return (+ <GeogebraTabCtx.Provider value={controller}>+ {children}+ </GeogebraTabCtx.Provider>+ );+}++/**+ * Hook for descendants that need to open a GeoGebra tab. Returns ``null``+ * when no provider is mounted — callers should treat that as "feature+ * unavailable" and degrade gracefully (e.g. don't render the CTA at all).+ */+export function useGeogebraTabOpener(): GeogebraTabController | null {+ return useContext(GeogebraTabCtx);+}diff --git a/web/context/QuizFollowupContext.tsx b/web/context/QuizFollowupContext.tsxnew file mode 100644index 000000000..bfff662a7--- /dev/null+++ b/web/context/QuizFollowupContext.tsx@@ -0,0 +1,573 @@+"use client";++/**+ * QuizFollowupContext — owns the per-question follow-up chat state+ * (messages, sessionId, streaming flags) and the WS runners that drive it.+ *+ * Lifted out of QuizViewer so the same thread can be read from:+ * • the quiz card itself (for the "follow-up has N messages" badge), and+ * • the SessionViewerPanel's quiz-followup tab body, where the actual+ * chat now happens.+ *+ * The provider also exposes ``openFollowupTab`` which forwards to whichever+ * SessionViewerPanel has registered itself via ``setOpenTabHandler`` — i.e.+ * the chat page wires the viewer panel's imperative ``openQuizFollowupTab``+ * method through this context so QuizViewer (a descendant of ChatMessages)+ * doesn't need to drill the ref through several layers of props.+ */++import {+ type ReactNode,+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { updateNotebookEntry } from "@/lib/notebook-api";+import { shouldAppendEventContent } from "@/lib/stream";+import { hasPendingAskUser } from "@/lib/ask-user-state";+import {+ type ChatMessage,+ type LLMSelection,+ type StreamEvent,+ UnifiedWSClient,+} from "@/lib/unified-ws";+import type { QuizQuestion } from "@/lib/quiz-types";++export interface FollowupMessage {+ role: "user" | "assistant" | "system";+ content: string;+ /**+ * Stream events that produced this message (assistant turns only).+ * Keeping the full event log on the assistant message lets the+ * follow-up tab render the same ``TraceSurface`` the main chat uses —+ * reasoning blocks, tool calls, stage transitions, etc.+ */+ events?: StreamEvent[];+}++export interface FollowupThreadState {+ isOpen: boolean;+ input: string;+ isStreaming: boolean;+ currentStage: string;+ sessionId: string | null;+ activeTurnId: string | null;+ messages: FollowupMessage[];+ error: string | null;+}++export function createEmptyThreadState(): FollowupThreadState {+ return {+ isOpen: false,+ input: "",+ isStreaming: false,+ currentStage: "",+ sessionId: null,+ activeTurnId: null,+ messages: [],+ error: null,+ };+}++/** Snapshot of the question + answer + judgment that a follow-up tab pins. */+export interface QuizFollowupTabContext {+ /** Stable key for the question — same key used by ``threads``. */+ questionKey: string;+ question: QuizQuestion;+ /** Plain-text user answer the learner submitted. */+ userAnswer: string;+ /** True / false / null (open-ended). */+ isCorrect: boolean | null;+ /** Image attachments associated with the answer (multi-image supported). */+ answerImages: Array<{+ id: string;+ base64: string | null;+ url: string | null;+ filename: string;+ mime: string;+ previewUrl?: string | null;+ }>;+ /** Latest AI judgment text (empty when never run). */+ aiJudgment: string;+ /** Parent quiz session id — passed through to the followup_question_context. */+ parentQuizSessionId: string | null;+ /** Notebook entry id for ``followup_session_id`` persistence. */+ notebookEntryId: number | null;+ /**+ * Persisted follow-up session id from the notebook entry, if any. When+ * non-null the tab body restores prior chat history from the backend on+ * mount instead of starting a fresh thread.+ */+ followupSessionId: string | null;+ /** UI language ("zh" / "en") for the conversation. */+ language: string;+ /** Short label for the tab strip, e.g. "Q1 follow-up". */+ tabLabel: string;+}++export interface SendMessageInput {+ questionKey: string;+ content: string;+ /** Files / images / docs the user is attaching to this turn. */+ attachments: Array<{+ type: string;+ base64?: string;+ url?: string;+ filename?: string;+ mime_type?: string;+ }>;+ config?: Record<string, unknown>;+ language?: string;+ /** Selected knowledge bases (names) for this turn. */+ knowledgeBases?: string[];+ /** Notebook/book/history/question/skill references — same shape the+ * main ChatPage builds for ``sendMessage``. */+ notebookReferences?: { notebook_id: string; record_ids: string[] }[];+ historyReferences?: string[];+ bookReferences?: { book_id: string; page_ids: string[] }[];+ questionNotebookReferences?: number[];+ skills?: string[];+ /** Pinned LLM selection — when null/undefined the server default applies. */+ llmSelection?: LLMSelection | null;+}++export interface HydratedFollowupMessage {+ role: "user" | "assistant" | "system";+ content: string;+ events?: StreamEvent[];+}++export interface QuizFollowupController {+ /** Returns the current thread snapshot for a question (or an empty one). */+ getThread(questionKey: string): FollowupThreadState;+ /** Patch a thread's state; merges into the existing entry. */+ updateThread(+ questionKey: string,+ updater: (prev: FollowupThreadState) => FollowupThreadState,+ ): void;+ /**+ * Hydrate a thread from previously-persisted messages (e.g. from+ * ``getSession()``). No-op when the thread already has messages — we+ * never overwrite live state with a stale snapshot.+ */+ hydrateThread(+ questionKey: string,+ sessionId: string,+ messages: HydratedFollowupMessage[],+ ): void;+ /** Send a user turn through the chat capability for this question. */+ sendMessage(input: SendMessageInput): void;+ /**+ * Deliver an answer for a turn paused on ``ask_user``. Mirrors the main+ * chat's ``submitUserReply`` — sends a same-turn ``submit_user_reply``+ * over the existing runner so the agent loop resumes without spawning a+ * new user bubble. Accepts either a flat ``text`` string (legacy+ * single-question) or a structured ``{text?, answers[]}`` (v2 path).+ */+ submitAskUserReply(+ questionKey: string,+ reply:+ | string+ | { text?: string; answers?: Array<{ questionId: string; text: string }> },+ ): void;+ /** Tab open helper — forwards to whoever registered an open handler. */+ openFollowupTab(context: QuizFollowupTabContext): void;+ /**+ * Wire up the SessionViewerPanel's imperative ``openQuizFollowupTab``.+ * Called once by the chat page after it acquires its viewer-panel ref.+ * Returns an unregister fn so the chat page can clean up on unmount.+ */+ setOpenTabHandler(+ handler: ((ctx: QuizFollowupTabContext) => void) | null,+ ): void;+ /**+ * Subscribe to follow-up state changes — used by descendants that aren't+ * part of the React subtree this provider wraps (i.e. components inside+ * SessionViewerPanel rendered via a portal would still re-render through+ * the normal React tree, but the subscriber API also lets non-React+ * consumers observe state).+ */+ /* getSnapshot returns the full threads record. Components prefer to+ * select via ``useFollowupThread`` rather than reading this directly. */+ getAllThreads(): Record<string, FollowupThreadState>;+}++const QuizFollowupCtx = createContext<QuizFollowupController | null>(null);+// Public access to the threads state for components that want to react to+// thread updates without keeping their own snapshot. Updating the inner+// state triggers re-renders of subscribers via React's normal mechanism.+const QuizFollowupStateCtx = createContext<+ Record<string, FollowupThreadState>+>({});++interface ProviderProps {+ children: ReactNode;+}++export function QuizFollowupProvider({ children }: ProviderProps) {+ const [threads, setThreads] = useState<Record<string, FollowupThreadState>>(+ {},+ );+ const threadsRef = useRef<Record<string, FollowupThreadState>>({});+ const runnersRef = useRef<+ Map<string, { questionKey: string; client: UnifiedWSClient }>+ >(new Map());+ // Notebook entry ids per question — captured from sendMessage so the+ // ``session`` event handler can persist ``followup_session_id`` on the+ // matching entry once the backend assigns one.+ const entryIdsRef = useRef<Map<string, number | null>>(new Map());+ const openTabHandlerRef = useRef<+ ((ctx: QuizFollowupTabContext) => void) | null+ >(null);++ useEffect(() => {+ threadsRef.current = threads;+ }, [threads]);++ useEffect(+ () => () => {+ runnersRef.current.forEach(({ client }) => client.disconnect());+ runnersRef.current.clear();+ },+ [],+ );++ const updateThread = useCallback(+ (+ key: string,+ updater: (prev: FollowupThreadState) => FollowupThreadState,+ ) => {+ setThreads((prev) => ({+ ...prev,+ [key]: updater(prev[key] ?? createEmptyThreadState()),+ }));+ },+ [],+ );++ const handleThreadEvent = useCallback(+ (key: string, event: StreamEvent) => {+ if (event.type === "session") {+ const metadata = (event.metadata ?? {}) as {+ session_id?: string;+ turn_id?: string;+ };+ const nextSessionId = metadata.session_id || event.session_id || "";+ const nextTurnId = metadata.turn_id || event.turn_id || null;+ if (!nextSessionId) return;+ updateThread(key, (prev) => ({+ ...prev,+ sessionId: nextSessionId,+ activeTurnId: nextTurnId,+ }));+ const runner = runnersRef.current.get(key);+ if (runner) runner.questionKey = nextSessionId;+ const entryId = entryIdsRef.current.get(key);+ if (entryId) {+ void updateNotebookEntry(entryId, {+ followup_session_id: nextSessionId,+ }).catch(() => {});+ }+ return;+ }++ if (event.type === "done") {+ updateThread(key, (prev) => ({+ ...prev,+ isStreaming: false,+ currentStage: "",+ activeTurnId: null,+ }));+ const runner = runnersRef.current.get(key);+ runner?.client.disconnect();+ runnersRef.current.delete(key);+ return;+ }++ updateThread(key, (prev) => {+ const next = {+ ...prev,+ activeTurnId: event.turn_id || prev.activeTurnId,+ };+ if (event.type === "stage_start") {+ next.currentStage = event.stage;+ } else if (event.type === "stage_end") {+ next.currentStage = "";+ } else if (event.type === "error") {+ next.error = event.content || prev.error;+ const terminal = Boolean(+ ((event.metadata ?? {}) as { turn_terminal?: boolean })+ .turn_terminal,+ );+ if (terminal) {+ next.isStreaming = false;+ next.currentStage = "";+ next.activeTurnId = null;+ }+ }+ // Append the streaming event to the latest assistant message's+ // event log so the trace surface can render the full reasoning /+ // tool-call narrative — matching the main chat's behaviour.+ const messages = [...prev.messages];+ let last = messages[messages.length - 1];+ if (!last || last.role !== "assistant") {+ messages.push({ role: "assistant", content: "", events: [event] });+ } else {+ messages[messages.length - 1] = {+ ...last,+ events: [...(last.events ?? []), event],+ };+ }+ last = messages[messages.length - 1];+ if (last && last.role === "assistant" && shouldAppendEventContent(event)) {+ messages[messages.length - 1] = {+ ...last,+ content: `${last.content}${event.content}`,+ };+ }+ next.messages = messages;+ return next;+ });+ },+ [updateThread],+ );++ const ensureRunner = useCallback(+ (key: string) => {+ const existing = runnersRef.current.get(key);+ if (existing) {+ if (!existing.client.connected) existing.client.connect();+ return existing;+ }+ const record = {+ questionKey: key,+ client: new UnifiedWSClient(+ (event) => handleThreadEvent(key, event),+ () => {+ const current = threadsRef.current[key];+ if (current?.isStreaming) {+ updateThread(key, (prev) => ({+ ...prev,+ isStreaming: false,+ currentStage: "",+ activeTurnId: null,+ error:+ prev.error ||+ "Follow-up chat failed because the connection closed.",+ }));+ }+ },+ ),+ };+ runnersRef.current.set(key, record);+ record.client.connect();+ return record;+ },+ [handleThreadEvent, updateThread],+ );++ const sendThroughRunner = useCallback(+ function send(key: string, message: ChatMessage, attempt = 0) {+ const runner = ensureRunner(key);+ if (!runner.client.connected) {+ if (attempt >= 10) {+ updateThread(key, (prev) => ({+ ...prev,+ isStreaming: false,+ currentStage: "",+ error: "Follow-up chat failed to connect.",+ }));+ return;+ }+ window.setTimeout(() => send(key, message, attempt + 1), 200);+ return;+ }+ runner.client.send(message);+ },+ [ensureRunner, updateThread],+ );++ const sendMessage = useCallback(+ (input: SendMessageInput) => {+ const current =+ threadsRef.current[input.questionKey] ?? createEmptyThreadState();+ const content = input.content.trim();+ if (!content && input.attachments.length === 0) return;+ if (current.isStreaming) return;++ updateThread(input.questionKey, (prev) => ({+ ...prev,+ isOpen: true,+ input: "",+ isStreaming: true,+ error: null,+ messages: [...prev.messages, { role: "user", content }],+ }));++ sendThroughRunner(input.questionKey, {+ type: "start_turn",+ content,+ tools: [],+ capability: "chat",+ knowledge_bases: input.knowledgeBases ?? [],+ session_id: current.sessionId,+ attachments: input.attachments,+ language: input.language,+ config: input.config,+ notebook_references: input.notebookReferences,+ history_references: input.historyReferences,+ book_references: input.bookReferences,+ question_notebook_references: input.questionNotebookReferences,+ skills: input.skills,+ llm_selection: input.llmSelection ?? null,+ });+ },+ [sendThroughRunner, updateThread],+ );++ const submitAskUserReply = useCallback(+ (+ key: string,+ reply:+ | string+ | { text?: string; answers?: Array<{ questionId: string; text: string }> },+ ) => {+ const current = threadsRef.current[key];+ const turnId = current?.activeTurnId;+ if (!current || !turnId) return;+ // Allow submission either while the turn is still streaming OR while+ // it's paused on an unresolved ask_user card (matches the main chat's+ // ``submitUserReply`` guard).+ const pendingAskUser = current.messages.some((m) =>+ hasPendingAskUser(m.events, turnId),+ );+ if (!current.isStreaming && !pendingAskUser) return;++ const message: import("@/lib/unified-ws").SubmitUserReplyMessage = {+ type: "submit_user_reply",+ turn_id: turnId,+ };+ if (typeof reply === "string") {+ message.text = reply;+ } else {+ if (typeof reply.text === "string") message.text = reply.text;+ if (Array.isArray(reply.answers)) message.answers = reply.answers;+ }+ // Flip the thread back into the streaming state so the trace surface+ // shows the spinner while the resumed iteration runs. The runner is+ // already alive (ask_user pauses without disconnecting), so we just+ // forward the reply through it.+ updateThread(key, (prev) => ({+ ...prev,+ isStreaming: true,+ error: null,+ }));+ sendThroughRunner(key, message);+ },+ [sendThroughRunner, updateThread],+ );++ const openFollowupTab = useCallback((context: QuizFollowupTabContext) => {+ entryIdsRef.current.set(context.questionKey, context.notebookEntryId);+ const handler = openTabHandlerRef.current;+ if (handler) handler(context);+ }, []);++ const hydrateThread = useCallback(+ (+ key: string,+ sessionId: string,+ messages: HydratedFollowupMessage[],+ ) => {+ // Skip when the thread already holds local state — we never+ // overwrite an active conversation with a stale snapshot. The+ // ``sessionId`` check covers the case where the in-memory thread+ // is empty but we already wired a session id from a prior call.+ const current = threadsRef.current[key];+ if (current && (current.messages.length > 0 || current.isStreaming)) {+ return;+ }+ updateThread(key, (prev) => ({+ ...prev,+ sessionId,+ messages: messages.map((m) => ({+ role: m.role,+ content: m.content,+ events: m.events ?? [],+ })),+ }));+ },+ [updateThread],+ );++ const setOpenTabHandler = useCallback(+ (handler: ((ctx: QuizFollowupTabContext) => void) | null) => {+ openTabHandlerRef.current = handler;+ },+ [],+ );++ const getThread = useCallback((key: string): FollowupThreadState => {+ return threadsRef.current[key] ?? createEmptyThreadState();+ }, []);++ const getAllThreads = useCallback(() => threadsRef.current, []);++ const controller = useMemo<QuizFollowupController>(+ () => ({+ getThread,+ updateThread,+ hydrateThread,+ sendMessage,+ submitAskUserReply,+ openFollowupTab,+ setOpenTabHandler,+ getAllThreads,+ }),+ [+ getThread,+ updateThread,+ hydrateThread,+ sendMessage,+ submitAskUserReply,+ openFollowupTab,+ setOpenTabHandler,+ getAllThreads,+ ],+ );++ return (+ <QuizFollowupCtx.Provider value={controller}>+ <QuizFollowupStateCtx.Provider value={threads}>+ {children}+ </QuizFollowupStateCtx.Provider>+ </QuizFollowupCtx.Provider>+ );+}++export function useQuizFollowupController(): QuizFollowupController {+ const ctx = useContext(QuizFollowupCtx);+ if (!ctx) {+ throw new Error(+ "useQuizFollowupController must be used inside a QuizFollowupProvider",+ );+ }+ return ctx;+}++/** Returns the live thread snapshot for a question key, re-rendering on+ * every update. Returns the empty thread when no entry exists yet. */+export function useFollowupThread(questionKey: string): FollowupThreadState {+ const threads = useContext(QuizFollowupStateCtx);+ return threads[questionKey] ?? createEmptyThreadState();+}++/** Returns the full threads record — used by QuizViewer for "any thread+ * with messages?" lookups across all questions in a quiz. */+export function useAllFollowupThreads(): Record<string, FollowupThreadState> {+ return useContext(QuizFollowupStateCtx);+}diff --git a/web/lib/quiz-judge.ts b/web/lib/quiz-judge.tsnew file mode 100644index 000000000..3d3b79762--- /dev/null+++ b/web/lib/quiz-judge.ts@@ -0,0 +1,138 @@+import { wsUrl } from "@/lib/api";++export interface QuizJudgeImage {+ /** Base64 of the freshly-picked image (no ``data:`` prefix). */+ base64: string | null;+ /** AttachmentStore URL for a previously persisted image. */+ url: string | null;+ filename: string;+ mime_type: string;+}++export interface QuizJudgeRequest {+ question: string;+ question_type: string;+ options: Record<string, string> | null;+ correct_answer: string;+ explanation: string;+ user_answer: string;+ /** Multi-image list — backend builds a multimodal user message from this. */+ user_answer_images: QuizJudgeImage[];+ language: "zh" | "en";+}++export interface QuizJudgeHandle {+ close: () => void;+}++export interface QuizJudgeHandlers {+ onStart?: () => void;+ onChunk: (chunk: string) => void;+ onDone: (finalText: string) => void;+ onError: (message: string) => void;+}++export function startQuizJudge(+ payload: QuizJudgeRequest,+ handlers: QuizJudgeHandlers,+): QuizJudgeHandle {+ const ws = new WebSocket(wsUrl("/api/v1/question/judge"));+ let buffer = "";+ let finished = false;++ const finalize = (kind: "done" | "error", message?: string) => {+ if (finished) return;+ finished = true;+ if (kind === "done") {+ handlers.onDone(buffer);+ } else {+ handlers.onError(message ?? "AI judge failed.");+ }+ try {+ ws.close();+ } catch {+ /* ignore */+ }+ };++ ws.onopen = () => {+ try {+ ws.send(JSON.stringify(payload));+ } catch (err) {+ finalize("error", err instanceof Error ? err.message : String(err));+ }+ };++ ws.onmessage = (ev) => {+ let frame: { type?: string; content?: string };+ try {+ frame = JSON.parse(ev.data);+ } catch {+ return;+ }+ if (frame.type === "started") {+ handlers.onStart?.();+ return;+ }+ if (frame.type === "text" && typeof frame.content === "string") {+ buffer += frame.content;+ handlers.onChunk(frame.content);+ return;+ }+ if (frame.type === "done") {+ finalize("done");+ return;+ }+ if (frame.type === "error") {+ finalize("error", frame.content || "AI judge failed.");+ }+ };++ ws.onerror = () => {+ finalize("error", "AI judge connection error.");+ };++ ws.onclose = () => {+ if (!finished) {+ finalize("error", "AI judge connection closed unexpectedly.");+ }+ };++ return {+ close: () => {+ if (!finished) {+ finished = true;+ }+ try {+ ws.close();+ } catch {+ /* ignore */+ }+ },+ };+}++export function readFileAsBase64(+ file: File,+): Promise<{ base64: string; mime: string; name: string }> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => {+ const result = reader.result;+ if (typeof result !== "string") {+ reject(new Error("Failed to read file"));+ return;+ }+ const comma = result.indexOf(",");+ const base64 = comma >= 0 ? result.slice(comma + 1) : result;+ resolve({+ base64,+ mime: file.type || "image/png",+ name: file.name || "answer.png",+ });+ };+ reader.onerror = () =>+ reject(reader.error ?? new Error("Failed to read file"));+ reader.readAsDataURL(file);+ });+}diff --git a/web/lib/quiz-question-type.ts b/web/lib/quiz-question-type.tsindex 3b066e99d..e5d34b0cc 100644--- a/web/lib/quiz-question-type.ts+++ b/web/lib/quiz-question-type.ts@@ -1,20 +1,42 @@-export type NormalizedQuizQuestionType = "choice" | "written" | "coding";+export type NormalizedQuizQuestionType =+ | "choice"+ | "concept"+ | "fill_in_blank"+ | "short_answer"+ | "written"+ | "coding";++export const QUIZ_QUESTION_TYPES: ReadonlyArray<NormalizedQuizQuestionType> = [+ "choice",+ "concept",+ "fill_in_blank",+ "short_answer",+ "written",+ "coding",+];const QUESTION_TYPE_ALIASES: Record<string, NormalizedQuizQuestionType> = {choice: "choice",multiple_choice: "choice","multiple-choice": "choice",mcq: "choice",+ concept: "concept",+ true_false: "concept",+ "true-false": "concept",+ tf: "concept",+ judgement: "concept",+ fill_in_blank: "fill_in_blank",+ "fill-in-the-blank": "fill_in_blank",+ fill_in_the_blank: "fill_in_blank",+ cloze: "fill_in_blank",+ short_answer: "short_answer",+ "short-answer": "short_answer",written: "written",open_ended: "written","open-ended": "written",open_response: "written","open-response": "written",- short_answer: "written",- "short-answer": "written",essay: "written",- fill_in_blank: "written",- "fill-in-the-blank": "written",coding: "coding",code: "coding",programming: "coding",@@ -27,13 +49,26 @@ export function normalizeQuizQuestionType(.trim().toLowerCase().replace(/\s+/g, "_");- return QUESTION_TYPE_ALIASES[normalized] || "written";+ return QUESTION_TYPE_ALIASES[normalized] || "short_answer";}export function isChoiceQuizQuestion(value: unknown): boolean {return normalizeQuizQuestionType(value) === "choice";}+export function isConceptQuizQuestion(value: unknown): boolean {+ return normalizeQuizQuestionType(value) === "concept";+}++export function isFillInBlankQuizQuestion(value: unknown): boolean {+ return normalizeQuizQuestionType(value) === "fill_in_blank";+}++export function isFreeTextQuizQuestion(value: unknown): boolean {+ const t = normalizeQuizQuestionType(value);+ return t === "short_answer" || t === "written" || t === "coding";+}+export function resolveChoiceAnswerKey(correctAnswer: unknown,options: Record<string, string> | null | undefined,@@ -60,3 +95,19 @@ export function resolveChoiceAnswerKey(return directKey;}++/**+ * Canonical T/F answer for ``concept`` questions. The backend pipeline+ * normalizes the model's output into the lowercase strings ``"true"`` /+ * ``"false"``; callers should compare against this exactly.+ */+export function resolveConceptAnswer(+ correctAnswer: unknown,+): "true" | "false" | "" {+ const normalized = String(correctAnswer || "")+ .trim()+ .toLowerCase();+ if (normalized === "true") return "true";+ if (normalized === "false") return "false";+ return "";+}diff --git a/web/lib/quiz-types.ts b/web/lib/quiz-types.tsindex 11a2c8b05..b7b687c5e 100644--- a/web/lib/quiz-types.ts+++ b/web/lib/quiz-types.ts@@ -2,7 +2,10 @@* Shared types for Quiz Generation (deep_question capability).*/-import { normalizeQuizQuestionType } from "./quiz-question-type";+import {+ type NormalizedQuizQuestionType,+ normalizeQuizQuestionType,+} from "./quiz-question-type";export type DeepQuestionMode = "custom" | "mimic";@@ -11,8 +14,18 @@ export interface DeepQuestionFormConfig {topic: string;num_questions: number;difficulty: string;- question_type: string;- preference: string;+ /**+ * Multi-select allowed-types whitelist. Empty list = "auto" (planner+ * picks any type per question). When ≥1 type is selected, the planner+ * is restricted to those types.+ */+ question_types: NormalizedQuizQuestionType[];+ /**+ * Per-type quantity targets (sums to num_questions when non-empty).+ * Only populated when ≥2 types are selected and the user has tweaked+ * the ratio bar; empty means "distribute evenly across allowed types".+ */+ per_type_counts: Partial<Record<NormalizedQuizQuestionType, number>>;paper_path: string;max_questions: number;}@@ -22,8 +35,8 @@ export const DEFAULT_QUIZ_CONFIG: DeepQuestionFormConfig = {topic: "",num_questions: 3,difficulty: "auto",- question_type: "auto",- preference: "",+ question_types: [],+ per_type_counts: {},paper_path: "",max_questions: 10,};@@ -31,7 +44,7 @@ export const DEFAULT_QUIZ_CONFIG: DeepQuestionFormConfig = {export interface QuizQuestion {question_id: string;question: string;- question_type: "choice" | "written" | "coding";+ question_type: NormalizedQuizQuestionType;options?: Record<string, string>;correct_answer: string;explanation: string;@@ -53,6 +66,67 @@ export interface QuizFollowupContext {knowledge_context?: string;user_answer?: string;is_correct?: boolean;+ /**+ * Filenames of the images the learner attached as their answer. Image+ * bytes ride on the first follow-up message as regular attachments so+ * vision-capable models see them; the filenames here let the follow-up+ * system prompt mention them explicitly so the LLM knows the attached+ * images are the learner's answer, not unrelated context.+ */+ user_answer_image_filenames?: string[];+ /** Latest AI judgment text for this question, when one has been run. */+ ai_judgment?: string;+}++/**+ * Extract QuizQuestion[] from per-question ``content`` events emitted live+ * by the new ``QuestionPipeline`` while the quizzing phase is running.+ *+ * The backend tags each event with ``metadata.call_kind ===+ * "quiz_question_emitted"`` and the structured ``qa_pair`` payload. We+ * collect them, dedupe by ``question_id``, and order by+ * ``question_index`` so QuizViewer can render each question the moment+ * it lands — without waiting for the final ``result`` event.+ *+ * Returns ``null`` until at least one valid quiz event has arrived, so+ * the caller can fall back to the legacy ``extractQuizQuestions`` shape+ * for older (mimic / answer-now) result envelopes.+ */+export function extractStreamingQuizQuestions(+ events: Array<{+ type?: string;+ metadata?: Record<string, unknown> | undefined;+ }>,+): QuizQuestion[] | null {+ if (!Array.isArray(events) || events.length === 0) return null;+ const byId = new Map<string, { idx: number; qa: QuizQuestion }>();+ for (const event of events) {+ if (event.type !== "content") continue;+ const meta = (event.metadata ?? {}) as Record<string, unknown>;+ if (meta.call_kind !== "quiz_question_emitted") continue;+ const qa = meta.qa_pair as Record<string, unknown> | undefined;+ if (!qa || typeof qa !== "object" || !qa.question) continue;+ const idx = Number(meta.question_index);+ const question: QuizQuestion = {+ question_id: String(qa.question_id ?? ""),+ question: String(qa.question ?? ""),+ question_type: normalizeQuizQuestionType(qa.question_type),+ options: qa.options as Record<string, string> | undefined,+ correct_answer: String(qa.correct_answer ?? ""),+ explanation: String(qa.explanation ?? ""),+ difficulty: qa.difficulty ? String(qa.difficulty) : undefined,+ concentration: qa.concentration ? String(qa.concentration) : undefined,+ };+ const key = question.question_id || String(idx);+ byId.set(key, {+ idx: Number.isFinite(idx) ? idx : byId.size,+ qa: question,+ });+ }+ if (byId.size === 0) return null;+ return Array.from(byId.values())+ .sort((a, b) => a.idx - b.idx)+ .map((entry) => entry.qa);}/**@@ -96,12 +170,23 @@ export function extractQuizQuestions();}+export interface QuizFollowupExtras {+ /** Filenames of the learner's image answers (bytes ride on first msg). */+ userAnswerImageFilenames?: string[] | null;+ /** Last AI-judgment text for this question, if the learner ran it. */+ aiJudgment?: string | null;+}+export function buildQuizFollowupConfig(question: QuizQuestion,userAnswer: string,isCorrect: boolean | null,parentQuizSessionId?: string | null,+ extras?: QuizFollowupExtras,): Record<string, unknown> {+ const filenames = (extras?.userAnswerImageFilenames ?? [])+ .map((name) => (typeof name === "string" ? name.trim() : ""))+ .filter((name) => name.length > 0);const context: QuizFollowupContext = {question_id: question.question_id,question: question.question,@@ -115,6 +200,8 @@ export function buildQuizFollowupConfig(user_answer: userAnswer || undefined,is_correct: typeof isCorrect === "boolean" ? isCorrect : undefined,parent_quiz_session_id: parentQuizSessionId || undefined,+ user_answer_image_filenames: filenames.length > 0 ? filenames : undefined,+ ai_judgment: extras?.aiJudgment?.trim() || undefined,};return {@@ -127,6 +214,16 @@ function titleCase(value: string): string {return value.charAt(0).toUpperCase() + value.slice(1);}+export const QUIZ_TYPE_LABEL_KEYS: Record<NormalizedQuizQuestionType, string> =+ {+ choice: "Multiple Choice",+ concept: "Concept Question",+ fill_in_blank: "Fill in the Blank",+ short_answer: "Short Answer",+ written: "Essay",+ coding: "Coding",+ };+/*** One-line summary of the quiz form, shown next to the collapsed `Settings`* chevron in the composer. Pass `translate` (`t` from `react-i18next`) so the@@ -145,11 +242,17 @@ export function summarizeQuizConfig(`${tr("Max")} ${cfg.max_questions}`,].join(" · ");}+ const typeSummary =+ cfg.question_types.length === 0+ ? tr("Auto")+ : cfg.question_types.length === 1+ ? tr(QUIZ_TYPE_LABEL_KEYS[cfg.question_types[0]])+ : `${cfg.question_types.length} ${tr("types")}`;return [tr("Custom"),`${cfg.num_questions} ${tr("questions")}`,tr(titleCase(cfg.difficulty || "auto")),- tr(titleCase(cfg.question_type || "auto")),+ typeSummary,].join(" · ");}@@ -167,11 +270,19 @@ export function buildQuizWSConfig(max_questions: cfg.max_questions,};}+ // Only forward per-type counts when >=2 types are selected AND the user+ // actually populated counts that sum to num_questions. Otherwise let+ // the backend distribute freely across the allowed set.+ const countsValid =+ cfg.question_types.length >= 2 &&+ Object.keys(cfg.per_type_counts).length > 0 &&+ Object.values(cfg.per_type_counts).reduce((sum, v) => sum + (v || 0), 0) ===+ cfg.num_questions;return {mode: "custom",num_questions: cfg.num_questions,difficulty: cfg.difficulty === "auto" ? "" : cfg.difficulty,- question_type: cfg.question_type === "auto" ? "" : cfg.question_type,- preference: cfg.preference.trim(),+ question_types: cfg.question_types,+ per_type_counts: countsValid ? cfg.per_type_counts : {},};}diff --git a/web/tests/quiz-question-type.test.ts b/web/tests/quiz-question-type.test.tsindex 2c3fd0a35..9f367718c 100644--- a/web/tests/quiz-question-type.test.ts+++ b/web/tests/quiz-question-type.test.ts@@ -3,8 +3,11 @@ import assert from "node:assert/strict";import {isChoiceQuizQuestion,+ isConceptQuizQuestion,+ isFillInBlankQuizQuestion,normalizeQuizQuestionType,resolveChoiceAnswerKey,+ resolveConceptAnswer,} from "../lib/quiz-question-type";import { extractQuizQuestions } from "../lib/quiz-types";@@ -16,11 +19,26 @@ test("normalizeQuizQuestionType maps legacy choice aliases to choice", () => {assert.equal(isChoiceQuizQuestion("multiple_choice"), true);});-test("normalizeQuizQuestionType keeps written and coding families stable", () => {+test("normalizeQuizQuestionType preserves every canonical type", () => {assert.equal(normalizeQuizQuestionType("written"), "written");- assert.equal(normalizeQuizQuestionType("fill_in_blank"), "written");+ assert.equal(normalizeQuizQuestionType("essay"), "written");+ assert.equal(normalizeQuizQuestionType("short_answer"), "short_answer");+ assert.equal(normalizeQuizQuestionType("concept"), "concept");+ assert.equal(normalizeQuizQuestionType("true_false"), "concept");+ assert.equal(normalizeQuizQuestionType("fill_in_blank"), "fill_in_blank");+ assert.equal(normalizeQuizQuestionType("fill-in-the-blank"), "fill_in_blank");assert.equal(normalizeQuizQuestionType("coding"), "coding");assert.equal(normalizeQuizQuestionType("programming"), "coding");+ assert.equal(isConceptQuizQuestion("true_false"), true);+ assert.equal(isFillInBlankQuizQuestion("fill-in-the-blank"), true);+});++test("resolveConceptAnswer normalizes T/F variants", () => {+ assert.equal(resolveConceptAnswer("true"), "true");+ assert.equal(resolveConceptAnswer("TRUE"), "true");+ assert.equal(resolveConceptAnswer("false"), "false");+ assert.equal(resolveConceptAnswer(""), "");+ assert.equal(resolveConceptAnswer("maybe"), "");});test("resolveChoiceAnswerKey accepts either the option key or label text", () => {