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
refactor: share the ?ids= batch param and client batch fetch (#4148)
Adam Eivy9fe309d23580
diff --git a/client/src/services/README.md b/client/src/services/README.mdindex be7b9b7c01..dcf89a101f 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -29,6 +29,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire|---|---|| `api.js` | Barrel — re-exports every `apiX.js`. || `apiCore.js` | `request()` helper + stable PortOS-app id. Shared error / toast handling. |+| `apiBatch.js` | `fetchByIds(path, ids, options)` — batch-fetch records through a list route's `?ids=a,b,c` filter (dedupe, empty-list short-circuit, `{ items }` envelope unwrap). || `socket.js` | Singleton Socket.IO client over relative path (Tailscale-friendly). || `appUrls.js` | Compute candidate launch URLs for an app from page context. |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 989be41e98..dafc6d08f6 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -70,6 +70,7 @@ export * from './apiRounds.js';export * from './apiSongbook.js';export * from './apiPeerSync.js';export * from './apiSyncReview.js';+export * from './apiBatch.js';export * from './apiCreativeDirector.js';export * from './apiCreativeCommission.js';export * from './apiGames.js';diff --git a/client/src/services/apiBatch.js b/client/src/services/apiBatch.jsnew file mode 100644index 0000000000..fd863d4ef9--- /dev/null+++ b/client/src/services/apiBatch.js@@ -0,0 +1,26 @@+import { request } from './apiCore.js';++/**+ * 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+ * 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.+ *+ * 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))];+ if (list.length === 0) return [];+ const params = new URLSearchParams({ ids: list.join(',') });+ const res = await request(`${path}?${params}`, options);+ return Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : []);+}diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.jsindex 334f7f2999..cc85b867e4 100644--- a/client/src/services/apiCatalog.js+++ b/client/src/services/apiCatalog.js@@ -1,4 +1,5 @@import { request } from './apiCore.js';+import { fetchByIds } 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@@ -84,19 +85,16 @@ export const listCatalogIngredients = ({ type, tag, q, refKind, refId, unlinked,// 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 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.+// `fetchByIds` handles the shared `?ids=` mechanics (dedupe, empty-list+// short-circuit, `{ items }` envelope unwrap); the extra step here is+// re-ordering to the requested `ids` — the paged list returns created_at DESC,+// 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 params = new URLSearchParams();- params.set('ids', list.join(','));- const res = await request(`/catalog/ingredients?${params}`, options);- const items = Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : []);+ const items = await fetchByIds('/catalog/ingredients', list, options);const byId = new Map(items.map((ing) => [ing.id, ing]));- return list.map((id) => byId.get(id)).filter(Boolean);+ return [...new Set(list)].map((id) => byId.get(id)).filter(Boolean);};export const getCatalogIngredient = (id, options) =>diff --git a/client/src/services/apiCreativeDirector.js b/client/src/services/apiCreativeDirector.jsindex 9b89477163..00e77d3e3a 100644--- a/client/src/services/apiCreativeDirector.js+++ b/client/src/services/apiCreativeDirector.js@@ -1,4 +1,5 @@import { request } from './apiCore.js';+import { fetchByIds } from './apiBatch.js';export const listCreativeDirectorProjects = (options = {}) => request('/creative-director', options);// Pass `{ slim: true }` to receive only the fields a polling consumer needs@@ -11,16 +12,9 @@ export const getCreativeDirectorProject = (id, { slim = false } = {}) =>// endpoint, so the response is the same full, non-slim project shape previews// compute from. Used by surfaces that reference a known handful of projects// (the Creative Commission detail page's render history) instead of pulling-// every project on the install. Empty/falsy ids are dropped; an all-empty list-// short-circuits with no request. Ids that don't resolve are absent from the-// result — callers index by `id` rather than assuming positional parity.-export const getCreativeDirectorProjectsByIds = async (ids = [], options = {}) => {- const list = [...new Set((Array.isArray(ids) ? ids : []).filter(Boolean))];- if (list.length === 0) return [];- const params = new URLSearchParams({ ids: list.join(',') });- const res = await request(`/creative-director?${params}`, options);- return Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : []);-};+// every project on the install. Server-side cap is 100 ids per batch.+export const getCreativeDirectorProjectsByIds = (ids = [], options = {}) =>+ fetchByIds('/creative-director', ids, options);export const createCreativeDirectorProject = (data, options = {}) => request('/creative-director', {method: 'POST',body: JSON.stringify(data),diff --git a/client/src/services/apiCreativeDirector.test.js b/client/src/services/apiCreativeDirector.test.jsnew file mode 100644index 0000000000..ddf43143a0--- /dev/null+++ b/client/src/services/apiCreativeDirector.test.js@@ -0,0 +1,66 @@+/**+ * Creative Director API wrapper — batch-by-id fetch (#4148).+ *+ * 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 every project on the install — exactly the over-fetch this+ * helper exists to remove.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./apiCore.js', async (importOriginal) => ({+ ...(await importOriginal()),+ request: vi.fn(),+}));++let request;+let getCreativeDirectorProjectsByIds;++beforeEach(async () => {+ vi.resetModules();+ ({ request } = await import('./apiCore.js'));+ ({ getCreativeDirectorProjectsByIds } = await import('./apiCreativeDirector.js'));+ request.mockReset();+});++describe('getCreativeDirectorProjectsByIds', () => {+ it('sends the ids as a CSV on the list route and returns the bare array', async () => {+ request.mockResolvedValue([{ id: 'cd-1' }, { id: 'cd-2' }]);+ const out = await getCreativeDirectorProjectsByIds(['cd-1', 'cd-2']);+ expect(out.map((p) => p.id)).toEqual(['cd-1', 'cd-2']);++ const [path, options] = request.mock.calls[0];+ expect(path.startsWith('/creative-director?')).toBe(true);+ expect(decodeURIComponent(path)).toContain('ids=cd-1,cd-2');+ expect(options).toEqual({});+ });++ it('de-duplicates and drops falsy ids before building the query', async () => {+ request.mockResolvedValue([]);+ await getCreativeDirectorProjectsByIds(['cd-1', '', 'cd-1', null, 'cd-2', undefined]);+ expect(decodeURIComponent(request.mock.calls[0][0])).toContain('ids=cd-1,cd-2');+ });++ it('short-circuits an empty/all-falsy id list without issuing a request', async () => {+ expect(await getCreativeDirectorProjectsByIds([])).toEqual([]);+ expect(await getCreativeDirectorProjectsByIds([null, '', undefined])).toEqual([]);+ expect(await getCreativeDirectorProjectsByIds()).toEqual([]);+ expect(await getCreativeDirectorProjectsByIds('not-an-array')).toEqual([]);+ expect(request).not.toHaveBeenCalled();+ });++ 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' }]);++ request.mockResolvedValue(null);+ expect(await getCreativeDirectorProjectsByIds(['cd-1'])).toEqual([]);+ });++ it('forwards request options (e.g. { silent: true }) through to request()', async () => {+ request.mockResolvedValue([]);+ await getCreativeDirectorProjectsByIds(['cd-1'], { silent: true });+ expect(request.mock.calls[0][1]).toEqual({ silent: true });+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 46465093f5..5b451bfb3d 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -24,7 +24,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |-| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`). |+| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). || `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). || `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). || `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.jsindex 0a59c33da0..453a818536 100644--- a/server/lib/catalogValidation.js+++ b/server/lib/catalogValidation.js@@ -19,6 +19,7 @@ import {USER_TYPE_FIELD_KINDS,isActiveType,} from './catalogTypes.js';+import { csvIdsParam } from './sharedSchemas.js';// Derived from the shared type registry (`catalogTypes.js`) — adding a SYSTEM// type there flows through to consumers automatically. Kept as a frozen@@ -298,16 +299,13 @@ export const catalogRevisionRestoreSchema = z.object({}).strict();export const catalogIngredientQuerySchema = z.object({- // Batch-fetch by id. The wire form is a CSV string (`?ids=a,b,c`); we- // preprocess it into a trimmed, empties-dropped, ≤50 string[]. An empty/- // all-blank CSV collapses to `undefined` so the field reads cleanly as- // absent (the route/service then falls through to the type/tag/q filters).- // When present, `ids` takes precedence over type/tag/q in `listIngredients`.- ids: z.preprocess((v) => {- if (typeof v !== 'string') return v;- const parts = v.split(',').map((s) => s.trim()).filter(Boolean).slice(0, 50);- return parts.length ? parts : undefined;- }, z.array(z.string().trim().min(1).max(64)).max(50).optional()),+ // Batch-fetch by id — the shared CSV param (see sharedSchemas.csvIdsParam),+ // trimmed and empties-dropped into a ≤50 string[]. An empty/all-blank CSV+ // reads as absent (the route/service then falls through to the type/tag/q+ // filters); when present, `ids` takes precedence over type/tag/q in+ // `listIngredients`. `truncate` keeps this route's long-standing "silently+ // slice at 50" contract rather than 400ing an over-cap batch.+ ids: csvIdsParam({ max: 50, truncate: true }),type: ingredientTypeGate.optional(),tag: tag.optional(),q: z.string().trim().max(500).optional(),diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex 3230e7bd5e..5aa3f17ba8 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -3,6 +3,7 @@ import { ASPECT_RATIOS, QUALITIES, PROJECT_STATUSES, SCENE_STATUSES, PLAN_STEP_Simport { ARC_SHAPE_IDS, ARC_ROLES } from './storyArc.js';import { BIBLE_LIMITS } from './storyBible.js';import { emptyToUndefined } from './zodCompat.js';+import { csvIdsParam } from './sharedSchemas.js';// =============================================================================// CREATIVE DIRECTOR + CREATE-SUITE IMPORTER SCHEMAS@@ -219,22 +220,14 @@ export const creativeDirectorProjectUpdateSchema = z.object({// never has to chunk while the request still stays bounded.export const CREATIVE_DIRECTOR_IDS_BATCH_MAX = 100;-// Query params for `GET /creative-director` (#4148). `ids` is the batch-by-id-// filter: the wire form is a CSV string (`?ids=a,b,c`) preprocessed into a-// trimmed, empties-dropped string[], mirroring catalogIngredientQuerySchema.-// An empty/all-blank CSV collapses to `undefined` so it reads cleanly as absent-// and the route falls through to the full list. Unlike the catalog schema this-// does NOT silently slice at the cap — an over-cap request is a 400 rather than-// a partial result the caller can't distinguish from "those ids don't exist".-// A repeated `?ids=a&ids=b` form arrives as an array and is validated as-is.-// Unknown keys (limit/offset) strip out of the parsed result — the route reads-// those straight off `req.query` for paginateArray.+// Query params for `GET /creative-director` (#4148). `ids` is the shared+// batch-by-id filter (see csvIdsParam) — an over-cap batch 400s rather than+// truncating, so the client can't mistake a sliced result for missing projects.+// An empty/all-blank value reads as absent and the route falls through to the+// 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: z.preprocess((v) => {- if (typeof v !== 'string') return v;- const parts = v.split(',').map((s) => s.trim()).filter(Boolean);- return parts.length ? parts : undefined;- }, z.array(z.string().trim().min(1).max(64)).max(CREATIVE_DIRECTOR_IDS_BATCH_MAX).optional()),+ ids: csvIdsParam({ max: CREATIVE_DIRECTOR_IDS_BATCH_MAX }),});// One scene in the treatment, written by the agent on the treatment task.diff --git a/server/lib/sharedSchemas.js b/server/lib/sharedSchemas.jsindex 08b9e1eb94..36e65f7850 100644--- a/server/lib/sharedSchemas.js+++ b/server/lib/sharedSchemas.js@@ -56,6 +56,25 @@ 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.+//+// `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+// partial result it can't distinguish from "those ids don't exist". `true`+// silently slices at `max`, which the catalog's ingredient list has done since+// 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);+ 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());+// subdirFilter is interpolated into an rsync `--include=${subdirFilter}/***`// arg (rsync runs shell:false, so this is not shell injection — but `*` would// expand to `--include=*/***` and defeat the filter chain, and `../foo` would