Skip to content

Commit 35c2674

Browse files
fix(web): refresh embedded assets in markdown file previews
1 parent df26ef9 commit 35c2674

6 files changed

Lines changed: 194 additions & 8 deletions

File tree

‎apps/web/src/assets/assetUrls.test.ts‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
EnvironmentId,
55
ThreadId,
66
type AuthSessionState,
7+
type AssetCreateUrlResult,
78
} from "@t3tools/contracts";
89
import * as Cause from "effect/Cause";
910
import { AsyncResult } from "effect/reactivity";
@@ -15,13 +16,15 @@ const state = vi.hoisted(() => ({
1516
assetAtom: {},
1617
mint: vi.fn(),
1718
assetQuery: vi.fn(),
19+
assetResult: null as AsyncResult.AsyncResult<AssetCreateUrlResult, unknown> | null,
1820
}));
1921

2022
vi.mock("react", () => ({ useCallback: <A>(callback: A) => callback }));
2123
vi.mock("@effect/atom-react", () => ({
2224
useAtomValue: (atom: unknown) =>
2325
atom === state.assetAtom
24-
? AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 })
26+
? (state.assetResult ??
27+
AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 }))
2528
: AsyncResult.initial(false),
2629
}));
2730
vi.mock("~/state/session", () => ({
@@ -53,12 +56,41 @@ const resource = { _tag: "media-file", threadId, path: "/repo/image.png" } as co
5356
beforeEach(() => {
5457
state.session = null;
5558
state.phase = "connected";
59+
state.assetResult = null;
5660
state.assetQuery.mockReset().mockReturnValue(state.assetAtom);
5761
state.mint
5862
.mockReset()
5963
.mockResolvedValue(AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 }));
6064
});
6165

66+
it.each(["Success", "Failure"] as const)(
67+
"exposes a refresh in progress while preserving a cached %s result",
68+
(outcome) => {
69+
state.session = { authenticated: true, scopes: [AuthFilesystemReadScope] };
70+
state.assetResult =
71+
outcome === "Success"
72+
? AsyncResult.success(
73+
{ relativeUrl: "/api/assets/image.png", expiresAt: 1 },
74+
{ waiting: true },
75+
)
76+
: AsyncResult.failure(Cause.fail(new Error("Image missing")), { waiting: true });
77+
expect(useAssetUrlState(environmentId, resource)).toMatchObject({
78+
_tag: outcome,
79+
waiting: true,
80+
});
81+
if (outcome === "Success") {
82+
expect(useAssetUrlState(environmentId, resource)).toMatchObject({
83+
url: "https://host.test/api/assets/image.png",
84+
});
85+
}
86+
state.assetResult = AsyncResult.success({
87+
relativeUrl: "/api/assets/updated.png",
88+
expiresAt: 2,
89+
});
90+
expect(useAssetUrlState(environmentId, resource).waiting).toBeUndefined();
91+
},
92+
);
93+
6294
it.each(["workspace-file", "media-file"] as const)(
6395
"keeps %s loading until its file grant resolves",
6496
(_tag) => {

‎apps/web/src/assets/assetUrls.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { useAtomValue } from "@effect/atom-react";
22
import {
3-
type AssetUrlState,
3+
type AssetUrlState as RuntimeAssetUrlState,
44
assetUrlStateFromResult,
55
EMPTY_ASSET_URL_ATOM,
66
resolveAssetUrl,
@@ -15,7 +15,12 @@ import { useFilesystemReadAccess } from "~/state/filesystem";
1515
import { usePreparedConnection } from "~/state/session";
1616
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
1717

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 & {
21+
/** A cached result remains visible while its replacement is being requested. */
22+
readonly waiting?: boolean;
23+
};
1924

2025
export function useAssetUrlState(
2126
environmentId: EnvironmentId | null,
@@ -34,10 +39,13 @@ export function useAssetUrlState(
3439
: assetEnvironment.createUrl({ environmentId, input: { resource } }),
3540
);
3641
if (!canReadResource) return { _tag: fileAccess.isPending ? "Loading" : "Failure" };
37-
return assetUrlStateFromResult(
38-
result,
39-
preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null,
40-
);
42+
return {
43+
...assetUrlStateFromResult(
44+
result,
45+
preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null,
46+
),
47+
...(result.waiting ? { waiting: true } : {}),
48+
};
4149
}
4250

4351
export function useAssetUrlRefresh(

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

Lines changed: 111 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,32 @@
11
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2+
import type { AssetUrlState } from "../assets/assetUrls";
23
import { AsyncResult } from "effect/reactivity";
34
import { act, type ComponentProps, type ReactNode } from "react";
45
import { create, type ReactTestRenderer } from "react-test-renderer";
56
import { expect, it, vi } from "vite-plus/test";
67

78
const mint = vi.hoisted(() => vi.fn());
9+
const asset = vi.hoisted(() => ({
10+
state: { _tag: "Loading" } as AssetUrlState,
11+
listeners: new Set<() => void>(),
12+
}));
13+
vi.mock("../assets/assetUrls", async (importOriginal) => {
14+
const { useSyncExternalStore } = await import("react");
15+
return {
16+
...(await importOriginal<typeof import("../assets/assetUrls")>()),
17+
useAssetUrlState: () =>
18+
useSyncExternalStore(
19+
(listener) => {
20+
asset.listeners.add(listener);
21+
return () => {
22+
asset.listeners.delete(listener);
23+
};
24+
},
25+
() => asset.state,
26+
),
27+
};
28+
});
29+
vi.mock("./media/MediaActions", () => ({ MediaActions: () => null }));
830
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
931
vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
1032
vi.mock("../hooks/useFileMetadata", () => ({ useFileMetadata: () => undefined }));
@@ -58,7 +80,95 @@ vi.mock("~/lib/openPullRequestLink", () => ({
5880
useOpenChangeRequestLink: () => vi.fn(),
5981
}));
6082

61-
import ChatMarkdown from "./ChatMarkdown";
83+
import ChatMarkdown, { ChatMarkdownAssetImage } from "./ChatMarkdown";
84+
85+
const assetProps = {
86+
environmentId: EnvironmentId.make("media-environment"),
87+
resource: {
88+
_tag: "media-file",
89+
threadId: ThreadId.make("media-thread"),
90+
path: "/repo/diagram.svg",
91+
},
92+
alt: "Diagram",
93+
} satisfies ComponentProps<typeof ChatMarkdownAssetImage>;
94+
95+
async function publishAssetState(state: AssetUrlState) {
96+
await act(async () => {
97+
asset.state = state;
98+
for (const listener of asset.listeners) listener();
99+
});
100+
}
101+
102+
it("does not mint a second URL when the initial file preview request completes", async () => {
103+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
104+
mint.mockClear();
105+
asset.state = { _tag: "Loading" };
106+
let renderer: ReactTestRenderer | undefined;
107+
const image = <ChatMarkdownAssetImage {...assetProps} workspaceMutationId="initial" />;
108+
try {
109+
await act(async () => {
110+
renderer = create(image);
111+
});
112+
await publishAssetState({
113+
_tag: "Success",
114+
url: "https://host.test/diagram.svg",
115+
expiresAt: 1,
116+
});
117+
expect(mint).not.toHaveBeenCalled();
118+
} finally {
119+
await act(async () => renderer?.unmount());
120+
vi.unstubAllGlobals();
121+
}
122+
});
123+
124+
it.each(
125+
(["Loading", "Success", "Failure"] as const).flatMap((initial) =>
126+
(["Success", "Failure"] as const).map((outcome) => [initial, outcome] as const),
127+
),
128+
)(
129+
"refreshes a file changed during a pending %s request after it ends in %s",
130+
async (initial, outcome) => {
131+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
132+
mint.mockReset();
133+
mint.mockResolvedValue(
134+
AsyncResult.success({ relativeUrl: "/api/assets/updated.svg", expiresAt: 1 }),
135+
);
136+
asset.state =
137+
initial === "Success"
138+
? { _tag: "Success", url: "https://host.test/stale.svg", expiresAt: 1, waiting: true }
139+
: { _tag: initial, waiting: true };
140+
let renderer: ReactTestRenderer | undefined;
141+
try {
142+
await act(async () => {
143+
renderer = create(<ChatMarkdownAssetImage {...assetProps} workspaceMutationId="initial" />);
144+
});
145+
for (const mutation of ["edit-1", "edit-2"]) {
146+
await act(async () => {
147+
renderer!.update(
148+
<ChatMarkdownAssetImage {...assetProps} workspaceMutationId={mutation} />,
149+
);
150+
});
151+
}
152+
expect(mint).not.toHaveBeenCalled();
153+
await publishAssetState(
154+
outcome === "Failure"
155+
? { _tag: "Failure" }
156+
: { _tag: "Success", url: "https://host.test/stale.svg", expiresAt: 1 },
157+
);
158+
expect(mint).toHaveBeenCalledExactlyOnceWith({
159+
environmentId: assetProps.environmentId,
160+
input: { resource: assetProps.resource },
161+
});
162+
await act(async () => {
163+
renderer!.update(<ChatMarkdownAssetImage {...assetProps} workspaceMutationId="edit-2" />);
164+
});
165+
expect(mint).toHaveBeenCalledTimes(1);
166+
} finally {
167+
await act(async () => renderer?.unmount());
168+
vi.unstubAllGlobals();
169+
}
170+
},
171+
);
62172

63173
it("opens host media through server authorization before the client grant loads", async () => {
64174
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);

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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,8 @@ interface ChatMarkdownProps {
235235
/** Directory that anchors relative links and images; defaults to `cwd`. Set
236236
to the file's own directory when rendering a markdown file. */
237237
imageBaseDir?: string | undefined;
238+
/** File previews refresh embedded host assets when opened or after workspace edits. */
239+
workspaceMutationId?: string | null | undefined;
238240
onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
239241
extraRemarkPlugins?: NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
240242
/** Renders a `t3-context://` link as a chip; without it the link shows its label as text. */
@@ -1598,11 +1600,34 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
15981600
too old to know this resource. Only safe when the client can reach it directly. */
15991601
readonly fallbackSrc?: string | undefined;
16001602
readonly workspaceRoot?: string | undefined;
1603+
readonly workspaceMutationId?: string | null | undefined;
16011604
readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
16021605
}) {
16031606
const assetUrl = useAssetUrlState(props.environmentId, props.resource);
16041607
const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, props.resource);
16051608
const resource = props.resource;
1609+
const refreshToken = JSON.stringify([props.environmentId, resource, props.workspaceMutationId]);
1610+
const handledRefreshToken = useRef<string | null>(null);
1611+
const assetLoading = assetUrl._tag === "Loading" || assetUrl.waiting === true;
1612+
useEffect(() => {
1613+
if (
1614+
props.workspaceMutationId === undefined ||
1615+
(resource._tag !== "media-file" && resource._tag !== "workspace-file") ||
1616+
handledRefreshToken.current === refreshToken
1617+
) {
1618+
return;
1619+
}
1620+
// A first request already reads the current file. Cached URLs and failures
1621+
// need a new signature after a file is created or atomically replaced.
1622+
if (assetLoading) {
1623+
// Only the initial token is covered by that request. Later edits stay
1624+
// pending until it settles, then refresh the latest file state.
1625+
handledRefreshToken.current ??= refreshToken;
1626+
return;
1627+
}
1628+
handledRefreshToken.current = refreshToken;
1629+
void refreshAssetUrl().catch(() => undefined);
1630+
}, [assetLoading, props.workspaceMutationId, refreshAssetUrl, refreshToken, resource._tag]);
16061631
const path =
16071632
resource._tag === "media-file"
16081633
? resource.path
@@ -2316,6 +2341,7 @@ function useChatMarkdownState({
23162341
onUseArtifactTemplate,
23172342
onRunShellCommand,
23182343
imageBaseDir,
2344+
workspaceMutationId,
23192345
onImageExpand,
23202346
renderContextReference,
23212347
headingLevelOffset = 0,
@@ -2730,6 +2756,7 @@ function useChatMarkdownState({
27302756
renderContextReference,
27312757
headingLevelOffset,
27322758
imageBaseDir,
2759+
workspaceMutationId,
27332760
inlineCodeFileLinkMetaByText,
27342761
isStreaming,
27352762
linkTargetPreference,
@@ -2763,6 +2790,7 @@ function useChatMarkdownState({
27632790
renderContextReference,
27642791
headingLevelOffset,
27652792
imageBaseDir,
2793+
workspaceMutationId,
27662794
inlineCodeFileLinkMetaByText,
27672795
isStreaming,
27682796
linkTargetPreference,
@@ -3219,6 +3247,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
32193247
githubMedia,
32203248
imageBaseDir,
32213249
threadRef,
3250+
workspaceMutationId,
32223251
renderContextReference,
32233252
} = use(ChatMarkdownRendererContext);
32243253
const imageExpand = use(MarkdownLinkContext) ? undefined : expandMedia;
@@ -3334,6 +3363,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
33343363
standalone={standalone}
33353364
style={authoredSizeStyle}
33363365
workspaceRoot={cwd}
3366+
workspaceMutationId={workspaceMutationId}
33373367
onImageExpand={imageExpand}
33383368
/>
33393369
);

‎apps/web/src/components/files/FileMarkdownPreview.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export function FileMarkdownPreview(props: {
88
readonly relativePath: string;
99
readonly text: string;
1010
readonly threadRef: ScopedThreadRef;
11+
readonly workspaceMutationId?: string | null;
1112
readonly onTaskListChange?:
1213
| ((input: { readonly markerOffset: number; readonly checked: boolean }) => void)
1314
| undefined;
@@ -27,6 +28,7 @@ export function FileMarkdownPreview(props: {
2728
cwd={props.cwd}
2829
imageBaseDir={imageBaseDir}
2930
threadRef={props.threadRef}
31+
workspaceMutationId={props.workspaceMutationId ?? null}
3032
className="mx-auto max-w-4xl px-6 py-5"
3133
onTaskListChange={props.onTaskListChange}
3234
/>

‎apps/web/src/components/files/FilePreviewPanel.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -964,6 +964,7 @@ function RenderedMarkdownSurface({
964964
relativePath,
965965
contents,
966966
threadRef,
967+
workspaceMutationId,
967968
readOnly,
968969
onPendingChange,
969970
}: Omit<
@@ -977,6 +978,7 @@ function RenderedMarkdownSurface({
977978
> & {
978979
threadRef: ScopedThreadRef;
979980
readOnly: boolean;
981+
workspaceMutationId: string | null;
980982
}) {
981983
const saveCoordinator = useFileSaveCoordinator({
982984
environmentId,
@@ -992,6 +994,7 @@ function RenderedMarkdownSurface({
992994
cwd={cwd}
993995
relativePath={relativePath}
994996
threadRef={threadRef}
997+
workspaceMutationId={workspaceMutationId}
995998
onTaskListChange={
996999
readOnly
9971000
? undefined
@@ -1441,6 +1444,7 @@ export default function FilePreviewPanel({
14411444
relativePath={relativePath}
14421445
threadRef={threadRef}
14431446
contents={file.data.contents}
1447+
workspaceMutationId={workspaceMutationId}
14441448
readOnly={isHostFile || !canWriteFiles}
14451449
onPendingChange={onPendingChange}
14461450
/>

0 commit comments

Comments
 (0)