The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Feeds share unchanged generations by id, so a new result doesn't re-render every row
Claudec946e4083424
diff --git a/src/lib/api.ts b/src/lib/api.tsindex 4ca9c7fe..0296bfdf 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -6,7 +6,7 @@ import { toast } from "sonner";import type { AssistThread, AssistThreadSummary, AssistThreadView } from "./assist";import type { ElementKind, StudioElement } from "./catalog/elements";import type { Engine, Generation, GenerationRequest, MediaKind } from "./catalog/types";-import { applyToList, applyToPages, applyToThread, backoff, parseSse, toStreamEvent, type Pages, type StreamEvent } from "./generation-stream";+import { applyToList, applyToPages, applyToThread, backoff, parseSse, shareById, sharePagesById, toStreamEvent, type Pages, type StreamEvent } from "./generation-stream";import { filterToSearch, type FeedFilter, type Folder } from "./library";export interface Asset {@@ -180,6 +180,7 @@ export function useGenerations(filter: FeedFilter, opts: { keepPrevious?: booleaqueryKey: feedKey(filter),queryFn: async () => (await json<{ items: Generation[] }>(await fetch(`/api/generations?${filterToSearch(filter)}`))).items,placeholderData: opts.keepPrevious ? keepPreviousData : undefined,+ structuralSharing: shareById,refetchInterval: (q) => pollEvery(q.state.data, connected),});}@@ -201,6 +202,7 @@ export function useLibrary(filter: FeedFilter) {return f.trashed ? (tail.deletedAt ?? undefined) : tail.createdAt;},placeholderData: keepPreviousData,+ structuralSharing: sharePagesById,refetchInterval: (q) => pollEvery(q.state.data?.pages.flat(), connected),});}diff --git a/src/lib/generation-stream.ts b/src/lib/generation-stream.tsindex 6e4b1baf..1d93e66c 100644--- a/src/lib/generation-stream.ts+++ b/src/lib/generation-stream.ts@@ -6,6 +6,7 @@* event: deleted data: {"id": "..."}* : ping (every 15 s)*/+import { replaceEqualDeep } from "@tanstack/react-query";import type { Generation } from "./catalog/types";import { byNewest, matchesFilter, type FeedFilter } from "./library";@@ -123,6 +124,40 @@ export function applyToThread<T extends { generations: Generation[] }>(view: T |return { ...view, generations };}+/**+ * Structural sharing by id for generation lists. React Query's default compares arrays index by+ * index, so one new result at the top (everything shifts by one) would hand every row a new+ * object and re-render the whole feed. Matching by id keeps every unchanged generation identical.+ */+export function shareById(prev: unknown, next: unknown): unknown {+ if (!Array.isArray(prev) || !Array.isArray(next)) return replaceEqualDeep(prev, next);+ const byId = new Map((prev as Generation[]).map((g) => [g.id, g]));+ let same = prev.length === next.length;+ const out = (next as Generation[]).map((g, i) => {+ const old = byId.get(g.id);+ const v = old ? (replaceEqualDeep(old, g) as Generation) : g;+ if (v !== prev[i]) same = false;+ return v;+ });+ return same ? prev : out;+}++/** The same for paged lists ({ pages, pageParams }), matching across pages. */+export function sharePagesById(prev: unknown, next: unknown): unknown {+ const p = prev as Pages | undefined;+ const n = next as Pages | undefined;+ if (!p?.pages || !n?.pages) return replaceEqualDeep(prev, next);+ const all = p.pages.flat();+ const pages = n.pages.map((page, i) => {+ const shared = shareById(all, page) as Generation[];+ const old = p.pages[i];+ return old && old.length === shared.length && shared.every((g, k) => g === old[k]) ? old : shared;+ });+ const samePages = pages.length === p.pages.length && pages.every((page, i) => page === p.pages[i]);+ const pageParams = replaceEqualDeep(p.pageParams, n.pageParams);+ return samePages && pageParams === p.pageParams ? p : { ...n, pages, pageParams };+}+/** Reconnect delays: 1 s, 2 s, 4 s … capped at 30 s (5 min once the endpoint said it doesn't exist). */export function backoff(attempt: number, missing = false): number {return missing ? 300_000 : Math.min(30_000, 1000 * 2 ** Math.max(0, attempt));diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.tsindex 73bd8706..3ad9ef7d 100644--- a/tests/library-pure.test.ts+++ b/tests/library-pure.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";import type { Generation } from "@/lib/catalog/types";-import { applyToList, applyToPages, applyToThread, backoff, parseSse, toStreamEvent } from "@/lib/generation-stream";+import { applyToList, applyToPages, applyToThread, backoff, parseSse, shareById, sharePagesById, toStreamEvent } from "@/lib/generation-stream";import { buildEntries, dayLabel, downloadName, matchesFilter, splitByDate, trashDaysLeft } from "@/lib/library";import { cuesToSrt, cueTime, layerInfo, modelPreview, outputActions, textOf } from "@/lib/output-actions";@@ -163,6 +163,26 @@ describe("stream reducer", () => {expect(applyToThread(view, { type: "deleted", id: p1[0].id })!.generations).toEqual([]);});+ it("shares unchanged generations by id when the list shifts (one new result at the top)", () => {+ const a = gen();+ const b = gen();+ const prev = [b, a];+ const fresh = gen();+ // What the server returns next: new objects (JSON), shifted by one.+ const next = JSON.parse(JSON.stringify([fresh, b, a])) as Generation[];+ const shared = shareById(prev, next) as Generation[];+ expect(shared[1]).toBe(b);+ expect(shared[2]).toBe(a);+ expect(shareById(prev, JSON.parse(JSON.stringify(prev)))).toBe(prev);+ const changed = shareById(prev, [{ ...b, status: "failed" }, a]) as Generation[];+ expect(changed[0]).not.toBe(b);+ expect(changed[1]).toBe(a);+ const pages = { pages: [[b], [a]], pageParams: [undefined, b.createdAt] };+ const morePages = sharePagesById(pages, JSON.parse(JSON.stringify({ pages: [[fresh, b], [a]], pageParams: [null, b.createdAt] }))) as { pages: Generation[][] };+ expect(morePages.pages[0][1]).toBe(b);+ expect(morePages.pages[1]).toBe(pages.pages[1]);+ });+it("backs off between reconnects", () => {expect([0, 1, 2, 10].map((a) => backoff(a))).toEqual([1000, 2000, 4000, 30_000]);expect(backoff(0, true)).toBe(300_000);