Skip to content
TypeScript

fix(web): asset URLs re-mint per revision and before expiry without effects (#24970)

Julius Marmingeb2baf7533704
diff --git a/apps/web/src/assets/assetUrls.test.ts b/apps/web/src/assets/assetUrls.test.ts
new file mode 100644
index 00000000000..bb442959f18
--- /dev/null
+++ b/apps/web/src/assets/assetUrls.test.ts
@@ -0,0 +1,107 @@
+import { EnvironmentId, ThreadId, type AssetResource } from "@t3tools/contracts";
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
+import { describe, expect, it } from "vite-plus/test";
+
+import { makeRevisionedAssetUrlFamily } from "./assetUrls";
+
+const environmentId = EnvironmentId.make("environment-1");
+const resource: AssetResource = {
+ _tag: "workspace-file",
+ threadId: ThreadId.make("thread-1"),
+ path: "docs/diagram.png",
+};
+
+type MintResult = AsyncResult.AsyncResult<{ relativeUrl: string; expiresAt: number }>;
+
+const minted = (n: number): MintResult =>
+ AsyncResult.success({ relativeUrl: `/a/${n}`, expiresAt: 0 });
+
+// A stand-in for the asset URL query: a refresh starts a mint (counted, shown as
+// waiting) and `settle` completes the latest one.
+function setup(initial: MintResult) {
+ let mints = 0;
+ // Node removal runs on the registry's scheduler; `unmount` flushes it so the
+ // next mount of the same revision builds a fresh node.
+ const scheduled: Array<() => void> = [];
+ const registry = AtomRegistry.make({
+ scheduleTask: (task) => {
+ scheduled.push(task);
+ return () => {};
+ },
+ });
+ const server = Atom.make(initial).pipe(Atom.keepAlive);
+ const query = Atom.readable(
+ (get) => get(server),
+ () => {
+ mints += 1;
+ registry.set(server, AsyncResult.waiting(registry.get(server)));
+ },
+ ).pipe(Atom.keepAlive);
+ const revisioned = makeRevisionedAssetUrlFamily(() => query);
+ const mount = (revision: string | null) => {
+ const release = registry.mount(revisioned({ environmentId, input: { resource }, revision }));
+ return () => {
+ release();
+ for (const task of scheduled.splice(0)) task();
+ };
+ };
+ const settle = () => registry.set(server, minted(mints + 1));
+ return { mount, settle, mints: () => mints };
+}
+
+describe("makeRevisionedAssetUrlFamily", () => {
+ it("re-mints a settled URL on first read and on each new revision, not on remount", () => {
+ const { mount, settle, mints } = setup(minted(0));
+
+ mount("mutation-1")();
+ expect(mints()).toBe(1);
+ settle();
+
+ mount("mutation-1")();
+ expect(mints()).toBe(1);
+
+ mount("mutation-2")();
+ expect(mints()).toBe(2);
+ });
+
+ it("re-mints when a revert returns to an earlier revision", () => {
+ const { mount, settle, mints } = setup(minted(0));
+
+ mount("mutation-a")();
+ settle();
+ mount("mutation-b")();
+ settle();
+ expect(mints()).toBe(2);
+
+ const reverted = mount("mutation-a");
+ expect(mints()).toBe(3);
+ reverted();
+ });
+
+ it("shares a mint in flight on the first read", () => {
+ const { mount, mints } = setup(AsyncResult.initial(true));
+
+ mount("mutation-1")();
+ expect(mints()).toBe(0);
+ });
+
+ it("re-mints after a mint that was in flight when the revision changed", () => {
+ const { mount, settle, mints } = setup(minted(0));
+
+ const before = mount("mutation-1");
+ settle();
+ const edited = mount("mutation-2");
+ expect(mints()).toBe(2);
+ before();
+
+ const stillMinting = mount("mutation-3");
+ edited();
+ expect(mints()).toBe(2);
+
+ settle();
+ expect(mints()).toBe(3);
+ settle();
+ expect(mints()).toBe(3);
+ stillMinting();
+ });
+});
diff --git a/apps/web/src/assets/assetUrls.ts b/apps/web/src/assets/assetUrls.ts
index 38a282279f8..6e0dbfb5c6a 100644
--- a/apps/web/src/assets/assetUrls.ts
+++ b/apps/web/src/assets/assetUrls.ts
@@ -7,8 +7,9 @@ import {
resolveAssetUrl,
} from "@t3tools/client-runtime/state/assets";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
-import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
-import { AsyncResult } from "effect/reactivity";
+import { AssetResource, type AssetCreateUrlResult, EnvironmentId } from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
import { assetEnvironment } from "~/state/assets";
import { useFilesystemReadAccess } from "~/state/filesystem";
@@ -19,16 +20,91 @@ export { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
export type AssetUrlState = RuntimeAssetUrlState & { readonly waiting?: boolean };
+type AssetUrlTarget = {
+ readonly environmentId: EnvironmentId;
+ readonly input: { readonly resource: AssetResource };
+};
+
+const decodeRevisionedAssetUrlKey = Schema.decodeUnknownSync(
+ Schema.Tuple([EnvironmentId, AssetResource, Schema.NullOr(Schema.String)]),
+);
+
+const isSettled = (result: AsyncResult.AsyncResult<unknown, unknown>) =>
+ !AsyncResult.isInitial(result) && !result.waiting;
+
+/**
+ * The URL is minted per resource and shared across revisions, so reading a
+ * different revision (even an earlier one after a revert) re-mints it. An
+ * in-flight mint is shared only on first read; after an edit the server must
+ * re-read the file, so the re-mint waits for that mint to settle.
+ */
+export function makeRevisionedAssetUrlFamily(
+ createUrl: (
+ target: AssetUrlTarget,
+ ) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>,
+) {
+ // Outside the nodes: a node is dropped once unmounted, and the next read of
+ // its revision must still see the revisions minted since. Never pruned on
+ // purpose: pruning would forget the revision and re-mint on the next mount.
+ // It holds one short entry per file shown, and goes with the registry.
+ const mintedUnder = new WeakMap<AtomRegistry.AtomRegistry, Map<string, string | null>>();
+ const family = Atom.family((key: string) => {
+ const [environmentId, resource, revision] = decodeRevisionedAssetUrlKey(JSON.parse(key));
+ const resourceKey = JSON.stringify([environmentId, resource]);
+ const query = createUrl({ environmentId, input: { resource } });
+ return Atom.transform(
+ query,
+ (get) => {
+ let minted = mintedUnder.get(get.registry);
+ if (minted === undefined) {
+ minted = new Map();
+ mintedUnder.set(get.registry, minted);
+ }
+ const firstRead = !minted.has(resourceKey);
+ let pending = minted.get(resourceKey) !== revision;
+ const current = get.once(query);
+ if (pending && (firstRead || isSettled(current))) {
+ pending = false;
+ minted.set(resourceKey, revision);
+ if (isSettled(current)) get.refresh(query);
+ }
+ get.subscribe(query, (value) => {
+ get.setSelf(value);
+ if (!pending || !isSettled(value)) return;
+ pending = false;
+ minted.set(resourceKey, revision);
+ get.refresh(query);
+ });
+ return get.once(query);
+ },
+ { initialValueTarget: query },
+ // No idle TTL: each mount rebuilds the node, so a revision read again after
+ // another one is compared against the record instead of a cached node.
+ ).pipe(Atom.setIdleTTL(0));
+ });
+ return (target: AssetUrlTarget & { readonly revision: string | null }) =>
+ family(JSON.stringify([target.environmentId, target.input.resource, target.revision]));
+}
+
+export const revisionedAssetUrl = makeRevisionedAssetUrlFamily(assetEnvironment.createUrl);
+
+/**
+ * Pass `revision` for a workspace file whose bytes can change under the same
+ * path; each new revision gets a freshly minted URL.
+ */
export function useAssetUrlState(
environmentId: EnvironmentId | null,
resource: AssetResource | null,
+ revision?: string | null,
): AssetUrlState {
const blocked = blockedAssetUrlState(resource, useFilesystemReadAccess(environmentId));
const preparedConnection = usePreparedConnection(environmentId);
const result = useAtomValue(
blocked !== null || environmentId === null || resource === null
? EMPTY_ASSET_URL_ATOM
- : assetEnvironment.createUrl({ environmentId, input: { resource } }),
+ : revision === undefined
+ ? assetEnvironment.createUrl({ environmentId, input: { resource } })
+ : revisionedAssetUrl({ environmentId, input: { resource }, revision }),
);
if (blocked !== null) return blocked;
return {
diff --git a/apps/web/src/assets/longLivedAssetUrls.test.ts b/apps/web/src/assets/longLivedAssetUrls.test.ts
new file mode 100644
index 00000000000..be444bd9561
--- /dev/null
+++ b/apps/web/src/assets/longLivedAssetUrls.test.ts
@@ -0,0 +1,100 @@
+import { EnvironmentId, type AssetResource } from "@t3tools/contracts";
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
+import { describe, expect, it } from "vite-plus/test";
+
+import { makeLongLivedAssetUrlFamily } from "./longLivedAssetUrls";
+
+const environmentId = EnvironmentId.make("environment-1");
+const resource: AssetResource = {
+ _tag: "attachment",
+ attachmentId: "attachment-1",
+ fileName: "page.html",
+ mimeType: "text/html",
+ disposition: "inline",
+};
+
+type MintResult = AsyncResult.AsyncResult<{ relativeUrl: string; expiresAt: number }>;
+
+const url = (relativeUrl: string, expiresAt: number): MintResult =>
+ AsyncResult.success({ relativeUrl, expiresAt });
+
+function setup(initial: MintResult) {
+ let mints = 0;
+ const tasks: Array<() => void> = [];
+ const registry = AtomRegistry.make({
+ scheduleTask: (task) => {
+ tasks.push(task);
+ return () => {};
+ },
+ });
+ const server = Atom.make(initial).pipe(Atom.keepAlive);
+ const query = Atom.readable(
+ (get) => get(server),
+ () => {
+ mints += 1;
+ registry.set(server, AsyncResult.waiting(registry.get(server)));
+ },
+ ).pipe(Atom.keepAlive);
+ const family = makeLongLivedAssetUrlFamily(() => query, { minLifeMs: 100, now: () => 1_000 });
+ const atom = family({ environmentId, input: { resource } });
+ let unmount = registry.mount(atom);
+ // Readers adopt any Success, waiting or not, as `assetUrlStateFromResult` does.
+ const relativeUrl = () => {
+ const value = registry.get(atom);
+ return value._tag === "Success" ? value.value.relativeUrl : null;
+ };
+ return {
+ relativeUrl,
+ mints: () => mints,
+ serve: (result: MintResult) => registry.set(server, result),
+ remount: () => {
+ unmount();
+ // Runs the idle-TTL disposal, so the next mount builds a fresh node.
+ for (const task of tasks.splice(0)) task();
+ unmount = registry.mount(atom);
+ },
+ };
+}
+
+describe("makeLongLivedAssetUrlFamily", () => {
+ it("reuses a cached URL with enough life left", () => {
+ const { relativeUrl, mints } = setup(url("/cached", 2_000));
+ expect(relativeUrl()).toBe("/cached");
+ expect(mints()).toBe(0);
+ });
+
+ it("mints a URL near expiry and hides it until the new one arrives", () => {
+ const { relativeUrl, mints, serve } = setup(url("/stale", 1_050));
+ expect(mints()).toBe(1);
+ expect(relativeUrl()).toBeNull();
+
+ serve(url("/fresh", 5_000));
+ expect(relativeUrl()).toBe("/fresh");
+ });
+
+ it("does not hand a new reader the expiring URL while an earlier reader's mint is in flight", () => {
+ const { relativeUrl, mints, serve, remount } = setup(url("/stale", 1_050));
+ expect(mints()).toBe(1);
+ remount();
+ expect(relativeUrl()).toBeNull();
+
+ serve(url("/fresh", 5_000));
+ expect(relativeUrl()).toBe("/fresh");
+ expect(mints()).toBe(1);
+ });
+
+ it("mints at most once when the clock disagrees with the server", () => {
+ const { relativeUrl, mints, serve } = setup(url("/stale", 1_050));
+ serve(url("/still-short", 1_050));
+ expect(relativeUrl()).toBe("/still-short");
+ expect(mints()).toBe(1);
+ });
+
+ it("waits for a URL still loading", () => {
+ const { relativeUrl, mints, serve } = setup(AsyncResult.initial(true));
+ expect(relativeUrl()).toBeNull();
+ serve(url("/loaded", 5_000));
+ expect(relativeUrl()).toBe("/loaded");
+ expect(mints()).toBe(0);
+ });
+});
diff --git a/apps/web/src/assets/longLivedAssetUrls.ts b/apps/web/src/assets/longLivedAssetUrls.ts
new file mode 100644
index 00000000000..2643e44751b
--- /dev/null
+++ b/apps/web/src/assets/longLivedAssetUrls.ts
@@ -0,0 +1,87 @@
+import { useAtomValue } from "@effect/atom-react";
+import {
+ type AssetUrlState,
+ assetUrlStateFromResult,
+ blockedAssetUrlState,
+ EMPTY_ASSET_URL_ATOM,
+} from "@t3tools/client-runtime/state/assets";
+import { AssetResource, type AssetCreateUrlResult, EnvironmentId } from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+import { AsyncResult, Atom } from "effect/reactivity";
+
+import { assetEnvironment } from "~/state/assets";
+import { useFilesystemReadAccess } from "~/state/filesystem";
+import { usePreparedConnection } from "~/state/session";
+
+type AssetUrlTarget = {
+ readonly environmentId: EnvironmentId;
+ readonly input: { readonly resource: AssetResource };
+};
+
+const decodeAssetUrlKey = Schema.decodeUnknownSync(Schema.Tuple([EnvironmentId, AssetResource]));
+
+/**
+ * Asset URLs for documents that cannot report a failed load, such as frames. A
+ * cached URL with `minLifeMs` left is reused; one closer to expiry is re-minted.
+ * A node mints at most once, so a skewed client clock cannot mint on every update.
+ */
+export function makeLongLivedAssetUrlFamily(
+ createUrl: (
+ target: AssetUrlTarget,
+ ) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>,
+ options: { readonly minLifeMs: number; readonly now?: () => number },
+) {
+ const now = options.now ?? Date.now;
+ const family = Atom.family((key: string) => {
+ const [environmentId, resource] = decodeAssetUrlKey(JSON.parse(key));
+ const query = createUrl({ environmentId, input: { resource } });
+ return Atom.transform(
+ query,
+ (get) => {
+ let minting = false;
+ const settle = (
+ value: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
+ ): AsyncResult.AsyncResult<AssetCreateUrlResult, unknown> => {
+ if (value._tag !== "Success") return value;
+ const lasts = value.value.expiresAt - now() > options.minLifeMs;
+ // An expiring URL must not be handed out while its successor mints,
+ // whichever reader started the mint.
+ if (value.waiting) return lasts ? value : AsyncResult.initial(true);
+ if (minting || lasts) return value;
+ minting = true;
+ get.refresh(query);
+ return AsyncResult.initial(true);
+ };
+ get.subscribe(query, (value) => get.setSelf(settle(value)));
+ return settle(get.once(query));
+ },
+ { initialValueTarget: query },
+ // Each mount gets its own node, so a later mount may mint again.
+ ).pipe(Atom.setIdleTTL(0));
+ });
+ return (target: AssetUrlTarget) =>
+ family(JSON.stringify([target.environmentId, target.input.resource]));
+}
+
+const longLivedAssetUrl = makeLongLivedAssetUrlFamily(assetEnvironment.createUrl, {
+ minLifeMs: 5 * 60_000,
+});
+
+/** Pass a null environment once the URL is adopted, so later mints do not re-render. */
+export function useLongLivedAssetUrl(
+ environmentId: EnvironmentId | null,
+ resource: AssetResource,
+): AssetUrlState {
+ const blocked = blockedAssetUrlState(resource, useFilesystemReadAccess(environmentId));
+ const preparedConnection = usePreparedConnection(environmentId);
+ const result = useAtomValue(
+ blocked !== null || environmentId === null
+ ? EMPTY_ASSET_URL_ATOM
+ : longLivedAssetUrl({ environmentId, input: { resource } }),
+ );
+ if (blocked !== null) return blocked;
+ return assetUrlStateFromResult(
+ result,
+ preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null,
+ );
+}
diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx
new file mode 100644
index 00000000000..3c49f7a88f4
--- /dev/null
+++ b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx
@@ -0,0 +1,86 @@
+import type { PreparedConnection } from "@t3tools/client-runtime/connection";
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { render } from "../../../test/render";
+import { ChatMarkdownAssetImage } from "./ChatMarkdownMedia";
+
+// Every evaluation of the URL query is one mint: the first read, then one per refresh.
+const assetQuery = vi.hoisted(() => ({ mints: 0 }));
+vi.mock(import("~/state/assets"), async (original) => {
+ const { AsyncResult, Atom } = await import("effect/reactivity");
+ const createUrl = Atom.family((_key: string) =>
+ Atom.make(() => {
+ assetQuery.mints += 1;
+ return AsyncResult.success({
+ relativeUrl:
+ "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
+ expiresAt: Number.MAX_SAFE_INTEGER,
+ });
+ }).pipe(Atom.keepAlive),
+ );
+ const actual = await original();
+ return {
+ ...actual,
+ assetEnvironment: {
+ ...actual.assetEnvironment,
+ createUrl: (target: { readonly input: unknown }) => createUrl(JSON.stringify(target.input)),
+ },
+ };
+});
+vi.mock(import("~/state/session"), async (original) => {
+ const { Option } = await import("effect");
+ const { PrimaryConnectionTarget } = await import("@t3tools/client-runtime/connection");
+ const { EnvironmentId } = await import("@t3tools/contracts");
+ const target = new PrimaryConnectionTarget({
+ environmentId: EnvironmentId.make("environment-1"),
+ label: "Local",
+ httpBaseUrl: "http://localhost:1",
+ wsBaseUrl: "ws://localhost:1",
+ });
+ const prepared: PreparedConnection = {
+ environmentId: target.environmentId,
+ label: target.label,
+ httpBaseUrl: target.httpBaseUrl,
+ socketUrl: target.wsBaseUrl,
+ httpAuthorization: null,
+ target,
+ };
+ return {
+ ...(await original()),
+ usePreparedConnection: () => Option.some(prepared),
+ };
+});
+vi.mock(import("~/state/filesystem"), async (original) => ({
+ ...(await original()),
+ useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
+}));
+
+describe("ChatMarkdownAssetImage", () => {
+ it("does not re-mint an unchanged workspace image's URL on remount", async () => {
+ assetQuery.mints = 0;
+ const image = (
+ <ChatMarkdownAssetImage
+ environmentId={EnvironmentId.make("environment-1")}
+ resource={{
+ _tag: "workspace-file",
+ threadId: ThreadId.make("thread-1"),
+ path: "docs/diagram.png",
+ }}
+ alt="diagram"
+ workspaceMutationId="mutation-1"
+ />
+ );
+
+ {
+ await using screen = await render(image);
+ await expect.element(screen.getByRole("img", { name: "diagram" })).toBeInTheDocument();
+ }
+ // The first mount at a known revision re-mints the cached URL once.
+ expect(assetQuery.mints).toBe(2);
+
+ await using screen = await render(<ChatMarkdownAssetImage {...image.props} />);
+ await expect.element(screen.getByRole("img", { name: "diagram" })).toBeInTheDocument();
+ expect(assetQuery.mints).toBe(2);
+ });
+});
diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.tsx
index 18aadf4b76d..f2740de785b 100644
--- a/apps/web/src/components/chat/ChatMarkdownMedia.tsx
+++ b/apps/web/src/components/chat/ChatMarkdownMedia.tsx
@@ -5,8 +5,6 @@ import { TriangleAlertIcon } from "lucide-react";
import {
createContext,
memo,
- useEffect,
- useRef,
useState,
type ComponentProps,
type CSSProperties,
@@ -17,7 +15,6 @@ import {
import { useAssetUrlRefresh, useAssetUrlState } from "../../assets/assetUrls";
import { cn } from "../../lib/utils";
import { useRightPanelStore } from "../../rightPanelStore";
-import { usePreparedConnection } from "../../state/session";
import { MediaActions, type MediaActionSource } from "../media/MediaActions";
import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
import type { ExpandedImagePreview } from "./ExpandedImagePreview";
@@ -341,44 +338,17 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
readonly workspaceMutationId?: string | null | undefined;
readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
}) {
- const assetUrl = useAssetUrlState(props.environmentId, props.resource);
- const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, props.resource);
- const connectionReady = usePreparedConnection(props.environmentId)._tag === "Some";
const resource = props.resource;
- const refreshToken = JSON.stringify([props.environmentId, resource, props.workspaceMutationId]);
- const handledRefreshToken = useRef<string | null | undefined>(undefined);
- const assetLoading = assetUrl._tag === "Loading" || assetUrl.waiting === true;
- useEffect(() => {
- if (!connectionReady) {
- handledRefreshToken.current = null;
- return;
- }
- if (
- props.workspaceMutationId === undefined ||
- props.kind === "video" ||
- (resource._tag !== "media-file" && resource._tag !== "workspace-file") ||
- handledRefreshToken.current === refreshToken
- ) {
- return;
- }
- if (assetLoading) {
- // Only the initial mount shares a pending request; edits and reconnects need a new one.
- if (handledRefreshToken.current === undefined) {
- handledRefreshToken.current = refreshToken;
- }
- return;
- }
- handledRefreshToken.current = refreshToken;
- void refreshAssetUrl().catch(() => undefined);
- }, [
- assetLoading,
- connectionReady,
- props.kind,
- props.workspaceMutationId,
- refreshAssetUrl,
- refreshToken,
- resource._tag,
- ]);
+ const assetUrl = useAssetUrlState(
+ props.environmentId,
+ resource,
+ props.workspaceMutationId !== undefined &&
+ props.kind !== "video" &&
+ (resource._tag === "media-file" || resource._tag === "workspace-file")
+ ? props.workspaceMutationId
+ : undefined,
+ );
+ const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
const path =
resource._tag === "media-file"
? resource.path
diff --git a/apps/web/src/components/chat/HtmlRenderFrame.tsx b/apps/web/src/components/chat/HtmlRenderFrame.tsx
index c6afd6a2d22..cbf9edaefaa 100644
--- a/apps/web/src/components/chat/HtmlRenderFrame.tsx
+++ b/apps/web/src/components/chat/HtmlRenderFrame.tsx
@@ -8,7 +8,8 @@ import {
import { Maximize2Icon } from "lucide-react";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
-import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
+import { useAssetUrlRefresh } from "~/assets/assetUrls";
+import { useLongLivedAssetUrl } from "~/assets/longLivedAssetUrls";
import { HtmlRenderDocument } from "../files/BrowserDocumentFrame";
import { Button } from "../ui/button";
@@ -47,9 +48,15 @@ export function HtmlRenderFrame(props: {
mimeType: "text/html",
disposition: "inline" as const,
};
- // Re-mint near-expiry URLs because frames cannot report failed loads.
- const [src, setSrc] = useState<string | null>(null);
- const srcExpiresAt = useRef(0);
+ // The frame keeps the first URL it loads, so later mints do not reload the page.
+ const [loaded, setLoaded] = useState<{ src: string; expiresAt: number } | null>(null);
+ const assetUrl = useLongLivedAssetUrl(loaded === null ? props.environmentId : null, resource);
+ if (loaded === null && assetUrl._tag === "Success") {
+ setLoaded({ src: assetUrl.url, expiresAt: assetUrl.expiresAt });
+ }
+ const src = loaded?.src ?? null;
+ const failed = loaded === null && assetUrl._tag === "Failure";
+ const refresh = useAssetUrlRefresh(props.environmentId, resource);
const [expandedSrc, setExpandedSrc] = useState<string | null>(null);
const { onFullscreenChange } = props;
useEffect(() => {
@@ -57,33 +64,6 @@ export function HtmlRenderFrame(props: {
onFullscreenChange?.(true);
return () => onFullscreenChange?.(false);
}, [expandedSrc, onFullscreenChange]);
- const [failed, setFailed] = useState(false);
- const assetUrl = useAssetUrlState(src === null ? props.environmentId : null, resource);
- const cachedUrl = assetUrl._tag === "Success" ? assetUrl.url : null;
- const cachedExpiresAt = assetUrl._tag === "Success" ? assetUrl.expiresAt : 0;
- const cacheFailed = assetUrl._tag === "Failure";
- const refresh = useAssetUrlRefresh(props.environmentId, resource);
- // Mint once per mount to prevent clock skew from causing repeated mints.
- const minting = useRef(false);
- useEffect(() => {
- if (src !== null || minting.current) return;
- if (cacheFailed) {
- // oxlint-disable-next-line react/set-state-in-effect -- Mirrors the cached URL's failure.
- setFailed(true);
- return;
- }
- if (cachedUrl === null) return;
- if (cachedExpiresAt - Date.now() > MIN_URL_LIFE_MS) {
- srcExpiresAt.current = cachedExpiresAt;
- setSrc(cachedUrl);
- return;
- }
- minting.current = true;
- void refresh().then(
- (url) => (url === null ? setFailed(true) : setSrc(url)),
- () => setFailed(true),
- );
- }, [cacheFailed, cachedExpiresAt, cachedUrl, refresh, src]);
return (
<div ref={boxRef} className="group/html-render relative" style={{ height }}>
@@ -107,7 +87,7 @@ export function HtmlRenderFrame(props: {
variant="glass"
onClick={async () => {
const url =
- srcExpiresAt.current - Date.now() > MIN_URL_LIFE_MS
+ loaded !== null && loaded.expiresAt - Date.now() > MIN_URL_LIFE_MS
? src
: await refresh().catch(() => null);
if (url !== null) setExpandedSrc(url);