From 5e2452172c9e923fc01e481283946ff0face1fc1 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Mon, 12 Oct 2026 09:13:47 -0400 Subject: [PATCH] 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 --- backend/src/routes/files.ts | 50 ++++++++-- backend/src/routes/opencode-proxy.ts | 2 +- backend/src/services/files.ts | 33 +++++++ .../services/opencode-manager-tool-plugin.ts | 11 ++- backend/src/services/sandbox/command.ts | 6 +- backend/src/services/sandbox/shell-shim.ts | 3 +- backend/src/services/session-artifacts.ts | 16 ++-- backend/src/utils/fs-safe.ts | 5 + backend/test/routes/files.test.ts | 94 ++++++++++++++++++- .../routes/internal-session-artifacts.test.ts | 40 +++++++- backend/test/services/files.test.ts | 35 +++++++ .../opencode-manager-tool-plugin.test.ts | 2 +- backend/test/services/sandbox/command.test.ts | 2 +- .../components/message/ExplorationGroup.tsx | 2 + .../components/message/MessagePart.test.tsx | 28 ++++++ .../src/components/message/MessagePart.tsx | 9 +- .../src/components/message/MessageThread.tsx | 19 +++- .../components/message/ToolCallPart.test.tsx | 37 +++++++- .../src/components/message/ToolCallPart.tsx | 20 ++-- frontend/src/lib/artifactTool.test.ts | 81 ++++++++++++++++ frontend/src/lib/artifactTool.ts | 25 +++++ frontend/src/lib/markdownLinks.test.ts | 6 ++ frontend/src/lib/markdownLinks.ts | 3 +- frontend/src/pages/SessionDetail.tsx | 2 + shared/src/opencode/artifact.ts | 14 --- shared/src/opencode/index.ts | 2 - 26 files changed, 489 insertions(+), 58 deletions(-) create mode 100644 frontend/src/lib/artifactTool.test.ts create mode 100644 frontend/src/lib/artifactTool.ts delete mode 100644 shared/src/opencode/artifact.ts diff --git a/backend/src/routes/files.ts b/backend/src/routes/files.ts index 47028b33..1815cbb9 100644 --- a/backend/src/routes/files.ts +++ b/backend/src/routes/files.ts @@ -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, { diff --git a/backend/src/routes/opencode-proxy.ts b/backend/src/routes/opencode-proxy.ts index fe2ae637..d3be10b5 100644 --- a/backend/src/routes/opencode-proxy.ts +++ b/backend/src/routes/opencode-proxy.ts @@ -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, diff --git a/backend/src/services/files.ts b/backend/src/services/files.ts index bfa13007..6f711ba2 100644 --- a/backend/src/services/files.ts +++ b/backend/src/services/files.ts @@ -40,6 +40,12 @@ interface FileUploadResult { mimeType: string } +export interface RawFileMetadata { + size: number + mimeType: AllowedMimeType + lastModified: Date +} + export async function getRawFileContent(userPath: string): Promise { 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 { } } +export async function getRawFileMetadata(userPath: string): Promise { + 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 { 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 = { '.txt': 'text/plain', '.html': 'text/html', + '.htm': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.ts': 'text/typescript', diff --git a/backend/src/services/opencode-manager-tool-plugin.ts b/backend/src/services/opencode-manager-tool-plugin.ts index 45fa1e01..ecbc4d61 100644 --- a/backend/src/services/opencode-manager-tool-plugin.ts +++ b/backend/src/services/opencode-manager-tool-plugin.ts @@ -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 } }, }) }) diff --git a/backend/src/services/sandbox/command.ts b/backend/src/services/sandbox/command.ts index 4913c2c4..5923c78b 100644 --- a/backend/src/services/sandbox/command.ts +++ b/backend/src/services/sandbox/command.ts @@ -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 diff --git a/backend/src/services/sandbox/shell-shim.ts b/backend/src/services/sandbox/shell-shim.ts index 9170a132..afa3a01b 100644 --- a/backend/src/services/sandbox/shell-shim.ts +++ b/backend/src/services/sandbox/shell-shim.ts @@ -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, diff --git a/backend/src/services/session-artifacts.ts b/backend/src/services/session-artifacts.ts index 7e1a8269..12a80af2 100644 --- a/backend/src/services/session-artifacts.ts +++ b/backend/src/services/session-artifacts.ts @@ -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 } diff --git a/backend/src/utils/fs-safe.ts b/backend/src/utils/fs-safe.ts index 1e70c180..c6193a75 100644 --- a/backend/src/utils/fs-safe.ts +++ b/backend/src/utils/fs-safe.ts @@ -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 { const dir = path.dirname(filePath) await mkdirSafe(dir) diff --git a/backend/test/routes/files.test.ts b/backend/test/routes/files.test.ts index 427d697b..27c0daba 100644 --- a/backend/test/routes/files.test.ts +++ b/backend/test/routes/files.test.ts @@ -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 +const getRawFileContent = fileService.getRawFileContent as MockedFunction +const getRawFileMetadata = fileService.getRawFileMetadata as MockedFunction const getFileRange = fileService.getFileRange as MockedFunction const uploadFile = fileService.uploadFile as MockedFunction const createFileOrFolder = fileService.createFileOrFolder as MockedFunction @@ -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('

hi

\n\n')) + getRawFileMetadata.mockResolvedValue({ size: 13, mimeType: 'text/html', lastModified: rawLastModified }) + getRawFileContent.mockResolvedValue(Buffer.from('

hi

\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('

hi

\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('

hi

\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('

hi

\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 () => { diff --git a/backend/test/routes/internal-session-artifacts.test.ts b/backend/test/routes/internal-session-artifacts.test.ts index 2da4fb98..fd366d47 100644 --- a/backend/test/routes/internal-session-artifacts.test.ts +++ b/backend/test/routes/internal-session-artifacts.test.ts @@ -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'), '

Report

') + 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, '

Outside

') + 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' }) diff --git a/backend/test/services/files.test.ts b/backend/test/services/files.test.ts index 3f118e1e..5797672f 100644 --- a/backend/test/services/files.test.ts +++ b/backend/test/services/files.test.ts @@ -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`, '

hi

') + + 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`, '

hi

') + + 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) diff --git a/backend/test/services/opencode-manager-tool-plugin.test.ts b/backend/test/services/opencode-manager-tool-plugin.test.ts index f4f9d720..c091f64d 100644 --- a/backend/test/services/opencode-manager-tool-plugin.test.ts +++ b/backend/test/services/opencode-manager-tool-plugin.test.ts @@ -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 () => { diff --git a/backend/test/services/sandbox/command.test.ts b/backend/test/services/sandbox/command.test.ts index 04608556..f8ab84f8 100644 --- a/backend/test/services/sandbox/command.test.ts +++ b/backend/test/services/sandbox/command.test.ts @@ -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() diff --git a/frontend/src/components/message/ExplorationGroup.tsx b/frontend/src/components/message/ExplorationGroup.tsx index 4920e73e..c6688604 100644 --- a/frontend/src/components/message/ExplorationGroup.tsx +++ b/frontend/src/components/message/ExplorationGroup.tsx @@ -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 diff --git a/frontend/src/components/message/MessagePart.test.tsx b/frontend/src/components/message/MessagePart.test.tsx index e1aa75a4..df1da2fa 100644 --- a/frontend/src/components/message/MessagePart.test.tsx +++ b/frontend/src/components/message/MessagePart.test.tsx @@ -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( + , + ) + + 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', () => { diff --git a/frontend/src/components/message/MessagePart.tsx b/frontend/src/components/message/MessagePart.tsx index b5b6d5ec..f68a7b74 100644 --- a/frontend/src/components/message/MessagePart.tsx +++ b/frontend/src/components/message/MessagePart.tsx @@ -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} diff --git a/frontend/src/components/message/MessageThread.tsx b/frontend/src/components/message/MessageThread.tsx index eea6e806..fd34c902 100644 --- a/frontend/src/components/message/MessageThread.tsx +++ b/frontend/src/components/message/MessageThread.tsx @@ -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} diff --git a/frontend/src/components/message/ToolCallPart.test.tsx b/frontend/src/components/message/ToolCallPart.test.tsx index 9f4e0165..d24ffaf9 100644 --- a/frontend/src/components/message/ToolCallPart.test.tsx +++ b/frontend/src/components/message/ToolCallPart.test.tsx @@ -395,7 +395,7 @@ describe('ToolCallPart show artifact action', () => { mocks.useToolCallPermission.mockReturnValue(null) }) - const showArtifact = (params: unknown): SessionMessageAssistantTool => ({ + const showArtifact = (params: unknown, metadata?: Record): 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( + , + ) + + 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( + , + ) + + 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 } }) diff --git a/frontend/src/components/message/ToolCallPart.tsx b/frontend/src/components/message/ToolCallPart.tsx index b2b185da..0cdc5196 100644 --- a/frontend/src/components/message/ToolCallPart.tsx +++ b/frontend/src/components/message/ToolCallPart.tsx @@ -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
{parts}
} -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 + if (artifact && (artifact.resolvedPath || artifact.path.startsWith('/') || directory)) { + const servedPath = getWorkspaceFilePath(artifact.resolvedPath ?? artifact.path, { + directory, + repoFullPath, + repoLocalPath, + }) + return } if (isSubagent) { diff --git a/frontend/src/lib/artifactTool.test.ts b/frontend/src/lib/artifactTool.test.ts new file mode 100644 index 00000000..a2e782a9 --- /dev/null +++ b/frontend/src/lib/artifactTool.test.ts @@ -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() + }) +}) diff --git a/frontend/src/lib/artifactTool.ts b/frontend/src/lib/artifactTool.ts new file mode 100644 index 00000000..93d36baf --- /dev/null +++ b/frontend/src/lib/artifactTool.ts @@ -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, + } +} diff --git a/frontend/src/lib/markdownLinks.test.ts b/frontend/src/lib/markdownLinks.test.ts index 99764104..0b374a33 100644 --- a/frontend/src/lib/markdownLinks.test.ts +++ b/frontend/src/lib/markdownLinks.test.ts @@ -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', () => { diff --git a/frontend/src/lib/markdownLinks.ts b/frontend/src/lib/markdownLinks.ts index fd3474be..3d93994a 100644 --- a/frontend/src/lib/markdownLinks.ts +++ b/frontend/src/lib/markdownLinks.ts @@ -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 diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index c32f9745..4ec7aeb0 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -743,6 +743,8 @@ export function SessionDetail() {