feat(chat): preview agent media on web and mobile
This commit is contained in:
38 files changed
+2341
-81
No files matched your search
@@ -21,6 +21,8 @@ export {
|
||||
type MarkdownHighlightedToken,
|
||||
} from "./src/SelectableMarkdownText";
|
||||
export type {
|
||||
MarkdownImagePresentation,
|
||||
MarkdownImageRenderer,
|
||||
NativeMarkdownTextStyle,
|
||||
SelectableMarkdownSkill,
|
||||
SelectableMarkdownTextProps,
|
||||
|
||||
@@ -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<MarkdownImageRenderer | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
|
||||
|
||||
const highlightedCodeCache = new Map<string, HighlightedCode>();
|
||||
@@ -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 (
|
||||
<View style={{ gap: 6 }}>
|
||||
<Image
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
nativeMarkdownDocumentRuns,
|
||||
nativeMarkdownWithPreservedSoftBreaks,
|
||||
} from "./nativeMarkdownText";
|
||||
import { NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
|
||||
import { MarkdownImageRendererContext, NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
|
||||
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
|
||||
import type {
|
||||
SelectableMarkdownSkill,
|
||||
@@ -36,6 +36,7 @@ export function SelectableMarkdownText({
|
||||
highlightCode,
|
||||
preserveSoftBreaks = false,
|
||||
onLinkPress,
|
||||
renderImage,
|
||||
marginTop = 0,
|
||||
marginBottom = 0,
|
||||
}: SelectableMarkdownTextProps) {
|
||||
@@ -59,37 +60,39 @@ export function SelectableMarkdownText({
|
||||
}, [markdown, preserveSoftBreaks, skills]);
|
||||
|
||||
return (
|
||||
// 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.
|
||||
<View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
|
||||
{chunks.map((chunk, index) => {
|
||||
const content =
|
||||
chunk.kind === "rich" ? (
|
||||
<NativeMarkdownBlock
|
||||
node={chunk.node}
|
||||
textStyle={textStyle}
|
||||
highlightCode={highlightCode}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={chunk.runs}
|
||||
textStyle={textStyle}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
);
|
||||
<MarkdownImageRendererContext.Provider value={renderImage}>
|
||||
{/* 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. */}
|
||||
<View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
|
||||
{chunks.map((chunk, index) => {
|
||||
const content =
|
||||
chunk.kind === "rich" ? (
|
||||
<NativeMarkdownBlock
|
||||
node={chunk.node}
|
||||
textStyle={textStyle}
|
||||
highlightCode={highlightCode}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={chunk.runs}
|
||||
textStyle={textStyle}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<View
|
||||
key={chunk.key}
|
||||
style={{ paddingTop: nativeMarkdownChunkSpacing(chunks[index - 1], chunk) }}
|
||||
>
|
||||
{content}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
return (
|
||||
<View
|
||||
key={chunk.key}
|
||||
style={{ paddingTop: nativeMarkdownChunkSpacing(chunks[index - 1], chunk) }}
|
||||
>
|
||||
{content}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</MarkdownImageRendererContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -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<SelectableMarkdownSkill>;
|
||||
readonly preserveSoftBreaks?: boolean;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
readonly renderImage?: MarkdownImageRenderer;
|
||||
readonly marginTop?: number;
|
||||
readonly marginBottom?: number;
|
||||
}
|
||||
@@ -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 (
|
||||
<View className="my-1 max-w-full self-start rounded-lg border border-border px-2.5 py-1.5">
|
||||
<Text className="font-mono text-xs" style={{ color: props.color }}>
|
||||
Media unavailable: {props.name}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function LoadingMedia(props: {
|
||||
readonly name: string;
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly color: ColorValue;
|
||||
}) {
|
||||
return (
|
||||
<View
|
||||
className="my-2 h-40 w-full items-center justify-center gap-2 rounded-xl"
|
||||
style={{ backgroundColor: props.backgroundColor }}
|
||||
>
|
||||
<ActivityIndicator color={props.color} />
|
||||
<Text className="font-mono text-xs" numberOfLines={1} style={{ color: props.color }}>
|
||||
{props.name}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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 `<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
|
||||
<style>
|
||||
html, body { background: #000; height: 100%; margin: 0; overflow: hidden; width: 100%; }
|
||||
video { height: 100%; object-fit: contain; width: 100%; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<video id="media" controls playsinline preload="metadata" aria-label="${name}" src="${url}"></video>
|
||||
<script>
|
||||
document.getElementById("media").addEventListener("error", function () {
|
||||
window.ReactNativeWebView.postMessage("media-error");
|
||||
}, { once: true });
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}, [props.name, props.url]);
|
||||
|
||||
return (
|
||||
<View className="my-2 w-full gap-1.5">
|
||||
<View
|
||||
className="w-full overflow-hidden rounded-xl"
|
||||
style={{ aspectRatio: 16 / 9, backgroundColor: props.backgroundColor }}
|
||||
>
|
||||
<WebView
|
||||
accessibilityLabel={`Video ${props.name}`}
|
||||
allowsFullscreenVideo
|
||||
allowsInlineMediaPlayback
|
||||
bounces={false}
|
||||
javaScriptEnabled
|
||||
mediaPlaybackRequiresUserAction
|
||||
onError={props.onError}
|
||||
onMessage={(event) => {
|
||||
if (event.nativeEvent.data === "media-error") {
|
||||
props.onError();
|
||||
}
|
||||
}}
|
||||
originWhitelist={["*"]}
|
||||
scrollEnabled={false}
|
||||
source={{ html }}
|
||||
style={{ flex: 1, backgroundColor: "#000000" }}
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-sans text-xs" numberOfLines={1} style={{ color: props.color }}>
|
||||
{props.name}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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<string | null>(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 <MediaUnavailable name={props.name} color={props.color} />;
|
||||
}
|
||||
|
||||
if (props.isVideo) {
|
||||
return (
|
||||
<MarkdownVideo
|
||||
url={props.url}
|
||||
name={props.name}
|
||||
backgroundColor={props.backgroundColor}
|
||||
color={props.color}
|
||||
onError={() => setFailedUrl(props.url)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="my-2 w-full gap-1.5">
|
||||
<Pressable
|
||||
accessibilityLabel={`Expand image ${props.name}`}
|
||||
accessibilityRole="button"
|
||||
className="w-full overflow-hidden rounded-xl active:opacity-80"
|
||||
onPress={() => props.onPressImage(props.url)}
|
||||
style={{ aspectRatio, backgroundColor: props.backgroundColor }}
|
||||
>
|
||||
<Image
|
||||
accessibilityLabel={props.name}
|
||||
onError={() => 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%" }}
|
||||
/>
|
||||
</Pressable>
|
||||
<Text className="font-sans text-xs" numberOfLines={1} style={{ color: props.color }}>
|
||||
{props.name}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<ResolvedMedia
|
||||
url={normalizeDirectUrl(source.url)}
|
||||
name={name}
|
||||
isVideo={isVideo}
|
||||
backgroundColor={props.backgroundColor}
|
||||
color={props.mutedColor}
|
||||
onPressImage={props.onPressImage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (assetUrl._tag === "Failure") {
|
||||
return <MediaUnavailable name={name} color={props.mutedColor} />;
|
||||
}
|
||||
if (assetUrl._tag === "Loading") {
|
||||
return (
|
||||
<LoadingMedia name={name} backgroundColor={props.backgroundColor} color={props.mutedColor} />
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ResolvedMedia
|
||||
url={assetUrl.url}
|
||||
name={name}
|
||||
isVideo={isVideo}
|
||||
backgroundColor={props.backgroundColor}
|
||||
color={props.mutedColor}
|
||||
onPressImage={props.onPressImage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -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 }) => (
|
||||
<MarkdownMedia
|
||||
environmentId={environmentId}
|
||||
threadId={threadId}
|
||||
src={href}
|
||||
{...(alt ? { alt } : {})}
|
||||
{...(title ? { title } : {})}
|
||||
backgroundColor={backgroundColor}
|
||||
mutedColor={mutedColor}
|
||||
onPressImage={onPressImage}
|
||||
/>
|
||||
);
|
||||
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<ThreadFeedEntry, { readonly type: "image-output" }>;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly mutedColor: ColorValue;
|
||||
readonly onPressImage: (uri: string) => void;
|
||||
}) {
|
||||
const [failedUrl, setFailedUrl] = useState<string | null>(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 (
|
||||
<View className="mb-4 h-32 items-center justify-center rounded-xl border border-border px-4">
|
||||
<Text className="text-center text-xs" style={{ color: props.mutedColor }}>
|
||||
Image no longer available
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
if (assetUrl._tag === "Loading") {
|
||||
return (
|
||||
<View className="mb-4 h-40 items-center justify-center rounded-xl bg-black/5 dark:bg-white/5">
|
||||
<ActivityIndicator color={props.mutedColor} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="mb-4 gap-1.5 px-1">
|
||||
<Pressable
|
||||
accessibilityLabel={`Expand image ${name}`}
|
||||
accessibilityRole="button"
|
||||
className="w-full overflow-hidden rounded-xl bg-black/5 active:opacity-80 dark:bg-white/5"
|
||||
onPress={() => props.onPressImage(assetUrl.url)}
|
||||
style={{ aspectRatio: 4 / 3 }}
|
||||
>
|
||||
<Image
|
||||
accessibilityLabel={name}
|
||||
onError={() => setFailedUrl(assetUrl.url)}
|
||||
resizeMode="contain"
|
||||
source={{ uri: assetUrl.url }}
|
||||
style={{ height: "100%", width: "100%" }}
|
||||
/>
|
||||
</Pressable>
|
||||
<Text className="px-1 text-xs" numberOfLines={1} style={{ color: props.mutedColor }}>
|
||||
{name}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function renderFeedEntry(
|
||||
info: { item: ThreadFeedEntry; index: number },
|
||||
props: Pick<ThreadFeedProps, "environmentId" | "skills" | "threadId" | "workspaceRoot"> & {
|
||||
@@ -984,6 +1078,17 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === "image-output") {
|
||||
return (
|
||||
<ThreadImageOutput
|
||||
entry={entry}
|
||||
environmentId={props.environmentId}
|
||||
mutedColor={iconSubtleColor}
|
||||
onPressImage={props.onPressImage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
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}
|
||||
/>
|
||||
) : (
|
||||
<Markdown
|
||||
@@ -1212,6 +1318,7 @@ function UserMessageContent(props: {
|
||||
textStyle={props.markdownStyles.nativeTextStyle}
|
||||
preserveSoftBreaks
|
||||
onLinkPress={props.onLinkPress}
|
||||
renderImage={props.markdownStyles.renderImage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1253,6 +1360,7 @@ function UserMessageContent(props: {
|
||||
textStyle={props.markdownStyles.nativeTextStyle}
|
||||
preserveSoftBreaks
|
||||
onLinkPress={props.onLinkPress}
|
||||
renderImage={props.markdownStyles.renderImage}
|
||||
/>
|
||||
) : (
|
||||
<Markdown
|
||||
@@ -1492,6 +1600,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
uri: string;
|
||||
headers?: Record<string, string>;
|
||||
} | null>(null);
|
||||
const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
|
||||
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<string, string>) => {
|
||||
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
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<RawThreadFeedEntry, { type: "message" }>
|
||||
| Extract<RawThreadFeedEntry, { type: "image-output" }>
|
||||
| {
|
||||
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",
|
||||
|
||||
@@ -8,6 +8,7 @@ import { highlightCodeSnippet } from "../features/review/shikiReviewHighlighter"
|
||||
type MobileSelectableMarkdownTextProps = Omit<SelectableMarkdownTextProps, "highlightCode">;
|
||||
|
||||
export type {
|
||||
MarkdownImageRenderer,
|
||||
NativeMarkdownTextStyle,
|
||||
SelectableMarkdownSkill,
|
||||
} from "@t3tools/mobile-markdown-text/types";
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { SelectableMarkdownTextProps } from "@t3tools/mobile-markdown-text/
|
||||
type MobileSelectableMarkdownTextProps = Omit<SelectableMarkdownTextProps, "highlightCode">;
|
||||
|
||||
export type {
|
||||
MarkdownImageRenderer,
|
||||
NativeMarkdownTextStyle,
|
||||
SelectableMarkdownSkill,
|
||||
} from "@t3tools/mobile-markdown-text/types";
|
||||
|
||||
@@ -12,18 +12,35 @@ const EMPTY_ASSET_URL_ATOM = Atom.make(AsyncResult.initial<never, never>(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;
|
||||
}
|
||||
@@ -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<Uint8Array>): Promise<Uint8Array> {
|
||||
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;
|
||||
|
||||
@@ -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 = <A, R>(
|
||||
}),
|
||||
);
|
||||
|
||||
function normalizeBrowserArtifactFileName(fileName: string): string | null {
|
||||
const trimmed = fileName.trim();
|
||||
if (
|
||||
trimmed.length === 0 ||
|
||||
trimmed.includes("/") ||
|
||||
trimmed.includes("\\") ||
|
||||
trimmed.includes("\0") ||
|
||||
trimmed.startsWith(".")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (!isWorkspaceImagePreviewPath(trimmed) && !isWorkspaceVideoPreviewPath(trimmed)) {
|
||||
return null;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const statIsFile = (path: string) =>
|
||||
FileSystem.FileSystem.pipe(
|
||||
Effect.flatMap((fileSystem) => optionOnNotFound(fileSystem.stat(path))),
|
||||
Effect.map((info) => Option.isSome(info) && info.value.type === "File"),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
const 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<string>(), Option.none<string>()] 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({
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { OrchestrationV2ThreadProjection, TurnItemId } from "@t3tools/contracts";
|
||||
|
||||
export function resolveThreadImagePath(
|
||||
projection: Pick<OrchestrationV2ThreadProjection, "turnItems">,
|
||||
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;
|
||||
}
|
||||
@@ -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 }),
|
||||
|
||||
+13
-4
@@ -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 })),
|
||||
);
|
||||
|
||||
@@ -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<string, unknown>) =>
|
||||
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)),
|
||||
);
|
||||
@@ -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 = <E>(cause: Cause.Cause<E>) => {
|
||||
const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const snapshotHandlerContext = yield* Effect.context<
|
||||
| ServerConfig.ServerConfig
|
||||
| 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,
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -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 = <A>(
|
||||
return invoke<A>(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<PreviewAutomationStatus>("status", input ?? {}),
|
||||
preview_open: (input) =>
|
||||
@@ -70,7 +271,29 @@ const handlers = {
|
||||
invokeTargeted<PreviewAutomationResizeResult>("resize", input, input.timeoutMs),
|
||||
preview_set_appearance: (input) =>
|
||||
invokeTargeted<PreviewAutomationSetColorSchemeResult>("setColorScheme", input),
|
||||
preview_snapshot: (input) => invokeTargeted<PreviewAutomationSnapshot>("snapshot", input ?? {}),
|
||||
preview_snapshot: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const { save, savePath, ...target } = input ?? {};
|
||||
const snapshot = yield* invokeTargeted<PreviewAutomationSnapshot>("snapshot", target);
|
||||
if (savePath !== undefined) {
|
||||
const scope = yield* McpInvocationContext.McpInvocationContext;
|
||||
const savedScreenshotPath = yield* saveSnapshotScreenshot({
|
||||
scope,
|
||||
savePath,
|
||||
screenshotBase64: snapshot.screenshot.data,
|
||||
});
|
||||
return { ...snapshot, savedScreenshotPath };
|
||||
}
|
||||
if (save === true) {
|
||||
const scope = yield* McpInvocationContext.McpInvocationContext;
|
||||
const savedScreenshotPath = yield* saveSnapshotScreenshotArtifact({
|
||||
scope,
|
||||
screenshotBase64: snapshot.screenshot.data,
|
||||
});
|
||||
return { ...snapshot, savedScreenshotPath };
|
||||
}
|
||||
return snapshot;
|
||||
}),
|
||||
preview_click: (input) =>
|
||||
invokeTargeted<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_type: (input) =>
|
||||
|
||||
@@ -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 = <T extends Tool.Any>(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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<NodeFSP.FileHandle> {
|
||||
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<NodeFSP.FileHandle> {
|
||||
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<NodeFSP.FileHandle> {
|
||||
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<NodeFSP.FileHandle> {
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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* () {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -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<ReactMarkdownOptions["remarkPlugins"]>;
|
||||
|
||||
interface HastNodeLike {
|
||||
readonly type: string;
|
||||
readonly tagName?: string;
|
||||
properties?: Record<string, unknown>;
|
||||
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<ReactMarkdownOptions["rehypePlugins"]>;
|
||||
|
||||
@@ -1542,6 +1573,24 @@ function ChatMarkdown({
|
||||
</code>
|
||||
);
|
||||
},
|
||||
img({ node: _node, src, alt }) {
|
||||
return (
|
||||
<MarkdownMedia
|
||||
src={typeof src === "string" ? src : undefined}
|
||||
alt={alt}
|
||||
threadRef={threadRef}
|
||||
/>
|
||||
);
|
||||
},
|
||||
video({ node: _node, src }) {
|
||||
return (
|
||||
<MarkdownMedia
|
||||
src={typeof src === "string" ? src : undefined}
|
||||
threadRef={threadRef}
|
||||
kind="video"
|
||||
/>
|
||||
);
|
||||
},
|
||||
table({ node: _node, ...props }) {
|
||||
return <MarkdownTable {...props} />;
|
||||
},
|
||||
|
||||
@@ -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 (
|
||||
<span className="my-1 inline-flex max-w-full items-baseline gap-1 rounded-md border border-border/60 bg-muted/40 px-2 py-1 text-xs text-muted-foreground">
|
||||
Media unavailable:
|
||||
<span className="truncate font-mono">{name}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ResolvedMedia({ url, name, isVideo }: { url: string; name: string; isVideo: boolean }) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [failedUrl, setFailedUrl] = useState<string | null>(null);
|
||||
|
||||
if (failedUrl === url) {
|
||||
return <MediaUnavailable name={name} />;
|
||||
}
|
||||
|
||||
if (isVideo) {
|
||||
return (
|
||||
<video
|
||||
src={url}
|
||||
controls
|
||||
playsInline
|
||||
preload="metadata"
|
||||
aria-label={name}
|
||||
className={MEDIA_FRAME_CLASS_NAME}
|
||||
onError={() => setFailedUrl(url)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="block max-w-full cursor-zoom-in"
|
||||
aria-label={`Expand image ${name}`}
|
||||
onClick={() => setExpanded(true)}
|
||||
>
|
||||
<img
|
||||
src={url}
|
||||
alt={name}
|
||||
loading="lazy"
|
||||
className={MEDIA_FRAME_CLASS_NAME}
|
||||
onError={() => setFailedUrl(url)}
|
||||
/>
|
||||
</button>
|
||||
{expanded &&
|
||||
createPortal(
|
||||
<ExpandedImageDialog
|
||||
preview={{ images: [{ src: url, name }], index: 0 }}
|
||||
onClose={() => setExpanded(false)}
|
||||
/>,
|
||||
document.body,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ResourceMedia({
|
||||
threadRef,
|
||||
resource,
|
||||
name,
|
||||
isVideo,
|
||||
}: {
|
||||
threadRef: ScopedThreadRef;
|
||||
resource: AssetResource;
|
||||
name: string;
|
||||
isVideo: boolean;
|
||||
}) {
|
||||
const assetUrl = useAssetUrlState(threadRef.environmentId, resource);
|
||||
|
||||
if (assetUrl._tag === "Failure") {
|
||||
return <MediaUnavailable name={name} />;
|
||||
}
|
||||
if (assetUrl._tag === "Loading") {
|
||||
return (
|
||||
<span className="my-2 flex h-24 w-56 max-w-full animate-pulse items-center justify-center rounded-lg border border-border/40 bg-muted/30 px-2 text-xs text-muted-foreground">
|
||||
<span className="truncate">{name}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return <ResolvedMedia url={assetUrl.url} name={name} isVideo={isVideo} />;
|
||||
}
|
||||
|
||||
export const MarkdownMedia = memo(function MarkdownMedia({
|
||||
src,
|
||||
alt,
|
||||
threadRef,
|
||||
kind,
|
||||
}: MarkdownMediaProps) {
|
||||
if (!src) {
|
||||
return null;
|
||||
}
|
||||
const name = alt && alt.trim().length > 0 ? alt.trim() : markdownMediaFileName(src);
|
||||
const isVideo = kind === "video" || (kind === undefined && isWorkspaceVideoPreviewPath(src));
|
||||
if (isDirectMarkdownMediaSource(src)) {
|
||||
return <ResolvedMedia url={src} name={name} isVideo={isVideo} />;
|
||||
}
|
||||
if (!threadRef) {
|
||||
return <MediaUnavailable name={name} />;
|
||||
}
|
||||
const source = resolveMarkdownMediaSource(src, threadRef.threadId);
|
||||
return source._tag === "Asset" ? (
|
||||
<ResourceMedia threadRef={threadRef} resource={source.resource} name={name} isVideo={isVideo} />
|
||||
) : (
|
||||
<ResolvedMedia url={source.url} name={name} isVideo={isVideo} />
|
||||
);
|
||||
});
|
||||
@@ -149,6 +149,13 @@ export type MessagesTimelineRow =
|
||||
createdAt: string;
|
||||
groupedEntries: WorkLogEntry[];
|
||||
}
|
||||
| {
|
||||
kind: "image-output";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
imagePath: string;
|
||||
projectedItem: OrchestrationV2ProjectedTurnItem;
|
||||
}
|
||||
| {
|
||||
kind: "turn-fold";
|
||||
id: string;
|
||||
@@ -590,6 +597,17 @@ export function deriveMessagesTimelineRows(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (timelineEntry.kind === "image-output") {
|
||||
nextRows.push({
|
||||
kind: "image-output",
|
||||
id: timelineEntry.id,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
imagePath: timelineEntry.imagePath,
|
||||
projectedItem: timelineEntry.projectedItem,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (timelineEntry.kind === "proposed-plan") {
|
||||
nextRows.push({
|
||||
kind: "proposed-plan",
|
||||
@@ -704,6 +722,11 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
case "event":
|
||||
return a.projectedItem === (b as typeof a).projectedItem;
|
||||
|
||||
case "image-output": {
|
||||
const bi = b as typeof a;
|
||||
return a.imagePath === bi.imagePath && a.projectedItem === bi.projectedItem;
|
||||
}
|
||||
|
||||
case "work":
|
||||
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
|
||||
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { markdownMediaFileName } from "@t3tools/shared/filePreview";
|
||||
import {
|
||||
createContext,
|
||||
Fragment,
|
||||
@@ -106,6 +107,7 @@ import {
|
||||
type ParsedPreviewAnnotation,
|
||||
} from "~/lib/previewAnnotation";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { useAssetUrlState } from "~/assets/assetUrls";
|
||||
import { useUiStateStore } from "~/uiStateStore";
|
||||
import { type TimestampFormat } from "@t3tools/contracts/settings";
|
||||
import { formatChatTimestampTooltip, formatShortTimestamp } from "../../timestampFormat";
|
||||
@@ -918,6 +920,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
// they sit closer to the work that follows them.
|
||||
(row.kind === "message" && row.message.role === "assistant" && !row.showAssistantMeta) ||
|
||||
row.kind === "work" ||
|
||||
row.kind === "image-output" ||
|
||||
row.kind === "event" ||
|
||||
row.kind === "attempt-fold"
|
||||
? "pb-2"
|
||||
@@ -930,6 +933,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
data-message-role={row.kind === "message" ? row.message.role : undefined}
|
||||
>
|
||||
{row.kind === "work" ? <WorkGroupSection groupedEntries={row.groupedEntries} /> : null}
|
||||
{row.kind === "image-output" ? <ImageOutputTimelineRow row={row} /> : null}
|
||||
{row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
|
||||
{row.kind === "attempt-fold" ? <AttemptFoldTimelineRow row={row} /> : null}
|
||||
{row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
|
||||
@@ -943,6 +947,54 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
);
|
||||
});
|
||||
|
||||
function ImageOutputTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "image-output" }> }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const [failedUrl, setFailedUrl] = useState<string | null>(null);
|
||||
const assetUrl = useAssetUrlState(ctx.activeThreadEnvironmentId, {
|
||||
_tag: "thread-image",
|
||||
threadId: row.projectedItem.item.threadId,
|
||||
turnItemId: row.projectedItem.item.id,
|
||||
});
|
||||
const name = markdownMediaFileName(row.imagePath) || "Image";
|
||||
|
||||
if (assetUrl._tag === "Failure" || (assetUrl._tag === "Success" && failedUrl === assetUrl.url)) {
|
||||
return (
|
||||
<div className="flex h-32 w-48 items-center justify-center rounded-xl border border-dashed border-border/70 bg-muted/20 px-3 text-center text-xs text-muted-foreground">
|
||||
Image no longer available
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (assetUrl._tag === "Loading") {
|
||||
return (
|
||||
<div
|
||||
className="h-32 w-48 animate-pulse rounded-xl border border-border/50 bg-muted/35"
|
||||
aria-label={`Loading ${name}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="block max-w-full cursor-zoom-in overflow-hidden rounded-xl border border-border/70 bg-muted/20 p-1 transition-colors hover:border-border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/70"
|
||||
aria-label={`Preview ${name}`}
|
||||
onClick={() =>
|
||||
ctx.onImageExpand({
|
||||
images: [{ src: assetUrl.url, name }],
|
||||
index: 0,
|
||||
})
|
||||
}
|
||||
>
|
||||
<img
|
||||
src={assetUrl.url}
|
||||
alt={name}
|
||||
className="block max-h-72 max-w-full rounded-md object-contain"
|
||||
onError={() => setFailedUrl(assetUrl.url)}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const userImages = row.message.attachments ?? [];
|
||||
|
||||
@@ -363,6 +363,64 @@ describe("V2 session presentation", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("projects completed V2 image items as image output entries", () => {
|
||||
const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
|
||||
const threadId = ThreadId.make("thread-image-output");
|
||||
const item = {
|
||||
id: TurnItemId.make("item-image-output"),
|
||||
threadId,
|
||||
runId: RunId.make("run-image-output"),
|
||||
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_generation" as const,
|
||||
path: "/tmp/generated-preview.png",
|
||||
} satisfies OrchestrationV2TurnItem;
|
||||
const projectedItem = {
|
||||
position: 0,
|
||||
visibility: "local" as const,
|
||||
sourceThreadId: threadId,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
};
|
||||
|
||||
expect(
|
||||
deriveTimelineEntriesFromVisibleTurnItems({
|
||||
visibleTurnItems: [projectedItem],
|
||||
optimisticMessages: [],
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
id: item.id,
|
||||
kind: "image-output",
|
||||
createdAt: "2026-06-20T00:00:00.000Z",
|
||||
imagePath: item.path,
|
||||
projectedItem,
|
||||
},
|
||||
]);
|
||||
|
||||
expect(
|
||||
deriveTimelineEntriesFromVisibleTurnItems({
|
||||
visibleTurnItems: [
|
||||
{
|
||||
...projectedItem,
|
||||
item: { ...item, status: "running", completedAt: null },
|
||||
},
|
||||
],
|
||||
optimisticMessages: [],
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("waits for a dispatched turn item before adding queued input to the timeline", () => {
|
||||
const projection = makeThreadProjectionFixture();
|
||||
const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
|
||||
|
||||
@@ -119,6 +119,13 @@ export type TimelineEntry = (
|
||||
readonly createdAt: string;
|
||||
readonly entry: WorkLogEntry;
|
||||
}
|
||||
| {
|
||||
readonly id: string;
|
||||
readonly kind: "image-output";
|
||||
readonly createdAt: string;
|
||||
readonly imagePath: string;
|
||||
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
|
||||
}
|
||||
| {
|
||||
readonly id: string;
|
||||
readonly kind: "event";
|
||||
@@ -610,6 +617,20 @@ export function deriveTimelineEntriesFromVisibleTurnItems(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (item.type === "image_view") {
|
||||
if (item.status === "completed") {
|
||||
entries.push({
|
||||
id: item.id,
|
||||
kind: "image-output",
|
||||
createdAt,
|
||||
imagePath: item.path,
|
||||
projectedItem: row,
|
||||
...attemptMetadata,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
|
||||
entries.push({
|
||||
id: item.id,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts";
|
||||
|
||||
const ASSET_PATH_MAX_LENGTH = 1024;
|
||||
|
||||
@@ -12,6 +12,15 @@ export const AssetResource = Schema.Union([
|
||||
Schema.TaggedStruct("attachment", {
|
||||
attachmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),
|
||||
}),
|
||||
/** A file in the server's browser-artifacts directory (screenshots/recordings). */
|
||||
Schema.TaggedStruct("browser-artifact", {
|
||||
fileName: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),
|
||||
}),
|
||||
/** An image path owned by a durable orchestration V2 turn item. */
|
||||
Schema.TaggedStruct("thread-image", {
|
||||
threadId: ThreadId,
|
||||
turnItemId: TurnItemId,
|
||||
}),
|
||||
Schema.TaggedStruct("project-favicon", {
|
||||
cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
|
||||
}),
|
||||
@@ -83,7 +92,7 @@ export class AssetPreviewTypeValidationError extends Schema.TaggedErrorClass<Ass
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Only browser documents and images can be previewed.";
|
||||
return "Only browser documents, images, and videos can be previewed.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,6 +142,40 @@ export class AssetAttachmentNotFoundError extends Schema.TaggedErrorClass<AssetA
|
||||
}
|
||||
}
|
||||
|
||||
export class AssetBrowserArtifactNotFoundError extends Schema.TaggedErrorClass<AssetBrowserArtifactNotFoundError>()(
|
||||
"AssetBrowserArtifactNotFoundError",
|
||||
{
|
||||
resource: AssetResource,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Browser artifact was not found.";
|
||||
}
|
||||
}
|
||||
|
||||
export class AssetThreadImageNotFoundError extends Schema.TaggedErrorClass<AssetThreadImageNotFoundError>()(
|
||||
"AssetThreadImageNotFoundError",
|
||||
{
|
||||
resource: AssetResource,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Image view asset was not found.";
|
||||
}
|
||||
}
|
||||
|
||||
export class AssetThreadImageResolutionError extends Schema.TaggedErrorClass<AssetThreadImageResolutionError>()(
|
||||
"AssetThreadImageResolutionError",
|
||||
{
|
||||
resource: AssetResource,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to resolve image view asset.";
|
||||
}
|
||||
}
|
||||
|
||||
export class AssetProjectFaviconResolutionError extends Schema.TaggedErrorClass<AssetProjectFaviconResolutionError>()(
|
||||
"AssetProjectFaviconResolutionError",
|
||||
{
|
||||
@@ -190,6 +233,9 @@ export const AssetAccessError = Schema.Union([
|
||||
AssetWorkspaceAssetNotFoundError,
|
||||
AssetWorkspaceResolutionError,
|
||||
AssetAttachmentNotFoundError,
|
||||
AssetBrowserArtifactNotFoundError,
|
||||
AssetThreadImageNotFoundError,
|
||||
AssetThreadImageResolutionError,
|
||||
AssetProjectFaviconResolutionError,
|
||||
AssetProjectFaviconInspectionError,
|
||||
AssetProjectFaviconNotFoundError,
|
||||
|
||||
@@ -878,6 +878,12 @@ export const OrchestrationV2TurnItem = Schema.Union([
|
||||
patterns: Schema.optional(Schema.Array(Schema.String)),
|
||||
results: Schema.optional(Schema.Array(OrchestrationV2WebSearchResult)),
|
||||
}),
|
||||
Schema.Struct({
|
||||
...OrchestrationV2TurnItemBaseFields,
|
||||
type: Schema.Literal("image_view"),
|
||||
source: Schema.Literals(["image_view", "image_generation"]),
|
||||
path: TrimmedNonEmptyString.check(Schema.isMaxLength(4096)),
|
||||
}),
|
||||
Schema.Struct({
|
||||
...OrchestrationV2TurnItemBaseFields,
|
||||
type: Schema.Literal("approval_request"),
|
||||
@@ -1532,6 +1538,12 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
|
||||
patterns: Schema.optional(Schema.Array(Schema.String)),
|
||||
results: Schema.optional(Schema.Array(OrchestrationV2WebSearchResult)),
|
||||
}),
|
||||
Schema.Struct({
|
||||
...OrchestrationV2TurnItemJsonBaseFields,
|
||||
type: Schema.Literal("image_view"),
|
||||
source: Schema.Literals(["image_view", "image_generation"]),
|
||||
path: TrimmedNonEmptyString.check(Schema.isMaxLength(4096)),
|
||||
}),
|
||||
Schema.Struct({
|
||||
...OrchestrationV2TurnItemJsonBaseFields,
|
||||
type: Schema.Literal("approval_request"),
|
||||
|
||||
@@ -66,6 +66,31 @@ 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 so the human sees it in chat. Preferred for UI evidence. Cannot be combined with savePath.";
|
||||
|
||||
const SNAPSHOT_SAVE_PATH_DESCRIPTION =
|
||||
"Optional workspace-relative file path ending in .png. Use when the screenshot should live inside the repo; prefer save:true for temporary chat evidence.";
|
||||
|
||||
export const PreviewAutomationSnapshotInput = Schema.Struct({
|
||||
...PreviewAutomationTabTargetFields,
|
||||
save: Schema.optional(
|
||||
Schema.Boolean.annotate({ description: SNAPSHOT_SAVE_DESCRIPTION }),
|
||||
).annotate({ description: SNAPSHOT_SAVE_DESCRIPTION }),
|
||||
savePath: Schema.optional(
|
||||
TrimmedNonEmptyString.check(Schema.isMaxLength(512)).annotate({
|
||||
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({
|
||||
available: Schema.Boolean,
|
||||
visible: Schema.Boolean,
|
||||
@@ -548,6 +573,8 @@ export const PreviewAutomationSnapshot = Schema.Struct({
|
||||
width: Schema.Int,
|
||||
height: Schema.Int,
|
||||
}),
|
||||
/** Path the screenshot was also written to when persistence was requested. */
|
||||
savedScreenshotPath: Schema.optional(Schema.String),
|
||||
});
|
||||
export type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;
|
||||
|
||||
@@ -861,6 +888,36 @@ export class PreviewAutomationMalformedResponseError extends Schema.TaggedErrorC
|
||||
}
|
||||
}
|
||||
|
||||
export const PreviewAutomationScreenshotSaveStage = Schema.Literals([
|
||||
"artifact-write",
|
||||
"extension-validation",
|
||||
"thread-workspace-resolution",
|
||||
"thread-lookup",
|
||||
"workspace-path-validation",
|
||||
"save-path-resolution",
|
||||
"workspace-root-resolution",
|
||||
"save-directory-resolution",
|
||||
"workspace-containment-validation",
|
||||
"save-directory-creation",
|
||||
"destination-symlink-validation",
|
||||
"screenshot-write",
|
||||
]);
|
||||
export type PreviewAutomationScreenshotSaveStage = typeof PreviewAutomationScreenshotSaveStage.Type;
|
||||
|
||||
export class PreviewAutomationScreenshotSaveError extends Schema.TaggedErrorClass<PreviewAutomationScreenshotSaveError>()(
|
||||
"PreviewAutomationScreenshotSaveError",
|
||||
{
|
||||
...PreviewAutomationScopeErrorFields,
|
||||
savePath: TrimmedNonEmptyString,
|
||||
stage: PreviewAutomationScreenshotSaveStage,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to save the preview screenshot to ${this.savePath} during ${this.stage.replaceAll("-", " ")}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const PreviewAutomationError = Schema.Union([
|
||||
PreviewAutomationUnavailableError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
@@ -876,6 +933,7 @@ export const PreviewAutomationError = Schema.Union([
|
||||
PreviewAutomationRequestQueueClosedError,
|
||||
PreviewAutomationRemoteUnavailableError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationScreenshotSaveError,
|
||||
]);
|
||||
export type PreviewAutomationError = typeof PreviewAutomationError.Type;
|
||||
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
isWorkspaceBrowserPreviewPath,
|
||||
isWorkspaceImagePreviewPath,
|
||||
isWorkspacePreviewEntryPath,
|
||||
markdownMediaFileName,
|
||||
resolveMarkdownMediaSource,
|
||||
} from "./filePreview.ts";
|
||||
|
||||
describe("workspace file previews", () => {
|
||||
@@ -33,4 +36,70 @@ describe("workspace file previews", () => {
|
||||
expect(isWorkspacePreviewEntryPath(path)).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["recording.mp4", "capture.WEBM", "clip.mov?download=1"])(
|
||||
"recognizes video preview path %s",
|
||||
(path) => {
|
||||
expect(isWorkspacePreviewEntryPath(path)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it("classifies direct markdown media without asset resolution", () => {
|
||||
expect(
|
||||
resolveMarkdownMediaSource("https://cdn.example/preview.png", ThreadId.make("thread-1")),
|
||||
).toEqual({
|
||||
_tag: "Direct",
|
||||
url: "https://cdn.example/preview.png",
|
||||
});
|
||||
});
|
||||
|
||||
it("scopes relative markdown media to the thread worktree", () => {
|
||||
expect(
|
||||
resolveMarkdownMediaSource("./tmp/evidence%20capture.png?cache=1", ThreadId.make("thread-1")),
|
||||
).toEqual({
|
||||
_tag: "Asset",
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: "thread-1",
|
||||
path: "tmp/evidence capture.png",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
"/tmp/userdata/browser-artifacts/browser-recording-1.webm",
|
||||
"C:\\t3\\userdata\\browser-artifacts\\browser-recording-1.webm",
|
||||
"/C:/t3/userdata/browser-artifacts/browser-recording-1.webm",
|
||||
])("resolves absolute browser artifact path %s", (path) => {
|
||||
expect(resolveMarkdownMediaSource(path, ThreadId.make("thread-1"))).toEqual({
|
||||
_tag: "Asset",
|
||||
resource: {
|
||||
_tag: "browser-artifact",
|
||||
fileName: "browser-recording-1.webm",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("does not treat a relative browser-artifacts directory as the artifact store", () => {
|
||||
expect(
|
||||
resolveMarkdownMediaSource(
|
||||
"docs/browser-artifacts/browser-recording-1.webm",
|
||||
ThreadId.make("thread-1"),
|
||||
),
|
||||
).toEqual({
|
||||
_tag: "Asset",
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: "thread-1",
|
||||
path: "docs/browser-artifacts/browser-recording-1.webm",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("derives a decoded media file name without query or fragment", () => {
|
||||
expect(markdownMediaFileName("tmp/evidence%20capture.png?cache=1#preview")).toBe(
|
||||
"evidence capture.png",
|
||||
);
|
||||
expect(markdownMediaFileName("C:\\tmp\\evidence%20capture.png")).toBe("evidence capture.png");
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { AssetResource, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [".htm", ".html", ".pdf"] as const;
|
||||
|
||||
export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [
|
||||
@@ -11,6 +13,21 @@ export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [
|
||||
".webp",
|
||||
] as const;
|
||||
|
||||
export const WORKSPACE_VIDEO_PREVIEW_EXTENSIONS = [".m4v", ".mov", ".mp4", ".webm"] as const;
|
||||
|
||||
/** Sources a client can load directly without a signed workspace asset URL. */
|
||||
const DIRECT_MARKDOWN_MEDIA_SRC_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i;
|
||||
|
||||
/** Web markdown URL normalization carries Windows drive paths as `/C:/…`. */
|
||||
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]:[\\/])/;
|
||||
|
||||
export type MarkdownMediaSource =
|
||||
| { readonly _tag: "Direct"; readonly url: string }
|
||||
| { readonly _tag: "Asset"; readonly resource: AssetResource };
|
||||
|
||||
function hasPreviewExtension(path: string, extensions: ReadonlyArray<string>): boolean {
|
||||
const pathWithoutQuery = path.split(/[?#]/, 1)[0]?.toLowerCase() ?? "";
|
||||
return extensions.some((extension) => pathWithoutQuery.endsWith(extension));
|
||||
@@ -24,6 +41,63 @@ export function isWorkspaceImagePreviewPath(path: string): boolean {
|
||||
return hasPreviewExtension(path, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS);
|
||||
}
|
||||
|
||||
export function isWorkspacePreviewEntryPath(path: string): boolean {
|
||||
return isWorkspaceBrowserPreviewPath(path) || isWorkspaceImagePreviewPath(path);
|
||||
export function isWorkspaceVideoPreviewPath(path: string): boolean {
|
||||
return hasPreviewExtension(path, WORKSPACE_VIDEO_PREVIEW_EXTENSIONS);
|
||||
}
|
||||
|
||||
export function isWorkspacePreviewEntryPath(path: string): boolean {
|
||||
return (
|
||||
isWorkspaceBrowserPreviewPath(path) ||
|
||||
isWorkspaceImagePreviewPath(path) ||
|
||||
isWorkspaceVideoPreviewPath(path)
|
||||
);
|
||||
}
|
||||
|
||||
export function isDirectMarkdownMediaSource(src: string): boolean {
|
||||
return DIRECT_MARKDOWN_MEDIA_SRC_PATTERN.test(src);
|
||||
}
|
||||
|
||||
function safeDecode(value: string): string {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
export function markdownMediaFileName(src: string): string {
|
||||
const withoutQuery = src.split(/[?#]/, 1)[0] ?? src;
|
||||
const basename = withoutQuery.slice(
|
||||
Math.max(withoutQuery.lastIndexOf("/"), withoutQuery.lastIndexOf("\\")) + 1,
|
||||
);
|
||||
return basename.length > 0 ? safeDecode(basename) : safeDecode(withoutQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize markdown media into either a directly loadable URL or an asset RPC
|
||||
* resource. Absolute preview-tool artifact paths are served from the dedicated
|
||||
* artifact store; every other non-direct path is scoped to the thread worktree.
|
||||
*/
|
||||
export function resolveMarkdownMediaSource(src: string, threadId: ThreadId): MarkdownMediaSource {
|
||||
if (isDirectMarkdownMediaSource(src)) {
|
||||
return { _tag: "Direct", url: src };
|
||||
}
|
||||
|
||||
const withoutQuery = src.split(/[?#]/, 1)[0] ?? src;
|
||||
const decoded = safeDecode(withoutQuery);
|
||||
const path = ESCAPED_WINDOWS_DRIVE_PATH_PATTERN.test(decoded) ? decoded.slice(1) : decoded;
|
||||
const artifactMatch = ABSOLUTE_PATH_PATTERN.test(path)
|
||||
? /[/\\]browser-artifacts[/\\]([^/\\]+)$/.exec(path)
|
||||
: null;
|
||||
|
||||
return {
|
||||
_tag: "Asset",
|
||||
resource: artifactMatch?.[1]
|
||||
? { _tag: "browser-artifact", fileName: artifactMatch[1] }
|
||||
: {
|
||||
_tag: "workspace-file",
|
||||
threadId,
|
||||
path: path.startsWith("./") ? path.slice(2) : path,
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user