Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
275e7d9215 | ||
|
|
42ade0bfa0 | ||
|
|
292b685509 | ||
|
|
54456158be | ||
|
|
4cd0891030 | ||
|
|
c63b980e17 | ||
|
|
c6847cef59 | ||
|
|
d7d2d74848 | ||
|
|
a1682683ce | ||
|
|
86756e7e49 | ||
|
|
89d667e042 | ||
|
|
492f68e1ed | ||
|
|
23702f1914 |
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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -59,6 +59,7 @@ import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import {
|
||||
hasNativeSelectableMarkdownText,
|
||||
SelectableMarkdownText,
|
||||
type MarkdownImageRenderer,
|
||||
type NativeMarkdownTextStyle,
|
||||
type SelectableMarkdownSkill,
|
||||
} from "../../native/SelectableMarkdownText";
|
||||
@@ -101,6 +102,7 @@ import {
|
||||
ThreadWorkLog,
|
||||
WORK_GROUP_TOGGLE_HEIGHT,
|
||||
} from "./thread-work-log";
|
||||
import { MarkdownMedia } from "./MarkdownMedia";
|
||||
import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
@@ -244,6 +246,7 @@ interface MarkdownStyleSet {
|
||||
readonly theme: PartialMarkdownTheme;
|
||||
readonly styles: NodeStyleOverrides;
|
||||
readonly renderers: CustomRenderers;
|
||||
readonly renderImage: MarkdownImageRenderer;
|
||||
readonly nativeTextStyle: NativeMarkdownTextStyle;
|
||||
}
|
||||
|
||||
@@ -446,7 +449,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(
|
||||
@@ -575,7 +583,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") {
|
||||
@@ -689,6 +704,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,
|
||||
@@ -747,7 +778,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
userBubbleForegroundMuted,
|
||||
true,
|
||||
false,
|
||||
userMediaRenderer,
|
||||
),
|
||||
renderImage: userMediaRenderer,
|
||||
nativeTextStyle: {
|
||||
color: markdownUserBodyColor,
|
||||
strongColor: markdownUserBodyColor,
|
||||
@@ -780,7 +813,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
iconSubtleColor,
|
||||
false,
|
||||
true,
|
||||
assistantMediaRenderer,
|
||||
),
|
||||
renderImage: assistantMediaRenderer,
|
||||
nativeTextStyle: {
|
||||
color: markdownBodyColor,
|
||||
strongColor: markdownStrongColor,
|
||||
@@ -810,9 +845,12 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
inlineSkillForeground,
|
||||
markdownFontSizes,
|
||||
nativeMarkdownTypography,
|
||||
environmentId,
|
||||
onLinkPress,
|
||||
onPressImage,
|
||||
regularFontFamily,
|
||||
themeMode,
|
||||
threadId,
|
||||
userBubbleForegroundMuted,
|
||||
]);
|
||||
}
|
||||
@@ -969,6 +1007,7 @@ function renderFeedEntry(
|
||||
skills={props.skills}
|
||||
textStyle={styles.nativeTextStyle}
|
||||
onLinkPress={props.onMarkdownLinkPress}
|
||||
renderImage={styles.renderImage}
|
||||
/>
|
||||
) : (
|
||||
<Markdown
|
||||
@@ -1066,6 +1105,7 @@ function UserMessageContent(props: {
|
||||
textStyle={props.markdownStyles.nativeTextStyle}
|
||||
preserveSoftBreaks
|
||||
onLinkPress={props.onLinkPress}
|
||||
renderImage={props.markdownStyles.renderImage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1107,6 +1147,7 @@ function UserMessageContent(props: {
|
||||
textStyle={props.markdownStyles.nativeTextStyle}
|
||||
preserveSoftBreaks
|
||||
onLinkPress={props.onLinkPress}
|
||||
renderImage={props.markdownStyles.renderImage}
|
||||
/>
|
||||
) : (
|
||||
<Markdown
|
||||
@@ -1346,6 +1387,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,
|
||||
@@ -1400,7 +1444,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.
|
||||
@@ -1692,10 +1741,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
|
||||
|
||||
@@ -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 { EventId, ThreadId } 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-",
|
||||
});
|
||||
@@ -70,6 +78,117 @@ describe("AssetAccess", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues exact-file workspace URLs for video files", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-video-",
|
||||
});
|
||||
const videoPath = path.join(root, "recordings", "demo.webm");
|
||||
yield* fileSystem.makeDirectory(path.join(root, "recordings"), { recursive: true });
|
||||
yield* fileSystem.writeFileString(videoPath, "webm-bytes");
|
||||
const canonicalVideoPath = yield* fileSystem.realPath(videoPath);
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
path: "recordings/demo.webm",
|
||||
},
|
||||
workspaceRoot: root,
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const separatorIndex = suffix.indexOf("/");
|
||||
const token = suffix.slice(0, separatorIndex);
|
||||
|
||||
expect(yield* resolveAsset(token, "demo.webm")).toEqual({
|
||||
kind: "file",
|
||||
path: canonicalVideoPath,
|
||||
});
|
||||
// Exact-file claim: the token must not grant access to sibling files.
|
||||
expect(yield* resolveAsset(token, "other.webm")).toBeNull();
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues and resolves browser artifact URLs by file name only", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true });
|
||||
const artifactPath = path.join(config.browserArtifactsDir, "browser-recording-demo.webm");
|
||||
yield* fileSystem.writeFileString(artifactPath, "webm-bytes");
|
||||
const canonicalArtifactPath = yield* fileSystem.realPath(artifactPath);
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(config.browserArtifactsDir, "notes.txt"),
|
||||
"not media",
|
||||
);
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "browser-artifact", fileName: "browser-recording-demo.webm" },
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const token = suffix.slice(0, suffix.indexOf("/"));
|
||||
const resolved = yield* resolveAsset(token, "browser-recording-demo.webm");
|
||||
expect(resolved).toMatchObject({
|
||||
kind: "open-file",
|
||||
path: canonicalArtifactPath,
|
||||
});
|
||||
if (!resolved || resolved.kind !== "open-file") return;
|
||||
|
||||
const outsideDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-open-artifact-outside-",
|
||||
});
|
||||
const secretPath = path.join(outsideDir, "secret.webm");
|
||||
yield* fileSystem.writeFileString(secretPath, "secret-bytes");
|
||||
yield* fileSystem.remove(artifactPath);
|
||||
yield* fileSystem.symlink(secretPath, artifactPath);
|
||||
expect(
|
||||
Buffer.from(yield* Effect.promise(() => readStream(resolved.stream))).toString("utf8"),
|
||||
).toBe("webm-bytes");
|
||||
|
||||
// Non-media files and traversal-style names are not issuable.
|
||||
const nonMedia = yield* issueAssetUrl({
|
||||
resource: { _tag: "browser-artifact", fileName: "notes.txt" },
|
||||
}).pipe(Effect.flip);
|
||||
expect(nonMedia._tag).toBe("AssetBrowserArtifactNotFoundError");
|
||||
const traversal = yield* issueAssetUrl({
|
||||
resource: { _tag: "browser-artifact", fileName: "../state.sqlite" },
|
||||
}).pipe(Effect.flip);
|
||||
expect(traversal._tag).toBe("AssetBrowserArtifactNotFoundError");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("serves workspace files in directories whose name starts with ..", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-dotdot-name-",
|
||||
});
|
||||
yield* fileSystem.makeDirectory(path.join(root, "..screenshots"), { recursive: true });
|
||||
const imagePath = path.join(root, "..screenshots", "capture.png");
|
||||
yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
|
||||
const canonicalImagePath = yield* fileSystem.realPath(imagePath);
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
path: "..screenshots/capture.png",
|
||||
},
|
||||
workspaceRoot: root,
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const token = suffix.slice(0, suffix.indexOf("/"));
|
||||
expect(yield* resolveAsset(token, "capture.png")).toEqual({
|
||||
kind: "file",
|
||||
path: canonicalImagePath,
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects workspace files outside the authorized root", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -206,6 +325,173 @@ describe("AssetAccess", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues exact capabilities for image view activities 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"),
|
||||
activityId: EventId.make("activity-1"),
|
||||
};
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource,
|
||||
threadImagePath: imagePath,
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const separatorIndex = suffix.indexOf("/");
|
||||
const token = suffix.slice(0, separatorIndex);
|
||||
|
||||
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 missing and non-image paths for image view activities", () =>
|
||||
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"),
|
||||
activityId: EventId.make("activity-1"),
|
||||
};
|
||||
|
||||
const unsupportedError = yield* issueAssetUrl({
|
||||
resource,
|
||||
threadImagePath: textPath,
|
||||
}).pipe(Effect.flip);
|
||||
expect(unsupportedError._tag).toBe("AssetThreadImageNotFoundError");
|
||||
|
||||
const missingError = yield* issueAssetUrl({
|
||||
resource,
|
||||
threadImagePath: path.join(directory, "missing.png"),
|
||||
}).pipe(Effect.flip);
|
||||
expect(missingError._tag).toBe("AssetThreadImageNotFoundError");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects image view symlinks that escape to non-image files", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-image-view-symlink-",
|
||||
});
|
||||
const secretPath = path.join(directory, "secret.env");
|
||||
yield* fileSystem.writeFileString(secretPath, "SECRET=value");
|
||||
const disguisedPath = path.join(directory, "disguised.png");
|
||||
yield* fileSystem.symlink(secretPath, disguisedPath);
|
||||
const resource = {
|
||||
_tag: "thread-image" as const,
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activityId: EventId.make("activity-1"),
|
||||
};
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource,
|
||||
threadImagePath: disguisedPath,
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("AssetThreadImageNotFoundError");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("re-resolves image view claims so post-issuance swaps are rejected", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-image-view-swap-",
|
||||
});
|
||||
const imagePath = path.join(directory, "tool-output.png");
|
||||
yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
|
||||
const outsidePath = path.join(directory, "secret.png");
|
||||
yield* fileSystem.writeFileString(outsidePath, "SECRET");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "thread-image" as const,
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activityId: EventId.make("activity-1"),
|
||||
},
|
||||
threadImagePath: imagePath,
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const token = suffix.slice(0, suffix.indexOf("/"));
|
||||
|
||||
// Swap the issued file for a symlink pointing elsewhere.
|
||||
yield* fileSystem.remove(imagePath);
|
||||
yield* fileSystem.symlink(outsidePath, imagePath);
|
||||
expect(yield* resolveAsset(token, "tool-output.png")).toBeNull();
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects browser artifact symlinks that escape the artifacts directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true });
|
||||
const outsideDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-artifact-outside-",
|
||||
});
|
||||
const secretPath = path.join(outsideDir, "secret.png");
|
||||
yield* fileSystem.writeFileString(secretPath, "SECRET=value");
|
||||
yield* fileSystem.symlink(secretPath, path.join(config.browserArtifactsDir, "escape.png"));
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource: { _tag: "browser-artifact", fileName: "escape.png" },
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("AssetBrowserArtifactNotFoundError");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("re-resolves browser artifact claims so post-issuance swaps are rejected", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true });
|
||||
const outsideDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-artifact-swap-",
|
||||
});
|
||||
const secretPath = path.join(outsideDir, "secret.png");
|
||||
yield* fileSystem.writeFileString(secretPath, "SECRET=value");
|
||||
const artifactPath = path.join(config.browserArtifactsDir, "swapped.png");
|
||||
yield* fileSystem.writeFile(artifactPath, new Uint8Array([137, 80, 78, 71]));
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "browser-artifact", fileName: "swapped.png" },
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const token = suffix.slice(0, suffix.indexOf("/"));
|
||||
|
||||
yield* fileSystem.remove(artifactPath);
|
||||
yield* fileSystem.symlink(secretPath, artifactPath);
|
||||
expect(yield* resolveAsset(token, "swapped.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 { 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,95 @@ 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),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Resolve a browser artifact to its canonical path, rejecting anything that
|
||||
* escapes the artifacts directory. Names are validated before and after
|
||||
* `realPath` so a symlink with an allowed media name cannot redirect to an
|
||||
* arbitrary (or non-media) server-readable file.
|
||||
*/
|
||||
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 [canonicalDir, canonicalFile] = yield* Effect.all([
|
||||
optionOnNotFound(fileSystem.realPath(config.browserArtifactsDir)),
|
||||
optionOnNotFound(fileSystem.realPath(path.join(config.browserArtifactsDir, 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;
|
||||
|
||||
// Artifacts are stored flat, so the canonical parent must be the
|
||||
// canonical artifacts directory itself.
|
||||
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 +266,16 @@ 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;
|
||||
// `..name` is an ordinary in-root directory, so only a real `..` segment
|
||||
// counts as an escape.
|
||||
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 +300,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 +370,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 +410,78 @@ 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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
// The extension check above ran on the pre-realPath input; re-check the
|
||||
// canonical target so a symlink named `*.png` cannot smuggle out an
|
||||
// arbitrary non-image file.
|
||||
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 +598,54 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
: null;
|
||||
}
|
||||
|
||||
if (claims.kind === "browser-artifact") {
|
||||
// Re-resolve and keep the validated descriptor open for the response so
|
||||
// serving the asset cannot follow a path swapped after this check.
|
||||
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;
|
||||
// The claim stores the path that was canonical at issuance. Re-canonicalize
|
||||
// on every request so a file later replaced by a symlink cannot redirect
|
||||
// this token to somewhere else on disk.
|
||||
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({
|
||||
|
||||
@@ -33,6 +33,12 @@ export interface ServerDerivedPaths {
|
||||
readonly providerStatusCacheDir: string;
|
||||
readonly worktreesDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
/**
|
||||
* Browser evidence artifacts (screenshots/recordings). The desktop app
|
||||
* writes recordings here too — both derive `<baseDir>/(dev|userdata)`, so
|
||||
* in the standard local setup this is the same directory.
|
||||
*/
|
||||
readonly browserArtifactsDir: string;
|
||||
readonly logsDir: string;
|
||||
readonly serverLogPath: string;
|
||||
readonly serverTracePath: string;
|
||||
@@ -108,6 +114,7 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
);
|
||||
const dbPath = join(stateDir, "state.sqlite");
|
||||
const attachmentsDir = join(stateDir, "attachments");
|
||||
const browserArtifactsDir = join(stateDir, "browser-artifacts");
|
||||
const logsDir = join(stateDir, "logs");
|
||||
const providerLogsDir = join(logsDir, "provider");
|
||||
const providerStatusCacheDir = join(baseDir, "caches");
|
||||
@@ -119,6 +126,7 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
providerStatusCacheDir,
|
||||
worktreesDir: join(baseDir, "worktrees"),
|
||||
attachmentsDir,
|
||||
browserArtifactsDir,
|
||||
logsDir,
|
||||
serverLogPath: join(logsDir, "server.log"),
|
||||
serverTracePath: join(logsDir, "server.trace.ndjson"),
|
||||
@@ -143,6 +151,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
|
||||
fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.browserArtifactsDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
|
||||
|
||||
+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,28 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { NodeHttpServer } from "@effect/platform-node";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PreviewTabId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { McpSchema, McpServer } from "effect/unstable/ai";
|
||||
import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import * as McpHttpServer from "./McpHttpServer.ts";
|
||||
import * as McpInvocationContext from "./McpInvocationContext.ts";
|
||||
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
|
||||
@@ -16,6 +31,7 @@ const environmentId = EnvironmentId.make("environment-mcp-test");
|
||||
const threadId = ThreadId.make("thread-mcp-test");
|
||||
const tabId = PreviewTabId.make("tab-mcp-test");
|
||||
const alternateTabId = PreviewTabId.make("tab-mcp-alternate");
|
||||
const testWorkspaceRoot = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "mcp-snapshot-test-"));
|
||||
const invocation = {
|
||||
environmentId,
|
||||
threadId,
|
||||
@@ -33,9 +49,44 @@ const client = McpSchema.McpServerClient.of({
|
||||
},
|
||||
getClient: Effect.die("unused"),
|
||||
});
|
||||
const stubProjectionSnapshotQueryLayer = Layer.succeed(
|
||||
ProjectionSnapshotQuery.ProjectionSnapshotQuery,
|
||||
{
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getArchivedShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: (contextThreadId) =>
|
||||
Effect.succeed(
|
||||
contextThreadId === threadId
|
||||
? Option.some({
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-mcp-test"),
|
||||
workspaceRoot: testWorkspaceRoot,
|
||||
worktreePath: null,
|
||||
checkpoints: [],
|
||||
})
|
||||
: Option.none(),
|
||||
),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
},
|
||||
);
|
||||
|
||||
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpServer.McpServer.layer),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
|
||||
Layer.provideMerge(stubProjectionSnapshotQueryLayer),
|
||||
Layer.provideMerge(WorkspacePaths.layer),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-test-" })),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
it("normalizes empty successful notification responses to accepted", () => {
|
||||
@@ -209,8 +260,10 @@ 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);
|
||||
// save/savePath write files, so the snapshot tool is not read-only.
|
||||
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 +322,128 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
}),
|
||||
).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("writes snapshot screenshots into the workspace when savePath is set", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const events = yield* broker.connect({
|
||||
clientId: "mcp-save-client",
|
||||
environmentId,
|
||||
});
|
||||
yield* Stream.runForEach(events, (event) =>
|
||||
event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "mcp-save-client",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: true,
|
||||
result: {
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
visibleText: "Example",
|
||||
interactiveElements: [],
|
||||
accessibilityTree: {},
|
||||
consoleEntries: [],
|
||||
networkEntries: [],
|
||||
actionTimeline: [],
|
||||
screenshot: {
|
||||
mimeType: "image/png",
|
||||
data: Buffer.from("png-bytes").toString("base64"),
|
||||
width: 10,
|
||||
height: 5,
|
||||
},
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const callSnapshot = (savePath: string) =>
|
||||
server
|
||||
.callTool({ name: "preview_snapshot", arguments: { savePath } })
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
);
|
||||
|
||||
const saved = yield* callSnapshot("evidence/login.png");
|
||||
expect(saved.isError).toBe(false);
|
||||
expect(saved.structuredContent).toMatchObject({
|
||||
savedScreenshotPath: "evidence/login.png",
|
||||
});
|
||||
expect(
|
||||
NodeFS.readFileSync(NodePath.join(testWorkspaceRoot, "evidence/login.png"), "utf8"),
|
||||
).toBe("png-bytes");
|
||||
|
||||
const wrongExtension = yield* callSnapshot("evidence/login.txt");
|
||||
expect(wrongExtension.isError).toBe(true);
|
||||
|
||||
const traversal = yield* callSnapshot("../outside.png");
|
||||
expect(traversal.isError).toBe(true);
|
||||
expect(NodeFS.existsSync(NodePath.join(testWorkspaceRoot, "..", "outside.png"))).toBe(false);
|
||||
|
||||
// A directory symlink pointing outside the workspace must be rejected
|
||||
// before mkdir creates anything at the symlink target.
|
||||
const outsideDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "mcp-outside-"));
|
||||
NodeFS.symlinkSync(outsideDir, NodePath.join(testWorkspaceRoot, "escape-dir"));
|
||||
const dirSymlink = yield* callSnapshot("escape-dir/sub/leak.png");
|
||||
expect(dirSymlink.isError).toBe(true);
|
||||
expect(NodeFS.existsSync(NodePath.join(outsideDir, "sub"))).toBe(false);
|
||||
|
||||
// An existing file symlink at the destination must not be followed
|
||||
// outside the workspace.
|
||||
const victimPath = NodePath.join(outsideDir, "victim.png");
|
||||
NodeFS.writeFileSync(victimPath, "original");
|
||||
NodeFS.mkdirSync(NodePath.join(testWorkspaceRoot, "evidence"), { recursive: true });
|
||||
NodeFS.symlinkSync(victimPath, NodePath.join(testWorkspaceRoot, "evidence", "escape.png"));
|
||||
const fileSymlink = yield* callSnapshot("evidence/escape.png");
|
||||
expect(fileSymlink.isError).toBe(true);
|
||||
expect(NodeFS.readFileSync(victimPath, "utf8")).toBe("original");
|
||||
|
||||
// A dangling destination symlink must not be followed into existence.
|
||||
const danglingTarget = NodePath.join(outsideDir, "not-yet-created.png");
|
||||
NodeFS.symlinkSync(
|
||||
danglingTarget,
|
||||
NodePath.join(testWorkspaceRoot, "evidence", "dangling.png"),
|
||||
);
|
||||
const danglingSymlink = yield* callSnapshot("evidence/dangling.png");
|
||||
expect(danglingSymlink.isError).toBe(true);
|
||||
expect(NodeFS.existsSync(danglingTarget)).toBe(false);
|
||||
|
||||
// A directory whose name merely starts with ".." is inside the root.
|
||||
const dotDotName = yield* callSnapshot("..screenshots/ok.png");
|
||||
expect(dotDotName.isError).toBe(false);
|
||||
expect(
|
||||
NodeFS.readFileSync(NodePath.join(testWorkspaceRoot, "..screenshots", "ok.png"), "utf8"),
|
||||
).toBe("png-bytes");
|
||||
|
||||
const bothDestinations = yield* server
|
||||
.callTool({
|
||||
name: "preview_snapshot",
|
||||
arguments: { save: true, savePath: "evidence/login.png" },
|
||||
})
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
);
|
||||
expect(bothDestinations.isError).toBe(true);
|
||||
|
||||
const savedArtifact = yield* server
|
||||
.callTool({ name: "preview_snapshot", arguments: { save: true } })
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
);
|
||||
expect(savedArtifact.isError).toBe(false);
|
||||
const artifactPath = (savedArtifact.structuredContent as { savedScreenshotPath?: string })
|
||||
.savedScreenshotPath;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
expect(artifactPath).toBeDefined();
|
||||
expect(NodePath.dirname(artifactPath!)).toBe(config.browserArtifactsDir);
|
||||
expect(NodeFS.readFileSync(artifactPath!, "utf8")).toBe("png-bytes");
|
||||
}),
|
||||
).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
@@ -1,8 +1,10 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import type * as Types from "effect/Types";
|
||||
@@ -10,6 +12,9 @@ import { McpSchema, McpServer, Tool } from "effect/unstable/ai";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import * as McpInvocationContext from "./McpInvocationContext.ts";
|
||||
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
|
||||
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
|
||||
@@ -130,6 +135,13 @@ const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {
|
||||
const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const snapshotHandlerContext = yield* Effect.context<
|
||||
| ServerConfig.ServerConfig
|
||||
| ProjectionSnapshotQuery.ProjectionSnapshotQuery
|
||||
| WorkspacePaths.WorkspacePaths
|
||||
| FileSystem.FileSystem
|
||||
| Path.Path
|
||||
>();
|
||||
const built = yield* PreviewSnapshotToolkit;
|
||||
const tool = PreviewSnapshotTool;
|
||||
yield* server.addTool({
|
||||
@@ -160,6 +172,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,
|
||||
|
||||
@@ -1,16 +1,31 @@
|
||||
// @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 ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as WorkspacePaths from "../../../workspace/WorkspacePaths.ts";
|
||||
import * as McpInvocationContext from "../../McpInvocationContext.ts";
|
||||
import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
|
||||
import { PreviewSnapshotToolkit, PreviewStandardToolkit, PreviewToolkit } from "./tools.ts";
|
||||
@@ -60,6 +75,192 @@ const invokeTargeted = <A>(
|
||||
return invoke<A>(operation, operationInput, timeoutMs, tabId);
|
||||
};
|
||||
|
||||
const writeScreenshotFile = (input: {
|
||||
readonly absolutePath: string;
|
||||
readonly screenshotBase64: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.makeDirectory(path.dirname(input.absolutePath), { recursive: true });
|
||||
yield* fileSystem.writeFile(
|
||||
input.absolutePath,
|
||||
new Uint8Array(Buffer.from(input.screenshotBase64, "base64")),
|
||||
);
|
||||
});
|
||||
|
||||
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;
|
||||
// Timestamp for ordering plus a random component so concurrent
|
||||
// same-millisecond captures never overwrite each other.
|
||||
const fileName = `browser-screenshot-${(yield* Clock.currentTimeMillis).toString(36)}-${NodeCrypto.randomUUID().slice(0, 8)}.png`;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(config.browserArtifactsDir, fileName);
|
||||
yield* writeScreenshotFile({ absolutePath, screenshotBase64: input.screenshotBase64 }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PreviewAutomationScreenshotSaveError({
|
||||
operation: "snapshot",
|
||||
environmentId: input.scope.environmentId,
|
||||
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 projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const threadContext = yield* projectionSnapshotQuery
|
||||
.getThreadCheckpointContext(scope.threadId)
|
||||
.pipe(Effect.mapError((cause) => fail("thread-workspace-resolution", cause)));
|
||||
if (Option.isNone(threadContext)) {
|
||||
return yield* fail("thread-lookup");
|
||||
}
|
||||
const workspaceRoot = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||
|
||||
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
|
||||
const resolved = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath: savePath })
|
||||
.pipe(Effect.mapError((cause) => fail("workspace-path-validation", cause)));
|
||||
|
||||
// Lexical containment is not enough: symlinks inside the workspace could
|
||||
// point outside it. Every filesystem step below re-verifies canonical
|
||||
// containment before it acts.
|
||||
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)));
|
||||
|
||||
// Before creating anything: the deepest EXISTING ancestor of the target
|
||||
// must canonicalize inside the root, or recursive mkdir would follow an
|
||||
// outward directory symlink and create directories outside the workspace.
|
||||
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");
|
||||
}
|
||||
|
||||
// Report a stable validation stage for links already present at the final
|
||||
// destination. The descriptor-based write below also refuses path
|
||||
// components swapped to symlinks after this check.
|
||||
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,20 @@ import {
|
||||
PreviewAutomationSetColorSchemeInput,
|
||||
PreviewAutomationSetColorSchemeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationSnapshotInput,
|
||||
PreviewAutomationStatus,
|
||||
PreviewAutomationTabTargetInput,
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "@t3tools/contracts";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Tool, Toolkit } from "effect/unstable/ai";
|
||||
|
||||
import * as ServerConfig from "../../../config.ts";
|
||||
import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as WorkspacePaths from "../../../workspace/WorkspacePaths.ts";
|
||||
import * as McpInvocationContext from "../../McpInvocationContext.ts";
|
||||
import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
|
||||
|
||||
@@ -29,6 +35,15 @@ const dependencies = [
|
||||
PreviewAutomationBroker.PreviewAutomationBroker,
|
||||
];
|
||||
|
||||
const snapshotDependencies = [
|
||||
...dependencies,
|
||||
ServerConfig.ServerConfig,
|
||||
ProjectionSnapshotQuery.ProjectionSnapshotQuery,
|
||||
WorkspacePaths.WorkspacePaths,
|
||||
FileSystem.FileSystem,
|
||||
Path.Path,
|
||||
];
|
||||
|
||||
const browserTool = <T extends Tool.Any>(tool: T): T =>
|
||||
tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, true) as T;
|
||||
|
||||
@@ -101,14 +116,17 @@ export const PreviewSetAppearanceTool = safeBrowserTool(
|
||||
.annotate(Tool.Idempotent, true),
|
||||
);
|
||||
|
||||
export const PreviewSnapshotTool = readonlyBrowserTool(
|
||||
// Not `readonlyBrowserTool`: `save`/`savePath` write a screenshot file, and
|
||||
// `save:true` names a fresh artifact per call, so it is neither read-only
|
||||
// nor idempotent.
|
||||
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. To keep visual evidence for the human (before/after states of UI work), pass save:true — the result then includes savedScreenshotPath, which you embed in your final reply with markdown image syntax, e.g. . Use savePath only when the screenshot should live inside the repo.",
|
||||
parameters: PreviewAutomationSnapshotInput,
|
||||
success: PreviewAutomationSnapshot,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
dependencies: snapshotDependencies,
|
||||
}).annotate(Tool.Title, "Inspect browser page"),
|
||||
);
|
||||
|
||||
@@ -192,7 +210,7 @@ export const PreviewRecordingStartTool = safeBrowserTool(
|
||||
export const PreviewRecordingStopTool = safeBrowserTool(
|
||||
Tool.make("preview_recording_stop", {
|
||||
description:
|
||||
"Stop recording the collaborative browser tab selected by tabId, or this agent session's current tab when omitted, and save it as a local evidence artifact.",
|
||||
"Stop recording the collaborative browser tab selected by tabId, or this agent session's current tab when omitted, and save it as a local evidence artifact (.webm). To show the recording to the human, embed the returned path directly in your final reply with markdown image syntax, e.g.  — the chat renders it as a playable video. The recording is saved on the machine running the desktop app; if the server runs on a different machine the embed can show as unavailable — in that case copy the file into the workspace and embed the workspace-relative path instead.",
|
||||
parameters: PreviewAutomationTabTargetInput,
|
||||
success: PreviewAutomationRecordingArtifact,
|
||||
failure: PreviewAutomationError,
|
||||
|
||||
@@ -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,150 @@
|
||||
// @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) {
|
||||
// Each lookup is anchored to an already-open directory, so replacing its
|
||||
// original pathname cannot redirect any later component.
|
||||
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);
|
||||
}
|
||||
|
||||
// Other platforms lack an openat-style primitive in Node. Keep the handle
|
||||
// only when its identity still matches the canonical pathname.
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { projectActivityPayload } from "./ActivityPayloadProjection.ts";
|
||||
|
||||
const makeImageActivity = (item: Record<string, unknown>): OrchestrationThreadActivity => ({
|
||||
id: EventId.make("activity-image-1"),
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: "Image view",
|
||||
payload: {
|
||||
itemType: "image_view",
|
||||
detail: "/tmp/generated.png",
|
||||
data: { completedAtMs: 1, item },
|
||||
},
|
||||
turnId: TurnId.make("turn-1"),
|
||||
createdAt: "2026-07-27T21:17:50.000Z",
|
||||
});
|
||||
|
||||
const projectedItem = (activity: OrchestrationThreadActivity): Record<string, unknown> => {
|
||||
const payload = activity.payload as { data?: { item?: Record<string, unknown> } };
|
||||
return payload.data?.item ?? {};
|
||||
};
|
||||
|
||||
describe("projectActivityPayload", () => {
|
||||
it("keeps the saved path for generated images while pruning the base64 result", () => {
|
||||
const projected = projectActivityPayload(
|
||||
makeImageActivity({
|
||||
id: "call-1",
|
||||
type: "imageGeneration",
|
||||
savedPath: "/Users/test/.codex/generated_images/thread/call.png",
|
||||
revisedPrompt: "a prompt",
|
||||
result: "iVBORw0KGgoAAAANSUhEUg",
|
||||
status: "completed",
|
||||
}),
|
||||
);
|
||||
|
||||
const item = projectedItem(projected);
|
||||
expect(item.savedPath).toBe("/Users/test/.codex/generated_images/thread/call.png");
|
||||
expect(item.type).toBe("imageGeneration");
|
||||
// The generated image bytes are megabytes per activity and unread by clients.
|
||||
expect(item.result).toBeUndefined();
|
||||
expect(item.revisedPrompt).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps the viewed path for image view items", () => {
|
||||
const projected = projectActivityPayload(
|
||||
makeImageActivity({ id: "call-2", type: "imageView", path: "/tmp/screenshot.png" }),
|
||||
);
|
||||
|
||||
const item = projectedItem(projected);
|
||||
expect(item.path).toBe("/tmp/screenshot.png");
|
||||
expect(item.type).toBe("imageView");
|
||||
});
|
||||
|
||||
it("still prunes unrelated tool item payloads", () => {
|
||||
const projected = projectActivityPayload(
|
||||
makeImageActivity({ id: "call-3", type: "somethingElse", secret: "value" }),
|
||||
);
|
||||
|
||||
expect(projectedItem(projected)).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -104,6 +104,31 @@ function projectCommandData(data: Record<string, unknown>): Record<string, unkno
|
||||
return Object.keys(projectedItem).length > 0 ? projectedItem : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Image view items carry the on-disk path both clients need to render the
|
||||
* output gallery. The generated image itself also rides along in `result` as
|
||||
* base64 — that stays pruned, since it is megabytes per activity and no client
|
||||
* reads it.
|
||||
*/
|
||||
function projectImageViewData(data: Record<string, unknown>): Record<string, unknown> | undefined {
|
||||
const item = asRecord(data.item);
|
||||
if (!item) {
|
||||
return undefined;
|
||||
}
|
||||
if (item.type !== "imageView" && item.type !== "imageGeneration") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const projectedItem: Record<string, unknown> = { type: item.type };
|
||||
if (asTrimmedString(item.path)) {
|
||||
projectedItem.path = item.path;
|
||||
}
|
||||
if (asTrimmedString(item.savedPath)) {
|
||||
projectedItem.savedPath = item.savedPath;
|
||||
}
|
||||
return Object.keys(projectedItem).length > 1 ? projectedItem : undefined;
|
||||
}
|
||||
|
||||
function summarizeToolTextOutput(value: string): string | null {
|
||||
const lines: string[] = [];
|
||||
for (const rawLine of value.split(/\r?\n/u)) {
|
||||
@@ -165,7 +190,7 @@ export function projectActivityPayload(
|
||||
}
|
||||
|
||||
const projectedData: Record<string, unknown> = {};
|
||||
const item = projectCommandData(data);
|
||||
const item = projectCommandData(data) ?? projectImageViewData(data);
|
||||
if (item) {
|
||||
projectedData.item = item;
|
||||
}
|
||||
|
||||
@@ -613,6 +613,95 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps image view items with their local path", () =>
|
||||
Effect.gen(function* () {
|
||||
const { adapter, runtime } = yield* startLifecycleRuntime();
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
const imagePath = "/tmp/codex-preview.png";
|
||||
|
||||
yield* runtime.emit({
|
||||
id: asEventId("evt-image-view-complete"),
|
||||
kind: "notification",
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
method: "item/completed",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
itemId: asItemId("image_1"),
|
||||
payload: {
|
||||
completedAtMs: 1_778_000_000_000,
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
item: {
|
||||
type: "imageView",
|
||||
id: "image_1",
|
||||
path: imagePath,
|
||||
},
|
||||
},
|
||||
});
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
|
||||
NodeAssert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some" || firstEvent.value.type !== "item.completed") {
|
||||
return;
|
||||
}
|
||||
NodeAssert.equal(firstEvent.value.payload.itemType, "image_view");
|
||||
NodeAssert.equal(firstEvent.value.payload.title, "Image view");
|
||||
NodeAssert.equal(firstEvent.value.payload.detail, imagePath);
|
||||
NodeAssert.deepStrictEqual(firstEvent.value.payload.data, {
|
||||
completedAtMs: 1_778_000_000_000,
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
item: {
|
||||
type: "imageView",
|
||||
id: "image_1",
|
||||
path: imagePath,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps generated images with their saved path", () =>
|
||||
Effect.gen(function* () {
|
||||
const { adapter, runtime } = yield* startLifecycleRuntime();
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
const imagePath = "/Users/test/.codex/generated_images/thread-1/generated.png";
|
||||
|
||||
yield* runtime.emit({
|
||||
id: asEventId("evt-image-generation-complete"),
|
||||
kind: "notification",
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
method: "item/completed",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
itemId: asItemId("image_generation_1"),
|
||||
payload: {
|
||||
completedAtMs: 1_778_000_000_000,
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
item: {
|
||||
type: "imageGeneration",
|
||||
id: "image_generation_1",
|
||||
status: "completed",
|
||||
revisedPrompt: "A generated image",
|
||||
result: "base64-image-data",
|
||||
savedPath: imagePath,
|
||||
},
|
||||
},
|
||||
});
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
|
||||
NodeAssert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some" || firstEvent.value.type !== "item.completed") {
|
||||
return;
|
||||
}
|
||||
NodeAssert.equal(firstEvent.value.payload.itemType, "image_view");
|
||||
NodeAssert.equal(firstEvent.value.payload.title, "Image view");
|
||||
NodeAssert.equal(firstEvent.value.payload.detail, imagePath);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps completed plan items to canonical proposed-plan completion events", () =>
|
||||
Effect.gen(function* () {
|
||||
const { adapter, runtime } = yield* startLifecycleRuntime();
|
||||
|
||||
@@ -281,6 +281,7 @@ function itemDetail(itemType: CanonicalItemType, item: CodexLifecycleItem): stri
|
||||
"summary" in item ? item.summary : undefined,
|
||||
"text" in item ? item.text : undefined,
|
||||
"path" in item ? item.path : undefined,
|
||||
"savedPath" in item ? item.savedPath : undefined,
|
||||
"prompt" in item ? item.prompt : undefined,
|
||||
];
|
||||
|
||||
|
||||
@@ -4878,6 +4878,83 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("issues image view asset URLs only for the exact thread activity", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const imageDirectory = yield* fs.makeTempDirectoryScoped({
|
||||
prefix: "t3-ws-image-view-",
|
||||
});
|
||||
const imagePath = path.join(imageDirectory, "tool-output.png");
|
||||
yield* fs.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
|
||||
const activityId = EventId.make("image-view-activity");
|
||||
const thread = {
|
||||
...makeDefaultOrchestrationReadModel().threads[0]!,
|
||||
activities: [
|
||||
{
|
||||
id: activityId,
|
||||
tone: "tool" as const,
|
||||
kind: "tool.completed",
|
||||
summary: "Image view",
|
||||
payload: {
|
||||
itemType: "image_view",
|
||||
data: {
|
||||
item: {
|
||||
type: "imageGeneration",
|
||||
savedPath: imagePath,
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
projectionSnapshotQuery: {
|
||||
getThreadDetailById: (threadId) =>
|
||||
Effect.succeed(threadId === defaultThreadId ? Option.some(thread) : Option.none()),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const response = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.assetsCreateUrl]({
|
||||
resource: {
|
||||
_tag: "thread-image",
|
||||
threadId: defaultThreadId,
|
||||
activityId,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.include(response.relativeUrl, "/tool-output.png");
|
||||
|
||||
const unrelatedActivityResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.assetsCreateUrl]({
|
||||
resource: {
|
||||
_tag: "thread-image",
|
||||
threadId: defaultThreadId,
|
||||
activityId: EventId.make("unrelated-activity"),
|
||||
},
|
||||
}).pipe(Effect.result),
|
||||
),
|
||||
);
|
||||
if (
|
||||
unrelatedActivityResult._tag !== "Failure" ||
|
||||
unrelatedActivityResult.failure._tag !== "AssetThreadImageNotFoundError"
|
||||
) {
|
||||
assert.fail("Expected an AssetThreadImageNotFoundError");
|
||||
}
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("creates a missing workspace root during websocket project.create dispatch", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -45,6 +45,8 @@ import {
|
||||
AssetWorkspaceContextNotFoundError,
|
||||
AssetWorkspaceContextResolutionError,
|
||||
RpcClientId,
|
||||
AssetThreadImageNotFoundError,
|
||||
AssetThreadImageResolutionError,
|
||||
EnvironmentAuthorizationError,
|
||||
ThreadId,
|
||||
type TerminalAttachStreamEvent,
|
||||
@@ -116,6 +118,27 @@ import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
|
||||
import * as SessionStore from "./auth/SessionStore.ts";
|
||||
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
|
||||
function asUnknownRecord(value: unknown): Record<string, unknown> | null {
|
||||
return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : null;
|
||||
}
|
||||
|
||||
function extractImageViewPath(payload: unknown): string | null {
|
||||
const payloadRecord = asUnknownRecord(payload);
|
||||
if (payloadRecord?.itemType !== "image_view") return null;
|
||||
const data = asUnknownRecord(payloadRecord.data);
|
||||
const item = asUnknownRecord(data?.item);
|
||||
const rawPath =
|
||||
item?.type === "imageView"
|
||||
? item.path
|
||||
: item?.type === "imageGeneration"
|
||||
? item.savedPath
|
||||
: null;
|
||||
if (typeof rawPath !== "string") return null;
|
||||
const path = rawPath.trim();
|
||||
return path.length > 0 ? path : null;
|
||||
}
|
||||
|
||||
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
@@ -1622,6 +1645,35 @@ const makeWsRpcLayer = (
|
||||
observeRpcEffect(
|
||||
WS_METHODS.assetsCreateUrl,
|
||||
Effect.gen(function* () {
|
||||
if (input.resource._tag === "thread-image") {
|
||||
const resource = input.resource;
|
||||
const thread = yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(resource.threadId)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetThreadImageResolutionError({
|
||||
resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const activity = Option.isSome(thread)
|
||||
? thread.value.activities.find(
|
||||
(candidate) => candidate.id === resource.activityId,
|
||||
)
|
||||
: undefined;
|
||||
const threadImagePath = activity ? extractImageViewPath(activity.payload) : null;
|
||||
if (!threadImagePath) {
|
||||
return yield* new AssetThreadImageNotFoundError({
|
||||
resource,
|
||||
});
|
||||
}
|
||||
return yield* issueAssetUrl({
|
||||
resource,
|
||||
threadImagePath,
|
||||
});
|
||||
}
|
||||
if (input.resource._tag !== "workspace-file") {
|
||||
return yield* issueAssetUrl({ resource: input.resource });
|
||||
}
|
||||
|
||||
@@ -47,6 +47,17 @@ export function useAssetUrls(
|
||||
environmentId: EnvironmentId,
|
||||
resources: ReadonlyArray<AssetResource>,
|
||||
): ReadonlyArray<string | null> {
|
||||
const states = useAssetUrlStates(environmentId, resources);
|
||||
return useMemo(
|
||||
() => states.map((state) => (state._tag === "Success" ? state.url : null)),
|
||||
[states],
|
||||
);
|
||||
}
|
||||
|
||||
export function useAssetUrlStates(
|
||||
environmentId: EnvironmentId,
|
||||
resources: ReadonlyArray<AssetResource>,
|
||||
): ReadonlyArray<AssetUrlState> {
|
||||
const preparedConnection = usePreparedConnection(environmentId);
|
||||
const results = useAtomValue(
|
||||
assetEnvironment.createUrls({
|
||||
@@ -56,13 +67,16 @@ export function useAssetUrls(
|
||||
);
|
||||
return useMemo(
|
||||
() =>
|
||||
preparedConnection._tag === "None"
|
||||
? resources.map(() => null)
|
||||
: results.map((result) =>
|
||||
AsyncResult.isSuccess(result)
|
||||
? resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl)
|
||||
: null,
|
||||
),
|
||||
results.map((result): AssetUrlState => {
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
return { _tag: "Failure" };
|
||||
}
|
||||
if (preparedConnection._tag === "None" || !AsyncResult.isSuccess(result)) {
|
||||
return { _tag: "Loading" };
|
||||
}
|
||||
const url = resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl);
|
||||
return url === null ? { _tag: "Failure" } : { _tag: "Success", url };
|
||||
}),
|
||||
[preparedConnection, resources, results],
|
||||
);
|
||||
}
|
||||
@@ -39,6 +39,7 @@ import rehypeRaw from "rehype-raw";
|
||||
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
|
||||
import remarkBreaks from "remark-breaks";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { MarkdownMedia } from "./chat/MarkdownMedia";
|
||||
import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
|
||||
import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
|
||||
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
|
||||
@@ -161,10 +162,12 @@ function findTaskListMarkerOffset(markdown: string, listItemStart: number): numb
|
||||
}
|
||||
const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
|
||||
...defaultSchema,
|
||||
tagNames: [...(defaultSchema.tagNames ?? []), "video"],
|
||||
attributes: {
|
||||
...defaultSchema.attributes,
|
||||
"*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
|
||||
code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
|
||||
video: ["src", "controls", "muted", "loop", "playsInline", "poster", "preload"],
|
||||
},
|
||||
protocols: {
|
||||
...defaultSchema.protocols,
|
||||
@@ -187,8 +190,39 @@ const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
|
||||
remarkTagInlineCode,
|
||||
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
|
||||
|
||||
interface HastNodeLike {
|
||||
readonly type: string;
|
||||
readonly tagName?: string;
|
||||
properties?: Record<string, unknown>;
|
||||
children?: HastNodeLike[];
|
||||
}
|
||||
|
||||
const WINDOWS_DRIVE_SRC_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||
|
||||
// rehype-sanitize parses a Windows drive path source such as "C:\shot.png"
|
||||
// as an unknown "c:" protocol and strips it. Escape media sources to
|
||||
// "/C:/…" before sanitization runs; MarkdownMedia unescapes when resolving.
|
||||
function rehypeEscapeWindowsDriveMediaSrc() {
|
||||
const escapeNode = (node: HastNodeLike): void => {
|
||||
if (
|
||||
node.type === "element" &&
|
||||
(node.tagName === "img" || node.tagName === "video") &&
|
||||
node.properties &&
|
||||
typeof node.properties.src === "string" &&
|
||||
WINDOWS_DRIVE_SRC_PATTERN.test(node.properties.src)
|
||||
) {
|
||||
node.properties.src = `/${node.properties.src}`;
|
||||
}
|
||||
for (const child of node.children ?? []) {
|
||||
escapeNode(child);
|
||||
}
|
||||
};
|
||||
return escapeNode;
|
||||
}
|
||||
|
||||
const CHAT_MARKDOWN_REHYPE_PLUGINS = [
|
||||
rehypeRaw,
|
||||
rehypeEscapeWindowsDriveMediaSrc,
|
||||
[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
|
||||
] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
|
||||
|
||||
@@ -1584,6 +1618,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,24 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildExpandedImagePreview } from "./ExpandedImagePreview";
|
||||
|
||||
describe("buildExpandedImagePreview", () => {
|
||||
it("opens the selected image at its index in the available gallery", () => {
|
||||
expect(
|
||||
buildExpandedImagePreview(
|
||||
[
|
||||
{ id: "first", name: "first.png", previewUrl: "https://example.test/first.png" },
|
||||
{ id: "missing", name: "missing.png" },
|
||||
{ id: "second", name: "second.png", previewUrl: "https://example.test/second.png" },
|
||||
],
|
||||
"second",
|
||||
),
|
||||
).toEqual({
|
||||
images: [
|
||||
{ src: "https://example.test/first.png", name: "first.png" },
|
||||
{ src: "https://example.test/second.png", name: "second.png" },
|
||||
],
|
||||
index: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { memo, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import type { AssetResource, ScopedThreadRef } from "@t3tools/contracts";
|
||||
import {
|
||||
isDirectMarkdownMediaSource,
|
||||
isWorkspaceVideoPreviewPath,
|
||||
markdownMediaFileName,
|
||||
resolveMarkdownMediaSource,
|
||||
} from "@t3tools/shared/filePreview";
|
||||
|
||||
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;
|
||||
/** Force the media kind; when omitted it is inferred from the file extension. */
|
||||
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 &&
|
||||
// Portal to the body: message rows create containing blocks that would
|
||||
// otherwise trap the fixed-position dialog inside the chat scroller.
|
||||
createPortal(
|
||||
<ExpandedImageDialog
|
||||
preview={{ images: [{ src: url, name }], index: 0 }}
|
||||
onClose={() => setExpanded(false)}
|
||||
/>,
|
||||
document.body,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ResourceMedia({
|
||||
threadRef,
|
||||
resource,
|
||||
name,
|
||||
isVideo,
|
||||
}: {
|
||||
threadRef: ScopedThreadRef;
|
||||
resource: AssetResource;
|
||||
name: string;
|
||||
isVideo: boolean;
|
||||
}) {
|
||||
const assetUrl = useAssetUrlState(threadRef.environmentId, resource);
|
||||
|
||||
if (assetUrl._tag === "Failure") {
|
||||
return <MediaUnavailable name={name} />;
|
||||
}
|
||||
if (assetUrl._tag === "Loading") {
|
||||
return (
|
||||
<span className="my-2 flex h-24 w-56 max-w-full animate-pulse items-center justify-center rounded-lg border border-border/40 bg-muted/30 px-2 text-xs text-muted-foreground">
|
||||
<span className="truncate">{name}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return <ResolvedMedia url={assetUrl.url} name={name} isVideo={isVideo} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders markdown-referenced media (images and videos) in chat messages.
|
||||
*
|
||||
* Workspace-relative sources are resolved to signed asset URLs for the
|
||||
* thread's worktree, so agents can save screenshots/recordings into the
|
||||
* workspace and embed them with plain markdown image syntax.
|
||||
*/
|
||||
export const MarkdownMedia = memo(function MarkdownMedia({
|
||||
src,
|
||||
alt,
|
||||
threadRef,
|
||||
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} />
|
||||
);
|
||||
});
|
||||
@@ -261,6 +261,293 @@ describe("resolveAssistantMessageCopyState", () => {
|
||||
});
|
||||
|
||||
describe("deriveMessagesTimelineRows", () => {
|
||||
it("renders unscoped image output when no turn is unsettled", () => {
|
||||
const timelineEntries = [
|
||||
{
|
||||
id: "unscoped-image-entry",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
entry: {
|
||||
id: "unscoped-image-activity",
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
turnId: null,
|
||||
label: "Image view",
|
||||
tone: "tool" as const,
|
||||
itemType: "image_view" as const,
|
||||
imagePath: "/tmp/unscoped.png",
|
||||
toolLifecycleStatus: "completed" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-entry",
|
||||
kind: "message" as const,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
message: {
|
||||
id: "assistant-message" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Here is the image.",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:21Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
expandedTurnIds: new Set(),
|
||||
});
|
||||
|
||||
const imageOutputRow = rows.find((row) => row.kind === "image-output");
|
||||
expect(imageOutputRow).toMatchObject({
|
||||
kind: "image-output",
|
||||
id: "image-output:unscoped",
|
||||
images: [
|
||||
{
|
||||
entry: { id: "unscoped-image-activity" },
|
||||
imagePath: "/tmp/unscoped.png",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("deduplicates and groups image output after the terminal assistant message", () => {
|
||||
const timelineEntries = [
|
||||
{
|
||||
id: "user-entry",
|
||||
kind: "message" as const,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
message: {
|
||||
id: "user-message" as never,
|
||||
role: "user" as const,
|
||||
text: "Generate an image",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "image-view-entry",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
entry: {
|
||||
id: "image-view-activity",
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "Image view",
|
||||
tone: "tool" as const,
|
||||
itemType: "image_view" as const,
|
||||
imagePath: "/tmp/generated.png",
|
||||
toolLifecycleStatus: "completed" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "duplicate-image-view-entry",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:11Z",
|
||||
entry: {
|
||||
id: "duplicate-image-view-activity",
|
||||
createdAt: "2026-01-01T00:00:11Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "Image view",
|
||||
tone: "tool" as const,
|
||||
itemType: "image_view" as const,
|
||||
imagePath: "/tmp/generated.png",
|
||||
toolLifecycleStatus: "completed" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "second-image-view-entry",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:12Z",
|
||||
entry: {
|
||||
id: "second-image-view-activity",
|
||||
createdAt: "2026-01-01T00:00:12Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "Image view",
|
||||
tone: "tool" as const,
|
||||
itemType: "image_view" as const,
|
||||
imagePath: "/tmp/second.png",
|
||||
toolLifecycleStatus: "completed" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-entry",
|
||||
kind: "message" as const,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
message: {
|
||||
id: "assistant-message" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Here is the generated image.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:21Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
];
|
||||
const input = {
|
||||
timelineEntries,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
};
|
||||
|
||||
const expandedRows = deriveMessagesTimelineRows({
|
||||
...input,
|
||||
expandedTurnIds: new Set(["turn-1" as never]),
|
||||
});
|
||||
const toolRowIndex = expandedRows.findIndex((row) => row.kind === "work");
|
||||
const assistantRowIndex = expandedRows.findIndex(
|
||||
(row) => row.kind === "message" && row.message.role === "assistant",
|
||||
);
|
||||
const assistantRow = expandedRows[assistantRowIndex];
|
||||
|
||||
expect(toolRowIndex).toBeGreaterThan(-1);
|
||||
expect(assistantRowIndex).toBeGreaterThan(toolRowIndex);
|
||||
expect(assistantRow).toMatchObject({
|
||||
kind: "message",
|
||||
assistantImageOutputs: [
|
||||
{
|
||||
entry: { id: "image-view-activity" },
|
||||
imagePath: "/tmp/generated.png",
|
||||
},
|
||||
{
|
||||
entry: { id: "second-image-view-activity" },
|
||||
imagePath: "/tmp/second.png",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(expandedRows.some((row) => row.kind === "image-output")).toBe(false);
|
||||
|
||||
const collapsedRows = deriveMessagesTimelineRows(input);
|
||||
expect(collapsedRows.some((row) => row.kind === "work")).toBe(false);
|
||||
expect(collapsedRows.at(-1)).toMatchObject({
|
||||
kind: "message",
|
||||
assistantImageOutputs: [
|
||||
{
|
||||
entry: { id: "image-view-activity" },
|
||||
imagePath: "/tmp/generated.png",
|
||||
},
|
||||
{
|
||||
entry: { id: "second-image-view-activity" },
|
||||
imagePath: "/tmp/second.png",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("withholds image output until its turn is settled", () => {
|
||||
const timelineEntries = [
|
||||
{
|
||||
id: "image-view-entry",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
entry: {
|
||||
id: "image-view-activity",
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "Image view",
|
||||
tone: "tool" as const,
|
||||
itemType: "image_view" as const,
|
||||
imagePath: "/tmp/generated.png",
|
||||
toolLifecycleStatus: "completed" as const,
|
||||
},
|
||||
},
|
||||
];
|
||||
const sharedInput = {
|
||||
timelineEntries,
|
||||
activeTurnStartedAt: "2026-01-01T00:00:00Z",
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
};
|
||||
|
||||
const runningRows = deriveMessagesTimelineRows({
|
||||
...sharedInput,
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "running" as const,
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: null,
|
||||
},
|
||||
isWorking: true,
|
||||
});
|
||||
expect(runningRows.some((row) => row.kind === "image-output")).toBe(false);
|
||||
|
||||
const settledRows = deriveMessagesTimelineRows({
|
||||
...sharedInput,
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "completed" as const,
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: "2026-01-01T00:00:20Z",
|
||||
},
|
||||
isWorking: false,
|
||||
});
|
||||
expect(settledRows.some((row) => row.kind === "image-output")).toBe(true);
|
||||
});
|
||||
|
||||
it("allows the same image to appear once in each turn", () => {
|
||||
const imagePath = "/tmp/shared.png";
|
||||
const makeImageEntry = (turnId: string, id: string, createdAt: string) => ({
|
||||
id: `${id}-entry`,
|
||||
kind: "work" as const,
|
||||
createdAt,
|
||||
entry: {
|
||||
id,
|
||||
createdAt,
|
||||
turnId: turnId as never,
|
||||
label: "Image view",
|
||||
tone: "tool" as const,
|
||||
itemType: "image_view" as const,
|
||||
imagePath,
|
||||
toolLifecycleStatus: "completed" as const,
|
||||
},
|
||||
});
|
||||
const makeAssistantEntry = (turnId: string, id: string, createdAt: string) => ({
|
||||
id: `${id}-entry`,
|
||||
kind: "message" as const,
|
||||
createdAt,
|
||||
message: {
|
||||
id: id as never,
|
||||
role: "assistant" as const,
|
||||
text: `Response for ${turnId}`,
|
||||
turnId: turnId as never,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
streaming: false,
|
||||
},
|
||||
});
|
||||
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
makeImageEntry("turn-1", "image-view-1", "2026-01-01T00:00:01Z"),
|
||||
makeAssistantEntry("turn-1", "assistant-1", "2026-01-01T00:00:02Z"),
|
||||
makeImageEntry("turn-2", "image-view-2", "2026-01-01T00:00:03Z"),
|
||||
makeAssistantEntry("turn-2", "assistant-2", "2026-01-01T00:00:04Z"),
|
||||
],
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
expandedTurnIds: new Set(["turn-1" as never, "turn-2" as never]),
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
expect(
|
||||
rows.filter((row) => row.kind === "message").map((row) => row.assistantImageOutputs),
|
||||
).toMatchObject([
|
||||
[{ entry: { id: "image-view-1" }, imagePath }],
|
||||
[{ entry: { id: "image-view-2" }, imagePath }],
|
||||
]);
|
||||
});
|
||||
|
||||
it("only enables assistant copy for the terminal assistant message in a turn", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
|
||||
@@ -133,6 +133,11 @@ export type TimelineLatestTurn = Pick<
|
||||
"turnId" | "state" | "startedAt" | "completedAt"
|
||||
>;
|
||||
|
||||
export interface TimelineImageOutput {
|
||||
entry: WorkLogEntry;
|
||||
imagePath: string;
|
||||
}
|
||||
|
||||
export type MessagesTimelineRow =
|
||||
| {
|
||||
kind: "work";
|
||||
@@ -140,6 +145,12 @@ export type MessagesTimelineRow =
|
||||
createdAt: string;
|
||||
groupedEntries: WorkLogEntry[];
|
||||
}
|
||||
| {
|
||||
kind: "image-output";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
images: TimelineImageOutput[];
|
||||
}
|
||||
| {
|
||||
kind: "work-toggle";
|
||||
id: string;
|
||||
@@ -167,6 +178,7 @@ export type MessagesTimelineRow =
|
||||
showAssistantCopyButton: boolean;
|
||||
assistantCopyStreaming: boolean;
|
||||
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
|
||||
assistantImageOutputs?: TimelineImageOutput[] | undefined;
|
||||
revertTurnCount?: number | undefined;
|
||||
}
|
||||
| {
|
||||
@@ -247,6 +259,137 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
|
||||
return new Set(lastAssistantMessageIdByResponseKey.values());
|
||||
}
|
||||
|
||||
function appendImageOutputRows(input: {
|
||||
rows: ReadonlyArray<MessagesTimelineRow>;
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
unsettledTurnId: TurnId | null;
|
||||
}): MessagesTimelineRow[] {
|
||||
const outputsByTurnId = new Map<TurnId, TimelineImageOutput[]>();
|
||||
const unscopedOutputs: TimelineImageOutput[] = [];
|
||||
const seenImagePathsByTurnId = new Map<TurnId | null, Set<string>>();
|
||||
|
||||
for (const timelineEntry of input.timelineEntries) {
|
||||
if (timelineEntry.kind !== "work") {
|
||||
continue;
|
||||
}
|
||||
const entry = timelineEntry.entry;
|
||||
if (entry.itemType !== "image_view" || !entry.imagePath) {
|
||||
continue;
|
||||
}
|
||||
// Only skip images that belong to the in-flight turn; an unscoped entry
|
||||
// (null turnId) must still render when no turn is unsettled.
|
||||
if (input.unsettledTurnId !== null && entry.turnId === input.unsettledTurnId) {
|
||||
continue;
|
||||
}
|
||||
const turnId = entry.turnId ?? null;
|
||||
const seenImagePaths = seenImagePathsByTurnId.get(turnId) ?? new Set<string>();
|
||||
if (seenImagePaths.has(entry.imagePath)) {
|
||||
continue;
|
||||
}
|
||||
seenImagePaths.add(entry.imagePath);
|
||||
seenImagePathsByTurnId.set(turnId, seenImagePaths);
|
||||
const output = {
|
||||
entry,
|
||||
imagePath: entry.imagePath,
|
||||
};
|
||||
if (!entry.turnId) {
|
||||
unscopedOutputs.push(output);
|
||||
continue;
|
||||
}
|
||||
const existing = outputsByTurnId.get(entry.turnId);
|
||||
if (existing) {
|
||||
existing.push(output);
|
||||
} else {
|
||||
outputsByTurnId.set(entry.turnId, [output]);
|
||||
}
|
||||
}
|
||||
|
||||
if (outputsByTurnId.size === 0 && unscopedOutputs.length === 0) {
|
||||
return [...input.rows];
|
||||
}
|
||||
|
||||
const toRow = (
|
||||
id: string,
|
||||
images: TimelineImageOutput[],
|
||||
): Extract<MessagesTimelineRow, { kind: "image-output" }> => ({
|
||||
kind: "image-output",
|
||||
id,
|
||||
createdAt: images.at(-1)?.entry.createdAt ?? "",
|
||||
images,
|
||||
});
|
||||
const terminalRowIdByTurnId = new Map<TurnId, string>();
|
||||
const lastRowIdByTurnId = new Map<TurnId, string>();
|
||||
for (const row of input.rows) {
|
||||
if (row.kind === "turn-fold") {
|
||||
lastRowIdByTurnId.set(row.turnId, row.id);
|
||||
continue;
|
||||
}
|
||||
if (row.kind === "work") {
|
||||
for (const entry of row.groupedEntries) {
|
||||
if (entry.turnId) {
|
||||
lastRowIdByTurnId.set(entry.turnId, row.id);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (row.kind !== "message") {
|
||||
continue;
|
||||
}
|
||||
const message = row.message;
|
||||
if (message.role !== "assistant" || !message.turnId) {
|
||||
continue;
|
||||
}
|
||||
lastRowIdByTurnId.set(message.turnId, row.id);
|
||||
if (input.terminalAssistantMessageIds.has(message.id)) {
|
||||
terminalRowIdByTurnId.set(message.turnId, row.id);
|
||||
}
|
||||
}
|
||||
|
||||
const outputsAfterRowId = new Map<
|
||||
string,
|
||||
Array<Extract<MessagesTimelineRow, { kind: "image-output" }>>
|
||||
>();
|
||||
const outputsByAssistantRowId = new Map<string, TimelineImageOutput[]>();
|
||||
const trailingOutputs: Array<Extract<MessagesTimelineRow, { kind: "image-output" }>> = [];
|
||||
if (unscopedOutputs.length > 0) {
|
||||
trailingOutputs.push(toRow("image-output:unscoped", unscopedOutputs));
|
||||
}
|
||||
for (const [turnId, outputs] of outputsByTurnId) {
|
||||
const terminalRowId = terminalRowIdByTurnId.get(turnId);
|
||||
if (terminalRowId) {
|
||||
outputsByAssistantRowId.set(terminalRowId, outputs);
|
||||
continue;
|
||||
}
|
||||
const outputRow = toRow(`image-output:turn:${turnId}`, outputs);
|
||||
const targetRowId = lastRowIdByTurnId.get(turnId) ?? null;
|
||||
if (!targetRowId) {
|
||||
trailingOutputs.push(outputRow);
|
||||
continue;
|
||||
}
|
||||
// A grouped work row can cover several turns, so multiple turns may map to
|
||||
// the same target row — append rather than replacing the previous gallery.
|
||||
const existingOutputs = outputsAfterRowId.get(targetRowId);
|
||||
if (existingOutputs) {
|
||||
existingOutputs.push(outputRow);
|
||||
} else {
|
||||
outputsAfterRowId.set(targetRowId, [outputRow]);
|
||||
}
|
||||
}
|
||||
|
||||
return input.rows
|
||||
.flatMap((row) => [
|
||||
row.kind === "message" && outputsByAssistantRowId.has(row.id)
|
||||
? {
|
||||
...row,
|
||||
assistantImageOutputs: outputsByAssistantRowId.get(row.id),
|
||||
}
|
||||
: row,
|
||||
...(outputsAfterRowId.get(row.id) ?? []),
|
||||
])
|
||||
.concat(trailingOutputs);
|
||||
}
|
||||
|
||||
interface TurnFold {
|
||||
turnId: TurnId;
|
||||
anchorEntryId: string;
|
||||
@@ -563,15 +706,22 @@ export function deriveMessagesTimelineRows(input: {
|
||||
});
|
||||
}
|
||||
|
||||
const rowsWithImageOutputs = appendImageOutputRows({
|
||||
rows: nextRows,
|
||||
timelineEntries: input.timelineEntries,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
});
|
||||
|
||||
if (input.isWorking) {
|
||||
nextRows.push({
|
||||
rowsWithImageOutputs.push({
|
||||
kind: "working",
|
||||
id: "working-indicator-row",
|
||||
createdAt: input.activeTurnStartedAt,
|
||||
});
|
||||
}
|
||||
|
||||
return nextRows;
|
||||
return rowsWithImageOutputs;
|
||||
}
|
||||
|
||||
export function computeStableMessagesTimelineRows(
|
||||
@@ -594,6 +744,21 @@ export function computeStableMessagesTimelineRows(
|
||||
return anyChanged ? { byId: next, result } : previous;
|
||||
}
|
||||
|
||||
function imageOutputsEqual(
|
||||
a: ReadonlyArray<TimelineImageOutput> | undefined,
|
||||
b: ReadonlyArray<TimelineImageOutput> | undefined,
|
||||
): boolean {
|
||||
const aImages = a ?? [];
|
||||
const bImages = b ?? [];
|
||||
return (
|
||||
aImages.length === bImages.length &&
|
||||
aImages.every(
|
||||
(image, index) =>
|
||||
image.entry === bImages[index]?.entry && image.imagePath === bImages[index]?.imagePath,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** Shallow field comparison per row variant — avoids deep equality cost. */
|
||||
function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
|
||||
if (a.kind !== b.kind || a.id !== b.id) return false;
|
||||
@@ -610,6 +775,11 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
case "proposed-plan":
|
||||
return a.proposedPlan === (b as typeof a).proposedPlan;
|
||||
|
||||
case "image-output": {
|
||||
const bi = b as typeof a;
|
||||
return imageOutputsEqual(a.images, bi.images);
|
||||
}
|
||||
|
||||
case "work":
|
||||
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
|
||||
|
||||
@@ -633,6 +803,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
a.showAssistantCopyButton === bm.showAssistantCopyButton &&
|
||||
a.assistantCopyStreaming === bm.assistantCopyStreaming &&
|
||||
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
|
||||
imageOutputsEqual(a.assistantImageOutputs, bm.assistantImageOutputs) &&
|
||||
a.revertTurnCount === bm.revertTurnCount
|
||||
);
|
||||
}
|
||||
|
||||
@@ -122,6 +122,14 @@ vi.mock("@pierre/diffs/react", () => {
|
||||
return { FileDiff: MockFileDiff };
|
||||
});
|
||||
|
||||
vi.mock("~/assets/assetUrls", () => ({
|
||||
useAssetUrlStates: (_environmentId: unknown, resources: ReadonlyArray<unknown>) =>
|
||||
resources.map(() => ({
|
||||
_tag: "Success",
|
||||
url: "https://environment.example/api/assets/image-token/tool-output.png",
|
||||
})),
|
||||
}));
|
||||
|
||||
function matchMedia() {
|
||||
return {
|
||||
matches: false,
|
||||
@@ -655,4 +663,109 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).toContain("lucide-x");
|
||||
expect(markup).toContain('aria-label="Tool call failed"');
|
||||
});
|
||||
|
||||
it("renders deduplicated image view output as a compact gallery row", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const assistantMessageId = MessageId.make("assistant-final");
|
||||
const turnId = TurnId.make("turn-image-view");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
workspaceRoot="/repo"
|
||||
turnDiffSummaryByAssistantMessageId={
|
||||
new Map([
|
||||
[
|
||||
assistantMessageId,
|
||||
{
|
||||
turnId,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: CheckpointRef.make("checkpoint-image-view"),
|
||||
status: "ready",
|
||||
files: [{ path: "image.ts", kind: "modified", additions: 2, deletions: 1 }],
|
||||
assistantMessageId,
|
||||
completedAt: "2026-03-17T19:12:30.000Z",
|
||||
},
|
||||
],
|
||||
])
|
||||
}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-image-view",
|
||||
kind: "work",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
entry: {
|
||||
id: "image-view-complete",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
turnId,
|
||||
label: "Image view",
|
||||
tone: "tool",
|
||||
itemType: "image_view",
|
||||
imagePath: "/tmp/tool-output.png",
|
||||
toolLifecycleStatus: "completed",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "entry-image-view-duplicate",
|
||||
kind: "work",
|
||||
createdAt: "2026-03-17T19:12:28.100Z",
|
||||
entry: {
|
||||
id: "image-view-duplicate",
|
||||
createdAt: "2026-03-17T19:12:28.100Z",
|
||||
turnId,
|
||||
label: "Image view",
|
||||
tone: "tool",
|
||||
itemType: "image_view",
|
||||
imagePath: "/tmp/tool-output.png",
|
||||
toolLifecycleStatus: "completed",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "entry-image-view-second",
|
||||
kind: "work",
|
||||
createdAt: "2026-03-17T19:12:28.200Z",
|
||||
entry: {
|
||||
id: "image-view-second",
|
||||
createdAt: "2026-03-17T19:12:28.200Z",
|
||||
turnId,
|
||||
label: "Image view",
|
||||
tone: "tool",
|
||||
itemType: "image_view",
|
||||
imagePath: "/tmp/second-output.png",
|
||||
toolLifecycleStatus: "completed",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "entry-assistant-final",
|
||||
kind: "message",
|
||||
createdAt: "2026-03-17T19:12:29.000Z",
|
||||
message: {
|
||||
id: assistantMessageId,
|
||||
role: "assistant",
|
||||
text: "Here is the generated image.",
|
||||
turnId,
|
||||
createdAt: "2026-03-17T19:12:29.000Z",
|
||||
updatedAt: "2026-03-17T19:12:30.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-image-view-activity-id="image-view-complete"');
|
||||
expect(markup).not.toContain('data-image-view-activity-id="image-view-duplicate"');
|
||||
expect(markup).toContain('data-image-view-activity-id="image-view-second"');
|
||||
expect(markup).toContain('aria-label="Image outputs"');
|
||||
expect(markup).toContain("size-32");
|
||||
expect(markup).toContain(
|
||||
'src="https://environment.example/api/assets/image-token/tool-output.png"',
|
||||
);
|
||||
expect(markup).toContain('aria-label="Preview tool-output.png"');
|
||||
expect(markup).toContain('aria-label="Preview second-output.png"');
|
||||
const responseIndex = markup.indexOf("Here is the generated image.");
|
||||
const imageIndex = markup.indexOf('data-image-view-activity-id="image-view-complete"');
|
||||
const changedFilesIndex = markup.indexOf("1 changed file");
|
||||
expect(responseIndex).toBeLessThan(imageIndex);
|
||||
expect(imageIndex).toBeLessThan(changedFilesIndex);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
EventId,
|
||||
type EnvironmentId,
|
||||
type MessageId,
|
||||
type ScopedThreadRef,
|
||||
@@ -77,6 +78,7 @@ import {
|
||||
resolveTimelineMinimapInteractiveWidth,
|
||||
resolveTimelineMinimapTopPercent,
|
||||
type StableMessagesTimelineRowsState,
|
||||
type TimelineImageOutput,
|
||||
type MessagesTimelineRow,
|
||||
TIMELINE_MINIMAP_MIN_ITEMS,
|
||||
type TimelineLatestTurn,
|
||||
@@ -96,6 +98,7 @@ import {
|
||||
type ParsedPreviewAnnotation,
|
||||
} from "~/lib/previewAnnotation";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { useAssetUrlStates, type AssetUrlState } from "~/assets/assetUrls";
|
||||
import { useUiStateStore } from "~/uiStateStore";
|
||||
import { type TimestampFormat } from "@t3tools/contracts/settings";
|
||||
import { formatChatTimestampTooltip, formatShortTimestamp } from "../../timestampFormat";
|
||||
@@ -856,6 +859,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
{row.kind === "work" ? <WorkGroupSection groupedEntries={row.groupedEntries} /> : null}
|
||||
{row.kind === "work-toggle" ? <WorkGroupToggleTimelineRow row={row} /> : null}
|
||||
{row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
|
||||
{row.kind === "image-output" ? <ImageOutputTimelineRow row={row} /> : null}
|
||||
{row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
|
||||
{row.kind === "message" && row.message.role === "assistant" ? (
|
||||
<AssistantTimelineRow row={row} />
|
||||
@@ -1029,6 +1033,13 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
|
||||
isStreaming={Boolean(row.message.streaming)}
|
||||
skills={ctx.skills}
|
||||
/>
|
||||
{ctx.threadRef && row.assistantImageOutputs?.length ? (
|
||||
<ImageOutputGallery
|
||||
images={row.assistantImageOutputs}
|
||||
threadRef={ctx.threadRef}
|
||||
className="mt-3"
|
||||
/>
|
||||
) : null}
|
||||
<AssistantChangedFilesSection
|
||||
turnSummary={row.assistantTurnDiffSummary}
|
||||
routeThreadKey={ctx.routeThreadKey}
|
||||
@@ -1921,6 +1932,135 @@ function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {
|
||||
|
||||
const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation();
|
||||
|
||||
function imageFileName(path: string): string {
|
||||
return path.split(/[\\/]/).at(-1) || "Image";
|
||||
}
|
||||
|
||||
function ImageOutputTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "image-output" }> }) {
|
||||
const { threadRef } = use(TimelineRowCtx);
|
||||
if (!threadRef) return null;
|
||||
return <ImageOutputGallery images={row.images} threadRef={threadRef} />;
|
||||
}
|
||||
|
||||
function ImageOutputGallery({
|
||||
images,
|
||||
threadRef,
|
||||
className,
|
||||
}: {
|
||||
images: TimelineImageOutput[];
|
||||
threadRef: ScopedThreadRef;
|
||||
className?: string;
|
||||
}) {
|
||||
const { activeThreadEnvironmentId, onImageExpand } = use(TimelineRowCtx);
|
||||
const resources = useMemo(
|
||||
() =>
|
||||
images.map((image) => ({
|
||||
_tag: "thread-image" as const,
|
||||
threadId: threadRef.threadId,
|
||||
activityId: EventId.make(image.entry.imageActivityId ?? image.entry.id),
|
||||
})),
|
||||
[images, threadRef.threadId],
|
||||
);
|
||||
const assetUrls = useAssetUrlStates(activeThreadEnvironmentId, resources);
|
||||
const [failedUrls, setFailedUrls] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const previewImages = useMemo(
|
||||
() =>
|
||||
images.map((image, index) => {
|
||||
const assetUrl = assetUrls[index];
|
||||
return {
|
||||
id: image.entry.id,
|
||||
name: imageFileName(image.imagePath),
|
||||
...(assetUrl?._tag === "Success" && !failedUrls.has(assetUrl.url)
|
||||
? { previewUrl: assetUrl.url }
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
[assetUrls, failedUrls, images],
|
||||
);
|
||||
const handleImageFailure = useCallback((url: string) => {
|
||||
setFailedUrls((current) => {
|
||||
if (current.has(url)) return current;
|
||||
const next = new Set(current);
|
||||
next.add(url);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
const handleImageExpand = useCallback(
|
||||
(imageId: string) => {
|
||||
const preview = buildExpandedImagePreview(previewImages, imageId);
|
||||
if (preview) onImageExpand(preview);
|
||||
},
|
||||
[onImageExpand, previewImages],
|
||||
);
|
||||
|
||||
return (
|
||||
<article
|
||||
className={cn("flex max-w-full items-start gap-2 overflow-x-auto px-1 pb-1", className)}
|
||||
aria-label={images.length === 1 ? "Image output" : "Image outputs"}
|
||||
>
|
||||
{images.map((image, index) => (
|
||||
<ImageOutputThumbnail
|
||||
key={image.imagePath}
|
||||
image={image}
|
||||
assetUrl={assetUrls[index] ?? { _tag: "Loading" }}
|
||||
failedUrls={failedUrls}
|
||||
onImageFailure={handleImageFailure}
|
||||
onImageExpand={handleImageExpand}
|
||||
/>
|
||||
))}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
function ImageOutputThumbnail({
|
||||
image,
|
||||
assetUrl,
|
||||
failedUrls,
|
||||
onImageFailure,
|
||||
onImageExpand,
|
||||
}: {
|
||||
image: TimelineImageOutput;
|
||||
assetUrl: AssetUrlState;
|
||||
failedUrls: ReadonlySet<string>;
|
||||
onImageFailure: (url: string) => void;
|
||||
onImageExpand: (imageId: string) => void;
|
||||
}) {
|
||||
const imageName = imageFileName(image.imagePath);
|
||||
const loadedUrl =
|
||||
assetUrl._tag === "Success" && !failedUrls.has(assetUrl.url) ? assetUrl.url : null;
|
||||
const failed =
|
||||
assetUrl._tag === "Failure" || (assetUrl._tag === "Success" && failedUrls.has(assetUrl.url));
|
||||
|
||||
return (
|
||||
<div className="shrink-0" data-image-view-activity-id={image.entry.id}>
|
||||
{loadedUrl ? (
|
||||
<button
|
||||
type="button"
|
||||
className="block size-32 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 ${imageName}`}
|
||||
onClick={() => onImageExpand(image.entry.id)}
|
||||
>
|
||||
<img
|
||||
src={loadedUrl}
|
||||
alt={imageName}
|
||||
className="block size-full rounded-md object-contain"
|
||||
onError={() => onImageFailure(loadedUrl)}
|
||||
/>
|
||||
</button>
|
||||
) : failed ? (
|
||||
<div className="flex size-32 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>
|
||||
) : (
|
||||
<div
|
||||
className="size-32 animate-pulse rounded-xl border border-border/50 bg-muted/35"
|
||||
aria-label={`Loading ${imageName}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
workEntry: TimelineWorkEntry;
|
||||
workspaceRoot: string | undefined;
|
||||
|
||||
@@ -995,6 +995,111 @@ describe("deriveWorkLogEntries", () => {
|
||||
expect(entry?.toolData).toEqual(item);
|
||||
});
|
||||
|
||||
it("extracts the local path from completed image view activities", () => {
|
||||
const imagePath = "/tmp/codex-preview.png";
|
||||
const [entry] = deriveWorkLogEntries([
|
||||
makeActivity({
|
||||
id: "image-view-complete",
|
||||
kind: "tool.completed",
|
||||
summary: "Image view",
|
||||
payload: {
|
||||
itemType: "image_view",
|
||||
status: "completed",
|
||||
title: "Image view",
|
||||
detail: imagePath,
|
||||
data: {
|
||||
item: {
|
||||
id: "call-image-1",
|
||||
path: imagePath,
|
||||
type: "imageView",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(entry).toMatchObject({
|
||||
id: "image-view-complete",
|
||||
itemType: "image_view",
|
||||
imagePath,
|
||||
toolLifecycleStatus: "completed",
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts the saved path from completed image generation activities", () => {
|
||||
const imagePath = "/Users/test/.codex/generated_images/thread-1/generated.png";
|
||||
const [entry] = deriveWorkLogEntries([
|
||||
makeActivity({
|
||||
id: "image-generation-complete",
|
||||
kind: "tool.completed",
|
||||
summary: "Image view",
|
||||
payload: {
|
||||
itemType: "image_view",
|
||||
data: {
|
||||
item: {
|
||||
id: "call-image-generation-1",
|
||||
result: "base64-image-data",
|
||||
revisedPrompt: "A generated image",
|
||||
savedPath: imagePath,
|
||||
status: "completed",
|
||||
type: "imageGeneration",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(entry).toMatchObject({
|
||||
id: "image-generation-complete",
|
||||
itemType: "image_view",
|
||||
imagePath,
|
||||
toolLifecycleStatus: "completed",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the image activity id paired with the path when collapsing entries", () => {
|
||||
const imagePath = "/tmp/codex-preview.png";
|
||||
const entries = deriveWorkLogEntries([
|
||||
makeActivity({
|
||||
id: "image-view-with-path",
|
||||
kind: "tool.updated",
|
||||
summary: "Image view",
|
||||
payload: {
|
||||
itemType: "image_view",
|
||||
status: "in_progress",
|
||||
title: "Image view",
|
||||
data: {
|
||||
toolCallId: "call-image-1",
|
||||
item: { id: "call-image-1", path: imagePath, type: "imageView" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
// The completion for the same tool call carries no path; collapsing
|
||||
// adopts its id, so the path's owning activity id must be retained.
|
||||
makeActivity({
|
||||
id: "image-view-without-path",
|
||||
kind: "tool.completed",
|
||||
summary: "Image view",
|
||||
payload: {
|
||||
itemType: "image_view",
|
||||
status: "completed",
|
||||
title: "Image view",
|
||||
data: {
|
||||
toolCallId: "call-image-1",
|
||||
item: { id: "call-image-1", type: "imageView" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]).toMatchObject({
|
||||
id: "image-view-without-path",
|
||||
imagePath,
|
||||
imageActivityId: "image-view-with-path",
|
||||
});
|
||||
});
|
||||
|
||||
it("unwraps PowerShell command wrappers for displayed command text", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
|
||||
@@ -69,6 +69,13 @@ export interface WorkLogEntry {
|
||||
command?: string;
|
||||
rawCommand?: string;
|
||||
changedFiles?: ReadonlyArray<string>;
|
||||
imagePath?: string;
|
||||
/**
|
||||
* Activity that carried `imagePath`. Collapsing can merge a later activity's
|
||||
* `id` onto an earlier activity's `imagePath`, and the asset lookup resolves
|
||||
* the path from this activity's payload — so it must stay paired with it.
|
||||
*/
|
||||
imageActivityId?: string;
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
toolTitle?: string;
|
||||
toolData?: unknown;
|
||||
@@ -740,6 +747,20 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
entry.toolData = data.item;
|
||||
}
|
||||
}
|
||||
if (itemType === "image_view") {
|
||||
const data = asRecord(payload?.data);
|
||||
const item = asRecord(data?.item);
|
||||
const imagePath =
|
||||
item?.type === "imageView"
|
||||
? asTrimmedString(item.path)
|
||||
: item?.type === "imageGeneration"
|
||||
? asTrimmedString(item.savedPath)
|
||||
: null;
|
||||
if (imagePath) {
|
||||
entry.imagePath = imagePath;
|
||||
entry.imageActivityId = entry.id;
|
||||
}
|
||||
}
|
||||
if (itemType) {
|
||||
entry.itemType = itemType;
|
||||
}
|
||||
@@ -811,6 +832,11 @@ function mergeDerivedWorkLogEntries(
|
||||
const detail = next.detail ?? previous.detail;
|
||||
const command = next.command ?? previous.command;
|
||||
const rawCommand = next.rawCommand ?? previous.rawCommand;
|
||||
// Keep the owning activity id paired with the path it came from.
|
||||
const imagePath = next.imagePath ?? previous.imagePath;
|
||||
const imageActivityId = next.imagePath
|
||||
? (next.imageActivityId ?? next.id)
|
||||
: (previous.imageActivityId ?? previous.id);
|
||||
const toolTitle = next.toolTitle ?? previous.toolTitle;
|
||||
const itemType = next.itemType ?? previous.itemType;
|
||||
const requestKind = next.requestKind ?? previous.requestKind;
|
||||
@@ -824,6 +850,7 @@ function mergeDerivedWorkLogEntries(
|
||||
...(detail ? { detail } : {}),
|
||||
...(command ? { command } : {}),
|
||||
...(rawCommand ? { rawCommand } : {}),
|
||||
...(imagePath ? { imagePath, imageActivityId } : {}),
|
||||
...(changedFiles.length > 0 ? { changedFiles } : {}),
|
||||
...(toolTitle ? { toolTitle } : {}),
|
||||
...(itemType ? { itemType } : {}),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { EventId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
|
||||
const ASSET_PATH_MAX_LENGTH = 1024;
|
||||
|
||||
@@ -12,6 +12,14 @@ export const AssetResource = Schema.Union([
|
||||
Schema.TaggedStruct("attachment", {
|
||||
attachmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),
|
||||
}),
|
||||
/** A file in the server's browser-artifacts directory (screenshots/recordings). */
|
||||
Schema.TaggedStruct("browser-artifact", {
|
||||
fileName: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),
|
||||
}),
|
||||
Schema.TaggedStruct("thread-image", {
|
||||
threadId: ThreadId,
|
||||
activityId: EventId,
|
||||
}),
|
||||
Schema.TaggedStruct("project-favicon", {
|
||||
cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
|
||||
}),
|
||||
@@ -83,7 +91,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 +141,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 +232,9 @@ export const AssetAccessError = Schema.Union([
|
||||
AssetWorkspaceAssetNotFoundError,
|
||||
AssetWorkspaceResolutionError,
|
||||
AssetAttachmentNotFoundError,
|
||||
AssetBrowserArtifactNotFoundError,
|
||||
AssetThreadImageNotFoundError,
|
||||
AssetThreadImageResolutionError,
|
||||
AssetProjectFaviconResolutionError,
|
||||
AssetProjectFaviconInspectionError,
|
||||
AssetProjectFaviconNotFoundError,
|
||||
|
||||
@@ -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 (e.g. ) so the human sees the screenshot in chat. Preferred for before/after evidence of UI work. Cannot be combined with savePath.";
|
||||
|
||||
const SNAPSHOT_SAVE_PATH_DESCRIPTION =
|
||||
"Optional workspace-relative file path ending in .png. Use only when the screenshot should live inside the repo (e.g. committed docs or fixtures); prefer save:true for chat evidence. The file is written into the thread workspace and can be embedded with markdown image syntax, e.g. .";
|
||||
|
||||
export const PreviewAutomationSnapshotInput = Schema.Struct({
|
||||
...PreviewAutomationTabTargetFields,
|
||||
save: Schema.optional(
|
||||
Schema.Boolean.annotate({ description: 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,
|
||||
}),
|
||||
/** Workspace-relative path the screenshot was also written to, when savePath was requested. */
|
||||
savedScreenshotPath: Schema.optional(Schema.String),
|
||||
});
|
||||
export type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;
|
||||
|
||||
@@ -861,6 +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,63 @@ describe("workspace file previews", () => {
|
||||
expect(isWorkspacePreviewEntryPath(path)).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
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