@devries-cameron20 / t3code-1 / commits / cb0553ea39
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(markdown): render LaTeX across web and native mobile (#18735)

Yash Singh committed Oct 19, 2026 at 18:51 UTC cb0553ea3941efd084aea57b0d096048fdc8ea15
41 files changed +1866 -120
apps/mobile/deps/README.md
+2 -2
@@ -1,3 +1,3 @@
1 -The Enriched Markdown tarball comes from the [`fork/t3-mobile` branch](https://github.com/pingdotgg/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. File/skill link recognition, back navigation from horizontal blocks, table-image presses, and code-block headers use upstream implementations. The remaining fork adds clipboard metadata, parsed asset manifests, signed image source resolution, React media slots, and development-host autolinks.
1 +The Enriched Markdown tarball comes from [`feat/t3chat-markdown-parity-v2`](https://github.com/pingdotgg/enriched-markdown/tree/feat/t3chat-markdown-parity-v2), based on Julius's [`fork/t3-mobile` branch](https://github.com/pingdotgg/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. File/skill link recognition, back navigation from horizontal blocks, table-image presses, and code-block headers use upstream implementations. The fork retains clipboard metadata, parsed asset manifests, signed image source resolution, React media slots, and development-host autolinks. The fork retains native math parsing, scrolling and copying, table layout and gestures, and inline-code layout. Character-reference decoding, iOS intrinsic-width measurement, and HTML clipboard round trips now use the upstream fixes included in Julius's base. RaTeX uses the upstream-released 0.1.15 dependency.
2
3 -To replace it, commit the fork changes, run `yarn install --immutable` and `yarn workspace react-native-enriched-markdown prepare` in the fork checkout, then `node scripts/pack-t3.mjs /path/to/t3code/apps/mobile/deps`. Bump the fork package version for each replacement, update the tarball path in `apps/mobile/package.json` and `pnpm-workspace.yaml`'s `allowBuilds`, and run `vp i` to update the lockfile. Native clients need rebuilding when this dependency changes.
3 +To replace it, commit the fork changes, run `yarn install --immutable` and `yarn workspace react-native-enriched-markdown prepare` in the fork checkout, then `node scripts/pack-t3.mjs /path/to/t3code/apps/mobile/deps`. Keep the package version aligned with Julius's `fork/t3-mobile` branch. Rename the archive to include the first eight characters of the source commit, such as `react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz`, so each build has a distinct dependency path without version bumps. Update the tarball path in `apps/mobile/package.json` and `pnpm-workspace.yaml`'s `allowBuilds`, and run `vp i` to update the lockfile. Native clients need rebuilding when this dependency changes.
apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz
Binary files /dev/null and b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz differ
apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz
Binary files a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz and /dev/null differ
apps/mobile/package.json
+2 -2
@@ -125,7 +125,7 @@
125 "react-dom": "catalog:",
126 "react-native": "0.88.0",
127 "react-native-blob-util": "0.25.1",
128 - "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.15.tgz",
128 + "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz",
129 "react-native-gesture-handler": "~3.3.0",
130 "react-native-image-viewing": "^0.2.2",
131 "react-native-keyboard-controller": "1.22.7",
@@ -159,7 +159,7 @@
159 "typescript": "catalog:"
160 },
161 "enriched-markdown": {
162 - "enableMath": false,
162 + "enableMath": true,
163 "enableVideo": false
164 },
165 "expo": {
apps/mobile/src/features/review/ReviewCommentCard.tsx
+7 -3
@@ -1,6 +1,8 @@
1 import { memo, useMemo, useState } from "react";
2 import { getFiletypeFromFileName } from "@pierre/diffs/utils/getFiletypeFromFileName";
3 import { ScrollView, StyleSheet, Text as NativeText, View, type ColorValue } from "react-native";
4 +import { SelectableMarkdownText } from "../../native/SelectableMarkdownText";
5 +import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview";
6 import { AppText as Text } from "../../components/ui/AppText";
7 import { SymbolView } from "../../components/ui/AppSymbol";
8 import { useUniwindTheme } from "../../lib/useUniwindTheme";
@@ -48,6 +50,7 @@ export const ReviewCommentCard = memo(function ReviewCommentCard(props: {
50 readonly colors: ReviewCommentColors;
51 }) {
52 const { codeSurface, nativeReviewDiffStyle } = useAppearanceCodeSurface();
53 + const markdownStyles = useMarkdownPreviewStyles();
54 const { themeAppearance: appearanceScheme, themeId } = useAppearancePreferences();
55 const appTheme = useUniwindTheme();
56 const [NativeReviewDiffView] = useState(() => resolveNativeReviewDiffView());
@@ -166,9 +169,10 @@ export const ReviewCommentCard = memo(function ReviewCommentCard(props: {
169 </View>
170 {props.comment.text.length > 0 ? (
171 <View className="px-3 py-3">
169 - <Text selectable className="text-base leading-snug" style={{ color: props.colors.text }}>
170 - {props.comment.text}
171 - </Text>
172 + <SelectableMarkdownText
173 + markdown={props.comment.text}
174 + textStyle={markdownStyles.nativeTextStyle}
175 + />
176 </View>
177 ) : null}
178 {shouldRenderNativeDiff ? (
apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx
+12
@@ -68,6 +68,8 @@ interface AppearancePreferencesContextValue {
68 readonly setTerminalFontSize: (value: number | null) => void;
69 readonly setCodeFontSize: (value: number | null) => void;
70 readonly setCodeWordBreak: (value: boolean) => void;
71 + readonly mathRenderingEnabled: boolean;
72 + readonly setMathRenderingEnabled: (value: boolean) => void;
73 }
74
75 const AppearancePreferencesContext = createContext<AppearancePreferencesContextValue | null>(null);
@@ -264,6 +266,12 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
266 [updatePreferences],
267 );
268
269 + const mathRenderingEnabled = storedPreferences?.mathRenderingEnabled === true;
270 + const setMathRenderingEnabled = useCallback(
271 + (value: boolean) => updatePreferences({ mathRenderingEnabled: value }),
272 + [updatePreferences],
273 + );
274 +
275 const value = useMemo(
276 (): AppearancePreferencesContextValue => ({
277 appearance,
@@ -284,6 +292,8 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
292 setTerminalFontSize,
293 setCodeFontSize,
294 setCodeWordBreak,
295 + mathRenderingEnabled,
296 + setMathRenderingEnabled,
297 }),
298 [
299 appearance,
@@ -303,6 +313,8 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
313 setTerminalFontSize,
314 setCodeFontSize,
315 setCodeWordBreak,
316 + mathRenderingEnabled,
317 + setMathRenderingEnabled,
318 ],
319 );
320
apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx
+10 -1
@@ -10,9 +10,11 @@ import {
10 TextAppearancePreview,
11 } from "../components/AppearancePreviews";
12 import { FontSizeSliderRow } from "../components/FontSizeSliderRow";
13 +import { SettingsSwitchRow } from "../../components/SettingsSwitchRow";
14
15 export function TextAppearanceSection() {
15 - const { isReady, appearance, setBaseFontSize } = useAppearancePreferences();
16 + const { isReady, appearance, setBaseFontSize, mathRenderingEnabled, setMathRenderingEnabled } =
17 + useAppearancePreferences();
18
19 return (
20 <SettingsSection title="Text">
@@ -29,6 +31,13 @@ export function TextAppearanceSection() {
31 value={appearance.baseFontSize}
32 valueLabel={`${appearance.baseFontSize} pt`}
33 />
34 + <SettingsSwitchRow
35 + disabled={!isReady}
36 + icon="plusminus"
37 + label="Render math"
38 + value={mathRenderingEnabled}
39 + onValueChange={setMathRenderingEnabled}
40 + />
41 </SettingsSection>
42 );
43 }
apps/mobile/src/native/EnrichedMarkdownText.tsx
+11 -2
@@ -59,6 +59,15 @@ function enrichedStyle(
59 };
60 return {
61 paragraph: body,
62 + math: {
63 + fontSize: style.fontSize,
64 + color: style.color,
65 + backgroundColor: "transparent",
66 + padding: 8,
67 + marginTop: 4,
68 + marginBottom: 12,
69 + },
70 + inlineMath: { color: style.color },
71 h1: heading(1),
72 h2: heading(2),
73 h3: heading(3),
@@ -140,11 +149,11 @@ function enrichedStyle(
149
150 export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
151 const { renderImage, resolveImageSource } = props;
152 + const { themeAppearance, mathRenderingEnabled } = useAppearancePreferences();
153 const markdown = useMemo(
154 () => markdownWithTableBreaks(markdownWithHtml(props.markdown)),
155 [props.markdown],
156 );
147 - const { themeAppearance } = useAppearancePreferences();
157 const [documentAssets, setDocumentAssets] = useState<DocumentAssetsEvent["assets"]>([]);
158 const onDocumentAssets = useCallback(({ assets }: DocumentAssetsEvent) => {
159 setDocumentAssets((previous) =>
@@ -308,7 +317,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
317 selectionColor={props.textStyle.selectionColor}
318 selectionHandleColor={props.textStyle.selectionHandleColor}
319 md4cFlags={{
311 - latexMath: false,
320 + latexMath: mathRenderingEnabled,
321 hardSoftBreaks: props.preserveSoftBreaks ?? false,
322 admonitions: true,
323 }}
apps/mobile/src/persistence/mobile-preferences.ts
+4
@@ -63,6 +63,7 @@ export interface Preferences {
63 readonly markdownFontSize?: number;
64 readonly codeFontSize?: number | null;
65 readonly codeWordBreak?: boolean;
66 + readonly mathRenderingEnabled?: boolean;
67 readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
68 readonly collapsedProjectGroups?: readonly string[];
69 /** Environments whose "reclaim database space" notice was dismissed. */
@@ -137,6 +138,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
138 markdownFontSize?: number;
139 codeFontSize?: number | null;
140 codeWordBreak?: boolean;
141 + mathRenderingEnabled?: boolean;
142 connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
143 collapsedProjectGroups?: readonly string[];
144 dismissedDatabaseStorageNotices?: readonly string[];
@@ -206,6 +208,8 @@ function sanitizePreferences(parsed: Preferences): Preferences {
208 preferences.codeFontSize = parsed.codeFontSize;
209 }
210 if (typeof parsed.codeWordBreak === "boolean") preferences.codeWordBreak = parsed.codeWordBreak;
211 + if (typeof parsed.mathRenderingEnabled === "boolean")
212 + preferences.mathRenderingEnabled = parsed.mathRenderingEnabled;
213 if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
214 preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
215 (account): account is string => typeof account === "string",
apps/web/package.json
+2
@@ -61,6 +61,7 @@
61 "jose": "catalog:",
62 "jsonc-parser": "3.3.1",
63 "jszip": "3.10.1",
64 + "katex": "^0.16.47",
65 "lucide": "^0.564.0",
66 "lucide-react": "^0.564.0",
67 "mermaid": "^11.17.2",
@@ -69,6 +70,7 @@
70 "react-dom": "catalog:",
71 "react-markdown": "^10.1.0",
72 "remark-gfm": "catalog:",
73 + "remark-math": "6.0.0",
74 "tailwind-merge": "^3.4.0",
75 "unbash": "^5.0.0",
76 "use-sync-external-store": "^1.6.0",
apps/web/src/components/ChatMarkdown.browser.test.tsx
+180
@@ -5,6 +5,7 @@ import { AsyncResult } from "effect/reactivity";
5 import { act, type ReactElement } from "react";
6 import { createRoot, type Root } from "react-dom/client";
7 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
8 +import { page, userEvent } from "vite-plus/test/browser";
9
10 import { filesystemEnvironment } from "../state/filesystem";
11 import { useRightPanelStore } from "../rightPanelStore";
@@ -64,11 +65,25 @@ vi.mock(import("./chat/MermaidDiagram"), async (original) => {
65 };
66 });
67
68 +const settingsOverrides = vi.hoisted(() => ({ mathRenderingEnabled: false }));
69 +vi.mock(import("../hooks/useSettings"), async (original) => {
70 + const actual = await original();
71 + type Settings = ReturnType<typeof actual.getClientSettings>;
72 + function useClientSettings<T = Settings>(select?: (settings: Settings) => T): T {
73 + const settings = { ...actual.getClientSettings(), ...settingsOverrides };
74 + return select ? select(settings) : (settings as T);
75 + }
76 + return { ...actual, useClientSettings };
77 +});
78 +
79 import ChatMarkdown from "./ChatMarkdown";
80 +import { serializeTableElementToCsv, chatMarkdownClipboardPayload } from "../markdown-clipboard";
81 +import { captureAssistantTextSelection } from "../lib/assistantTextSelection";
82
83 const roots: Root[] = [];
84
85 beforeEach(() => {
86 + settingsOverrides.mathRenderingEnabled = false;
87 renderDiagram.mockReset();
88 workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
89 filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
@@ -1129,3 +1144,168 @@ describe("ChatMarkdown thread find", () => {
1144 },
1145 );
1146 });
1147 +
1148 +describe("ChatMarkdown math", () => {
1149 + const renderMath = async (
1150 + text: string,
1151 + options: Partial<Parameters<typeof ChatMarkdown>[0]> = {},
1152 + ) => {
1153 + settingsOverrides.mathRenderingEnabled = true;
1154 + const { container: host } = await render(
1155 + <ChatMarkdown cwd="/tmp/project" text={text} {...options} />,
1156 + );
1157 + host.setAttribute("data-assistant-citation-source", "assistant");
1158 + await act(async () => {
1159 + await import("./chat/MathTypeset");
1160 + });
1161 + return { host };
1162 + };
1163 +
1164 + it.each(["$x$", "$$x$$", "```math\nx\n```", "$\\notACommand{x}$"])(
1165 + "keeps keyboard focus on the parent control in compact previews of %s",
1166 + async (formula) => {
1167 + settingsOverrides.mathRenderingEnabled = true;
1168 + const { container } = await render(
1169 + <>
1170 + <button type="button">
1171 + Preview <ChatMarkdown inline text={formula} cwd={undefined} />
1172 + </button>
1173 + <button type="button">After preview</button>
1174 + </>,
1175 + );
1176 + await act(async () => {
1177 + await import("./chat/MathTypeset");
1178 + });
1179 + const [preview, after] = container.querySelectorAll("button");
1180 + preview!.focus();
1181 + await act(() => userEvent.tab());
1182 + expect(document.activeElement).toBe(after);
1183 + if (formula.includes("notACommand")) {
1184 + expect(page.getByRole("button", { name: /notACommand/ }).element()).toBe(preview);
1185 + }
1186 + },
1187 + );
1188 +
1189 + it("keeps message formulas reachable by keyboard", async () => {
1190 + settingsOverrides.mathRenderingEnabled = true;
1191 + const { container } = await render(
1192 + <>
1193 + <button type="button">Before equation</button>
1194 + <ChatMarkdown text="$x$" cwd={undefined} />
1195 + </>,
1196 + );
1197 + container.querySelector("button")!.focus();
1198 + await act(() => userEvent.tab());
1199 + expect(document.activeElement).toBe(
1200 + container.querySelector('[aria-label="Scroll inline equation"]'),
1201 + );
1202 + });
1203 +
1204 + it("renders table formulas and exports their TeX instead of duplicate glyph text", async () => {
1205 + const rendered = await renderMath(
1206 + "| Name | Formula |\n| --- | --- |\n| Norm | $|x|$ and \\(\\|y\\|\\) |\n| Price | $5 and $10 |",
1207 + );
1208 +
1209 + const table = rendered.host.querySelector("table")!;
1210 + expect([...table.rows].map((row) => row.cells.length)).toEqual([2, 2, 2]);
1211 + expect(table.querySelectorAll(".katex")).toHaveLength(2);
1212 + const norm = table.querySelectorAll(".katex")[1]!;
1213 + expect([...norm.querySelectorAll(".katex-mathml mi")].map((node) => node.textContent)).toEqual([
1214 + "∥",
1215 + "y",
1216 + "∥",
1217 + ]);
1218 + expect(serializeTableElementToCsv(table)).toBe(
1219 + "Name,Formula\nNorm,\\(|x|\\) and \\(\\|y\\|\\)\nPrice,$5 and $10",
1220 + );
1221 + const glyph = table.querySelector(".katex-mathml mi")!.firstChild!;
1222 + const range = document.createRange();
1223 + range.setStart(glyph, 0);
1224 + range.setEnd(glyph, 1);
1225 + const selection = window.getSelection()!;
1226 + selection.removeAllRanges();
1227 + selection.addRange(range);
1228 + const payload = chatMarkdownClipboardPayload(selection)!;
1229 + expect(payload.text).toBe("\\(|x|\\)");
1230 + expect(payload.html).toContain("\\(|x|\\)");
1231 + expect(payload.html).not.toContain("katex");
1232 + expect(captureAssistantTextSelection(rendered.host, selection)?.selector.text).toBe(
1233 + "\\(|x|\\)",
1234 + );
1235 + });
1236 +
1237 + it("renders explicit math fences and keeps unfinished streamed fences readable", async () => {
1238 + const rendered = await renderMath("```math\nx_i^2\n```\n\n`$literal$`\n\n$unfinished");
1239 +
1240 + expect(rendered.host.querySelectorAll(".katex")).toHaveLength(1);
1241 + expect(rendered.host.textContent).toContain("$literal$");
1242 + expect(rendered.host.textContent).toContain("$unfinished");
1243 +
1244 + const streamed = await renderMath("```math\nx_i^2", { isStreaming: true });
1245 +
1246 + expect(streamed.host.querySelector(".katex")).toBeNull();
1247 + expect(streamed.host.textContent).toContain("x_i^2");
1248 + });
1249 +
1250 + it.each(["$$\nx^2\n", "\\[\nx^2\n"])(
1251 + "keeps unfinished display %s and following prose readable while streaming",
1252 + async (source) => {
1253 + for (const text of [source, `${source}\nFollowing prose.`]) {
1254 + const { host } = await renderMath(text, { isStreaming: true });
1255 + expect(host.querySelector(".katex")).toBeNull();
1256 + expect(host.querySelector("[data-markdown-math]")).toBeNull();
1257 + expect(host.textContent).toContain("x^2");
1258 + if (text.includes("Following prose."))
1259 + expect(host.textContent).toContain("Following prose.");
1260 + }
1261 + },
1262 + );
1263 +
1264 + it.each(["$$x^2$$", "$$\nx^2\n$$", "\\[\nx^2\n\\]", "```math\nx^2\n```"])(
1265 + "renders completed %s while the response is streaming",
1266 + async (source) => {
1267 + const { host } = await renderMath(source, { isStreaming: true });
1268 + expect(host.querySelectorAll(".katex")).toHaveLength(1);
1269 + expect(host.querySelector('[data-markdown-math="display"]')).not.toBeNull();
1270 + },
1271 + );
1272 +
1273 + it("shows unsupported TeX as source and keeps active TeX commands inert", async () => {
1274 + const rendered = await renderMath(
1275 + "\\(\\notACommand{x}\\) and \\(\\href{https://example.com}{x}\\)",
1276 + );
1277 +
1278 + expect(rendered.host.textContent).toContain("\\(\\notACommand{x}\\)");
1279 + expect(rendered.host.querySelector('a[href="https://example.com"]')).toBeNull();
1280 + });
1281 +
1282 + it("typesets only when enabled, keeping prices and task offsets intact", async () => {
1283 + const text = "Area $\\pi r^2$ costs $5 and $10.\n\n\\[\nE = mc^2\n\\]\n\n- [ ] check \\(x\\)";
1284 + const off = await renderText(text);
1285 + expect(off.querySelector("[data-markdown-math]")).toBeNull();
1286 + const html = await renderText('<code class="language-math math-inline">x</code>');
1287 + expect(html.querySelector("[data-markdown-math]")).toBeNull();
1288 + for (const parseRawHtml of [true, false]) {
1289 + let editedText = text;
1290 + const { host } = await renderMath(text, {
1291 + parseRawHtml,
1292 + onTaskListChange: ({ markerOffset, checked }) => {
1293 + editedText = setMarkdownTaskChecked(text, markerOffset, checked);
1294 + },
1295 + });
1296 + expect(
1297 + [...host.querySelectorAll("[data-markdown-math]")].map((node) =>
1298 + node.getAttribute("data-markdown-copy"),
1299 + ),
1300 + ).toEqual(["\\(\\pi r^2\\)", "\\[\nE = mc^2\n\\]\n\n", "\\(x\\)"]);
1301 + await act(() => host.querySelector<HTMLInputElement>('input[type="checkbox"]')!.click());
1302 + expect(editedText).toBe(text.replace("- [ ]", "- [x]"));
1303 + }
1304 + const { host } = await renderMath("- intro\n\n $$\n x^2\n $$");
1305 + expect(
1306 + [...host.querySelectorAll("[data-markdown-math]")].map((node) =>
1307 + node.getAttribute("data-markdown-copy"),
1308 + ),
1309 + ).toEqual(["\\[\nx^2\n\\]\n\n"]);
1310 + });
1311 +});
apps/web/src/components/ChatMarkdown.tsx
+55 -13
@@ -110,11 +110,14 @@ import { parseComposerContextHref } from "@t3tools/shared/composerContextReferen
110 import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";
111 import { AssistantCitationChip } from "./chat/AssistantCitationChip";
112 import { MarkdownThreadLink } from "./chat/MarkdownThreadLink";
113 +import { mathKind } from "@t3tools/shared/markdownMath";
114 +import remarkMath from "remark-math";
115 import {
116 artifactTemplateFromHastProperties,
117 renderCodexInlineDirectivesAsMarkdown,
118 } from "@t3tools/shared/codexMarkdownDirectives";
119 import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
120 +import { MarkdownMath } from "./chat/MarkdownMath";
121 import {
122 resolveMarkdownMediaPreview,
123 type ExpandedImagePreview,
@@ -226,6 +229,8 @@ import { resolveLinkTarget } from "../browser/browserLinkTarget";
229 import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview";
230
231 interface ChatMarkdownProps {
232 + /** Compact markdown transforms remove blocks before rendering inside a label. */
233 + inline?: boolean;
234 text: string;
235 cwd: string | undefined;
236 threadRef?: ScopedThreadRef | undefined;
@@ -2354,6 +2359,7 @@ const markdownServerConfigFieldsAtom = Atom.family((environmentId: EnvironmentId
2359
2360 function useChatMarkdownState({
2361 text,
2362 + inline = false,
2363 cwd,
2364 threadRef,
2365 pullRequestPanelRef,
@@ -2371,7 +2377,7 @@ function useChatMarkdownState({
2377 githubMedia = false,
2378 }: ChatMarkdownProps) {
2379 const { resolvedTheme } = useTheme();
2374 - const markdownRef = useRef<HTMLDivElement>(null);
2380 + const markdownRef = useRef<HTMLElement>(null);
2381 const mediaRequestId = useRef(0);
2382 // A preview opened from another thread or workspace never carries over.
2383 const mediaScopeKey = [
@@ -2545,7 +2551,7 @@ function useChatMarkdownState({
2551 if (isWindowsDrivePathHref(href)) return href;
2552 return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
2553 };
2548 - const handleCopy = (event: ReactClipboardEvent<HTMLDivElement>) => {
2554 + const handleCopy = (event: ReactClipboardEvent<HTMLElement>) => {
2555 const selection = window.getSelection();
2556 if (!selection || selection.isCollapsed || !event.clipboardData) return;
2557 const payload = chatMarkdownClipboardPayload(selection);
@@ -2566,6 +2572,7 @@ function useChatMarkdownState({
2572 // synchronously whether to intercept its `_blank`, and a subscription is what
2573 // makes a persisted "app" apply once settings hydrate after launch.
2574 const linkTargetPreference = useClientSettings((settings) => settings.browserLinkTarget);
2575 + const mathEnabled = useClientSettings((settings) => settings.mathRenderingEnabled);
2576 const resolveThreadPullRequest = (
2577 href: string,
2578 ): (ThreadPullRequestKey & { readonly url: string }) | null => {
@@ -2779,6 +2786,8 @@ function useChatMarkdownState({
2786 imageBaseDir,
2787 workspaceMutationId,
2788 inlineCodeFileLinkMetaByText,
2789 + inline,
2790 + mathEnabled,
2791 isStreaming,
2792 linkTargetPreference,
2793 markdownFileLinkMetaByHref,
@@ -3196,9 +3205,18 @@ const CHAT_MARKDOWN_COMPONENTS = {
3205 );
3206 },
3207 code: function MarkdownCode({ node, children, className, ...props }) {
3199 - const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip } = use(
3200 - ChatMarkdownRendererContext,
3201 - );
3208 + const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip, mathEnabled, inline } =
3209 + use(ChatMarkdownRendererContext);
3210 + const math = mathEnabled ? mathKind(className) : null;
3211 + if (math) {
3212 + return (
3213 + <MarkdownMath
3214 + tex={nodeToPlainText(children)}
3215 + display={math === "display"}
3216 + focusable={!inline}
3217 + />
3218 + );
3219 + }
3220 if (node?.properties?.dataInlineCode != null) {
3221 const codeText = nodeToPlainText(children);
3222 const fileLinkMeta =
@@ -3352,9 +3370,15 @@ const CHAT_MARKDOWN_COMPONENTS = {
3370 return <MarkdownDetails open={detailsOpen}>{children}</MarkdownDetails>;
3371 },
3372 pre: function MarkdownPre({ node, children, ...props }) {
3355 - const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand } = use(
3356 - ChatMarkdownRendererContext,
3357 - );
3373 + const {
3374 + resolvedTheme,
3375 + diffThemeName,
3376 + expandMedia,
3377 + isStreaming,
3378 + onRunShellCommand,
3379 + inline,
3380 + mathEnabled,
3381 + } = use(ChatMarkdownRendererContext);
3382 const text = use(ChatMarkdownTextContext);
3383 const codeBlock = extractCodeBlock(children);
3384 if (!codeBlock) {
@@ -3362,6 +3386,15 @@ const CHAT_MARKDOWN_COMPONENTS = {
3386 }
3387
3388 const language = extractFenceLanguage(codeBlock.className);
3389 + if (
3390 + mathEnabled &&
3391 + language === "math" &&
3392 + (!isStreaming ||
3393 + mathKind(codeBlock.className) === "display" ||
3394 + isClosedCodeFence(node, text, codeBlock.code))
3395 + ) {
3396 + return <MarkdownMath tex={codeBlock.code} display focusable={!inline} />;
3397 + }
3398 const fenceTitle = extractFenceTitle(extractPreCodeMeta(node));
3399 const highlightedCode = (
3400 <RenderErrorBoundary
@@ -3419,6 +3452,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
3452 function ChatMarkdown({
3453 text,
3454 className,
3455 + inline = false,
3456 lineBreaks = false,
3457 parseRawHtml = true,
3458 extraRemarkPlugins = EMPTY_REMARK_PLUGINS,
@@ -3431,22 +3465,30 @@ function ChatMarkdown({
3465 markdownUrlTransform,
3466 localMediaPreview,
3467 closeLocalMediaPreview,
3434 - } = useChatMarkdownState({ text, ...props });
3468 + } = useChatMarkdownState({ text, inline, ...props });
3469 const incrementalParsing =
3470 props.isStreaming === true &&
3471 extraRemarkPlugins.length === 0 &&
3472 /(?:^|\n) {0,3}(?:`{3}|~{3})/.test(text);
3473 + const Root = inline ? "span" : "div";
3474 + const bindMarkdownRef = (node: HTMLElement | null) => {
3475 + markdownRef.current = node;
3476 + };
3477 const remarkPlugins = [
3478 ...(lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS),
3479 ...extraRemarkPlugins,
3480 ...(incrementalParsing ? [createIncrementalMarkdownPlugin()] : []),
3481 ];
3482 + if (componentState.mathEnabled)
3483 + remarkPlugins.unshift([remarkMath, { singleDollarTextMath: true }]);
3484
3485 return (
3446 - <div
3447 - ref={markdownRef}
3486 + <Root
3487 + ref={bindMarkdownRef}
3488 className={cn(
3449 - "chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/[calc(80%+var(--appearance-contrast-boost)/5)] [overflow-wrap:anywhere] [word-break:break-word]",
3489 + "chat-markdown w-full min-w-0 [overflow-wrap:anywhere] [word-break:break-word]",
3490 + !inline &&
3491 + "text-sm leading-relaxed text-foreground/[calc(80%+var(--appearance-contrast-boost)/5)]",
3492 className,
3493 )}
3494 data-streaming={componentState.isStreaming ? "" : undefined}
@@ -3472,7 +3514,7 @@ function ChatMarkdown({
3514 {localMediaPreview ? (
3515 <ExpandedImageDialog preview={localMediaPreview} onClose={closeLocalMediaPreview} />
3516 ) : null}
3475 - </div>
3517 + </Root>
3518 );
3519 }
3520
apps/web/src/components/chat/MarkdownMath.tsx new
+59
@@ -0,0 +1,59 @@
1 +import { lazy, memo, Suspense } from "react";
2 +
3 +import { RenderErrorBoundary } from "../RenderErrorBoundary";
4 +
5 +const MathTypeset = lazy(() => import("./MathTypeset"));
6 +
7 +/**
8 + * One formula from `remark-math`. Shows its TeX until KaTeX loads, and
9 + * keeps showing it when KaTeX cannot parse it, such as mid-stream. Copying
10 + * any part of a formula copies its whole TeX source.
11 + */
12 +export const MarkdownMath = memo(function MarkdownMath(props: {
13 + tex: string;
14 + display: boolean;
15 + focusable?: boolean;
16 +}) {
17 + const tex = props.tex.trim();
18 + const source = props.display ? `\\[\n${tex}\n\\]` : `\\(${tex}\\)`;
19 + const fallback = <span className="whitespace-pre-wrap">{source}</span>;
20 + return (
21 + <span
22 + className={
23 + props.display
24 + ? "chat-markdown-math-display my-[0.65rem] block in-[.chat-markdown-table-container]:max-w-none in-[.chat-markdown-table-container]:overflow-visible"
25 + : "inline-block max-w-full align-middle whitespace-nowrap wrap-normal break-normal in-[.chat-markdown-table-container]:max-w-none in-[.chat-markdown-table-container]:overflow-visible"
26 + }
27 + data-markdown-math={props.display ? "display" : "inline"}
28 + data-markdown-copy={props.display ? `${source}\n\n` : source}
29 + role={props.focusable === false ? undefined : "group"}
30 + aria-label={
31 + props.focusable === false
32 + ? undefined
33 + : props.display
34 + ? "Display equation"
35 + : "Inline equation"
36 + }
37 + >
38 + <span
39 + className="block max-w-full overflow-x-auto overflow-y-hidden in-[.chat-markdown-table-container]:max-w-none in-[.chat-markdown-table-container]:overflow-visible px-0.5 py-0.75 focus-visible:outline-1 focus-visible:outline-solid focus-visible:-outline-offset-1 focus-visible:outline-border [&::-webkit-scrollbar]:h-2 [&::-webkit-scrollbar-thumb]:rounded [&::-webkit-scrollbar-thumb]:border [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-clip-content"
40 + tabIndex={props.focusable === false ? -1 : 0}
41 + aria-label={
42 + props.focusable === false
43 + ? undefined
44 + : props.display
45 + ? "Scroll display equation"
46 + : "Scroll inline equation"
47 + }
48 + >
49 + <span className={props.display ? "inline-block w-max min-w-full" : "inline-block w-max"}>
50 + <RenderErrorBoundary resetKeys={[tex]} fallback={fallback}>
51 + <Suspense fallback={fallback}>
52 + <MathTypeset tex={tex} display={props.display} fallback={fallback} />
53 + </Suspense>
54 + </RenderErrorBoundary>
55 + </span>
56 + </span>
57 + </span>
58 + );
59 +});
apps/web/src/components/chat/MathTypeset.tsx new
+40
@@ -0,0 +1,40 @@
1 +import katex from "katex";
2 +import "katex/dist/katex.min.css";
3 +import type { ReactNode } from "react";
4 +
5 +import { LRUCache } from "../../lib/lruCache";
6 +
7 +// Virtualized threads remount messages while scrolling; cached markup keeps
8 +// that from typesetting the same formulas again. "" records a parse error.
9 +const typesetCache = new LRUCache<string>(1000, 4 * 1024 * 1024);
10 +
11 +function typeset(tex: string, display: boolean): string {
12 + const key = `${display ? "display" : "inline"}:${tex}`;
13 + const cached = typesetCache.get(key);
14 + if (cached !== null) return cached;
15 + let html = "";
16 + try {
17 + html = katex.renderToString(tex, {
18 + displayMode: display,
19 + output: "htmlAndMathml",
20 + throwOnError: true,
21 + // No \href, \url, \htmlClass, or other commands that emit active HTML.
22 + trust: false,
23 + strict: "ignore",
24 + maxSize: 20,
25 + maxExpand: 1000,
26 + });
27 + } catch {
28 + // Unfinished or unsupported TeX stays readable as its source.
29 + }
30 + typesetCache.set(key, html, (key.length + html.length) * 2);
31 + return html;
32 +}
33 +
34 +/** KaTeX lives in this lazily loaded chunk, so it is only fetched once a formula renders. */
35 +export default function MathTypeset(props: { tex: string; display: boolean; fallback: ReactNode }) {
36 + const html = typeset(props.tex, props.display);
37 + if (!html) return props.fallback;
38 + // KaTeX escapes the TeX it renders, and `trust: false` keeps it from emitting links or attributes.
39 + return <span dangerouslySetInnerHTML={{ __html: html }} />;
40 +}
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+21 -1
@@ -18,7 +18,8 @@ import "~/index.css";
18 import { serverEnvironment } from "../../state/server";
19 import { PullRequestLinkPreview } from "../pullRequest/PullRequestLinkPreview";
20 import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "../ui/tooltip";
21 -import { MessagesTimeline } from "./MessagesTimeline";
21 +import { MessagesTimeline, remarkThoughtPreview } from "./MessagesTimeline";
22 +import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
23 import { readTimelinePosition } from "./timelineScrollAnchoring";
24 import { useComposerFocusState } from "./useComposerFocusState";
25
@@ -1480,3 +1481,22 @@ describe("MessagesTimeline send anchor", () => {
1481 expect(onAnchorReady).not.toHaveBeenCalled();
1482 });
1483 });
1484 +
1485 +describe("compact reasoning math", () => {
1486 + it("keeps formulas while flattening compact reasoning previews", () => {
1487 + const tree = parseMarkdownWithMath("## Reasoning\n\nUse **norm** $|x|$ and \\[x^2\\]");
1488 + remarkThoughtPreview("Reasoning")(tree);
1489 + expect(tree.children.map((node) => node.type)).toEqual([
1490 + "text",
1491 + "inlineMath",
1492 + "text",
1493 + "inlineMath",
1494 + ]);
1495 + expect(tree.children.map((node) => ("value" in node ? node.value : null))).toEqual([
1496 + "Reasoning Use norm ",
1497 + "|x|",
1498 + " and ",
1499 + "x^2",
1500 + ]);
1501 + });
1502 +});
apps/web/src/components/chat/MessagesTimeline.tsx
+78 -44
@@ -1,9 +1,7 @@
1 +import type { Root, RootContent } from "mdast";
2 import { ThreadFindTimelineContext } from "./ThreadFindProvider";
3 import { shallow } from "zustand/vanilla/shallow";
3 -import {
4 - remarkKeepWindowsPaths,
5 - shouldPreserveAssistantLineBreaks,
6 -} from "@t3tools/shared/markdownPipeline";
4 +import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
5 import { MarkdownFindContext, findRevealRef } from "./markdownFindContext";
6 import { useChatCanvas } from "./ChatCanvasContext";
7 import { WorkLogBlock, WorkLogButton, WorkLogDetails, WorkLogList, WorkLogRow } from "./WorkLog";
@@ -119,9 +117,6 @@ import {
117 } from "../../lib/diffRendering";
118 import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting";
119 import ChatMarkdown, { ChatMarkdownAssetImage } from "../ChatMarkdown";
122 -import ReactMarkdown from "react-markdown";
123 -import remarkGfm from "remark-gfm";
124 -import type { Root, RootContent } from "mdast";
120 import { T3Wordmark } from "../T3Wordmark";
121 import { ThreadContextChip } from "../ThreadContextChip";
122 import {
@@ -302,7 +297,7 @@ import { SecretRequestCard } from "./SecretRequestCard";
297 import { TimelineSystemDivider } from "./TimelineSystemDivider";
298 import { WorkflowOpeningBlock } from "./WorkflowOpeningBlock";
299
305 -import { SkillChipIcon, SkillInlineText } from "./SkillInlineText";
300 +import { SkillChipIcon } from "./SkillInlineText";
301 import * as DateTime from "effect/DateTime";
302 import { formatWorkspaceRelativePath } from "../../filePathDisplay";
303 import { forwardWheelToTimeline } from "./timelineMinimapWheel";
@@ -3861,7 +3856,17 @@ function LiveWorkEntryTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "
3856 />
3857 </span>
3858 }
3864 - label={<span className="line-clamp-4">{thoughtLine}</span>}
3859 + label={
3860 + <span className="line-clamp-4">
3861 + <ChatMarkdown
3862 + inline
3863 + text={thoughtLine}
3864 + cwd={ctx.markdownCwd}
3865 + parseRawHtml={false}
3866 + extraRemarkPlugins={[[remarkThoughtPreview, "Thought"]]}
3867 + />
3868 + </span>
3869 + }
3870 wrapLabel
3871 />
3872 ) : null}
@@ -3881,15 +3886,13 @@ function LiveWorkEntryTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "
3886 </span>
3887 </span>
3888 ) : row.entry.itemType === "reasoning" ? (
3884 - <ReactMarkdown
3885 - remarkPlugins={[
3886 - remarkGfm,
3887 - remarkKeepWindowsPaths,
3888 - [remarkThoughtPreview, row.active ? "Thinking" : "Thought"],
3889 - ]}
3890 - >
3891 - {row.entry.detail ?? label}
3892 - </ReactMarkdown>
3889 + <ChatMarkdown
3890 + inline
3891 + text={row.entry.detail ?? label}
3892 + cwd={ctx.markdownCwd}
3893 + parseRawHtml={false}
3894 + extraRemarkPlugins={[[remarkThoughtPreview, row.active ? "Thinking" : "Thought"]]}
3895 + />
3896 ) : threadLabel ? (
3897 <ThreadReadLabel
3898 label={threadLabel}
@@ -4688,8 +4691,14 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
4691 </div>
4692 </div>
4693 {comment.text.length > 0 && (
4691 - <div className="whitespace-pre-wrap wrap-break-word text-sm">
4692 - <SkillInlineText text={comment.text} skills={ctx.skills} />
4694 + <div className="wrap-break-word text-sm">
4695 + <ChatMarkdown
4696 + text={comment.text}
4697 + cwd={ctx.markdownCwd}
4698 + skills={ctx.skills}
4699 + parseRawHtml={false}
4700 + lineBreaks
4701 + />
4702 </div>
4703 )}
4704 {fenceLanguage !== "diff" && comment.diff.trim().length > 0 && (
@@ -5195,25 +5204,50 @@ function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
5204
5205 const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation();
5206
5198 -function remarkThoughtPreview(fallback: string) {
5207 +/** Compact reasoning keeps formulas while flattening other Markdown into label text. */
5208 +export function remarkThoughtPreview(fallback: string) {
5209 return (tree: Root) => {
5200 - const plainText = (node: Root | RootContent): string => {
5201 - if (node.type === "html" || node.type === "definition") return "";
5202 - if ("alt" in node) return node.alt ?? "";
5203 - if ("value" in node) return node.value;
5204 - if ("children" in node) {
5205 - const separator = ["root", "blockquote", "list", "listItem", "table", "tableRow"].includes(
5206 - node.type,
5207 - )
5208 - ? " "
5209 - : "";
5210 - return node.children.map(plainText).join(separator);
5211 - }
5212 - return node.type === "break" ? " " : "";
5210 + const children: RootContent[] = [];
5211 + const append = (value: string) => {
5212 + const last = children.at(-1);
5213 + const text = value.replace(/\s+/g, " ");
5214 + if (last?.type === "text") last.value = (last.value + text).replace(/\s+/g, " ");
5215 + else children.push({ type: "text", value: text });
5216 };
5214 - tree.children = [
5215 - { type: "text", value: plainText(tree).replace(/\s+/g, " ").trim() || fallback },
5216 - ];
5217 + const visit = (node: Root | RootContent) => {
5218 + if (node.type === "html" || node.type === "definition") return;
5219 + if (node.type === "math" || node.type === "inlineMath") {
5220 + children.push({
5221 + type: "inlineMath",
5222 + value: node.value,
5223 + position: node.position,
5224 + data: {
5225 + hName: "code",
5226 + hProperties: { className: ["language-math", "math-inline"] },
5227 + hChildren: [{ type: "text", value: node.value }],
5228 + },
5229 + });
5230 + } else if ("alt" in node) append(node.alt ?? "");
5231 + else if ("value" in node) append(node.value);
5232 + else if ("children" in node) {
5233 + node.children.forEach((child, index) => {
5234 + if (
5235 + index &&
5236 + ["root", "blockquote", "list", "listItem", "table", "tableRow"].includes(node.type)
5237 + )
5238 + append(" ");
5239 + visit(child);
5240 + });
5241 + } else if (node.type === "break") append(" ");
5242 + };
5243 + visit(tree);
5244 + const first = children[0];
5245 + const last = children.at(-1);
5246 + if (first?.type === "text") first.value = first.value.trimStart();
5247 + if (last?.type === "text") last.value = last.value.trimEnd();
5248 + tree.children = children.some((child) => child.type !== "text" || child.value)
5249 + ? children
5250 + : [{ type: "text", value: fallback }];
5251 };
5252 }
5253
@@ -5512,18 +5546,18 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {
5546 className={cn(answerPreview ? "min-w-0" : "min-w-0 flex-1", "truncate", headingClass)}
5547 >
5548 {isReasoning && !expanded ? (
5515 - <ReactMarkdown
5516 - remarkPlugins={[
5517 - remarkGfm,
5518 - remarkKeepWindowsPaths,
5549 + <ChatMarkdown
5550 + inline
5551 + text={workEntry.detail ?? previewText}
5552 + cwd={ctx.markdownCwd}
5553 + parseRawHtml={false}
5554 + extraRemarkPlugins={[
5555 [
5556 remarkThoughtPreview,
5557 workEntry.toolLifecycleStatus === "inProgress" ? "Thinking" : "Thought",
5558 ],
5559 ]}
5524 - >
5525 - {workEntry.detail ?? previewText}
5526 - </ReactMarkdown>
5560 + />
5561 ) : threadLabel ? (
5562 <ThreadReadLabel
5563 label={threadLabel}
apps/web/src/components/chat/SkillInlineText.tsx
+1 -1
@@ -5,7 +5,7 @@ import { matchInlineSkills, type InlineSkill } from "@t3tools/shared/inlineSkill
5 import { SKILL_CHIP_ICON_SVG } from "../composerInlineChip";
6 import { ContextChip, ContextChipLabel } from "../ContextChip";
7
8 -export function SkillInlineText(props: { text: string; skills: ReadonlyArray<InlineSkill> }) {
8 +function SkillInlineText(props: { text: string; skills: ReadonlyArray<InlineSkill> }) {
9 const nodes: ReactNode[] = [];
10 let cursor = 0;
11
apps/web/src/components/settings/SettingsPanels.tsx
+29
@@ -543,6 +543,9 @@ export function useSettingsRestore(onRestored?: () => void) {
543 ? ["Diff colors"]
544 : []),
545 ...(settings.chatWidth !== DEFAULT_UNIFIED_SETTINGS.chatWidth ? ["Chat width"] : []),
546 + ...(settings.mathRenderingEnabled !== DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled
547 + ? ["Render math"]
548 + : []),
549 ...(settings.panelAnimationDurationMs !== DEFAULT_UNIFIED_SETTINGS.panelAnimationDurationMs
550 ? ["Panel animations"]
551 : []),
@@ -717,6 +720,7 @@ export function useSettingsRestore(onRestored?: () => void) {
720 appearanceContrast: DEFAULT_UNIFIED_SETTINGS.appearanceContrast,
721 diffColorScheme: DEFAULT_UNIFIED_SETTINGS.diffColorScheme,
722 chatWidth: DEFAULT_UNIFIED_SETTINGS.chatWidth,
723 + mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled,
724 timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
725 notificationMode: DEFAULT_UNIFIED_SETTINGS.notificationMode,
726 inAppNotificationsEnabled: DEFAULT_UNIFIED_SETTINGS.inAppNotificationsEnabled,
@@ -1374,6 +1378,31 @@ export function AppearanceSettingsPanel() {
1378 </div>
1379 }
1380 />
1381 + <SettingsRow
1382 + {...searchableSetting("math-rendering")}
1383 + description="Typeset LaTeX math, such as $x^2$ or \[x^2\], in messages and Markdown previews. The composer keeps TeX source editable."
1384 + resetAction={
1385 + settings.mathRenderingEnabled !== DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled ? (
1386 + <SettingResetButton
1387 + label="math rendering"
1388 + onClick={() =>
1389 + updateSettings({
1390 + mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled,
1391 + })
1392 + }
1393 + />
1394 + ) : null
1395 + }
1396 + control={
1397 + <Switch
1398 + checked={settings.mathRenderingEnabled}
1399 + onCheckedChange={(checked) =>
1400 + updateSettings({ mathRenderingEnabled: Boolean(checked) })
1401 + }
1402 + aria-label="Render math"
1403 + />
1404 + }
1405 + />
1406 </SettingsSection>
1407
1408 <SettingsSection id="motion" title="Motion">
apps/web/src/components/settings/settingsSearch.ts
+6
@@ -238,6 +238,12 @@ export const SETTINGS_SEARCH_ITEMS = [
238 to: "/settings/appearance",
239 searchTerms: ["wide full width column layout messages composer monitor"],
240 },
241 + {
242 + id: "math-rendering",
243 + title: "Render math",
244 + to: "/settings/appearance",
245 + searchTerms: ["latex tex katex equations formulas markdown"],
246 + },
247 {
248 id: "panel-animations",
249 title: "Panel animations",
apps/web/src/composer-rich-text-doc.test.ts
+48
@@ -86,6 +86,54 @@ function roundTrip(value: string) {
86 return serializeEditorDoc(doc);
87 }
88
89 +describe("editable math source", () => {
90 + it.each([
91 + "Area $x_i^2$ after",
92 + "before \\(\\frac{1}{2}\\) after",
93 + "before $$x^2$$ after",
94 + "\\[\nx = 1\ny = 2\n\\]",
95 + "\\[\\text{use $browser then @README.md and **literal**}\\]",
96 + "```math\nx_i + y_i\n```",
97 + "- **use** $x_i$ then @README.md",
98 + "**$x_i$** and **A $x_i$ B**",
99 + "| Name | Formula |\n| --- | --- |\n| Norm | $|x|$ |",
100 + "| Name | Formula |\n| --- | --- |\n| Norm | \\(\\|x\\|\\) |",
101 + ])("keeps TeX editable and round trips its source: %s", (source) => {
102 + const map = roundTrip(source);
103 + expect(map.value).toBe(source);
104 + expect(map.runs.some((run) => run.nodeName === "composer-math")).toBe(false);
105 + const doc = schema.nodeFromJSON(
106 + buildDocJson(source, (name) => ({ label: name, description: null })),
107 + );
108 + expect(serializeSelection(doc, 1, doc.content.size - 1)).toBe(source);
109 + });
110 +
111 + it("edits a command character directly without replacing a formula node", () => {
112 + const source = "before \\(\\frac{a}{b}\\) after";
113 + const doc = schema.nodeFromJSON(
114 + buildDocJson(source, (name) => ({ label: name, description: null })),
115 + );
116 + const map = serializeEditorDoc(doc);
117 + const offset = source.indexOf("{a}") + 1;
118 + const position = flatToPm(map, offset);
119 + const state = EditorState.create({ doc });
120 + const next = state.apply(state.tr.insertText("c", position, position + 1));
121 + expect(serializeEditorDoc(next.doc).value).toBe(source.replace("{a}", "{c}"));
122 + });
123 + it("preserves formula source as text when styling is disabled", () => {
124 + const source =
125 + "\\[\n\\text{use $browser, @README.md and [file](t3-context://v1/file/ctx_1)}\n\\]";
126 + const doc = plainSchema.nodeFromJSON(
127 + buildDocJson(source, (name) => ({ label: name, description: null }), { styling: false }),
128 + );
129 + const map = serializeEditorDoc(doc);
130 + expect(map.value).toBe(source);
131 + expect(map.runs.some((run) => run.kind === "token")).toBe(false);
132 + });
133 +});
134 +
135 +// Plain mode: the same engine with the mark extensions off. Markers stay
136 +// literal characters and task lines stay paragraphs.
137 const plainSchema = getSchemaByResolvedExtensions(
138 resolveExtensions([
139 StarterKit.configure({
apps/web/src/composer-rich-text-doc.ts
+27 -6
@@ -28,6 +28,7 @@ import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
28 import { nextOrderedMarkerText } from "~/composer-list-continuation";
29 import { parseInlineMarkdown, RICH_TEXT_DELIMITERS, type RichTextMark } from "~/composer-rich-text";
30 import { collectInlineContextIds } from "~/lib/composerContextReferences";
31 +import { markdownMathRanges } from "@t3tools/shared/markdownMath";
32
33 export type SkillMeta = { label: string; description: string | null };
34
@@ -541,12 +542,32 @@ export function buildTiptapContent(
542 const atoms: InlineJson[] = [];
543 const atomSources: string[] = [];
544 const literal = value.slice(0, options?.literalLength ?? 0);
544 - const text = splitPromptIntoComposerSegments(value.slice(literal.length))
545 - .map((segment) => {
546 - if (segment.type === "text") return segment.text;
547 - atoms.push(atomJsonForSegment(segment, skillLabelFor));
548 - atomSources.push(segment.source);
549 - return sentinel;
545 + const remainder = value.slice(literal.length);
546 + const formulas = markdownMathRanges(remainder);
547 + let offset = 0;
548 + const chunks: Array<{ text: string } | { source: string }> = [];
549 + for (const formula of formulas) {
550 + chunks.push({ text: remainder.slice(offset, formula.start) }, { source: formula.source });
551 + offset = formula.end;
552 + }
553 + chunks.push({ text: remainder.slice(offset) });
554 + // Math stays editable source. Shield its commands and Markdown-like markers
555 + // from styling and context-chip parsing, then restore ordinary text nodes.
556 + const text = chunks
557 + .map((chunk) => {
558 + if ("source" in chunk) {
559 + atoms.push(textJsonForSpan(chunk.source, []));
560 + atomSources.push(chunk.source);
561 + return sentinel;
562 + }
563 + return splitPromptIntoComposerSegments(chunk.text)
564 + .map((segment) => {
565 + if (segment.type === "text") return segment.text;
566 + atoms.push(atomJsonForSegment(segment, skillLabelFor));
567 + atomSources.push(segment.source);
568 + return sentinel;
569 + })
570 + .join("");
571 })
572 .join("");
573 let atomIndex = 0;
apps/web/src/index.css
+10
@@ -1801,6 +1801,10 @@ code {
1801 margin: 0.65rem 0;
1802 }
1803
1804 +.chat-markdown-math-display .katex-display {
1805 + margin: 0;
1806 +}
1807 +
1808 :is(.chat-markdown, .composer-tiptap) h1,
1809 :is(.chat-markdown, .composer-tiptap) h2,
1810 :is(.chat-markdown, .composer-tiptap) h3,
@@ -2101,6 +2105,12 @@ code {
2105 overflow-wrap: anywhere;
2106 }
2107
2108 +/* Formula cells keep their natural width and scroll with the table. */
2109 +.chat-markdown .chat-markdown-table-container td:has([data-markdown-math]) {
2110 + max-width: none;
2111 + overflow: visible;
2112 +}
2113 +
2114 :root {
2115 --diff-addition: var(--success);
2116 --diff-deletion: var(--destructive);
apps/web/src/lib/assistantTextSelection.ts
+37 -17
@@ -1,5 +1,7 @@
1 import { ASSISTANT_CITATION_CONTEXT_LENGTH, type AssistantCitation } from "@t3tools/contracts";
2
3 +import { mathWrapperOf } from "../markdown-clipboard";
4 +
5 export type AssistantTextSelector = {
6 readonly text: string;
7 readonly start: number;
@@ -122,7 +124,10 @@ export function findAssistantCitationText(
124 return match ?? (quoteCount === 1 ? onlyQuote : null);
125 }
126
125 -type TextChunk = { node: Text; start: number; end: number };
127 +/** A text node, or a whole rendered formula standing for its TeX. */
128 +type TextChunk = { node: Text | Element; start: number; end: number };
129 +
130 +const isText = (node: Node): node is Text => node.nodeType === 3;
131
132 function readAssistantText(root: HTMLElement) {
133 const parts: string[] = [];
@@ -130,18 +135,21 @@ function readAssistantText(root: HTMLElement) {
135 let length = 0;
136 let separator = false;
137
138 + const append = (node: Text | Element, text: string) => {
139 + if (separator && length > 0) {
140 + parts.push("\n");
141 + length += 1;
142 + }
143 + separator = false;
144 + chunks.push({ node, start: length, end: length + text.length });
145 + parts.push(text);
146 + length += text.length;
147 + };
148 +
149 const visit = (node: Node) => {
150 if (node.nodeType === 3) {
151 const text = node as Text;
136 - if (text.length === 0) return;
137 - if (separator && length > 0) {
138 - parts.push("\n");
139 - length += 1;
140 - }
141 - separator = false;
142 - chunks.push({ node: text, start: length, end: length + text.length });
143 - parts.push(text.data);
144 - length += text.length;
152 + if (text.length > 0) append(text, text.data);
153 return;
154 }
155 if (node.nodeType !== 1) return;
@@ -149,7 +157,11 @@ function readAssistantText(root: HTMLElement) {
157 if (element.matches(EXCLUDED_SELECTOR)) return;
158 const block = element.matches(BLOCK_SELECTOR);
159 if (block || element.tagName === "BR") separator = true;
152 - for (const child of element.childNodes) visit(child);
160 + if (element.matches("[data-markdown-math]")) {
161 + append(element, element.getAttribute("data-markdown-copy")?.trim() ?? "");
162 + } else {
163 + for (const child of element.childNodes) visit(child);
164 + }
165 if (block) separator = true;
166 };
167
@@ -176,7 +188,7 @@ function isUsableRange(root: HTMLElement, range: Range): boolean {
188 }
189
190 function isUnselectable(text: Text): boolean {
179 - const element = text.parentElement;
191 + const element = mathWrapperOf(text.parentElement) ?? text.parentElement;
192 const view = element?.ownerDocument?.defaultView;
193 return !!element && !!view && view.getComputedStyle(element).userSelect === "none";
194 }
@@ -216,8 +228,13 @@ export function captureAssistantTextSelection(
228
229 // Paragraph selection can end at the next block's offset 0 or a parent
230 // boundary. Validate the text actually selected, not that empty endpoint.
219 - range.setStart(first, first === range.startContainer ? range.startOffset : 0);
220 - range.setEnd(last, last === range.endContainer ? range.endOffset : last.length);
231 + // An endpoint inside a formula's glyphs takes in the whole formula.
232 + const startFormula = mathWrapperOf(first.parentElement);
233 + const endFormula = mathWrapperOf(last.parentElement);
234 + if (startFormula) range.setStartBefore(startFormula);
235 + else range.setStart(first, first === range.startContainer ? range.startOffset : 0);
236 + if (endFormula) range.setEndAfter(endFormula);
237 + else range.setEnd(last, last === range.endContainer ? range.endOffset : last.length);
238 if (!isUsableRange(source, range)) return null;
239
240 const stream = readAssistantText(source);
@@ -226,7 +243,7 @@ export function captureAssistantTextSelection(
243 for (const chunk of stream.chunks) {
244 if (!range.intersectsNode(chunk.node)) continue;
245 const start = range.startContainer === chunk.node ? range.startOffset : 0;
229 - const end = range.endContainer === chunk.node ? range.endOffset : chunk.node.length;
246 + const end = range.endContainer === chunk.node ? range.endOffset : chunk.end - chunk.start;
247 if (start === end) continue;
248 rawStart ??= chunk.start + start;
249 rawEnd = chunk.start + end;
@@ -268,7 +285,10 @@ export function resolveAssistantCitationRange(
285 if (first === undefined || last === undefined) return null;
286
287 const range = root.ownerDocument.createRange();
271 - range.setStart(first.node, Math.max(0, start - first.start));
272 - range.setEnd(last.node, Math.min(last.node.length, end - last.start));
288 + // A match that touches a formula covers the formula as rendered.
289 + if (isText(first.node)) range.setStart(first.node, Math.max(0, start - first.start));
290 + else range.setStartBefore(first.node);
291 + if (isText(last.node)) range.setEnd(last.node, Math.min(last.node.length, end - last.start));
292 + else range.setEndAfter(last.node);
293 return isUsableRange(root, range) ? range : null;
294 }
apps/web/src/markdown-clipboard.math.browser.test.ts new
+26
@@ -0,0 +1,26 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { chatMarkdownClipboardPayload } from "./markdown-clipboard";
4 +
5 +function select(start: Node, startOffset: number, end: Node, endOffset: number) {
6 + const range = document.createRange();
7 + range.setStart(start, startOffset);
8 + range.setEnd(end, endOffset);
9 + const selection = window.getSelection()!;
10 + selection.removeAllRanges();
11 + selection.addRange(range);
12 + return selection;
13 +}
14 +
15 +describe("copying rendered math", () => {
16 + it("copies a formula's TeX whether the selection spans it or starts inside it", () => {
17 + document.body.innerHTML = `<div class="chat-markdown"><p>Area <span data-markdown-math="" data-markdown-copy="$\\pi r^2$"><span class="katex"><span class="katex-mathml">πr2</span><span class="katex-html" aria-hidden="true">πr2</span></span></span> grows.</p></div>`;
18 + const paragraph = document.querySelector("p")!;
19 + const glyphs = document.querySelector(".katex-mathml")!.firstChild!;
20 +
21 + expect(
22 + chatMarkdownClipboardPayload(select(paragraph.firstChild!, 0, paragraph.lastChild!, 7))?.text,
23 + ).toBe("Area $\\pi r^2$ grows.");
24 + expect(chatMarkdownClipboardPayload(select(glyphs, 0, glyphs, 1))?.text).toBe("$\\pi r^2$");
25 + });
26 +});
apps/web/src/markdown-clipboard.ts
+38 -1
@@ -324,6 +324,24 @@ export function serializeTableElementToMarkdown(table: Element): string {
324 return serializeTable(table).trim();
325 }
326
327 +// The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops
328 +// the attribute from authored HTML.
329 +const MATH_SELECTOR = "[data-markdown-math]";
330 +
331 +export function mathWrapperOf(element: Element | null): Element | null {
332 + return element?.closest(MATH_SELECTOR) ?? null;
333 +}
334 +
335 +/** A cell's text, with each formula as its TeX. */
336 +function csvCellText(cell: Element): string {
337 + if (!cell.querySelector(MATH_SELECTOR)) return cell.textContent ?? "";
338 + const copy = cell.cloneNode(true) as Element;
339 + for (const wrapper of copy.querySelectorAll(MATH_SELECTOR)) {
340 + wrapper.replaceWith(wrapper.getAttribute("data-markdown-copy")?.trim() ?? "");
341 + }
342 + return copy.textContent ?? "";
343 +}
344 +
345 function csvCell(value: string): string {
346 const normalized = value.replace(/\s+/g, " ").trim();
347 return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
@@ -337,12 +355,24 @@ export function serializeTableElementToCsv(table: Element): string {
355 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
356 );
357 if (cells.length === 0) continue;
340 - lines.push(cells.map((cell) => csvCell(cell.textContent ?? "")).join(","));
358 + lines.push(cells.map((cell) => csvCell(csvCellText(cell))).join(","));
359 }
360 return lines.join("\n");
361 }
362
363 +function mathSourceElement(wrapper: Element): Element {
364 + const code = document.createElement("code");
365 + code.textContent = wrapper.getAttribute("data-markdown-copy")?.trim() ?? "";
366 + if (wrapper.getAttribute("data-markdown-math") !== "display") return code;
367 + const pre = document.createElement("pre");
368 + pre.append(code);
369 + return pre;
370 +}
371 +
372 function sanitizedHtmlFrom(container: Element): string {
373 + for (const wrapper of container.querySelectorAll(MATH_SELECTOR)) {
374 + wrapper.replaceWith(mathSourceElement(wrapper));
375 + }
376 for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
377 if (
378 node.classList.contains("chat-markdown-file-link") ||
@@ -371,6 +401,13 @@ export function chatMarkdownClipboardPayload(
401 const ancestor = range.commonAncestorContainer;
402 const ancestorElement =
403 ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
404 + // A range inside a formula would clone only KaTeX's glyphs, not the wrapper holding the TeX.
405 + const math = mathWrapperOf(ancestorElement);
406 + if (math) {
407 + texts.push(math.getAttribute("data-markdown-copy")?.trim() ?? "");
408 + htmls.push(`<meta charset="utf-8">${mathSourceElement(math).outerHTML}`);
409 + continue;
410 + }
411 if (ancestorElement?.closest("pre")) {
412 const text = range.toString();
413 if (text) {
docs/user/appearance.md
+12
@@ -29,6 +29,18 @@ The controls retreat as the composer docks after you send the first message.
29 Turn on **Composer context** to keep those controls visible after the thread starts. This preference
30 applies to the web and desktop clients.
31
32 +## Math
33 +
34 +Turn on **Render math** in **Settings → Appearance** to typeset LaTeX in messages and Markdown
35 +previews on web, desktop, and mobile. It reads `$…$`, `$$…$$`, `\(…\)`, and `\[…\]`, outside of code.
36 +Fenced `math` blocks also render. Formulas work in tables, including absolute-value bars.
37 +Dollar amounts such as `$5 and $10` stay text; write `\$` to keep any other dollar sign literal.
38 +Wide formulas scroll horizontally while the surrounding text wraps. Copying a formula or
39 +exporting a table preserves the TeX.
40 +
41 +The composer keeps TeX source editable, including when rich text is enabled. The Render math
42 +preference is saved separately on each device.
43 +
44 ## Motion
45
46 The main sidebar, right panel, and terminal drawer open and close immediately by default. Move the
packages/contracts/src/settings.test.ts
+9
@@ -150,6 +150,15 @@ describe("storage cleanup settings", () => {
150 });
151
152 describe("ClientSettings rich text composer", () => {
153 + it("keeps math opt-in and preserves its preference through patches and persistence", () => {
154 + expect(decodeClientSettings({}).mathRenderingEnabled).toBe(false);
155 + for (const mathRenderingEnabled of [true, false]) {
156 + const preference = { mathRenderingEnabled };
157 + expect(decodeClientSettingsPatch(preference)).toEqual(preference);
158 + expect(encodeClientSettings(decodeClientSettings(preference))).toMatchObject(preference);
159 + }
160 + expect(() => decodeClientSettingsPatch({ mathRenderingEnabled: "yes" })).toThrow();
161 + });
162 it("enables rich text for new and existing settings without a saved preference", () => {
163 expect(decodeClientSettings({}).composerRichTextEnabled).toBe(true);
164 expect(decodeClientSettings({ sendShortcut: "mod-enter" }).composerRichTextEnabled).toBe(true);
packages/contracts/src/settings.ts
+4
@@ -479,6 +479,9 @@ export const ClientSettingsSchema = Schema.Struct({
479 snapShotFlash: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
480 snapShotAnimations: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
481 wordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
482 + // Opt-in TeX typesetting in rendered Markdown. Off keeps math parsing and
483 + // KaTeX out of the render path entirely.
484 + mathRenderingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
485 });
486 export type ClientSettings = typeof ClientSettingsSchema.Type;
487
@@ -1648,5 +1651,6 @@ export const ClientSettingsPatch = Schema.Struct({
1651 snapShotFlash: Schema.optionalKey(Schema.Boolean),
1652 snapShotAnimations: Schema.optionalKey(Schema.Boolean),
1653 wordWrap: Schema.optionalKey(Schema.Boolean),
1654 + mathRenderingEnabled: Schema.optionalKey(Schema.Boolean),
1655 });
1656 export type ClientSettingsPatch = typeof ClientSettingsPatch.Type;
packages/shared/package.json
+7
@@ -490,6 +490,10 @@
490 "./PtyAdapter": {
491 "types": "./src/PtyAdapter.ts",
492 "import": "./src/PtyAdapter.ts"
493 + },
494 + "./markdownMath": {
495 + "types": "./src/markdownMath.ts",
496 + "import": "./src/markdownMath.ts"
497 }
498 },
499 "scripts": {
@@ -503,12 +507,14 @@
507 "effect": "catalog:",
508 "jose": "catalog:",
509 "mdast-util-directive": "catalog:",
510 + "mdast-util-to-hast": "^13.2.1",
511 "micromark-extension-directive": "catalog:",
512 "micromark-util-character": "catalog:",
513 "rehype-raw": "catalog:",
514 "rehype-sanitize": "catalog:",
515 "remark-breaks": "catalog:",
516 "remark-gfm": "catalog:",
517 + "remark-math": "6.0.0",
518 "remark-parse": "catalog:",
519 "remark-rehype": "catalog:",
520 "unified": "catalog:",
@@ -517,6 +523,7 @@
523 "devDependencies": {
524 "@effect/platform-node": "catalog:",
525 "@effect/vitest": "catalog:",
526 + "@types/mdast": "^4.0.4",
527 "@types/node": "catalog:",
528 "micromark-util-types": "catalog:",
529 "vite-plus": "catalog:"
packages/shared/src/composerInlineTokens.test.ts
+7
@@ -210,4 +210,11 @@ describe("collectComposerInlineTokens", () => {
210 expect(collectComposerInlineTokens(" [[".repeat(40_000))).toEqual([]);
211 expect(performance.now() - started).toBeLessThan(1_000);
212 });
213 +
214 + it("keeps skill and mention sources inside TeX out of the context chip list", () => {
215 + const source = "\\[\\text{use $browser and @README.md here}\\] then $real-skill ";
216 + expect(collectComposerInlineTokens(source).map((token) => token.source)).toEqual([
217 + "$real-skill",
218 + ]);
219 + });
220 });
packages/shared/src/composerInlineTokens.ts
+10 -1
@@ -1,3 +1,5 @@
1 +import { markdownMathRanges } from "./markdownMath.ts";
2 +
3 export type ComposerInlineToken =
4 | {
5 readonly type: "mention";
@@ -134,5 +136,12 @@ export function collectComposerInlineTokens(
136 }
137 }
138
137 - return [...matches].sort((left, right) => left.start - right.start);
139 + // TeX can contain literal skill and file tokens, especially inside \text{}.
140 + // They remain formula source rather than becoming composer context chips.
141 + const math = matches.length > 0 ? markdownMathRanges(text) : [];
142 + return matches
143 + .filter(
144 + (match) => !math.some((formula) => match.start < formula.end && match.end > formula.start),
145 + )
146 + .sort((left, right) => left.start - right.start);
147 }
packages/shared/src/markdownMath.test.ts new
+386
@@ -0,0 +1,386 @@
1 +import type { Nodes } from "mdast";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import { mathKind } from "./markdownMath.ts";
5 +import { markdownMathRanges, parseMarkdownWithMath } from "./markdownMath.ts";
6 +
7 +const parse = parseMarkdownWithMath;
8 +
9 +function collect(node: Nodes, out: Nodes[] = []): Nodes[] {
10 + out.push(node);
11 + if ("children" in node) for (const child of node.children) collect(child, out);
12 + return out;
13 +}
14 +
15 +/** Formulas as `[kind, tex]`, in document order. */
16 +function formulas(markdown: string) {
17 + return collect(parse(markdown)).flatMap((node) => {
18 + if (node.type === "math") return [["display", node.value]];
19 + if (node.type !== "inlineMath") return [];
20 + const className = node.data?.hProperties?.className;
21 + return [[mathKind(Array.isArray(className) ? className.join(" ") : undefined), node.value]];
22 + });
23 +}
24 +
25 +function text(markdown: string) {
26 + return collect(parse(markdown))
27 + .flatMap((node) => (node.type === "text" ? [node.value] : []))
28 + .join("");
29 +}
30 +
31 +describe("chat math parsing", () => {
32 + it("keeps GFM autolink destinations intact while restoring literal dollars", () => {
33 + const source = "Query www.example.com/?$select=id and $x$.";
34 + const link = collect(parse(source)).find((node) => node.type === "link");
35 + expect(link).toMatchObject({ url: "http://www.example.com/?$select=id" });
36 + expect(formulas(source)).toEqual([["inline", "x"]]);
37 + });
38 +
39 + it.each(["&#57344;", "&#xE000;", "&#xe000;"])(
40 + "preserves decoded private-use reference %s",
41 + (reference) => {
42 + const source = `${reference} [${reference}](https://example.com/?q=${reference}) $x$`;
43 + const nodes = collect(parse(source));
44 + expect(
45 + nodes
46 + .filter((node) => node.type === "text")
47 + .map((node) => node.value)
48 + .join(""),
49 + ).toBe("\uE000 \uE000 ");
50 + expect(nodes.find((node) => node.type === "link")).toMatchObject({
51 + url: "https://example.com/?q=\uE000",
52 + });
53 + expect(formulas(source)).toEqual([["inline", "x"]]);
54 + },
55 + );
56 +
57 + it.each(["\\(x\\)", "\\[x\\]", "$x$", "$$x$$"])(
58 + "preserves indented code containing %s",
59 + (formula) => {
60 + const source = ` ${formula}`;
61 + expect(collect(parse(source)).find((node) => node.type === "code")).toMatchObject({
62 + value: formula,
63 + });
64 + expect(markdownMathRanges(source)).toEqual([]);
65 + },
66 + );
67 +
68 + it("parses formulas without reserving private-use characters", () => {
69 + const characters = Array.from({ length: 6400 }, (_, index) =>
70 + String.fromCharCode(0xe000 + index),
71 + ).join("");
72 + const source = "$x$ " + characters;
73 + expect(formulas(source)).toEqual([["inline", "x"]]);
74 + expect(text(source)).toBe(" " + characters);
75 + });
76 +
77 + it("only exposes closed explicit math fences to editors and native rendering", () => {
78 + expect(markdownMathRanges("```math\nx^2")).toEqual([]);
79 + expect(markdownMathRanges("```math\nx^2\n```")[0]?.tex).toBe("x^2");
80 + expect(markdownMathRanges("> ```math\n> x^2\n> ```")[0]?.tex).toBe("x^2");
81 + });
82 + it("reads the four delimiters models emit", () => {
83 + expect(formulas("Inline $x^2$ and \\(y_1\\), display $$a+b$$ and \\[c\\].")).toEqual([
84 + ["inline", "x^2"],
85 + ["inline", "y_1"],
86 + ["display", "a+b"],
87 + ["display", "c"],
88 + ]);
89 + });
90 +
91 + it("reads display blocks on their own lines", () => {
92 + expect(formulas("$$\n\\frac{a}{b}\n$$")).toEqual([["display", "\\frac{a}{b}"]]);
93 + expect(
94 + formulas("Where\n\\[\n\\begin{aligned} a &= b \\\\ c &= d \\end{aligned}\n\\]\nholds."),
95 + ).toEqual([["display", "\\begin{aligned} a &= b \\\\ c &= d \\end{aligned}"]]);
96 + });
97 +
98 + it.each([" is the first formula.", ", followed by prose.", " \tthen more text."])(
99 + "keeps text after a same-line formula separate from later display math: %s",
100 + (trailing) => {
101 + const source = `$$a$$${trailing}\nSome prose.\n$$\nb\n$$`;
102 + const nodes = collect(parse(source));
103 + expect(
104 + nodes.filter((node) => node.type === "inlineMath" || node.type === "math"),
105 + ).toMatchObject([
106 + { type: "inlineMath", value: "a" },
107 + { type: "math", value: "b" },
108 + ]);
109 + expect(text(source)).toContain(`${trailing}\nSome prose.`);
110 + expect(markdownMathRanges(source).map((formula) => formula.source)).toEqual([
111 + "$$a$$",
112 + "$$\nb\n$$",
113 + ]);
114 + },
115 + );
116 +
117 + it("keeps block syntax inside display blocks as TeX", () => {
118 + expect(formulas("\\[\nx\n- y\n# z\n\\]\nafter")).toEqual([["display", "x\n- y\n# z"]]);
119 + expect(formulas("> $$\n> x\n> $$")).toEqual([["display", "x"]]);
120 + // Same-line content is not a fence; it stays one formula.
121 + expect(formulas("$$x^2\n+y^2$$")).toEqual([["display", "x^2\n+y^2"]]);
122 + expect(text("$$E=mc^2")).toBe("$$E=mc^2");
123 + });
124 +
125 + it("keeps prices, shell variables, and skill tokens as prose", () => {
126 + for (const prose of [
127 + "It costs $5 and $10.",
128 + "Budget $5-$10 per seat, or $20,000-$30,000 a year.",
129 + "Plans are $5/$10 monthly.",
130 + "Run $browser then $deploy on it.",
131 + "Set $HOME before running.",
132 + ]) {
133 + expect(formulas(prose), prose).toEqual([]);
134 + expect(text(prose), prose).toBe(prose);
135 + }
136 + });
137 +
138 + it("keeps prices as prose when math follows on the same line", () => {
139 + for (const price of ["$5-$10", "$5 and $10", "$5/$10", "$20,000-$30,000"]) {
140 + const source = `Price ${price} stays literal. The formula is $x_i$ and $5$.`;
141 + expect(formulas(source)).toEqual([
142 + ["inline", "x_i"],
143 + ["inline", "5"],
144 + ]);
145 + expect(text(source)).toBe(`Price ${price} stays literal. The formula is and .`);
146 + }
147 + });
148 +
149 + it("leaves code, escapes, links, and citations alone", () => {
150 + for (const [markdown, rendered] of [
151 + ["Use `$x$` in code.", "Use in code."],
152 + ["It costs $5 and $10, and `$HOME` stays code.", "It costs $5 and $10, and stays code."],
153 + ["Export $PATH, then `$HOME`.", "Export $PATH, then ."],
154 + ["\\(a `\\)` b", "(a b"],
155 + [
156 + "Set $TOKEN, then open [users](https://graph.microsoft.com/v1.0/users?$select=id).",
157 + "Set $TOKEN, then open users.",
158 + ],
159 + [
160 + "Set $TOKEN, then open <https://graph.microsoft.com/v1.0/users?$select=id>.",
161 + "Set $TOKEN, then open https://graph.microsoft.com/v1.0/users?$select=id.",
162 + ],
163 + ["```\n$x$ \\(y\\)\n```", ""],
164 + ["Escaped \\$x\\$ stays.", "Escaped $x$ stays."],
165 + ["Escaped \\\\(x\\\\) stays.", "Escaped \\(x\\) stays."],
166 + ["See [docs](https://example.com/\\(a\\)) here.", "See docs here."],
167 + ["As shown in \\[1\\] and \\[2, 3\\].", "As shown in [1] and [2, 3]."],
168 + ] as const) {
169 + expect(formulas(markdown), markdown).toEqual([]);
170 + expect(text(markdown), markdown).toBe(rendered);
171 + }
172 + });
173 +
174 + it("starts a formula right after an escaped dollar", () => {
175 + expect(formulas("Pay \\$$x$ now.")).toEqual([["inline", "x"]]);
176 + });
177 +
178 + it.each([
179 + ["$a`$HOME`", "$HOME"],
180 + ["\\(a`\\)`", "\\)"],
181 + ["\\(a\\alpha`\\)`", "\\)"],
182 + ["text \\[a`\\]`", "\\]"],
183 + ])("preserves an adjacent code span in %s", (source, code) => {
184 + expect(formulas(source)).toEqual([]);
185 + expect(collect(parse(source)).find((node) => node.type === "inlineCode")).toMatchObject({
186 + value: code,
187 + });
188 + });
189 +
190 + it.each([
191 + ["$$ $$", ""],
192 + ["$$ $$", ""],
193 + ["$$\n$\n$$", "$"],
194 + ["$$\n$$\n", ""],
195 + ])("parses display math without empty content tokens in %j", (source, tex) => {
196 + expect(formulas(source)).toEqual([["display", tex]]);
197 + });
198 +
199 + it.each([1, 2, 3, 4])("respects %i backslashes before a display fence", (count) => {
200 + const prefix = "a+" + "\\".repeat(count);
201 + for (const opening of ["$$", "$$\n"]) {
202 + const source = `${opening}${prefix}$$\nb\n$$`;
203 + expect(formulas(source)).toEqual([["display", count % 2 === 1 ? `${prefix}$$\nb` : prefix]]);
204 + expect(markdownMathRanges(source)[0]?.source).toBe(
205 + count % 2 === 1 ? source : `${opening}${prefix}$$`,
206 + );
207 + }
208 + });
209 +
210 + it("keeps TeX escapes inside formulas", () => {
211 + expect(formulas("Cost $a\\$b$ and \\(\\left(x\\right)\\).")).toEqual([
212 + ["inline", "a\\$b"],
213 + ["inline", "\\left(x\\right)"],
214 + ]);
215 + });
216 +
217 + it("keeps source offsets of the original message", () => {
218 + const markdown = "- [ ] check \\(x\\)\n- [x] then $y$";
219 + const offsets = collect(parse(markdown)).flatMap((node) =>
220 + node.type === "inlineMath" || node.type === "listItem"
221 + ? [[node.type, node.position?.start.offset]]
222 + : [],
223 + );
224 + expect(offsets).toEqual([
225 + ["listItem", 0],
226 + ["inlineMath", markdown.indexOf("\\(")],
227 + ["listItem", markdown.indexOf("- [x]")],
228 + ["inlineMath", markdown.indexOf("$y$")],
229 + ]);
230 + });
231 +
232 + it.each(["\n", "\r\n", "\r"])("keeps authored lines and UTF-16 offsets with %j", (eol) => {
233 + const source = `😀 \\(x${eol}+y\\)${eol}${eol}- [ ] check $z$`;
234 + const nodes = collect(parse(source));
235 + const formula = nodes.find(
236 + (node) => node.type === "inlineMath" && node.value === "x" + eol + "+y",
237 + );
238 + expect(formula?.position?.start).toEqual({ line: 1, column: 4, offset: 3 });
239 + expect(formula?.position?.end).toEqual({
240 + line: 2,
241 + column: 5,
242 + offset: source.indexOf(eol + eol),
243 + });
244 + expect(nodes.find((node) => node.type === "listItem")?.position?.start).toEqual({
245 + line: 4,
246 + column: 1,
247 + offset: source.indexOf("- [ ]"),
248 + });
249 + });
250 +
251 + it("shows unfinished formulas as text while a response streams", () => {
252 + const message = "Energy \\(E = mc^2\\) and $$\\sum_i x_i$$ done.";
253 + for (let end = 0; end <= message.length; end++) {
254 + expect(() => parse(message.slice(0, end))).not.toThrow();
255 + }
256 + expect(text("Energy \\(E = mc")).toBe("Energy (E = mc");
257 + expect(formulas("$$\nx^2")).toEqual([]);
258 + expect(formulas("\\[\nx^2\n- y")).toEqual([]);
259 + expect(formulas(message)).toEqual([
260 + ["inline", "E = mc^2"],
261 + ["display", "\\sum_i x_i"],
262 + ]);
263 + });
264 +});
265 +
266 +describe("math in GFM tables", () => {
267 + it("renders math in link labels while retaining dollars in their destinations", () => {
268 + const row = "| [norm $|x|$](https://example.com/$path) | y$ |";
269 + for (const source of [`${row}\n| --- | --- |`, `| First | Second |\n| --- | --- |\n${row}`]) {
270 + const tree = parse(source);
271 + const table = tree.children[0];
272 + expect(table?.type).toBe("table");
273 + if (table?.type !== "table") throw new Error("Missing table");
274 + expect(table.children.every((entry) => entry.children.length === 2)).toBe(true);
275 + expect(markdownMathRanges(source, tree).map((range) => range.tex)).toEqual(["|x|"]);
276 + expect(collect(tree).find((node) => node.type === "link")).toMatchObject({
277 + url: "https://example.com/$path",
278 + });
279 + }
280 + });
281 +
282 + it.each([
283 + "[a](https://example.com/$x)",
284 + '[a](https://example.com "title $x")',
285 + "<https://example.com/$x>",
286 + "`$x`",
287 + '<span title="$x">a</span>',
288 + ])("preserves table separators after literal dollars in %s", (literal) => {
289 + const row = `| ${literal} | y$ |`;
290 + for (const source of [`${row}\n| --- | --- |`, `| First | Second |\n| --- | --- |\n${row}`]) {
291 + const tree = parse(source);
292 + const table = tree.children[0];
293 + expect(table?.type).toBe("table");
294 + if (table?.type !== "table") throw new Error("Missing table");
295 + expect(table.children.every((entry) => entry.children.length === 2)).toBe(true);
296 + expect(markdownMathRanges(source, tree)).toEqual([]);
297 + if (literal.startsWith("[a](https://example.com/$x)")) {
298 + expect(collect(tree).find((node) => node.type === "link")).toMatchObject({
299 + url: "https://example.com/$x",
300 + });
301 + }
302 + }
303 + });
304 +
305 + it("retains multiline math after a prose pipe outside tables", () => {
306 + const source = "a | b: \\(x\n+y\\)";
307 + expect(formulas(source)).toEqual([["inline", "x\n+y"]]);
308 + expect(markdownMathRanges(source)).toEqual([
309 + expect.objectContaining({ source: "\\(x\n+y\\)", inTable: false }),
310 + ]);
311 + });
312 + it.each(["\\(", "\\["])("keeps table rows intact when %s closes in a later row", (opener) => {
313 + const closer = opener === "\\(" ? "\\)" : "\\]";
314 + const source = `| Name | Value |\n| --- | --- |\n| first | ${opener}x |\n| second | y${closer} |\n| valid | $|z|$ |`;
315 + const tree = parseMarkdownWithMath(source);
316 + const table = tree.children[0];
317 + expect(table?.type).toBe("table");
318 + if (table?.type !== "table") throw new Error("Missing table");
319 + expect(table.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2]);
320 + expect(
321 + collect(tree)
322 + .filter((node) => node.type === "text")
323 + .map((node) => node.value),
324 + ).toEqual([
325 + "Name",
326 + "Value",
327 + "first",
328 + opener.slice(1) + "x",
329 + "second",
330 + "y" + closer.slice(1),
331 + "valid",
332 + ]);
333 + expect(markdownMathRanges(source)).toEqual([
334 + expect.objectContaining({ source: "$|z|$", tex: "|z|" }),
335 + ]);
336 + expect(JSON.stringify(tree)).not.toMatch(/[\uE000-\uF8FF]/);
337 + });
338 +
339 + it("retains multiline math pipes outside tables", () => {
340 + const source = "Outside \\(x|y\n+z\\) remains math.\n\n\\[\n|a|\n+|b|\n\\]";
341 + expect(markdownMathRanges(source).map((range) => range.tex)).toEqual(["x|y\n+z", "|a|\n+|b|"]);
342 + });
343 + it.each(["\\(\\frac{1}{|x|}\\)", "$$|x|$$", "$|x|$", "\\[|x|\\]"])(
344 + "keeps pipes inside %s in one cell and preserves source offsets",
345 + (formula) => {
346 + const source = `| Name | Value |\n| --- | --- |\n| x | ${formula} |\n\n- [ ] next`;
347 + const tree = parseMarkdownWithMath(source);
348 + const table = tree.children[0];
349 + expect(table?.type).toBe("table");
350 + if (table?.type !== "table") throw new Error("Missing table");
351 + expect(table.children.map((row) => row.children.length)).toEqual([2, 2]);
352 + expect(markdownMathRanges(source)).toEqual([
353 + expect.objectContaining({ source: formula, start: source.indexOf(formula) }),
354 + ]);
355 + const checkbox = collect(tree).find((node) => node.type === "listItem");
356 + expect(checkbox?.position?.start.offset).toBe(source.indexOf("- [ ]"));
357 + },
358 + );
359 +
360 + it("preserves TeX pipe commands inside and outside tables", () => {
361 + const source = "| Formula |\n| --- |\n| \\(\\|x\\|\\) |\n\n\\(\\|x\\|\\)";
362 + expect(markdownMathRanges(source).map((formula) => formula.tex)).toEqual([
363 + "\\|x\\|",
364 + "\\|x\\|",
365 + ]);
366 + });
367 +
368 + it("leaves code, URLs, incomplete math, and private-use text unchanged", () => {
369 + const source =
370 + "| Value | Other |\n| --- | --- |\n| `\\(a\\|b\\)` | \\(x|y\\) |\n\n\uE000\n\n[link](https://example.com/$x|y$)\n\nUnclosed \\(x|y";
371 + const tree = parseMarkdownWithMath(source);
372 + expect(markdownMathRanges(source).map((formula) => formula.tex)).toEqual(["x|y"]);
373 + expect(JSON.stringify(tree)).toContain("https://example.com/$x|y$");
374 + expect(collect(tree).find((node) => node.type === "inlineCode")).toMatchObject({
375 + value: "\\(a|b\\)",
376 + });
377 + expect(JSON.stringify(tree)).toContain("\uE000");
378 + });
379 +
380 + it("keeps a display equation's equality line out of Markdown headings", () => {
381 + const source = "\\[\na\n=\nb\n\\]";
382 + expect(parseMarkdownWithMath(source).children).toEqual([
383 + expect.objectContaining({ type: "math", value: "a\n=\nb" }),
384 + ]);
385 + });
386 +});
packages/shared/src/markdownMath.ts new
+67
@@ -0,0 +1,67 @@
1 +/// <reference types="mdast-util-to-hast" />
2 +import type { Root } from "mdast";
3 +import remarkMath from "remark-math";
4 +import remarkParse from "remark-parse";
5 +import remarkGfm from "remark-gfm";
6 +import { unified } from "unified";
7 +
8 +const mathParser = unified()
9 + .use(remarkParse)
10 + .use(remarkGfm)
11 + .use(remarkMath, { singleDollarTextMath: true })
12 + .freeze();
13 +
14 +export function parseMarkdownWithMath(source: string) {
15 + return mathParser.parse(source);
16 +}
17 +
18 +/** Closed, parser-owned formulas with authored source for editors. */
19 +export function markdownMathRanges(source: string, tree?: Root) {
20 + const ranges: Array<{
21 + start: number;
22 + end: number;
23 + source: string;
24 + tex: string;
25 + display: boolean;
26 + inTable: boolean;
27 + }> = [];
28 + if (!mayContainMath(source)) return ranges;
29 + const visit = (node: Root | Root["children"][number], inTable = false) => {
30 + const table = inTable || node.type === "tableCell";
31 + if (
32 + node.type === "math" ||
33 + node.type === "inlineMath" ||
34 + (node.type === "code" && node.lang === "math")
35 + ) {
36 + const start = node.position?.start.offset;
37 + const end = node.position?.end.offset;
38 + if (start === undefined || end === undefined) return;
39 + const authored = source.slice(start, end);
40 + if (node.type === "code") {
41 + const open = /^[ \t]*(`{3,}|~{3,})/.exec(authored)?.[1];
42 + const close = /\n[ \t>]*(`{3,}|~{3,})[ \t\r]*$/.exec(authored)?.[1];
43 + if (!open || !close || open[0] !== close[0] || close.length < open.length) return;
44 + }
45 + const display = node.type !== "inlineMath" || /^(?:\$\$|\\\[)/.test(authored);
46 + ranges.push({ start, end, source: authored, tex: node.value, display, inTable: table });
47 + } else if ("children" in node) node.children.forEach((child) => visit(child, table));
48 + };
49 + visit(tree ?? parseMarkdownWithMath(source));
50 + return ranges;
51 +}
52 +
53 +/** Messages without these characters skip math parsing entirely. */
54 +function mayContainMath(text: string): boolean {
55 + return (
56 + text.includes("$") ||
57 + text.includes("\\(") ||
58 + text.includes("\\[") ||
59 + /(?:`{3,}|~{3,})[ \t]*math\b/.test(text)
60 + );
61 +}
62 +
63 +export function mathKind(className: string | undefined): "inline" | "display" | null {
64 + if (!className?.includes("language-math")) return null;
65 + if (className.includes("math-display")) return "display";
66 + return className.includes("math-inline") ? "inline" : null;
67 +}
packages/shared/src/markdownPipeline.ts
+7 -2
@@ -132,7 +132,12 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
132 attributes: {
133 ...defaultSchema.attributes,
134 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
135 - code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
135 + // Fence languages plus the two math classes the web chat's math plugin emits.
136 + code: [
137 + ["className", /^language-./, "math-inline", "math-display"],
138 + "dataCodeMeta",
139 + "dataInlineCode",
140 + ],
141 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
142 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
143 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
@@ -279,7 +284,7 @@ function keepWindowsPathEscape(this: EscapeCompileContext) {
284 * Prose paths end at whitespace: past that, nothing tells a path from a sentence, and
285 * `C:\x and \*this\*` must still read `*this*`.
286 */
282 -export function remarkKeepWindowsPaths(this: Processor) {
287 +function remarkKeepWindowsPaths(this: Processor) {
288 const data = this.data();
289 (data.fromMarkdownExtensions ??= []).push({
290 exit: {
patches/mdast-util-math@3.0.0.patch new
+14
@@ -0,0 +1,14 @@
1 +diff --git a/lib/index.js b/lib/index.js
2 +--- a/lib/index.js
3 ++++ b/lib/index.js
4 +@@ -144,6 +144,10 @@
5 + const data = this.resume()
6 + const node = this.stack[this.stack.length - 1]
7 + assert(node.type === 'inlineMath')
8 ++ const source = this.sliceSerialize(token)
9 ++ if (source.startsWith('$$') || source.startsWith('\\[')) {
10 ++ node.data.hProperties.className = ['language-math', 'math-display']
11 ++ }
12 + this.exit(token)
13 + node.value = data
14 + const children = /** @type {Array<HastElementContent>} */ (
patches/micromark-extension-gfm-table@2.1.1.patch new
+146
@@ -0,0 +1,146 @@
1 +diff --git a/dev/lib/syntax.js b/dev/lib/syntax.js
2 +--- a/dev/lib/syntax.js
3 ++++ b/dev/lib/syntax.js
4 +@@ -46,6 +46,10 @@
5 + let sizeB = 0
6 + /** @type {boolean | undefined} */
7 + let seen
8 ++ let mathEnd = 0
9 ++ let afterMath
10 ++ let literalRow = -1
11 ++ let literalRanges = []
12 +
13 + return start
14 +
15 +@@ -223,6 +227,21 @@
16 + * @type {State}
17 + */
18 + function headRowData(code) {
19 ++ const construct = (self.parser.constructs.text[code] || []).find(
20 ++ (entry) => entry.name === 'mathText' || entry.name === 'mathTexText'
21 ++ )
22 ++ if (construct && (!construct.previous || construct.previous.call(self, self.previous))) {
23 ++ afterMath = headRowData
24 ++ return effects.check({tokenize: checkMath}, mathData, ordinaryData)(code)
25 ++ }
26 ++ return ordinaryData(code)
27 ++
28 ++ function ordinaryData(code) {
29 ++ return headRowDataOrdinary(code)
30 ++ }
31 ++ }
32 ++
33 ++ function headRowDataOrdinary(code) {
34 + if (
35 + code === codes.eof ||
36 + code === codes.verticalBar ||
37 +@@ -585,6 +604,21 @@
38 + * @type {State}
39 + */
40 + function bodyRowData(code) {
41 ++ const construct = (self.parser.constructs.text[code] || []).find(
42 ++ (entry) => entry.name === 'mathText' || entry.name === 'mathTexText'
43 ++ )
44 ++ if (construct && (!construct.previous || construct.previous.call(self, self.previous))) {
45 ++ afterMath = bodyRowData
46 ++ return effects.check({tokenize: checkMath}, mathData, ordinaryData)(code)
47 ++ }
48 ++ return ordinaryData(code)
49 ++
50 ++ function ordinaryData(code) {
51 ++ return bodyRowDataOrdinary(code)
52 ++ }
53 ++ }
54 ++
55 ++ function bodyRowDataOrdinary(code) {
56 + if (
57 + code === codes.eof ||
58 + code === codes.verticalBar ||
59 +@@ -618,6 +652,75 @@
60 +
61 + return bodyRowData(code)
62 + }
63 ++ function checkMath(effects, ok, nok) {
64 ++ const context = this
65 ++ const startLine = context.now().line
66 ++ const mathStart = context.now().offset
67 ++ const row = self.events.findLast(
68 ++ (event) => event[0] === 'enter' && event[1].type === 'tableRow'
69 ++ )[1]
70 ++ return startMath
71 ++
72 ++ function startMath(code) {
73 ++ const construct = context.parser.constructs.text[code].find(
74 ++ (entry) => entry.name === 'mathText' || entry.name === 'mathTexText'
75 ++ )
76 ++ const inlineContext = Object.create(context)
77 ++ inlineContext.mathSingleLine = true
78 ++ return effects.attempt({
79 ++ partial: true,
80 ++ tokenize: (effects, ok, nok) => construct.tokenize.call(inlineContext, effects, ok, nok)
81 ++ }, done, nok)(code)
82 ++ }
83 ++
84 ++ function done(code) {
85 ++ if (context.now().line !== startLine) return nok(code)
86 ++ mathEnd = context.now().offset
87 ++ if (literalRow === row.start.offset) return acceptMath(code)
88 ++ if (code === codes.eof || markdownLineEnding(code)) return inspectRow(code)
89 ++ effects.enter(types.data)
90 ++ return rowEnd(code)
91 ++ }
92 ++
93 ++ function rowEnd(code) {
94 ++ if (code !== codes.eof && !markdownLineEnding(code)) {
95 ++ effects.consume(code)
96 ++ return rowEnd
97 ++ }
98 ++ effects.exit(types.data)
99 ++ return inspectRow(code)
100 ++ }
101 ++
102 ++ function inspectRow(code) {
103 ++ // Inline parsing owns destinations, code, autolinks and tag attributes.
104 ++ const events = context.parser.text(row.start).write([
105 ++ ...context.sliceStream({start: row.start, end: context.now()}),
106 ++ codes.eof
107 ++ ])
108 ++ literalRanges = events.flatMap(([kind, token]) =>
109 ++ kind === 'enter' &&
110 ++ (token.type === 'resource' || token.type === 'codeText' ||
111 ++ token.type === 'autolink' || token.type === 'htmlText')
112 ++ ? [[token.start.offset, token.end.offset]]
113 ++ : []
114 ++ )
115 ++ literalRow = row.start.offset
116 ++ return acceptMath(code)
117 ++ }
118 ++
119 ++ function acceptMath(code) {
120 ++ return literalRanges.some(([start, end]) => start <= mathStart && mathStart < end)
121 ++ ? nok(code)
122 ++ : ok(code)
123 ++ }
124 ++ }
125 ++
126 ++ function mathData(code) {
127 ++ if (self.now().offset >= mathEnd) return afterMath(code)
128 ++ effects.consume(code)
129 ++ return mathData
130 ++ }
131 ++
132 + }
133 +
134 + /** @type {Resolver} */
135 +diff --git a/package.json b/package.json
136 +--- a/package.json
137 ++++ b/package.json
138 +@@ -27,7 +27,7 @@
139 + },
140 + "exports": {
141 + "development": "./dev/index.js",
142 +- "default": "./index.js"
143 ++ "default": "./dev/index.js"
144 + },
145 + "files": [
146 + "dev/",
patches/micromark-extension-llm-math@3.1.0.patch new
+343
@@ -0,0 +1,343 @@
1 +diff --git a/dev/lib/math-flow.js b/dev/lib/math-flow.js
2 +--- a/dev/lib/math-flow.js
3 ++++ b/dev/lib/math-flow.js
4 +@@ -4,7 +4,7 @@
5 +
6 + import {ok as assert} from 'devlop'
7 + import {factorySpace} from 'micromark-factory-space'
8 +-import {markdownLineEnding} from 'micromark-util-character'
9 ++import {markdownLineEnding, markdownSpace} from 'micromark-util-character'
10 + import {codes, constants, types} from 'micromark-util-symbol'
11 +
12 + /** @type {Construct} */
13 +@@ -32,6 +32,9 @@
14 + ? tail[2].sliceSerialize(tail[1], true).length
15 + : 0
16 + let sizeOpen = 0
17 ++ let closed = false
18 ++ let slashes = 0
19 ++ let trailingAfterClose = false
20 +
21 + return start
22 +
23 +@@ -79,7 +82,32 @@
24 + }
25 +
26 + effects.exit('mathFlowFenceSequence')
27 +- return factorySpace(effects, metaBefore, types.whitespace)(code)
28 ++
29 ++ return factorySpace(effects, afterOpeningWhitespace, types.whitespace)(code)
30 ++ }
31 ++
32 ++ /**
33 ++ * After opening fence whitespace, check for same-line content.
34 ++ *
35 ++ * ```markdown
36 ++ * > | $$ 1 + 1 $$
37 ++ * ^
38 ++ * ```
39 ++ *
40 ++ * @type {State}
41 ++ */
42 ++ function afterOpeningWhitespace(code) {
43 ++ if (code === codes.eof || markdownLineEnding(code)) {
44 ++ return metaAfter(code)
45 ++ }
46 ++
47 ++ effects.exit('mathFlowFence')
48 ++
49 ++ if (self.interrupt) {
50 ++ return ok(code)
51 ++ }
52 ++
53 ++ return beforeContentChunk(code)
54 + }
55 +
56 + /**
57 +@@ -230,6 +258,14 @@
58 + )(code)
59 + }
60 +
61 ++ if (code === codes.dollarSign) {
62 ++ return effects.attempt(
63 ++ {tokenize: tokenizeInlineClosingFence, partial: true},
64 ++ after,
65 ++ resumeContentAfterFailedClose
66 ++ )(code)
67 ++ }
68 ++
69 + effects.enter('mathFlowValue')
70 + return contentChunk(code)
71 + }
72 +@@ -247,13 +283,74 @@
73 + * @type {State}
74 + */
75 + function contentChunk(code) {
76 ++ const escaped = slashes % 2 === 1
77 ++ slashes = code === codes.backslash ? slashes + 1 : 0
78 + if (code === codes.eof || markdownLineEnding(code)) {
79 + effects.exit('mathFlowValue')
80 + return beforeContentChunk(code)
81 + }
82 +
83 ++ if (code === codes.dollarSign && !escaped) {
84 ++ effects.exit('mathFlowValue')
85 ++ return effects.attempt(
86 ++ {tokenize: tokenizeInlineClosingFence, partial: true},
87 ++ after,
88 ++ resumeContentAfterFailedClose
89 ++ )(code)
90 ++ }
91 ++
92 + effects.consume(code)
93 + return contentChunk
94 ++ }
95 ++
96 ++ /**
97 ++ * Resume content after a failed inline closing fence attempt.
98 ++ *
99 ++ * @type {State}
100 ++ */
101 ++ function resumeContentAfterFailedClose(code) {
102 ++ if (trailingAfterClose) return nok(code)
103 ++ effects.enter('mathFlowValue')
104 ++ effects.consume(code)
105 ++ return contentChunk
106 ++ }
107 ++
108 ++ /** @type {Tokenizer} */
109 ++ function tokenizeInlineClosingFence(effects, ok, nok) {
110 ++ let size = 0
111 ++ return sequenceStart
112 ++
113 ++ function sequenceStart(code) {
114 ++ effects.enter('mathFlowFence')
115 ++ effects.enter('mathFlowFenceSequence')
116 ++ return sequenceClose(code)
117 ++ }
118 ++
119 ++ function sequenceClose(code) {
120 ++ if (code === codes.dollarSign) {
121 ++ size++
122 ++ effects.consume(code)
123 ++ return sequenceClose
124 ++ }
125 ++
126 ++ if (size < sizeOpen) {
127 ++ return nok(code)
128 ++ }
129 ++
130 ++ effects.exit('mathFlowFenceSequence')
131 ++ return factorySpace(effects, afterSequenceClose, types.whitespace)(code)
132 ++ }
133 ++
134 ++ function afterSequenceClose(code) {
135 ++ if (code === codes.eof || markdownLineEnding(code)) {
136 ++ effects.exit('mathFlowFence')
137 ++ closed = true
138 ++ return ok(code)
139 ++ }
140 ++
141 ++ trailingAfterClose = true
142 ++ return nok(code)
143 ++ }
144 + }
145 +
146 + /**
147 +@@ -269,6 +366,7 @@
148 + * @type {State}
149 + */
150 + function after(code) {
151 ++ if (!closed) return nok(code)
152 + effects.exit('mathFlow')
153 + return ok(code)
154 + }
155 +@@ -357,6 +455,7 @@
156 + function afterSequenceClose(code) {
157 + if (code === codes.eof || markdownLineEnding(code)) {
158 + effects.exit('mathFlowFence')
159 ++ closed = true
160 + return ok(code)
161 + }
162 +
163 +diff --git a/dev/lib/math-tex-flow.js b/dev/lib/math-tex-flow.js
164 +--- a/dev/lib/math-tex-flow.js
165 ++++ b/dev/lib/math-tex-flow.js
166 +@@ -26,6 +26,7 @@
167 + */
168 + function tokenizeMathFenced(effects, ok, nok) {
169 + const self = this
170 ++ let closed = false
171 + const tail = self.events[self.events.length - 1]
172 + const initialSize =
173 + tail && tail[1].type === types.linePrefix
174 +@@ -90,6 +91,7 @@
175 + * @type {State}
176 + */
177 + function metaAfter(code) {
178 ++ if (code !== codes.eof && !markdownLineEnding(code)) return nok(code)
179 + effects.exit('mathFlowFence')
180 +
181 + if (self.interrupt) {
182 +@@ -245,6 +247,7 @@
183 + * @type {State}
184 + */
185 + function after(code) {
186 ++ if (!closed) return nok(code)
187 + effects.exit('mathFlow')
188 + return ok(code)
189 + }
190 +@@ -327,6 +330,7 @@
191 + function afterSequenceClose(code) {
192 + if (code === codes.eof || markdownLineEnding(code)) {
193 + effects.exit('mathFlowFence')
194 ++ closed = true
195 + return ok(code)
196 + }
197 +
198 +diff --git a/dev/lib/math-tex-text.js b/dev/lib/math-tex-text.js
199 +--- a/dev/lib/math-tex-text.js
200 ++++ b/dev/lib/math-tex-text.js
201 +@@ -25,6 +25,7 @@
202 + let token
203 + /** @type {number} */
204 + let openSequenceCode
205 ++ let substantive = false
206 +
207 + return start
208 +
209 +@@ -83,7 +84,7 @@
210 + * @type {State}
211 + */
212 + function between(code) {
213 +- if (code === codes.eof) {
214 ++ if (code === codes.eof || code === codes.graveAccent || (self.mathSingleLine && markdownLineEnding(code))) {
215 + return nok(code)
216 + }
217 +
218 +@@ -124,6 +125,8 @@
219 + * @type {State}
220 + */
221 + function data(code) {
222 ++ if (code === codes.graveAccent) return nok(code)
223 ++ if (code !== codes.backslash && code !== codes.eof && code !== codes.space && code !== codes.comma && !markdownLineEnding(code) && !(code >= codes.digit0 && code <= codes.digit9)) substantive = true
224 + if (
225 + code === codes.eof ||
226 + code === codes.space ||
227 +@@ -155,6 +158,7 @@
228 + ? codes.rightParenthesis
229 + : codes.rightSquareBracket
230 + if (code === closeSequenceCode) {
231 ++ if (openSequenceCode === codes.leftSquareBracket && !substantive) return nok(code)
232 + effects.consume(code)
233 + effects.exit('mathTextSequence')
234 + effects.exit('mathText')
235 +diff --git a/dev/lib/math-text.js b/dev/lib/math-text.js
236 +--- a/dev/lib/math-text.js
237 ++++ b/dev/lib/math-text.js
238 +@@ -42,6 +42,13 @@
239 + let size
240 + /** @type {Token} */
241 + let token
242 ++ /** @type {boolean} */
243 ++ let openWhitespace
244 ++ /** @type {number | undefined} */
245 ++ let charBeforeClose
246 ++ let slashes = 0
247 ++ let previousData
248 ++ let beforeData
249 +
250 + return start
251 +
252 +@@ -89,6 +96,16 @@
253 + }
254 +
255 + effects.exit('mathTextSequence')
256 ++ // Reject if opening is followed by line ending
257 ++ if (markdownLineEnding(code)) {
258 ++ return nok(code)
259 ++ }
260 ++ // Track if opening sequence is followed by whitespace
261 ++ openWhitespace =
262 ++ code === codes.space ||
263 ++ code === codes.horizontalTab ||
264 ++ code === codes.comma
265 ++ if (sizeOpen === 1 && openWhitespace) return nok(code)
266 + return between(code)
267 + }
268 +
269 +@@ -103,13 +120,14 @@
270 + * @type {State}
271 + */
272 + function between(code) {
273 +- if (code === codes.eof) {
274 ++ if (code === codes.eof || code === codes.graveAccent || ((sizeOpen === 1 || self.mathSingleLine) && markdownLineEnding(code))) {
275 + return nok(code)
276 + }
277 +
278 + if (code === codes.dollarSign) {
279 + token = effects.enter('mathTextSequence')
280 + size = 0
281 ++ charBeforeClose = self.previous
282 + return sequenceClose(code)
283 + }
284 +
285 +@@ -144,6 +162,16 @@
286 + * @type {State}
287 + */
288 + function data(code) {
289 ++ if (code === codes.graveAccent) return nok(code)
290 ++ if (code === codes.dollarSign && slashes % 2 === 1) {
291 ++ slashes = 0
292 ++ effects.consume(code)
293 ++ return data
294 ++ }
295 ++ if (code === codes.slash && previousData === codes.slash && beforeData === codes.colon) return nok(code)
296 ++ beforeData = previousData
297 ++ previousData = code
298 ++ slashes = code === codes.backslash ? slashes + 1 : 0
299 + if (
300 + code === codes.eof ||
301 + code === codes.space ||
302 +@@ -179,9 +207,26 @@
303 +
304 + // Done!
305 + if (size === sizeOpen) {
306 +- effects.exit('mathTextSequence')
307 +- effects.exit('mathText')
308 +- return ok(code)
309 ++ // Reject if closing is preceded by line ending
310 ++ if (markdownLineEnding(charBeforeClose)) {
311 ++ return nok(code)
312 ++ }
313 ++ // Reject if closing is followed by a digit
314 ++ if (code !== null && code >= codes.digit0 && code <= codes.digit9) {
315 ++ return nok(code)
316 ++ }
317 ++ // Check if closing sequence has matching whitespace pattern
318 ++ const closeWhitespace =
319 ++ charBeforeClose === codes.space ||
320 ++ charBeforeClose === codes.horizontalTab ||
321 ++ charBeforeClose === codes.comma
322 ++ if (openWhitespace === closeWhitespace) {
323 ++ effects.exit('mathTextSequence')
324 ++ effects.exit('mathText')
325 ++ return ok(code)
326 ++ }
327 ++ // Whitespace mismatch: mark as data
328 ++ return nok(code)
329 + }
330 +
331 + // More or less accents: mark as data.
332 +diff --git a/package.json b/package.json
333 +--- a/package.json
334 ++++ b/package.json
335 +@@ -27,7 +27,7 @@
336 + "type": "module",
337 + "exports": {
338 + "development": "./dev/index.js",
339 +- "default": "./index.js"
340 ++ "default": "./dev/index.js"
341 + },
342 + "files": [
343 + "dev/",
pnpm-lock.yaml
+88 -22
@@ -139,6 +139,8 @@ overrides:
139 expo-sharing>@expo/config-plugins: 58.0.9
140 expo-sharing>@expo/config-types: 58.0.3
141 '@pierre/diffs>@shikijs/transformers': ^4.2.0
142 + remark-math>micromark-extension-math: npm:micromark-extension-llm-math@3.1.0
143 + micromark-extension-gfm-table: 2.1.1
144 '@tailwindcss/node': 4.3.3
145 '@tailwindcss/oxide': 4.3.3
146 '@tailwindcss/vite': 4.3.3
@@ -177,6 +179,9 @@ patchedDependencies:
179 expo-audio@58.0.9: 2c2f8c73a23d48804c8b537b8cd73c25eb331aa47d82eaa481c6766cb81e5add
180 expo-sharing@58.0.19: ad248759641ddd71b8331c09dbb3b18c8a551785f2df507533805babd3c0c124
181 expo-widgets@58.0.20: 8623cb034b720c5ef2da8012c765805a7298909bd92eaf8381f64dbde41b77dd
182 + mdast-util-math@3.0.0: afe6b2c89e1eaddfd3c90cf2723f12c9a17d513e65beff51653781486013251c
183 + micromark-extension-gfm-table@2.1.1: 9ad23a530e45d9f83cba1da8654fe16d5af8b59d5c73d5c7a7c91fd25b9be1d8
184 + micromark-extension-llm-math@3.1.0: 49ab4815c18b003f6af998dcc6c258c17a21b50b2cc87745f12d4bd8b6d591f9
185 node-pty@1.2.0-beta.15: f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651
186 react-native-gesture-handler@3.3.0: abe20e1d1c23549297cbbc818e14fe479b41455930d9663135d6b40fe359b626
187 react-native-keyboard-controller@1.22.7: f28d08f1233e3cce8b9324b4357d2b10f1ee040b8051bc87235b0fb95069b9bb
@@ -556,8 +561,8 @@ importers:
561 specifier: 0.25.1
562 version: 0.25.1(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
563 react-native-enriched-markdown:
559 - specifier: file:deps/react-native-enriched-markdown-1.2.0-t3.15.tgz
560 - version: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz(katex@0.16.47)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
564 + specifier: file:deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz
565 + version: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz(katex@0.16.47)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
566 react-native-gesture-handler:
567 specifier: ~3.3.0
568 version: 3.3.0(patch_hash=abe20e1d1c23549297cbbc818e14fe479b41455930d9663135d6b40fe359b626)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0)
@@ -944,6 +949,9 @@ importers:
949 jszip:
950 specifier: 3.10.1
951 version: 3.10.1
952 + katex:
953 + specifier: ^0.16.47
954 + version: 0.16.47
955 lucide:
956 specifier: ^0.564.0
957 version: 0.564.0
@@ -968,6 +976,9 @@ importers:
976 remark-gfm:
977 specifier: 'catalog:'
978 version: 4.0.1
979 + remark-math:
980 + specifier: 6.0.0
981 + version: 6.0.0
982 tailwind-merge:
983 specifier: ^3.4.0
984 version: 3.6.0
@@ -1560,6 +1571,9 @@ importers:
1571 mdast-util-directive:
1572 specifier: 'catalog:'
1573 version: 3.1.0
1574 + mdast-util-to-hast:
1575 + specifier: ^13.2.1
1576 + version: 13.2.1
1577 micromark-extension-directive:
1578 specifier: 'catalog:'
1579 version: 4.0.0
@@ -1578,6 +1592,9 @@ importers:
1592 remark-gfm:
1593 specifier: 'catalog:'
1594 version: 4.0.1
1595 + remark-math:
1596 + specifier: 6.0.0
1597 + version: 6.0.0
1598 remark-parse:
1599 specifier: 'catalog:'
1600 version: 11.0.0
@@ -1597,6 +1614,9 @@ importers:
1614 '@effect/vitest':
1615 specifier: 4.0.5
1616 version: 4.0.5(patch_hash=2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.1)(@vitest/ui@5.0.1)(bufferutil@4.1.0)(effect@4.0.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(msw@2.12.11(@types/node@24.12.4)(typescript@7.0.2))(terser@5.48.0)(typescript@7.0.2)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)
1617 + '@types/mdast':
1618 + specifier: ^4.0.4
1619 + version: 4.0.4
1620 '@types/node':
1621 specifier: 24.12.4
1622 version: 24.12.4
@@ -6676,9 +6696,6 @@ packages:
6696 '@types/geojson@7946.0.16':
6697 resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==}
6698
6679 - '@types/hast@3.0.4':
6680 - resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}
6681 -
6699 '@types/hast@3.0.5':
6700 resolution: {integrity: sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==}
6701
@@ -6700,6 +6717,9 @@ packages:
6717 '@types/json-schema@7.0.15':
6718 resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
6719
6720 + '@types/katex@0.16.8':
6721 + resolution: {integrity: sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg==}
6722 +
6723 '@types/keyv@3.1.4':
6724 resolution: {integrity: sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==}
6725
@@ -10094,6 +10114,9 @@ packages:
10114 mdast-util-gfm@3.1.0:
10115 resolution: {integrity: sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==}
10116
10117 + mdast-util-math@3.0.0:
10118 + resolution: {integrity: sha512-Tl9GBNeG/AhJnQM221bJR2HPvLOSnLE/T9cJI9tlc6zwQk2nPk/4f0cHkOdEixQPC/j8UtKDdITswvLAy1OZ1w==}
10119 +
10120 mdast-util-mdx-expression@2.0.1:
10121 resolution: {integrity: sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==}
10122
@@ -10235,6 +10258,9 @@ packages:
10258 micromark-extension-gfm@3.0.0:
10259 resolution: {integrity: sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==}
10260
10261 + micromark-extension-llm-math@3.1.0:
10262 + resolution: {integrity: sha512-VIYHuIEk0gpHrojEtNGaxGwdpSLtdWYlLL2vu9PM4M1ilEtak10S8F9zzbNAPBNRoWFs/bjs+J7R3yUBoIQUEA==}
10263 +
10264 micromark-factory-destination@2.0.1:
10265 resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==}
10266
@@ -11163,8 +11189,8 @@ packages:
11189 react: '*'
11190 react-native: '*'
11191
11166 - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz:
11167 - resolution: {integrity: sha512-p9o8zNoVoNwqdlG8a9Fvhj0RFUjmpE6VecwOVsO6a8Alj2HPfCDzeLBq0SFn2KdUYX32MC2fH1gJJs/HyfP5Mg==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz}
11192 + react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz:
11193 + resolution: {integrity: sha512-dFBqwCTfgVXNU1wxwwZidHdpMxGCd+8jCPunbdO8fNG0uYVr3RQZmTwX/bC5JdgzFODZ8A7heqNBoukNpPiNtA==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz}
11194 version: 1.2.0-t3.15
11195 peerDependencies:
11196 katex: '>=0.16.0'
@@ -11356,6 +11382,9 @@ packages:
11382 remark-gfm@4.0.1:
11383 resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}
11384
11385 + remark-math@6.0.0:
11386 + resolution: {integrity: sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA==}
11387 +
11388 remark-parse@11.0.0:
11389 resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}
11390
@@ -12110,6 +12139,9 @@ packages:
12139 unist-util-position@5.0.0:
12140 resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}
12141
12142 + unist-util-remove-position@5.0.0:
12143 + resolution: {integrity: sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==}
12144 +
12145 unist-util-stringify-position@4.0.0:
12146 resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}
12147
@@ -17367,10 +17399,6 @@ snapshots:
17399
17400 '@types/geojson@7946.0.16': {}
17401
17370 - '@types/hast@3.0.4':
17371 - dependencies:
17372 - '@types/unist': 3.0.3
17373 -
17402 '@types/hast@3.0.5':
17403 dependencies:
17404 '@types/unist': 3.0.3
@@ -17391,6 +17419,8 @@ snapshots:
17419
17420 '@types/json-schema@7.0.15': {}
17421
17422 + '@types/katex@0.16.8': {}
17423 +
17424 '@types/keyv@3.1.4':
17425 dependencies:
17426 '@types/node': 24.12.4
@@ -20345,7 +20375,7 @@ snapshots:
20375
20376 hast-util-to-html@9.0.5:
20377 dependencies:
20348 - '@types/hast': 3.0.4
20378 + '@types/hast': 3.0.5
20379 '@types/unist': 3.0.3
20380 ccount: 2.0.1
20381 comma-separated-tokens: 2.0.3
@@ -20360,7 +20390,7 @@ snapshots:
20390 hast-util-to-jsx-runtime@2.3.6:
20391 dependencies:
20392 '@types/estree': 1.0.9
20363 - '@types/hast': 3.0.4
20393 + '@types/hast': 3.0.5
20394 '@types/unist': 3.0.3
20395 comma-separated-tokens: 2.0.3
20396 devlop: 1.1.0
@@ -20389,7 +20419,7 @@ snapshots:
20419
20420 hast-util-whitespace@3.0.0:
20421 dependencies:
20392 - '@types/hast': 3.0.4
20422 + '@types/hast': 3.0.5
20423
20424 hastscript@9.0.1:
20425 dependencies:
@@ -21012,10 +21042,22 @@ snapshots:
21042 transitivePeerDependencies:
21043 - supports-color
21044
21045 + mdast-util-math@3.0.0(patch_hash=afe6b2c89e1eaddfd3c90cf2723f12c9a17d513e65beff51653781486013251c):
21046 + dependencies:
21047 + '@types/hast': 3.0.5
21048 + '@types/mdast': 4.0.4
21049 + devlop: 1.1.0
21050 + longest-streak: 3.1.0
21051 + mdast-util-from-markdown: 2.0.3
21052 + mdast-util-to-markdown: 2.1.2
21053 + unist-util-remove-position: 5.0.0
21054 + transitivePeerDependencies:
21055 + - supports-color
21056 +
21057 mdast-util-mdx-expression@2.0.1:
21058 dependencies:
21059 '@types/estree-jsx': 1.0.5
21018 - '@types/hast': 3.0.4
21060 + '@types/hast': 3.0.5
21061 '@types/mdast': 4.0.4
21062 devlop: 1.1.0
21063 mdast-util-from-markdown: 2.0.3
@@ -21026,7 +21068,7 @@ snapshots:
21068 mdast-util-mdx-jsx@3.2.0:
21069 dependencies:
21070 '@types/estree-jsx': 1.0.5
21029 - '@types/hast': 3.0.4
21071 + '@types/hast': 3.0.5
21072 '@types/mdast': 4.0.4
21073 '@types/unist': 3.0.3
21074 ccount: 2.0.1
@@ -21043,7 +21085,7 @@ snapshots:
21085 mdast-util-mdxjs-esm@2.0.1:
21086 dependencies:
21087 '@types/estree-jsx': 1.0.5
21046 - '@types/hast': 3.0.4
21088 + '@types/hast': 3.0.5
21089 '@types/mdast': 4.0.4
21090 devlop: 1.1.0
21091 mdast-util-from-markdown: 2.0.3
@@ -21063,7 +21105,7 @@ snapshots:
21105
21106 mdast-util-to-hast@13.2.1:
21107 dependencies:
21066 - '@types/hast': 3.0.4
21108 + '@types/hast': 3.0.5
21109 '@types/mdast': 4.0.4
21110 '@ungap/structured-clone': 1.3.1
21111 devlop: 1.1.0
@@ -21359,7 +21401,7 @@ snapshots:
21401 micromark-util-symbol: 2.0.1
21402 micromark-util-types: 2.0.2
21403
21362 - micromark-extension-gfm-table@2.1.1:
21404 + micromark-extension-gfm-table@2.1.1(patch_hash=9ad23a530e45d9f83cba1da8654fe16d5af8b59d5c73d5c7a7c91fd25b9be1d8):
21405 dependencies:
21406 devlop: 1.1.0
21407 micromark-factory-space: 2.0.1
@@ -21384,12 +21426,22 @@ snapshots:
21426 micromark-extension-gfm-autolink-literal: 2.1.0
21427 micromark-extension-gfm-footnote: 2.1.0
21428 micromark-extension-gfm-strikethrough: 2.1.0
21387 - micromark-extension-gfm-table: 2.1.1
21429 + micromark-extension-gfm-table: 2.1.1(patch_hash=9ad23a530e45d9f83cba1da8654fe16d5af8b59d5c73d5c7a7c91fd25b9be1d8)
21430 micromark-extension-gfm-tagfilter: 2.0.0
21431 micromark-extension-gfm-task-list-item: 2.1.0
21432 micromark-util-combine-extensions: 2.0.1
21433 micromark-util-types: 2.0.2
21434
21435 + micromark-extension-llm-math@3.1.0(patch_hash=49ab4815c18b003f6af998dcc6c258c17a21b50b2cc87745f12d4bd8b6d591f9):
21436 + dependencies:
21437 + '@types/katex': 0.16.8
21438 + devlop: 1.1.0
21439 + katex: 0.16.47
21440 + micromark-factory-space: 2.0.1
21441 + micromark-util-character: 2.1.1
21442 + micromark-util-symbol: 2.0.1
21443 + micromark-util-types: 2.0.2
21444 +
21445 micromark-factory-destination@2.0.1:
21446 dependencies:
21447 micromark-util-character: 2.1.1
@@ -22501,7 +22553,7 @@ snapshots:
22553
22554 react-markdown@10.1.0(@types/react@19.3.0)(react@19.3.0):
22555 dependencies:
22504 - '@types/hast': 3.0.4
22556 + '@types/hast': 3.0.5
22557 '@types/mdast': 4.0.4
22558 '@types/react': 19.3.0
22559 devlop: 1.1.0
@@ -22523,7 +22575,7 @@ snapshots:
22575 react: 19.3.0
22576 react-native: 0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6)
22577
22526 - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz(katex@0.16.47)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0):
22578 + react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz(katex@0.16.47)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6))(react@19.3.0):
22579 dependencies:
22580 react: 19.3.0
22581 react-native: 0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(utf-8-validate@6.0.6)
@@ -22787,6 +22839,15 @@ snapshots:
22839 transitivePeerDependencies:
22840 - supports-color
22841
22842 + remark-math@6.0.0:
22843 + dependencies:
22844 + '@types/mdast': 4.0.4
22845 + mdast-util-math: 3.0.0(patch_hash=afe6b2c89e1eaddfd3c90cf2723f12c9a17d513e65beff51653781486013251c)
22846 + micromark-extension-math: micromark-extension-llm-math@3.1.0(patch_hash=49ab4815c18b003f6af998dcc6c258c17a21b50b2cc87745f12d4bd8b6d591f9)
22847 + unified: 11.0.5
22848 + transitivePeerDependencies:
22849 + - supports-color
22850 +
22851 remark-parse@11.0.0:
22852 dependencies:
22853 '@types/mdast': 4.0.4
@@ -23669,6 +23730,11 @@ snapshots:
23730 dependencies:
23731 '@types/unist': 3.0.3
23732
23733 + unist-util-remove-position@5.0.0:
23734 + dependencies:
23735 + '@types/unist': 3.0.3
23736 + unist-util-visit: 5.1.0
23737 +
23738 unist-util-stringify-position@4.0.0:
23739 dependencies:
23740 '@types/unist': 3.0.3
pnpm-workspace.yaml
+7 -1
@@ -20,7 +20,7 @@ allowBuilds:
20 node-pty: true
21 # Ships N-API prebuilds; its install script only rebuilds from source.
22 objc-js: false
23 - "react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz": true
23 + "react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz": true
24 sharp: true
25 tsc-rs: true
26 utf-8-validate: false
@@ -271,6 +271,9 @@ overrides:
271 "expo-sharing>@expo/config-plugins": 58.0.9
272 "expo-sharing>@expo/config-types": 58.0.3
273 "@pierre/diffs>@shikijs/transformers": ^4.2.0
274 + # Resolve below remark-math so Vite, Metro and Node use the same tokenizer.
275 + "remark-math>micromark-extension-math": npm:micromark-extension-llm-math@3.1.0
276 + micromark-extension-gfm-table: 2.1.1
277 # Keep one copy of these native-binary packages. lightningcss ships 11 platform binaries per
278 # version, and the workspaces' tailwindcss ^4 ranges drift into two 4.3.x copies of the family.
279 "@tailwindcss/node": "catalog:"
@@ -314,6 +317,9 @@ packageExtensions:
317 vite-plus: "catalog:"
318
319 patchedDependencies:
320 + mdast-util-math@3.0.0: patches/mdast-util-math@3.0.0.patch
321 + micromark-extension-llm-math@3.1.0: patches/micromark-extension-llm-math@3.1.0.patch
322 + micromark-extension-gfm-table@2.1.1: patches/micromark-extension-gfm-table@2.1.1.patch
323 alchemy@2.0.0-beta.80: patches/alchemy@2.0.0-beta.80.patch
324 expo-audio@58.0.9: patches/expo-audio@58.0.9.patch
325 "@clerk/expo-native-components@0.2.0": patches/@clerk__expo-native-components@0.2.0.patch
scripts/build-desktop-artifact.test.ts
+1 -1
@@ -516,7 +516,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
516 const { allowBuilds = {} } = yield* readWorkspaceConfig();
517 const repoRoot = path.join(import.meta.dirname, "..");
518 for (const key of Object.keys(allowBuilds)) {
519 - const tarball = key.split("@file:")[1];
519 + const tarball = key.split("@file:")[1]?.replace(/\(patch_hash=[a-f0-9]+\)$/, "");
520 if (tarball === undefined) continue;
521 assert.isTrue(
522 yield* fs.exists(path.join(repoRoot, tarball)),
third-party-licenses.config.json
+53
@@ -159,9 +159,62 @@
159 "name": "Expo text editor implementation",
160 "noticeFile": "apps/mobile/modules/t3-composer-editor/LICENSE",
161 "sourceUrl": "https://github.com/expo/expo"
162 + },
163 + {
164 + "bundles": ["ios", "android", "mobile"],
165 + "license": "MIT",
166 + "name": "RaTeX",
167 + "version": "0.1.15",
168 + "sourceUrl": "https://github.com/erweixin/RaTeX/tree/v0.1.15",
169 + "generatedNotices": [
170 + {
171 + "licenseId": "MIT",
172 + "copyrights": ["Copyright (c) erweixin"]
173 + }
174 + ]
175 + },
176 + {
177 + "bundles": ["ios", "android", "mobile", "web", "desktop"],
178 + "license": "MIT",
179 + "name": "micromark-extension-llm-math",
180 + "version": "3.1.0",
181 + "sourceUrl": "https://github.com/ofk/micromark-extension-llm-math",
182 + "generatedNotices": [
183 + {
184 + "licenseId": "MIT",
185 + "copyrights": ["Copyright (c) 2020 Titus Wormer <tituswormer@gmail.com>"]
186 + }
187 + ]
188 + },
189 + {
190 + "bundles": ["ios", "android", "mobile", "web", "desktop"],
191 + "license": "OFL-1.1",
192 + "name": "KaTeX mathematical fonts",
193 + "sourceUrl": "https://github.com/KaTeX/KaTeX",
194 + "generatedNotices": [
195 + {
196 + "licenseId": "OFL-1.1",
197 + "copyrights": [
198 + "Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)",
199 + "Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>)"
200 + ],
201 + "preamble": [
202 + "Unmodified KaTeX_* mathematical fonts. Reserved Font Names include KaTeX_Main, KaTeX_Math, KaTeX_AMS, and KaTeX_Caligraphic."
203 + ]
204 + }
205 + ]
206 }
207 ],
208 "packageOverrides": [
209 + {
210 + "name": "remark-math",
211 + "version": "6.0.0",
212 + "sourceUrl": "https://github.com/remarkjs/remark-math/blob/main/license",
213 + "generatedNotice": {
214 + "licenseId": "MIT",
215 + "copyrights": ["Copyright (c) Junyoung Choi <fluke8259@gmail.com>"]
216 + }
217 + },
218 {
219 "name": "@react-native-async-storage/async-storage",
220 "version": "3.1.1",