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

perf: resolve a commission's render projects with a by-id batch (#4148)

Adam Eivy3c0018db451d
diff --git a/client/src/pages/CreativeCommissionDetail.jsx b/client/src/pages/CreativeCommissionDetail.jsx
index 9fa797a02f..bb19de48e1 100644
--- a/client/src/pages/CreativeCommissionDetail.jsx
+++ b/client/src/pages/CreativeCommissionDetail.jsx
@@ -27,7 +27,7 @@ import {
} from '../components/creative-commission/commissionForm.js';
import {
getCommission, updateCommission, deleteCommission,
- submitCommissionFeedback, runCommissionNow, listCreativeDirectorProjects,
+ submitCommissionFeedback, runCommissionNow, getCreativeDirectorProjectsByIds,
} from '../services/api';
export default function CreativeCommissionDetail() {
@@ -89,10 +89,11 @@ export default function CreativeCommissionDetail() {
}
}, [commission]);
- // The set of CD projects referenced by this commission's runs. Fetch the full
- // project list once (the list route returns non-slim payloads, so previews
- // compute with no per-card fetch) and index the referenced ones. Re-runs when
- // the projectId set changes (e.g. a Run Now appends a new render).
+ // The set of CD projects referenced by this commission's runs. Fetch ONLY
+ // those (#4148) — the batch `?ids=` filter costs one round trip sized to this
+ // commission's ≤50 persisted runs rather than to the install's total project
+ // count, and still returns the full non-slim payload previews compute from.
+ // Re-runs when the projectId set changes (e.g. a Run Now appends a render).
const projectIdsKey = useMemo(() => {
const ids = (commission?.runs || []).map((r) => r.projectId).filter(Boolean);
return [...new Set(ids)].sort().join(',');
@@ -100,17 +101,15 @@ export default function CreativeCommissionDetail() {
useEffect(() => {
if (!projectIdsKey) { setProjectsById(new Map()); setProjectsLoading(false); return; }
- const wanted = new Set(projectIdsKey.split(','));
let cancelled = false;
setProjectsLoading(true);
- listCreativeDirectorProjects()
+ getCreativeDirectorProjectsByIds(projectIdsKey.split(','), { silent: true })
.then((projects) => {
if (cancelled) return;
- const map = new Map();
- for (const p of Array.isArray(projects) ? projects : []) {
- if (wanted.has(p.id)) map.set(p.id, p);
- }
- setProjectsById(map);
+ // Index by id, not position: an id that no longer resolves (pruned
+ // project) is absent from the response, and its card degrades to the
+ // status-only placeholder.
+ setProjectsById(new Map((Array.isArray(projects) ? projects : []).map((p) => [p.id, p])));
})
.catch(() => { /* status-only cards degrade gracefully */ })
.finally(() => { if (!cancelled) setProjectsLoading(false); });
diff --git a/client/src/pages/CreativeCommissionDetail.test.jsx b/client/src/pages/CreativeCommissionDetail.test.jsx
new file mode 100644
index 0000000000..e119d70b1f
--- /dev/null
+++ b/client/src/pages/CreativeCommissionDetail.test.jsx
@@ -0,0 +1,107 @@
+/**
+ * Creative Commission detail page — render-history project resolution (#4148).
+ *
+ * The page used to pull EVERY Creative Director project just to index the ones
+ * its runs reference, so its cost scaled with the install's total project count.
+ * These cases pin the batch-by-id fetch: only the referenced ids go out, the
+ * whole-list route is never touched, and an id the batch can't resolve still
+ * degrades to the status-only card.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+vi.mock('../services/api', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getCommission: vi.fn(),
+ updateCommission: vi.fn(),
+ deleteCommission: vi.fn(),
+ submitCommissionFeedback: vi.fn(),
+ runCommissionNow: vi.fn(),
+ getCreativeDirectorProjectsByIds: vi.fn(() => Promise.resolve([])),
+ listCreativeDirectorProjects: vi.fn(() => Promise.resolve([])),
+}));
+// The config form loads model catalogs on mount — out of scope here, and it
+// would put real requests behind the assertions about which projects load.
+vi.mock('../components/creative-commission/CommissionConfigForm.jsx', () => ({ default: () => null }));
+vi.mock('../components/ui/Toast', () => ({
+ default: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() },
+}));
+// ProjectPreview reaches into the media/job graph; the assertions here are about
+// which projects resolved, so stub it down to an identifiable marker.
+vi.mock('../components/creative-director/ProjectPreview.jsx', () => ({
+ default: ({ project }) => <div data-testid={`preview-${project.id}`} />,
+}));
+
+import * as api from '../services/api';
+import CreativeCommissionDetail from './CreativeCommissionDetail';
+
+const COMMISSION = {
+ id: 'cc-1',
+ name: 'Example commission',
+ enabled: true,
+ targetAbility: 'video',
+ schedule: { kind: 'cron', cron: '0 9 * * *' },
+ assignment: {},
+ feedback: [],
+ runs: [
+ { id: 'run-1', projectId: 'cd-1', status: 'started', ranAt: '2026-05-01T10:00:00.000Z' },
+ { id: 'run-2', projectId: 'cd-2', status: 'started', ranAt: '2026-05-02T10:00:00.000Z' },
+ // Same project as run-1 — the batch must de-duplicate it.
+ { id: 'run-3', projectId: 'cd-1', status: 'started', ranAt: '2026-05-03T10:00:00.000Z' },
+ // No render at all — contributes no id.
+ { id: 'run-4', projectId: null, status: 'skipped', ranAt: '2026-05-04T10:00:00.000Z' },
+ ],
+};
+
+const renderPage = async () => {
+ render(<MemoryRouter><CreativeCommissionDetail /></MemoryRouter>);
+ await screen.findByRole('heading', { name: COMMISSION.name });
+};
+
+describe('CreativeCommissionDetail render-history project resolution (#4148)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.getCommission.mockResolvedValue(COMMISSION);
+ api.getCreativeDirectorProjectsByIds.mockResolvedValue([]);
+ });
+
+ it('fetches only the projects its runs reference, never the whole list', async () => {
+ api.getCreativeDirectorProjectsByIds.mockResolvedValue([
+ { id: 'cd-1', name: 'P1' }, { id: 'cd-2', name: 'P2' },
+ ]);
+ await renderPage();
+
+ await waitFor(() => expect(api.getCreativeDirectorProjectsByIds).toHaveBeenCalled());
+ const [ids] = api.getCreativeDirectorProjectsByIds.mock.calls[0];
+ expect([...ids].sort()).toEqual(['cd-1', 'cd-2']);
+ expect(api.listCreativeDirectorProjects).not.toHaveBeenCalled();
+
+ await waitFor(() => expect(screen.getAllByTestId('preview-cd-1')).toHaveLength(2));
+ expect(screen.getAllByTestId('preview-cd-2')).toHaveLength(1);
+ });
+
+ it('skips the request entirely when no run references a project', async () => {
+ api.getCommission.mockResolvedValue({
+ ...COMMISSION,
+ runs: [{ id: 'run-9', projectId: null, status: 'skipped', ranAt: '2026-05-04T10:00:00.000Z' }],
+ });
+ await renderPage();
+
+ await screen.findByText('no render');
+ expect(api.getCreativeDirectorProjectsByIds).not.toHaveBeenCalled();
+ expect(api.listCreativeDirectorProjects).not.toHaveBeenCalled();
+ });
+
+ it('degrades a run whose project the batch could not resolve to a status-only card', async () => {
+ api.getCreativeDirectorProjectsByIds.mockResolvedValue([{ id: 'cd-1', name: 'P1' }]);
+ await renderPage();
+
+ await waitFor(() => expect(screen.getAllByTestId('preview-cd-1')).toHaveLength(2));
+ // cd-2 was requested but is gone (pruned project) — no preview, and the
+ // placeholder must read "unavailable" rather than staying on "loading…".
+ expect(screen.queryByTestId('preview-cd-2')).toBeNull();
+ expect(screen.getByText('render unavailable')).toBeTruthy();
+ });
+});
diff --git a/client/src/services/apiCreativeDirector.js b/client/src/services/apiCreativeDirector.js
index 5e664956d6..9b89477163 100644
--- a/client/src/services/apiCreativeDirector.js
+++ b/client/src/services/apiCreativeDirector.js
@@ -7,6 +7,20 @@ export const listCreativeDirectorProjects = (options = {}) => request('/creative
// for 4s-poll surfaces like the Pipeline EpisodeVideoStage.
export const getCreativeDirectorProject = (id, { slim = false } = {}) =>
request(`/creative-director/${encodeURIComponent(id)}${slim ? '?slim=1' : ''}`);
+// Batch fetch projects by id (#4148) — the `ids` filter rides the normal list
+// 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 : []);
+};
export const createCreativeDirectorProject = (data, options = {}) => request('/creative-director', {
method: 'POST',
body: JSON.stringify(data),
diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.js
index 8d6884024e..3230e7bd5e 100644
--- a/server/lib/creativeDirectorValidation.js
+++ b/server/lib/creativeDirectorValidation.js
@@ -213,6 +213,30 @@ export const creativeDirectorProjectUpdateSchema = z.object({
modelOverrides: creativeDirectorModelOverridesSchema.optional(),
}).strict();
+// Max ids one `GET /creative-director?ids=` batch may resolve (#4148). Sized at
+// 2x the Creative Commission run cap (MAX_PERSISTED_RUNS = 50) — the batch's
+// heaviest caller resolves one project per persisted run — so the real consumer
+// 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.
+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()),
+});
+
// One scene in the treatment, written by the agent on the treatment task.
export const creativeDirectorSceneSchema = z.object({
sceneId: z.string().min(1).max(64),
diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.js
index 9b3489b298..d8830bfc23 100644
--- a/server/routes/creativeDirector.js
+++ b/server/routes/creativeDirector.js
@@ -20,11 +20,13 @@ import {
creativeDirectorSceneUpdateSchema,
creativeDirectorAutoCastSuggestSchema,
creativeDirectorAutoCastApplySchema,
+ creativeDirectorProjectQuerySchema,
isPaginationRequested,
paginateArray,
} from '../lib/validation.js';
import {
listProjects,
+ getProjectsByIds,
getProject,
createProject,
updateProject,
@@ -45,8 +47,16 @@ const router = Router();
// Backward-compatible by default: returns the full projects array. When a client
// passes `limit`/`offset`, the response becomes the bounded
// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.
+//
+// `?ids=a,b,c` (#4148) narrows to a known id set in one round trip — a caller
+// that needs a handful of projects (the Creative Commission detail page
+// resolving its runs' renders) no longer pays for every project on the install.
+// Ids that don't resolve are simply absent, so the response is never padded with
+// placeholders the client would have to filter. Mirrors the catalog's
+// `GET /catalog/ingredients?ids=` batch filter.
router.get('/', asyncHandler(async (req, res) => {
- const projects = await listProjects();
+ const { ids } = validateRequest(creativeDirectorProjectQuerySchema, req.query);
+ const projects = ids ? await getProjectsByIds(ids) : await listProjects();
if (!isPaginationRequested(req.query)) {
return res.json(projects);
}
diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.js
index 863c7435e0..f9e75804f9 100644
--- a/server/routes/creativeDirector.test.js
+++ b/server/routes/creativeDirector.test.js
@@ -4,6 +4,7 @@ import { request } from '../lib/testHelper.js';
vi.mock('../services/creativeDirector/local.js', () => ({
listProjects: vi.fn(async () => [{ id: 'cd-1', name: 'A' }]),
+ getProjectsByIds: vi.fn(async () => []),
getProject: vi.fn(),
createProject: vi.fn(),
updateProject: vi.fn(async (id, patch) => ({ id, ...patch })),
@@ -58,6 +59,7 @@ import * as autoCast from '../services/creativeDirector/autoCast.js';
import * as hook from '../services/creativeDirector/completionHook.js';
import * as firstPass from '../services/creativeDirector/firstPassGen.js';
import * as firstPassMusicBed from '../services/creativeDirector/firstPassMusicGen.js';
+import { CREATIVE_DIRECTOR_IDS_BATCH_MAX } from '../lib/creativeDirectorValidation.js';
import creativeDirectorRoutes from './creativeDirector.js';
describe('creativeDirector routes', () => {
@@ -89,6 +91,36 @@ describe('creativeDirector routes', () => {
expect(r.body.limit).toBe(2);
expect(r.body.offset).toBe(1);
});
+
+ // #4148 — batch-by-id so a caller referencing a handful of projects doesn't
+ // pay for every project on the install.
+ it('with ?ids= resolves only the named projects and never lists them all', async () => {
+ cdService.getProjectsByIds.mockResolvedValueOnce([{ id: 'cd-2', name: 'B' }, { id: 'cd-9', name: 'I' }]);
+ const r = await request(app).get('/api/creative-director?ids=cd-2,cd-9');
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual([{ id: 'cd-2', name: 'B' }, { id: 'cd-9', name: 'I' }]);
+ expect(cdService.getProjectsByIds).toHaveBeenCalledWith(['cd-2', 'cd-9']);
+ expect(cdService.listProjects).not.toHaveBeenCalled();
+ });
+
+ it('trims and drops blank ids, and falls back to the full list when all are blank', async () => {
+ cdService.getProjectsByIds.mockResolvedValueOnce([{ id: 'cd-2', name: 'B' }]);
+ await request(app).get('/api/creative-director?ids=%20cd-2%20,,');
+ expect(cdService.getProjectsByIds).toHaveBeenCalledWith(['cd-2']);
+
+ const r = await request(app).get('/api/creative-director?ids=%20,,');
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual([{ id: 'cd-1', name: 'A' }]);
+ expect(cdService.listProjects).toHaveBeenCalled();
+ });
+
+ 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}`);
+ expect(r.status).toBe(400);
+ expect(cdService.getProjectsByIds).not.toHaveBeenCalled();
+ expect(cdService.listProjects).not.toHaveBeenCalled();
+ });
});
describe('GET /:id', () => {
diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.js
index 7906f00803..dca7042799 100644
--- a/server/services/creativeDirector/local.js
+++ b/server/services/creativeDirector/local.js
@@ -75,6 +75,11 @@ export async function getProject(id, options = {}) {
return (await selectBackend()).getProject(id, options);
}
+/** Batch fetch by id (#4148) — see the backends for the per-store implementation. */
+export async function getProjectsByIds(ids, options = {}) {
+ return (await selectBackend()).getProjectsByIds(ids, options);
+}
+
/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
export async function listProjectIds(options = {}) {
return (await selectBackend()).listProjectIds(options);
diff --git a/server/services/creativeDirector/local.test.js b/server/services/creativeDirector/local.test.js
index de6706e6ae..4f124aae1d 100644
--- a/server/services/creativeDirector/local.test.js
+++ b/server/services/creativeDirector/local.test.js
@@ -32,7 +32,7 @@ vi.mock('./firstPassGen.js', () => ({
enqueueFirstPassSceneFrames: vi.fn(async () => ({ mode: 'local', enqueued: [], skipped: [] })),
}));
-const { setTreatment, recordRun, updateRun, trimRuns } = await import('./local.js');
+const { setTreatment, recordRun, updateRun, trimRuns, getProjectsByIds } = await import('./local.js');
import * as firstPassGen from './firstPassGen.js';
const VALID_TREATMENT = {
@@ -226,3 +226,35 @@ describe('runs[] cap enforced at saveAll chokepoint', () => {
expect(patched.status).toBe('completed');
});
});
+
+// #4148 — batch-by-id read (file backend, through the dispatcher). The Creative
+// Commission detail page resolves only the projects its runs reference instead
+// of listing every project on the install.
+describe('getProjectsByIds (#4148)', () => {
+ const STORED = [
+ { id: 'cd-1', name: 'One' },
+ { id: 'cd-2', name: 'Two' },
+ { id: 'cd-3', name: 'Three', deleted: true },
+ ];
+
+ it('returns only the requested live projects, ignoring unknown ids', async () => {
+ mockReadJSONFile.mockResolvedValue(STORED);
+ const found = await getProjectsByIds(['cd-2', 'cd-nope', 'cd-1']);
+ expect(found.map((p) => p.id)).toEqual(['cd-1', 'cd-2']);
+ });
+
+ it('omits tombstoned projects unless includeDeleted is set', async () => {
+ mockReadJSONFile.mockResolvedValue(STORED);
+ expect(await getProjectsByIds(['cd-3'])).toEqual([]);
+ const withDeleted = await getProjectsByIds(['cd-3'], { includeDeleted: true });
+ expect(withDeleted.map((p) => p.id)).toEqual(['cd-3']);
+ });
+
+ it('short-circuits an empty/blank id list without reading the store', async () => {
+ mockReadJSONFile.mockResolvedValue(STORED);
+ expect(await getProjectsByIds([])).toEqual([]);
+ expect(await getProjectsByIds([null, undefined, ''])).toEqual([]);
+ expect(await getProjectsByIds()).toEqual([]);
+ expect(mockReadJSONFile).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/creativeDirector/projectsDB.js b/server/services/creativeDirector/projectsDB.js
index 21ce611d25..35f0fff4dc 100644
--- a/server/services/creativeDirector/projectsDB.js
+++ b/server/services/creativeDirector/projectsDB.js
@@ -113,6 +113,21 @@ export async function getProject(id, { includeDeleted = false } = {}) {
return includeDeleted || !project.deleted ? project : null;
}
+/**
+ * Batch fetch by id (#4148) — one round trip for a known id set, so a caller
+ * that only needs a handful of projects (the Creative Commission detail page
+ * resolving its runs' renders) doesn't pull the whole table. Unknown ids are
+ * simply absent from the result; order matches listProjects (created_at ASC).
+ */
+export async function getProjectsByIds(ids, { includeDeleted = false } = {}) {
+ const wanted = [...new Set((ids || []).filter(Boolean))];
+ if (wanted.length === 0) return [];
+ const result = includeDeleted
+ ? await query(`SELECT id, data FROM creative_director_projects WHERE id = ANY($1) ORDER BY created_at ASC`, [wanted])
+ : await query(`SELECT id, data FROM creative_director_projects WHERE id = ANY($1) AND deleted = FALSE ORDER BY created_at ASC`, [wanted]);
+ return result.rows.map(rowToProject);
+}
+
/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
export async function listProjectIds({ includeDeleted = false } = {}) {
const result = includeDeleted
diff --git a/server/services/creativeDirector/projectsDB.test.js b/server/services/creativeDirector/projectsDB.test.js
index 19432469df..4350fe37ac 100644
--- a/server/services/creativeDirector/projectsDB.test.js
+++ b/server/services/creativeDirector/projectsDB.test.js
@@ -98,6 +98,24 @@ describe.skipIf(!dbReady)('projectsDB round-trip', () => {
expect(all.find((p) => p.name === 'Legacy row')?.id).toBe(id);
});
+ // #4148 — the batch-by-id read the Creative Commission detail page uses so it
+ // doesn't list every project on the install.
+ it('batch-fetches by id, skipping unknown ids and tombstoned projects', async () => {
+ const a = await db.createProject(CREATE_INPUT);
+ const b = await db.createProject(CREATE_INPUT);
+ const gone = await db.createProject(CREATE_INPUT);
+ created.push(a.id, b.id, gone.id);
+ await db.deleteProject(gone.id);
+
+ const batch = await db.getProjectsByIds([a.id, 'cd-does-not-exist', gone.id, b.id]);
+ expect(batch.map((p) => p.id).sort()).toEqual([a.id, b.id].sort());
+
+ expect(await db.getProjectsByIds([])).toEqual([]);
+ // includeDeleted opts the tombstone back in (the sync/GC read shape).
+ const withDeleted = await db.getProjectsByIds([gone.id], { includeDeleted: true });
+ expect(withDeleted.map((p) => p.id)).toEqual([gone.id]);
+ });
+
it('applies a treatment and patches a scene', async () => {
const p = await db.createProject(CREATE_INPUT);
created.push(p.id);
diff --git a/server/services/creativeDirector/projectsFile.js b/server/services/creativeDirector/projectsFile.js
index a5f22498cc..9813db7942 100644
--- a/server/services/creativeDirector/projectsFile.js
+++ b/server/services/creativeDirector/projectsFile.js
@@ -63,6 +63,18 @@ export async function getProject(id, { includeDeleted = false } = {}) {
return includeDeleted || !found.deleted ? found : null;
}
+/**
+ * Batch fetch by id (#4148) — mirrors the PG backend's single-round-trip lookup
+ * so a caller with a known id set doesn't have to list every project. Unknown
+ * ids are simply absent from the result; order follows the stored append order.
+ */
+export async function getProjectsByIds(ids, { includeDeleted = false } = {}) {
+ const wanted = new Set((ids || []).filter(Boolean));
+ if (wanted.size === 0) return [];
+ const all = await loadAll();
+ return all.filter((p) => wanted.has(p.id) && (includeDeleted || !p.deleted));
+}
+
/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
export async function listProjectIds({ includeDeleted = false } = {}) {
const all = await loadAll();