an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
feat(ide): view images, name the agent in the title, surface real shortcuts
Chaitanya Girib81597a51f0e
diff --git a/package.json b/package.jsonindex 42f7ff4a..ce59c72b 100644--- a/package.json+++ b/package.json@@ -19,7 +19,7 @@"typecheck:node": "tsc --noEmit -p tsconfig.node.json","typecheck:web": "tsc --noEmit -p tsconfig.web.json","typecheck": "npm run typecheck:node && npm run typecheck:web",- "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/terminal-selection.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs",+ "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/terminal-selection.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs test/ide-image.test.cjs","check:links": "node tools/check-release-links.cjs","dist": "npm run build && electron-builder","dist:mac": "npm run build && electron-builder --mac",diff --git a/src/main/fs.ts b/src/main/fs.tsindex a868cd01..fbd2feca 100644--- a/src/main/fs.ts+++ b/src/main/fs.ts@@ -1,6 +1,7 @@import { readdir, readFile, writeFile, stat } from 'node:fs/promises';import { isAbsolute, join, normalize, relative, resolve } from 'node:path';import { homedir } from 'node:os';+import { imageMimeForPath } from '../shared/imageTypes';/*** Confines `path` inside `root` to prevent path-traversal escapes.@@ -71,6 +72,73 @@ export async function readFileText(root: string, rel: string): Promise<{}}+/**+ * Ceiling for the BINARY read. Deliberately larger than MAX_READ_BYTES (2 MB):+ * that cap exists to stop Monaco choking on a huge text buffer, and applying it+ * to images would reject the exact files people want to look at — a retina+ * screenshot of a full 5K display is routinely 3–6 MB. 10 MB covers real+ * screenshots and design assets while still refusing to hand the renderer a+ * video-sized payload over structured clone.+ */+const MAX_BINARY_READ_BYTES = 10 * 1024 * 1024; // 10 MB++/**+ * Read a file as raw BYTES, confined to `root` by the same `safeJoin` guard as+ * every other fs entry point here.+ *+ * Exists because the text path deliberately refuses binary content (the+ * null-byte sniff in readFileText), which meant a PNG in an agent's workspace+ * was completely unviewable inside the app — the IDE opened a tab that said+ * "binary file (not displayable)" and stopped there. The renderer cannot reach+ * the file itself: the CSP is `default-src 'self'` with no `file:` source and+ * there is no registered file protocol, so `<img src="file://…">` silently+ * fails. Bytes therefore have to travel over IPC, and the renderer turns them+ * into a `blob:` URL (already allowed by `img-src`).+ *+ * NEVER reads unbounded: the size is checked from stat BEFORE opening, and+ * re-checked against the bytes actually read so a file that grows between the+ * two calls can't slip past the cap.+ */+export async function readFileBinary(root: string, rel: string, maxBytes = MAX_BINARY_READ_BYTES): Promise<{+ ok: true; bytes: Uint8Array<ArrayBuffer>; mime: string; path: string; size: number;+} | { ok: false; error: string }> {+ const abs = safeJoin(root, rel);+ if (!abs) return { ok: false, error: 'path escapes root' };+ try {+ const s = await stat(abs);+ // Directories and FIFOs are the trap here: readFile on a directory throws+ // (fine) but on a FIFO it BLOCKS forever with no size to check against, which+ // would hang the IPC call and, with it, the renderer's loading state.+ if (!s.isFile()) return { ok: false, error: 'not a regular file' };+ if (s.size > maxBytes) {+ return { ok: false, error: `file too large (${(s.size / 1024 / 1024).toFixed(1)} MB)` };+ }+ const buf = await readFile(abs);+ if (buf.byteLength > maxBytes) {+ // The file grew between stat and read. Rare, but the cap is a memory+ // guarantee for the renderer, not an advisory.+ return { ok: false, error: 'file grew past the size limit while reading' };+ }+ // COPY into a freshly-allocated Uint8Array instead of forwarding the Buffer.+ // Node serves small reads out of a shared 8 KB Buffer pool, so a pooled+ // Buffer is a VIEW onto memory that also holds unrelated recently-read+ // bytes; structured-clone carries the whole backing ArrayBuffer across the+ // IPC boundary, not just the view. Copying keeps the renderer's payload+ // exactly the file and nothing else.+ const bytes = new Uint8Array(buf.byteLength);+ bytes.set(buf);+ return {+ ok: true,+ bytes,+ mime: imageMimeForPath(abs) ?? 'application/octet-stream',+ path: abs,+ size: s.size+ };+ } catch (e) {+ return { ok: false, error: e instanceof Error ? e.message : String(e) };+ }+}+export async function writeFileText(root: string, rel: string, content: string): Promise<{ok: true; path: string;} | { ok: false; error: string }> {diff --git a/src/main/index.ts b/src/main/index.tsindex 78bfd88b..ab8839a9 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -16,7 +16,7 @@ import {readConfig, writeConfig, resetConfig, ensureHarnessHome, ensureClaudePermissionsAccepted,modelForRole, OPS_STANDUP_MISSION, HEARTBEAT_MISSION, COMPACT_MAINTENANCE_MISSION, type HarnessConfig, type ScheduledMission} from './config';-import { listDir, readFileText, writeFileText, statAbs, expandTilde } from './fs';+import { listDir, readFileText, readFileBinary, writeFileText, statAbs, expandTilde } from './fs';import {getBranch, getStatus, getLog, getBranches, getAheadBehind, isRepo, getDiff, mainRepoRoot,addWorktree, removeWorktree, worktreeHasUnintegratedWork, worktreeIsGcSafe,@@ -2989,6 +2989,14 @@ ipcMain.handle('fs:readFile', (_evt, root: unknown, rel: unknown) => {if (typeof root !== 'string' || typeof rel !== 'string') return { ok: false, error: 'invalid args' };return readFileText(root, rel);});+// Raw bytes for files the text reader refuses (images). The renderer cannot+// load them off disk itself — the CSP has no `file:` source and no file+// protocol is registered — so the bytes come through here and become a `blob:`+// URL on the other side. Same root confinement as every other fs handler.+ipcMain.handle('fs:readBinary', (_evt, root: unknown, rel: unknown) => {+ if (typeof root !== 'string' || typeof rel !== 'string') return { ok: false, error: 'invalid args' };+ return readFileBinary(root, rel);+});ipcMain.handle('fs:writeFile', (_evt, root: unknown, rel: unknown, content: unknown) => {if (typeof root !== 'string' || typeof rel !== 'string' || typeof content !== 'string') {return { ok: false, error: 'invalid args' };diff --git a/src/preload/index.ts b/src/preload/index.tsindex ca355ebf..b174552c 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -647,6 +647,19 @@ const api = {readFile: (root: string, rel: string): Promise<{ ok: true; content: string; path: string; size: number } | { ok: false; error: string }> => ipcRenderer.invoke('fs:readFile', root, rel),+ /** Raw bytes for files `readFile` refuses (images). The renderer has no way to+ * load them off disk — the CSP allows no `file:` source and no file protocol+ * is registered — so images travel as bytes and become a `blob:` URL in the+ * renderer, which `img-src` already permits. Root-confined and size-capped in+ * the main process; `mime` is derived from the extension. */+ readBinary: (root: string, rel: string): Promise<+ // `Uint8Array<ArrayBuffer>`, not the bare alias: structured clone always+ // hands the renderer a view over a plain ArrayBuffer, and saying so is what+ // lets the value go straight into `new Blob([...])` — the default+ // `ArrayBufferLike` admits SharedArrayBuffer, which BlobPart rejects.+ { ok: true; bytes: Uint8Array<ArrayBuffer>; mime: string; path: string; size: number }+ | { ok: false; error: string }+ > => ipcRenderer.invoke('fs:readBinary', root, rel),writeFile: (root: string, rel: string, content: string): Promise<{ ok: true; path: string } | { ok: false; error: string }> => ipcRenderer.invoke('fs:writeFile', root, rel, content),diff --git a/src/renderer/src/components/AgentDetailPanel.tsx b/src/renderer/src/components/AgentDetailPanel.tsxindex b1b73ed8..890f30f1 100644--- a/src/renderer/src/components/AgentDetailPanel.tsx+++ b/src/renderer/src/components/AgentDetailPanel.tsx@@ -119,7 +119,7 @@ export function AgentDetailPanel({ agent }: AgentDetailPanelProps) {</div>{/* v0.3.4: the IDE lives at agent level (replaces the old files tab) —opens the full-window Monaco editor rooted at this agent's workspace. */}- <PixelButton variant="secondary" size="sm" onClick={() => useStore.getState().setIdeOpen(true)}>+ <PixelButton variant="secondary" size="sm" onClick={() => useStore.getState().setIdeOpen(true, agent.id)}><span title={`Open the IDE — file editor + git diff for ${agent.project}`} style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="code" /> IDE</span>diff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsxindex ccdf6de9..da7dfc20 100644--- a/src/renderer/src/components/CommandCenterPanel.tsx+++ b/src/renderer/src/components/CommandCenterPanel.tsx@@ -197,7 +197,13 @@ export function CommandCenterPanel({ agent, fullscreen = false }: { agent: Agent{floorDeliveryPaused ? 'paused' : 'auto'}</span></PixelButton>- <PixelButton variant="secondary" size="sm" onClick={() => useStore.getState().setIdeOpen(true)}>+ {/* Floor-level surface with no agent of its own: the honest target is+ whoever is selected, stated explicitly rather than left to the+ IDE's fallback so the intent is visible at the call site. */}+ <PixelButton variant="secondary" size="sm" onClick={() => {+ const s = useStore.getState();+ s.setIdeOpen(true, s.selectedId);+ }}><span title="Open the IDE — file editor + git diff" style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="code" /> IDE</span>diff --git a/src/renderer/src/components/FullscreenFileEditor.tsx b/src/renderer/src/components/FullscreenFileEditor.tsxindex a91c0a15..be949bc3 100644--- a/src/renderer/src/components/FullscreenFileEditor.tsx+++ b/src/renderer/src/components/FullscreenFileEditor.tsx@@ -48,7 +48,10 @@ export function FullscreenFileEditor() {const s = useStore.getState();s.setIdeInitialFile(fullscreenFilePath);s.setFullscreenFile(null);- s.setIdeOpen(true);+ // The owning agent is already resolved above (it is how `root` was derived),+ // so hand it over instead of making the IDE re-guess from the selection —+ // this overlay is often reached from a terminal link with nothing selected.+ s.setIdeOpen(true, matchedAgent?.id ?? null);};const chip: React.CSSProperties = {@@ -152,7 +155,10 @@ function SavedFilePreview({ root, rel }: { root: string; rel: string }) {}return (<div style={{ display: 'flex', justifyContent: 'center' }}>- <MarkdownPreview source={state.content} baseRel={rel} />+ {/* `root` is what lets screenshots referenced by the report actually+ render — it is the same root this component already reads through, so+ images are confined to exactly the tree the text came from. */}+ <MarkdownPreview source={state.content} baseRel={rel} root={root} /></div>);}diff --git a/src/renderer/src/components/FullscreenTerminal.tsx b/src/renderer/src/components/FullscreenTerminal.tsxindex 8a4eaa11..37f89f07 100644--- a/src/renderer/src/components/FullscreenTerminal.tsx+++ b/src/renderer/src/components/FullscreenTerminal.tsx@@ -808,8 +808,11 @@ function Header({ agent }: { agent: Agent }) {}}>“{agent.description}”</span><div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 6 }}>{/* v0.3.4: the IDE opens from agent level — full Monaco editor + git- diff over this agent's workspace. */}- <PixelButton variant="secondary" size="sm" onClick={() => useStore.getState().setIdeOpen(true)}>+ diff over this agent's workspace. The id is passed EXPLICITLY:+ fullscreen does not change the selection, so leaving the IDE to infer+ its agent would open whichever agent happens to be selected in the+ sidebar rather than the one filling the screen. */}+ <PixelButton variant="secondary" size="sm" onClick={() => useStore.getState().setIdeOpen(true, agent.id)}><span title="Open the IDE — file editor + git diff" style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="code" /> IDE</span>diff --git a/src/renderer/src/components/Icon.tsx b/src/renderer/src/components/Icon.tsxindex fdb0ebc3..323b5897 100644--- a/src/renderer/src/components/Icon.tsx+++ b/src/renderer/src/components/Icon.tsx@@ -6,7 +6,8 @@ import { CSSProperties } from 'react';export type IconName =| 'gear' | 'plus' | 'x' | 'check' | 'arrow-right' | 'pause' | 'play'| 'bell' | 'folder' | 'terminal' | 'code' | 'web' | 'mcp' | 'sparkle'- | 'expand' | 'minimize' | 'clock' | 'mic' | 'ledger' | 'info' | 'sidebar';+ | 'expand' | 'minimize' | 'clock' | 'mic' | 'ledger' | 'info' | 'sidebar'+ | 'image';interface IconDef {ink: string; // primary color path d@@ -54,6 +55,14 @@ const paths: Record<IconName, IconDef> = {accentColor: 'var(--cth-lemon)',ink: 'M1 3h6v1h8v9H1V3zm1 1v8h12V5H6V4H2z'},+ // Picture frame with a stepped mountain and a sun. The frame's two subpaths+ // cut a hole via evenodd (same trick as `terminal`); the mountain rows sit+ // inside that hole, so each adds a third crossing and fills again.+ image: {+ accentColor: 'var(--cth-lemon)',+ accent: 'M4 5h2v2H4V5z',+ ink: 'M1 2h14v12H1V2zm1 1v10h12V3H2zM8 6h2v1H8zM7 7h4v1H7zM6 8h6v1H6zM5 9h8v1H5zM4 10h9v2H4z'+ },terminal: {accentColor: 'var(--cth-mint)',ink: 'M1 2h14v12H1V2zm1 1v10h12V3H2zm1 2h1v1h1v1h1v1H5v1H4v1H3V9h1V8h1V7H4V6H3V5zm5 5h4v1H8v-1z'diff --git a/src/renderer/src/design/global.css b/src/renderer/src/design/global.cssindex b7a23ce1..63e52d60 100644--- a/src/renderer/src/design/global.css+++ b/src/renderer/src/design/global.css@@ -187,6 +187,15 @@ canvas, img, svg { image-rendering: pixelated; image-rendering: crisp-edges; }}.cth-md-preview th { background: var(--cth-cream-200); font-weight: 600; }.cth-md-preview hr { border: none; border-top: 1px solid var(--cth-ink-100); margin: 1.4em 0; }+/* Real (local) images inside rendered markdown. `max-width: 100%` is the whole+ trick: agent screenshots are routinely 3000px wide and would otherwise force+ a horizontal scrollbar on the entire preview pane. The hairline gives a light+ screenshot an edge against the paper background so it doesn't bleed away. */+.cth-md-preview .cth-md-image {+ display: block; max-width: 100%; height: auto; margin: 0.6em 0;+ box-shadow: inset 0 0 0 1px var(--cth-ink-100);+ border-radius: 2px;+}.cth-md-preview .cth-md-img {display: inline-block; padding: 2px 8px; font-size: 12px;background: var(--cth-cream-200); box-shadow: inset 0 0 0 1px var(--cth-ink-100);diff --git a/src/renderer/src/hooks/useWorkspaceImage.ts b/src/renderer/src/hooks/useWorkspaceImage.tsnew file mode 100644index 00000000..677e1178--- /dev/null+++ b/src/renderer/src/hooks/useWorkspaceImage.ts@@ -0,0 +1,67 @@+/**+ * Load a workspace image over IPC and hand back a `blob:` URL for it.+ *+ * WHY A HOOK, AND WHY BLOB: the renderer cannot read the disk. The CSP is+ * `default-src 'self'` with `img-src 'self' data: blob:` and the app registers+ * no file protocol, so `<img src="file:///…">` fails silently — the classic+ * dead end for "why is my screenshot blank". Bytes therefore come over+ * `fs:readBinary` and get wrapped locally.+ *+ * `blob:` over `data:`: a data URI base64-encodes the payload, inflating a 6 MB+ * screenshot to ~8 MB of JavaScript STRING that lives in the heap for as long as+ * the element does, and re-decodes on every render. A blob URL is a handle to+ * bytes the browser already holds, and it is cheap to pass around.+ *+ * The catch — and the reason every consumer must go through this hook — is that+ * a blob URL is a document-scoped registration that is NOT garbage collected+ * when the <img> disappears. The IDE opens and closes image tabs, and a markdown+ * report can hold a dozen screenshots; without an explicit revoke, every open+ * would strand its bytes for the lifetime of the window. The effect cleanup here+ * is the only revoke site, so "mounted" and "URL alive" are the same interval by+ * construction.+ *+ * SVG note: an SVG loaded through <img> renders in the browser's static secure+ * mode — no scripts, no external fetches — so agent-authored SVGs are safe to+ * display this way even though their source is executable-looking markup.+ */+import { useEffect, useState } from 'react';++export type WorkspaceImageState =+ | { status: 'loading' }+ | { status: 'ready'; url: string; mime: string; size: number }+ | { status: 'error'; error: string };++export function useWorkspaceImage(+ root: string | null | undefined,+ rel: string | null | undefined+): WorkspaceImageState {+ const [state, setState] = useState<WorkspaceImageState>({ status: 'loading' });++ useEffect(() => {+ if (!root || !rel) {+ setState({ status: 'error', error: 'no file' });+ return;+ }+ let alive = true;+ let created: string | null = null;+ setState({ status: 'loading' });++ void window.cth.readBinary(root, rel).then((res) => {+ // Bail BEFORE creating the URL when the consumer already unmounted — a URL+ // created after cleanup has run would never be revoked by anyone.+ if (!alive) return;+ if (!res.ok) { setState({ status: 'error', error: res.error }); return; }+ created = URL.createObjectURL(new Blob([res.bytes], { type: res.mime }));+ setState({ status: 'ready', url: created, mime: res.mime, size: res.size });+ }).catch((e: unknown) => {+ if (alive) setState({ status: 'error', error: e instanceof Error ? e.message : String(e) });+ });++ return () => {+ alive = false;+ if (created) URL.revokeObjectURL(created);+ };+ }, [root, rel]);++ return state;+}diff --git a/src/renderer/src/ide/IdePanel.tsx b/src/renderer/src/ide/IdePanel.tsxindex 8e11f98b..00f0e4f9 100644--- a/src/renderer/src/ide/IdePanel.tsx+++ b/src/renderer/src/ide/IdePanel.tsx@@ -1,11 +1,14 @@import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';-import { useStore } from '@/store/store';+import { useStore, type Agent } from '@/store/store';import { FileTree } from '@/components/FileTree';import { Icon } from '@/components/Icon';import { MonacoEditor } from './MonacoEditor';import { MonacoDiff } from './MonacoDiff';+import { ImagePreview } from './ImagePreview';import { MarkdownPreview } from '@/markdown/MarkdownPreview';import { HistoryPane, ComparePane } from './GitPanes';+import { isImagePath, isSvgPath } from '@shared/imageTypes';+import { ideBarStyle, ideIconBtn as iconBtn, ideTextBtn as textBtn } from './chrome';// v0.3.4 markdown preview: per-md-tab view mode, defaulted from the last choice.type MdView = 'code' | 'split' | 'preview';@@ -26,7 +29,7 @@ const GIT_RAIL_COLLAPSED_KEY = 'cth.ide.gitRailCollapsed';interface GitStatusEntry { path: string; index: string; worktree: string }interface GitStatusT { staged: GitStatusEntry[]; unstaged: GitStatusEntry[]; untracked: string[] }-type TabMode = 'edit' | 'diff' | 'revdiff';+type TabMode = 'edit' | 'diff' | 'revdiff' | 'image';interface Tab {key: string; rel: string; mode: TabMode;/** revdiff only: the two sides + a short human label ("a1b2c3d" / "main…feat"). */@@ -59,18 +62,40 @@ function statusColor(code: string): string {return 'var(--cth-ink-500)';}-/** Snapshot the workspace root once at mount: the selected agent's cwd, else the- * god agent's cwd, else the first agent's. The IDE is a full-window overlay, so- * the user can't switch agents while it's open — a stable root is correct. */-function pickRoot(): string | null {+/** Which agent's workspace the IDE is showing, and how confidently we know it. */+interface IdeTarget {+ agent: Agent | null;+ root: string | null;+ /** True when NOBODY told us which agent this is and we had to guess. The+ * guess is usually right, but the title says so rather than asserting a name+ * it cannot stand behind. */+ inferred: boolean;+}++/** Snapshot the IDE's target once at mount. The IDE is a full-window overlay, so+ * the user can't switch agents while it's open — a stable target is correct.+ *+ * Preference order, most-trustworthy first:+ * 1. `ideAgentId` — the opener said exactly who this is for.+ * 2. the current selection — right for anything opened off the sidebar.+ * 3. the god agent, then the first agent — last resorts so the IDE still+ * opens on *something* browsable instead of an empty shell.+ * Everything past (1) is marked `inferred`, because those paths are exactly the+ * ones that can disagree with what the user was actually looking at. */+function pickIdeTarget(): IdeTarget {const s = useStore.getState();- const sel = s.selectedId ? s.agents.find((a) => a.id === s.selectedId) : null;- return sel?.cwd ?? s.agents.find((a) => a.isGod)?.cwd ?? s.agents[0]?.cwd ?? null;+ const byId = (id: string | null): Agent | null => (id ? s.agents.find((a) => a.id === id) ?? null : null);+ const named = byId(s.ideAgentId);+ if (named?.cwd) return { agent: named, root: named.cwd, inferred: false };+ const guess = byId(s.selectedId) ?? s.agents.find((a) => a.isGod) ?? s.agents[0] ?? null;+ if (guess?.cwd) return { agent: guess, root: guess.cwd, inferred: true };+ return { agent: null, root: null, inferred: false };}export function IdePanel() {const setIdeOpen = useStore((s) => s.setIdeOpen);- const [root] = useState<string | null>(pickRoot);+ const [target] = useState<IdeTarget>(pickIdeTarget);+ const root = target.root;const [tabs, setTabs] = useState<Tab[]>([]);const [activeKey, setActiveKey] = useState<string | null>(null);@@ -162,7 +187,19 @@ export function IdePanel() {setActiveKey(key);}, []);- const openEdit = useCallback((rel: string) => { ensureEdit(rel); openTab('edit', rel); }, [ensureEdit, openTab]);+ /** Force a file into Monaco regardless of type — the "view source" escape+ * hatch behind the image preview. */+ const openSource = useCallback((rel: string) => { ensureEdit(rel); openTab('edit', rel); }, [ensureEdit, openTab]);++ /** The default open. Images go to the preview instead of Monaco: routing them+ * through `ensureEdit` is what produced the old "binary file (not+ * displayable)" tab, since the text reader rejects anything with a null byte.+ * SVG has no null bytes and so used to open as unhighlighted plaintext — it+ * is a picture first here too, with `view source` one click away. */+ const openEdit = useCallback((rel: string) => {+ if (isImagePath(rel)) { openTab('image', rel); return; }+ openSource(rel);+ }, [openSource, openTab]);// v0.3.4: rev-pinned diff tabs (per-commit files + branch compare). Both// sides load through the metadata-guarded git:showFile IPC at the MAIN root.@@ -204,10 +241,11 @@ export function IdePanel() {const prefix = root.endsWith('/') ? root : `${root}/`;if (!abs.startsWith(prefix)) return; // different workspace — tree still lets them browseconst rel = abs.slice(prefix.length);- ensureEdit(rel);- openTab('edit', rel);+ // Same routing as a tree click — an "open in IDE" on a screenshot must land+ // on the preview, not on a tab that refuses to display it.+ openEdit(rel);if (isMarkdown(rel)) setMdViews((p) => ({ ...p, [rel]: 'preview' }));- }, [root, ensureEdit, openTab]);+ }, [root, openEdit]);const openDiff = useCallback((rel: string) => { ensureDiff(rel, true); openTab('diff', rel); }, [ensureDiff, openTab]);const closeTab = useCallback((key: string) => {@@ -303,7 +341,11 @@ export function IdePanel() {if (root) navigator.clipboard.writeText(rel ? `${root}/${rel}` : root).catch(() => { /* noop */ });};- const activeEditRel = activeTab?.mode === 'edit' ? activeTab.rel : undefined;+ // Image tabs highlight in the tree too — the tree's job is "what am I looking+ // at", and an image is as much "open" as a text file is.+ const activeEditRel = activeTab && (activeTab.mode === 'edit' || activeTab.mode === 'image')+ ? activeTab.rel+ : undefined;return (<div style={{@@ -329,9 +371,46 @@ export function IdePanel() {}}>MUNDER DIFFLIN · IDE</span>+ {/* WHOSE workspace this is. The folder name alone was ambiguous the+ moment two agents shared a repo (worktrees named for the branch, not+ the agent) or an agent worked in a generically-named directory —+ "src" tells you nothing about which of eight agents you are editing+ under. Name first, directory second: the name is the identity, the+ path is the detail. */}+ {target.agent ? (+ <span style={{ display: 'inline-flex', alignItems: 'baseline', gap: 6, minWidth: 0 }}>+ <span+ title={target.inferred+ ? `No agent was named when the IDE opened — showing ${target.agent.name}'s workspace (the current selection)`+ : `${target.agent.name}'s workspace`}+ style={{+ fontFamily: 'var(--cth-font-ui)', fontSize: 13, fontWeight: 600,+ color: 'var(--cth-ink-900)',+ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '22vw'+ }}+ >{target.agent.name}</span>+ {target.agent.isGod && (+ <span style={{+ fontFamily: 'var(--cth-font-display)', fontSize: 7, padding: '1px 3px',+ background: 'var(--cth-lilac-light)', color: 'var(--cth-ink-900)'+ }}>god</span>+ )}+ {target.inferred && (+ // Never assert a name we had to guess at. One quiet word is enough+ // to stop someone trusting the wrong agent's directory.+ <span style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 11, color: 'var(--cth-ink-500)' }}>+ (assumed)+ </span>+ )}+ </span>+ ) : (+ <span style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 13, color: 'var(--cth-ink-500)' }}>+ no agent+ </span>+ )}<span title={root ?? ''} style={{fontFamily: 'var(--cth-font-mono)', fontSize: 13, color: 'var(--cth-ink-500)',- whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '40vw'+ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '30vw'}}>{root ? basename(root) : 'no workspace'}</span>@@ -497,9 +576,11 @@ export function IdePanel() {{t.mode !== 'edit' && (<span style={{fontFamily: 'var(--cth-font-display)', fontSize: 7, padding: '1px 3px',- background: t.mode === 'revdiff' ? 'var(--cth-lilac-light)' : 'var(--cth-sky-light)',+ background: t.mode === 'revdiff' ? 'var(--cth-lilac-light)'+ : t.mode === 'image' ? 'var(--cth-peach-light)'+ : 'var(--cth-sky-light)',color: 'var(--cth-ink-900)'- }}>{t.mode === 'revdiff' ? (t.revLabel ?? 'REV') : 'DIFF'}</span>+ }}>{t.mode === 'revdiff' ? (t.revLabel ?? 'REV') : t.mode === 'image' ? 'IMG' : 'DIFF'}</span>)}<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{basename(t.rel)}{dirty ? ' •' : ''}@@ -531,9 +612,22 @@ export function IdePanel() {<div style={{ fontFamily: 'var(--cth-font-ui)', fontSize: 13 }}>Pick a file from the tree to edit, or a changed file to diff.</div>+ <ShortcutHint /></div>)}+ {activeTab?.mode === 'image' && root && (+ <ImagePreview+ // Keyed by path so switching image tabs tears the previous+ // preview down — that unmount is what revokes its blob URL.+ key={activeTab.key}+ root={root}+ rel={activeTab.rel}+ onCopyPath={() => copyAbs(activeTab.rel)}+ onViewSource={isSvgPath(activeTab.rel) ? () => openSource(activeTab.rel) : undefined}+ />+ )}+{activeTab?.mode === 'edit' && (() => {const buf = editBuffers[activeTab.rel];if (!buf || buf.status === 'loading') return <Centered>loading…</Centered>;@@ -550,6 +644,8 @@ export function IdePanel() {onCopy={() => copyAbs(activeTab.rel)}mdView={md ? view : undefined}onMdView={md ? (v) => setMdView(activeTab.rel, v) : undefined}+ // The return leg of the SVG round trip: source ⇄ picture.+ onViewImage={isImagePath(activeTab.rel) ? () => openTab('image', activeTab.rel) : undefined}/><div style={{ flex: 1, minHeight: 0, display: 'flex' }}>{view !== 'preview' && (@@ -565,12 +661,12 @@ export function IdePanel() {{md && view !== 'code' && (<MdPanerel={activeTab.rel}+ root={root}source={buf.content}split={view === 'split'}- onOpenMarkdownLink={(target) => {- ensureEdit(target);- openTab('edit', target);- setMdViews((p) => ({ ...p, [target]: 'preview' }));+ onOpenMarkdownLink={(link) => {+ openSource(link);+ setMdViews((p) => ({ ...p, [link]: 'preview' }));}}/>)}@@ -656,17 +752,15 @@ function SectionHeader({ title, right }: { title: string; right?: React.ReactNod);}-function EditorBar({ rel, dirty, saveState, onSave, onCopy, mdView, onMdView }: {+function EditorBar({ rel, dirty, saveState, onSave, onCopy, mdView, onMdView, onViewImage }: {rel: string; dirty: boolean; saveState: EditBuffer['saveState']; onSave: () => void; onCopy: () => void;/** Set only for markdown files — renders the code|split|preview switch. */mdView?: MdView; onMdView?: (v: MdView) => void;+ /** Set only for files that are ALSO images (SVG) — jumps back to the picture. */+ onViewImage?: () => void;}) {return (- <div style={{- display: 'flex', alignItems: 'center', gap: 6, padding: '3px 8px',- background: 'var(--cth-cream-200)', borderBottom: '1px solid var(--cth-ink-700)',- fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-ink-700)'- }}>+ <div style={ideBarStyle}><Icon name="code" /><span style={{ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', fontFamily: 'var(--cth-font-mono)' }} title={rel}>{rel}{dirty ? ' •' : ''}@@ -687,6 +781,9 @@ function EditorBar({ rel, dirty, saveState, onSave, onCopy, mdView, onMdView }:))}</span>)}+ {onViewImage && (+ <button onClick={onViewImage} title="Show this file as an image" style={textBtn}>view image</button>+ )}<button onClick={onCopy} title="Copy absolute path" style={textBtn}>copy path</button><button onClick={onSave} disabled={!dirty || saveState === 'saving'} title="Save (Cmd/Ctrl+S)"style={{ ...textBtn, opacity: dirty ? 1 : 0.5 }}>@@ -699,8 +796,8 @@ function EditorBar({ rel, dirty, saveState, onSave, onCopy, mdView, onMdView }:/** Markdown preview pane — renders the LIVE edit buffer (deferred so fast typing* never blocks the editor). In split view it takes the right half behind a* hairline divider; in preview view it fills the body. */-function MdPane({ rel, source, split, onOpenMarkdownLink }: {- rel: string; source: string; split: boolean; onOpenMarkdownLink: (rel: string) => void;+function MdPane({ rel, root, source, split, onOpenMarkdownLink }: {+ rel: string; root: string; source: string; split: boolean; onOpenMarkdownLink: (rel: string) => void;}) {const deferred = useDeferredValue(source);return (@@ -709,11 +806,64 @@ function MdPane({ rel, source, split, onOpenMarkdownLink }: {background: 'var(--cth-paper-100)',borderLeft: split ? '1px solid var(--cth-ink-100)' : 'none'}}>- <MarkdownPreview source={deferred} baseRel={rel} onOpenMarkdownLink={onOpenMarkdownLink} />+ {/* `root` is what lets a report's screenshots render inline instead of+ collapsing to placeholder chips. */}+ <MarkdownPreview source={deferred} baseRel={rel} root={root} onOpenMarkdownLink={onOpenMarkdownLink} /></div>);}+/**+ * The IDE's empty state doubles as the only place these capabilities are+ * advertised.+ *+ * Monaco ships find/replace, a command palette and go-to-line/symbol, all of+ * which have worked here since the editor landed — and essentially nobody knew,+ * because the panel never mentioned them and there is no menu bar to discover+ * them from. People asked for "search in the IDE" while ⌘F was already bound.+ * (Repo-wide search is genuinely absent; this hint deliberately promises only+ * what exists.)+ *+ * Kept as a muted list under the empty state rather than a banner: it is the one+ * moment the pane has nothing to say, and it must not compete with an open file.+ */+function ShortcutHint() {+ return (+ <div style={{+ marginTop: 10, display: 'grid', gap: 2, justifyItems: 'center',+ fontFamily: 'var(--cth-font-ui)', fontSize: 11, color: 'var(--cth-ink-300)'+ }}>+ {EDITOR_SHORTCUTS.map(([keys, label]) => (+ <div key={label} style={{ display: 'flex', gap: 6, alignItems: 'baseline' }}>+ <span style={{ fontFamily: 'var(--cth-font-mono)', color: 'var(--cth-ink-500)' }}>{keys}</span>+ <span>{label}</span>+ </div>+ ))}+ </div>+ );+}++/** Electron reports the host platform in the UA; there is no platform helper in+ * the renderer, and printing ⌘ to a Linux user would be worse than useless. */+const IS_MAC = typeof navigator !== 'undefined' && /mac/i.test(navigator.userAgent);++/** Monaco's own default bindings — do not invent entries here. */+const EDITOR_SHORTCUTS: ReadonlyArray<readonly [string, string]> = IS_MAC+ ? [+ ['⌘F', 'find in file'],+ ['⌥⌘F', 'replace'],+ ['F1', 'command palette'],+ ['⌃G', 'go to line'],+ ['⇧⌘O', 'go to symbol']+ ]+ : [+ ['Ctrl+F', 'find in file'],+ ['Ctrl+H', 'replace'],+ ['F1', 'command palette'],+ ['Ctrl+G', 'go to line'],+ ['Ctrl+Shift+O', 'go to symbol']+ ];+function Centered({ children, tone }: { children: React.ReactNode; tone?: 'error' }) {return (<div style={{@@ -723,15 +873,3 @@ function Centered({ children, tone }: { children: React.ReactNode; tone?: 'error}}>{children}</div>);}--const iconBtn: React.CSSProperties = {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- padding: 0, width: 18, height: 18, background: 'transparent', border: 'none',- cursor: 'pointer', color: 'var(--cth-ink-500)'-};-const textBtn: React.CSSProperties = {- padding: '0 6px', height: 20, fontFamily: 'var(--cth-font-ui)', fontSize: 12,- color: 'var(--cth-ink-900)', background: 'var(--cth-cream-100)', border: 'none',- boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)', cursor: 'pointer',- display: 'inline-flex', alignItems: 'center', gap: 4-};diff --git a/src/renderer/src/ide/ImagePreview.tsx b/src/renderer/src/ide/ImagePreview.tsxnew file mode 100644index 00000000..fe4ea3ed--- /dev/null+++ b/src/renderer/src/ide/ImagePreview.tsx@@ -0,0 +1,139 @@+/**+ * Image tab body for the IDE.+ *+ * Replaces the dead end this app used to have: opening a .png in the IDE created+ * a tab whose entire content was the red text "binary file (not displayable)",+ * because the only file reader available refused anything with a null byte. That+ * made screenshots — the single most common non-text artefact an agent writes —+ * invisible inside the product that produced them.+ *+ * The bytes arrive over IPC and are held as a `blob:` URL by useWorkspaceImage,+ * which owns revocation (see the note there: blob URLs outlive the elements that+ * reference them, and IDE tabs open and close all day).+ *+ * The bar deliberately mirrors the editor's bar minus Save — nothing here is+ * editable — so the tab strip reads as one surface rather than two.+ */+import { useState } from 'react';+import { Icon } from '@/components/Icon';+import { useWorkspaceImage } from '@/hooks/useWorkspaceImage';+import { formatBytes, isSvgPath } from '@shared/imageTypes';+import { ideBarStyle, ideTextBtn } from './chrome';++export interface ImagePreviewProps {+ /** Absolute workspace root the path is confined to. */+ root: string;+ /** Workspace-relative path of the image. */+ rel: string;+ /** Copy the absolute path (same affordance as the editor bar). */+ onCopyPath: () => void;+ /** Open this file in Monaco instead. Present for SVG, whose source is+ * hand-edited often enough that a read-only preview would be a regression. */+ onViewSource?: () => void;+}++export function ImagePreview({ root, rel, onCopyPath, onViewSource }: ImagePreviewProps) {+ const img = useWorkspaceImage(root, rel);+ // Fit is the default because the common case is a full-screen screenshot that+ // is far wider than the pane; showing it at 1:1 first would open every tab+ // scrolled into the top-left corner of a picture nobody can see the shape of.+ const [fit, setFit] = useState(true);+ const [dims, setDims] = useState<{ w: number; h: number } | null>(null);+ const [decodeFailed, setDecodeFailed] = useState(false);++ return (+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>+ <div style={ideBarStyle}>+ <Icon name="image" />+ <span+ style={{ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', fontFamily: 'var(--cth-font-mono)' }}+ title={rel}+ >{rel}</span>++ {/* Facts about the file, in the same muted register as the diff bar's+ HEAD → working tree label. Dimensions only exist once the image has+ actually decoded, so this stays honest about what is known. */}+ <span style={{ fontFamily: 'var(--cth-font-mono)', fontSize: 11, color: 'var(--cth-ink-500)', whiteSpace: 'nowrap' }}>+ {dims ? `${dims.w}×${dims.h}` : '—'}+ {img.status === 'ready' ? ` · ${formatBytes(img.size)}` : ''}+ </span>++ <span style={{ display: 'inline-flex', gap: 0 }}>+ {([true, false] as const).map((v) => (+ <button+ key={String(v)}+ onClick={() => setFit(v)}+ title={v ? 'Scale the image down to fit the pane' : 'Show every pixel at 1:1 (scroll to pan)'}+ style={{+ ...ideTextBtn,+ background: fit === v ? 'var(--cth-sky-light)' : 'var(--cth-cream-100)',+ boxShadow: fit === v ? 'inset 0 0 0 1px var(--cth-ink-500)' : 'inset 0 0 0 1px var(--cth-ink-100)'+ }}+ >{v ? 'fit' : '1:1'}</button>+ ))}+ </span>++ {onViewSource && (+ <button onClick={onViewSource} title="Open the SVG markup in the editor" style={ideTextBtn}>+ view source+ </button>+ )}+ <button onClick={onCopyPath} title="Copy absolute path" style={ideTextBtn}>copy path</button>+ </div>++ <div style={{+ flex: 1, minHeight: 0, overflow: 'auto',+ display: 'flex', alignItems: fit ? 'center' : 'flex-start', justifyContent: fit ? 'center' : 'flex-start',+ padding: 16,+ // A checkerboard, not a flat fill: transparent PNGs are everywhere in+ // agent output (icons, cropped screenshots) and on a plain background a+ // transparent region is indistinguishable from a white or black one.+ // Both tones are tokens, so the board inverts with the theme instead of+ // glowing white in dark mode.+ backgroundColor: 'var(--cth-paper-100)',+ backgroundImage: `+ linear-gradient(45deg, var(--cth-cream-200) 25%, transparent 25%),+ linear-gradient(-45deg, var(--cth-cream-200) 25%, transparent 25%),+ linear-gradient(45deg, transparent 75%, var(--cth-cream-200) 75%),+ linear-gradient(-45deg, transparent 75%, var(--cth-cream-200) 75%)`,+ backgroundSize: '16px 16px',+ backgroundPosition: '0 0, 0 8px, 8px -8px, -8px 0px'+ }}>+ {img.status === 'loading' && <Centered>loading image…</Centered>}+ {img.status === 'error' && <Centered tone="error">{img.error}</Centered>}+ {img.status === 'ready' && decodeFailed && (+ <Centered tone="error">+ could not decode this image — the file may be corrupt or misnamed+ </Centered>+ )}+ {img.status === 'ready' && !decodeFailed && (+ <img+ src={img.url}+ alt={rel}+ onLoad={(e) => setDims({ w: e.currentTarget.naturalWidth, h: e.currentTarget.naturalHeight })}+ onError={() => setDecodeFailed(true)}+ style={fit+ // `maxWidth/maxHeight: 100%` only shrinks — a 32px favicon is not+ // blown up into a blurry poster, it just sits there at 32px.+ ? { maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }+ // 1:1 must NOT be allowed to shrink: it is inside a flex row, and+ // flex's default `min-width: auto` would squeeze the image back+ // down to the pane — which is precisely the state the user just+ // clicked away from.+ : { flexShrink: 0 }}+ />+ )}+ </div>+ </div>+ );+}++function Centered({ children, tone }: { children: React.ReactNode; tone?: 'error' }) {+ return (+ <div style={{+ margin: 'auto', padding: 16, textAlign: 'center',+ fontFamily: 'var(--cth-font-ui)', fontSize: 13,+ color: tone === 'error' ? 'var(--cth-coral)' : 'var(--cth-ink-500)'+ }}>{children}</div>+ );+}diff --git a/src/renderer/src/ide/chrome.ts b/src/renderer/src/ide/chrome.tsnew file mode 100644index 00000000..9d120c18--- /dev/null+++ b/src/renderer/src/ide/chrome.ts@@ -0,0 +1,37 @@+/**+ * The IDE's shared bar chrome.+ *+ * These three style objects were previously private to IdePanel, which was fine+ * while IdePanel rendered every pane itself. The image preview renders its own+ * bar, and a second copy of "padding 3px 8px, cream-200, ink-700 hairline" would+ * drift the moment either file was touched — the two bars sit directly on top of+ * each other in the same tab strip, so any drift is immediately visible. One+ * definition, imported by both.+ *+ * Every colour is a token, never a literal: the app ships a light AND a dark+ * theme that swap by redefining these variables, so a hardcoded hex here would+ * look correct in exactly one of them.+ */+import type { CSSProperties } from 'react';++/** The horizontal bar above an editor / preview body. */+export const ideBarStyle: CSSProperties = {+ display: 'flex', alignItems: 'center', gap: 6, padding: '3px 8px',+ background: 'var(--cth-cream-200)', borderBottom: '1px solid var(--cth-ink-700)',+ fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-ink-700)'+};++/** Square, borderless button that holds only an icon. */+export const ideIconBtn: CSSProperties = {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ padding: 0, width: 18, height: 18, background: 'transparent', border: 'none',+ cursor: 'pointer', color: 'var(--cth-ink-500)'+};++/** Small labelled button used for bar actions (save, copy path, view toggles). */+export const ideTextBtn: CSSProperties = {+ padding: '0 6px', height: 20, fontFamily: 'var(--cth-font-ui)', fontSize: 12,+ color: 'var(--cth-ink-900)', background: 'var(--cth-cream-100)', border: 'none',+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)', cursor: 'pointer',+ display: 'inline-flex', alignItems: 'center', gap: 4+};diff --git a/src/renderer/src/markdown/MarkdownPreview.tsx b/src/renderer/src/markdown/MarkdownPreview.tsxindex c9d4d5c3..f4a9b050 100644--- a/src/renderer/src/markdown/MarkdownPreview.tsx+++ b/src/renderer/src/markdown/MarkdownPreview.tsx@@ -12,40 +12,26 @@* opener; relative *.md links surface through onOpenMarkdownLink so the host* (IDE tab / overlay) opens them in context; everything else is inert.*/-import { memo } from 'react';+import { memo, useState } from 'react';import ReactMarkdown from 'react-markdown';import remarkGfm from 'remark-gfm';+import { useWorkspaceImage } from '@/hooks/useWorkspaceImage';+import { isExternal, isRelativeMd, resolveLocalImageRel, resolveRel } from './mdLinks';export interface MarkdownPreviewProps {source: string;/** Repo-relative path of the file being previewed (for resolving relative links). */baseRel?: string;+ /** Absolute workspace root. Supplying it turns LOCAL images from placeholder+ * chips into actual pictures (read through the root-confined fs IPC); without+ * it every image stays a chip, because there is nothing to resolve against. */+ root?: string;/** Open a sibling markdown file (repo-relative path) in the host's context. */onOpenMarkdownLink?: (rel: string) => void;}-/** Resolve `href` against the directory of `baseRel` ('' when unknown). */-function resolveRel(baseRel: string | undefined, href: string): string {- const baseDir = (baseRel ?? '').split('/').slice(0, -1);- const parts = [...baseDir];- for (const seg of href.split('/')) {- if (seg === '' || seg === '.') continue;- if (seg === '..') { parts.pop(); continue; }- parts.push(seg);- }- return parts.join('/');-}--function isExternal(href: string): boolean {- return /^(https?:|mailto:)/i.test(href);-}--function isRelativeMd(href: string): boolean {- return !/^[a-z][a-z0-9+.-]*:/i.test(href) && /\.(md|markdown)(#.*)?$/i.test(href);-}-export const MarkdownPreview = memo(function MarkdownPreview({- source, baseRel, onOpenMarkdownLink+ source, baseRel, root, onOpenMarkdownLink}: MarkdownPreviewProps) {return (<div className="cth-md-preview">@@ -74,13 +60,17 @@ export const MarkdownPreview = memo(function MarkdownPreview({</a>);},- // Local/remote images: remote is blocked by CSP anyway; render alt text- // as a placeholder chip instead of a broken-image icon.- img: ({ alt, src }) => (- <span className="cth-md-img" title={typeof src === 'string' ? src : undefined}>- 🖼 {alt || 'image'}- </span>- )+ // Images. LOCAL ones render for real (bytes via the root-confined fs+ // IPC → blob URL); remote ones stay a placeholder chip. Until now+ // every image was a chip, which meant an agent's report saying "see+ // the screenshot below" showed a pill reading "🖼 screenshot" and the+ // evidence was unviewable anywhere in the app.+ img: ({ alt, src }) => {+ const s = typeof src === 'string' ? src : undefined;+ const rel = root ? resolveLocalImageRel(baseRel, s) : null;+ if (!root || !rel) return <ImageChip alt={alt} src={s} />;+ return <MdImage root={root} rel={rel} alt={alt} src={s} />;+ }}}>{source}@@ -88,3 +78,33 @@ export const MarkdownPreview = memo(function MarkdownPreview({</div>);});++/** Fallback for anything we won't (or can't) load: remote URLs, non-images,+ * and local files that turned out to be missing or undecodable. */+function ImageChip({ alt, src, note }: { alt?: string; src?: string; note?: string }) {+ return (+ <span className="cth-md-img" title={src}>+ 🖼 {alt || 'image'}{note ? ` — ${note}` : ''}+ </span>+ );+}++/** A local image inside rendered markdown. Falls back to the chip on any+ * failure so a stale path in a report degrades to the old behaviour instead of+ * a broken-image glyph. Blob lifetime (create AND revoke) belongs to the hook. */+function MdImage({ root, rel, alt, src }: { root: string; rel: string; alt?: string; src?: string }) {+ const img = useWorkspaceImage(root, rel);+ const [decodeFailed, setDecodeFailed] = useState(false);+ if (img.status === 'loading') return <ImageChip alt={alt} src={src} note="loading" />;+ if (img.status === 'error') return <ImageChip alt={alt} src={src} note={img.error} />;+ if (decodeFailed) return <ImageChip alt={alt} src={src} note="could not decode" />;+ return (+ <img+ className="cth-md-image"+ src={img.url}+ alt={alt || rel}+ title={src}+ onError={() => setDecodeFailed(true)}+ />+ );+}diff --git a/src/renderer/src/markdown/mdLinks.ts b/src/renderer/src/markdown/mdLinks.tsnew file mode 100644index 00000000..67602a9b--- /dev/null+++ b/src/renderer/src/markdown/mdLinks.ts@@ -0,0 +1,77 @@+/**+ * Pure link/path logic for the markdown preview.+ *+ * Extracted from MarkdownPreview.tsx so it can be unit-tested: these are the+ * functions that decide what a rendered document is allowed to REACH, and a+ * `.tsx` file cannot be loaded by the `node --test` harness. The component keeps+ * only the rendering.+ */+import { isImagePath } from '@shared/imageTypes';++/** Resolve `href` against the directory of `baseRel` ('' when unknown).+ *+ * Note that `..` can only ever pop segments that this function itself pushed —+ * once `parts` is empty a `..` is dropped — so the result is always a path+ * UNDER the workspace root, never a sibling of it. That is a convenience, not+ * the security boundary: the real containment check is `safeJoin` in the main+ * process, which every read goes through. */+export function resolveRel(baseRel: string | undefined, href: string): string {+ const baseDir = (baseRel ?? '').split('/').slice(0, -1);+ const parts = [...baseDir];+ for (const seg of href.split('/')) {+ if (seg === '' || seg === '.') continue;+ if (seg === '..') { parts.pop(); continue; }+ parts.push(seg);+ }+ return parts.join('/');+}++export function isExternal(href: string): boolean {+ return /^(https?:|mailto:)/i.test(href);+}++/** True when `href` carries any URI scheme (http:, data:, file:, javascript:…). */+function hasScheme(href: string): boolean {+ return /^[a-z][a-z0-9+.-]*:/i.test(href);+}++export function isRelativeMd(href: string): boolean {+ return !hasScheme(href) && /\.(md|markdown)(#.*)?$/i.test(href);+}++/**+ * Workspace-relative path for a markdown `<img src>`, or null when the source is+ * not a local image we may load.+ *+ * WHY THIS EXISTS: the preview used to replace EVERY image with a placeholder+ * chip, so an agent-written report containing screenshots rendered as a row of+ * "🖼 screenshot" pills — the report's evidence was invisible everywhere in the+ * app. Local images can now be resolved and read through the same root-confined+ * IPC as everything else.+ *+ * What is refused, and why:+ * - anything with a SCHEME (http:, https:, data:, file:, javascript:). Remote+ * URLs are already dead under the CSP (`img-src 'self' data: blob:`), and+ * silently proxying them through the main process would turn a rendered+ * document into a network beacon that leaks "this user opened this file" to+ * whoever authored the markdown. Agent-generated markdown is untrusted.+ * - anything whose extension is not a known image type — there is no reason for+ * an <img> to pull an arbitrary file's bytes into the renderer.+ *+ * A leading `/` is read as workspace-root-relative rather than as a filesystem+ * absolute path; the leading slashes are stripped and the rest resolves from the+ * root, so `/etc/passwd` becomes the (harmless, nonexistent) `etc/passwd` inside+ * the workspace instead of escaping to the real one.+ */+export function resolveLocalImageRel(baseRel: string | undefined, src: string | undefined): string | null {+ if (typeof src !== 'string') return null;+ const raw = src.trim();+ if (!raw) return null;+ if (hasScheme(raw)) return null;+ if (!isImagePath(raw)) return null;+ // Strip the query/hash before resolving — they are cache-busters, not path.+ const clean = raw.split('#')[0].split('?')[0];+ const rooted = clean.startsWith('/');+ const rel = resolveRel(rooted ? undefined : baseRel, clean);+ return rel || null;+}diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.tsindex 230af954..900780cd 100644--- a/src/renderer/src/store/store.ts+++ b/src/renderer/src/store/store.ts@@ -159,6 +159,17 @@ interface State {* is open. Toggled from the title-bar IDE button; a global feature surface,* independent of the per-agent sidebar Files/Git tabs. */ideOpen: boolean;+ /** WHICH agent the IDE was opened FOR — set by whoever opens it.+ *+ * The IDE used to infer its workspace purely from `selectedId`, which is a+ * guess that is usually right and occasionally wrong: `setFullscreen` puts an+ * agent's terminal on screen WITHOUT selecting it, so hitting IDE from a+ * fullscreen terminal could open a different agent's directory than the one+ * being looked at. That was invisible while the title said only "IDE" and the+ * folder name; it becomes a flatly wrong agent NAME once the title names one.+ * Callers therefore state their intent, and `selectedId` stays as the+ * fallback for anything that genuinely has no particular agent in mind. */+ ideAgentId: string | null;sidebarWidth: number;sidebarTab: SidebarTab;godStatus: GodStatus;@@ -261,7 +272,10 @@ interface State {setPendingHire: (m: HireManifest | null) => void;setFullscreen: (id: string | null) => void;setFullscreenFile: (path: string | null, view?: 'edit' | 'preview') => void;- setIdeOpen: (open: boolean) => void;+ /** Open/close the IDE. `agentId` names the agent whose workspace it should+ * show; omit it only when the caller truly has no specific agent (the IDE+ * then falls back to the selection and says so in its title). */+ setIdeOpen: (open: boolean, agentId?: string | null) => void;setIdeInitialFile: (path: string | null) => void;setSidebarWidth: (px: number) => void;setSidebarTab: (tab: SidebarTab) => void;@@ -576,6 +590,7 @@ export const useStore = create<State>((set) => ({fullscreenFileView: 'edit',ideInitialFile: null,ideOpen: false,+ ideAgentId: null,sidebarWidth: initialSidebarWidth,sidebarTab: initialSidebarTab,godStatus: 'booting',@@ -804,7 +819,10 @@ export const useStore = create<State>((set) => ({setPendingHire: (m) => set({ pendingHire: m }),setFullscreen: (id) => set({ fullscreenAgentId: id }),setFullscreenFile: (path, view) => set({ fullscreenFilePath: path, fullscreenFileView: view ?? 'edit' }),- setIdeOpen: (open) => set({ ideOpen: open }),+ // Closing CLEARS the target: the id is scoped to one IDE session, and a stale+ // one left behind would silently win over the selection on the next open from+ // a caller that passes nothing.+ setIdeOpen: (open, agentId) => set({ ideOpen: open, ideAgentId: open ? (agentId ?? null) : null }),setIdeInitialFile: (path) => set({ ideInitialFile: path }),setSidebarWidth: (px) => {const clamped = Math.min(1200, Math.max(320, Math.round(px)));diff --git a/src/shared/imageTypes.ts b/src/shared/imageTypes.tsnew file mode 100644index 00000000..fe69e88f--- /dev/null+++ b/src/shared/imageTypes.ts@@ -0,0 +1,80 @@+/**+ * Image file detection — the ONE place that answers "is this path an image, and+ * what mime does it carry?".+ *+ * Shared on purpose. Three call sites need the same answer and they live on+ * opposite sides of the IPC boundary: the main process stamps a mime onto the+ * bytes it reads (`fs.readFileBinary`), the IDE decides whether a click opens+ * Monaco or the image preview, and the markdown renderer decides whether an+ * `<img src>` is worth resolving. If those three ever disagree, the failure is+ * silent and confusing — a file opens as a preview that then reports "unknown+ * image", or opens in Monaco as mojibake. Keeping the table here makes+ * disagreement impossible.+ *+ * Detection is BY EXTENSION, not by magic bytes. That is deliberate: the+ * renderer must decide how to open a file *before* it has any bytes, so a+ * content sniff isn't available at the moment the decision is made. The mime is+ * only ever used to label a `blob:` URL for the platform's own image decoder —+ * a mislabelled file simply fails to decode and shows the preview's error state,+ * it never becomes a script or a navigation.+ */++/** Extension (lower-case, no dot) → mime type. */+const MIME_BY_EXT: Readonly<Record<string, string>> = {+ png: 'image/png',+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ gif: 'image/gif',+ webp: 'image/webp',+ bmp: 'image/bmp',+ ico: 'image/x-icon',+ avif: 'image/avif',+ svg: 'image/svg+xml'+};++/**+ * Lower-cased extension of `p` without the dot, or '' when there is none.+ *+ * Strips a `?query` / `#hash` first: markdown authored by an agent routinely+ * carries cache-busting suffixes (`./shot.png?v=2`), and treating `png?v=2` as+ * the extension would silently drop exactly the screenshots we want to render.+ * Only the LAST path segment is considered, so a dotted directory name+ * (`v1.2/report`) can never masquerade as an extension.+ */+export function extensionOf(p: string): string {+ if (typeof p !== 'string') return '';+ const clean = p.split('#')[0].split('?')[0];+ const base = clean.split('/').pop() ?? '';+ const dot = base.lastIndexOf('.');+ if (dot < 0 || dot === base.length - 1) return '';+ return base.slice(dot + 1).toLowerCase();+}++/** The image mime for `p`, or null when the extension isn't a known image. */+export function imageMimeForPath(p: string): string | null {+ return MIME_BY_EXT[extensionOf(p)] ?? null;+}++/** True when `p` names a raster or vector image we can render. */+export function isImagePath(p: string): boolean {+ return imageMimeForPath(p) !== null;+}++/**+ * SVG is the one image format that is ALSO source code people edit by hand.+ * Callers use this to keep a "view source" escape hatch: an .svg opens as a+ * picture (that's what you want 95% of the time) but must never become+ * un-editable, which is what routing every image straight to a read-only+ * preview would have done.+ */+export function isSvgPath(p: string): boolean {+ return extensionOf(p) === 'svg';+}++/** Human byte size for a status line: "864 B", "1.4 MB". */+export function formatBytes(n: number): string {+ if (!Number.isFinite(n) || n < 0) return '—';+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / 1024 / 1024).toFixed(1)} MB`;+}diff --git a/test/ide-image.test.cjs b/test/ide-image.test.cjsnew file mode 100644index 00000000..b68c2811--- /dev/null+++ b/test/ide-image.test.cjs@@ -0,0 +1,242 @@+'use strict';++/**+ * Images in the IDE.+ *+ * Opening a .png used to produce a tab that said "binary file (not displayable)"+ * — the text reader rejects anything containing a null byte, and it was the only+ * reader the renderer had. Images now travel as raw bytes over a separate,+ * root-confined, size-capped read and become a blob URL in the renderer.+ *+ * The three things worth pinning down are the ones that are silent when they+ * break: the extension→mime table (three call sites depend on agreeing about+ * it), the path-traversal guard on the new binary read, and the size cap that+ * keeps a huge file from being pulled into the renderer whole.+ */++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const loadTs = require('./load-ts.cjs');++const { extensionOf, imageMimeForPath, isImagePath, isSvgPath, formatBytes } = loadTs('src/shared/imageTypes.ts');+const { readFileBinary } = loadTs('src/main/fs.ts');+const { resolveLocalImageRel, resolveRel } = loadTs('src/renderer/src/markdown/mdLinks.ts');++// ─── extension → mime ───────────────────────────────────────────────────────++test('detects the image formats agents actually produce', () => {+ assert.equal(imageMimeForPath('shot.png'), 'image/png');+ assert.equal(imageMimeForPath('photo.jpg'), 'image/jpeg');+ assert.equal(imageMimeForPath('photo.jpeg'), 'image/jpeg');+ assert.equal(imageMimeForPath('anim.gif'), 'image/gif');+ assert.equal(imageMimeForPath('modern.webp'), 'image/webp');+ assert.equal(imageMimeForPath('icon.svg'), 'image/svg+xml');+ assert.equal(imageMimeForPath('old.bmp'), 'image/bmp');+ assert.equal(imageMimeForPath('fav.ico'), 'image/x-icon');+ assert.equal(imageMimeForPath('new.avif'), 'image/avif');+});++test('extension matching is case-insensitive', () => {+ // macOS screenshots and camera exports both ship upper-case extensions.+ assert.equal(imageMimeForPath('Screenshot.PNG'), 'image/png');+ assert.equal(imageMimeForPath('IMG_0001.JPG'), 'image/jpeg');+ assert.ok(isImagePath('/abs/path/A.WebP'));+});++test('non-images are not images', () => {+ for (const p of ['notes.md', 'index.ts', 'Makefile', 'archive.tar.gz', 'a.png.bak', '']) {+ assert.equal(imageMimeForPath(p), null, `${p} must not be treated as an image`);+ assert.equal(isImagePath(p), false);+ }+});++test('query strings and hashes do not hide the extension', () => {+ // Agent-written markdown carries cache-busters; treating `png?v=2` as the+ // extension would silently drop exactly the screenshots we want to render.+ assert.equal(extensionOf('shot.png?v=2'), 'png');+ assert.equal(extensionOf('shot.png#fig1'), 'png');+ assert.ok(isImagePath('./out/shot.png?v=2'));+});++test('a dotted DIRECTORY name cannot masquerade as an extension', () => {+ assert.equal(extensionOf('v1.2/report'), '');+ assert.equal(isImagePath('release-1.png/report'), false);+});++test('svg is flagged separately — it is the one image that is also source', () => {+ assert.ok(isSvgPath('logo.svg'));+ assert.ok(isSvgPath('a/b/LOGO.SVG'));+ assert.equal(isSvgPath('logo.png'), false);+});++test('formatBytes reads like a status line', () => {+ assert.equal(formatBytes(0), '0 B');+ assert.equal(formatBytes(864), '864 B');+ assert.equal(formatBytes(1536), '1.5 KB');+ assert.equal(formatBytes(3 * 1024 * 1024), '3.0 MB');+ assert.equal(formatBytes(-1), '—');+});++// ─── markdown <img src> resolution ──────────────────────────────────────────++test('local markdown images resolve against the document directory', () => {+ assert.equal(resolveLocalImageRel('docs/report.md', './img/shot.png'), 'docs/img/shot.png');+ assert.equal(resolveLocalImageRel('docs/report.md', 'shot.png'), 'docs/shot.png');+ assert.equal(resolveLocalImageRel('docs/deep/report.md', '../shot.png'), 'docs/shot.png');+ assert.equal(resolveLocalImageRel('report.md', 'out/shot.png?v=3'), 'out/shot.png');+});++test('a leading slash means the WORKSPACE root, not the filesystem root', () => {+ assert.equal(resolveLocalImageRel('docs/report.md', '/assets/shot.png'), 'assets/shot.png');+ // Worst case it names a path that simply does not exist inside the workspace.+ assert.equal(resolveLocalImageRel('docs/report.md', '/etc/secret.png'), 'etc/secret.png');+});++test('anything with a URI scheme is refused', () => {+ // Remote URLs are dead under the CSP anyway; proxying them through the main+ // process would turn a rendered report into a beacon for whoever wrote it.+ for (const src of [+ 'https://evil.example/track.png',+ 'http://evil.example/track.png',+ 'data:image/png;base64,AAAA',+ 'file:///etc/passwd.png',+ 'javascript:alert(1)'+ ]) {+ assert.equal(resolveLocalImageRel('docs/report.md', src), null, `${src} must not resolve`);+ }+});++test('non-image sources are refused even when local', () => {+ assert.equal(resolveLocalImageRel('docs/report.md', './secrets.env'), null);+ assert.equal(resolveLocalImageRel('docs/report.md', '../../.ssh/id_rsa'), null);+ assert.equal(resolveLocalImageRel('docs/report.md', undefined), null);+ assert.equal(resolveLocalImageRel('docs/report.md', ' '), null);+});++test('`..` can never climb above the workspace root textually', () => {+ // Not the security boundary (safeJoin is), but it must not even try.+ assert.equal(resolveRel('a/b/c.md', '../../../../../etc/passwd'), 'etc/passwd');+ assert.equal(resolveLocalImageRel('a/b.md', '../../../../x.png'), 'x.png');+});++// ─── the binary read itself ─────────────────────────────────────────────────++/** A 1×1 PNG — a real file with a null byte in its header, i.e. exactly what the+ * text reader refuses. */+const ONE_PIXEL_PNG = Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',+ 'base64'+);++function makeWorkspace() {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cth-img-'));+ const root = path.join(dir, 'workspace');+ fs.mkdirSync(path.join(root, 'docs'), { recursive: true });+ fs.writeFileSync(path.join(root, 'docs', 'shot.png'), ONE_PIXEL_PNG);+ // A sibling of the root, i.e. the thing traversal would be reaching for.+ fs.writeFileSync(path.join(dir, 'outside.png'), ONE_PIXEL_PNG);+ return { dir, root };+}++test('reads an image the text reader refuses, with its mime and size', async () => {+ const { dir, root } = makeWorkspace();+ try {+ const res = await readFileBinary(root, 'docs/shot.png');+ assert.equal(res.ok, true, res.ok ? '' : res.error);+ assert.equal(res.mime, 'image/png');+ assert.equal(res.size, ONE_PIXEL_PNG.length);+ assert.ok(Buffer.from(res.bytes).equals(ONE_PIXEL_PNG), 'bytes must round-trip exactly');+ assert.ok(res.bytes.includes(0), 'the null byte is the whole reason this path exists');+ assert.equal(+ res.bytes.byteLength, res.bytes.buffer.byteLength,+ 'bytes must be COPIED into their own buffer — a pooled Buffer would ship unrelated file data across IPC'+ );+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('path traversal out of the root is rejected', async () => {+ const { dir, root } = makeWorkspace();+ try {+ for (const rel of [+ '../outside.png',+ 'docs/../../outside.png',+ path.join(dir, 'outside.png'), // absolute, outside the root+ '/etc/hosts'+ ]) {+ const res = await readFileBinary(root, rel);+ assert.equal(res.ok, false, `${rel} must not be readable`);+ assert.equal(res.error, 'path escapes root');+ }+ // …while an absolute path INSIDE the root is still fine (safeJoin's rule).+ const inside = await readFileBinary(root, path.join(root, 'docs', 'shot.png'));+ assert.equal(inside.ok, true);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('the size cap is enforced before any bytes are read', async () => {+ const { dir, root } = makeWorkspace();+ try {+ const res = await readFileBinary(root, 'docs/shot.png', 8);+ assert.equal(res.ok, false);+ assert.match(res.error, /too large/);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('the default cap clears a retina screenshot (the 2 MB text cap did not)', async () => {+ const { dir, root } = makeWorkspace();+ try {+ // 2.5 MB: over the text reader's MAX_READ_BYTES, comfortably under this one.+ const big = path.join(root, 'docs', 'big.png');+ fs.writeFileSync(big, Buffer.concat([ONE_PIXEL_PNG, Buffer.alloc(2.5 * 1024 * 1024)]));+ const res = await readFileBinary(root, 'docs/big.png');+ assert.equal(res.ok, true, res.ok ? '' : res.error);+ assert.ok(res.size > 2 * 1024 * 1024);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('non-regular files are refused rather than opened', async () => {+ const { dir, root } = makeWorkspace();+ try {+ // A directory read would throw; a FIFO would BLOCK FOREVER with no size to+ // check, hanging the IPC call and the renderer's loading state with it.+ const res = await readFileBinary(root, 'docs');+ assert.equal(res.ok, false);+ assert.equal(res.error, 'not a regular file');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('a missing file reports an error instead of throwing', async () => {+ const { dir, root } = makeWorkspace();+ try {+ const res = await readFileBinary(root, 'docs/nope.png');+ assert.equal(res.ok, false);+ assert.match(res.error, /ENOENT/);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('unknown binary types still read, labelled octet-stream', async () => {+ const { dir, root } = makeWorkspace();+ try {+ fs.writeFileSync(path.join(root, 'blob.bin'), Buffer.from([0, 1, 2, 3]));+ const res = await readFileBinary(root, 'blob.bin');+ assert.equal(res.ok, true);+ assert.equal(res.mime, 'application/octet-stream', 'never guess an image mime for an unknown extension');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});