Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: render Brain notes through the shared MarkdownOutput renderer
[._.]/ Adam Eivy062b11388a66
diff --git a/client/src/components/brain/tabs/NotesTab.jsx b/client/src/components/brain/tabs/NotesTab.jsxindex 4c83c586aa..8464f56b21 100644--- a/client/src/components/brain/tabs/NotesTab.jsx+++ b/client/src/components/brain/tabs/NotesTab.jsx@@ -26,6 +26,7 @@ import { clickableProps, onActivateKeyDown } from '../../../lib/a11yKeyboard.js'import OfflineNotesNotice from '../../OfflineNotesNotice.jsx';import NoteDetailPane from '../../notes/NoteDetailPane.jsx';import useVaultNote from '../../../hooks/useVaultNote.js';+import MarkdownOutput from '../../cos/MarkdownOutput.jsx';function UnavailableState({ title, message, onRetry }) {return (@@ -662,7 +663,7 @@ export default function NotesTab() {onRequestDelete={requestDelete} onDelete={handleDeleteNote}onCancelDelete={cancelDelete} forceOffered={forceOffered}dismissForce={dismissForce}- renderPreview={content => <MarkdownPreview content={content} onLinkClick={handleSelectNote} />}+ renderPreview={content => <MarkdownOutput content={content} linkifyText={noteLinkify(handleSelectNote)} />}renderLinks={note => (<><LinkSection icon={<Link2 size={10} />} label="Links" items={note.wikilinks}@@ -899,223 +900,20 @@ function NoteListItem({ note, selected, onClick, compact, isSearch }) {);}-/**- * Simple markdown preview renderer- * Handles headings, bold, italic, code, links, wikilinks, lists, blockquotes- */-function MarkdownPreview({ content, onLinkClick }) {- if (!content) return null;-- const lines = content.split('\n');- const elements = [];- let inCodeBlock = false;- let codeLines = [];-- for (let i = 0; i < lines.length; i++) {- const line = lines[i];-- // Code blocks- if (line.trimStart().startsWith('```')) {- if (inCodeBlock) {- elements.push(- <pre key={i} className="bg-port-bg border border-port-border rounded p-3 overflow-x-auto text-sm text-gray-300 font-mono my-2">- <code>{codeLines.join('\n')}</code>- </pre>- );- codeLines = [];- inCodeBlock = false;- } else {- inCodeBlock = true;- }- continue;- }-- if (inCodeBlock) {- codeLines.push(line);- continue;- }-- // Empty lines- if (!line.trim()) {- elements.push(<div key={i} className="h-3" />);- continue;- }-- // Headings- const headingMatch = line.match(/^(#{1,6})\s+(.+)/);- if (headingMatch) {- const level = headingMatch[1].length;- const sizes = ['text-2xl', 'text-xl', 'text-lg', 'text-base', 'text-sm', 'text-xs'];- elements.push(- <div key={i} className={`${sizes[level - 1]} font-bold text-white mt-4 mb-2`}>- {renderInline(headingMatch[2], onLinkClick)}- </div>- );- continue;- }-- // Horizontal rule- if (/^---+$/.test(line.trim()) || /^\*\*\*+$/.test(line.trim())) {- elements.push(<hr key={i} className="border-port-border my-3" />);- continue;- }-- // Blockquotes- if (line.trimStart().startsWith('> ')) {- elements.push(- <div key={i} className="border-l-2 border-port-accent/40 pl-3 text-gray-400 text-sm italic my-1">- {renderInline(line.replace(/^>\s*/, ''), onLinkClick)}- </div>- );- continue;- }-- // Unordered lists- const listMatch = line.match(/^(\s*)[*-]\s+(.+)/);- if (listMatch) {- const indent = Math.floor(listMatch[1].length / 2);- elements.push(- <div key={i} className="text-sm text-gray-300 my-0.5" style={{ paddingLeft: `${indent * 16 + 16}px` }}>- <span className="text-gray-500 mr-2">•</span>- {renderInline(listMatch[2], onLinkClick)}- </div>- );- continue;- }-- // Ordered lists- const olMatch = line.match(/^(\s*)\d+\.\s+(.+)/);- if (olMatch) {- const indent = Math.floor(olMatch[1].length / 2);- elements.push(- <div key={i} className="text-sm text-gray-300 my-0.5" style={{ paddingLeft: `${indent * 16 + 16}px` }}>- {renderInline(olMatch[2], onLinkClick)}- </div>- );- continue;- }-- // Checkbox items- const checkMatch = line.match(/^(\s*)[*-]\s+\[([ xX])\]\s+(.+)/);- if (checkMatch) {- const checked = checkMatch[2] !== ' ';- elements.push(- <div key={i} className={`text-sm my-0.5 flex items-start gap-2 ${checked ? 'text-gray-500 line-through' : 'text-gray-300'}`} style={{ paddingLeft: '16px' }}>- <span className="mt-0.5">{checked ? '☑' : '☐'}</span>- {renderInline(checkMatch[3], onLinkClick)}- </div>- );- continue;+// Note-specific inline syntax the shared renderer leaves as literal text:+// `[[target|display]]` opens that vault note in place, and `#tag` gets the+// accent tint. Everything else — including href vetting for `[text](url)` —+// is MarkdownOutput's.+const NOTE_INLINE_RE = /(\[\[[^\]|]+(?:\|[^\]]+)?\]\]|(?<=^|\s)#[a-zA-Z][a-zA-Z0-9_/-]*)/;++function noteLinkify(onLinkClick) {+ return text => text.split(NOTE_INLINE_RE).filter(Boolean).map(seg => {+ const wiki = seg.match(/^\[\[([^\]|]+)(?:\|([^\]]+))?\]\]$/);+ if (wiki) {+ const target = wiki[1].trim();+ return { ref: wiki[2]?.trim() || target, onClick: () => onLinkClick?.(`${target}.md`) };}-- // Regular paragraph- elements.push(- <p key={i} className="text-sm text-gray-300 my-1 leading-relaxed">- {renderInline(line, onLinkClick)}- </p>- );- }-- // Close unclosed code block- if (inCodeBlock && codeLines.length > 0) {- elements.push(- <pre key="unclosed-code" className="bg-port-bg border border-port-border rounded p-3 overflow-x-auto text-sm text-gray-300 font-mono my-2">- <code>{codeLines.join('\n')}</code>- </pre>- );- }-- return <div className="prose-dark">{elements}</div>;-}--/**- * Render inline markdown: bold, italic, code, links, wikilinks, tags- */-function renderInline(text, onLinkClick) {- if (!text) return null;-- // Split on inline patterns and rebuild- const parts = [];- let remaining = text;- let key = 0;-- while (remaining) {- // Wikilinks: [[target|display]] or [[target]]- const wikiMatch = remaining.match(/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/);- // Inline code- const codeMatch = remaining.match(/`([^`]+)`/);- // Bold- const boldMatch = remaining.match(/\*\*(.+?)\*\*/);- // Italic- const italicMatch = remaining.match(/(?<!\*)\*([^*]+)\*(?!\*)/);- // External links: [text](url)- const linkMatch = remaining.match(/\[([^\]]+)\]\(([^)]+)\)/);- // Tags: #tag- const tagMatch = remaining.match(/(?:^|\s)(#[a-zA-Z][a-zA-Z0-9_/-]*)/);-- // Find earliest match- const matches = [- wikiMatch && { type: 'wiki', match: wikiMatch },- codeMatch && { type: 'code', match: codeMatch },- boldMatch && { type: 'bold', match: boldMatch },- italicMatch && { type: 'italic', match: italicMatch },- linkMatch && { type: 'link', match: linkMatch },- tagMatch && { type: 'tag', match: tagMatch }- ].filter(Boolean).sort((a, b) => a.match.index - b.match.index);-- if (matches.length === 0) {- parts.push(remaining);- break;- }-- const first = matches[0];- const before = remaining.slice(0, first.match.index);- if (before) parts.push(before);-- switch (first.type) {- case 'wiki': {- const target = first.match[1].trim();- const display = first.match[2]?.trim() || target;- parts.push(- <button- key={key++}- onClick={() => onLinkClick?.(target + '.md')}- className="text-port-accent hover:text-white hover:underline"- >- {display}- </button>- );- break;- }- case 'code':- parts.push(- <code key={key++} className="bg-port-bg border border-port-border rounded px-1 py-0.5 text-xs text-port-accent font-mono">- {first.match[1]}- </code>- );- break;- case 'bold':- parts.push(<strong key={key++} className="text-white font-semibold">{first.match[1]}</strong>);- break;- case 'italic':- parts.push(<em key={key++} className="text-gray-400 italic">{first.match[1]}</em>);- break;- case 'link':- parts.push(- <a key={key++} href={first.match[2]} target="_blank" rel="noopener noreferrer" className="text-port-accent hover:underline">- {first.match[1]}- </a>- );- break;- case 'tag':- parts.push(- <span key={key++} className="text-port-accent/70">{first.match[1]}</span>- );- break;- }-- remaining = remaining.slice(first.match.index + first.match[0].length);- }-- return parts;+ if (seg[0] === '#') return { ref: seg, className: 'text-port-accent/70' };+ return seg;+ });}diff --git a/client/src/components/brain/tabs/NotesTab.test.jsx b/client/src/components/brain/tabs/NotesTab.test.jsxindex a0b11f4ab8..2b9e6f6672 100644--- a/client/src/components/brain/tabs/NotesTab.test.jsx+++ b/client/src/components/brain/tabs/NotesTab.test.jsx@@ -661,3 +661,46 @@ describe('NotesTab URL state and unavailable reads', () => {expect(screen.queryByText('Search is unavailable')).toBeNull();});});++describe('NotesTab preview rendering', () => {+ const note = (name, content) => ({+ path: `${name}.md`, name, folder: '', size: 12, tags: [],+ modifiedAt: '2026-09-11T00:00:00Z', content, body: content, backlinks: []+ });++ beforeEach(() => {+ vi.resetAllMocks();+ api.getNotesVaults.mockResolvedValue([{ id: 'a', name: 'Vault A' }]);+ api.scanNotesVault.mockResolvedValue({ notes: [note('first', ''), note('second', 'second body')], total: 2 });+ api.getNotesVaultFolders.mockResolvedValue({ folders: [] });+ api.getNotesVaultTags.mockResolvedValue({ tags: [] });+ });++ it('renders notes through the shared markdown renderer with inert unsafe hrefs and live wikilinks', async () => {+ const body = [+ '# Title',+ 'See [docs](https://example.com/docs) and [evil](javascript:alert(1)) and [[second|the other note]] #tagged',+ '- [ ] open task',+ '- [x] done task',+ ].join('\n');+ api.getNote.mockImplementation((_vault, path) => Promise.resolve(path === 'first.md' ? note('first', body) : note('second', 'second body')));+ await renderTab();+ await act(async () => { fireEvent.click(screen.getByText('first')); });++ // The shared renderer clamps embedded headings below the page outline.+ expect(screen.getByRole('heading', { level: 3, name: 'Title' })).toBeInTheDocument();+ expect(screen.getByRole('link', { name: 'docs' })).toHaveAttribute('href', 'https://example.com/docs');+ // A javascript: destination never becomes an anchor — the label stays as text.+ expect(screen.queryByRole('link', { name: 'evil' })).toBeNull();+ expect(screen.getByText('evil')).toBeInTheDocument();+ expect(screen.getByText('#tagged')).toBeInTheDocument();+ expect(screen.getByText('open task')).toBeInTheDocument();+ expect(screen.getByText('done task').closest('li').className).toContain('line-through');++ // A wikilink opens the target note in place.+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'the other note' })); });+ expect(api.getNote).toHaveBeenLastCalledWith('a', 'second.md', { silent: true });+ expect(screen.getByRole('heading', { name: 'second' })).toBeInTheDocument();+ expect(screen.getByTestId('location').textContent).toContain('note=second.md');+ });+});diff --git a/client/src/components/cos/MarkdownOutput.jsx b/client/src/components/cos/MarkdownOutput.jsxindex 7393115ea0..bb83c83edc 100644--- a/client/src/components/cos/MarkdownOutput.jsx+++ b/client/src/components/cos/MarkdownOutput.jsx@@ -23,15 +23,24 @@ function renderText(text, linkifyText, key) {// no-reference path costs exactly what it did before the resolver existed.if (!segments || (segments.length === 1 && typeof segments[0] === 'string')) return [text];return segments.map((seg, i) => {- // `safeSrc` for the same reason a markdown link's href gets it: the- // resolver is supplied by the caller, and a `javascript:`/`data:`- // destination must not become an anchor just because it arrived through a- // different door. A rejected destination degrades to the literal text.- const href = seg?.url ? safeSrc(seg.url) : null;- if (!seg?.url) return seg;- return href- ? <a key={`${key}-${i}`} href={href} className={LINK_CLASS} target="_blank" rel="noopener noreferrer">{seg.ref}</a>- : seg.ref;+ if (typeof seg === 'string') return seg;+ const segKey = `${key}-${i}`;+ if (seg.url) {+ // `safeSrc` for the same reason a markdown link's href gets it: the+ // resolver is supplied by the caller, and a `javascript:`/`data:`+ // destination must not become an anchor just because it arrived through+ // a different door. A rejected destination degrades to the literal text.+ const href = safeSrc(seg.url);+ return href+ ? <a key={segKey} href={href} className={LINK_CLASS} target="_blank" rel="noopener noreferrer">{seg.ref}</a>+ : seg.ref;+ }+ // An in-app destination (a vault wikilink) has no href at all — it is a+ // button the caller handles, so there is no URL to vet.+ if (seg.onClick) {+ return <button key={segKey} type="button" onClick={seg.onClick} className="text-port-accent hover:text-white hover:underline">{seg.ref}</button>;+ }+ return seg.className ? <span key={segKey} className={seg.className}>{seg.ref}</span> : seg.ref;});}@@ -126,11 +135,22 @@ function parseBlocks(md, baseLevel, linkifyText, preserveLineBreaks) {continue;}- // Unordered list+ // Unordered list. A GFM task item (`- [ ] todo` / `- [x] done`) renders+ // its box as a glyph instead of a bullet; a checked one is struck through.if (/^[-*+] /.test(line)) {const items = [];while (i < lines.length && /^[-*+] /.test(lines[i])) { items.push(lines[i].replace(/^[-*+] /, '')); i++; }- blocks.push(<ul key={`ul${i}`} className="my-0.5 pl-4 space-y-0.5">{items.map((it, j) => <li key={j} className="text-xs text-gray-300 list-disc">{parseInline(it, linkifyText)}</li>)}</ul>);+ blocks.push(<ul key={`ul${i}`} className="my-0.5 pl-4 space-y-0.5">{items.map((it, j) => {+ const task = it.match(/^\[([ xX])\]\s+(.*)$/);+ if (!task) return <li key={j} className="text-xs text-gray-300 list-disc">{parseInline(it, linkifyText)}</li>;+ const checked = task[1] !== ' ';+ return (+ <li key={j} className={`text-xs list-none -ml-4 flex items-start gap-2 ${checked ? 'text-gray-500 line-through' : 'text-gray-300'}`}>+ <span aria-hidden="true">{checked ? '☑' : '☐'}</span>+ <span>{parseInline(task[2], linkifyText)}</span>+ </li>+ );+ })}</ul>);continue;}@@ -183,10 +203,12 @@ function parseBlocks(md, baseLevel, linkifyText, preserveLineBreaks) {return blocks;}-// `linkifyText(text) => Array<string | { ref, url }>` optionally turns spans of-// literal text into links — how a CoS run card resolves the bare `#7640` an-// agent wrote in its summary against that run's own tracker. Omit it and the-// text renders exactly as before.+// `linkifyText(text) => Array<string | { ref, url } | { ref, onClick } | { ref, className }>`+// optionally turns spans of literal text into links — how a CoS run card+// resolves the bare `#7640` an agent wrote in its summary against that run's+// own tracker, and how a vault note turns `[[wikilinks]]` into in-app buttons+// and `#tags` into tinted spans. Omit it and the text renders exactly as+// before.export default function MarkdownOutput({ content, baseLevel = 3, linkifyText = null, preserveLineBreaks = false }) {return (<div className="markdown-output min-w-0 overflow-hidden break-words">diff --git a/client/src/components/cos/MarkdownOutput.test.jsx b/client/src/components/cos/MarkdownOutput.test.jsxindex 6ad12527dd..fcedde1a85 100644--- a/client/src/components/cos/MarkdownOutput.test.jsx+++ b/client/src/components/cos/MarkdownOutput.test.jsx@@ -1,4 +1,4 @@-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi } from 'vitest';import { render, screen } from '@testing-library/react';import MarkdownOutput from './MarkdownOutput';@@ -131,3 +131,34 @@ describe('preserveLineBreaks', () => {expect(container.querySelector('p').textContent).toBe('first linesecond line');});});++describe('task list items', () => {+ it('renders GFM checkboxes as glyphs and strikes through the checked ones', () => {+ render(<MarkdownOutput content={'- [ ] open\n- [x] done\n- plain'} />);+ const open = screen.getByText('open').closest('li');+ const done = screen.getByText('done').closest('li');+ expect(open).toHaveTextContent('☐open');+ expect(open.className).not.toContain('line-through');+ expect(done).toHaveTextContent('☑done');+ expect(done.className).toContain('line-through');+ expect(screen.getByText('plain').className).toContain('list-disc');+ });+});++describe('resolver segments without a URL', () => {+ it('renders an onClick segment as a button and a className segment as a styled span', () => {+ const onClick = vi.fn();+ const linkifyText = (text) => text.split(/(\[\[[^\]]+\]\]|#\w+)/).filter(Boolean).map(seg => {+ if (seg.startsWith('[[')) return { ref: seg.slice(2, -2), onClick };+ if (seg.startsWith('#')) return { ref: seg, className: 'text-port-accent/70' };+ return seg;+ });+ render(<MarkdownOutput content="open [[Other Note]] #tag" linkifyText={linkifyText} />);+ const button = screen.getByRole('button', { name: 'Other Note' });+ expect(button).toHaveAttribute('type', 'button');+ button.click();+ expect(onClick).toHaveBeenCalledTimes(1);+ expect(screen.queryByRole('link')).toBeNull();+ expect(screen.getByText('#tag').className).toContain('text-port-accent/70');+ });+});