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
fix(markdown): links in rendered markdown never navigate the app window
review46a132154f30
diff --git a/CLAUDE.md b/CLAUDE.mdindex 5bb49e185..89698adfb 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1539,6 +1539,29 @@ Monaco is wired in `renderer/editor/monaco-setup.ts` (language workers bundled v`?worker` — no CDN; CSP `worker-src` allows them). Markdown rendering is shared in`renderer/lib/markdown.ts` (`marked` + DOMPurify sanitize).+**A link in rendered markdown must never navigate the app window.** DOMPurify keeps an anchor's+href as written, and agents write relative links constantly (`[pty-manager.ts](src/core/pty-manager.ts:4100)`).+A click resolved it against the app document: on the desktop another `file://` path, which the old+`will-navigate` guard ALLOWED ("any `file://` is ours"), so the main window navigated to a file that+does not exist and the whole canvas was gone until a reload; in the Server Edition any `<a href>`+click, relative or http(s), navigated the app's own tab away. Two layers now:+- **Renderer, every surface** — ONE delegated, document-level click listener installed at boot+ (`renderer/lib/markdownLinks.ts`, from `boot.tsx`), scoped by `RENDERED_MARKDOWN_CONTAINERS`+ (`.term-md__content` — terminal ⌘M view + editor Preview, `.term-chat__text` — ChatPanel,+ `.sticky-node__md` — sticky notes on canvas AND in the kanban card modal). http/https/mailto →+ `shell.openExternal` (system browser / a new browser tab); `#fragment` and empty href → swallowed;+ anything else → swallowed + an error toast (`nodeterm:toast` — the only kind Canvas renders).+ Local links deliberately do NOT open a file: resolving one needs the owning node's cwd AND its+ filesystem dialect (session source, core platform, SSH/relay — TerminalNode's `pathConvention`),+ which a document-level handler cannot see; a wrong guess opens the wrong file on the wrong machine.+ **A new markdown surface must render inside a listed container** — `markdownLinks.test.ts` fails+ on a component that pipes `renderMarkdown` into `dangerouslySetInnerHTML` outside the list, and on+ a listed class nothing renders any more.+- **Main, desktop backstop** — `decideMainFrameNavigation` (`main/navigation-guard.ts`) allows a+ main-frame navigation ONLY to the entry document itself (scheme + host + decoded pathname; hash+ and query ignored, so reload and dev HMR work); a safe external scheme goes to the OS; everything+ else — any other `file://` path, any other dev-server path — is blocked.+### Webview keep-alive across project switches (browser/web nodes)Issue #301: a project switch used to reload every browser node's page — SPA state, forms, scroll,diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 88a3e8417..9c0fa949b 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -368,6 +368,12 @@ lane unaffected.removing the class or adding a renderer wheel handler cannot implement guest zoom. The sharedrenderer controls call the same `@shared/webview-zoom` policy directly on the attached guest.+- **Rendered markdown goes inside a listed container.** A link in `renderMarkdown` output keeps its+ href as written, and a relative one used to navigate the whole app window away (the canvas was+ gone until a reload). One delegated handler (`renderer/lib/markdownLinks.ts`) intercepts clicks+ inside `RENDERED_MARKDOWN_CONTAINERS`; a new surface that injects markdown HTML must use one of+ those classes or join the list — `markdownLinks.test.ts` fails otherwise.+These are the ones that come up in review most often. Each exists because its absence caused a realbug.diff --git a/src/main/index.ts b/src/main/index.tsindex 91ff20c85..94f716b8a 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -22,6 +22,7 @@ installLogSink(logBuffer)import { writeFilesToClipboard } from './clipboard-files'import { pickProjectIcon } from './project-icon-upload'import { allowGuestNavigation } from './webview-nav'+import { appEntryUrlFor, decideMainFrameNavigation, isSafeExternalUrl } from './navigation-guard'import { installWebviewZoom } from './webview-zoom'import { hostOsFromPlatform, sshServerCopy } from '../shared/ssh-server'import { macTitleBarOptions, trafficLightPositionFor } from './window-chrome'@@ -352,19 +353,6 @@ if (NT_MULTI && process.platform === 'darwin') app.commandLine.appendSwitch('useconst corePlatform = electronPlatform()initPlatform(corePlatform)-// Only hand the OS a URL with a vetted scheme. Blocks file://, smb://, and custom-// protocol-handler schemes that could be smuggled in via remote announcement feeds or-// rendered markdown links. Used by both the window-open handler and the IPC handler.-function isSafeExternalUrl(url: unknown): url is string {- if (typeof url !== 'string') return false- try {- const { protocol } = new URL(url)- return protocol === 'http:' || protocol === 'https:' || protocol === 'mailto:'- } catch {- return false- }-}-const settingsStore = new SettingsStore()// ⌘M / ⌘W are registry commands (`node.toggleMarkdown` / `node.close`), so what the window// intercepts follows the user's settings. Resolved LAZILY (first keystroke, long after@@ -1230,19 +1218,24 @@ function createWindow(): BrowserWindow {return { action: 'deny' }})- // Block any in-page top-level navigation away from the app origin (defense in depth).+ // Main-frame navigation is allowed ONLY back to the entry document (reload / dev HMR); a safe+ // external URL goes to the OS; everything else is blocked. "Any file://" used to be allowed, and+ // a relative link in rendered markdown resolved to another file:// path and wiped the canvas —+ // policy + reasoning in navigation-guard.ts.+ const rendererIndexPath = join(__dirname, '../renderer/index.html')+ const appEntryUrl = appEntryUrlFor(process.env['ELECTRON_RENDERER_URL'], rendererIndexPath)win.webContents.on('will-navigate', (e, url) => {- if (!url.startsWith('file://') && !url.startsWith(process.env['ELECTRON_RENDERER_URL'] ?? '\0')) {- e.preventDefault()- if (isSafeExternalUrl(url)) void shell.openExternal(url)- }+ const decision = decideMainFrameNavigation(url, appEntryUrl)+ if (decision === 'allow') return+ e.preventDefault()+ if (decision === 'external') void shell.openExternal(url)})// Load the electron-vite dev server if present, otherwise the built file.if (process.env['ELECTRON_RENDERER_URL']) {win.loadURL(process.env['ELECTRON_RENDERER_URL'])} else {- win.loadFile(join(__dirname, '../renderer/index.html'))+ win.loadFile(rendererIndexPath)}return windiff --git a/src/main/navigation-guard.test.ts b/src/main/navigation-guard.test.tsnew file mode 100644index 000000000..3396d20bf--- /dev/null+++ b/src/main/navigation-guard.test.ts@@ -0,0 +1,74 @@+import { describe, it, expect } from 'vitest'+import { decideMainFrameNavigation, isSafeExternalUrl, appEntryUrlFor } from './navigation-guard'++const PACKAGED = 'file:///Applications/nodeterm.app/Contents/Resources/app.asar/out/renderer/index.html'+const DEV = 'http://localhost:5173/'++describe('decideMainFrameNavigation', () => {+ it('allows the entry document itself, ignoring hash and query (reload, dev HMR)', () => {+ expect(decideMainFrameNavigation(PACKAGED, PACKAGED)).toBe('allow')+ expect(decideMainFrameNavigation(`${PACKAGED}#glyphgrid`, PACKAGED)).toBe('allow')+ expect(decideMainFrameNavigation(`${PACKAGED}?t=1`, PACKAGED)).toBe('allow')+ expect(decideMainFrameNavigation(DEV, DEV)).toBe('allow')+ expect(decideMainFrameNavigation('http://localhost:5173/?reload=1#x', DEV)).toBe('allow')+ })++ it('treats a percent-encoded spelling of the same entry path as the same document', () => {+ const entry = 'file:///Users/me/My%20Apps/out/renderer/index.html'+ expect(decideMainFrameNavigation('file:///Users/me/My Apps/out/renderer/index.html', entry)).toBe(+ 'allow'+ )+ })++ it('BLOCKS a relative markdown link resolved against the packaged entry (the canvas wipe)', () => {+ // `[pty-manager.ts](src/core/pty-manager.ts:4100)` clicked in rendered markdown.+ const resolved = new URL('src/core/pty-manager.ts:4100', PACKAGED).href+ expect(decideMainFrameNavigation(resolved, PACKAGED)).toBe('block')+ })++ it('blocks every other file:// URL', () => {+ expect(decideMainFrameNavigation('file:///etc/passwd', PACKAGED)).toBe('block')+ expect(decideMainFrameNavigation('file:///etc/passwd', DEV)).toBe('block')+ })++ it('blocks another path on the dev server instead of opening it in the system browser', () => {+ const resolved = new URL('src/core/pty-manager.ts:4100', DEV).href+ expect(decideMainFrameNavigation(resolved, DEV)).toBe('block')+ })++ it('hands safe external schemes to the OS', () => {+ expect(decideMainFrameNavigation('https://github.com/x', PACKAGED)).toBe('external')+ expect(decideMainFrameNavigation('http://example.com/', DEV)).toBe('external')+ expect(decideMainFrameNavigation('mailto:[email protected]', PACKAGED)).toBe('external')+ })++ it('blocks other schemes and garbage', () => {+ expect(decideMainFrameNavigation('javascript:alert(1)', PACKAGED)).toBe('block')+ expect(decideMainFrameNavigation('smb://server/share', PACKAGED)).toBe('block')+ expect(decideMainFrameNavigation('data:text/html,x', PACKAGED)).toBe('block')+ expect(decideMainFrameNavigation('not a url', PACKAGED)).toBe('block')+ // An unparsable entry never turns into "allow everything".+ expect(decideMainFrameNavigation(PACKAGED, '')).toBe('block')+ })+})++describe('appEntryUrlFor', () => {+ it('prefers the dev-server URL', () => {+ expect(appEntryUrlFor(DEV, '/x/out/renderer/index.html')).toBe(DEV)+ })+ it('turns the packaged file path into a file URL', () => {+ expect(appEntryUrlFor(undefined, '/x/My Apps/out/renderer/index.html')).toBe(+ 'file:///x/My%20Apps/out/renderer/index.html'+ )+ })+})++describe('isSafeExternalUrl', () => {+ it('accepts only http/https/mailto', () => {+ expect(isSafeExternalUrl('https://a.b')).toBe(true)+ expect(isSafeExternalUrl('mailto:[email protected]')).toBe(true)+ expect(isSafeExternalUrl('file:///etc/passwd')).toBe(false)+ expect(isSafeExternalUrl('relative/path')).toBe(false)+ expect(isSafeExternalUrl(42)).toBe(false)+ })+})diff --git a/src/main/navigation-guard.ts b/src/main/navigation-guard.tsnew file mode 100644index 000000000..de0a8444b--- /dev/null+++ b/src/main/navigation-guard.ts@@ -0,0 +1,75 @@+// Main-window navigation policy (pure, unit-tested in navigation-guard.test.ts).+//+// The main window hosts the whole canvas as ONE document. Any top-level navigation away from it+// wipes the canvas until a reload — every terminal, every node, all live renderer state. The old+// `will-navigate` guard allowed every `file://` URL and every URL under the dev server, on the+// theory that "same origin" meant "our app". It does not: a relative link in rendered markdown —+// Claude's habitual `[pty-manager.ts](src/core/pty-manager.ts:4100)` survives DOMPurify with its+// relative href — resolves against the packaged `…/out/renderer/index.html` to another `file://`+// path, the guard let it through, and the window navigated to a file that does not exist.+//+// So the rule is the narrowest one that keeps the app working: the ONLY allowed main-frame+// navigation is to the entry document itself (the exact URL the window loaded, compared on+// scheme + host + decoded pathname; hash and query are ignored so a reload and dev HMR still+// work). Safe external schemes go to the OS. Everything else — any other file:// path, any other+// path on the dev server, any other scheme — is blocked. The renderer's delegated markdown link+// handler (renderer/lib/markdownLinks.ts) is the first line; this is the backstop.++import { pathToFileURL } from 'url'++// Only hand the OS a URL with a vetted scheme. Blocks file://, smb://, and custom+// protocol-handler schemes that could be smuggled in via remote announcement feeds or+// rendered markdown links. Used by the window-open handler, `will-navigate`, and the+// shellOpenExternal IPC handler.+export function isSafeExternalUrl(url: unknown): url is string {+ if (typeof url !== 'string') return false+ try {+ const { protocol } = new URL(url)+ return protocol === 'http:' || protocol === 'https:' || protocol === 'mailto:'+ } catch {+ return false+ }+}++/** The URL the main window loads: the electron-vite dev server when present, else the packaged+ * `index.html` as a file URL (the same file `win.loadFile` is handed). */+export function appEntryUrlFor(devServerUrl: string | undefined, packagedIndexPath: string): string {+ return devServerUrl || pathToFileURL(packagedIndexPath).href+}++function decodedPath(u: URL): string {+ try {+ return decodeURI(u.pathname)+ } catch {+ return u.pathname+ }+}++export type MainFrameNavigation = 'allow' | 'external' | 'block'++export function decideMainFrameNavigation(url: string, appEntryUrl: string): MainFrameNavigation {+ let target: URL+ try {+ target = new URL(url)+ } catch {+ return 'block'+ }+ let entry: URL | null = null+ try {+ entry = new URL(appEntryUrl)+ } catch {+ entry = null+ }+ if (entry && target.protocol === entry.protocol && target.host === entry.host) {+ // `file:` paths compare case-insensitively: loadFile and Chromium may spell a drive letter or+ // a case-insensitive volume differently, and a false "block" here would break reload.+ const a = decodedPath(target)+ const b = decodedPath(entry)+ const same = target.protocol === 'file:' ? a.toLowerCase() === b.toLowerCase() : a === b+ // Same origin, different document: that is the relative-link canvas wipe. Never open it+ // externally either — on the dev server it would hand a garbage localhost URL to the browser.+ return same ? 'allow' : 'block'+ }+ if (isSafeExternalUrl(url)) return 'external'+ return 'block'+}diff --git a/src/renderer/boot.tsx b/src/renderer/boot.tsxindex 8866d249f..987f38db2 100644--- a/src/renderer/boot.tsx+++ b/src/renderer/boot.tsx@@ -7,6 +7,7 @@ import { ensureCodexCliCaps } from './state/codexCli'import { initAgentResolver } from './state/agent-resolver'import { refreshAgentEnv } from './lib/agentEnv'import { applyWindowChrome } from './lib/windowChrome'+import { installMarkdownLinkGuard, LOCAL_LINK_MESSAGE } from './lib/markdownLinks'import './styles.css'import './tailwind.css'@@ -16,6 +17,20 @@ import './tailwind.css'// logo in and squeezed the tabs). Runs after main.tsx's shell switch, so the browser flag is set.applyWindowChrome()+// Links in rendered markdown (terminal ⌘M view, transcript bubbles, sticky notes, editor preview,+// the kanban card modal) must never navigate this window: a relative link used to wipe the canvas+// on the desktop, and any link navigated the Server Edition's tab away. One delegated listener for+// every surface — contract and reasoning in lib/markdownLinks.ts. Web links go through the bridge+// (system browser on desktop, a new tab in the Server Edition). The toast is kind 'error' because+// that is the only kind Canvas renders — an 'info' toast would be a silent no-op.+installMarkdownLinkGuard(document, {+ openExternal: (url) => window.nodeTerminal.shell.openExternal(url),+ notifyLocal: () =>+ window.dispatchEvent(+ new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: LOCAL_LINK_MESSAGE } })+ )+})+// Register the custom-agent → baseAgent resolver so the capability predicates (hasHooks, canResume,// canControlCanvas, …) resolve a custom agent's inherited harness. Reads the live settings store.initAgentResolver()diff --git a/src/renderer/components/NoteMarkdown.tsx b/src/renderer/components/NoteMarkdown.tsxindex 0ba7bfba5..563141959 100644--- a/src/renderer/components/NoteMarkdown.tsx+++ b/src/renderer/components/NoteMarkdown.tsx@@ -6,8 +6,9 @@ import { useEffect, useState } from 'react'* overlay does it, so notes keep it out of the boot bundle. Rendered with `breaks`: sticky text* predates markdown, and a plain list of lines must not collapse into one paragraph.*- * Anchor clicks are safe to leave alone: the main process routes every `will-navigate` /- * window-open through `isSafeExternalUrl` → `shell.openExternal`.+ * Anchor clicks are handled by the delegated rendered-markdown link guard+ * (lib/markdownLinks.ts) — `sticky-node__md`, the class every caller passes, is in its container+ * list. Never navigate the app window from here.*/export function NoteMarkdown({ text, className }: { text: string; className?: string }) {const [html, setHtml] = useState<string | null>(null)diff --git a/src/renderer/lib/markdownLinks.test.ts b/src/renderer/lib/markdownLinks.test.tsnew file mode 100644index 000000000..b52d2c107--- /dev/null+++ b/src/renderer/lib/markdownLinks.test.ts@@ -0,0 +1,181 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, afterEach } from 'vitest'+import fs from 'fs'+import path from 'path'+import {+ decideMarkdownLinkClick,+ installMarkdownLinkGuard,+ RENDERED_MARKDOWN_CONTAINERS+} from './markdownLinks'++describe('decideMarkdownLinkClick', () => {+ it('opens http/https/mailto externally', () => {+ expect(decideMarkdownLinkClick('https://github.com/x')).toEqual({+ action: 'external',+ url: 'https://github.com/x'+ })+ expect(decideMarkdownLinkClick('http://a.b/')).toEqual({ action: 'external', url: 'http://a.b/' })+ expect(decideMarkdownLinkClick('mailto:[email protected]')).toEqual({ action: 'external', url: 'mailto:[email protected]' })+ expect(decideMarkdownLinkClick(' HTTPS://A.B/x ')).toEqual({ action: 'external', url: 'https://a.b/x' })+ })++ it('ignores same-document fragments and empty hrefs', () => {+ expect(decideMarkdownLinkClick('#section')).toEqual({ action: 'ignore' })+ expect(decideMarkdownLinkClick('#')).toEqual({ action: 'ignore' })+ expect(decideMarkdownLinkClick('')).toEqual({ action: 'ignore' })+ })++ it('treats relative paths, file: and other schemes as local (never navigated)', () => {+ expect(decideMarkdownLinkClick('src/core/pty-manager.ts:4100')).toEqual({ action: 'local' })+ expect(decideMarkdownLinkClick('./README.md')).toEqual({ action: 'local' })+ expect(decideMarkdownLinkClick('/etc/hosts')).toEqual({ action: 'local' })+ expect(decideMarkdownLinkClick('//evil.example/x')).toEqual({ action: 'local' })+ expect(decideMarkdownLinkClick('file:///etc/passwd')).toEqual({ action: 'local' })+ expect(decideMarkdownLinkClick('vscode://file/x')).toEqual({ action: 'local' })+ expect(decideMarkdownLinkClick('javascript:alert(1)')).toEqual({ action: 'local' })+ })+})++describe('installMarkdownLinkGuard', () => {+ let uninstall: (() => void) | undefined+ afterEach(() => {+ uninstall?.()+ uninstall = undefined+ document.body.innerHTML = ''+ })++ function setup(html: string) {+ document.body.innerHTML = html+ const openExternal = vi.fn()+ const notifyLocal = vi.fn()+ uninstall = installMarkdownLinkGuard(document, { openExternal, notifyLocal })+ return { openExternal, notifyLocal }+ }++ function click(el: Element, init: MouseEventInit = {}): MouseEvent {+ const ev = new MouseEvent('click', { bubbles: true, cancelable: true, button: 0, ...init })+ el.dispatchEvent(ev)+ return ev+ }++ it('prevents navigation for a relative link inside rendered markdown and tells the user', () => {+ const { openExternal, notifyLocal } = setup(+ '<div class="term-md__content"><p><a href="src/core/pty-manager.ts:4100">pty</a></p></div>'+ )+ const ev = click(document.querySelector('a')!)+ expect(ev.defaultPrevented).toBe(true)+ expect(notifyLocal).toHaveBeenCalledTimes(1)+ expect(openExternal).not.toHaveBeenCalled()+ })++ it('routes an https link through openExternal in every container', () => {+ for (const sel of RENDERED_MARKDOWN_CONTAINERS) {+ const cls = sel.slice(1)+ const { openExternal } = setup(`<div class="${cls}"><a href="https://a.b/x"><code>x</code></a></div>`)+ // Click lands on a CHILD of the anchor — closest() must still find it.+ const ev = click(document.querySelector('code')!)+ expect(ev.defaultPrevented, sel).toBe(true)+ expect(openExternal, sel).toHaveBeenCalledWith('https://a.b/x')+ uninstall?.()+ uninstall = undefined+ }+ })++ it('swallows a fragment link without doing anything', () => {+ const { openExternal, notifyLocal } = setup(+ '<div class="term-chat__text"><a href="#heading">jump</a></div>'+ )+ const ev = click(document.querySelector('a')!)+ expect(ev.defaultPrevented).toBe(true)+ expect(openExternal).not.toHaveBeenCalled()+ expect(notifyLocal).not.toHaveBeenCalled()+ })++ it('handles modifier clicks too (nothing else owns them on rendered markdown)', () => {+ const { openExternal } = setup('<div class="sticky-node__md"><a href="https://a.b/">x</a></div>')+ const ev = click(document.querySelector('a')!, { metaKey: true })+ expect(ev.defaultPrevented).toBe(true)+ expect(openExternal).toHaveBeenCalledWith('https://a.b/')+ })++ it('leaves anchors outside rendered markdown alone', () => {+ const { openExternal, notifyLocal } = setup('<div class="toolbar"><a href="relative">x</a></div>')+ const ev = click(document.querySelector('a')!)+ expect(ev.defaultPrevented).toBe(false)+ expect(openExternal).not.toHaveBeenCalled()+ expect(notifyLocal).not.toHaveBeenCalled()+ })++ it('skips an event someone already handled, and non-primary buttons', () => {+ const { openExternal } = setup('<div class="term-md__content"><a href="https://a.b/">x</a></div>')+ const a = document.querySelector('a')!+ a.addEventListener('click', (e) => e.preventDefault(), { once: true })+ click(a)+ click(a, { button: 1 })+ expect(openExternal).not.toHaveBeenCalled()+ })++ it('uninstalls cleanly', () => {+ const { openExternal } = setup('<div class="term-md__content"><a href="https://a.b/">x</a></div>')+ uninstall!()+ uninstall = undefined+ const ev = click(document.querySelector('a')!)+ expect(ev.defaultPrevented).toBe(false)+ expect(openExternal).not.toHaveBeenCalled()+ })+})++describe('RENDERED_MARKDOWN_CONTAINERS contract', () => {+ // The list is a contract with the components that render markdown into these classes. A rename+ // there without a rename here would silently re-open the canvas-wipe bug, so pin that every+ // class is still emitted by some component source file.+ const RENDERER = path.join(__dirname, '..')+ function sources(dir: string, out: string[] = []): string[] {+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, e.name)+ if (e.isDirectory()) sources(full, out)+ else if (/\.tsx$/.test(e.name) && !/\.test\.tsx$/.test(e.name)) out.push(full)+ }+ return out+ }+ const all = sources(RENDERER).map((f) => fs.readFileSync(f, 'utf8'))++ it('names only class selectors that a component still renders', () => {+ expect(RENDERED_MARKDOWN_CONTAINERS.length).toBeGreaterThan(0)+ for (const sel of RENDERED_MARKDOWN_CONTAINERS) {+ expect(sel.startsWith('.'), sel).toBe(true)+ const cls = sel.slice(1)+ const used = all.some((src) => new RegExp(`className=["'{][^"'}]*\\b${cls}\\b`).test(src))+ expect(used, `${cls} is not rendered by any component`).toBe(true)+ }+ })++ it('covers every component that injects rendered markdown HTML', () => {+ // Any file that pipes renderMarkdown output into dangerouslySetInnerHTML must do it inside one+ // of the listed containers — a new markdown surface has to join the list.+ const offenders = sources(RENDERER)+ .filter((f) => {+ const src = fs.readFileSync(f, 'utf8')+ return /renderMarkdown/.test(src) && /dangerouslySetInnerHTML/.test(src)+ })+ // NoteMarkdown takes its container class from its callers — pinned by the next test.+ .filter((f) => path.basename(f) !== 'NoteMarkdown.tsx')+ .filter((f) => {+ const src = fs.readFileSync(f, 'utf8')+ return !RENDERED_MARKDOWN_CONTAINERS.some((sel) => src.includes(sel.slice(1)))+ })+ expect(offenders.map((f) => path.relative(RENDERER, f))).toEqual([])+ })++ it('every NoteMarkdown usage renders into a listed container', () => {+ const usages = all.flatMap((src) => [...src.matchAll(/<NoteMarkdown\b[^>]*>/g)].map((m) => m[0]))+ expect(usages.length).toBeGreaterThan(0)+ for (const u of usages) {+ const cls = /className="([^"]+)"/.exec(u)?.[1] ?? ''+ expect(+ RENDERED_MARKDOWN_CONTAINERS.some((sel) => cls.split(/\s+/).includes(sel.slice(1))),+ u+ ).toBe(true)+ }+ })+})diff --git a/src/renderer/lib/markdownLinks.ts b/src/renderer/lib/markdownLinks.tsnew file mode 100644index 000000000..a8016b0eb--- /dev/null+++ b/src/renderer/lib/markdownLinks.ts@@ -0,0 +1,95 @@+// Clicks on links inside RENDERED MARKDOWN must never navigate the app's own window.+//+// `renderMarkdown` (marked + DOMPurify) keeps an anchor's href as written, and agents write+// relative links constantly — Claude's `[pty-manager.ts](src/core/pty-manager.ts:4100)`. A plain+// click on one resolves against the app document: on the desktop that is another `file://` path+// (the main window navigated to a file that does not exist and the whole canvas was gone until a+// reload); in the Server Edition ANY `<a href>` click — relative or http(s) — navigated the app's+// own browser tab away. The main process's `will-navigate` guard (src/main/navigation-guard.ts)+// is the desktop backstop; this handler is the first line on every surface, and the ONLY line in+// a browser, where nothing sits above the page.+//+// One delegated, document-level, bubble-phase listener installed once at boot (boot.tsx), scoped+// by a selector list of the containers markdown is rendered into. Delegation rather than a handler+// per component on purpose: the markdown surfaces are owned by different components (terminal ⌘M+// view, ChatPanel, sticky notes on the canvas and in the kanban card modal, the editor preview),+// and a per-component handler is one more thing every new surface has to remember.+//+// Local (non-web) links show a toast rather than opening a file: resolving a path the way the+// terminal's Cmd+click file links do needs the owning node's cwd AND its filesystem dialect+// (session source, core platform, SSH/relay — see TerminalNode's `pathConvention`), which is+// per-node state a document-level handler cannot see. A wrong guess would open the wrong file on+// the wrong machine, so this degrades to "say so" instead.++/**+ * CONTRACT: the container classes rendered markdown HTML is injected into. Every component that+ * pipes `renderMarkdown` output into `dangerouslySetInnerHTML` must render it inside one of these —+ * `markdownLinks.test.ts` fails when a listed class stops being rendered or when a new markdown+ * surface renders outside the list.+ * - `.term-md__content` — terminal ⌘M markdown view (TerminalNode) and the editor's Preview+ * - `.term-chat__text` — ⌘M transcript bubbles (ChatPanel)+ * - `.sticky-node__md` — sticky notes, canvas node AND kanban card modal (NoteMarkdown)+ */+export const RENDERED_MARKDOWN_CONTAINERS: readonly string[] = [+ '.term-md__content',+ '.term-chat__text',+ '.sticky-node__md'+]++export type MarkdownLinkDecision =+ | { action: 'external'; url: string }+ | { action: 'ignore' }+ | { action: 'local' }++const EXTERNAL_PROTOCOLS = new Set(['http:', 'https:', 'mailto:'])++/** What to do with a click on an anchor whose RAW `href` attribute is `rawHref`. Decided on the+ * raw attribute, never on the resolved `a.href`, because resolution against the app document is+ * exactly what turns a harmless relative path into a navigation. */+export function decideMarkdownLinkClick(rawHref: string): MarkdownLinkDecision {+ const href = rawHref.trim()+ // `#x` is a same-document fragment; `""` resolves to the document itself (a reload). Neither+ // does anything useful here, and a hash change could trip hash-keyed dev routes.+ if (href === '' || href.startsWith('#')) return { action: 'ignore' }+ let parsed: URL+ try {+ // No base: only an ABSOLUTE URL parses. Relative and protocol-relative hrefs throw → local.+ parsed = new URL(href)+ } catch {+ return { action: 'local' }+ }+ if (EXTERNAL_PROTOCOLS.has(parsed.protocol)) return { action: 'external', url: parsed.href }+ return { action: 'local' }+}++export interface MarkdownLinkDeps {+ openExternal(url: string): void+ /** A link that cannot be opened from this view was clicked. */+ notifyLocal(): void+}++/** Install the delegated handler; returns its uninstaller. */+export function installMarkdownLinkGuard(doc: Document, deps: MarkdownLinkDeps): () => void {+ const scope = RENDERED_MARKDOWN_CONTAINERS.join(',')+ const onClick = (e: MouseEvent): void => {+ // Someone closer to the anchor already owned this click; and only the primary button — a+ // middle click never fires `click`, and a secondary one is the context menu's.+ if (e.defaultPrevented || e.button !== 0) return+ const target = e.target+ if (!(target instanceof Element)) return+ const anchor = target.closest('a[href]')+ if (!anchor || !anchor.closest(scope)) return+ // Modifier clicks are handled the same way: nothing else in the app owns Cmd/Ctrl/Shift+click+ // on rendered markdown, and letting the default run would open a new window/tab on the same+ // unresolvable relative URL.+ e.preventDefault()+ const decision = decideMarkdownLinkClick(anchor.getAttribute('href') ?? '')+ if (decision.action === 'external') deps.openExternal(decision.url)+ else if (decision.action === 'local') deps.notifyLocal()+ }+ doc.addEventListener('click', onClick)+ return () => doc.removeEventListener('click', onClick)+}++/** The message shown for a local link. */+export const LOCAL_LINK_MESSAGE = "Local file links can't be opened from rendered markdown."