app: the chat renders Markdown images from data: URLs and the chat's own folder; remote pictures stay links (O3)
 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.
This commit is contained in:
1 parent
e2858b9855
commit
1fa22cd29a
5 files changed
+143
-13
No files matched your search
@@ -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 <img key={i} src={plan.src} alt={image[1]} className="md-image" loading="lazy" referrerPolicy="no-referrer"/>;
|
||||
if (plan.kind === 'link')
|
||||
return <a key={i} href={plan.href} target="_blank" rel="noreferrer" onClick={e => { if (onOpenLink) {
|
||||
e.preventDefault();
|
||||
onOpenLink(plan.href);
|
||||
} }}>{image[1] || plan.href}</a>;
|
||||
return <Fragment key={i}>{image[1] || part}</Fragment>;
|
||||
}
|
||||
if (part.startsWith('`') && part.endsWith('`'))
|
||||
return <code key={i} className="md-code">{part.slice(1, -1)}</code>;
|
||||
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 <Fragment key={c}>{inlineMarks(chunk, onOpenLink)}</Fragment>;
|
||||
return <Fragment key={c}>{inlineMarks(chunk, onOpenLink, imageSession)}</Fragment>;
|
||||
return <Fragment key={c}>{splitMath(chunk).map((part, p) => part.kind === 'math'
|
||||
? <MathView key={p} tex={part.tex} display={part.display}/>
|
||||
: <Fragment key={p}>{inlineMarks(part.text, onOpenLink)}</Fragment>)}</Fragment>;
|
||||
: <Fragment key={p}>{inlineMarks(part.text, onOpenLink, imageSession)}</Fragment>)}</Fragment>;
|
||||
});
|
||||
}
|
||||
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(<Tag key={i}>{tr(inline(heading[2], onOpenLink))}</Tag>);
|
||||
nodes.push(<Tag key={i}>{tr(inline(heading[2], onOpenLink, imageSession))}</Tag>);
|
||||
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(<div className="md-table-wrap" key={key}><table className="md-table"><thead><tr>{tr(header.map((c, j) => <th key={j}>{tr(inline(c, onOpenLink))}</th>))}</tr></thead><tbody>{tr(rows.map((r, j) => <tr key={j}>{tr(r.map((c, k) => <td key={k}>{tr(inline(c, onOpenLink))}</td>))}</tr>))}</tbody></table></div>);
|
||||
nodes.push(<div className="md-table-wrap" key={key}><table className="md-table"><thead><tr>{tr(header.map((c, j) => <th key={j}>{tr(inline(c, onOpenLink, imageSession))}</th>))}</tr></thead><tbody>{tr(rows.map((r, j) => <tr key={j}>{tr(r.map((c, k) => <td key={k}>{tr(inline(c, onOpenLink, imageSession))}</td>))}</tr>))}</tbody></table></div>);
|
||||
continue;
|
||||
}
|
||||
if (/^>\s?/.test(line)) {
|
||||
@@ -98,7 +113,7 @@ export function Markdown({ text, onOpenLink, onPreviewHtml }: {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
nodes.push(<p key={i}>{tr(inline(line, onOpenLink))}</p>);
|
||||
nodes.push(<p key={i}>{tr(inline(line, onOpenLink, imageSession))}</p>);
|
||||
i++;
|
||||
}
|
||||
return <>{tr(nodes)}</>;
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { rawUrlOf } from './deliverables';
|
||||
|
||||
/**
|
||||
* Which picture addresses a model's Markdown may put in an <img> (tools and images review O3, 2026-10-22).
|
||||
*
|
||||
* An answer can carry ``. 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) };
|
||||
}
|
||||
@@ -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 (<div className="st-msg st-msg--user" onMouseEnter={() => setSentTime(relTime(m.at))} onFocus={() => setSentTime(relTime(m.at))}>
|
||||
<div className="st-bubble">{tr(m.photos?.length ? <ChatPhotos photos={m.photos}/> : null)}{m.markdown ? <Markdown text={m.content} onOpenLink={onOpenLink}/> : m.content}</div>
|
||||
<div className="st-bubble">{tr(m.photos?.length ? <ChatPhotos photos={m.photos}/> : null)}{m.markdown ? <Markdown text={m.content} onOpenLink={onOpenLink} imageSession={activeSession}/> : m.content}</div>
|
||||
<div className="st-msg__meta">
|
||||
<time dateTime={m.at} title={tr(new Date(m.at).toLocaleString(localeTag()))}>{tr(sentTime)}</time>
|
||||
<span className="st-msg__actions">
|
||||
@@ -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) ? <div className="st-bubble">
|
||||
{tr(planCard ? <PlanCard chatId={activeSession} planId={m.planId!}/> : null)}
|
||||
{tr(m.error ? (<ErrorNotice message={m.error} next={tr("Try sending the message again.")}/>) : null)}
|
||||
{tr(grouped && !planCard && !m.timeSkipId ? m.blocks!.map((b, i) => b.kind === 'group' ? <ActivityLine key={b.id} group={b} sessionId={activeSession ?? ''} onPreview={onPreview}/> : <Markdown key={i} text={b.text} onOpenLink={onOpenLink} onPreviewHtml={content => onPreview({ id: m.id + '-html-' + i, kind: 'website', title: 'HTML preview', content })}/>) : null)}
|
||||
{tr(m.content && !planCard && !grouped ? (<Markdown text={m.timeSkipId && !timeSkipReal ? hostLive ? tr('This was a sample run made while the app could not reach its host.') : timeSkipDone ? tr('The result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.') : tr('Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.') : m.content} onOpenLink={onOpenLink} onPreviewHtml={content => onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming && !liveStatus ? (<span className="typing" aria-label={tr("Generating")}>
|
||||
{tr(grouped && !planCard && !m.timeSkipId ? m.blocks!.map((b, i) => b.kind === 'group' ? <ActivityLine key={b.id} group={b} sessionId={activeSession ?? ''} onPreview={onPreview}/> : <Markdown key={i} text={b.text} onOpenLink={onOpenLink} imageSession={activeSession} onPreviewHtml={content => onPreview({ id: m.id + '-html-' + i, kind: 'website', title: 'HTML preview', content })}/>) : null)}
|
||||
{tr(m.content && !planCard && !grouped ? (<Markdown text={m.timeSkipId && !timeSkipReal ? hostLive ? tr('This was a sample run made while the app could not reach its host.') : timeSkipDone ? tr('The result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.') : tr('Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.') : m.content} onOpenLink={onOpenLink} imageSession={activeSession} onPreviewHtml={content => onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming && !liveStatus ? (<span className="typing" aria-label={tr("Generating")}>
|
||||
<i />
|
||||
<i />
|
||||
<i />
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 <img>', async () => {
|
||||
const { render } = await load();
|
||||
const html = render(`Here it is:  done`);
|
||||
assert.match(html, /<img [^>]*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(``), /<img /, type);
|
||||
});
|
||||
|
||||
test('SVG data, script addresses, file: and other schemes never become an <img>', 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(``, 'chat-1');
|
||||
assert.ok(!/<img /.test(html), src);
|
||||
assert.ok(!/<a /.test(html), src);
|
||||
}
|
||||
});
|
||||
|
||||
test('a remote picture is a link, not a request: nothing is fetched from the internet by default', async () => {
|
||||
const { render, imagePlan } = await load();
|
||||
const html = render('', 'chat-1');
|
||||
assert.ok(!/<img /.test(html));
|
||||
assert.match(html, /<a [^>]*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('', 'chat 1');
|
||||
assert.match(html, /<img [^>]*src="\/api\/files\/raw\?sessionId=chat%201&path=plots%2Fsales.png"/);
|
||||
assert.match(render('', 'c1'), /<img [^>]*path=C%3A%5Cwork%5Csales.png/);
|
||||
assert.ok(!/<img /.test(render(''))); // no chat: shown as its alt text
|
||||
assert.match(render(''), /chart/);
|
||||
assert.deepEqual(imagePlan('/api/files/raw?sessionId=a&path=b'), { kind: 'img', src: '/api/files/raw?sessionId=a&path=b' });
|
||||
});
|
||||
|
||||
test('links, code and emphasis around a picture are unchanged, and the old text-with-a-bang is gone', async () => {
|
||||
const { render } = await load();
|
||||
const html = render('See [the report](https://example.com/r) and `code` and **bold**. ');
|
||||
assert.match(html, /<a [^>]*>the report<\/a>/);
|
||||
assert.match(html, /<code class="md-code">code<\/code>/);
|
||||
assert.match(html, /<strong>bold<\/strong>/);
|
||||
assert.ok(!html.includes('>!<') && !/!<a /.test(html));
|
||||
assert.ok(!/<img /.test(render('``'))); // inside a code span it stays code
|
||||
});
|
||||
|
||||
test('every incomplete stream prefix of an answer with a picture renders', async () => {
|
||||
const { render } = await load();
|
||||
const text = `Chart:\n\n\n\nand  end`;
|
||||
for (let i = 0; i <= text.length; i += 7) assert.equal(typeof render(text.slice(0, i), 'c1'), 'string');
|
||||
});
|
||||
Reference in new issue
Block a user