Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Uploads tab pages with Load more; folder cover order is stable

Claude2665eea26bdd
diff --git a/src/app/api/assets/route.ts b/src/app/api/assets/route.ts
index 51b9ed58..88181793 100644
--- a/src/app/api/assets/route.ts
+++ b/src/app/api/assets/route.ts
@@ -1,7 +1,9 @@
import { connection } from "next/server";
import { listAssets } from "@/server/storage";
+import { cursorFrom } from "@/server/library";
import type { MediaKind } from "@/lib/catalog/types";
+/** Stored files, newest first: source / kind filters, limit, and paging with before=<createdAt>:<id> of the last one. */
export async function GET(request: Request) {
await connection();
const u = new URL(request.url);
@@ -10,6 +12,7 @@ export async function GET(request: Request) {
source: (u.searchParams.get("source") as "upload" | "generation" | null) ?? undefined,
kind: (u.searchParams.get("kind") as MediaKind | null) ?? undefined,
limit: Number(u.searchParams.get("limit") ?? 60),
+ ...cursorFrom(u.searchParams.get("before")),
}),
});
}
diff --git a/src/components/library-view.tsx b/src/components/library-view.tsx
index 4e61d373..0f6b6904 100644
--- a/src/components/library-view.tsx
+++ b/src/components/library-view.tsx
@@ -237,7 +237,7 @@ function Inner() {
const items = useMemo(() => {
if (!uploadsTab) return lib.data?.pages.flat() ?? [];
// Uploads search by file name.
- const all = (uploads.data ?? []).map(uploadAsGeneration);
+ const all = (uploads.data?.pages.flat() ?? []).map(uploadAsGeneration);
return dq ? all.filter((g) => g.request.prompt?.toLowerCase().includes(dq.toLowerCase())) : all;
}, [uploadsTab, uploads.data, lib.data, dq]);
const built = useMemo(() => buildEntries(items, { stacks: prefs.stacks && !trash && !uploadsTab }), [items, prefs.stacks, trash, uploadsTab]);
@@ -341,14 +341,14 @@ function Inner() {
// --- Paging ---------------------------------------------------------------------------------
const sentinel = useRef<HTMLDivElement>(null);
- const { hasNextPage, isFetchingNextPage, fetchNextPage } = lib;
+ const { hasNextPage, isFetchingNextPage, fetchNextPage } = uploadsTab ? uploads : lib;
useEffect(() => {
const el = sentinel.current;
- if (!el || !hasNextPage || uploadsTab) return;
+ if (!el || !hasNextPage) return;
const io = new IntersectionObserver((es) => es.some((x) => x.isIntersecting) && !isFetchingNextPage && void fetchNextPage(), { rootMargin: "600px" });
io.observe(el);
return () => io.disconnect();
- }, [hasNextPage, isFetchingNextPage, fetchNextPage, uploadsTab]);
+ }, [hasNextPage, isFetchingNextPage, fetchNextPage]);
const go = (params: Record<string, string | undefined>) => {
const next = new URLSearchParams(sp.toString());
@@ -618,7 +618,7 @@ function Inner() {
</section>
))}
<div ref={sentinel} className="flex flex-col items-center gap-2 py-4">
- {!uploadsTab && hasNextPage ? (
+ {hasNextPage ? (
<button
onClick={() => void fetchNextPage()}
disabled={isFetchingNextPage}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 8dfe803a..ae391a1b 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -529,15 +529,20 @@ export function useGenerationActions() {
}, [qc]);
}
-/** Files you uploaded (the Library's Uploads tab), newest first. */
+const UPLOADS_PAGE = 100;
+
+/** Files you uploaded (the Library's Uploads tab), newest first, paged like the Library ("Load more"). */
export function useUploads(kind?: MediaKind) {
- return useQuery({
- queryKey: ["assets", "upload", kind, 200],
- queryFn: async () => {
- const qs = new URLSearchParams({ source: "upload", limit: "200" });
+ return useInfiniteQuery({
+ queryKey: ["assets", "upload", kind, "paged"],
+ initialPageParam: undefined as string | undefined,
+ queryFn: async ({ pageParam }) => {
+ const qs = new URLSearchParams({ source: "upload", limit: String(UPLOADS_PAGE) });
if (kind) qs.set("kind", kind);
+ if (pageParam) qs.set("before", pageParam);
return (await json<{ items: Asset[] }>(await fetch(`/api/assets?${qs}`))).items;
},
+ getNextPageParam: (last) => (last.length < UPLOADS_PAGE ? undefined : `${last.at(-1)!.createdAt}:${last.at(-1)!.id}`),
placeholderData: keepPreviousData,
});
}
diff --git a/src/server/library.ts b/src/server/library.ts
index c9f7d553..b84da1eb 100644
--- a/src/server/library.ts
+++ b/src/server/library.ts
@@ -190,7 +190,7 @@ const FOLDER_SELECT = `SELECT f.*,
(SELECT COUNT(*) FROM folder_items i JOIN generations g ON g.id = i.generation_id LEFT JOIN generation_trash t ON t.generation_id = g.id
WHERE i.folder_id = f.id AND t.generation_id IS NULL) AS count,
(SELECT g.outputs_json FROM folder_items i JOIN generations g ON g.id = i.generation_id LEFT JOIN generation_trash t ON t.generation_id = g.id
- WHERE i.folder_id = f.id AND t.generation_id IS NULL AND g.status = 'succeeded' AND g.outputs_json != '[]' ORDER BY g.created_at DESC LIMIT 1) AS cover_json
+ WHERE i.folder_id = f.id AND t.generation_id IS NULL AND g.status = 'succeeded' AND g.outputs_json != '[]' ORDER BY g.created_at DESC, g.id DESC LIMIT 1) AS cover_json
FROM folders f`;
export function listFolders(): Folder[] {
diff --git a/src/server/storage.ts b/src/server/storage.ts
index e0b5017b..09b2d9d9 100644
--- a/src/server/storage.ts
+++ b/src/server/storage.ts
@@ -153,7 +153,8 @@ export function getAsset(id: string): Asset | null {
return row ? toAsset(row) : null;
}
-export function listAssets(opts: { source?: Asset["source"]; kind?: MediaKind; limit?: number }): Asset[] {
+/** Newest first; page with `before` (+ `beforeId`): the last asset of the previous page. */
+export function listAssets(opts: { source?: Asset["source"]; kind?: MediaKind; limit?: number; before?: number; beforeId?: string }): Asset[] {
const where: string[] = [];
const args: unknown[] = [];
if (opts.source) {
@@ -164,7 +165,11 @@ export function listAssets(opts: { source?: Asset["source"]; kind?: MediaKind; l
where.push("kind = ?");
args.push(opts.kind);
}
- const sql = `SELECT * FROM assets ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY created_at DESC LIMIT ?`;
+ if (opts.before) {
+ where.push(opts.beforeId ? "(created_at < ? OR (created_at = ? AND id < ?))" : "created_at < ?");
+ args.push(...(opts.beforeId ? [opts.before, opts.before, opts.beforeId] : [opts.before]));
+ }
+ const sql = `SELECT * FROM assets ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY created_at DESC, id DESC LIMIT ?`;
return (db().prepare(sql).all(...args, opts.limit ?? 100) as AssetRow[]).map(toAsset);
}
diff --git a/tests/library.test.ts b/tests/library.test.ts
index ced98fac..a7d683cf 100644
--- a/tests/library.test.ts
+++ b/tests/library.test.ts
@@ -14,7 +14,7 @@ process.env.COMFYUI_URL = "http://127.0.0.1:9";
const { setSetting } = await import("@/server/settings");
const gens = await import("@/server/generations");
const lib = await import("@/server/library");
-const { saveFile, absolutePath } = await import("@/server/storage");
+const { saveFile, absolutePath, listAssets } = await import("@/server/storage");
const { zipStream, zipSize } = await import("@/server/zip");
const { TOOLS } = await import("@/server/assist/tools");
const { POST: bulk } = await import("@/app/api/generations/bulk/route");
@@ -189,6 +189,20 @@ describe("paging", () => {
expect(seen.sort()).toEqual([...items].sort());
});
+ it("pages uploads (the Uploads tab) the same way", () => {
+ const ups = Array.from({ length: 5 }, (_, i) => saveFile({ data: Buffer.concat([PNG, Buffer.from(`up ${i}`)]), contentType: "image/png", source: "upload" }).id);
+ db().prepare(`UPDATE assets SET created_at = 4321 WHERE id IN (${ups.map(() => "?").join(",")})`).run(...ups);
+ const seen: string[] = [];
+ let cursor: { before?: number; beforeId?: string } = { before: 4322 };
+ for (let i = 0; i < 5; i++) {
+ const page = listAssets({ source: "upload", limit: 2, ...cursor }).filter((a) => a.createdAt === 4321);
+ seen.push(...page.map((a) => a.id));
+ if (page.length < 2) break;
+ cursor = lib.cursorFrom(`${page[1].createdAt}:${page[1].id}`);
+ }
+ expect(seen.sort()).toEqual([...ups].sort());
+ });
+
it("reads the cursor in both forms", () => {
expect(lib.cursorFrom("1700000000000:Ab_c-9")).toEqual({ before: 1700000000000, beforeId: "Ab_c-9" });
expect(lib.cursorFrom("1700000000000")).toEqual({ before: 1700000000000 });
@@ -318,6 +332,8 @@ describe("folders", () => {
expect(lib.createFolder({ name: "Other", color: "nope" }).color).toBe("lime");
const a = made("in folder a").g;
const b = made("in folder b").g;
+ // The cover is the newest: make b clearly newer (both can land in the same millisecond).
+ db().prepare("UPDATE generations SET created_at = created_at + 1000 WHERE id = ?").run(b.id);
expect(lib.moveToFolder([a.id, b.id], f.id)).toBe(2);
expect(lib.getFolder(f.id)).toMatchObject({ count: 2 });
expect(lib.getFolder(f.id)!.cover?.url).toBe(b.outputs[0].url);