From 23702f191411a32e55c0fcf97de0ebc72a6fdf6f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 23 Jul 2026 01:42:33 +0200 Subject: [PATCH] Render saved screenshots and recordings in chat markdown - Add secure asset access for workspace media and browser artifacts - Support saving preview screenshots and embedding playable recordings --- apps/server/src/assets/AssetAccess.test.ts | 68 +++++++ apps/server/src/assets/AssetAccess.ts | 97 ++++++++-- apps/server/src/config.ts | 9 + apps/server/src/mcp/McpHttpServer.test.ts | 132 +++++++++++++- apps/server/src/mcp/McpHttpServer.ts | 13 ++ .../src/mcp/toolkits/preview/handlers.ts | 116 +++++++++++- apps/server/src/mcp/toolkits/preview/tools.ts | 23 ++- apps/web/src/components/ChatMarkdown.tsx | 17 ++ .../web/src/components/chat/MarkdownMedia.tsx | 166 ++++++++++++++++++ packages/contracts/src/assets.ts | 18 +- packages/contracts/src/previewAutomation.ts | 33 ++++ packages/shared/src/filePreview.ts | 14 +- 12 files changed, 682 insertions(+), 24 deletions(-) create mode 100644 apps/web/src/components/chat/MarkdownMedia.tsx diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 42fd3f900e..8350ace7f1 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -70,6 +70,74 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(testLayer)), ); + it.effect("issues exact-file workspace URLs for video files", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-asset-video-", + }); + const videoPath = path.join(root, "recordings", "demo.webm"); + yield* fileSystem.makeDirectory(path.join(root, "recordings"), { recursive: true }); + yield* fileSystem.writeFileString(videoPath, "webm-bytes"); + const canonicalVideoPath = yield* fileSystem.realPath(videoPath); + + const result = yield* issueAssetUrl({ + resource: { + _tag: "workspace-file", + threadId: ThreadId.make("thread-1"), + path: "recordings/demo.webm", + }, + workspaceRoot: root, + }); + const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const separatorIndex = suffix.indexOf("/"); + const token = suffix.slice(0, separatorIndex); + + expect(yield* resolveAsset(token, "demo.webm")).toEqual({ + kind: "file", + path: canonicalVideoPath, + }); + // Exact-file claim: the token must not grant access to sibling files. + expect(yield* resolveAsset(token, "other.webm")).toBeNull(); + }).pipe(Effect.provide(testLayer)), + ); + + it.effect("issues and resolves browser artifact URLs by file name only", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const config = yield* ServerConfig.ServerConfig; + yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true }); + const artifactPath = path.join(config.browserArtifactsDir, "browser-recording-demo.webm"); + yield* fileSystem.writeFileString(artifactPath, "webm-bytes"); + yield* fileSystem.writeFileString( + path.join(config.browserArtifactsDir, "notes.txt"), + "not media", + ); + + const result = yield* issueAssetUrl({ + resource: { _tag: "browser-artifact", fileName: "browser-recording-demo.webm" }, + }); + const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const token = suffix.slice(0, suffix.indexOf("/")); + expect(yield* resolveAsset(token, "browser-recording-demo.webm")).toEqual({ + kind: "file", + path: artifactPath, + }); + + // Non-media files and traversal-style names are not issuable. + const nonMedia = yield* issueAssetUrl({ + resource: { _tag: "browser-artifact", fileName: "notes.txt" }, + }).pipe(Effect.flip); + expect(nonMedia._tag).toBe("AssetBrowserArtifactNotFoundError"); + const traversal = yield* issueAssetUrl({ + resource: { _tag: "browser-artifact", fileName: "../state.sqlite" }, + }).pipe(Effect.flip); + expect(traversal._tag).toBe("AssetBrowserArtifactNotFoundError"); + }).pipe(Effect.provide(testLayer)), + ); + it.effect("rejects workspace files outside the authorized root", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index b469e0e315..476250cfbf 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -1,6 +1,7 @@ import type { AssetResource } from "@t3tools/contracts"; import { AssetAttachmentNotFoundError, + AssetBrowserArtifactNotFoundError, AssetPreviewTypeValidationError, AssetProjectFaviconInspectionError, AssetProjectFaviconNotFoundError, @@ -16,8 +17,10 @@ import { import { isWorkspaceImagePreviewPath, isWorkspacePreviewEntryPath, + isWorkspaceVideoPreviewPath, WORKSPACE_BROWSER_PREVIEW_EXTENSIONS, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS, + WORKSPACE_VIDEO_PREVIEW_EXTENSIONS, } from "@t3tools/shared/filePreview"; import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon"; import * as Clock from "effect/Clock"; @@ -47,6 +50,7 @@ const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000; const PREVIEW_ASSET_EXTENSIONS = new Set([ ...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS, ...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS, + ...WORKSPACE_VIDEO_PREVIEW_EXTENSIONS, ".css", ".js", ".mjs", @@ -77,6 +81,12 @@ const AssetClaimsSchema = Schema.Union([ attachmentId: Schema.String, expiresAt: Schema.Number, }), + Schema.Struct({ + version: Schema.Literal(1), + kind: Schema.Literal("browser-artifact"), + fileName: Schema.String, + expiresAt: Schema.Number, + }), Schema.Struct({ version: Schema.Literal(1), kind: Schema.Literal("project-favicon"), @@ -120,6 +130,30 @@ const optionOnNotFound = ( }), ); +function normalizeBrowserArtifactFileName(fileName: string): string | null { + const trimmed = fileName.trim(); + if ( + trimmed.length === 0 || + trimmed.includes("/") || + trimmed.includes("\\") || + trimmed.includes("\0") || + trimmed.startsWith(".") + ) { + return null; + } + if (!isWorkspaceImagePreviewPath(trimmed) && !isWorkspaceVideoPreviewPath(trimmed)) { + return null; + } + return trimmed; +} + +const statIsFile = (path: string) => + FileSystem.FileSystem.pipe( + Effect.flatMap((fileSystem) => optionOnNotFound(fileSystem.stat(path))), + Effect.map((info) => Option.isSome(info) && info.value.type === "File"), + Effect.orElseSucceed(() => false), + ); + const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")( function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) { const fileSystem = yield* FileSystem.FileSystem; @@ -234,21 +268,23 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i }), ), ); - claims = isWorkspaceImagePreviewPath(resolved.relativePath) - ? { - version: 1, - kind: "workspace-file-exact", - workspaceRoot: canonicalWorkspaceRoot, - relativePath: resolved.relativePath, - expiresAt, - } - : { - version: 1, - kind: "workspace-file", - workspaceRoot: canonicalWorkspaceRoot, - baseRelativePath: path.dirname(resolved.relativePath), - expiresAt, - }; + claims = + isWorkspaceImagePreviewPath(resolved.relativePath) || + isWorkspaceVideoPreviewPath(resolved.relativePath) + ? { + version: 1, + kind: "workspace-file-exact", + workspaceRoot: canonicalWorkspaceRoot, + relativePath: resolved.relativePath, + expiresAt, + } + : { + version: 1, + kind: "workspace-file", + workspaceRoot: canonicalWorkspaceRoot, + baseRelativePath: path.dirname(resolved.relativePath), + expiresAt, + }; fileName = path.basename(resolved.relativePath); break; } @@ -272,6 +308,26 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i fileName = path.basename(attachmentPath); break; } + case "browser-artifact": { + const config = yield* ServerConfig.ServerConfig; + const artifactFileName = normalizeBrowserArtifactFileName(input.resource.fileName); + const artifactPath = artifactFileName + ? path.join(config.browserArtifactsDir, artifactFileName) + : null; + if (!artifactFileName || !artifactPath || !(yield* statIsFile(artifactPath))) { + return yield* new AssetBrowserArtifactNotFoundError({ + resource: input.resource, + }); + } + claims = { + version: 1, + kind: "browser-artifact", + fileName: artifactFileName, + expiresAt, + }; + fileName = artifactFileName; + break; + } case "project-favicon": { const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe( Effect.mapError( @@ -388,6 +444,17 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* ( : null; } + if (claims.kind === "browser-artifact") { + const config = yield* ServerConfig.ServerConfig; + const artifactFileName = normalizeBrowserArtifactFileName(claims.fileName); + if (!artifactFileName) return null; + const path = yield* Path.Path; + const artifactPath = path.join(config.browserArtifactsDir, artifactFileName); + return (yield* statIsFile(artifactPath)) + ? ({ kind: "file", path: artifactPath } satisfies ResolvedAsset) + : null; + } + if (claims.kind === "project-favicon") { if (claims.relativePath === null) return null; const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({ diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index e678264dde..49039c160e 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -33,6 +33,12 @@ export interface ServerDerivedPaths { readonly providerStatusCacheDir: string; readonly worktreesDir: string; readonly attachmentsDir: string; + /** + * Browser evidence artifacts (screenshots/recordings). The desktop app + * writes recordings here too — both derive `/(dev|userdata)`, so + * in the standard local setup this is the same directory. + */ + readonly browserArtifactsDir: string; readonly logsDir: string; readonly serverLogPath: string; readonly serverTracePath: string; @@ -108,6 +114,7 @@ export const deriveServerPaths = Effect.fn(function* ( ); const dbPath = join(stateDir, "state.sqlite"); const attachmentsDir = join(stateDir, "attachments"); + const browserArtifactsDir = join(stateDir, "browser-artifacts"); const logsDir = join(stateDir, "logs"); const providerLogsDir = join(logsDir, "provider"); const providerStatusCacheDir = join(baseDir, "caches"); @@ -119,6 +126,7 @@ export const deriveServerPaths = Effect.fn(function* ( providerStatusCacheDir, worktreesDir: join(baseDir, "worktrees"), attachmentsDir, + browserArtifactsDir, logsDir, serverLogPath: join(logsDir, "server.log"), serverTracePath: join(logsDir, "server.trace.ndjson"), @@ -143,6 +151,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }), fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }), fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.browserArtifactsDir, { recursive: true }), fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }), fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }), fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }), diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index e1cdf992f0..8f86497cad 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -1,13 +1,28 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + import { expect, it } from "@effect/vitest"; import { NodeHttpServer } from "@effect/platform-node"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import { + EnvironmentId, + PreviewTabId, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; import { McpSchema, McpServer } from "effect/unstable/ai"; import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http"; +import * as ServerConfig from "../config.ts"; +import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import * as McpHttpServer from "./McpHttpServer.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts"; @@ -16,6 +31,7 @@ const environmentId = EnvironmentId.make("environment-mcp-test"); const threadId = ThreadId.make("thread-mcp-test"); const tabId = PreviewTabId.make("tab-mcp-test"); const alternateTabId = PreviewTabId.make("tab-mcp-alternate"); +const testWorkspaceRoot = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "mcp-snapshot-test-")); const invocation = { environmentId, threadId, @@ -33,9 +49,44 @@ const client = McpSchema.McpServerClient.of({ }, getClient: Effect.die("unused"), }); +const stubProjectionSnapshotQueryLayer = Layer.succeed( + ProjectionSnapshotQuery.ProjectionSnapshotQuery, + { + getCommandReadModel: () => Effect.die("unused"), + getSnapshot: () => Effect.die("unused"), + getShellSnapshot: () => Effect.die("unused"), + getArchivedShellSnapshot: () => Effect.die("unused"), + getSnapshotSequence: () => Effect.die("unused"), + getCounts: () => Effect.die("unused"), + getActiveProjectByWorkspaceRoot: () => Effect.die("unused"), + getProjectShellById: () => Effect.die("unused"), + getFirstActiveThreadIdByProjectId: () => Effect.die("unused"), + getThreadCheckpointContext: (contextThreadId) => + Effect.succeed( + contextThreadId === threadId + ? Option.some({ + threadId, + projectId: ProjectId.make("project-mcp-test"), + workspaceRoot: testWorkspaceRoot, + worktreePath: null, + checkpoints: [], + }) + : Option.none(), + ), + getFullThreadDiffContext: () => Effect.die("unused"), + getThreadShellById: () => Effect.die("unused"), + getThreadDetailById: () => Effect.die("unused"), + getThreadDetailSnapshot: () => Effect.die("unused"), + }, +); + const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe( Layer.provideMerge(McpServer.McpServer.layer), Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))), + Layer.provideMerge(stubProjectionSnapshotQueryLayer), + Layer.provideMerge(WorkspacePaths.layer), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-test-" })), + Layer.provideMerge(NodeServices.layer), ); it("normalizes empty successful notification responses to accepted", () => { @@ -269,3 +320,82 @@ it.effect("registers annotated tools and preserves authenticated request context }), ).pipe(Effect.provide(TestLayer)), ); + +it.effect("writes snapshot screenshots into the workspace when savePath is set", () => + Effect.scoped( + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker; + const events = yield* broker.connect({ + clientId: "mcp-save-client", + environmentId, + }); + yield* Stream.runForEach(events, (event) => + event.type === "connected" + ? Effect.void + : broker.respond({ + clientId: "mcp-save-client", + connectionId: event.connectionId, + requestId: event.request.requestId, + ok: true, + result: { + url: "http://example.test/", + title: "Example", + loading: false, + visibleText: "Example", + interactiveElements: [], + accessibilityTree: {}, + consoleEntries: [], + networkEntries: [], + actionTimeline: [], + screenshot: { + mimeType: "image/png", + data: Buffer.from("png-bytes").toString("base64"), + width: 10, + height: 5, + }, + }, + }), + ).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + + const callSnapshot = (savePath: string) => + server + .callTool({ name: "preview_snapshot", arguments: { savePath } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), + Effect.provideService(McpSchema.McpServerClient, client), + ); + + const saved = yield* callSnapshot("evidence/login.png"); + expect(saved.isError).toBe(false); + expect(saved.structuredContent).toMatchObject({ + savedScreenshotPath: "evidence/login.png", + }); + expect( + NodeFS.readFileSync(NodePath.join(testWorkspaceRoot, "evidence/login.png"), "utf8"), + ).toBe("png-bytes"); + + const wrongExtension = yield* callSnapshot("evidence/login.txt"); + expect(wrongExtension.isError).toBe(true); + + const traversal = yield* callSnapshot("../outside.png"); + expect(traversal.isError).toBe(true); + expect(NodeFS.existsSync(NodePath.join(testWorkspaceRoot, "..", "outside.png"))).toBe(false); + + const savedArtifact = yield* server + .callTool({ name: "preview_snapshot", arguments: { save: true } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect(savedArtifact.isError).toBe(false); + const artifactPath = (savedArtifact.structuredContent as { savedScreenshotPath?: string }) + .savedScreenshotPath; + const config = yield* ServerConfig.ServerConfig; + expect(artifactPath).toBeDefined(); + expect(NodePath.dirname(artifactPath!)).toBe(config.browserArtifactsDir); + expect(NodeFS.readFileSync(artifactPath!, "utf8")).toBe("png-bytes"); + }), + ).pipe(Effect.provide(TestLayer)), +); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 3ead607489..fbd050f6ee 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -1,8 +1,10 @@ import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import type * as Types from "effect/Types"; @@ -10,6 +12,9 @@ import { McpSchema, McpServer, Tool } from "effect/unstable/ai"; import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; import packageJson from "../../package.json" with { type: "json" }; +import * as ServerConfig from "../config.ts"; +import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpSessionRegistry from "./McpSessionRegistry.ts"; import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts"; @@ -130,6 +135,13 @@ const previewSnapshotFailure = (cause: Cause.Cause) => { const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () { const server = yield* McpServer.McpServer; const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker; + const snapshotHandlerContext = yield* Effect.context< + | ServerConfig.ServerConfig + | ProjectionSnapshotQuery.ProjectionSnapshotQuery + | WorkspacePaths.WorkspacePaths + | FileSystem.FileSystem + | Path.Path + >(); const built = yield* PreviewSnapshotToolkit; const tool = PreviewSnapshotTool; yield* server.addTool({ @@ -161,6 +173,7 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot Effect.flatMap(Effect.fromOption), Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker), Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), + Effect.provideContext(snapshotHandlerContext), Effect.matchCauseEffect({ onFailure: previewSnapshotFailure, onSuccess: ({ encodedResult }) => { diff --git a/apps/server/src/mcp/toolkits/preview/handlers.ts b/apps/server/src/mcp/toolkits/preview/handlers.ts index 1c7ff6f9cd..b4f316ad04 100644 --- a/apps/server/src/mcp/toolkits/preview/handlers.ts +++ b/apps/server/src/mcp/toolkits/preview/handlers.ts @@ -1,4 +1,8 @@ +import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import type { PreviewAutomationOperation, PreviewAutomationOpenInput, @@ -10,7 +14,11 @@ import type { PreviewAutomationStatus, PreviewTabId, } from "@t3tools/contracts"; +import { PreviewAutomationScreenshotSaveError } from "@t3tools/contracts"; +import * as ServerConfig from "../../../config.ts"; +import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts"; +import * as WorkspacePaths from "../../../workspace/WorkspacePaths.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts"; import { PreviewSnapshotToolkit, PreviewStandardToolkit, PreviewToolkit } from "./tools.ts"; @@ -60,6 +68,90 @@ const invokeTargeted = ( return invoke(operation, operationInput, timeoutMs, tabId); }; +const writeScreenshotFile = (input: { + readonly absolutePath: string; + readonly screenshotBase64: string; +}) => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem.makeDirectory(path.dirname(input.absolutePath), { recursive: true }); + yield* fileSystem.writeFile( + input.absolutePath, + new Uint8Array(Buffer.from(input.screenshotBase64, "base64")), + ); + }); + +const saveSnapshotScreenshotArtifact = Effect.fn("PreviewToolkit.saveSnapshotScreenshotArtifact")( + function* (input: { + readonly scope: McpInvocationContext.McpInvocationScope; + readonly screenshotBase64: string; + }) { + const config = yield* ServerConfig.ServerConfig; + const fileName = `browser-screenshot-${(yield* Clock.currentTimeMillis).toString(36)}.png`; + const path = yield* Path.Path; + const absolutePath = path.join(config.browserArtifactsDir, fileName); + yield* writeScreenshotFile({ absolutePath, screenshotBase64: input.screenshotBase64 }).pipe( + Effect.mapError( + () => + new PreviewAutomationScreenshotSaveError({ + operation: "snapshot", + environmentId: input.scope.environmentId, + threadId: input.scope.threadId, + providerSessionId: input.scope.providerSessionId, + providerInstanceId: input.scope.providerInstanceId, + savePath: fileName, + reason: "failed to write the screenshot artifact", + }), + ), + ); + return absolutePath; + }, +); + +const saveSnapshotScreenshot = Effect.fn("PreviewToolkit.saveSnapshotScreenshot")( + function* (input: { + readonly scope: McpInvocationContext.McpInvocationScope; + readonly savePath: string; + readonly screenshotBase64: string; + }) { + const { savePath, scope } = input; + const fail = (reason: string) => + new PreviewAutomationScreenshotSaveError({ + operation: "snapshot", + environmentId: scope.environmentId, + threadId: scope.threadId, + providerSessionId: scope.providerSessionId, + providerInstanceId: scope.providerInstanceId, + savePath, + reason, + }); + if (!savePath.toLowerCase().endsWith(".png")) { + return yield* fail("savePath must end with .png"); + } + + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; + const threadContext = yield* projectionSnapshotQuery + .getThreadCheckpointContext(scope.threadId) + .pipe(Effect.mapError(() => fail("failed to resolve the thread workspace"))); + if (Option.isNone(threadContext)) { + return yield* fail("thread was not found"); + } + const workspaceRoot = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot; + + const workspacePaths = yield* WorkspacePaths.WorkspacePaths; + const resolved = yield* workspacePaths + .resolveRelativePathWithinRoot({ workspaceRoot, relativePath: savePath }) + .pipe(Effect.mapError(() => fail("savePath must be a relative path inside the workspace"))); + + yield* writeScreenshotFile({ + absolutePath: resolved.absolutePath, + screenshotBase64: input.screenshotBase64, + }).pipe(Effect.mapError(() => fail("failed to write the screenshot file"))); + return resolved.relativePath; + }, +); + const handlers = { preview_status: (input) => invokeTargeted("status", input ?? {}), preview_open: (input) => @@ -70,7 +162,29 @@ const handlers = { invokeTargeted("resize", input, input.timeoutMs), preview_set_appearance: (input) => invokeTargeted("setColorScheme", input), - preview_snapshot: (input) => invokeTargeted("snapshot", input ?? {}), + preview_snapshot: (input) => + Effect.gen(function* () { + const { save, savePath, ...target } = input ?? {}; + const snapshot = yield* invokeTargeted("snapshot", target); + if (savePath !== undefined) { + const scope = yield* McpInvocationContext.McpInvocationContext; + const savedScreenshotPath = yield* saveSnapshotScreenshot({ + scope, + savePath, + screenshotBase64: snapshot.screenshot.data, + }); + return { ...snapshot, savedScreenshotPath }; + } + if (save === true) { + const scope = yield* McpInvocationContext.McpInvocationContext; + const savedScreenshotPath = yield* saveSnapshotScreenshotArtifact({ + scope, + screenshotBase64: snapshot.screenshot.data, + }); + return { ...snapshot, savedScreenshotPath }; + } + return snapshot; + }), preview_click: (input) => invokeTargeted("click", input, input.timeoutMs).pipe(Effect.as(null)), preview_type: (input) => diff --git a/apps/server/src/mcp/toolkits/preview/tools.ts b/apps/server/src/mcp/toolkits/preview/tools.ts index a94d2b056f..6838c1ea64 100644 --- a/apps/server/src/mcp/toolkits/preview/tools.ts +++ b/apps/server/src/mcp/toolkits/preview/tools.ts @@ -13,14 +13,20 @@ import { PreviewAutomationSetColorSchemeInput, PreviewAutomationSetColorSchemeResult, PreviewAutomationSnapshot, + PreviewAutomationSnapshotInput, PreviewAutomationStatus, PreviewAutomationTabTargetInput, PreviewAutomationTypeInput, PreviewAutomationWaitForInput, } from "@t3tools/contracts"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import { Tool, Toolkit } from "effect/unstable/ai"; +import * as ServerConfig from "../../../config.ts"; +import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts"; +import * as WorkspacePaths from "../../../workspace/WorkspacePaths.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts"; @@ -29,6 +35,15 @@ const dependencies = [ PreviewAutomationBroker.PreviewAutomationBroker, ]; +const snapshotDependencies = [ + ...dependencies, + ServerConfig.ServerConfig, + ProjectionSnapshotQuery.ProjectionSnapshotQuery, + WorkspacePaths.WorkspacePaths, + FileSystem.FileSystem, + Path.Path, +]; + const browserTool = (tool: T): T => tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, true) as T; @@ -104,11 +119,11 @@ export const PreviewSetAppearanceTool = safeBrowserTool( export const PreviewSnapshotTool = readonlyBrowserTool( Tool.make("preview_snapshot", { description: - "Inspect a page before interacting. Pass tabId to inspect a specific tab; omit it to use this agent session's current tab. Returns page state, semantic elements, diagnostics, action history, and a PNG screenshot.", - parameters: PreviewAutomationTabTargetInput, + "Inspect a page before interacting. Pass tabId to inspect a specific tab; omit it to use this agent session's current tab. Returns page state, semantic elements, diagnostics, action history, and a PNG screenshot. To keep visual evidence for the human (before/after states of UI work), pass save:true — the result then includes savedScreenshotPath, which you embed in your final reply with markdown image syntax, e.g. ![after](). Use savePath only when the screenshot should live inside the repo.", + parameters: PreviewAutomationSnapshotInput, success: PreviewAutomationSnapshot, failure: PreviewAutomationError, - dependencies, + dependencies: snapshotDependencies, }).annotate(Tool.Title, "Inspect browser page"), ); @@ -192,7 +207,7 @@ export const PreviewRecordingStartTool = safeBrowserTool( export const PreviewRecordingStopTool = safeBrowserTool( Tool.make("preview_recording_stop", { description: - "Stop recording the collaborative browser tab selected by tabId, or this agent session's current tab when omitted, and save it as a local evidence artifact.", + "Stop recording the collaborative browser tab selected by tabId, or this agent session's current tab when omitted, and save it as a local evidence artifact (.webm). To show the recording to the human, embed the returned path directly in your final reply with markdown image syntax, e.g. ![demo]() — the chat renders it as a playable video.", parameters: PreviewAutomationTabTargetInput, success: PreviewAutomationRecordingArtifact, failure: PreviewAutomationError, diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index d86fe39a77..dfdfb58932 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -39,6 +39,7 @@ import rehypeRaw from "rehype-raw"; import rehypeSanitize, { defaultSchema } from "rehype-sanitize"; import remarkBreaks from "remark-breaks"; import remarkGfm from "remark-gfm"; +import { MarkdownMedia } from "./chat/MarkdownMedia"; import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText"; import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip"; import { PierreEntryIcon } from "./chat/PierreEntryIcon"; @@ -161,10 +162,12 @@ function findTaskListMarkerOffset(markdown: string, listItemStart: number): numb } const CHAT_MARKDOWN_SANITIZE_SCHEMA = { ...defaultSchema, + tagNames: [...(defaultSchema.tagNames ?? []), "video"], attributes: { ...defaultSchema.attributes, "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"), code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"], + video: ["src", "controls", "muted", "loop", "playsInline", "poster", "preload"], }, protocols: { ...defaultSchema.protocols, @@ -1584,6 +1587,20 @@ function ChatMarkdown({ ); }, + img({ node: _node, src, alt }) { + return ( + + ); + }, + video({ node: _node, src }) { + return ( + + ); + }, table({ node: _node, ...props }) { return ; }, diff --git a/apps/web/src/components/chat/MarkdownMedia.tsx b/apps/web/src/components/chat/MarkdownMedia.tsx new file mode 100644 index 0000000000..209cd1a3a7 --- /dev/null +++ b/apps/web/src/components/chat/MarkdownMedia.tsx @@ -0,0 +1,166 @@ +import { memo, useState } from "react"; +import { createPortal } from "react-dom"; +import type { AssetResource, ScopedThreadRef } from "@t3tools/contracts"; +import { isWorkspaceVideoPreviewPath } from "@t3tools/shared/filePreview"; + +import { useAssetUrlState } from "../../assets/assetUrls"; +import { ExpandedImageDialog } from "./ExpandedImageDialog"; + +/** Sources the browser can load directly without a signed workspace asset URL. */ +const DIRECT_MEDIA_SRC_PATTERN = /^(?:https?:|data:|blob:)/i; + +const MEDIA_FRAME_CLASS_NAME = + "my-2 block max-h-96 max-w-full rounded-lg border border-border/60 bg-background object-contain"; + +interface MarkdownMediaProps { + src: string | undefined; + alt?: string | undefined; + threadRef?: ScopedThreadRef | undefined; +} + +function safeDecode(value: string): string { + try { + return decodeURIComponent(value); + } catch { + return value; + } +} + +function mediaFileName(src: string): string { + const withoutQuery = src.split(/[?#]/, 1)[0] ?? src; + const basename = withoutQuery.slice(withoutQuery.lastIndexOf("/") + 1); + return basename.length > 0 ? safeDecode(basename) : safeDecode(withoutQuery); +} + +/** + * Browser evidence artifacts (screenshots/recordings from the embedded + * browser) are referenced by the absolute path the preview tools return, + * e.g. `/…/userdata/browser-artifacts/browser-recording-x.webm`. They are + * served by file name from the server's browser-artifacts directory. + */ +function browserArtifactFileName(src: string): string | null { + const withoutQuery = src.split(/[?#]/, 1)[0] ?? src; + const match = /[/\\]browser-artifacts[/\\]([^/\\]+)$/.exec(safeDecode(withoutQuery)); + return match?.[1] ?? null; +} + +function MediaUnavailable({ name }: { name: string }) { + return ( + + Media unavailable: + {name} + + ); +} + +function ResolvedMedia({ url, name, isVideo }: { url: string; name: string; isVideo: boolean }) { + const [expanded, setExpanded] = useState(false); + const [failedUrl, setFailedUrl] = useState(null); + + if (failedUrl === url) { + return ; + } + + if (isVideo) { + return ( +