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

address review (claude): order client batch fetch by selection + de-dupe resolver ids

[._.]/ Adam Eivy5d0a52b3bb7d
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index 4acadd5651..5031d2908c 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -70,14 +70,18 @@ export const listCatalogIngredients = ({ type, tag, q, limit, offset, ...options
// Batch fetch ingredients by id (max 50 server-side) — used by the Story
// Builder remix handoff to hydrate the catalog ingredients the user selected.
// The `ids` filter rides the normal paged list endpoint, which returns the
-// `{ items, nextOffset }` envelope; this unwraps to a plain array of ingredient
-// objects for callers. Empty/falsy ids are dropped before the request.
+// `{ items, nextOffset }` envelope ordered created_at DESC; this unwraps to a
+// plain array AND re-orders it to the requested `ids` so chips + seed read in
+// the user's selection order (mirroring the server's resolveCatalogIngredients).
+// Empty/falsy ids are dropped before the request.
export const listCatalogIngredientsByIds = async (ids = [], options) => {
const list = (Array.isArray(ids) ? ids : []).filter(Boolean);
const params = new URLSearchParams();
params.set('ids', list.join(','));
const res = await request(`/catalog/ingredients?${params}`, options);
- return Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : []);
+ const items = Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : []);
+ const byId = new Map(items.map((ing) => [ing.id, ing]));
+ return list.map((id) => byId.get(id)).filter(Boolean);
};
export const getCatalogIngredient = (id, options) =>
diff --git a/client/src/services/apiCatalog.test.js b/client/src/services/apiCatalog.test.js
new file mode 100644
index 0000000000..7e6f26c36a
--- /dev/null
+++ b/client/src/services/apiCatalog.test.js
@@ -0,0 +1,50 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./apiCore.js', () => ({
+ request: vi.fn(),
+}));
+
+let request;
+let listCatalogIngredientsByIds;
+
+beforeEach(async () => {
+ vi.resetModules();
+ ({ request } = await import('./apiCore.js'));
+ ({ listCatalogIngredientsByIds } = await import('./apiCatalog.js'));
+ request.mockReset();
+});
+
+describe('listCatalogIngredientsByIds', () => {
+ it('unwraps the { items } envelope and re-orders to the requested ids', async () => {
+ // Server returns created_at DESC (NOT request order) inside the paged envelope.
+ request.mockResolvedValue({
+ items: [
+ { id: 'cat-b', name: 'B' },
+ { id: 'cat-a', name: 'A' },
+ { id: 'cat-c', name: 'C' },
+ ],
+ nextOffset: 3,
+ });
+
+ const out = await listCatalogIngredientsByIds(['cat-a', 'cat-b', 'cat-c']);
+ // Restored to the user's pick order, as a plain array.
+ expect(out.map((i) => i.id)).toEqual(['cat-a', 'cat-b', 'cat-c']);
+
+ // The ids ride the normal list endpoint as a CSV query.
+ const [path] = request.mock.calls[0];
+ expect(path).toContain('/catalog/ingredients?');
+ expect(decodeURIComponent(path)).toContain('ids=cat-a,cat-b,cat-c');
+ });
+
+ it('drops falsy ids and ids the server omits (missing / soft-deleted)', async () => {
+ request.mockResolvedValue({ items: [{ id: 'cat-a', name: 'A' }], nextOffset: 1 });
+ const out = await listCatalogIngredientsByIds(['cat-a', '', 'cat-missing', null]);
+ expect(out.map((i) => i.id)).toEqual(['cat-a']);
+ });
+
+ it('tolerates a bare-array response shape', async () => {
+ request.mockResolvedValue([{ id: 'cat-a', name: 'A' }]);
+ const out = await listCatalogIngredientsByIds(['cat-a']);
+ expect(out.map((i) => i.id)).toEqual(['cat-a']);
+ });
+});
diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.js
index 44d7289f67..77baad1bce 100644
--- a/server/services/storyBuilder.js
+++ b/server/services/storyBuilder.js
@@ -122,9 +122,11 @@ function composeSeedFromIngredients(ingredients) {
// rows), then re-order to the caller's pick order so the composed seed reads in
// the order the user selected. Missing/deleted ids are simply absent and skipped.
async function resolveCatalogIngredients(ids) {
- const list = (Array.isArray(ids) ? ids : [])
+ // De-dupe so a direct API caller passing the same id twice doesn't double the
+ // seed bullet (the UI selects via a Set, so this is only reachable off-UI).
+ const list = [...new Set((Array.isArray(ids) ? ids : [])
.filter((id) => isStr(id) && id.trim())
- .map((id) => id.trim());
+ .map((id) => id.trim()))];
if (list.length === 0) return [];
const { items } = await listIngredients({ ids: list, limit: list.length });
const byId = new Map(items.map((ing) => [ing.id, ing]));
diff --git a/server/services/storyBuilder.test.js b/server/services/storyBuilder.test.js
index 5d7744b6d7..66aefaa0b6 100644
--- a/server/services/storyBuilder.test.js
+++ b/server/services/storyBuilder.test.js
@@ -187,6 +187,26 @@ describe('storyBuilder — catalog ingredient linking (#1761)', () => {
]);
});
+ it('de-dupes repeated ids (off-UI API callers) so the link + seed are not doubled', async () => {
+ catalogMocks.listIngredients.mockResolvedValue({
+ items: [{ id: 'cat-c', type: 'character', name: 'Mira', payload: { description: 'A foreman.' } }],
+ });
+
+ const s = await sb.createStorySession({
+ title: 'Dupes', // blank seed so the composed fallback is observable
+ catalogIngredientIds: ['cat-c', 'cat-c', 'cat-c'],
+ });
+
+ // Resolver collapses the dupes to one id before the batch query.
+ expect(catalogMocks.listIngredients).toHaveBeenCalledWith({ ids: ['cat-c'], limit: 1 });
+ expect(catalogMocks.linkIngredientsToSeries).toHaveBeenCalledWith(s.seriesId, [
+ { id: 'cat-c', type: 'character', name: 'Mira', payload: { description: 'A foreman.' } },
+ ]);
+ // The composed premise lists the ingredient exactly once, not three times.
+ const series = await seriesSvc.getSeries(s.seriesId);
+ expect(series.premise.match(/- Mira:/g)).toHaveLength(1);
+ });
+
it('composes a fallback seed from ingredients when seedIdea is blank', async () => {
catalogMocks.listIngredients.mockResolvedValue({ items: [
{ id: 'cat-c', type: 'character', name: 'Mira', payload: { description: 'A weary foundry foreman.' } },