feat(artifacts): render agent HTML files inline in the session chat

This commit is contained in:
Chris Scott authored and Chris Scott committed 2026-10-12 16:43:04 -04:00
1 parent 377e3c2784
commit f7b2ffb865
17 files changed
+579 -10

No files matched your search

@@ -0,0 +1,60 @@
import { memo, useState } from 'react'
import { AppWindow, ExternalLink, RotateCw } from 'lucide-react'
import { Button } from '@/components/ui/button'
interface ArtifactPartProps {
title: string
src: string
path?: string
}
/** Renders the sandboxed HTML document produced by an `ocm` `show_artifact` call. */
export const ArtifactPart = memo(function ArtifactPart({ title, src, path }: ArtifactPartProps) {
const [reloadKey, setReloadKey] = useState(0)
return (
<div className="border rounded-lg overflow-hidden my-2 border-border">
<div className="flex items-center gap-2 bg-card px-4 py-2">
<AppWindow className="w-4 h-4 shrink-0 text-muted-foreground" />
<div className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-sm font-medium">{title}</span>
{path && (
<span className="truncate text-xs text-muted-foreground" title={path}>
{path}
</span>
)}
</div>
<Button
variant="ghost"
size="icon-sm"
className="shrink-0"
onClick={() => setReloadKey((key) => key + 1)}
aria-label="Reload artifact"
title="Reload artifact"
>
<RotateCw />
</Button>
<Button variant="ghost" size="icon-sm" asChild className="shrink-0">
<a
href={src}
target="_blank"
rel="noopener noreferrer"
aria-label="Open in new tab"
title="Open in new tab"
>
<ExternalLink />
</a>
</Button>
</div>
<iframe
key={reloadKey}
src={src}
title={title}
sandbox="allow-scripts"
loading="lazy"
referrerPolicy="no-referrer"
className="block w-full h-[480px] border-0 bg-white"
/>
</div>
)
})
@@ -3,6 +3,7 @@ import { render, screen, fireEvent } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter } from 'react-router-dom'
import { MessagePart } from './MessagePart'
import { getFileApiUrl } from '@/api/files'
import { applySessionEvent, emptySessionTranscript } from '@/lib/session-projection'
import { promptSequence } from '@/test/fixtures/session-projection'
import type {
@@ -276,6 +277,55 @@ describe('MessagePart', () => {
fireEvent.click(screen.getByRole('button'))
expect(onChildSessionClick).toHaveBeenCalledWith('child-session')
})
it('renders an ocm show_artifact tool in simpleChatMode', () => {
setupSettings({
simpleChatMode: true,
showReasoning: false,
expandToolCalls: false,
expandDiffs: true,
})
renderWithProviders(
<MessagePart
part={toolPart('ocm', {
status: 'completed',
input: { action: 'show_artifact', params: { title: 'Report', path: 'reports/summary.html' } },
content: [{ type: 'text', text: 'Artifact shown' }],
})}
messageID="msg_1"
directory="/repo"
/>,
)
const iframe = screen.getByTitle('Report')
expect(iframe.tagName).toBe('IFRAME')
expect(iframe).toHaveAttribute('src', getFileApiUrl('/repo/reports/summary.html', { params: { raw: true } }))
})
it('renders an ocm show_artifact tool with an absolute path', () => {
setupSettings({
simpleChatMode: true,
showReasoning: false,
expandToolCalls: false,
expandDiffs: true,
})
renderWithProviders(
<MessagePart
part={toolPart('ocm', {
status: 'completed',
input: { action: 'show_artifact', params: { title: 'Report', path: '/tmp/artifacts/report.html' } },
content: [{ type: 'text', text: 'Artifact shown' }],
})}
messageID="msg_1"
/>,
)
const iframe = screen.getByTitle('Report')
expect(iframe.tagName).toBe('IFRAME')
expect(iframe).toHaveAttribute('src', getFileApiUrl('/tmp/artifacts/report.html', { params: { raw: true } }))
})
})
describe('sandbox indicator', () => {
@@ -1,5 +1,5 @@
import { memo } from 'react'
import type { SessionMessageAssistant } from '@opencode-manager/shared/opencode'
import { readShowArtifactCall, type SessionMessageAssistant } from '@opencode-manager/shared/opencode'
import { TextPart } from './TextPart'
import { ToolCallPart } from './ToolCallPart'
import { useSettings } from '@/hooks/useSettings'
@@ -40,7 +40,7 @@ export const MessagePart = memo(function MessagePart({ part, messageID, director
</details>
)
case 'tool':
if (simpleChatMode && part.name !== 'subagent') return null
if (simpleChatMode && part.name !== 'subagent' && !readShowArtifactCall(part)) return null
return (
<ToolCallPart
part={part}
@@ -1,6 +1,6 @@
import { memo, useCallback, useMemo, useState } from 'react'
import { Pencil, Loader2 } from 'lucide-react'
import { assistantText, formatOpenCodeModelRef } from '@opencode-manager/shared/opencode'
import { assistantText, formatOpenCodeModelRef, readShowArtifactCall } from '@opencode-manager/shared/opencode'
import type {
PromptAgentAttachment,
PromptFileAttachment,
@@ -50,6 +50,12 @@ function isSubagentTool(
return part.type === 'tool' && part.name === 'subagent'
}
function isArtifactTool(
part: SessionMessageAssistant['content'][number],
): part is SessionMessageAssistantTool {
return part.type === 'tool' && readShowArtifactCall(part) !== undefined
}
function hasRenderableContent(
message: SessionMessageInfo,
simpleChatMode: boolean,
@@ -63,7 +69,7 @@ function hasRenderableContent(
return message.content.some((part) => {
if (part.type === 'text') return part.text.trim().length > 0
if (part.type === 'reasoning') return !simpleChatMode && showReasoning && part.text.trim().length > 0
if (part.type === 'tool') return !simpleChatMode || isSubagentTool(part)
if (part.type === 'tool') return !simpleChatMode || isSubagentTool(part) || isArtifactTool(part)
return false
})
case 'synthetic':
@@ -4,6 +4,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter } from 'react-router-dom'
import type { PermissionRequest, SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { ToolCallPart } from './ToolCallPart'
import { getFileApiUrl } from '@/api/files'
import { useUserBash } from '@/stores/userBashStore'
import { useSessionStatus } from '@/stores/sessionStatusStore'
@@ -381,3 +382,108 @@ describe('ToolCallPart open walkthrough action', () => {
expect(screen.queryByRole('button', { name: 'Open walkthrough' })).not.toBeInTheDocument()
})
})
describe('ToolCallPart show artifact action', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useSettings.mockReturnValue({
preferences: { expandToolCalls: false },
isLoading: false,
updateSettings: vi.fn(),
isUpdating: false,
})
mocks.useToolCallPermission.mockReturnValue(null)
})
const showArtifact = (params: unknown): SessionMessageAssistantTool => ({
type: 'tool',
id: 'call_artifact',
name: 'ocm',
time: { created: 1, ran: 2, completed: 3 },
state: {
status: 'completed',
input: { action: 'show_artifact', params },
content: [{ type: 'text', text: 'Artifact shown' }],
},
})
it('renders the sandboxed iframe, path label, and open-in-new-tab link', () => {
const src = getFileApiUrl('/repo/reports/summary.html', { params: { raw: true } })
renderWithProviders(
<ToolCallPart
part={showArtifact({ title: 'Report', path: 'reports/summary.html' })}
messageID="msg_1"
directory="/repo"
/>,
)
const iframe = screen.getByTitle('Report')
expect(iframe.tagName).toBe('IFRAME')
expect(iframe).toHaveAttribute('sandbox', 'allow-scripts')
expect(iframe.getAttribute('sandbox')).not.toContain('allow-same-origin')
expect(iframe).toHaveAttribute('src', src)
const pathLabel = screen.getByText('reports/summary.html')
expect(pathLabel).toHaveAttribute('title', 'reports/summary.html')
const link = screen.getByRole('link', { name: 'Open in new tab' })
expect(link).toHaveAttribute('href', src)
expect(link).toHaveAttribute('target', '_blank')
expect(link).toHaveAttribute('rel', 'noopener noreferrer')
})
it('resolves an absolute artifact path without a session directory', () => {
const src = getFileApiUrl('/tmp/artifacts/report.html', { params: { raw: true } })
renderWithProviders(
<ToolCallPart
part={showArtifact({ title: 'Report', path: '/tmp/artifacts/report.html' })}
messageID="msg_1"
/>,
)
const iframe = screen.getByTitle('Report')
expect(iframe).toHaveAttribute('src', src)
expect(screen.getByText('/tmp/artifacts/report.html')).toHaveAttribute('title', '/tmp/artifacts/report.html')
})
it('remounts the iframe with an unchanged src when Reload is clicked', () => {
const src = getFileApiUrl('/repo/reports/summary.html', { params: { raw: true } })
const { container } = renderWithProviders(
<ToolCallPart
part={showArtifact({ title: 'Report', path: 'reports/summary.html' })}
messageID="msg_1"
directory="/repo"
/>,
)
const before = container.querySelector('iframe')
expect(before).not.toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'Reload artifact' }))
const after = container.querySelector('iframe')
expect(after).not.toBe(before)
expect(after).toHaveAttribute('src', src)
})
it('falls back to the generic tool card for invalid params', () => {
const { container } = renderWithProviders(
<ToolCallPart part={showArtifact({ title: 'No path' })} messageID="msg_1" directory="/repo" />,
)
expect(container.querySelector('iframe')).toBeNull()
expect(screen.getByText('ocm')).toBeInTheDocument()
})
it('falls back to the generic tool card for a relative path without a directory', () => {
const { container } = renderWithProviders(
<ToolCallPart part={showArtifact({ title: 'Report', path: 'reports/summary.html' })} messageID="msg_1" />,
)
expect(container.querySelector('iframe')).toBeNull()
expect(screen.getByText('ocm')).toBeInTheDocument()
})
})
@@ -1,6 +1,6 @@
import { useState, useRef, useEffect, useMemo, memo } from 'react'
import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils'
import { toolContentText, type SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { readShowArtifactCall, toolContentText, type SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { useSettings } from '@/hooks/useSettings'
import { useUserBash } from '@/stores/userBashStore'
import { useChildLifecycleForSession } from '@/stores/sessionStatusStore'
@@ -28,6 +28,8 @@ import {
} from '@/lib/backgroundWork'
import { getToolInputPath, getToolSpecificRender } from './FileToolRender'
import { readOpenWalkthroughCall } from '@/lib/walkthroughTool'
import { getFileApiUrl } from '@/api/files'
import { ArtifactPart } from './ArtifactPart'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
const DISPLAY_LIMIT = 30_000
@@ -251,6 +253,14 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
</Badge>
) : null
const artifact = readShowArtifactCall(part)
if (artifact && (artifact.path.startsWith('/') || directory)) {
const fullPath = artifact.path.startsWith('/')
? artifact.path
: `${directory?.replace(/\/+$/, '')}/${artifact.path}`
return <ArtifactPart title={artifact.title} path={artifact.path} src={getFileApiUrl(fullPath, { params: { raw: true } })} />
}
if (isSubagent) {
const status = part.state.status
const isRunning = status !== 'streaming' && isRunningLifecycle(subagentStatus)