TypeScript
fix(web): dark-mode <picture> images load instead of showing "Image unavailable" (#26398)
Vikas-Maurb46a4edc0372
diff --git a/apps/server/src/guest/guestAttachments.test.ts b/apps/server/src/guest/guestAttachments.test.tsindex c65dd1364c2..eeb2b618176 100644--- a/apps/server/src/guest/guestAttachments.test.ts+++ b/apps/server/src/guest/guestAttachments.test.ts@@ -16,6 +16,16 @@ describe("guest host images", () => {["", "/w/url form.png", "image/png"],["", "C:\\w\\win.png", "image/png"],["![a][r]\n\n[r]: C:\\w\\ref.png", "C:/w/ref.png", "image/png"],+ [+ '<picture><source media="(prefers-color-scheme: dark)" srcset="/w/dark.png"><img src="/w/light.png"></picture>',+ "/w/dark.png",+ "image/png",+ ],+ [+ '<picture><source media="(prefers-color-scheme: dark)" srcset="C:\\w\\dark.png"><img src="C:\\w\\light.png"></picture>',+ "C:/w/dark.png",+ "image/png",+ ],// Shown as a link, in code, or not at all: the guest sees no image, so none loads.["[a](/w/link.png)", "/w/link.png", null],["```\n\n```", "/w/code.png", null],diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsxindex e4dfceefd91..9a56cdf8b36 100644--- a/apps/web/src/components/ChatMarkdown.browser.test.tsx+++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx@@ -74,6 +74,22 @@ vi.mock(import("./chat/MermaidDiagram"), async (original) => {};});+const appearance = vi.hoisted(() => ({+ value: "light" as "light" | "dark",+ listeners: new Set<() => void>(),+}));+vi.mock(import("../hooks/useTheme"), async (original) => {+ const { useSyncExternalStore } = await import("react");+ const subscribe = (listener: () => void) => {+ appearance.listeners.add(listener);+ return () => appearance.listeners.delete(listener);+ };+ return {+ ...(await original()),+ useRenderedAppearance: () => useSyncExternalStore(subscribe, () => appearance.value),+ };+});+const settingsOverrides = vi.hoisted(() => ({ mathRenderingEnabled: false }));vi.mock(import("../hooks/useSettings"), async (original) => {const actual = await original();@@ -111,6 +127,7 @@ it("keeps compact audio playback loaded across signed URL renewals", async () =>});function setup() {+ appearance.value = "light";parsedSources.length = 0;settingsOverrides.mathRenderingEnabled = false;renderDiagram.mockReset();@@ -152,6 +169,34 @@ it("loads a host image through the page's own route when there is no environment);});+it("loads the <picture> source for the current theme through the image route", async () => {+ setup();+ const pixel =+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";+ const hostImageUrl = (path: string) => `${pixel}#${path}`;+ await using screen = await render(+ <HostImageUrlContext value={hostImageUrl}>+ <ChatMarkdown+ cwd={undefined}+ text={+ '<picture><source media="(prefers-color-scheme: dark)" srcset="/work/dark.png"><img src="/work/light.png" alt="Shot"></picture>'+ }+ />+ </HostImageUrlContext>,+ );+ await expect+ .element(screen.getByAltText("Shot"))+ .toHaveAttribute("src", `${pixel}#/work/light.png`);++ await act(() => {+ appearance.value = "dark";+ for (const listener of appearance.listeners) listener();+ });+ await expect+ .element(screen.getByAltText("Shot"))+ .toHaveAttribute("src", `${pixel}#/work/dark.png`);+});+it("reuses the parse of a streaming reply's finished blocks when it remounts", async () => {setup();const message = (diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex 928d21fc46b..dd37be3b4b6 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -1380,6 +1380,7 @@ const CHAT_MARKDOWN_COMPONENTS = {workspaceMutationId,renderContextReference,fileLinkChip,+ resolvedTheme,} = use(ChatMarkdownRendererContext);const imageExpand = use(MarkdownLinkContext) ? undefined : expandMedia;const contextReference = typeof src === "string" ? parseComposerContextHref(src) : null;@@ -1391,10 +1392,13 @@ const CHAT_MARKDOWN_COMPONENTS = {<span>{label}</span>);}- const localSrc = node?.properties?.dataLocalSrc;+ // A `<picture>`'s source for this theme, resolved like any other image.+ const themeSrc = node?.properties?.[resolvedTheme === "dark" ? "dataDarkSrc" : "dataLightSrc"];+ const localSrc = typeof themeSrc === "string" ? undefined : node?.properties?.dataLocalSrc;const markdownTitle = node?.properties?.dataMarkdownTitle;const standalone = node?.properties?.dataStandalone === true;- const authoredSrc = typeof localSrc === "string" ? localSrc : src;+ const authoredSrc =+ typeof themeSrc === "string" ? themeSrc : typeof localSrc === "string" ? localSrc : src;const authoredTitle = typeof markdownTitle === "string" ? markdownTitle : title;const srcString =typeof authoredSrc === "string" ? normalizeMarkdownLinkDestination(authoredSrc) : "";diff --git a/packages/shared/src/markdownPipeline.test.ts b/packages/shared/src/markdownPipeline.test.tsindex 214f55f8f42..44e6cebe558 100644--- a/packages/shared/src/markdownPipeline.test.ts+++ b/packages/shared/src/markdownPipeline.test.ts@@ -139,3 +139,41 @@ it("keeps an image on its own line under a label but leaves inline images inlineexpect(render("Built [](/ci)\nand wrapped")).toBe("Built <img>\nand wrapped");expect(render("Hard-wrapped\nprose")).toBe("Hard-wrapped\nprose");});++it("moves a <picture>'s color-scheme sources onto its <img>, which the renderer resolves", () => {+ const processor = unified()+ .use(remarkParse)+ .use(CHAT_MARKDOWN_REMARK_PLUGINS)+ .use(remarkRehype, { allowDangerousHtml: true })+ .use(CHAT_MARKDOWN_REHYPE_PLUGINS);+ type Node = { type: string; tagName?: string; properties?: object; children?: Node[] };+ const tags = (node: Node): string[] => [+ ...(node.tagName ? [node.tagName] : []),+ ...(node.children ?? []).flatMap(tags),+ ];+ const images = (node: Node): Node[] =>+ node.tagName === "img" ? [node] : (node.children ?? []).flatMap(images);+ const tree = processor.runSync(+ processor.parse(+ [+ "<picture>",+ ' <source media="(prefers-color-scheme: dark)" srcset="docs/dark.webp 1x, docs/[email protected] 2x">',+ ' <source media="(prefers-color-scheme: dark)" srcset="docs/dark-unused.webp">',+ ' <source media="(min-width: 600px)" srcset="docs/wide.webp">',+ ' <img src="docs/light.webp" alt="Studio">',+ "</picture>",+ "",+ '<picture><source media="(prefers-color-scheme: light)" srcset="javascript:alert(1)"><img src="docs/dark.webp"></picture>',+ "",+ String.raw`<picture><source media="(prefers-color-scheme: dark)" srcset="C:\shots\dark.png"><img src="C:\shots\light.png"></picture>`,+ ].join("\n"),+ ),+ ) as Node;++ expect(tags(tree)).toEqual(["picture", "img", "p", "picture", "img", "p", "picture", "img"]);+ expect(images(tree).map((image) => image.properties)).toEqual([+ { src: "docs/light.webp", alt: "Studio", dataDarkSrc: "docs/dark.webp" },+ { src: "docs/dark.webp" },+ { dataLocalSrc: String.raw`C:\shots\light.png`, dataDarkSrc: "file:///C:/shots/dark.png" },+ ]);+});diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.tsindex 89ebdcf6089..85b9280ab8c 100644--- a/packages/shared/src/markdownPipeline.ts+++ b/packages/shared/src/markdownPipeline.ts@@ -109,11 +109,44 @@ function rehypePreserveBareAnchorPlaceholders() {};}+const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i;++/**+ * The renderer resolves an `<img>`'s `src` (workspace files, host media) but never a `<source>`'s+ * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves+ * onto the `<img>` for the renderer to pick by theme; every source is then dropped.+ */+function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) {+ if (!picture.children) return;+ const image = picture.children.find((child) => child.tagName === "img");+ for (const source of picture.children) {+ if (source.tagName !== "source" || !image) continue;+ const media = source.properties?.media;+ const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined;+ const srcSet = source.properties?.srcSet;+ const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet;+ // A candidate's URL runs to the first space (a descriptor such as `2x` may follow).+ const url =+ typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : "";+ const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc";+ // As in a browser, the first source that matches a scheme is the one shown.+ if (scheme && url && image.properties?.[key] === undefined) {+ // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path.+ const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url;+ image.properties = { ...image.properties, [key]: value };+ }+ }+ picture.children = picture.children.filter((child) => child.tagName !== "source");+}+function rehypePreserveImageSourceMeta() {return (tree: MarkdownImageHastNode) => {const visit = (node: MarkdownImageHastNode) => {const src = node.properties?.src;const title = node.properties?.title;+ if (node.type === "element" && node.tagName === "picture") {+ moveColorSchemeSourcesToImage(node);+ }if (node.type === "element" && node.tagName === "img") {node.properties = {...node.properties,@@ -129,6 +162,8 @@ function rehypePreserveImageSourceMeta() {};}+const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"];+const CHAT_MARKDOWN_SANITIZE_SCHEMA = {...defaultSchema,attributes: {@@ -145,6 +180,8 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],img: [...(defaultSchema.attributes?.img ?? []),+ "dataDarkSrc",+ "dataLightSrc","dataLocalSrc","dataMarkdownTitle","dataStandalone",@@ -159,7 +196,9 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {"t3-context",THREAD_LINK_PROTOCOL,],- src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],+ src: IMAGE_SRC_PROTOCOLS,+ dataDarkSrc: IMAGE_SRC_PROTOCOLS,+ dataLightSrc: IMAGE_SRC_PROTOCOLS,},} satisfies Parameters<typeof rehypeSanitize>[0];@@ -388,7 +427,12 @@ const imageSourceProcessor = unified()interface ImageSourceNode {readonly type: string;readonly tagName?: string;- readonly properties?: { readonly src?: unknown; readonly dataLocalSrc?: unknown };+ readonly properties?: {+ readonly src?: unknown;+ readonly dataLocalSrc?: unknown;+ readonly dataDarkSrc?: unknown;+ readonly dataLightSrc?: unknown;+ };readonly children?: ReadonlyArray<ImageSourceNode>;}@@ -400,13 +444,17 @@ export function chatMarkdownImageSources(markdown: string): Array<string> {const sources: Array<string> = [];const visit = (node: ImageSourceNode) => {if (node.type === "element" && node.tagName === "img") {- const { src, dataLocalSrc } = node.properties ?? {};+ const { src, dataLocalSrc, dataDarkSrc, dataLightSrc } = node.properties ?? {};// The sanitizer drops a Windows drive path from `src`; the renderer reads it from here.if (typeof dataLocalSrc === "string") {sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/"));} else if (typeof src === "string") {sources.push(normalizeMarkdownLinkDestination(src));}+ // A `<picture>` shows one of these instead, by the viewer's theme.+ for (const variant of [dataDarkSrc, dataLightSrc]) {+ if (typeof variant === "string") sources.push(normalizeMarkdownLinkDestination(variant));+ }}node.children?.forEach(visit);};