Skip to content

Commit b14b353

Browse files
VikasMaur-2ndclaude
andcommitted
fix(web): dark-mode <picture> images load instead of showing "Image unavailable"
A Markdown `<picture>` with a `(prefers-color-scheme: dark)` source, the pattern GitHub documents for theme-aware README images, showed "Image unavailable" in dark mode. The renderer resolves an `<img>`'s `src` (workspace files, host media), but the browser picked the `<source>`'s raw `srcset` and loaded it against the app's own origin. The shared pipeline now moves each color-scheme source onto the `<img>` (through the same protocol check as `src`) and drops the sources. The renderer picks the variant for the current theme and resolves it like any other image, and guest shares allow both variants. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c677d5f commit b14b353

4 files changed

Lines changed: 93 additions & 5 deletions

File tree

‎apps/server/src/guest/guestAttachments.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ describe("guest host images", () => {
1616
["![a](file:///w/url%20form.png)", "/w/url form.png", "image/png"],
1717
["![a](C:\\w\\win.png)", "C:\\w\\win.png", "image/png"],
1818
["![a][r]\n\n[r]: C:\\w\\ref.png", "C:/w/ref.png", "image/png"],
19+
[
20+
'<picture><source media="(prefers-color-scheme: dark)" srcset="/w/dark.png"><img src="/w/light.png"></picture>',
21+
"/w/dark.png",
22+
"image/png",
23+
],
1924
// Shown as a link, in code, or not at all: the guest sees no image, so none loads.
2025
["[a](/w/link.png)", "/w/link.png", null],
2126
["```\n![a](/w/code.png)\n```", "/w/code.png", null],

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1352,6 +1352,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
13521352
workspaceMutationId,
13531353
renderContextReference,
13541354
fileLinkChip,
1355+
resolvedTheme,
13551356
} = use(ChatMarkdownRendererContext);
13561357
const imageExpand = use(MarkdownLinkContext) ? undefined : expandMedia;
13571358
const contextReference = typeof src === "string" ? parseComposerContextHref(src) : null;
@@ -1363,10 +1364,13 @@ const CHAT_MARKDOWN_COMPONENTS = {
13631364
<span>{label}</span>
13641365
);
13651366
}
1366-
const localSrc = node?.properties?.dataLocalSrc;
1367+
// A `<picture>`'s source for this theme, resolved like any other image.
1368+
const themeSrc = node?.properties?.[resolvedTheme === "dark" ? "dataDarkSrc" : "dataLightSrc"];
1369+
const localSrc = typeof themeSrc === "string" ? undefined : node?.properties?.dataLocalSrc;
13671370
const markdownTitle = node?.properties?.dataMarkdownTitle;
13681371
const standalone = node?.properties?.dataStandalone === true;
1369-
const authoredSrc = typeof localSrc === "string" ? localSrc : src;
1372+
const authoredSrc =
1373+
typeof themeSrc === "string" ? themeSrc : typeof localSrc === "string" ? localSrc : src;
13701374
const authoredTitle = typeof markdownTitle === "string" ? markdownTitle : title;
13711375
const srcString =
13721376
typeof authoredSrc === "string" ? normalizeMarkdownLinkDestination(authoredSrc) : "";

‎packages/shared/src/markdownPipeline.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,37 @@ it("keeps an image on its own line under a label but leaves inline images inline
8686
expect(render("Built [![CI](/ci.svg)](/ci)\nand wrapped")).toBe("Built <img>\nand wrapped");
8787
expect(render("Hard-wrapped\nprose")).toBe("Hard-wrapped\nprose");
8888
});
89+
90+
it("moves a <picture>'s color-scheme sources onto its <img>, which the renderer resolves", () => {
91+
const processor = unified()
92+
.use(remarkParse)
93+
.use(CHAT_MARKDOWN_REMARK_PLUGINS)
94+
.use(remarkRehype, { allowDangerousHtml: true })
95+
.use(CHAT_MARKDOWN_REHYPE_PLUGINS);
96+
type Node = { type: string; tagName?: string; properties?: object; children?: Node[] };
97+
const tags = (node: Node): string[] => [
98+
...(node.tagName ? [node.tagName] : []),
99+
...(node.children ?? []).flatMap(tags),
100+
];
101+
const images = (node: Node): Node[] =>
102+
node.tagName === "img" ? [node] : (node.children ?? []).flatMap(images);
103+
const tree = processor.runSync(
104+
processor.parse(
105+
[
106+
"<picture>",
107+
' <source media="(prefers-color-scheme: dark)" srcset="docs/dark.webp 1x, docs/[email protected] 2x">',
108+
' <source media="(min-width: 600px)" srcset="docs/wide.webp">',
109+
' <img src="docs/light.webp" alt="Studio">',
110+
"</picture>",
111+
"",
112+
'<picture><source media="(prefers-color-scheme: light)" srcset="javascript:alert(1)"><img src="docs/dark.webp"></picture>',
113+
].join("\n"),
114+
),
115+
) as Node;
116+
117+
expect(tags(tree)).toEqual(["picture", "img", "p", "picture", "img"]);
118+
expect(images(tree).map((image) => image.properties)).toEqual([
119+
{ src: "docs/light.webp", alt: "Studio", dataDarkSrc: "docs/dark.webp" },
120+
{ src: "docs/dark.webp" },
121+
]);
122+
});

‎packages/shared/src/markdownPipeline.ts‎

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,11 +108,41 @@ function rehypePreserveBareAnchorPlaceholders() {
108108
};
109109
}
110110

111+
const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i;
112+
113+
/**
114+
* The renderer resolves an `<img>`'s `src` (workspace files, host media) but never a `<source>`'s
115+
* `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves
116+
* onto the `<img>` for the renderer to pick by theme; every source is then dropped.
117+
*/
118+
function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) {
119+
if (!picture.children) return;
120+
const image = picture.children.find((child) => child.tagName === "img");
121+
for (const source of picture.children) {
122+
if (source.tagName !== "source" || !image) continue;
123+
const media = source.properties?.media;
124+
const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined;
125+
const srcSet = source.properties?.srcSet;
126+
const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet;
127+
// A candidate's URL runs to the first space (a descriptor such as `2x` may follow).
128+
const url =
129+
typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : "";
130+
if (scheme && url) {
131+
const key = scheme.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc";
132+
image.properties = { ...image.properties, [key]: url };
133+
}
134+
}
135+
picture.children = picture.children.filter((child) => child.tagName !== "source");
136+
}
137+
111138
function rehypePreserveImageSourceMeta() {
112139
return (tree: MarkdownImageHastNode) => {
113140
const visit = (node: MarkdownImageHastNode) => {
114141
const src = node.properties?.src;
115142
const title = node.properties?.title;
143+
if (node.type === "element" && node.tagName === "picture") {
144+
moveColorSchemeSourcesToImage(node);
145+
}
116146
if (node.type === "element" && node.tagName === "img") {
117147
node.properties = {
118148
...node.properties,
@@ -128,6 +158,8 @@ function rehypePreserveImageSourceMeta() {
128158
};
129159
}
130160

161+
const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"];
162+
131163
const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
132164
...defaultSchema,
133165
attributes: {
@@ -144,6 +176,8 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
144176
a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
145177
img: [
146178
...(defaultSchema.attributes?.img ?? []),
179+
"dataDarkSrc",
180+
"dataLightSrc",
147181
"dataLocalSrc",
148182
"dataMarkdownTitle",
149183
"dataStandalone",
@@ -158,7 +192,9 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
158192
"t3-context",
159193
THREAD_LINK_PROTOCOL,
160194
],
161-
src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],
195+
src: IMAGE_SRC_PROTOCOLS,
196+
dataDarkSrc: IMAGE_SRC_PROTOCOLS,
197+
dataLightSrc: IMAGE_SRC_PROTOCOLS,
162198
},
163199
} satisfies Parameters<typeof rehypeSanitize>[0];
164200

@@ -316,7 +352,12 @@ const imageSourceProcessor = unified()
316352
interface ImageSourceNode {
317353
readonly type: string;
318354
readonly tagName?: string;
319-
readonly properties?: { readonly src?: unknown; readonly dataLocalSrc?: unknown };
355+
readonly properties?: {
356+
readonly src?: unknown;
357+
readonly dataLocalSrc?: unknown;
358+
readonly dataDarkSrc?: unknown;
359+
readonly dataLightSrc?: unknown;
360+
};
320361
readonly children?: ReadonlyArray<ImageSourceNode>;
321362
}
322363

@@ -328,13 +369,17 @@ export function chatMarkdownImageSources(markdown: string): Array<string> {
328369
const sources: Array<string> = [];
329370
const visit = (node: ImageSourceNode) => {
330371
if (node.type === "element" && node.tagName === "img") {
331-
const { src, dataLocalSrc } = node.properties ?? {};
372+
const { src, dataLocalSrc, dataDarkSrc, dataLightSrc } = node.properties ?? {};
332373
// The sanitizer drops a Windows drive path from `src`; the renderer reads it from here.
333374
if (typeof dataLocalSrc === "string") {
334375
sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/"));
335376
} else if (typeof src === "string") {
336377
sources.push(normalizeMarkdownLinkDestination(src));
337378
}
379+
// A `<picture>` shows one of these instead, by the viewer's theme.
380+
for (const variant of [dataDarkSrc, dataLightSrc]) {
381+
if (typeof variant === "string") sources.push(normalizeMarkdownLinkDestination(variant));
382+
}
338383
}
339384
node.children?.forEach(visit);
340385
};

0 commit comments

Comments
 (0)