Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(markdown): render GFM tables in previews
Me80a61032f32
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex 43ddaf14e..f27db4edb 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -13001,6 +13001,51 @@ button.cu-gfs-tree__button:focus-visible,overflow-wrap: anywhere;}+.cu-gfs-markdown-preview__content img {+ max-width: 100%;+ height: auto;+}++.cu-gfs-markdown-preview__content .gfs-markdown-table-scroll {+ max-width: 100%;+ overflow-x: auto;+ margin: 0 0 var(--cu-space-3);+ overscroll-behavior-x: contain;+}++.cu-gfs-markdown-preview__content .gfs-markdown-table-scroll:focus-visible {+ outline: 2px solid rgba(var(--cu-focus-rgb), 0.8);+ outline-offset: 2px;+}++.cu-gfs-markdown-preview__content .gfs-markdown-table-scroll table {+ width: max-content;+ min-width: 100%;+ border-collapse: collapse;+}++.cu-gfs-markdown-preview__content .gfs-markdown-table-scroll th,+.cu-gfs-markdown-preview__content .gfs-markdown-table-scroll td {+ max-width: 24rem;+ overflow-wrap: anywhere;+ padding: var(--cu-space-2) var(--cu-space-3);+ border: 1px solid var(--cu-border-subtle);+ text-align: left;+ vertical-align: top;+}++.cu-gfs-markdown-preview__content .gfs-markdown-table-scroll th {+ background: rgba(var(--cu-edge-rgb), 0.14);+ color: var(--cu-text);+ font-size: inherit;+ font-weight: 600;+ letter-spacing: normal;+ position: static;+ text-transform: none;+ white-space: normal;+ z-index: auto;+}+.cu-gfs-markdown-preview__content > :first-child {margin-top: 0;}diff --git a/control-ui/components/GfsMarkdownPreview/index.tsx b/control-ui/components/GfsMarkdownPreview/index.tsxindex d7fceccd0..7b2d6b923 100644--- a/control-ui/components/GfsMarkdownPreview/index.tsx+++ b/control-ui/components/GfsMarkdownPreview/index.tsx@@ -1,66 +1,74 @@'use client'-import { Fragment, useEffect, useId, useMemo, useRef, useState } from 'react'-import type { ReactNode } from 'react'+import { useEffect, useId, useRef, useState } from 'react'import { createPortal } from 'react-dom'+import ReactMarkdown from 'react-markdown'+import type { Components } from 'react-markdown'+import remarkGfm from 'remark-gfm'+import { DataTable, TableViewport } from '@clerum/frontend-components'import { IconCopy } from '@components/Sidebar/icons'import { useToast } from '@components/Toast'import { IconX } from '@components/icons'import { Button } from '@components/ui'import { gfsFetchFileBlob } from '@lib/api'import { assertGfsMarkdownPreviewSize } from '@lib/gfsMarkdownPreview'-import { parseVanillaMarkdown } from '@lib/vanillaMarkdown'-import type { MarkdownBlock, MarkdownInlineNode } from '@lib/vanillaMarkdown.types'import type { GfsMarkdownPreviewProps } from './types'-function renderInlineNodes(nodes: MarkdownInlineNode[]): ReactNode[] {- return nodes.map(node => {- if (node.kind === 'text') return <Fragment key={node.id}>{node.value}</Fragment>- if (node.kind === 'code') return <code key={node.id}>{node.value}</code>- const children = renderInlineNodes(node.children)- if (node.kind === 'strong') return <strong key={node.id}>{children}</strong>- if (node.kind === 'emphasis') return <em key={node.id}>{children}</em>- if (node.kind === 'strikethrough') return <s key={node.id}>{children}</s>- return node.href ? (- <a href={node.href} key={node.id} rel="noreferrer" target="_blank">+function transformMarkdownUrl(url: string, key: string): string {+ const value = url.trim()+ if (key === 'src') {+ return /^(?:https:\/\/|data:image\/(?:png|gif|jpe?g|webp);base64,)/i.test(value) ? value : ''+ }+ return /^(?:https?:\/\/|mailto:|#)/i.test(value) ? value : ''+}++const GFS_MARKDOWN_COMPONENTS: Components = {+ a: ({ children, href, node, ...props }) => {+ void node+ return href ? (+ <a {...props} href={href} rel="noreferrer" target="_blank">{children}</a>) : (- <span key={node.id}>{children}</span>+ <span>{children}</span>)- })-}--function renderHeading(block: Extract<MarkdownBlock, { kind: 'heading' }>): ReactNode {- const children = renderInlineNodes(block.children)- if (block.level === 1) return <h1 key={block.id}>{children}</h1>- if (block.level === 2) return <h2 key={block.id}>{children}</h2>- if (block.level === 3) return <h3 key={block.id}>{children}</h3>- if (block.level === 4) return <h4 key={block.id}>{children}</h4>- if (block.level === 5) return <h5 key={block.id}>{children}</h5>- return <h6 key={block.id}>{children}</h6>-}--function renderBlock(block: MarkdownBlock): ReactNode {- if (block.kind === 'heading') return renderHeading(block)- if (block.kind === 'paragraph') {- return <p key={block.id}>{renderInlineNodes(block.children)}</p>- }- if (block.kind === 'blockquote') {- return <blockquote key={block.id}>{renderInlineNodes(block.children)}</blockquote>- }- if (block.kind === 'divider') return <hr key={block.id} />- if (block.kind === 'code') {+ },+ img: ({ alt, node, src, ...props }) => {+ void node+ return src ? (+ <img {...props} alt={alt ?? ''} loading="lazy" referrerPolicy="no-referrer" src={src} />+ ) : alt ? (+ <span>{alt}</span>+ ) : null+ },+ table: ({ children, node, ...props }) => {+ void nodereturn (- <pre key={block.id}>- <code data-language={block.language ?? undefined}>{block.value}</code>- </pre>+ <TableViewport+ aria-label="Scrollable Markdown table"+ className="gfs-markdown-table-scroll"+ embedded+ role="region"+ tabIndex={0}+ >+ <DataTable {...props} className="cu-table gfs-markdown-table" variant="embedded">+ {children}+ </DataTable>+ </TableViewport>)- }- const items = block.items.map(item => <li key={item.id}>{renderInlineNodes(item.children)}</li>)- return block.ordered ? <ol key={block.id}>{items}</ol> : <ul key={block.id}>{items}</ul>+ },+ th: ({ children, node, ...props }) => {+ void node+ return (+ <th {...props} scope={props.scope ?? 'col'}>+ {children}+ </th>+ )+ },}+const GFS_MARKDOWN_REMARK_PLUGINS = [remarkGfm]+function isPlainTextName(fileName: string): boolean {return fileName.toLowerCase().endsWith('.txt')}@@ -79,7 +87,6 @@ export function GfsMarkdownPreview({const copyResetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)const mountedRef = useRef(true)const { showToast } = useToast()- const blocks = useMemo(() => (source === null ? [] : parseVanillaMarkdown(source)), [source])const isPlainText = isPlainTextName(fileName)useEffect(() => {@@ -233,8 +240,14 @@ export function GfsMarkdownPreview({aria-label={`Markdown preview of ${fileName}`}className="cu-gfs-markdown-preview__content">- {blocks.length > 0 ? (- blocks.map(renderBlock)+ {source.trim() ? (+ <ReactMarkdown+ components={GFS_MARKDOWN_COMPONENTS}+ remarkPlugins={GFS_MARKDOWN_REMARK_PLUGINS}+ urlTransform={transformMarkdownUrl}+ >+ {source}+ </ReactMarkdown>) : (<p className="cu-gfs-markdown-preview__empty">This Markdown file is empty.</p>)}diff --git a/control-ui/components/__tests__/GfsMarkdownPreview.test.tsx b/control-ui/components/__tests__/GfsMarkdownPreview.test.tsxnew file mode 100644index 000000000..b4a94a07e--- /dev/null+++ b/control-ui/components/__tests__/GfsMarkdownPreview.test.tsx@@ -0,0 +1,97 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { cleanup, render, screen, within } from '@testing-library/react'+import { GfsMarkdownPreview } from '../GfsMarkdownPreview'+import { ToastProvider } from '../Toast'++const mockGfsFetchFileBlob = vi.fn()++vi.mock('@lib/api', () => ({+ gfsFetchFileBlob: (...args: unknown[]) => mockGfsFetchFileBlob(...args),+}))++function renderMarkdownPreview(markdown: string, fileName = 'inventory.md') {+ mockGfsFetchFileBlob.mockResolvedValueOnce(new Blob([markdown], { type: 'text/markdown' }))++ return render(+ <ToastProvider>+ <GfsMarkdownPreview+ byteLength={new TextEncoder().encode(markdown).byteLength}+ fileName={fileName}+ onClose={vi.fn()}+ rid="r-markdown"+ />+ </ToastProvider>+ )+}++describe('GfsMarkdownPreview', () => {+ beforeEach(() => {+ mockGfsFetchFileBlob.mockReset()+ })++ afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ })++ it('renders GFM tables accessibly alongside other Markdown content', async () => {+ const markdown = [+ '# Inventory',+ '',+ '| Item | Count |',+ '| --- | ---: |',+ '| **GFS files** | 12 |',+ '',+ '- [x] Review complete',+ '',+ '> Checked this morning.',+ '',+ '',+ '',+ '[Documentation](https://example.com/docs)',+ '[Unsafe link](javascript:alert(1))',+ '<script>alert(1)</script>',+ ].join('\n')++ renderMarkdownPreview(markdown)++ const article = await screen.findByRole('article', {+ name: 'Markdown preview of inventory.md',+ })+ const table = within(article).getByRole('table')+ expect(within(table).getByRole('columnheader', { name: 'Item' })).toHaveAttribute(+ 'scope',+ 'col'+ )+ expect(within(table).getByRole('cell', { name: 'GFS files' })).toBeInTheDocument()+ expect(screen.getByRole('region', { name: 'Scrollable Markdown table' })).toHaveAttribute(+ 'tabindex',+ '0'+ )+ expect(within(article).getByRole('heading', { name: 'Inventory' })).toBeInTheDocument()+ expect(within(article).getByRole('checkbox')).toBeDisabled()+ expect(within(article).getByRole('img', { name: 'Trend chart' })).toHaveAttribute(+ 'referrerpolicy',+ 'no-referrer'+ )+ expect(within(article).getByRole('link', { name: 'Documentation' })).toHaveAttribute(+ 'target',+ '_blank'+ )+ expect(within(article).queryByRole('link', { name: 'Unsafe link' })).not.toBeInTheDocument()+ expect(article.querySelector('script')).toBeNull()+ })++ it('leaves malformed table syntax readable without constructing a table', async () => {+ const markdown = '| Broken | Table |\n| not a separator |\n| still text | here |'++ renderMarkdownPreview(markdown, 'malformed.md')++ const article = await screen.findByRole('article', {+ name: 'Markdown preview of malformed.md',+ })+ expect(within(article).queryByRole('table')).not.toBeInTheDocument()+ expect(article).toHaveTextContent('Broken')+ expect(article).toHaveTextContent('not a separator')+ })+})diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex f00f3900c..5e6c53516 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.608",+ "version": "0.1.609","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.608",+ "version": "0.1.609","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/frontend-components": "file:../packages/frontend-components",@@ -17,7 +17,9 @@"next": "^16.3.5","react": "^18.3.1","react-dom": "^18.3.1",+ "react-markdown": "^10.1.0","recharts": "^3.8.1",+ "remark-gfm": "^4.0.1","yaml": "^2.8.3"},"devDependencies": {diff --git a/control-ui/package.json b/control-ui/package.jsonindex fb19480cd..569aa1d0a 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.608",+ "version": "0.1.609","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",@@ -71,7 +71,9 @@"next": "^16.3.5","react": "^18.3.1","react-dom": "^18.3.1",+ "react-markdown": "^10.1.0","recharts": "^3.8.1",+ "remark-gfm": "^4.0.1","yaml": "^2.8.3"},"overrides": {diff --git a/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsx b/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsxindex f4380f676..f53c44fc7 100644--- a/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsx+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsx@@ -1,66 +1,70 @@-import { Fragment, useEffect, useId, useMemo, useRef, useState } from 'react'-import type { ReactNode } from 'react'+import { useEffect, useId, useRef, useState } from 'react'+import ReactMarkdown from 'react-markdown'+import type { Components } from 'react-markdown'+import remarkGfm from 'remark-gfm'import { Button, StatusBanner } from '@components/Common'import { IconCopy } from '@components/SidebarNav/icons'import { GFS_MARKDOWN_PREVIEW_MAX_BYTES } from '@constants/gfsMarkdownPreview'import { describeGfsReadError } from '@lib/gfsGrantErrors'import { assertGfsMarkdownPreviewSize } from '@lib/gfsMarkdownPreview'-import { parseVanillaMarkdown } from '@lib/vanillaMarkdown'-import type { MarkdownBlock, MarkdownInlineNode } from '@lib/vanillaMarkdown.types'import type { GfsMarkdownPreviewBodyProps } from './types'function isPlainTextName(fileName: string): boolean {return fileName.toLowerCase().endsWith('.txt')}-function renderInlineNodes(nodes: MarkdownInlineNode[]): ReactNode[] {- return nodes.map(node => {- if (node.kind === 'text') return <Fragment key={node.id}>{node.value}</Fragment>- if (node.kind === 'code') return <code key={node.id}>{node.value}</code>- const children = renderInlineNodes(node.children)- if (node.kind === 'strong') return <strong key={node.id}>{children}</strong>- if (node.kind === 'emphasis') return <em key={node.id}>{children}</em>- if (node.kind === 'strikethrough') return <s key={node.id}>{children}</s>- return node.href ? (- <a href={node.href} key={node.id} rel="noreferrer" target="_blank">+function transformMarkdownUrl(url: string, key: string): string {+ const value = url.trim()+ if (key === 'src') {+ return /^(?:https:\/\/|data:image\/(?:png|gif|jpe?g|webp);base64,)/i.test(value) ? value : ''+ }+ return /^(?:https?:\/\/|mailto:|#)/i.test(value) ? value : ''+}++const GFS_MARKDOWN_COMPONENTS: Components = {+ a: ({ children, href, node, ...props }) => {+ void node+ return href ? (+ <a {...props} href={href} rel="noreferrer" target="_blank">{children}</a>) : (- <span key={node.id}>{children}</span>+ <span>{children}</span>)- })-}--function renderHeading(block: Extract<MarkdownBlock, { kind: 'heading' }>): ReactNode {- const children = renderInlineNodes(block.children)- if (block.level === 1) return <h1 key={block.id}>{children}</h1>- if (block.level === 2) return <h2 key={block.id}>{children}</h2>- if (block.level === 3) return <h3 key={block.id}>{children}</h3>- if (block.level === 4) return <h4 key={block.id}>{children}</h4>- if (block.level === 5) return <h5 key={block.id}>{children}</h5>- return <h6 key={block.id}>{children}</h6>-}--function renderBlock(block: MarkdownBlock): ReactNode {- if (block.kind === 'heading') return renderHeading(block)- if (block.kind === 'paragraph') {- return <p key={block.id}>{renderInlineNodes(block.children)}</p>- }- if (block.kind === 'blockquote') {- return <blockquote key={block.id}>{renderInlineNodes(block.children)}</blockquote>- }- if (block.kind === 'divider') return <hr key={block.id} />- if (block.kind === 'code') {+ },+ img: ({ alt, node, src, ...props }) => {+ void node+ return src ? (+ <img {...props} alt={alt ?? ''} loading="lazy" referrerPolicy="no-referrer" src={src} />+ ) : alt ? (+ <span>{alt}</span>+ ) : null+ },+ table: ({ children, node, ...props }) => {+ void nodereturn (- <pre key={block.id}>- <code data-language={block.language ?? undefined}>{block.value}</code>- </pre>+ <div+ aria-label="Scrollable Markdown table"+ className="gfs-markdown-table-scroll"+ role="region"+ tabIndex={0}+ >+ <table {...props}>{children}</table>+ </div>)- }- const items = block.items.map(item => <li key={item.id}>{renderInlineNodes(item.children)}</li>)- return block.ordered ? <ol key={block.id}>{items}</ol> : <ul key={block.id}>{items}</ul>+ },+ th: ({ children, node, ...props }) => {+ void node+ return (+ <th {...props} scope={props.scope ?? 'col'}>+ {children}+ </th>+ )+ },}+const GFS_MARKDOWN_REMARK_PLUGINS = [remarkGfm]+/*** De-modalized markdown/text preview body (spec 18 §3.B.2). Owns the byte fetch* (by `gfsUri`), the size-guard, copy-source-to-clipboard, and the rendered@@ -85,7 +89,6 @@ export function GfsMarkdownPreviewBody({const copyResetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)const mountedRef = useRef(true)const onDownloadErrorRef = useRef(onDownloadError)- const blocks = useMemo(() => (source === null ? [] : parseVanillaMarkdown(source)), [source])const isPlainText = isPlainTextName(fileName)const HeadingTag = `h${headingLevel}` as const@@ -215,8 +218,14 @@ export function GfsMarkdownPreviewBody({aria-label={`Markdown preview of ${fileName}`}className="da-gfs-markdown-preview__content markdown-content">- {blocks.length > 0 ? (- blocks.map(renderBlock)+ {source.trim() ? (+ <ReactMarkdown+ components={GFS_MARKDOWN_COMPONENTS}+ remarkPlugins={GFS_MARKDOWN_REMARK_PLUGINS}+ urlTransform={transformMarkdownUrl}+ >+ {source}+ </ReactMarkdown>) : (<p className="da-gfs-markdown-preview__empty">This Markdown file is empty.</p>)}diff --git a/desktop-app/ui/src/components/GfsMarkdownPreview/GfsMarkdownPreviewBody.gfm.test.tsx b/desktop-app/ui/src/components/GfsMarkdownPreview/GfsMarkdownPreviewBody.gfm.test.tsxnew file mode 100644index 000000000..7b2ef77b1--- /dev/null+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/GfsMarkdownPreviewBody.gfm.test.tsx@@ -0,0 +1,94 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from 'vitest'+import { cleanup, render, screen, within } from '@testing-library/react'+import { GfsMarkdownPreviewBody } from './Body'++function stubDownload(text: string) {+ const downloadPreview = vi.fn(async () => ({ bytes: new TextEncoder().encode(text).buffer }))+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: { gfs: { downloadPreview } },+ })+ return downloadPreview+}++describe('GfsMarkdownPreviewBody GFM rendering', () => {+ afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ })++ it('renders accessible tables and other Markdown content safely', async () => {+ const markdown = [+ '# Inventory',+ '',+ '| Item | Count |',+ '| :--- | ---: |',+ '| **GFS files** | 12 |',+ '',+ '- [x] Review complete',+ '',+ '> Checked this morning.',+ '',+ '~~outdated~~',+ '',+ '',+ '',+ '[Documentation](https://example.com/docs)',+ '[Unsafe link](javascript:alert(1))',+ '',+ '<script>alert(1)</script>',+ ].join('\n')+ stubDownload(markdown)++ const { container } = render(+ <GfsMarkdownPreviewBody+ byteLength={new TextEncoder().encode(markdown).byteLength}+ fileName="inventory.md"+ gfsUri="gfs://main/inventory"+ />+ )++ const article = await screen.findByRole('article', {+ name: 'Markdown preview of inventory.md',+ })+ const table = within(article).getByRole('table')+ expect(within(table).getByRole('columnheader', { name: 'Item' }).getAttribute('scope')).toBe(+ 'col'+ )+ expect(within(table).getByRole('cell', { name: 'GFS files' })).toBeTruthy()+ expect(screen.getByRole('region', { name: 'Scrollable Markdown table' }).tabIndex).toBe(0)+ expect(within(article).getByRole('heading', { name: 'Inventory', level: 1 })).toBeTruthy()+ expect((within(article).getByRole('checkbox') as HTMLInputElement).disabled).toBe(true)+ expect(within(article).getByText('outdated').tagName).toBe('DEL')+ expect(+ within(article).getByRole('img', { name: 'Trend chart' }).getAttribute('referrerpolicy')+ ).toBe('no-referrer')+ expect(+ within(article).getByRole('link', { name: 'Documentation' }).getAttribute('target')+ ).toBe('_blank')+ expect(within(article).queryByRole('link', { name: 'Unsafe link' })).toBeNull()+ expect(container.querySelector('script')).toBeNull()+ })++ it('keeps malformed table syntax readable without inventing a table', async () => {+ const markdown = '| Broken | Table |\n| not a separator |\n| still text | here |'+ stubDownload(markdown)++ const { container } = render(+ <GfsMarkdownPreviewBody+ byteLength={markdown.length}+ fileName="malformed.md"+ gfsUri="gfs://main/malformed"+ />+ )++ const article = await screen.findByRole('article', {+ name: 'Markdown preview of malformed.md',+ })+ expect(within(article).queryByRole('table')).toBeNull()+ expect(article.textContent).toContain('Broken')+ expect(article.textContent).toContain('not a separator')+ expect(container.querySelector('script')).toBeNull()+ })+})diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.cssindex f073ba7a7..c2d43d0c9 100644--- a/desktop-app/ui/src/styles.css+++ b/desktop-app/ui/src/styles.css@@ -15722,6 +15722,36 @@ pre {width: min(100%, 52rem);margin: 0 auto;color: var(--text);+ font-family: var(--font-family-base);+ overflow-wrap: anywhere;+}++.da-gfs-markdown-preview__content img {+ max-width: 100%;+ height: auto;+}++.da-gfs-markdown-preview__content .gfs-markdown-table-scroll {+ max-width: 100%;+ overflow-x: auto;+ margin: 0 0 var(--space-3);+ overscroll-behavior-x: contain;+}++.da-gfs-markdown-preview__content .gfs-markdown-table-scroll:focus-visible {+ outline: 2px solid rgba(var(--focus-rgb), 0.85);+ outline-offset: 2px;+}++.da-gfs-markdown-preview__content .gfs-markdown-table-scroll table {+ width: max-content;+ min-width: 100%;+ margin: 0;+}++.da-gfs-markdown-preview__content .gfs-markdown-table-scroll th,+.da-gfs-markdown-preview__content .gfs-markdown-table-scroll td {+ max-width: 24rem;overflow-wrap: anywhere;}