Skip to content

fix(frontend): render data-URI images in chat markdown - #10269

Merged
Etherll merged 3 commits into
unslothai:mainfrom
CelesteHeartsong:fix/markdown-data-images
Sep 4, 2026
Merged

Etherll merged 3 commits into
unslothai:mainfrom
CelesteHeartsong:fix/markdown-data-images

Conversation

@CelesteHeartsong

Copy link
Copy Markdown
Contributor

TL;DR

Base64 images in assistant messages rendered as [Image blocked: ...]. Streamdown strips data: image sources during sanitize, before the harden stage that actually allows them. One derived pipeline restores them without changing anything else about how chat markdown is sanitized.

Problem

Assistant messages containing inline base64 images (![alt](data:image/png;base64,...)) rendered as [Image blocked: ...] instead of the image.

Root cause

Streamdown sanitizes before hardening, and sanitize wins:

// hast-util-sanitize/lib/schema.js  (installed 2.5.0)
protocols.src: ["http", "https"]        // no "data" -> src is dropped HERE

harden does allow data images (allowDataImages: true) — but it runs second, so by the time it decides, the src attribute is already gone. The flag is effectively dead for data URIs as shipped.

Why we can't just pass a pipeline and forget about it: Streamdown folds caller allowedTags into its schema only while it still holds its own default pipeline (an identity check):

// streamdown/dist/chunk-BO2N2NFS.js  (de-minified)
gn = Object.values(xt)                    // the default pipeline
if (allowedTags && Object.keys(allowedTags).length > 0 && rehypePlugins === gn) {
  const K = { ...Ze, tagNames: [...Ze.tagNames ?? [], ...Object.keys(allowedTags)],
              attributes: { ...Ze.attributes, ...allowedTags } };
  pipeline = [xt.raw, [sanitize, K], xt.harden];   // merge happens ONLY here
}

So a caller-supplied pipeline silently opts out of the allowedTags merge unless it carries that merge itself.

Fix

Pass an explicit pipeline derived from Streamdown's exported defaults, adding "data" to image source protocols:

  • Derived, not hand-rolled, so the default-pipeline merge above is carried unchanged.
  • Destructuring the exported schema (not bare defaultSchema) also preserves Streamdown's own widenings, which a hand-rolled schema would silently drop: protocols.href += ["tel"], attributes.code += ["metastring"]. Both are now pinned by tests.
  • Positional destructuring of Object.values is deliberate: upstream builds its default pipeline from Object.values of that same object, so the same order reproduces upstream exactly, instead of pinning ours against theirs.
  • Harden still gates the scheme itself (allowDataImages + data:image/* only), so widening src does not widen what may be embedded.

What else touches this path (checked, unchanged)

Site Props Effect
assistant-ui/markdown-text.tsx allowedTags + new rehypePlugins the fix
hub/catalog/model-readme.tsx:536 allowedTags, no rehypePlugins identity still holds internally; merge still fires
markdown/markdown-preview.tsx:96 neither untouched

Nothing downstream is lost either: the literalTagContent append and the math/mermaid plugin appends both run after the identity branch unconditionally, and withoutStreamdownAnimationPlugin filters by function identity, so it is order-agnostic.

Verification

  • Facts above read out of the installed [email protected] chunk and hast-util-sanitize/lib/schema.js, not inferred.
  • SSR probe through real <Streamdown mode="static">: default pipeline renders the blocked pill and keeps no src; this pipeline emits <img ... src="data:image/png;base64,...">; a custom allowed tag survives via the carried merge; non-image data:text/html stays blocked.
  • npm run typecheck -> 0 errors. Suite -> 6824 pass / 0 fail.

Tests

tests/markdown-data-images.test.ts — data + http(s) survive sanitize, harden entry unchanged, caller allowedTags survive the pipeline swap, and Streamdown's own widenings (tel, metastring) survive derivation. tests/math-block-containment-wiring.test.ts guard retargeted from "no rehypePlugins prop" to "the passed pipeline carries the merge".

Follow-up (not blocking)

Upstream, this is one line: "data" in Streamdown's own protocols.src. If that lands, this shim and the pipeline swap both become deletable. Unrelated note found nearby: safeMarkdownUrl returns null for any scheme'd <img> URL including https:, so remote images lose src too — byte-identical before/after this PR, i.e. pre-existing and out of scope here.

Streamdown sanitizes before hardening, and its default sanitize schema lists only http(s)
under protocols.src. A data:image/... src is therefore stripped before the harden stage
(which itself sets allowDataImages: true), so assistant messages with base64 images rendered
as "[Image blocked: ...]". Pass an explicit rehypePlugins pipeline derived from Streamdown's
exported defaults, extended with 'data' on image source protocols; derive it rather than
hand-roll one so the default-pipeline merge (tagNames/attributes for allowedTags) is carried
unchanged. Tests included.
@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

CI red is pre-existing at the base commit, not from this diff

Repo tests (CPU) fails 4 / 15829 passed — all four in tests/studio/test_update_release_notes.py, none touching markdown or sanitization. This branch touches 5 files (markdown-data-images.ts, markdown-text.tsx, math-block-marker.ts + two .test.ts); it doesn't touch the banner components or that test file, and both sides of the mismatch were last written by #10229 — this PR's parent commit. main is at that same commit, so these fail on main too; a rebase can't clear them.

The literals are stale, not the layout. The pixel values match exactly; what changed in #10229 is that they moved behind a has-[[data-slot=…]]: variant prefix (and grow was added), so whole-class-string substring assertions stopped matching:

test asserts component now has
flex max-h-[calc(100dvh_-_2rem)] min-h-0 flex-col overflow-hidden …min-h-0 **grow** flex-col overflow-hidden
_NARROW_FLOOR_WEB = "max-[383px]:min-h-[calc(139px+96px*var(--ui-font-scale,1))]" max-[383px]:has-[[data-slot=update-release-notes]]:min-h-[calc(139px+96px*…)]

Same digits, extra variant segment between the breakpoint and min-h-[…]. _SCALED_FLOOR_WEB survived only because its variant prefix sits outside the asserted substring.

Covered by #10267 (match on classes, not file substrings) — that PR is test-only, so this one needs no change. Running those four tests against this branch's tree with #10267's test file: 4 passed. Noting it only so the red check isn't read as a regression here; happy to rebase once it lands.

This PR's own gates: npm run typecheck 0 errors, node suite 6824/6824, both green in CI (Frontend unit tests (Windows), Frontend build + bundle sanity).

@Etherll Etherll self-assigned this Sep 4, 2026
@Etherll

Etherll commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

@codex review

1 similar comment
@Etherll

Etherll commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-04T15:07:43.490913Z 5be5666 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 202bc9c572

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Etherll

Etherll commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

UI evidence — data-URI images in assistant Markdown

Compared merge base 8e26d2c2bacfddff53bf3e353213bc898f8c86e4 with exact PR head 202bc9c572cfa362763076f96f58516fd687cf6f using the same deterministic stored assistant message on both isolated Studio installs.

Fact Before After
Rendered image elements 0 1
Blocked-image placeholders 1 0
Embedded PNG size — 320×180 natural and rendered

PR #10269 UI evidence: BEFORE shows an Image blocked placeholder; AFTER renders the orange and charcoal embedded PNG

Chromium 131, 1500×900 viewport. The labelled composite was visually inspected and contains only the synthetic fixture.

@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

Unintended, but additionally, the assistant can now include anything with an image/* type:

{C6A071FE-73D8-43A8-843B-5ED25E2380ED}

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the chat renderer in studio/frontend/src/components/assistant-ui/markdown-text.tsx still passes no derived pipeline, so inline base64 images are dropped at sanitize before harden can allow them, and the derived pipeline keeps the allowedTags merge. Will get this reviewed.

@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

Followup I have planned once this is confirmed/merged. Current PR gets us to where data:image/* can be rendered in the assistant chat, this will add to where the assistant can post images from disk:

CelesteHeartsong#1 (feat(chat): render on-disk sandbox images in chat markdown)

Want to let this settle first and have Codex review the additional changes once ready.

CelesteHeartsong added a commit to CelesteHeartsong/unsloth that referenced this pull request Sep 4, 2026
A model that writes `![plot](/api/inference/sandbox/<sid>/plot.png)` got "[Image blocked]"
before, and "Image not available" after unslothai#10269: the src carries no scheme, so sanitize keeps it
and safeMarkdownUrl returns it unchanged -- but the route answers on the Authorization header
(_authenticate_header_or_query), so a bare <img src> hits it unauthenticated and 401s. Only
tool cards did the authed fetch (tool-ui-python.tsx), so markdown was the one path left.

Resolve the src through sandboxFilePath(sandboxSessionIdFor(threadId, projectId)) and fetch it
into an object URL before it reaches the DOM: the session segment the model happened to write is
discarded and rebuilt from this chat's scope, so a project thread reads the project's workspace.
One hook, useSandboxImage, now does that for markdown AND for the Python card, which had its own
copy; abort + revokeObjectURL on cleanup in both.

Registering `img` replaces Streamdown's default renderer wholesale (its Components map is keyed by
tag), so everything that renderer did for a data: image is restated: wrapper, hidden-when-failed,
fallback text, hover download. The two features are load-bearing on each other rather than merely
compatible: unslothai#10269's early return for `data:`/`blob:` is exactly why the rewritten src survives the
way back out, and it returns those unchanged, so scheme-carrying sources never reach this path.

.avif joins _SANDBOX_MEDIA_TYPES (a raster codec, and nosniff pins the type either way); .svg stays
out on purpose -- the filename is model-chosen, so inline SVG would be same-origin script execution,
and a non-image extension stays the download card the file list already renders. Tests included.
Review feedback on unslothai#10269 (alkinun / @codex, 2026-09-04): line 22's cast carried three
explicit `any`s, which are the only `@typescript-eslint/no-explicit-any` hits this PR
introduces. `defaultRehypePlugins` is declared `Record<string, Pluggable>`, so the tuple
element can be typed as `Plugin<[SanitizeSchema]>` against the interface already in this
file -- same cast, same inference at the call site, no `any`.

Type-only: one line, no behaviour change. `tsc -b` clean; the PR's own tests still pass
(10/10 across markdown-data-images + math-block-containment-wiring); the 4 failures in
math-block-marker-pipeline/remend are the pre-existing remend-pin assertions, identical on
the base commit.
@CelesteHeartsong

Copy link
Copy Markdown
Contributor Author

Codex review:

The sanitizer/hardener change is functionally sound, but I found one actionable issue before merge.

P2 — the newly added files do not pass the repository lint/format commands. In markdown-data-images.ts:22, the cast Plugin<Array<any>, any, any> introduces three explicit any values. Running the repository ESLint configuration against just the new source file gives three @typescript-eslint/no-explicit-any errors:

src/lib/markdown-data-images.ts:22:67  Unexpected any
src/lib/markdown-data-images.ts:22:73  Unexpected any
src/lib/markdown-data-images.ts:22:78  Unexpected any

npx biome check src/lib/markdown-data-images.ts tests/markdown-data-images.test.ts also fails on those explicit anys, import ordering, and formatting in both newly added files. The current CI set does not appear to run these checks, which is why the PR is green on the frontend jobs.

The cast can remain precise without weakening type safety; I locally changed only that declaration to:

const sanitize = defaultRehypePlugins.sanitize as [
  Plugin<[SanitizeSchema]>,
  SanitizeSchema,
];

That version passes both tsc -b and ESLint. Please make that (or an equivalent typed change) and run the checked-in Biome formatter on the new source/test files.

Fixed in 59991fa — type-only, one line: as [Plugin<[SanitizeSchema]>, SanitizeSchema]. ESLint now clean on that file

@Etherll Etherll left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work !

@Etherll
Etherll merged commit a2a4143 into unslothai:main Sep 4, 2026
37 checks passed
CelesteHeartsong added a commit to CelesteHeartsong/unsloth that referenced this pull request Sep 5, 2026
A model that writes `![plot](/api/inference/sandbox/<sid>/plot.png)` got "[Image blocked]"
before, and "Image not available" after unslothai#10269: the src carries no scheme, so sanitize keeps it
and safeMarkdownUrl returns it unchanged -- but the route answers on the Authorization header
(_authenticate_header_or_query), so a bare <img src> hits it unauthenticated and 401s. Only
tool cards did the authed fetch (tool-ui-python.tsx), so markdown was the one path left.

Resolve the src through sandboxFilePath(sandboxSessionIdFor(threadId, projectId)) and fetch it
into an object URL before it reaches the DOM: the session segment the model happened to write is
discarded and rebuilt from this chat's scope, so a project thread reads the project's workspace.
One hook, useSandboxImage, now does that for markdown AND for the Python card, which had its own
copy; abort + revokeObjectURL on cleanup in both.

Registering `img` replaces Streamdown's default renderer wholesale (its Components map is keyed by
tag), so everything that renderer did for a data: image is restated: wrapper, hidden-when-failed,
fallback text, hover download. The two features are load-bearing on each other rather than merely
compatible: unslothai#10269's early return for `data:`/`blob:` is exactly why the rewritten src survives the
way back out, and it returns those unchanged, so scheme-carrying sources never reach this path.

.avif joins _SANDBOX_MEDIA_TYPES (a raster codec, and nosniff pins the type either way); .svg stays
out on purpose -- the filename is model-chosen, so inline SVG would be same-origin script execution,
and a non-image extension stays the download card the file list already renders. Tests included.
Etherll added a commit that referenced this pull request Sep 6, 2026
* feat(chat): render on-disk sandbox images in chat markdown

A model that writes `![plot](/api/inference/sandbox/<sid>/plot.png)` got "[Image blocked]"
before, and "Image not available" after #10269: the src carries no scheme, so sanitize keeps it
and safeMarkdownUrl returns it unchanged -- but the route answers on the Authorization header
(_authenticate_header_or_query), so a bare <img src> hits it unauthenticated and 401s. Only
tool cards did the authed fetch (tool-ui-python.tsx), so markdown was the one path left.

Resolve the src through sandboxFilePath(sandboxSessionIdFor(threadId, projectId)) and fetch it
into an object URL before it reaches the DOM: the session segment the model happened to write is
discarded and rebuilt from this chat's scope, so a project thread reads the project's workspace.
One hook, useSandboxImage, now does that for markdown AND for the Python card, which had its own
copy; abort + revokeObjectURL on cleanup in both.

Registering `img` replaces Streamdown's default renderer wholesale (its Components map is keyed by
tag), so everything that renderer did for a data: image is restated: wrapper, hidden-when-failed,
fallback text, hover download. The two features are load-bearing on each other rather than merely
compatible: #10269's early return for `data:`/`blob:` is exactly why the rewritten src survives the
way back out, and it returns those unchanged, so scheme-carrying sources never reach this path.

.avif joins _SANDBOX_MEDIA_TYPES (a raster codec, and nosniff pins the type either way); .svg stays
out on purpose -- the filename is model-chosen, so inline SVG would be same-origin script execution,
and a non-image extension stays the download card the file list already renders. Tests included.

* fix(chat): address review on sandbox markdown images: recorded session wins, decoded names, avif parity

Three review threads and one manual note, all in the same seam.

The session a src RECORDS wins when it names one (r3941897041). Replay shows the model its own
tool-result stdout, not the envelope -- and stdout carries real workdir paths, so the sid a model
echoes into a URL IS the folder its files were written to. That is exactly what the tool card above
the prose already resolves from (the persisted envelope's sessionId); re-deriving from current scope
was the one place that disagreed with it, and it broke older answers' images after a project move.
sandboxSessionInSrc reads the recorded session back out (path segment, or ?session= under `_`);
markdownSandboxImageSrc falls back to this chat's scope only when nothing was recorded. A bare
outputs/plot.png still takes project-<id> else threadId, exactly as before.

And a dot segment can no longer smuggle a scope: sandboxFileForSrc decodes BEFORE judging (so %2e%2e
is caught too) and returns null on `..` -- one dot pops the prepended scope into another chat's
folder, two land on another route; a bare `.` is dropped as noise.

Download names decode (r3941897043): the tail is split on raw [?#] first, so delimiters keep their
meaning, then decodedSegment'd -- `loss curve #1.png` saves under its real name now.

.avif joins _IMAGE_EXTS (r3941897045), and the frontend pin now pins set(_SANDBOX_MEDIA_TYPES) ==
_IMAGE_EXTS outright: what the route serves inline, what a tool call reports inline, and what the
frontend renders as an <img> are one set in three files and must not drift apart again.

Tests re-pinned for recorded-wins (a moved chat's older answer keeps resolving to the folder named
in its own URL even when projectId is set; bare paths still beat scope from project over threadId),
the `?session=` form round-trips, dot segments fail honestly, and the decode pin rides the restatement.
6881 pass / 0 fail on the frontend suite, tsc -b clean; backend suites byte-identical to main here.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix sandbox image URL validation and error recovery

* Fix sandbox image retries reusing cancelled results

---------

Co-authored-by: CelesteHeartsong <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Etherll <[email protected]>
@CelesteHeartsong
CelesteHeartsong deleted the fix/markdown-data-images branch October 7, 2026 23:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants