From 5ffa12010f426b8404036126e0cbb90c5f0758fd Mon Sep 17 00:00:00 2001 From: TeleporterGuy <117867648+TeleporterGuy@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:17:06 +0200 Subject: [PATCH 1/2] feat(notebooks): show JSON, HTML, markdown, JPEG/SVG outputs and markdown attachments Windows testing found two notebook contents that were saved correctly but never displayed: - Outputs without PNG or text/plain (e.g. display({...}, raw=True), which is application/json only) rendered as nothing, so the cell looked empty. Outputs now show, in order: PNG, JPEG, SVG, plain text, sanitized HTML, markdown, pretty-printed JSON; anything else is named ("Output not shown here: ") instead of silently hidden. PNG-then-text stays first so common outputs (pandas frames) look as before. - Markdown cells' pasted images (`attachment:name`, bytes in the cell's attachments) were broken images. The preview now rewrites them to data URLs, which the markdown sanitizer and CSP allow. Co-Authored-By: Claude Opus 5.5 --- src/renderer/components/NotebookCell.tsx | 3 +- src/renderer/components/NotebookOutputs.tsx | 31 ++++---- src/shared/notebook.ts | 57 ++++++++++++++ tests/notebook-rich-output.test.tsx | 85 +++++++++++++++++++++ 4 files changed, 162 insertions(+), 14 deletions(-) create mode 100644 tests/notebook-rich-output.test.tsx diff --git a/src/renderer/components/NotebookCell.tsx b/src/renderer/components/NotebookCell.tsx index 1d427830..f5e6ee0e 100644 --- a/src/renderer/components/NotebookCell.tsx +++ b/src/renderer/components/NotebookCell.tsx @@ -6,6 +6,7 @@ import type { AppConfig } from '../../shared/types' import { isNotebookCellCollapsed, notebookCellSourcePreview, + resolveMarkdownAttachments, type NotebookCell, type NotebookCellType } from '../../shared/notebook' @@ -430,7 +431,7 @@ export default function NotebookCellView({ {cell.source.trim() ? ( - {png && ( - + {display.kind === 'image' && } + {display.kind === 'text' &&
{display.text}
} + {display.kind === 'json' &&
{display.text}
} + {display.kind === 'html' && ( + // Kernel HTML is sanitized (no scripts, no event handlers) before it is shown. +
)} - {!png && text && ( -
{text}
+ {display.kind === 'markdown' && ( + + )} + {display.kind === 'unsupported' && ( +
Output not shown here: {display.mimeTypes.join(', ')}
)} {truncated && }
diff --git a/src/shared/notebook.ts b/src/shared/notebook.ts index b70e2317..a46bb7d8 100644 --- a/src/shared/notebook.ts +++ b/src/shared/notebook.ts @@ -936,3 +936,60 @@ export function storedCellIds(text: string): Set { return new Set() } } + +/** + * What an `execute_result` / `display_data` output shows. Earlier entries win, + * keeping the long-standing PNG-then-plain-text order for the common outputs + * (a pandas frame keeps its text form); richer forms are used when nothing + * simpler is there, and anything left is named so a cell never looks empty. + */ +export type NotebookDisplay = + | { kind: 'image'; src: string } + | { kind: 'text'; text: string } + | { kind: 'html'; html: string } + | { kind: 'markdown'; markdown: string } + | { kind: 'json'; text: string } + | { kind: 'unsupported'; mimeTypes: string[] } + +export function notebookOutputDisplay( + data: Record, + jsonData?: Record +): NotebookDisplay | null { + const png = mimePng(data) + if (png) return { kind: 'image', src: `data:image/png;base64,${png.replace(/\s/g, '')}` } + const jpeg = data['image/jpeg'] + if (jpeg) return { kind: 'image', src: `data:image/jpeg;base64,${jpeg.replace(/\s/g, '')}` } + const svg = data['image/svg+xml'] + if (svg) return { kind: 'image', src: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}` } + const plain = mimePlainText(data) + if (plain) return { kind: 'text', text: plain } + if (data['text/html']) return { kind: 'html', html: data['text/html'] } + if (data['text/markdown']) return { kind: 'markdown', markdown: data['text/markdown'] } + const jsonKey = Object.keys(jsonData ?? {}).find(isJsonMimeType) + if (jsonKey) return { kind: 'json', text: JSON.stringify(jsonData![jsonKey], null, 2) } + const mimeTypes = [...Object.keys(data), ...Object.keys(jsonData ?? {})].filter((m) => m !== 'text/plain') + return mimeTypes.length > 0 ? { kind: 'unsupported', mimeTypes } : null +} + +/** + * Markdown cells reference pasted images as `attachment:`; the bytes live + * in the cell's `attachments` (`{ name: { "image/png": base64 } }`). Rewrite + * those references to data URLs so the preview can show them. Unknown names + * are left alone. + */ +export function resolveMarkdownAttachments(source: string, attachments: unknown): string { + const record = asRecord(attachments) + if (!record) return source + return source.replace(/attachment:([^\s)"'<>]+)/g, (match, rawName: string) => { + let name = rawName + try { name = decodeURIComponent(rawName) } catch { /* keep raw */ } + const bundle = asRecord(record[name] ?? record[rawName]) + if (!bundle) return match + const mime = Object.keys(bundle).find((key) => key.startsWith('image/')) + const value = mime ? bundle[mime] : undefined + const base64 = typeof value === 'string' ? value : Array.isArray(value) ? value.join('') : null + if (!mime || !base64) return match + if (mime === 'image/svg+xml') return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(base64)}` + return `data:${mime};base64,${base64.replace(/\s/g, '')}` + }) +} diff --git a/tests/notebook-rich-output.test.tsx b/tests/notebook-rich-output.test.tsx new file mode 100644 index 00000000..5b53109a --- /dev/null +++ b/tests/notebook-rich-output.test.tsx @@ -0,0 +1,85 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it } from 'vitest' +import React from 'react' +import { cleanup, render } from '@testing-library/react' +import NotebookOutputs from '../src/renderer/components/NotebookOutputs' +import MarkdownPreview from '../src/renderer/components/MarkdownPreview' +import { notebookOutputDisplay, resolveMarkdownAttachments, type NotebookOutput } from '../src/shared/notebook' + +void React + +afterEach(() => cleanup()) + +const PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==' + +describe('notebookOutputDisplay', () => { + it('keeps PNG, then plain text, first', () => { + expect(notebookOutputDisplay({ 'image/png': PNG, 'text/plain': 'x' })).toMatchObject({ kind: 'image' }) + expect(notebookOutputDisplay({ 'text/html': 'x', 'text/plain': 'x' })).toEqual({ kind: 'text', text: 'x' }) + }) + + it('shows JSON-only output (display(..., raw=True)) pretty-printed', () => { + expect(notebookOutputDisplay({}, { 'application/json': { a: 1 } })).toEqual({ kind: 'json', text: '{\n "a": 1\n}' }) + }) + + it('uses JPEG, SVG, HTML and markdown when nothing simpler is there', () => { + expect(notebookOutputDisplay({ 'image/jpeg': 'abc' })).toEqual({ kind: 'image', src: 'data:image/jpeg;base64,abc' }) + expect(notebookOutputDisplay({ 'image/svg+xml': '' })?.kind).toBe('image') + expect(notebookOutputDisplay({ 'text/html': 'x' })).toEqual({ kind: 'html', html: 'x' }) + expect(notebookOutputDisplay({ 'text/markdown': '# x' })).toEqual({ kind: 'markdown', markdown: '# x' }) + }) + + it('names what it cannot show instead of showing nothing', () => { + expect(notebookOutputDisplay({ 'application/vnd.custom': 'z' })).toEqual({ kind: 'unsupported', mimeTypes: ['application/vnd.custom'] }) + expect(notebookOutputDisplay({})).toBeNull() + }) +}) + +describe('NotebookOutputs rendering', () => { + it('renders a JSON-only display_data output', () => { + const outputs: NotebookOutput[] = [{ + type: 'display_data', + data: {}, + jsonData: { 'application/json': { a: 1, message: 'survives' } } + }] + const { container } = render() + expect(container.textContent).toContain('"message": "survives"') + }) + + it('sanitizes HTML output', () => { + const outputs: NotebookOutput[] = [{ + type: 'display_data', + data: { 'text/html': '
cell
' } + }] + const { container } = render() + expect(container.querySelector('td')?.textContent).toBe('cell') + expect(container.querySelector('script')).toBeNull() + expect(container.querySelector('img')?.getAttribute('onerror')).toBeNull() + }) +}) + +describe('markdown attachments', () => { + const attachments = { 'checker.png': { 'image/png': PNG } } + + it('rewrites attachment: references to data URLs', () => { + expect(resolveMarkdownAttachments('![alt](attachment:checker.png)', attachments)) + .toBe(`![alt](data:image/png;base64,${PNG})`) + }) + + it('leaves unknown attachments and plain text alone', () => { + expect(resolveMarkdownAttachments('![a](attachment:missing.png) attachment', attachments)) + .toBe('![a](attachment:missing.png) attachment') + expect(resolveMarkdownAttachments('![a](attachment:x.png)', undefined)).toBe('![a](attachment:x.png)') + }) + + it('handles URL-encoded names', () => { + const named = { 'my image.png': { 'image/png': PNG } } + expect(resolveMarkdownAttachments('![a](attachment:my%20image.png)', named)).toContain('data:image/png;base64,') + }) + + it('survives the markdown preview sanitizer as a data: image', () => { + const content = resolveMarkdownAttachments('![Checkerboard](attachment:checker.png)', attachments) + const { container } = render() + expect(container.querySelector('img')?.getAttribute('src')).toBe(`data:image/png;base64,${PNG}`) + }) +}) From 03d52b9c8fe7fa7f1afa11864260b5feb2d3674a Mon Sep 17 00:00:00 2001 From: TeleporterGuy <117867648+TeleporterGuy@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:23:09 +0200 Subject: [PATCH 2/2] fix(notebooks): keep JSON outputs from live kernel events truncateMimeBundle (run in main on every kernel output) turned every mime value into text; a JSON object became "". The kernel helper already passes JSON mime values through and drops oversized ones, so keep them as-is here. Found on Windows: display({'application/json': ...}, raw=True) showed "" under the cell. Co-Authored-By: Claude Opus 5.5 --- src/shared/notebook.ts | 6 ++++++ tests/notebook-rich-output.test.tsx | 18 +++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/shared/notebook.ts b/src/shared/notebook.ts index a46bb7d8..5ef50d48 100644 --- a/src/shared/notebook.ts +++ b/src/shared/notebook.ts @@ -708,6 +708,12 @@ export function truncateMimeBundle(data: Record): Record = {} let omittedPng = false for (const [key, value] of Object.entries(data)) { + // JSON mime values are objects, not text: keep them (the kernel helper already + // drops oversized ones). Turning them into text here made them "". + if (isJsonMimeType(key)) { + out[key] = value + continue + } const text = typeof value === 'string' ? value : joinNotebookText(value) if (key === 'image/png' && text.length > NOTEBOOK_MIME_CHAR_LIMIT) { omittedPng = true diff --git a/tests/notebook-rich-output.test.tsx b/tests/notebook-rich-output.test.tsx index 5b53109a..b4ca3d3c 100644 --- a/tests/notebook-rich-output.test.tsx +++ b/tests/notebook-rich-output.test.tsx @@ -4,7 +4,7 @@ import React from 'react' import { cleanup, render } from '@testing-library/react' import NotebookOutputs from '../src/renderer/components/NotebookOutputs' import MarkdownPreview from '../src/renderer/components/MarkdownPreview' -import { notebookOutputDisplay, resolveMarkdownAttachments, type NotebookOutput } from '../src/shared/notebook' +import { applyKernelEventToOutputs, notebookOutputDisplay, parseKernelEventLine, resolveMarkdownAttachments, type NotebookOutput } from '../src/shared/notebook' void React @@ -35,6 +35,22 @@ describe('notebookOutputDisplay', () => { }) }) +describe('live kernel output path', () => { + it('keeps a JSON-only display_data object through parsing and into the cell outputs', () => { + const line = JSON.stringify({ + event: 'display_data', + id: 'req-1', + data: { 'application/json': { a: 1, message: 'This rich output should survive save/reopen.' } } + }) + const event = parseKernelEventLine(line) + expect(event).toMatchObject({ event: 'display_data', data: { 'application/json': { a: 1 } } }) + const outputs = applyKernelEventToOutputs([], event!)! + const out = outputs[0] as Extract + expect(notebookOutputDisplay(out.data, out.jsonData)).toMatchObject({ kind: 'json' }) + expect((notebookOutputDisplay(out.data, out.jsonData) as { text: string }).text).toContain('"message"') + }) +}) + describe('NotebookOutputs rendering', () => { it('renders a JSON-only display_data output', () => { const outputs: NotebookOutput[] = [{