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
52 changes: 50 additions & 2 deletions web/features/chat/messages/ChatMessageList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import dynamic from "next/dynamic";
import { UsageFooter } from "./UsageFooter";
import { cumulativeMessageUsage, messageUsage } from "./usage-summary";
import {
Component,
memo,
useCallback,
useEffect,
Expand Down Expand Up @@ -42,6 +43,7 @@ import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker
import { ActivityFold, FoldCaret } from "@/components/activity";
import { LearningText } from "@/components/common/LearningText";
import AssistantResponse from "@/components/common/AssistantResponse";
import { useUserMessageMath } from "@/hooks/useUserMessageMath";
import {
InlineFileCardProvider,
mergeGeneratedFiles,
Expand Down Expand Up @@ -131,6 +133,32 @@ import {
researchFollowupStatus,
} from "@/lib/deep-research-report";

const UserMathText = dynamic(() => import("./UserMathText"), { ssr: false });

/**
* An optional renderer must never take the transcript down with it. If the
* math chunk fails to load or a formula throws mid-render, the bubble falls
* back to the literal message text.
*/
class UserMathBoundary extends Component<
{ fallback: ReactNode; children: ReactNode },
{ failed: boolean }
> {
state = { failed: false };

static getDerivedStateFromError() {
return { failed: true };
}

componentDidCatch(error: unknown) {
console.error("User message math rendering failed", error);
}

render() {
return this.state.failed ? this.props.fallback : this.props.children;
}
}

const MathAnimatorViewer = dynamic(
() => import("@/components/math-animator/MathAnimatorViewer"),
{ ssr: false },
Expand Down Expand Up @@ -405,6 +433,7 @@ function ProcessFold({
*/
function SentMidTurn({ messages }: { messages: string[] }) {
const { t } = useTranslation();
const renderMath = useUserMessageMath();
return (
<div data-sent-mid-turn="true" className="my-3 flex flex-col items-end gap-1">
<span className="pr-1 text-[11px] text-[var(--muted-foreground)]">
Expand All @@ -416,7 +445,15 @@ function SentMidTurn({ messages }: { messages: string[] }) {
dir="auto"
className="max-w-[85%] whitespace-pre-wrap rounded-2xl bg-[var(--secondary)] px-3.5 py-2 text-[13.5px] leading-relaxed text-[var(--foreground)]"
>
<LearningText size={13.5}>{text}</LearningText>
{renderMath ? (
<UserMathBoundary
fallback={<LearningText size={13.5}>{text}</LearningText>}
>
<UserMathText content={text} size={13.5} />
</UserMathBoundary>
) : (
<LearningText size={13.5}>{text}</LearningText>
)}
</div>
))}
</div>
Expand Down Expand Up @@ -1563,6 +1600,7 @@ export const UserMessage = memo(function UserMessage({
onOpenConsultation?: () => void;
}) {
const { t } = useTranslation();
const renderMath = useUserMessageMath();
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(msg.content);
const [discarding, setDiscarding] = useState(false);
Expand Down Expand Up @@ -1847,7 +1885,17 @@ export const UserMessage = memo(function UserMessage({
{quoteText(a)}
</div>
))}
<div dir="auto" className="whitespace-pre-wrap"><LearningText size={14}>{msg.content}</LearningText></div>
<div dir="auto" className={renderMath ? undefined : "whitespace-pre-wrap"}>
{renderMath ? (
<UserMathBoundary
fallback={<LearningText size={14}>{msg.content}</LearningText>}
>
<UserMathText content={msg.content} />
</UserMathBoundary>
) : (
<LearningText size={14}>{msg.content}</LearningText>
)}
</div>
</div>
)}
{/* Recovery records are local to this browser. Keep their actions
Expand Down
193 changes: 193 additions & 0 deletions web/features/chat/messages/UserMathText.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
"use client";

import { useMemo, type CSSProperties } from "react";
import katex from "katex";
import "katex/dist/katex.min.css";

type UserMathSegment =
| { kind: "text"; value: string }
| { kind: "math"; value: string; display: boolean };

const FENCED_CODE_RE = /(```[\s\S]*?```|~~~[\s\S]*?~~~)/g;
const INLINE_CODE_RE = /(`[^`\n]*`)/g;

/**
* Split a learner's message into literal text and explicit math.
*
* Only `$...$` and `$$...$$` count: the learner opted in, so their delimiters
* are the intent. Fenced code and inline code stay literal, and a pair that
* does not read as a formula (prices, paths, `$PATH`) stays literal too.
*/
export function splitUserMath(content: string): UserMathSegment[] {
const segments: UserMathSegment[] = [];
for (const chunk of content.split(FENCED_CODE_RE)) {
if (!chunk) continue;
if (/^(```|~~~)/.test(chunk)) {
appendText(segments, chunk);
continue;
}
for (const part of chunk.split(INLINE_CODE_RE)) {
if (!part) continue;
if (/^`[^`\n]*`$/.test(part)) {
appendText(segments, part);
continue;
}
splitProse(part, segments);
}
}
return segments;
}

function splitProse(text: string, segments: UserMathSegment[]): void {
let cursor = 0;
while (cursor < text.length) {
const open = findDollar(text, cursor);
if (open === -1) {
appendText(segments, text.slice(cursor));
return;
}
const display = text[open + 1] === "$";
const bodyStart = open + (display ? 2 : 1);
const close = display
? findDoubleDollar(text, bodyStart)
: findDollar(text, bodyStart);
if (close === -1) {
appendText(segments, text.slice(cursor));
return;
}
const body = text.slice(bodyStart, close);
const isMath = display
? body.trim().length > 0
: looksLikeInlineMath(body);
if (isMath) {
appendText(segments, text.slice(cursor, open));
segments.push({ kind: "math", value: body, display });
cursor = close + (display ? 2 : 1);
} else {
// Keep the opening delimiter literal and keep looking after it.
appendText(segments, text.slice(cursor, bodyStart));
cursor = bodyStart;
}
}
}

function findDollar(text: string, from: number): number {
let index = text.indexOf("$", from);
while (index !== -1) {
if (!isEscaped(text, index)) return index;
index = text.indexOf("$", index + 1);
}
return -1;
}

function findDoubleDollar(text: string, from: number): number {
let index = text.indexOf("$$", from);
while (index !== -1) {
if (!isEscaped(text, index)) return index;
index = text.indexOf("$$", index + 2);
}
return -1;
}

function isEscaped(text: string, index: number): boolean {
return text[index - 1] === "\\";
}

/**
* An explicit `$...$` pair that reads as math rather than prose or money.
*
* `$5 和 $10` and `$5 and $10` do not read as formulas, `$PATH` has no
* operator, while `$x$`, `$x=1$`, `$f(x)$` and `$\alpha$` pass.
*/
function looksLikeInlineMath(body: string): boolean {
const value = body.trim();
if (!value || value.length > 400 || body.includes("\n")) return false;
// A price range like `$5-$10` pairs its dollars with a trailing operator.
if (/[+\-*/]$/.test(value)) return false;
if (/[\\^_=+\-*/<>()]/.test(value)) return true;
if (/^\d+(\.\d+)?$/.test(value)) return true;
return /^[A-Za-z]$/.test(value);
}

function appendText(segments: UserMathSegment[], value: string): void {
if (!value) return;
const previous = segments[segments.length - 1];
if (previous?.kind === "text") {
previous.value += value;
return;
}
segments.push({ kind: "text", value });
}

function MathSegment({
segment,
}: {
segment: Extract<UserMathSegment, { kind: "math" }>;
}) {
const html = useMemo(() => {
try {
return katex.renderToString(segment.value, {
displayMode: segment.display,
throwOnError: true,
trust: false,
strict: "ignore",
maxExpand: 1000,
maxSize: 20,
output: "htmlAndMathml",
});
} catch {
return null;
}
}, [segment.value, segment.display]);

if (!html) {
return (
<span className="whitespace-pre-wrap">
{segment.display ? `$$${segment.value}$$` : `$${segment.value}$`}
</span>
);
}

return segment.display ? (
<div
dir="ltr"
className="my-2 overflow-x-auto whitespace-normal"
dangerouslySetInnerHTML={{ __html: html }}
/>
) : (
<span
dir="ltr"
className="mx-0.5 inline-block whitespace-normal align-middle"
dangerouslySetInnerHTML={{ __html: html }}
/>
);
}

/** A user message with only its explicit formulas rendered. */
export default function UserMathText({
content,
size = 14,
}: {
content: string;
size?: number;
}) {
const source = typeof content === "string" ? content : "";
const segments = useMemo(() => splitUserMath(source), [source]);

return (
<div
className="learning-text"
style={{ "--learning-text-base": `${size}px` } as CSSProperties}
>
{segments.map((segment, index) =>
segment.kind === "text" ? (
<span key={index} className="whitespace-pre-wrap">
{segment.value}
</span>
) : (
<MathSegment key={index} segment={segment} />
),
)}
</div>
);
}
25 changes: 25 additions & 0 deletions web/features/settings/sections/AppearanceSettingsSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import type { CodeBlockThemeId } from "@/components/common/code-block-themes";
import { CODE_BLOCK_THEME_OPTIONS } from "@/components/common/code-block-themes";
import { Toggle } from "@/components/settings/Toggle";
import { useUiSettings } from "@/features/settings/store";
import {
setUserMessageMath,
useUserMessageMath,
} from "@/hooks/useUserMessageMath";
import { ThemePreviewCard } from "@/components/settings/ThemePreviewCard";
import {
SettingRow,
Expand Down Expand Up @@ -60,6 +64,7 @@ export default function AppearanceSettingsPage() {
updateCodeBlockShowLineNumbers,
updateCodeBlockWrapLongLines,
} = useUiSettings();
const renderUserMath = useUserMessageMath();

// All code-block values come straight from the settings context (backed by
// AppShellContext, the single source of truth), so the toggles reflect the
Expand Down Expand Up @@ -210,6 +215,26 @@ export default function AppearanceSettingsPage() {
</div>
</SettingSection>

<SettingSection
title={t("Chat messages")}
description={t(
"Choose how the messages you send are displayed. Changes take effect immediately.",
)}
>
<SettingRow
title={t("Math in my messages")}
description={t(
"Render $...$ and $$...$$ formulas in your own chat bubbles. Your message is still sent to the model as plain text.",
)}
control={
<Toggle
checked={renderUserMath}
onChange={setUserMessageMath}
/>
}
/>
</SettingSection>

<SettingSection
title={t("Code blocks")}
description={t(
Expand Down
37 changes: 37 additions & 0 deletions web/hooks/useUserMessageMath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"use client";

import { useEffect, useState } from "react";
import { browserStorage } from "@/shared/storage";

const STORAGE_NAME = "deeptutor.userMessageMath";
const CHANGE_EVENT = "deeptutor:user-message-math";

/** Whether the learner opted into math rendering in their own chat bubbles. */
export function readUserMessageMath(): boolean {
return browserStorage.readRaw("local", STORAGE_NAME) === "1";
}

export function setUserMessageMath(enabled: boolean): void {
browserStorage.writeRaw("local", STORAGE_NAME, enabled ? "1" : "0");
if (typeof window !== "undefined") {
window.dispatchEvent(new Event(CHANGE_EVENT));
}
}

/** Read the preference, defaulting to off on the server and before hydration. */
export function useUserMessageMath(): boolean {
const [enabled, setEnabled] = useState(false);

useEffect(() => {
const sync = () => setEnabled(readUserMessageMath());
sync();
window.addEventListener(CHANGE_EVENT, sync);
window.addEventListener("storage", sync);
return () => {
window.removeEventListener(CHANGE_EVENT, sync);
window.removeEventListener("storage", sync);
};
}, []);

return enabled;
}
4 changes: 4 additions & 0 deletions web/locales/de/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -1575,6 +1575,10 @@
"Off": "Aus",
"Appearance": "Erscheinungsbild",
"Pick the colour palette and interface style. Each tile previews the theme it applies.": "Wähle Farbpalette und Oberflächenstil. Jede Kachel zeigt eine Vorschau des Designs.",
"Chat messages": "Chat-Nachrichten",
"Choose how the messages you send are displayed. Changes take effect immediately.": "Wähle, wie deine gesendeten Nachrichten angezeigt werden. Änderungen gelten sofort.",
"Math in my messages": "Mathematik in meinen Nachrichten",
"Render $...$ and $$...$$ formulas in your own chat bubbles. Your message is still sent to the model as plain text.": "Rendere $...$ und $$...$$ Formeln in deinen eigenen Chatblasen. Deine Nachricht wird weiterhin als reiner Text an das Modell gesendet.",
"Code blocks": "Codeblöcke",
"Choose how code snippets look across the app. Changes apply immediately to saved and streamed responses.": "Wähle das Aussehen von Code-Ausschnitten in der gesamten App. Änderungen wirken sich sofort auf gespeicherte und gestreamte Antworten aus.",
"Default is a clean pure-white theme with a blue accent. Cream is warm and paper-like with a terracotta accent. Dark keeps Cream's warmth on near-black. Glass adds translucent purple panels on a deep gradient.": "Standard ist ein schlichtes reinweißes Design mit blauem Akzent. Cream ist warm und papierähnlich mit Terrakotta-Akzent. Dark behält die Wärme von Cream auf Fast-Schwarz bei. Glass ergänzt halbtransparente lila Bereiche auf einem tiefen Farbverlauf.",
Expand Down
Loading
Loading