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 tracks/collections lists and fold three duplications into existing helpers (#3294)
[._.]/ Adam Eivyd7cf9096e136
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f04c4af6c2..48309dd434 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -46,6 +46,7 @@- **[issue-3265] Fixed a test that broke on its own once the calendar passed 2026-07-31.** An image-quota test compared against a reset timestamp baked into its fixture; once that instant passed, the code correctly ignored the stale time and the test started comparing against the wall clock, failing every run. The test now pins its own clock, and the ignore-a-past-reset path it accidentally exercised has coverage of its own.- **[issue-3267] Removed the unmount guard from the shared async-action hook, along with the test that could never fail.** The guard existed to avoid a "state update on an unmounted component" warning React stopped emitting in version 18, so its only remaining effect was to skip a no-op — while being the exact shape that froze every button backed by the hook under StrictMode. Its regression test asserted that the vanished warning never appeared, which stayed green even with the guard deleted; it now unmounts mid-request and asserts the action still resolves with its value.- **[issue-3291] The Video Gen form moved out of the page and into a hook of its own.** The page carried 56 pieces of form state and every URL-prefill, mode-transition and payload-shaping rule in one 2,100-line component, so the request the client sends had no single place to read — and no second surface could ever generate video without copying it. Form state, the ImageGen/Continue/Remix/`?lora=` prefill paths, the mode and backend switches that clear stale conditioning inputs, the keyframe/extend/audio/IC submit gates, and `buildGeneratePayload()` now live in `useVideoGenForm`, leaving the page to fetch, run, and render. Behaviour is unchanged, and the payload contract — grok versus local shapes, the empty-string sentinels, keyframe JSON, LoRA parallel arrays, and the mutually-exclusive IC reference channels — now has direct test coverage it never had before.+- **[issue-3294] Track and collection lists can now be paged, and three small duplications were folded back into the helpers that already existed.** `GET /api/tracks` and `GET /api/media/collections` returned every record with no ceiling while the structurally identical albums, artists and LoRA lists already accepted `?limit`/`?offset` — and tracks grow with every upload and generation. Both now take the same opt-in pagination as their siblings, still returning the plain array when no pagination is asked for, so existing callers are untouched. Alongside that: the Writers Room analysis banner stopped re-deriving the shared duration formatter, the Chief of Staff's on-demand spawner reads the app registry once per cycle instead of once per queued request, and the Feature Agents output and runs tabs now clear the previous agent's content when you switch agents — including a refresh whose response arrives after the switch, which could still paint the wrong agent's output.- **[issue-3250] Stabilize Music Video project-selection tests under CI load.** Project-selection coverage now waits for the requested project to be available before opening its board, preventing intermittent false failures.- **[issue-3292] Three sprite dialogs that every suite mocked away now have tests of their own.** The fork-a-character dialog, the reference-sprite picker, and the click-to-enlarge preview each carry real logic — the submit gate, the exact payload sent when forking, search filtering by name and id, and which asset the enlarged view opens — but no test file, and every suite that rendered them swapped in a stub. The fork payload was the sharpest edge: the server only ever checked a hand-written example of it, so a mismatch between what the dialog sends and what the server accepts could have sat behind two passing suites. Both of the payloads the dialog actually builds are now asserted on the client and replayed through the real server schema. No behaviour changed.diff --git a/client/src/components/feature-agents/OutputTab.jsx b/client/src/components/feature-agents/OutputTab.jsxindex 6e8442cf78..d84acd36ec 100644--- a/client/src/components/feature-agents/OutputTab.jsx+++ b/client/src/components/feature-agents/OutputTab.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useRef } from 'react';+import { useState, useEffect, useRef, useCallback } from 'react';import { Terminal, RefreshCw } from 'lucide-react';import * as api from '../../services/api';import socket from '../../services/socket';@@ -7,19 +7,31 @@ export default function OutputTab({ agent }) {const [output, setOutput] = useState('');const [agentId, setAgentId] = useState(null);const bottomRef = useRef(null);+ // Always holds the currently-selected agent so a response can be matched+ // against it. The refresh button fires outside the fetch effect, so an+ // effect-local `cancelled` flag would not cover it.+ const selectedIdRef = useRef(agent.id);+ const loadOutput = useCallback((id) => {+ api.getFeatureAgentOutput(id).then(data => {+ if (selectedIdRef.current !== id || !data) return;+ setOutput(data.output || '');+ setAgentId(data.agentId);+ }).catch(() => {});+ }, []);++ // Drop the previous agent's output the moment the selection changes —+ // otherwise it lingers until the new fetch lands and reads as though the+ // newly selected agent had already produced it. Keyed on `agent.id` alone so+ // a run starting (`currentAgentId` change) doesn't wipe streamed output.useEffect(() => {- let cancelled = false;- const fetch = () => {- api.getFeatureAgentOutput(agent.id).then(data => {- if (cancelled) return;- if (data) {- setOutput(data.output || '');- setAgentId(data.agentId);- }- }).catch(() => {});- };- fetch();+ selectedIdRef.current = agent.id;+ setOutput('');+ setAgentId(null);+ }, [agent.id]);++ useEffect(() => {+ loadOutput(agent.id);const handler = (data) => {if (data.agentId === agent.currentAgentId || data.featureAgentId === agent.id) {@@ -30,11 +42,10 @@ export default function OutputTab({ agent }) {socket.on('cos:feature-agent:output', handler);return () => {- cancelled = true;socket.off('cos:agent:output', handler);socket.off('cos:feature-agent:output', handler);};- }, [agent.id, agent.currentAgentId]);+ }, [agent.id, agent.currentAgentId, loadOutput]);useEffect(() => {bottomRef.current?.scrollIntoView({ behavior: 'smooth' });@@ -61,7 +72,7 @@ export default function OutputTab({ agent }) {)}</div><button- onClick={() => api.getFeatureAgentOutput(agent.id).then(d => d && setOutput(d.output || '')).catch(() => {})}+ onClick={() => loadOutput(agent.id)}aria-label="Refresh output"className="p-1.5 text-gray-400 hover:text-white hover:bg-port-border/50 rounded transition-colors">diff --git a/client/src/components/feature-agents/OutputTab.test.jsx b/client/src/components/feature-agents/OutputTab.test.jsxindex 88dff950fb..fdaf05c72d 100644--- a/client/src/components/feature-agents/OutputTab.test.jsx+++ b/client/src/components/feature-agents/OutputTab.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { act, render, screen } from '@testing-library/react';+import { act, fireEvent, render, screen } from '@testing-library/react';const getFeatureAgentOutput = vi.fn();@@ -51,4 +51,48 @@ describe('OutputTab staleness', () => {expect(screen.getByText(/run-b/)).toBeInTheDocument();expect(screen.queryByText(/A output/)).not.toBeInTheDocument();});++ it('drops a refresh-button response that lands after the user switched agents', async () => {+ const aResolvers = [];+ getFeatureAgentOutput.mockImplementation((agentId) => {+ if (agentId === 'agent-a') return new Promise((res) => { aResolvers.push(res); });+ return Promise.resolve({ output: 'B output', agentId: 'run-b' });+ });++ const { rerender } = render(<OutputTab agent={{ id: 'agent-a', currentAgentId: 'run-a' }} />);+ // Refresh fires outside the fetch effect, so it is not covered by the+ // effect cleanup — the guard has to key on the current selection.+ await act(async () => { fireEvent.click(screen.getByLabelText('Refresh output')); });++ rerender(<OutputTab agent={{ id: 'agent-b', currentAgentId: null }} />);+ await act(async () => {});+ expect(screen.getByText(/B output/)).toBeInTheDocument();++ await act(async () => {+ aResolvers.forEach((res) => res({ output: 'A output', agentId: 'run-a' }));+ await Promise.resolve();+ });++ expect(screen.queryByText(/A output/)).not.toBeInTheDocument();+ expect(screen.getByText(/B output/)).toBeInTheDocument();+ });++ it('clears the prior agent output while the new agent fetch is still in flight', async () => {+ let resolveB;+ getFeatureAgentOutput.mockImplementation((agentId) => {+ if (agentId === 'agent-a') return Promise.resolve({ output: 'A output', agentId: 'run-a' });+ return new Promise((res) => { resolveB = res; });+ });++ const { rerender } = render(<OutputTab agent={{ id: 'agent-a', currentAgentId: 'run-a' }} />);+ await act(async () => {});+ expect(screen.getByText(/A output/)).toBeInTheDocument();++ rerender(<OutputTab agent={{ id: 'agent-b', currentAgentId: 'run-b' }} />);+ await act(async () => {});+ expect(screen.queryByText(/A output/)).not.toBeInTheDocument();++ await act(async () => { resolveB({ output: 'B output', agentId: 'run-b' }); });+ expect(screen.getByText(/B output/)).toBeInTheDocument();+ });});diff --git a/client/src/components/feature-agents/RunsTab.jsx b/client/src/components/feature-agents/RunsTab.jsxindex adfb0be9f2..b045091df5 100644--- a/client/src/components/feature-agents/RunsTab.jsx+++ b/client/src/components/feature-agents/RunsTab.jsx@@ -11,6 +11,10 @@ export default function RunsTab({ agent }) {useEffect(() => {let cancelled = false;+ // Clear the previous agent's runs while the new fetch is in flight —+ // otherwise they stay on screen as though they belonged to this agent.+ setRuns([]);+ setLoading(true);api.getFeatureAgentRuns(agent.id, 50).then(data => {if (cancelled) return;setRuns(data || []);diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxindex 405a59a839..aced145b1e 100644--- a/client/src/components/writers-room/WorkEditor.jsx+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -46,7 +46,7 @@ import {import { listCatalogIngredientsForRef } from '../../services/apiCatalog';import { safeReadStorage, safeWriteStorage } from '../../lib/safeStorage';import { STATUS_LABELS } from './labels';-import { countWords } from '../../utils/formatters';+import { countWords, formatDurationSec } from '../../utils/formatters';import StoryboardPanel, { STORYBOARD_TAB, STORYBOARD_TAB_VALUES } from './StoryboardPanel';import LiveContinuationPanel from './LiveContinuationPanel';import LiveRenderPanel from './LiveRenderPanel';@@ -1232,9 +1232,7 @@ function AnalysisRunBanner({ kind, label, startedAt }) {return () => clearInterval(id);}, [startedAt]);- const mm = Math.floor(elapsed / 60);- const ss = elapsed % 60;- const timeStr = `${mm}:${ss.toString().padStart(2, '0')}`;+ const timeStr = formatDurationSec(elapsed);// Reassurance ladder — escalating context so the user can tell the// difference between "normal" and "this is taking unusually long."diff --git a/server/routes/mediaCollections.js b/server/routes/mediaCollections.jsindex 4c8670f2de..bd7502e22b 100644--- a/server/routes/mediaCollections.js+++ b/server/routes/mediaCollections.js@@ -1,5 +1,6 @@/**- * GET /api/media/collections → Collection[]+ * GET /api/media/collections → Collection[] (`?limit`/`?offset` switch it to+ * `{ items, total, limit, offset }`)* POST /api/media/collections → Collection (body: { name, description? })* GET /api/media/collections/:id → Collection* PATCH /api/media/collections/:id → Collection (body: { name?, description?, coverKey?, source? })@@ -13,7 +14,7 @@import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError, createServiceErrorMapper } from '../lib/errorHandler.js';-import { validateRequest, mediaCollectionBulkItemsSchema } from '../lib/validation.js';+import { validateRequest, mediaCollectionBulkItemsSchema, isPaginationRequested, paginateArray } from '../lib/validation.js';import * as svc from '../services/mediaCollections.js';const router = Router();@@ -56,8 +57,13 @@ const itemSchema = z.object({ref: refSchema,});-router.get('/', asyncHandler(async (_req, res) => {- res.json(await svc.listCollections());+// Backward-compatible by default: returns the full collections 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 list = await svc.listCollections();+ if (!isPaginationRequested(req.query)) return res.json(list);+ res.json(paginateArray(list, req.query, { defaultLimit: 50, maxLimit: 500 }));}));router.post('/', asyncHandler(async (req, res) => {diff --git a/server/routes/mediaCollections.test.js b/server/routes/mediaCollections.test.jsindex 1fd4a589fb..299c1ac3cc 100644--- a/server/routes/mediaCollections.test.js+++ b/server/routes/mediaCollections.test.js@@ -9,6 +9,7 @@ const stubs = {bulkUpdateCollectionItems: vi.fn(),updateCollection: vi.fn(async (id, patch) => ({ id, ...patch })),createCollection: vi.fn(async (input) => ({ id: 'new', ...input })),+ listCollections: vi.fn(async () => []),};vi.mock('../services/mediaCollections.js', async () => {@@ -18,6 +19,7 @@ vi.mock('../services/mediaCollections.js', async () => {bulkUpdateCollectionItems: (...args) => stubs.bulkUpdateCollectionItems(...args),updateCollection: (...args) => stubs.updateCollection(...args),createCollection: (...args) => stubs.createCollection(...args),+ listCollections: (...args) => stubs.listCollections(...args),};});@@ -124,3 +126,35 @@ describe('mediaCollections routes — provenance (#3311)', () => {expect(stubs.createCollection).toHaveBeenCalledWith({ name: 'Concept Art', description: '' });});});++describe('mediaCollections routes — GET / pagination', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ // Regression guard: every client caller (apiImageVideo.listMediaCollections)+ // calls this with no query params. If it ever returns an envelope instead of+ // a bare array, those pickers silently render empty.+ it('without pagination params returns the unbounded bare array', async () => {+ stubs.listCollections.mockResolvedValueOnce(+ Array.from({ length: 120 }, (_, i) => ({ id: `c-${i}`, name: `C${i}` }))+ );+ const r = await request(makeApp()).get('/api/media/collections');+ expect(r.status).toBe(200);+ expect(Array.isArray(r.body)).toBe(true);+ expect(r.body).toHaveLength(120);+ });++ it('returns a bounded envelope when pagination is requested', async () => {+ stubs.listCollections.mockResolvedValueOnce(+ Array.from({ length: 5 }, (_, i) => ({ id: `c-${i}`, name: `C${i}` }))+ );+ const r = await request(makeApp()).get('/api/media/collections?limit=2&offset=1');+ expect(r.status).toBe(200);+ expect(r.body.items).toHaveLength(2);+ expect(r.body.items[0].id).toBe('c-1');+ expect(r.body.total).toBe(5);+ expect(r.body.limit).toBe(2);+ expect(r.body.offset).toBe(1);+ });+});diff --git a/server/routes/tracks.js b/server/routes/tracks.jsindex 6aaf1ab364..0051ce690f 100644--- a/server/routes/tracks.js+++ b/server/routes/tracks.js@@ -1,7 +1,9 @@/*** Music track routes.*- * GET /api/tracks → Track[] (live, creation order)+ * GET /api/tracks → Track[] (live, creation order; `?limit`/`?offset`+ * switch it to the bounded+ * `{ items, total, limit, offset }` envelope)* POST /api/tracks → Track* GET /api/tracks/library → { tracks } (shared music library list)* POST /api/tracks/import/youtube → { jobId } (download + extract audio from a YouTube URL)@@ -28,7 +30,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 { uploadSingle } from '../lib/multipart.js';import * as tracks from '../services/tracks/index.js';import * as albums from '../services/albums/index.js';@@ -176,8 +178,13 @@ async function reconcileTrackAlbum(trackId, prevAlbumId, nextAlbumId) {}}-router.get('/', asyncHandler(async (_req, res) => {- res.json(await tracks.listTracks());+// Backward-compatible by default: returns the full tracks 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 list = await tracks.listTracks();+ if (!isPaginationRequested(req.query)) return res.json(list);+ res.json(paginateArray(list, req.query, { defaultLimit: 50, maxLimit: 500 }));}));// Shared music library — every uploaded/generated track sits here. The studiodiff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.jsindex 4b04fb3fd5..a086a0a9a8 100644--- a/server/routes/tracks.test.js+++ b/server/routes/tracks.test.js@@ -83,6 +83,32 @@ describe('tracks routes', () => {expect(r.body).toEqual([{ id: 'track-1', title: 'Intro' }]);});+ // Regression guard: every client caller (apiTracks.listTracks) calls this+ // with no query params. If it ever returns an envelope instead of a bare+ // array, those lists silently render empty.+ it('GET / without pagination params returns the unbounded bare array', async () => {+ tracks.listTracks.mockResolvedValueOnce(+ Array.from({ length: 120 }, (_, i) => ({ id: `track-${i}`, title: `T${i}` }))+ );+ const r = await request(app).get('/api/tracks');+ expect(r.status).toBe(200);+ expect(Array.isArray(r.body)).toBe(true);+ expect(r.body).toHaveLength(120);+ });++ it('GET / returns a bounded envelope when pagination is requested', async () => {+ tracks.listTracks.mockResolvedValueOnce(+ Array.from({ length: 5 }, (_, i) => ({ id: `track-${i}`, title: `T${i}` }))+ );+ const r = await request(app).get('/api/tracks?limit=2&offset=1');+ expect(r.status).toBe(200);+ expect(r.body.items).toHaveLength(2);+ expect(r.body.items[0].id).toBe('track-1');+ expect(r.body.total).toBe(5);+ expect(r.body.limit).toBe(2);+ expect(r.body.offset).toBe(1);+ });+it('GET /library returns the shared music library (not read as an id)', async () => {const r = await request(app).get('/api/tracks/library');expect(r.status).toBe(200);diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 70a20d1e54..4c9847524a 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -702,6 +702,9 @@ async function spawnPriority0OnDemand(ctx) {// requests for the same app don't each rewrite its activity record.const reviewStartedApps = new Set();if (onDemandRequests.length > 0 && tasksToSpawn.length < availableSlots) {+ // The app registry can't change mid-loop, so read it once per cycle rather+ // than once per request (getActiveApps' 2s cache can miss at a boundary).+ const apps = await getActiveApps().catch(() => []);for (const request of onDemandRequests) {if (tasksToSpawn.length >= availableSlots) break;@@ -720,7 +723,6 @@ async function spawnPriority0OnDemand(ctx) {let task = null;// Determine target app (if any)- const apps = await getActiveApps().catch(() => []);let targetApp = null;if (request.appId) {