Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 43 additions & 12 deletions web/components/quiz/QuizViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -186,17 +186,21 @@ function getUserAnswer(question: QuizQuestion, answer: AnswerState): string {
return answer.typed.trim();
}

function resolveObjectiveChoiceKey(question: QuizQuestion): string {
const correct = question.correct_answer.trim();
const options = question.options!;
const resolved = resolveChoiceAnswerKey(correct, options);
if (Object.hasOwn(options, resolved)) return resolved;
const first = correct.charAt(0).toUpperCase();
return Object.hasOwn(options, first) ? first : "";
}

function isAnswerCorrect(question: QuizQuestion, answer: AnswerState): boolean {
const userAnswer = getUserAnswer(question, answer);
if (!userAnswer) return false;
const correct = question.correct_answer.trim();
if (isMultipleChoice(question)) {
const correctChoiceKey = resolveChoiceAnswerKey(correct, question.options);
return (
userAnswer.toUpperCase() === correctChoiceKey ||
userAnswer.toUpperCase() === correct.toUpperCase() ||
userAnswer.toUpperCase() === correct.charAt(0).toUpperCase()
);
return userAnswer.toUpperCase() === resolveObjectiveChoiceKey(question);
}
if (isConceptQuizQuestion(question.question_type)) {
const correctTF = resolveConceptAnswer(correct);
Expand All @@ -209,6 +213,23 @@ function isAnswerCorrect(question: QuizQuestion, answer: AnswerState): boolean {
);
}

/**
* Choice / true-false items graded by exact match. A key that names no
* option or no truth value ("Richtig, weil …", or no key at all) leaves the
* item to the AI judge instead.
*/
function hasObjectiveKey(question: QuizQuestion): boolean {
const key = question.correct_answer.trim();
if (!key) return false;
if (isMultipleChoice(question)) {
return resolveObjectiveChoiceKey(question) !== "";
}
if (isConceptQuizQuestion(question.question_type)) {
return resolveConceptAnswer(key) !== "";
}
return false;
}

/** Exact matching first; the AI verdict only grades what it cannot. */
function getAssessment(
question: QuizQuestion,
Expand All @@ -217,9 +238,7 @@ function getAssessment(
) {
return resolveQuizAssessment({
exactCorrect: isAnswerCorrect(question, answer),
objective:
isMultipleChoice(question) ||
isConceptQuizQuestion(question.question_type),
objective: hasObjectiveKey(question),
hasImages: answer.images.length > 0,
verdict,
});
Expand Down Expand Up @@ -983,18 +1002,30 @@ export default function QuizViewer({
</span>
)}
<span className="rounded-md bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">
{t(QUIZ_TYPE_LABEL_KEYS[normalizeQuizQuestionType(q.question_type)])}
{t(
QUIZ_TYPE_LABEL_KEYS[
normalizeQuizQuestionType(q.question_type)
],
)}
</span>
</div>

{ans.submitted && (
<div className="relative flex items-center gap-1">
<Tooltip label={currentBookmarked ? t("Unmark question") : t("Mark question")}>
<Tooltip
label={
currentBookmarked ? t("Unmark question") : t("Mark question")
}
>
<button
type="button"
onClick={handleToggleBookmark}
disabled={!currentEntryId}
aria-label={currentBookmarked ? t("Unmark question") : t("Mark question")}
aria-label={
currentBookmarked
? t("Unmark question")
: t("Mark question")
}
className={`rounded-lg p-1.5 transition-all disabled:opacity-30 ${
currentBookmarked
? "scale-110 text-amber-500 dark:text-amber-400"
Expand Down
112 changes: 98 additions & 14 deletions web/tests/quiz/QuizViewer.smoke.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,13 @@ const shortAnswerQuestion: QuizQuestion = {
difficulty: "medium",
};

function renderViewer(questions: QuizQuestion[], props: {
sessionId?: string | null;
turnId?: string | null;
} = {}) {
function renderViewer(
questions: QuizQuestion[],
props: {
sessionId?: string | null;
turnId?: string | null;
} = {},
) {
return render(
<StrictMode>
<QuizViewer
Expand Down Expand Up @@ -133,7 +136,9 @@ describe("QuizViewer smoke", () => {

it("renders the quiz card with question, options and progress (render smoke)", () => {
renderViewer([choiceQuestion, conceptQuestion]);
expect(screen.getByText("What is the capital of France?")).toBeInTheDocument();
expect(
screen.getByText("What is the capital of France?"),
).toBeInTheDocument();
expect(screen.getByRole("button", { name: /Berlin/ })).toBeInTheDocument();
expect(screen.getByRole("button", { name: /Paris/ })).toBeInTheDocument();
expect(screen.getByRole("button", { name: /Madrid/ })).toBeInTheDocument();
Expand Down Expand Up @@ -167,11 +172,15 @@ describe("QuizViewer smoke", () => {

expect(screen.getByText("Correct")).toBeInTheDocument();
expect(screen.getByText("Explanation")).toBeInTheDocument();
expect(screen.getByText("Paris is the capital of France.")).toBeInTheDocument();
expect(
screen.getByText("Paris is the capital of France."),
).toBeInTheDocument();
// Options lock after submission; the action row flips to retry/judge.
expect(screen.getByRole("button", { name: /Paris/ })).toBeDisabled();
expect(screen.getByRole("button", { name: /Retry/ })).toBeInTheDocument();
expect(screen.getByRole("button", { name: /AI Judge/ })).toBeInTheDocument();
expect(
screen.getByRole("button", { name: /AI Judge/ }),
).toBeInTheDocument();
expect(screen.queryByRole("button", { name: /Check Answer/ })).toBeNull();
});

Expand Down Expand Up @@ -230,7 +239,9 @@ describe("QuizViewer smoke", () => {
expect(screen.getByText("1/2")).toBeInTheDocument();

await user.click(screen.getByRole("button", { name: "Next" }));
expect(screen.getByText("The Earth is perfectly flat.")).toBeInTheDocument();
expect(
screen.getByText("The Earth is perfectly flat."),
).toBeInTheDocument();
// Chip 1 is no longer current and was graded correct → green tint.
expect(screen.getByRole("button", { name: "1" }).className).toContain(
"bg-green-100",
Expand All @@ -239,7 +250,9 @@ describe("QuizViewer smoke", () => {

// Chips are also a navigation surface.
await user.click(screen.getByRole("button", { name: "1" }));
expect(screen.getByText("What is the capital of France?")).toBeInTheDocument();
expect(
screen.getByText("What is the capital of France?"),
).toBeInTheDocument();
});

it("persists each submit and records results once every question is answered (mock API)", async () => {
Expand Down Expand Up @@ -325,9 +338,7 @@ describe("QuizViewer smoke", () => {

// Free-text question graded against the reference first (label +
// tab can both render; at least the reference block must show).
expect(
screen.getAllByText("Reference Answer").length,
).toBeGreaterThan(0);
expect(screen.getAllByText("Reference Answer").length).toBeGreaterThan(0);
expect(
screen.getByText("Plants convert light into chemical energy."),
).toBeInTheDocument();
Expand Down Expand Up @@ -376,8 +387,13 @@ describe("QuizViewer smoke", () => {
turnId: "turn-1",
});

const input = container.querySelector('input[type="file"]') as HTMLInputElement;
await user.upload(input, new File(["x"], "work.jpg", { type: "image/jpeg" }));
const input = container.querySelector(
'input[type="file"]',
) as HTMLInputElement;
await user.upload(
input,
new File(["x"], "work.jpg", { type: "image/jpeg" }),
);
await user.click(screen.getByRole("button", { name: /Check Answer/ }));

// A photo answer is pending, not a mistake, until the judge grades it.
Expand Down Expand Up @@ -503,6 +519,74 @@ describe("QuizViewer smoke", () => {
expect(screen.queryByText("Incorrect")).toBeNull();
});

it.each(["B) Paris", "B. Paris"])(
"keeps the objective grade for a wrong choice with key %s",
async (key) => {
const user = userEvent.setup();
renderViewer([{ ...choiceQuestion, correct_answer: key }], {
sessionId: "session-1",
turnId: "turn-1",
});
await user.click(screen.getByRole("button", { name: /Madrid/ }));
await user.click(screen.getByRole("button", { name: /Check Answer/ }));
await user.click(screen.getByRole("button", { name: /AI Judge/ }));
const verdict = {
result: "correct" as const,
is_correct: true,
final: true,
confidence: 0.9,
steps: [],
};
act(() => {
mocks.judgeHandlers!.onVerdict!(verdict);
mocks.judgeHandlers!.onDone("Right.");
});
await waitFor(() => {
expect(mocks.updateNotebookEntry).toHaveBeenCalledWith(11, {
ai_judgment: "Right.",
ai_verdict: verdict,
is_correct: false,
result: "incorrect",
});
});
},
);

it("lets the judge grade a true/false item whose key names no truth value", async () => {
const user = userEvent.setup();
renderViewer(
[{ ...conceptQuestion, correct_answer: "Richtig, weil ..." }],
{
sessionId: "session-1",
turnId: "turn-1",
},
);
await user.click(screen.getByRole("button", { name: "True" }));
await user.click(screen.getByRole("button", { name: /Check Answer/ }));
await user.click(screen.getByRole("button", { name: /AI Judge/ }));
const verdict = {
result: "correct" as const,
is_correct: true,
final: true,
confidence: 0.9,
steps: [],
};
act(() => {
mocks.judgeHandlers!.onVerdict!(verdict);
mocks.judgeHandlers!.onDone("Right.");
});

// Exact matching cannot read the key, so it must not overrule the judge.
await waitFor(() => {
expect(mocks.updateNotebookEntry).toHaveBeenCalledWith(11, {
ai_judgment: "Right.",
ai_verdict: verdict,
is_correct: true,
result: "correct",
});
});
});

it("closes in-flight judge handles on unmount", async () => {
const user = userEvent.setup();
const { unmount } = renderViewer([shortAnswerQuestion]);
Expand Down
Loading