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: add a durable Rapid Reader shelf so saved books survive a refresh (#5316)
[._.]/ Adam Eivye79305c8975f
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 500ddcaedb..fb48b7a3d8 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -483,6 +483,7 @@ export default function App() {<Route path="wiki" element={<RedirectWithSearch to="/wiki/overview" />} /><Route path="wiki/:tab" element={<Wiki />} /><Route path="rapid-reader" element={<RapidReaderPage />} />+ <Route path="rapid-reader/:id" element={<RapidReaderPage />} />{/* `/universes` is the universe index (list/table). The editor livesat `/universes/:universeId`; `new` is the create-mode sentinel(UniverseBuilder treats it as no-id → blank draft). Universe ids arediff --git a/client/src/pages/RapidReader.jsx b/client/src/pages/RapidReader.jsxindex c8ca4add60..542a48d829 100644--- a/client/src/pages/RapidReader.jsx+++ b/client/src/pages/RapidReader.jsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Bookmark, BookOpen, ClipboardPaste, Eraser, ExternalLink, Play, Zap } from 'lucide-react';+import { Bookmark, BookOpen, ClipboardPaste, Eraser, ExternalLink, Play, Save, Trash2, Zap } from 'lucide-react';import RapidReader from '../components/RapidReader';import PageHeader from '../components/PageHeader';import { readClipboard } from '../lib/clipboard';@@ -11,10 +11,16 @@ import {writeRapidReaderProgress,} from '../lib/rapidReaderPosition';import { useAsyncAction } from '../hooks/useAsyncAction';+import { useNavigate, useParams } from 'react-router';import {ACCELERANDO_LICENSE_URL,ACCELERANDO_SOURCE_PAGE_URL,+ createRapidReaderLibraryEntry,+ deleteRapidReaderLibraryEntry,+ fetchRapidReaderLibraryEntry,getAccelerandoBook,+ getRapidReaderLibraryEntry,+ listRapidReaderLibrary,} from '../services/api';const SAMPLE = `Speed reading is a collection of techniques used to scan text quickly while still understanding what you've read. Most people read in chunks of three or four words at a time, which slows them down. Rapid serial visual presentation flashes one word at a time at a fixed location, removing the need to move your eyes. With practice, comprehension stays intact at three to five hundred words per minute, and many readers can push past six hundred for familiar material.`;@@ -28,6 +34,8 @@ const focalPalette = [];export default function RapidReaderPage() {+ const navigate = useNavigate();+ const { id: shelfId } = useParams();const [text, setText] = useState('');const [active, setActive] = useState(null);const [wpm, setWpm] = useState(350);@@ -36,6 +44,12 @@ export default function RapidReaderPage() {const [bookmark, setBookmark] = useState(null);const [bookStatus, setBookStatus] = useState('idle');const [bookError, setBookError] = useState('');+ const [shelf, setShelf] = useState([]);+ const [shelfError, setShelfError] = useState('');+ const [shelfLoading, setShelfLoading] = useState(true);+ const [saveTitle, setSaveTitle] = useState('');+ const [url, setUrl] = useState('');+ const [pendingDelete, setPendingDelete] = useState(null);const textareaRef = useRef(null);const latestProgressRef = useRef(null);const lastAutoSavedWordRef = useRef(-1);@@ -51,6 +65,14 @@ export default function RapidReaderPage() {setBookmark(readRapidReaderProgress(documentText, documentIdentity));}, [documentText, documentIdentity]);+ const loadShelf = useCallback(async () => {+ setShelfLoading(true); setShelfError('');+ const entries = await listRapidReaderLibrary({ silent: true }).catch((error) => { setShelfError(error?.message || 'Could not load shelf'); return null; });+ if (entries) setShelf(entries);+ setShelfLoading(false);+ }, []);+ useEffect(() => { loadShelf(); }, [loadShelf]);+const [loadBook, loadingBook] = useAsyncAction(async () => {setBookStatus('loading');setBookError('');@@ -66,10 +88,33 @@ export default function RapidReaderPage() {return null;}setText(book.text);+ if (book.id === 'accelerando' && book.shelfStored !== false) setShelf((previous) => previous.some((entry) => entry.id === book.id) ? previous : [{ ...book, text: undefined }, ...previous]);setBookStatus(book.cached ? 'cached' : book.cacheStored === false ? 'downloaded-uncached' : 'downloaded');return book;});+ // The URL owns which shelf entry is open, so the row click only navigates —+ // the effect below is the single place that loads the record's text.+ const openShelf = (id) => navigate(`/rapid-reader/${id}`);+ const loadShelfEntry = useCallback(async (id) => {+ const entry = await getRapidReaderLibraryEntry(id, { silent: true }).catch((error) => { setShelfError(error?.message || 'Could not open shelf entry'); return null; });+ if (entry?.text) { setText(entry.text); setActive({ text: entry.text, initialWordIndex: 0, documentId: rapidReaderDocumentId(entry.text), wordCount: entry.wordCount }); }+ }, []);+ useEffect(() => { if (shelfId) loadShelfEntry(shelfId); }, [shelfId, loadShelfEntry]);+ const addToShelf = (entry) => setShelf((previous) => [Object.fromEntries(Object.entries(entry).filter(([key]) => key !== 'text')), ...previous]);+ const [saveToShelf, savingShelf] = useAsyncAction(async () => {+ const entry = await createRapidReaderLibraryEntry({ title: saveTitle, text: documentText }, { silent: true }).catch((error) => { setShelfError(error?.message || 'Could not save to shelf'); return null; });+ if (entry) { addToShelf(entry); setSaveTitle(''); }+ });+ const [fetchToShelf, fetchingShelf] = useAsyncAction(async () => {+ const entry = await fetchRapidReaderLibraryEntry({ url }, { silent: true }).catch((error) => { setShelfError(error?.message || 'Could not fetch URL'); return null; });+ if (entry) { addToShelf(entry); setUrl(''); }+ });+ const deleteShelf = async (id) => {+ const deleted = await deleteRapidReaderLibraryEntry(id, { silent: true }).then(() => true, (error) => { setShelfError(error?.message || 'Could not delete shelf entry'); return false; });+ if (deleted) { setShelf((previous) => previous.filter((entry) => entry.id !== id)); setPendingDelete(null); }+ };+const startAt = (wordIndex, saved = null) => {if (!documentText) return;if (saved) {@@ -213,6 +258,12 @@ export default function RapidReaderPage() {)}</div>+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3" aria-label="Shelf">+ <div className="flex items-center justify-between gap-3"><div><h2 className="text-sm font-medium text-gray-200">Shelf</h2><p className="text-xs text-gray-400">Saved books stay on this machine and in its backups.</p></div><button type="button" onClick={loadShelf} className="text-xs text-port-accent hover:underline">Retry</button></div>+ {shelfError && <p role="alert" className="text-xs text-red-400">{shelfError}</p>}+ {shelfLoading ? <p className="text-xs text-gray-500">Loading shelf…</p> : shelf.length === 0 ? <p className="text-xs text-gray-500">No saved books yet.</p> : <ul className="divide-y divide-port-border">{shelf.map((entry) => <li key={entry.id} className="py-2 flex flex-wrap items-center justify-between gap-2"><button type="button" onClick={() => openShelf(entry.id)} aria-label={`Open ${entry.title}`} className="text-left min-h-10"><span className="block text-sm text-gray-200">{entry.title}</span><span className="block text-xs text-gray-500">{entry.author || entry.sourceUrl || entry.sourceType} · {entry.wordCount} words</span></button>{pendingDelete === entry.id ? <span className="flex gap-2 text-xs"><button type="button" onClick={() => deleteShelf(entry.id)} className="text-red-400">Delete</button><button type="button" onClick={() => setPendingDelete(null)} className="text-gray-400">Cancel</button></span> : <button type="button" onClick={() => setPendingDelete(entry.id)} aria-label={`Delete ${entry.title}`} className="min-h-10 px-2 text-gray-500 hover:text-red-400"><Trash2 size={15} /></button>}</li>)}</ul>}+ </section>+<div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3"><div className="flex items-center justify-between gap-2"><label htmlFor="rr-text" className="text-sm font-medium text-gray-300">@@ -260,6 +311,11 @@ export default function RapidReaderPage() {{wordCount} word{wordCount === 1 ? '' : 's'} · approx {estSec}s at {wpm} WPM</span></div>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 pt-1">+ <label className="text-xs text-gray-400"><span className="sr-only">Shelf title</span><input value={saveTitle} onChange={(event) => setSaveTitle(event.target.value)} placeholder="Title to save" className="w-full min-h-10 bg-port-bg border border-port-border rounded-md px-3" /></label>+ <button type="button" disabled={savingShelf || !documentText || !saveTitle.trim()} onClick={saveToShelf} className="inline-flex justify-center items-center gap-1 min-h-10 border border-port-accent/50 text-port-accent rounded-md disabled:opacity-40"><Save size={14} /> Save to shelf</button>+ <label className="sm:col-span-2 text-xs text-gray-400 flex flex-col sm:flex-row gap-2"><span className="sr-only">URL to add to shelf</span><input value={url} onChange={(event) => setUrl(event.target.value)} placeholder="https://example.com/article" className="flex-1 min-h-10 bg-port-bg border border-port-border rounded-md px-3" /><button type="button" disabled={fetchingShelf || !url.trim()} onClick={fetchToShelf} className="min-h-10 px-3 border border-port-accent/50 text-port-accent rounded-md disabled:opacity-40">Fetch URL to shelf</button></label>+ </div></div><div className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">diff --git a/client/src/pages/RapidReader.test.jsx b/client/src/pages/RapidReader.test.jsxindex 5f88be52b9..38456b809a 100644--- a/client/src/pages/RapidReader.test.jsx+++ b/client/src/pages/RapidReader.test.jsx@@ -1,10 +1,16 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter, Route, Routes } from 'react-router';const api = vi.hoisted(() => ({ACCELERANDO_LICENSE_URL: 'https://creativecommons.org/licenses/by-nc-nd/2.5/',ACCELERANDO_SOURCE_PAGE_URL: 'http://www.antipope.org/charlie/blog-static/fiction/accelerando/accelerando-intro.html',getAccelerandoBook: vi.fn(),+ listRapidReaderLibrary: vi.fn(),+ getRapidReaderLibraryEntry: vi.fn(),+ createRapidReaderLibraryEntry: vi.fn(),+ fetchRapidReaderLibraryEntry: vi.fn(),+ deleteRapidReaderLibraryEntry: vi.fn(),}));vi.mock('../services/api', () => api);@@ -12,6 +18,15 @@ vi.mock('../services/api', () => api);const RapidReaderPage = (await import('./RapidReader')).default;const { writeRapidReaderProgress } = await import('../lib/rapidReaderPosition');+const renderPage = (path = '/rapid-reader') => render(+ <MemoryRouter initialEntries={[path]}>+ <Routes>+ <Route path="/rapid-reader" element={<RapidReaderPage />} />+ <Route path="/rapid-reader/:id" element={<RapidReaderPage />} />+ </Routes>+ </MemoryRouter>,+);+const BOOK = {id: 'accelerando',title: 'Accelerando',@@ -23,13 +38,14 @@ const BOOK = {beforeEach(() => {vi.clearAllMocks();+ api.listRapidReaderLibrary.mockResolvedValue([]);localStorage.clear();});describe('RapidReader Accelerando loader', () => {it('waits for the explicit load action and puts the book into the reader text area', async () => {api.getAccelerandoBook.mockResolvedValue(BOOK);- render(<RapidReaderPage />);+ renderPage();expect(api.getAccelerandoBook).not.toHaveBeenCalled();expect(screen.getByRole('link', { name: /author's page/i })).toHaveAttribute(@@ -50,7 +66,7 @@ describe('RapidReader Accelerando loader', () => {it('shows a retryable inline error without a duplicate toast', async () => {api.getAccelerandoBook.mockRejectedValue(new Error('Author source unavailable'));- render(<RapidReaderPage />);+ renderPage();fireEvent.click(screen.getByRole('button', { name: 'Load Accelerando' }));@@ -60,7 +76,7 @@ describe('RapidReader Accelerando loader', () => {it('rejects an invalid successful response with a retryable inline error', async () => {api.getAccelerandoBook.mockResolvedValue({ cached: false });- render(<RapidReaderPage />);+ renderPage();fireEvent.click(screen.getByRole('button', { name: 'Load Accelerando' }));@@ -70,8 +86,9 @@ describe('RapidReader Accelerando loader', () => {});describe('RapidReader reading position', () => {- it('starts from the word under the textarea cursor', () => {- render(<RapidReaderPage />);+ it('starts from the word under the textarea cursor', async () => {+ renderPage();+ await waitFor(() => expect(api.listRapidReaderLibrary).toHaveBeenCalled());const textarea = screen.getByRole('textbox', { name: 'Text to read' });fireEvent.change(textarea, { target: { value: 'alpha bravo charlie delta' } });textarea.setSelectionRange(13, 13);@@ -81,10 +98,11 @@ describe('RapidReader reading position', () => {expect(screen.getByText(/3\/4 words/)).toBeInTheDocument();});- it('offers and restores saved progress for the same text', () => {+ it('offers and restores saved progress for the same text', async () => {const text = 'alpha bravo charlie delta echo';writeRapidReaderProgress(text, { wordIndex: 2, wpm: 425, chunkSize: 1 });- render(<RapidReaderPage />);+ renderPage();+ await waitFor(() => expect(api.listRapidReaderLibrary).toHaveBeenCalled());fireEvent.change(screen.getByRole('textbox', { name: 'Text to read' }), { target: { value: text } });fireEvent.click(screen.getByRole('button', { name: 'Resume at word 3' }));@@ -93,8 +111,9 @@ describe('RapidReader reading position', () => {expect(screen.getByLabelText('Reading speed')).toHaveValue('425');});- it('saves a bookmark from the reader and offers it after closing', () => {- render(<RapidReaderPage />);+ it('saves a bookmark from the reader and offers it after closing', async () => {+ renderPage();+ await waitFor(() => expect(api.listRapidReaderLibrary).toHaveBeenCalled());fireEvent.change(screen.getByRole('textbox', { name: 'Text to read' }), {target: { value: 'alpha bravo charlie delta echo' },});@@ -106,3 +125,94 @@ describe('RapidReader reading position', () => {expect(screen.getByRole('button', { name: 'Resume at word 2' })).toBeInTheDocument();});});++describe('RapidReader shelf', () => {+ const ENTRY = {+ id: 'shelf-1', title: 'Saved Article', author: null, sourceUrl: 'https://example.com/article',+ sourceType: 'fetch', wordCount: 4, addedAt: '2026-08-01T00:00:00.000Z', updatedAt: '2026-08-01T00:00:00.000Z',+ };++ it('lists shelf metadata on mount without requesting any book text', async () => {+ api.listRapidReaderLibrary.mockResolvedValue([ENTRY]);+ renderPage();++ expect(await screen.findByRole('button', { name: 'Open Saved Article' })).toBeInTheDocument();+ expect(api.getRapidReaderLibraryEntry).not.toHaveBeenCalled();+ expect(api.getAccelerandoBook).not.toHaveBeenCalled();+ });++ it('loads the entry named by the URL exactly once', async () => {+ api.listRapidReaderLibrary.mockResolvedValue([ENTRY]);+ api.getRapidReaderLibraryEntry.mockResolvedValue({ ...ENTRY, text: 'alpha bravo charlie delta' });+ renderPage('/rapid-reader/shelf-1');++ await waitFor(() => expect(api.getRapidReaderLibraryEntry).toHaveBeenCalledTimes(1));+ expect(await screen.findByText(/1\/4 words/)).toBeInTheDocument();+ expect(api.getRapidReaderLibraryEntry).toHaveBeenCalledWith('shelf-1', { silent: true });+ });++ it('puts the opened entry in the URL rather than local state', async () => {+ api.listRapidReaderLibrary.mockResolvedValue([ENTRY]);+ api.getRapidReaderLibraryEntry.mockResolvedValue({ ...ENTRY, text: 'alpha bravo charlie delta' });+ renderPage();++ fireEvent.click(await screen.findByRole('button', { name: 'Open Saved Article' }));++ await waitFor(() => expect(api.getRapidReaderLibraryEntry).toHaveBeenCalledWith('shelf-1', { silent: true }));+ expect(api.getRapidReaderLibraryEntry).toHaveBeenCalledTimes(1);+ });++ it('saves the current text and prepends the new entry without refetching the list', async () => {+ api.createRapidReaderLibraryEntry.mockResolvedValue({ ...ENTRY, id: 'shelf-2', title: 'My Notes', sourceType: 'paste', text: 'alpha bravo' });+ renderPage();+ await waitFor(() => expect(api.listRapidReaderLibrary).toHaveBeenCalledTimes(1));++ fireEvent.change(screen.getByRole('textbox', { name: 'Text to read' }), { target: { value: 'alpha bravo' } });+ fireEvent.change(screen.getByPlaceholderText('Title to save'), { target: { value: 'My Notes' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save to shelf' }));++ expect(await screen.findByRole('button', { name: 'Open My Notes' })).toBeInTheDocument();+ expect(api.createRapidReaderLibraryEntry).toHaveBeenCalledWith({ title: 'My Notes', text: 'alpha bravo' }, { silent: true });+ expect(api.listRapidReaderLibrary).toHaveBeenCalledTimes(1);+ expect(screen.getByPlaceholderText('Title to save')).toHaveValue('');+ });++ it('adds a URL-fetched entry to the shelf', async () => {+ api.fetchRapidReaderLibraryEntry.mockResolvedValue({ ...ENTRY, id: 'shelf-3', title: 'Fetched Page', text: 'alpha bravo' });+ renderPage();+ await waitFor(() => expect(api.listRapidReaderLibrary).toHaveBeenCalled());++ fireEvent.change(screen.getByPlaceholderText('https://example.com/article'), { target: { value: 'https://example.com/article' } });+ fireEvent.click(screen.getByRole('button', { name: 'Fetch URL to shelf' }));++ expect(await screen.findByRole('button', { name: 'Open Fetched Page' })).toBeInTheDocument();+ expect(api.fetchRapidReaderLibraryEntry).toHaveBeenCalledWith({ url: 'https://example.com/article' }, { silent: true });+ expect(screen.getByPlaceholderText('https://example.com/article')).toHaveValue('');+ });++ it('requires a second click to delete a shelf entry', async () => {+ api.listRapidReaderLibrary.mockResolvedValue([ENTRY]);+ api.deleteRapidReaderLibraryEntry.mockResolvedValue(undefined);+ renderPage();++ fireEvent.click(await screen.findByRole('button', { name: 'Delete Saved Article' }));+ expect(api.deleteRapidReaderLibraryEntry).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));++ await waitFor(() => expect(screen.queryByRole('button', { name: 'Open Saved Article' })).not.toBeInTheDocument());+ expect(api.deleteRapidReaderLibraryEntry).toHaveBeenCalledWith('shelf-1', { silent: true });+ });++ it('keeps pasting usable when the shelf list fails, and retries', async () => {+ api.listRapidReaderLibrary.mockRejectedValueOnce(new Error('Shelf unavailable')).mockResolvedValueOnce([ENTRY]);+ renderPage();++ expect(await screen.findByRole('alert')).toHaveTextContent('Shelf unavailable');+ expect(screen.getByRole('textbox', { name: 'Text to read' })).toBeEnabled();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));++ expect(await screen.findByRole('button', { name: 'Open Saved Article' })).toBeInTheDocument();+ });+});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex c4d0f6c440..d7ae256727 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -62,7 +62,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiScaffold.js` | App scaffolding templates. || `apiSchedules.js` | Automation schedules. || `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`), plus `rearmQuotaBurn` to put spent `run once` steps back into the rotation. |-| `apiRapidReader.js` | Rapid Reader's optional author-hosted Accelerando book loader. |+| `apiRapidReader.js` | Rapid Reader's optional author-hosted Accelerando loader and machine-local shelf API. || `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison). || `apiAuth.js` | Optional login password — status, login/logout, set/clear password. || `apiLoops.js` | Scheduled loops. |diff --git a/client/src/services/apiRapidReader.js b/client/src/services/apiRapidReader.jsindex e2ad23b672..78363273bd 100644--- a/client/src/services/apiRapidReader.js+++ b/client/src/services/apiRapidReader.js@@ -4,3 +4,8 @@ export const ACCELERANDO_SOURCE_PAGE_URL = 'http://www.antipope.org/charlie/blogexport const ACCELERANDO_LICENSE_URL = 'https://creativecommons.org/licenses/by-nc-nd/2.5/';export const getAccelerandoBook = (options) => request('/rapid-reader/accelerando', options);+export const listRapidReaderLibrary = (options) => request('/rapid-reader/library', options);+export const getRapidReaderLibraryEntry = (id, options) => request(`/rapid-reader/library/${encodeURIComponent(id)}`, options);+export const createRapidReaderLibraryEntry = (body, options) => request('/rapid-reader/library', { method: 'POST', body: JSON.stringify(body), ...options });+export const fetchRapidReaderLibraryEntry = (body, options) => request('/rapid-reader/library/fetch', { method: 'POST', body: JSON.stringify(body), ...options });+export const deleteRapidReaderLibraryEntry = (id, options) => request(`/rapid-reader/library/${encodeURIComponent(id)}`, { method: 'DELETE', ...options });diff --git a/client/src/services/apiRapidReader.test.js b/client/src/services/apiRapidReader.test.jsnew file mode 100644index 0000000000..b1a445b7e7--- /dev/null+++ b/client/src/services/apiRapidReader.test.js@@ -0,0 +1,49 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('./apiCore.js', () => ({+ request: vi.fn(),+}));++let request;+let api;++beforeEach(async () => {+ vi.resetModules();+ ({ request } = await import('./apiCore.js'));+ api = await import('./apiRapidReader.js');+ request.mockReset();+ request.mockResolvedValue({});+});++describe('apiRapidReader', () => {+ it('lists shelf metadata and passes request options through', async () => {+ await api.listRapidReaderLibrary({ silent: true });+ expect(request).toHaveBeenCalledWith('/rapid-reader/library', { silent: true });+ });++ it('encodes the id when loading or deleting one entry', async () => {+ await api.getRapidReaderLibraryEntry('shelf/1', { silent: true });+ expect(request).toHaveBeenCalledWith('/rapid-reader/library/shelf%2F1', { silent: true });++ await api.deleteRapidReaderLibraryEntry('shelf/1', { silent: true });+ expect(request).toHaveBeenCalledWith('/rapid-reader/library/shelf%2F1', { method: 'DELETE', silent: true });+ });++ it('posts a pasted entry to the collection', async () => {+ await api.createRapidReaderLibraryEntry({ title: 'Notes', text: 'alpha' }, { silent: true });+ expect(request).toHaveBeenCalledWith('/rapid-reader/library', {+ method: 'POST',+ body: JSON.stringify({ title: 'Notes', text: 'alpha' }),+ silent: true,+ });+ });++ it('posts a URL import to the dedicated fetch lane, not the id lane', async () => {+ await api.fetchRapidReaderLibraryEntry({ url: 'https://example.com/a' }, { silent: true });+ expect(request).toHaveBeenCalledWith('/rapid-reader/library/fetch', {+ method: 'POST',+ body: JSON.stringify({ url: 'https://example.com/a' }),+ silent: true,+ });+ });+});diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex e5690ca17b..44c4f3412e 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -105,6 +105,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- CoS event ledgers — ordinary diagnostics use `data/cos/run-events.jsonl` + `run-events.1.jsonl`; persistent-mind trajectory uses the separate `mind-events.jsonl` + `mind-events.1.jsonl` pair (`server/services/agentRunEventLog.js`, #4540, #5082). Both are append-only, machine-local `ephemeral-file` replay aids with no federation cursor, tombstone, or `PORTOS_SCHEMA_VERSIONS` entry. The durable ordinary run record remains `data/runs/{id}/metadata.json`; mind rollups remain in their own bounded cache. Ordinary generations rotate at 5000 events and additionally expire after 30 days. Mind generations rotate at 10000 events without an age cutoff so a stopped mind keeps its unsummarized window, while high-volume mind chatter cannot evict ordinary run diagnostics. Migration 301 moves existing `mind.*` lines out of the shared files and stamps predecessor sequence provenance used to distinguish a legitimate timestamp jump from lost retained events. Payloads are redacted at append time, and both bounded pairs are backed up with the rest of `data/cos/`.- Remote-API metadata cache — `data/cache/huggingface-repos.json` (`server/services/huggingFaceRepoCache.js`). Hugging Face per-repo records (file sizes, native context window) backing the local-LLM catalog's quant pickers. `ephemeral-file` rather than `db-primary` because it is a pure projection of someone else's API with no queries, no relationships, and no sync cursor — and because it is *machine-local by construction*: it exists to spare THIS install's cold-start requests, so federating it would be pure noise. Long TTL (7 days) since published GGUF file sizes are immutable, but bounded because a repo can gain a new quant. Non-overridable backup exclude — regenerable on demand, and stale by restore time anyway. Purgeable from Data Manager (`cache` category).- Rapid Reader's Accelerando source cache — `data/cache/accelerando.html` (`server/services/rapidReader.js`). The official author-hosted HTML edition is fetched only when the user asks to load it, then retained locally for repeat and offline reads. `ephemeral-file` rather than `db-primary`: it is a machine-local copy of a separately licensed remote work, has no PortOS records or queries, and can be re-downloaded or purged without data loss. It is not bundled, federated, or backed up; Data Manager purges it with the `cache` category.+- Rapid Reader shelf — `data/rapid-reader-library/{id}/index.json` (collectionStore). Durable user-curated prose is `file-primary`: it is machine-local, never federated, and included in normal filesystem backups. It has no relationship graph or full-text search requirement that justifies Postgres.---diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex e16291820a..2d283e6604 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -18476,7 +18476,62 @@"sources": [{"source": "server/routes/rapidReader.js",- "line": 7+ "line": 9+ }+ ]+ },+ {+ "method": "GET",+ "path": "/api/rapid-reader/library",+ "mountPath": "/api/rapid-reader",+ "sources": [+ {+ "source": "server/routes/rapidReader.js",+ "line": 14+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/rapid-reader/library",+ "mountPath": "/api/rapid-reader",+ "sources": [+ {+ "source": "server/routes/rapidReader.js",+ "line": 15+ }+ ]+ },+ {+ "method": "DELETE",+ "path": "/api/rapid-reader/library/:id",+ "mountPath": "/api/rapid-reader",+ "sources": [+ {+ "source": "server/routes/rapidReader.js",+ "line": 18+ }+ ]+ },+ {+ "method": "GET",+ "path": "/api/rapid-reader/library/:id",+ "mountPath": "/api/rapid-reader",+ "sources": [+ {+ "source": "server/routes/rapidReader.js",+ "line": 17+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/rapid-reader/library/fetch",+ "mountPath": "/api/rapid-reader",+ "sources": [+ {+ "source": "server/routes/rapidReader.js",+ "line": 16}]},@@ -23070,8 +23125,8 @@],"stats": {"mounts": 145,- "operations": 2081,- "declarations": 2084,+ "operations": 2086,+ "declarations": 2089,"sourceFiles": 225}}diff --git a/server/lib/paths.js b/server/lib/paths.jsindex 198216f698..236621b81f 100644--- a/server/lib/paths.js+++ b/server/lib/paths.js@@ -97,6 +97,7 @@ export const PATHS = {// lora-datasets/<id>/index.json + lora-datasets/<id>/images/*.png).// Machine-local like `loras/` — datasets never federate.loraDatasets: join(INSTALL_ROOT, 'data/lora-datasets'),+ rapidReaderLibrary: join(INSTALL_ROOT, 'data/rapid-reader-library'),// LoRA training run artifacts (checkpoints/samples/cache per run). Run// RECORDS live in Postgres (lora_training_runs); only artifacts live here.trainingRuns: join(INSTALL_ROOT, 'data/training-runs'),diff --git a/server/lib/validation.js b/server/lib/validation.jsindex e0aa0ab82b..2ec5665d26 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1285,6 +1285,10 @@ export function validateRequest(schema, data) {});}+export const rapidReaderLibraryParamsSchema = z.object({ id: z.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/) });+export const rapidReaderLibraryCreateSchema = z.object({ title: z.string().trim().min(1).max(200), author: z.string().trim().max(200).optional(), text: z.string().trim().min(1).max(2 * 1024 * 1024) });+export const rapidReaderLibraryFetchSchema = z.object({ url: z.string().trim().url().max(2000).refine((value) => /^https?:\/\//i.test(value), 'url must be http(s)'), title: z.string().trim().min(1).max(200).optional() });+// =============================================================================// SHELL// =============================================================================diff --git a/server/routes/rapidReader.js b/server/routes/rapidReader.jsindex 2f2632a3df..c54a7dfbaa 100644--- a/server/routes/rapidReader.js+++ b/server/routes/rapidReader.js@@ -1,6 +1,8 @@import { Router } from 'express';import { asyncHandler } from '../lib/errorHandler.js';import { getAccelerandoBook } from '../services/rapidReader.js';+import { validateRequest, rapidReaderLibraryParamsSchema, rapidReaderLibraryCreateSchema, rapidReaderLibraryFetchSchema } from '../lib/validation.js';+import { listRapidReaderLibrary, getRapidReaderLibraryEntry, createPastedRapidReaderEntry, fetchRapidReaderEntry, deleteRapidReaderLibraryEntry } from '../services/rapidReaderLibrary.js';const router = Router();@@ -9,5 +11,10 @@ router.get('/accelerando', asyncHandler(async (_req, res) => {res.set('Cache-Control', 'private, no-store');res.json(book);}));+router.get('/library', asyncHandler(async (_req, res) => res.json(await listRapidReaderLibrary())));+router.post('/library', asyncHandler(async (req, res) => res.status(201).json(await createPastedRapidReaderEntry(validateRequest(rapidReaderLibraryCreateSchema, req.body)))));+router.post('/library/fetch', asyncHandler(async (req, res) => res.status(201).json(await fetchRapidReaderEntry(validateRequest(rapidReaderLibraryFetchSchema, req.body)))));+router.get('/library/:id', asyncHandler(async (req, res) => res.json(await getRapidReaderLibraryEntry(validateRequest(rapidReaderLibraryParamsSchema, req.params).id))));+router.delete('/library/:id', asyncHandler(async (req, res) => { await deleteRapidReaderLibraryEntry(validateRequest(rapidReaderLibraryParamsSchema, req.params).id); res.status(204).end(); }));export default router;diff --git a/server/routes/rapidReader.test.js b/server/routes/rapidReader.test.jsindex 41e60adc7f..e845180ac6 100644--- a/server/routes/rapidReader.test.js+++ b/server/routes/rapidReader.test.js@@ -7,8 +7,17 @@ vi.mock('../services/rapidReader.js', () => ({getAccelerandoBook: vi.fn(),}));+vi.mock('../services/rapidReaderLibrary.js', () => ({+ listRapidReaderLibrary: vi.fn(),+ getRapidReaderLibraryEntry: vi.fn(),+ createPastedRapidReaderEntry: vi.fn(),+ fetchRapidReaderEntry: vi.fn(),+ deleteRapidReaderLibraryEntry: vi.fn(),+}));+const routes = (await import('./rapidReader.js')).default;const service = await import('../services/rapidReader.js');+const library = await import('../services/rapidReaderLibrary.js');const BOOK = {id: 'accelerando',@@ -20,6 +29,7 @@ const BOOK = {function makeApp() {const app = express();+ app.use(express.json());app.use('/api/rapid-reader', routes);app.use(errorMiddleware);return app;@@ -38,3 +48,73 @@ describe('GET /api/rapid-reader/accelerando', () => {expect(response.body).toEqual(BOOK);});});++const SHELF_META = {+ id: 'shelf-1', title: 'Saved Article', author: null, sourceUrl: 'https://example.com/a',+ sourceType: 'fetch', wordCount: 2, addedAt: '2026-08-01T00:00:00.000Z', updatedAt: '2026-08-01T00:00:00.000Z',+};++describe('rapid reader shelf routes', () => {+ it('lists shelf metadata', async () => {+ library.listRapidReaderLibrary.mockResolvedValue([SHELF_META]);++ const response = await request(makeApp()).get('/api/rapid-reader/library');++ expect(response.status).toBe(200);+ expect(response.body).toEqual([SHELF_META]);+ });++ it('returns one entry with its text, and 404s an unknown id', async () => {+ library.getRapidReaderLibraryEntry.mockResolvedValueOnce({ ...SHELF_META, text: 'alpha bravo' });+ const found = await request(makeApp()).get('/api/rapid-reader/library/shelf-1');+ expect(found.status).toBe(200);+ expect(found.body.text).toBe('alpha bravo');+ expect(library.getRapidReaderLibraryEntry).toHaveBeenCalledWith('shelf-1');++ library.getRapidReaderLibraryEntry.mockRejectedValueOnce(Object.assign(new Error('Shelf entry not found'), { status: 404, code: 'NOT_FOUND' }));+ const missing = await request(makeApp()).get('/api/rapid-reader/library/nope');+ expect(missing.status).toBe(404);+ });++ it('creates a pasted entry and rejects an invalid body without calling the service', async () => {+ library.createPastedRapidReaderEntry.mockResolvedValue({ ...SHELF_META, id: 'shelf-2', sourceType: 'paste', text: 'alpha bravo' });++ const created = await request(makeApp()).post('/api/rapid-reader/library').send({ title: 'Notes', text: 'alpha bravo' });+ expect(created.status).toBe(201);+ expect(library.createPastedRapidReaderEntry).toHaveBeenCalledWith({ title: 'Notes', text: 'alpha bravo' });++ const invalid = await request(makeApp()).post('/api/rapid-reader/library').send({ title: '', text: '' });+ expect(invalid.status).toBe(400);+ expect(library.createPastedRapidReaderEntry).toHaveBeenCalledTimes(1);+ });++ it('routes /library/fetch to the importer rather than treating "fetch" as an id', async () => {+ library.fetchRapidReaderEntry.mockResolvedValue({ ...SHELF_META, text: 'alpha bravo' });++ const response = await request(makeApp()).post('/api/rapid-reader/library/fetch').send({ url: 'https://example.com/a' });++ expect(response.status).toBe(201);+ expect(library.fetchRapidReaderEntry).toHaveBeenCalledWith({ url: 'https://example.com/a' });+ expect(library.getRapidReaderLibraryEntry).not.toHaveBeenCalled();+ });++ it('rejects a non-http URL before fetching, and surfaces an unsafe target', async () => {+ const rejected = await request(makeApp()).post('/api/rapid-reader/library/fetch').send({ url: 'file:///etc/passwd' });+ expect(rejected.status).toBe(400);+ expect(library.fetchRapidReaderEntry).not.toHaveBeenCalled();++ library.fetchRapidReaderEntry.mockRejectedValueOnce(Object.assign(new Error('Refused to fetch a private address'), { status: 400, code: 'UNSAFE_URL' }));+ const unsafe = await request(makeApp()).post('/api/rapid-reader/library/fetch').send({ url: 'http://192.0.2.10/a' });+ expect(unsafe.status).toBe(400);+ expect(unsafe.body.code).toBe('UNSAFE_URL');+ });++ it('deletes one entry with no content', async () => {+ library.deleteRapidReaderLibraryEntry.mockResolvedValue(undefined);++ const response = await request(makeApp()).delete('/api/rapid-reader/library/shelf-1');++ expect(response.status).toBe(204);+ expect(library.deleteRapidReaderLibraryEntry).toHaveBeenCalledWith('shelf-1');+ });+});diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex f7b8df5207..c380d3a8e3 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -140,6 +140,7 @@ import { storyBuilderStore } from './storyBuilder.js';import { writersRoomStore } from './writersRoom/store.js';import { mediaCollectionStore } from './mediaCollections.js';import { loraDatasetStore } from './loraDatasets.js';+import { rapidReaderLibraryStore } from './rapidReaderLibrary.js';import { commissionStore, backfillAllCommissionFeedback } from './creativeCommissions/store.js';import { backfillProjectCommissionIds } from './creativeCommissions/projectControl.js';import { outcomesStore as liOutcomesStore } from './layeredIntelligenceOutcomes.js';@@ -233,7 +234,7 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// but DO NOT crash the server. PortOS is single-user (AGENTS.md "Security// Model"); a hard exit on startup is worse than a noisy log the user can act// on. Returns per-store statuses for downstream telemetry; we discard them.- verifyCollections: () => verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore(), loraDatasetStore, liOutcomesStore(), commissionStore(), gameStore, fableLoomStore, ...brainCollectionStores()]),+ verifyCollections: () => verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore(), loraDatasetStore, rapidReaderLibraryStore, liOutcomesStore(), commissionStore(), gameStore, fableLoomStore, ...brainCollectionStores()]),createToolkit: () => createAIToolkit({dataDir,diff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex 6966c95edc..d602213b92 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -110,6 +110,9 @@ export const CATEGORIES = {'privacy': { label: 'Privacy', description: 'Data-broker opt-out records and request history', archivable: true, deletable: false },'prompts': { label: 'Prompts', description: 'AI prompt templates', archivable: false, deletable: false },'python': { label: 'Python Runtime', description: 'Managed virtualenv for local ML tooling — rebuilt on the next Python-backed run (re-downloads several GB of wheels)', archivable: false, deletable: true, purgeScope: 'category' },+ // A pasted or URL-fetched book is the user's only copy — the shelf is not a+ // cache of anything re-fetchable, so it is neither archivable nor deletable.+ 'rapid-reader-library': { label: 'Rapid Reader Shelf', description: 'Saved books for Rapid Reader — pasted and URL-imported prose kept on this machine, not regenerable', archivable: false, deletable: false },'repos': { label: 'Cloned Repos', description: 'Git repositories cloned by agents', archivable: false, deletable: true, purgeScope: 'category' },'review': { label: 'Review', description: 'Review hub items', archivable: true, deletable: true, purgeScope: 'category' },'runs': { label: 'AI Runs', description: 'Agent run logs and outputs', archivable: true, deletable: true, purgeScope: 'category' },diff --git a/server/services/rapidReader.js b/server/services/rapidReader.jsindex 0564113203..4f1c68e279 100644--- a/server/services/rapidReader.js+++ b/server/services/rapidReader.js@@ -3,6 +3,7 @@ import { PATHS, atomicWrite, tryReadFileStrict } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';import { htmlToText } from '../lib/htmlToText.js';import { fetchPublicText } from '../lib/safeUrlFetch.js';+import { upsertAccelerandoShelfEntry } from './rapidReaderLibrary.js';export const ACCELERANDO_BOOK = Object.freeze({id: 'accelerando',@@ -133,7 +134,15 @@ async function loadAccelerando() {let loadPromise = null;/** Load the official edition, using the local cache after the first request. */+async function loadAndStoreAccelerando() {+ const book = await loadAccelerando();+ const shelfStored = await upsertAccelerandoShelfEntry(book).then(() => true, (error) => {+ console.error(`❌ Failed to save Accelerando to shelf: ${error.code || 'unknown error'}`);+ return false;+ });+ return { ...book, shelfStored };+}export function getAccelerandoBook() {- if (!loadPromise) loadPromise = loadAccelerando().finally(() => { loadPromise = null; });+ if (!loadPromise) loadPromise = loadAndStoreAccelerando().finally(() => { loadPromise = null; });return loadPromise;}diff --git a/server/services/rapidReader.test.js b/server/services/rapidReader.test.jsindex 3ff2892d8a..200cfa6caf 100644--- a/server/services/rapidReader.test.js+++ b/server/services/rapidReader.test.js@@ -7,13 +7,15 @@ const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'portos-rapid-reader-'));vi.mock('../lib/fileUtils.js', async (importOriginal) => {const actual = await importOriginal();- return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT, rapidReaderLibrary: join(TEST_DATA_ROOT, 'rapid-reader-library') } };});vi.mock('../lib/safeUrlFetch.js', () => ({ fetchPublicText: vi.fn() }));const service = await import('./rapidReader.js');const { fetchPublicText } = await import('../lib/safeUrlFetch.js');+const libraryStore = (await import('./rapidReaderLibrary.js')).rapidReaderLibraryStore;+const listShelf = (await import('./rapidReaderLibrary.js')).listRapidReaderLibrary;const CACHE_FILE = join(TEST_DATA_ROOT, 'cache', 'accelerando.html');const SOURCE_HTML = `<!doctype html>@@ -108,6 +110,33 @@ describe('getAccelerandoBook', () => {expect(fetchPublicText).toHaveBeenCalledOnce();});+ it('upserts one stable shelf entry after a successful load', async () => {+ fetchPublicText.mockResolvedValue(SOURCE_HTML);++ const book = await service.getAccelerandoBook();+ await service.getAccelerandoBook();++ expect(book.shelfStored).toBe(true);+ const shelf = await listShelf();+ expect(shelf).toHaveLength(1);+ expect(shelf[0]).toMatchObject({ id: 'accelerando', sourceType: 'accelerando', title: 'Accelerando' });+ });++ // The shelf is a convenience on top of the book, so an unwritable store+ // degrades the same way an unwritable cache does: the book still returns.+ it('still returns the book with shelfStored:false when the shelf write fails', async () => {+ fetchPublicText.mockResolvedValue(SOURCE_HTML);+ const saveOne = vi.spyOn(libraryStore, 'saveOne').mockRejectedValue(new Error('disk full'));+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ const book = await service.getAccelerandoBook();++ expect(book.shelfStored).toBe(false);+ expect(book.text).toContain('Chapter 1');+ saveOne.mockRestore();+ consoleError.mockRestore();+ });+it('fails closed when the remote source is unavailable or unrecognized', async () => {fetchPublicText.mockResolvedValueOnce(null);await expect(service.getAccelerandoBook()).rejects.toMatchObject({diff --git a/server/services/rapidReaderLibrary.js b/server/services/rapidReaderLibrary.jsnew file mode 100644index 0000000000..b458b8cf0e--- /dev/null+++ b/server/services/rapidReaderLibrary.js@@ -0,0 +1,73 @@+import { PATHS } from '../lib/fileUtils.js';+import { createCollectionStore } from '../lib/collectionStore.js';+import { ServerError } from '../lib/errorHandler.js';+import { htmlToText } from '../lib/htmlToText.js';+import { fetchPublicText } from '../lib/safeUrlFetch.js';+import { v4 as uuidv4 } from '../lib/uuid.js';++export const RAPID_READER_LIBRARY_SCHEMA_VERSION = 1;+export const MAX_RAPID_READER_TEXT_BYTES = 2 * 1024 * 1024;+const MAX_TITLE_LENGTH = 200;+const now = () => new Date().toISOString();+const wordCount = (text) => (text.match(/\S+/g) || []).length;+const textBytes = (text) => Buffer.byteLength(text, 'utf8');+const normalizeText = (text) => typeof text === 'string' ? text.trim() : '';+const normalizeTitle = (title) => typeof title === 'string' ? title.trim().slice(0, MAX_TITLE_LENGTH) : '';++export const rapidReaderLibraryStore = createCollectionStore({+ dir: PATHS.rapidReaderLibrary,+ type: 'rapid-reader-library',+ schemaVersion: RAPID_READER_LIBRARY_SCHEMA_VERSION,+ sanitizeRecord: (record) => {+ const text = normalizeText(record?.text);+ const title = normalizeTitle(record?.title);+ if (!record?.id || !text || !title || !['paste', 'fetch', 'accelerando'].includes(record.sourceType)) return null;+ return { ...record, title, text, author: typeof record.author === 'string' ? record.author : null, sourceUrl: typeof record.sourceUrl === 'string' ? record.sourceUrl : null, wordCount: wordCount(text) };+ },+});++function assertText(text) {+ if (!text) throw new ServerError('Text is required', { status: 400, code: 'VALIDATION_ERROR' });+ if (textBytes(text) > MAX_RAPID_READER_TEXT_BYTES) throw new ServerError('Text exceeds the 2 MiB limit', { status: 400, code: 'VALIDATION_ERROR' });+}+function metadata(record) { const { text, ...entry } = record; return entry; }+function titleFromHtml(source) {+ const match = /<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(source);+ return match ? htmlToText(match[1]).trim() : '';+}+function hostnameFor(url) { return new URL(url).hostname; }+export async function listRapidReaderLibrary() { return (await rapidReaderLibraryStore.loadAll()).map(metadata).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); }+export async function getRapidReaderLibraryEntry(id) {+ const entry = await rapidReaderLibraryStore.loadOne(id);+ if (!entry) throw new ServerError('Shelf entry not found', { status: 404, code: 'NOT_FOUND' });+ return entry;+}+// saveOne only writes {dir}/{id}/index.json — it never touches the type-level+// index, so a store whose records were all written by saveOne would report+// "no index.json (fresh install)" to the boot verifier forever. Stamp it once+// per process on the first write (same guard as creativeCommissions).+let typeIndexStamped = false;+async function ensureTypeIndex() {+ if (typeIndexStamped) return;+ typeIndexStamped = true;+ await rapidReaderLibraryStore.saveTypeIndex({}).catch(() => { typeIndexStamped = false; });+}+async function saveEntry(entry) { await rapidReaderLibraryStore.saveOne(entry.id, entry); await ensureTypeIndex(); return entry; }+export async function createPastedRapidReaderEntry({ title, author, text }) {+ const cleanText = normalizeText(text); const cleanTitle = normalizeTitle(title); assertText(cleanText);+ if (!cleanTitle) throw new ServerError('Title is required', { status: 400, code: 'VALIDATION_ERROR' });+ const timestamp = now();+ return saveEntry({ id: uuidv4(), title: cleanTitle, author: normalizeTitle(author) || null, sourceUrl: null, sourceType: 'paste', text: cleanText, wordCount: wordCount(cleanText), addedAt: timestamp, updatedAt: timestamp });+}+export async function fetchRapidReaderEntry({ url, title }) {+ const source = await fetchPublicText(url, { blockPrivate: true, maxBytes: MAX_RAPID_READER_TEXT_BYTES, timeoutMs: 20_000 });+ if (!source) throw new ServerError('Could not fetch the requested URL', { status: 502, code: 'FETCH_FAILED' });+ const text = normalizeText(htmlToText(source)); assertText(text);+ const timestamp = now(); const derivedTitle = normalizeTitle(title) || normalizeTitle(titleFromHtml(source)) || hostnameFor(url);+ return saveEntry({ id: uuidv4(), title: derivedTitle, author: null, sourceUrl: url, sourceType: 'fetch', text, wordCount: wordCount(text), addedAt: timestamp, updatedAt: timestamp });+}+export async function deleteRapidReaderLibraryEntry(id) { await getRapidReaderLibraryEntry(id); await rapidReaderLibraryStore.deleteOne(id); }+export async function upsertAccelerandoShelfEntry(book) {+ const current = await rapidReaderLibraryStore.loadOne('accelerando'); const timestamp = now(); const text = normalizeText(book.text); assertText(text);+ return saveEntry({ id: 'accelerando', title: book.title, author: book.author, sourceUrl: book.sourceUrl, sourceType: 'accelerando', text, wordCount: wordCount(text), addedAt: current?.addedAt || timestamp, updatedAt: timestamp });+}diff --git a/server/services/rapidReaderLibrary.test.js b/server/services/rapidReaderLibrary.test.jsnew file mode 100644index 0000000000..d65e781b64--- /dev/null+++ b/server/services/rapidReaderLibrary.test.js@@ -0,0 +1,148 @@+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'portos-rapid-reader-library-'));+const LIBRARY_DIR = join(TEST_DATA_ROOT, 'rapid-reader-library');++vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT, rapidReaderLibrary: LIBRARY_DIR } };+});++vi.mock('../lib/safeUrlFetch.js', () => ({ fetchPublicText: vi.fn() }));++const library = await import('./rapidReaderLibrary.js');+const { fetchPublicText } = await import('../lib/safeUrlFetch.js');++const ACCELERANDO = {+ id: 'accelerando',+ title: 'Accelerando',+ author: 'Charles Stross',+ sourceUrl: 'https://example.com/accelerando',+ text: 'A novel by Charles Stross.',+};++beforeEach(async () => {+ vi.clearAllMocks();+ rmSync(LIBRARY_DIR, { recursive: true, force: true });+ library.rapidReaderLibraryStore.clearCache?.();+});+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++describe('rapid reader shelf store', () => {+ it('persists a pasted entry and reloads its text from disk', async () => {+ const created = await library.createPastedRapidReaderEntry({ title: ' Notes ', text: ' alpha bravo charlie ' });++ expect(created).toMatchObject({ title: 'Notes', sourceType: 'paste', sourceUrl: null, author: null, wordCount: 3, text: 'alpha bravo charlie' });+ expect(created.addedAt).toBe(created.updatedAt);++ const reloaded = await library.getRapidReaderLibraryEntry(created.id);+ expect(reloaded.text).toBe('alpha bravo charlie');+ });++ // The stamp is a once-per-process guard, so this needs a module instance that+ // has not already written the type index for an earlier test's (since-deleted)+ // directory.+ it('stamps the type-level schema version so the boot verifier sees the store', async () => {+ vi.resetModules();+ const fresh = await import('./rapidReaderLibrary.js');+ await fresh.createPastedRapidReaderEntry({ title: 'Notes', text: 'alpha bravo' });++ const index = JSON.parse(readFileSync(join(LIBRARY_DIR, 'index.json'), 'utf8'));+ expect(index).toMatchObject({ type: 'rapid-reader-library', schemaVersion: library.RAPID_READER_LIBRARY_SCHEMA_VERSION });+ await expect(fresh.rapidReaderLibraryStore.verifySchemaVersion()).resolves.toMatchObject({ ok: true, onDisk: fresh.RAPID_READER_LIBRARY_SCHEMA_VERSION });+ });++ it('lists metadata newest-first and never includes the text', async () => {+ const older = await library.createPastedRapidReaderEntry({ title: 'Older', text: 'alpha' });+ await new Promise((resolve) => setTimeout(resolve, 2));+ const newer = await library.createPastedRapidReaderEntry({ title: 'Newer', text: 'bravo' });++ const listed = await library.listRapidReaderLibrary();+ expect(listed.map((entry) => entry.id)).toEqual([newer.id, older.id]);+ expect(listed.every((entry) => !('text' in entry))).toBe(true);+ });++ it('rejects an empty or oversized paste without writing a record', async () => {+ await expect(library.createPastedRapidReaderEntry({ title: 'Empty', text: ' ' })).rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });+ await expect(library.createPastedRapidReaderEntry({ title: ' ', text: 'alpha' })).rejects.toMatchObject({ status: 400 });+ await expect(library.createPastedRapidReaderEntry({ title: 'Big', text: 'x'.repeat(library.MAX_RAPID_READER_TEXT_BYTES + 1) })).rejects.toMatchObject({ status: 400 });++ await expect(library.listRapidReaderLibrary()).resolves.toEqual([]);+ });++ it('404s on an unknown id, and deletes only the requested entry', async () => {+ const kept = await library.createPastedRapidReaderEntry({ title: 'Kept', text: 'alpha' });+ const doomed = await library.createPastedRapidReaderEntry({ title: 'Doomed', text: 'bravo' });++ await expect(library.getRapidReaderLibraryEntry('missing')).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });++ await library.deleteRapidReaderLibraryEntry(doomed.id);+ expect((await library.listRapidReaderLibrary()).map((entry) => entry.id)).toEqual([kept.id]);+ await expect(library.deleteRapidReaderLibraryEntry(doomed.id)).rejects.toMatchObject({ status: 404 });+ });++ describe('URL import', () => {+ it('derives the title from the page <title> and keeps the source URL', async () => {+ fetchPublicText.mockResolvedValue('<html><head><title> Example Article </title></head><body><p>alpha bravo</p></body></html>');++ const entry = await library.fetchRapidReaderEntry({ url: 'https://example.com/a' });++ expect(entry).toMatchObject({ title: 'Example Article', sourceType: 'fetch', sourceUrl: 'https://example.com/a', author: null, text: 'alpha bravo' });+ expect(fetchPublicText).toHaveBeenCalledWith('https://example.com/a', { blockPrivate: true, maxBytes: library.MAX_RAPID_READER_TEXT_BYTES, timeoutMs: 20_000 });+ });++ it('prefers a caller title, then falls back to the hostname when the page has none', async () => {+ fetchPublicText.mockResolvedValue('<html><head><title>Ignored</title></head><body><p>alpha</p></body></html>');+ await expect(library.fetchRapidReaderEntry({ url: 'https://example.com/a', title: 'Mine' })).resolves.toMatchObject({ title: 'Mine' });++ fetchPublicText.mockResolvedValue('alpha bravo charlie');+ await expect(library.fetchRapidReaderEntry({ url: 'https://example.com/b' })).resolves.toMatchObject({ title: 'example.com', text: 'alpha bravo charlie' });+ });++ it('writes no record when the fetch fails or converts to empty text', async () => {+ fetchPublicText.mockResolvedValue('');+ await expect(library.fetchRapidReaderEntry({ url: 'https://example.com/a' })).rejects.toMatchObject({ status: 502, code: 'FETCH_FAILED' });++ fetchPublicText.mockResolvedValue('<html><body> </body></html>');+ await expect(library.fetchRapidReaderEntry({ url: 'https://example.com/b' })).rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });++ fetchPublicText.mockRejectedValue(Object.assign(new Error('blocked'), { code: 'UNSAFE_URL' }));+ await expect(library.fetchRapidReaderEntry({ url: 'http://192.0.2.10/a' })).rejects.toMatchObject({ code: 'UNSAFE_URL' });++ await expect(library.listRapidReaderLibrary()).resolves.toEqual([]);+ });++ it('creates a new entry per fetch of the same URL — no dedup', async () => {+ fetchPublicText.mockResolvedValue('<html><body><p>alpha</p></body></html>');++ const first = await library.fetchRapidReaderEntry({ url: 'https://example.com/a' });+ const second = await library.fetchRapidReaderEntry({ url: 'https://example.com/a' });++ expect(second.id).not.toBe(first.id);+ expect(await library.listRapidReaderLibrary()).toHaveLength(2);+ });+ });++ describe('Accelerando upsert', () => {+ it('always uses the fixed id and refreshes the text', async () => {+ const created = await library.upsertAccelerandoShelfEntry(ACCELERANDO);+ expect(created).toMatchObject({ id: 'accelerando', sourceType: 'accelerando', author: 'Charles Stross' });++ const updated = await library.upsertAccelerandoShelfEntry({ ...ACCELERANDO, text: 'A revised novel.' });+ expect(updated.text).toBe('A revised novel.');+ expect(await library.listRapidReaderLibrary()).toHaveLength(1);+ });++ it('preserves the original addedAt across re-upserts', async () => {+ const created = await library.upsertAccelerandoShelfEntry(ACCELERANDO);+ await new Promise((resolve) => setTimeout(resolve, 2));+ const updated = await library.upsertAccelerandoShelfEntry({ ...ACCELERANDO, text: 'A revised novel.' });++ expect(updated.addedAt).toBe(created.addedAt);+ expect(updated.updatedAt > created.updatedAt).toBe(true);+ });+ });+});