From 7f9403ce5e63d4e869d7179cbd1e0498c445a531 Mon Sep 17 00:00:00 2001
From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
Date: Sat, 20 Jun 2026 18:32:56 +0000
Subject: [PATCH] feat: add HTML artifact preview for inline and file-based
HTML outputs
---
backend/src/routes/files.ts | 91 ++++++++
backend/src/services/files.ts | 1 +
backend/test/routes/files.test.ts | 131 +++++++++++
frontend/src/api/files.test.ts | 40 ++++
frontend/src/api/files.ts | 9 +
.../file-browser/FilePreview.test.tsx | 104 +++++++++
.../components/file-browser/FilePreview.tsx | 40 +++-
.../html-preview/HtmlArtifactPanel.test.tsx | 211 ++++++++++++++++++
.../html-preview/HtmlArtifactPanel.tsx | 96 ++++++++
.../html-preview/HtmlPreviewFrame.tsx | 21 ++
.../components/message/CodePreview.test.tsx | 111 +++++++++
.../src/components/message/CodePreview.tsx | 29 ++-
.../src/components/message/FileToolRender.tsx | 14 +-
.../src/components/message/MessagePart.tsx | 9 +-
.../src/components/message/MessageThread.tsx | 8 +
.../src/components/message/TextPart.test.tsx | 100 +++++++++
frontend/src/components/message/TextPart.tsx | 30 ++-
.../src/components/message/ToolCallPart.tsx | 10 +-
frontend/src/lib/htmlArtifacts.test.ts | 156 +++++++++++++
frontend/src/lib/htmlArtifacts.ts | 52 +++++
frontend/src/pages/SessionDetail.tsx | 122 ++++++----
21 files changed, 1323 insertions(+), 62 deletions(-)
create mode 100644 frontend/src/api/files.test.ts
create mode 100644 frontend/src/components/file-browser/FilePreview.test.tsx
create mode 100644 frontend/src/components/html-preview/HtmlArtifactPanel.test.tsx
create mode 100644 frontend/src/components/html-preview/HtmlArtifactPanel.tsx
create mode 100644 frontend/src/components/html-preview/HtmlPreviewFrame.tsx
create mode 100644 frontend/src/components/message/CodePreview.test.tsx
create mode 100644 frontend/src/components/message/TextPart.test.tsx
create mode 100644 frontend/src/lib/htmlArtifacts.test.ts
create mode 100644 frontend/src/lib/htmlArtifacts.ts
diff --git a/backend/src/routes/files.ts b/backend/src/routes/files.ts
index 4b43f6e4..6560413c 100644
--- a/backend/src/routes/files.ts
+++ b/backend/src/routes/files.ts
@@ -23,12 +23,103 @@ function getSpecialRoutePathFromRequest(c: Context, routeName: string): string |
return match?.[1] ? decodeFilePath(match[1]) : undefined
}
+function getPreviewPathFromRequest(c: Context): string | undefined {
+ const path = c.req.path
+ const prefix = '/api/files/preview'
+
+ const queryPath = c.req.query('path')
+ if (queryPath !== undefined) {
+ return queryPath
+ }
+
+ if (path.startsWith(prefix + '/')) {
+ const previewPath = path.slice(prefix.length + 1)
+ return decodeURIComponent(previewPath)
+ }
+
+ return undefined
+}
+
+const PREVIEWABLE_MIME_TYPES = new Set([
+ 'text/html',
+ 'text/css',
+ 'text/javascript',
+ 'application/javascript',
+ 'application/json',
+ 'application/xml',
+ 'image/png',
+ 'image/jpeg',
+ 'image/gif',
+ 'image/svg+xml',
+])
+
+function isPreviewableMimeType(mimeType?: string): boolean {
+ return mimeType !== undefined && PREVIEWABLE_MIME_TYPES.has(mimeType)
+}
+
+function getPreviewHeaders(result: { name: string; size: number; mimeType?: string }): Record {
+ const isHtmlSvg = result.mimeType === 'text/html' || result.mimeType === 'image/svg+xml'
+ const headers: Record = {
+ 'Content-Type': result.mimeType || 'application/octet-stream',
+ 'Content-Length': result.size.toString(),
+ 'Content-Disposition': `inline; filename="${result.name}"`,
+ 'X-Content-Type-Options': 'nosniff',
+ 'Referrer-Policy': 'no-referrer',
+ }
+
+ if (isHtmlSvg) {
+ headers['Content-Security-Policy'] = [
+ 'sandbox allow-scripts;',
+ "default-src 'self' http: https: data: blob: 'unsafe-inline' 'unsafe-eval';",
+ "script-src 'self' http: https: 'unsafe-inline' 'unsafe-eval';",
+ "style-src 'self' http: https: 'unsafe-inline';",
+ "img-src 'self' http: https: data: blob:;",
+ "font-src 'self' http: https: data:;",
+ "connect-src 'self' http: https:;",
+ "media-src 'self' http: https: data: blob:;",
+ "object-src 'none';",
+ "base-uri 'none';",
+ "frame-ancestors 'self'",
+ ].join(' ')
+ }
+
+ return headers
+}
+
export function createFileRoutes() {
const app = new Hono()
app.get('*', async (c) => {
const path = c.req.path
+ if (path === '/api/files/preview' || path.startsWith('/api/files/preview/')) {
+ const userPath = getPreviewPathFromRequest(c)
+
+ if (!userPath) {
+ return c.json({ error: 'No path provided' }, 400)
+ }
+
+ try {
+ const result = await fileService.getFile(userPath)
+
+ if (result.isDirectory) {
+ return c.json({ error: 'Cannot preview directories' }, 400)
+ }
+
+ if (!isPreviewableMimeType(result.mimeType)) {
+ return c.json({ error: 'File type cannot be previewed' }, 415)
+ }
+
+ const content = await fileService.getRawFileContent(userPath)
+ const headers = getPreviewHeaders(result)
+
+ return new Response(content, { headers })
+ } catch (error: unknown) {
+ logger.error('Failed to preview file:', error)
+ return c.json({ error: getErrorMessage(error) || 'Failed to preview file' }, getStatusCode(error) as ContentfulStatusCode)
+ }
+ }
+
if (path.endsWith('/download-zip')) {
const userPath = getSpecialRoutePathFromRequest(c, 'download-zip')
diff --git a/backend/src/services/files.ts b/backend/src/services/files.ts
index 4dfc77f1..e49b7390 100644
--- a/backend/src/services/files.ts
+++ b/backend/src/services/files.ts
@@ -253,6 +253,7 @@ function getMimeType(filePath: string): AllowedMimeType {
const mimeTypes: Record = {
'.txt': 'text/plain',
'.html': 'text/html',
+ '.htm': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.ts': 'text/typescript',
diff --git a/backend/test/routes/files.test.ts b/backend/test/routes/files.test.ts
index 23aaa5ad..7d8d64a2 100644
--- a/backend/test/routes/files.test.ts
+++ b/backend/test/routes/files.test.ts
@@ -47,6 +47,7 @@ vi.mock('../../src/services/archive', () => ({
}))
const getFile = fileService.getFile as MockedFunction
+const getRawFileContent = fileService.getRawFileContent as MockedFunction
const getFileRange = fileService.getFileRange as MockedFunction
const uploadFile = fileService.uploadFile as MockedFunction
const createFileOrFolder = fileService.createFileOrFolder as MockedFunction
@@ -69,6 +70,125 @@ describe('File Routes', () => {
app.route('/api/files', filesApp)
})
+ describe('GET /preview/* - HTML Preview Assets', () => {
+ const htmlFileInfo: FileInfo = {
+ name: 'index.html',
+ path: 'test-repo/index.html',
+ isDirectory: false,
+ size: 31,
+ mimeType: 'text/html',
+ content: '',
+ lastModified: new Date(),
+ }
+
+ it('should serve HTML files with sandbox CSP headers', async () => {
+ getFile.mockResolvedValue(htmlFileInfo)
+ getRawFileContent.mockResolvedValue(Buffer.from('Hello'))
+
+ const response = await app.request('/api/files/preview/test-repo/index.html')
+ const body = await response.text()
+
+ expect(response.status).toBe(200)
+ expect(body).toBe('Hello')
+ expect(response.headers.get('Content-Type')).toContain('text/html')
+ expect(response.headers.get('Content-Disposition')).toContain('inline')
+ expect(response.headers.get('X-Content-Type-Options')).toBe('nosniff')
+ expect(response.headers.get('Referrer-Policy')).toBe('no-referrer')
+ expect(response.headers.get('Content-Security-Policy')).toContain('sandbox allow-scripts')
+ expect(response.headers.get('Content-Security-Policy')).toContain('https:')
+ expect(getFile).toHaveBeenCalledWith('test-repo/index.html')
+ expect(getRawFileContent).toHaveBeenCalledWith('test-repo/index.html')
+ })
+
+ it('should serve CSS files with text/css Content-Type', async () => {
+ const cssFileInfo: FileInfo = {
+ name: 'styles.css',
+ path: 'test-repo/styles/app.css',
+ isDirectory: false,
+ size: 50,
+ mimeType: 'text/css',
+ content: '',
+ lastModified: new Date(),
+ }
+ getFile.mockResolvedValue(cssFileInfo)
+ getRawFileContent.mockResolvedValue(Buffer.from('body { color: red }'))
+
+ const response = await app.request('/api/files/preview/test-repo/styles/app.css')
+
+ expect(response.status).toBe(200)
+ expect(response.headers.get('Content-Type')).toContain('text/css')
+ expect(response.headers.get('Content-Security-Policy')).toBeNull()
+ expect(getFile).toHaveBeenCalledWith('test-repo/styles/app.css')
+ })
+
+ it('should support query-based path parameter', async () => {
+ getFile.mockResolvedValue(htmlFileInfo)
+ getRawFileContent.mockResolvedValue(Buffer.from('Hello'))
+
+ const response = await app.request('/api/files/preview?path=test-repo/index.html')
+ const body = await response.text()
+
+ expect(response.status).toBe(200)
+ expect(body).toBe('Hello')
+ expect(getFile).toHaveBeenCalledWith('test-repo/index.html')
+ })
+
+ it('should return 400 for directory results', async () => {
+ const dirInfo: FileInfo = {
+ name: 'test-repo',
+ path: 'test-repo',
+ isDirectory: true,
+ size: 0,
+ lastModified: new Date(),
+ }
+ getFile.mockResolvedValue(dirInfo)
+
+ const response = await app.request('/api/files/preview/test-repo')
+
+ expect(response.status).toBe(400)
+ const body = await response.json() as { error: string }
+ expect(body.error).toContain('Cannot preview directories')
+ })
+
+ it('should return 415 for non-previewable MIME types', async () => {
+ const pdfFileInfo: FileInfo = {
+ name: 'doc.pdf',
+ path: 'test-repo/doc.pdf',
+ isDirectory: false,
+ size: 100,
+ mimeType: 'application/pdf',
+ content: '',
+ lastModified: new Date(),
+ }
+ getFile.mockResolvedValue(pdfFileInfo)
+
+ const response = await app.request('/api/files/preview/test-repo/doc.pdf')
+
+ expect(response.status).toBe(415)
+ const body = await response.json() as { error: string }
+ expect(body.error).toContain('File type cannot be previewed')
+ })
+
+ it('should return 400 when no path is provided', async () => {
+ const response = await app.request('/api/files/preview')
+
+ expect(response.status).toBe(400)
+ const body = await response.json() as { error: string }
+ expect(body.error).toContain('No path provided')
+ })
+
+ it('should return 403 for path traversal attempts', async () => {
+ const error = { message: 'Path traversal detected', statusCode: 403 }
+ getFile.mockRejectedValue(error)
+
+ const response = await app.request('/api/files/preview/test-repo/../outside')
+
+ expect(response.status).toBe(403)
+ const body = await response.json() as { error: string }
+ expect(body.error).toContain('Path traversal detected')
+ })
+ })
+
describe('GET /*/download-zip - Route Order Regression Test', () => {
it('should route to archive service for directory download, not file service', async () => {
const mockStream = {
@@ -175,6 +295,17 @@ describe('File Routes', () => {
expect(response.status).toBe(404)
expect(body).toHaveProperty('error')
})
+
+ it('should route paths starting with "preview" but not matching /preview/ to generic handler', async () => {
+ getFile.mockResolvedValue(mockFileInfo)
+
+ const response = await app.request('/api/files/previewer')
+ const body = await response.json() as FileInfo
+
+ expect(response.status).toBe(200)
+ expect(body).toHaveProperty('isDirectory', false)
+ expect(getFile).toHaveBeenCalledWith('previewer')
+ })
})
describe('GET /* with ?startLine&endLine - File Range', () => {
diff --git a/frontend/src/api/files.test.ts b/frontend/src/api/files.test.ts
new file mode 100644
index 00000000..13373d12
--- /dev/null
+++ b/frontend/src/api/files.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest'
+import { getFileApiUrl } from './files'
+import { encodePathForRoute, getFilePreviewUrl } from './files'
+
+describe('getFilePreviewUrl', () => {
+ it('constructs preview URL with encoded path segments', () => {
+ const url = getFilePreviewUrl('repo/dir/index.html')
+ expect(url).toBe('/api/files/preview/repo/dir/index.html')
+ })
+
+ it('encodes spaces per segment', () => {
+ const url = getFilePreviewUrl('my repo/file name.html')
+ expect(url).toBe('/api/files/preview/my%20repo/file%20name.html')
+ })
+
+ it('encodes hash characters per segment', () => {
+ const url = getFilePreviewUrl('repo/file#1.html')
+ expect(url).toBe('/api/files/preview/repo/file%231.html')
+ })
+})
+
+describe('encodePathForRoute', () => {
+ it('encodes each path segment separately', () => {
+ const result = encodePathForRoute('repo/dir/index.html')
+ expect(result).toBe('repo/dir/index.html')
+ })
+
+ it('encodes special characters per segment', () => {
+ const result = encodePathForRoute('my dir/file name.html')
+ expect(result).toBe('my%20dir/file%20name.html')
+ })
+})
+
+describe('getFileApiUrl - existing behavior unchanged', () => {
+ it('still returns a URL with path query param', () => {
+ const url = getFileApiUrl('repo/dir/index.html')
+ expect(url).toContain('/api/files')
+ expect(url).toContain('path=repo%2Fdir%2Findex.html')
+ })
+})
diff --git a/frontend/src/api/files.ts b/frontend/src/api/files.ts
index 7337d9f3..df4a12cd 100644
--- a/frontend/src/api/files.ts
+++ b/frontend/src/api/files.ts
@@ -77,3 +77,12 @@ export async function applyFilePatches(path: string, patches: PatchOperation[]):
body: JSON.stringify({ patches }),
})
}
+
+export function encodePathForRoute(path: string): string {
+ return path.split('/').map(encodeURIComponent).join('/')
+}
+
+export function getFilePreviewUrl(path: string): string {
+ const encodedPath = encodePathForRoute(path)
+ return `${API_BASE_URL}/api/files/preview/${encodedPath}`
+}
diff --git a/frontend/src/components/file-browser/FilePreview.test.tsx b/frontend/src/components/file-browser/FilePreview.test.tsx
new file mode 100644
index 00000000..c8c3f017
--- /dev/null
+++ b/frontend/src/components/file-browser/FilePreview.test.tsx
@@ -0,0 +1,104 @@
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import '@testing-library/jest-dom'
+import { FilePreview } from './FilePreview'
+import type { FileInfo } from '@/types/files'
+
+vi.mock('@/api/files', () => ({
+ getFileApiUrl: (path: string) => `/api/files?path=${encodeURIComponent(path)}`,
+ getFilePreviewUrl: (path: string) => {
+ const encodedPath = path.split('/').map(encodeURIComponent).join('/')
+ return `/api/files/preview/${encodedPath}`
+ },
+}))
+
+vi.mock('@/components/ui/virtualized-text-view', () => ({
+ VirtualizedTextView: vi.fn(() => ),
+}))
+
+function htmlFile(content: string, overrides?: Partial): FileInfo {
+ return {
+ name: 'dashboard.html',
+ path: 'test-repo/dashboard.html',
+ isDirectory: false,
+ size: content.length,
+ mimeType: 'text/html',
+ content: btoa(content),
+ lastModified: new Date(),
+ ...overrides,
+ }
+}
+
+function textFile(name: string, content: string, mimeType: string): FileInfo {
+ return {
+ name,
+ path: `test-repo/${name}`,
+ isDirectory: false,
+ size: content.length,
+ mimeType,
+ content: btoa(content),
+ lastModified: new Date(),
+ }
+}
+
+describe('FilePreview - HTML preview', () => {
+ it('renders HTML preview iframe by default for .html file', () => {
+ render(Dashboard')} />)
+
+ const iframe = screen.getByTitle('HTML preview: dashboard.html')
+ expect(iframe).toBeInTheDocument()
+ expect(iframe).toHaveAttribute('sandbox', 'allow-scripts')
+ expect(iframe.getAttribute('src')).toContain('/api/files/preview/test-repo/dashboard.html')
+ })
+
+ it('toggles to source view when code button is clicked', () => {
+ render(Dashboard')} />)
+
+ const toggleButton = screen.getByTitle('Show HTML source')
+ expect(toggleButton).toBeInTheDocument()
+
+ fireEvent.click(toggleButton)
+
+ expect(screen.queryByTitle('HTML preview: dashboard.html')).not.toBeInTheDocument()
+ expect(screen.getByText('Dashboard
')).toBeInTheDocument()
+ })
+
+ it('toggles back to preview when eye button is clicked from source view', () => {
+ render(Dashboard')} />)
+
+ const showSourceButton = screen.getByTitle('Show HTML source')
+ fireEvent.click(showSourceButton)
+ expect(screen.queryByTitle('HTML preview: dashboard.html')).not.toBeInTheDocument()
+
+ const showPreviewButton = screen.getByTitle('Preview rendered HTML')
+ expect(showPreviewButton).toBeInTheDocument()
+
+ fireEvent.click(showPreviewButton)
+
+ const iframe = screen.getByTitle('HTML preview: dashboard.html')
+ expect(iframe).toBeInTheDocument()
+ })
+
+ it('renders HTML preview for .htm file', () => {
+ render(HTM test
', { name: 'test.htm', path: 'test-repo/test.htm', mimeType: 'text/html' })} />)
+
+ const iframe = screen.getByTitle('HTML preview: test.htm')
+ expect(iframe).toBeInTheDocument()
+ expect(iframe.getAttribute('src')).toContain('/api/files/preview/test-repo/test.htm')
+ })
+
+ it('does not show HTML preview toggle for non-HTML text file', () => {
+ render()
+
+ expect(screen.queryByTitle('Show HTML source')).not.toBeInTheDocument()
+ expect(screen.queryByTitle('Preview rendered HTML')).not.toBeInTheDocument()
+ expect(screen.getByText('Hello world')).toBeInTheDocument()
+ })
+
+ it('preserves markdown preview behavior for .md files', () => {
+ render()
+
+ const toggleButton = screen.getByTitle('Show raw markdown')
+ expect(toggleButton).toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/components/file-browser/FilePreview.tsx b/frontend/src/components/file-browser/FilePreview.tsx
index 9f8dfcb3..564094c5 100644
--- a/frontend/src/components/file-browser/FilePreview.tsx
+++ b/frontend/src/components/file-browser/FilePreview.tsx
@@ -2,9 +2,11 @@ import { useState, useCallback, useRef, useEffect, memo } from 'react'
import { Button } from '@/components/ui/button'
import { Download, X, Edit3, Save, X as XIcon, WrapText, Eye, Code } from 'lucide-react'
import type { FileInfo } from '@/types/files'
-import { getFileApiUrl } from '@/api/files'
+import { getFileApiUrl, getFilePreviewUrl } from '@/api/files'
import { VirtualizedTextView, type VirtualizedTextViewHandle } from '@/components/ui/virtualized-text-view'
import { MarkdownRenderer } from './MarkdownRenderer'
+import { HtmlPreviewFrame } from '@/components/html-preview/HtmlPreviewFrame'
+import { isHtmlPath } from '@/lib/htmlArtifacts'
const VIRTUALIZATION_THRESHOLD_BYTES = 50_000
@@ -21,6 +23,7 @@ interface FilePreviewProps {
export const FilePreview = memo(function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal, onFileSaved, initialLineNumber }: FilePreviewProps) {
const isMarkdownFile = file.name.toLowerCase().endsWith('.md') || file.name.toLowerCase().endsWith('.mdx') || file.mimeType === 'text/markdown'
+ const isHtmlFile = isHtmlPath(file.name) || file.mimeType === 'text/html'
const [viewMode, setViewMode] = useState<'preview' | 'edit'>('preview')
const [editContent, setEditContent] = useState('')
@@ -29,6 +32,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
const [highlightedLine, setHighlightedLine] = useState(initialLineNumber)
const [lineWrap, setLineWrap] = useState(true)
const [markdownPreview, setMarkdownPreview] = useState(isMarkdownFile)
+ const [htmlPreview, setHtmlPreview] = useState(isHtmlFile)
const [isLoadingAllContent, setIsLoadingAllContent] = useState(false)
const [fullContentLoaded, setFullContentLoaded] = useState(false)
const [fullContent, setFullContent] = useState(null)
@@ -42,9 +46,10 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
useEffect(() => {
setFullContentLoaded(false)
setMarkdownPreview(isMarkdownFile)
+ setHtmlPreview(isHtmlFile)
setFullContent(null)
setLocalMdContent(null)
- }, [file.path, isMarkdownFile])
+ }, [file.path, isMarkdownFile, isHtmlFile])
useEffect(() => {
if (shouldVirtualize && isMarkdownFile && markdownPreview && !isMarkdownTooLarge && !fullContentLoaded) {
@@ -227,8 +232,17 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
}
if (shouldVirtualize && isTextFile) {
+ const showHtmlPreview = isHtmlFile && htmlPreview && viewMode !== 'edit'
const showMarkdownPreview = isMarkdownFile && markdownPreview && viewMode !== 'edit'
+ if (showHtmlPreview) {
+ return (
+
+
+
+ )
+ }
+
return (
<>
@@ -285,6 +299,14 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
/>
)
}
+
+ if (isHtmlFile && htmlPreview) {
+ return (
+
+
+
+ )
+ }
try {
const textContent = decodeBase64(file.content)
@@ -392,8 +414,20 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
{markdownPreview ?
:
}
)}
+
+ {isHtmlFile && viewMode !== 'edit' && (
+
+ )}
- {isTextFile && !markdownPreview && (
+ {isTextFile && !markdownPreview && !htmlPreview && (
@@ -329,6 +335,7 @@ export const MessageThread = memo(function MessageThread({
messages,
onFileClick,
onChildSessionClick,
+ onHtmlArtifactOpen,
onUndoMessage,
model
}: MessageThreadProps) {
@@ -442,6 +449,7 @@ export const MessageThread = memo(function MessageThread({
directory={directory}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
+ onHtmlArtifactOpen={onHtmlArtifactOpen}
handleStartEditUserMessage={handleStartEditUserMessage}
handleCancelEdit={handleCancelEdit}
model={model}
diff --git a/frontend/src/components/message/TextPart.test.tsx b/frontend/src/components/message/TextPart.test.tsx
new file mode 100644
index 00000000..e0febd7a
--- /dev/null
+++ b/frontend/src/components/message/TextPart.test.tsx
@@ -0,0 +1,100 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import { TextPart } from './TextPart'
+
+const mocks = vi.hoisted(() => ({
+ useTheme: vi.fn(() => 'dark'),
+}))
+
+vi.mock('@/hooks/useTheme', () => ({
+ useTheme: () => mocks.useTheme(),
+}))
+
+vi.mock('mermaid', () => ({
+ default: {
+ initialize: vi.fn(),
+ render: vi.fn(),
+ },
+}))
+
+const createTextPart = (text: string) => ({
+ type: 'text' as const,
+ text,
+ sessionID: 'test-session',
+ id: 'part-1',
+})
+
+describe('TextPart', () => {
+ beforeEach(() => {
+ mocks.useTheme.mockReturnValue('dark')
+ })
+
+ it('renders HTML fenced code block with artifact button', () => {
+ const onHtmlArtifactOpen = vi.fn()
+ const markdown = 'Here is a page:\n\n```html\nHello artifact
\n```'
+ const part = createTextPart(markdown)
+
+ render()
+
+ const button = screen.getByTitle('Preview HTML artifact')
+ expect(button).toBeInTheDocument()
+ })
+
+ it('calls onHtmlArtifactOpen with correct data when artifact button is clicked', () => {
+ const onHtmlArtifactOpen = vi.fn()
+ const markdown = 'Here is a page:\n\n```html\nHello artifact
\n```'
+ const part = createTextPart(markdown)
+
+ render()
+
+ const button = screen.getByTitle('Preview HTML artifact')
+ fireEvent.click(button)
+
+ expect(onHtmlArtifactOpen).toHaveBeenCalledWith({
+ source: 'inline',
+ html: 'Hello artifact
',
+ title: 'HTML artifact',
+ })
+ })
+
+ it('does not show artifact button for non-HTML code blocks', () => {
+ const onHtmlArtifactOpen = vi.fn()
+ const markdown = '```ts\nconst x = 1\n```'
+ const part = createTextPart(markdown)
+
+ render()
+
+ expect(screen.queryByTitle('Preview HTML artifact')).not.toBeInTheDocument()
+ })
+
+ it('still shows copy button for code blocks', () => {
+ const onHtmlArtifactOpen = vi.fn()
+ const markdown = '```html\ntest
\n```'
+ const part = createTextPart(markdown)
+
+ render()
+
+ expect(screen.getByTitle('Copy code')).toBeInTheDocument()
+ })
+
+ it('preserves leading/trailing whitespace when copying code content', () => {
+ const onHtmlArtifactOpen = vi.fn()
+ const markdown = '```\n const x = 1\n \n```'
+ const part = createTextPart(markdown)
+
+ render()
+
+ const copyButton = screen.getByTitle('Copy code')
+ expect(copyButton).toBeInTheDocument()
+ })
+
+ it('does not show artifact button for mermaid code blocks', () => {
+ const onHtmlArtifactOpen = vi.fn()
+ const markdown = '```mermaid\ngraph TD;\nA-->B;\n```'
+ const part = createTextPart(markdown)
+
+ render()
+
+ expect(screen.queryByTitle('Preview HTML artifact')).not.toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/components/message/TextPart.tsx b/frontend/src/components/message/TextPart.tsx
index 721c0dfa..0fb81617 100644
--- a/frontend/src/components/message/TextPart.tsx
+++ b/frontend/src/components/message/TextPart.tsx
@@ -7,6 +7,7 @@ import mermaid from 'mermaid'
import { Maximize2, X, AlertCircle } from 'lucide-react'
import { CopyButton } from '@/components/ui/copy-button'
import type { components } from '@/api/opencode-types'
+import type { OpenHtmlArtifactInput } from '@/lib/htmlArtifacts'
import { useTheme } from '@/hooks/useTheme'
import 'highlight.js/styles/github-dark.css'
@@ -14,6 +15,7 @@ type TextPart = components['schemas']['TextPart']
interface TextPartProps {
part: TextPart
+ onHtmlArtifactOpen?: (input: OpenHtmlArtifactInput) => void
}
interface MermaidBlockProps {
@@ -146,10 +148,11 @@ function MermaidBlock({ code }: MermaidBlockProps) {
interface CodeBlockProps {
children?: React.ReactNode
className?: string
+ onHtmlArtifactOpen?: (input: OpenHtmlArtifactInput) => void
[key: string]: unknown
}
-function CodeBlock({ children, className, ...props }: CodeBlockProps) {
+function CodeBlock({ children, className, onHtmlArtifactOpen, ...props }: CodeBlockProps) {
const extractTextContent = (node: React.ReactNode): string => {
if (typeof node === 'string') return node
if (typeof node === 'number') return node.toString()
@@ -163,14 +166,31 @@ function CodeBlock({ children, className, ...props }: CodeBlockProps) {
return ''
}
- const codeContent = extractTextContent(children)
+ const rawCodeContent = extractTextContent(children)
+ const codeContent = rawCodeContent.trim()
+
+ const childArray = React.Children.toArray(children)
+ const codeElement = childArray.find((child): child is React.ReactElement => React.isValidElement(child))
+ const codeClassName = codeElement?.props?.className
+ const isHtmlCode = typeof codeClassName === 'string' && (codeClassName.includes('language-html') || codeClassName.includes('language-htm'))
return (
{children}
-
+
+ {isHtmlCode && onHtmlArtifactOpen && (
+ onHtmlArtifactOpen({ source: 'inline', html: codeContent, title: 'HTML artifact' })}
+ className="p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground text-xs"
+ title="Preview HTML artifact"
+ >
+ Preview HTML
+
+ )}
+
+
)
}
@@ -184,7 +204,7 @@ function isMermaidBlockComplete(text: string): boolean {
return false
}
-export function TextPart({ part }: TextPartProps) {
+export function TextPart({ part, onHtmlArtifactOpen }: TextPartProps) {
const mermaidComplete = React.useMemo(() => {
return part.text ? isMermaidBlockComplete(part.text) : false
}, [part.text])
@@ -234,7 +254,7 @@ export function TextPart({ part }: TextPartProps) {
},
pre({ children }) {
return (
-
+
{children}
)
diff --git a/frontend/src/components/message/ToolCallPart.tsx b/frontend/src/components/message/ToolCallPart.tsx
index 77ceae93..6d4f287a 100644
--- a/frontend/src/components/message/ToolCallPart.tsx
+++ b/frontend/src/components/message/ToolCallPart.tsx
@@ -5,6 +5,7 @@ import { useUserBash } from '@/stores/userBashStore'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { usePermissions, useQuestions } from '@/contexts/EventContext'
import { detectFileReferences } from '@/lib/fileReferences'
+import type { OpenHtmlArtifactInput } from '@/lib/htmlArtifacts'
import { ExternalLink, Loader2 } from 'lucide-react'
import { CopyButton } from '@/components/ui/copy-button'
import { getToolSpecificRender } from './FileToolRender'
@@ -15,6 +16,7 @@ interface ToolCallPartProps {
part: ToolPart
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
+ onHtmlArtifactOpen?: (input: OpenHtmlArtifactInput) => void
simpleChatMode?: boolean
}
@@ -26,7 +28,7 @@ function getTaskSessionId(part: ToolPart): string | undefined {
return sessionId
}
-function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (filePath: string) => void }) {
+function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (filePath: string, lineNumber?: number) => void }) {
const jsonString = JSON.stringify(json, null, 2)
const references = detectFileReferences(jsonString)
@@ -47,7 +49,7 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
key={`ref-${index}`}
onClick={(e) => {
e.stopPropagation()
- onFileClick?.(ref.filePath)
+ onFileClick?.(ref.filePath, ref.lineNumber)
}}
className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 cursor-pointer underline decoration-dotted"
title={`Click to open ${ref.filePath}`}
@@ -66,7 +68,7 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
return {parts}
}
-export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCallPartProps) {
+export function ToolCallPart({ part, onFileClick, onChildSessionClick, onHtmlArtifactOpen }: ToolCallPartProps) {
const { preferences } = useSettings()
const { userBashCommands } = useUserBash()
const taskSessionId = part.tool === 'task' ? getTaskSessionId(part) : undefined
@@ -219,7 +221,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
return null
}
- const toolSpecificRender = getToolSpecificRender(part, onFileClick)
+ const toolSpecificRender = getToolSpecificRender(part, onFileClick, onHtmlArtifactOpen)
if (toolSpecificRender) {
return toolSpecificRender
}
diff --git a/frontend/src/lib/htmlArtifacts.test.ts b/frontend/src/lib/htmlArtifacts.test.ts
new file mode 100644
index 00000000..99f3236d
--- /dev/null
+++ b/frontend/src/lib/htmlArtifacts.test.ts
@@ -0,0 +1,156 @@
+import { describe, it, expect } from 'vitest'
+import {
+ isHtmlPath,
+ normalizeWorkspaceFilePath,
+ createHtmlArtifact,
+ getArtifactTitle,
+} from './htmlArtifacts'
+
+describe('isHtmlPath', () => {
+ it('returns true for .html paths', () => {
+ expect(isHtmlPath('repo/report.html')).toBe(true)
+ })
+
+ it('returns true for .HTM paths (case-insensitive)', () => {
+ expect(isHtmlPath('page.HTM')).toBe(true)
+ expect(isHtmlPath('page.Htm')).toBe(true)
+ })
+
+ it('returns false for .tsx paths', () => {
+ expect(isHtmlPath('component.tsx')).toBe(false)
+ })
+
+ it('returns false for .md paths', () => {
+ expect(isHtmlPath('readme.md')).toBe(false)
+ })
+
+ it('returns false for missing path', () => {
+ expect(isHtmlPath(undefined)).toBe(false)
+ expect(isHtmlPath('')).toBe(false)
+ })
+
+ it('ignores query strings and hash fragments', () => {
+ expect(isHtmlPath('index.html?raw=true')).toBe(true)
+ expect(isHtmlPath('index.html#section')).toBe(true)
+ expect(isHtmlPath('page.htm?query=1#hash')).toBe(true)
+ })
+})
+
+describe('normalizeWorkspaceFilePath', () => {
+ it('strips workspace repos path prefix', () => {
+ const result = normalizeWorkspaceFilePath(
+ '/workspace/repos/my-repo/dist/index.html',
+ '/workspace/repos/my-repo',
+ )
+ expect(result).toBe('my-repo/dist/index.html')
+ })
+
+ it('returns non-matching absolute paths unchanged', () => {
+ const result = normalizeWorkspaceFilePath(
+ '/some/other/path/file.html',
+ '/workspace/repos/my-repo',
+ )
+ expect(result).toBe('/some/other/path/file.html')
+ })
+
+ it('returns relative paths unchanged', () => {
+ const result = normalizeWorkspaceFilePath('relative/path.html', '/workspace/repos/my-repo')
+ expect(result).toBe('relative/path.html')
+ })
+
+ it('returns path unchanged when repoFullPath is missing', () => {
+ const result = normalizeWorkspaceFilePath('/workspace/repos/my-repo/file.html')
+ expect(result).toBe('/workspace/repos/my-repo/file.html')
+ })
+})
+
+describe('createHtmlArtifact', () => {
+ it('creates an inline artifact with required html', () => {
+ const artifact = createHtmlArtifact({ source: 'inline', html: 'Hello
' })
+ expect(artifact.source).toBe('inline')
+ expect(artifact.html).toBe('Hello
')
+ expect(artifact.id).toBeTruthy()
+ expect(artifact.title).toBe('Untitled Artifact')
+ })
+
+ it('creates a file artifact with required path', () => {
+ const artifact = createHtmlArtifact({ source: 'file', path: 'my-repo/dist/index.html' })
+ expect(artifact.source).toBe('file')
+ expect(artifact.path).toBe('my-repo/dist/index.html')
+ expect(artifact.id).toBeTruthy()
+ expect(artifact.title).toBe('index')
+ })
+
+ it('uses provided title', () => {
+ const artifact = createHtmlArtifact({
+ source: 'inline',
+ html: 'Hello
',
+ title: 'My Artifact',
+ })
+ expect(artifact.title).toBe('My Artifact')
+ })
+
+ it('throws when path is missing for file artifact', () => {
+ expect(() => createHtmlArtifact({ source: 'file' })).toThrow('path is required')
+ })
+
+ it('throws when html is missing for inline artifact', () => {
+ expect(() => createHtmlArtifact({ source: 'inline' })).toThrow('html is required')
+ })
+})
+
+describe('handleFileClick path detection (normalize + isHtml combo)', () => {
+ it('classifies normalized .html path as artifact', () => {
+ const path = normalizeWorkspaceFilePath(
+ '/workspace/repos/my-repo/dist/index.html',
+ '/workspace/repos/my-repo',
+ )
+ expect(path).toBe('my-repo/dist/index.html')
+ expect(isHtmlPath(path)).toBe(true)
+ })
+
+ it('classifies normalized .htm path as artifact', () => {
+ const path = normalizeWorkspaceFilePath(
+ '/workspace/repos/my-repo/public/page.htm',
+ '/workspace/repos/my-repo',
+ )
+ expect(path).toBe('my-repo/public/page.htm')
+ expect(isHtmlPath(path)).toBe(true)
+ })
+
+ it('does not classify non-HTML path as artifact', () => {
+ const path = normalizeWorkspaceFilePath(
+ '/workspace/repos/my-repo/src/app.tsx',
+ '/workspace/repos/my-repo',
+ )
+ expect(path).toBe('my-repo/src/app.tsx')
+ expect(isHtmlPath(path)).toBe(false)
+ })
+
+ it('does not classify relative non-HTML path as artifact', () => {
+ expect(isHtmlPath(normalizeWorkspaceFilePath('src/utils.ts'))).toBe(false)
+ })
+
+ it('classifies .html path without repo prefix as artifact', () => {
+ const path = normalizeWorkspaceFilePath('some-folder/index.html')
+ expect(isHtmlPath(path)).toBe(true)
+ })
+})
+
+describe('getArtifactTitle', () => {
+ it('returns file name without extension for .html paths', () => {
+ expect(getArtifactTitle('my-repo/dist/index.html')).toBe('index')
+ })
+
+ it('returns file name without extension for .htm paths', () => {
+ expect(getArtifactTitle('page.htm')).toBe('page')
+ })
+
+ it('returns last segment for non-HTML paths', () => {
+ expect(getArtifactTitle('some/path/file.txt')).toBe('file.txt')
+ })
+
+ it('returns Untitled Artifact for undefined', () => {
+ expect(getArtifactTitle(undefined)).toBe('Untitled Artifact')
+ })
+})
diff --git a/frontend/src/lib/htmlArtifacts.ts b/frontend/src/lib/htmlArtifacts.ts
new file mode 100644
index 00000000..1401b275
--- /dev/null
+++ b/frontend/src/lib/htmlArtifacts.ts
@@ -0,0 +1,52 @@
+export interface HtmlArtifact {
+ id: string
+ title: string
+ source: 'inline' | 'file'
+ html?: string
+ path?: string
+}
+
+export interface OpenHtmlArtifactInput {
+ title?: string
+ source: 'inline' | 'file'
+ html?: string
+ path?: string
+}
+
+const HTML_EXTENSIONS = new Set(['.html', '.htm'])
+
+export function isHtmlPath(path: string | undefined): boolean {
+ if (!path) return false
+ const clean = path.split(/[?#]/)[0].toLowerCase()
+ return HTML_EXTENSIONS.has(clean.slice(clean.lastIndexOf('.')))
+}
+
+export function getArtifactTitle(pathOrTitle: string | undefined): string {
+ if (!pathOrTitle) return 'Untitled Artifact'
+ const lastSegment = pathOrTitle.split('/').pop() || pathOrTitle
+ if (isHtmlPath(lastSegment)) {
+ return lastSegment.slice(0, lastSegment.lastIndexOf('.'))
+ }
+ return lastSegment
+}
+
+export function createHtmlArtifact(input: OpenHtmlArtifactInput): HtmlArtifact {
+ if (input.source === 'file' && !input.path) {
+ throw new Error('path is required for file artifacts')
+ }
+ if (input.source === 'inline' && !input.html) {
+ throw new Error('html is required for inline artifacts')
+ }
+ const id = `${Date.now()}-${Math.random().toString(36).slice(2)}`
+ const title = input.title ?? getArtifactTitle(input.source === 'file' ? input.path : undefined)
+ return { id, title, source: input.source, html: input.html, path: input.path }
+}
+
+export function normalizeWorkspaceFilePath(filePath: string, repoFullPath?: string): string {
+ if (!filePath.startsWith('/') || !repoFullPath) return filePath
+ const workspaceReposPath = repoFullPath.substring(0, repoFullPath.lastIndexOf('/'))
+ if (filePath.startsWith(`${workspaceReposPath}/`)) {
+ return filePath.substring(workspaceReposPath.length + 1)
+ }
+ return filePath
+}
diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx
index 2242592e..5d43186d 100644
--- a/frontend/src/pages/SessionDetail.tsx
+++ b/frontend/src/pages/SessionDetail.tsx
@@ -52,6 +52,9 @@ import { SessionTodoDisplay } from "@/components/message/SessionTodoDisplay";
import { useDialogParam } from "@/hooks/useDialogParam";
import { useSidebarAction } from "@/hooks/useSidebarAction";
import { SessionMoreButton } from "@/components/navigation/SessionMoreButton";
+import { HtmlArtifactPanel } from "@/components/html-preview/HtmlArtifactPanel";
+import type { HtmlArtifact, OpenHtmlArtifactInput } from '@/lib/htmlArtifacts'
+import { createHtmlArtifact, isHtmlPath, normalizeWorkspaceFilePath } from '@/lib/htmlArtifacts'
const compareMessageIds = (id1: string, id2: string): number => {
const num1 = parseInt(id1, 10)
@@ -84,6 +87,8 @@ export function SessionDetail() {
const [showScrollButton, setShowScrollButton] = useState(false);
const [hasPromptContent, setHasPromptContent] = useState(false);
const [minimizedQuestion, setMinimizedQuestion] = useState(null);
+ const [htmlArtifact, setHtmlArtifact] = useState(null);
+ const [htmlArtifactFullscreen, setHtmlArtifactFullscreen] = useState(false);
const isMobile = useMobile();
const { keyboardHeight } = useVisualViewport();
@@ -202,6 +207,28 @@ export function SessionDetail() {
setMinimizedQuestion(null)
}, [])
+ const handleHtmlArtifactOpen = useCallback((input: OpenHtmlArtifactInput) => {
+ try {
+ const normalizedPath = input.source === 'file' && input.path
+ ? normalizeWorkspaceFilePath(input.path, repo?.fullPath)
+ : input.path
+ const artifact = createHtmlArtifact({ ...input, path: normalizedPath })
+ setHtmlArtifact(artifact)
+ setHtmlArtifactFullscreen(isMobile)
+ } catch {
+ showToast.error('Failed to create artifact')
+ }
+ }, [isMobile, repo?.fullPath])
+
+ const handleHtmlArtifactClose = useCallback(() => {
+ setHtmlArtifact(null)
+ setHtmlArtifactFullscreen(false)
+ }, [])
+
+ const handleHtmlArtifactFullscreenToggle = useCallback(() => {
+ setHtmlArtifactFullscreen(v => !v)
+ }, [])
+
useEffect(() => {
if (minimizedQuestion && minimizedQuestion.sessionID !== sessionId) {
setMinimizedQuestion(null)
@@ -336,22 +363,21 @@ export function SessionDetail() {
},
});
-
-
const handleFileClick = useCallback((filePath: string) => {
- let pathToOpen = filePath
-
- if (filePath.startsWith('/') && repo?.fullPath) {
- const workspaceReposPath = repo.fullPath.substring(0, repo.fullPath.lastIndexOf('/'))
-
- if (filePath.startsWith(workspaceReposPath + '/')) {
- pathToOpen = filePath.substring(workspaceReposPath.length + 1)
- }
+ const pathToOpen = normalizeWorkspaceFilePath(filePath, repo?.fullPath)
+
+ if (isHtmlPath(pathToOpen)) {
+ handleHtmlArtifactOpen({
+ source: 'file',
+ path: pathToOpen,
+ title: pathToOpen.split('/').pop() || 'HTML artifact',
+ })
+ return
}
-
+
setSelectedFilePath(pathToOpen)
setFileBrowserOpen(true)
- }, [repo?.fullPath, setFileBrowserOpen]);
+ }, [repo?.fullPath, handleHtmlArtifactOpen, setFileBrowserOpen]);
const handleSessionTitleUpdate = useCallback((newTitle: string) => {
if (sessionId) {
@@ -400,10 +426,6 @@ export function SessionDetail() {
promptInputRef.current?.clearPrompt()
}, []);
-
-
-
-
if (!sessionId) {
return ;
}
@@ -480,29 +502,31 @@ export function SessionDetail() {
-
-
- {repoLoading || sessionLoading || messagesLoading ? (
-
- ) : opcodeUrl && repoDirectory ? (
-
- ) : null}
-
- {opcodeUrl && repoDirectory && !isEditingMessage && (
-
+
+
+
+ {repoLoading || sessionLoading || messagesLoading ? (
+
+ ) : opcodeUrl && repoDirectory ? (
+
+ ) : null}
+
+ {opcodeUrl && repoDirectory && !isEditingMessage && (
+
{ttsEnabled && !hasPromptContent && !isSessionActive && latestPlayableAssistant && (
@@ -567,6 +591,16 @@ export function SessionDetail() {
)}
+
+ {htmlArtifact && !htmlArtifactFullscreen && !isMobile && (
+
+ )}
{/* Sessions Dialog */}
@@ -598,6 +632,16 @@ export function SessionDetail() {
initialSelectedFile={selectedFilePath}
/>
+ {htmlArtifact && (htmlArtifactFullscreen || isMobile) && (
+
+ )}
+