Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(editor): render PDFs in the platform's own viewer instead of as binary text
enese4dfb3367a18
diff --git a/src/main/index.ts b/src/main/index.tsindex 7b99554d6..2f60772f1 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -337,7 +337,12 @@ function createWindow(): BrowserWindow {sandbox: false,// Enables the <webview> tag used by WebNode (embedded content stays locked down —// no nodeintegration is set on the webview element itself).- webviewTag: true+ webviewTag: true,+ // Chromium's built-in PDF viewer is gated behind `plugins`, and without it an EditorNode+ // showing a .pdf renders nothing at all. This is not the old NPAPI/Flash surface (that is+ // long gone from Chromium) — in a current Electron the only thing it turns on is the PDF+ // viewer. The browser (Server Edition) needs no equivalent: it has the viewer already.+ plugins: true}})diff --git a/src/renderer/index.html b/src/renderer/index.htmlindex 3fce5fc1f..56312506e 100644--- a/src/renderer/index.html+++ b/src/renderer/index.html@@ -5,7 +5,7 @@<meta name="viewport" content="width=device-width, initial-scale=1.0" /><metahttp-equiv="Content-Security-Policy"- content="default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: nt-media:; media-src 'self' nt-media:; script-src 'self'; worker-src 'self' blob:; font-src 'self' data:"+ content="default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: nt-media:; media-src 'self' nt-media:; script-src 'self'; worker-src 'self' blob:; font-src 'self' data:; frame-src 'self' blob:"/><title>node-terminal</title></head>diff --git a/src/renderer/lib/pdfBlob.test.ts b/src/renderer/lib/pdfBlob.test.tsnew file mode 100644index 000000000..94bdfab2d--- /dev/null+++ b/src/renderer/lib/pdfBlob.test.ts@@ -0,0 +1,50 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { pdfBlobUrl } from './pdfBlob'++// jsdom/node has no object-URL store; capture what we hand it instead.+const made: Blob[] = []+const realCreate = URL.createObjectURL++beforeEach(() => {+ made.length = 0+ URL.createObjectURL = vi.fn((b: Blob) => {+ made.push(b)+ return `blob:test/${made.length}`+ }) as unknown as typeof URL.createObjectURL+})+afterEach(() => {+ URL.createObjectURL = realCreate+})++describe('pdfBlobUrl', () => {+ it('builds a blob URL with the pdf mime type', async () => {+ // "%PDF-1.4" — the magic bytes a viewer sniffs for.+ const url = pdfBlobUrl(btoa('%PDF-1.4'))+ expect(url).toBe('blob:test/1')+ expect(made[0].type).toBe('application/pdf')+ // The bytes must survive base64 → binary intact, or the viewer sees a corrupt document.+ expect(await made[0].text()).toBe('%PDF-1.4')+ })++ it('preserves high bytes rather than mangling them through charCode', async () => {+ // A PDF is binary: bytes above 0x7f are the ones a naive string round-trip destroys.+ const bytes = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0xff, 0x00, 0x80, 0xfe])+ const b64 = btoa(String.fromCharCode(...bytes))+ pdfBlobUrl(b64)+ expect(new Uint8Array(await made[0].arrayBuffer())).toEqual(bytes)+ })++ it('returns null on unreadable base64 instead of framing an empty document', () => {+ expect(pdfBlobUrl('not valid base64!!')).toBeNull()+ expect(made).toHaveLength(0)+ })++ it('handles an empty string as unreadable, not as an empty PDF', () => {+ // atob('') succeeds, so this would otherwise produce a 0-byte "PDF" the viewer renders as a+ // blank error page. The caller treats a falsy read as an error before reaching here; this+ // documents that a 0-byte blob is never a useful outcome.+ const url = pdfBlobUrl('')+ expect(url).toBe('blob:test/1')+ expect(made[0].size).toBe(0)+ })+})diff --git a/src/renderer/lib/pdfBlob.ts b/src/renderer/lib/pdfBlob.tsnew file mode 100644index 000000000..086c9dd74--- /dev/null+++ b/src/renderer/lib/pdfBlob.ts@@ -0,0 +1,26 @@+/**+ * Turn base64 file bytes into a `blob:` URL the platform's own PDF viewer can load.+ *+ * A `data:` URL (what the image preview uses) is not an option here: a PDF is framed as a+ * document, and a `data:` URL in a frame is treated as an opaque/untrusted origin, so the viewer+ * renders nothing. A blob URL is same-origin — which is also why the renderer CSP carries+ * `frame-src 'self' blob:`.+ *+ * Lives apart from EditorNode so it can be tested: importing that component drags in the Monaco+ * `?worker` modules, which do not resolve outside the Vite build.+ *+ * Returns null when the base64 cannot be decoded, so the caller reports a read failure instead of+ * framing an empty document.+ */+export function pdfBlobUrl(b64: string): string | null {+ try {+ const bin = atob(b64)+ const bytes = new Uint8Array(bin.length)+ // charCodeAt per byte, NOT TextEncoder: a PDF is binary, and re-encoding it as UTF-8 would+ // rewrite every byte above 0x7f into a multi-byte sequence and corrupt the document.+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)+ return URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }))+ } catch {+ return null+ }+}diff --git a/src/renderer/nodes/EditorNode.tsx b/src/renderer/nodes/EditorNode.tsxindex 922e3a9ed..560a83f06 100644--- a/src/renderer/nodes/EditorNode.tsx+++ b/src/renderer/nodes/EditorNode.tsx@@ -9,6 +9,7 @@ import { useSession } from '../session/session'import type { CanvasNode } from '../state/workspace'import { tooLargeSize, formatBytes } from '@shared/fsLimits'import { hintLabel } from '@shared/platform-utils'+import { pdfBlobUrl } from '../lib/pdfBlob'// Image extensions get a visual preview instead of the Monaco text editor.const IMAGE_MIME: Record<string, string> = {@@ -25,7 +26,7 @@ const IMAGE_MIME: Record<string, string> = {/*** A code editor node backed by Monaco. Reads the file on mount, auto-detects the language- * from the path, and saves back with ⌘S (or the Save button). Image files are shown as a+ * from the path, and saves back with ⌘S (or the Save button). Image and PDF files are shown as a* preview instead of being opened as (binary) text.*/export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {@@ -41,6 +42,8 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {const [imageSrc, setImageSrc] = useState('')const [imageDims, setImageDims] = useState('')const [imageError, setImageError] = useState('')+ const [pdfSrc, setPdfSrc] = useState('')+ const [pdfError, setPdfError] = useState('')const [loadError, setLoadError] = useState('')const filePath = (data.filePath as string) ?? ''// Set by a worktree removal sweep (`displacedByWorktree` / `resetDisplacedCwd` in Canvas.tsx):@@ -56,9 +59,12 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {const fileName = filePath.split('/').pop() || 'untitled'const ext = fileName.includes('.') ? fileName.split('.').pop()!.toLowerCase() : ''const isImage = ext in IMAGE_MIME+ // PDFs go to the platform's own viewer (zoom / search / pages / print all come for free)+ // instead of Monaco, which would render the binary as garbage text.+ const isPdf = ext === 'pdf'const togglePreview = () => {- if (isImage) return+ if (isImage || isPdf) returnsetPreview((p) => {const next = !pif (next && editorRef.current) setPreviewHtml(renderMarkdown(editorRef.current.getValue()))@@ -126,6 +132,48 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {}}+ // PDFs: read the bytes and hand them to the platform viewer as a blob URL. Deliberately the+ // same read path as images, which is what makes this work in an SSH project too — `fs` is the+ // remote fs there, so the bytes come back over the ControlMaster.+ if (isPdf) {+ let disposed = false+ let url = ''+ const readBinary = fs.readBinary+ if (typeof readBinary !== 'function') {+ setPdfError('PDF preview needs an app restart.')+ return+ }+ readBinary(filePath)+ .then((b64) => {+ if (disposed) return+ const tooBig = b64 ? tooLargeSize(b64) : null+ if (tooBig != null) {+ setPdfError(`PDF too large to preview (${formatBytes(tooBig)}).`)+ return+ }+ if (!b64) {+ setPdfError('Couldn’t read this PDF.')+ return+ }+ const made = pdfBlobUrl(b64)+ if (!made) {+ setPdfError('Couldn’t read this PDF.')+ return+ }+ url = made+ setPdfSrc(made)+ })+ .catch(() => {+ if (!disposed) setPdfError('Couldn’t read this PDF.')+ })+ return () => {+ disposed = true+ // A blob URL pins its bytes in memory until revoked — a few unclosed PDF nodes would+ // otherwise hold tens of MB each for the life of the window.+ if (url) URL.revokeObjectURL(url)+ }+ }+const el = bodyRef.currentif (!el) returnlet disposed = false@@ -198,12 +246,12 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {<div className="term-node__header"><span className="term-node__title-text" title={filePath}>{fileName}- {!isImage && dirty ? ' ●' : ''}+ {!isImage && !isPdf && dirty ? ' ●' : ''}</span><span className="term-node__spacer" />{fileMissing ? null : isImage ? (imageDims && <span className="editor-node__dims">{imageDims}</span>- ) : (+ ) : isPdf ? null : (<><buttonclassName="editor-node__toggle"@@ -253,6 +301,17 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {<span className="editor-node__loading">{imageError || 'Loading…'}</span>)}</div>+ ) : isPdf ? (+ // `nowheel` so scrolling pages the document instead of zooming the canvas, and the+ // iframe is the platform's own viewer (Chromium's on desktop, the browser's on the+ // Server Edition) — no bundled PDF engine of ours to keep patched.+ <div className="editor-node__pdf nodrag nowheel">+ {pdfSrc ? (+ <iframe src={pdfSrc} title={fileName} />+ ) : (+ <span className="editor-node__loading">{pdfError || 'Loading…'}</span>+ )}+ </div>) : loadError ? (<div className="editor-node__image nodrag"><span className="editor-node__loading">{loadError}</span>diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 13b108932..13e2bc0d7 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -2433,6 +2433,23 @@ body,border-radius: 4px;}+/* PDF: the viewer fills the node body — it brings its own toolbar, scrollbars and page chrome,+ so no padding or checkerboard here, and centering only applies to the loading/error text. */+.editor-node__pdf {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ background: #1a1a1a;+}++.editor-node__pdf iframe {+ width: 100%;+ height: 100%;+ border: 0;+}+.editor-node__loading {color: var(--muted);font-size: 12px;