Skip to content

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

simplify: fetch only unhydrated sidecars, and compose the deck fallback prompt

[._.]/ Adam Eivy95bd331007a4
diff --git a/client/src/hooks/useGallerySidecars.js b/client/src/hooks/useGallerySidecars.js
index 936b2c178b..ed9b9ae0d4 100644
--- a/client/src/hooks/useGallerySidecars.js
+++ b/client/src/hooks/useGallerySidecars.js
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { getGalleryImages } from '../services/apiImageVideo';
/**
@@ -12,35 +12,50 @@ import { getGalleryImages } from '../services/apiImageVideo';
* a page shows the row's display text and Refine / Remix / Send to Video open
* with the wrong prompt.
*
- * `filenames` may be a fresh array each render — the fetch is keyed on the
- * sorted, de-duplicated contents, not on array identity. `refreshKey` re-runs
- * the lookup once a new render has landed on disk.
+ * `filenames` may be a fresh array each render — the lookup is keyed on the
+ * sorted, de-duplicated contents, not on array identity. Only filenames not
+ * already held are requested, and results merge into the map rather than
+ * replacing it: a render completing appends ONE filename to its record, and
+ * re-fetching the whole set each time turned rendering a 78-card deck into 78
+ * lookups carrying 3,081 filenames between them. A filename that comes back
+ * empty stays unresolved, so `refreshKey` (bumped once a render has landed)
+ * retries just that one.
*
* Returns `{ byFilename, setSidecar }`; `setSidecar(record)` splices one
* freshly written record in (e.g. after a clean) without a refetch.
*/
export default function useGallerySidecars(filenames, refreshKey = 0) {
- const lookupKey = useMemo(
- () => JSON.stringify([...new Set((Array.isArray(filenames) ? filenames : []).filter(Boolean))].sort()),
- [filenames],
- );
+ const { wanted, lookupKey } = useMemo(() => {
+ const unique = [...new Set((Array.isArray(filenames) ? filenames : []).filter(Boolean))].sort();
+ return { wanted: unique, lookupKey: unique.join('\n') };
+ }, [filenames]);
const [byFilename, setByFilename] = useState(() => new Map());
+ // What the map already holds, readable from the effect without making the
+ // map its own dependency (which would re-run the effect on its own result).
+ const loadedRef = useRef(new Set());
useEffect(() => {
- const wanted = JSON.parse(lookupKey);
- if (!wanted.length) { setByFilename(new Map()); return undefined; }
+ const missing = wanted.filter((f) => !loadedRef.current.has(f));
+ if (!missing.length) return undefined;
let cancelled = false;
- getGalleryImages(wanted, { silent: true }).then((list) => {
+ getGalleryImages(missing, { silent: true }).then((list) => {
if (cancelled) return;
- const map = new Map();
- for (const item of Array.isArray(list) ? list : []) {
- if (item?.filename) map.set(item.filename, item);
- }
- setByFilename(map);
+ const found = (Array.isArray(list) ? list : []).filter((item) => item?.filename);
+ if (!found.length) return;
+ for (const item of found) loadedRef.current.add(item.filename);
+ setByFilename((prev) => {
+ const next = new Map(prev);
+ for (const item of found) next.set(item.filename, item);
+ return next;
+ });
}).catch(() => { /* non-fatal; callers fall back to their own labels */ });
return () => { cancelled = true; };
+ // `lookupKey` stands in for `wanted`, which is rebuilt on every change to
+ // the caller's (memoized) list even when its contents are identical.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [lookupKey, refreshKey]);
const setSidecar = useCallback((record) => {
if (!record?.filename) return;
+ loadedRef.current.add(record.filename);
setByFilename((prev) => new Map(prev).set(record.filename, record));
}, []);
return { byFilename, setSidecar };
diff --git a/client/src/hooks/useGallerySidecars.test.jsx b/client/src/hooks/useGallerySidecars.test.jsx
index a5a4945261..ee89ba4594 100644
--- a/client/src/hooks/useGallerySidecars.test.jsx
+++ b/client/src/hooks/useGallerySidecars.test.jsx
@@ -26,8 +26,12 @@ describe('useGallerySidecars', () => {
// keystroke on a 79-card deck.
rerender({ names: ['a.png'] });
expect(getGalleryImages).toHaveBeenCalledTimes(1);
+ // …and a longer list asks only for what is not already held: a finished
+ // render appends one filename, and re-requesting the other 78 to learn it
+ // is the difference between one lookup and a whole-deck sweep per card.
rerender({ names: ['a.png', 'b.png'] });
await waitFor(() => expect(getGalleryImages).toHaveBeenCalledTimes(2));
+ expect(getGalleryImages).toHaveBeenLastCalledWith(['b.png'], { silent: true });
});
it('splices one freshly written record in without a refetch', async () => {
diff --git a/client/src/hooks/useUniverseGallery.js b/client/src/hooks/useUniverseGallery.js
index 675d096165..75293d9c55 100644
--- a/client/src/hooks/useUniverseGallery.js
+++ b/client/src/hooks/useUniverseGallery.js
@@ -1,4 +1,5 @@
import { useState, useMemo, useCallback } from 'react';
+import { normalizeImage } from '../components/media/normalize';
import { descriptorForCanonEntry } from '../lib/canonPrompt';
import { listSheetPointers } from '../lib/sheetPointers';
import useGallerySidecars from './useGallerySidecars';
@@ -65,35 +66,17 @@ export default function useUniverseGallery({ draft, runsLength }) {
// Pull the real prompt + render settings out of the gallery metadata
// map when available so the lightbox shows the full prompt that was
// sent to the renderer (with universe style influences, variation
- // prompt fragment, etc.), not just the row's display label.
- // Falls back to the label-only shape for filenames not in the gallery
- // (legacy renders or pending re-fetch).
- const meta = galleryByFilename.get(filename) || null;
- out.push({
- // Same `image:<filename>` key normalizeImage() stamps everywhere
- // else — History, Collections, ImageGen — so a star/note added
- // from this lightbox is the SAME annotation record those pages
- // already read. A page-local key would silently fork the user's
- // favorites by surface.
- key: `image:${filename}`,
- kind: 'image',
- filename,
- previewUrl: `/data/images/${filename}`,
- downloadUrl: `/data/images/${filename}`,
- prompt: meta?.prompt || label || filename,
- negativePrompt: meta?.negativePrompt || null,
- modelId: meta?.modelId || meta?.model || null,
- width: meta?.width ?? null,
- height: meta?.height ?? null,
- seed: meta?.seed ?? null,
- steps: meta?.steps ?? null,
- guidance: meta?.guidance ?? null,
- quantize: meta?.quantize ?? null,
- // `raw` carries the original sidecar so MediaLightbox's "Refine
- // Prompt" / clean / remix downstream handlers can pull any field
- // the spec doesn't surface at the top level.
- raw: meta,
- });
+ // prompt fragment, etc.), not just the row's display label. The row's
+ // label is the fallback for filenames not in the gallery (legacy
+ // renders or a pending re-fetch).
+ //
+ // Same `image:<filename>` key normalizeImage() stamps everywhere else —
+ // History, Collections, ImageGen — so a star/note added from this
+ // lightbox is the SAME annotation record those pages already read, and
+ // the cleaning/regen lineage the lightbox's variant toggle keys on
+ // survives the hop (a hand-rolled item shape silently dropped it).
+ const meta = galleryByFilename.get(filename);
+ out.push(normalizeImage({ ...meta, filename, prompt: meta?.prompt || label || filename }));
};
const cats = draft?.categories && typeof draft.categories === 'object' ? draft.categories : {};
for (const [bucketKey, bucket] of Object.entries(cats)) {
diff --git a/client/src/pages/DeckDetail.jsx b/client/src/pages/DeckDetail.jsx
index 0d968d1397..ddf2bebcce 100644
--- a/client/src/pages/DeckDetail.jsx
+++ b/client/src/pages/DeckDetail.jsx
@@ -37,7 +37,7 @@ import useUrlParams from '../hooks/useUrlParams';
import usePreviewRoute from '../hooks/usePreviewRoute';
import useFieldDraft from '../hooks/useFieldDraft';
import useGallerySidecars from '../hooks/useGallerySidecars';
-import { DECK_KIND_LABELS, cardInFlightJobId, deckCompletion } from '../lib/decks';
+import { DECK_KIND_LABELS, cardInFlightJobId, composeCardRenderPrompt, deckCompletion } from '../lib/decks';
import {
deleteDeck, generateDeckPrompts, getDeck, listUniverseSummaries, removeDeckSample,
renderDeckCard, renderDeckCards, updateDeck, updateDeckCard,
@@ -116,25 +116,26 @@ function DeckEditor({ id }) {
() => (deck ? deck.cards.flatMap((c) => c.imageRefs) : []),
[deck],
);
- // The card's own `prompt` is only the subject line. What the renderer was
- // actually sent is the composed prompt — deck style clause, layout clause,
- // titled subject, merged negatives — and that is what the sidecar recorded,
- // so hydrate from it and let the lightbox show the real thing. The card
- // prompt stays the fallback for a render whose sidecar is missing (a legacy
- // deck render, or a refetch that has not landed yet). A finished render
- // appends its filename to the card, which re-keys the lookup on its own —
- // the sidecar is on disk before the server hook attaches the image.
+ // The card's own `prompt` is only its subject line; the renderer was sent the
+ // composed prompt (deck style clause, layout, titled subject, merged
+ // negatives). The sidecar records what was actually sent, so hydrate from it
+ // — and when there is no sidecar (a legacy render, a peer-synced one, or the
+ // first paint before the lookup lands), compose it locally rather than
+ // falling back to the subject line, which is the wording that was never sent.
const { byFilename: sidecars } = useGallerySidecars(cardImageRefs);
const previewItems = useMemo(() => (deck
- ? deck.cards.flatMap((c) => c.imageRefs.map((filename) => {
- const meta = sidecars.get(filename) || null;
- return normalizeImage({
- ...(meta || {}),
- filename,
- path: `/data/images/${filename}`,
- prompt: meta?.prompt || c.prompt,
+ ? deck.cards.flatMap((c) => {
+ const composed = c.imageRefs.length ? composeCardRenderPrompt(deck, c) : null;
+ return c.imageRefs.map((filename) => {
+ const meta = sidecars.get(filename);
+ return normalizeImage({
+ ...meta,
+ filename,
+ prompt: meta?.prompt || composed.prompt,
+ negativePrompt: meta?.negativePrompt || composed.negativePrompt || null,
+ });
});
- }))
+ })
: []), [deck, sidecars]);
const [preview, setPreview] = usePreviewRoute(previewItems);
const previewFilename = (filename) => {
diff --git a/client/src/pages/DeckDetail.preview.test.jsx b/client/src/pages/DeckDetail.preview.test.jsx
index 7d1bb96b69..e2e08f2390 100644
--- a/client/src/pages/DeckDetail.preview.test.jsx
+++ b/client/src/pages/DeckDetail.preview.test.jsx
@@ -81,12 +81,17 @@ describe('DeckDetail preview items', () => {
});
});
- it('falls back to the card prompt when the render has no sidecar', async () => {
+ it('composes the prompt locally when the render has no sidecar', async () => {
+ // A legacy or peer-synced render has no sidecar, and nothing does before
+ // the lookup lands. The composed prompt is derivable right here — falling
+ // back to the card's subject line would re-show the wording that was
+ // never sent.
getGalleryImages.mockResolvedValue([]);
renderPage();
await waitFor(() => {
const item = previewProps?.items?.find((i) => i.filename === 'fool.png');
- expect(item?.prompt).toBe('a youth at a cliff edge');
+ expect(item?.prompt).toBe('copperplate engraving. Full tarot card, framed border. The Fool: a youth at a cliff edge');
+ expect(item?.negativePrompt).toBe('blurry');
});
});
});
diff --git a/server/lib/deckTemplates.js b/server/lib/deckTemplates.js
index 03d0569794..2cba46633f 100644
--- a/server/lib/deckTemplates.js
+++ b/server/lib/deckTemplates.js
@@ -212,10 +212,9 @@ export function composeCardRenderPrompt(deck, card) {
const avoid = universeVisualStyleTokens(deck).avoid.join(', ');
const layout = trimmed(deck?.layoutPrompt);
const subject = [trimmed(card?.name), trimmed(card?.prompt)].filter(Boolean).join(': ');
- const cardNegative = trimmed(card?.negativePrompt);
const body = [layout, subject].filter(Boolean).join('. ');
- const composed = composeStyledPrompt(body, cardNegative, { prompt: style, negativePrompt: avoid });
- return { ...composed, parts: { style, layout, subject, cardNegative, styleNegative: avoid } };
+ const composed = composeStyledPrompt(body, trimmed(card?.negativePrompt), { prompt: style, negativePrompt: avoid });
+ return { ...composed, parts: { style, layout, subject } };
}
const IN_FLIGHT_RENDER = new Set(['queued', 'running']);
diff --git a/server/lib/deckTemplates.test.js b/server/lib/deckTemplates.test.js
index 7fdf03e70c..16bdc9321e 100644
--- a/server/lib/deckTemplates.test.js
+++ b/server/lib/deckTemplates.test.js
@@ -43,7 +43,7 @@ describe('composeCardRenderPrompt', () => {
const out = composeCardRenderPrompt({}, { name: 'Ace of Spades', prompt: 'one large ornate spade' });
expect(out.prompt).toBe('Ace of Spades: one large ornate spade');
expect(out.negativePrompt).toBe('');
- expect(out.parts).toEqual({ style: '', layout: '', subject: 'Ace of Spades: one large ornate spade', cardNegative: '', styleNegative: '' });
+ expect(out.parts).toEqual({ style: '', layout: '', subject: 'Ace of Spades: one large ornate spade' });
});
it('reports each contribution unjoined so the editor can attribute it', () => {
@@ -52,8 +52,6 @@ describe('composeCardRenderPrompt', () => {
style: 'copperplate engraving, aged paper',
layout: 'Full tarot card, framed border',
subject: 'XVII · The Star: a kneeling figure',
- cardNegative: 'text',
- styleNegative: 'blurry',
});
});
});