mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat(artifacts): render agent HTML files inline in the session chat
This commit is contained in:
1 parent
377e3c2784
commit
f7b2ffb865
17 files changed
+579
-10
No files matched your search
@@ -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',
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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<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('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)
|
||||
})
|
||||
})
|
||||
@@ -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 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { MessagePart } from './MessagePart'
|
||||
import { getFileApiUrl } from '@/api/files'
|
||||
import { applySessionEvent, emptySessionTranscript } from '@/lib/session-projection'
|
||||
import { promptSequence } from '@/test/fixtures/session-projection'
|
||||
import type {
|
||||
@@ -276,6 +277,55 @@ 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 } }))
|
||||
})
|
||||
})
|
||||
|
||||
describe('sandbox indicator', () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { memo } from 'react'
|
||||
import type { SessionMessageAssistant } from '@opencode-manager/shared/opencode'
|
||||
import { readShowArtifactCall, type SessionMessageAssistant } from '@opencode-manager/shared/opencode'
|
||||
import { TextPart } from './TextPart'
|
||||
import { ToolCallPart } from './ToolCallPart'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
@@ -40,7 +40,7 @@ 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}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { memo, useCallback, useMemo, useState } from 'react'
|
||||
import { Pencil, Loader2 } from 'lucide-react'
|
||||
import { assistantText, formatOpenCodeModelRef } from '@opencode-manager/shared/opencode'
|
||||
import { assistantText, formatOpenCodeModelRef, readShowArtifactCall } from '@opencode-manager/shared/opencode'
|
||||
import type {
|
||||
PromptAgentAttachment,
|
||||
PromptFileAttachment,
|
||||
@@ -50,6 +50,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,
|
||||
@@ -63,7 +69,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':
|
||||
|
||||
@@ -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,108 @@ 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): 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' }],
|
||||
},
|
||||
})
|
||||
|
||||
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('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()
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useRef, useEffect, useMemo, memo } from 'react'
|
||||
import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils'
|
||||
import { toolContentText, type SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
|
||||
import { readShowArtifactCall, 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 { getFileApiUrl } from '@/api/files'
|
||||
import { ArtifactPart } from './ArtifactPart'
|
||||
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
|
||||
|
||||
const DISPLAY_LIMIT = 30_000
|
||||
@@ -251,6 +253,14 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
|
||||
</Badge>
|
||||
) : null
|
||||
|
||||
const artifact = readShowArtifactCall(part)
|
||||
if (artifact && (artifact.path.startsWith('/') || directory)) {
|
||||
const fullPath = artifact.path.startsWith('/')
|
||||
? artifact.path
|
||||
: `${directory?.replace(/\/+$/, '')}/${artifact.path}`
|
||||
return <ArtifactPart title={artifact.title} path={artifact.path} src={getFileApiUrl(fullPath, { params: { raw: true } })} />
|
||||
}
|
||||
|
||||
if (isSubagent) {
|
||||
const status = part.state.status
|
||||
const isRunning = status !== 'streaming' && isRunningLifecycle(subagentStatus)
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { SessionMessageAssistantTool } from '@opencode/client'
|
||||
import { MANAGER_TOOL_NAME, MANAGER_TOOL_SHOW_ARTIFACT_ACTION, ShowArtifactParamsSchema } from '../schemas/internal-assistant'
|
||||
import type { ShowArtifactParams } from '../schemas/internal-assistant'
|
||||
|
||||
/**
|
||||
* Reads an assistant tool part as a completed `ocm` `show_artifact` call, or undefined for every
|
||||
* other tool, action, unfinished state, and set of parameters that does not validate.
|
||||
*/
|
||||
export function readShowArtifactCall(part: SessionMessageAssistantTool): ShowArtifactParams | undefined {
|
||||
if (part.name !== MANAGER_TOOL_NAME || part.state.status !== 'completed') return undefined
|
||||
if (part.state.input.action !== MANAGER_TOOL_SHOW_ARTIFACT_ACTION) return undefined
|
||||
const parsed = ShowArtifactParamsSchema.safeParse(part.state.input.params)
|
||||
return parsed.success ? parsed.data : undefined
|
||||
}
|
||||
@@ -48,6 +48,8 @@ export { ClientError, isIntegrationNotFoundError, isMcpServerNotFoundError, isSe
|
||||
|
||||
export { assistantText, sessionIDFromEvent, toolContentText } from './content'
|
||||
|
||||
export { readShowArtifactCall } from './artifact'
|
||||
|
||||
export { configModelRef, formatOpenCodeModelRef, parseOpenCodeModelRef, selectConfiguredModelRef } from './modelRef'
|
||||
|
||||
export {
|
||||
|
||||
@@ -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'])
|
||||
|
||||
|
||||
Reference in new issue
Block a user