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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/mobile-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,15 @@
"@openbitfun/ui": "workspace:^",
"@xterm/addon-fit": "0.12.0-beta.141",
"@xterm/xterm": "6.1.0-beta.141",
"katex": "^0.16.25",
"lucide-react": "^0.560.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-markdown": "^10.1.0",
"react-syntax-highlighter": "^15.6.6",
"rehype-katex": "^7.0.1",
"remark-gfm": "^4.0.1",
"remark-math": "^6.0.0",
"socket.io-client": "4.8.3",
"zustand": "^5.0.10"
},
Expand Down
77 changes: 58 additions & 19 deletions src/mobile-web/src/components/ChatMarkdown.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Check as LucideCheck, Copy as LucideCopy, FileText as LucideFileText } from 'lucide-react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import ReactMarkdown from 'react-markdown';
import type { Components, UrlTransform } from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { PrismLight as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus, vs } from 'react-syntax-highlighter/dist/esm/styles/prism';
Expand Down Expand Up @@ -30,6 +31,8 @@ import yaml from 'react-syntax-highlighter/dist/esm/languages/prism/yaml';
import { MobileButton, MobileIconButton, MobileLink } from '@openbitfun/ui/mobile';
import { useI18n } from '../i18n';
import { useTheme } from '../theme';
import { mayContainMarkdownMath, normalizeMathDelimiters } from './chatMarkdownMath';
import type { MarkdownMathContentProps } from './MarkdownMathContent';
import { RemoteArtifactImage } from './RemoteArtifactImage';

const SYNTAX_LANGUAGES = { bash, c, cpp, csharp, css, diff, go, java, javascript, json, jsx, kotlin, markdown, markup, php, python, ruby, rust, sql, swift, tsx, typescript, yaml };
Expand Down Expand Up @@ -359,6 +362,7 @@ const FileCard: React.FC<FileCardProps> = ({ path, onGetFileInfo, onDownload })
</MobileButton>
);
};

interface MarkdownContentProps {
content: string;
onFileDownload?: (path: string, onProgress?: (downloaded: number, total: number) => void) => Promise<void>;
Expand All @@ -368,12 +372,37 @@ interface MarkdownContentProps {
export const MarkdownContent: React.FC<MarkdownContentProps> = ({ content, onFileDownload, onGetFileInfo }) => {
const { isDark } = useTheme();
const syntaxTheme = isDark ? vscDarkPlus : vs;
const hasMath = useMemo(() => mayContainMarkdownMath(content), [content]);
const normalizedContent = useMemo(
() => (hasMath ? normalizeMathDelimiters(content) : content),
[content, hasMath],
);
const [MathRenderer, setMathRenderer] = useState<React.ComponentType<MarkdownMathContentProps> | null>(null);

// KaTeX is only downloaded for chats that actually contain math. If the
// optional chunk cannot load, keep the base renderer instead of breaking the
// transcript.
useEffect(() => {
if (!hasMath || MathRenderer) return;
let cancelled = false;
import('./MarkdownMathContent')
.then((module) => {
if (!cancelled) setMathRenderer(() => module.MarkdownMathContent);
})
.catch((error) => {
console.error('[ChatMarkdown] math renderer failed to load', error);
});
return () => {
cancelled = true;
};
}, [hasMath, MathRenderer]);

const fileReferences = useMemo(
() => onFileDownload && onGetFileInfo ? projectFileReferences(content) : [],
[content, onFileDownload, onGetFileInfo],
);

const components: React.ComponentProps<typeof ReactMarkdown>['components'] = useMemo(() => ({
const components: Components = useMemo(() => ({
code({ className, children, ...props }: any) {
const match = /language-(\w+)/.exec(className || '');
const codeStr = String(children).replace(/\n$/, '');
Expand Down Expand Up @@ -477,26 +506,36 @@ export const MarkdownContent: React.FC<MarkdownContentProps> = ({ content, onFil
},
}), [syntaxTheme, isDark, onFileDownload, onGetFileInfo]);

const markdownUrlTransform = useCallback<UrlTransform>((url, key) => {
if (key === 'src' && /^data:image\/(?:png|jpeg|gif|webp|bmp|svg\+xml|avif);base64,/i.test(url)) return url;
if (/^[A-Za-z]:[\\/]/.test(url)) return url;
if (url.startsWith('computer://') || /^openbitfun:\/\/(?:runtime|current-session)\//.test(url)) return url;
if (/^(https?|mailto|tel|file):/i.test(url) || url.startsWith('#') || url.startsWith('/')) {
return url;
}
// Preserve relative paths without a protocol (e.g. "report.pptx",
// "./output.pdf"). Unknown schemes remain blocked.
if (!url.includes(':')) return url;
return '';
}, []);

return (
<>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={components}
urlTransform={(url, key) => {
if (key === 'src' && /^data:image\/(?:png|jpeg|gif|webp|bmp|svg\+xml|avif);base64,/i.test(url)) return url;
if (/^[A-Za-z]:[\\/]/.test(url)) return url;
if (url.startsWith('computer://') || /^openbitfun:\/\/(?:runtime|current-session)\//.test(url)) return url;
if (/^(https?|mailto|tel|file):/i.test(url) || url.startsWith('#') || url.startsWith('/')) {
return url;
}
// Preserve relative paths without a protocol (e.g. "report.pptx",
// "./output.pdf"). Unknown schemes remain blocked.
if (!url.includes(':')) return url;
return '';
}}
>
{content}
</ReactMarkdown>
{hasMath && MathRenderer ? (
<MathRenderer
components={components}
content={normalizedContent}
urlTransform={markdownUrlTransform}
/>
) : (
<ReactMarkdown
components={components}
remarkPlugins={[remarkGfm]}
urlTransform={markdownUrlTransform}
>
{content}
</ReactMarkdown>
)}
{fileReferences.length > 0 && onGetFileInfo && onFileDownload && (
<div className="message-file-cards">
{fileReferences.map((reference) => (
Expand Down
34 changes: 34 additions & 0 deletions src/mobile-web/src/components/MarkdownMathContent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React from 'react';
import ReactMarkdown from 'react-markdown';
import type { Components, UrlTransform } from 'react-markdown';
import rehypeKatex from 'rehype-katex';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import 'katex/dist/katex.min.css';

export interface MarkdownMathContentProps {
content: string;
components: Components;
urlTransform: UrlTransform;
}

/**
* KaTeX-enabled Markdown renderer. It is imported lazily so chats without math
* do not download the KaTeX runtime; the base renderer stays in ChatMarkdown.
*/
export const MarkdownMathContent: React.FC<MarkdownMathContentProps> = ({
content,
components,
urlTransform,
}) => (
<ReactMarkdown
components={components}
rehypePlugins={[[rehypeKatex, { strict: false, throwOnError: false }]]}
remarkPlugins={[remarkGfm, [remarkMath, { singleDollarTextMath: false }]]}
urlTransform={urlTransform}
>
{content}
</ReactMarkdown>
);

export default MarkdownMathContent;
202 changes: 202 additions & 0 deletions src/mobile-web/src/components/chatMarkdownMath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
/**
* Mobile chat math activation and delimiter normalization.
*
* Math is rendered from a lazily loaded module, so this detection decides
* whether the browser downloads KaTeX at all. Keep the single-dollar boundary
* checks aligned with desktop MarkdownRenderer.mayContainMarkdownMath: a
* closing dollar directly followed by a digit is ordinary currency text
* (`$5 and $10`), not math.
*/
export function mayContainMarkdownMath(content: string): boolean {
if (!content) return false;
if (content.includes('$$') || content.includes('\\(') || content.includes('\\[')) {
return true;
}
return /(^|[^\\$])\$[^$\n]{1,240}\$(?!\d)/.test(content);
}

const CODE_FENCE =
/(^|\n)((?:[ \t]*>[ \t]?)*[ \t]*)(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:\n(?:(?:[ \t]*>[ \t]?)*[ \t]*)\3[^\n]*(?=\n|$)|$)/g;
const INLINE_CODE = /(`+)((?:[^\n`]|(?!\1)`)*?)\1/g;
const PROPER_DISPLAY_MATH = /(^|\n)([ \t]{0,3}\$\$[^\n]*\n[\s\S]*?\n[ \t]{0,3}\$\$[^\n]*)(?=\n|$)/g;
const SINGLE_LINE_DISPLAY_MATH = /(^|[^\\])\$\$([^\n]+?)\$\$/g;
const BRACKET_DISPLAY_MATH = /(^|[^\\])\\\[([\s\S]*?)\\\]/g;
const BRACKET_INLINE_MATH = /(^|[^\\])\\\(([\s\S]*?)\\\)/g;

type Span = { key: string; content: string };

function placeholder(spans: Span[], kind: string, content: string): string {
const key = `@@MATH_${kind}_${spans.length}@@`;
spans.push({ key, content });
return key;
}

/** True when the delimiter owns a top-level line; indented/container math stays inline. */
function startsLine(text: string, index: number): boolean {
const before = text.slice(0, index);
return before === '' || before.endsWith('\n');
}

/**
* A bare identifier of one or two characters is commonly a formula (`$x$`,
* `$n$th`). Longer shell-style names, brace expansions, and text containing
* whitespace without operators stay literal.
*/
function looksLikeInlineMath(raw: string): boolean {
const value = raw.trim();
if (!value) return false;
if (/^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(value)) return false;
if (/[\\^_=+*/<>|{}()[\]]/.test(value)) return true;
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) return value.length <= 2;
if (/\s/.test(value)) return false;
return /^[A-Za-z0-9.,'+-]+$/.test(value);
}

/**
* `remark-math` is configured with `singleDollarTextMath: false`, so a lone
* `$` always stays literal. Recognized inline formulas are widened to
* `$$...$$`, which `remark-math` treats as inline math, and every other dollar
* pair (currency, shell variables, paths) is left alone.
*/
function convertInlineDollarMath(text: string, spans: Span[]): string {
let output = '';
let index = 0;
while (index < text.length) {
const character = text[index];
if (character === '\\') {
output += text.slice(index, index + 2);
index += 2;
continue;
}
if (character !== '$') {
output += character;
index += 1;
continue;
}
// Proper `$$` fences are already placeholders; keep any stray pair intact
// rather than pairing it with a later single dollar.
if (text[index + 1] === '$') {
output += '$$';
index += 2;
continue;
}
// `${VAR}` is a shell expansion, not a math delimiter.
if (text[index + 1] === '{') {
output += '$';
index += 1;
continue;
}
let cursor = index + 1;
let closing = -1;
while (cursor < text.length) {
const next = text[cursor];
if (next === '\n') break;
if (next === '\\') {
cursor += 2;
continue;
}
if (next === '$') {
closing = cursor;
break;
}
cursor += 1;
}
if (closing > index + 1) {
const content = text.slice(index + 1, closing);
if (looksLikeInlineMath(content)) {
output += placeholder(spans, 'INLINE', `$$${content.trim()}$$`);
index = closing + 1;
continue;
}
}
output += '$';
index += 1;
}
return output;
}

/**
* Convert the LaTeX delimiter styles that common models emit into the
* `$$...$$` forms remark-math parses. Code fences and inline code are replaced
* with placeholders first, so literal `\[`/`$$` examples survive.
*
* Display delimiters only become a block when they own their line. Inside a
* list item, table row, or blockquote they stay inline so the surrounding
* container is not torn apart.
*/
export function normalizeMathDelimiters(content: string): string {
if (!content) return content;
const hasDisplayBracket = content.includes('\\[');
const hasInlineBracket = content.includes('\\(');
const hasDollar = content.includes('$');
if (!hasDisplayBracket && !hasInlineBracket && !hasDollar) {
return content;
}

const spans: Span[] = [];

// Protect code fences (including blockquoted and list-indented fences).
let transformed = content.replace(CODE_FENCE, (match) =>
placeholder(spans, 'CODE_BLOCK', match),
);

// Protect inline code spans.
transformed = transformed.replace(INLINE_CODE, (match) =>
placeholder(spans, 'CODE_INLINE', match),
);

// Leave well-formed block math untouched; it already has the shape
// remark-math expects, and its body must not be scanned for `$`.
transformed = transformed.replace(PROPER_DISPLAY_MATH, (match) =>
placeholder(spans, 'DISPLAY', match),
);

// remark-math only treats `$$` as a display fence when it owns its line.
// A single-line `$$...$$` is a display fence at line start and inline math
// everywhere else.
transformed = transformed.replace(
SINGLE_LINE_DISPLAY_MATH,
(match, prefix: string, math: string, offset: number) => {
const display = startsLine(transformed, offset + prefix.length);
const rendered = display
? `\n\n$$\n${math.trim()}\n$$\n\n`
: `$$${math.trim()}$$`;
return prefix + placeholder(spans, display ? 'BLOCK' : 'INLINE', rendered);
},
);

// \[ ... \] is display math when it owns its line, inline math otherwise.
transformed = transformed.replace(
BRACKET_DISPLAY_MATH,
(match, prefix: string, math: string, offset: number) => {
const delimiterIndex = offset + prefix.length;
// `C:\[dir\]\file` is a Windows path, not display math.
if (prefix === ':' && /[A-Za-z]/.test(transformed[delimiterIndex - 2] ?? '')) {
return match;
}
const display = startsLine(transformed, delimiterIndex);
const rendered = display
? `\n\n$$\n${math.trim()}\n$$\n\n`
: `$$${math.trim()}$$`;
return prefix + placeholder(spans, display ? 'BLOCK' : 'INLINE', rendered);
},
);

// \( ... \) is inline math.
transformed = transformed.replace(BRACKET_INLINE_MATH, (match, prefix: string, math: string) =>
prefix + placeholder(spans, 'INLINE', `$$${math.trim()}$$`),
);

// Remaining single-dollar pairs are only math when they clearly are.
transformed = convertInlineDollarMath(transformed, spans);

// Restore protected content. Math spans are restored before code spans so a
// code placeholder inside a formula still resolves; reverse order also keeps
// nested placeholders stable.
for (let index = spans.length - 1; index >= 0; index -= 1) {
const { key, content: value } = spans[index];
transformed = transformed.replace(key, () => value);
}

return transformed;
}
Loading
Loading