Address review feedback on chat media rendering
- Preserve error causes in screenshot save failures - Reject save+savePath combinations and describe both schema fields - Verify canonical (symlink-resolved) containment before workspace writes - Add collision-resistant suffix to artifact screenshot names - Fix Windows drive paths, protocol-relative URLs, query strings, and extensionless video sources in markdown media resolution - Only treat absolute browser-artifacts paths as server artifacts Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
44dd6f67f6
commit
ad9e4fa446
6 files changed
+134
-25
No files matched your search
@@ -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(
|
||||
|
||||
@@ -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;
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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.  — 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.  — 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,
|
||||
|
||||
@@ -190,8 +190,39 @@ const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
|
||||
remarkTagInlineCode,
|
||||
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
|
||||
|
||||
interface HastNodeLike {
|
||||
readonly type: string;
|
||||
readonly tagName?: string;
|
||||
properties?: Record<string, unknown>;
|
||||
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<ReactMarkdownOptions["rehypePlugins"]>;
|
||||
|
||||
@@ -1598,7 +1629,11 @@ function ChatMarkdown({
|
||||
},
|
||||
video({ node: _node, src }) {
|
||||
return (
|
||||
<MarkdownMedia src={typeof src === "string" ? src : undefined} threadRef={threadRef} />
|
||||
<MarkdownMedia
|
||||
src={typeof src === "string" ? src : undefined}
|
||||
threadRef={threadRef}
|
||||
kind="video"
|
||||
/>
|
||||
);
|
||||
},
|
||||
table({ node: _node, ...props }) {
|
||||
|
||||
@@ -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 <ResolvedMedia url={src} name={name} isVideo={isVideo} />;
|
||||
}
|
||||
if (!threadRef) {
|
||||
return <MediaUnavailable name={name} />;
|
||||
}
|
||||
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 <ResourceMedia threadRef={threadRef} resource={resource} name={name} isVideo={isVideo} />;
|
||||
});
|
||||
@@ -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. ) 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. .";
|
||||
|
||||
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. ) 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. .",
|
||||
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 {
|
||||
|
||||
Reference in new issue
Block a user