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
This commit is contained in:
Julius Marminge authored and Gabriel De Andrade committed 2026-07-29 21:58:12 -04:00
1 parent 35a684000d
commit 23702f1914
12 files changed
+682 -24

No files matched your search

@@ -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;
+82 -15
View File
@@ -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 = <A, R>(
}),
);
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({
+9
View File
@@ -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 `<baseDir>/(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 }),
+131 -1
View File
@@ -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)),
);
+13
View File
@@ -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 = <E>(cause: Cause.Cause<E>) => {
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 }) => {
@@ -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 = <A>(
return invoke<A>(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<PreviewAutomationStatus>("status", input ?? {}),
preview_open: (input) =>
@@ -70,7 +162,29 @@ const handlers = {
invokeTargeted<PreviewAutomationResizeResult>("resize", input, input.timeoutMs),
preview_set_appearance: (input) =>
invokeTargeted<PreviewAutomationSetColorSchemeResult>("setColorScheme", input),
preview_snapshot: (input) => invokeTargeted<PreviewAutomationSnapshot>("snapshot", input ?? {}),
preview_snapshot: (input) =>
Effect.gen(function* () {
const { save, savePath, ...target } = input ?? {};
const snapshot = yield* invokeTargeted<PreviewAutomationSnapshot>("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<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
preview_type: (input) =>
+19 -4
View File
@@ -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 = <T extends Tool.Any>(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](<savedScreenshotPath>). 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](<path>) — the chat renders it as a playable video.",
parameters: PreviewAutomationTabTargetInput,
success: PreviewAutomationRecordingArtifact,
failure: PreviewAutomationError,
+17
View File
@@ -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({
</code>
);
},
img({ node: _node, src, alt }) {
return (
<MarkdownMedia
src={typeof src === "string" ? src : undefined}
alt={alt}
threadRef={threadRef}
/>
);
},
video({ node: _node, src }) {
return (
<MarkdownMedia src={typeof src === "string" ? src : undefined} threadRef={threadRef} />
);
},
table({ node: _node, ...props }) {
return <MarkdownTable {...props} />;
},
@@ -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 (
<span className="my-1 inline-flex max-w-full items-baseline gap-1 rounded-md border border-border/60 bg-muted/40 px-2 py-1 text-xs text-muted-foreground">
Media unavailable:
<span className="truncate font-mono">{name}</span>
</span>
);
}
function ResolvedMedia({ url, name, isVideo }: { url: string; name: string; isVideo: boolean }) {
const [expanded, setExpanded] = useState(false);
const [failedUrl, setFailedUrl] = useState<string | null>(null);
if (failedUrl === url) {
return <MediaUnavailable name={name} />;
}
if (isVideo) {
return (
<video
src={url}
controls
playsInline
preload="metadata"
aria-label={name}
className={MEDIA_FRAME_CLASS_NAME}
onError={() => setFailedUrl(url)}
/>
);
}
return (
<>
<button
type="button"
className="block max-w-full cursor-zoom-in"
aria-label={`Expand image ${name}`}
onClick={() => setExpanded(true)}
>
<img
src={url}
alt={name}
loading="lazy"
className={MEDIA_FRAME_CLASS_NAME}
onError={() => setFailedUrl(url)}
/>
</button>
{expanded &&
// Portal to the body: message rows create containing blocks that would
// otherwise trap the fixed-position dialog inside the chat scroller.
createPortal(
<ExpandedImageDialog
preview={{ images: [{ src: url, name }], index: 0 }}
onClose={() => setExpanded(false)}
/>,
document.body,
)}
</>
);
}
function ResourceMedia({
threadRef,
resource,
name,
isVideo,
}: {
threadRef: ScopedThreadRef;
resource: AssetResource;
name: string;
isVideo: boolean;
}) {
const assetUrl = useAssetUrlState(threadRef.environmentId, resource);
if (assetUrl._tag === "Failure") {
return <MediaUnavailable name={name} />;
}
if (assetUrl._tag === "Loading") {
return (
<span className="my-2 flex h-24 w-56 max-w-full animate-pulse items-center justify-center rounded-lg border border-border/40 bg-muted/30 px-2 text-xs text-muted-foreground">
<span className="truncate">{name}</span>
</span>
);
}
return <ResolvedMedia url={assetUrl.url} name={name} isVideo={isVideo} />;
}
/**
* Renders markdown-referenced media (images and videos) in chat messages.
*
* Workspace-relative sources are resolved to signed asset URLs for the
* thread's worktree, so agents can save screenshots/recordings into the
* workspace and embed them with plain markdown image syntax.
*/
export const MarkdownMedia = memo(function MarkdownMedia({
src,
alt,
threadRef,
}: MarkdownMediaProps) {
if (!src) {
return null;
}
const name = alt && alt.trim().length > 0 ? alt.trim() : mediaFileName(src);
const isVideo = isWorkspaceVideoPreviewPath(src);
if (DIRECT_MEDIA_SRC_PATTERN.test(src)) {
return <ResolvedMedia url={src} name={name} isVideo={isVideo} />;
}
if (!threadRef) {
return <MediaUnavailable name={name} />;
}
const artifactFileName = browserArtifactFileName(src);
const resource: AssetResource = artifactFileName
? { _tag: "browser-artifact", fileName: artifactFileName }
: {
_tag: "workspace-file",
threadId: threadRef.threadId,
path: safeDecode(src.startsWith("./") ? src.slice(2) : src),
};
return <ResourceMedia threadRef={threadRef} resource={resource} name={name} isVideo={isVideo} />;
});
+17 -1
View File
@@ -12,6 +12,10 @@ export const AssetResource = Schema.Union([
Schema.TaggedStruct("attachment", {
attachmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),
}),
/** A file in the server's browser-artifacts directory (screenshots/recordings). */
Schema.TaggedStruct("browser-artifact", {
fileName: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),
}),
Schema.TaggedStruct("project-favicon", {
cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
}),
@@ -83,7 +87,7 @@ export class AssetPreviewTypeValidationError extends Schema.TaggedErrorClass<Ass
},
) {
override get message(): string {
return "Only browser documents and images can be previewed.";
return "Only browser documents, images, and videos can be previewed.";
}
}
@@ -133,6 +137,17 @@ export class AssetAttachmentNotFoundError extends Schema.TaggedErrorClass<AssetA
}
}
export class AssetBrowserArtifactNotFoundError extends Schema.TaggedErrorClass<AssetBrowserArtifactNotFoundError>()(
"AssetBrowserArtifactNotFoundError",
{
resource: AssetResource,
},
) {
override get message(): string {
return "Browser artifact was not found.";
}
}
export class AssetProjectFaviconResolutionError extends Schema.TaggedErrorClass<AssetProjectFaviconResolutionError>()(
"AssetProjectFaviconResolutionError",
{
@@ -190,6 +205,7 @@ export const AssetAccessError = Schema.Union([
AssetWorkspaceAssetNotFoundError,
AssetWorkspaceResolutionError,
AssetAttachmentNotFoundError,
AssetBrowserArtifactNotFoundError,
AssetProjectFaviconResolutionError,
AssetProjectFaviconInspectionError,
AssetProjectFaviconNotFoundError,
@@ -66,6 +66,23 @@ const PreviewAutomationTabTargetFields = {
export const PreviewAutomationTabTargetInput = Schema.Struct(PreviewAutomationTabTargetFields);
export type PreviewAutomationTabTargetInput = typeof PreviewAutomationTabTargetInput.Type;
export const PreviewAutomationSnapshotInput = Schema.Struct({
...PreviewAutomationTabTargetFields,
save: Schema.optional(
Schema.Boolean.annotate({
description:
"When true, the screenshot is persisted as a browser evidence artifact outside the workspace and the result includes savedScreenshotPath. Embed that exact path in your final reply with markdown image syntax (e.g. ![after](<savedScreenshotPath>)) so the human sees the screenshot in chat. Preferred for before/after evidence of UI work.",
}),
),
savePath: Schema.optional(
TrimmedNonEmptyString.check(Schema.isMaxLength(512)).annotate({
description:
"Optional workspace-relative file path ending in .png. Use only when the screenshot should live inside the repo (e.g. committed docs or fixtures); prefer save:true for chat evidence. The file is written into the thread workspace and can be embedded with markdown image syntax, e.g. ![login page](screenshots/login.png).",
}),
),
});
export type PreviewAutomationSnapshotInput = typeof PreviewAutomationSnapshotInput.Type;
export const PreviewAutomationStatus = Schema.Struct({
available: Schema.Boolean,
visible: Schema.Boolean,
@@ -548,6 +565,8 @@ export const PreviewAutomationSnapshot = Schema.Struct({
width: Schema.Int,
height: Schema.Int,
}),
/** Workspace-relative path the screenshot was also written to, when savePath was requested. */
savedScreenshotPath: Schema.optional(Schema.String),
});
export type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;
@@ -861,6 +880,19 @@ export class PreviewAutomationMalformedResponseError extends Schema.TaggedErrorC
}
}
export class PreviewAutomationScreenshotSaveError extends Schema.TaggedErrorClass<PreviewAutomationScreenshotSaveError>()(
"PreviewAutomationScreenshotSaveError",
{
...PreviewAutomationScopeErrorFields,
savePath: TrimmedNonEmptyString,
reason: Schema.String,
},
) {
override get message(): string {
return `Failed to save the preview screenshot to ${this.savePath}: ${this.reason}`;
}
}
export const PreviewAutomationError = Schema.Union([
PreviewAutomationUnavailableError,
PreviewAutomationNoAvailableHostError,
@@ -876,6 +908,7 @@ export const PreviewAutomationError = Schema.Union([
PreviewAutomationRequestQueueClosedError,
PreviewAutomationRemoteUnavailableError,
PreviewAutomationMalformedResponseError,
PreviewAutomationScreenshotSaveError,
]);
export type PreviewAutomationError = typeof PreviewAutomationError.Type;
+12 -2
View File
@@ -11,6 +11,8 @@ export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [
".webp",
] as const;
export const WORKSPACE_VIDEO_PREVIEW_EXTENSIONS = [".m4v", ".mov", ".mp4", ".webm"] as const;
function hasPreviewExtension(path: string, extensions: ReadonlyArray<string>): boolean {
const pathWithoutQuery = path.split(/[?#]/, 1)[0]?.toLowerCase() ?? "";
return extensions.some((extension) => pathWithoutQuery.endsWith(extension));
@@ -24,6 +26,14 @@ export function isWorkspaceImagePreviewPath(path: string): boolean {
return hasPreviewExtension(path, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS);
}
export function isWorkspacePreviewEntryPath(path: string): boolean {
return isWorkspaceBrowserPreviewPath(path) || isWorkspaceImagePreviewPath(path);
export function isWorkspaceVideoPreviewPath(path: string): boolean {
return hasPreviewExtension(path, WORKSPACE_VIDEO_PREVIEW_EXTENSIONS);
}
export function isWorkspacePreviewEntryPath(path: string): boolean {
return (
isWorkspaceBrowserPreviewPath(path) ||
isWorkspaceImagePreviewPath(path) ||
isWorkspaceVideoPreviewPath(path)
);
}