From 1fa22cd29a689a93d3fc08e91ce3067b5aef342d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 22 Oct 2026 12:58:22 +0200 Subject: [PATCH] app: the chat renders Markdown images from data: URLs and the chat's own folder; remote pictures stay links (O3) ![alt](src) used to come out as a link with a stray '!', and a data: URI as literal text. Allowlist (src/lib/markdown-images.ts): data: PNG/JPEG/WebP/GIF (never SVG), the host's /api/files/raw address, and a scheme-less path read through that address for the active chat. http(s) pictures are not fetched: they show as a link with the alt text. file:, javascript:, blob:, share paths and every other scheme show as text. One .md-image rule keeps the picture inside the bubble. --- apps/host/src/components/Markdown.tsx | 35 ++++++++--- apps/host/src/lib/markdown-images.ts | 32 ++++++++++ apps/host/src/screens/Chat.tsx | 6 +- apps/host/src/styles/app.css | 6 ++ apps/host/tests/markdown-images.test.mjs | 77 ++++++++++++++++++++++++ 5 files changed, 143 insertions(+), 13 deletions(-) create mode 100644 apps/host/src/lib/markdown-images.ts create mode 100644 apps/host/tests/markdown-images.test.mjs diff --git a/apps/host/src/components/Markdown.tsx b/apps/host/src/components/Markdown.tsx index 87e6c327..996b191f 100644 --- a/apps/host/src/components/Markdown.tsx +++ b/apps/host/src/components/Markdown.tsx @@ -5,8 +5,21 @@ import { Btn, IconBtn } from './ui'; import { SyntaxCode } from './SyntaxCode'; import { MathView } from './MathView'; import { displayBlock, hasMath, splitMath } from '../lib/math'; -function inlineMarks(text: string, onOpenLink?: (url: string) => void): ReactNode { - return text.split(/(`[^`]+`|\*\*[^*]+\*\*|\*[^*\n]+\*|\[[^\]]+\]\([^\s)]+\))/g).map((part, i) => { +import { imagePlan } from '../lib/markdown-images'; +function inlineMarks(text: string, onOpenLink?: (url: string) => void, imageSession?: string | null): ReactNode { + return text.split(/(!\[[^\]]*\]\([^\s)]+\)|`[^`]+`|\*\*[^*]+\*\*|\*[^*\n]+\*|\[[^\]]+\]\([^\s)]+\))/g).map((part, i) => { + const image = part.match(/^!\[([^\]]*)\]\(([^\s)]+)\)$/); + if (image) { + const plan = imagePlan(image[2], imageSession); + if (plan.kind === 'img') + return {image[1]}; + if (plan.kind === 'link') + return { if (onOpenLink) { + e.preventDefault(); + onOpenLink(plan.href); + } }}>{image[1] || plan.href}; + return {image[1] || part}; + } if (part.startsWith('`') && part.endsWith('`')) return {part.slice(1, -1)}; if (part.startsWith('**') && part.endsWith('**')) @@ -23,21 +36,23 @@ function inlineMarks(text: string, onOpenLink?: (url: string) => void): ReactNod }); } /** Text with its inline marks and, outside code spans, its math (#3268). Math is cut out first: a * or _ inside a formula is not emphasis. */ -function inline(text: string, onOpenLink?: (url: string) => void): ReactNode { +function inline(text: string, onOpenLink?: (url: string) => void, imageSession?: string | null): ReactNode { if (!hasMath(text)) - return inlineMarks(text, onOpenLink); + return inlineMarks(text, onOpenLink, imageSession); return text.split(/(`[^`]+`)/g).map((chunk, c) => { if (chunk.length > 1 && chunk.startsWith('`') && chunk.endsWith('`')) - return {inlineMarks(chunk, onOpenLink)}; + return {inlineMarks(chunk, onOpenLink, imageSession)}; return {splitMath(chunk).map((part, p) => part.kind === 'math' ? - : {inlineMarks(part.text, onOpenLink)})}; + : {inlineMarks(part.text, onOpenLink, imageSession)})}; }); } -export function Markdown({ text, onOpenLink, onPreviewHtml }: { +export function Markdown({ text, onOpenLink, onPreviewHtml, imageSession }: { text: string; onOpenLink?: (url: string) => void; onPreviewHtml?: (html: string) => void; + /** The chat whose folder a picture path in the answer is read from (the host serves only files inside it). */ + imageSession?: string | null; }) { const nodes: ReactNode[] = []; const lines = text.split('\n'); @@ -66,7 +81,7 @@ export function Markdown({ text, onOpenLink, onPreviewHtml }: { const heading = line.match(/^(#{1,6})\s+(.+)$/); if (heading) { const Tag = heading[1].length <= 2 ? 'h2' : heading[1].length === 3 ? 'h3' : 'h4'; - nodes.push({tr(inline(heading[2], onOpenLink))}); + nodes.push({tr(inline(heading[2], onOpenLink, imageSession))}); i++; continue; } @@ -90,7 +105,7 @@ export function Markdown({ text, onOpenLink, onPreviewHtml }: { i += 2; while (i < lines.length && lines[i].includes('|')) rows.push(cells(lines[i++])); - nodes.push(
{tr(header.map((c, j) => ))}{tr(rows.map((r, j) => {tr(r.map((c, k) => ))}))}
{tr(inline(c, onOpenLink))}
{tr(inline(c, onOpenLink))}
); + nodes.push(
{tr(header.map((c, j) => ))}{tr(rows.map((r, j) => {tr(r.map((c, k) => ))}))}
{tr(inline(c, onOpenLink, imageSession))}
{tr(inline(c, onOpenLink, imageSession))}
); continue; } if (/^>\s?/.test(line)) { @@ -98,7 +113,7 @@ export function Markdown({ text, onOpenLink, onPreviewHtml }: { i++; continue; } - nodes.push(

{tr(inline(line, onOpenLink))}

); + nodes.push(

{tr(inline(line, onOpenLink, imageSession))}

); i++; } return <>{tr(nodes)}; diff --git a/apps/host/src/lib/markdown-images.ts b/apps/host/src/lib/markdown-images.ts new file mode 100644 index 00000000..d6c3ba47 --- /dev/null +++ b/apps/host/src/lib/markdown-images.ts @@ -0,0 +1,32 @@ +import { rawUrlOf } from './deliverables'; + +/** + * Which picture addresses a model's Markdown may put in an (tools and images review O3, 2026-10-22). + * + * An answer can carry `![chart](...)`. It is shown only when the picture is already on this computer or inside the message: + * - a data: address of a PNG, JPEG, WebP or GIF (never SVG: an SVG can carry script and styles); + * - the host's own /api/files/raw address (a file inside the chat's folder, served by the host and by nobody else); + * - a path without a scheme, which is read as a file of the chat's folder through that same address. + * Nothing is fetched from the internet by default (an address in the answer would tell its owner that the answer was read, and + * which IP read it): an http(s) picture stays a link the person can open. file:, javascript:, blob: and every other scheme show as text. + */ +export type ImagePlan = + | { kind: 'img'; src: string } + | { kind: 'link'; href: string } + | { kind: 'text' }; + +const DATA_IMAGE = /^data:image\/(?:png|jpe?g|webp|gif);base64,[A-Za-z0-9+/]+={0,2}$/i; +const SCHEME = /^[a-z][a-z0-9+.-]*:/i; + +export function imagePlan(src: string, sessionId?: string | null): ImagePlan { + const value = src.trim(); + if (!value) return { kind: 'text' }; + if (DATA_IMAGE.test(value)) return { kind: 'img', src: value }; + if (/^https?:\/\//i.test(value)) return { kind: 'link', href: value }; + if (value.startsWith('/api/files/raw?')) return { kind: 'img', src: value }; + // a drive letter (C:\x.png, C:/x.png) is a path, not a scheme + if (SCHEME.test(value) && !/^[a-z]:[\\/]/i.test(value)) return { kind: 'text' }; + if (value.startsWith('//') || value.startsWith('\\\\')) return { kind: 'text' }; // another computer's share + if (!sessionId) return { kind: 'text' }; + return { kind: 'img', src: rawUrlOf(sessionId, value) }; +} diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index 2a95cedc..aa32de7a 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -615,7 +615,7 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp const [sentTime, setSentTime] = useState(() => relTime(m.at)); if (m.role === 'user') { return (
setSentTime(relTime(m.at))} onFocus={() => setSentTime(relTime(m.at))}> -
{tr(m.photos?.length ? : null)}{m.markdown ? : m.content}
+
{tr(m.photos?.length ? : null)}{m.markdown ? : m.content}
@@ -639,8 +639,8 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp {tr(!(m.timeSkipId && timeSkipReal && !timeSkipDone) && (m.content || m.error || !m.streaming || !liveStatus) ?
{tr(planCard ? : null)} {tr(m.error ? () : null)} - {tr(grouped && !planCard && !m.timeSkipId ? m.blocks!.map((b, i) => b.kind === 'group' ? : onPreview({ id: m.id + '-html-' + i, kind: 'website', title: 'HTML preview', content })}/>) : null)} - {tr(m.content && !planCard && !grouped ? ( onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming && !liveStatus ? ( + {tr(grouped && !planCard && !m.timeSkipId ? m.blocks!.map((b, i) => b.kind === 'group' ? : onPreview({ id: m.id + '-html-' + i, kind: 'website', title: 'HTML preview', content })}/>) : null)} + {tr(m.content && !planCard && !grouped ? ( onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming && !liveStatus ? ( diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index c740716c..bb27e246 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -2467,6 +2467,12 @@ textarea.st-input { border: 1px solid var(--st-line); } +.md-image { + max-width: 100%; + height: auto; + border-radius: 8px; +} + .typing { display: inline-flex; gap: 4px; diff --git a/apps/host/tests/markdown-images.test.mjs b/apps/host/tests/markdown-images.test.mjs new file mode 100644 index 00000000..732cb092 --- /dev/null +++ b/apps/host/tests/markdown-images.test.mjs @@ -0,0 +1,77 @@ +// O3 (tools and images review, 2026-10-22): a Markdown image in an answer renders as a picture when it is already on this computer or inside +// the message, and never fetches anything from the internet by default. +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { resolve } from 'node:path'; +import { createRequire } from 'node:module'; +import { build } from 'esbuild'; + +const root = resolve(import.meta.dirname, '..'); +const PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='; + +async function load() { + const bundle = await build({ + stdin: { contents: `import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import { Markdown } from './src/components/Markdown.tsx'; import { imagePlan } from './src/lib/markdown-images.ts'; export { imagePlan }; export const render = (text, imageSession) => renderToStaticMarkup(React.createElement(Markdown, { text, imageSession }));`, resolveDir: root }, + bundle: true, write: false, platform: 'node', format: 'cjs', jsx: 'automatic', external: ['katex', 'katex/dist/katex.min.css'], + plugins: [{ name: 'copy-control-stub', setup(b) { + b.onResolve({ filter: /^\.\/ui$/ }, () => ({ path: 'ui', namespace: 'test-stub' })); + b.onLoad({ filter: /.*/, namespace: 'test-stub' }, () => ({ contents: 'export const IconBtn = () => null; export const Btn = () => null;' })); + } }], + }); + const mod = { exports: {} }; + new Function('require', 'module', 'exports', bundle.outputFiles[0].text)(createRequire(import.meta.url), mod, mod.exports); + return mod.exports; +} + +test('a data: PNG, JPEG, WebP or GIF renders as an ', async () => { + const { render } = await load(); + const html = render(`Here it is: ![dot](${PNG}) done`); + assert.match(html, /]*src="data:image\/png;base64,/); + assert.match(html, /alt="dot"/); + assert.match(html, /referrerPolicy|referrerpolicy="no-referrer"/i); + for (const type of ['jpeg', 'jpg', 'webp', 'gif']) assert.match(render(`![x](data:image/${type};base64,QUJD)`), /', async () => { + const { render } = await load(); + for (const src of ['data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=', 'data:text/html;base64,QUJD', 'javascript:alert(1)', 'file:///C:/secret.png', + 'blob:https://x/1', 'ftp://x/y.png', '//host/share/x.png', '\\\\host\\share\\x.png', 'data:image/png;base64,QUJD" onerror="alert(1)']) { + const html = render(`![x](${src})`, 'chat-1'); + assert.ok(!/ { + const { render, imagePlan } = await load(); + const html = render('![Monthly sales](https://example.com/sales.png)', 'chat-1'); + assert.ok(!/]*href="https:\/\/example.com\/sales.png"[^>]*>Monthly sales<\/a>/); + assert.deepEqual(imagePlan('http://example.com/a.png'), { kind: 'link', href: 'http://example.com/a.png' }); +}); + +test('a path in the chat folder is read through the host, and only when the chat is known', async () => { + const { render, imagePlan } = await load(); + const html = render('![chart](plots/sales.png)', 'chat 1'); + assert.match(html, /]*src="\/api\/files\/raw\?sessionId=chat%201&path=plots%2Fsales.png"/); + assert.match(render('![chart](C:\\work\\sales.png)', 'c1'), /]*path=C%3A%5Cwork%5Csales.png/); + assert.ok(!/ { + const { render } = await load(); + const html = render('See [the report](https://example.com/r) and `code` and **bold**. ![a](' + PNG + ')'); + assert.match(html, /]*>the report<\/a>/); + assert.match(html, /code<\/code>/); + assert.match(html, /bold<\/strong>/); + assert.ok(!html.includes('>!<') && !/! { + const { render } = await load(); + const text = `Chart:\n\n![sales](${PNG})\n\nand ![b](https://example.com/b.png) end`; + for (let i = 0; i <= text.length; i += 7) assert.equal(typeof render(text.slice(0, i), 'c1'), 'string'); +});