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: paginate the Writers Room library with stable snapshots (#8268)

[._.]/ Adam Eivye6802a8bce22
diff --git a/client/src/components/writers-room/LibraryPane.jsx b/client/src/components/writers-room/LibraryPane.jsx
index afab794851..51e62b7c97 100644
--- a/client/src/components/writers-room/LibraryPane.jsx
+++ b/client/src/components/writers-room/LibraryPane.jsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Folder, FolderPlus, FilePlus, FileText, ChevronDown, ChevronRight, Trash2, GripVertical, PanelLeftClose } from 'lucide-react';
import {
DndContext, DragOverlay, KeyboardSensor, PointerSensor,
@@ -6,6 +6,9 @@ import {
} from '@dnd-kit/core';
import { createFreeDroppableKeyboardCoordinates, keyboardAwareCollisionDetection } from '../../lib/dndKeyboardCoordinates';
import toast from '../ui/Toast';
+import CollapsibleListItem from '../ui/CollapsibleListItem';
+import InfiniteScrollFooter from '../ui/InfiniteScrollFooter';
+import { formatCount } from '../../utils/formatters';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import {
createWritersRoomFolder,
@@ -26,8 +29,10 @@ const libraryKeyboardCoordinates = createFreeDroppableKeyboardCoordinates();
export default function LibraryPane({
folders, works, activeWorkId, onSelectWork, onRefresh, onCollapse,
- creatingWork, onCreatingWorkChange,
+ creatingWork, onCreatingWorkChange, paging,
}) {
+ const deletingWorks = useRef(new Set());
+ const [removingWorks, setRemovingWorks] = useState(new Set());
const [openFolders, setOpenFolders] = useState({});
const [creatingFolder, setCreatingFolder] = useState(false);
const [folderName, setFolderName] = useState('');
@@ -70,7 +75,7 @@ export default function LibraryPane({
setFolderName('');
setCreatingFolder(false);
setOpenFolders((s) => ({ ...s, [folder.id]: true }));
- onRefresh?.();
+ onRefresh?.({ folder });
};
const submitWork = async (e) => {
@@ -85,19 +90,27 @@ export default function LibraryPane({
setWorkTitle('');
setWorkKind('short-story');
onCreatingWorkChange(null);
- onRefresh?.();
+ onRefresh?.({ work });
onSelectWork?.(work.id);
};
const handleDeleteFolder = (id) => confirmDelete(async () => {
- await deleteWritersRoomFolder(id, { silent: true }).catch((err) => toast.error(`Delete failed: ${err.message}`));
- onRefresh?.();
+ const result = await deleteWritersRoomFolder(id, { silent: true }).catch((err) => {
+ toast.error(`Delete failed: ${err.message}`);
+ return null;
+ });
+ if (result) onRefresh?.({ deletedFolderId: id });
});
const handleDeleteWork = (id) => confirmDelete(async () => {
- await deleteWritersRoomWork(id, { silent: true }).catch((err) => toast.error(`Delete failed: ${err.message}`));
- if (activeWorkId === id) onSelectWork?.(null);
- onRefresh?.();
+ if (deletingWorks.current.has(id)) return;
+ deletingWorks.current.add(id);
+ const result = await deleteWritersRoomWork(id, { silent: true }).catch((err) => {
+ toast.error(`Delete failed: ${err.message}`);
+ return null;
+ });
+ if (!result) { deletingWorks.current.delete(id); return; }
+ setRemovingWorks(prev => new Set([...prev, id]));
});
// PointerSensor with a small activation distance so a quick click still
@@ -132,7 +145,7 @@ export default function LibraryPane({
const targetFolder = folders.find((f) => f.id === targetFolderId);
toast.success(`Moved "${work.title}" to ${targetFolder ? targetFolder.name : 'Unfiled'}`);
if (targetFolderId) setOpenFolders((s) => ({ ...s, [targetFolderId]: true }));
- onRefresh?.();
+ onRefresh?.({ work: updated });
}, [folders, onRefresh]);
// Escape (and a pointer drag released outside any zone) ends the drag without
@@ -175,8 +188,14 @@ export default function LibraryPane({
}, [folders]);
const renderWorkRow = (work) => (
+ <li key={work.id} tabIndex={-1}>
+ <CollapsibleListItem removing={removingWorks.has(work.id)} spacing="0.125rem" onExited={() => {
+ if (activeWorkId === work.id) onSelectWork?.(null);
+ onRefresh?.({ deletedWorkId: work.id });
+ deletingWorks.current.delete(work.id);
+ setRemovingWorks(prev => { const next = new Set(prev); next.delete(work.id); return next; });
+ }}>
<WorkRow
- key={work.id}
work={work}
isActive={work.id === activeWorkId}
confirming={isConfirming(`work:${work.id}`)}
@@ -185,6 +204,8 @@ export default function LibraryPane({
onConfirmDelete={() => handleDeleteWork(work.id)}
onCancelDelete={cancelDelete}
/>
+ </CollapsibleListItem>
+ </li>
);
return (
@@ -278,7 +299,7 @@ export default function LibraryPane({
onDragCancel={handleDragCancel}
>
<ul className="space-y-1">
- {folders.length === 0 && grouped.get(null).length === 0 && !creatingFolder && !creatingWork && (
+ {(!paging || (paging.loaded && !paging.hasMore && !paging.error)) && folders.length === 0 && grouped.get(null).length === 0 && !creatingFolder && !creatingWork && (
<li className="px-2 py-3 text-center">
<p className="text-xs text-gray-500 mb-2">No works yet.</p>
<button
@@ -303,6 +324,7 @@ export default function LibraryPane({
<FolderRow
key={folder.id}
folder={folder}
+ partial={paging?.hasMore}
works={grouped.get(folder.id) || []}
isOpen={!!openFolders[folder.id]}
isDragging={!!draggingWork}
@@ -326,6 +348,21 @@ export default function LibraryPane({
)}
</DragOverlay>
</DndContext>
+ {paging && (
+ <>
+ <p className="px-2 text-xs text-port-text-muted">
+ {formatCount(works.length)} works loaded
+ </p>
+ <InfiniteScrollFooter
+ autoLoad={false}
+ hasMore={paging.hasMore}
+ loading={paging.loading}
+ error={paging.error}
+ onLoadMore={paging.error?.code === 'CURSOR_EXPIRED' ? paging.reload : paging.loadMore}
+ label="Load more works"
+ />
+ </>
+ )}
</div>
);
}
@@ -338,7 +375,7 @@ function WorkRow({ work, isActive, confirming, onSelect, onRequestDelete, onConf
data: { work },
});
return (
- <li className={`group relative ${isDragging ? 'opacity-30' : ''}`}>
+ <div className={`group relative ${isDragging ? 'opacity-30' : ''}`}>
<div className="flex items-stretch">
<button
ref={setNodeRef}
@@ -380,7 +417,7 @@ function WorkRow({ work, isActive, confirming, onSelect, onRequestDelete, onConf
<Trash2 size={14} />
</button>
)}
- </li>
+ </div>
);
}
@@ -399,7 +436,7 @@ function UnfiledZone({ works, renderWorkRow, showHeader, isDragging }) {
<div className="text-[10px] uppercase text-gray-500 px-2 py-1">Unfiled</div>
)}
{hasWorks ? (
- <ul className="space-y-0.5 pl-1 relative">{works.map(renderWorkRow)}</ul>
+ <ul className="pl-1 relative">{works.map(renderWorkRow)}</ul>
) : (
<div className="text-xs text-gray-600 italic px-2 py-1">Drop here to unfile</div>
)}
@@ -407,7 +444,7 @@ function UnfiledZone({ works, renderWorkRow, showHeader, isDragging }) {
);
}
-function FolderRow({ folder, works, isOpen, isDragging, confirming, onToggle, onCreateWork, onRequestDelete, onConfirmDelete, onCancelDelete, renderWorkRow }) {
+function FolderRow({ folder, partial, works, isOpen, isDragging, confirming, onToggle, onCreateWork, onRequestDelete, onConfirmDelete, onCancelDelete, renderWorkRow }) {
const { setNodeRef, isOver } = useDroppable({ id: `folder:${folder.id}`, data: { folderId: folder.id } });
return (
<li className="group/folder">
@@ -424,7 +461,7 @@ function FolderRow({ folder, works, isOpen, isDragging, confirming, onToggle, on
{isOpen ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
<Folder size={14} className="text-gray-400" />
<span className="flex-1 text-left truncate">{folder.name}</span>
- <span className="text-[10px] text-gray-500">{works.length}</span>
+ <span className="text-[10px] text-gray-500">{formatCount(works.length)}{partial ? '+ loaded' : ''}</span>
</button>
{confirming ? (
<ConfirmButtonPair
@@ -456,9 +493,9 @@ function FolderRow({ folder, works, isOpen, isDragging, confirming, onToggle, on
)}
</div>
{isOpen && (
- <ul className="space-y-0.5 pl-5 relative">
+ <ul className="pl-5 relative">
{works.length === 0 && (
- <li className="text-xs text-gray-500 px-2 py-1">Empty</li>
+ <li className="text-xs text-gray-500 px-2 py-1">{partial ? 'No loaded works in this folder' : 'Empty'}</li>
)}
{works.map(renderWorkRow)}
</ul>
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index fa27ad05db..3ccd462506 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -264,4 +264,4 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useGalleryPreviewResolver` | Builds the stable `resolveItem` callback that resolves a `?preview=` param the host's own items list does not contain, by looking the record up in the gallery and normalizing it. `usePreviewRoute` uses it as its DEFAULT. | Call it directly only to narrow the lookup — `collectionId` scopes it to one collection. |
| `useImageVariants` | Fetches the original-vs-cleaned variant set for the one open image (`GET /api/image-gen/:filename/variants`), normalized; reuses the held group across toggle clicks and aborts a superseded lookup. `null` while unfetched or failed, `[]` when the image is not indexed. | `MediaPreview` calls it for every image preview; neither a page-owned ref list nor a 60-row gallery window is a complete source of variant lineage. |
| `useGalleryPage` | Bounded image or mixed-media browsing with debounced server search, scopes, totals, stale-response cancellation and retryable next pages. | Gallery grids and pickers; `getGalleryImages` hydrates known references separately. |
-| `usePagedCollection` | `usePagedCollection(fetchPage, { enabled })` — bounded cursor pages, deduplication by id, single-flight loading, abort/stale-query protection, retry and reset. | Growing cursor-based collections; pair with `InfiniteScrollFooter`. |
+| `usePagedCollection` | `usePagedCollection(fetchPage, { enabled })` — bounded cursor pages, deduplication by id, single-flight loading, abort/stale-query protection, retry, reset, and local mutation via setItems. | Growing cursor-based collections; pair with `InfiniteScrollFooter`. |
diff --git a/client/src/hooks/usePagedCollection.js b/client/src/hooks/usePagedCollection.js
index 9b3bda46a4..eeb4ea0faa 100644
--- a/client/src/hooks/usePagedCollection.js
+++ b/client/src/hooks/usePagedCollection.js
@@ -64,5 +64,8 @@ export function usePagedCollection(fetchPage, { enabled = true } = {}) {
return () => { generation.current += 1; refreshQueued.current = false; pending.current?.abort(); pending.current = null; };
}, [reload]);
- return { ...page, hasMore: !page.loaded || page.nextCursor != null, loadMore, reload, refreshFirst };
+ const setItems = useCallback(update => commit({ ...state.current,
+ items: typeof update === 'function' ? update(state.current.items) : update }), [commit]);
+
+ return { ...page, setItems, hasMore: !page.loaded || page.nextCursor != null, loadMore, reload, refreshFirst };
}
diff --git a/client/src/pages/WritersRoom.jsx b/client/src/pages/WritersRoom.jsx
index 898e080c24..b9a9d8826a 100644
--- a/client/src/pages/WritersRoom.jsx
+++ b/client/src/pages/WritersRoom.jsx
@@ -12,6 +12,7 @@ import {
getWritersRoomWork,
} from '../services/apiWritersRoom';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
+import { usePagedCollection } from '../hooks/usePagedCollection';
import useMounted from '../hooks/useMounted';
const LIBRARY_COLLAPSED_KEY = 'wr.libraryCollapsed';
@@ -20,7 +21,10 @@ export default function WritersRoom() {
const { workId } = useParams();
const navigate = useNavigate();
const [folders, setFolders] = useState([]);
- const [works, setWorks] = useState([]);
+ const fetchWorks = useCallback(({ cursor, signal }) =>
+ listWritersRoomWorks({ limit: 50, cursor }, { signal, silent: true }), []);
+ const worksPage = usePagedCollection(fetchWorks);
+ const { items: works, setItems: setWorks, reload: reloadWorks } = worksPage;
const [activeWork, setActiveWork] = useState(null);
const [creatingWork, setCreatingWork] = useState(null);
const [loadingWork, setLoadingWork] = useState(false);
@@ -39,13 +43,9 @@ export default function WritersRoom() {
const mountedRef = useMounted();
const refreshLibrary = useCallback(async () => {
- const [foldersList, worksList] = await Promise.all([
- listWritersRoomFolders().catch(() => []),
- listWritersRoomWorks().catch(() => []),
- ]);
+ const foldersList = await listWritersRoomFolders().catch(() => []);
if (!mountedRef.current) return;
setFolders(foldersList);
- setWorks(worksList);
}, []);
useEffect(() => { refreshLibrary(); }, [refreshLibrary]);
@@ -179,7 +179,21 @@ export default function WritersRoom() {
works={works}
activeWorkId={activeWork?.id}
onSelectWork={selectWork}
- onRefresh={refreshLibrary}
+ onRefresh={(change) => {
+ if (change?.work) {
+ const updated = change.work;
+ const draft = updated.drafts?.find(item => item.id === updated.activeDraftVersionId);
+ setWorks(prev => [{ ...updated, wordCount: draft?.wordCount ?? 0 }, ...prev.filter(item => item.id !== updated.id)]);
+ } else if (change?.deletedWorkId) {
+ setWorks(prev => prev.filter(item => item.id !== change.deletedWorkId));
+ } else if (change?.folder) {
+ setFolders(prev => [...prev, change.folder]);
+ } else if (change?.deletedFolderId) {
+ refreshLibrary();
+ setWorks(prev => prev.map(item => item.folderId === change.deletedFolderId ? { ...item, folderId: null } : item));
+ } else { refreshLibrary(); reloadWorks(); }
+ }}
+ paging={worksPage}
onCollapse={toggleLibrary}
creatingWork={creatingWork}
onCreatingWorkChange={setCreatingWork}
diff --git a/client/src/pages/WritersRoom.test.jsx b/client/src/pages/WritersRoom.test.jsx
index 88cf8bff9e..f092ae00e0 100644
--- a/client/src/pages/WritersRoom.test.jsx
+++ b/client/src/pages/WritersRoom.test.jsx
@@ -5,12 +5,13 @@ import { MemoryRouter, Route, Routes } from 'react-router';
vi.mock('../services/apiWritersRoom', async (importOriginal) => ({
...await importOriginal(),
listWritersRoomFolders: vi.fn(async () => []),
- listWritersRoomWorks: vi.fn(async () => []),
+ listWritersRoomWorks: vi.fn(async () => ({ items: [], total: 0, nextCursor: null })),
getWritersRoomWork: vi.fn(),
createWritersRoomWork: vi.fn(async () => ({ id: 'work-new' })),
}));
import WritersRoom from './WritersRoom';
+import { listWritersRoomWorks } from '../services/apiWritersRoom';
describe('WritersRoom empty state', () => {
it('opens the existing New work form from the unselected work pane', async () => {
@@ -40,3 +41,24 @@ describe('WritersRoom empty state', () => {
expect(await screen.findByText('New work opened')).toBeInTheDocument();
});
});
+
+
+it('loads 50 works, appends on demand, and restarts an expired snapshot', async () => {
+ listWritersRoomWorks.mockResolvedValueOnce({ items: [{ id: 'a', title: 'First work' }], total: 2, nextCursor: 'page-two' })
+ .mockResolvedValueOnce({ items: [{ id: 'b', title: 'Second work' }], total: 3, nextCursor: 'page-three' })
+ .mockRejectedValueOnce(Object.assign(new Error('Library page expired. Restart the library to continue.'), { code: 'CURSOR_EXPIRED' }))
+ .mockResolvedValueOnce({ items: [{ id: 'c', title: 'Fresh work' }], total: 1, nextCursor: null });
+ render(<MemoryRouter><WritersRoom /></MemoryRouter>);
+ expect(await screen.findByText('First work')).toBeInTheDocument();
+ expect(screen.queryByText('Second work')).toBeNull();
+ expect(listWritersRoomWorks).toHaveBeenLastCalledWith({ limit: 50, cursor: null }, expect.objectContaining({ silent: true }));
+ fireEvent.click(screen.getByRole('button', { name: 'Load more works' }));
+ expect(await screen.findByText('Second work')).toBeInTheDocument();
+ expect(screen.getByText('First work')).toBeInTheDocument();
+ expect(listWritersRoomWorks).toHaveBeenLastCalledWith({ limit: 50, cursor: 'page-two' }, expect.anything());
+ fireEvent.click(screen.getByRole('button', { name: 'Load more works' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Retry loading' }));
+ expect(await screen.findByText('Fresh work')).toBeInTheDocument();
+ expect(screen.queryByText('First work')).toBeNull();
+ expect(listWritersRoomWorks).toHaveBeenLastCalledWith({ limit: 50, cursor: null }, expect.anything());
+});
diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.js
index 60526e726f..8491090cb3 100644
--- a/client/src/services/apiWritersRoom.js
+++ b/client/src/services/apiWritersRoom.js
@@ -15,7 +15,11 @@ export const deleteWritersRoomFolder = (id, options = {}) => request(`/writers-r
});
// Works
-export const listWritersRoomWorks = () => request('/writers-room/works');
+export const listWritersRoomWorks = (query, options = {}) => {
+ const params = new URLSearchParams();
+ for (const [key, value] of Object.entries(query || {})) if (value != null) params.set(key, value);
+ return request(`/writers-room/works${params.size ? `?${params}` : ''}`, options);
+};
export const createWritersRoomWork = (data, options = {}) => request('/writers-room/works', {
method: 'POST',
body: JSON.stringify(data),
diff --git a/docs/features/writers-room.md b/docs/features/writers-room.md
index 8e941b2d97..1471e8ebdb 100644
--- a/docs/features/writers-room.md
+++ b/docs/features/writers-room.md
@@ -124,3 +124,21 @@ Most services carry sibling `.test.js` suites (storage CRUD, draft save/version/
- Creative Director (`server/services/creativeDirector/`, `/creative-director`) — treatment/scene/run orchestration the CD bridge feeds into
- Comic pipeline — the promote-to-pipeline target
- Media collections, image-gen, and the media job queue — shared render infrastructure
+
+
+### Library paging
+
+The library requests 50 works initially and appends more with **Load more works**.
+Folder counts describe loaded works while more pages remain. Opening a work by
+URL still loads it directly, even if its library row has not loaded.
+
+`GET /api/writers-room/works?limit=50` returns `{ items, total, limit, offset, nextCursor }`.
+Limits are validated from 1 to 100. Echo the opaque `nextCursor` as `cursor` to
+continue; a query-less request keeps the legacy array response, and legacy
+`offset` requests keep their envelope. Each new paging request snapshots live
+work IDs in `updated_at DESC, id ASC` order for five minutes. Only page members
+are hydrated with drafts; capturing membership reads IDs, not manifests. Edits
+cannot move an ID between pages, new works appear on a fresh snapshot, and
+subsequent deletions are omitted (total remains the original membership count).
+Up to 32 snapshots are retained per process. Expiry, eviction, or server restart
+returns HTTP 409 `CURSOR_EXPIRED`; retrying in the library restarts at page one.
diff --git a/server/lib/apiOperationContracts.js b/server/lib/apiOperationContracts.js
index 13137f2b6e..e7fcf8e86b 100644
--- a/server/lib/apiOperationContracts.js
+++ b/server/lib/apiOperationContracts.js
@@ -5,6 +5,7 @@ import {
voiceSynthesizeBodySchema,
zodToOpenApiSchema,
} from './apiContractSchemas.js';
+import { writersRoomWorksQuerySchema, writersRoomWorksResponseSchema } from './pipelineValidation.js';
import { TTS_ENGINE_IDS } from './voiceEngines.js';
import { cosToolCallSchema } from './cosToolContracts.js';
import { agentContextMcpInboundSchema } from './agentContextValidation.js';
@@ -33,6 +34,21 @@ export const API_OPERATION_CONTRACTS = Object.freeze({
'/api/api-docs/tools.min.json': {
get: { summary: 'Read minimized semantic tool resource', responses: { 200: { description: 'Schema-optimized provider-neutral tool resource' } } },
},
+ '/api/writers-room/works': {
+ get: {
+ summary: 'List Writers Room works',
+ description: 'No query returns the legacy array. Paging captures ordered membership for five minutes; echo nextCursor to continue. Deleted works are omitted; total describes original membership. Restart on CURSOR_EXPIRED.',
+ parameters: Object.entries(writersRoomWorksQuerySchema.shape).map(([name, schema]) => ({
+ name, in: 'query', required: false, schema: zodToOpenApiSchema(schema),
+ })),
+ responses: {
+ 200: { description: 'Legacy array or bounded snapshot page',
+ content: { 'application/json': { schema: zodToOpenApiSchema(writersRoomWorksResponseSchema) } } },
+ 400: { description: 'Invalid paging query or cursor' },
+ 409: { description: 'Restart pagination', 'x-portos-error-codes': ['CURSOR_EXPIRED'] },
+ },
+ },
+ },
'/api/review/queue': {
get: {
summary: 'Read the cross-domain review action queue',
diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.js
index 09fb6c6c5e..7cc2d7eeb8 100644
--- a/server/lib/pipelineValidation.js
+++ b/server/lib/pipelineValidation.js
@@ -762,3 +762,25 @@ export const issuesListQuerySchema = z.object({
offset: z.preprocess((v) => (v === undefined ? 0 : Number(v)), z.number().int().min(0)).default(0),
limit: z.preprocess((v) => (v === undefined ? 1000 : Number(v)), z.number().int().min(1).max(1000)).default(1000),
});
+
+
+// Query-less callers retain the legacy array; limit/offset opt into a snapshot.
+export const writersRoomWorksQuerySchema = z.object({
+ limit: z.coerce.number().int().min(1).max(100).default(50),
+ offset: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
+ cursor: z.string().regex(/^[0-9a-f-]{36}\.[0-9]+$/).max(80).optional(),
+});
+export const writersRoomWorkSummarySchema = z.object({
+ id: z.string(), folderId: z.string().nullable().optional(), title: z.string(),
+ kind: z.string(), status: z.string(), activeDraftVersionId: z.string().nullable().optional(),
+ wordCount: z.number(), draftCount: z.number(),
+ pipelineSeriesId: z.string().nullable(), pipelineIssueId: z.string().nullable(),
+ createdAt: z.string(), updatedAt: z.string(),
+});
+export const writersRoomWorksResponseSchema = z.union([
+ z.array(writersRoomWorkSummarySchema),
+ z.object({
+ items: z.array(writersRoomWorkSummarySchema), total: z.number().int(),
+ limit: z.number().int(), offset: z.number().int(), nextCursor: z.string().nullable(),
+ }),
+]);
diff --git a/server/routes/apiDocs.test.js b/server/routes/apiDocs.test.js
index 0eb998bb9c..f851c81826 100644
--- a/server/routes/apiDocs.test.js
+++ b/server/routes/apiDocs.test.js
@@ -45,6 +45,11 @@ describe('GET /api/api-docs/openapi.json', () => {
const res = await request(buildApp()).get('/api/api-docs/internal/openapi.json');
expect(res.status).toBe(200);
expect(res.body.paths['/api/cos/mind/tools'].get).toBeDefined();
+ const works = res.body.paths['/api/writers-room/works'].get;
+ expect(works.parameters.find(param => param.name === 'limit').schema.maximum).toBe(100);
+ expect(works.parameters.some(param => param.name === 'cursor')).toBe(true);
+ expect(works.responses[200].content['application/json'].schema.anyOf).toHaveLength(2);
+ expect(works.responses[409]['x-portos-error-codes']).toContain('CURSOR_EXPIRED');
expect(Object.keys(res.body.paths).length).toBeGreaterThan(1000);
});
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index e7f74621f9..866cc9d1f0 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -28,12 +28,11 @@ import {
writersRoomPlaceUpdateSchema,
writersRoomObjectCreateSchema,
writersRoomObjectUpdateSchema,
- isPaginationRequested,
- paginateArray,
+ writersRoomWorksQuerySchema,
} from '../lib/validation.js';
import {
listFolders, createFolder, deleteFolder,
- listWorks, getWorkWithBody, createWork, updateWork, deleteWork,
+ listWorks, listWorksPage, getWorkWithBody, createWork, updateWork, deleteWork,
saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,
listExercises, createExercise, finishExercise, discardExercise, promoteExercise,
} from '../services/writersRoom/local.js';
@@ -85,15 +84,12 @@ router.delete('/folders/:id', asyncHandler(async (req, res) => {
// ---------- works ----------
-// Backward-compatible by default: returns the full works array. When a client
-// passes `limit`/`offset`, the response becomes the bounded
-// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.
+// No paging query preserves the legacy response for older callers.
router.get('/works', asyncHandler(async (req, res) => {
- const works = await listWorks();
- if (!isPaginationRequested(req.query)) {
- return res.json(works);
+ if (req.query.limit === undefined && req.query.offset === undefined && req.query.cursor === undefined) {
+ return res.json(await listWorks());
}
- res.json(paginateArray(works, req.query, { defaultLimit: 50, maxLimit: 500 }));
+ res.json(await listWorksPage(validateRequest(writersRoomWorksQuerySchema, req.query)));
}));
router.post('/works', asyncHandler(async (req, res) => {
diff --git a/server/routes/writersRoom.test.js b/server/routes/writersRoom.test.js
index 6ab08e5d50..4f8b28db64 100644
--- a/server/routes/writersRoom.test.js
+++ b/server/routes/writersRoom.test.js
@@ -7,6 +7,7 @@ vi.mock('../services/writersRoom/local.js', () => ({
listFolders: vi.fn(async () => [{ id: 'wr-folder-1', name: 'Drafts' }]),
createFolder: vi.fn(async (data) => ({ id: 'wr-folder-new', ...data })),
deleteFolder: vi.fn(async () => ({ ok: true })),
+ listWorksPage: vi.fn(),
listWorks: vi.fn(async () => [{ id: 'wr-work-1', title: 'A' }]),
createWork: vi.fn(async (data) => ({ id: 'wr-work-new', title: data.title, kind: data.kind || 'short-story' })),
getWorkWithBody: vi.fn(),
@@ -149,9 +150,7 @@ describe('writersRoom routes', () => {
});
it('GET /works returns a bounded envelope when pagination is requested', async () => {
- svc.listWorks.mockResolvedValueOnce(
- Array.from({ length: 5 }, (_, i) => ({ id: `wr-work-${i}`, title: `W${i}` }))
- );
+ svc.listWorksPage.mockResolvedValueOnce({ items: [{ id: 'wr-work-1' }, { id: 'wr-work-2' }], total: 5, limit: 2, offset: 1, nextCursor: 'cursor' });
const r = await request(app).get('/api/writers-room/works?limit=2&offset=1');
expect(r.status).toBe(200);
expect(r.body.items).toHaveLength(2);
@@ -161,6 +160,15 @@ describe('writersRoom routes', () => {
expect(r.body.offset).toBe(1);
});
+ it('rejects oversized pages and forwards validated cursor queries', async () => {
+ expect((await request(app).get('/api/writers-room/works?limit=101')).status).toBe(400);
+ expect((await request(app).get('/api/writers-room/works?cursor=bad')).status).toBe(400);
+ svc.listWorksPage.mockResolvedValueOnce({ items: [], total: 0, nextCursor: null });
+ const cursor = '00000000-0000-4000-8000-000000000000.50';
+ expect((await request(app).get(`/api/writers-room/works?cursor=${cursor}`)).status).toBe(200);
+ expect(svc.listWorksPage).toHaveBeenLastCalledWith({ limit: 50, offset: 0, cursor });
+ });
+
it('POST /works rejects unknown kind', async () => {
const r = await request(app).post('/api/writers-room/works').send({ title: 'X', kind: 'manifesto' });
expect(r.status).toBe(400);
diff --git a/server/services/writersRoom/db.js b/server/services/writersRoom/db.js
index f4a31225ae..12d417a416 100644
--- a/server/services/writersRoom/db.js
+++ b/server/services/writersRoom/db.js
@@ -310,23 +310,46 @@ export async function listWorkIds({ includeDeleted = false } = {}) {
return rows.map((r) => r.id);
}
+/** Snapshot membership only: no work bodies or draft history are hydrated. */
+export async function listOrderedWorkIds() {
+ const { rows } = await query(
+ `SELECT id FROM writers_room_works WHERE deleted = FALSE ORDER BY updated_at DESC, id ASC`,
+ );
+ return rows.map(row => row.id);
+}
+
+/** Hydrate only the already bounded page, preserving snapshot order. */
+export async function readWorksPage(ids) {
+ if (!ids.length) return [];
+ const works = await query(
+ `SELECT id, data FROM writers_room_works
+ WHERE deleted = FALSE AND id = ANY($1::text[])
+ ORDER BY array_position($1::text[], id) LIMIT $2`, [ids, ids.length],
+ );
+ return hydrateWorks(works.rows);
+}
+
/** Every live work's manifest, rebuilt with its drafts[] — one pair of queries. */
export async function listWorks() {
const works = await query(
`SELECT id, data FROM writers_room_works WHERE deleted = FALSE`,
);
- if (works.rows.length === 0) return [];
+ return hydrateWorks(works.rows);
+}
+
+async function hydrateWorks(works) {
+ if (works.length === 0) return [];
const drafts = await query(
`SELECT work_id, data FROM writers_room_draft_versions
WHERE work_id = ANY($1::text[]) ORDER BY created_at, id`,
- [works.rows.map((r) => r.id)],
+ [works.map((r) => r.id)],
);
const draftsByWork = new Map();
for (const d of drafts.rows) {
if (!draftsByWork.has(d.work_id)) draftsByWork.set(d.work_id, []);
draftsByWork.get(d.work_id).push({ data: d.data });
}
- return works.rows.map((w) => rowsToManifest(w, draftsByWork.get(w.id) || []));
+ return works.map((w) => rowsToManifest(w, draftsByWork.get(w.id) || []));
}
/**
diff --git a/server/services/writersRoom/db.test.js b/server/services/writersRoom/db.test.js
index 7ec4a87f94..f594ea3dcf 100644
--- a/server/services/writersRoom/db.test.js
+++ b/server/services/writersRoom/db.test.js
@@ -152,6 +152,8 @@ describe.skipIf(!runDb)('Writers Room DB adapter round-trip', () => {
// Live reads filter the tombstone out…
expect(await db.readWork('wr-work-2')).toBeNull();
expect(await db.listWorkIds()).toEqual(['wr-work-1']);
+ expect(await db.listOrderedWorkIds()).toEqual(['wr-work-1']);
+ expect(await db.readWorksPage(['wr-work-2', 'wr-work-1'])).toEqual(works);
// …but the row, its draft rows, and the tombstone trio survive until prune.
expect((await query(`SELECT deleted FROM writers_room_works WHERE id = 'wr-work-2'`)).rows[0].deleted).toBe(true);
expect((await query(`SELECT 1 FROM writers_room_draft_versions WHERE work_id = 'wr-work-2'`)).rows).toHaveLength(1);
diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.js
index 853a3781ac..8e005f9d05 100644
--- a/server/services/writersRoom/local.js
+++ b/server/services/writersRoom/local.js
@@ -14,6 +14,8 @@
* the manifest shape are unchanged. See docs/features/writers-room.md.
*/
+import { ServerError } from '../../lib/errorHandler.js';
+import { writersRoomWorksQuerySchema } from '../../lib/pipelineValidation.js';
import { randomUUID, createHash } from 'crypto';
import { readFile } from 'fs/promises';
import { atomicWrite, ensureDir, rmGuarded } from '../../lib/fileUtils.js';
@@ -275,6 +277,24 @@ export async function ensureWorkMediaCollection(workId) {
return collection;
}
+function summarizeWork(manifest) {
+ const activeDraft = (manifest.drafts || []).find((d) => d.id === manifest.activeDraftVersionId);
+ return {
+ id: manifest.id,
+ folderId: manifest.folderId,
+ title: manifest.title,
+ kind: manifest.kind,
+ status: manifest.status,
+ activeDraftVersionId: manifest.activeDraftVersionId,
+ wordCount: activeDraft?.wordCount ?? 0,
+ draftCount: (manifest.drafts || []).length,
+ pipelineSeriesId: manifest.pipelineSeriesId || null,
+ pipelineIssueId: manifest.pipelineIssueId || null,
+ createdAt: manifest.createdAt,
+ updatedAt: manifest.updatedAt,
+ };
+}
+
export async function listWorks() {
// The store returns full manifests (rebuilt with drafts[] on the PG backend),
// dropping any work with a corrupted manifest on the file backend so one bad
@@ -282,26 +302,44 @@ export async function listWorks() {
const manifests = await store().listWorks();
return manifests
.filter(Boolean)
- .map((manifest) => {
- const activeDraft = (manifest.drafts || []).find((d) => d.id === manifest.activeDraftVersionId);
- return {
- id: manifest.id,
- folderId: manifest.folderId,
- title: manifest.title,
- kind: manifest.kind,
- status: manifest.status,
- activeDraftVersionId: manifest.activeDraftVersionId,
- wordCount: activeDraft?.wordCount ?? 0,
- draftCount: (manifest.drafts || []).length,
- pipelineSeriesId: manifest.pipelineSeriesId || null,
- pipelineIssueId: manifest.pipelineIssueId || null,
- createdAt: manifest.createdAt,
- updatedAt: manifest.updatedAt,
- };
- })
+ .map(summarizeWork)
.sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));
}
+// Membership snapshots retain IDs only, never prose or draft histories. They are
+// process-local and expire after five minutes (including after a server restart).
+const workSnapshots = new Map();
+const SNAPSHOT_TTL = 5 * 60 * 1000;
+const MAX_SNAPSHOTS = 32;
+
+export async function listWorksPage(query = {}) {
+ const { limit, offset, cursor } = writersRoomWorksQuerySchema.parse(query);
+ const now = Date.now();
+ for (const [id, entry] of workSnapshots) if (entry.expires <= now) workSnapshots.delete(id);
+ let snapshot;
+ let position = offset;
+ if (cursor) {
+ const [id, index] = cursor.split('.');
+ snapshot = workSnapshots.get(id);
+ if (!snapshot) throw new ServerError('Library page expired. Restart the library to continue.', {
+ status: 409, code: 'CURSOR_EXPIRED',
+ });
+ position = Number(index);
+ if (!Number.isSafeInteger(position) || position > snapshot.ids.length) {
+ throw new ServerError('Invalid library cursor', { status: 400, code: 'INVALID_CURSOR' });
+ }
+ } else {
+ snapshot = { id: randomUUID(), ids: await store().listOrderedWorkIds(), expires: now + SNAPSHOT_TTL };
+ while (workSnapshots.size >= MAX_SNAPSHOTS) workSnapshots.delete(workSnapshots.keys().next().value);
+ workSnapshots.set(snapshot.id, snapshot);
+ }
+ const ids = snapshot.ids.slice(position, position + limit);
+ const items = (await store().readWorksPage(ids)).map(summarizeWork);
+ const next = position + ids.length;
+ return { items, total: snapshot.ids.length, limit, offset: position,
+ nextCursor: next < snapshot.ids.length ? `${snapshot.id}.${next}` : null };
+}
+
/**
* How many works listWorks() would return — without rebuilding a single
* manifest (#2729). A `COUNT(*)` on PG; the shared live-set read on the file
diff --git a/server/services/writersRoom/local.test.js b/server/services/writersRoom/local.test.js
index 4de9939d0a..827db2c891 100644
--- a/server/services/writersRoom/local.test.js
+++ b/server/services/writersRoom/local.test.js
@@ -651,3 +651,27 @@ describe('retrospective evolution-lens anchors (#6445)', () => {
expect(block).toContain('[unverified]');
});
});
+
+
+describe('library snapshot pages', () => {
+ it('holds membership across equal timestamps, edits, inserts and deletions; expires with restart guidance', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
+ const created = await Promise.all(['A', 'B', 'C', 'D'].map(title => createWork({ title, kind: 'short-story' })));
+ const ordered = created.map(work => work.id).sort();
+ const first = await local.listWorksPage({ limit: 2 });
+ expect(first.items.map(work => work.id)).toEqual(ordered.slice(0, 2));
+ vi.setSystemTime(new Date('2026-01-01T00:01:00Z'));
+ await updateWork(ordered[3], { title: 'Edited' });
+ await deleteWork(ordered[2]);
+ await createWork({ title: 'New arrival', kind: 'short-story' });
+ const second = await local.listWorksPage({ limit: 2, cursor: first.nextCursor });
+ expect(second.items.map(work => work.id)).toEqual([ordered[3]]);
+ expect(second.items[0].title).toBe('Edited');
+ expect(second.total).toBe(4);
+ expect(second.nextCursor).toBeNull();
+ vi.setSystemTime(new Date('2026-01-01T00:06:00Z'));
+ await expect(local.listWorksPage({ cursor: first.nextCursor })).rejects.toMatchObject({ code: 'CURSOR_EXPIRED' });
+ expect((await local.listWorksPage({ limit: 100 })).items).toHaveLength(4);
+ });
+});
diff --git a/server/services/writersRoom/paging.test.js b/server/services/writersRoom/paging.test.js
new file mode 100644
index 0000000000..9f4dfd4807
--- /dev/null
+++ b/server/services/writersRoom/paging.test.js
@@ -0,0 +1,19 @@
+import { describe, it, expect, vi } from 'vitest';
+vi.mock('../../lib/db.js', () => ({ query: vi.fn(), withTransaction: vi.fn() }));
+import { query } from '../../lib/db.js';
+import { listOrderedWorkIds, readWorksPage } from './db.js';
+
+describe('Postgres library paging', () => {
+ it('captures ordered IDs without hydrating data and restricts draft reads to the selected live page', async () => {
+ query.mockResolvedValueOnce({ rows: [{ id: 'a' }, { id: 'b' }, { id: 'c' }] });
+ expect(await listOrderedWorkIds()).toEqual(['a', 'b', 'c']);
+ expect(query.mock.calls[0][0]).toMatch(/SELECT id .*deleted = FALSE ORDER BY updated_at DESC, id ASC/);
+ query.mockResolvedValueOnce({ rows: [{ id: 'b', data: { id: 'b', title: 'Example' } }] });
+ query.mockResolvedValueOnce({ rows: [{ work_id: 'b', data: { id: 'draft-b' } }] });
+ expect(await readWorksPage(['b', 'c'])).toEqual([{ id: 'b', title: 'Example', drafts: [{ id: 'draft-b' }] }]);
+ expect(query.mock.calls[1][0]).toContain('LIMIT $2');
+ expect(query.mock.calls[1][1]).toEqual([['b', 'c'], 2]);
+ expect(query.mock.calls[2][1]).toEqual([['b']]);
+ expect(query).toHaveBeenCalledTimes(3);
+ });
+});
diff --git a/server/services/writersRoom/store.js b/server/services/writersRoom/store.js
index 59fd4a700c..fcf90d8898 100644
--- a/server/services/writersRoom/store.js
+++ b/server/services/writersRoom/store.js
@@ -232,6 +232,11 @@ function makeFileBackend() {
return ids.filter((_, i) => manifests[i] && manifests[i].deleted !== true);
},
listWorks: loadLiveManifests,
+ listOrderedWorkIds: async () => (await loadLiveManifests())
+ .sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || '') || a.id.localeCompare(b.id))
+ .map(work => work.id),
+ readWorksPage: async (ids) => (await Promise.all(ids.map(id => loadManifest(id).catch(() => null))))
+ .filter(work => work && !work.deleted),
// No cheap count on the file layout — `deleted` lives inside each manifest,
// so the live set can only be known by reading them. Counting the shared
// live-set reader makes agreement with listWorks structural rather than a
@@ -342,6 +347,8 @@ export function writersRoomStore() {
readWork: async (id, opts) => (await getBackend()).readWork(id, opts),
listWorkIds: async (opts) => (await getBackend()).listWorkIds(opts),
listWorks: async () => (await getBackend()).listWorks(),
+ listOrderedWorkIds: async () => (await getBackend()).listOrderedWorkIds(),
+ readWorksPage: async (ids) => (await getBackend()).readWorksPage(ids),
countWorks: async () => (await getBackend()).countWorks(),
writeWork: async (manifest) => (await getBackend()).writeWork(manifest),
deleteWork: async (id) => (await getBackend()).deleteWork(id),