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
show a rendered cover thumbnail on each series in the pipeline list
[._.]/ Adam Eivyece9387790bc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 993845108a..d9f1cb8d80 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **The series pipeline list now shows a cover thumbnail on each series card.** Like the reference-image thumbnail on the Universe list, each series in **Pipeline** now leads with a small thumbnail of its graphic-novel cover — the first rendered **volume (trade-paperback) cover**, falling back to the earliest rendered **issue cover** — so you can recognize a series at a glance instead of reading names. The thumbnail filename is **persisted onto the series record** (`series.coverImage`) rather than computed at list time, so the list stays cheap (no per-series issue scan): the two cover filename hooks stamp it when a cover render completes, and a one-time, marker-gated boot backfill (`data/series-cover-backfill.applied.json`) derives it for series whose covers rendered before this shipped. Volume covers come straight off the series record (free); the issue fallback is only scanned when no volume cover exists. The field is wire-gated (`pipelineSeries` schema v5) so an older peer can't strip-then-LWW the pointer back, and the card falls back to a book icon when no cover exists yet (or 404s on a peer that synced the pointer but not the bytes). (`server/services/pipeline/seriesCoverImage.js`, `server/services/pipeline/series.js`, `server/services/pipeline/{comicPagesFilenameHook,seasonCoverFilenameHook}.js`, `server/scripts/backfillSeriesCoverImages.js`, `client/src/pages/Pipeline.jsx`)+- **Enrich a Universe noun — and refine a Universe style — from a reference image.** The Universe Bible's "Describe from image" modal now takes reference images from your **gallery** as well as uploads, and for **characters** it can do more than write the descriptor paragraph: a new **Build character details** action has a vision model read the reference image(s) and *propose* values for the character's still-blank structured fields (pronouns, age, visual notes, color palette, expressions, …). The proposals are shown for review — uncheck any, edit the text inline — and applied through the normal entry-patch path, so existing values are never overwritten (no-clobber, characters-only). Separately, the **Refine Prompts** form gains an optional **style-reference image**: pick one from the gallery and the refiner runs through a vision-capable provider, folding the image's palette/lighting/mood into the universe's `influences` + `styleNotes`. Both vision paths require an API provider with a vision model and reject a silent fallback to a non-vision provider rather than hallucinating from text alone; the vision provider/model pickers scope local (Ollama/LM Studio) backends to vision-capable models. Relatedly, a **model-not-found error no longer benches the whole provider** — that's a bad model id in one request, not a provider outage, so (like a content refusal) the single call still falls back but the provider stays available for its other working models (previously one bad model id could take Ollama offline for 30 minutes). (`server/services/universeVisionExpand.js`, `server/services/universeBuilderRefine.js`, `server/routes/universeBuilder.js`, `server/lib/promptRunner.js`, `client/src/components/universe/VisionDescribeModal.jsx`, `client/src/pages/UniverseBuilder.jsx`)- **[issue-1431] Legacy Export can now include a rendered PDF portrait.** Phase 2 of the Legacy Export (#901) bundle: pass `includePdf: true` to `POST /api/legacy-export` and the `.zip` gains a `legacy-portrait.pdf` rendered from the same per-section Markdown the bundle already produces — title page, per-section pages, heading sizing, word-wrapped body, and bullet/quote handling. It uses the already-present `pdf-lib` dependency (the same primitives as the comic-pages PDF — no new package) and degrades non-ASCII glyphs (VO₂, smart quotes, em-dashes, ⚠️) to WinAnsi-safe text so a stray Unicode character can't fail the render. The PDF is hashed into `manifest.json` like every other file and the manifest's `pdf.included` flag (previously hard-false) now reflects it, with the file name recorded under `pdf.file`. Default `includePdf` is **false** — the Markdown/JSON bundle stays the primary artifact. (`server/services/legacyExport.js`, `server/routes/legacyExport.js`, `server/lib/validation.js`, #1431)diff --git a/client/src/components/ui/ImageThumb.jsx b/client/src/components/ui/ImageThumb.jsxnew file mode 100644index 0000000000..51a85899db--- /dev/null+++ b/client/src/components/ui/ImageThumb.jsx@@ -0,0 +1,27 @@+import { useState } from 'react';++/**+ * Square list-card thumbnail with graceful fallback. Renders the image from+ * `/data/images/<imageRef>` and swaps to `FallbackIcon` when there's no ref or+ * the image 404s (e.g. a peer synced the pointer but not the bytes yet). Shared+ * by the universe reference thumbnail and the series cover thumbnail.+ */+export default function ImageThumb({ imageRef, FallbackIcon, alt = '' }) {+ const [broken, setBroken] = useState(false);+ const showImage = imageRef && !broken;+ return (+ <div className="flex-shrink-0 w-12 h-12 rounded-md overflow-hidden bg-port-bg border border-port-border flex items-center justify-center">+ {showImage ? (+ <img+ src={`/data/images/${encodeURIComponent(imageRef)}`}+ alt={alt}+ loading="lazy"+ onError={() => setBroken(true)}+ className="w-full h-full object-cover"+ />+ ) : (+ <FallbackIcon className="w-5 h-5 text-gray-600" aria-hidden="true" />+ )}+ </div>+ );+}diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsxindex 54e8c62300..004e1a26ea 100644--- a/client/src/pages/Pipeline.jsx+++ b/client/src/pages/Pipeline.jsx@@ -9,8 +9,9 @@import { useEffect, useMemo, useState } from 'react';import { Link, useNavigate } from 'react-router-dom';-import { Plus, Workflow as WorkflowIcon, Trash2, Loader2, Globe2, FileInput, Sparkles } from 'lucide-react';+import { Plus, Workflow as WorkflowIcon, Trash2, Loader2, Globe2, FileInput, Sparkles, BookOpen } from 'lucide-react';import toast from '../components/ui/Toast';+import ImageThumb from '../components/ui/ImageThumb';import ShareToButton from '../components/sharing/ShareToButton';import SyncToPeerButton from '../components/sharing/SyncToPeerButton';import OriginBadge from '../components/sharing/OriginBadge';@@ -433,30 +434,33 @@ export default function Pipeline() {const shapeDef = s.arc?.shape ? getStoryShape(s.arc.shape) : null;return (<li key={s.id} className="flex items-start justify-between gap-3 p-3 bg-port-card border border-port-border rounded-lg hover:border-port-accent/40 transition-colors">- <Link to={`/pipeline/series/${s.id}`} className="flex-1 min-w-0">- <div className="text-white font-medium flex items-center gap-2 flex-wrap">- <span>{s.name}</span>- {s.origin ? <OriginBadge origin={s.origin} compact /> : null}- {shapeDef ? (- <span- className="inline-flex items-center gap-1.5 text-[10px] uppercase tracking-wider px-2 py-0.5 rounded bg-port-bg border border-port-accent/40 text-port-accent"- title={shapeDef.description}- >- <ArcShapeSparkline shape={shapeDef} width={40} height={14} />- {shapeDef.label}- </span>+ <Link to={`/pipeline/series/${s.id}`} className="flex-1 min-w-0 flex items-start gap-3">+ <ImageThumb imageRef={s.coverImage} FallbackIcon={BookOpen} />+ <div className="min-w-0 flex-1">+ <div className="text-white font-medium flex items-center gap-2 flex-wrap">+ <span>{s.name}</span>+ {s.origin ? <OriginBadge origin={s.origin} compact /> : null}+ {shapeDef ? (+ <span+ className="inline-flex items-center gap-1.5 text-[10px] uppercase tracking-wider px-2 py-0.5 rounded bg-port-bg border border-port-accent/40 text-port-accent"+ title={shapeDef.description}+ >+ <ArcShapeSparkline shape={shapeDef} width={40} height={14} />+ {shapeDef.label}+ </span>+ ) : null}+ </div>+ {s.logline ? (+ <div className="text-xs text-gray-500 mt-1 whitespace-pre-wrap break-words">{s.logline}</div>+ ) : (+ <div className="text-xs text-gray-600 italic mt-1">No logline yet</div>+ )}+ {s.issueCountTarget ? (+ <div className="text-xs text-gray-600 mt-1">+ Target {s.issueCountTarget} issues / episodes+ </div>) : null}</div>- {s.logline ? (- <div className="text-xs text-gray-500 mt-1 whitespace-pre-wrap break-words">{s.logline}</div>- ) : (- <div className="text-xs text-gray-600 italic mt-1">No logline yet</div>- )}- {s.issueCountTarget ? (- <div className="text-xs text-gray-600 mt-1">- Target {s.issueCountTarget} issues / episodes- </div>- ) : null}</Link><SyncBadgestatus={syncBadgeStatus(sync, s.id)}diff --git a/client/src/pages/Universes.jsx b/client/src/pages/Universes.jsxindex bb957d83ea..d38240e926 100644--- a/client/src/pages/Universes.jsx+++ b/client/src/pages/Universes.jsx@@ -12,6 +12,7 @@ import { useEffect, useMemo, useState, useCallback } from 'react';import { Link, useNavigate } from 'react-router-dom';import { Plus, Globe, Trash2, Users, Workflow as WorkflowIcon, Copy } from 'lucide-react';import toast from '../components/ui/Toast';+import ImageThumb from '../components/ui/ImageThumb';import ShareToButton from '../components/sharing/ShareToButton';import SyncToPeerButton from '../components/sharing/SyncToPeerButton';import OriginBadge from '../components/sharing/OriginBadge';@@ -66,27 +67,11 @@ const baseStyleImageRef = (u) => {// 48px square thumbnail showing the universe's base style image, falling back// to the latest image from its auto-managed media collection, then a Globe-// placeholder when neither exists (or hasn't loaded yet). onError hides the-// <img> so a stale ref pointing at a deleted file falls back to the placeholder-// instead of a broken-image icon. Shared between desktop row and mobile card.+// placeholder when neither exists (or hasn't loaded yet). The shared ImageThumb+// hides the <img> on error so a stale ref pointing at a deleted file falls back+// to the placeholder instead of a broken-image icon. Used by desktop row + card.function UniverseThumb({ imageRef }) {- const [broken, setBroken] = useState(false);- const showImage = imageRef && !broken;- return (- <div className="flex-shrink-0 w-12 h-12 rounded-md overflow-hidden bg-port-bg border border-port-border flex items-center justify-center">- {showImage ? (- <img- src={`/data/images/${encodeURIComponent(imageRef)}`}- alt=""- loading="lazy"- onError={() => setBroken(true)}- className="w-full h-full object-cover"- />- ) : (- <Globe className="w-5 h-5 text-gray-600" aria-hidden="true" />- )}- </div>- );+ return <ImageThumb imageRef={imageRef} FallbackIcon={Globe} />;}// Shared between the desktop table row and the mobile card so the armed-statediff --git a/server/index.js b/server/index.jsindex d998f090d8..a0c1a21129 100644--- a/server/index.js+++ b/server/index.js@@ -989,6 +989,20 @@ ensureSelf()}}})+ .then(async () => {+ // One-time series cover-thumbnail backfill: derive `series.coverImage` (the+ // rendered volume/issue cover shown on the pipeline list) for series whose+ // covers rendered before the feature shipped. Runs after the series + issues+ // stores are warmed above so the derivation reads migrated records. Drives+ // the services, so it works on both the PG backend and the file escape hatch.+ // FIRE-AND-FORGET (not awaited): a cosmetic thumbnail backfill must never+ // delay the server accepting requests, and it's marker-gated so it runs at+ // most once regardless.+ const { backfillSeriesCoverImages } = await import('./scripts/backfillSeriesCoverImages.js');+ backfillSeriesCoverImages().catch((err) => {+ console.error(`❌ series cover backfill failed at boot: ${err?.message ?? err}`);+ });+ }).then(() => {// Start server only after sync log + media job queue are initialized.// initMediaJobQueue failure is fatal: the queue owns persistence + SSEdiff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex a2694f7258..4f5de5f5e9 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -90,7 +90,17 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// `sanitizeSeries`, drops the guide, and last-writer-wins the loss back onto// the newer peer. Bump makes the older peer reject the ahead-version series// transfer instead. Per-category gate → only series sync pauses with old peers.- pipelineSeries: 4,+ // v5 = `series.coverImage` added — a top-level derived field holding the+ // filename of a rendered volume/issue cover, shown as a thumbnail on the+ // pipeline series list. Derived (any peer can recompute it from its own+ // seasons/issues), but it's only recomputed on cover-render or the one-time+ // boot backfill — never on every read — so a ≤v4 peer that re-sanitizes a+ // series through its coverImage-unaware `sanitizeSeries` would drop the+ // pointer and LWW the loss back onto the newer peer, where it may never+ // recompute (a finished series renders no new cover). Gate so the older peer+ // rejects the ahead-version transfer instead. Per-category gate → only series+ // sync pauses with old peers.+ pipelineSeries: 5,// NOT bumped for the manuscript-review sibling doc now bundled on series// pushes/exports (`data/pipeline-series/{id}/manuscript-review.json`).// Unlike `readerMap` (v2), the review is NOT a field inside the seriesdiff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex 2797ce8acc..a672c3b8b8 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -27,8 +27,9 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {it('declares pipeline collection layout versions', () => {// pipelineIssues bumped to 2 when stages.audio.audioMode + cues[] were added.expect(PORTOS_SCHEMA_VERSIONS.pipelineIssues).toBe(2);- // pipelineSeries bumped to 4 when series.styleGuide was added (v2 = readerMap, v3 = tickingClock).- expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(4);+ // pipelineSeries bumped to 5 when series.coverImage was added (v2 = readerMap,+ // v3 = tickingClock, v4 = styleGuide).+ expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(5);});it('declares mediaCollections layout version', () => {@@ -42,7 +43,7 @@ describe('buildPortosMeta', () => {expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);expect(meta.schemaVersions.universes).toBe(7);expect(meta.schemaVersions.pipelineIssues).toBe(2);- expect(meta.schemaVersions.pipelineSeries).toBe(4);+ expect(meta.schemaVersions.pipelineSeries).toBe(5);});it('overrides merge into schemaVersions', async () => {diff --git a/server/scripts/backfillSeriesCoverImages.js b/server/scripts/backfillSeriesCoverImages.jsnew file mode 100644index 0000000000..1d2289a26b--- /dev/null+++ b/server/scripts/backfillSeriesCoverImages.js@@ -0,0 +1,97 @@+/**+ * One-time backfill: stamp `series.coverImage` on existing series.+ *+ * `series.coverImage` (the rendered volume/issue cover filename shown as the+ * pipeline list thumbnail) is populated going forward by the cover filename+ * hooks (comicPagesFilenameHook / seasonCoverFilenameHook) as covers render.+ * Series whose covers rendered BEFORE this feature shipped have no pointer yet,+ * so this walk derives it once for every existing series.+ *+ * Derives each series' cover with `deriveSeriesCoverImage` — a rendered volume+ * cover (free; seasons live on the series record) wins, else the earliest issue+ * cover. Volume covers come straight off the records `listSeries` already+ * returned (no per-series re-fetch); the issue fallback loads EVERY issue once+ * via `listAllIssues` and groups by series, instead of a per-series store scan.+ * `setSeriesCoverImage` no-ops when a series already carries the right cover, so+ * a re-run (or a boot after the hooks already decorated a series) writes nothing.+ *+ * Idempotent + marker-gated in `data/series-cover-backfill.applied.json` so the+ * scan doesn't repeat on every boot once done. `force` re-runs the walk (tests /+ * admin re-trigger). Fire-and-forget at boot (see server/index.js) — a cosmetic+ * thumbnail backfill must never delay the server accepting requests.+ *+ * Backend-agnostic: it drives the series/issues SERVICES, so it works under both+ * the PostgreSQL backend (normal installs) and the file escape hatch (tests).+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { PATHS } from '../lib/fileUtils.js';+import { listSeries, setSeriesCoverImage } from '../services/pipeline/series.js';+import { listAllIssues } from '../services/pipeline/issues.js';+import { deriveSeriesCoverImage, pickVolumeCoverFilename } from '../services/pipeline/seriesCoverImage.js';++const MARKER_VERSION = 1;+const MARKER_FILENAME = 'series-cover-backfill.applied.json';++async function readMarker() {+ const path = join(PATHS.data, MARKER_FILENAME);+ const raw = await readFile(path, 'utf-8').catch(() => null);+ if (!raw) return null;+ try { return JSON.parse(raw); } catch { return null; }+}++async function writeMarker(payload) {+ const path = join(PATHS.data, MARKER_FILENAME);+ await writeFile(path, JSON.stringify(payload, null, 2), 'utf-8');+}++/**+ * Public entry point. Runs once, then no-ops on every subsequent boot via the+ * marker file. `force` re-runs the walk regardless of the marker.+ */+export async function backfillSeriesCoverImages({ force = false } = {}) {+ const marker = await readMarker();+ if (marker?.version === MARKER_VERSION && !force) {+ return { skipped: true, marker };+ }++ const series = await listSeries().catch((err) => {+ console.error(`❌ series cover backfill: listSeries failed: ${err?.message || err}`);+ return [];+ });++ // Only fall back to an issue scan when at least one series lacks a volume+ // cover — and load every issue just ONCE, grouped by series, rather than a+ // per-series store scan. Drop run history (not needed to read a cover slot).+ const issuesBySeries = new Map();+ if (series.some((s) => !pickVolumeCoverFilename(s?.seasons))) {+ const all = await listAllIssues({ withHistory: false }).catch((err) => {+ console.error(`❌ series cover backfill: listAllIssues failed: ${err?.message || err}`);+ return [];+ });+ for (const issue of all) {+ if (!issue?.seriesId) continue;+ const list = issuesBySeries.get(issue.seriesId);+ if (list) list.push(issue);+ else issuesBySeries.set(issue.seriesId, [issue]);+ }+ }++ let scanned = 0;+ let decorated = 0;+ for (const s of series) {+ if (!s?.id) continue;+ scanned += 1;+ const next = deriveSeriesCoverImage({ seasons: s.seasons, issues: issuesBySeries.get(s.id) });+ if (next) decorated += 1;+ if ((s.coverImage || null) === (next || null)) continue; // already correct+ await setSeriesCoverImage(s.id, next).catch((err) => {+ console.error(`❌ series cover backfill: setSeriesCoverImage failed for ${String(s.id).slice(0, 8)}: ${err?.message || err}`);+ });+ }++ await writeMarker({ version: MARKER_VERSION, appliedAt: new Date().toISOString(), scanned });+ console.log(`🖼️ series cover backfill: scanned ${scanned} series, ${decorated} have a cover`);+ return { skipped: false, scanned, decorated };+}diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex cd839d63e2..2bc660e6ff 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -1053,12 +1053,12 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {const result = await dataSync.applyRemote('pipeline', {series: [{ id: 'ser-1', name: 'Foundry', updatedAt: '2026-05-17T11:00:00Z' }],issues: [],- }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 5, pipelineIssues: 1, mediaCollections: 1 } } });+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 6, pipelineIssues: 1, mediaCollections: 1 } } });expect(result.applied).toBe(false);expect(result.blockedBySchema).toBeDefined();// The reported gap is scoped to the relevant category — NOT mis-attributed.expect(result.blockedBySchema.ahead).toEqual([- { category: 'pipelineSeries', senderV: 5, receiverV: 4 },+ { category: 'pipelineSeries', senderV: 6, receiverV: 5 },]);expect(readSeriesState()).toEqual([]); // nothing written});diff --git a/server/services/pipeline/comicPagesFilenameHook.js b/server/services/pipeline/comicPagesFilenameHook.jsindex 48013be7bf..a3147936c2 100644--- a/server/services/pipeline/comicPagesFilenameHook.js+++ b/server/services/pipeline/comicPagesFilenameHook.js@@ -18,6 +18,7 @@ import { createFilenameHook } from './filenameHookFactory.js';import { buildRenderSlot } from './visualStages.js';import { getIssue } from './issues.js';import { fileCoverIntoAutoCollection } from './coverUniverseFiler.js';+import { refreshSeriesCoverImage } from './seriesCoverImage.js';// Slot record for a legacy in-flight completion (job enqueued before the// proof/final split). `job.params` carries the originally-requested width@@ -114,6 +115,11 @@ const hook = createFilenameHook({const issue = await getIssue(parsed.issueId).catch(() => null);if (!issue?.seriesId) return;await fileCoverIntoAutoCollection({ seriesId: issue.seriesId, filename });+ // Refresh the series' list thumbnail. Only a FRONT cover render can change+ // it (the thumbnail derives from front covers, never back covers), so a+ // back-cover landing skips the recompute + its issue scan. The recompute+ // no-ops the write when the chosen cover is unchanged.+ if (parsed.target === 'cover') await refreshSeriesCoverImage(issue.seriesId);},});diff --git a/server/services/pipeline/seasonCoverFilenameHook.js b/server/services/pipeline/seasonCoverFilenameHook.jsindex 1244aeec66..a59c2df6c2 100644--- a/server/services/pipeline/seasonCoverFilenameHook.js+++ b/server/services/pipeline/seasonCoverFilenameHook.js@@ -22,6 +22,7 @@ import { mediaJobEvents } from '../mediaJobQueue/index.js';import { parseSeasonCoverOwner, slotKeyForVariant } from './owners.js';import * as seriesSvc from './series.js';import { fileCoverIntoAutoCollection } from './coverUniverseFiler.js';+import { refreshSeriesCoverImage } from './seriesCoverImage.js';let registeredHandler = null;@@ -65,6 +66,9 @@ const handler = (job) => {if (reducerStamped && writeOk) {console.log(`📎 seasonCover filename stamped — series=${seriesId.slice(0, 8)} season=${seasonId.slice(0, 8)} ${target}.${slotKey} ← ${filename}`);await fileCoverIntoAutoCollection({ seriesId, filename });+ // Volume (front) covers are the top-priority series thumbnail. A back+ // cover never becomes the thumbnail, so skip the recompute for it.+ if (target === 'cover') await refreshSeriesCoverImage(seriesId);}})().catch((err) => {console.error(`❌ seasonCover filename hook crashed: ${err?.message || err}`);diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 059ed3795c..5bd30e7c47 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -63,6 +63,12 @@ export const STYLE_PROMPT_OVERRIDE_MODE_DEFAULT = 'prepend';// title-screen prompts as the "logo design" cue. Generated from the universe's// style notes on series creation; editable in the bible.export const TITLE_LOGO_MAX = 2000;+// Derived cover thumbnail — the filename of a rendered volume/issue cover,+// stamped by seriesCoverImage.refreshSeriesCoverImage so the pipeline series+// list can show a thumbnail (like the universe reference image) without+// scanning every issue at read time. Server-set/derived only — never accepted+// from a route body. Sized to RENDER_FILENAME_MAX (renderSlot.js).+export const COVER_IMAGE_MAX = 500;export const AUTHOR_MAX = 120;// FK to an Author persona (auth-<uuid>). The `author` string above stays as a// denormalized byline so a federated series renders the cover correctly even@@ -188,6 +194,13 @@ const sanitizeSeries = (raw) => {// (which predate this field) migrate forward without a writer pass.styleGuide: sanitizeStyleGuide(raw.styleGuide),titleLogo: trimTo(raw.titleLogo, TITLE_LOGO_MAX),+ // Derived cover thumbnail filename (a rendered volume/issue cover). Stamped+ // by the cover filename hooks + the one-time boot backfill via+ // setSeriesCoverImage; null until a cover renders. Additive + gracefully+ // degrading (a pre-feature peer's sanitizeSeries drops it), but wire-gated+ // (pipelineSeries schema v5) so an older peer can't strip-then-LWW the+ // pointer back onto a newer peer.+ coverImage: trimTo(raw.coverImage, COVER_IMAGE_MAX) || null,author: trimTo(raw.author, AUTHOR_MAX),authorId: trimTo(raw.authorId, AUTHOR_ID_MAX) || null,// Per-series override that prepends ahead of the linked universe's@@ -534,6 +547,32 @@ export async function setArcFieldLock(id, field, locked) {});}+/**+ * Stamp the derived cover thumbnail (a rendered volume/issue cover filename)+ * onto the series record so the pipeline list can show a thumbnail without+ * scanning issues at read time. Server-set/derived only — see+ * seriesCoverImage.refreshSeriesCoverImage for the recompute that calls this.+ *+ * No-op (no write, no `recordUpdated` emit) when the value is unchanged so+ * repeat cover renders for an already-decorated series don't churn the record+ * or re-broadcast to peers. Mirrors the empty-patch fast-path in+ * `updateSeasonOnSeries`.+ */+export async function setSeriesCoverImage(id, filename) {+ const next = isStr(filename) && filename ? filename.slice(0, COVER_IMAGE_MAX) : null;+ return store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);+ if ((cur.coverImage || null) === next) return cur; // no-op guard+ const merged = sanitizeSeries({ ...cur, coverImage: next, updatedAt: new Date().toISOString() });+ if (!merged) throw makeErr('Invalid series payload', ERR_VALIDATION);+ await store().saveOneNow(merged.id, merged);+ emitRecordUpdated('series', merged.id);+ return merged;+ });+}+/*** Apply a structured patch to one season inside a series. Routes through the* per-series collection-store queue so a season-cover render PATCH, thediff --git a/server/services/pipeline/seriesCoverImage.js b/server/services/pipeline/seriesCoverImage.jsnew file mode 100644index 0000000000..26ed62608f--- /dev/null+++ b/server/services/pipeline/seriesCoverImage.js@@ -0,0 +1,88 @@+/**+ * Pipeline — derive a series' cover thumbnail.+ *+ * The pipeline series list (client/src/pages/Pipeline.jsx) shows a small cover+ * thumbnail on each series card, mirroring the reference-image thumbnail on the+ * universe list. Rather than scan every issue at read time, the chosen cover+ * filename is persisted onto `series.coverImage` (see series.setSeriesCoverImage)+ * so the list endpoint stays cheap — this module owns the *recompute*.+ *+ * Priority: the first rendered VOLUME (season) cover, else the earliest rendered+ * ISSUE cover. Volume covers win because they're the trade-paperback "graphic+ * novel" cover; per-issue covers are the fallback for series that haven't+ * assembled a volume yet. Back covers never count — the thumbnail is the front.+ *+ * `refreshSeriesCoverImage` is called from the two cover filename hooks+ * (comicPagesFilenameHook, seasonCoverFilenameHook) on render completion, and+ * from the one-time boot backfill (server/scripts/backfillSeriesCoverImages.js).+ * Season covers live on the series record itself, so a series that has any+ * rendered volume cover never pays the issue scan.+ */++import { pickRenderedFilename } from '../../lib/renderSlot.js';+import { getSeries, setSeriesCoverImage } from './series.js';+import { listIssues } from './issues.js';++/**+ * First rendered volume (season) cover, in season order. Seasons live on the+ * series record, so this needs no extra I/O.+ */+export function pickVolumeCoverFilename(seasons) {+ if (!Array.isArray(seasons)) return null;+ for (const season of seasons) {+ const filename = pickRenderedFilename(season?.cover);+ if (filename) return filename;+ }+ return null;+}++/**+ * Earliest rendered issue cover, by issue number ascending. Deleted issues are+ * skipped. Sorts a copy so callers can pass the list straight from `listIssues`.+ */+export function pickIssueCoverFilename(issues) {+ if (!Array.isArray(issues)) return null;+ const ordered = [...issues]+ .filter((i) => i && !i.deleted)+ .sort((a, b) => (a.number ?? Infinity) - (b.number ?? Infinity));+ for (const issue of ordered) {+ const filename = pickRenderedFilename(issue?.stages?.comicPages?.cover);+ if (filename) return filename;+ }+ return null;+}++/**+ * Pure derivation over already-loaded data: volume cover wins, else earliest+ * issue cover, else null. Used by the boot backfill, which loads every issue+ * once and groups by series. The runtime `refreshSeriesCoverImage` does NOT use+ * this — it short-circuits the issue load when a volume cover exists, so it+ * composes the pickers directly.+ */+export function deriveSeriesCoverImage({ seasons, issues } = {}) {+ return pickVolumeCoverFilename(seasons) || pickIssueCoverFilename(issues) || null;+}++/**+ * Recompute and persist a series' cover thumbnail. Cheap when a volume cover+ * exists (no issue scan); otherwise scans the series' issues for the earliest+ * rendered cover. setSeriesCoverImage no-ops when the value is unchanged, so a+ * repeat render on an already-decorated series writes nothing. Best-effort —+ * a cosmetic thumbnail must never fail the user's render.+ */+export async function refreshSeriesCoverImage(seriesId) {+ if (!seriesId) return;+ const series = await getSeries(seriesId).catch(() => null);+ if (!series) return;+ // Volume covers win and are already on the record — skip the issue scan+ // entirely when one exists (keeps the common path cheap).+ let next = pickVolumeCoverFilename(series.seasons);+ if (!next) {+ const issues = await listIssues({ seriesId }).catch(() => []);+ next = pickIssueCoverFilename(issues);+ }+ if ((series.coverImage || null) === (next || null)) return;+ await setSeriesCoverImage(seriesId, next || null).catch((err) => {+ console.error(`❌ refreshSeriesCoverImage failed for series=${String(seriesId).slice(0, 8)}: ${err?.message || err}`);+ });+}diff --git a/server/services/pipeline/seriesCoverImage.test.js b/server/services/pipeline/seriesCoverImage.test.jsnew file mode 100644index 0000000000..8a01999229--- /dev/null+++ b/server/services/pipeline/seriesCoverImage.test.js@@ -0,0 +1,151 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the two heavy service deps so this stays a fast unit test — series.js+// pulls in the store + sharing graph, issues.js the issue store.+const getSeries = vi.fn();+const setSeriesCoverImage = vi.fn();+const listIssues = vi.fn();++vi.mock('./series.js', () => ({+ getSeries: (...a) => getSeries(...a),+ setSeriesCoverImage: (...a) => setSeriesCoverImage(...a),+}));+vi.mock('./issues.js', () => ({+ listIssues: (...a) => listIssues(...a),+}));++const {+ pickVolumeCoverFilename,+ pickIssueCoverFilename,+ deriveSeriesCoverImage,+ refreshSeriesCoverImage,+} = await import('./seriesCoverImage.js');++// A cover-like record with a rendered image in the given slot.+const final = (filename) => ({ finalImage: { filename } });+const proof = (filename) => ({ proofImage: { filename } });++describe('pickVolumeCoverFilename', () => {+ it('returns the first rendered season cover in season order', () => {+ const seasons = [+ { cover: null },+ { cover: final('vol2.png') },+ { cover: final('vol3.png') },+ ];+ expect(pickVolumeCoverFilename(seasons)).toBe('vol2.png');+ });++ it('prefers finalImage but falls back to proofImage', () => {+ expect(pickVolumeCoverFilename([{ cover: proof('proof.png') }])).toBe('proof.png');+ });++ it('returns null when no season has a rendered cover', () => {+ expect(pickVolumeCoverFilename([{ cover: null }, { cover: { script: 'x' } }])).toBeNull();+ });++ it('tolerates a non-array', () => {+ expect(pickVolumeCoverFilename(undefined)).toBeNull();+ expect(pickVolumeCoverFilename(null)).toBeNull();+ });+});++describe('pickIssueCoverFilename', () => {+ const issue = (number, cover, extra = {}) => ({ number, stages: { comicPages: { cover } }, ...extra });++ it('returns the earliest-numbered rendered issue cover regardless of input order', () => {+ const issues = [+ issue(3, final('iss3.png')),+ issue(1, final('iss1.png')),+ issue(2, final('iss2.png')),+ ];+ expect(pickIssueCoverFilename(issues)).toBe('iss1.png');+ });++ it('skips issues without a rendered cover and deleted issues', () => {+ const issues = [+ issue(1, null),+ issue(2, final('iss2.png'), { deleted: true }),+ issue(3, final('iss3.png')),+ ];+ expect(pickIssueCoverFilename(issues)).toBe('iss3.png');+ });++ it('returns null when no issue has a rendered cover', () => {+ expect(pickIssueCoverFilename([issue(1, null), issue(2, { script: 'x' })])).toBeNull();+ });++ it('tolerates a non-array and missing stages', () => {+ expect(pickIssueCoverFilename(null)).toBeNull();+ expect(pickIssueCoverFilename([{ number: 1 }])).toBeNull();+ });+});++describe('deriveSeriesCoverImage', () => {+ it('prefers a volume cover over an issue cover', () => {+ const out = deriveSeriesCoverImage({+ seasons: [{ cover: final('vol.png') }],+ issues: [{ number: 1, stages: { comicPages: { cover: final('iss.png') } } }],+ });+ expect(out).toBe('vol.png');+ });++ it('falls back to the issue cover when no volume cover exists', () => {+ const out = deriveSeriesCoverImage({+ seasons: [{ cover: null }],+ issues: [{ number: 1, stages: { comicPages: { cover: final('iss.png') } } }],+ });+ expect(out).toBe('iss.png');+ });++ it('returns null when neither exists', () => {+ expect(deriveSeriesCoverImage({ seasons: [], issues: [] })).toBeNull();+ expect(deriveSeriesCoverImage()).toBeNull();+ });+});++describe('refreshSeriesCoverImage', () => {+ beforeEach(() => {+ getSeries.mockReset();+ setSeriesCoverImage.mockReset();+ listIssues.mockReset();+ setSeriesCoverImage.mockResolvedValue(undefined);+ });++ it('uses the volume cover and does NOT scan issues when one exists', async () => {+ getSeries.mockResolvedValue({ id: 'ser-1', coverImage: null, seasons: [{ cover: final('vol.png') }] });+ await refreshSeriesCoverImage('ser-1');+ expect(setSeriesCoverImage).toHaveBeenCalledWith('ser-1', 'vol.png');+ expect(listIssues).not.toHaveBeenCalled();+ });++ it('falls back to scanning issues when there is no volume cover', async () => {+ getSeries.mockResolvedValue({ id: 'ser-1', coverImage: null, seasons: [] });+ listIssues.mockResolvedValue([+ { number: 2, stages: { comicPages: { cover: final('iss2.png') } } },+ { number: 1, stages: { comicPages: { cover: final('iss1.png') } } },+ ]);+ await refreshSeriesCoverImage('ser-1');+ expect(listIssues).toHaveBeenCalledWith({ seriesId: 'ser-1' });+ expect(setSeriesCoverImage).toHaveBeenCalledWith('ser-1', 'iss1.png');+ });++ it('no-ops the write when the derived cover is unchanged', async () => {+ getSeries.mockResolvedValue({ id: 'ser-1', coverImage: 'vol.png', seasons: [{ cover: final('vol.png') }] });+ await refreshSeriesCoverImage('ser-1');+ expect(setSeriesCoverImage).not.toHaveBeenCalled();+ });++ it('clears a stale pointer to null when no cover remains', async () => {+ getSeries.mockResolvedValue({ id: 'ser-1', coverImage: 'old.png', seasons: [] });+ listIssues.mockResolvedValue([]);+ await refreshSeriesCoverImage('ser-1');+ expect(setSeriesCoverImage).toHaveBeenCalledWith('ser-1', null);+ });++ it('is a no-op for a missing series or empty id', async () => {+ getSeries.mockResolvedValue(null);+ await refreshSeriesCoverImage('ser-x');+ await refreshSeriesCoverImage('');+ expect(setSeriesCoverImage).not.toHaveBeenCalled();+ });+});