Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): album pagination, universe series-rollup, URL/tag fixes (#1762)
[._.]/ Adam Eivy231d45a16bd4
diff --git a/client/src/components/catalog/CatalogAlbum.jsx b/client/src/components/catalog/CatalogAlbum.jsxindex ab6f8aa4ad..3530807460 100644--- a/client/src/components/catalog/CatalogAlbum.jsx+++ b/client/src/components/catalog/CatalogAlbum.jsx@@ -2,9 +2,11 @@* CatalogAlbum — a collapsible group section in the Catalog "Albums" view (#1762).** One album per live universe, plus the pinned "Unsorted / Raw" and "Orphaned"- * albums. Cards lazy-load via `loadItems()` the FIRST time the album is+ * albums. Cards lazy-load via `loadPage(offset)` the FIRST time the album is* expanded (album headers show the count from /facets up front, so an unexpanded- * album costs nothing). Reuses <CatalogCard> so album cards match the flat grid.+ * album costs nothing), and paginate with "Load more" so an album with more than+ * one page's worth of ingredients is never silently truncated. Reuses+ * <CatalogCard> so album cards match the flat grid.*/import { useState, useEffect, useCallback } from 'react';@@ -15,8 +17,9 @@ export default function CatalogAlbum({title,subtitle,count,+ pageSize,defaultExpanded = false,- loadItems,+ loadPage,getType,selectedIds,onToggleSelect,@@ -29,20 +32,29 @@ export default function CatalogAlbum({// `null` = not yet loaded (distinct from `[]` = loaded-and-empty), so an// empty album doesn't re-fetch on every expand toggle.const [items, setItems] = useState(null);+ const [hasMore, setHasMore] = useState(false);const [loading, setLoading] = useState(false);+ const [loadingMore, setLoadingMore] = useState(false);const [error, setError] = useState('');+ const fetchPage = useCallback(async (offset) => {+ const list = await loadPage(offset).catch((err) => {+ setError(err?.message || 'Failed to load album');+ return null;+ });+ if (!Array.isArray(list)) return null;+ setHasMore(list.length === pageSize);+ return list;+ }, [loadPage, pageSize]);+const ensureLoaded = useCallback(async () => {if (items !== null || loading) return;setLoading(true);setError('');- const list = await loadItems().catch((err) => {- setError(err?.message || 'Failed to load album');- return null;- });+ const list = await fetchPage(0);setLoading(false);- if (Array.isArray(list)) setItems(list);- }, [items, loading, loadItems]);+ if (list) setItems(list);+ }, [items, loading, fetchPage]);// Load the first time the album is expanded — covers both an explicit toggle// and a `defaultExpanded` album that mounts already open (the pinned Raw album).@@ -52,6 +64,13 @@ export default function CatalogAlbum({const toggle = () => setExpanded((e) => !e);+ const loadMore = async () => {+ setLoadingMore(true);+ const list = await fetchPage((items || []).length);+ setLoadingMore(false);+ if (list) setItems((prev) => [...(prev || []), ...list]);+ };+// Album-local optimistic delete: remove the card immediately, restore it if// the parent's delete handler reports failure (it owns the toast + rollback// of shared state like selection + facet counts).@@ -93,21 +112,36 @@ export default function CatalogAlbum({) : error ? (<div className="text-sm text-port-error py-3">{error}</div>) : (items && items.length > 0) ? (- <ul className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">- {items.map((it) => (- <CatalogCard- key={it.id}- ingredient={it}- getType={getType}- selected={selectedIds.has(it.id)}- onToggleSelect={onToggleSelect}- armed={armedId === it.id}- onArm={onArm}- onCancelArm={onCancelArm}- onConfirmDelete={handleDelete}- />- ))}- </ul>+ <>+ <ul className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">+ {items.map((it) => (+ <CatalogCard+ key={it.id}+ ingredient={it}+ getType={getType}+ selected={selectedIds.has(it.id)}+ onToggleSelect={onToggleSelect}+ armed={armedId === it.id}+ onArm={onArm}+ onCancelArm={onCancelArm}+ onConfirmDelete={handleDelete}+ />+ ))}+ </ul>+ {hasMore && (+ <div className="flex justify-center mt-3">+ <button+ type="button"+ onClick={loadMore}+ disabled={loadingMore}+ className="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-port-border bg-port-card hover:bg-port-bg text-white text-sm font-medium disabled:opacity-50"+ >+ {loadingMore ? <Loader2 size={14} className="animate-spin" /> : null}+ Load more+ </button>+ </div>+ )}+ </>) : (<div className="text-sm text-gray-500 py-3">No ingredients in this album.</div>)}diff --git a/client/src/pages/Catalog.jsx b/client/src/pages/Catalog.jsxindex f2248ba23c..e4c8130a7d 100644--- a/client/src/pages/Catalog.jsx+++ b/client/src/pages/Catalog.jsx@@ -128,6 +128,20 @@ export default function Catalog() {return () => clearTimeout(t);}, [searchInput, updateParams]);+ // Adopt an externally-changed `?q=` (Back/Forward, or an in-app link to a+ // different query while this page stays mounted) so the box + fetch never lag+ // the URL. Our own debounced write lands urlQ === q, so this is a no-op for+ // typing and only fires on a real external change.+ const urlQ = searchParams.get('q') || '';+ useEffect(() => {+ if (urlQ !== q) {+ setSearchInput(urlQ);+ setQ(urlQ);+ }+ // Keyed on urlQ only: this effect reacts to URL changes, not to our own+ // debounce writing q (which already set urlQ to match, making this a no-op).+ }, [urlQ, q]);+const loadStats = useCallback(() => {getCatalogStats({ silent: true }).then((s) => setStats(s || null))@@ -272,8 +286,11 @@ export default function Catalog() {// unlinked, so it never belongs in a universe/series-filtered grid.const matchesType = !selectedType || created.type === selectedType;const matchesSearch = !q || (created.name || '').toLowerCase().includes(q.toLowerCase());+ // The create form always posts tags: [], so an active tag filter can never+ // match a fresh row — gate on it too, else the grid shows a non-matching card.+ const matchesTag = !selectedTag || (created.tags || []).includes(selectedTag);const refFiltered = !!(selectedUniverse || selectedSeries);- if (view === 'grid' && matchesType && matchesSearch && !refFiltered) {+ if (view === 'grid' && matchesType && matchesSearch && matchesTag && !refFiltered) {setItems((prev) => [created, ...prev]);}loadStats();@@ -849,14 +866,22 @@ export default function Catalog() {// Albums grouped view (decision #1: flat universe albums + Raw + Orphaned).// Album headers show counts from /facets up front; each album lazy-loads its-// cards the first time it is expanded. Mounted under a `key={dataVersion}` so a-// mutation remounts it and the lazy loads re-run against fresh data.+// cards the first time it is expanded and paginates with Load more. Mounted+// under a `key={dataVersion}` so a mutation remounts it and the lazy loads+// re-run against fresh data. A universe album rolls up its series' members+// server-side (decision #1), so a series-only ingredient still has a home here.function AlbumsView({ facets, cardProps, onConfirmDelete }) {if (!facets) {return <div className="text-gray-500 text-sm">Loading albums…</div>;}const { universes = [], unlinkedCount = 0, orphanedCount = 0 } = facets;- const albumProps = { ...cardProps, onConfirmDelete };+ const albumProps = { ...cardProps, onConfirmDelete, pageSize: PAGE_SIZE };+ // One page fetcher per album view — paginated so albums never reintroduce the+ // old silent cap. `extra` carries the view's filter (unlinked / orphaned / a+ // universe ref).+ const pageLoader = (extra) => (offset) =>+ listCatalogIngredients({ ...extra, limit: PAGE_SIZE, offset, silent: true })+ .then((d) => (Array.isArray(d?.items) ? d.items : []));const noAlbums = universes.length === 0 && unlinkedCount === 0 && orphanedCount === 0;if (noAlbums) {return (@@ -873,8 +898,7 @@ function AlbumsView({ facets, cardProps, onConfirmDelete }) {subtitle="not yet placed in a universe or series"count={unlinkedCount}defaultExpanded- loadItems={() => listCatalogIngredients({ unlinked: true, limit: 200, silent: true })- .then((d) => (Array.isArray(d?.items) ? d.items : []))}+ loadPage={pageLoader({ unlinked: true })}{...albumProps}/>)}@@ -883,8 +907,7 @@ function AlbumsView({ facets, cardProps, onConfirmDelete }) {key={u.refId}title={u.name}count={u.count}- loadItems={() => listCatalogIngredients({ refKind: 'universe', refId: u.refId, limit: 200, silent: true })- .then((d) => (Array.isArray(d?.items) ? d.items : []))}+ loadPage={pageLoader({ refKind: 'universe', refId: u.refId })}{...albumProps}/>))}@@ -893,8 +916,7 @@ function AlbumsView({ facets, cardProps, onConfirmDelete }) {title="Orphaned"subtitle="linked to a deleted universe/series — re-home these"count={orphanedCount}- loadItems={() => listCatalogIngredients({ orphaned: true, limit: 200, silent: true })- .then((d) => (Array.isArray(d?.items) ? d.items : []))}+ loadPage={pageLoader({ orphaned: true })}{...albumProps}/>)}diff --git a/client/src/pages/Catalog.test.jsx b/client/src/pages/Catalog.test.jsxindex 4b1cda9a06..29dce7864e 100644--- a/client/src/pages/Catalog.test.jsx+++ b/client/src/pages/Catalog.test.jsx@@ -348,6 +348,32 @@ describe('Catalog page', () => {});});+ it('paginates an album past one page with its own Load more', async () => {+ const rawPage = Array.from({ length: 60 }, (_, i) => ({+ id: `raw-${i}`, name: `Raw ${i}`, type: 'idea', payload: {}, tags: [],+ }));+ // Grid loads return the default sample; the Raw album (unlinked) gets a full+ // first page then a short second page.+ listCatalogIngredients.mockImplementation((params = {}) => {+ if (params.unlinked && params.offset === 0) return Promise.resolve({ items: rawPage, nextOffset: 60 });+ if (params.unlinked && params.offset === 60) return Promise.resolve({ items: [{ id: 'raw-60', name: 'Raw 60', type: 'idea', payload: {}, tags: [] }], nextOffset: 61 });+ return Promise.resolve({ items: sample, nextOffset: sample.length });+ });+ renderCatalog();+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());++ fireEvent.click(screen.getByRole('button', { name: /^Albums$/i }));+ await waitFor(() => expect(screen.getByText('Raw 0')).toBeTruthy());++ const loadMore = await screen.findByRole('button', { name: /Load more/i });+ await act(async () => { fireEvent.click(loadMore); });++ expect(listCatalogIngredients).toHaveBeenCalledWith(+ expect.objectContaining({ unlinked: true, offset: 60 }),+ );+ await waitFor(() => expect(screen.getByText('Raw 60')).toBeTruthy());+ });+it('bulk-places the selection into a universe with type-derived roles', async () => {renderCatalog();await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());diff --git a/server/services/catalogDB.facets.db.test.js b/server/services/catalogDB.facets.db.test.jsindex 8c9a19b8f6..3bafc94ac0 100644--- a/server/services/catalogDB.facets.db.test.js+++ b/server/services/catalogDB.facets.db.test.js@@ -76,6 +76,21 @@ describe.skipIf(!dbReady)('catalogDB facets + album filters (#1762)', () => {expect(typedMiss.items.map((i) => i.id)).not.toContain(linked.id);});+ it('rolls a series-only ingredient up under its parent universe (decision #1)', async () => {+ const seriesOnly = await catalogDB.createIngredient({ type: 'character', name: `SeriesOnly ${nonce}` });+ createdIngredientIds.add(seriesOnly.id);+ // Linked ONLY to the series (which belongs to UNI) — no direct universe ref.+ await catalogDB.linkIngredientToRef(seriesOnly.id, 'series', SER_ID, 'cast-character');++ const { items } = await catalogDB.listIngredients({ refKind: 'universe', refId: UNI_ID, limit: 200 });+ expect(items.map((i) => i.id)).toContain(seriesOnly.id);++ // And the universe facet count reflects the rolled-up series member.+ const facets = await catalogDB.getCatalogFacets();+ const uni = facets.universes.find((u) => u.refId === UNI_ID);+ expect(uni.count).toBeGreaterThanOrEqual(1);+ });+it('does not duplicate a row linked under multiple roles', async () => {const multi = await catalogDB.createIngredient({ type: 'character', name: `Multi ${nonce}` });createdIngredientIds.add(multi.id);diff --git a/server/services/catalogDB.js b/server/services/catalogDB.jsindex e57c23bf41..6cf027946d 100644--- a/server/services/catalogDB.js+++ b/server/services/catalogDB.js@@ -747,7 +747,20 @@ export async function listIngredients({ ids, type, tag, query: q, refKind = null// under multiple roles isn't duplicated — no DISTINCT needed. Composes with// type/tag/q above. `unlinked` and `orphaned` are mutually exclusive views// of the un-homed set; the route schema rejects combining them with ref.- if (refKind && refId) {+ if (refKind === 'universe' && refId) {+ // A universe album/filter is the universe's WHOLE membership: ingredients+ // linked directly to the universe OR to any live series under it (decision+ // #1 — the series dropdown narrows *within* the universe, so a series-only+ // ingredient must still land in its parent universe). $refId is referenced+ // twice via one placeholder.+ const refIdx = idx++;+ conditions.push(`EXISTS (SELECT 1 FROM catalog_ingredient_refs r+ WHERE r.ingredient_id = catalog_ingredients.id AND r.deleted = false+ AND ((r.ref_kind = 'universe' AND r.ref_id = $${refIdx})+ OR (r.ref_kind = 'series' AND r.ref_id IN (+ SELECT id FROM pipeline_series WHERE universe_id = $${refIdx} AND deleted = false))))`);+ params.push(refId);+ } else if (refKind && refId) {conditions.push(`EXISTS (SELECT 1 FROM catalog_ingredient_refs rWHERE r.ingredient_id = catalog_ingredients.id AND r.deleted = falseAND r.ref_kind = $${idx++} AND r.ref_id = $${idx++})`);@@ -1751,11 +1764,17 @@ export async function getCatalogFacets() {query(`SELECT type, COUNT(*)::int AS countFROM catalog_ingredients WHERE deleted = falseGROUP BY type ORDER BY count DESC, type`),+ // Universe membership rolls up its series' members (decision #1), so the+ // album header count matches what the universe album/filter actually lists:+ // distinct ingredients linked to the universe OR to a live series under it.query(`SELECT u.id AS ref_id, u.name, COUNT(DISTINCT r.ingredient_id)::int AS count- FROM catalog_ingredient_refs r+ FROM universes u+ JOIN catalog_ingredient_refs r ON r.deleted = false AND (+ (r.ref_kind = 'universe' AND r.ref_id = u.id)+ OR (r.ref_kind = 'series' AND r.ref_id IN (+ SELECT s.id FROM pipeline_series s WHERE s.universe_id = u.id AND s.deleted = false)))JOIN catalog_ingredients i ON i.id = r.ingredient_id AND i.deleted = false- JOIN universes u ON u.id = r.ref_id AND u.deleted = false- WHERE r.deleted = false AND r.ref_kind = 'universe'+ WHERE u.deleted = falseGROUP BY u.id, u.name ORDER BY count DESC, u.name`),query(`SELECT s.id AS ref_id, s.name, s.universe_id, COUNT(DISTINCT r.ingredient_id)::int AS countFROM catalog_ingredient_refs r