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

feat: load Accelerando in Rapid Reader

[._.]/ Adam Eivy170b24dc25b3
diff --git a/client/src/pages/RapidReader.jsx b/client/src/pages/RapidReader.jsx
index 3b7f0d245c..c3ff22ef75 100644
--- a/client/src/pages/RapidReader.jsx
+++ b/client/src/pages/RapidReader.jsx
@@ -1,8 +1,14 @@
import { useState } from 'react';
-import { Zap, ClipboardPaste, Eraser } from 'lucide-react';
+import { BookOpen, ClipboardPaste, Eraser, ExternalLink, Zap } from 'lucide-react';
import RapidReader from '../components/RapidReader';
import PageHeader from '../components/PageHeader';
import { readClipboard } from '../lib/clipboard';
+import { useAsyncAction } from '../hooks/useAsyncAction';
+import {
+ ACCELERANDO_LICENSE_URL,
+ ACCELERANDO_SOURCE_PAGE_URL,
+ getAccelerandoBook,
+} 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.`;
@@ -20,6 +26,27 @@ export default function RapidReaderPage() {
const [wpm, setWpm] = useState(350);
const [chunkSize, setChunkSize] = useState(1);
const [focalColor, setFocalColor] = useState('#ef4444');
+ const [bookStatus, setBookStatus] = useState('idle');
+ const [bookError, setBookError] = useState('');
+
+ const [loadBook, loadingBook] = useAsyncAction(async () => {
+ setBookStatus('loading');
+ setBookError('');
+ const book = await getAccelerandoBook({ silent: true }).catch((error) => {
+ setBookStatus('error');
+ setBookError(error?.message || 'Could not load Accelerando');
+ return null;
+ });
+ if (!book) return null;
+ if (typeof book?.text !== 'string' || !book.text.trim()) {
+ setBookStatus('error');
+ setBookError('The Accelerando response was invalid — please retry');
+ return null;
+ }
+ setText(book.text);
+ setBookStatus(book.cached ? 'cached' : book.cacheStored === false ? 'downloaded-uncached' : 'downloaded');
+ return book;
+ });
const start = () => {
const trimmed = text.trim();
@@ -64,6 +91,59 @@ export default function RapidReaderPage() {
</div>
) : (
<div className="space-y-4">
+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
+ <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
+ <div className="flex items-start gap-3">
+ <BookOpen size={20} className="mt-0.5 text-port-accent shrink-0" aria-hidden="true" />
+ <div>
+ <h2 className="text-sm font-medium text-gray-200">Accelerando</h2>
+ <p className="text-xs text-gray-400">Charles Stross · official HTML edition</p>
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={() => loadBook()}
+ disabled={loadingBook}
+ className="inline-flex items-center justify-center min-h-10 px-3 py-2 rounded-md bg-port-accent text-white text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed hover:bg-port-accent/90"
+ >
+ {loadingBook ? 'Loading…' : 'Load Accelerando'}
+ </button>
+ </div>
+ <p className="text-xs leading-5 text-gray-400">
+ Downloads the author-hosted book when requested, then keeps the source in this instance's local cache for repeat and offline reads.
+ </p>
+ <div className="flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-500">
+ <a
+ href={ACCELERANDO_SOURCE_PAGE_URL}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex items-center gap-1 text-port-accent hover:underline"
+ >
+ Author's page <ExternalLink size={11} aria-hidden="true" />
+ </a>
+ <a
+ href={ACCELERANDO_LICENSE_URL}
+ target="_blank"
+ rel="noreferrer"
+ className="text-port-accent hover:underline"
+ >
+ CC BY-NC-ND 2.5
+ </a>
+ </div>
+ {bookStatus === 'downloaded' && (
+ <p role="status" className="text-xs text-green-400">Downloaded from the author's site and cached on this instance.</p>
+ )}
+ {bookStatus === 'downloaded-uncached' && (
+ <p role="status" className="text-xs text-yellow-400">Downloaded from the author's site, but this instance could not save its local cache.</p>
+ )}
+ {bookStatus === 'cached' && (
+ <p role="status" className="text-xs text-green-400">Loaded from this instance's local cache.</p>
+ )}
+ {bookStatus === 'error' && (
+ <p role="alert" className="text-xs text-red-400">{bookError}</p>
+ )}
+ </div>
+
<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">
diff --git a/client/src/pages/RapidReader.test.jsx b/client/src/pages/RapidReader.test.jsx
new file mode 100644
index 0000000000..3648aac3a0
--- /dev/null
+++ b/client/src/pages/RapidReader.test.jsx
@@ -0,0 +1,66 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+const api = vi.hoisted(() => ({
+ ACCELERANDO_LICENSE_URL: 'https://creativecommons.org/licenses/by-nc-nd/2.5/',
+ ACCELERANDO_SOURCE_PAGE_URL: 'https://www.antipope.org/charlie/blog-static/fiction/accelerando/accelerando-intro.html',
+ getAccelerandoBook: vi.fn(),
+}));
+
+vi.mock('../services/api', () => api);
+
+const RapidReaderPage = (await import('./RapidReader')).default;
+
+const BOOK = {
+ id: 'accelerando',
+ title: 'Accelerando',
+ author: 'Charles Stross',
+ text: 'A novel by Charles Stross. Chapter 1: Example.',
+ wordCount: 8,
+ cached: false,
+};
+
+beforeEach(() => vi.clearAllMocks());
+
+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 />);
+
+ expect(api.getAccelerandoBook).not.toHaveBeenCalled();
+ expect(screen.getByRole('link', { name: /author's page/i })).toHaveAttribute(
+ 'href',
+ 'https://www.antipope.org/charlie/blog-static/fiction/accelerando/accelerando-intro.html',
+ );
+ expect(screen.getByRole('link', { name: 'CC BY-NC-ND 2.5' })).toHaveAttribute(
+ 'href',
+ 'https://creativecommons.org/licenses/by-nc-nd/2.5/',
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Load Accelerando' }));
+
+ await waitFor(() => expect(screen.getByRole('textbox', { name: 'Text to read' })).toHaveValue(BOOK.text));
+ expect(api.getAccelerandoBook).toHaveBeenCalledWith({ silent: true });
+ expect(screen.getByRole('status')).toHaveTextContent(/cached on this instance/i);
+ });
+
+ it('shows a retryable inline error without a duplicate toast', async () => {
+ api.getAccelerandoBook.mockRejectedValue(new Error('Author source unavailable'));
+ render(<RapidReaderPage />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Load Accelerando' }));
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('Author source unavailable');
+ expect(screen.getByRole('button', { name: 'Load Accelerando' })).toBeEnabled();
+ });
+
+ it('rejects an invalid successful response with a retryable inline error', async () => {
+ api.getAccelerandoBook.mockResolvedValue({ cached: false });
+ render(<RapidReaderPage />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Load Accelerando' }));
+
+ expect(await screen.findByRole('alert')).toHaveTextContent(/response was invalid/i);
+ expect(screen.getByRole('button', { name: 'Load Accelerando' })).toBeEnabled();
+ });
+});
diff --git a/client/src/services/README.md b/client/src/services/README.md
index bac40d645f..0503b642b4 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -62,6 +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. |
| `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/api.js b/client/src/services/api.js
index b67cfbddc2..efefc3a7f5 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -87,6 +87,7 @@ export * from './apiAuth.js';
export * from './apiOpenWorld.js';
export * from './apiPrivacy.js';
export * from './apiQuotaBurn.js';
+export * from './apiRapidReader.js';
// Default export for simplified imports (get/post/put/delete helpers)
export { default } from './apiCore.js';
diff --git a/client/src/services/apiRapidReader.js b/client/src/services/apiRapidReader.js
new file mode 100644
index 0000000000..78e50f22f5
--- /dev/null
+++ b/client/src/services/apiRapidReader.js
@@ -0,0 +1,6 @@
+import { request } from './apiCore.js';
+
+export const ACCELERANDO_SOURCE_PAGE_URL = 'https://www.antipope.org/charlie/blog-static/fiction/accelerando/accelerando-intro.html';
+export const ACCELERANDO_LICENSE_URL = 'https://creativecommons.org/licenses/by-nc-nd/2.5/';
+
+export const getAccelerandoBook = (options) => request('/rapid-reader/accelerando', options);
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 8427a91d27..89acbc81c1 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -103,6 +103,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- Brain parity audit results — `data/brain_parity_reports.json` (`server/services/brainParity.js`, #4519). The last record-level brain-parity report per peer, keyed by peer `instanceId` (the same key `data/instances_sync_cursors.json` uses). `ephemeral-file` because it is a point-in-time *observation* about two installs, fully regenerable by re-running the audit, and stale the moment either side syncs — the durable state it describes lives in the brain stores. **Intentionally machine-local — never federated**: it is this install's view of a peer, and each peer computes its own. No sync cursor, no tombstone, no migration (an absent file reads as "nothing audited yet"). Per-type record lists are capped at 25 ids with a `truncated` flag so a badly diverged install can't grow the file without bound.
- CoS run event ledger — `data/cos/run-events.jsonl` + one retained archive generation `run-events.1.jsonl` (`server/services/agentRunEventLog.js`, #4540). The ordered, append-only trace of how a CoS agent run reached its current state: spawn, handoff to/from the CoS Runner, first output, PTY reconnect, pause/resume, interruption, PR-claim verification, orphan reap, runner re-adoption, finalization, and the ledger-driven close of a run record left open (`run.reconciled`, `server/services/agentRunReconciler.js`). `ephemeral-file` because the DURABLE record of a run is still `data/runs/{id}/metadata.json` — this is a regenerable-by-observation diagnostic over it, with no cross-record queries, no relationships, and no sync cursor; the projection that derives current status is a pure fold (`server/lib/agentRunEvents.js`), so losing the ledger costs post-mortem detail and nothing else. **Intentionally machine-local — never federated**: every line describes a process on THIS box, so a peer would inherit a trace of runs that never existed there. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Bounded on TWO axes, because neither alone is a retention policy. A COUNT: the active generation rotates at 5000 events and exactly one archive is kept, so the ledger is capped at ~2×5000 events forever with no cleanup job. And an AGE (30 days), because the count alone bounds a busy install but lets a quiet one keep a trace of a run from last spring, describing a workspace, a provider, and a code path that no longer exist. Expired events are filtered out of every read (so the bound holds continuously) and swept off disk on a throttled prune (so the files actually shrink). No migration and no `data.reference/` seed: an absent file reads as an empty ledger. Payloads are redacted at APPEND time (prompt/description/output/result keys dropped to a `{ redacted, chars }` stub, home-dir prefix scrubbed, string/array/key/depth capped), so no reader has to re-redact. Backed up with the rest of `data/cos/` — it is small, bounded, and the thing you most want after the crash you are debugging.
- 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.
---
diff --git a/server/index.js b/server/index.js
index b0411fdfd8..40ffa7bc13 100644
--- a/server/index.js
+++ b/server/index.js
@@ -91,6 +91,7 @@ import databaseRoutes from './routes/database.js';
import localLlmRoutes from './routes/localLlm.js';
import codeReviewRoutes from './routes/codeReview.js';
import searchRoutes from './routes/search.js';
+import rapidReaderRoutes from './routes/rapidReader.js';
import paletteRoutes from './routes/palette.js';
import dashboardLayoutsRoutes from './routes/dashboardLayouts.js';
import dashboardDailyActionsRoutes from './routes/dashboardDailyActions.js';
@@ -266,6 +267,7 @@ app.use('/api/quota-burn', quotaBurnRoutes);
app.use('/api/screenshots', screenshotsRoutes);
app.use('/api/shell', shellRoutes);
app.use('/api/search', searchRoutes);
+app.use('/api/rapid-reader', rapidReaderRoutes);
app.use('/api/palette', paletteRoutes);
app.use('/api/dashboard/layouts', dashboardLayoutsRoutes);
app.use('/api/dashboard/daily-actions', dashboardDailyActionsRoutes);
diff --git a/server/routes/rapidReader.js b/server/routes/rapidReader.js
new file mode 100644
index 0000000000..2f2632a3df
--- /dev/null
+++ b/server/routes/rapidReader.js
@@ -0,0 +1,13 @@
+import { Router } from 'express';
+import { asyncHandler } from '../lib/errorHandler.js';
+import { getAccelerandoBook } from '../services/rapidReader.js';
+
+const router = Router();
+
+router.get('/accelerando', asyncHandler(async (_req, res) => {
+ const book = await getAccelerandoBook();
+ res.set('Cache-Control', 'private, no-store');
+ res.json(book);
+}));
+
+export default router;
diff --git a/server/routes/rapidReader.test.js b/server/routes/rapidReader.test.js
new file mode 100644
index 0000000000..41e60adc7f
--- /dev/null
+++ b/server/routes/rapidReader.test.js
@@ -0,0 +1,40 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/rapidReader.js', () => ({
+ getAccelerandoBook: vi.fn(),
+}));
+
+const routes = (await import('./rapidReader.js')).default;
+const service = await import('../services/rapidReader.js');
+
+const BOOK = {
+ id: 'accelerando',
+ title: 'Accelerando',
+ text: 'A novel by Charles Stross',
+ wordCount: 5,
+ cached: true,
+};
+
+function makeApp() {
+ const app = express();
+ app.use('/api/rapid-reader', routes);
+ app.use(errorMiddleware);
+ return app;
+}
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('GET /api/rapid-reader/accelerando', () => {
+ it('returns the book and prevents shared HTTP caching', async () => {
+ service.getAccelerandoBook.mockResolvedValue(BOOK);
+
+ const response = await request(makeApp()).get('/api/rapid-reader/accelerando');
+
+ expect(response.status).toBe(200);
+ expect(response.headers['cache-control']).toBe('private, no-store');
+ expect(response.body).toEqual(BOOK);
+ });
+});
diff --git a/server/services/backup.js b/server/services/backup.js
index 1bb7a654ce..3f36ab9098 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -92,7 +92,7 @@ export const DEFAULT_EXCLUDES = [
{ path: '/repos/', reason: 'Cloned git repositories — large, re-cloneable from origin', overridable: true },
{ path: '/cos/reference-repos/', reason: 'Reference upstream repos used by agents — re-cloneable', overridable: true },
{ path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true },
- { path: '/cache/', reason: 'Remote-API metadata caches (e.g. Hugging Face repo records) — regenerable on demand, and stale on restore anyway', overridable: false },
+ { path: '/cache/', reason: 'Remote-API metadata and licensed reading caches — regenerable on demand, and stale on restore anyway', overridable: false },
// Sprite animation-run raw intermediates: 30–96 ffmpeg-extracted PNGs per
// run, byte-for-byte regenerable from the archived source video by the
// deterministic postprocess (walkPostprocess.js). The source video, packaged
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index e90a0f826e..6966c95edc 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -56,7 +56,7 @@ export const CATEGORIES = {
// but installs that predate that move still carry the dir, and backup still excludes it.
'browser-downloads': { label: 'Browser Downloads', description: 'Files the agent browser downloaded — re-downloadable, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },
'browser-profile': { label: 'Browser Profile', description: 'Chrome/Chromium browser data', archivable: false, deletable: true, purgeScope: 'category' },
- cache: { label: 'Remote API Cache', description: 'Cached metadata from remote APIs (Hugging Face repo records) — refetched on demand, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },
+ cache: { label: 'Remote API and Reading Cache', description: 'Cached remote API metadata and the author-hosted Accelerando reading source — refetched on demand, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },
'calendar': { label: 'Calendar', description: 'Calendar sync data', archivable: true, deletable: false },
'certs': { label: 'TLS Certificates', description: 'HTTPS certificate and private key — purging drops the install back to HTTP', archivable: false, deletable: false },
'commission-feedback': { label: 'Commission Feedback', description: 'Reactions on creative commissions (file mirror of the Postgres store)', archivable: true, deletable: false },
diff --git a/server/services/rapidReader.js b/server/services/rapidReader.js
new file mode 100644
index 0000000000..f51b0f581c
--- /dev/null
+++ b/server/services/rapidReader.js
@@ -0,0 +1,119 @@
+import { join } from 'node:path';
+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';
+
+export const ACCELERANDO_BOOK = Object.freeze({
+ id: 'accelerando',
+ title: 'Accelerando',
+ author: 'Charles Stross',
+ sourceUrl: 'https://www.antipope.org/charlie/blog-static/fiction/accelerando/accelerando.html',
+ sourcePageUrl: 'https://www.antipope.org/charlie/blog-static/fiction/accelerando/accelerando-intro.html',
+ licenseName: 'CC BY-NC-ND 2.5',
+ licenseUrl: 'https://creativecommons.org/licenses/by-nc-nd/2.5/',
+});
+
+const CACHE_FILE = join(PATHS.data, 'cache', 'accelerando.html');
+const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
+const SOURCE_TIMEOUT_MS = 20_000;
+const SOURCE_ENTITIES = {
+ ccedil: 'ç',
+ copy: '©',
+ ecirc: 'ê',
+ eacute: 'é',
+ egrave: 'è',
+ igrave: 'ì',
+ mdash: '—',
+ Mu: 'Μ',
+ ndash: '–',
+ ograve: 'ò',
+ ouml: 'ö',
+ uuml: 'ü',
+};
+const REQUIRED_MARKERS = [
+ 'A novel by Charles Stross',
+ 'Creative Commons Attribution-NonCommercial-NoDerivs 2.5',
+ 'Chapter 1:',
+];
+
+/**
+ * Extract the book body from the official single-page HTML edition and turn it
+ * into the plain text the RSVP reader expects. The marker checks keep an error
+ * page or a future unrelated replacement from being cached as a book.
+ */
+export function extractAccelerandoText(html) {
+ if (typeof html !== 'string') return '';
+ const bookHtml = html.match(/<div\b[^>]*\bid=["']book["'][^>]*>([\s\S]*?)<\/div>/i)?.[1];
+ if (!bookHtml) return '';
+ const text = htmlToText(bookHtml.replace(/<!--[\s\S]*?-->/g, ''), {
+ extraEntities: SOURCE_ENTITIES,
+ paragraphBreak: '\n\n',
+ collapseSpaces: true,
+ });
+ return REQUIRED_MARKERS.every((marker) => text.includes(marker)) ? text : '';
+}
+
+function sourceError(message, code) {
+ return new ServerError(message, { status: 502, code });
+}
+
+async function readCachedSource() {
+ const result = await tryReadFileStrict(CACHE_FILE);
+ if (!result.ok) {
+ throw new ServerError('Accelerando cache is unreadable — purge the cache and retry', {
+ status: 500,
+ code: 'ACCELERANDO_CACHE_UNREADABLE',
+ });
+ }
+ if (!result.value) return '';
+ return extractAccelerandoText(result.value);
+}
+
+function buildBook(text, cached, cacheStored = true) {
+ return {
+ ...ACCELERANDO_BOOK,
+ text,
+ wordCount: text.split(/\s+/).length,
+ cached,
+ cacheStored,
+ };
+}
+
+async function loadAccelerando() {
+ const cachedText = await readCachedSource();
+ if (cachedText) return buildBook(cachedText, true);
+
+ const source = await fetchPublicText(ACCELERANDO_BOOK.sourceUrl, {
+ blockPrivate: true,
+ headers: { 'User-Agent': 'PortOS-RapidReader/1.0' },
+ maxBytes: MAX_SOURCE_BYTES,
+ throwOnUnsafe: false,
+ timeoutMs: SOURCE_TIMEOUT_MS,
+ });
+ if (!source) {
+ throw sourceError('Could not download Accelerando from the author’s site', 'ACCELERANDO_FETCH_FAILED');
+ }
+
+ const text = extractAccelerandoText(source);
+ if (!text) {
+ throw sourceError('The downloaded Accelerando source was not a recognized book edition', 'ACCELERANDO_SOURCE_INVALID');
+ }
+
+ const cacheStored = await atomicWrite(CACHE_FILE, source).then(
+ () => true,
+ (error) => {
+ console.error(`❌ Failed to cache Accelerando source: ${error.code || 'unknown error'}`);
+ return false;
+ },
+ );
+ return buildBook(text, false, cacheStored);
+}
+
+let loadPromise = null;
+
+/** Load the official edition, using the local cache after the first request. */
+export function getAccelerandoBook() {
+ if (!loadPromise) loadPromise = loadAccelerando().finally(() => { loadPromise = null; });
+ return loadPromise;
+}
diff --git a/server/services/rapidReader.test.js b/server/services/rapidReader.test.js
new file mode 100644
index 0000000000..6d1ad509af
--- /dev/null
+++ b/server/services/rapidReader.test.js
@@ -0,0 +1,114 @@
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+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 } };
+});
+
+vi.mock('../lib/safeUrlFetch.js', () => ({ fetchPublicText: vi.fn() }));
+
+const service = await import('./rapidReader.js');
+const { fetchPublicText } = await import('../lib/safeUrlFetch.js');
+
+const CACHE_FILE = join(TEST_DATA_ROOT, 'cache', 'accelerando.html');
+const SOURCE_HTML = `<!doctype html>
+<html><body>
+ <h1>Accelerando</h1>
+ <div id="book">
+ <p>A novel by Charles Stross</p>
+ <p>Creative Commons Attribution-NonCommercial-NoDerivs 2.5</p>
+ <h3>Chapter 1: Example</h3>
+ <p>Café &ndash; déjà vu. &copy; Charles Stross.</p>
+ <!-- this comment must not become reader text -->
+ </div>
+</body></html>`;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ rmSync(CACHE_FILE, { force: true });
+});
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+describe('extractAccelerandoText', () => {
+ it('extracts readable text and decodes the official HTML entities', () => {
+ const text = service.extractAccelerandoText(SOURCE_HTML);
+
+ expect(text).toContain('A novel by Charles Stross');
+ expect(text).toContain('Café – déjà vu. © Charles Stross.');
+ expect(text).not.toContain('this comment must not become reader text');
+ });
+
+ it('rejects a page that does not contain the recognized book body', () => {
+ expect(service.extractAccelerandoText('<html><body>Temporary error</body></html>')).toBe('');
+ expect(service.extractAccelerandoText(null)).toBe('');
+ });
+});
+
+describe('getAccelerandoBook', () => {
+ it('fetches the fixed official source and caches the raw edition', async () => {
+ fetchPublicText.mockResolvedValue(SOURCE_HTML);
+
+ const book = await service.getAccelerandoBook();
+
+ expect(book).toMatchObject({
+ id: 'accelerando',
+ title: 'Accelerando',
+ author: 'Charles Stross',
+ licenseName: 'CC BY-NC-ND 2.5',
+ licenseUrl: 'https://creativecommons.org/licenses/by-nc-nd/2.5/',
+ cached: false,
+ wordCount: expect.any(Number),
+ });
+ expect(fetchPublicText).toHaveBeenCalledWith(
+ service.ACCELERANDO_BOOK.sourceUrl,
+ expect.objectContaining({
+ blockPrivate: true,
+ maxBytes: 2 * 1024 * 1024,
+ throwOnUnsafe: false,
+ }),
+ );
+ expect(readFileSync(CACHE_FILE, 'utf8')).toBe(SOURCE_HTML);
+ });
+
+ it('uses a valid local cache without making another remote request', async () => {
+ fetchPublicText.mockResolvedValue(SOURCE_HTML);
+ await service.getAccelerandoBook();
+ fetchPublicText.mockClear();
+
+ const book = await service.getAccelerandoBook();
+
+ expect(book.cached).toBe(true);
+ expect(fetchPublicText).not.toHaveBeenCalled();
+ });
+
+ it('does not trust an invalid cached source', async () => {
+ mkdirSync(join(TEST_DATA_ROOT, 'cache'), { recursive: true });
+ writeFileSync(CACHE_FILE, '<html><body>not a book</body></html>');
+ fetchPublicText.mockResolvedValue(SOURCE_HTML);
+
+ const book = await service.getAccelerandoBook();
+
+ expect(book.cached).toBe(false);
+ expect(fetchPublicText).toHaveBeenCalledOnce();
+ });
+
+ it('fails closed when the remote source is unavailable or unrecognized', async () => {
+ fetchPublicText.mockResolvedValueOnce(null);
+ await expect(service.getAccelerandoBook()).rejects.toMatchObject({
+ code: 'ACCELERANDO_FETCH_FAILED',
+ status: 502,
+ });
+
+ fetchPublicText.mockResolvedValueOnce('<html><body>not a book</body></html>');
+ await expect(service.getAccelerandoBook()).rejects.toMatchObject({
+ code: 'ACCELERANDO_SOURCE_INVALID',
+ status: 502,
+ });
+ });
+});