fix: render workspace images in chat markdown #6433
MergedSunkenInTime(GitHub profile, opens in a new tab)merged 9 commits into
main fromrefs/pull/6433/headmerged by maria-rcks View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/mobile/src/features/threads/ThreadFeed.tsx line 218Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -195,0 +229,21 @@229+/** Markdown image whose src is a workspace file — loads through a signed asset URL. */230+function ThreadMarkdownImage(props: {231+ readonly environmentId: EnvironmentId;232+ readonly threadId: ThreadId;233+ readonly path: string;234+ readonly alt: string | null;235+ readonly onPressImage: (uri: string) => void;236+}) {237+ const colorScheme = useColorScheme();238+ const palette = MARKDOWN_COLORS[colorScheme === "light" ? "light" : "dark"];239+ const [failedUri, setFailedUri] = useState<string | null>(null);240+ const uri = useAssetUrl(props.environmentId, {241+ _tag: "workspace-file",242+ threadId: props.threadId,243+ path: props.path,244+ });245+ const failed = uri !== null && failedUri === uri;246+247+ return (248+ <View style={{ gap: 6 }}>249+ {uri === null || failed ? (apps/mobile/src/features/threads/ThreadFeed.tsx line 1567OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1440,4 +1558,10 @@14401558 },14411559 [props.environmentId, props.threadId, props.workspaceRoot, navigation],14421560 );1443- const markdownStyles = useMarkdownStyles(onMarkdownLinkPress);1561+ const renderMarkdownImage = useCallback<MarkdownImageRenderer>(1562+ (image) => {1563+ // Remote URIs load fine in a plain RN Image — keep the module fallback.1564+ if (REMOTE_IMAGE_SRC_PATTERN.test(image.href)) {1565+ return null;1566+ }1567+ const path = markdownImageWorkspacePath(image.href, props.workspaceRoot ?? null);apps/mobile/src/features/threads/ThreadFeed.tsx line 713Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -654,3 +757,4 @@654757 })}655758 </View>656759 ),760+ image: ({ node }) =>apps/mobile/src/features/threads/ThreadFeed.tsx lines 206 to 211OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -193,3 +194,18 @@193194 );194195 }195196197+const REMOTE_IMAGE_SRC_PATTERN = /^https?:\/\//i;198+const NON_FILE_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/;199+200+/**201+ * Absolute filesystem path for a markdown image src, or null when the src is202+ * not a workspace file (remote URL, other scheme, or a relative path with no203+ * workspace root to resolve against).204+ */205+function markdownImageWorkspacePath(href: string, workspaceRoot: string | null): string | null {206+ let path = href.replace(/^file:\/\//i, "");207+ try {208+ path = decodeURIComponent(path);209+ } catch {210+ // Keep the raw path when it is not valid percent-encoding.211+ }apps/web/src/components/ChatMarkdown.tsx line 1704OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1642,3 +1695,10 @@16421695 </code>16431696 );16441697 },1698+ img({ node: _node, src, alt, ...props }) {1699+ const srcString = typeof src === "string" ? normalizeMarkdownLinkDestination(src) : "";1700+ const altText = alt ?? "";1701+ if (srcString.length === 0) {1702+ return <ChatMarkdownImageFallback alt={altText} />;1703+ }1704+ if (!DIRECTLY_LOADABLE_IMAGE_SRC_PATTERN.test(srcString)) {
- apps/mobile/src/features/threads/ThreadFeed.tsx line 720Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -654,3 +757,11 @@654757 })}655758 </View>656759 ),760+ image: ({ node }) =>761+ node.href762+ ? (renderImage({763+ href: node.href,764+ alt: node.alt ?? null,765+ title: node.title ?? null,766+ }) ?? undefined)767+ : undefined,apps/mobile/src/features/threads/ThreadFeed.tsx line 233Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -195,0 +244,21 @@244+ });245+ const failed = uri !== null && failedUri === uri;246+247+ return (248+ <View style={{ gap: 6 }}>249+ {uri === null || failed ? (250+ <View251+ style={{252+ width: "100%",253+ aspectRatio: 16 / 9,254+ borderRadius: 10,255+ backgroundColor: palette.codeBackground,256+ alignItems: "center",257+ justifyContent: "center",258+ }}259+ >260+ {failed ? (261+ <Text className="text-xs text-foreground-muted">Image unavailable</Text>262+ ) : (263+ <ActivityIndicator />264+ )}apps/mobile/src/features/threads/ThreadFeed.tsx line 221OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -195,0 +201,21 @@201+ * Absolute filesystem path for a markdown image src, or null when the src is202+ * not a workspace file (remote URL, other scheme, or a relative path with no203+ * workspace root to resolve against).204+ */205+function markdownImageWorkspacePath(href: string, workspaceRoot: string | null): string | null {206+ let path = href.replace(/^file:\/\//i, "");207+ try {208+ path = decodeURIComponent(path);209+ } catch {210+ // Keep the raw path when it is not valid percent-encoding.211+ }212+ if (path.length === 0) {213+ return null;214+ }215+ const isAbsolute =216+ path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\");217+ if (!isAbsolute && NON_FILE_SCHEME_PATTERN.test(path)) {218+ return null;219+ }220+ if (isAbsolute) {221+ return path;
- apps/web/src/components/ChatMarkdown.tsx lines 989 to 990OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -919,0 +970,21 @@970+const ChatMarkdownWorkspaceImage = memo(function ChatMarkdownWorkspaceImage(props: {971+ readonly threadRef: ScopedThreadRef;972+ readonly path: string;973+ readonly alt: string;974+}) {975+ const assetUrl = useAssetUrlState(props.threadRef.environmentId, {976+ _tag: "workspace-file",977+ threadId: props.threadRef.threadId,978+ path: props.path,979+ });980+ const [failedUrl, setFailedUrl] = useState<string | null>(null);981+982+ if (assetUrl._tag === "Failure" || (assetUrl._tag === "Success" && failedUrl === assetUrl.url)) {983+ return <ChatMarkdownImageFallback alt={props.alt} />;984+ }985+ if (assetUrl._tag !== "Success") {986+ return (987+ <span988+ aria-label="Loading image"989+ className="my-1 block aspect-video w-full max-w-md animate-pulse rounded-lg bg-muted/60"990+ />apps/web/src/components/ChatMarkdown.tsx lines 1736 to 1747OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1642,3 +1727,21 @@16421727 </code>16431728 );16441729 },1730+ img({ node: _node, src, alt, ...props }) {1731+ const srcString = typeof src === "string" ? normalizeMarkdownLinkDestination(src) : "";1732+ const altText = alt ?? "";1733+ if (srcString.length === 0) {1734+ return <ChatMarkdownImageFallback alt={altText} />;1735+ }1736+ if (!DIRECTLY_LOADABLE_IMAGE_SRC_PATTERN.test(srcString)) {1737+ // Agents reference screenshots they saved into the workspace by path1738+ // (relative, absolute, or file://); those bytes only exist on the1739+ // environment host, so they load through a signed asset URL.1740+ const fileMeta = resolveMarkdownFileLinkMeta(srcString, cwd);1741+ if (fileMeta && threadRef) {1742+ return (1743+ <ChatMarkdownWorkspaceImage1744+ threadRef={threadRef}1745+ path={fileMeta.filePath}1746+ alt={altText}1747+ />
- apps/web/src/components/ChatMarkdown.tsx line 1837OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1731,0 +1817,21 @@1817+ const srcString = typeof src === "string" ? normalizeMarkdownLinkDestination(src) : "";1818+ const altText = alt ?? "";1819+ if (srcString.length === 0) {1820+ return <ChatMarkdownImageFallback alt={altText} />;1821+ }1822+ if (!DIRECTLY_LOADABLE_IMAGE_SRC_PATTERN.test(srcString)) {1823+ // Agents reference screenshots they saved into the workspace by path1824+ // (relative, absolute, or file://); those bytes only exist on the1825+ // environment host, so they load through a signed asset URL.1826+ const fileMeta = resolveMarkdownFileLinkMeta(srcString, cwd);1827+ if (fileMeta && threadRef) {1828+ return (1829+ <ChatMarkdownWorkspaceImage1830+ threadRef={threadRef}1831+ path={fileMeta.filePath}1832+ alt={altText}1833+ />1834+ );1835+ }1836+ }1837+ return <img {...props} src={srcString} alt={altText} loading="lazy" />;
- apps/web/src/markdown-links.ts lines 88 to 90OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -85,4 +85,6 @@8585 const parsed = new URL(href);8686 if (parsed.protocol.toLowerCase() !== "file:") return null;878788- const rawPath = parsed.pathname;88+ const rawPath = parsed.hostname89+ ? `\\\\${parsed.hostname}${parsed.pathname.replaceAll("/", "\\")}`90+ : parsed.pathname;
- packages/client-runtime/src/markdownImages.ts line 90Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +66,21 @@66+ workspaceRoot?: string | null,67+): MarkdownImageSource {68+ if (value === null || value === undefined) return { _tag: "Blocked" };69+70+ const source = normalizeSource(value);71+ if (source.length === 0 || source.startsWith("#") || source.startsWith("?")) {72+ return { _tag: "Blocked" };73+ }74+ if (DIRECT_IMAGE_SOURCE_PATTERN.test(source)) {75+ return { _tag: "Direct", uri: source };76+ }77+78+ if (/^file:/i.test(source)) {79+ const path = parseFileUrl(source);80+ return path === null ? { _tag: "Blocked" } : { _tag: "WorkspaceFile", path };81+ }82+83+ const path = safeDecode(stripSearchAndHash(source));84+ if (path.length === 0) return { _tag: "Blocked" };85+ if (path.startsWith("/") || WINDOWS_DRIVE_PATH_PATTERN.test(path) || path.startsWith("\\\\")) {86+ return { _tag: "WorkspaceFile", path };
- @@ -950,3 +984,5 @@950984 );951985 });952986987+const CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME =988+ "h-auto w-auto max-h-[30rem] max-w-[min(100%,30rem)] object-contain";
maria-rcks merged this77c9d1e
maria-rcks closed this
Sign in to join this conversation.


No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
1d256c6e-97bc-43ab-8f7a-d359c6f1e887📥 Commits
Reviewing files that changed from the base of the PR and between c2dcbb798ef1c625890efa004e9e4410d5e1fcfe and f2f79bd4ac0b70e03f1351a9a2c683a190ec6d79.
📒 Files selected for processing (3)
apps/web/src/components/ChatMarkdown.workspace-images.test.tsxapps/web/src/markdown-links.test.tsapps/web/src/markdown-links.ts🚧 Files skipped from review as they are similar to previous changes (1)
📝 Walkthrough
Walkthrough#
The change adds a shared Markdown image-renderer contract. Mobile and web Markdown components now resolve workspace image paths through signed asset URLs, display loading or failure states, and preserve fallback rendering for unsupported sources.
Changes#
Workspace Markdown Image Rendering
apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.types.ts,apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsxapps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.ios.tsx,apps/mobile/modules/t3-markdown-text/src/SelectableMarkdownText.tsx,apps/mobile/src/native/SelectableMarkdownText.*renderImageprop, provides it through context, and re-exports the image-rendering types.apps/mobile/src/features/threads/ThreadFeed.tsx,apps/mobile/src/state/assets.tsapps/web/src/components/ChatMarkdown.tsx,apps/web/src/components/ChatMarkdown.workspace-images.test.tsx,apps/web/src/markdown-links.ts,apps/web/src/markdown-links.test.tsEstimated code review effort: 4 (Complex) | ~60 minutes
Merge Risk: 🟡 Moderate · up to
f2f79The PR adds workspace-image rendering across web and mobile, but UNC file paths may still resolve to the wrong asset and cause images to render incorrectly; the loading placeholder also adds avoidable continuous animation overhead. Merge should wait for the path-handling issue to be fixed or explicitly accepted.
Sequence Diagram(s)#
Suggested reviewers:
juliusmarminge🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
✨ Finishing Touches 💡 2
⚔️ Resolve merge conflicts 💡
🛠️ Fix failing CI checks 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share