Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

refactor(web): rebuild the question bank and fix filing from a quiz card

Bingxi Zhao (Frank)b471160680c3
diff --git a/web/app/(utility)/space/questions/page.tsx b/web/app/(utility)/space/questions/page.tsx
index 1f525c94e..a95b91cb4 100644
--- a/web/app/(utility)/space/questions/page.tsx
+++ b/web/app/(utility)/space/questions/page.tsx
@@ -1,4 +1,4 @@
-import QuestionBankSection from "@/components/space/QuestionBankSection";
+import { QuestionBankSection } from "@/components/space/question-bank";
export default function SpaceQuestionsPage() {
return <QuestionBankSection />;
diff --git a/web/components/quiz/QuizViewer.tsx b/web/components/quiz/QuizViewer.tsx
index e15752441..d25d614cd 100644
--- a/web/components/quiz/QuizViewer.tsx
+++ b/web/components/quiz/QuizViewer.tsx
@@ -15,11 +15,9 @@ import {
ChevronLeft,
ChevronRight,
Eye,
- FolderPlus,
ImagePlus,
Loader2,
MessageSquarePlus,
- Plus,
RotateCcw,
Sparkles,
X,
@@ -43,6 +41,7 @@ import {
type QuizJudgeHandle,
} from "@/lib/quiz-judge";
import { type QuizQuestion } from "@/lib/quiz-types";
+import CategoryMenu from "@/components/space/question-bank/CategoryMenu";
import {
addEntryToCategory,
createCategory,
@@ -212,11 +211,6 @@ export default function QuizViewer({
Record<string, string>
>({});
const [categories, setCategories] = useState<NotebookCategory[]>([]);
- const [categoryDropdownKey, setCategoryDropdownKey] = useState<string | null>(
- null,
- );
- const [newCategoryName, setNewCategoryName] = useState("");
- const [categoryBusy, setCategoryBusy] = useState(false);
const [judgments, setJudgments] = useState<Record<number, JudgmentState>>({});
const [answerViews, setAnswerViews] = useState<Record<number, AnswerView>>(
@@ -364,51 +358,45 @@ export default function QuizViewer({
}
}, []);
- const handleOpenCategoryDropdown = useCallback(() => {
- if (!q) return;
- const key = getQuestionKey(q, idx);
- if (categoryDropdownKey === key) {
- setCategoryDropdownKey(null);
- return;
- }
- setCategoryDropdownKey(key);
- void loadCategories();
- }, [categoryDropdownKey, idx, loadCategories, q]);
+ // Load the category list once, so the file-into menu opens already
+ // populated. Guarded against a late response landing after unmount.
+ useEffect(() => {
+ let cancelled = false;
+ void (async () => {
+ try {
+ const next = await listCategories();
+ if (!cancelled) setCategories(next);
+ } catch {
+ /* ignore */
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, []);
const handleAddToCategory = useCallback(
async (catId: number) => {
if (!q) return;
- const key = getQuestionKey(q, idx);
- const eId = entryIds[key];
+ const eId = entryIds[getQuestionKey(q, idx)];
if (!eId) return;
- setCategoryBusy(true);
- try {
- await addEntryToCategory(eId, catId);
- setCategoryDropdownKey(null);
- } catch {
- /* ignore */
- }
- setCategoryBusy(false);
+ await addEntryToCategory(eId, catId);
+ await loadCategories();
},
- [entryIds, idx, q],
+ [entryIds, idx, loadCategories, q],
);
- const handleCreateAndAdd = useCallback(async () => {
- if (!q || !newCategoryName.trim()) return;
- const key = getQuestionKey(q, idx);
- const eId = entryIds[key];
- if (!eId) return;
- setCategoryBusy(true);
- try {
- const cat = await createCategory(newCategoryName.trim());
+ const handleCreateAndAdd = useCallback(
+ async (name: string) => {
+ if (!q) return;
+ const eId = entryIds[getQuestionKey(q, idx)];
+ if (!eId) return;
+ const cat = await createCategory(name);
await addEntryToCategory(eId, cat.id);
- setNewCategoryName("");
- setCategoryDropdownKey(null);
- } catch {
- /* ignore */
- }
- setCategoryBusy(false);
- }, [entryIds, idx, newCategoryName, q]);
+ await loadCategories();
+ },
+ [entryIds, idx, loadCategories, q],
+ );
const isChoice = q ? isMultipleChoice(q) : false;
const isConcept = q ? isConceptQuizQuestion(q.question_type) : false;
@@ -768,7 +756,6 @@ export default function QuizViewer({
const currentEntryId = entryIds[questionKey];
const currentBookmarked = bookmarked[questionKey] ?? false;
- const showCategoryDropdown = categoryDropdownKey === questionKey;
return (
<div className="overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--card)]">
@@ -917,14 +904,12 @@ export default function QuizViewer({
fill={currentBookmarked ? "currentColor" : "none"}
/>
</button>
- <button
- onClick={handleOpenCategoryDropdown}
+ <CategoryMenu
+ categories={categories}
disabled={!currentEntryId}
- title={t("Add to Category")}
- className="rounded-lg p-1.5 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] disabled:opacity-30"
- >
- <FolderPlus size={16} />
- </button>
+ onPick={handleAddToCategory}
+ onCreate={handleCreateAndAdd}
+ />
<button
onClick={handleOpenFollowup}
title={t("Follow-up Chat")}
@@ -945,48 +930,6 @@ export default function QuizViewer({
})()}
</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">
- {categories.length > 0 && (
- <div className="max-h-[160px] overflow-y-auto">
- {categories.map((cat) => (
- <button
- key={cat.id}
- disabled={categoryBusy}
- onClick={() => void handleAddToCategory(cat.id)}
- className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)] disabled:opacity-40"
- >
- {cat.name}
- </button>
- ))}
- </div>
- )}
- <div className="border-t border-[var(--border)] px-2 py-1.5">
- <div className="flex items-center gap-1">
- <input
- value={newCategoryName}
- onChange={(e) => setNewCategoryName(e.target.value)}
- onKeyDown={(e) =>
- e.key === "Enter" && void handleCreateAndAdd()
- }
- placeholder={t("New category...")}
- className="flex-1 rounded border border-[var(--border)] bg-[var(--background)] px-2 py-1 text-[11px] text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"
- />
- <button
- disabled={!newCategoryName.trim() || categoryBusy}
- onClick={() => void handleCreateAndAdd()}
- className="rounded p-1 text-[var(--primary)] disabled:opacity-30"
- >
- {categoryBusy ? (
- <Loader2 size={12} className="animate-spin" />
- ) : (
- <Plus size={12} />
- )}
- </button>
- </div>
- </div>
- </div>
- )}
</div>
)}
</div>
diff --git a/web/components/space/QuestionBankSection.tsx b/web/components/space/QuestionBankSection.tsx
deleted file mode 100644
index 85278b1d7..000000000
--- a/web/components/space/QuestionBankSection.tsx
+++ /dev/null
@@ -1,659 +0,0 @@
-"use client";
-
-import dynamic from "next/dynamic";
-import Link from "next/link";
-import { useCallback, useEffect, useState } from "react";
-import { useTranslation } from "react-i18next";
-import {
- AlertTriangle,
- Bookmark,
- ChevronDown,
- ClipboardList,
- ExternalLink,
- FolderOpen,
- Loader2,
- MessageSquare,
- Pencil,
- Plus,
- Trash2,
- X,
-} from "lucide-react";
-import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";
-import {
- createCategory,
- deleteCategory,
- deleteNotebookEntry,
- listCategories,
- listNotebookEntries,
- removeEntryFromCategory,
- renameCategory,
- updateNotebookEntry,
- type NotebookCategory,
- type NotebookEntry,
-} from "@/lib/notebook-api";
-
-const MarkdownRenderer = dynamic(
- () => import("@/components/common/MarkdownRenderer"),
- { ssr: false },
-);
-
-type FilterMode = "all" | "bookmarked" | "wrong";
-
-const FILTERS: { mode: FilterMode; label: string }[] = [
- { mode: "all", label: "All" },
- { mode: "bookmarked", label: "Bookmarked" },
- { mode: "wrong", label: "Wrong Only" },
-];
-
-export default function QuestionBankSection() {
- const { t } = useTranslation();
- const [items, setItems] = useState<NotebookEntry[]>([]);
- const [total, setTotal] = useState(0);
- const [loading, setLoading] = useState(true);
- const [errorMsg, setErrorMsg] = useState<string | null>(null);
- const [filter, setFilter] = useState<FilterMode>("all");
- const [activeCategoryId, setActiveCategoryId] = useState<number | null>(null);
- const [categories, setCategories] = useState<NotebookCategory[]>([]);
- const [pendingId, setPendingId] = useState<number | null>(null);
- const [showCategoryManager, setShowCategoryManager] = useState(false);
- const [newCatName, setNewCatName] = useState("");
- const [renamingCat, setRenamingCat] = useState<{
- id: number;
- name: string;
- } | null>(null);
-
- const loadCategoriesData = useCallback(async () => {
- try {
- setCategories(await listCategories());
- } catch {
- /* ignore */
- }
- }, []);
-
- const loadItems = useCallback(
- async (mode: FilterMode, catId: number | null) => {
- setErrorMsg(null);
- try {
- const response = await listNotebookEntries({
- bookmarked: mode === "bookmarked" ? true : undefined,
- is_correct: mode === "wrong" ? false : undefined,
- category_id: catId ?? undefined,
- limit: 200,
- });
- setItems(response.items);
- setTotal(response.total);
- } catch (err) {
- setErrorMsg(String(err instanceof Error ? err.message : err));
- } finally {
- setLoading(false);
- }
- },
- [],
- );
-
- useEffect(() => {
- void loadItems(filter, activeCategoryId);
- void loadCategoriesData();
- }, [filter, activeCategoryId, loadItems, loadCategoriesData]);
-
- const handleToggleBookmark = useCallback(
- async (item: NotebookEntry) => {
- const next = !item.bookmarked;
- setPendingId(item.id);
- try {
- await updateNotebookEntry(item.id, { bookmarked: next });
- setItems((prev) =>
- filter === "bookmarked" && !next
- ? prev.filter((e) => e.id !== item.id)
- : prev.map((e) =>
- e.id === item.id ? { ...e, bookmarked: next } : e,
- ),
- );
- if (filter === "bookmarked" && !next)
- setTotal((p) => Math.max(0, p - 1));
- } catch {
- /* ignore */
- }
- setPendingId(null);
- },
- [filter],
- );
-
- const handleDelete = useCallback(
- async (item: NotebookEntry) => {
- if (!window.confirm(t("Delete this entry?"))) return;
- setPendingId(item.id);
- try {
- await deleteNotebookEntry(item.id);
- setItems((prev) => prev.filter((e) => e.id !== item.id));
- setTotal((p) => Math.max(0, p - 1));
- } catch {
- /* ignore */
- }
- setPendingId(null);
- },
- [t],
- );
-
- const handleRemoveFromCategory = useCallback(
- async (item: NotebookEntry) => {
- if (activeCategoryId === null) return;
- setPendingId(item.id);
- try {
- await removeEntryFromCategory(item.id, activeCategoryId);
- setItems((prev) => prev.filter((e) => e.id !== item.id));
- setTotal((p) => Math.max(0, p - 1));
- } catch {
- /* ignore */
- }
- setPendingId(null);
- },
- [activeCategoryId],
- );
-
- const handleCreateCategory = useCallback(async () => {
- if (!newCatName.trim()) return;
- try {
- await createCategory(newCatName.trim());
- setNewCatName("");
- await loadCategoriesData();
- } catch {
- /* ignore */
- }
- }, [loadCategoriesData, newCatName]);
-
- const handleRenameCategory = useCallback(async () => {
- if (!renamingCat || !renamingCat.name.trim()) return;
- try {
- await renameCategory(renamingCat.id, renamingCat.name.trim());
- setRenamingCat(null);
- await loadCategoriesData();
- } catch {
- /* ignore */
- }
- }, [loadCategoriesData, renamingCat]);
-
- const handleDeleteCategory = useCallback(
- async (catId: number) => {
- if (!window.confirm(t("Delete this category?"))) return;
- try {
- await deleteCategory(catId);
- if (activeCategoryId === catId) setActiveCategoryId(null);
- await loadCategoriesData();
- } catch {
- /* ignore */
- }
- },
- [activeCategoryId, loadCategoriesData, t],
- );
-
- return (
- <div className="space-y-4">
- <SpaceSectionHeader
- icon={ClipboardList}
- title={t("Question Bank")}
- description={t(
- "Review and organize quiz questions across sessions. Bookmark items, group them into categories, and jump back to the original chat.",
- )}
- meta={
- <span className="rounded-full border border-[var(--border)] bg-[var(--card)] px-2 py-0.5 text-[10.5px] font-medium text-[var(--muted-foreground)]">
- {total} {t("questions.count.suffix")}
- </span>
- }
- />
-
- {/* Category manager */}
- <div
- className={`overflow-hidden rounded-xl border transition-colors ${
- showCategoryManager
- ? "border-[var(--border)] bg-[var(--card)] shadow-sm"
- : "border-[var(--border)]/60 bg-[var(--card)]/40"
- }`}
- >
- <button
- onClick={() => setShowCategoryManager((v) => !v)}
- className="flex w-full items-center justify-between px-4 py-3 text-[13px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/30"
- >
- <span className="flex items-center gap-2">
- <FolderOpen className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
- {t("Manage Categories")}
- <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] tabular-nums text-[var(--muted-foreground)]">
- {categories.length}
- </span>
- </span>
- <ChevronDown
- className={`h-3.5 w-3.5 text-[var(--muted-foreground)] transition-transform duration-200 ${showCategoryManager ? "rotate-180" : ""}`}
- />
- </button>
-
- {showCategoryManager && (
- <div className="border-t border-[var(--border)]/70 px-4 pb-4 pt-3">
- <div className="space-y-1.5">
- {categories.map((cat) => (
- <div
- key={cat.id}
- className="flex items-center justify-between gap-2 rounded-lg bg-[var(--muted)]/30 px-3 py-2"
- >
- {renamingCat?.id === cat.id ? (
- <input
- autoFocus
- value={renamingCat.name}
- onChange={(e) =>
- setRenamingCat({
- ...renamingCat,
- name: e.target.value,
- })
- }
- onKeyDown={(e) => {
- if (e.key === "Enter") void handleRenameCategory();
- if (e.key === "Escape") setRenamingCat(null);
- }}
- onBlur={() => void handleRenameCategory()}
- className="flex-1 rounded border border-[var(--border)] bg-[var(--background)] px-2 py-0.5 text-[12px] text-[var(--foreground)] outline-none"
- />
- ) : (
- <span className="text-[12px] text-[var(--foreground)]">
- {cat.name}
- <span className="ml-1.5 text-[var(--muted-foreground)]">
- ({cat.entry_count})
- </span>
- </span>
- )}
- <div className="flex items-center gap-1">
- <button
- onClick={() =>
- setRenamingCat({ id: cat.id, name: cat.name })
- }
- className="rounded p-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- >
- <Pencil size={12} />
- </button>
- <button
- onClick={() => void handleDeleteCategory(cat.id)}
- className="rounded p-1 text-[var(--muted-foreground)] transition-colors hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-950/30"
- >
- <Trash2 size={12} />
- </button>
- </div>
- </div>
- ))}
- {!categories.length && (
- <p className="py-2 text-center text-[12px] text-[var(--muted-foreground)]">
- {t("No categories yet.")}
- </p>
- )}
- </div>
- <div className="mt-3 flex items-center gap-1.5">
- <input
- value={newCatName}
- onChange={(e) => setNewCatName(e.target.value)}
- onKeyDown={(e) =>
- e.key === "Enter" && void handleCreateCategory()
- }
- placeholder={t("New category name...")}
- className="flex-1 rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-[12px] text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"
- />
- <button
- onClick={() => void handleCreateCategory()}
- disabled={!newCatName.trim()}
- className="rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-white disabled:opacity-30"
- >
- <Plus size={13} />
- </button>
- </div>
- </div>
- )}
- </div>
-
- {/* Filter bar */}
- <div className="flex items-center justify-between gap-3 px-1">
- <div className="flex items-center gap-1 overflow-x-auto">
- {FILTERS.map(({ mode, label }) => {
- const active = filter === mode && activeCategoryId === null;
- return (
- <button
- key={mode}
- onClick={() => {
- setFilter(mode);
- setActiveCategoryId(null);
- }}
- className={`inline-flex shrink-0 items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
- active
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- {t(label)}
- </button>
- );
- })}
- {categories.length > 0 && (
- <span className="mx-1 text-[var(--border)]">|</span>
- )}
- {categories.map((cat) => {
- const active = activeCategoryId === cat.id;
- return (
- <button
- key={cat.id}
- onClick={() => {
- setActiveCategoryId(cat.id);
- setFilter("all");
- }}
- className={`inline-flex shrink-0 items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
- active
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- <FolderOpen size={12} />
- {cat.name}
- </button>
- );
- })}
- </div>
- <span className="shrink-0 text-[12px] text-[var(--muted-foreground)]">
- {t("Total")}: {total}
- </span>
- </div>
-
- {/* Content */}
- {loading ? (
- <div className="flex min-h-[420px] items-center justify-center">
- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
- </div>
- ) : errorMsg ? (
- <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-red-300 text-center dark:border-red-900">
- <div className="mb-3 rounded-xl bg-red-50 p-2.5 text-red-500 dark:bg-red-950/30">
- <AlertTriangle size={18} />
- </div>
- <p className="text-[14px] font-medium text-[var(--foreground)]">
- {t("Failed to load entries")}
- </p>
- <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
- {errorMsg}
- </p>
- <button
- onClick={() => void loadItems(filter, activeCategoryId)}
- className="mt-3 rounded-lg bg-[var(--primary)] px-4 py-1.5 text-[12px] font-medium text-white"
- >
- {t("Retry")}
- </button>
- </div>
- ) : items.length === 0 ? (
- <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
- <div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
- <ClipboardList size={18} />
- </div>
- <p className="text-[14px] font-medium text-[var(--foreground)]">
- {t("No entries yet")}
- </p>
- <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
- {t("Questions from your quizzes will appear here.")}
- </p>
- </div>
- ) : (
- <ul className="flex flex-col gap-3">
- {items.map((item) => {
- const disabled = pendingId === item.id;
- return (
- <li
- key={item.id}
- className={`rounded-xl border border-[var(--border)] bg-[var(--card)] px-5 py-4 shadow-sm transition-opacity ${
- disabled ? "opacity-60" : ""
- }`}
- >
- <div className="mb-3 flex items-start justify-between gap-3">
- <div className="min-w-0 flex-1">
- <div className="mb-1.5 flex flex-wrap items-center gap-1.5">
- {item.difficulty && (
- <span
- className={`rounded-md px-1.5 py-0.5 text-[10px] font-medium uppercase ${
- item.difficulty === "hard"
- ? "bg-red-50 text-red-600 dark:bg-red-950/30 dark:text-red-400"
- : item.difficulty === "medium"
- ? "bg-amber-50 text-amber-600 dark:bg-amber-950/30 dark:text-amber-400"
- : "bg-green-50 text-green-600 dark:bg-green-950/30 dark:text-green-400"
- }`}
- >
- {item.difficulty}
- </span>
- )}
- {item.question_type && (
- <span className="rounded-md bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">
- {item.question_type}
- </span>
- )}
- <span
- className={`rounded-md px-1.5 py-0.5 text-[10px] font-semibold ${
- item.is_correct
- ? "bg-green-100 text-green-700 dark:bg-green-950/30 dark:text-green-400"
- : "bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400"
- }`}
- >
- {item.is_correct ? t("Correct") : t("Incorrect")}
- </span>
- </div>
- <div className="text-[14px] font-medium text-[var(--foreground)]">
- <MarkdownRenderer
- content={item.question}
- variant="prose"
- className="text-[14px] leading-relaxed"
- />
- </div>
- </div>
- <div className="flex items-center gap-1">
- <button
- onClick={() => void handleToggleBookmark(item)}
- disabled={disabled}
- title={
- item.bookmarked ? t("Remove Bookmark") : t("Bookmark")
- }
- className={`rounded-lg p-1.5 transition-colors disabled:opacity-40 ${
- item.bookmarked
- ? "text-[var(--primary)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- <Bookmark
- className="h-4 w-4"
- fill={item.bookmarked ? "currentColor" : "none"}
- />
- </button>
- {activeCategoryId !== null && (
- <button
- onClick={() => void handleRemoveFromCategory(item)}
- disabled={disabled}
- title={t("Remove from category")}
- className="rounded-lg p-1.5 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] disabled:opacity-40"
- >
- <X className="h-4 w-4" />
- </button>
- )}
- <button
- onClick={() => void handleDelete(item)}
- disabled={disabled}
- title={t("Delete")}
- className="rounded-lg p-1.5 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] disabled:opacity-40"
- >
- <Trash2 className="h-4 w-4" />
- </button>
- </div>
- </div>
-
- {item.options && Object.keys(item.options).length > 0 && (
- <div className="mb-3 space-y-1.5">
- {Object.entries(item.options).map(([key, text]) => {
- const isUserAnswer =
- item.user_answer?.toUpperCase() === key.toUpperCase();
- const isCorrectAnswer =
- item.correct_answer?.toUpperCase() ===
- key.toUpperCase();
- const isWrongPick = isUserAnswer && !item.is_correct;
- return (
- <div
- key={key}
- className={`flex items-start gap-2.5 rounded-lg border px-3 py-2 text-[13px] transition-colors ${
- isCorrectAnswer
- ? "border-green-200 bg-green-50/60 dark:border-green-900 dark:bg-green-950/20"
- : isWrongPick
- ? "border-red-200 bg-red-50/60 dark:border-red-900 dark:bg-red-950/20"
- : "border-transparent bg-[var(--muted)]/30"
- }`}
- >
- <span
- className={`mt-px shrink-0 font-semibold ${
- isCorrectAnswer
- ? "text-green-600 dark:text-green-400"
- : isWrongPick
- ? "text-red-600 dark:text-red-400"
- : "text-[var(--muted-foreground)]"
- }`}
- >
- {key}.
- </span>
- <span
- className={`flex-1 ${
- isCorrectAnswer || isWrongPick
- ? "text-[var(--foreground)]"
- : "text-[var(--muted-foreground)]"
- }`}
- >
- {text}
- </span>
- {isCorrectAnswer && (
- <span className="mt-px shrink-0 text-[10px] font-medium text-green-600 dark:text-green-400">
- ✓ {t("Correct")}
- </span>
- )}
- {isWrongPick && (
- <span className="mt-px shrink-0 text-[10px] font-medium text-red-600 dark:text-red-400">
- ✗ {t("Your pick")}
- </span>
- )}
- </div>
- );
- })}
- </div>
- )}
-
- {(!item.options || Object.keys(item.options).length === 0) && (
- <div className="mb-3 space-y-2 text-[13px]">
- <div
- className={`rounded-lg border px-3 py-2.5 ${
- !item.is_correct
- ? "border-red-200/60 bg-red-50/40 dark:border-red-900/40 dark:bg-red-950/15"
- : "border-green-200/60 bg-green-50/40 dark:border-green-900/40 dark:bg-green-950/15"
- }`}
- >
- <div
- className={`mb-1 text-[11px] font-medium uppercase tracking-wide ${
- !item.is_correct
- ? "text-red-500 dark:text-red-400"
- : "text-green-600 dark:text-green-400"
- }`}
- >
- {t("Your Answer")} {item.is_correct ? "✓" : "✗"}
- </div>
- <div className="text-[var(--foreground)]">
- {item.user_answer ? (
- item.question_type === "coding" ? (
- <MarkdownRenderer
- content={`\`\`\`python\n${item.user_answer}\n\`\`\``}
- variant="prose"
- className="text-[13px]"
- />
- ) : (
- <MarkdownRenderer
- content={item.user_answer}
- variant="prose"
- className="text-[13px] leading-relaxed"
- />
- )
- ) : (
- <span className="text-[var(--muted-foreground)]">
- —
- </span>
- )}
- </div>
- </div>
- <div className="rounded-lg border border-green-200/60 bg-green-50/40 px-3 py-2.5 dark:border-green-900/40 dark:bg-green-950/15">
- <div className="mb-1 text-[11px] font-medium uppercase tracking-wide text-green-600 dark:text-green-400">
- {t("Reference Answer")}
- </div>
- <div className="text-[var(--foreground)]">
- {item.correct_answer ? (
- item.question_type === "coding" ? (
- <MarkdownRenderer
- content={
- item.correct_answer
- .trimStart()
- .startsWith("```")
- ? item.correct_answer
- : `\`\`\`python\n${item.correct_answer}\n\`\`\``
- }
- variant="prose"
- className="text-[13px]"
- />
- ) : (
- <MarkdownRenderer
- content={item.correct_answer}
- variant="prose"
- className="text-[13px] leading-relaxed"
- />
- )
- ) : (
- <span className="text-[var(--muted-foreground)]">
- —
- </span>
- )}
- </div>
- </div>
- </div>
- )}
-
- {item.explanation && (
- <div className="mb-3 rounded-lg border border-blue-200/60 bg-blue-50/30 px-3 py-2.5 dark:border-blue-900/40 dark:bg-blue-950/15">
- <div className="mb-1 text-[11px] font-medium uppercase tracking-wide text-blue-600 dark:text-blue-400">
- {t("Explanation")}
- </div>
- <div className="text-[13px] leading-relaxed text-[var(--foreground)]">
- <MarkdownRenderer
- content={item.explanation}
- variant="prose"
- className="text-[13px] leading-relaxed"
- />
- </div>
- </div>
- )}
-
- <div className="mt-3 flex flex-wrap items-center justify-between gap-2 text-[11px]">
- <div className="flex items-center gap-2">
- <Link
- href={`/?session=${encodeURIComponent(item.session_id)}`}
- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--muted)]/40 px-2.5 py-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- >
- <ExternalLink size={10} />
- {item.session_title || t("Original Session")}
- </Link>
- {item.followup_session_id && (
- <Link
- href={`/?session=${encodeURIComponent(item.followup_session_id)}`}
- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--muted)]/40 px-2.5 py-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- >
- <MessageSquare size={10} />
- {t("Follow-up")}
- </Link>
- )}
- </div>
- <span className="text-[var(--muted-foreground)]">
- {new Date(item.created_at * 1000).toLocaleString()}
- </span>
- </div>
- </li>
- );
- })}
- </ul>
- )}
- </div>
- );
-}
diff --git a/web/components/space/question-bank/BankScopeRail.tsx b/web/components/space/question-bank/BankScopeRail.tsx
new file mode 100644
index 000000000..8efedae23
--- /dev/null
+++ b/web/components/space/question-bank/BankScopeRail.tsx
@@ -0,0 +1,118 @@
+"use client";
+
+import { useTranslation } from "react-i18next";
+import { Bookmark, FolderOpen, Inbox, LayoutGrid, XCircle } from "lucide-react";
+import type { LucideIcon } from "lucide-react";
+import type { NotebookCategory, QuestionBankStats } from "@/lib/notebook-api";
+import type { BankScope } from "./useQuestionBank";
+
+interface BankScopeRailProps {
+ scope: BankScope;
+ stats: QuestionBankStats;
+ categories: NotebookCategory[];
+ onSelect: (scope: BankScope) => void;
+}
+
+const STATUS_SCOPES: {
+ kind: "all" | "wrong" | "bookmarked" | "uncategorized";
+ label: string;
+ icon: LucideIcon;
+ count: (stats: QuestionBankStats) => number;
+}[] = [
+ { kind: "all", label: "All", icon: LayoutGrid, count: (s) => s.total },
+ { kind: "wrong", label: "Wrong Only", icon: XCircle, count: (s) => s.wrong },
+ {
+ kind: "bookmarked",
+ label: "Bookmarked",
+ icon: Bookmark,
+ count: (s) => s.bookmarked,
+ },
+ {
+ kind: "uncategorized",
+ label: "Unfiled",
+ icon: Inbox,
+ count: (s) => s.uncategorized,
+ },
+];
+
+/**
+ * The view switcher, with live counts on every chip.
+ *
+ * "Unfiled" is deliberately a first-class view: it is the pile the learner
+ * actually wants to work through when they say the bank needs tidying, and
+ * without a count they cannot tell whether the work is done.
+ */
+export default function BankScopeRail({
+ scope,
+ stats,
+ categories,
+ onSelect,
+}: BankScopeRailProps) {
+ const { t } = useTranslation();
+
+ const chipClass = (active: boolean) =>
+ `inline-flex shrink-0 items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[12.5px] transition-colors ${
+ active
+ ? "bg-[var(--foreground)] font-medium text-[var(--background)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ }`;
+
+ return (
+ <div className="flex items-center gap-1 overflow-x-auto pb-0.5">
+ {STATUS_SCOPES.map(({ kind, label, icon: Icon, count }) => {
+ const active = scope.kind === kind;
+ return (
+ <button
+ key={kind}
+ type="button"
+ onClick={() => onSelect({ kind })}
+ className={chipClass(active)}
+ >
+ <Icon className="h-3.5 w-3.5" />
+ {t(label)}
+ <span
+ className={`tabular-nums text-[11px] ${
+ active
+ ? "text-[var(--background)]/70"
+ : "text-[var(--muted-foreground)]"
+ }`}
+ >
+ {count(stats)}
+ </span>
+ </button>
+ );
+ })}
+
+ {categories.length > 0 && (
+ <span className="mx-1 h-4 w-px shrink-0 bg-[var(--border)]" />
+ )}
+
+ {categories.map((category) => {
+ const active =
+ scope.kind === "category" && scope.categoryId === category.id;
+ return (
+ <button
+ key={category.id}
+ type="button"
+ onClick={() =>
+ onSelect({ kind: "category", categoryId: category.id })
+ }
+ className={chipClass(active)}
+ >
+ <FolderOpen className="h-3.5 w-3.5" />
+ <span className="max-w-[10rem] truncate">{category.name}</span>
+ <span
+ className={`tabular-nums text-[11px] ${
+ active
+ ? "text-[var(--background)]/70"
+ : "text-[var(--muted-foreground)]"
+ }`}
+ >
+ {category.entry_count}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/web/components/space/question-bank/BankSelectionBar.tsx b/web/components/space/question-bank/BankSelectionBar.tsx
new file mode 100644
index 000000000..dcc09925c
--- /dev/null
+++ b/web/components/space/question-bank/BankSelectionBar.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import { useTranslation } from "react-i18next";
+import { CheckSquare, FolderMinus, X } from "lucide-react";
+import type { NotebookCategory } from "@/lib/notebook-api";
+import CategoryMenu from "./CategoryMenu";
+import type { BankScope } from "./useQuestionBank";
+
+interface BankSelectionBarProps {
+ count: number;
+ visibleCount: number;
+ scope: BankScope;
+ categories: NotebookCategory[];
+ onSelectAll: () => void;
+ onClear: () => void;
+ onFile: (categoryId: number) => Promise<boolean>;
+ onCreateAndFile: (name: string) => Promise<boolean>;
+ onUnfileFromCurrent: () => Promise<boolean>;
+}
+
+/**
+ * Floating bar for acting on a multi-selection.
+ *
+ * Appears only once something is selected, so the default reading view
+ * stays clean; "remove from this category" is offered only while actually
+ * inside a category, where it is the one unambiguous meaning.
+ */
+export default function BankSelectionBar({
+ count,
+ visibleCount,
+ scope,
+ categories,
+ onSelectAll,
+ onClear,
+ onFile,
+ onCreateAndFile,
+ onUnfileFromCurrent,
+}: BankSelectionBarProps) {
+ const { t } = useTranslation();
+ if (count === 0) return null;
+
+ return (
+ <div className="sticky bottom-4 z-20 mx-auto flex w-fit max-w-full flex-wrap items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2 shadow-lg">
+ <span className="text-[12.5px] font-medium text-[var(--foreground)]">
+ {count} {t("selected")}
+ </span>
+
+ {count < visibleCount && (
+ <button
+ type="button"
+ onClick={onSelectAll}
+ className="inline-flex items-center gap-1.5 rounded-lg px-2 py-1.5 text-[12px] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ >
+ <CheckSquare className="h-3.5 w-3.5" />
+ {t("Select all")}
+ </button>
+ )}
+
+ <span className="h-4 w-px bg-[var(--border)]" />
+
+ <CategoryMenu
+ categories={categories}
+ label={t("Add to category")}
+ align="left"
+ direction="up"
+ variant="outlined"
+ onPick={onFile}
+ onCreate={onCreateAndFile}
+ />
+
+ {scope.kind === "category" && (
+ <button
+ type="button"
+ onClick={() => void onUnfileFromCurrent()}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-2 py-1.5 text-[11.5px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ >
+ <FolderMinus className="h-3.5 w-3.5" />
+ {t("Remove from category")}
+ </button>
+ )}
+
+ <button
+ type="button"
+ onClick={onClear}
+ title={t("Clear selection")}
+ className="rounded-lg p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ );
+}
diff --git a/web/components/space/question-bank/BankToolbar.tsx b/web/components/space/question-bank/BankToolbar.tsx
new file mode 100644
index 000000000..0c8fbb8e2
--- /dev/null
+++ b/web/components/space/question-bank/BankToolbar.tsx
@@ -0,0 +1,85 @@
+"use client";
+
+import { useTranslation } from "react-i18next";
+import { ArrowDownWideNarrow, Loader2, Search, Settings2, X } from "lucide-react";
+import type { BankSort } from "./useQuestionBank";
+
+interface BankToolbarProps {
+ search: string;
+ sort: BankSort;
+ refreshing: boolean;
+ managerOpen: boolean;
+ onSearchChange: (value: string) => void;
+ onSortChange: (sort: BankSort) => void;
+ onToggleManager: () => void;
+}
+
+/**
+ * Search + sort + the entry point to category management.
+ *
+ * Search is the other half of "I can't organize this": with a few hundred
+ * entries, filing the right ones starts with finding them.
+ */
+export default function BankToolbar({
+ search,
+ sort,
+ refreshing,
+ managerOpen,
+ onSearchChange,
+ onSortChange,
+ onToggleManager,
+}: BankToolbarProps) {
+ const { t } = useTranslation();
+
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="relative min-w-[200px] flex-1">
+ <Search className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--muted-foreground)]" />
+ <input
+ value={search}
+ onChange={(event) => onSearchChange(event.target.value)}
+ placeholder={t("Search questions and answers…")}
+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] py-1.5 pl-8 pr-8 text-[12.5px] text-[var(--foreground)] outline-none transition-colors placeholder:text-[var(--muted-foreground)] focus:border-[var(--primary)]/50"
+ />
+ {refreshing ? (
+ <Loader2 className="absolute right-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 animate-spin text-[var(--muted-foreground)]" />
+ ) : search ? (
+ <button
+ type="button"
+ onClick={() => onSearchChange("")}
+ title={t("Clear")}
+ className="absolute right-2.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ ) : null}
+ </div>
+
+ <button
+ type="button"
+ onClick={() => onSortChange(sort === "recent" ? "oldest" : "recent")}
+ title={t("Toggle sort order")}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--card)] px-2.5 py-1.5 text-[12px] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ >
+ <ArrowDownWideNarrow
+ className={`h-3.5 w-3.5 transition-transform ${sort === "oldest" ? "rotate-180" : ""}`}
+ />
+ {sort === "recent" ? t("Newest first") : t("Oldest first")}
+ </button>
+
+ <button
+ type="button"
+ onClick={onToggleManager}
+ title={t("Manage Categories")}
+ className={`inline-flex shrink-0 items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-[12px] transition-colors ${
+ managerOpen
+ ? "border-[var(--primary)]/40 bg-[var(--primary)]/10 text-[var(--primary)]"
+ : "border-[var(--border)] bg-[var(--card)] text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ }`}
+ >
+ <Settings2 className="h-3.5 w-3.5" />
+ {t("Manage Categories")}
+ </button>
+ </div>
+ );
+}
diff --git a/web/components/space/question-bank/CategoryManager.tsx b/web/components/space/question-bank/CategoryManager.tsx
new file mode 100644
index 000000000..5a3708118
--- /dev/null
+++ b/web/components/space/question-bank/CategoryManager.tsx
@@ -0,0 +1,176 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Check, Pencil, Plus, Trash2, X } from "lucide-react";
+import type { NotebookCategory } from "@/lib/notebook-api";
+
+interface CategoryManagerProps {
+ categories: NotebookCategory[];
+ onCreate: (name: string) => Promise<boolean>;
+ onRename: (id: number, name: string) => Promise<boolean>;
+ onDelete: (id: number) => Promise<boolean>;
+}
+
+/**
+ * Rename / delete / create categories.
+ *
+ * Filing lives on the entries themselves (see CategoryMenu); this panel is
+ * only for maintaining the set of names, which is a rarer job and does not
+ * belong in the way of the common one.
+ */
+export default function CategoryManager({
+ categories,
+ onCreate,
+ onRename,
+ onDelete,
+}: CategoryManagerProps) {
+ const { t } = useTranslation();
+ const [newName, setNewName] = useState("");
+ const [renaming, setRenaming] = useState<{ id: number; name: string } | null>(
+ null,
+ );
+ const [busy, setBusy] = useState(false);
+
+ const run = useCallback(async (action: () => Promise<boolean>) => {
+ setBusy(true);
+ try {
+ return await action();
+ } finally {
+ setBusy(false);
+ }
+ }, []);
+
+ const commitRename = useCallback(async () => {
+ if (!renaming?.name.trim()) {
+ setRenaming(null);
+ return;
+ }
+ const { id, name } = renaming;
+ if (await run(() => onRename(id, name))) setRenaming(null);
+ }, [onRename, renaming, run]);
+
+ return (
+ <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-3">
+ <div className="space-y-1">
+ {categories.map((category) => (
+ <div
+ key={category.id}
+ className="flex items-center justify-between gap-2 rounded-lg px-2.5 py-1.5 transition-colors hover:bg-[var(--muted)]/40"
+ >
+ {renaming?.id === category.id ? (
+ <>
+ <input
+ autoFocus
+ value={renaming.name}
+ disabled={busy}
+ onChange={(event) =>
+ setRenaming({ id: category.id, name: event.target.value })
+ }
+ onKeyDown={(event) => {
+ // Ignore the enter that confirms an IME candidate.
+ if (event.nativeEvent.isComposing) return;
+ if (event.key === "Enter") void commitRename();
+ if (event.key === "Escape") setRenaming(null);
+ }}
+ className="min-w-0 flex-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1 text-[12.5px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/50"
+ />
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => void commitRename()}
+ title={t("Save")}
+ className="rounded-md p-1 text-[var(--primary)] transition-colors hover:bg-[var(--muted)] disabled:opacity-40"
+ >
+ <Check size={13} />
+ </button>
+ <button
+ type="button"
+ onClick={() => setRenaming(null)}
+ title={t("Cancel")}
+ className="rounded-md p-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]"
+ >
+ <X size={13} />
+ </button>
+ </>
+ ) : (
+ <>
+ <span className="min-w-0 flex-1 truncate text-[12.5px] text-[var(--foreground)]">
+ {category.name}
+ <span className="ml-1.5 tabular-nums text-[11px] text-[var(--muted-foreground)]">
+ {category.entry_count}
+ </span>
+ </span>
+ <button
+ type="button"
+ onClick={() =>
+ setRenaming({ id: category.id, name: category.name })
+ }
+ title={t("Rename")}
+ className="rounded-md p-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ <Pencil size={13} />
+ </button>
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => {
+ // Deleting a category unfiles its questions; it never
+ // deletes them. Say so — the wording is the whole point
+ // of the prompt.
+ if (
+ window.confirm(
+ t(
+ "Delete this category? The questions themselves stay in your bank.",
+ ),
+ )
+ )
+ void run(() => onDelete(category.id));
+ }}
+ title={t("Delete")}
+ className="rounded-md p-1 text-[var(--muted-foreground)] transition-colors hover:bg-red-50 hover:text-red-500 disabled:opacity-40 dark:hover:bg-red-950/30"
+ >
+ <Trash2 size={13} />
+ </button>
+ </>
+ )}
+ </div>
+ ))}
+ {categories.length === 0 && (
+ <p className="py-2 text-center text-[12px] text-[var(--muted-foreground)]">
+ {t("No categories yet.")}
+ </p>
+ )}
+ </div>
+
+ <div className="mt-2.5 flex items-center gap-1.5 border-t border-[var(--border)]/70 pt-2.5">
+ <input
+ value={newName}
+ disabled={busy}
+ onChange={(event) => setNewName(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.nativeEvent.isComposing) return;
+ if (event.key !== "Enter" || !newName.trim()) return;
+ void run(() => onCreate(newName)).then((ok) => {
+ if (ok) setNewName("");
+ });
+ }}
+ placeholder={t("New category name...")}
+ className="min-w-0 flex-1 rounded-lg border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-[12px] text-[var(--foreground)] outline-none transition-colors placeholder:text-[var(--muted-foreground)] focus:border-[var(--primary)]/50"
+ />
+ <button
+ type="button"
+ disabled={busy || !newName.trim()}
+ onClick={() =>
+ void run(() => onCreate(newName)).then((ok) => {
+ if (ok) setNewName("");
+ })
+ }
+ className="shrink-0 rounded-lg bg-[var(--primary)] p-1.5 text-white transition-opacity disabled:opacity-30"
+ >
+ <Plus size={13} />
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/space/question-bank/CategoryMenu.tsx b/web/components/space/question-bank/CategoryMenu.tsx
new file mode 100644
index 000000000..83bee08fe
--- /dev/null
+++ b/web/components/space/question-bank/CategoryMenu.tsx
@@ -0,0 +1,205 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Check, FolderPlus, Loader2, Plus } from "lucide-react";
+import { notify } from "@/lib/notifications";
+import type { NotebookCategory } from "@/lib/notebook-api";
+
+interface CategoryMenuProps {
+ categories: NotebookCategory[];
+ /** Ids of the categories the target entries are already in. */
+ activeIds?: number[];
+ disabled?: boolean;
+ label?: string;
+ align?: "left" | "right";
+ /** Which way the panel opens. "up" for triggers pinned near the viewport
+ * bottom, where a downward panel would be clipped. */
+ direction?: "down" | "up";
+ /** "ghost" sits in an icon-button row (no border, like its neighbours);
+ * "outlined" stands alone with a label. */
+ variant?: "ghost" | "outlined";
+ /** Resolve `false` to say the write failed and the menu should stay put.
+ * Throwing works too — the menu reports that itself. */
+ onPick: (categoryId: number) => Promise<boolean | void> | boolean | void;
+ onUnpick?: (categoryId: number) => Promise<boolean | void> | boolean | void;
+ onCreate: (name: string) => Promise<boolean | void> | boolean | void;
+}
+
+/**
+ * The "file this into a set" control — the piece the bank never had.
+ *
+ * Creating and filing are one flow, not two screens: typing a new name and
+ * pressing enter files the target in the same gesture, which is what a
+ * learner means by "put these in a new mistakes set". Existing categories
+ * are listed first so the common case is one click and no typing.
+ */
+export default function CategoryMenu({
+ categories,
+ activeIds = [],
+ disabled = false,
+ label,
+ align = "right",
+ direction = "down",
+ variant = "ghost",
+ onPick,
+ onUnpick,
+ onCreate,
+}: CategoryMenuProps) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const [name, setName] = useState("");
+ const [busy, setBusy] = useState(false);
+ const rootRef = useRef<HTMLDivElement | null>(null);
+
+ // Close on outside press, not on blur: blur fires before the click that
+ // was meant for an item inside the menu and swallows it.
+ useEffect(() => {
+ if (!open) return;
+ const onPointerDown = (event: MouseEvent) => {
+ if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
+ };
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") setOpen(false);
+ };
+ document.addEventListener("mousedown", onPointerDown);
+ document.addEventListener("keydown", onKeyDown);
+ return () => {
+ document.removeEventListener("mousedown", onPointerDown);
+ document.removeEventListener("keydown", onKeyDown);
+ };
+ }, [open]);
+
+ // Callers that already report their own failures resolve normally; the
+ // ones that throw (the quiz viewer's direct API calls) are reported here,
+ // so no path can fail silently behind a closing menu.
+ const run = useCallback(
+ async (action: () => Promise<boolean | void> | boolean | void) => {
+ setBusy(true);
+ try {
+ // An explicit false means the caller already reported the failure.
+ return (await action()) !== false;
+ } catch (err) {
+ notify(err instanceof Error ? err.message : String(err), {
+ tone: "error",
+ });
+ return false;
+ } finally {
+ setBusy(false);
+ }
+ },
+ [],
+ );
+
+ const handleCreate = useCallback(async () => {
+ const trimmed = name.trim();
+ if (!trimmed) return;
+ const ok = await run(() => onCreate(trimmed));
+ if (ok) {
+ setName("");
+ setOpen(false);
+ }
+ }, [name, onCreate, run]);
+
+ const active = new Set(activeIds);
+
+ return (
+ <div ref={rootRef} className="relative">
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() => setOpen((v) => !v)}
+ title={t("Add to category")}
+ className={`inline-flex items-center gap-1.5 rounded-lg text-[11.5px] font-medium transition-colors disabled:opacity-40 ${
+ variant === "outlined" ? "border px-2 py-1.5" : "p-1.5"
+ } ${
+ open
+ ? variant === "outlined"
+ ? "border-[var(--primary)]/40 bg-[var(--primary)]/10 text-[var(--primary)]"
+ : "bg-[var(--muted)]/60 text-[var(--primary)]"
+ : variant === "outlined"
+ ? "border-[var(--border)] text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ }`}
+ >
+ <FolderPlus className="h-3.5 w-3.5" />
+ {label ? <span>{label}</span> : null}
+ </button>
+
+ {open && (
+ <div
+ className={`absolute z-30 w-60 overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--card)] shadow-lg ${
+ align === "right" ? "right-0" : "left-0"
+ } ${direction === "up" ? "bottom-full mb-1.5" : "mt-1.5"}`}
+ >
+ <div className="max-h-56 overflow-y-auto p-1.5">
+ {categories.length === 0 && (
+ <p className="px-2 py-3 text-center text-[11.5px] text-[var(--muted-foreground)]">
+ {t("No categories yet. Type a name below to create one.")}
+ </p>
+ )}
+ {categories.map((category) => {
+ const isActive = active.has(category.id);
+ return (
+ <button
+ key={category.id}
+ type="button"
+ disabled={busy}
+ onClick={() =>
+ void run(() =>
+ isActive ? onUnpick?.(category.id) : onPick(category.id),
+ ).then((ok) => {
+ if (ok) setOpen(false);
+ })
+ }
+ className="flex w-full items-center justify-between gap-2 rounded-lg px-2.5 py-1.5 text-left text-[12.5px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/70 disabled:opacity-50"
+ >
+ <span className="min-w-0 flex-1 truncate">
+ {category.name}
+ </span>
+ {isActive ? (
+ <Check className="h-3.5 w-3.5 shrink-0 text-[var(--primary)]" />
+ ) : (
+ <span className="shrink-0 text-[10.5px] tabular-nums text-[var(--muted-foreground)]">
+ {category.entry_count}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+
+ <div className="flex items-center gap-1.5 border-t border-[var(--border)]/70 p-1.5">
+ <input
+ value={name}
+ autoFocus={categories.length === 0}
+ disabled={busy}
+ onChange={(event) => setName(event.target.value)}
+ onKeyDown={(event) => {
+ // An IME's enter confirms the candidate word; committing on it
+ // would file a half-typed 中文 name.
+ if (event.key === "Enter" && !event.nativeEvent.isComposing)
+ void handleCreate();
+ }}
+ placeholder={t("New category…")}
+ className="min-w-0 flex-1 rounded-lg border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-[12px] text-[var(--foreground)] outline-none transition-colors placeholder:text-[var(--muted-foreground)] focus:border-[var(--primary)]/50"
+ />
+ <button
+ type="button"
+ disabled={busy || !name.trim()}
+ onClick={() => void handleCreate()}
+ title={t("Create and add")}
+ className="shrink-0 rounded-lg bg-[var(--primary)] p-1.5 text-white transition-opacity disabled:opacity-30"
+ >
+ {busy ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Plus className="h-3.5 w-3.5" />
+ )}
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/space/question-bank/QuestionBankSection.tsx b/web/components/space/question-bank/QuestionBankSection.tsx
new file mode 100644
index 000000000..07e13e031
--- /dev/null
+++ b/web/components/space/question-bank/QuestionBankSection.tsx
@@ -0,0 +1,216 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { AlertTriangle, ClipboardList, Inbox, Loader2, Search } from "lucide-react";
+import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";
+import BankScopeRail from "./BankScopeRail";
+import BankSelectionBar from "./BankSelectionBar";
+import BankToolbar from "./BankToolbar";
+import CategoryManager from "./CategoryManager";
+import QuestionCard from "./QuestionCard";
+import { useQuestionBank } from "./useQuestionBank";
+
+function EmptyState({
+ icon: Icon,
+ title,
+ hint,
+}: {
+ icon: typeof ClipboardList;
+ title: string;
+ hint: string;
+}) {
+ return (
+ <div className="flex min-h-[300px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
+ <div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
+ <Icon size={18} />
+ </div>
+ <p className="text-[14px] font-medium text-[var(--foreground)]">{title}</p>
+ <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
+ {hint}
+ </p>
+ </div>
+ );
+}
+
+/**
+ * Learning Space → Question Bank.
+ *
+ * Everything stateful lives in ``useQuestionBank``; this file is layout and
+ * which empty state to show. The three jobs it has to support are review
+ * (read a question back), triage (work the unfiled pile down), and filing
+ * (put questions into a set) — the last one being what the surface used to
+ * make impossible: categories could be created but never filled.
+ */
+export default function QuestionBankSection() {
+ const { t } = useTranslation();
+ const bank = useQuestionBank();
+ const [managerOpen, setManagerOpen] = useState(false);
+
+ const selectedIds = Array.from(bank.selectedIds);
+ const searching = bank.searchInput.trim().length > 0;
+
+ return (
+ <div className="space-y-3">
+ <SpaceSectionHeader
+ icon={ClipboardList}
+ title={t("Question Bank")}
+ description={t(
+ "Review and organize quiz questions across sessions. Bookmark items, group them into categories, and jump back to the original chat.",
+ )}
+ meta={
+ <span className="rounded-full border border-[var(--border)] bg-[var(--card)] px-2 py-0.5 text-[10.5px] font-medium text-[var(--muted-foreground)]">
+ {bank.stats.total} {t("questions.count.suffix")}
+ </span>
+ }
+ />
+
+ <BankToolbar
+ search={bank.searchInput}
+ sort={bank.sort}
+ refreshing={bank.refreshing}
+ managerOpen={managerOpen}
+ onSearchChange={bank.setSearchInput}
+ onSortChange={bank.setSort}
+ onToggleManager={() => setManagerOpen((open) => !open)}
+ />
+
+ {managerOpen && (
+ <CategoryManager
+ categories={bank.categories}
+ onCreate={bank.addCategory}
+ onRename={bank.renameExistingCategory}
+ onDelete={bank.removeCategory}
+ />
+ )}
+
+ <BankScopeRail
+ scope={bank.scope}
+ stats={bank.stats}
+ categories={bank.categories}
+ onSelect={bank.setScope}
+ />
+
+ {bank.loading ? (
+ <div className="flex min-h-[300px] items-center justify-center">
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ ) : bank.error ? (
+ <div className="flex min-h-[300px] flex-col items-center justify-center rounded-xl border border-dashed border-red-300 text-center dark:border-red-900">
+ <div className="mb-3 rounded-xl bg-red-50 p-2.5 text-red-500 dark:bg-red-950/30">
+ <AlertTriangle size={18} />
+ </div>
+ <p className="text-[14px] font-medium text-[var(--foreground)]">
+ {t("Failed to load entries")}
+ </p>
+ <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
+ {bank.error}
+ </p>
+ <button
+ type="button"
+ onClick={() => void bank.refresh()}
+ className="mt-3 rounded-lg bg-[var(--primary)] px-4 py-1.5 text-[12px] font-medium text-white"
+ >
+ {t("Retry")}
+ </button>
+ </div>
+ ) : bank.items.length === 0 ? (
+ searching ? (
+ <EmptyState
+ icon={Search}
+ title={t("No matching questions")}
+ hint={t("Try a different word, or clear the search to see everything.")}
+ />
+ ) : bank.scope.kind === "uncategorized" ? (
+ <EmptyState
+ icon={Inbox}
+ title={t("Everything is filed")}
+ hint={t("No questions are waiting to be sorted into a category.")}
+ />
+ ) : bank.stats.total === 0 ? (
+ <EmptyState
+ icon={ClipboardList}
+ title={t("No entries yet")}
+ hint={t("Questions from your quizzes will appear here.")}
+ />
+ ) : (
+ <EmptyState
+ icon={ClipboardList}
+ title={t("Nothing in this view")}
+ hint={t("Switch to another filter to see your other questions.")}
+ />
+ )
+ ) : (
+ <>
+ <ul
+ className={`flex flex-col gap-2.5 transition-opacity ${
+ bank.refreshing ? "opacity-60" : ""
+ }`}
+ >
+ {bank.items.map((entry) => (
+ <QuestionCard
+ key={entry.id}
+ entry={entry}
+ categories={bank.categories}
+ selected={bank.selectedIds.has(entry.id)}
+ disabled={bank.pendingIds.has(entry.id)}
+ onToggleSelected={() => bank.toggleSelected(entry.id)}
+ onToggleBookmark={() => void bank.toggleBookmark(entry)}
+ onDelete={() => {
+ if (window.confirm(t("Delete this entry?")))
+ void bank.removeEntry(entry);
+ }}
+ onFile={(categoryId) => bank.fileEntries([entry.id], categoryId)}
+ onUnfile={(categoryId) =>
+ bank.unfileEntries([entry.id], categoryId)
+ }
+ onCreateAndFile={(name) =>
+ bank.fileIntoNewCategory([entry.id], name)
+ }
+ />
+ ))}
+ </ul>
+
+ {bank.total > bank.items.length && (
+ <p className="pt-1 text-center text-[11.5px] text-[var(--muted-foreground)]">
+ {t("Showing {{shown}} of {{total}} — narrow the view to see the rest.", {
+ shown: bank.items.length,
+ total: bank.total,
+ })}
+ </p>
+ )}
+
+ <BankSelectionBar
+ count={selectedIds.length}
+ visibleCount={bank.items.length}
+ scope={bank.scope}
+ categories={bank.categories}
+ onSelectAll={bank.selectAll}
+ onClear={bank.clearSelection}
+ // Clear the selection only when the write landed — a failed
+ // bulk action should leave the rows staged for a retry.
+ onFile={async (categoryId) => {
+ const ok = await bank.fileEntries(selectedIds, categoryId);
+ if (ok) bank.clearSelection();
+ return ok;
+ }}
+ onCreateAndFile={async (name) => {
+ const ok = await bank.fileIntoNewCategory(selectedIds, name);
+ if (ok) bank.clearSelection();
+ return ok;
+ }}
+ onUnfileFromCurrent={async () => {
+ if (bank.scope.kind !== "category") return false;
+ const ok = await bank.unfileEntries(
+ selectedIds,
+ bank.scope.categoryId,
+ );
+ if (ok) bank.clearSelection();
+ return ok;
+ }}
+ />
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/space/question-bank/QuestionCard.tsx b/web/components/space/question-bank/QuestionCard.tsx
new file mode 100644
index 000000000..f3320bd79
--- /dev/null
+++ b/web/components/space/question-bank/QuestionCard.tsx
@@ -0,0 +1,337 @@
+"use client";
+
+import dynamic from "next/dynamic";
+import Link from "next/link";
+import { useTranslation } from "react-i18next";
+import {
+ Bookmark,
+ ExternalLink,
+ MessageSquare,
+ Trash2,
+ X,
+} from "lucide-react";
+import type { NotebookCategory, NotebookEntry } from "@/lib/notebook-api";
+import CategoryMenu from "./CategoryMenu";
+
+const MarkdownRenderer = dynamic(
+ () => import("@/components/common/MarkdownRenderer"),
+ { ssr: false },
+);
+
+interface QuestionCardProps {
+ entry: NotebookEntry;
+ categories: NotebookCategory[];
+ selected: boolean;
+ disabled: boolean;
+ onToggleSelected: () => void;
+ onToggleBookmark: () => void;
+ onDelete: () => void;
+ onFile: (categoryId: number) => Promise<boolean>;
+ onUnfile: (categoryId: number) => Promise<boolean>;
+ onCreateAndFile: (name: string) => Promise<boolean>;
+}
+
+function AnswerBlock({
+ label,
+ body,
+ tone,
+ isCode,
+}: {
+ label: string;
+ body: string;
+ tone: "correct" | "wrong" | "neutral";
+ isCode: boolean;
+}) {
+ const toneClass =
+ tone === "wrong"
+ ? "border-red-200/60 bg-red-50/40 dark:border-red-900/40 dark:bg-red-950/15"
+ : tone === "correct"
+ ? "border-green-200/60 bg-green-50/40 dark:border-green-900/40 dark:bg-green-950/15"
+ : "border-[var(--border)] bg-[var(--muted)]/30";
+ const labelClass =
+ tone === "wrong"
+ ? "text-red-500 dark:text-red-400"
+ : tone === "correct"
+ ? "text-green-600 dark:text-green-400"
+ : "text-[var(--muted-foreground)]";
+
+ return (
+ <div className={`rounded-lg border px-3 py-2 ${toneClass}`}>
+ <div
+ className={`mb-1 text-[10.5px] font-medium uppercase tracking-wide ${labelClass}`}
+ >
+ {label}
+ </div>
+ <div className="text-[13px] text-[var(--foreground)]">
+ {body ? (
+ <MarkdownRenderer
+ content={
+ isCode && !body.trimStart().startsWith("```")
+ ? `\`\`\`python\n${body}\n\`\`\``
+ : body
+ }
+ variant="prose"
+ className="text-[13px] leading-relaxed"
+ />
+ ) : (
+ <span className="text-[var(--muted-foreground)]">—</span>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * One bank entry.
+ *
+ * Reading comes first — question, what was answered, what was right — and
+ * the organising controls sit in the header where they are reachable
+ * without scrolling past the explanation.
+ */
+export default function QuestionCard({
+ entry,
+ categories,
+ selected,
+ disabled,
+ onToggleSelected,
+ onToggleBookmark,
+ onDelete,
+ onFile,
+ onUnfile,
+ onCreateAndFile,
+}: QuestionCardProps) {
+ const { t } = useTranslation();
+ const options = entry.options || {};
+ const hasOptions = Object.keys(options).length > 0;
+ const isCode = entry.question_type === "coding";
+ const filed = entry.categories || [];
+
+ return (
+ <li
+ className={`group rounded-xl border bg-[var(--card)] px-4 py-3.5 transition-all ${
+ selected
+ ? "border-[var(--primary)]/50 shadow-sm ring-1 ring-[var(--primary)]/20"
+ : "border-[var(--border)] hover:border-[var(--border)] hover:shadow-sm"
+ } ${disabled ? "pointer-events-none opacity-50" : ""}`}
+ >
+ <div className="flex items-start gap-3">
+ <input
+ type="checkbox"
+ checked={selected}
+ onChange={onToggleSelected}
+ aria-label={t("Select")}
+ className={`mt-1 h-3.5 w-3.5 shrink-0 cursor-pointer accent-[var(--primary)] transition-opacity ${
+ selected ? "opacity-100" : "opacity-0 group-hover:opacity-100"
+ }`}
+ />
+
+ <div className="min-w-0 flex-1">
+ <div className="mb-1.5 flex flex-wrap items-center gap-1.5">
+ <span
+ className={`rounded-md px-1.5 py-0.5 text-[10px] font-semibold ${
+ entry.is_correct
+ ? "bg-green-100 text-green-700 dark:bg-green-950/30 dark:text-green-400"
+ : "bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400"
+ }`}
+ >
+ {entry.is_correct ? t("Correct") : t("Incorrect")}
+ </span>
+ {entry.difficulty && (
+ <span
+ className={`rounded-md px-1.5 py-0.5 text-[10px] font-medium uppercase ${
+ entry.difficulty === "hard"
+ ? "bg-red-50 text-red-600 dark:bg-red-950/30 dark:text-red-400"
+ : entry.difficulty === "medium"
+ ? "bg-amber-50 text-amber-600 dark:bg-amber-950/30 dark:text-amber-400"
+ : "bg-green-50 text-green-600 dark:bg-green-950/30 dark:text-green-400"
+ }`}
+ >
+ {entry.difficulty}
+ </span>
+ )}
+ {entry.question_type && (
+ <span className="rounded-md bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">
+ {entry.question_type}
+ </span>
+ )}
+ </div>
+
+ <div className="text-[14px] font-medium text-[var(--foreground)]">
+ <MarkdownRenderer
+ content={entry.question}
+ variant="prose"
+ className="text-[14px] leading-relaxed"
+ />
+ </div>
+ </div>
+
+ <div className="flex shrink-0 items-center gap-1">
+ <CategoryMenu
+ categories={categories}
+ activeIds={filed.map((category) => category.id)}
+ disabled={disabled}
+ onPick={onFile}
+ onUnpick={onUnfile}
+ onCreate={onCreateAndFile}
+ />
+ <button
+ type="button"
+ onClick={onToggleBookmark}
+ disabled={disabled}
+ title={entry.bookmarked ? t("Remove Bookmark") : t("Bookmark")}
+ className={`rounded-lg p-1.5 transition-colors disabled:opacity-40 ${
+ entry.bookmarked
+ ? "text-[var(--primary)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ }`}
+ >
+ <Bookmark
+ className="h-3.5 w-3.5"
+ fill={entry.bookmarked ? "currentColor" : "none"}
+ />
+ </button>
+ <button
+ type="button"
+ onClick={onDelete}
+ disabled={disabled}
+ title={t("Delete")}
+ className="rounded-lg p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-red-50 hover:text-red-500 disabled:opacity-40 dark:hover:bg-red-950/30"
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ </div>
+
+ {/* Aligned with the question text: checkbox (0.875rem) + gap (0.75rem). */}
+ <div className="mt-3 space-y-2" style={{ paddingLeft: "1.625rem" }}>
+ {hasOptions && (
+ <div className="space-y-1">
+ {Object.entries(options).map(([key, text]) => {
+ const isUserAnswer =
+ entry.user_answer?.toUpperCase() === key.toUpperCase();
+ const isCorrectAnswer =
+ entry.correct_answer?.toUpperCase() === key.toUpperCase();
+ const isWrongPick = isUserAnswer && !entry.is_correct;
+ return (
+ <div
+ key={key}
+ className={`flex items-start gap-2.5 rounded-lg border px-3 py-1.5 text-[13px] ${
+ isCorrectAnswer
+ ? "border-green-200 bg-green-50/60 dark:border-green-900 dark:bg-green-950/20"
+ : isWrongPick
+ ? "border-red-200 bg-red-50/60 dark:border-red-900 dark:bg-red-950/20"
+ : "border-transparent bg-[var(--muted)]/30"
+ }`}
+ >
+ <span
+ className={`mt-px shrink-0 font-semibold ${
+ isCorrectAnswer
+ ? "text-green-600 dark:text-green-400"
+ : isWrongPick
+ ? "text-red-600 dark:text-red-400"
+ : "text-[var(--muted-foreground)]"
+ }`}
+ >
+ {key}.
+ </span>
+ <span
+ className={`flex-1 ${
+ isCorrectAnswer || isWrongPick
+ ? "text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)]"
+ }`}
+ >
+ {text}
+ </span>
+ {isCorrectAnswer && (
+ <span className="mt-px shrink-0 text-[10px] font-medium text-green-600 dark:text-green-400">
+ ✓ {t("Correct")}
+ </span>
+ )}
+ {isWrongPick && (
+ <span className="mt-px shrink-0 text-[10px] font-medium text-red-600 dark:text-red-400">
+ ✗ {t("Your pick")}
+ </span>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {!hasOptions && (
+ <div className="grid gap-2 sm:grid-cols-2">
+ <AnswerBlock
+ label={`${t("Your Answer")} ${entry.is_correct ? "✓" : "✗"}`}
+ body={entry.user_answer}
+ tone={entry.is_correct ? "correct" : "wrong"}
+ isCode={isCode}
+ />
+ <AnswerBlock
+ label={t("Reference Answer")}
+ body={entry.correct_answer}
+ tone="correct"
+ isCode={isCode}
+ />
+ </div>
+ )}
+
+ {entry.explanation && (
+ <div className="rounded-lg border border-blue-200/60 bg-blue-50/30 px-3 py-2 dark:border-blue-900/40 dark:bg-blue-950/15">
+ <div className="mb-1 text-[10.5px] font-medium uppercase tracking-wide text-blue-600 dark:text-blue-400">
+ {t("Explanation")}
+ </div>
+ <div className="text-[13px] leading-relaxed text-[var(--foreground)]">
+ <MarkdownRenderer
+ content={entry.explanation}
+ variant="prose"
+ className="text-[13px] leading-relaxed"
+ />
+ </div>
+ </div>
+ )}
+
+ <div className="flex flex-wrap items-center justify-between gap-2 pt-0.5 text-[11px]">
+ <div className="flex flex-wrap items-center gap-1.5">
+ {filed.map((category) => (
+ <span
+ key={category.id}
+ className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] bg-[var(--muted)]/40 py-0.5 pl-2 pr-1 text-[var(--muted-foreground)]"
+ >
+ {category.name}
+ <button
+ type="button"
+ onClick={() => void onUnfile(category.id)}
+ disabled={disabled}
+ title={t("Remove from category")}
+ className="rounded p-0.5 transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-40"
+ >
+ <X className="h-2.5 w-2.5" />
+ </button>
+ </span>
+ ))}
+ <Link
+ href={`/?session=${encodeURIComponent(entry.session_id)}`}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--muted)]/40 px-2 py-0.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ <ExternalLink size={10} />
+ {entry.session_title || t("Original Session")}
+ </Link>
+ {entry.followup_session_id && (
+ <Link
+ href={`/?session=${encodeURIComponent(entry.followup_session_id)}`}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--muted)]/40 px-2 py-0.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ <MessageSquare size={10} />
+ {t("Follow-up")}
+ </Link>
+ )}
+ </div>
+ <span className="text-[var(--muted-foreground)]">
+ {new Date(entry.created_at * 1000).toLocaleString()}
+ </span>
+ </div>
+ </div>
+ </li>
+ );
+}
diff --git a/web/components/space/question-bank/index.ts b/web/components/space/question-bank/index.ts
new file mode 100644
index 000000000..8c2a88d9a
--- /dev/null
+++ b/web/components/space/question-bank/index.ts
@@ -0,0 +1,4 @@
+export { default as QuestionBankSection } from "./QuestionBankSection";
+export { default as CategoryMenu } from "./CategoryMenu";
+export { useQuestionBank } from "./useQuestionBank";
+export type { BankScope, BankSort } from "./useQuestionBank";
diff --git a/web/components/space/question-bank/useQuestionBank.ts b/web/components/space/question-bank/useQuestionBank.ts
new file mode 100644
index 000000000..816bbfc57
--- /dev/null
+++ b/web/components/space/question-bank/useQuestionBank.ts
@@ -0,0 +1,422 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { notify } from "@/lib/notifications";
+import {
+ addEntryToCategory,
+ bulkLinkEntriesToCategory,
+ createCategory,
+ deleteCategory,
+ deleteNotebookEntry,
+ getQuestionBankStats,
+ listCategories,
+ listNotebookEntries,
+ removeEntryFromCategory,
+ renameCategory,
+ updateNotebookEntry,
+ type NotebookCategory,
+ type NotebookEntry,
+ type QuestionBankStats,
+} from "@/lib/notebook-api";
+
+/**
+ * What the learner is currently looking at.
+ *
+ * A discriminated union rather than two independent pieces of state: a
+ * filter and a category are two views of the same axis, and holding them
+ * separately makes "wrong answers, but also inside category 3, but also
+ * uncategorized" representable when it is not a real thing.
+ */
+export type BankScope =
+ | { kind: "all" | "wrong" | "bookmarked" | "uncategorized" }
+ | { kind: "category"; categoryId: number };
+
+export type BankSort = "recent" | "oldest";
+
+/** Entries fetched per page. The bank is a review surface, not a feed. */
+const PAGE_SIZE = 60;
+const SEARCH_DEBOUNCE_MS = 250;
+
+export const DEFAULT_SCOPE: BankScope = { kind: "all" };
+
+function scopeToFilter(scope: BankScope, search: string, sort: BankSort) {
+ return {
+ category_id: scope.kind === "category" ? scope.categoryId : undefined,
+ uncategorized: scope.kind === "uncategorized" || undefined,
+ bookmarked: scope.kind === "bookmarked" ? true : undefined,
+ is_correct: scope.kind === "wrong" ? false : undefined,
+ search: search || undefined,
+ sort,
+ limit: PAGE_SIZE,
+ };
+}
+
+export interface QuestionBankController {
+ items: NotebookEntry[];
+ total: number;
+ categories: NotebookCategory[];
+ stats: QuestionBankStats;
+ scope: BankScope;
+ sort: BankSort;
+ searchInput: string;
+ loading: boolean;
+ /** True while re-fetching an already-rendered list (keeps content visible). */
+ refreshing: boolean;
+ error: string | null;
+ pendingIds: ReadonlySet<number>;
+ selectedIds: ReadonlySet<number>;
+
+ setScope: (scope: BankScope) => void;
+ setSort: (sort: BankSort) => void;
+ setSearchInput: (value: string) => void;
+ refresh: () => Promise<void>;
+
+ toggleSelected: (id: number) => void;
+ selectAll: () => void;
+ clearSelection: () => void;
+
+ // Mutations resolve to whether the write landed. Failures are reported
+ // once, as a toast, from inside the hook — the boolean is for the caller's
+ // own UI decisions (keep the menu open, keep the typed name).
+ toggleBookmark: (entry: NotebookEntry) => Promise<boolean>;
+ removeEntry: (entry: NotebookEntry) => Promise<boolean>;
+ fileEntries: (ids: number[], categoryId: number) => Promise<boolean>;
+ unfileEntries: (ids: number[], categoryId: number) => Promise<boolean>;
+ fileIntoNewCategory: (ids: number[], name: string) => Promise<boolean>;
+
+ addCategory: (name: string) => Promise<boolean>;
+ renameExistingCategory: (id: number, name: string) => Promise<boolean>;
+ removeCategory: (id: number) => Promise<boolean>;
+}
+
+const EMPTY_STATS: QuestionBankStats = {
+ total: 0,
+ wrong: 0,
+ bookmarked: 0,
+ uncategorized: 0,
+};
+
+/**
+ * Owns every piece of question-bank state so the views stay presentational.
+ *
+ * Two rules keep the surface honest under mutation:
+ * - counts (`stats`, category `entry_count`) are re-read from the server
+ * after any write, never patched locally, because filing one entry moves
+ * several counters at once;
+ * - a re-fetch never blanks the list — `refreshing` dims it instead, so
+ * filing a question does not make the page jump.
+ */
+export function useQuestionBank(): QuestionBankController {
+ const [items, setItems] = useState<NotebookEntry[]>([]);
+ const [total, setTotal] = useState(0);
+ const [categories, setCategories] = useState<NotebookCategory[]>([]);
+ const [stats, setStats] = useState<QuestionBankStats>(EMPTY_STATS);
+ const [scope, setScopeState] = useState<BankScope>(DEFAULT_SCOPE);
+ const [sort, setSort] = useState<BankSort>("recent");
+ const [searchInput, setSearchInput] = useState("");
+ const [search, setSearch] = useState("");
+ const [loading, setLoading] = useState(true);
+ const [refreshing, setRefreshing] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [pendingIds, setPendingIds] = useState<ReadonlySet<number>>(new Set());
+ const [selectedIds, setSelectedIds] = useState<ReadonlySet<number>>(
+ new Set(),
+ );
+
+ const loadedOnce = useRef(false);
+ // Guards against an older in-flight list response overwriting a newer one
+ // when the learner clicks through filters faster than the network answers.
+ const requestSeq = useRef(0);
+
+ useEffect(() => {
+ const timer = setTimeout(
+ () => setSearch(searchInput.trim()),
+ SEARCH_DEBOUNCE_MS,
+ );
+ return () => clearTimeout(timer);
+ }, [searchInput]);
+
+ const loadEntries = useCallback(async () => {
+ const seq = ++requestSeq.current;
+ if (loadedOnce.current) setRefreshing(true);
+ setError(null);
+ try {
+ const response = await listNotebookEntries(
+ scopeToFilter(scope, search, sort),
+ );
+ if (seq !== requestSeq.current) return;
+ setItems(response.items);
+ setTotal(response.total);
+ // Converge the selection onto the new rows: searching, re-sorting or a
+ // refresh after a write can all drop a selected row out of view, and a
+ // bulk action must never reach something off screen.
+ const visible = new Set(response.items.map((item) => item.id));
+ setSelectedIds((prev) => {
+ if (prev.size === 0) return prev;
+ const next = new Set([...prev].filter((id) => visible.has(id)));
+ return next.size === prev.size ? prev : next;
+ });
+ } catch (err) {
+ if (seq !== requestSeq.current) return;
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ if (seq === requestSeq.current) {
+ loadedOnce.current = true;
+ setLoading(false);
+ setRefreshing(false);
+ }
+ }
+ }, [scope, search, sort]);
+
+ const loadMeta = useCallback(async () => {
+ const [nextCategories, nextStats] = await Promise.allSettled([
+ listCategories(),
+ getQuestionBankStats(),
+ ]);
+ if (nextCategories.status === "fulfilled")
+ setCategories(nextCategories.value);
+ if (nextStats.status === "fulfilled") setStats(nextStats.value);
+ }, []);
+
+ useEffect(() => {
+ void loadEntries();
+ }, [loadEntries]);
+
+ useEffect(() => {
+ void loadMeta();
+ }, [loadMeta]);
+
+ // Selection is scoped to what is on screen: switching filters must not
+ // leave invisible rows staged for a bulk action.
+ const setScope = useCallback((next: BankScope) => {
+ setSelectedIds(new Set());
+ setScopeState(next);
+ }, []);
+
+ const refresh = useCallback(async () => {
+ await Promise.all([loadEntries(), loadMeta()]);
+ }, [loadEntries, loadMeta]);
+
+ /**
+ * Run a write and report it if it fails.
+ *
+ * Every mutation here used to swallow its error, so a rejected rename or
+ * a duplicate category name looked exactly like a no-op click. The server
+ * sends a reason; the learner should get it.
+ */
+ const attempt = useCallback(async (action: () => Promise<void>) => {
+ try {
+ await action();
+ return true;
+ } catch (err) {
+ notify(err instanceof Error ? err.message : String(err), {
+ tone: "error",
+ });
+ return false;
+ }
+ }, []);
+
+ const withPending = useCallback(
+ async (ids: number[], action: () => Promise<void>) => {
+ setPendingIds((prev) => new Set([...prev, ...ids]));
+ try {
+ return await attempt(action);
+ } finally {
+ setPendingIds((prev) => {
+ const next = new Set(prev);
+ ids.forEach((id) => next.delete(id));
+ return next;
+ });
+ }
+ },
+ [attempt],
+ );
+
+ const toggleSelected = useCallback((id: number) => {
+ setSelectedIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+ }, []);
+
+ const selectAll = useCallback(() => {
+ setSelectedIds(new Set(items.map((item) => item.id)));
+ }, [items]);
+
+ const clearSelection = useCallback(() => setSelectedIds(new Set()), []);
+
+ const toggleBookmark = useCallback(
+ async (entry: NotebookEntry) => {
+ const next = !entry.bookmarked;
+ return withPending([entry.id], async () => {
+ await updateNotebookEntry(entry.id, { bookmarked: next });
+ // Optimistic on the row itself; the counters come back from refresh.
+ setItems((prev) =>
+ prev.map((item) =>
+ item.id === entry.id ? { ...item, bookmarked: next } : item,
+ ),
+ );
+ await refresh();
+ });
+ },
+ [refresh, withPending],
+ );
+
+ const removeEntry = useCallback(
+ async (entry: NotebookEntry) => {
+ return withPending([entry.id], async () => {
+ await deleteNotebookEntry(entry.id);
+ setSelectedIds((prev) => {
+ const next = new Set(prev);
+ next.delete(entry.id);
+ return next;
+ });
+ await refresh();
+ });
+ },
+ [refresh, withPending],
+ );
+
+ const fileEntries = useCallback(
+ async (ids: number[], categoryId: number) => {
+ if (!ids.length) return false;
+ return withPending(ids, async () => {
+ // The single-entry endpoint 404s on a stale id; the bulk one reports
+ // 0 changed. For a one-row action the sharper error is worth the
+ // separate call.
+ if (ids.length === 1) await addEntryToCategory(ids[0], categoryId);
+ else await bulkLinkEntriesToCategory(ids, categoryId, true);
+ await refresh();
+ });
+ },
+ [refresh, withPending],
+ );
+
+ const unfileEntries = useCallback(
+ async (ids: number[], categoryId: number) => {
+ if (!ids.length) return false;
+ return withPending(ids, async () => {
+ if (ids.length === 1)
+ await removeEntryFromCategory(ids[0], categoryId);
+ else await bulkLinkEntriesToCategory(ids, categoryId, false);
+ await refresh();
+ });
+ },
+ [refresh, withPending],
+ );
+
+ const fileIntoNewCategory = useCallback(
+ async (ids: number[], name: string) => {
+ const trimmed = name.trim();
+ if (!trimmed) return false;
+ return attempt(async () => {
+ const created = await createCategory(trimmed);
+ if (ids.length) await fileEntries(ids, created.id);
+ else await loadMeta();
+ });
+ },
+ [attempt, fileEntries, loadMeta],
+ );
+
+ const addCategory = useCallback(
+ async (name: string) => {
+ const trimmed = name.trim();
+ if (!trimmed) return false;
+ return attempt(async () => {
+ await createCategory(trimmed);
+ await loadMeta();
+ });
+ },
+ [attempt, loadMeta],
+ );
+
+ const renameExistingCategory = useCallback(
+ async (id: number, name: string) => {
+ const trimmed = name.trim();
+ if (!trimmed) return false;
+ return attempt(async () => {
+ await renameCategory(id, trimmed);
+ await refresh();
+ });
+ },
+ [attempt, refresh],
+ );
+
+ const removeCategory = useCallback(
+ async (id: number) => {
+ return attempt(async () => {
+ await deleteCategory(id);
+ // Deleting the category being viewed would otherwise leave the list
+ // filtered by an id the server no longer knows.
+ setScopeState((prev) =>
+ prev.kind === "category" && prev.categoryId === id
+ ? DEFAULT_SCOPE
+ : prev,
+ );
+ await refresh();
+ });
+ },
+ [attempt, refresh],
+ );
+
+ return useMemo(
+ () => ({
+ items,
+ total,
+ categories,
+ stats,
+ scope,
+ sort,
+ searchInput,
+ loading,
+ refreshing,
+ error,
+ pendingIds,
+ selectedIds,
+ setScope,
+ setSort,
+ setSearchInput,
+ refresh,
+ toggleSelected,
+ selectAll,
+ clearSelection,
+ toggleBookmark,
+ removeEntry,
+ fileEntries,
+ unfileEntries,
+ fileIntoNewCategory,
+ addCategory,
+ renameExistingCategory,
+ removeCategory,
+ }),
+ [
+ items,
+ total,
+ categories,
+ stats,
+ scope,
+ sort,
+ searchInput,
+ loading,
+ refreshing,
+ error,
+ pendingIds,
+ selectedIds,
+ setScope,
+ refresh,
+ toggleSelected,
+ selectAll,
+ clearSelection,
+ toggleBookmark,
+ removeEntry,
+ fileEntries,
+ unfileEntries,
+ fileIntoNewCategory,
+ addCategory,
+ renameExistingCategory,
+ removeCategory,
+ ],
+ );
+}
diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.ts
index afeeab53d..040f51817 100644
--- a/web/lib/notebook-api.ts
+++ b/web/lib/notebook-api.ts
@@ -232,29 +232,47 @@ export interface NotebookEntryListResponse {
async function expectJson<T>(response: Response): Promise<T> {
if (!response.ok) {
- throw new Error(`Request failed: ${response.status}`);
+ // Surface FastAPI's `detail` when there is one: "A category named 'Math'
+ // already exists" is actionable, "Request failed: 409" is not.
+ let detail = "";
+ try {
+ const body = await response.json();
+ if (typeof body?.detail === "string") detail = body.detail;
+ } catch {
+ /* non-JSON error body — fall back to the status line */
+ }
+ throw new Error(detail || `Request failed: ${response.status}`);
}
return response.json() as Promise<T>;
}
// ── Entries ──────────────────────────────────────────────────────
+export interface NotebookEntryFilter {
+ category_id?: number;
+ /** Only entries in no category at all — the triage inbox. */
+ uncategorized?: boolean;
+ bookmarked?: boolean;
+ is_correct?: boolean;
+ search?: string;
+ sort?: "recent" | "oldest";
+ limit?: number;
+ offset?: number;
+}
+
export async function listNotebookEntries(
- filter: {
- category_id?: number;
- bookmarked?: boolean;
- is_correct?: boolean;
- limit?: number;
- offset?: number;
- } = {},
+ filter: NotebookEntryFilter = {},
): Promise<NotebookEntryListResponse> {
const params = new URLSearchParams();
if (filter.category_id !== undefined)
params.set("category_id", String(filter.category_id));
+ if (filter.uncategorized) params.set("uncategorized", "true");
if (filter.bookmarked !== undefined)
params.set("bookmarked", String(filter.bookmarked));
if (filter.is_correct !== undefined)
params.set("is_correct", String(filter.is_correct));
+ if (filter.search) params.set("search", filter.search);
+ if (filter.sort) params.set("sort", filter.sort);
if (filter.limit !== undefined) params.set("limit", String(filter.limit));
if (filter.offset !== undefined) params.set("offset", String(filter.offset));
const query = params.toString();
@@ -388,6 +406,54 @@ export async function addEntryToCategory(
await expectJson<{ added: boolean }>(response);
}
+export interface BulkCategoryResult {
+ changed: number;
+ requested: number;
+ category_id: number;
+ link: boolean;
+}
+
+/**
+ * File (or unfile) many entries in one request.
+ *
+ * One round-trip instead of N: the list refreshes once against a settled
+ * server state rather than racing a burst of per-entry writes.
+ */
+export async function bulkLinkEntriesToCategory(
+ entryIds: number[],
+ categoryId: number,
+ link = true,
+): Promise<BulkCategoryResult> {
+ const response = await apiFetch(
+ apiUrl("/api/v1/question-notebook/entries/categories/bulk"),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ entry_ids: entryIds,
+ category_id: categoryId,
+ link,
+ }),
+ },
+ );
+ return expectJson<BulkCategoryResult>(response);
+}
+
+export interface QuestionBankStats {
+ total: number;
+ wrong: number;
+ bookmarked: number;
+ uncategorized: number;
+}
+
+export async function getQuestionBankStats(): Promise<QuestionBankStats> {
+ const response = await apiFetch(
+ apiUrl("/api/v1/question-notebook/stats"),
+ { cache: "no-store" },
+ );
+ return expectJson<QuestionBankStats>(response);
+}
+
export async function removeEntryFromCategory(
entryId: number,
categoryId: number,
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 8b56a22ae..118dfe1b1 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -3183,5 +3183,22 @@
"Drag to resize · double-click to reset": "Drag to resize · double-click to reset",
"Available only after every stale page has been recompiled.": "Available only after every stale page has been recompiled.",
"Mark as seen anyway": "Mark as seen anyway",
- "Dismiss the warning without recompiling those pages.": "Dismiss the warning without recompiling those pages."
+ "Dismiss the warning without recompiling those pages.": "Dismiss the warning without recompiling those pages.",
+ "Add to category": "Add to category",
+ "No categories yet. Type a name below to create one.": "No categories yet. Type a name below to create one.",
+ "New category…": "New category…",
+ "Create and add": "Create and add",
+ "Search questions and answers…": "Search questions and answers…",
+ "Toggle sort order": "Toggle sort order",
+ "Newest first": "Newest first",
+ "Oldest first": "Oldest first",
+ "Unfiled": "Unfiled",
+ "No matching questions": "No matching questions",
+ "Try a different word, or clear the search to see everything.": "Try a different word, or clear the search to see everything.",
+ "Everything is filed": "Everything is filed",
+ "No questions are waiting to be sorted into a category.": "No questions are waiting to be sorted into a category.",
+ "Nothing in this view": "Nothing in this view",
+ "Switch to another filter to see your other questions.": "Switch to another filter to see your other questions.",
+ "Showing {{shown}} of {{total}} — narrow the view to see the rest.": "Showing {{shown}} of {{total}} — narrow the view to see the rest.",
+ "Delete this category? The questions themselves stay in your bank.": "Delete this category? The questions themselves stay in your bank."
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 6d755126a..375db84ab 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -3183,5 +3183,22 @@
"Drag to resize · double-click to reset": "拖动调整宽度 · 双击恢复默认",
"Available only after every stale page has been recompiled.": "只有所有过期页面重新编译完成后才能使用。",
"Mark as seen anyway": "仍然标记为已读",
- "Dismiss the warning without recompiling those pages.": "不重新编译这些页面,直接忽略该提示。"
+ "Dismiss the warning without recompiling those pages.": "不重新编译这些页面,直接忽略该提示。",
+ "Add to category": "归入分类",
+ "No categories yet. Type a name below to create one.": "还没有分类。在下方输入名称即可新建。",
+ "New category…": "新建分类…",
+ "Create and add": "新建并归入",
+ "Search questions and answers…": "搜索题目和答案…",
+ "Toggle sort order": "切换排序",
+ "Newest first": "最新在前",
+ "Oldest first": "最早在前",
+ "Unfiled": "未归类",
+ "No matching questions": "没有匹配的题目",
+ "Try a different word, or clear the search to see everything.": "换个关键词,或清空搜索查看全部。",
+ "Everything is filed": "全部已归类",
+ "No questions are waiting to be sorted into a category.": "没有待归类的题目了。",
+ "Nothing in this view": "此视图下没有内容",
+ "Switch to another filter to see your other questions.": "切换筛选条件查看其他题目。",
+ "Showing {{shown}} of {{total}} — narrow the view to see the rest.": "已显示 {{shown}} / {{total}} 条 —— 缩小范围可查看其余。",
+ "Delete this category? The questions themselves stay in your bank.": "删除这个分类?题目本身会保留在题库里。"
}