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, 17:00 UTC
fix(web): asset URLs re-mint per revision and before expiry without effects (#24970)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 15:26 UTC
b2baf7533704d70490ec78d73bef7e317a6f2577
7 files changed
+481
-75
apps/web/src/assets/assetUrls.test.ts
new
+107
@@ -0,0 +1,107 @@
1
+import { EnvironmentId, ThreadId, type AssetResource } from "@t3tools/contracts";
2
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
3
+import { describe, expect, it } from "vite-plus/test";
4
+
5
+import { makeRevisionedAssetUrlFamily } from "./assetUrls";
6
+
7
+const environmentId = EnvironmentId.make("environment-1");
8
+const resource: AssetResource = {
9
+ _tag: "workspace-file",
10
+ threadId: ThreadId.make("thread-1"),
11
+ path: "docs/diagram.png",
12
+};
13
+
14
+type MintResult = AsyncResult.AsyncResult<{ relativeUrl: string; expiresAt: number }>;
15
+
16
+const minted = (n: number): MintResult =>
17
+ AsyncResult.success({ relativeUrl: `/a/${n}`, expiresAt: 0 });
18
+
19
+// A stand-in for the asset URL query: a refresh starts a mint (counted, shown as
20
+// waiting) and `settle` completes the latest one.
21
+function setup(initial: MintResult) {
22
+ let mints = 0;
23
+ // Node removal runs on the registry's scheduler; `unmount` flushes it so the
24
+ // next mount of the same revision builds a fresh node.
25
+ const scheduled: Array<() => void> = [];
26
+ const registry = AtomRegistry.make({
27
+ scheduleTask: (task) => {
28
+ scheduled.push(task);
29
+ return () => {};
30
+ },
31
+ });
32
+ const server = Atom.make(initial).pipe(Atom.keepAlive);
33
+ const query = Atom.readable(
34
+ (get) => get(server),
35
+ () => {
36
+ mints += 1;
37
+ registry.set(server, AsyncResult.waiting(registry.get(server)));
38
+ },
39
+ ).pipe(Atom.keepAlive);
40
+ const revisioned = makeRevisionedAssetUrlFamily(() => query);
41
+ const mount = (revision: string | null) => {
42
+ const release = registry.mount(revisioned({ environmentId, input: { resource }, revision }));
43
+ return () => {
44
+ release();
45
+ for (const task of scheduled.splice(0)) task();
46
+ };
47
+ };
48
+ const settle = () => registry.set(server, minted(mints + 1));
49
+ return { mount, settle, mints: () => mints };
50
+}
51
+
52
+describe("makeRevisionedAssetUrlFamily", () => {
53
+ it("re-mints a settled URL on first read and on each new revision, not on remount", () => {
54
+ const { mount, settle, mints } = setup(minted(0));
55
+
56
+ mount("mutation-1")();
57
+ expect(mints()).toBe(1);
58
+ settle();
59
+
60
+ mount("mutation-1")();
61
+ expect(mints()).toBe(1);
62
+
63
+ mount("mutation-2")();
64
+ expect(mints()).toBe(2);
65
+ });
66
+
67
+ it("re-mints when a revert returns to an earlier revision", () => {
68
+ const { mount, settle, mints } = setup(minted(0));
69
+
70
+ mount("mutation-a")();
71
+ settle();
72
+ mount("mutation-b")();
73
+ settle();
74
+ expect(mints()).toBe(2);
75
+
76
+ const reverted = mount("mutation-a");
77
+ expect(mints()).toBe(3);
78
+ reverted();
79
+ });
80
+
81
+ it("shares a mint in flight on the first read", () => {
82
+ const { mount, mints } = setup(AsyncResult.initial(true));
83
+
84
+ mount("mutation-1")();
85
+ expect(mints()).toBe(0);
86
+ });
87
+
88
+ it("re-mints after a mint that was in flight when the revision changed", () => {
89
+ const { mount, settle, mints } = setup(minted(0));
90
+
91
+ const before = mount("mutation-1");
92
+ settle();
93
+ const edited = mount("mutation-2");
94
+ expect(mints()).toBe(2);
95
+ before();
96
+
97
+ const stillMinting = mount("mutation-3");
98
+ edited();
99
+ expect(mints()).toBe(2);
100
+
101
+ settle();
102
+ expect(mints()).toBe(3);
103
+ settle();
104
+ expect(mints()).toBe(3);
105
+ stillMinting();
106
+ });
107
+});
apps/web/src/assets/assetUrls.ts
+79
-3
@@ -7,8 +7,9 @@ import {
7
resolveAssetUrl,
8
} from "@t3tools/client-runtime/state/assets";
9
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
10
-import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
11
-import { AsyncResult } from "effect/reactivity";
10
+import { AssetResource, type AssetCreateUrlResult, EnvironmentId } from "@t3tools/contracts";
11
+import * as Schema from "effect/Schema";
12
+import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
13
14
import { assetEnvironment } from "~/state/assets";
15
import { useFilesystemReadAccess } from "~/state/filesystem";
@@ -19,16 +20,91 @@ export { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
20
21
export type AssetUrlState = RuntimeAssetUrlState & { readonly waiting?: boolean };
22
23
+type AssetUrlTarget = {
24
+ readonly environmentId: EnvironmentId;
25
+ readonly input: { readonly resource: AssetResource };
26
+};
27
+
28
+const decodeRevisionedAssetUrlKey = Schema.decodeUnknownSync(
29
+ Schema.Tuple([EnvironmentId, AssetResource, Schema.NullOr(Schema.String)]),
30
+);
31
+
32
+const isSettled = (result: AsyncResult.AsyncResult<unknown, unknown>) =>
33
+ !AsyncResult.isInitial(result) && !result.waiting;
34
+
35
+/**
36
+ * The URL is minted per resource and shared across revisions, so reading a
37
+ * different revision (even an earlier one after a revert) re-mints it. An
38
+ * in-flight mint is shared only on first read; after an edit the server must
39
+ * re-read the file, so the re-mint waits for that mint to settle.
40
+ */
41
+export function makeRevisionedAssetUrlFamily(
42
+ createUrl: (
43
+ target: AssetUrlTarget,
44
+ ) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>,
45
+) {
46
+ // Outside the nodes: a node is dropped once unmounted, and the next read of
47
+ // its revision must still see the revisions minted since. Never pruned on
48
+ // purpose: pruning would forget the revision and re-mint on the next mount.
49
+ // It holds one short entry per file shown, and goes with the registry.
50
+ const mintedUnder = new WeakMap<AtomRegistry.AtomRegistry, Map<string, string | null>>();
51
+ const family = Atom.family((key: string) => {
52
+ const [environmentId, resource, revision] = decodeRevisionedAssetUrlKey(JSON.parse(key));
53
+ const resourceKey = JSON.stringify([environmentId, resource]);
54
+ const query = createUrl({ environmentId, input: { resource } });
55
+ return Atom.transform(
56
+ query,
57
+ (get) => {
58
+ let minted = mintedUnder.get(get.registry);
59
+ if (minted === undefined) {
60
+ minted = new Map();
61
+ mintedUnder.set(get.registry, minted);
62
+ }
63
+ const firstRead = !minted.has(resourceKey);
64
+ let pending = minted.get(resourceKey) !== revision;
65
+ const current = get.once(query);
66
+ if (pending && (firstRead || isSettled(current))) {
67
+ pending = false;
68
+ minted.set(resourceKey, revision);
69
+ if (isSettled(current)) get.refresh(query);
70
+ }
71
+ get.subscribe(query, (value) => {
72
+ get.setSelf(value);
73
+ if (!pending || !isSettled(value)) return;
74
+ pending = false;
75
+ minted.set(resourceKey, revision);
76
+ get.refresh(query);
77
+ });
78
+ return get.once(query);
79
+ },
80
+ { initialValueTarget: query },
81
+ // No idle TTL: each mount rebuilds the node, so a revision read again after
82
+ // another one is compared against the record instead of a cached node.
83
+ ).pipe(Atom.setIdleTTL(0));
84
+ });
85
+ return (target: AssetUrlTarget & { readonly revision: string | null }) =>
86
+ family(JSON.stringify([target.environmentId, target.input.resource, target.revision]));
87
+}
88
+
89
+export const revisionedAssetUrl = makeRevisionedAssetUrlFamily(assetEnvironment.createUrl);
90
+
91
+/**
92
+ * Pass `revision` for a workspace file whose bytes can change under the same
93
+ * path; each new revision gets a freshly minted URL.
94
+ */
95
export function useAssetUrlState(
96
environmentId: EnvironmentId | null,
97
resource: AssetResource | null,
98
+ revision?: string | null,
99
): AssetUrlState {
100
const blocked = blockedAssetUrlState(resource, useFilesystemReadAccess(environmentId));
101
const preparedConnection = usePreparedConnection(environmentId);
102
const result = useAtomValue(
103
blocked !== null || environmentId === null || resource === null
104
? EMPTY_ASSET_URL_ATOM
31
- : assetEnvironment.createUrl({ environmentId, input: { resource } }),
105
+ : revision === undefined
106
+ ? assetEnvironment.createUrl({ environmentId, input: { resource } })
107
+ : revisionedAssetUrl({ environmentId, input: { resource }, revision }),
108
);
109
if (blocked !== null) return blocked;
110
return {
apps/web/src/assets/longLivedAssetUrls.test.ts
new
+100
@@ -0,0 +1,100 @@
1
+import { EnvironmentId, type AssetResource } from "@t3tools/contracts";
2
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
3
+import { describe, expect, it } from "vite-plus/test";
4
+
5
+import { makeLongLivedAssetUrlFamily } from "./longLivedAssetUrls";
6
+
7
+const environmentId = EnvironmentId.make("environment-1");
8
+const resource: AssetResource = {
9
+ _tag: "attachment",
10
+ attachmentId: "attachment-1",
11
+ fileName: "page.html",
12
+ mimeType: "text/html",
13
+ disposition: "inline",
14
+};
15
+
16
+type MintResult = AsyncResult.AsyncResult<{ relativeUrl: string; expiresAt: number }>;
17
+
18
+const url = (relativeUrl: string, expiresAt: number): MintResult =>
19
+ AsyncResult.success({ relativeUrl, expiresAt });
20
+
21
+function setup(initial: MintResult) {
22
+ let mints = 0;
23
+ const tasks: Array<() => void> = [];
24
+ const registry = AtomRegistry.make({
25
+ scheduleTask: (task) => {
26
+ tasks.push(task);
27
+ return () => {};
28
+ },
29
+ });
30
+ const server = Atom.make(initial).pipe(Atom.keepAlive);
31
+ const query = Atom.readable(
32
+ (get) => get(server),
33
+ () => {
34
+ mints += 1;
35
+ registry.set(server, AsyncResult.waiting(registry.get(server)));
36
+ },
37
+ ).pipe(Atom.keepAlive);
38
+ const family = makeLongLivedAssetUrlFamily(() => query, { minLifeMs: 100, now: () => 1_000 });
39
+ const atom = family({ environmentId, input: { resource } });
40
+ let unmount = registry.mount(atom);
41
+ // Readers adopt any Success, waiting or not, as `assetUrlStateFromResult` does.
42
+ const relativeUrl = () => {
43
+ const value = registry.get(atom);
44
+ return value._tag === "Success" ? value.value.relativeUrl : null;
45
+ };
46
+ return {
47
+ relativeUrl,
48
+ mints: () => mints,
49
+ serve: (result: MintResult) => registry.set(server, result),
50
+ remount: () => {
51
+ unmount();
52
+ // Runs the idle-TTL disposal, so the next mount builds a fresh node.
53
+ for (const task of tasks.splice(0)) task();
54
+ unmount = registry.mount(atom);
55
+ },
56
+ };
57
+}
58
+
59
+describe("makeLongLivedAssetUrlFamily", () => {
60
+ it("reuses a cached URL with enough life left", () => {
61
+ const { relativeUrl, mints } = setup(url("/cached", 2_000));
62
+ expect(relativeUrl()).toBe("/cached");
63
+ expect(mints()).toBe(0);
64
+ });
65
+
66
+ it("mints a URL near expiry and hides it until the new one arrives", () => {
67
+ const { relativeUrl, mints, serve } = setup(url("/stale", 1_050));
68
+ expect(mints()).toBe(1);
69
+ expect(relativeUrl()).toBeNull();
70
+
71
+ serve(url("/fresh", 5_000));
72
+ expect(relativeUrl()).toBe("/fresh");
73
+ });
74
+
75
+ it("does not hand a new reader the expiring URL while an earlier reader's mint is in flight", () => {
76
+ const { relativeUrl, mints, serve, remount } = setup(url("/stale", 1_050));
77
+ expect(mints()).toBe(1);
78
+ remount();
79
+ expect(relativeUrl()).toBeNull();
80
+
81
+ serve(url("/fresh", 5_000));
82
+ expect(relativeUrl()).toBe("/fresh");
83
+ expect(mints()).toBe(1);
84
+ });
85
+
86
+ it("mints at most once when the clock disagrees with the server", () => {
87
+ const { relativeUrl, mints, serve } = setup(url("/stale", 1_050));
88
+ serve(url("/still-short", 1_050));
89
+ expect(relativeUrl()).toBe("/still-short");
90
+ expect(mints()).toBe(1);
91
+ });
92
+
93
+ it("waits for a URL still loading", () => {
94
+ const { relativeUrl, mints, serve } = setup(AsyncResult.initial(true));
95
+ expect(relativeUrl()).toBeNull();
96
+ serve(url("/loaded", 5_000));
97
+ expect(relativeUrl()).toBe("/loaded");
98
+ expect(mints()).toBe(0);
99
+ });
100
+});
apps/web/src/assets/longLivedAssetUrls.ts
new
+87
@@ -0,0 +1,87 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
+import {
3
+ type AssetUrlState,
4
+ assetUrlStateFromResult,
5
+ blockedAssetUrlState,
6
+ EMPTY_ASSET_URL_ATOM,
7
+} from "@t3tools/client-runtime/state/assets";
8
+import { AssetResource, type AssetCreateUrlResult, EnvironmentId } from "@t3tools/contracts";
9
+import * as Schema from "effect/Schema";
10
+import { AsyncResult, Atom } from "effect/reactivity";
11
+
12
+import { assetEnvironment } from "~/state/assets";
13
+import { useFilesystemReadAccess } from "~/state/filesystem";
14
+import { usePreparedConnection } from "~/state/session";
15
+
16
+type AssetUrlTarget = {
17
+ readonly environmentId: EnvironmentId;
18
+ readonly input: { readonly resource: AssetResource };
19
+};
20
+
21
+const decodeAssetUrlKey = Schema.decodeUnknownSync(Schema.Tuple([EnvironmentId, AssetResource]));
22
+
23
+/**
24
+ * Asset URLs for documents that cannot report a failed load, such as frames. A
25
+ * cached URL with `minLifeMs` left is reused; one closer to expiry is re-minted.
26
+ * A node mints at most once, so a skewed client clock cannot mint on every update.
27
+ */
28
+export function makeLongLivedAssetUrlFamily(
29
+ createUrl: (
30
+ target: AssetUrlTarget,
31
+ ) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>,
32
+ options: { readonly minLifeMs: number; readonly now?: () => number },
33
+) {
34
+ const now = options.now ?? Date.now;
35
+ const family = Atom.family((key: string) => {
36
+ const [environmentId, resource] = decodeAssetUrlKey(JSON.parse(key));
37
+ const query = createUrl({ environmentId, input: { resource } });
38
+ return Atom.transform(
39
+ query,
40
+ (get) => {
41
+ let minting = false;
42
+ const settle = (
43
+ value: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
44
+ ): AsyncResult.AsyncResult<AssetCreateUrlResult, unknown> => {
45
+ if (value._tag !== "Success") return value;
46
+ const lasts = value.value.expiresAt - now() > options.minLifeMs;
47
+ // An expiring URL must not be handed out while its successor mints,
48
+ // whichever reader started the mint.
49
+ if (value.waiting) return lasts ? value : AsyncResult.initial(true);
50
+ if (minting || lasts) return value;
51
+ minting = true;
52
+ get.refresh(query);
53
+ return AsyncResult.initial(true);
54
+ };
55
+ get.subscribe(query, (value) => get.setSelf(settle(value)));
56
+ return settle(get.once(query));
57
+ },
58
+ { initialValueTarget: query },
59
+ // Each mount gets its own node, so a later mount may mint again.
60
+ ).pipe(Atom.setIdleTTL(0));
61
+ });
62
+ return (target: AssetUrlTarget) =>
63
+ family(JSON.stringify([target.environmentId, target.input.resource]));
64
+}
65
+
66
+const longLivedAssetUrl = makeLongLivedAssetUrlFamily(assetEnvironment.createUrl, {
67
+ minLifeMs: 5 * 60_000,
68
+});
69
+
70
+/** Pass a null environment once the URL is adopted, so later mints do not re-render. */
71
+export function useLongLivedAssetUrl(
72
+ environmentId: EnvironmentId | null,
73
+ resource: AssetResource,
74
+): AssetUrlState {
75
+ const blocked = blockedAssetUrlState(resource, useFilesystemReadAccess(environmentId));
76
+ const preparedConnection = usePreparedConnection(environmentId);
77
+ const result = useAtomValue(
78
+ blocked !== null || environmentId === null
79
+ ? EMPTY_ASSET_URL_ATOM
80
+ : longLivedAssetUrl({ environmentId, input: { resource } }),
81
+ );
82
+ if (blocked !== null) return blocked;
83
+ return assetUrlStateFromResult(
84
+ result,
85
+ preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null,
86
+ );
87
+}
apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx
new
+86
@@ -0,0 +1,86 @@
1
+import type { PreparedConnection } from "@t3tools/client-runtime/connection";
2
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
3
+import { describe, expect, it, vi } from "vite-plus/test";
4
+
5
+import { render } from "../../../test/render";
6
+import { ChatMarkdownAssetImage } from "./ChatMarkdownMedia";
7
+
8
+// Every evaluation of the URL query is one mint: the first read, then one per refresh.
9
+const assetQuery = vi.hoisted(() => ({ mints: 0 }));
10
+vi.mock(import("~/state/assets"), async (original) => {
11
+ const { AsyncResult, Atom } = await import("effect/reactivity");
12
+ const createUrl = Atom.family((_key: string) =>
13
+ Atom.make(() => {
14
+ assetQuery.mints += 1;
15
+ return AsyncResult.success({
16
+ relativeUrl:
17
+ "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
18
+ expiresAt: Number.MAX_SAFE_INTEGER,
19
+ });
20
+ }).pipe(Atom.keepAlive),
21
+ );
22
+ const actual = await original();
23
+ return {
24
+ ...actual,
25
+ assetEnvironment: {
26
+ ...actual.assetEnvironment,
27
+ createUrl: (target: { readonly input: unknown }) => createUrl(JSON.stringify(target.input)),
28
+ },
29
+ };
30
+});
31
+vi.mock(import("~/state/session"), async (original) => {
32
+ const { Option } = await import("effect");
33
+ const { PrimaryConnectionTarget } = await import("@t3tools/client-runtime/connection");
34
+ const { EnvironmentId } = await import("@t3tools/contracts");
35
+ const target = new PrimaryConnectionTarget({
36
+ environmentId: EnvironmentId.make("environment-1"),
37
+ label: "Local",
38
+ httpBaseUrl: "http://localhost:1",
39
+ wsBaseUrl: "ws://localhost:1",
40
+ });
41
+ const prepared: PreparedConnection = {
42
+ environmentId: target.environmentId,
43
+ label: target.label,
44
+ httpBaseUrl: target.httpBaseUrl,
45
+ socketUrl: target.wsBaseUrl,
46
+ httpAuthorization: null,
47
+ target,
48
+ };
49
+ return {
50
+ ...(await original()),
51
+ usePreparedConnection: () => Option.some(prepared),
52
+ };
53
+});
54
+vi.mock(import("~/state/filesystem"), async (original) => ({
55
+ ...(await original()),
56
+ useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
57
+}));
58
+
59
+describe("ChatMarkdownAssetImage", () => {
60
+ it("does not re-mint an unchanged workspace image's URL on remount", async () => {
61
+ assetQuery.mints = 0;
62
+ const image = (
63
+ <ChatMarkdownAssetImage
64
+ environmentId={EnvironmentId.make("environment-1")}
65
+ resource={{
66
+ _tag: "workspace-file",
67
+ threadId: ThreadId.make("thread-1"),
68
+ path: "docs/diagram.png",
69
+ }}
70
+ alt="diagram"
71
+ workspaceMutationId="mutation-1"
72
+ />
73
+ );
74
+
75
+ {
76
+ await using screen = await render(image);
77
+ await expect.element(screen.getByRole("img", { name: "diagram" })).toBeInTheDocument();
78
+ }
79
+ // The first mount at a known revision re-mints the cached URL once.
80
+ expect(assetQuery.mints).toBe(2);
81
+
82
+ await using screen = await render(<ChatMarkdownAssetImage {...image.props} />);
83
+ await expect.element(screen.getByRole("img", { name: "diagram" })).toBeInTheDocument();
84
+ expect(assetQuery.mints).toBe(2);
85
+ });
86
+});
apps/web/src/components/chat/ChatMarkdownMedia.tsx
+10
-40
@@ -5,8 +5,6 @@ import { TriangleAlertIcon } from "lucide-react";
5
import {
6
createContext,
7
memo,
8
- useEffect,
9
- useRef,
8
useState,
9
type ComponentProps,
10
type CSSProperties,
@@ -17,7 +15,6 @@ import {
15
import { useAssetUrlRefresh, useAssetUrlState } from "../../assets/assetUrls";
16
import { cn } from "../../lib/utils";
17
import { useRightPanelStore } from "../../rightPanelStore";
20
-import { usePreparedConnection } from "../../state/session";
18
import { MediaActions, type MediaActionSource } from "../media/MediaActions";
19
import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
20
import type { ExpandedImagePreview } from "./ExpandedImagePreview";
@@ -341,44 +338,17 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
338
readonly workspaceMutationId?: string | null | undefined;
339
readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
340
}) {
344
- const assetUrl = useAssetUrlState(props.environmentId, props.resource);
345
- const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, props.resource);
346
- const connectionReady = usePreparedConnection(props.environmentId)._tag === "Some";
341
const resource = props.resource;
348
- const refreshToken = JSON.stringify([props.environmentId, resource, props.workspaceMutationId]);
349
- const handledRefreshToken = useRef<string | null | undefined>(undefined);
350
- const assetLoading = assetUrl._tag === "Loading" || assetUrl.waiting === true;
351
- useEffect(() => {
352
- if (!connectionReady) {
353
- handledRefreshToken.current = null;
354
- return;
355
- }
356
- if (
357
- props.workspaceMutationId === undefined ||
358
- props.kind === "video" ||
359
- (resource._tag !== "media-file" && resource._tag !== "workspace-file") ||
360
- handledRefreshToken.current === refreshToken
361
- ) {
362
- return;
363
- }
364
- if (assetLoading) {
365
- // Only the initial mount shares a pending request; edits and reconnects need a new one.
366
- if (handledRefreshToken.current === undefined) {
367
- handledRefreshToken.current = refreshToken;
368
- }
369
- return;
370
- }
371
- handledRefreshToken.current = refreshToken;
372
- void refreshAssetUrl().catch(() => undefined);
373
- }, [
374
- assetLoading,
375
- connectionReady,
376
- props.kind,
377
- props.workspaceMutationId,
378
- refreshAssetUrl,
379
- refreshToken,
380
- resource._tag,
381
- ]);
342
+ const assetUrl = useAssetUrlState(
343
+ props.environmentId,
344
+ resource,
345
+ props.workspaceMutationId !== undefined &&
346
+ props.kind !== "video" &&
347
+ (resource._tag === "media-file" || resource._tag === "workspace-file")
348
+ ? props.workspaceMutationId
349
+ : undefined,
350
+ );
351
+ const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
352
const path =
353
resource._tag === "media-file"
354
? resource.path
apps/web/src/components/chat/HtmlRenderFrame.tsx
+12
-32
@@ -8,7 +8,8 @@ import {
8
import { Maximize2Icon } from "lucide-react";
9
import { useEffect, useLayoutEffect, useRef, useState } from "react";
10
11
-import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
11
+import { useAssetUrlRefresh } from "~/assets/assetUrls";
12
+import { useLongLivedAssetUrl } from "~/assets/longLivedAssetUrls";
13
14
import { HtmlRenderDocument } from "../files/BrowserDocumentFrame";
15
import { Button } from "../ui/button";
@@ -47,9 +48,15 @@ export function HtmlRenderFrame(props: {
48
mimeType: "text/html",
49
disposition: "inline" as const,
50
};
50
- // Re-mint near-expiry URLs because frames cannot report failed loads.
51
- const [src, setSrc] = useState<string | null>(null);
52
- const srcExpiresAt = useRef(0);
51
+ // The frame keeps the first URL it loads, so later mints do not reload the page.
52
+ const [loaded, setLoaded] = useState<{ src: string; expiresAt: number } | null>(null);
53
+ const assetUrl = useLongLivedAssetUrl(loaded === null ? props.environmentId : null, resource);
54
+ if (loaded === null && assetUrl._tag === "Success") {
55
+ setLoaded({ src: assetUrl.url, expiresAt: assetUrl.expiresAt });
56
+ }
57
+ const src = loaded?.src ?? null;
58
+ const failed = loaded === null && assetUrl._tag === "Failure";
59
+ const refresh = useAssetUrlRefresh(props.environmentId, resource);
60
const [expandedSrc, setExpandedSrc] = useState<string | null>(null);
61
const { onFullscreenChange } = props;
62
useEffect(() => {
@@ -57,33 +64,6 @@ export function HtmlRenderFrame(props: {
64
onFullscreenChange?.(true);
65
return () => onFullscreenChange?.(false);
66
}, [expandedSrc, onFullscreenChange]);
60
- const [failed, setFailed] = useState(false);
61
- const assetUrl = useAssetUrlState(src === null ? props.environmentId : null, resource);
62
- const cachedUrl = assetUrl._tag === "Success" ? assetUrl.url : null;
63
- const cachedExpiresAt = assetUrl._tag === "Success" ? assetUrl.expiresAt : 0;
64
- const cacheFailed = assetUrl._tag === "Failure";
65
- const refresh = useAssetUrlRefresh(props.environmentId, resource);
66
- // Mint once per mount to prevent clock skew from causing repeated mints.
67
- const minting = useRef(false);
68
- useEffect(() => {
69
- if (src !== null || minting.current) return;
70
- if (cacheFailed) {
71
- // oxlint-disable-next-line react/set-state-in-effect -- Mirrors the cached URL's failure.
72
- setFailed(true);
73
- return;
74
- }
75
- if (cachedUrl === null) return;
76
- if (cachedExpiresAt - Date.now() > MIN_URL_LIFE_MS) {
77
- srcExpiresAt.current = cachedExpiresAt;
78
- setSrc(cachedUrl);
79
- return;
80
- }
81
- minting.current = true;
82
- void refresh().then(
83
- (url) => (url === null ? setFailed(true) : setSrc(url)),
84
- () => setFailed(true),
85
- );
86
- }, [cacheFailed, cachedExpiresAt, cachedUrl, refresh, src]);
67
68
return (
69
<div ref={boxRef} className="group/html-render relative" style={{ height }}>
@@ -107,7 +87,7 @@ export function HtmlRenderFrame(props: {
87
variant="glass"
88
onClick={async () => {
89
const url =
110
- srcExpiresAt.current - Date.now() > MIN_URL_LIFE_MS
90
+ loaded !== null && loaded.expiresAt - Date.now() > MIN_URL_LIFE_MS
91
? src
92
: await refresh().catch(() => null);
93
if (url !== null) setExpandedSrc(url);