@devries-cameron20 / t3code Mirror · read-only / commits / b46a4edc03
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 08:15 UTC

fix(web): dark-mode <picture> images load instead of showing "Image unavailable" (#26398)

Co-authored-by: Vikas - AWS Auto <vikasmaur.in.13@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>

Vikas-Maur committed Nov 2, 2026 at 02:30 UTC b46a4edc03722dccd941708fe6976e871a394e5a
5 files changed +150 -5
apps/server/src/guest/guestAttachments.test.ts
+10
@@ -16,6 +16,16 @@ describe("guest host images", () => {
16 ["![a](file:///w/url%20form.png)", "/w/url form.png", "image/png"],
17 ["![a](C:\\w\\win.png)", "C:\\w\\win.png", "image/png"],
18 ["![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 + ],
24 + [
25 + '<picture><source media="(prefers-color-scheme: dark)" srcset="C:\\w\\dark.png"><img src="C:\\w\\light.png"></picture>',
26 + "C:/w/dark.png",
27 + "image/png",
28 + ],
29 // Shown as a link, in code, or not at all: the guest sees no image, so none loads.
30 ["[a](/w/link.png)", "/w/link.png", null],
31 ["```\n![a](/w/code.png)\n```", "/w/code.png", null],
apps/web/src/components/ChatMarkdown.browser.test.tsx
+45
@@ -74,6 +74,22 @@ vi.mock(import("./chat/MermaidDiagram"), async (original) => {
74 };
75 });
76
77 +const appearance = vi.hoisted(() => ({
78 + value: "light" as "light" | "dark",
79 + listeners: new Set<() => void>(),
80 +}));
81 +vi.mock(import("../hooks/useTheme"), async (original) => {
82 + const { useSyncExternalStore } = await import("react");
83 + const subscribe = (listener: () => void) => {
84 + appearance.listeners.add(listener);
85 + return () => appearance.listeners.delete(listener);
86 + };
87 + return {
88 + ...(await original()),
89 + useRenderedAppearance: () => useSyncExternalStore(subscribe, () => appearance.value),
90 + };
91 +});
92 +
93 const settingsOverrides = vi.hoisted(() => ({ mathRenderingEnabled: false }));
94 vi.mock(import("../hooks/useSettings"), async (original) => {
95 const actual = await original();
@@ -111,6 +127,7 @@ it("keeps compact audio playback loaded across signed URL renewals", async () =>
127 });
128
129 function setup() {
130 + appearance.value = "light";
131 parsedSources.length = 0;
132 settingsOverrides.mathRenderingEnabled = false;
133 renderDiagram.mockReset();
@@ -152,6 +169,34 @@ it("loads a host image through the page's own route when there is no environment
169 );
170 });
171
172 +it("loads the <picture> source for the current theme through the image route", async () => {
173 + setup();
174 + const pixel =
175 + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
176 + const hostImageUrl = (path: string) => `${pixel}#${path}`;
177 + await using screen = await render(
178 + <HostImageUrlContext value={hostImageUrl}>
179 + <ChatMarkdown
180 + cwd={undefined}
181 + text={
182 + '<picture><source media="(prefers-color-scheme: dark)" srcset="/work/dark.png"><img src="/work/light.png" alt="Shot"></picture>'
183 + }
184 + />
185 + </HostImageUrlContext>,
186 + );
187 + await expect
188 + .element(screen.getByAltText("Shot"))
189 + .toHaveAttribute("src", `${pixel}#/work/light.png`);
190 +
191 + await act(() => {
192 + appearance.value = "dark";
193 + for (const listener of appearance.listeners) listener();
194 + });
195 + await expect
196 + .element(screen.getByAltText("Shot"))
197 + .toHaveAttribute("src", `${pixel}#/work/dark.png`);
198 +});
199 +
200 it("reuses the parse of a streaming reply's finished blocks when it remounts", async () => {
201 setup();
202 const message = (
apps/web/src/components/ChatMarkdown.tsx
+6 -2
@@ -1380,6 +1380,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
1380 workspaceMutationId,
1381 renderContextReference,
1382 fileLinkChip,
1383 + resolvedTheme,
1384 } = use(ChatMarkdownRendererContext);
1385 const imageExpand = use(MarkdownLinkContext) ? undefined : expandMedia;
1386 const contextReference = typeof src === "string" ? parseComposerContextHref(src) : null;
@@ -1391,10 +1392,13 @@ const CHAT_MARKDOWN_COMPONENTS = {
1392 <span>{label}</span>
1393 );
1394 }
1394 - const localSrc = node?.properties?.dataLocalSrc;
1395 + // A `<picture>`'s source for this theme, resolved like any other image.
1396 + const themeSrc = node?.properties?.[resolvedTheme === "dark" ? "dataDarkSrc" : "dataLightSrc"];
1397 + const localSrc = typeof themeSrc === "string" ? undefined : node?.properties?.dataLocalSrc;
1398 const markdownTitle = node?.properties?.dataMarkdownTitle;
1399 const standalone = node?.properties?.dataStandalone === true;
1397 - const authoredSrc = typeof localSrc === "string" ? localSrc : src;
1400 + const authoredSrc =
1401 + typeof themeSrc === "string" ? themeSrc : typeof localSrc === "string" ? localSrc : src;
1402 const authoredTitle = typeof markdownTitle === "string" ? markdownTitle : title;
1403 const srcString =
1404 typeof authoredSrc === "string" ? normalizeMarkdownLinkDestination(authoredSrc) : "";
packages/shared/src/markdownPipeline.test.ts
+38
@@ -139,3 +139,41 @@ it("keeps an image on its own line under a label but leaves inline images inline
139 expect(render("Built [![CI](/ci.svg)](/ci)\nand wrapped")).toBe("Built <img>\nand wrapped");
140 expect(render("Hard-wrapped\nprose")).toBe("Hard-wrapped\nprose");
141 });
142 +
143 +it("moves a <picture>'s color-scheme sources onto its <img>, which the renderer resolves", () => {
144 + const processor = unified()
145 + .use(remarkParse)
146 + .use(CHAT_MARKDOWN_REMARK_PLUGINS)
147 + .use(remarkRehype, { allowDangerousHtml: true })
148 + .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
149 + type Node = { type: string; tagName?: string; properties?: object; children?: Node[] };
150 + const tags = (node: Node): string[] => [
151 + ...(node.tagName ? [node.tagName] : []),
152 + ...(node.children ?? []).flatMap(tags),
153 + ];
154 + const images = (node: Node): Node[] =>
155 + node.tagName === "img" ? [node] : (node.children ?? []).flatMap(images);
156 + const tree = processor.runSync(
157 + processor.parse(
158 + [
159 + "<picture>",
160 + ' <source media="(prefers-color-scheme: dark)" srcset="docs/dark.webp 1x, docs/dark@2x.webp 2x">',
161 + ' <source media="(prefers-color-scheme: dark)" srcset="docs/dark-unused.webp">',
162 + ' <source media="(min-width: 600px)" srcset="docs/wide.webp">',
163 + ' <img src="docs/light.webp" alt="Studio">',
164 + "</picture>",
165 + "",
166 + '<picture><source media="(prefers-color-scheme: light)" srcset="javascript:alert(1)"><img src="docs/dark.webp"></picture>',
167 + "",
168 + String.raw`<picture><source media="(prefers-color-scheme: dark)" srcset="C:\shots\dark.png"><img src="C:\shots\light.png"></picture>`,
169 + ].join("\n"),
170 + ),
171 + ) as Node;
172 +
173 + expect(tags(tree)).toEqual(["picture", "img", "p", "picture", "img", "p", "picture", "img"]);
174 + expect(images(tree).map((image) => image.properties)).toEqual([
175 + { src: "docs/light.webp", alt: "Studio", dataDarkSrc: "docs/dark.webp" },
176 + { src: "docs/dark.webp" },
177 + { dataLocalSrc: String.raw`C:\shots\light.png`, dataDarkSrc: "file:///C:/shots/dark.png" },
178 + ]);
179 +});
packages/shared/src/markdownPipeline.ts
+51 -3
@@ -109,11 +109,44 @@ function rehypePreserveBareAnchorPlaceholders() {
109 };
110 }
111
112 +const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i;
113 +
114 +/**
115 + * The renderer resolves an `<img>`'s `src` (workspace files, host media) but never a `<source>`'s
116 + * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves
117 + * onto the `<img>` for the renderer to pick by theme; every source is then dropped.
118 + */
119 +function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) {
120 + if (!picture.children) return;
121 + const image = picture.children.find((child) => child.tagName === "img");
122 + for (const source of picture.children) {
123 + if (source.tagName !== "source" || !image) continue;
124 + const media = source.properties?.media;
125 + const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined;
126 + const srcSet = source.properties?.srcSet;
127 + const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet;
128 + // A candidate's URL runs to the first space (a descriptor such as `2x` may follow).
129 + const url =
130 + typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : "";
131 + const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc";
132 + // As in a browser, the first source that matches a scheme is the one shown.
133 + if (scheme && url && image.properties?.[key] === undefined) {
134 + // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path.
135 + const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url;
136 + image.properties = { ...image.properties, [key]: value };
137 + }
138 + }
139 + picture.children = picture.children.filter((child) => child.tagName !== "source");
140 +}
141 +
142 function rehypePreserveImageSourceMeta() {
143 return (tree: MarkdownImageHastNode) => {
144 const visit = (node: MarkdownImageHastNode) => {
145 const src = node.properties?.src;
146 const title = node.properties?.title;
147 + if (node.type === "element" && node.tagName === "picture") {
148 + moveColorSchemeSourcesToImage(node);
149 + }
150 if (node.type === "element" && node.tagName === "img") {
151 node.properties = {
152 ...node.properties,
@@ -129,6 +162,8 @@ function rehypePreserveImageSourceMeta() {
162 };
163 }
164
165 +const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"];
166 +
167 const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
168 ...defaultSchema,
169 attributes: {
@@ -145,6 +180,8 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
180 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
181 img: [
182 ...(defaultSchema.attributes?.img ?? []),
183 + "dataDarkSrc",
184 + "dataLightSrc",
185 "dataLocalSrc",
186 "dataMarkdownTitle",
187 "dataStandalone",
@@ -159,7 +196,9 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
196 "t3-context",
197 THREAD_LINK_PROTOCOL,
198 ],
162 - src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],
199 + src: IMAGE_SRC_PROTOCOLS,
200 + dataDarkSrc: IMAGE_SRC_PROTOCOLS,
201 + dataLightSrc: IMAGE_SRC_PROTOCOLS,
202 },
203 } satisfies Parameters<typeof rehypeSanitize>[0];
204
@@ -388,7 +427,12 @@ const imageSourceProcessor = unified()
427 interface ImageSourceNode {
428 readonly type: string;
429 readonly tagName?: string;
391 - readonly properties?: { readonly src?: unknown; readonly dataLocalSrc?: unknown };
430 + readonly properties?: {
431 + readonly src?: unknown;
432 + readonly dataLocalSrc?: unknown;
433 + readonly dataDarkSrc?: unknown;
434 + readonly dataLightSrc?: unknown;
435 + };
436 readonly children?: ReadonlyArray<ImageSourceNode>;
437 }
438
@@ -400,13 +444,17 @@ export function chatMarkdownImageSources(markdown: string): Array<string> {
444 const sources: Array<string> = [];
445 const visit = (node: ImageSourceNode) => {
446 if (node.type === "element" && node.tagName === "img") {
403 - const { src, dataLocalSrc } = node.properties ?? {};
447 + const { src, dataLocalSrc, dataDarkSrc, dataLightSrc } = node.properties ?? {};
448 // The sanitizer drops a Windows drive path from `src`; the renderer reads it from here.
449 if (typeof dataLocalSrc === "string") {
450 sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/"));
451 } else if (typeof src === "string") {
452 sources.push(normalizeMarkdownLinkDestination(src));
453 }
454 + // A `<picture>` shows one of these instead, by the viewer's theme.
455 + for (const variant of [dataDarkSrc, dataLightSrc]) {
456 + if (typeof variant === "string") sources.push(normalizeMarkdownLinkDestination(variant));
457 + }
458 }
459 node.children?.forEach(visit);
460 };