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
feat: paginate creative-catalog + media list endpoints with shared paginateArray (#2535)
Adam Eivyf4ae538db04c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d3ff52d053..3de70938f1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -85,3 +85,4 @@- **[issue-2548] Replace the vacuous agentLifecycle spawn/completion replica tests with imports of real guard helpers.** `agentLifecycle.test.js` re-implemented production logic — local `unfixedSpawn`/`fixedSpawn` copies of the `spawningTasks` dedup flow and a `runCompletion`/`makeCompletionHarness` copy of the completion try/finally — and never imported `spawnAgentForTask`/`handleAgentCompletion`, so they stayed green when production regressed. The two concurrency contracts those replicas modelled are now extracted into `server/services/agentGuards.js`: `withSpawnDedupGuard(spawningTasks, taskId, fn)` (acquire-before-first-await, hold across the whole spawn body incl. the runner-enqueue handoff, release in `finally`, `SPAWN_DEDUP_SKIP` on a concurrent duplicate) and `withMapEntryCleanup(map, key, fn)` (delete the `runnerAgents` entry in `finally` even when a completion step throws). `spawnAgentForTask` now wraps `runAgentSpawn` in the former (dropping six inline `spawningTasks.delete` sites), and `handleAgentCompletion` wraps its body in the latter — so the tests drive the exact code production runs. The late-delete race that spawned a second agent for the same task id is now a behavioral test against the real guard, not a hand-copied one; the remaining source-scan tests were trimmed to non-negotiable orderings (the handedOff pre-spawn/post-handoff split, the #1563 claim/register ordering, the #989 marker release, the #2243 runner env merge) plus two wiring guards that pin the delegation. `cos.test.js` already drove the real `createDequeueCapacity`/`isMissionTierEligible`/`isIdleTierEligible` exports after #2530, so it was left as-is. New `agentGuards.test.js` unit-tests both helpers in isolation.- **[issue-2554] Align CoS chrome and scrollbar colors with port design tokens.** The Chief of Staff panel chrome hardcoded `bg-slate-900/60`, `hover:bg-slate-800/80`, the `from-slate-900/80 to-slate-900/40` gradients, and `text-slate-400` — a `slate` surface that ignored the active theme. Those now map to `bg-port-card`/`hover:bg-port-border`/`text-port-text-muted` (the collapse button's `text-gray-500 hover:text-white` also became `text-port-text-muted hover:text-port-text` so its icon stays legible in light themes), so the panel restyles with the selected theme. The global `::-webkit-scrollbar-thumb` (and its `:hover`) dropped their hardcoded `#3a3a3a`/`#4a4a4a` for the opaque, theme-derived `rgb(var(--port-text-muted))` and `rgb(var(--port-text))` — colors that stay high-contrast against the already-tokenized `rgb(var(--port-card))` track in both dark and light themes (an alpha-over-track blend would wash out on light cards, so the opaque muted-text token is used). The unread-count badges in `Layout.jsx` (four sites) and `NotificationDropdown.jsx` swapped `bg-yellow-500 text-black` for `bg-port-warning text-port-on-warning`; the Dashboard server-health glow's `shadow-[0_0_8px_#22c55e]`/`#ef4444` now reference `rgb(var(--port-success))`/`rgb(var(--port-error))`. The Ambient full-screen idle display is intentionally left on its fixed deep-black `bg-[#050505]` (with `text-white` content) — it is a theme-independent ambient/OLED surface, and making the backdrop theme-following would strand its non-tokenized white clock and translucent panels invisibly on light themes. Visual-only token swaps — no logic or layout change; the retokenized surfaces now follow the active theme instead of a fixed palette.+- **[issue-2535] Paginate the creative-catalog + media list endpoints with the shared `paginateArray` helper.** The primary index `GET`s for creativeDirector (`/`), storyBuilder (`/`), universeBuilder (`/`), moodBoard (`/`), videoTimeline (`/projects`), and loras (`/`) returned unbounded arrays. Each now opts into pagination the moment a client sends `limit`/`offset`, mirroring the `brainCrud` precedent: `isPaginationRequested(req.query)` gates a bounded `{ items, total, limit, offset }` envelope (via the existing `paginateArray` in `server/lib/validation.js`, `defaultLimit: 50`, `maxLimit: 500`), while a request with no pagination params still returns the full array byte-for-byte — so every current client (none of which pass those params to these routes) is unaffected and no client change is required. New route tests assert both the default array and the paginated envelope for each domain (moodBoard gains its first route test). Refs #2535 — CoS tasks (the `?full=1` default-paginated slice) already shipped; privacy vault/orgs/changes/brokers and digital-twin documents remain.diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsindex d5a718faa5..12fe374b6d 100644--- a/server/routes/creativeDirector.js+++ b/server/routes/creativeDirector.js@@ -20,6 +20,8 @@ import {creativeDirectorSceneUpdateSchema,creativeDirectorAutoCastSuggestSchema,creativeDirectorAutoCastApplySchema,+ isPaginationRequested,+ paginateArray,} from '../lib/validation.js';import {listProjects,@@ -40,8 +42,15 @@ import { createSmokeTestProject } from '../services/creativeDirector/smokeTest.jconst router = Router();-router.get('/', asyncHandler(async (_req, res) => {- res.json(await listProjects());+// 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.+router.get('/', asyncHandler(async (req, res) => {+ const projects = await listProjects();+ if (!isPaginationRequested(req.query)) {+ return res.json(projects);+ }+ res.json(paginateArray(projects, req.query, { defaultLimit: 50, maxLimit: 500 }));}));// Creative tool catalog (CDO Phase 4, #2186) — the studio Plan board + directivediff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.jsindex 68ea3c55d5..a8eae0aa5a 100644--- a/server/routes/creativeDirector.test.js+++ b/server/routes/creativeDirector.test.js@@ -76,6 +76,19 @@ describe('creativeDirector routes', () => {expect(r.status).toBe(200);expect(r.body).toEqual([{ id: 'cd-1', name: 'A' }]);});++ it('returns a bounded envelope when pagination is requested', async () => {+ cdService.listProjects.mockResolvedValueOnce(+ Array.from({ length: 5 }, (_, i) => ({ id: `cd-${i}`, name: `P${i}` }))+ );+ const r = await request(app).get('/api/creative-director?limit=2&offset=1');+ expect(r.status).toBe(200);+ expect(r.body.items).toHaveLength(2);+ expect(r.body.items[0].id).toBe('cd-1');+ expect(r.body.total).toBe(5);+ expect(r.body.limit).toBe(2);+ expect(r.body.offset).toBe(1);+ });});describe('GET /:id', () => {diff --git a/server/routes/loras.js b/server/routes/loras.jsindex 5a088bcbb3..39e8ef596e 100644--- a/server/routes/loras.js+++ b/server/routes/loras.js@@ -11,7 +11,7 @@ import { Router } from 'express';import { z } from 'zod';import { asyncHandler } from '../lib/errorHandler.js';import { deepMerge, isPlainObject } from '../lib/objects.js';-import { emptyToUndefined, validateRequest } from '../lib/validation.js';+import { emptyToUndefined, validateRequest, isPaginationRequested, paginateArray } from '../lib/validation.js';import {deleteLora,getLora,@@ -29,8 +29,15 @@ import { openSseStream } from '../lib/sseDownload.js';const router = Router();-router.get('/', asyncHandler(async (_req, res) => {- res.json(await listLoras());+// Backward-compatible by default: returns the full LoRA array. When a client+// passes `limit`/`offset`, the response becomes the bounded+// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.+router.get('/', asyncHandler(async (req, res) => {+ const loras = await listLoras();+ if (!isPaginationRequested(req.query)) {+ return res.json(loras);+ }+ res.json(paginateArray(loras, req.query, { defaultLimit: 50, maxLimit: 500 }));}));// LoRA suggestions — Civitai image LoRAs per runner family (mflux / flux2 /diff --git a/server/routes/loras.test.js b/server/routes/loras.test.jsindex 0fa0934746..ed426d7bab 100644--- a/server/routes/loras.test.js+++ b/server/routes/loras.test.js@@ -40,7 +40,7 @@ vi.mock('../services/settings.js', () => ({const { default: lorasRoutes } = await import('./loras.js');const { searchLorasInFamily } = await import('../services/civitaiSuggestions.js');-const { installFromHuggingface } = await import('../services/loras.js');+const { installFromHuggingface, listLoras } = await import('../services/loras.js');// Parse an SSE response body into an array of decoded frame objects.const parseSseFrames = (text) => text@@ -56,6 +56,29 @@ const makeApp = () => {return app;};+describe('GET /api/loras', () => {+ it('returns the full LoRA array by default', async () => {+ listLoras.mockResolvedValueOnce([{ filename: 'a.safetensors' }]);+ const res = await request(makeApp()).get('/api/loras');+ expect(res.status).toBe(200);+ expect(Array.isArray(res.body)).toBe(true);+ expect(res.body).toHaveLength(1);+ });++ it('returns a bounded envelope when pagination is requested', async () => {+ listLoras.mockResolvedValueOnce(+ Array.from({ length: 5 }, (_, i) => ({ filename: `l${i}.safetensors` }))+ );+ const res = await request(makeApp()).get('/api/loras?limit=2&offset=1');+ expect(res.status).toBe(200);+ expect(res.body.items).toHaveLength(2);+ expect(res.body.items[0].filename).toBe('l1.safetensors');+ expect(res.body.total).toBe(5);+ expect(res.body.limit).toBe(2);+ expect(res.body.offset).toBe(1);+ });+});+describe('POST /api/loras/install/huggingface/stream', () => {it('streams byte-progress frames then a complete frame carrying the sidecar', async () => {const res = await request(makeApp())diff --git a/server/routes/moodBoard.js b/server/routes/moodBoard.jsindex 9f2b09e4be..8615a67acb 100644--- a/server/routes/moodBoard.js+++ b/server/routes/moodBoard.js@@ -16,6 +16,8 @@ import {moodBoardItemCreateSchema,moodBoardItemUpdateSchema,moodBoardPinterestLinkSchema,+ isPaginationRequested,+ paginateArray,} from '../lib/validation.js';import {listBoards,@@ -33,8 +35,15 @@ import {const router = Router();-router.get('/', asyncHandler(async (_req, res) => {- res.json(await listBoards());+// Backward-compatible by default: returns the full boards array. When a client+// passes `limit`/`offset`, the response becomes the bounded+// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.+router.get('/', asyncHandler(async (req, res) => {+ const boards = await listBoards();+ if (!isPaginationRequested(req.query)) {+ return res.json(boards);+ }+ res.json(paginateArray(boards, req.query, { defaultLimit: 50, maxLimit: 500 }));}));router.get('/:id', asyncHandler(async (req, res) => {diff --git a/server/routes/moodBoard.test.js b/server/routes/moodBoard.test.jsnew file mode 100644index 0000000000..ee8387d14a--- /dev/null+++ b/server/routes/moodBoard.test.js@@ -0,0 +1,73 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Stub the service graph — this test verifies routing + the pagination envelope,+// not the DB-backed board logic (covered by moodBoard/db.test.js).+vi.mock('../services/moodBoard/index.js', () => ({+ listBoards: vi.fn(async () => []),+ getBoard: vi.fn(),+ createBoard: vi.fn(),+ updateBoard: vi.fn(),+ deleteBoard: vi.fn(),+ addBoardItem: vi.fn(),+ updateBoardItem: vi.fn(),+ removeBoardItem: vi.fn(),+ linkPinterestBoard: vi.fn(),+ unlinkPinterestBoard: vi.fn(),+ syncPinterestBoard: vi.fn(),+}));++import * as svc from '../services/moodBoard/index.js';+import moodBoardRoutes from './moodBoard.js';++const makeApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/mood-board', moodBoardRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('mood-board routes', () => {+ beforeEach(() => vi.clearAllMocks());++ describe('GET /', () => {+ it('returns the full boards array by default', async () => {+ svc.listBoards.mockResolvedValueOnce([{ id: 'mb-1', name: 'A' }]);+ const res = await request(makeApp()).get('/api/mood-board');+ expect(res.status).toBe(200);+ expect(Array.isArray(res.body)).toBe(true);+ expect(res.body).toHaveLength(1);+ });++ it('returns a bounded envelope when pagination is requested', async () => {+ svc.listBoards.mockResolvedValueOnce(+ Array.from({ length: 5 }, (_, i) => ({ id: `mb-${i}`, name: `B${i}` }))+ );+ const res = await request(makeApp()).get('/api/mood-board?limit=2&offset=1');+ expect(res.status).toBe(200);+ expect(res.body.items).toHaveLength(2);+ expect(res.body.items[0].id).toBe('mb-1');+ expect(res.body.total).toBe(5);+ expect(res.body.limit).toBe(2);+ expect(res.body.offset).toBe(1);+ });+ });++ describe('GET /:id', () => {+ it('returns 404 when the board is missing', async () => {+ svc.getBoard.mockResolvedValueOnce(null);+ const res = await request(makeApp()).get('/api/mood-board/nope');+ expect(res.status).toBe(404);+ });++ it('returns the board when found', async () => {+ svc.getBoard.mockResolvedValueOnce({ id: 'mb-1', name: 'A' });+ const res = await request(makeApp()).get('/api/mood-board/mb-1');+ expect(res.status).toBe(200);+ expect(res.body.id).toBe('mb-1');+ });+ });+});diff --git a/server/routes/storyBuilder.js b/server/routes/storyBuilder.jsindex 77b9a186c1..33b6515cfa 100644--- a/server/routes/storyBuilder.js+++ b/server/routes/storyBuilder.js@@ -9,6 +9,8 @@ import {storyStepRefineSchema,storyIssueLockSchema,storyIssuesGenerateSchema,+ isPaginationRequested,+ paginateArray,} from '../lib/validation.js';import { STEPS, isValidStepId } from '../lib/storyBuilderSteps.js';import {@@ -44,8 +46,15 @@ router.get('/steps', (_req, res) => {res.json({ steps: STEPS });});-router.get('/', asyncHandler(async (_req, res) => {- res.json(await listStorySessions());+// Backward-compatible by default: returns the full sessions array. When a client+// passes `limit`/`offset`, the response becomes the bounded+// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.+router.get('/', asyncHandler(async (req, res) => {+ const sessions = await listStorySessions();+ if (!isPaginationRequested(req.query)) {+ return res.json(sessions);+ }+ res.json(paginateArray(sessions, req.query, { defaultLimit: 50, maxLimit: 500 }));}));router.post('/', asyncHandler(async (req, res) => {diff --git a/server/routes/storyBuilder.test.js b/server/routes/storyBuilder.test.jsindex 508ac6d2ef..165d06e645 100644--- a/server/routes/storyBuilder.test.js+++ b/server/routes/storyBuilder.test.js@@ -56,6 +56,27 @@ describe('GET /api/story-builder/steps', () => {});});+describe('GET /api/story-builder', () => {+ it('returns the full sessions array by default', async () => {+ const res = await request(makeApp()).get('/api/story-builder');+ expect(res.status).toBe(200);+ expect(Array.isArray(res.body)).toBe(true);+ });++ it('returns a bounded envelope when pagination is requested', async () => {+ svc.listStorySessions.mockResolvedValueOnce(+ Array.from({ length: 5 }, (_, i) => ({ id: `stb-${i}` }))+ );+ const res = await request(makeApp()).get('/api/story-builder?limit=2&offset=1');+ expect(res.status).toBe(200);+ expect(res.body.items).toHaveLength(2);+ expect(res.body.items[0].id).toBe('stb-1');+ expect(res.body.total).toBe(5);+ expect(res.body.limit).toBe(2);+ expect(res.body.offset).toBe(1);+ });+});+describe('POST /api/story-builder', () => {it('creates a session (201) and dispatches to the service', async () => {const res = await request(makeApp()).post('/api/story-builder').send({ title: 'Salt Run', seedIdea: 'seed' });diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 3810e3734d..1d60d7f6c6 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -16,7 +16,7 @@import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError, createServiceErrorMapper } from '../lib/errorHandler.js';-import { validateRequest, optionalBooleanMap, llmSchema } from '../lib/validation.js';+import { validateRequest, optionalBooleanMap, llmSchema, isPaginationRequested, paginateArray } from '../lib/validation.js';import * as svc from '../services/universeBuilder.js';import * as canonSvc from '../services/universeCanon.js';import { expandUniverseCharacter } from '../services/universeCharacterExpand.js';@@ -370,8 +370,15 @@ const renderSchema = z.object({path: ['collectionName'],});-router.get('/', asyncHandler(async (_req, res) => {- res.json(await svc.listUniverses());+// Backward-compatible by default: returns the full universes array. When a client+// passes `limit`/`offset`, the response becomes the bounded+// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.+router.get('/', asyncHandler(async (req, res) => {+ const universes = await svc.listUniverses();+ if (!isPaginationRequested(req.query)) {+ return res.json(universes);+ }+ res.json(paginateArray(universes, req.query, { defaultLimit: 50, maxLimit: 500 }));}));router.post('/', asyncHandler(async (req, res) => {diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.jsindex 216c3b6b25..e496346759 100644--- a/server/routes/universeBuilder.test.js+++ b/server/routes/universeBuilder.test.js@@ -252,6 +252,19 @@ describe('universe-builder routes', () => {expect(res.body).toEqual([]);});+ it('GET / returns a bounded envelope when pagination is requested', async () => {+ const app = buildApp();+ for (const name of ['Alpha', 'Beta', 'Gamma']) {+ await request(app).post('/api/universe-builder').send({ name });+ }+ const res = await request(app).get('/api/universe-builder?limit=2&offset=1');+ expect(res.status).toBe(200);+ expect(res.body.items).toHaveLength(2);+ expect(res.body.total).toBe(3);+ expect(res.body.limit).toBe(2);+ expect(res.body.offset).toBe(1);+ });+it('GET /:id for a missing universe 404s without spamming console.error', async () => {// LoraDatasetDetail speculatively fetches a dataset's character.universeId// ({ silent: true }); that 404s whenever the universe was deleted. The routediff --git a/server/routes/videoTimeline.js b/server/routes/videoTimeline.jsindex cb6ac130cb..44cb3a7151 100644--- a/server/routes/videoTimeline.js+++ b/server/routes/videoTimeline.js@@ -9,7 +9,7 @@import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest } from '../lib/validation.js';+import { validateRequest, isPaginationRequested, paginateArray } from '../lib/validation.js';import {listProjects,getProject,@@ -41,8 +41,15 @@ const updateBodySchema = z.object({message: 'PATCH body must include at least name or clips',});-router.get('/projects', asyncHandler(async (_req, res) => {- res.json(await listProjects());+// 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.+router.get('/projects', asyncHandler(async (req, res) => {+ const projects = await listProjects();+ if (!isPaginationRequested(req.query)) {+ return res.json(projects);+ }+ res.json(paginateArray(projects, req.query, { defaultLimit: 50, maxLimit: 500 }));}));router.post('/projects', asyncHandler(async (req, res) => {diff --git a/server/routes/videoTimeline.test.js b/server/routes/videoTimeline.test.jsindex 985a52caad..c729a9e698 100644--- a/server/routes/videoTimeline.test.js+++ b/server/routes/videoTimeline.test.js@@ -34,6 +34,19 @@ describe('videoTimeline routes', () => {expect(r.status).toBe(200);expect(r.body).toHaveLength(1);});++ it('returns a bounded envelope when pagination is requested', async () => {+ svc.listProjects.mockResolvedValue(+ Array.from({ length: 5 }, (_, i) => ({ id: `p${i}`, name: `P${i}` }))+ );+ const r = await request(app).get('/api/video-timeline/projects?limit=2&offset=1');+ expect(r.status).toBe(200);+ expect(r.body.items).toHaveLength(2);+ expect(r.body.items[0].id).toBe('p1');+ expect(r.body.total).toBe(5);+ expect(r.body.limit).toBe(2);+ expect(r.body.offset).toBe(1);+ });});describe('POST /projects', () => {