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

fix: hasOwn-guard humanizeCategory and clear the picker's filter sources on close (review round 3)

[._.]/ Adam Eivy63aa351d3f7d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 82598a7aec..9f9fc7fcc9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -72,4 +72,4 @@
- **`completeAgent` had three addresses, and the four callers that most needed one address were using the wrong one.** Continuing #3450's sequencing: `agentManagement.js`, `agentLifecycle.js`, `agentFinalization.js` and `agentCliSpawning.js` all reached the completion transition through the `cosAgents.js` barrel. These four are the callers the "move the caller above the facade" recipe cannot reach — the first two DEFINE transitions `agentOrchestrator.js` re-exports, so importing the facade from either is the cycle itself, and the other two are leaves those two must call to spawn and to finalize. So the rule they follow is the other half of the same property: above the facade's closure a transition comes from the facade, inside it from the module that DECLARES it (`cosAgentLifecycle.js`), and never from a barrel. `cleanupOrphanedAgents`'s `await import('./cos.js')` went with it — it was pulling `completeAgent` and `getAgents` through the `cos.js` re-export block while the module was already a static import three lines up, so the deferral bought no cycle protection at all. The new guard in `agentImportCycles.test.js` derives the transition names from the facade's export blocks and walks re-export edges to work out which modules forward them, so a barrel added later is covered without being named; it catches a named import, a renamed one, a namespace property read, a destructure off a namespace handle, and the three deferred spellings of the same reaches — including `const { completeAgent } = await import('./cos.js')`, the exact pattern this change deleted. Each bypass-probed.
-- **The "Pick from Gallery" picker could only be narrowed by typing, so finding one object in one universe meant recalling a word from its prompt.** It now carries two dropdowns beside the search box: a scope select that groups every universe and media collection under `<optgroup>`s, and a type select built from the `entryCategory`/`entryKind` tags the Universe Builder stamps onto sidecars, labelled through the same `humanizeCategory` the Builder uses. Those two are separate vocabularies — a user-authored bucket can legitimately be keyed `canon` — so the type options are prefixed by which field they filter and grouped under Categories/Entry kinds rather than flattened into one list where the bucket and the stage would silently match each other. All three filters AND-combine, and both dropdowns list only universes/collections/types that actually match an image currently in the picker — a scope that can only ever produce an empty grid isn't offered, and a selection that stops matching resets itself to "All" rather than silently blanking the grid. Collection membership is matched on the stored `{ kind, ref }` pair (the same `<kind>:<ref>` string `normalizeImage` puts on `item.key`), not on a bare filename, so a collection holding video refs alongside images filters correctly. Both option fetches are best-effort: if the collections or universes call fails the picker keeps working, falling back to the universe name stamped on each sidecar (#3479).
+- **The "Pick from Gallery" picker could only be narrowed by typing, so finding one object in one universe meant recalling a word from its prompt.** It now carries two dropdowns beside the search box: a scope select that groups every universe and media collection under `<optgroup>`s, and a type select built from the `entryCategory`/`entryKind` tags the Universe Builder stamps onto sidecars, labelled through the same `humanizeCategory` the Builder uses. Those two are separate vocabularies — a user-authored bucket can legitimately be keyed `canon` — so the type options are prefixed by which field they filter and grouped under Categories/Entry kinds rather than flattened into one list where the bucket and the stage would silently match each other. All three filters AND-combine, and both dropdowns list only universes/collections/types that actually match an image currently in the picker — a scope that can only ever produce an empty grid isn't offered, and a selection that stops matching resets itself to "All" rather than silently blanking the grid. Collection membership is matched on the stored `{ kind, ref }` pair (the same `<kind>:<ref>` string `normalizeImage` puts on `item.key`), not on a bare filename, so a collection holding video refs alongside images filters correctly. Both option fetches are best-effort: if the collections or universes call fails the picker keeps working, falling back to the universe name stamped on each sidecar, and the fetched lists are dropped on close so a reopen can't filter fresh images against stale membership. Sidecars are unvalidated JSON that also arrive from peers, so a tag that isn't a usable string is skipped rather than crashing the render — which surfaced a latent bug in the shared `humanizeCategory`: its label lookup wasn't `hasOwn`-guarded, so a user-authored category keyed `constructor` or `toString` resolved to an inherited function and handed every caller a label that throws on the next string method (#3479).
diff --git a/client/src/components/imageGen/GalleryImagePicker.jsx b/client/src/components/imageGen/GalleryImagePicker.jsx
index a37b407b5b..e9e26d2d03 100644
--- a/client/src/components/imageGen/GalleryImagePicker.jsx
+++ b/client/src/components/imageGen/GalleryImagePicker.jsx
@@ -86,7 +86,10 @@ export default function GalleryImagePicker({ open, onClose, onSelect, allowUploa
// from the scope dropdown, leaving text + type filtering intact. `silent`
// because the empty-list fallback below is this caller's error UI.
useEffect(() => {
- if (!open) return undefined;
+ // Drop the previous lists on close rather than letting them straddle a
+ // reopen: the gallery refetch can land first, and stale membership matched
+ // against fresh images offers options that filter to the wrong set.
+ if (!open) { setCollections([]); setUniverses([]); return undefined; }
let cancelled = false;
listMediaCollections({ silent: true })
.then((list) => { if (!cancelled) setCollections(Array.isArray(list) ? list : []); })
diff --git a/client/src/components/imageGen/GalleryImagePicker.test.jsx b/client/src/components/imageGen/GalleryImagePicker.test.jsx
index 422fb41d7b..cca2824f36 100644
--- a/client/src/components/imageGen/GalleryImagePicker.test.jsx
+++ b/client/src/components/imageGen/GalleryImagePicker.test.jsx
@@ -245,6 +245,8 @@ describe('GalleryImagePicker', () => {
// Sidecars are unvalidated JSON on disk and arrive from peers.
{ filename: 'bad.png', path: '/data/images/bad.png', prompt: 'bad metadata', entryCategory: 1, entryKind: {}, universeId: 7, universeName: 42 },
{ filename: 'ok.png', path: '/data/images/ok.png', prompt: 'good metadata', entryCategory: 'places', universeId: 'uni-a', universeName: 'Second Universe' },
+ // A string, but one that resolves to an inherited member on the label table.
+ { filename: 'proto.png', path: '/data/images/proto.png', prompt: 'prototype key', entryCategory: 'constructor' },
]);
listMediaCollections.mockResolvedValue([{ id: 'col-1', name: 5, items: [{ kind: 'image', ref: 'ok.png' }] }]);
listUniverses.mockResolvedValue([{ id: 'uni-a', name: 99 }]);
@@ -252,6 +254,7 @@ describe('GalleryImagePicker', () => {
await screen.findByAltText('bad metadata');
expect(screen.getByRole('option', { name: 'Places' })).toBeTruthy();
+ expect(screen.getByRole('option', { name: 'Constructor' })).toBeTruthy();
// The non-string universe/collection names fall back to their ids, not to a throw.
await waitFor(() => expect(screen.getByRole('option', { name: 'col-1' })).toBeTruthy());
expect(screen.getByRole('option', { name: 'Second Universe' })).toBeTruthy();
@@ -261,6 +264,19 @@ describe('GalleryImagePicker', () => {
expect(screen.getByAltText('good metadata')).toBeTruthy();
});
+ it('drops the previous collections/universes on close so a reopen cannot filter on stale membership', async () => {
+ const { rerender } = render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);
+ await screen.findByAltText('a neon sunset');
+ await waitFor(() => expect(screen.getByRole('option', { name: 'Mood Board' })).toBeTruthy());
+
+ rerender(<GalleryImagePicker open={false} onClose={vi.fn()} onSelect={vi.fn()} />);
+ // Reopen with the collections call left pending — the gallery still resolves.
+ listMediaCollections.mockReturnValue(new Promise(() => {}));
+ rerender(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);
+ await screen.findByAltText('a neon sunset');
+ expect(screen.queryByRole('option', { name: 'Mood Board' })).toBeNull();
+ });
+
it('does not render the filter selects when nothing is filterable', async () => {
listImageGallery.mockResolvedValue([{ filename: 'plain.png', path: '/data/images/plain.png', prompt: 'plain' }]);
listMediaCollections.mockResolvedValue([]);
diff --git a/client/src/lib/universeBuilderShared.js b/client/src/lib/universeBuilderShared.js
index 23b7e8ba8f..d796504596 100644
--- a/client/src/lib/universeBuilderShared.js
+++ b/client/src/lib/universeBuilderShared.js
@@ -64,7 +64,11 @@ export const normalizeCategoryKey = (raw) => (raw || '')
.replace(/_{2,}/g, '_')
.slice(0, WORLD_CATEGORY_KEY_MAX);
-export const humanizeCategory = (key) => CATEGORY_LABELS[key]
+// `hasOwn`-guarded because category keys are user-authored and reach here from
+// unvalidated sidecar metadata: a bare `CATEGORY_LABELS[key]` resolves
+// `'constructor'` / `'toString'` to an inherited function, which then flows into
+// callers as a label and throws the moment one calls a string method on it.
+export const humanizeCategory = (key) => (Object.hasOwn(CATEGORY_LABELS, key) ? CATEGORY_LABELS[key] : null)
|| (key || '').replace(/_/g, ' ').replace(/\b\w/g, (ch) => ch.toUpperCase());
export const ensureDraftCategories = (categories = {}) => ({
diff --git a/client/src/lib/universeBuilderShared.test.js b/client/src/lib/universeBuilderShared.test.js
index e52145325e..6a1a1b7c49 100644
--- a/client/src/lib/universeBuilderShared.test.js
+++ b/client/src/lib/universeBuilderShared.test.js
@@ -57,6 +57,13 @@ describe('universeBuilderShared — humanizeCategory', () => {
expect(humanizeCategory('deep_space')).toBe('Deep Space');
expect(humanizeCategory('')).toBe('');
});
+
+ it('title-cases Object.prototype keys instead of returning the inherited member', () => {
+ // Category keys are user-authored and reach here from unvalidated sidecar
+ // metadata, so an unguarded lookup would hand back a function.
+ expect(humanizeCategory('constructor')).toBe('Constructor');
+ expect(humanizeCategory('toString')).toBe('ToString');
+ });
});
describe('universeBuilderShared — draft categories', () => {