DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(web): render the tutor's formulas on the surfaces a learner reads
Bingxi Zhao (Frank)70650c02d130
diff --git a/web/components/chat/home/AskUserOptions.tsx b/web/components/chat/home/AskUserOptions.tsxindex e44b8d3c0..8938c8102 100644--- a/web/components/chat/home/AskUserOptions.tsx+++ b/web/components/chat/home/AskUserOptions.tsx@@ -4,6 +4,7 @@ import { ChevronDown, ChevronLeft, ChevronRight } from "lucide-react";import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";+import InlineMarkdown from "@/components/common/InlineMarkdown";import { useCardSubmission } from "@/hooks/use-card-submission";import { REPLY_NOT_DELIVERED } from "@/lib/ask-user-state";import { decodeEscapedUnicodeForDisplay } from "@/lib/markdown-display";@@ -997,7 +998,11 @@ const InteractiveAskUserCard = memo(function InteractiveAskUserCard({</div><div className="flex-1"><div className="text-[13px] font-medium leading-snug text-[var(--foreground)]">- {payload.intro || t("Please answer to continue.")}+ {payload.intro ? (+ <InlineMarkdown content={payload.intro} />+ ) : (+ t("Please answer to continue.")+ )}</div><divclassName={@@ -1166,7 +1171,7 @@ const QuestionBody = memo(function QuestionBody({return (<><div className="mt-3 text-[14px] font-medium leading-snug text-[var(--foreground)]">- {question.prompt}+ <InlineMarkdown content={question.prompt} />{question.multi_select ? (<span className="ml-1.5 text-[11px] font-normal text-[var(--muted-foreground)]">{t("Select all that apply.")}@@ -1207,11 +1212,11 @@ const QuestionBody = memo(function QuestionBody({</span><span className="min-w-0 flex-1"><span className="block text-[13.5px] leading-snug">- {option.label}+ <InlineMarkdown content={option.label} /></span>{option.description ? (<span className="mt-0.5 block text-[11.5px] leading-snug text-[var(--muted-foreground)]">- {option.description}+ <InlineMarkdown content={option.description} /></span>) : null}</span>diff --git a/web/components/chat/home/MasteryQuestionCard.tsx b/web/components/chat/home/MasteryQuestionCard.tsxindex abded25b8..2e5cd96d4 100644--- a/web/components/chat/home/MasteryQuestionCard.tsx+++ b/web/components/chat/home/MasteryQuestionCard.tsx@@ -21,9 +21,9 @@import { memo, useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";+import InlineMarkdown from "@/components/common/InlineMarkdown";import { useCardSubmission } from "@/hooks/use-card-submission";import { REPLY_NOT_DELIVERED } from "@/lib/ask-user-state";-import { decodeEscapedUnicodeForDisplay } from "@/lib/markdown-display";import type {MasteryGradeResult,MasteryQuestion,@@ -86,7 +86,7 @@ function OptionRow({</span>{/* The body is the option. It is never printed beside its own letter. */}<span className={"min-w-0 flex-1 text-[13.5px] leading-relaxed " + body}>- {decodeEscapedUnicodeForDisplay(option.body)}+ <InlineMarkdown content={option.body} /></span></button>);@@ -197,7 +197,7 @@ export const MasteryQuestionCard = memo(function MasteryQuestionCard({) : null}<div className="mt-0.5 font-serif text-[15.5px] font-semibold leading-relaxed tracking-[-0.01em] text-[var(--foreground)]">- {decodeEscapedUnicodeForDisplay(question.prompt)}+ <InlineMarkdown content={question.prompt} /></div>{hasChoices ? (@@ -269,7 +269,7 @@ export const MasteryQuestionCard = memo(function MasteryQuestionCard({</div>{grade.explanation ? (<div className="mt-1 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">- {decodeEscapedUnicodeForDisplay(grade.explanation)}+ <InlineMarkdown content={grade.explanation} /></div>) : null}</div>diff --git a/web/components/common/InlineMarkdown.tsx b/web/components/common/InlineMarkdown.tsxnew file mode 100644index 000000000..e8d5604cc--- /dev/null+++ b/web/components/common/InlineMarkdown.tsx@@ -0,0 +1,42 @@+"use client";++import dynamic from "next/dynamic";+import { hasMarkdownMath } from "@/lib/latex";+import { decodeEscapedUnicodeForDisplay } from "@/lib/markdown-display";++const RichInlineMarkdown = dynamic(() => import("./RichInlineMarkdown"), {+ ssr: false,+});++// Emphasis, inline code and links are the rest of what a tutor writes into a+// question stem or an option. Matching them here (not just math) is what keeps+// `**听懂**` from reaching the learner with its asterisks attached.+const INLINE_MARKUP_RE = /(\*\*|__|`|~~|\[[^\]]+\]\()/;++/**+ * A short string a model wrote, rendered as the inline markdown it is.+ *+ * Question stems, answer options and grade explanations were printed as plain+ * text, so a physics or maths question showed the learner raw `$V^\pi$` and a+ * bolded cue showed its asterisks. They are also *short* and sit inside+ * buttons and one-line rows, so they cannot use the block renderer: this one+ * emits phrasing content only, and loads KaTeX at all only when the string+ * actually contains something to render.+ */+export default function InlineMarkdown({+ content,+ className,+}: {+ content: string;+ className?: string;+}) {+ const text = decodeEscapedUnicodeForDisplay(content ?? "");+ const rich = hasMarkdownMath(text) || INLINE_MARKUP_RE.test(text);++ if (!rich) {+ return className ? <span className={className}>{text}</span> : <>{text}</>;+ }++ const rendered = <RichInlineMarkdown content={text} />;+ return className ? <span className={className}>{rendered}</span> : rendered;+}diff --git a/web/components/common/MarkdownRenderer.tsx b/web/components/common/MarkdownRenderer.tsxindex 3fbd536f8..ff0a60b57 100644--- a/web/components/common/MarkdownRenderer.tsx+++ b/web/components/common/MarkdownRenderer.tsx@@ -49,13 +49,18 @@ export default function MarkdownRenderer({// append-only nature of streaming content this gives us a stable// Simple→Rich one-way transition (the Rich subtree mounts once and// stays). No additional lock state is needed.+ //+ // `trace` is not excluded. It used to be, which pinned every trace bubble to+ // the Simple renderer and left `RichMarkdownRenderer`'s whole `trace` branch+ // unreachable — so a tutoring round that reasoned in formulas printed raw+ // `$y'' + 2y' + 5y = 0$` at the reader. The trigger is the content, not the+ // surface: a trace bubble with no math still takes the cheap path.const shouldUseRich =- variant !== "trace" &&- (trackSourceLines ||- resolvedEnableMath ||- resolvedEnableCode ||- resolvedEnableMermaid ||- resolvedAllowHtml);+ trackSourceLines ||+ resolvedEnableMath ||+ resolvedEnableCode ||+ resolvedEnableMermaid ||+ resolvedAllowHtml;if (!shouldUseRich) {return (diff --git a/web/components/common/RichInlineMarkdown.tsx b/web/components/common/RichInlineMarkdown.tsxnew file mode 100644index 000000000..2350f90bc--- /dev/null+++ b/web/components/common/RichInlineMarkdown.tsx@@ -0,0 +1,83 @@+"use client";++import "katex/dist/katex.min.css";+import React, { useEffect, useState } from "react";+import ReactMarkdown from "react-markdown";+import remarkGfm from "remark-gfm";+import { processLatexContent } from "@/lib/latex";++type Plugins = {+ remarkMath?: unknown;+ rehypeKatex?: unknown;+};++/**+ * Phrasing-only components.+ *+ * The host is frequently a `<button>` or a `<span>`, whose content model is+ * phrasing content — a `<p>` there is invalid markup and drags the block+ * spacing of the surrounding renderer in with it. Paragraphs and headings+ * therefore collapse to their children, and the block constructs a one-line+ * question cannot contain are simply not overridden: react-markdown will not+ * produce them from the inline grammar these strings use.+ */+const COMPONENTS = {+ p: ({ children }: { children?: React.ReactNode }) => <>{children}</>,+ h1: ({ children }: { children?: React.ReactNode }) => (+ <strong>{children}</strong>+ ),+ h2: ({ children }: { children?: React.ReactNode }) => (+ <strong>{children}</strong>+ ),+ h3: ({ children }: { children?: React.ReactNode }) => (+ <strong>{children}</strong>+ ),+ code: ({ children }: { children?: React.ReactNode }) => (+ <code className="rounded bg-[color-mix(in_srgb,var(--foreground)_8%,transparent)] px-1 py-px font-mono text-[0.92em]">+ {children}+ </code>+ ),+ a: ({ children }: { children?: React.ReactNode }) => (+ <span className="underline underline-offset-2">{children}</span>+ ),+ // A question stem is one line; a hard break inside it should not open a+ // block box the card then has to lay out around.+ br: () => <span> </span>,+} as const;++export default function RichInlineMarkdown({ content }: { content: string }) {+ const [plugins, setPlugins] = useState<Plugins>({});++ useEffect(() => {+ let cancelled = false;+ void (async () => {+ const [remarkMath, rehypeKatex] = await Promise.all([+ import("remark-math"),+ import("rehype-katex"),+ ]);+ if (!cancelled) {+ setPlugins({+ remarkMath: remarkMath.default,+ rehypeKatex: rehypeKatex.default,+ });+ }+ })();+ return () => {+ cancelled = true;+ };+ }, []);++ const remarkPlugins: any[] = [remarkGfm];+ if (plugins.remarkMath) remarkPlugins.push(plugins.remarkMath);+ const rehypePlugins: any[] = plugins.rehypeKatex ? [plugins.rehypeKatex] : [];++ return (+ <ReactMarkdown+ remarkPlugins={remarkPlugins}+ rehypePlugins={rehypePlugins}+ components={COMPONENTS as any}+ >+ {processLatexContent(content)}+ </ReactMarkdown>+ );+}diff --git a/web/tests/learner-card-math.spec.tsx b/web/tests/learner-card-math.spec.tsxnew file mode 100644index 000000000..461134f68--- /dev/null+++ b/web/tests/learner-card-math.spec.tsx@@ -0,0 +1,110 @@+import { render, waitFor } from "@testing-library/react";+import { describe, expect, it } from "vitest";++import { AskUserOptions } from "@/components/chat/home/AskUserOptions";+import { MasteryQuestionCard } from "@/components/chat/home/MasteryQuestionCard";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import { initI18n } from "@/i18n/init";+import type { MasteryQuestion } from "@/lib/mastery-question";++initI18n("zh");++/**+ * The cards a learner answers on are written by the same tutor that writes the+ * prose above them, and on a maths or physics path that prose is LaTeX. Both+ * cards printed it verbatim — a Bellman-equation stem reached the reader as+ * `$G_t = R_{t+1} + \gamma G_{t+1}$`, and a bolded cue as `**听懂**`.+ */+function masteryQuestion(): MasteryQuestion {+ return {+ questionId: "q1",+ prompt: "已知 $G_t = R_{t+1} + \\gamma G_{t+1}$,关于 $V^\\pi$ 的方程是?",+ questionType: "multiple_choice",+ objectiveName: "Bellman",+ difficulty: "medium",+ attempt: 1,+ options: [+ { label: "A", body: "自举:$V^\\pi(s) = E_\\pi[R_{t+1}]$" },+ { label: "B", body: "蒙特卡洛采样" },+ ],+ allowFreeText: false,+ };+}++describe("learner-facing cards render the tutor's markup", () => {+ it("renders KaTeX in a mastery question stem, its options and its verdict", async () => {+ const { container } = render(+ <MasteryQuestionCard+ question={masteryQuestion()}+ grade={{+ questionId: "q1",+ isCorrect: true,+ learnerAnswer: "A",+ correctLabel: "A",+ correctBody: "",+ explanation: "代入可得 $V^\\pi(s)$。",+ }}+ answered+ submittedAnswer="A"+ onSubmit={() => undefined}+ />,+ );++ await waitFor(() => {+ expect(container.querySelectorAll(".katex").length).toBeGreaterThanOrEqual(+ 4,+ );+ });+ expect(container).not.toHaveTextContent("$V^\\pi$");+ });++ it("renders math and emphasis on an ask_user card", async () => {+ const { container } = render(+ <AskUserOptions+ data={{+ resolved: false,+ answers: [],+ payload: {+ intro: "先确认一件事:**听懂**了吗?",+ questions: [+ {+ id: "goal",+ prompt: "$e^{i\\pi} + 1 = 0$ 说明了什么?",+ header: "Goal",+ multi_select: false,+ allow_free_text: false,+ placeholder: null,+ options: [+ { label: "$\\pi$ 与 $e$ 的关系", description: null },+ { label: "别的", description: null },+ ],+ },+ ],+ },+ }}+ onSubmit={() => undefined}+ />,+ );++ await waitFor(() => {+ expect(container.querySelectorAll(".katex").length).toBeGreaterThanOrEqual(+ 2,+ );+ });+ expect(container).not.toHaveTextContent("**听懂**");+ });++ it("renders math in a trace bubble", async () => {+ const { container } = render(+ <MarkdownRenderer+ content="特征方程 $r^2 + 2r + 5 = 0$,判别式 $\\Delta = -16 < 0$。"+ variant="trace"+ />,+ );++ await waitFor(() => {+ expect(container.querySelectorAll(".katex")).toHaveLength(2);+ });+ expect(container).not.toHaveTextContent("$r^2 + 2r + 5 = 0$");+ });+});