Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6872: fix(web): keep inline image blob URLs stable across re-entry to prevent flicker (#7799)
makesomethingshit0b98fe8ce1aa
diff --git a/packages/views/editor/attachment.test.tsx b/packages/views/editor/attachment.test.tsxindex fcd6f1271c..0b3c9768c6 100644--- a/packages/views/editor/attachment.test.tsx+++ b/packages/views/editor/attachment.test.tsx@@ -101,7 +101,8 @@ function attachmentIdFromTestDownloadURL(url: string): string | undefined {? (() => {try {return new URL(url).pathname;- } catch {+ } catch (_err) {+ void _err;return "";}})()@@ -190,7 +191,18 @@ beforeEach(() => {});});-afterEach(() => {+afterEach(async () => {+ // Flush any pending blob URL GC timers that use fake timers in suites.+ if (vi.isFakeTimers()) {+ await vi.runAllTimersAsync();+ vi.useRealTimers();+ }+ try {+ const { __resetInlineMediaBlobCacheForTests } = await import("./hooks/use-inline-media-url");+ __resetInlineMediaBlobCacheForTests();+ } catch (_err) {+ void _err;+ }restoreObjectURL("createObjectURL", originalCreateObjectURL);restoreObjectURL("revokeObjectURL", originalRevokeObjectURL);vi.restoreAllMocks();@@ -548,9 +560,13 @@ describe("Attachment — image dispatch", () => {expect(getAttachmentBlobMock).toHaveBeenCalledWith(id);expect(createObjectURLMock).toHaveBeenCalledWith(blob);- // The bytes are released once nothing renders them.+ // The bytes are scheduled for release 5 min after last unmount.+ vi.useFakeTimers();unmount();+ expect(revokeObjectURLMock).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);expect(revokeObjectURLMock).toHaveBeenCalledWith(OBJECT_URL);+ vi.useRealTimers();});it("copies the durable URL, not the session-local object URL (MUL-5445)", async () => {@@ -959,3 +975,202 @@ describe("Attachment — absolutize site-relative URLs (MUL-3192)", () => {expect(img?.getAttribute("src")).toBe("/api/attachments/abc-3/download");});});++describe("Attachment — blob URL GC (MUL-7741)", () => {+ it("defers revoke by 5 min after last unmount", async () => {+ getBaseUrlMock.mockReturnValue("https://multica-api.copilothub.ai");+ const id = "11111111-2222-3333-4444-555555555555";+ const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;+ resolverState.attachments = [+ makeRecord({ id, url: "https://minio:9000/multica/uploads/ws/shot.png", markdown_url: markdownUrl, download_url: "" }),+ ];+ getAttachmentMock.mockResolvedValue(makeRecord({ id, download_url: `/api/attachments/${id}/download` }));+ const blob = new Blob(["png-bytes"], { type: "image/png" });+ getAttachmentBlobMock.mockResolvedValue(blob);++ const { unmount } = renderWithQuery(+ <Attachment attachment={{ kind: "url", url: markdownUrl, filename: "shot.png", forceKind: "image" }} />,+ );+ await waitFor(() => expect(document.querySelector("img")?.getAttribute("src")).toBe(OBJECT_URL));+ expect(createObjectURLMock).toHaveBeenCalledTimes(1);+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });+ unmount();+ expect(revokeObjectURLMock).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000 - 1000);+ expect(revokeObjectURLMock).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1000);+ expect(revokeObjectURLMock).toHaveBeenCalledWith(OBJECT_URL);+ vi.useRealTimers();+ });++ it("cancels pending GC on re-enter before expiry", async () => {+ getBaseUrlMock.mockReturnValue("https://multica-api.copilothub.ai");+ const id = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";+ const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;+ resolverState.attachments = [makeRecord({ id, url: "https://minio:9000/a.png", markdown_url: markdownUrl, download_url: "" })];+ getAttachmentMock.mockResolvedValue(makeRecord({ id, download_url: `/api/attachments/${id}/download` }));+ const blob = new Blob(["x"], { type: "image/png" });+ getAttachmentBlobMock.mockResolvedValue(blob);+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ const first = render(+ <QueryClientProvider client={qc}>+ <Attachment attachment={{ kind: "url", url: markdownUrl, filename: "shot.png", forceKind: "image" }} />+ </QueryClientProvider>,+ );+ await waitFor(() => expect(document.querySelector("img")?.getAttribute("src")).toBe(OBJECT_URL));+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });+ first.unmount();+ await vi.advanceTimersByTimeAsync(60 * 1000);+ vi.useRealTimers();+ const second = render(+ <QueryClientProvider client={qc}>+ <Attachment attachment={{ kind: "url", url: markdownUrl, filename: "shot.png", forceKind: "image" }} />+ </QueryClientProvider>,+ );+ await waitFor(() => expect(document.querySelector("img")?.getAttribute("src")).toBe(OBJECT_URL));+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });+ // Pending GC was cancelled on re-enter — advancing to original expiry must NOT revoke+ await vi.advanceTimersByTimeAsync(4 * 60 * 1000);+ expect(revokeObjectURLMock).not.toHaveBeenCalled();+ second.unmount();+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);+ expect(revokeObjectURLMock).toHaveBeenCalledWith(OBJECT_URL);+ vi.useRealTimers();+ });++ it("reuses cached blob URL on re-enter before GC expiry without new createObjectURL", async () => {+ getBaseUrlMock.mockReturnValue("https://multica-api.copilothub.ai");+ const id = "99999999-aaaa-bbbb-cccc-dddddddddddd";+ const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;+ resolverState.attachments = [makeRecord({ id, url: "https://minio:9000/r.png", markdown_url: markdownUrl, download_url: "" })];+ getAttachmentMock.mockResolvedValue(makeRecord({ id, download_url: `/api/attachments/${id}/download` }));+ getAttachmentBlobMock.mockResolvedValue(new Blob(["r"], { type: "image/png" }));+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ const first = render(+ <QueryClientProvider client={qc}>+ <Attachment attachment={{ kind: "url", url: markdownUrl, filename: "r.png", forceKind: "image" }} />+ </QueryClientProvider>,+ );+ await waitFor(() => expect(document.querySelector("img")?.getAttribute("src")).toBe(OBJECT_URL));+ expect(createObjectURLMock).toHaveBeenCalledTimes(1);+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });+ first.unmount();+ await vi.advanceTimersByTimeAsync(60 * 1000);+ createObjectURLMock.mockClear();+ const second = render(+ <QueryClientProvider client={qc}>+ <Attachment attachment={{ kind: "url", url: markdownUrl, filename: "r.png", forceKind: "image" }} />+ </QueryClientProvider>,+ );+ // Same session — cached fresh + blob URL reused synchronously (no network).+ expect(document.querySelector("img")?.getAttribute("src")).toBe(OBJECT_URL);+ expect(createObjectURLMock).not.toHaveBeenCalled();+ second.unmount();+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);+ expect(revokeObjectURLMock).toHaveBeenCalledWith(OBJECT_URL);+ vi.useRealTimers();+ });++ it("both concurrent consumers of same id get blob URL (no fallback stick)", async () => {+ getBaseUrlMock.mockReturnValue("https://multica-api.copilothub.ai");+ const id = "cccccccc-cccc-cccc-cccc-cccccccccccc";+ const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;+ resolverState.attachments = [makeRecord({ id, url: "https://minio:9000/c.png", markdown_url: markdownUrl, download_url: "" })];+ getAttachmentMock.mockResolvedValue(makeRecord({ id, download_url: `/api/attachments/${id}/download` }));+ getAttachmentBlobMock.mockResolvedValue(new Blob(["c"], { type: "image/png" }));+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ const { unmount } = render(+ <QueryClientProvider client={qc}>+ <Attachment attachment={{ kind: "url", url: markdownUrl, filename: "c.png", forceKind: "image" }} />+ <Attachment attachment={{ kind: "url", url: markdownUrl, filename: "c.png", forceKind: "image" }} />+ </QueryClientProvider>,+ );+ await waitFor(() => {+ const imgs = document.querySelectorAll("img");+ expect(imgs).toHaveLength(2);+ expect(imgs[0]?.getAttribute("src")).toBe(OBJECT_URL);+ expect(imgs[1]?.getAttribute("src")).toBe(OBJECT_URL);+ });+ expect(createObjectURLMock).toHaveBeenCalledTimes(1);+ vi.useFakeTimers();+ unmount();+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);+ expect(revokeObjectURLMock).toHaveBeenCalledWith(OBJECT_URL);+ vi.useRealTimers();+ });++ it("does not show previous image when gallery id changes and new blob fetch fails (A→B) via rerender", async () => {+ getBaseUrlMock.mockReturnValue("https://multica-api.copilothub.ai");+ const idA = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";+ const idB = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";+ const urlA = `https://multica-api.copilothub.ai/api/attachments/${idA}/download`;+ const urlB = `https://multica-api.copilothub.ai/api/attachments/${idB}/download`;+ resolverState.attachments = [+ makeRecord({ id: idA, url: "https://minio:9000/a.png", markdown_url: urlA, download_url: "" }),+ makeRecord({ id: idB, url: "https://minio:9000/b.png", markdown_url: urlB, download_url: "" }),+ ];+ getAttachmentMock.mockImplementation((id: string) => Promise.resolve(makeRecord({ id, download_url: `/api/attachments/${id}/download` })));+ getAttachmentBlobMock.mockImplementation((id: string) => {+ if (id === idA) return Promise.resolve(new Blob(["a"], { type: "image/png" }));+ return Promise.reject(new Error("fetch failed"));+ });+ const { rerender, unmount } = renderWithQuery(<Attachment attachment={{ kind: "url", url: urlA, filename: "a.png", forceKind: "image" }} />);+ await waitFor(() => expect(document.querySelector("img")?.getAttribute("src")).toBe(OBJECT_URL));+ // Same instance id change — panel reuse, not unmount+mount+ rerender(+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } })}>+ <Attachment attachment={{ kind: "url", url: urlB, filename: "b.png", forceKind: "image" }} />+ </QueryClientProvider>,+ );+ await waitFor(() => expect(document.querySelector("img")?.getAttribute("src")).toBe(urlB));+ expect(document.querySelector("img")?.getAttribute("src")).not.toBe(OBJECT_URL);+ unmount();+ });++ it("does not reuse previous account blob URL after query cache clear on account switch", async () => {+ getBaseUrlMock.mockReturnValue("https://multica-api.copilothub.ai");+ const id = "dddddddd-eeee-ffff-aaaa-bbbbbbbbbbbb";+ const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;+ const record = makeRecord({ id, url: "https://minio:9000/d.png", markdown_url: markdownUrl, download_url: "" });+ resolverState.attachments = [record];+ getAttachmentMock.mockResolvedValue(record);+ getAttachmentBlobMock.mockResolvedValue(new Blob(["d"], { type: "image/png" }));+ const qcA = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ const first = render(+ <QueryClientProvider client={qcA}>+ <Attachment attachment={{ kind: "url", url: markdownUrl, filename: "d.png", forceKind: "image" }} />+ </QueryClientProvider>,+ );+ await waitFor(() => expect(document.querySelector("img")?.getAttribute("src")).toBe(OBJECT_URL));+ first.unmount();+ expect(revokeObjectURLMock).not.toHaveBeenCalled();+ getAttachmentMock.mockImplementation(() => new Promise(() => {}));+ getAttachmentBlobMock.mockClear();+ const qcB = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ const { unmount: unmountB } = render(+ <QueryClientProvider client={qcB}>+ <Attachment attachment={{ kind: "url", url: markdownUrl, filename: "d.png", forceKind: "image" }} />+ </QueryClientProvider>,+ );+ await new Promise((r) => setTimeout(r, 20));+ expect(document.querySelector("img")?.getAttribute("src")).toBe(markdownUrl);+ expect(document.querySelector("img")?.getAttribute("src")).not.toBe(OBJECT_URL);+ expect(getAttachmentBlobMock).not.toHaveBeenCalled();+ unmountB();+ getAttachmentMock.mockRejectedValue(new Error("forbidden"));+ const qcB2 = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ const { unmount: unmountB2 } = render(+ <QueryClientProvider client={qcB2}>+ <Attachment attachment={{ kind: "url", url: markdownUrl, filename: "d.png", forceKind: "image" }} />+ </QueryClientProvider>,+ );+ await new Promise((r) => setTimeout(r, 20));+ expect(document.querySelector("img")?.getAttribute("src")).not.toBe(OBJECT_URL);+ expect(getAttachmentBlobMock).not.toHaveBeenCalled();+ unmountB2();+ // A's blob cache still exists (GC is 5 min) — verify revoke hasn't happened yet+ // and B still shows fallback, not A's bytes. The GC timer itself is+ // exercised by the sibling tests above.+ expect(revokeObjectURLMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/editor/hooks/use-inline-media-url.ts b/packages/views/editor/hooks/use-inline-media-url.tsindex f5f1a0a1cd..d542f90c9f 100644--- a/packages/views/editor/hooks/use-inline-media-url.ts+++ b/packages/views/editor/hooks/use-inline-media-url.ts@@ -25,7 +25,22 @@ const RESIGN_STALE_MS = 20 * 60 * 1000;// `staleTime: Infinity`; this bound exists purely to keep a long scroll// through an image-heavy thread from pinning every decoded screenshot in// renderer memory forever.-const INLINE_BLOB_GC_MS = 5 * 60 * 1000;+export const INLINE_BLOB_GC_MS = 5 * 60 * 1000;++// Module-level cache for blob: URLs keyed by attachment id. Without this,+// useObjectURL creates a new object URL on every mount (state "" -> effect+// creates URL), so a cached blob still flashes the fallback pickedUrl for one+// frame on re-entry — the flicker reported in #7741 for image-heavy issues.+const blobUrlCache = new Map<string, string>();+const blobUrlRefCount = new Map<string, number>();+const blobUrlGCTimers = new Map<string, ReturnType<typeof setTimeout>>();++export function __resetInlineMediaBlobCacheForTests(): void {+ for (const t of blobUrlGCTimers.values()) clearTimeout(t);+ blobUrlGCTimers.clear();+ blobUrlRefCount.clear();+ blobUrlCache.clear();+}// useResignedInlineMediaURL upgrades an auth-gated media URL to a freshly// signed one for clients that cannot load `/api/attachments/<id>/download`@@ -71,7 +86,8 @@ export function useResignedInlineMediaURL(}try {return new URL(pickedUrl).origin !== window.location.origin;- } catch {+ } catch (_err) {+ void _err;return false;}})();@@ -108,31 +124,93 @@ export function useResignedInlineMediaURL(staleTime: Infinity,gcTime: INLINE_BLOB_GC_MS,});- const blobUrl = useObjectURL(blob);+ const isAuthenticated = !!fresh;+ const blobUrl = useObjectURL(resignAttachmentId, blob, isAuthenticated);if (!needsResign) return pickedUrl;if (signedUrl) return signedUrl;- return blobUrl || pickedUrl;+ // Only return the cached blob URL when it belongs to the current id and+ // the current QueryClient has authenticated metadata for it. This keeps+ // the 5-min re-entry cache for the same session but prevents a logged-out+ // or account-switched QueryClient (fresh pending/rejected) from reusing a+ // previous account's private blob: URL without coupling to logout code.+ if (+ blobUrl &&+ resignAttachmentId &&+ isAuthenticated &&+ blobUrlCache.get(resignAttachmentId) === blobUrl+ ) {+ return blobUrl;+ }+ if (blobUrl && !resignAttachmentId && isAuthenticated) return blobUrl;+ return pickedUrl;}-// useObjectURL turns a Blob into a `blob:` URL for the lifetime of the calling-// component, revoking it on unmount / replacement so the bytes are released-// once nothing renders them. Returns "" while there is no blob (and during-// SSR, where createObjectURL does not exist).-function useObjectURL(blob: Blob | undefined): string {- const [url, setUrl] = useState("");+// useObjectURL turns a Blob into a `blob:` URL. The module cache keeps the+// URL stable across remounts so a re-entry with a cached blob does not flash+// the fallback pickedUrl for one frame (see #7741). Refcount + delayed GC+// ensures bytes are released 5 min after last unmount (matching+// INLINE_BLOB_GC_MS) without leaking until renderer exit.+function useObjectURL(+ id: string | undefined,+ blob: Blob | undefined,+ isAuthenticated: boolean,+): string {+ const [, bump] = useState(0);++ // Refcount: cancel pending GC on re-enter, schedule revoke+delete after+ // INLINE_BLOB_GC_MS when last consumer unmounts. Only participate when the+ // current QueryClient has authenticated metadata — otherwise a logged-out+ // client would cancel the previous account's GC and extend the lifetime of+ // private bytes.useEffect(() => {- if (!blob || typeof URL.createObjectURL !== "function") {- setUrl("");- return;+ if (!id || !isAuthenticated) return;+ const pending = blobUrlGCTimers.get(id);+ if (pending) {+ clearTimeout(pending);+ blobUrlGCTimers.delete(id);}- const next = URL.createObjectURL(blob);- setUrl(next);+ blobUrlRefCount.set(id, (blobUrlRefCount.get(id) ?? 0) + 1);return () => {- URL.revokeObjectURL(next);+ const cur = blobUrlRefCount.get(id) ?? 1;+ const next = cur - 1;+ if (next <= 0) {+ blobUrlRefCount.delete(id);+ const t = setTimeout(() => {+ const cached = blobUrlCache.get(id);+ if (cached) {+ try {+ URL.revokeObjectURL(cached);+ } catch (_err) {+ void _err;+ }+ blobUrlCache.delete(id);+ }+ blobUrlGCTimers.delete(id);+ }, INLINE_BLOB_GC_MS);+ if (typeof (t as unknown as { unref?: () => void }).unref === "function") {+ (t as unknown as { unref: () => void }).unref();+ }+ blobUrlGCTimers.set(id, t);+ } else {+ blobUrlRefCount.set(id, next);+ }};- }, [blob]);- return url;+ }, [id, isAuthenticated]);++ useEffect(() => {+ if (!blob || !id || !isAuthenticated || typeof URL.createObjectURL !== "function") return;+ if (blobUrlCache.has(id)) {+ bump((v) => v + 1);+ return;+ }+ const next = URL.createObjectURL(blob);+ blobUrlCache.set(id, next);+ bump((v) => v + 1);+ }, [blob, id, isAuthenticated]);++ if (isAuthenticated && id && blobUrlCache.has(id)) return blobUrlCache.get(id)!;+ return "";}// isObjectURL flags a src that only resolves inside this renderer session —