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: normalize both ?ids= wire forms and accept peer-length project ids (#4148)

Adam Eivy37b628cb852a
diff --git a/client/src/services/apiBatch.js b/client/src/services/apiBatch.js
index fd863d4ef9..e771415475 100644
--- a/client/src/services/apiBatch.js
+++ b/client/src/services/apiBatch.js
@@ -1,24 +1,37 @@
import { request } from './apiCore.js';
+/**
+ * The id list `fetchByIds` will actually request: trimmed, non-strings and
+ * blanks dropped, de-duplicated, in first-seen order. Exported so a caller that
+ * re-orders the response into its request order (apiCatalog) indexes against the
+ * exact same normalized list rather than its own raw input.
+ */
+export const normalizeIds = (ids) => [...new Set(
+ (Array.isArray(ids) ? ids : [])
+ .map((id) => (typeof id === 'string' ? id.trim() : ''))
+ .filter(Boolean),
+)];
+
/**
* Batch-fetch records by id through a list route's `?ids=a,b,c` filter (#4148) —
* the client half of the server's shared `csvIdsParam` query param.
*
- * De-dupes and drops falsy ids, then unwraps a paginated `{ items }` envelope to
- * a plain array. Ids the server omits (missing or soft-deleted) are simply
+ * Normalizes the ids (see above), then unwraps a paginated `{ items }` envelope
+ * to a plain array. Ids the server omits (missing or soft-deleted) are simply
* absent from the result, so callers index it by `id` rather than assuming
* positional parity with the request.
*
- * The empty-list short-circuit is load-bearing, not a micro-optimization: a
- * present-but-blank `?ids=` reads as ABSENT server-side, so issuing the request
- * anyway would return the whole unfiltered list — the exact over-fetch these
- * batch helpers exist to remove.
+ * The trim and the empty-list short-circuit are load-bearing, not
+ * micro-optimizations: a present-but-blank `?ids=` (which is what a
+ * whitespace-only id serializes to) reads as ABSENT server-side, so issuing the
+ * request anyway would return the whole unfiltered list — the exact over-fetch
+ * these batch helpers exist to remove.
*
* Lives in its own module rather than inside `apiCore.js` so the suites that
* mock `./apiCore.js` wholesale still intercept the `request` this makes.
*/
export async function fetchByIds(path, ids = [], options) {
- const list = [...new Set((Array.isArray(ids) ? ids : []).filter(Boolean))];
+ const list = normalizeIds(ids);
if (list.length === 0) return [];
const params = new URLSearchParams({ ids: list.join(',') });
const res = await request(`${path}?${params}`, options);
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index cc85b867e4..75fd6c3e8f 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -1,5 +1,5 @@
import { request } from './apiCore.js';
-import { fetchByIds } from './apiBatch.js';
+import { fetchByIds, normalizeIds } from './apiBatch.js';
// Creative Ingredients Catalog API surface. Every helper takes an optional
// `options` second arg so callers with their own `.catch` toast can pass
@@ -91,10 +91,10 @@ export const listCatalogIngredients = ({ type, tag, q, refKind, refId, unlinked,
// and chips + seed must read in the user's selection order (mirroring the
// server's resolveCatalogIngredients).
export const listCatalogIngredientsByIds = async (ids = [], options) => {
- const list = (Array.isArray(ids) ? ids : []).filter(Boolean);
+ const list = normalizeIds(ids);
const items = await fetchByIds('/catalog/ingredients', list, options);
const byId = new Map(items.map((ing) => [ing.id, ing]));
- return [...new Set(list)].map((id) => byId.get(id)).filter(Boolean);
+ return list.map((id) => byId.get(id)).filter(Boolean);
};
export const getCatalogIngredient = (id, options) =>
diff --git a/client/src/services/apiCreativeDirector.test.js b/client/src/services/apiCreativeDirector.test.js
index ddf43143a0..3af8c891bd 100644
--- a/client/src/services/apiCreativeDirector.test.js
+++ b/client/src/services/apiCreativeDirector.test.js
@@ -50,6 +50,18 @@ describe('getCreativeDirectorProjectsByIds', () => {
expect(request).not.toHaveBeenCalled();
});
+ // A whitespace-only id survives a bare `filter(Boolean)` and serializes to
+ // `?ids=%20`, which the server trims back to ABSENT — i.e. it would return
+ // every project on the install, the exact over-fetch this helper removes.
+ it('trims ids, and treats an all-whitespace list as empty (no request)', async () => {
+ expect(await getCreativeDirectorProjectsByIds([' ', '\t', 42])).toEqual([]);
+ expect(request).not.toHaveBeenCalled();
+
+ request.mockResolvedValue([]);
+ await getCreativeDirectorProjectsByIds([' cd-1 ', ' ', 'cd-2']);
+ expect(decodeURIComponent(request.mock.calls[0][0])).toContain('ids=cd-1,cd-2');
+ });
+
it('unwraps a paginated { items } envelope and tolerates a junk response', async () => {
request.mockResolvedValue({ items: [{ id: 'cd-1' }], total: 1 });
expect(await getCreativeDirectorProjectsByIds(['cd-1'])).toEqual([{ id: 'cd-1' }]);
diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.js
index 5aa3f17ba8..b8492581a1 100644
--- a/server/lib/creativeDirectorValidation.js
+++ b/server/lib/creativeDirectorValidation.js
@@ -227,7 +227,11 @@ export const CREATIVE_DIRECTOR_IDS_BATCH_MAX = 100;
// full list. Unknown keys (limit/offset) strip out of the parsed result — the
// route reads those straight off `req.query` for paginateArray.
export const creativeDirectorProjectQuerySchema = z.object({
- ids: csvIdsParam({ max: CREATIVE_DIRECTOR_IDS_BATCH_MAX }),
+ // 120 matches the per-record peer-sync `recordId` bound (validation.js), not
+ // the helper's 64-char default: a locally-minted id is `cd-<uuid>` (39), but a
+ // project that arrived from a peer may carry anything that contract accepts,
+ // and such a project must still be resolvable through this batch.
+ ids: csvIdsParam({ max: CREATIVE_DIRECTOR_IDS_BATCH_MAX, maxIdLength: 120 }),
});
// One scene in the treatment, written by the agent on the treatment task.
diff --git a/server/lib/sharedSchemas.js b/server/lib/sharedSchemas.js
index 36e65f7850..ad5bef6df5 100644
--- a/server/lib/sharedSchemas.js
+++ b/server/lib/sharedSchemas.js
@@ -56,11 +56,13 @@ export const recordRenderPinFields = {
),
};
-// Batch-by-id query param — `?ids=a,b,c` on a list route (#4148). The wire form
-// is a CSV string, preprocessed into a trimmed, empties-dropped string[]; a
-// repeated `?ids=a&ids=b` arrives as an array and passes through untouched. An
-// empty/all-blank value collapses to `undefined` so the field reads cleanly as
-// absent (sentinel-not-empty) and the route falls through to its normal filters.
+// Batch-by-id query param — `?ids=a,b,c` on a list route (#4148). Both wire
+// forms normalize identically: a CSV string, and the repeated `?ids=a&ids=b`
+// form Express hands over as an array (whose members may themselves be CSV).
+// Each entry is trimmed and blanks are dropped, so one shape can't slip past the
+// blank-removal or the cap the other enforces. An empty/all-blank value
+// collapses to `undefined` so the field reads cleanly as absent
+// (sentinel-not-empty) and the route falls through to its normal filters.
//
// `truncate` picks what an over-cap batch does. `false` (the default) rejects it
// with a 400 — the caller learns its request was too big instead of receiving a
@@ -69,8 +71,11 @@ export const recordRenderPinFields = {
// it shipped; kept as an option so this shared helper doesn't change that
// route's established contract.
export const csvIdsParam = ({ max, maxIdLength = 64, truncate = false } = {}) => z.preprocess((v) => {
- if (typeof v !== 'string') return v;
- const parts = v.split(',').map((s) => s.trim()).filter(Boolean);
+ if (typeof v !== 'string' && !Array.isArray(v)) return v;
+ const parts = (Array.isArray(v) ? v : [v])
+ .flatMap((entry) => (typeof entry === 'string' ? entry.split(',') : [entry]))
+ .map((s) => (typeof s === 'string' ? s.trim() : s))
+ .filter((s) => s !== '');
const bounded = truncate ? parts.slice(0, max) : parts;
return bounded.length ? bounded : undefined;
}, z.array(z.string().trim().min(1).max(maxIdLength)).max(max).optional());
diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.js
index f9e75804f9..d5243830ce 100644
--- a/server/routes/creativeDirector.test.js
+++ b/server/routes/creativeDirector.test.js
@@ -114,6 +114,28 @@ describe('creativeDirector routes', () => {
expect(cdService.listProjects).toHaveBeenCalled();
});
+ // Express hands `?ids=a&ids=b` over as an ARRAY — it must normalize through
+ // the same trim / blank-drop / cap path as the CSV form.
+ it('normalizes the repeated ?ids= array form identically to the CSV form', async () => {
+ cdService.getProjectsByIds.mockResolvedValueOnce([{ id: 'cd-2', name: 'B' }]);
+ await request(app).get('/api/creative-director?ids=%20cd-2%20&ids=&ids=cd-9');
+ expect(cdService.getProjectsByIds).toHaveBeenCalledWith(['cd-2', 'cd-9']);
+
+ const many = Array.from({ length: CREATIVE_DIRECTOR_IDS_BATCH_MAX + 1 }, (_, i) => `ids=cd-${i}`).join('&');
+ const over = await request(app).get(`/api/creative-director?${many}`);
+ expect(over.status).toBe(400);
+ });
+
+ // A project that arrived from a peer may carry any id the per-record sync
+ // contract accepts (recordId, max 120) — the batch must still resolve it.
+ it('accepts a peer-length (120-char) project id', async () => {
+ const longId = `cd-${'a'.repeat(117)}`;
+ cdService.getProjectsByIds.mockResolvedValueOnce([{ id: longId }]);
+ const r = await request(app).get(`/api/creative-director?ids=${longId}`);
+ expect(r.status).toBe(200);
+ expect(cdService.getProjectsByIds).toHaveBeenCalledWith([longId]);
+ });
+
it('rejects an over-cap ids batch instead of silently truncating it', async () => {
const ids = Array.from({ length: CREATIVE_DIRECTOR_IDS_BATCH_MAX + 1 }, (_, i) => `cd-${i}`).join(',');
const r = await request(app).get(`/api/creative-director?ids=${ids}`);