DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
style(reading): retain the frontend quotation and semicolon conventions
Bingxi Zhao (Frank)c74915ab8b3f
diff --git a/web/components/reading/ReadingExtensionBar.tsx b/web/components/reading/ReadingExtensionBar.tsxindex c7706d07c..6d97970c2 100644--- a/web/components/reading/ReadingExtensionBar.tsx+++ b/web/components/reading/ReadingExtensionBar.tsx@@ -1,34 +1,34 @@-'use client'+"use client";-import { useEffect, useMemo, useState } from 'react'-import { Loader2, Sparkles, Square, Volume2, X } from 'lucide-react'-import { useTranslation } from 'react-i18next'+import { useEffect, useMemo, useState } from "react";+import { Loader2, Sparkles, Square, Volume2, X } from "lucide-react";+import { useTranslation } from "react-i18next";import {listReadingExtensions,runReadingExtension,submitReadingQuizAnswers,type ReadingExtensionManifest,type ReadingExtensionResult,-} from '@/lib/reading-api'+} from "@/lib/reading-api";type VocabularyTerm = {- term: string- meaning: string- usage: string-}+ term: string;+ meaning: string;+ usage: string;+};type QuizQuestion = {- id?: string- prompt: string- choices: string[]- correct_choice_index?: number-}+ id?: string;+ prompt: string;+ choices: string[];+ correct_choice_index?: number;+};type TranslationResult = {- translation: string- alternatives: string[]- note: string-}+ translation: string;+ alternatives: string[];+ note: string;+};export function ReadingExtensionBar({materialId,@@ -38,8 +38,8 @@ export function ReadingExtensionBar({sessionId,onError,}: {- materialId: string- locator: number+ materialId: string;+ locator: number;/*** The unit the selection was made in, when there is one.*@@ -47,113 +47,114 @@ export function ReadingExtensionBar({* server verifies the quote against the text of the unit it is told about* and 400s when they disagree, so a selection has to travel with its own.*/- selectionLocator?: number- selection?: string- sessionId?: string | null- onError: (message: string) => void+ selectionLocator?: number;+ selection?: string;+ sessionId?: string | null;+ onError: (message: string) => void;}) {- const { i18n, t } = useTranslation()- const [extensions, setExtensions] = useState<ReadingExtensionManifest[]>([])- const [busy, setBusy] = useState('')- const [result, setResult] = useState<ReadingExtensionResult | null>(null)- const [resultLocator, setResultLocator] = useState(locator)- const [speaking, setSpeaking] = useState(false)+ const { i18n, t } = useTranslation();+ const [extensions, setExtensions] = useState<ReadingExtensionManifest[]>([]);+ const [busy, setBusy] = useState("");+ const [result, setResult] = useState<ReadingExtensionResult | null>(null);+ const [resultLocator, setResultLocator] = useState(locator);+ const [speaking, setSpeaking] = useState(false);function stopSpeaking() {- window.speechSynthesis?.cancel()- setSpeaking(false)+ window.speechSynthesis?.cancel();+ setSpeaking(false);}useEffect(() => {- let active = true+ let active = true;void listReadingExtensions()- .then(rows => {- if (active) setExtensions(rows)- })- .catch(error => {- if (active) onError(error instanceof Error ? error.message : String(error))+ .then((rows) => {+ if (active) setExtensions(rows);})+ .catch((error) => {+ if (active) onError(error instanceof Error ? error.message : String(error));+ });return () => {- active = false- }- }, [onError])+ active = false;+ };+ }, [onError]);// Two effects, because the two things they clean up move on different// clocks. A result belongs to the document: keyed on `locator` as well, an// ordinary scroll erased a card the reader was still reading, since// `locator` is the scroll-derived *viewport* locator.useEffect(() => {- setResult(null)- }, [materialId])+ setResult(null);+ }, [materialId]);// Speech, on the other hand, must stop the moment the reader navigates// away from the passage being read aloud — so this one keeps both keys.useEffect(() => {return () => {- window.speechSynthesis?.cancel()- setSpeaking(false)- }- }, [locator, materialId])+ window.speechSynthesis?.cancel();+ setSpeaking(false);+ };+ }, [locator, materialId]);const actions = useMemo(- () => extensions.flatMap(extension => extension.actions.map(action => ({ extension, action }))),- [extensions]- )+ () =>+ extensions.flatMap((extension) => extension.actions.map((action) => ({ extension, action }))),+ [extensions],+ );async function run(extension: ReadingExtensionManifest,- action: ReadingExtensionManifest['actions'][number]+ action: ReadingExtensionManifest["actions"][number],) {- const key = `${extension.id}:${action.id}`- const requestedLocator = selection?.trim() ? (selectionLocator ?? locator) : locator- setBusy(key)+ const key = `${extension.id}:${action.id}`;+ const requestedLocator = selection?.trim() ? (selectionLocator ?? locator) : locator;+ setBusy(key);try {const next = await runReadingExtension(materialId, extension.id, action.id, {locator: requestedLocator,- selection: selection || '',+ selection: selection || "",locale: i18n.language,- })- setResult(next)- setResultLocator(requestedLocator)- if (next.type === 'browser_speech') {- const text = String(next.payload.text || '')- if (!('speechSynthesis' in window) || !text) {- onError(t('No speech voice is available in this browser.'))- return+ });+ setResult(next);+ setResultLocator(requestedLocator);+ if (next.type === "browser_speech") {+ const text = String(next.payload.text || "");+ if (!("speechSynthesis" in window) || !text) {+ onError(t("No speech voice is available in this browser."));+ return;}- window.speechSynthesis.cancel()- const utterance = new SpeechSynthesisUtterance(text)- utterance.lang = String(next.payload.locale || i18n.language)- utterance.onend = () => setSpeaking(false)- utterance.onerror = () => setSpeaking(false)- window.speechSynthesis.speak(utterance)- setSpeaking(true)+ window.speechSynthesis.cancel();+ const utterance = new SpeechSynthesisUtterance(text);+ utterance.lang = String(next.payload.locale || i18n.language);+ utterance.onend = () => setSpeaking(false);+ utterance.onerror = () => setSpeaking(false);+ window.speechSynthesis.speak(utterance);+ setSpeaking(true);}} catch (error) {- onError(error instanceof Error ? error.message : String(error))+ onError(error instanceof Error ? error.message : String(error));} finally {- setBusy('')+ setBusy("");}}- if (actions.length === 0) return null+ if (actions.length === 0) return null;return (<><div className="flex shrink-0 gap-1.5 overflow-x-auto border-b border-[var(--border)] bg-[color-mix(in_srgb,var(--muted)_25%,transparent)] px-2.5 py-2">{actions.map(({ extension, action }) => {- const key = `${extension.id}:${action.id}`- const needsSelection = action.requires.includes('selection') && !selection?.trim()+ const key = `${extension.id}:${action.id}`;+ const needsSelection = action.requires.includes("selection") && !selection?.trim();// `busy === key`, not `Boolean(busy)`: an action can take the full// server timeout, and disabling all six meanwhile is// indistinguishable from the toolbar being broken.- const disabled = busy === key || needsSelection- const builtInLabel = builtInActionLabel(extension.id, action.id)+ const disabled = busy === key || needsSelection;+ const builtInLabel = builtInActionLabel(extension.id, action.id);return (<buttonkey={key}type="button"disabled={disabled}- title={needsSelection ? t('Select text in the document first.') : undefined}+ title={needsSelection ? t("Select text in the document first.") : undefined}onClick={() => void run(extension, action)}className="inline-flex h-8 min-w-[88px] flex-1 items-center justify-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--card)] px-2 text-xs font-medium text-[var(--foreground)] transition hover:bg-[var(--muted)] disabled:opacity-50">@@ -164,7 +165,7 @@ export function ReadingExtensionBar({)}<span className="truncate">{builtInLabel ? t(builtInLabel) : action.label}</span></button>- )+ );})}</div>{speaking ? (@@ -173,11 +174,11 @@ export function ReadingExtensionBar({className="flex shrink-0 items-center gap-2 border-b border-[var(--border)] bg-[var(--card)] px-3 py-2 text-xs text-[var(--muted-foreground)]"><Volume2 size={14} />- <span>{t('Reading aloud')}</span>+ <span>{t("Reading aloud")}</span><buttontype="button"- aria-label={t('Stop reading aloud')}- title={t('Stop reading aloud')}+ aria-label={t("Stop reading aloud")}+ title={t("Stop reading aloud")}onClick={stopSpeaking}className="ml-auto inline-flex h-7 w-7 items-center justify-center rounded-md text-[var(--foreground)] transition hover:bg-[var(--muted)]">@@ -185,41 +186,41 @@ export function ReadingExtensionBar({</button></div>) : null}- {result && result.type !== 'browser_speech' ? (+ {result && result.type !== "browser_speech" ? (<ExtensionResultresult={result}materialId={materialId}locator={resultLocator}sessionId={sessionId}- closeLabel={t('Close')}+ closeLabel={t("Close")}onClose={() => setResult(null)}onError={onError}/>) : null}</>- )+ );}function builtInActionLabel(extensionId: string, actionId: string) {- if (extensionId === 'read_aloud' && actionId === 'read') {- return 'Read aloud'+ if (extensionId === "read_aloud" && actionId === "read") {+ return "Read aloud";}- if (extensionId === 'guided_learning' && actionId === 'guide') {- return 'Guide me'+ if (extensionId === "guided_learning" && actionId === "guide") {+ return "Guide me";}- if (extensionId === 'vocabulary' && actionId === 'explain') {- return 'Explain vocabulary'+ if (extensionId === "vocabulary" && actionId === "explain") {+ return "Explain vocabulary";}- if (extensionId === 'quiz' && actionId === 'start') {- return 'Quiz me'+ if (extensionId === "quiz" && actionId === "start") {+ return "Quiz me";}- if (extensionId === 'translation' && actionId === 'translate_en') {- return 'Translate to English'+ if (extensionId === "translation" && actionId === "translate_en") {+ return "Translate to English";}- if (extensionId === 'translation' && actionId === 'translate_zh') {- return 'Translate to Chinese'+ if (extensionId === "translation" && actionId === "translate_zh") {+ return "Translate to Chinese";}- return ''+ return "";}function ExtensionResult({@@ -231,40 +232,40 @@ function ExtensionResult({onClose,onError,}: {- result: ReadingExtensionResult- materialId: string- locator: number- sessionId?: string | null- closeLabel: string- onClose: () => void- onError: (message: string) => void+ result: ReadingExtensionResult;+ materialId: string;+ locator: number;+ sessionId?: string | null;+ closeLabel: string;+ onClose: () => void;+ onError: (message: string) => void;}) {const questions = Array.isArray(result.payload.questions)? (result.payload.questions as QuizQuestion[])- : []- const items = Array.isArray(result.payload.items) ? result.payload.items.map(String) : []- const steps = Array.isArray(result.payload.steps) ? result.payload.steps.map(String) : []+ : [];+ const items = Array.isArray(result.payload.items) ? result.payload.items.map(String) : [];+ const steps = Array.isArray(result.payload.steps) ? result.payload.steps.map(String) : [];const terms: VocabularyTerm[] = Array.isArray(result.payload.terms)? result.payload.terms- .map(row => {- if (typeof row !== 'object' || row === null) return null- const term = row as Partial<VocabularyTerm>+ .map((row) => {+ if (typeof row !== "object" || row === null) return null;+ const term = row as Partial<VocabularyTerm>;return {- term: String(term.term || ''),- meaning: String(term.meaning || ''),- usage: String(term.usage || ''),- }+ term: String(term.term || ""),+ meaning: String(term.meaning || ""),+ usage: String(term.usage || ""),+ };}).filter((row): row is VocabularyTerm => row !== null)- : []+ : [];const translation: TranslationResult = {- translation: String(result.payload.translation || ''),+ translation: String(result.payload.translation || ""),alternatives: Array.isArray(result.payload.alternatives)? result.payload.alternatives.map(String): [],- note: String(result.payload.note || ''),- }- const body = String(result.payload.body || result.payload.overview || '')+ note: String(result.payload.note || ""),+ };+ const body = String(result.payload.body || result.payload.overview || "");return (<section className="relative shrink-0 border-b border-[var(--border)] bg-[var(--card)] px-3 py-3 text-xs text-[var(--foreground)]"><button@@ -331,7 +332,7 @@ function ExtensionResult({/>) : null}</section>- )+ );}function QuizQuestions({@@ -341,56 +342,56 @@ function QuizQuestions({sessionId,onError,}: {- questions: QuizQuestion[]- materialId: string- locator: number- sessionId?: string | null- onError: (message: string) => void+ questions: QuizQuestion[];+ materialId: string;+ locator: number;+ sessionId?: string | null;+ onError: (message: string) => void;}) {- const { t } = useTranslation()- const [answers, setAnswers] = useState<Record<string, number>>({})- const [verdicts, setVerdicts] = useState<Record<string, boolean>>({})- const [saving, setSaving] = useState<Record<string, boolean>>({})+ const { t } = useTranslation();+ const [answers, setAnswers] = useState<Record<string, number>>({});+ const [verdicts, setVerdicts] = useState<Record<string, boolean>>({});+ const [saving, setSaving] = useState<Record<string, boolean>>({});async function persistAnswer(question: QuizQuestion, index: number, choiceIndex: number) {- const questionId = question.id || `q_${index + 1}`- const key = question.id || String(index)- setSaving(current => ({ ...current, [key]: true }))+ const questionId = question.id || `q_${index + 1}`;+ const key = question.id || String(index);+ setSaving((current) => ({ ...current, [key]: true }));try {const results = await submitReadingQuizAnswers(materialId, {locator,- session_id: sessionId || '',+ session_id: sessionId || "",answers: [{ question_id: questionId, selected_index: choiceIndex }],- })- const verdict = results.find(item => item.question_id === questionId)- if (!verdict) throw new Error(t('Failed to save answer. Please try again.'))- setAnswers(current => ({ ...current, [key]: choiceIndex }))- setVerdicts(current => ({ ...current, [key]: verdict.is_correct }))+ });+ const verdict = results.find((item) => item.question_id === questionId);+ if (!verdict) throw new Error(t("Failed to save answer. Please try again."));+ setAnswers((current) => ({ ...current, [key]: choiceIndex }));+ setVerdicts((current) => ({ ...current, [key]: verdict.is_correct }));} catch (error) {- onError(error instanceof Error ? error.message : String(error))+ onError(error instanceof Error ? error.message : String(error));} finally {- setSaving(current => ({ ...current, [key]: false }))+ setSaving((current) => ({ ...current, [key]: false }));}}return questions.map((question, index) => {- const key = question.id || String(index)- const selected = answers[key]+ const key = question.id || String(index);+ const selected = answers[key];const correctChoiceIndex = Number.isInteger(question.correct_choice_index)? Number(question.correct_choice_index)- : -1- const canGrade = correctChoiceIndex >= 0 && correctChoiceIndex < question.choices.length+ : -1;+ const canGrade = correctChoiceIndex >= 0 && correctChoiceIndex < question.choices.length;if (!canGrade) {return (<div key={key} className="mt-3"><p className="font-medium">{question.prompt}</p><ol className="mt-1 list-inside list-[upper-alpha] space-y-0.5 text-[var(--muted-foreground)]">- {question.choices.map(choice => (+ {question.choices.map((choice) => (<li key={choice}>{choice}</li>))}</ol></div>- )+ );}return (<fieldset key={key} className="mt-3">@@ -403,7 +404,7 @@ function QuizQuestions({aria-pressed={selected === choiceIndex}disabled={Boolean(saving[key])}onClick={() => {- void persistAnswer(question, index, choiceIndex)+ void persistAnswer(question, index, choiceIndex);}}className="rounded-md border border-[var(--border)] px-2 py-1.5 text-left text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] aria-pressed:bg-[var(--muted)] aria-pressed:text-[var(--foreground)]">@@ -416,14 +417,14 @@ function QuizQuestions({role="status"className={`mt-1 font-medium ${verdicts[key]- ? 'text-emerald-600 dark:text-emerald-400'- : 'text-amber-600 dark:text-amber-400'+ ? "text-emerald-600 dark:text-emerald-400"+ : "text-amber-600 dark:text-amber-400"}`}>- {verdicts[key] ? t('Correct') : t('Incorrect')}+ {verdicts[key] ? t("Correct") : t("Incorrect")}</p>) : null}</fieldset>- )- })+ );+ });}diff --git a/web/tests/reading-quiz-persistence.spec.tsx b/web/tests/reading-quiz-persistence.spec.tsxindex bd1625568..dd3dc7869 100644--- a/web/tests/reading-quiz-persistence.spec.tsx+++ b/web/tests/reading-quiz-persistence.spec.tsx@@ -1,82 +1,84 @@-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'-import { beforeEach, expect, it, vi } from 'vitest'-import { ReadingExtensionBar } from '@/components/reading/ReadingExtensionBar'-import { initI18n } from '@/i18n/init'+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vitest";+import { ReadingExtensionBar } from "@/components/reading/ReadingExtensionBar";+import { initI18n } from "@/i18n/init";import {listReadingExtensions,runReadingExtension,submitReadingQuizAnswers,-} from '@/lib/reading-api'-vi.mock('@/lib/reading-api', () => ({+} from "@/lib/reading-api";+vi.mock("@/lib/reading-api", () => ({listReadingExtensions: vi.fn(),runReadingExtension: vi.fn(),submitReadingQuizAnswers: vi.fn(),-}))-initI18n('en')+}));+initI18n("en");beforeEach(() => {vi.mocked(listReadingExtensions).mockResolvedValue([{- id: 'quiz',- name: 'Quiz',- version: '1',- protocol_version: '1',- actions: [{ id: 'start', label: 'Quiz me', trigger: 'toolbar', requires: [] }],- result_types: ['quiz'],+ id: "quiz",+ name: "Quiz",+ version: "1",+ protocol_version: "1",+ actions: [{ id: "start", label: "Quiz me", trigger: "toolbar", requires: [] }],+ result_types: ["quiz"],},- ])+ ]);vi.mocked(runReadingExtension).mockResolvedValue({- type: 'quiz',- title: '',- message: '',+ type: "quiz",+ title: "",+ message: "",payload: {questions: [{- id: 'quiz-1',- prompt: 'Which ocean?',- choices: ['Pacific', 'Atlantic'],+ id: "quiz-1",+ prompt: "Which ocean?",+ choices: ["Pacific", "Atlantic"],correct_choice_index: 1,},],},- })-})-it('waits for saving, uses the server verdict, and preserves the original locator after scrolling', async () => {- const onError = vi.fn()- let finish!: (value: Awaited<ReturnType<typeof submitReadingQuizAnswers>>) => void+ });+});+it("waits for saving, uses the server verdict, and preserves the original locator after scrolling", async () => {+ const onError = vi.fn();+ let finish!: (value: Awaited<ReturnType<typeof submitReadingQuizAnswers>>) => void;vi.mocked(submitReadingQuizAnswers).mockImplementation(() =>- new Promise(resolve => {- finish = resolve- })- )- const view = render(<ReadingExtensionBar materialId="material-1" locator={4} onError={onError} />)- fireEvent.click(await screen.findByRole('button', { name: 'Quiz me' }))- const answer = await screen.findByRole('button', { name: 'B. Atlantic' })- view.rerender(<ReadingExtensionBar materialId="material-1" locator={9} onError={onError} />)- fireEvent.click(answer)- expect(answer).toBeDisabled()- expect(screen.queryByText('Correct')).not.toBeInTheDocument()- expect(submitReadingQuizAnswers).toHaveBeenCalledWith('material-1', {+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const view = render(+ <ReadingExtensionBar materialId="material-1" locator={4} onError={onError} />,+ );+ fireEvent.click(await screen.findByRole("button", { name: "Quiz me" }));+ const answer = await screen.findByRole("button", { name: "B. Atlantic" });+ view.rerender(<ReadingExtensionBar materialId="material-1" locator={9} onError={onError} />);+ fireEvent.click(answer);+ expect(answer).toBeDisabled();+ expect(screen.queryByText("Correct")).not.toBeInTheDocument();+ expect(submitReadingQuizAnswers).toHaveBeenCalledWith("material-1", {locator: 4,- session_id: '',- answers: [{ question_id: 'quiz-1', selected_index: 1 }],- })+ session_id: "",+ answers: [{ question_id: "quiz-1", selected_index: 1 }],+ });await act(async () => {- finish([{ question_id: 'quiz-1', is_correct: false, result: 'incorrect' }])- })- expect(await screen.findByText('Incorrect')).toBeInTheDocument()- expect(answer).not.toBeDisabled()- expect(onError).not.toHaveBeenCalled()-})-it('keeps a failed answer retryable without showing a successful grade', async () => {- const onError = vi.fn()- vi.mocked(submitReadingQuizAnswers).mockRejectedValueOnce(new Error('Save failed'))- render(<ReadingExtensionBar materialId="material-1" locator={4} onError={onError} />)- fireEvent.click(await screen.findByRole('button', { name: 'Quiz me' }))- const answer = await screen.findByRole('button', { name: 'B. Atlantic' })- fireEvent.click(answer)- await waitFor(() => expect(onError).toHaveBeenCalledWith('Save failed'))- expect(screen.queryByText('Correct')).not.toBeInTheDocument()- expect(answer).toHaveAttribute('aria-pressed', 'false')- expect(answer).not.toBeDisabled()-})+ finish([{ question_id: "quiz-1", is_correct: false, result: "incorrect" }]);+ });+ expect(await screen.findByText("Incorrect")).toBeInTheDocument();+ expect(answer).not.toBeDisabled();+ expect(onError).not.toHaveBeenCalled();+});+it("keeps a failed answer retryable without showing a successful grade", async () => {+ const onError = vi.fn();+ vi.mocked(submitReadingQuizAnswers).mockRejectedValueOnce(new Error("Save failed"));+ render(<ReadingExtensionBar materialId="material-1" locator={4} onError={onError} />);+ fireEvent.click(await screen.findByRole("button", { name: "Quiz me" }));+ const answer = await screen.findByRole("button", { name: "B. Atlantic" });+ fireEvent.click(answer);+ await waitFor(() => expect(onError).toHaveBeenCalledWith("Save failed"));+ expect(screen.queryByText("Correct")).not.toBeInTheDocument();+ expect(answer).toHaveAttribute("aria-pressed", "false");+ expect(answer).not.toBeDisabled();+});