From f7b2ffb865292a0ad643c15752c45655c58b3f9d Mon Sep 17 00:00:00 2001 From: Chris Scott <> Date: Mon, 12 Oct 2026 00:45:06 +0000 Subject: [PATCH] feat(artifacts): render agent HTML files inline in the session chat --- backend/src/routes/files.ts | 2 + backend/src/routes/internal/index.ts | 2 + .../src/routes/internal/session-artifacts.ts | 31 +++++ .../services/opencode-manager-tool-plugin.ts | 15 ++- backend/src/services/session-artifacts.ts | 69 +++++++++++ backend/test/routes/files.test.ts | 2 + .../routes/internal-session-artifacts.test.ts | 110 ++++++++++++++++++ .../opencode-manager-tool-plugin.test.ts | 71 ++++++++++- .../src/components/message/ArtifactPart.tsx | 60 ++++++++++ .../components/message/MessagePart.test.tsx | 50 ++++++++ .../src/components/message/MessagePart.tsx | 4 +- .../src/components/message/MessageThread.tsx | 10 +- .../components/message/ToolCallPart.test.tsx | 106 +++++++++++++++++ .../src/components/message/ToolCallPart.tsx | 12 +- shared/src/opencode/artifact.ts | 14 +++ shared/src/opencode/index.ts | 2 + shared/src/schemas/internal-assistant.ts | 29 ++++- 17 files changed, 579 insertions(+), 10 deletions(-) create mode 100644 backend/src/routes/internal/session-artifacts.ts create mode 100644 backend/src/services/session-artifacts.ts create mode 100644 backend/test/routes/internal-session-artifacts.test.ts create mode 100644 frontend/src/components/message/ArtifactPart.tsx create mode 100644 shared/src/opencode/artifact.ts diff --git a/backend/src/routes/files.ts b/backend/src/routes/files.ts index c8be1056..47028b33 100644 --- a/backend/src/routes/files.ts +++ b/backend/src/routes/files.ts @@ -121,6 +121,8 @@ export function createFileRoutes() { 'Content-Type': result.mimeType || 'application/octet-stream', 'Content-Length': result.size.toString(), 'Content-Security-Policy': 'sandbox allow-scripts', + 'Cache-Control': 'no-cache', + 'X-Content-Type-Options': 'nosniff', } }) } diff --git a/backend/src/routes/internal/index.ts b/backend/src/routes/internal/index.ts index b664ef95..126579b4 100644 --- a/backend/src/routes/internal/index.ts +++ b/backend/src/routes/internal/index.ts @@ -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 diff --git a/backend/src/routes/internal/session-artifacts.ts b/backend/src/routes/internal/session-artifacts.ts new file mode 100644 index 00000000..c00483ad --- /dev/null +++ b/backend/src/routes/internal/session-artifacts.ts @@ -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 +} diff --git a/backend/src/services/opencode-manager-tool-plugin.ts b/backend/src/services/opencode-manager-tool-plugin.ts index 50b7e382..45fa1e01 100644 --- a/backend/src/services/opencode-manager-tool-plugin.ts +++ b/backend/src/services/opencode-manager-tool-plugin.ts @@ -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 { 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,16 @@ 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 '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.' + }, + }, } function assertParams(actionName, params) { diff --git a/backend/src/services/session-artifacts.ts b/backend/src/services/session-artifacts.ts new file mode 100644 index 00000000..7e1a8269 --- /dev/null +++ b/backend/src/services/session-artifacts.ts @@ -0,0 +1,69 @@ +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' + +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' + } +} + +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. + */ +export async function resolveSessionArtifactFile( + openCodeClient: OpenCodeClient, + sessionId: string, + artifactPath: string, +): Promise { + 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 (!isInsideDirectory(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 realFile +} diff --git a/backend/test/routes/files.test.ts b/backend/test/routes/files.test.ts index fedfcfa4..427d697b 100644 --- a/backend/test/routes/files.test.ts +++ b/backend/test/routes/files.test.ts @@ -175,6 +175,8 @@ describe('File Routes', () => { 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') }) 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 new file mode 100644 index 00000000..2da4fb98 --- /dev/null +++ b/backend/test/routes/internal-session-artifacts.test.ts @@ -0,0 +1,110 @@ +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 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 = {}) { + 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, '

Report

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

Report

') + + const res = await resolve({ path: filePath }) + + expect(res.status).toBe(200) + await expect(res.json()).resolves.toEqual({ path: filePath }) + }) + + 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'), '

Outside

') + + 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) + }) +}) diff --git a/backend/test/services/opencode-manager-tool-plugin.test.ts b/backend/test/services/opencode-manager-tool-plugin.test.ts index e826cbca..f4f9d720 100644 --- a/backend/test/services/opencode-manager-tool-plugin.test.ts +++ b/backend/test/services/opencode-manager-tool-plugin.test.ts @@ -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).toBeUndefined() + }) + + 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 }, + }, + }, ], }, }, diff --git a/frontend/src/components/message/ArtifactPart.tsx b/frontend/src/components/message/ArtifactPart.tsx new file mode 100644 index 00000000..11e45ad7 --- /dev/null +++ b/frontend/src/components/message/ArtifactPart.tsx @@ -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 ( +
+
+ +
+ {title} + {path && ( + + {path} + + )} +
+ + +
+