Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(notebooks): handle MathJax dynamic font load failure in LaTeX blocks (#69897)

Marius Andrad063c9f85498
diff --git a/frontend/src/lib/components/UniversalFilters/constants.ts b/frontend/src/lib/components/UniversalFilters/constants.ts
new file mode 100644
index 000000000000..6af027ba955b
--- /dev/null
+++ b/frontend/src/lib/components/UniversalFilters/constants.ts
@@ -0,0 +1,15 @@
+import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
+
+// Kept in a leaf module (instead of universalFiltersLogic) so consumers that only need the default
+// group don't import the logic's heavy dependency graph — the logic circularly imports back into
+// scenes/session-recordings, which caused "Cannot access 'DEFAULT_UNIVERSAL_GROUP_FILTER' before
+// initialization" TDZ errors on hot reload.
+export const DEFAULT_UNIVERSAL_GROUP_FILTER: UniversalFiltersGroup = {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: [],
+ },
+ ],
+}
diff --git a/frontend/src/lib/components/UniversalFilters/universalFiltersLogic.ts b/frontend/src/lib/components/UniversalFilters/universalFiltersLogic.ts
index 604d8fc2eaac..e333eddc1850 100644
--- a/frontend/src/lib/components/UniversalFilters/universalFiltersLogic.ts
+++ b/frontend/src/lib/components/UniversalFilters/universalFiltersLogic.ts
@@ -36,6 +36,7 @@ import {
isQuickFilterItem,
quickFilterToPropertyFilters,
} from '../TaxonomicFilter/types'
+import { DEFAULT_UNIVERSAL_GROUP_FILTER } from './constants'
import type { universalFiltersLogicType } from './universalFiltersLogicType'
function isApplicableSavedFilter(
@@ -80,15 +81,7 @@ function isPropertyEditableTaxonomicGroupType(groupType: TaxonomicFilterGroupTyp
)
}
-export const DEFAULT_UNIVERSAL_GROUP_FILTER: UniversalFiltersGroup = {
- type: FilterLogicalOperator.And,
- values: [
- {
- type: FilterLogicalOperator.And,
- values: [],
- },
- ],
-}
+export { DEFAULT_UNIVERSAL_GROUP_FILTER }
export type UniversalFiltersLogicProps = {
rootKey: string
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeLatex.test.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeLatex.test.tsx
new file mode 100644
index 000000000000..80330d82f9f8
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeLatex.test.tsx
@@ -0,0 +1,44 @@
+import { mathjax } from '@mathjax/src/mjs/mathjax.js'
+
+import { renderLatexToNode } from './NotebookNodeLatex'
+
+// Builds the retry signal MathJax throws (via retryAfter) when a glyph needs a dynamic font file:
+// an error carrying a `retry` promise that settles once the load finishes (or fails).
+const retrySignal = (retry: Promise<unknown>): Error => Object.assign(new Error('MathJax retry'), { retry })
+
+describe('renderLatexToNode', () => {
+ afterEach(() => {
+ ;(mathjax as any).__resetConvert()
+ })
+
+ it('resolves with the rendered node when no dynamic font load is needed', async () => {
+ const node = document.createElement('span')
+ ;(mathjax as any).__setConvert(() => node)
+
+ await expect(renderLatexToNode('E = mc^2')).resolves.toBe(node)
+ })
+
+ it('retries and resolves once the dynamic font file loads', async () => {
+ const node = document.createElement('span')
+ const convert = jest
+ .fn()
+ // First call: glyph needs the 'shapes' dynamic file, so convert throws a retry signal.
+ .mockImplementationOnce(() => {
+ throw retrySignal(Promise.resolve())
+ })
+ // Second call (after the load settles): rendering succeeds.
+ .mockImplementationOnce(() => node)
+ ;(mathjax as any).__setConvert(convert)
+
+ await expect(renderLatexToNode('\\bigstar')).resolves.toBe(node)
+ expect(convert).toHaveBeenCalledTimes(2)
+ })
+
+ it('rejects when a dynamic font file fails to load', async () => {
+ ;(mathjax as any).__setConvert(() => {
+ throw retrySignal(Promise.reject(new Error("dynamic file 'shapes' failed to load")))
+ })
+
+ await expect(renderLatexToNode('\\bigstar')).rejects.toThrow("dynamic file 'shapes' failed to load")
+ })
+})
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeLatex.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeLatex.tsx
index 6d8833ab831d..b5746d4e4db8 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeLatex.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeLatex.tsx
@@ -22,6 +22,14 @@ const tex = new TeX({
const svg = new SVG({ fontCache: 'none' })
const mjxDocument = mathjax.document(document, { InputJax: tex, OutputJax: svg })
+// Renders LaTeX to an SVG node. MathJax v4's modern SVG font loads glyph data lazily from "dynamic
+// files" (e.g. 'shapes', 'arrows'); convert() defers those loads through the retry mechanism, so we
+// run it inside handleRetriesFor() to await them. The returned promise rejects if a dynamic file
+// fails to load, which is async and a synchronous try/catch would miss, so callers must catch it.
+export function renderLatexToNode(content: string): Promise<Node> {
+ return mathjax.handleRetriesFor(() => mjxDocument.convert(content, { display: true }))
+}
+
interface NotebookNodeLatexAttributes extends CustomNotebookNodeAttributes {
content: string
editing: boolean
@@ -52,19 +60,35 @@ const LatexComponent = ({
useEffect(() => {
const mathJaxDisplayDiv = containerRef.current // The div for displaying rendered MathJax
- if (mathJaxDisplayDiv) {
- if (!editing && content) {
- try {
- mathJaxDisplayDiv.innerHTML = '' // Clear before rendering
- const math = mjxDocument.convert(content, { display: true })
+ if (!mathJaxDisplayDiv) {
+ return
+ }
+
+ if (editing || !content) {
+ mathJaxDisplayDiv.innerHTML = ''
+ return
+ }
+
+ // A failed dynamic font load rejects asynchronously, so we catch it and fall back to a
+ // friendly message rather than letting it surface as an unhandled error. See renderLatexToNode.
+ let cancelled = false
+ mathJaxDisplayDiv.innerHTML = '' // Clear before rendering
+ renderLatexToNode(content)
+ .then((math: Node) => {
+ if (!cancelled) {
+ mathJaxDisplayDiv.innerHTML = ''
mathJaxDisplayDiv.appendChild(math)
- } catch (err) {
+ }
+ })
+ .catch((err: unknown) => {
+ if (!cancelled) {
mathJaxDisplayDiv.innerHTML = '<span style="color:red">LaTeX error</span>'
console.error('MathJax error:', err)
}
- } else {
- mathJaxDisplayDiv.innerHTML = ''
- }
+ })
+
+ return () => {
+ cancelled = true
}
}, [content, editing])
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
index c12d5cc11654..40907ae11eb1 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
@@ -9,7 +9,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'
-import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/universalFiltersLogic'
+import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/constants'
import {
isActionFilter,
isEventFilter,
diff --git a/frontend/src/test/mocks/mathjaxMock.js b/frontend/src/test/mocks/mathjaxMock.js
index ad1ea32868cd..27f56a55e4e1 100644
--- a/frontend/src/test/mocks/mathjaxMock.js
+++ b/frontend/src/test/mocks/mathjaxMock.js
@@ -1,7 +1,40 @@
+// Test double for @mathjax/src. handleRetriesFor mirrors the real Retries.js loop so tests can
+// exercise MathJax's dynamic-font retry flow: convert() may throw a retry signal (an error carrying
+// a `retry` promise), and once that promise settles the code is re-run (or the whole thing rejects).
+let convertImpl = () => document.createElement('span')
+
+function handleRetriesFor(code) {
+ return new Promise(function run(resolve, reject) {
+ const handleRetry = (err) => {
+ if (err && err.retry instanceof Promise) {
+ err.retry.then(() => run(resolve, reject)).catch(reject)
+ } else {
+ reject(err)
+ }
+ }
+ try {
+ const result = code()
+ if (result instanceof Promise) {
+ result.then(resolve).catch(handleRetry)
+ } else {
+ resolve(result)
+ }
+ } catch (err) {
+ handleRetry(err)
+ }
+ })
+}
+
module.exports = {
browserAdaptor: () => ({}),
RegisterHTMLHandler: () => {},
TeX: class {},
SVG: class {},
- mathjax: { document: () => ({ convert: () => document.createElement('span') }) },
+ mathjax: {
+ document: () => ({ convert: (...args) => convertImpl(...args) }),
+ handleRetriesFor,
+ // Test seam: let a test drive what convert() does (e.g. throw a retry signal, then succeed).
+ __setConvert: (fn) => (convertImpl = fn),
+ __resetConvert: () => (convertImpl = () => document.createElement('span')),
+ },
}