@devries-cameron20 / t3code Mirror · read-only / commits / 41e6fbb1e3
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 23, 03:00 UTC

fix(web): refresh embedded assets in markdown file previews (#18647)

Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>

Saikrishna Ambeti committed Oct 19, 2026 at 10:37 UTC 41e6fbb1e3d5635246e9dc2f9d681a09260a9688
5 files changed +212 -30
apps/web/src/assets/assetUrls.ts
+11 -6
@@ -1,6 +1,6 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import {
3 - type AssetUrlState,
3 + type AssetUrlState as RuntimeAssetUrlState,
4 assetUrlStateFromResult,
5 blockedAssetUrlState,
6 EMPTY_ASSET_URL_ATOM,
@@ -15,7 +15,9 @@ import { useFilesystemReadAccess } from "~/state/filesystem";
15 import { usePreparedConnection } from "~/state/session";
16 import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
17
18 -export { resolveAssetUrl, type AssetUrlState } from "@t3tools/client-runtime/state/assets";
18 +export { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
19 +
20 +export type AssetUrlState = RuntimeAssetUrlState & { readonly waiting?: boolean };
21
22 export function useAssetUrlState(
23 environmentId: EnvironmentId | null,
@@ -29,10 +31,13 @@ export function useAssetUrlState(
31 : assetEnvironment.createUrl({ environmentId, input: { resource } }),
32 );
33 if (blocked !== null) return blocked;
32 - return assetUrlStateFromResult(
33 - result,
34 - preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null,
35 - );
34 + return {
35 + ...assetUrlStateFromResult(
36 + result,
37 + preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null,
38 + ),
39 + ...(result.waiting ? { waiting: true } : {}),
40 + };
41 }
42
43 export function useAssetUrlRefresh(
apps/web/src/components/ChatMarkdown.assets.browser.test.tsx
+153 -24
@@ -1,10 +1,12 @@
1 -import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 -import { AsyncResult } from "effect/reactivity";
3 -import { act } from "react";
1 +import { RegistryContext } from "@effect/atom-react";
2 +import { type AssetCreateUrlResult, EnvironmentId, ThreadId } from "@t3tools/contracts";
3 +import * as Effect from "effect/Effect";
4 +import { AtomRegistry } from "effect/reactivity";
5 +import { act, type ReactNode } from "react";
6 import { createRoot, type Root } from "react-dom/client";
7 import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
8
7 -const mint = vi.hoisted(() => vi.fn());
9 +const mint = vi.hoisted(() => vi.fn<() => Promise<AssetCreateUrlResult>>());
10 // Atoms derived from the server config run in the real registry over a missing config.
11 vi.mock(import("../state/server"), async (original) => {
12 const actual = await original();
@@ -15,47 +17,89 @@ vi.mock(import("../state/server"), async (original) => {
17 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => noConfig) as never },
18 };
19 });
18 -vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
20 +// Keep the real query runner and registry: refreshes during waiting requests are skipped.
21 +vi.mock(import("../state/assets"), async (original) => {
22 + const actual = await original();
23 + const { Atom } = await import("effect/reactivity");
24 + const family = Atom.family((_key: string) =>
25 + Atom.make(Effect.tryPromise(() => mint())).pipe(Atom.keepAlive),
26 + );
27 + return {
28 + ...actual,
29 + assetEnvironment: {
30 + ...actual.assetEnvironment,
31 + createUrl: (target) => family(JSON.stringify(target)),
32 + },
33 + };
34 +});
35 +vi.mock(import("../state/filesystem"), async (original) => ({
36 ...(await original()),
20 - useAtomQueryRunner: (() => mint) as never,
37 + useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
38 }));
39 vi.mock(import("../state/session"), async (original) => ({
40 ...(await original()),
41 readEnvironmentScope: () => false,
42 useEnvironmentScope: () => false,
43 readPreparedConnection: (() => ({ httpBaseUrl: "https://host.test" })) as never,
44 + usePreparedConnection: (() => ({
45 + _tag: "Some",
46 + value: { httpBaseUrl: "https://host.test" },
47 + })) as never,
48 }));
49
50 import ChatMarkdown from "./ChatMarkdown";
51
52 const roots: Root[] = [];
32 -beforeEach(() => vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true));
53 +let registry: AtomRegistry.AtomRegistry;
54 +
55 +const imageUrl = (version: string) =>
56 + `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>#${version}`;
57 +const assetResult = (version: string): AssetCreateUrlResult => ({
58 + relativeUrl: imageUrl(version),
59 + expiresAt: 1,
60 +});
61 +
62 +beforeEach(() => {
63 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
64 + registry = AtomRegistry.make();
65 + mint.mockReset().mockResolvedValue(assetResult("updated"));
66 +});
67 afterEach(async () => {
68 for (const root of roots.splice(0)) await act(async () => root.unmount());
69 + registry.dispose();
70 document.body.replaceChildren();
71 vi.unstubAllGlobals();
72 });
73
39 -it("opens host media through server authorization before the client grant loads", async () => {
40 - mint.mockResolvedValue(
41 - AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 }),
42 - );
43 - const onImageExpand = vi.fn();
74 +function createTestRoot() {
75 const container = document.body.appendChild(document.createElement("div"));
76 const root = createRoot(container);
77 roots.push(root);
47 - await act(async () =>
48 - root.render(
49 - <ChatMarkdown
50 - cwd="/repo"
51 - threadRef={{
52 - environmentId: EnvironmentId.make("media-environment"),
53 - threadId: ThreadId.make("media-thread"),
54 - }}
55 - text="[Open image](/tmp/image.png)"
56 - onImageExpand={onImageExpand}
57 - />,
58 - ),
78 + return {
79 + container,
80 + render: (children: ReactNode) =>
81 + act(async () => {
82 + root.render(
83 + <RegistryContext.Provider value={registry}>{children}</RegistryContext.Provider>,
84 + );
85 + }),
86 + };
87 +}
88 +
89 +it("opens host media through server authorization before the client grant loads", async () => {
90 + mint.mockResolvedValue({ relativeUrl: "/api/assets/image.png", expiresAt: 1 });
91 + const onImageExpand = vi.fn();
92 + const { container, render } = createTestRoot();
93 + await render(
94 + <ChatMarkdown
95 + cwd="/repo"
96 + threadRef={{
97 + environmentId: EnvironmentId.make("media-environment"),
98 + threadId: ThreadId.make("media-thread"),
99 + }}
100 + text="[Open image](/tmp/image.png)"
101 + onImageExpand={onImageExpand}
102 + />,
103 );
104 const link = container.querySelector<HTMLAnchorElement>('a[href="/tmp/image.png"]');
105 expect(link).not.toBeNull();
@@ -68,3 +112,88 @@ it("opens host media through server authorization before the client grant loads"
112 ),
113 );
114 });
115 +
116 +const threadRef = {
117 + environmentId: EnvironmentId.make("media-environment"),
118 + threadId: ThreadId.make("media-thread"),
119 +};
120 +
121 +function markdown(workspaceMutationId?: string | null) {
122 + return (
123 + <ChatMarkdown
124 + cwd="/repo"
125 + imageBaseDir="/repo"
126 + threadRef={threadRef}
127 + text="![Diagram](diagram.svg)"
128 + workspaceMutationId={workspaceMutationId}
129 + />
130 + );
131 +}
132 +
133 +function renderedImage(container: HTMLElement) {
134 + return container.querySelector<HTMLImageElement>('img[alt="Diagram"]')?.getAttribute("src");
135 +}
136 +
137 +it("ordinary chat keeps its embedded asset URL across renders and reopening", async () => {
138 + const { container, render } = createTestRoot();
139 + await render(markdown());
140 + expect(renderedImage(container)).toBe(imageUrl("updated"));
141 + mint.mockResolvedValue(assetResult("changed"));
142 +
143 + await render(markdown());
144 + await render(null);
145 + await render(markdown());
146 +
147 + expect(renderedImage(container)).toBe(imageUrl("updated"));
148 + expect(mint).toHaveBeenCalledTimes(1);
149 +});
150 +
151 +it.each(["URL", "failure"] as const)(
152 + "reopening a file preview with no workspace mutation replaces its cached %s",
153 + async (cached) => {
154 + if (cached === "failure") mint.mockRejectedValueOnce(new Error("Image missing"));
155 + else mint.mockResolvedValueOnce(assetResult("stale"));
156 + const { container, render } = createTestRoot();
157 + await render(markdown(null));
158 + expect(renderedImage(container)).toBe(cached === "URL" ? imageUrl("stale") : undefined);
159 + await render(null);
160 +
161 + mint.mockResolvedValue(assetResult("updated"));
162 + await render(markdown(null));
163 +
164 + expect(renderedImage(container)).toBe(imageUrl("updated"));
165 + expect(mint).toHaveBeenCalledTimes(2);
166 + },
167 +);
168 +
169 +it.each(["initial", "refresh"] as const)(
170 + "shows the latest workspace edit after a pending %s asset request settles",
171 + async (request) => {
172 + let resolvePending!: (value: AssetCreateUrlResult) => void;
173 + const pending = new Promise<AssetCreateUrlResult>((resolve) => {
174 + resolvePending = resolve;
175 + });
176 + const { container, render } = createTestRoot();
177 + if (request === "refresh") {
178 + await render(markdown("m0"));
179 + expect(renderedImage(container)).toBe(imageUrl("updated"));
180 + }
181 +
182 + mint.mockReturnValueOnce(pending).mockResolvedValue(assetResult("latest"));
183 + await render(markdown("m1"));
184 + const callsBeforeEdits = mint.mock.calls.length;
185 + await render(markdown("m2"));
186 + await render(markdown("m3"));
187 + expect(mint).toHaveBeenCalledTimes(callsBeforeEdits);
188 +
189 + await act(async () => {
190 + resolvePending(assetResult("before-edits"));
191 + await pending;
192 + });
193 +
194 + expect(renderedImage(container)).toBe(imageUrl("latest"));
195 + expect(mint).toHaveBeenCalledTimes(callsBeforeEdits + 1);
196 + await render(markdown("m3"));
197 + expect(mint).toHaveBeenCalledTimes(callsBeforeEdits + 1);
198 + },
199 +);
apps/web/src/components/ChatMarkdown.tsx
+42
@@ -189,6 +189,7 @@ import {
189 readEnvironmentScope,
190 readPreparedConnection,
191 useEnvironmentScope,
192 + usePreparedConnection,
193 } from "../state/session";
194 import { previewEnvironment } from "../state/preview";
195 import { useAtomCommand } from "../state/use-atom-command";
@@ -235,6 +236,7 @@ interface ChatMarkdownProps {
236 onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
237 onRunShellCommand?: ((command: string) => void) | undefined;
238 imageBaseDir?: string | undefined;
239 + workspaceMutationId?: string | null | undefined;
240 onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
241 extraRemarkPlugins?: NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
242 renderContextReference?: ((reference: ChatMarkdownContextReference) => ReactNode) | undefined;
@@ -1574,11 +1576,47 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
1576 readonly framed?: boolean | undefined;
1577 readonly fallbackSrc?: string | undefined;
1578 readonly workspaceRoot?: string | undefined;
1579 + readonly workspaceMutationId?: string | null | undefined;
1580 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
1581 }) {
1582 const assetUrl = useAssetUrlState(props.environmentId, props.resource);
1583 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, props.resource);
1584 + const connectionReady = usePreparedConnection(props.environmentId)._tag === "Some";
1585 const resource = props.resource;
1586 + const refreshToken = JSON.stringify([props.environmentId, resource, props.workspaceMutationId]);
1587 + const handledRefreshToken = useRef<string | null | undefined>(undefined);
1588 + const assetLoading = assetUrl._tag === "Loading" || assetUrl.waiting === true;
1589 + useEffect(() => {
1590 + if (!connectionReady) {
1591 + handledRefreshToken.current = null;
1592 + return;
1593 + }
1594 + if (
1595 + props.workspaceMutationId === undefined ||
1596 + props.kind === "video" ||
1597 + (resource._tag !== "media-file" && resource._tag !== "workspace-file") ||
1598 + handledRefreshToken.current === refreshToken
1599 + ) {
1600 + return;
1601 + }
1602 + if (assetLoading) {
1603 + // Only the initial mount shares a pending request; edits and reconnects need a new one.
1604 + if (handledRefreshToken.current === undefined) {
1605 + handledRefreshToken.current = refreshToken;
1606 + }
1607 + return;
1608 + }
1609 + handledRefreshToken.current = refreshToken;
1610 + void refreshAssetUrl().catch(() => undefined);
1611 + }, [
1612 + assetLoading,
1613 + connectionReady,
1614 + props.kind,
1615 + props.workspaceMutationId,
1616 + refreshAssetUrl,
1617 + refreshToken,
1618 + resource._tag,
1619 + ]);
1620 const path =
1621 resource._tag === "media-file"
1622 ? resource.path
@@ -2299,6 +2337,7 @@ function useChatMarkdownState({
2337 onUseArtifactTemplate,
2338 onRunShellCommand,
2339 imageBaseDir,
2340 + workspaceMutationId,
2341 onImageExpand,
2342 renderContextReference,
2343 headingLevelOffset = 0,
@@ -2688,6 +2727,7 @@ function useChatMarkdownState({
2727 renderContextReference,
2728 headingLevelOffset,
2729 imageBaseDir,
2730 + workspaceMutationId,
2731 inlineCodeFileLinkMetaByText,
2732 isStreaming,
2733 linkTargetPreference,
@@ -3136,6 +3176,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
3176 githubMedia,
3177 imageBaseDir,
3178 threadRef,
3179 + workspaceMutationId,
3180 renderContextReference,
3181 } = use(ChatMarkdownRendererContext);
3182 const imageExpand = use(MarkdownLinkContext) ? undefined : expandMedia;
@@ -3247,6 +3288,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
3288 standalone={standalone}
3289 style={authoredSizeStyle}
3290 workspaceRoot={cwd}
3291 + workspaceMutationId={workspaceMutationId}
3292 onImageExpand={imageExpand}
3293 />
3294 );
apps/web/src/components/files/FileMarkdownPreview.tsx
+2
@@ -8,6 +8,7 @@ export function FileMarkdownPreview(props: {
8 readonly relativePath: string;
9 readonly text: string;
10 readonly threadRef: ScopedThreadRef;
11 + readonly workspaceMutationId: string | null;
12 readonly onTaskListChange?:
13 | ((input: { readonly markerOffset: number; readonly checked: boolean }) => void)
14 | undefined;
@@ -27,6 +28,7 @@ export function FileMarkdownPreview(props: {
28 cwd={props.cwd}
29 imageBaseDir={imageBaseDir}
30 threadRef={props.threadRef}
31 + workspaceMutationId={props.workspaceMutationId}
32 className="mx-auto max-w-4xl px-6 py-5"
33 onTaskListChange={props.onTaskListChange}
34 />
apps/web/src/components/files/FilePreviewPanel.tsx
+4
@@ -905,6 +905,7 @@ function RenderedMarkdownSurface({
905 relativePath,
906 contents,
907 threadRef,
908 + workspaceMutationId,
909 readOnly,
910 onPendingChange,
911 }: Omit<
@@ -918,6 +919,7 @@ function RenderedMarkdownSurface({
919 > & {
920 threadRef: ScopedThreadRef;
921 readOnly: boolean;
922 + workspaceMutationId: string | null;
923 }) {
924 const saveCoordinator = useFileSaveCoordinator({
925 environmentId,
@@ -933,6 +935,7 @@ function RenderedMarkdownSurface({
935 cwd={cwd}
936 relativePath={relativePath}
937 threadRef={threadRef}
938 + workspaceMutationId={workspaceMutationId}
939 onTaskListChange={
940 readOnly
941 ? undefined
@@ -1399,6 +1402,7 @@ export default function FilePreviewPanel({
1402 relativePath={relativePath}
1403 threadRef={threadRef}
1404 contents={file.data.contents}
1405 + workspaceMutationId={workspaceMutationId}
1406 readOnly={isHostFile || !canWriteFiles}
1407 onPendingChange={onPendingChange}
1408 />