diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 8f86497cad..4103774e18 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -383,6 +383,17 @@ it.effect("writes snapshot screenshots into the workspace when savePath is set", expect(traversal.isError).toBe(true); expect(NodeFS.existsSync(NodePath.join(testWorkspaceRoot, "..", "outside.png"))).toBe(false); + const bothDestinations = yield* server + .callTool({ + name: "preview_snapshot", + arguments: { save: true, savePath: "evidence/login.png" }, + }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect(bothDestinations.isError).toBe(true); + const savedArtifact = yield* server .callTool({ name: "preview_snapshot", arguments: { save: true } }) .pipe( diff --git a/apps/server/src/mcp/toolkits/preview/handlers.ts b/apps/server/src/mcp/toolkits/preview/handlers.ts index b4f316ad04..55d848671f 100644 --- a/apps/server/src/mcp/toolkits/preview/handlers.ts +++ b/apps/server/src/mcp/toolkits/preview/handlers.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeCrypto from "node:crypto"; + import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -88,12 +91,14 @@ const saveSnapshotScreenshotArtifact = Effect.fn("PreviewToolkit.saveSnapshotScr readonly screenshotBase64: string; }) { const config = yield* ServerConfig.ServerConfig; - const fileName = `browser-screenshot-${(yield* Clock.currentTimeMillis).toString(36)}.png`; + // Timestamp for ordering plus a random component so concurrent + // same-millisecond captures never overwrite each other. + const fileName = `browser-screenshot-${(yield* Clock.currentTimeMillis).toString(36)}-${NodeCrypto.randomUUID().slice(0, 8)}.png`; const path = yield* Path.Path; const absolutePath = path.join(config.browserArtifactsDir, fileName); yield* writeScreenshotFile({ absolutePath, screenshotBase64: input.screenshotBase64 }).pipe( Effect.mapError( - () => + (cause) => new PreviewAutomationScreenshotSaveError({ operation: "snapshot", environmentId: input.scope.environmentId, @@ -102,6 +107,7 @@ const saveSnapshotScreenshotArtifact = Effect.fn("PreviewToolkit.saveSnapshotScr providerInstanceId: input.scope.providerInstanceId, savePath: fileName, reason: "failed to write the screenshot artifact", + cause, }), ), ); @@ -116,7 +122,7 @@ const saveSnapshotScreenshot = Effect.fn("PreviewToolkit.saveSnapshotScreenshot" readonly screenshotBase64: string; }) { const { savePath, scope } = input; - const fail = (reason: string) => + const fail = (reason: string, cause?: unknown) => new PreviewAutomationScreenshotSaveError({ operation: "snapshot", environmentId: scope.environmentId, @@ -125,6 +131,7 @@ const saveSnapshotScreenshot = Effect.fn("PreviewToolkit.saveSnapshotScreenshot" providerInstanceId: scope.providerInstanceId, savePath, reason, + ...(cause === undefined ? {} : { cause }), }); if (!savePath.toLowerCase().endsWith(".png")) { return yield* fail("savePath must end with .png"); @@ -133,7 +140,7 @@ const saveSnapshotScreenshot = Effect.fn("PreviewToolkit.saveSnapshotScreenshot" const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; const threadContext = yield* projectionSnapshotQuery .getThreadCheckpointContext(scope.threadId) - .pipe(Effect.mapError(() => fail("failed to resolve the thread workspace"))); + .pipe(Effect.mapError((cause) => fail("failed to resolve the thread workspace", cause))); if (Option.isNone(threadContext)) { return yield* fail("thread was not found"); } @@ -142,12 +149,33 @@ const saveSnapshotScreenshot = Effect.fn("PreviewToolkit.saveSnapshotScreenshot" 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"))); + .pipe( + Effect.mapError((cause) => + fail("savePath must be a relative path inside the workspace", cause), + ), + ); + + // Lexical containment is not enough: a symlinked directory inside the + // workspace could point outside it. Create the parent, then verify its + // canonical location is still inside the canonical workspace root. + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem + .makeDirectory(path.dirname(resolved.absolutePath), { recursive: true }) + .pipe(Effect.mapError((cause) => fail("failed to create the save directory", cause))); + const [canonicalRoot, canonicalParent] = yield* Effect.all([ + fileSystem.realPath(workspaceRoot), + fileSystem.realPath(path.dirname(resolved.absolutePath)), + ]).pipe(Effect.mapError((cause) => fail("failed to resolve the save directory", cause))); + const canonicalRelative = path.relative(canonicalRoot, canonicalParent); + if (canonicalRelative.startsWith("..") || path.isAbsolute(canonicalRelative)) { + return yield* fail("savePath must stay inside the workspace root"); + } yield* writeScreenshotFile({ - absolutePath: resolved.absolutePath, + absolutePath: path.join(canonicalParent, path.basename(resolved.absolutePath)), screenshotBase64: input.screenshotBase64, - }).pipe(Effect.mapError(() => fail("failed to write the screenshot file"))); + }).pipe(Effect.mapError((cause) => fail("failed to write the screenshot file", cause))); return resolved.relativePath; }, ); diff --git a/apps/server/src/mcp/toolkits/preview/tools.ts b/apps/server/src/mcp/toolkits/preview/tools.ts index 6838c1ea64..518eedb7a4 100644 --- a/apps/server/src/mcp/toolkits/preview/tools.ts +++ b/apps/server/src/mcp/toolkits/preview/tools.ts @@ -207,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 (.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.", + "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. The recording is saved on the machine running the desktop app; if the server runs on a different machine the embed can show as unavailable — in that case copy the file into the workspace and embed the workspace-relative path instead.", parameters: PreviewAutomationTabTargetInput, success: PreviewAutomationRecordingArtifact, failure: PreviewAutomationError, diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index dfdfb58932..b6ed7c7ebd 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -190,8 +190,39 @@ const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [ remarkTagInlineCode, ] satisfies NonNullable; +interface HastNodeLike { + readonly type: string; + readonly tagName?: string; + properties?: Record; + children?: HastNodeLike[]; +} + +const WINDOWS_DRIVE_SRC_PATTERN = /^[A-Za-z]:[\\/]/; + +// rehype-sanitize parses a Windows drive path source such as "C:\shot.png" +// as an unknown "c:" protocol and strips it. Escape media sources to +// "/C:/…" before sanitization runs; MarkdownMedia unescapes when resolving. +function rehypeEscapeWindowsDriveMediaSrc() { + const escapeNode = (node: HastNodeLike): void => { + if ( + node.type === "element" && + (node.tagName === "img" || node.tagName === "video") && + node.properties && + typeof node.properties.src === "string" && + WINDOWS_DRIVE_SRC_PATTERN.test(node.properties.src) + ) { + node.properties.src = `/${node.properties.src}`; + } + for (const child of node.children ?? []) { + escapeNode(child); + } + }; + return escapeNode; +} + const CHAT_MARKDOWN_REHYPE_PLUGINS = [ rehypeRaw, + rehypeEscapeWindowsDriveMediaSrc, [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA], ] satisfies NonNullable; @@ -1598,7 +1629,11 @@ function ChatMarkdown({ }, video({ node: _node, src }) { return ( - + ); }, table({ node: _node, ...props }) { diff --git a/apps/web/src/components/chat/MarkdownMedia.tsx b/apps/web/src/components/chat/MarkdownMedia.tsx index 209cd1a3a7..f9aba64ac7 100644 --- a/apps/web/src/components/chat/MarkdownMedia.tsx +++ b/apps/web/src/components/chat/MarkdownMedia.tsx @@ -7,7 +7,13 @@ 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 DIRECT_MEDIA_SRC_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i; + +/** `markdownUrlTransform` escapes Windows drive paths as `/C:/…` so they survive sanitization. */ +const ESCAPED_WINDOWS_DRIVE_PATH_PATTERN = /^\/[A-Za-z]:[\\/]/; + +/** Paths that are absolute on either platform (after Windows-drive unescaping). */ +const ABSOLUTE_PATH_PATTERN = /^(?:[/\\]|[A-Za-z]:[\\/])/; const MEDIA_FRAME_CLASS_NAME = "my-2 block max-h-96 max-w-full rounded-lg border border-border/60 bg-background object-contain"; @@ -16,6 +22,8 @@ interface MarkdownMediaProps { src: string | undefined; alt?: string | undefined; threadRef?: ScopedThreadRef | undefined; + /** Force the media kind; when omitted it is inferred from the file extension. */ + kind?: "image" | "video" | undefined; } function safeDecode(value: string): string { @@ -32,15 +40,31 @@ function mediaFileName(src: string): string { return basename.length > 0 ? safeDecode(basename) : safeDecode(withoutQuery); } +/** + * Normalize a non-direct markdown src into a filesystem-style path: strip + * query/fragment, decode percent escapes, and unescape the `/C:/…` form the + * markdown URL transform uses to carry Windows drive paths through + * sanitization. + */ +function mediaPathFromSrc(src: string): string { + const withoutQuery = src.split(/[?#]/, 1)[0] ?? src; + const decoded = safeDecode(withoutQuery); + return ESCAPED_WINDOWS_DRIVE_PATH_PATTERN.test(decoded) ? decoded.slice(1) : decoded; +} + /** * 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. + * served by file name from the server's browser-artifacts directory. Only + * absolute paths qualify — a workspace-relative path like + * `docs/browser-artifacts/x.png` is an ordinary repo file. */ -function browserArtifactFileName(src: string): string | null { - const withoutQuery = src.split(/[?#]/, 1)[0] ?? src; - const match = /[/\\]browser-artifacts[/\\]([^/\\]+)$/.exec(safeDecode(withoutQuery)); +function browserArtifactFileName(path: string): string | null { + if (!ABSOLUTE_PATH_PATTERN.test(path)) { + return null; + } + const match = /[/\\]browser-artifacts[/\\]([^/\\]+)$/.exec(path); return match?.[1] ?? null; } @@ -142,25 +166,27 @@ export const MarkdownMedia = memo(function MarkdownMedia({ src, alt, threadRef, + kind, }: MarkdownMediaProps) { if (!src) { return null; } const name = alt && alt.trim().length > 0 ? alt.trim() : mediaFileName(src); - const isVideo = isWorkspaceVideoPreviewPath(src); + const isVideo = kind === "video" || (kind === undefined && isWorkspaceVideoPreviewPath(src)); if (DIRECT_MEDIA_SRC_PATTERN.test(src)) { return ; } if (!threadRef) { return ; } - const artifactFileName = browserArtifactFileName(src); + const path = mediaPathFromSrc(src); + const artifactFileName = browserArtifactFileName(path); const resource: AssetResource = artifactFileName ? { _tag: "browser-artifact", fileName: artifactFileName } : { _tag: "workspace-file", threadId: threadRef.threadId, - path: safeDecode(src.startsWith("./") ? src.slice(2) : src), + path: path.startsWith("./") ? path.slice(2) : path, }; return ; }); diff --git a/packages/contracts/src/previewAutomation.ts b/packages/contracts/src/previewAutomation.ts index b4d0375ecb..d11dd2a76e 100644 --- a/packages/contracts/src/previewAutomation.ts +++ b/packages/contracts/src/previewAutomation.ts @@ -66,21 +66,29 @@ const PreviewAutomationTabTargetFields = { export const PreviewAutomationTabTargetInput = Schema.Struct(PreviewAutomationTabTargetFields); export type PreviewAutomationTabTargetInput = typeof PreviewAutomationTabTargetInput.Type; +const SNAPSHOT_SAVE_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]()) so the human sees the screenshot in chat. Preferred for before/after evidence of UI work. Cannot be combined with savePath."; + +const SNAPSHOT_SAVE_PATH_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 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]()) so the human sees the screenshot in chat. Preferred for before/after evidence of UI work.", - }), - ), + Schema.Boolean.annotate({ description: SNAPSHOT_SAVE_DESCRIPTION }), + ).annotate({ description: SNAPSHOT_SAVE_DESCRIPTION }), 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).", + description: SNAPSHOT_SAVE_PATH_DESCRIPTION, }), + ).annotate({ description: SNAPSHOT_SAVE_PATH_DESCRIPTION }), +}).check( + Schema.makeFilter( + (input) => + !(input.save === true && input.savePath !== undefined) || + "save cannot be combined with savePath; choose one destination.", ), -}); +); export type PreviewAutomationSnapshotInput = typeof PreviewAutomationSnapshotInput.Type; export const PreviewAutomationStatus = Schema.Struct({ @@ -886,6 +894,7 @@ export class PreviewAutomationScreenshotSaveError extends Schema.TaggedErrorClas ...PreviewAutomationScopeErrorFields, savePath: TrimmedNonEmptyString, reason: Schema.String, + cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string {