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

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

No files matched your search

+2
View File
@@ -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',
}
})
}
+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,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,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) {
+69
View File
@@ -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<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 (!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
}