Skip to content

fix: render streamed math incrementally - #2710

Closed
Michaelyklam wants to merge 2 commits into
nesquena:masterfrom
Michaelyklam:fix/issue-2699-live-katex
Closed

Michaelyklam wants to merge 2 commits into
nesquena:masterfrom
Michaelyklam:fix/issue-2699-live-katex

Conversation

@Michaelyklam

Copy link
Copy Markdown
Contributor

Thinking Path

  • Issue Improve live LaTeX rendering in chat messages #2699 reports that math-heavy streamed responses stay as raw LaTeX until the stream settles.
  • The current streaming path already uses streaming-markdown to create KaTeX placeholder nodes while tokens arrive.
  • The missing piece was a live render pass: KaTeX only ran at the terminal done event or on settled transcript rebuilds.
  • This PR keeps the existing renderer and adds a small throttled live scan scoped to the active assistant body.

What Changed

  • Added a 150ms throttled _scheduleStreamingKatex() call after each successful live smd delta write.
  • Scoped live rendering to renderKatexBlocks(assistantBody) so repeated scans only inspect the current streamed segment.
  • Clear the pending timer when the smd parser ends so the final done path cannot leave a stale scheduled render.
  • Added source-level regression coverage for the live scheduling hook, cleanup, and existing unrendered-node/container-scoped KaTeX contract.
  • Added an Unreleased changelog note.

Why It Matters

Math placeholders now get a chance to render during the live SSE turn instead of waiting for the final response settlement. This keeps math-heavy answers readable while they stream without swapping in MathJax or rewriting the markdown pipeline.

Verification

  • /home/michael/.hermes/hermes-agent/venv/bin/python -m pytest tests/test_streaming_katex_live_render.py tests/test_streaming_markdown.py tests/test_subpath_frontend_routes.py -q63 passed
  • node --check static/messages.js
  • node --check static/ui.js
  • git diff --check

UI media: not attached. This is a live-stream timing/rendering-path change; a static before/after screenshot would be misleading because the visual difference is whether KaTeX appears during token streaming rather than after the terminal done event.

Risks / Follow-ups

  • A very math-dense stream may still do more layout work than ordinary prose; the 150ms throttle limits scans to a bounded cadence and renderKatexBlocks() still ignores already-rendered nodes.
  • If streaming-markdown ever emits a closed malformed math placeholder early, the existing KaTeX fallback behavior still applies; this PR does not change the renderer's error contract.

Refs #2699

Model Used

AI-assisted change with repository inspection, targeted editing, and shell-based test verification.

@nesquena-hermes

Copy link
Copy Markdown
Collaborator

Summary

Reading the diff at static/messages.js:595,941-959,985 against origin/master, the live _scheduleStreamingKatex() hook is correctly wired into _smdWrite() after each delta and torn down in _smdEndParser(). The mechanics (single trailing 150ms timer, clear on parser end, scoped scan via assistantBody) are fine. The new tests in tests/test_streaming_katex_live_render.py assert the wiring is present.

But I don't think this PR actually renders streamed math, because the live and settled paths emit different DOM nodes.

Code reference

The new live scan calls into renderKatexBlocks(assistantBody) (static/ui.js:7229-7231 on master):

function renderKatexBlocks(container){
  const root=container||document;
  const blocks=root.querySelectorAll('.katex-block:not([data-rendered]),.katex-inline:not([data-rendered])');
  if(!blocks.length) return;
  ...
}

That selector only matches .katex-block / .katex-inline — and those classes are only produced by the settled-render pass in renderMd() (static/ui.js:194-195 and :3015-3017), which runs at 'done' time when renderMessages() rebuilds the DOM.

During the live stream, however, _smdNewParser() (static/messages.js:938) installs window.smd.default_renderer(el), and that renderer (in static/vendor/smd.min.js) creates raw custom elements for the equation tokens — case 30: t=document.createElement("equation-block") and case 31: t=document.createElement("equation-inline") — with no class attribute and no data-katex. There's no glue code that rewrites them into .katex-block / .katex-inline (a grep -rn "equation-block" static/ outside vendor/ returns nothing).

So renderKatexBlocks(assistantBody) on a partially streamed <equation-block>$E=mc^2$</equation-block> returns an empty NodeList and exits immediately on the first line of the function. No KaTeX is ever invoked during streaming.

Diagnosis

The 150ms throttle, the assistantBody scoping, and the cleanup in _smdEndParser() are all good — but they're running against a selector that can never match the live DOM. The only thing this PR will produce in practice is a series of 150ms-spaced no-op scans on the assistant body. The final KaTeX render is still happening at 'done' time via the requestAnimationFrame(() => renderKatexBlocks()) block at messages.js:1606-1610, after renderMessages() has swapped in renderMd()'s .katex-block placeholders.

To genuinely fix #2699 you need one of:

  1. Teach renderKatexBlocks() (or a streaming-specific sibling) to also pick up equation-block, equation-inline and pull the math source from textContent. Something like:

    const blocks=root.querySelectorAll(
      '.katex-block:not([data-rendered]),.katex-inline:not([data-rendered]),'+
      'equation-block:not([data-rendered]),equation-inline:not([data-rendered])'
    );

    Then in the render loop, infer displayMode from tag name when data-katex is absent.

  2. Or override add_token in _smdNewParser() so equation tokens 30/31 create <div class="katex-block" data-katex="display"> / <span class="katex-inline" data-katex="inline"> directly — mirroring renderMd()'s settled output so the existing selector keeps working.

Option 2 is cleaner because it makes the live DOM match the settled DOM, avoiding a follow-up swap when renderMessages() finalizes.

Test plan

A test that confirms wiring (the symbols are present) is what's there today. It would catch a refactor, but it doesn't catch this class of bug. Worth adding either:

  • A jsdom or headless render test that feeds streamed markdown like \\[ x+y \\]\n into the smd parser and asserts the resulting subtree contains a rendered KaTeX node (or at least a [data-rendered] placeholder).
  • Or a structural test that asserts renderKatexBlocks()'s selector intersects with the tag names smd actually creates — i.e. the selector contains equation-block / equation-inline (or _smdNewParser overrides add_token for tokens 30/31 to emit .katex-block / .katex-inline).

Happy to be wrong on this — if there's an existing transform from <equation-block> to .katex-block that I missed, please point me at it. Otherwise this PR will pass the new structural tests but not change the user-visible streaming behavior.

@Michaelyklam

Copy link
Copy Markdown
Contributor Author

Addressed the live-DOM mismatch in follow-up commit cd61072.

What changed:

  • renderKatexBlocks(container) now also scans streaming-markdown's live <equation-block> / <equation-inline> nodes, not just the settled .katex-block / .katex-inline placeholders.
  • Display mode now falls back from the live tag name when data-katex is absent, so <equation-block> renders as display math during the stream.
  • Updated the live KaTeX regression test to assert the selector intersects with the live smd equation tags.

Verification:

  • /home/michael/.hermes/hermes-agent/venv/bin/python -m pytest tests/test_streaming_katex_live_render.py tests/test_streaming_markdown.py tests/test_subpath_frontend_routes.py -q — 63 passed
  • node --check static/messages.js
  • node --check static/ui.js
  • git diff --check

GitHub Actions are queued on the new head now.

@nesquena-hermes

Copy link
Copy Markdown
Collaborator

Shipped in v0.51.107 via release/stage-400 (#2725) — squash-merged so the source branch doesn't auto-close on the keyword.

Thanks for the contribution! Your authorship is preserved via the Co-authored-by trailer on the merged commit.

pull Bot pushed a commit to TKaxv-7S/hermes-webui that referenced this pull request May 21, 2026
… (no flash when delta completes a KaTeX expression)

Co-authored-by: Michaelyklam <Michaelyklam@users.noreply.github.com>
eleboucher pushed a commit to eleboucher/homelab that referenced this pull request May 22, 2026
…➔ 0.51.107) (#621)

This PR contains the following updates:

| Package | Update | Change |
|---|---|---|
| [ghcr.io/nesquena/hermes-webui](https://github.com/nesquena/hermes-webui) | patch | `0.51.106` → `0.51.107` |

---

### Release Notes

<details>
<summary>nesquena/hermes-webui (ghcr.io/nesquena/hermes-webui)</summary>

### [`v0.51.107`](https://github.com/nesquena/hermes-webui/blob/HEAD/CHANGELOG.md#v051107--2026-05-21--Release-CE-stage-400--8-PR-batch--pinned-sessions-limit-getter-rename--uploaded-file-user-turn-dedupe--active-run-repair-guard--incremental-KaTeX-streaming--profile-default-model-on-fresh-boot--French-locale-completion--update-check-error-surfacing--release-update-apply-path)

[Compare Source](nesquena/hermes-webui@v0.51.106...v0.51.107)

##### Fixed

- **PR [#&#8203;2718](nesquena/hermes-webui#2718 by [@&#8203;eslicarrillo](https://github.com/eslicarrillo) — Follow-up to v0.51.105's [#&#8203;2700](nesquena/hermes-webui#2700): rename `_pinnedSessionsLimit()` to `_getPinnedSessionsLimit()` so the helper matches the rest of `sessions.js`'s `_get*()` naming convention for accessors. No behavior change.
- **PR [#&#8203;2723](nesquena/hermes-webui#2723 by [@&#8203;ai-ag2026](https://github.com/ai-ag2026) — Deduplicate uploaded-file user turns when the optimistic browser bubble uses plain text but the server-persisted pending turn includes the `[Attached files: ...]` suffix. Previously a turn with attachments could render twice (optimistic + persisted) in the visible transcript before reconciling.
- **PR [#&#8203;2721](nesquena/hermes-webui#2721 by [@&#8203;ai-ag2026](https://github.com/ai-ag2026) — During session repair on restart, treat sessions with a live in-flight run as active. The prior code path could prune restart-stale state for sessions that were actually mid-stream when the server bounced, dropping the resumable run. Now the active-stream check gates the prune so live runs survive a restart cleanly.
- **PR [#&#8203;2710](nesquena/hermes-webui#2710 by [@&#8203;Michaelyklam](https://github.com/Michaelyklam) — Render streamed math (KaTeX) incrementally during a stream so completed expressions render in place as their closing delimiter arrives, instead of all-at-once at the end of the turn. Eliminates the visual flash where prose-with-math sat as raw `\\[...\\]` markup until the final render pass.
- **PR [#&#8203;2709](nesquena/hermes-webui#2709 by [@&#8203;starship-s](https://github.com/starship-s) — On a fresh boot with no persisted model in localStorage, prefer the active profile's configured default model over the static HTML option. Previously a clean install / first-load could surface the placeholder model until the user manually picked a different one, even when the profile had a default configured. Behavior note: the boot path now calls `_clearPersistedModelState()` on each load when no profile default is found, so a previously-persisted user pick is wiped on refresh — this is intentional (matches the PR's "profile default wins on fresh boot" intent and is ratified by `tests/test_model_default_boot_precedence.py`).
- **PR [#&#8203;2722](nesquena/hermes-webui#2722 by [@&#8203;victorwhale](https://github.com/victorwhale) — Complete French (`fr`) locale coverage: +93 missing translation keys covering Settings, profile-ops, gateway tile, skills modal, session controls, and i18n test surfaces. Coverage 88.8% → 96.7%.
- **PR [#&#8203;2717](nesquena/hermes-webui#2717 by [@&#8203;ai-ag2026](https://github.com/ai-ag2026) — Surface update-check fetch errors in the UI instead of failing silently. The background `api/updates/check` request previously swallowed network failures, so an offline / blocked-CDN scenario showed no indication that the version banner couldn't render. Now the failure is logged and exposed to the System panel's update-status card.
- **PR [#&#8203;2719](nesquena/hermes-webui#2719 by [@&#8203;ai-ag2026](https://github.com/ai-ag2026) — Apply release-update target correctly when the user clicks "Check for updates" after a prior dismissal: clears the `sessionStorage` check-once stamp and forces banner re-evaluation. The prior path silently no-op'd because the once-per-tab guard fired before the explicit user click could re-trigger the fetch.

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4xMDEuMSIsInVwZGF0ZWRJblZlciI6IjQzLjEwMS4xIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJyZW5vdmF0ZS9jb250YWluZXIiLCJ0eXBlL3BhdGNoIl19-->

Reviewed-on: https://git.erwanleboucher.dev/eleboucher/homelab/pulls/621
SysAdminDoc pushed a commit to SysAdminDoc/hermes-webui that referenced this pull request Jun 26, 2026
… (no flash when delta completes a KaTeX expression)

Co-authored-by: Michaelyklam <Michaelyklam@users.noreply.github.com>
bernyforce pushed a commit to bernyforce/hermes-webui that referenced this pull request Jul 29, 2026
… (no flash when delta completes a KaTeX expression)

Co-authored-by: Michaelyklam <Michaelyklam@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants