From c868f11acac7b6a8f92002ff9efd7157180df55e Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 25 Oct 2026 12:53:46 -0700 Subject: [PATCH 1/5] fix(web): asset URLs re-mint per revision and before expiry without effects Problem: ChatMarkdownMedia re-minted a workspace image's URL from an effect keyed on a per-mount ref, so every remount of an unchanged file minted a new URL and reloaded the image. HtmlRenderFrame re-minted near-expiry frame URLs from an effect that copied the cached URL and its failure into state. Fix: two keyed atom families in apps/web/src/assets. - revisionedAssetUrl (via useAssetUrlState's new `revision` argument) records the revision each resource was minted under per registry, so a new revision (or a revert to an earlier one) re-mints, a remount of the same revision does not, and an in-flight mint is shared only on first read. - useLongLivedAssetUrl reuses a cached URL with five minutes left and re-mints at most once per mount otherwise, never handing out the expiring URL while its successor mints. ChatMarkdownMedia and HtmlRenderFrame read these. Effects removed: the ChatMarkdownMedia refresh effect and the HtmlRenderFrame mint effect. Kept: HtmlRenderFrame's resize layout effect and full-screen notification effect, which other changes own. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/assets/assetUrls.test.ts | 107 ++++++++++++++++++ apps/web/src/assets/assetUrls.ts | 80 ++++++++++++- .../web/src/assets/longLivedAssetUrls.test.ts | 100 ++++++++++++++++ apps/web/src/assets/longLivedAssetUrls.ts | 87 ++++++++++++++ .../src/components/chat/ChatMarkdownMedia.tsx | 50 ++------ .../src/components/chat/HtmlRenderFrame.tsx | 44 ++----- 6 files changed, 393 insertions(+), 75 deletions(-) create mode 100644 apps/web/src/assets/assetUrls.test.ts create mode 100644 apps/web/src/assets/longLivedAssetUrls.test.ts create mode 100644 apps/web/src/assets/longLivedAssetUrls.ts diff --git a/apps/web/src/assets/assetUrls.test.ts b/apps/web/src/assets/assetUrls.test.ts new file mode 100644 index 0000000000000..bb442959f1813 --- /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 38a282279f8f0..8d1f77bed75bc 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,89 @@ 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) => + !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>, +) { + // Outside the nodes: a node is dropped once unmounted, and the next read of + // its revision must still see the revisions minted since. + const mintedUnder = new WeakMap>(); + 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 0000000000000..6bf6874f710a2 --- /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", +} as AssetResource; + +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 0000000000000..2643e44751be2 --- /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>, + 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, + ): AsyncResult.AsyncResult => { + 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.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.tsx index 18aadf4b76ddc..f2740de785b29 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(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 c6afd6a2d2299..cbf9edaefaa0f 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(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(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 (
@@ -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); From d1c1dea50483000370e882dd0b0df28bb778d03a Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:09:31 -0700 Subject: [PATCH 2/5] test(web): remounting an unchanged workspace image does not re-mint its URL Adds a ChatMarkdownAssetImage browser test that fails on main (3 mints, expected 2), notes why the minted-revision record is never pruned, and types the long-lived test resource without a cast. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/assets/assetUrls.ts | 4 +- .../web/src/assets/longLivedAssetUrls.test.ts | 2 +- .../chat/ChatMarkdownMedia.browser.test.tsx | 69 +++++++++++++++++++ 3 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx diff --git a/apps/web/src/assets/assetUrls.ts b/apps/web/src/assets/assetUrls.ts index 8d1f77bed75bc..6e0dbfb5c6aee 100644 --- a/apps/web/src/assets/assetUrls.ts +++ b/apps/web/src/assets/assetUrls.ts @@ -44,7 +44,9 @@ export function makeRevisionedAssetUrlFamily( ) => Atom.Atom>, ) { // Outside the nodes: a node is dropped once unmounted, and the next read of - // its revision must still see the revisions minted since. + // 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>(); const family = Atom.family((key: string) => { const [environmentId, resource, revision] = decodeRevisionedAssetUrlKey(JSON.parse(key)); diff --git a/apps/web/src/assets/longLivedAssetUrls.test.ts b/apps/web/src/assets/longLivedAssetUrls.test.ts index 6bf6874f710a2..be444bd9561c5 100644 --- a/apps/web/src/assets/longLivedAssetUrls.test.ts +++ b/apps/web/src/assets/longLivedAssetUrls.test.ts @@ -11,7 +11,7 @@ const resource: AssetResource = { fileName: "page.html", mimeType: "text/html", disposition: "inline", -} as AssetResource; +}; type MintResult = AsyncResult.AsyncResult<{ relativeUrl: string; expiresAt: number }>; 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 0000000000000..45d25f7d13149 --- /dev/null +++ b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx @@ -0,0 +1,69 @@ +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"); + return { + ...(await original()), + usePreparedConnection: (() => Option.some({ httpBaseUrl: "http://localhost:1" })) as never, + }; +}); +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 = ( + + ); + + { + 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(); + await expect.element(screen.getByRole("img", { name: "diagram" })).toBeInTheDocument(); + expect(assetQuery.mints).toBe(2); + }); +}); From 50a61e5b09a5ca33fd7bf45aeb0dad994d869f03 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:24:00 -0700 Subject: [PATCH 3/5] test(web): type the prepared connection fixture in the asset image test Co-Authored-By: Claude Opus 5.5 --- .../chat/ChatMarkdownMedia.browser.test.tsx | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx index 45d25f7d13149..3c49f7a88f45b 100644 --- a/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx +++ b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx @@ -1,3 +1,4 @@ +import type { PreparedConnection } from "@t3tools/client-runtime/connection"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; @@ -29,9 +30,25 @@ vi.mock(import("~/state/assets"), async (original) => { }); 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({ httpBaseUrl: "http://localhost:1" })) as never, + usePreparedConnection: () => Option.some(prepared), }; }); vi.mock(import("~/state/filesystem"), async (original) => ({ From c865f34c50ba243b2a829b4811f43de736ec9c82 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 25 Oct 2026 14:16:35 -0700 Subject: [PATCH 4/5] chore: lower the effect budget for the removed effects Co-Authored-By: Claude Opus 5.5 --- scripts/effect-budget.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/scripts/effect-budget.json b/scripts/effect-budget.json index eba1a2c4822cb..2128632407c41 100644 --- a/scripts/effect-budget.json +++ b/scripts/effect-budget.json @@ -227,7 +227,6 @@ "apps/web/src/components/chat/ChatCanvas.tsx": 1, "apps/web/src/components/chat/ChatComposer.tsx": 26, "apps/web/src/components/chat/ChatHeader.tsx": 2, - "apps/web/src/components/chat/ChatMarkdownMedia.tsx": 1, "apps/web/src/components/chat/ChatOverlayHosts.tsx": 1, "apps/web/src/components/chat/CommandOutputPanel.tsx": 1, "apps/web/src/components/chat/ComposerAttachmentStrip.tsx": 1, @@ -240,7 +239,7 @@ "apps/web/src/components/chat/DraftHeroHeadline.tsx": 1, "apps/web/src/components/chat/DraftHeroProjectHeading.tsx": 1, "apps/web/src/components/chat/ExpandedImageDialog.tsx": 4, - "apps/web/src/components/chat/HtmlRenderFrame.tsx": 3, + "apps/web/src/components/chat/HtmlRenderFrame.tsx": 2, "apps/web/src/components/chat/MarkdownCodeBlock.tsx": 3, "apps/web/src/components/chat/MarkdownTable.tsx": 3, "apps/web/src/components/chat/McpAppFrame.tsx": 10, From b999729c781bcf286ecee5cb10e947b9956adf78 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:20:55 -0700 Subject: [PATCH 5/5] chore: leave the effect budget to a separate sweep Co-Authored-By: Claude Opus 5.5 --- scripts/effect-budget.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/effect-budget.json b/scripts/effect-budget.json index 2128632407c41..eba1a2c4822cb 100644 --- a/scripts/effect-budget.json +++ b/scripts/effect-budget.json @@ -227,6 +227,7 @@ "apps/web/src/components/chat/ChatCanvas.tsx": 1, "apps/web/src/components/chat/ChatComposer.tsx": 26, "apps/web/src/components/chat/ChatHeader.tsx": 2, + "apps/web/src/components/chat/ChatMarkdownMedia.tsx": 1, "apps/web/src/components/chat/ChatOverlayHosts.tsx": 1, "apps/web/src/components/chat/CommandOutputPanel.tsx": 1, "apps/web/src/components/chat/ComposerAttachmentStrip.tsx": 1, @@ -239,7 +240,7 @@ "apps/web/src/components/chat/DraftHeroHeadline.tsx": 1, "apps/web/src/components/chat/DraftHeroProjectHeading.tsx": 1, "apps/web/src/components/chat/ExpandedImageDialog.tsx": 4, - "apps/web/src/components/chat/HtmlRenderFrame.tsx": 2, + "apps/web/src/components/chat/HtmlRenderFrame.tsx": 3, "apps/web/src/components/chat/MarkdownCodeBlock.tsx": 3, "apps/web/src/components/chat/MarkdownTable.tsx": 3, "apps/web/src/components/chat/McpAppFrame.tsx": 10,