From 084f6c7a8cd6afe2feeb1852d7e6c63e073db256 Mon Sep 17 00:00:00 2001 From: Gabriel De Andrade <30420087+gabrielelpidio@users.noreply.github.com> Date: Thu, 30 Jul 2026 17:12:44 -0400 Subject: [PATCH] feat(chat): preview agent media on web and mobile --- apps/mobile/modules/t3-markdown-text/index.ts | 2 + .../src/NativeMarkdownBlock.ios.tsx | 20 +- .../src/SelectableMarkdownText.ios.tsx | 67 +++-- .../src/SelectableMarkdownText.types.ts | 11 + .../src/features/threads/MarkdownMedia.tsx | 233 +++++++++++++++ .../src/features/threads/ThreadFeed.tsx | 126 +++++++- apps/mobile/src/lib/threadActivity.test.ts | 23 ++ apps/mobile/src/lib/threadActivity.ts | 27 ++ .../src/native/SelectableMarkdownText.ios.tsx | 1 + .../src/native/SelectableMarkdownText.tsx | 1 + apps/mobile/src/state/assets.ts | 27 +- apps/server/src/assets/AssetAccess.test.ts | 157 +++++++++- apps/server/src/assets/AssetAccess.ts | 281 ++++++++++++++++-- .../server/src/assets/ThreadImagePath.test.ts | 48 +++ apps/server/src/assets/ThreadImagePath.ts | 14 + apps/server/src/config.ts | 1 + apps/server/src/http.ts | 17 +- apps/server/src/mcp/McpHttpServer.test.ts | 138 ++++++++- apps/server/src/mcp/McpHttpServer.ts | 15 + apps/server/src/mcp/OrchestratorMcpService.ts | 2 + .../src/mcp/toolkits/preview/handlers.ts | 225 +++++++++++++- apps/server/src/mcp/toolkits/preview/tools.ts | 27 +- apps/server/src/noFollowFile.test.ts | 31 ++ apps/server/src/noFollowFile.ts | 146 +++++++++ .../Adapters/CodexAdapterV2.test.ts | 42 +++ .../Adapters/CodexAdapterV2.ts | 111 +++++++ apps/server/src/ws.ts | 27 ++ apps/web/src/components/ChatMarkdown.tsx | 49 +++ .../web/src/components/chat/MarkdownMedia.tsx | 132 ++++++++ .../components/chat/MessagesTimeline.logic.ts | 23 ++ .../src/components/chat/MessagesTimeline.tsx | 52 ++++ apps/web/src/session-logic.test.ts | 58 ++++ apps/web/src/session-logic.ts | 21 ++ packages/contracts/src/assets.ts | 50 +++- packages/contracts/src/orchestrationV2.ts | 12 + packages/contracts/src/previewAutomation.ts | 58 ++++ packages/shared/src/filePreview.test.ts | 69 +++++ packages/shared/src/filePreview.ts | 78 ++++- 38 files changed, 2341 insertions(+), 81 deletions(-) create mode 100644 apps/mobile/src/features/threads/MarkdownMedia.tsx create mode 100644 apps/server/src/assets/ThreadImagePath.test.ts create mode 100644 apps/server/src/assets/ThreadImagePath.ts create mode 100644 apps/server/src/noFollowFile.test.ts create mode 100644 apps/server/src/noFollowFile.ts create mode 100644 apps/web/src/components/chat/MarkdownMedia.tsx diff --git a/apps/mobile/modules/t3-markdown-text/index.ts b/apps/mobile/modules/t3-markdown-text/index.ts index 89bce5395c..17fb433655 100644 --- a/apps/mobile/modules/t3-markdown-text/index.ts +++ b/apps/mobile/modules/t3-markdown-text/index.ts @@ -21,6 +21,8 @@ export { type MarkdownHighlightedToken, } from "./src/SelectableMarkdownText"; export type { + MarkdownImagePresentation, + MarkdownImageRenderer, NativeMarkdownTextStyle, SelectableMarkdownSkill, SelectableMarkdownTextProps, diff --git a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx index e6a045b3cd..8e9b4b2787 100644 --- a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx +++ b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { createContext, useContext, useEffect, useState } from "react"; import { Image, ScrollView, Text, useColorScheme, View } from "react-native"; import type { MarkdownNode } from "react-native-nitro-markdown/headless"; @@ -13,9 +13,14 @@ import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios import type { MarkdownCodeHighlighter, MarkdownHighlightedToken, + MarkdownImageRenderer, NativeMarkdownTextStyle, } from "./SelectableMarkdownText.types"; +export const MarkdownImageRendererContext = createContext( + undefined, +); + type HighlightedCode = ReadonlyArray>; const highlightedCodeCache = new Map(); @@ -379,6 +384,7 @@ function NativeMarkdownImage(props: { readonly textStyle: NativeMarkdownTextStyle; readonly onLinkPress?: (href: string) => void; }) { + const renderImage = useContext(MarkdownImageRendererContext); const href = props.node.href; if (!href) { return ( @@ -390,6 +396,18 @@ function NativeMarkdownImage(props: { ); } + if (renderImage) { + return ( + <> + {renderImage({ + href, + ...(props.node.alt ? { alt: props.node.alt } : {}), + ...(props.node.title ? { title: props.node.title } : {}), + })} + + ); + } + return ( - {chunks.map((chunk, index) => { - const content = - chunk.kind === "rich" ? ( - - ) : ( - - ); + + {/* A percentage width here creates a cyclic intrinsic measurement inside + shrink-to-fit containers such as user-message bubbles. Yoga then gives + the native text node an unbounded second pass and the parent only clips + the resulting single-line width instead of reflowing it. */} + + {chunks.map((chunk, index) => { + const content = + chunk.kind === "rich" ? ( + + ) : ( + + ); - return ( - - {content} - - ); - })} - + return ( + + {content} + + ); + })} + + ); } diff --git a/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts b/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts index 42cc3cd6fb..defebde68f 100644 --- a/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts +++ b/apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts @@ -1,3 +1,5 @@ +import type { ReactNode } from "react"; + export interface NativeMarkdownTextStyle { readonly color: string; readonly strongColor: string; @@ -36,6 +38,14 @@ export interface SelectableMarkdownSkill { readonly displayName?: string | null; } +export interface MarkdownImagePresentation { + readonly href: string; + readonly alt?: string; + readonly title?: string; +} + +export type MarkdownImageRenderer = (image: MarkdownImagePresentation) => ReactNode; + export interface SelectableMarkdownTextProps { readonly markdown: string; readonly textStyle: NativeMarkdownTextStyle; @@ -43,6 +53,7 @@ export interface SelectableMarkdownTextProps { readonly skills?: ReadonlyArray; readonly preserveSoftBreaks?: boolean; readonly onLinkPress?: (href: string) => void; + readonly renderImage?: MarkdownImageRenderer; readonly marginTop?: number; readonly marginBottom?: number; } diff --git a/apps/mobile/src/features/threads/MarkdownMedia.tsx b/apps/mobile/src/features/threads/MarkdownMedia.tsx new file mode 100644 index 0000000000..619d98d27f --- /dev/null +++ b/apps/mobile/src/features/threads/MarkdownMedia.tsx @@ -0,0 +1,233 @@ +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { + isWorkspaceVideoPreviewPath, + markdownMediaFileName, + resolveMarkdownMediaSource, +} from "@t3tools/shared/filePreview"; +import { useMemo, useState } from "react"; +import { ActivityIndicator, Image, Pressable, Text, type ColorValue, View } from "react-native"; +import { WebView } from "react-native-webview"; + +import { useAssetUrlState } from "../../state/assets"; + +interface MarkdownMediaProps { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly src: string; + readonly alt?: string; + readonly title?: string; + readonly backgroundColor: ColorValue; + readonly mutedColor: ColorValue; + readonly onPressImage: (uri: string) => void; +} + +function normalizeDirectUrl(url: string): string { + return url.startsWith("//") ? `https:${url}` : url; +} + +function escapeHtmlAttribute(value: string): string { + return value + .replaceAll("&", "&") + .replaceAll('"', """) + .replaceAll("<", "<") + .replaceAll(">", ">"); +} + +function MediaUnavailable(props: { readonly name: string; readonly color: ColorValue }) { + return ( + + + Media unavailable: {props.name} + + + ); +} + +function LoadingMedia(props: { + readonly name: string; + readonly backgroundColor: ColorValue; + readonly color: ColorValue; +}) { + return ( + + + + {props.name} + + + ); +} + +function MarkdownVideo(props: { + readonly url: string; + readonly name: string; + readonly backgroundColor: ColorValue; + readonly color: ColorValue; + readonly onError: () => void; +}) { + const html = useMemo(() => { + const url = escapeHtmlAttribute(props.url); + const name = escapeHtmlAttribute(props.name); + return ` + + + + + + + + + +`; + }, [props.name, props.url]); + + return ( + + + { + if (event.nativeEvent.data === "media-error") { + props.onError(); + } + }} + originWhitelist={["*"]} + scrollEnabled={false} + source={{ html }} + style={{ flex: 1, backgroundColor: "#000000" }} + /> + + + {props.name} + + + ); +} + +function ResolvedMedia(props: { + readonly url: string; + readonly name: string; + readonly isVideo: boolean; + readonly backgroundColor: ColorValue; + readonly color: ColorValue; + readonly onPressImage: (uri: string) => void; +}) { + const [failedUrl, setFailedUrl] = useState(null); + const [measuredImage, setMeasuredImage] = useState<{ + readonly url: string; + readonly aspectRatio: number; + } | null>(null); + const aspectRatio = measuredImage?.url === props.url ? measuredImage.aspectRatio : 16 / 9; + + if (failedUrl === props.url) { + return ; + } + + if (props.isVideo) { + return ( + setFailedUrl(props.url)} + /> + ); + } + + return ( + + props.onPressImage(props.url)} + style={{ aspectRatio, backgroundColor: props.backgroundColor }} + > + setFailedUrl(props.url)} + onLoad={(event) => { + const { width, height } = event.nativeEvent.source; + if (width > 0 && height > 0) { + setMeasuredImage({ + url: props.url, + aspectRatio: Math.min(2, Math.max(0.75, width / height)), + }); + } + }} + resizeMode="contain" + source={{ uri: props.url }} + style={{ height: "100%", width: "100%" }} + /> + + + {props.name} + + + ); +} + +export function MarkdownMedia(props: MarkdownMediaProps) { + const source = useMemo( + () => resolveMarkdownMediaSource(props.src, props.threadId), + [props.src, props.threadId], + ); + const assetUrl = useAssetUrlState( + source._tag === "Asset" ? props.environmentId : null, + source._tag === "Asset" ? source.resource : null, + ); + const name = + props.alt?.trim() || props.title?.trim() || markdownMediaFileName(props.src) || "Media"; + const isVideo = isWorkspaceVideoPreviewPath(props.src); + + if (source._tag === "Direct") { + return ( + + ); + } + if (assetUrl._tag === "Failure") { + return ; + } + if (assetUrl._tag === "Loading") { + return ( + + ); + } + return ( + + ); +} diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 21799364d4..9f2aa887d9 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -11,6 +11,7 @@ import { type RunId, } from "@t3tools/contracts"; import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList"; +import { markdownMediaFileName } from "@t3tools/shared/filePreview"; import { formatElapsed } from "@t3tools/shared/orchestrationTiming"; import { SymbolView } from "../../components/AppSymbol"; import { HeaderHeightContext } from "@react-navigation/elements"; @@ -68,6 +69,7 @@ import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { hasNativeSelectableMarkdownText, SelectableMarkdownText, + type MarkdownImageRenderer, type NativeMarkdownTextStyle, type SelectableMarkdownSkill, } from "../../native/SelectableMarkdownText"; @@ -112,8 +114,9 @@ import { ThreadWorkLog, WORK_GROUP_TOGGLE_HEIGHT, } from "./thread-work-log"; +import { MarkdownMedia } from "./MarkdownMedia"; import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState"; -import { useAssetUrl } from "../../state/assets"; +import { useAssetUrl, useAssetUrlState } from "../../state/assets"; import { appAtomRegistry } from "../../state/atom-registry"; import { environmentThreadShells, threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -347,6 +350,7 @@ interface MarkdownStyleSet { readonly theme: PartialMarkdownTheme; readonly styles: NodeStyleOverrides; readonly renderers: CustomRenderers; + readonly renderImage: MarkdownImageRenderer; readonly nativeTextStyle: NativeMarkdownTextStyle; } @@ -549,7 +553,12 @@ function useReviewCommentColors(): ReviewCommentColors { ); } -function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSets { +function useMarkdownStyles( + onLinkPress: (href: string) => void, + environmentId: EnvironmentId, + threadId: ThreadId, + onPressImage: (uri: string) => void, +): MarkdownStyleSets { const colorScheme = useColorScheme(); const { appearance } = useAppearancePreferences(); const markdownFontSizes = useMemo( @@ -678,7 +687,14 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe copyTintColor: ColorValue, preserveSoftBreaks: boolean, highlightCode: boolean, + renderImage: MarkdownImageRenderer, ): CustomRenderers => ({ + image: ({ url = "", alt, title }) => + renderImage({ + href: url, + ...(alt ? { alt } : {}), + ...(title ? { title } : {}), + }), link: ({ children, href = "" }) => { const presentation = resolveMarkdownLinkPresentation(href); if (presentation.kind === "file") { @@ -792,6 +808,22 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe /> ), }); + const createMediaRenderer = + (backgroundColor: ColorValue, mutedColor: ColorValue): MarkdownImageRenderer => + ({ href, alt, title }) => ( + + ); + const userMediaRenderer = createMediaRenderer(markdownUserCodeBg, markdownUserBodyColor); + const assistantMediaRenderer = createMediaRenderer(markdownCodeBg, iconSubtleColor); const userTheme: PartialMarkdownTheme = { ...baseTheme, @@ -850,7 +882,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe userBubbleForegroundMuted, true, false, + userMediaRenderer, ), + renderImage: userMediaRenderer, nativeTextStyle: { color: markdownUserBodyColor, strongColor: markdownUserBodyColor, @@ -883,7 +917,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe iconSubtleColor, false, true, + assistantMediaRenderer, ), + renderImage: assistantMediaRenderer, nativeTextStyle: { color: markdownBodyColor, strongColor: markdownStrongColor, @@ -909,17 +945,75 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe }, [ boldFontFamily, colors, + environmentId, iconSubtleColor, inlineSkillForeground, markdownFontSizes, nativeMarkdownTypography, onLinkPress, + onPressImage, regularFontFamily, themeMode, + threadId, userBubbleForegroundMuted, ]); } +function ThreadImageOutput(props: { + readonly entry: Extract; + readonly environmentId: EnvironmentId; + readonly mutedColor: ColorValue; + readonly onPressImage: (uri: string) => void; +}) { + const [failedUrl, setFailedUrl] = useState(null); + const assetUrl = useAssetUrlState(props.environmentId, { + _tag: "thread-image", + threadId: props.entry.projectedItem.item.threadId, + turnItemId: props.entry.projectedItem.item.id, + }); + const name = markdownMediaFileName(props.entry.imagePath) || "Image"; + + if (assetUrl._tag === "Failure" || (assetUrl._tag === "Success" && failedUrl === assetUrl.url)) { + return ( + + + Image no longer available + + + ); + } + if (assetUrl._tag === "Loading") { + return ( + + + + ); + } + + return ( + + props.onPressImage(assetUrl.url)} + style={{ aspectRatio: 4 / 3 }} + > + setFailedUrl(assetUrl.url)} + resizeMode="contain" + source={{ uri: assetUrl.url }} + style={{ height: "100%", width: "100%" }} + /> + + + {name} + + + ); +} + function renderFeedEntry( info: { item: ThreadFeedEntry; index: number }, props: Pick & { @@ -984,6 +1078,17 @@ function renderFeedEntry( ); } + if (entry.type === "image-output") { + return ( + + ); + } + if (entry.type === "message") { const { message } = entry; const isUser = message.role === "user"; @@ -1104,6 +1209,7 @@ function renderFeedEntry( skills={props.skills} textStyle={styles.nativeTextStyle} onLinkPress={props.onMarkdownLinkPress} + renderImage={styles.renderImage} /> ) : ( ); } @@ -1253,6 +1360,7 @@ function UserMessageContent(props: { textStyle={props.markdownStyles.nativeTextStyle} preserveSoftBreaks onLinkPress={props.onLinkPress} + renderImage={props.markdownStyles.renderImage} /> ) : ( ; } | null>(null); + const onPressImage = useCallback((uri: string, headers?: Record) => { + setExpandedImage({ uri, headers }); + }, []); const horizontalPadding = props.layoutVariant === "split" ? 20 : 16; const contentHorizontalPadding = deriveCenteredContentHorizontalPadding({ viewportWidth, @@ -1546,7 +1657,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }, [props.environmentId, props.threadId, props.workspaceRoot, navigation], ); - const markdownStyles = useMarkdownStyles(onMarkdownLinkPress); + const markdownStyles = useMarkdownStyles( + onMarkdownLinkPress, + props.environmentId, + props.threadId, + onPressImage, + ); const reviewCommentColors = useReviewCommentColors(); // LegendList does not invalidate visible rows when only the renderItem closure changes. // Keep row-local interaction props in extraData so disclosures and copy feedback repaint. @@ -1825,10 +1941,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { [suspendEndScrollMaintenanceForDisclosure], ); - const onPressImage = useCallback((uri: string, headers?: Record) => { - setExpandedImage({ uri, headers }); - }, []); - // Rows whose height is known before they ever render. Without this, every // row above the viewport is assumed to be estimatedItemSize tall, and // scrolling up through unmeasured content corrects each row's height as it diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 4d5f258a28..49a3104cd4 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -150,6 +150,29 @@ describe("buildThreadFeed", () => { expect(activity?.getFullDetail()).toContain('"input": "vp check"'); }); + it("projects completed V2 image items as native image output rows", () => { + const imageItem = { + ...base("item-image-output", "2026-06-20T00:00:02.000Z", 1), + type: "image_view" as const, + source: "image_view" as const, + path: "/tmp/tool-output.png", + } satisfies OrchestrationV2TurnItem; + const row = projected(imageItem, 0); + + expect(buildThreadFeed([row])).toEqual([ + { + type: "image-output", + id: imageItem.id, + createdAt: "2026-06-20T00:00:02.000Z", + imagePath: imageItem.path, + projectedItem: row, + }, + ]); + expect( + buildThreadFeed([projected({ ...imageItem, status: "running", completedAt: null }, 0)]), + ).toEqual([]); + }); + it("retains inherited and synthetic rows with their original projected identity", () => { const inherited = projected(command(), 0, "inherited"); const { providerThreadId: _providerThreadId, ...forkBase } = base( diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index e5729d8577..bf99b9582e 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -86,6 +86,13 @@ type RawThreadFeedEntry = readonly createdAt: string; readonly message: ThreadFeedMessage; } + | { + readonly type: "image-output"; + readonly id: string; + readonly createdAt: string; + readonly imagePath: string; + readonly projectedItem: OrchestrationV2ProjectedTurnItem; + } | { readonly type: "activity"; readonly id: string; @@ -96,6 +103,7 @@ type RawThreadFeedEntry = export type ThreadFeedEntry = | Extract + | Extract | { readonly type: "working"; readonly id: string; @@ -172,6 +180,7 @@ function itemIsToolLike(item: OrchestrationV2TurnItem): boolean { item.type === "file_change" || item.type === "file_search" || item.type === "web_search" || + item.type === "image_view" || item.type === "approval_request" || item.type === "user_input_request" || item.type === "dynamic_tool" || @@ -202,6 +211,8 @@ function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] { return "eye"; case "web_search": return "globe"; + case "image_view": + return "eye"; case "approval_request": case "user_input_request": case "user_message": @@ -252,6 +263,8 @@ function itemSummary( return "Searched files"; case "web_search": return "Searched the web"; + case "image_view": + return "Image"; case "approval_request": return "Approval requested"; case "user_input_request": @@ -299,6 +312,8 @@ function itemPreview(item: OrchestrationV2TurnItem): string | null { return item.pattern ?? null; case "web_search": return item.patterns?.join(", ") ?? null; + case "image_view": + return item.path; case "approval_request": return item.prompt ?? null; case "user_input_request": @@ -713,6 +728,18 @@ export function buildThreadFeed( }); continue; } + if (item.type === "image_view") { + if (item.status === "completed") { + entries.push({ + type: "image-output", + id: item.id, + createdAt, + imagePath: item.path, + projectedItem: row, + }); + } + continue; + } const activity = toFeedActivity(row); entries.push({ type: "activity", diff --git a/apps/mobile/src/native/SelectableMarkdownText.ios.tsx b/apps/mobile/src/native/SelectableMarkdownText.ios.tsx index 488766f369..6ecb361c98 100644 --- a/apps/mobile/src/native/SelectableMarkdownText.ios.tsx +++ b/apps/mobile/src/native/SelectableMarkdownText.ios.tsx @@ -8,6 +8,7 @@ import { highlightCodeSnippet } from "../features/review/shikiReviewHighlighter" type MobileSelectableMarkdownTextProps = Omit; export type { + MarkdownImageRenderer, NativeMarkdownTextStyle, SelectableMarkdownSkill, } from "@t3tools/mobile-markdown-text/types"; diff --git a/apps/mobile/src/native/SelectableMarkdownText.tsx b/apps/mobile/src/native/SelectableMarkdownText.tsx index 403f32a1de..db9a0b091e 100644 --- a/apps/mobile/src/native/SelectableMarkdownText.tsx +++ b/apps/mobile/src/native/SelectableMarkdownText.tsx @@ -3,6 +3,7 @@ import type { SelectableMarkdownTextProps } from "@t3tools/mobile-markdown-text/ type MobileSelectableMarkdownTextProps = Omit; export type { + MarkdownImageRenderer, NativeMarkdownTextStyle, SelectableMarkdownSkill, } from "@t3tools/mobile-markdown-text/types"; diff --git a/apps/mobile/src/state/assets.ts b/apps/mobile/src/state/assets.ts index b8b827585e..480b3aa234 100644 --- a/apps/mobile/src/state/assets.ts +++ b/apps/mobile/src/state/assets.ts @@ -12,18 +12,35 @@ const EMPTY_ASSET_URL_ATOM = Atom.make(AsyncResult.initial(false)) Atom.withLabel("mobile-asset-url:empty"), ); -export function useAssetUrl( +export type AssetUrlState = + | { readonly _tag: "Loading" } + | { readonly _tag: "Failure" } + | { readonly _tag: "Success"; readonly url: string }; + +export function useAssetUrlState( environmentId: EnvironmentId | null, resource: AssetResource | null, -): string | null { +): AssetUrlState { const preparedConnection = usePreparedConnection(environmentId); const result = useAtomValue( environmentId === null || resource === null ? EMPTY_ASSET_URL_ATOM : assetEnvironment.createUrl({ environmentId, input: { resource } }), ); - if (preparedConnection._tag === "None" || result._tag !== "Success") { - return null; + if (result._tag === "Failure") { + return { _tag: "Failure" }; } - return resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl); + if (preparedConnection._tag === "None" || result._tag !== "Success") { + return { _tag: "Loading" }; + } + const url = resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl); + return url === null ? { _tag: "Failure" } : { _tag: "Success", url }; +} + +export function useAssetUrl( + environmentId: EnvironmentId | null, + resource: AssetResource | null, +): string | null { + const result = useAssetUrlState(environmentId, resource); + return result._tag === "Success" ? result.url : null; } diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 42fd3f900e..2b441d31cf 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -1,5 +1,5 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; -import { ThreadId } from "@t3tools/contracts"; +import { ThreadId, TurnItemId } from "@t3tools/contracts"; import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -15,6 +15,14 @@ import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts"; +async function readStream(stream: AsyncIterable): Promise { + const chunks: Uint8Array[] = []; + for await (const chunk of stream) { + chunks.push(chunk); + } + return Buffer.concat(chunks); +} + const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-asset-access-test-", }); @@ -104,6 +112,83 @@ 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 token = suffix.slice(0, suffix.indexOf("/")); + + expect(yield* resolveAsset(token, "demo.webm")).toEqual({ + kind: "file", + path: canonicalVideoPath, + }); + expect(yield* resolveAsset(token, "other.webm")).toBeNull(); + }).pipe(Effect.provide(testLayer)), + ); + + it.effect("issues browser artifact URLs by media file name only", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const config = yield* ServerConfig.ServerConfig; + const artifactPath = path.join( + config.stateDir, + "browser-artifacts", + "browser-recording-demo.webm", + ); + yield* fileSystem.writeFileString(artifactPath, "webm-bytes"); + const canonicalArtifactPath = yield* fileSystem.realPath(artifactPath); + + 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("/")); + const resolved = yield* resolveAsset(token, "browser-recording-demo.webm"); + expect(resolved).toMatchObject({ + kind: "open-file", + path: canonicalArtifactPath, + }); + if (!resolved || resolved.kind !== "open-file") return; + expect( + Buffer.from(yield* Effect.promise(() => readStream(resolved.stream))).toString("utf8"), + ).toBe("webm-bytes"); + + const traversal = yield* issueAssetUrl({ + resource: { _tag: "browser-artifact", fileName: "../state.sqlite" }, + }).pipe(Effect.flip); + expect(traversal._tag).toBe("AssetBrowserArtifactNotFoundError"); + + const symlinkPath = path.join( + config.stateDir, + "browser-artifacts", + "browser-recording-link.webm", + ); + yield* fileSystem.symlink(artifactPath, symlinkPath); + const symlink = yield* issueAssetUrl({ + resource: { _tag: "browser-artifact", fileName: "browser-recording-link.webm" }, + }).pipe(Effect.flip); + expect(symlink._tag).toBe("AssetBrowserArtifactNotFoundError"); + }).pipe(Effect.provide(testLayer)), + ); + it.effect("preserves non-missing canonical path failures when issuing asset URLs", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -206,6 +291,76 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(testLayer)), ); + it.effect("issues exact capabilities for V2 image turn items outside the workspace", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-asset-image-view-", + }); + const imagePath = path.join(directory, "tool-output.png"); + yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71])); + const canonicalImagePath = yield* fileSystem.realPath(imagePath); + const resource = { + _tag: "thread-image" as const, + threadId: ThreadId.make("thread-1"), + turnItemId: TurnItemId.make("image-item-1"), + }; + + const result = yield* issueAssetUrl({ + resource, + threadImagePath: imagePath, + }); + const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const token = suffix.slice(0, suffix.indexOf("/")); + + const resolved = yield* resolveAsset(token, "tool-output.png"); + expect(resolved).toMatchObject({ + kind: "open-file", + path: canonicalImagePath, + }); + if (!resolved || resolved.kind !== "open-file") return; + expect(Array.from(yield* Effect.promise(() => readStream(resolved.stream)))).toEqual([ + 137, 80, 78, 71, + ]); + expect(yield* resolveAsset(token, "other.png")).toBeNull(); + }).pipe(Effect.provide(testLayer)), + ); + + it.effect("rejects non-image and post-issuance symlink targets for V2 image items", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-asset-image-view-invalid-", + }); + const textPath = path.join(directory, "notes.txt"); + yield* fileSystem.writeFileString(textPath, "not an image"); + const resource = { + _tag: "thread-image" as const, + threadId: ThreadId.make("thread-1"), + turnItemId: TurnItemId.make("image-item-1"), + }; + + const unsupportedError = yield* issueAssetUrl({ + resource, + threadImagePath: textPath, + }).pipe(Effect.flip); + expect(unsupportedError._tag).toBe("AssetThreadImageNotFoundError"); + + const imagePath = path.join(directory, "tool-output.png"); + const otherPath = path.join(directory, "other.png"); + yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71])); + yield* fileSystem.writeFile(otherPath, new Uint8Array([1, 2, 3])); + const result = yield* issueAssetUrl({ resource, threadImagePath: imagePath }); + const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const token = suffix.slice(0, suffix.indexOf("/")); + yield* fileSystem.remove(imagePath); + yield* fileSystem.symlink(otherPath, imagePath); + expect(yield* resolveAsset(token, "tool-output.png")).toBeNull(); + }).pipe(Effect.provide(testLayer)), + ); + it.effect("issues project favicon capabilities with a signed fallback", () => 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..fc1fe4016c 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -1,11 +1,17 @@ +// @effect-diagnostics nodeBuiltinImport:off +import type * as NodeFS from "node:fs"; + import type { AssetResource } from "@t3tools/contracts"; import { AssetAttachmentNotFoundError, + AssetBrowserArtifactNotFoundError, AssetPreviewTypeValidationError, AssetProjectFaviconInspectionError, AssetProjectFaviconNotFoundError, AssetProjectFaviconResolutionError, AssetSigningKeyLoadError, + AssetThreadImageNotFoundError, + AssetThreadImageResolutionError, AssetWorkspaceAssetInspectionError, AssetWorkspaceAssetNotFoundError, AssetWorkspaceContextNotFoundError, @@ -16,11 +22,15 @@ import { import { isWorkspaceImagePreviewPath, isWorkspacePreviewEntryPath, + isWorkspaceVideoPreviewPath, WORKSPACE_BROWSER_PREVIEW_EXTENSIONS, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS, + WORKSPACE_VIDEO_PREVIEW_EXTENSIONS, } from "@t3tools/shared/filePreview"; +import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon"; import * as Clock from "effect/Clock"; +import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; @@ -37,6 +47,7 @@ import { import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import { resolveAttachmentPathById } from "../attachmentStore.ts"; import * as ServerConfig from "../config.ts"; +import { canonicalPathsMatch, openReadableFileNoFollow } from "../noFollowFile.ts"; import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; @@ -47,6 +58,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 +89,18 @@ 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("thread-image"), + path: Schema.String, + expiresAt: Schema.Number, + }), Schema.Struct({ version: Schema.Literal(1), kind: Schema.Literal("project-favicon"), @@ -91,7 +115,20 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema); const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson); const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson); -export type ResolvedAsset = { readonly kind: "file"; readonly path: string }; +export type ResolvedAsset = + | { readonly kind: "file"; readonly path: string } + | { + readonly kind: "open-file"; + readonly path: string; + readonly stream: NodeFS.ReadStream; + readonly size: number; + }; + +class ResolvedAssetOpenError extends Data.TaggedError("ResolvedAssetOpenError")<{ + readonly path: string; + readonly resource: string; + readonly cause: unknown; +}> {} function decodeClaims(encodedPayload: string): AssetClaims | null { try { @@ -120,6 +157,94 @@ 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 openResolvedAssetForRequest = Effect.fn("AssetAccess.openResolvedAssetForRequest")( + function* (input: { readonly path: string; readonly resource: string }) { + const platform = yield* HostProcessPlatform; + const opened = yield* Effect.tryPromise({ + try: () => openReadableFileNoFollow(input.path, platform), + catch: (cause) => + new ResolvedAssetOpenError({ + path: input.path, + resource: input.resource, + cause, + }), + }); + return { + kind: "open-file", + path: input.path, + ...opened, + } satisfies ResolvedAsset; + }, + (effect, input) => + effect.pipe( + Effect.tapError((cause) => + Effect.logError("Failed to safely open resolved asset.", { + path: input.path, + resource: input.resource, + cause, + }), + ), + Effect.orElseSucceed(() => null), + ), +); + +const resolveCanonicalBrowserArtifact = Effect.fn("AssetAccess.resolveCanonicalBrowserArtifact")( + function* (fileName: string) { + const normalized = normalizeBrowserArtifactFileName(fileName); + if (!normalized) return null; + + const config = yield* ServerConfig.ServerConfig; + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const platform = yield* HostProcessPlatform; + const [canonicalDir, canonicalFile] = yield* Effect.all([ + optionOnNotFound(fileSystem.realPath(path.join(config.stateDir, "browser-artifacts"))), + optionOnNotFound( + fileSystem.realPath(path.join(config.stateDir, "browser-artifacts", normalized)), + ), + ]).pipe( + Effect.tapError((cause) => + Effect.logError("Failed to resolve the browser artifact path.", { fileName, cause }), + ), + Effect.orElseSucceed(() => [Option.none(), Option.none()] as const), + ); + if (Option.isNone(canonicalDir) || Option.isNone(canonicalFile)) return null; + if ( + !canonicalPathsMatch(path.join(canonicalDir.value, normalized), canonicalFile.value, platform) + ) { + return null; + } + if (path.dirname(canonicalFile.value) !== canonicalDir.value) return null; + if (!normalizeBrowserArtifactFileName(path.basename(canonicalFile.value))) return null; + + return (yield* statIsFile(canonicalFile.value)) ? canonicalFile.value : null; + }, +); + const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")( function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) { const fileSystem = yield* FileSystem.FileSystem; @@ -140,7 +265,14 @@ const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWor const path = yield* Path.Path; const relative = path.relative(canonicalRoot.value, canonicalFile.value); - if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null; + if ( + relative === "" || + relative === ".." || + relative.startsWith(`..${path.sep}`) || + path.isAbsolute(relative) + ) { + return null; + } const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value)); return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null; @@ -165,6 +297,7 @@ const resolveCanonicalWorkspaceFileForRequest = (input: { export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: { readonly resource: AssetResource; readonly workspaceRoot?: string; + readonly threadImagePath?: string; }) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -234,21 +367,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 +407,75 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i fileName = path.basename(attachmentPath); break; } + case "browser-artifact": { + const artifactFileName = normalizeBrowserArtifactFileName(input.resource.fileName); + if (!artifactFileName || !(yield* resolveCanonicalBrowserArtifact(artifactFileName))) { + return yield* new AssetBrowserArtifactNotFoundError({ + resource: input.resource, + }); + } + claims = { + version: 1, + kind: "browser-artifact", + fileName: artifactFileName, + expiresAt, + }; + fileName = artifactFileName; + break; + } + case "thread-image": { + if ( + !input.threadImagePath || + !path.isAbsolute(input.threadImagePath) || + !isWorkspaceImagePreviewPath(input.threadImagePath) + ) { + return yield* new AssetThreadImageNotFoundError({ + resource: input.resource, + }); + } + const canonicalPath = yield* optionOnNotFound( + fileSystem.realPath(input.threadImagePath), + ).pipe( + Effect.mapError( + (cause) => + new AssetThreadImageResolutionError({ + resource: input.resource, + cause, + }), + ), + ); + if (Option.isNone(canonicalPath)) { + return yield* new AssetThreadImageNotFoundError({ + resource: input.resource, + }); + } + const info = yield* optionOnNotFound(fileSystem.stat(canonicalPath.value)).pipe( + Effect.mapError( + (cause) => + new AssetThreadImageResolutionError({ + resource: input.resource, + cause, + }), + ), + ); + if ( + Option.isNone(info) || + info.value.type !== "File" || + !isWorkspaceImagePreviewPath(canonicalPath.value) + ) { + return yield* new AssetThreadImageNotFoundError({ + resource: input.resource, + }); + } + claims = { + version: 1, + kind: "thread-image", + path: canonicalPath.value, + expiresAt, + }; + fileName = path.basename(canonicalPath.value); + break; + } case "project-favicon": { const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe( Effect.mapError( @@ -388,6 +592,49 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* ( : null; } + if (claims.kind === "browser-artifact") { + const artifactPath = yield* resolveCanonicalBrowserArtifact(claims.fileName); + return artifactPath + ? yield* openResolvedAssetForRequest({ + path: artifactPath, + resource: "browser artifact", + }) + : null; + } + + if (claims.kind === "thread-image") { + const decodedPath = decodeRelativePath(relativePath); + const path = yield* Path.Path; + if (decodedPath !== path.basename(claims.path)) return null; + if (!isWorkspaceImagePreviewPath(claims.path)) return null; + const fileSystem = yield* FileSystem.FileSystem; + const canonicalPath = yield* optionOnNotFound(fileSystem.realPath(claims.path)).pipe( + Effect.tapError((cause) => + Effect.logError("Failed to resolve image view asset.", { + path: claims.path, + cause, + }), + ), + Effect.orElseSucceed(() => Option.none()), + ); + if (Option.isNone(canonicalPath) || canonicalPath.value !== claims.path) return null; + const info = yield* optionOnNotFound(fileSystem.stat(canonicalPath.value)).pipe( + Effect.tapError((cause) => + Effect.logError("Failed to inspect image view asset.", { + path: claims.path, + cause, + }), + ), + Effect.orElseSucceed(() => Option.none()), + ); + return Option.isSome(info) && info.value.type === "File" + ? yield* openResolvedAssetForRequest({ + path: canonicalPath.value, + resource: "thread image", + }) + : null; + } + if (claims.kind === "project-favicon") { if (claims.relativePath === null) return null; const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({ diff --git a/apps/server/src/assets/ThreadImagePath.test.ts b/apps/server/src/assets/ThreadImagePath.test.ts new file mode 100644 index 0000000000..755109cde5 --- /dev/null +++ b/apps/server/src/assets/ThreadImagePath.test.ts @@ -0,0 +1,48 @@ +import { + ThreadId, + TurnItemId, + type OrchestrationV2ThreadProjection, + type OrchestrationV2TurnItem, +} from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; + +import { resolveThreadImagePath } from "./ThreadImagePath.ts"; + +describe("resolveThreadImagePath", () => { + it("returns the path only for the exact V2 image item", () => { + const now = DateTime.makeUnsafe("2026-07-30T00:00:00.000Z"); + const item = { + id: TurnItemId.make("image-item"), + threadId: ThreadId.make("thread-1"), + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed" as const, + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "image_view" as const, + source: "image_view" as const, + path: "/tmp/tool-output.png", + } satisfies OrchestrationV2TurnItem; + const projection = { turnItems: [item] } satisfies Pick< + OrchestrationV2ThreadProjection, + "turnItems" + >; + + expect(resolveThreadImagePath(projection, item.id)).toBe(item.path); + expect(resolveThreadImagePath(projection, TurnItemId.make("missing-item"))).toBeNull(); + expect( + resolveThreadImagePath( + { turnItems: [{ ...item, status: "running", completedAt: null }] }, + item.id, + ), + ).toBeNull(); + }); +}); diff --git a/apps/server/src/assets/ThreadImagePath.ts b/apps/server/src/assets/ThreadImagePath.ts new file mode 100644 index 0000000000..35de896d63 --- /dev/null +++ b/apps/server/src/assets/ThreadImagePath.ts @@ -0,0 +1,14 @@ +import type { OrchestrationV2ThreadProjection, TurnItemId } from "@t3tools/contracts"; + +export function resolveThreadImagePath( + projection: Pick, + turnItemId: TurnItemId, +): string | null { + const item = projection.turnItems.find( + (candidate) => + candidate.id === turnItemId && + candidate.type === "image_view" && + candidate.status === "completed", + ); + return item?.type === "image_view" ? item.path : null; +} diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index e678264dde..6cc7e29866 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -143,6 +143,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(path.join(derivedPaths.stateDir, "browser-artifacts"), { 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/http.ts b/apps/server/src/http.ts index 5a380be8fe..a1dae6e110 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -270,12 +270,21 @@ export const assetRouteLayer = HttpRouter.add( if (!asset) { return HttpServerResponse.text("Not Found", { status: 404 }); } + const assetHeaders = { + "Cache-Control": "private, max-age=3600", + "X-Content-Type-Options": "nosniff", + }; + if (asset.kind === "open-file") { + return HttpServerResponse.raw(asset.stream, { + status: 200, + contentLength: asset.size, + contentType: Mime.getType(asset.path) ?? "application/octet-stream", + headers: assetHeaders, + }); + } return yield* HttpServerResponse.file(asset.path, { status: 200, - headers: { - "Cache-Control": "private, max-age=3600", - "X-Content-Type-Options": "nosniff", - }, + headers: assetHeaders, }).pipe( Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })), ); diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index e1cdf992f0..4e5feeb0c6 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -1,13 +1,31 @@ -import { expect, it } from "@effect/vitest"; +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { afterAll, 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, + type Project, + ProviderInstanceId, + ThreadId, + type OrchestrationV2ThreadProjection, +} 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 { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.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 +34,27 @@ 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 projectId = ProjectId.make("project-mcp-test"); +const testWorkspaceRoot = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "mcp-snapshot-test-")); +afterAll(() => NodeFS.rmSync(testWorkspaceRoot, { recursive: true, force: true })); +const testProject = { + id: projectId, + title: "MCP snapshot test", + workspaceRoot: testWorkspaceRoot, + repositoryIdentity: null, + faviconPath: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-07-30T00:00:00.000Z", + updatedAt: "2026-07-30T00:00:00.000Z", + deletedAt: null, +} satisfies Project; +const testProjection = { + thread: { + projectId, + worktreePath: null, + }, +} as unknown as OrchestrationV2ThreadProjection; const invocation = { environmentId, threadId, @@ -36,6 +75,20 @@ const client = McpSchema.McpServerClient.of({ const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe( Layer.provideMerge(McpServer.McpServer.layer), Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))), + Layer.provideMerge( + Layer.mock(ThreadManagementService)({ + getThreadProjection: () => Effect.succeed(testProjection), + }), + ), + Layer.provideMerge( + Layer.mock(ProjectService.ProjectService)({ + getById: (candidateProjectId) => + Effect.succeed(candidateProjectId === projectId ? Option.some(testProject) : Option.none()), + }), + ), + 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", () => { @@ -209,8 +262,9 @@ it.effect("registers annotated tools and preserves authenticated request context expect(statusTool?.tool.annotations?.destructiveHint).toBe(false); const snapshotTool = server.tools.find(({ tool }) => tool.name === "preview_snapshot"); - expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(true); - expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(true); + expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(false); + expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(false); + expect(snapshotTool?.tool.annotations?.destructiveHint).toBe(false); expect(snapshotTool?.tool.annotations?.openWorldHint).toBe(true); const clickTool = server.tools.find(({ tool }) => tool.name === "preview_click"); @@ -269,3 +323,79 @@ it.effect("registers annotated tools and preserves authenticated request context }), ).pipe(Effect.provide(TestLayer)), ); + +it.effect("persists preview snapshots to workspace and artifact destinations", () => + 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 = (arguments_: Record) => + server + .callTool({ name: "preview_snapshot", arguments: arguments_ }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), + Effect.provideService(McpSchema.McpServerClient, client), + ); + + const saved = yield* callSnapshot({ savePath: "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"); + + expect((yield* callSnapshot({ savePath: "../outside.png" })).isError).toBe(true); + expect((yield* callSnapshot({ savePath: "evidence/login.txt" })).isError).toBe(true); + expect((yield* callSnapshot({ save: true, savePath: "evidence/login.png" })).isError).toBe( + true, + ); + + const savedArtifact = yield* callSnapshot({ save: true }); + expect(savedArtifact.isError).toBe(false); + const artifactPath = (savedArtifact.structuredContent as { savedScreenshotPath?: string }) + .savedScreenshotPath; + expect(artifactPath).toBeDefined(); + expect(NodePath.dirname(artifactPath!)).toBe( + NodeFS.realpathSync( + NodePath.join((yield* ServerConfig.ServerConfig).stateDir, "browser-artifacts"), + ), + ); + 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 c49ab4a813..e3b3a41873 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,10 @@ 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 ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import * as McpSessionRegistry from "./McpSessionRegistry.ts"; @@ -136,6 +142,14 @@ 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 + | ThreadManagementService.ThreadManagementService + | ProjectService.ProjectService + | WorkspacePaths.WorkspacePaths + | FileSystem.FileSystem + | Path.Path + >(); const built = yield* PreviewSnapshotToolkit; const tool = PreviewSnapshotTool; yield* server.addTool({ @@ -166,6 +180,7 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption), Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker), + Effect.provideContext(snapshotHandlerContext), Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), Effect.matchCauseEffect({ onFailure: previewSnapshotFailure, diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index c41b4a5949..9e4ed7dfce 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -565,6 +565,8 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null { return jsonText({ pattern: item.pattern, results: item.results }); case "web_search": return jsonText({ patterns: item.patterns, results: item.results }); + case "image_view": + return item.path; case "approval_request": return item.prompt ?? item.requestKind; case "checkpoint": diff --git a/apps/server/src/mcp/toolkits/preview/handlers.ts b/apps/server/src/mcp/toolkits/preview/handlers.ts index 1c7ff6f9cd..df9812a310 100644 --- a/apps/server/src/mcp/toolkits/preview/handlers.ts +++ b/apps/server/src/mcp/toolkits/preview/handlers.ts @@ -1,16 +1,32 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeCrypto from "node:crypto"; + +import * as Clock from "effect/Clock"; +import * as Data from "effect/Data"; 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, PreviewAutomationRecordingArtifact, PreviewAutomationRecordingStatus, PreviewAutomationResizeResult, + PreviewAutomationScreenshotSaveStage, PreviewAutomationSetColorSchemeResult, PreviewAutomationSnapshot, PreviewAutomationStatus, PreviewTabId, } from "@t3tools/contracts"; +import { PreviewAutomationScreenshotSaveError } from "@t3tools/contracts"; +import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; +import * as ServerConfig from "../../../config.ts"; +import { openWritableFileNoFollow } from "../../../noFollowFile.ts"; +import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../../../project/ProjectService.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 +76,191 @@ const invokeTargeted = ( return invoke(operation, operationInput, timeoutMs, tabId); }; +class ScreenshotFileWriteError extends Data.TaggedError("ScreenshotFileWriteError")<{ + readonly path: string; + readonly cause: unknown; +}> {} + +const writeScreenshotFileNoFollow = Effect.fn("PreviewToolkit.writeScreenshotFileNoFollow")( + function* (input: { readonly absolutePath: string; readonly screenshotBase64: string }) { + const platform = yield* HostProcessPlatform; + return yield* Effect.acquireUseRelease( + Effect.tryPromise({ + try: () => openWritableFileNoFollow(input.absolutePath, platform), + catch: (cause) => new ScreenshotFileWriteError({ path: input.absolutePath, cause }), + }), + (handle) => + Effect.tryPromise({ + try: async () => { + const info = await handle.stat(); + if (!info.isFile()) { + throw new Error(`Expected a regular screenshot destination: ${input.absolutePath}`); + } + await handle.truncate(0); + await handle.writeFile(Buffer.from(input.screenshotBase64, "base64")); + }, + catch: (cause) => new ScreenshotFileWriteError({ path: input.absolutePath, cause }), + }), + (handle) => + Effect.tryPromise({ + try: () => handle.close(), + catch: (cause) => new ScreenshotFileWriteError({ path: input.absolutePath, cause }), + }), + ); + }, +); + +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)}-${NodeCrypto.randomUUID().slice(0, 8)}.png`; + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const artifactDirectory = yield* fileSystem + .realPath(path.join(config.stateDir, "browser-artifacts")) + .pipe( + Effect.mapError( + (cause) => + new PreviewAutomationScreenshotSaveError({ + operation: "snapshot", + environmentId: input.scope.environmentId, + threadId: input.scope.threadId, + providerSessionId: input.scope.providerSessionId, + providerInstanceId: input.scope.providerInstanceId, + savePath: fileName, + stage: "artifact-write", + cause, + }), + ), + ); + const absolutePath = path.join(artifactDirectory, fileName); + yield* writeScreenshotFileNoFollow({ + absolutePath, + screenshotBase64: input.screenshotBase64, + }).pipe( + Effect.mapError( + (cause) => + new PreviewAutomationScreenshotSaveError({ + operation: "snapshot", + environmentId: input.scope.environmentId, + threadId: input.scope.threadId, + providerSessionId: input.scope.providerSessionId, + providerInstanceId: input.scope.providerInstanceId, + savePath: fileName, + stage: "artifact-write", + cause, + }), + ), + ); + 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 = (stage: PreviewAutomationScreenshotSaveStage, cause?: unknown) => + new PreviewAutomationScreenshotSaveError({ + operation: "snapshot", + environmentId: scope.environmentId, + threadId: scope.threadId, + providerSessionId: scope.providerSessionId, + providerInstanceId: scope.providerInstanceId, + savePath, + stage, + ...(cause === undefined ? {} : { cause }), + }); + if (!savePath.toLowerCase().endsWith(".png")) { + return yield* fail("extension-validation"); + } + + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const projection = yield* threadManagement + .getThreadProjection(scope.threadId) + .pipe(Effect.mapError((cause) => fail("thread-workspace-resolution", cause))); + const projectService = yield* ProjectService.ProjectService; + const project = yield* projectService + .getById(projection.thread.projectId) + .pipe(Effect.mapError((cause) => fail("thread-workspace-resolution", cause))); + if (Option.isNone(project)) { + return yield* fail("thread-lookup"); + } + const workspaceRoot = projection.thread.worktreePath ?? project.value.workspaceRoot; + + const workspacePaths = yield* WorkspacePaths.WorkspacePaths; + const resolved = yield* workspacePaths + .resolveRelativePathWithinRoot({ workspaceRoot, relativePath: savePath }) + .pipe(Effect.mapError((cause) => fail("workspace-path-validation", cause))); + + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const realPathOrNull = (target: string) => + fileSystem.realPath(target).pipe( + Effect.map((canonical): string | null => canonical), + Effect.catchTags({ + PlatformError: (error) => + error.reason._tag === "NotFound" + ? Effect.succeed(null) + : Effect.fail(fail("save-path-resolution", error)), + }), + ); + const isOutsideRoot = (canonicalRoot: string, canonical: string) => { + const relative = path.relative(canonicalRoot, canonical); + return relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative); + }; + + const canonicalRoot = yield* fileSystem + .realPath(workspaceRoot) + .pipe(Effect.mapError((cause) => fail("workspace-root-resolution", cause))); + const lexicalParent = path.dirname(resolved.absolutePath); + let existingAncestor = lexicalParent; + let canonicalAncestor = yield* realPathOrNull(existingAncestor); + while (canonicalAncestor === null) { + const parent = path.dirname(existingAncestor); + if (parent === existingAncestor) { + return yield* fail("save-directory-resolution"); + } + existingAncestor = parent; + canonicalAncestor = yield* realPathOrNull(existingAncestor); + } + if (isOutsideRoot(canonicalRoot, canonicalAncestor)) { + return yield* fail("workspace-containment-validation"); + } + + yield* fileSystem + .makeDirectory(lexicalParent, { recursive: true }) + .pipe(Effect.mapError((cause) => fail("save-directory-creation", cause))); + const canonicalParent = yield* fileSystem + .realPath(lexicalParent) + .pipe(Effect.mapError((cause) => fail("save-directory-resolution", cause))); + if (isOutsideRoot(canonicalRoot, canonicalParent)) { + return yield* fail("workspace-containment-validation"); + } + + const destination = path.join(canonicalParent, path.basename(resolved.absolutePath)); + const destinationIsSymlink = yield* fileSystem.readLink(destination).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + if (destinationIsSymlink) { + return yield* fail("destination-symlink-validation"); + } + + yield* writeScreenshotFileNoFollow({ + absolutePath: destination, + screenshotBase64: input.screenshotBase64, + }).pipe(Effect.mapError((cause) => fail("screenshot-write", cause))); + return resolved.relativePath; + }, +); + const handlers = { preview_status: (input) => invokeTargeted("status", input ?? {}), preview_open: (input) => @@ -70,7 +271,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..7b552203b5 100644 --- a/apps/server/src/mcp/toolkits/preview/tools.ts +++ b/apps/server/src/mcp/toolkits/preview/tools.ts @@ -13,14 +13,21 @@ 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 ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../../../project/ProjectService.ts"; +import * as WorkspacePaths from "../../../workspace/WorkspacePaths.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts"; @@ -29,6 +36,16 @@ const dependencies = [ PreviewAutomationBroker.PreviewAutomationBroker, ]; +const snapshotDependencies = [ + ...dependencies, + ServerConfig.ServerConfig, + ThreadManagementService.ThreadManagementService, + ProjectService.ProjectService, + WorkspacePaths.WorkspacePaths, + FileSystem.FileSystem, + Path.Path, +]; + const browserTool = (tool: T): T => tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, true) as T; @@ -101,14 +118,14 @@ export const PreviewSetAppearanceTool = safeBrowserTool( .annotate(Tool.Idempotent, true), ); -export const PreviewSnapshotTool = readonlyBrowserTool( +export const PreviewSnapshotTool = safeBrowserTool( 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. Pass save:true to persist temporary visual evidence and receive savedScreenshotPath. Use savePath only when the PNG should live inside the thread workspace.", + parameters: PreviewAutomationSnapshotInput, success: PreviewAutomationSnapshot, failure: PreviewAutomationError, - dependencies, + dependencies: snapshotDependencies, }).annotate(Tool.Title, "Inspect browser page"), ); @@ -192,7 +209,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. Embed the returned .webm path in markdown to render a playable chat preview.", parameters: PreviewAutomationTabTargetInput, success: PreviewAutomationRecordingArtifact, failure: PreviewAutomationError, diff --git a/apps/server/src/noFollowFile.test.ts b/apps/server/src/noFollowFile.test.ts new file mode 100644 index 0000000000..011f98ae6c --- /dev/null +++ b/apps/server/src/noFollowFile.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { canonicalPathsMatch } from "./noFollowFile.ts"; + +describe("canonicalPathsMatch", () => { + it("accepts canonical Windows paths whose casing differs", () => { + expect( + canonicalPathsMatch( + String.raw`C:\Users\Example\capture.png`, + String.raw`C:\Users\example\CAPTURE.png`, + "win32", + ), + ).toBe(true); + }); + + it("keeps canonical path comparison case-sensitive on other platforms", () => { + expect( + canonicalPathsMatch("/Users/Example/capture.png", "/users/example/capture.png", "darwin"), + ).toBe(false); + }); + + it("rejects Windows paths that differ by more than casing", () => { + expect( + canonicalPathsMatch( + String.raw`C:\Users\Example\capture.png`, + String.raw`C:\Users\Example\outside.png`, + "win32", + ), + ).toBe(false); + }); +}); diff --git a/apps/server/src/noFollowFile.ts b/apps/server/src/noFollowFile.ts new file mode 100644 index 0000000000..cb61906cb0 --- /dev/null +++ b/apps/server/src/noFollowFile.ts @@ -0,0 +1,146 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import type * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; + +// Node does not expose Darwin's all-components no-follow flag. +const DARWIN_O_NOFOLLOW_ANY = 0x20000000; + +function errnoCode(cause: unknown): string | undefined { + return cause instanceof Error && "code" in cause && typeof cause.code === "string" + ? cause.code + : undefined; +} + +async function openLinuxPath( + absolutePath: string, + flags: number, + mode?: number, +): Promise { + const segments = absolutePath.split(NodePath.sep).filter(Boolean); + const fileName = segments.pop(); + if (!fileName || segments.some((segment) => segment === "." || segment === "..")) { + throw new Error(`Cannot safely open non-canonical path: ${absolutePath}`); + } + + let directory = await NodeFS.promises.open( + NodePath.sep, + NodeFS.constants.O_RDONLY | NodeFS.constants.O_DIRECTORY, + ); + try { + for (const segment of segments) { + const nextDirectory = await NodeFS.promises.open( + `/proc/self/fd/${directory.fd}/${segment}`, + NodeFS.constants.O_RDONLY | NodeFS.constants.O_DIRECTORY | NodeFS.constants.O_NOFOLLOW, + ); + await directory.close(); + directory = nextDirectory; + } + + return await NodeFS.promises.open( + `/proc/self/fd/${directory.fd}/${fileName}`, + flags | NodeFS.constants.O_NOFOLLOW, + mode, + ); + } finally { + await directory.close(); + } +} + +async function verifyFallbackHandle( + absolutePath: string, + handle: NodeFSP.FileHandle, + platform: NodeJS.Platform, +): Promise { + try { + const handleInfo = await handle.stat(); + const canonicalPath = await NodeFS.promises.realpath(absolutePath); + const pathInfo = await NodeFS.promises.stat(absolutePath); + if ( + !canonicalPathsMatch(absolutePath, canonicalPath, platform) || + pathInfo.dev !== handleInfo.dev || + pathInfo.ino !== handleInfo.ino + ) { + throw new Error(`Path changed while it was being opened: ${absolutePath}`); + } + return handle; + } catch (cause) { + await handle.close(); + throw cause; + } +} + +export function canonicalPathsMatch( + absolutePath: string, + canonicalPath: string, + platform: NodeJS.Platform, +): boolean { + if (canonicalPath === absolutePath) { + return true; + } + return platform === "win32" && canonicalPath.toLowerCase() === absolutePath.toLowerCase(); +} + +async function openPathNoFollow( + absolutePath: string, + flags: number, + platform: NodeJS.Platform, + mode?: number, +): Promise { + if (!NodePath.isAbsolute(absolutePath) || NodePath.resolve(absolutePath) !== absolutePath) { + throw new Error(`Cannot safely open non-canonical path: ${absolutePath}`); + } + + if (platform === "darwin") { + return NodeFS.promises.open(absolutePath, flags | DARWIN_O_NOFOLLOW_ANY, mode); + } + if (platform === "linux") { + return openLinuxPath(absolutePath, flags, mode); + } + + const noFollow = NodeFS.constants.O_NOFOLLOW ?? 0; + const handle = await NodeFS.promises.open(absolutePath, flags | noFollow, mode); + return verifyFallbackHandle(absolutePath, handle, platform); +} + +export async function openReadableFileNoFollow( + absolutePath: string, + platform: NodeJS.Platform, +): Promise<{ + readonly stream: NodeFS.ReadStream; + readonly size: number; +}> { + const handle = await openPathNoFollow(absolutePath, NodeFS.constants.O_RDONLY, platform); + try { + const info = await handle.stat(); + if (!info.isFile()) { + throw new Error(`Expected a regular file: ${absolutePath}`); + } + return { + stream: handle.createReadStream({ autoClose: true }), + size: info.size, + }; + } catch (cause) { + await handle.close(); + throw cause; + } +} + +export async function openWritableFileNoFollow( + absolutePath: string, + platform: NodeJS.Platform, +): Promise { + try { + return await openPathNoFollow(absolutePath, NodeFS.constants.O_WRONLY, platform); + } catch (cause) { + if (errnoCode(cause) !== "ENOENT") { + throw cause; + } + return openPathNoFollow( + absolutePath, + NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL, + platform, + 0o666, + ); + } +} diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index ca3e0cbbb9..c6db823a7d 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -57,6 +57,7 @@ import { makeCodexAppServerProtocolLogger, makeCodexAppServerSpawnCommand, projectCodexDynamicToolItem, + projectCodexImageItem, resolveCodexRollbackTurnCount, } from "./CodexAdapterV2.ts"; import { makeReplayServerConfig } from "./CodexAdapterV2.testkit.ts"; @@ -609,6 +610,47 @@ describe("CodexAdapterV2 dynamic tool projection", () => { }); }); +describe("CodexAdapterV2 image projection", () => { + it("projects image-view paths into durable media items", () => { + assert.deepEqual( + projectCodexImageItem({ + id: "image-view-1", + type: "imageView", + path: "/workspace/evidence.png", + }), + { + source: "image_view", + path: "/workspace/evidence.png", + }, + ); + }); + + it("projects saved image-generation paths and ignores unsaved results", () => { + assert.deepEqual( + projectCodexImageItem({ + id: "image-generation-1", + type: "imageGeneration", + result: "generated", + savedPath: "/workspace/generated.png", + status: "completed", + }), + { + source: "image_generation", + path: "/workspace/generated.png", + }, + ); + assert.isNull( + projectCodexImageItem({ + id: "image-generation-2", + type: "imageGeneration", + result: "generated", + savedPath: null, + status: "completed", + }), + ); + }); +}); + describe("CodexAdapterV2 native protocol logging", () => { it.effect("writes app-server protocol frames to the native provider log", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 65abca30d9..7c319a83b3 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -909,6 +909,25 @@ type CodexWebSearchItem = { | null; }; +export type CodexImageItem = Extract< + | CodexSchema.V2ItemStartedNotification__ThreadItem + | CodexSchema.V2ItemCompletedNotification__ThreadItem, + { readonly type: "imageView" | "imageGeneration" } +>; + +export function projectCodexImageItem( + item: CodexImageItem, +): { readonly source: "image_view" | "image_generation"; readonly path: string } | null { + const rawPath = item.type === "imageView" ? item.path : item.savedPath; + if (typeof rawPath !== "string") return null; + const path = rawPath.trim(); + if (path.length === 0) return null; + return { + source: item.type === "imageView" ? "image_view" : "image_generation", + path, + }; +} + export type CodexDynamicToolItem = Extract< | CodexSchema.V2ItemStartedNotification__ThreadItem | CodexSchema.V2ItemCompletedNotification__ThreadItem, @@ -2698,6 +2717,66 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi return { node, turnItem }; }); + const buildImageArtifacts = ( + context: ActiveCodexTurnContext, + item: CodexImageItem, + completed: boolean, + ) => + Effect.gen(function* () { + const projection = projectCodexImageItem(item); + if (projection === null) return null; + + const updatedAt = yield* DateTime.now; + const completedAt = completed ? updatedAt : null; + const status = completed ? "completed" : "running"; + const nodeId = idAllocator.derive.nodeFromProviderItem({ + driver: CODEX_PROVIDER, + nativeItemId: item.id, + }); + const turnItemId = idAllocator.derive.turnItemFromProviderItem({ + driver: CODEX_PROVIDER, + nativeItemId: item.id, + }); + const ordinal = yield* resolveItemOrdinal(context, item.id); + const node: OrchestrationV2ExecutionNode = { + id: nodeId, + threadId: context.projectionThreadId, + runId: context.projectionRunId, + parentNodeId: context.itemParentNodeId, + rootNodeId: context.rootNodeId, + kind: "tool_call", + status, + countsForRun: false, + providerThreadId: context.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef: codexNativeItemRef(item.id), + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: context.startedAt, + completedAt, + }; + const turnItem: OrchestrationV2TurnItem = { + id: turnItemId, + threadId: context.projectionThreadId, + runId: context.projectionRunId, + nodeId, + providerThreadId: context.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef: codexNativeItemRef(item.id), + parentItemId: null, + ordinal, + status, + title: null, + startedAt: context.startedAt, + completedAt, + updatedAt, + type: "image_view", + source: projection.source, + path: projection.path, + }; + return { node, turnItem }; + }); + const buildDynamicToolArtifacts = ( context: ActiveCodexTurnContext, item: CodexDynamicToolItem, @@ -3333,6 +3412,22 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi return; } + if (payload.item.type === "imageView" || payload.item.type === "imageGeneration") { + const artifacts = yield* buildImageArtifacts(context, payload.item, false); + if (artifacts === null) return; + yield* emitProviderEvent({ + type: "node.updated", + driver: CODEX_PROVIDER, + node: artifacts.node, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CODEX_PROVIDER, + turnItem: artifacts.turnItem, + }); + return; + } + if (payload.item.type !== "webSearch") { return; } @@ -3457,6 +3552,22 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi return; } + if (payload.item.type === "imageView" || payload.item.type === "imageGeneration") { + const artifacts = yield* buildImageArtifacts(context, payload.item, true); + if (artifacts === null) return; + yield* emitProviderEvent({ + type: "node.updated", + driver: CODEX_PROVIDER, + node: artifacts.node, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CODEX_PROVIDER, + turnItem: artifacts.turnItem, + }); + return; + } + if (payload.item.type === "fileChange") { const artifacts = yield* buildFileChangeArtifacts(context, payload.item); if (artifacts === null) { diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 770f768425..a704857d15 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -48,6 +48,8 @@ import { type ServerSelfUpdateProgressEvent, type FilesystemBrowseFailure, FilesystemBrowseError, + AssetThreadImageNotFoundError, + AssetThreadImageResolutionError, AssetWorkspaceContextNotFoundError, AssetWorkspaceContextResolutionError, ChatAttachmentId, @@ -101,6 +103,7 @@ import * as TerminalManager from "./terminal/Manager.ts"; import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts"; import * as PreviewManager from "./preview/Manager.ts"; import { issueAssetUrl } from "./assets/AssetAccess.ts"; +import { resolveThreadImagePath } from "./assets/ThreadImagePath.ts"; import { attachmentRelativePath, createDeterministicAttachmentId } from "./attachmentStore.ts"; import { parseBase64DataUrl } from "./imageMime.ts"; import * as PortScanner from "./preview/PortScanner.ts"; @@ -1564,6 +1567,30 @@ const makeWsRpcLayer = ( observeRpcEffect( WS_METHODS.assetsCreateUrl, Effect.gen(function* () { + if (input.resource._tag === "thread-image") { + const resource = input.resource; + const projection = yield* threadManagement + .getThreadProjection(resource.threadId) + .pipe( + Effect.mapError( + (cause) => + new AssetThreadImageResolutionError({ + resource, + cause, + }), + ), + ); + const threadImagePath = resolveThreadImagePath(projection, resource.turnItemId); + if (threadImagePath === null) { + return yield* new AssetThreadImageNotFoundError({ + resource, + }); + } + return yield* issueAssetUrl({ + resource, + threadImagePath, + }); + } if (input.resource._tag !== "workspace-file") { return yield* issueAssetUrl({ resource: input.resource }); } diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 985e943cb3..9b03659e56 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -38,6 +38,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"; @@ -140,10 +141,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, @@ -166,8 +169,36 @@ 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]:[\\/]/; + +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; @@ -1542,6 +1573,24 @@ 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..a2f820a4f2 --- /dev/null +++ b/apps/web/src/components/chat/MarkdownMedia.tsx @@ -0,0 +1,132 @@ +import type { AssetResource, ScopedThreadRef } from "@t3tools/contracts"; +import { + isDirectMarkdownMediaSource, + isWorkspaceVideoPreviewPath, + markdownMediaFileName, + resolveMarkdownMediaSource, +} from "@t3tools/shared/filePreview"; +import { memo, useState } from "react"; +import { createPortal } from "react-dom"; + +import { useAssetUrlState } from "../../assets/assetUrls"; +import { ExpandedImageDialog } from "./ExpandedImageDialog"; + +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; + kind?: "image" | "video" | undefined; +} + +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 ( +