fix(artifacts): render artifacts from the checked path and serve raw files once

- show_artifact returns the validated path as tool metadata; the chat card
  renders from it and maps repo paths with getWorkspaceFilePath, so local
  repos and moved sessions load the right file
- serve .htm as text/html
- raw file route stats and reads once and adds ETag/Last-Modified with 304
- reuse isPathWithinRoot from utils/fs-safe
- move readShowArtifactCall to frontend/src/lib/artifactTool
This commit is contained in:
Chris Scott committed 2026-10-12 16:43:04 -04:00
1 parent f7b2ffb865
commit 5e2452172c
26 files changed
+489 -58

No files matched your search

+44 -6
View File
@@ -23,6 +23,19 @@ function getSpecialRoutePathFromRequest(c: Context, routeName: string): string |
return match?.[1] ? decodeFilePath(match[1]) : undefined
}
function buildWeakEtag(size: number, lastModified: Date): string {
return `W/"${size}-${lastModified.getTime()}"`
}
function matchesIfNoneMatch(ifNoneMatch: string | undefined, etag: string): boolean {
if (!ifNoneMatch) {
return false
}
const values = ifNoneMatch.split(',').map((value) => value.trim())
return values.includes('*') || values.includes(etag)
}
export function createFileRoutes() {
const app = new Hono()
@@ -112,21 +125,46 @@ export function createFileRoutes() {
return c.json(result)
}
const result = await fileService.getFile(userPath)
if (raw && !result.isDirectory) {
if (raw) {
const metadata = await fileService.getRawFileMetadata(userPath)
if (!metadata) {
const result = await fileService.getFile(userPath)
return c.json(result)
}
const etag = buildWeakEtag(metadata.size, metadata.lastModified)
const lastModified = metadata.lastModified.toUTCString()
if (matchesIfNoneMatch(c.req.header('if-none-match'), etag)) {
return new Response(null, {
status: 304,
headers: {
'ETag': etag,
'Last-Modified': lastModified,
'Cache-Control': 'no-cache',
'Content-Security-Policy': 'sandbox allow-scripts',
'X-Content-Type-Options': 'nosniff',
},
})
}
const content = await fileService.getRawFileContent(userPath)
return new Response(content, {
headers: {
'Content-Type': result.mimeType || 'application/octet-stream',
'Content-Length': result.size.toString(),
'Content-Type': metadata.mimeType,
'Content-Length': content.byteLength.toString(),
'Content-Security-Policy': 'sandbox allow-scripts',
'Cache-Control': 'no-cache',
'X-Content-Type-Options': 'nosniff',
'ETag': etag,
'Last-Modified': lastModified,
}
})
}
const result = await fileService.getFile(userPath)
if (download && !result.isDirectory) {
const content = result.content ? Buffer.from(result.content, 'base64') : Buffer.alloc(0)
return new Response(content, {
+1 -1
View File
@@ -14,7 +14,7 @@ import {
} from '../services/opencode/upstream'
import { getRepoById } from '../db/queries'
import { getTrustedOrigins, getWorkspacePath } from '@opencode-manager/shared/config/env'
import { isPathWithinRoot } from '../services/sandbox/command'
import { isPathWithinRoot } from '../utils/fs-safe'
import { buildProxyResponseHeaders, filterProxyHeaders } from '../utils/proxy-headers'
import {
connectUpstreamWebSocket,
+33
View File
@@ -40,6 +40,12 @@ interface FileUploadResult {
mimeType: string
}
export interface RawFileMetadata {
size: number
mimeType: AllowedMimeType
lastModified: Date
}
export async function getRawFileContent(userPath: string): Promise<Buffer> {
const validatedPath = validatePath(userPath)
logger.info(`Getting raw file content for path: ${userPath} -> ${validatedPath}`)
@@ -62,6 +68,32 @@ export async function getRawFileContent(userPath: string): Promise<Buffer> {
}
}
export async function getRawFileMetadata(userPath: string): Promise<RawFileMetadata | null> {
const validatedPath = validatePath(userPath)
logger.info(`Getting raw file metadata for path: ${userPath} -> ${validatedPath}`)
try {
const exists = await fileExists(validatedPath)
if (!exists) {
throw new Error('Path does not exist')
}
const stats = await getFileStats(validatedPath)
if (stats.isDirectory) {
return null
}
return {
size: stats.size,
mimeType: getMimeType(validatedPath),
lastModified: stats.lastModified,
}
} catch (error) {
logger.error(`Failed to read raw file metadata ${validatedPath}:`, error)
throw { message: 'File or directory not found', statusCode: 404 }
}
}
export async function getFile(userPath: string): Promise<FileInfo> {
const validatedPath = validatePath(userPath)
const responsePath = path.isAbsolute(userPath.trim()) ? path.relative(SHARED_WORKSPACE_BASE, validatedPath) : userPath
@@ -262,6 +294,7 @@ function getMimeType(filePath: string): AllowedMimeType {
const mimeTypes: Record<string, AllowedMimeType> = {
'.txt': 'text/plain',
'.html': 'text/html',
'.htm': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.ts': 'text/typescript',
@@ -255,7 +255,10 @@ var ACTIONS = {
{ path: params.path },
context.signal,
)
return 'Showing the artifact "' + params.title + '" from ' + result.path + ' in the Manager chat. It renders the current file contents, so after editing the file the user can reload the view; call show_artifact again only to show a different file.'
return {
content: 'Showing the artifact "' + params.title + '" from ' + result.path + ' in the Manager chat. It renders the current file contents, so after editing the file the user can reload the view; call show_artifact again only to show a different file.',
metadata: { path: result.path },
}
},
},
}
@@ -294,7 +297,11 @@ export default {
input: INPUT_SCHEMA,
options: { codemode: false },
execute: async function (input, context) {
return { content: await runAction(input, context) }
var result = await runAction(input, context)
if (result !== null && typeof result === 'object') {
return result
}
return { content: result }
},
})
})
+1 -5
View File
@@ -11,6 +11,7 @@ import {
getReposPath,
getScheduleWorktreesPath,
} from '@opencode-manager/shared/config/env'
import { isPathWithinRoot } from '../../utils/fs-safe'
export const WORKSPACE_SANDBOX_NAME = 'ocm-workspace'
@@ -36,11 +37,6 @@ export function overrideSandboxExecutableTrustValidator(validator: ((candidate:
resetSandboxExecutableCache()
}
export function isPathWithinRoot(root: string, target: string): boolean {
const relative = path.relative(path.resolve(root), path.resolve(target))
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
}
function isWritableByManager(stat: { uid: number; gid: number; mode: number }): boolean {
if (typeof process.getuid === 'function' && typeof process.getgid === 'function') {
if (stat.uid === process.getuid() && (stat.mode & 0o200) !== 0) return true
+1 -2
View File
@@ -1,8 +1,7 @@
import path from 'path'
import { ENV } from '@opencode-manager/shared/config/env'
import { writeFileAtomic } from '../../utils/fs-safe'
import { isPathWithinRoot, writeFileAtomic } from '../../utils/fs-safe'
import {
isPathWithinRoot,
quoteForShell,
resolveSandboxExecUser,
sandboxExecutablePath,
+7 -9
View File
@@ -3,6 +3,7 @@ import path from 'node:path'
import { ARTIFACT_LIMITS } from '@opencode-manager/shared/schemas'
import type { OpenCodeClient } from './opencode/client'
import { ServiceError } from '../utils/service-error'
import { isPathWithinRoot } from '../utils/fs-safe'
const ARTIFACT_EXTENSIONS = new Set(['.html', '.htm'])
@@ -13,14 +14,11 @@ export class SessionArtifactError extends ServiceError {
}
}
function isInsideDirectory(directory: string, candidate: string): boolean {
const relative = path.relative(directory, candidate)
return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)
}
/**
* Resolves an `ocm` `show_artifact` path to the real, absolute path of a self-contained HTML file inside the
* session directory, rejecting paths that escape it (including through symlinks), non-HTML files and oversized files.
* Resolves an `ocm` `show_artifact` path to the absolute path of a self-contained HTML file inside the session
* directory, rejecting paths that escape it (including through symlinks), non-HTML files and oversized files.
* Symlinks are resolved for validation only; the returned path stays lexical so callers can map it by the
* session directory or repo prefix they were given.
*/
export async function resolveSessionArtifactFile(
openCodeClient: OpenCodeClient,
@@ -46,7 +44,7 @@ export async function resolveSessionArtifactFile(
throw new SessionArtifactError(`Artifact file not found: ${artifactPath}`, 404)
}
if (!isInsideDirectory(realSessionDirectory, realFile)) {
if (!isPathWithinRoot(realSessionDirectory, realFile)) {
throw new SessionArtifactError(`Artifact path must be inside the session directory ${sessionDirectory}`, 400)
}
@@ -65,5 +63,5 @@ export async function resolveSessionArtifactFile(
throw new SessionArtifactError('Artifact file exceeds 5 MB', 413)
}
return realFile
return resolved
}
+5
View File
@@ -26,6 +26,11 @@ export function canonicalPathSync(target: string): string {
}
}
export function isPathWithinRoot(root: string, target: string): boolean {
const relative = path.relative(path.resolve(root), path.resolve(target))
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
}
export async function writeFileAtomic(filePath: string, content: string | Buffer, options: { mode?: number } = {}): Promise<void> {
const dir = path.dirname(filePath)
await mkdirSafe(dir)
+92 -2
View File
@@ -31,6 +31,7 @@ vi.mock('@opencode-manager/shared/config/env', () => ({
vi.mock('../../src/services/files', () => ({
getFile: vi.fn(),
getRawFileContent: vi.fn(),
getRawFileMetadata: vi.fn(),
getFileRange: vi.fn(),
uploadFile: vi.fn(),
createFileOrFolder: vi.fn(),
@@ -47,6 +48,8 @@ vi.mock('../../src/services/archive', () => ({
}))
const getFile = fileService.getFile as MockedFunction<typeof fileService.getFile>
const getRawFileContent = fileService.getRawFileContent as MockedFunction<typeof fileService.getRawFileContent>
const getRawFileMetadata = fileService.getRawFileMetadata as MockedFunction<typeof fileService.getRawFileMetadata>
const getFileRange = fileService.getFileRange as MockedFunction<typeof fileService.getFileRange>
const uploadFile = fileService.uploadFile as MockedFunction<typeof fileService.uploadFile>
const createFileOrFolder = fileService.createFileOrFolder as MockedFunction<typeof fileService.createFileOrFolder>
@@ -141,6 +144,9 @@ describe('File Routes', () => {
lastModified: new Date(),
}
const rawLastModified = new Date('2024-01-02T03:04:05.000Z')
const rawEtag = `W/"13-${rawLastModified.getTime()}"`
it('should return directory listing when path is directory', async () => {
getFile.mockResolvedValue(mockDirInfo)
@@ -167,8 +173,8 @@ describe('File Routes', () => {
})
it('should serve raw content inside a CSP sandbox', async () => {
getFile.mockResolvedValue({ ...mockFileInfo, name: 'report.html', mimeType: 'text/html', size: 13 })
vi.mocked(fileService.getRawFileContent).mockResolvedValue(Buffer.from('<h1>hi</h1>\n\n'))
getRawFileMetadata.mockResolvedValue({ size: 13, mimeType: 'text/html', lastModified: rawLastModified })
getRawFileContent.mockResolvedValue(Buffer.from('<h1>hi</h1>\n\n'))
const response = await app.request('/api/files?path=test-repo/report.html&raw=true')
@@ -177,6 +183,90 @@ describe('File Routes', () => {
expect(response.headers.get('Content-Security-Policy')).toBe('sandbox allow-scripts')
expect(response.headers.get('Cache-Control')).toBe('no-cache')
expect(response.headers.get('X-Content-Type-Options')).toBe('nosniff')
expect(getFile).not.toHaveBeenCalled()
})
it('should serve .htm raw content as text/html', async () => {
getRawFileMetadata.mockResolvedValue({ size: 13, mimeType: 'text/html', lastModified: rawLastModified })
getRawFileContent.mockResolvedValue(Buffer.from('<h1>hi</h1>\n\n'))
const response = await app.request('/api/files?path=test-repo/report.htm&raw=true')
expect(response.status).toBe(200)
expect(response.headers.get('Content-Type')).toBe('text/html')
})
it('should include ETag and Last-Modified on raw responses', async () => {
getRawFileMetadata.mockResolvedValue({ size: 13, mimeType: 'text/html', lastModified: rawLastModified })
getRawFileContent.mockResolvedValue(Buffer.from('<h1>hi</h1>\n\n'))
const response = await app.request('/api/files?path=test-repo/report.html&raw=true')
expect(response.headers.get('ETag')).toBe(rawEtag)
expect(response.headers.get('Last-Modified')).toBe(rawLastModified.toUTCString())
})
it('should return 304 without a body when If-None-Match matches the ETag', async () => {
getRawFileMetadata.mockResolvedValue({ size: 13, mimeType: 'text/html', lastModified: rawLastModified })
const response = await app.request('/api/files?path=test-repo/report.html&raw=true', {
headers: { 'If-None-Match': rawEtag },
})
expect(response.status).toBe(304)
expect(response.headers.get('ETag')).toBe(rawEtag)
expect(response.headers.get('Cache-Control')).toBe('no-cache')
expect(response.headers.get('Content-Security-Policy')).toBe('sandbox allow-scripts')
expect(response.headers.get('X-Content-Type-Options')).toBe('nosniff')
expect(await response.text()).toBe('')
expect(getRawFileContent).not.toHaveBeenCalled()
})
it('should match If-None-Match within a comma-separated list', async () => {
getRawFileMetadata.mockResolvedValue({ size: 13, mimeType: 'text/html', lastModified: rawLastModified })
const response = await app.request('/api/files?path=test-repo/report.html&raw=true', {
headers: { 'If-None-Match': `"other", ${rawEtag}` },
})
expect(response.status).toBe(304)
expect(getRawFileContent).not.toHaveBeenCalled()
})
it('should match the If-None-Match wildcard', async () => {
getRawFileMetadata.mockResolvedValue({ size: 13, mimeType: 'text/html', lastModified: rawLastModified })
const response = await app.request('/api/files?path=test-repo/report.html&raw=true', {
headers: { 'If-None-Match': '*' },
})
expect(response.status).toBe(304)
expect(getRawFileContent).not.toHaveBeenCalled()
})
it('should return 200 when If-None-Match does not match', async () => {
getRawFileMetadata.mockResolvedValue({ size: 13, mimeType: 'text/html', lastModified: rawLastModified })
getRawFileContent.mockResolvedValue(Buffer.from('<h1>hi</h1>\n\n'))
const response = await app.request('/api/files?path=test-repo/report.html&raw=true', {
headers: { 'If-None-Match': 'W/"different"' },
})
expect(response.status).toBe(200)
expect(getRawFileContent).toHaveBeenCalled()
})
it('should fall through to the directory listing when raw is requested for a directory', async () => {
getRawFileMetadata.mockResolvedValue(null)
getFile.mockResolvedValue(mockDirInfo)
const response = await app.request('/api/files?path=test-repo/src&raw=true')
const body = await response.json() as FileInfo
expect(response.status).toBe(200)
expect(body).toHaveProperty('isDirectory', true)
expect(getFile).toHaveBeenCalledWith('test-repo/src')
expect(getRawFileContent).not.toHaveBeenCalled()
})
it('should return 404 when path does not exist', async () => {
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs'
import os from 'os'
import path from 'path'
import { allMigrations } from '../../src/db/migrations'
@@ -75,6 +75,44 @@ describe('internal/session-artifacts routes', () => {
await expect(res.json()).resolves.toEqual({ path: filePath })
})
it('keeps the symlinked session directory prefix in the returned path', async () => {
const realRoot = path.join(root, 'real')
const realSessionDirectory = path.join(realRoot, 'session')
mkdirSync(realSessionDirectory, { recursive: true })
writeFileSync(path.join(realSessionDirectory, 'report.html'), '<h1>Report</h1>')
const linkedRoot = path.join(root, 'linked')
symlinkSync(realRoot, linkedRoot, 'dir')
const linkedSessionDirectory = path.join(linkedRoot, 'session')
const client = {
api: { session: { get: vi.fn(async () => ({ location: { directory: linkedSessionDirectory } })) } },
} as unknown as OpenCodeClient
const linkedApp = new Hono()
linkedApp.route('/api/internal', createInternalTestApp(db, { openCodeClient: client }))
const res = await linkedApp.request(`/api/internal/session-artifacts/${SESSION_ID}/resolve`, {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: JSON.stringify({ path: 'report.html' }),
})
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({ path: path.join(linkedSessionDirectory, 'report.html') })
})
it('rejects a symlink that escapes the session directory', async () => {
const outside = path.join(root, 'outside.html')
writeFileSync(outside, '<h1>Outside</h1>')
symlinkSync(outside, path.join(sessionDirectory, 'link.html'))
const res = await resolve({ path: 'link.html' })
expect(res.status).toBe(400)
await expect(res.json()).resolves.toEqual({
error: `Artifact path must be inside the session directory ${sessionDirectory}`,
})
})
it('returns 404 when the file does not exist', async () => {
const res = await resolve({ path: 'missing.html' })
+35
View File
@@ -9,6 +9,7 @@ import {
getFile,
getFileRange,
getRawFileContent,
getRawFileMetadata,
renameOrMoveFile,
uploadFile,
} from '../../src/services/files'
@@ -74,6 +75,32 @@ describe('files service', () => {
})
})
describe('getRawFileMetadata', () => {
it('returns size, mime type and last modified for an existing file', async () => {
await writeLines(`${relativeRoot}/meta.htm`, '<h1>hi</h1>')
const metadata = await getRawFileMetadata(`${relativeRoot}/meta.htm`)
expect(metadata).not.toBeNull()
expect(metadata?.size).toBe(11)
expect(metadata?.mimeType).toBe('text/html')
expect(metadata?.lastModified).toBeInstanceOf(Date)
})
it('returns null for a directory', async () => {
await mkdir(resolveTempPath(`${relativeRoot}/meta-dir`))
expect(await getRawFileMetadata(`${relativeRoot}/meta-dir`)).toBeNull()
})
it('rejects with 404 when the file is missing', async () => {
await expect(getRawFileMetadata(`${relativeRoot}/missing.htm`)).rejects.toEqual({
message: 'File or directory not found',
statusCode: 404,
})
})
})
describe('getFile', () => {
it('returns base64 content for a text file', async () => {
await writeLines(`${relativeRoot}/note.txt`, 'hello world')
@@ -107,6 +134,14 @@ describe('files service', () => {
expect(Buffer.from(result.content ?? '', 'base64').toString('utf8')).toBe('mystery')
})
it('maps .htm files to text/html', async () => {
await writeLines(`${relativeRoot}/page.htm`, '<h1>hi</h1>')
const result = await getFile(`${relativeRoot}/page.htm`)
expect(result.mimeType).toBe('text/html')
})
it('omits content for files at the size limit', async () => {
const filePath = await writeLines(`${relativeRoot}/large.txt`, '')
await truncate(filePath, FILE_LIMITS.MAX_SIZE_BYTES)
@@ -310,7 +310,7 @@ describe('ocm-manager plugin', () => {
expect(result.content).toBe(
'Showing the artifact "Formation odds" from /workspace/repos/app/report.html in the Manager chat. It renders the current file contents, so after editing the file the user can reload the view; call show_artifact again only to show a different file.',
)
expect(result.metadata).toBeUndefined()
expect(result.metadata).toEqual({ path: '/workspace/repos/app/report.html' })
})
it('surfaces the resolve error when the artifact path is rejected', async () => {
@@ -21,7 +21,6 @@ import {
buildSandboxStartArgs,
buildSandboxStopManagedArgs,
buildSandboxVersionArgs,
isPathWithinRoot,
quoteForShell,
resolveExpectedSandboxNetworkPolicy,
resolveSandboxExecUser,
@@ -31,6 +30,7 @@ import {
sandboxMountRoots,
sandboxNetworkPolicyMismatch,
} from '../../../src/services/sandbox/command'
import { isPathWithinRoot } from '../../../src/utils/fs-safe'
afterEach(() => {
vi.restoreAllMocks()
@@ -11,6 +11,8 @@ interface ExplorationGroupProps {
parts: SessionMessageAssistantTool[]
messageID: string
directory?: string
repoFullPath?: string
repoLocalPath?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onOpenWalkthrough?: (source?: WalkthroughSource) => void
@@ -326,6 +326,34 @@ describe('MessagePart', () => {
expect(iframe.tagName).toBe('IFRAME')
expect(iframe).toHaveAttribute('src', getFileApiUrl('/tmp/artifacts/report.html', { params: { raw: true } }))
})
it('passes the resolved metadata path and repo mapping through to the artifact frame', () => {
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' }],
metadata: { path: '/workspace/repos/assistant/reports/summary.html' },
})}
messageID="msg_1"
directory="/workspace/repos/assistant"
repoFullPath="/workspace/repos/assistant"
repoLocalPath="assistant"
/>,
)
const iframe = screen.getByTitle('Report')
expect(iframe.tagName).toBe('IFRAME')
expect(iframe).toHaveAttribute('src', getFileApiUrl('assistant/reports/summary.html', { params: { raw: true } }))
})
})
describe('sandbox indicator', () => {
@@ -1,7 +1,8 @@
import { memo } from 'react'
import { readShowArtifactCall, type SessionMessageAssistant } from '@opencode-manager/shared/opencode'
import type { SessionMessageAssistant } from '@opencode-manager/shared/opencode'
import { TextPart } from './TextPart'
import { ToolCallPart } from './ToolCallPart'
import { readShowArtifactCall } from '@/lib/artifactTool'
import { useSettings } from '@/hooks/useSettings'
import type { ShellNoticeOutcome } from '@/lib/backgroundWork'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
@@ -12,13 +13,15 @@ interface MessagePartProps {
part: AssistantContentPart
messageID?: string
directory?: string
repoFullPath?: string
repoLocalPath?: string
shellOutcome?: ShellNoticeOutcome
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onOpenWalkthrough?: (source?: WalkthroughSource) => void
}
export const MessagePart = memo(function MessagePart({ part, messageID, directory, shellOutcome, onFileClick, onChildSessionClick, onOpenWalkthrough }: MessagePartProps) {
export const MessagePart = memo(function MessagePart({ part, messageID, directory, repoFullPath, repoLocalPath, shellOutcome, onFileClick, onChildSessionClick, onOpenWalkthrough }: MessagePartProps) {
const { preferences } = useSettings()
const simpleChatMode = preferences?.simpleChatMode ?? false
const showReasoning = preferences?.showReasoning ?? false
@@ -46,6 +49,8 @@ export const MessagePart = memo(function MessagePart({ part, messageID, director
part={part}
messageID={messageID}
directory={directory}
repoFullPath={repoFullPath}
repoLocalPath={repoLocalPath}
shellOutcome={shellOutcome}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
@@ -1,6 +1,6 @@
import { memo, useCallback, useMemo, useState } from 'react'
import { Pencil, Loader2 } from 'lucide-react'
import { assistantText, formatOpenCodeModelRef, readShowArtifactCall } from '@opencode-manager/shared/opencode'
import { assistantText, formatOpenCodeModelRef } from '@opencode-manager/shared/opencode'
import type {
PromptAgentAttachment,
PromptFileAttachment,
@@ -23,6 +23,7 @@ import { useSettings } from '@/hooks/useSettings'
import { CopyButton } from '@/components/ui/copy-button'
import { TTSButton } from '@/components/ui/tts-button'
import { backgroundShellID, collectBackgroundParts, type ShellNoticeOutcome } from '@/lib/backgroundWork'
import { readShowArtifactCall } from '@/lib/artifactTool'
import { groupExplorationParts, type AssistantContentItem } from '@/lib/explorationGroups'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
import { ExplorationGroup } from './ExplorationGroup'
@@ -329,6 +330,8 @@ interface MessageRowProps {
handleCancelEdit: () => void
sessionID: string
directory?: string
repoFullPath?: string
repoLocalPath?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onOpenWalkthrough?: (source?: WalkthroughSource) => void
@@ -350,6 +353,8 @@ const MessageRow = memo(function MessageRow({
handleCancelEdit,
sessionID,
directory,
repoFullPath,
repoLocalPath,
onFileClick,
onChildSessionClick,
onOpenWalkthrough,
@@ -458,6 +463,8 @@ const MessageRow = memo(function MessageRow({
part={part}
messageID={message.id}
directory={directory}
repoFullPath={repoFullPath}
repoLocalPath={repoLocalPath}
shellOutcome={shellOutcomeFor(part)}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
@@ -502,6 +509,8 @@ const MessageRow = memo(function MessageRow({
parts={item.parts}
messageID={message.id}
directory={directory}
repoFullPath={repoFullPath}
repoLocalPath={repoLocalPath}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
onOpenWalkthrough={onOpenWalkthrough}
@@ -511,6 +520,8 @@ const MessageRow = memo(function MessageRow({
part={item.part}
messageID={message.id}
directory={directory}
repoFullPath={repoFullPath}
repoLocalPath={repoLocalPath}
shellOutcome={shellOutcomeFor(item.part)}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
@@ -578,6 +589,8 @@ const MessageRow = memo(function MessageRow({
interface MessageThreadProps {
sessionID: string
directory?: string
repoFullPath?: string
repoLocalPath?: string
messages: SessionMessageInfo[]
pending: SessionInboxInfo[]
onFileClick?: (filePath: string, lineNumber?: number) => void
@@ -591,6 +604,8 @@ interface MessageThreadProps {
export const MessageThread = memo(function MessageThread({
sessionID,
directory,
repoFullPath,
repoLocalPath,
messages,
pending,
onFileClick,
@@ -661,6 +676,8 @@ export const MessageThread = memo(function MessageThread({
handleCancelEdit={handleCancelEdit}
sessionID={sessionID}
directory={directory}
repoFullPath={repoFullPath}
repoLocalPath={repoLocalPath}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
onOpenWalkthrough={onOpenWalkthrough}
@@ -395,7 +395,7 @@ describe('ToolCallPart show artifact action', () => {
mocks.useToolCallPermission.mockReturnValue(null)
})
const showArtifact = (params: unknown): SessionMessageAssistantTool => ({
const showArtifact = (params: unknown, metadata?: Record<string, string>): SessionMessageAssistantTool => ({
type: 'tool',
id: 'call_artifact',
name: 'ocm',
@@ -404,6 +404,7 @@ describe('ToolCallPart show artifact action', () => {
status: 'completed',
input: { action: 'show_artifact', params },
content: [{ type: 'text', text: 'Artifact shown' }],
metadata,
},
})
@@ -433,6 +434,40 @@ describe('ToolCallPart show artifact action', () => {
expect(link).toHaveAttribute('rel', 'noopener noreferrer')
})
it('prefers the backend-resolved metadata path over the directory join', () => {
const src = getFileApiUrl('/workspace/sessions/ses_1/report.html', { params: { raw: true } })
renderWithProviders(
<ToolCallPart
part={showArtifact(
{ title: 'Report', path: 'reports/summary.html' },
{ path: '/workspace/sessions/ses_1/report.html' },
)}
messageID="msg_1"
directory="/repo"
/>,
)
expect(screen.getByTitle('Report')).toHaveAttribute('src', src)
expect(screen.getByText('reports/summary.html')).toHaveAttribute('title', 'reports/summary.html')
})
it('maps a repo path outside the workspace to the repo-local path', () => {
const src = getFileApiUrl('assistant/reports/summary.html', { params: { raw: true } })
renderWithProviders(
<ToolCallPart
part={showArtifact({ title: 'Report', path: 'reports/summary.html' })}
messageID="msg_1"
directory="/workspace/repos/assistant"
repoFullPath="/workspace/repos/assistant"
repoLocalPath="assistant"
/>,
)
expect(screen.getByTitle('Report')).toHaveAttribute('src', src)
})
it('resolves an absolute artifact path without a session directory', () => {
const src = getFileApiUrl('/tmp/artifacts/report.html', { params: { raw: true } })
@@ -1,6 +1,6 @@
import { useState, useRef, useEffect, useMemo, memo } from 'react'
import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils'
import { readShowArtifactCall, toolContentText, type SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { 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 { readShowArtifactCall } from '@/lib/artifactTool'
import { getWorkspaceFilePath } from '@/lib/markdownLinks'
import { getFileApiUrl } from '@/api/files'
import { ArtifactPart } from './ArtifactPart'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
@@ -63,6 +65,8 @@ interface ToolCallPartProps {
part: SessionMessageAssistantTool
messageID?: string
directory?: string
repoFullPath?: string
repoLocalPath?: string
shellOutcome?: ShellNoticeOutcome
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
@@ -119,7 +123,7 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">{parts}</pre>
}
export const ToolCallPart = memo(function ToolCallPart({ part, messageID, directory, shellOutcome, onFileClick, onChildSessionClick, onOpenWalkthrough }: ToolCallPartProps) {
export const ToolCallPart = memo(function ToolCallPart({ part, messageID, directory, repoFullPath, repoLocalPath, shellOutcome, onFileClick, onChildSessionClick, onOpenWalkthrough }: ToolCallPartProps) {
const { preferences } = useSettings()
const { userBashCommands } = useUserBash()
const isSubagent = part.name === 'subagent'
@@ -254,11 +258,13 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
) : 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 (artifact && (artifact.resolvedPath || artifact.path.startsWith('/') || directory)) {
const servedPath = getWorkspaceFilePath(artifact.resolvedPath ?? artifact.path, {
directory,
repoFullPath,
repoLocalPath,
})
return <ArtifactPart title={artifact.title} path={artifact.path} src={getFileApiUrl(servedPath, { params: { raw: true } })} />
}
if (isSubagent) {
+81
View File
@@ -0,0 +1,81 @@
import { describe, it, expect } from 'vitest'
import type { SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { readShowArtifactCall } from './artifactTool'
const ocmPart = (
params: unknown,
options: { status?: 'running' | 'completed'; metadata?: { path: string } } = {},
): SessionMessageAssistantTool => ({
type: 'tool',
id: 't1',
name: 'ocm',
time: { created: 1 },
state:
options.status === 'running'
? {
status: 'running',
input: { action: 'show_artifact', params },
metadata: {},
}
: {
status: 'completed',
input: { action: 'show_artifact', params },
content: [{ type: 'text', text: 'Artifact shown.' }],
metadata: options.metadata,
},
})
describe('readShowArtifactCall', () => {
it('returns the validated title and path without a resolved path', () => {
expect(readShowArtifactCall(ocmPart({ title: 'Report', path: 'reports/summary.html' }))).toEqual({
title: 'Report',
path: 'reports/summary.html',
resolvedPath: undefined,
})
})
it('returns the backend-resolved absolute path when metadata carries one', () => {
expect(
readShowArtifactCall(
ocmPart(
{ title: 'Report', path: 'reports/summary.html' },
{ metadata: { path: '/workspace/sessions/ses_1/report.html' } },
),
),
).toEqual({
title: 'Report',
path: 'reports/summary.html',
resolvedPath: '/workspace/sessions/ses_1/report.html',
})
})
it('ignores an empty metadata path', () => {
expect(
readShowArtifactCall(ocmPart({ title: 'Report', path: 'a.html' }, { metadata: { path: '' } }))?.resolvedPath,
).toBeUndefined()
})
it('returns undefined for params that do not validate', () => {
expect(readShowArtifactCall(ocmPart({ title: 'No path' }))).toBeUndefined()
expect(readShowArtifactCall(ocmPart('not-an-object'))).toBeUndefined()
})
it('returns undefined for an unfinished call', () => {
expect(readShowArtifactCall(ocmPart({ title: 'Report', path: 'a.html' }, { status: 'running' }))).toBeUndefined()
})
it('returns undefined for another action', () => {
const part: SessionMessageAssistantTool = {
type: 'tool',
id: 't1',
name: 'ocm',
time: { created: 1 },
state: {
status: 'completed',
input: { action: 'open_walkthrough', params: { title: 'Report', path: 'a.html' } },
content: [{ type: 'text', text: 'Opened.' }],
},
}
expect(readShowArtifactCall(part)).toBeUndefined()
})
})
+25
View File
@@ -0,0 +1,25 @@
import type { SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { MANAGER_TOOL_NAME, MANAGER_TOOL_SHOW_ARTIFACT_ACTION, ShowArtifactParamsSchema } from '@opencode-manager/shared/schemas'
interface ShowArtifactCall {
title: string
path: string
resolvedPath?: string
}
/**
* Reads an assistant tool part as a completed `ocm` `show_artifact` call, or undefined for every
* other tool, action, unfinished state, and set of parameters that does not validate. `resolvedPath`
* is the absolute path the backend validated inside the session directory, when it recorded one.
*/
export function readShowArtifactCall(part: SessionMessageAssistantTool): ShowArtifactCall | undefined {
if (part.name !== MANAGER_TOOL_NAME || part.state.status !== 'completed') return undefined
if (part.state.input.action !== MANAGER_TOOL_SHOW_ARTIFACT_ACTION) return undefined
const parsed = ShowArtifactParamsSchema.safeParse(part.state.input.params)
if (!parsed.success) return undefined
const resolvedPath = part.state.metadata?.path
return {
...parsed.data,
resolvedPath: typeof resolvedPath === 'string' && resolvedPath.length > 0 ? resolvedPath : undefined,
}
}
+6
View File
@@ -58,6 +58,12 @@ describe('getWorkspaceFilePath', () => {
expect(getWorkspaceFilePath('out.md', worktree)).toBe('/workspace/worktrees/job-1-run-2/out.md')
expect(getWorkspaceFilePath('/etc/hosts', workspace)).toBe('/etc/hosts')
})
it('normalizes a trailing slash on the working directory', () => {
expect(getWorkspaceFilePath('recaps/daily.html', { ...workspace, directory: '/workspace/repos/assistant/' })).toBe(
'assistant/recaps/daily.html',
)
})
})
describe('isExternalLink', () => {
+2 -1
View File
@@ -48,9 +48,10 @@ export function getWorkspaceFilePath(
workspace: { directory?: string; repoFullPath?: string; repoLocalPath?: string },
): string {
const { directory, repoFullPath, repoLocalPath } = workspace
const baseDirectory = directory?.replace(/\/+$/, '')
const absolutePath = filePath.startsWith('/') || !directory
? filePath
: `${directory}/${filePath.replace(/^\.\//, '')}`
: `${baseDirectory}/${filePath.replace(/^\.\//, '')}`
return repoFullPath && repoLocalPath && absolutePath.startsWith(`${repoFullPath}/`)
? `${repoLocalPath}/${absolutePath.slice(repoFullPath.length + 1)}`
: absolutePath
+2
View File
@@ -743,6 +743,8 @@ export function SessionDetail() {
<MessageThread
sessionID={sessionId}
directory={sessionDirectory}
repoFullPath={repo?.fullPath}
repoLocalPath={repo?.localPath}
messages={messages}
pending={pendingPrompts}
isSessionBusy={isSessionActive}
-14
View File
@@ -1,14 +0,0 @@
import type { SessionMessageAssistantTool } from '@opencode/client'
import { MANAGER_TOOL_NAME, MANAGER_TOOL_SHOW_ARTIFACT_ACTION, ShowArtifactParamsSchema } from '../schemas/internal-assistant'
import type { ShowArtifactParams } from '../schemas/internal-assistant'
/**
* Reads an assistant tool part as a completed `ocm` `show_artifact` call, or undefined for every
* other tool, action, unfinished state, and set of parameters that does not validate.
*/
export function readShowArtifactCall(part: SessionMessageAssistantTool): ShowArtifactParams | undefined {
if (part.name !== MANAGER_TOOL_NAME || part.state.status !== 'completed') return undefined
if (part.state.input.action !== MANAGER_TOOL_SHOW_ARTIFACT_ACTION) return undefined
const parsed = ShowArtifactParamsSchema.safeParse(part.state.input.params)
return parsed.success ? parsed.data : undefined
}
-2
View File
@@ -48,8 +48,6 @@ export { ClientError, isIntegrationNotFoundError, isMcpServerNotFoundError, isSe
export { assistantText, sessionIDFromEvent, toolContentText } from './content'
export { readShowArtifactCall } from './artifact'
export { configModelRef, formatOpenCodeModelRef, parseOpenCodeModelRef, selectConfiguredModelRef } from './modelRef'
export {