Merge pull request #420 from chriswritescode-dev/feat/sandboxed-html-artifacts

feat(artifacts): render agent HTML files inline in the session chat
This commit is contained in:
Chris Scott authored and GitHub committed 2026-10-13 09:30:59 -04:00
commit 59ffe6c586
28 files changed
+1027 -28

No files matched your search

+46 -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,19 +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, {
+2
View File
@@ -17,6 +17,7 @@ import { createInternalSessionRoutes } from './sessions'
import { createInternalAssistantRoutes } from './assistant'
import { createInternalGitCredentialsRoutes } from './git-credentials'
import { createInternalSandboxRoutes } from './sandbox'
import { createInternalSessionArtifactRoutes } from './session-artifacts'
import { createSessionGoalRoutes } from '../session-goals'
import { createMultiRunRoutes } from '../multi-runs'
import { createChangeWalkthroughRoutes } from '../change-walkthroughs'
@@ -58,6 +59,7 @@ export function createInternalRoutes(
app.route('/sessions', createInternalSessionRoutes(db, openCodeClient, permissionModes, repoWorkspaces))
app.route('/assistant', createInternalAssistantRoutes(openCodeClient))
app.route('/change-walkthroughs', createChangeWalkthroughRoutes(changeWalkthroughService))
app.route('/session-artifacts', createInternalSessionArtifactRoutes(openCodeClient))
app.route('/git-credentials', createInternalGitCredentialsRoutes(db))
app.route('/sandbox', createInternalSandboxRoutes(db))
return app
@@ -0,0 +1,31 @@
import { Hono } from 'hono'
import { z } from 'zod'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import type { OpenCodeClient } from '../../services/opencode/client'
import { resolveSessionArtifactFile, SessionArtifactError } from '../../services/session-artifacts'
import { handleOpenCodeError, parseJsonBody } from '../../utils/route-helpers'
const ResolveSessionArtifactRequestSchema = z.object({ path: z.string().min(1) }).strict()
export function createInternalSessionArtifactRoutes(openCodeClient: OpenCodeClient) {
const app = new Hono()
app.post('/:sessionId/resolve', async (c) => {
const parsed = await parseJsonBody(c, ResolveSessionArtifactRequestSchema)
if (!parsed.ok) {
return parsed.response
}
try {
const path = await resolveSessionArtifactFile(openCodeClient, c.req.param('sessionId'), parsed.data.path)
return c.json({ path })
} catch (error) {
if (error instanceof SessionArtifactError) {
return c.json({ error: error.message }, error.status as ContentfulStatusCode)
}
return handleOpenCodeError(c, error, 'Failed to resolve artifact file', { unknownStatus: 502 })
}
})
return app
}
+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',
@@ -1,5 +1,5 @@
import { z } from 'zod'
import { ASSISTANT_NOTIFICATION_LIMITS, MANAGER_TOOL_ACTIONS, MANAGER_TOOL_NAME, WalkthroughSourceSchema } from '@opencode-manager/shared/schemas'
import { ASSISTANT_NOTIFICATION_LIMITS, MANAGER_TOOL_ACTIONS, MANAGER_TOOL_NAME, ShowArtifactParamsSchema, WalkthroughSourceSchema } from '@opencode-manager/shared/schemas'
const MANAGER_TOOL_REQUEST_TIMEOUT_MS = 60000
@@ -69,6 +69,7 @@ const MANAGER_TOOL_ACTION_PARAMS_SCHEMAS: Record<(typeof MANAGER_TOOL_ACTIONS)[n
send_notification: ManagerToolNotificationParamsSchema,
request: ManagerToolRequestParamsSchema,
open_walkthrough: ManagerToolWalkthroughParamsSchema,
show_artifact: ShowArtifactParamsSchema.describe('Show a self-contained HTML file the agent wrote to the user, rendered inline in the Manager chat in a sandboxed frame.'),
}
export function parseAllowedRoute(route: string): { method: string; path: string } {
@@ -102,6 +103,7 @@ function buildManagerToolInputJsonSchema(): Record<string, unknown> {
MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.send_notification,
MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.request,
MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.open_walkthrough,
MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.show_artifact,
])
.describe('The parameters for the chosen action.'),
})
@@ -123,6 +125,7 @@ function buildManagerToolDescription(): string {
'- send_notification: send a push notification to every device the user has registered.',
'- request: call an allow-listed internal API route to read and manage settings, the OpenCode configuration file, repos (list, inspect, clone from a git URL with POST /repos and body { repoUrl, branch?, directoryName? }), OpenCode workspaces, sessions (list, create, follow up, read the latest reply, fork), and schedules.',
"- open_walkthrough: request the change Walkthrough for the current session, generating it if needed. It opens in the user's Manager window when this session is open on desktop; otherwise the user opens it from this tool call. Use when the user asks to walk through, review or explain the changes.",
'- show_artifact: write a self-contained .html file with your file tools, then call show_artifact with its path to show it to the user, rendered inline in this session\'s Manager chat inside a sandboxed frame. Edit the file to fix or change it (no need to resend content). Inline your own CSS and JavaScript; libraries may load from public CDNs. Forms, popups, cookies and local storage are blocked. Single file only: sibling .js and .css files will not load.',
'Allowed request routes:',
]
.concat(MANAGER_TOOL_ALLOWED_ROUTES.map((route) => `- ${route}`))
@@ -245,6 +248,19 @@ var ACTIONS = {
return 'Requested the walkthrough.' + hint
},
},
show_artifact: {
run: async function (params, context) {
var result = await postInternalApi(
'/session-artifacts/' + encodeURIComponent(context.sessionID) + '/resolve',
{ path: params.path },
context.signal,
)
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 },
}
},
},
}
function assertParams(actionName, params) {
@@ -281,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,
+67
View File
@@ -0,0 +1,67 @@
import { promises as fs } from 'node:fs'
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'])
export class SessionArtifactError extends ServiceError {
constructor(message: string, status: 400 | 404 | 413) {
super(message, status)
this.name = 'SessionArtifactError'
}
}
/**
* 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,
sessionId: string,
artifactPath: string,
): Promise<string> {
const session = await openCodeClient.api.session.get({ sessionID: sessionId })
const sessionDirectory = session.location.directory
let realSessionDirectory: string
try {
realSessionDirectory = await fs.realpath(sessionDirectory)
} catch {
throw new SessionArtifactError(`Artifact path must be inside the session directory ${sessionDirectory}`, 400)
}
const resolved = path.isAbsolute(artifactPath) ? path.resolve(artifactPath) : path.resolve(sessionDirectory, artifactPath)
let realFile: string
try {
realFile = await fs.realpath(resolved)
} catch {
throw new SessionArtifactError(`Artifact file not found: ${artifactPath}`, 404)
}
if (!isPathWithinRoot(realSessionDirectory, realFile)) {
throw new SessionArtifactError(`Artifact path must be inside the session directory ${sessionDirectory}`, 400)
}
const stats = await fs.stat(realFile).catch(() => {
throw new SessionArtifactError(`Artifact file not found: ${artifactPath}`, 404)
})
if (!stats.isFile()) {
throw new SessionArtifactError(`Artifact file not found: ${artifactPath}`, 404)
}
if (!ARTIFACT_EXTENSIONS.has(path.extname(realFile).toLowerCase())) {
throw new SessionArtifactError('Artifact must be an .html file', 400)
}
if (stats.size > ARTIFACT_LIMITS.FILE_MAX_BYTES) {
throw new SessionArtifactError('Artifact file exceeds 5 MB', 413)
}
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)
+94 -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,14 +173,100 @@ 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')
expect(response.status).toBe(200)
expect(response.headers.get('Content-Type')).toBe('text/html')
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 () => {
@@ -0,0 +1,148 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs'
import os from 'os'
import path from 'path'
import { allMigrations } from '../../src/db/migrations'
import { getOrCreateInternalToken } from '../../src/services/internal-token'
import { migrate } from '../../src/db/migration-runner'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import { createInternalTestApp } from '../helpers/internal-test-app'
const SESSION_ID = 'ses_artifact_resolve'
describe('internal/session-artifacts routes', () => {
let db: Database
let app: Hono
let token: string
let root: string
let sessionDirectory: string
beforeEach(() => {
root = mkdtempSync(path.join(os.tmpdir(), 'ocm-internal-artifacts-'))
sessionDirectory = path.join(root, 'session')
mkdirSync(sessionDirectory, { recursive: true })
db = new Database(':memory:')
migrate(db, allMigrations)
const client = {
api: { session: { get: vi.fn(async () => ({ location: { directory: sessionDirectory } })) } },
} as unknown as OpenCodeClient
app = new Hono()
app.route('/api/internal', createInternalTestApp(db, { openCodeClient: client }))
token = getOrCreateInternalToken(db)
})
afterEach(() => {
rmSync(root, { recursive: true, force: true })
})
function resolve(body: unknown, headers: Record<string, string> = {}) {
return app.request(`/api/internal/session-artifacts/${SESSION_ID}/resolve`, {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', ...headers },
body: JSON.stringify(body),
})
}
it('returns 401 without a bearer token', async () => {
const res = await app.request(`/api/internal/session-artifacts/${SESSION_ID}/resolve`, { method: 'POST' })
expect(res.status).toBe(401)
})
it('resolves a relative path inside the session directory', async () => {
const filePath = path.join(sessionDirectory, 'reports', 'report.html')
mkdirSync(path.dirname(filePath), { recursive: true })
writeFileSync(filePath, '<h1>Report</h1>')
const res = await resolve({ path: 'reports/report.html' })
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({ path: filePath })
})
it('resolves an absolute path inside the session directory', async () => {
const filePath = path.join(sessionDirectory, 'report.html')
writeFileSync(filePath, '<h1>Report</h1>')
const res = await resolve({ path: filePath })
expect(res.status).toBe(200)
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' })
expect(res.status).toBe(404)
await expect(res.json()).resolves.toEqual({ error: 'Artifact file not found: missing.html' })
})
it('returns 400 when the path escapes the session directory', async () => {
writeFileSync(path.join(root, 'x.html'), '<h1>Outside</h1>')
const res = await resolve({ path: '../x.html' })
expect(res.status).toBe(400)
await expect(res.json()).resolves.toEqual({
error: `Artifact path must be inside the session directory ${sessionDirectory}`,
})
})
it('returns 400 when the file is not an .html file', async () => {
writeFileSync(path.join(sessionDirectory, 'notes.txt'), 'hello')
const res = await resolve({ path: 'notes.txt' })
expect(res.status).toBe(400)
await expect(res.json()).resolves.toEqual({ error: 'Artifact must be an .html file' })
})
it('returns 400 when the body is invalid', async () => {
const res = await resolve({})
expect(res.status).toBe(400)
})
})
+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)
@@ -47,6 +47,10 @@ function walkthroughParamsSchema(tool: GeneratedTool): JsonSchema {
return toolInputSchema(tool).properties?.params?.anyOf?.[2] ?? {}
}
function artifactParamsSchema(tool: GeneratedTool): JsonSchema {
return toolInputSchema(tool).properties?.params?.anyOf?.[3] ?? {}
}
async function runToolResult(
tool: GeneratedTool,
input: unknown,
@@ -108,14 +112,16 @@ describe('ocm-manager plugin', () => {
expect(schema.type).toBe('object')
expect(schema.required).toEqual(['action', 'params'])
expect(schema.additionalProperties).toBe(false)
expect(schema.properties?.action?.enum).toEqual(['send_notification', 'request', 'open_walkthrough'])
expect(schema.properties?.params?.anyOf).toHaveLength(3)
expect(schema.properties?.action?.enum).toEqual(['send_notification', 'request', 'open_walkthrough', 'show_artifact'])
expect(schema.properties?.params?.anyOf).toHaveLength(4)
expect(notificationParamsSchema(tool).required).toEqual(['title', 'body'])
expect(requestParamsSchema(tool).required).toEqual(['method', 'path'])
expect(walkthroughParamsSchema(tool).required).toBeUndefined()
expect(artifactParamsSchema(tool).required).toEqual(['title', 'path'])
expect(notificationParamsSchema(tool).additionalProperties).toBe(false)
expect(requestParamsSchema(tool).additionalProperties).toBe(false)
expect(walkthroughParamsSchema(tool).additionalProperties).toBe(false)
expect(artifactParamsSchema(tool).additionalProperties).toBe(false)
expect(notificationParamsSchema(tool).properties?.priority?.enum).toEqual(['normal', 'high'])
expect(requestParamsSchema(tool).properties?.method?.enum).toEqual(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
expect(walkthroughParamsSchema(tool).properties?.source?.oneOf?.map((variant) => variant.properties?.kind?.const)).toEqual([
@@ -136,6 +142,14 @@ describe('ocm-manager plugin', () => {
expect(tool.description).toContain('when this session is open on desktop')
})
it('lists the show_artifact action in the description', async () => {
const tool = await loadTool(configHome)
expect(tool.description).toContain('show_artifact')
expect(tool.description).toContain('write a self-contained .html file with your file tools')
expect(tool.description).toContain('rendered inline in this session')
})
it('enforces the notification limits the internal API enforces', async () => {
const tool = await loadTool(configHome)
const notification = notificationParamsSchema(tool)
@@ -275,6 +289,49 @@ describe('ocm-manager plugin', () => {
expect(init.body).toBeUndefined()
})
it('resolves the artifact file through the internal API and reports the resolved path', async () => {
const fetchMock = jsonResponse({ path: '/workspace/repos/app/report.html' })
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
const result = await runToolResult(
tool,
{ action: 'show_artifact', params: { title: 'Formation odds', path: 'reports/report.html' } },
{ sessionID: 'ses_abc' },
)
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0] ?? []
expect(url).toBe('http://localhost:5003/api/internal/session-artifacts/ses_abc/resolve')
expect(init.method).toBe('POST')
expect(init.headers.Authorization).toBe('Bearer secret-token')
expect(init.headers['content-type']).toBe('application/json')
expect(JSON.parse(init.body)).toEqual({ path: 'reports/report.html' })
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).toEqual({ path: '/workspace/repos/app/report.html' })
})
it('surfaces the resolve error when the artifact path is rejected', async () => {
vi.stubGlobal('fetch', jsonResponse({ error: 'Artifact file not found: reports/report.html' }, { ok: false, status: 404 }))
const tool = await loadTool(configHome)
await expect(
runTool(tool, { action: 'show_artifact', params: { title: 'Formation odds', path: 'reports/report.html' } }, { sessionID: 'ses_abc' }),
).rejects.toThrow(/404.*Artifact file not found: reports\/report\.html/)
})
it('rejects a show_artifact call missing path without calling the API', async () => {
const fetchMock = jsonResponse({})
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
await expect(runTool(tool, { action: 'show_artifact', params: { title: 'Formation odds' } }, { sessionID: 'ses_abc' }))
.rejects.toThrow('Invalid parameters for OpenCode Manager action: show_artifact. Missing required parameter: path.')
expect(fetchMock).not.toHaveBeenCalled()
})
it('sends an allow-listed GET request with a query string and no body', async () => {
const fetchMock = jsonResponse({ userId: 'default', theme: 'dark' })
vi.stubGlobal('fetch', fetchMock)
@@ -608,7 +665,7 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-manager plugin against the s
expect(managerTool?.function?.parameters).toMatchObject({
type: 'object',
properties: {
action: { type: 'string', enum: ['send_notification', 'request', 'open_walkthrough'] },
action: { type: 'string', enum: ['send_notification', 'request', 'open_walkthrough', 'show_artifact'] },
params: {
anyOf: [
{
@@ -638,6 +695,14 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-manager plugin against the s
source: expect.anything(),
},
},
{
type: 'object',
required: ['title', 'path'],
properties: {
title: { type: 'string', minLength: 1, maxLength: 120 },
path: { type: 'string', minLength: 1, maxLength: 1000 },
},
},
],
},
},
@@ -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()
@@ -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>
)
})
@@ -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
@@ -340,6 +340,83 @@ 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 } }))
})
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', () => {
@@ -2,6 +2,7 @@ import { memo } from 'react'
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
@@ -40,12 +43,14 @@ 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}
messageID={messageID}
directory={directory}
repoFullPath={repoFullPath}
repoLocalPath={repoLocalPath}
shellOutcome={shellOutcome}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
@@ -24,6 +24,7 @@ import { CopyButton } from '@/components/ui/copy-button'
import { InlineImage } from '@/components/ui/inline-image'
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'
@@ -51,6 +52,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,
@@ -64,7 +71,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':
@@ -333,6 +340,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
@@ -354,6 +363,8 @@ const MessageRow = memo(function MessageRow({
handleCancelEdit,
sessionID,
directory,
repoFullPath,
repoLocalPath,
onFileClick,
onChildSessionClick,
onOpenWalkthrough,
@@ -462,6 +473,8 @@ const MessageRow = memo(function MessageRow({
part={part}
messageID={message.id}
directory={directory}
repoFullPath={repoFullPath}
repoLocalPath={repoLocalPath}
shellOutcome={shellOutcomeFor(part)}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
@@ -506,6 +519,8 @@ const MessageRow = memo(function MessageRow({
parts={item.parts}
messageID={message.id}
directory={directory}
repoFullPath={repoFullPath}
repoLocalPath={repoLocalPath}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
onOpenWalkthrough={onOpenWalkthrough}
@@ -515,6 +530,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}
@@ -582,6 +599,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
@@ -595,6 +614,8 @@ interface MessageThreadProps {
export const MessageThread = memo(function MessageThread({
sessionID,
directory,
repoFullPath,
repoLocalPath,
messages,
pending,
onFileClick,
@@ -665,6 +686,8 @@ export const MessageThread = memo(function MessageThread({
handleCancelEdit={handleCancelEdit}
sessionID={sessionID}
directory={directory}
repoFullPath={repoFullPath}
repoLocalPath={repoLocalPath}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
onOpenWalkthrough={onOpenWalkthrough}
@@ -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,143 @@ 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, metadata?: Record<string, string>): 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' }],
metadata,
},
})
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('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 } })
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()
})
})
@@ -28,6 +28,10 @@ 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'
const DISPLAY_LIMIT = 30_000
@@ -61,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
@@ -117,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'
@@ -251,6 +257,16 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
</Badge>
) : null
const artifact = readShowArtifactCall(part)
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) {
const status = part.state.status
const isRunning = status !== 'streaming' && isRunningLifecycle(subagentStatus)
+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
@@ -70,6 +70,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
@@ -55,9 +55,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}
+28 -1
View File
@@ -5,7 +5,34 @@ export const MANAGER_TOOL_NAME = 'ocm'
export const MANAGER_TOOL_OPEN_WALKTHROUGH_ACTION = 'open_walkthrough'
export const MANAGER_TOOL_ACTIONS = ['send_notification', 'request', MANAGER_TOOL_OPEN_WALKTHROUGH_ACTION] as const
export const MANAGER_TOOL_SHOW_ARTIFACT_ACTION = 'show_artifact'
export const MANAGER_TOOL_ACTIONS = [
'send_notification',
'request',
MANAGER_TOOL_OPEN_WALKTHROUGH_ACTION,
MANAGER_TOOL_SHOW_ARTIFACT_ACTION,
] as const
export const ARTIFACT_LIMITS = {
TITLE_MAX: 120,
FILE_MAX_BYTES: 5 * 1024 * 1024,
} as const
export const ShowArtifactParamsSchema = z
.object({
title: z.string().min(1).max(ARTIFACT_LIMITS.TITLE_MAX).describe('A short title shown above the artifact.'),
path: z
.string()
.min(1)
.max(1000)
.describe(
'Path of a self-contained .html file the agent wrote, relative to the session directory or absolute inside it. Inline your own CSS and JavaScript; libraries may load from public CDNs.',
),
})
.strict()
export type ShowArtifactParams = z.infer<typeof ShowArtifactParamsSchema>
export const AssistantNotificationPrioritySchema = z.enum(['normal', 'high'])