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(pipeline): print-ready PDF export for comic issues
[._.]/ Adam Eivy8d5e30210ff8
diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsxindex 8ea307abc1..b3bd268466 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx@@ -9,7 +9,7 @@import { useCallback, useEffect, useMemo, useState } from 'react';import { useSearchParams } from 'react-router-dom';-import { Loader2, Sparkles, ImageIcon, Save, Trash2, ChevronDown, ChevronRight, Settings as SettingsIcon } from 'lucide-react';+import { Loader2, Sparkles, ImageIcon, Save, Trash2, ChevronDown, ChevronRight, Settings as SettingsIcon, FileDown } from 'lucide-react';import toast from '../../ui/Toast';import {generatePipelineStage,@@ -260,6 +260,11 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions}};+ const pdfRenderedCount = pages.filter((p) => p?.filename).length+ + (comicPages.cover?.filename ? 1 : 0);+ const pdfTotal = pages.length + (comicPages.cover ? 1 : 0);+ const pdfReady = pdfRenderedCount > 0;+return (<div className="space-y-4"><header className="flex items-center justify-between gap-3 flex-wrap">@@ -302,6 +307,22 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actionsSplit into pages</button>) : null}+ <a+ href={pdfReady ? `/api/pipeline/issues/${encodeURIComponent(issue.id)}/comic.pdf` : undefined}+ aria-disabled={!pdfReady}+ onClick={(e) => { if (!pdfReady) e.preventDefault(); }}+ title={pdfReady+ ? `Download a print-ready PDF (${pdfRenderedCount}/${pdfTotal} rendered)`+ : 'Render at least one page or the cover first'}+ className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm ${+ pdfReady+ ? 'bg-port-card border-port-border text-white hover:border-port-accent/50'+ : 'bg-port-card border-port-border text-gray-500 cursor-not-allowed'+ }`}+ >+ <FileDown size={14} />+ </a><buttontype="button"onClick={handleGenerate}diff --git a/server/package.json b/server/package.jsonindex 75fe1e5e6a..c874204468 100644--- a/server/package.json+++ b/server/package.json@@ -15,6 +15,7 @@"googleapis": "171.4.0","kokoro-js": "1.2.1","node-pty": "1.2.0-beta.10",+ "pdf-lib": "^1.17.1","pg": "8.19.0","pm2": "5.4.3","sax": "1.4.4",diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 77c8447b2c..af26bc2b51 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -50,6 +50,7 @@ import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipelimport { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';import { extractScenes, SOURCE_KIND } from '../lib/sceneExtractor.js';import { listVisualStyles } from '../lib/visualStyles.js';+import { buildComicPdf, PAGE_SIZES, DEFAULT_PAGE_SIZE, ERR_NO_RENDERED_PAGES } from '../services/pipeline/comicPdf.js';import { parseComicScript } from '../lib/comicScriptParser.js';import {LENGTH_PROFILE_NAMES,@@ -71,6 +72,7 @@ const SERVICE_ERROR_STATUS = {[seasonsSvc.ERR_REASSIGN_TARGET]: 400,[arcPlanner.ERR_VALIDATION]: 400,[ERR_NO_STORYBOARDS]: 400,+ [ERR_NO_RENDERED_PAGES]: 409,};const mapServiceError = (err) => {@@ -1046,6 +1048,26 @@ router.post('/issues/:id/stages/comicPages/pages/:pageIndex/render', asyncHandleres.json({ ...result, issue: updatedIssue, stage });}));+// Print-ready PDF export of a comic issue's rendered pages. Streams the+// assembled PDF straight to the response — no on-disk artifact, so a new+// render is always a fresh assembly. ?size= picks paper format+// (us-letter|a4|tabloid). 409 when the issue has no rendered cover/pages.+router.get('/issues/:id/comic.pdf', asyncHandler(async (req, res) => {+ const sizeRaw = typeof req.query.size === 'string' ? req.query.size : '';+ const size = PAGE_SIZES[sizeRaw] ? sizeRaw : DEFAULT_PAGE_SIZE;+ const includeCover = req.query.cover !== 'skip';+ const includeColophon = req.query.colophon !== 'skip';+ const { bytes, filename } = await buildComicPdf(req.params.id, {+ size, includeCover, includeColophon,+ }).catch((err) => { throw mapServiceError(err); });+ res.setHeader('Content-Type', 'application/pdf');+ res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);+ res.setHeader('Content-Length', String(bytes.length));+ // Zero-copy aliasing: Buffer shares the Uint8Array's ArrayBuffer instead of+ // duplicating tens of MB for a multi-page PDF.+ res.end(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));+}));+// AI-driven prompt refinement for a single comic panel. Uses// pipeline-comic-panel-image-prompt stage to elaborate the panel's existing// description into a richer image-gen prompt, then persists the result ondiff --git a/server/services/pipeline/comicPdf.js b/server/services/pipeline/comicPdf.jsnew file mode 100644index 0000000000..af6856307e--- /dev/null+++ b/server/services/pipeline/comicPdf.js@@ -0,0 +1,168 @@+/**+ * Assemble a print-ready PDF from a comic issue's rendered cover + pages.+ * Filenames come from `stages.comicPages.cover.filename` and+ * `stages.comicPages.pages[].filename`, stamped by the comic-pages filename+ * hook at media-job completion. Pages without a filename are skipped — the+ * route surfaces "X of Y rendered" to the user before download.+ */++import { join } from 'path';+import { readFile } from 'fs/promises';+import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';+import { PATHS, assertSafeFilename } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { slugifyForFilename } from '../../lib/civitai.js';+import { getIssue } from './issues.js';+import { getSeries } from './series.js';+import { resolveVisualStyle } from '../../lib/visualStyles.js';++export const PAGE_SIZES = Object.freeze({+ 'us-letter': { width: 612, height: 792 },+ 'a4': { width: 595.28, height: 841.89 },+ 'tabloid': { width: 792, height: 1224 },+});+export const DEFAULT_PAGE_SIZE = 'us-letter';++export const ERR_NO_RENDERED_PAGES = 'PIPELINE_COMIC_PDF_NO_PAGES';+const makeErr = (message, code) => Object.assign(new Error(message), { code });++const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47]);+const JPEG_MAGIC = Buffer.from([0xff, 0xd8, 0xff]);+const IMAGE_EXTS = Object.freeze(['.png', '.jpg', '.jpeg']);++// Magic-byte sniff so a .png-named file that's actually JPEG (or vice versa)+// still embeds correctly. Falls back to extension only when sniff is inconclusive.+function detectImageKind(bytes, filename) {+ if (bytes.length >= 4 && bytes.subarray(0, 4).equals(PNG_MAGIC)) return 'png';+ if (bytes.length >= 3 && bytes.subarray(0, 3).equals(JPEG_MAGIC)) return 'jpg';+ const ext = (filename || '').toLowerCase();+ if (ext.endsWith('.png')) return 'png';+ if (ext.endsWith('.jpg') || ext.endsWith('.jpeg')) return 'jpg';+ return null;+}++async function readImageFromMedia(filename) {+ assertSafeFilename(filename, { extensions: IMAGE_EXTS, subject: 'comic page image' });+ return readFile(join(PATHS.images, filename));+}++async function embedImageBytes(pdf, bytes, filename) {+ const kind = detectImageKind(bytes, filename);+ if (kind === 'png') return pdf.embedPng(bytes);+ if (kind === 'jpg') return pdf.embedJpg(bytes);+ throw new ServerError(`Unsupported image format for "${filename}" — expected PNG or JPEG`, {+ status: 415, code: 'PIPELINE_COMIC_PDF_UNSUPPORTED_IMAGE',+ });+}++// White margin reads as "edition" rather than "raw print plate" and avoids+// cropping signed art on the page edges.+function fitImage(imgW, imgH, pageW, pageH, marginPt = 18) {+ const availW = pageW - marginPt * 2;+ const availH = pageH - marginPt * 2;+ const scale = Math.min(availW / imgW, availH / imgH);+ const drawW = imgW * scale;+ const drawH = imgH * scale;+ return {+ x: (pageW - drawW) / 2,+ y: (pageH - drawH) / 2,+ width: drawW,+ height: drawH,+ };+}++/**+ * @returns {{ bytes: Uint8Array, pageCount: number, filename: string }}+ */+export async function buildComicPdf(issueId, opts = {}) {+ const issue = await getIssue(issueId);+ const series = await getSeries(issue.seriesId);++ const sizeKey = PAGE_SIZES[opts.size] ? opts.size : DEFAULT_PAGE_SIZE;+ const { width: pageW, height: pageH } = PAGE_SIZES[sizeKey];+ const includeCover = opts.includeCover !== false;+ const includeColophon = opts.includeColophon !== false;++ const comicPages = issue.stages?.comicPages || {};+ const cover = includeCover ? comicPages.cover : null;+ const pages = Array.isArray(comicPages.pages) ? comicPages.pages : [];+ const renderedPages = pages.filter((p) => p && typeof p.filename === 'string' && p.filename);++ const targets = [];+ if (cover?.filename) targets.push(cover.filename);+ for (const p of renderedPages) targets.push(p.filename);+ if (targets.length === 0) {+ throw makeErr('Issue has no rendered pages or cover yet', ERR_NO_RENDERED_PAGES);+ }++ // Read all files concurrently — disk I/O parallelizes cleanly; pdf-lib's+ // embed is CPU-bound on the event loop so embedding stays sequential below.+ // One bad page must not fail the whole download, so errors are captured+ // alongside the bytes and logged when the loop reaches them.+ const loaded = await Promise.all(targets.map((filename) =>+ readImageFromMedia(filename)+ .then((bytes) => ({ filename, bytes }))+ .catch((err) => ({ filename, err })),+ ));++ const pdf = await PDFDocument.create();+ if (series.name || issue.title) {+ pdf.setTitle(`${series.name || 'Untitled'} #${issue.number || 1} — ${issue.title || ''}`.trim());+ }+ if (series.logline) pdf.setSubject(series.logline);+ pdf.setProducer('PortOS');+ pdf.setCreator('PortOS pipeline');++ let pageCount = 0;+ for (const entry of loaded) {+ if (entry.err) {+ console.error(`❌ comicPdf — skipped "${entry.filename}": ${entry.err.message || entry.err}`);+ continue;+ }+ const img = await embedImageBytes(pdf, entry.bytes, entry.filename).catch((err) => {+ console.error(`❌ comicPdf — embed failed "${entry.filename}": ${err.message || err}`);+ return null;+ });+ if (!img) continue;+ const page = pdf.addPage([pageW, pageH]);+ page.drawImage(img, fitImage(img.width, img.height, pageW, pageH));+ pageCount += 1;+ }++ if (pageCount === 0) {+ throw makeErr('No usable pages — all embeds failed', ERR_NO_RENDERED_PAGES);+ }++ if (includeColophon) {+ const colophon = pdf.addPage([pageW, pageH]);+ const font = await pdf.embedFont(StandardFonts.Helvetica);+ const fontBold = await pdf.embedFont(StandardFonts.HelveticaBold);+ const left = 72;+ let cursor = pageH - 144;+ const drawLine = (text, { size = 11, bold = false, color = rgb(0.2, 0.2, 0.2) } = {}) => {+ colophon.drawText(text, { x: left, y: cursor, size, font: bold ? fontBold : font, color });+ cursor -= size + 8;+ };+ drawLine(series.name || 'Untitled Series', { size: 22, bold: true, color: rgb(0, 0, 0) });+ drawLine(`Issue #${issue.number || 1} — ${issue.title || ''}`.trim(), { size: 14, bold: true });+ cursor -= 12;+ if (series.logline) drawLine(`Logline: ${series.logline}`, { size: 10 });+ drawLine(`Generated: ${new Date().toISOString().slice(0, 19).replace('T', ' ')} UTC`, { size: 10 });+ const style = resolveVisualStyle(series, issue, 'comicPages');+ if (style?.name) drawLine(`Visual style: ${style.name}`, { size: 10 });+ drawLine(`Page count (rendered art): ${pageCount}`, { size: 10 });+ cursor -= 16;+ drawLine('Generated by PortOS pipeline.', { size: 9, color: rgb(0.45, 0.45, 0.45) });+ pageCount += 1;+ }++ const bytes = await pdf.save();+ return { bytes, pageCount, filename: buildPdfFilename(series, issue) };+}++function buildPdfFilename(series, issue) {+ const seriesSlug = slugifyForFilename(series.name || 'series');+ const num = String(issue.number || 1).padStart(2, '0');+ const titleSlug = issue.title ? slugifyForFilename(issue.title) : '';+ return titleSlug ? `${seriesSlug}-${num}-${titleSlug}.pdf` : `${seriesSlug}-${num}.pdf`;+}diff --git a/server/services/pipeline/comicPdf.test.js b/server/services/pipeline/comicPdf.test.jsnew file mode 100644index 0000000000..b0b9517ae1--- /dev/null+++ b/server/services/pipeline/comicPdf.test.js@@ -0,0 +1,170 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdir, writeFile, rm } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';++const TEST_HOME = join(tmpdir(), `portos-comicpdf-test-${process.pid}-${Date.now()}`);+const FAKE_IMAGES_DIR = join(TEST_HOME, 'images');++vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ return {+ ...actual,+ PATHS: { ...actual.PATHS, images: FAKE_IMAGES_DIR },+ };+});++// 1×1 RGBA PNG — smallest valid PNG pdf-lib will accept via embedPng.+const TINY_PNG = Buffer.from([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,+ 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,+ 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41,+ 0x54, 0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00,+ 0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00,+ 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae,+ 0x42, 0x60, 0x82,+]);++const mockIssue = {+ id: 'iss-test',+ seriesId: 'ser-test',+ number: 3,+ title: 'The Brass Key',+ stages: {+ comicPages: {+ cover: { filename: 'cover.png' },+ pages: [+ { filename: 'page1.png' },+ { filename: 'page2.png' },+ ],+ },+ },+};++const mockSeries = {+ id: 'ser-test',+ name: 'Bone Walker',+ logline: 'A cult, a city, a child.',+ visualStyleDefault: { id: 'graphic-novel', customPrompt: null },+};++const getIssueMock = vi.fn(async () => structuredClone(mockIssue));+const getSeriesMock = vi.fn(async () => structuredClone(mockSeries));+vi.mock('./issues.js', () => ({+ getIssue: (...a) => getIssueMock(...a),+ VISUAL_STAGE_IDS: ['comicPages', 'storyboards', 'episodeVideo'],+ STAGE_IDS: ['idea', 'prose', 'comicScript', 'teleplay', 'comicPages', 'storyboards', 'episodeVideo'],+}));+vi.mock('./series.js', () => ({+ getSeries: (...a) => getSeriesMock(...a),+}));++const { buildComicPdf, PAGE_SIZES, DEFAULT_PAGE_SIZE, ERR_NO_RENDERED_PAGES } = await import('./comicPdf.js');++beforeEach(async () => {+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });+ await writeFile(join(FAKE_IMAGES_DIR, 'cover.png'), TINY_PNG);+ await writeFile(join(FAKE_IMAGES_DIR, 'page1.png'), TINY_PNG);+ await writeFile(join(FAKE_IMAGES_DIR, 'page2.png'), TINY_PNG);+ getIssueMock.mockClear();+ getSeriesMock.mockClear();+});++afterEach(async () => {+ await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});+});++describe('PAGE_SIZES catalog', () => {+ it('exposes the three named paper sizes with non-zero dimensions', () => {+ expect(Object.keys(PAGE_SIZES)).toEqual(['us-letter', 'a4', 'tabloid']);+ for (const k of Object.keys(PAGE_SIZES)) {+ expect(PAGE_SIZES[k].width).toBeGreaterThan(0);+ expect(PAGE_SIZES[k].height).toBeGreaterThan(0);+ }+ });++ it('DEFAULT_PAGE_SIZE is a valid catalog key', () => {+ expect(PAGE_SIZES[DEFAULT_PAGE_SIZE]).toBeTruthy();+ });+});++describe('buildComicPdf — happy path', () => {+ it('produces a PDF with cover + 2 pages + colophon = 4 pages', async () => {+ const { bytes, pageCount, filename } = await buildComicPdf('iss-test');+ expect(pageCount).toBe(4);+ expect(filename).toBe('bone-walker-03-the-brass-key.pdf');+ expect(bytes.length).toBeGreaterThan(100);+ expect(Buffer.from(bytes).subarray(0, 4).toString()).toBe('%PDF');+ });++ it('omits the colophon when includeColophon=false', async () => {+ const { pageCount } = await buildComicPdf('iss-test', { includeColophon: false });+ expect(pageCount).toBe(3);+ });++ it('omits the cover when includeCover=false', async () => {+ const { pageCount } = await buildComicPdf('iss-test', { includeCover: false });+ expect(pageCount).toBe(3); // 2 pages + colophon+ });++ it('falls back to default size for unknown size keys', async () => {+ const a4 = await buildComicPdf('iss-test', { size: 'a4' });+ const fallback = await buildComicPdf('iss-test', { size: 'not-a-size' });+ expect(a4.pageCount).toBe(fallback.pageCount);+ });++ it('skips pages whose file is missing but still produces the PDF', async () => {+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue),+ stages: {+ comicPages: {+ cover: { filename: 'cover.png' },+ pages: [+ { filename: 'page1.png' },+ { filename: 'does-not-exist.png' },+ ],+ },+ },+ });+ const { pageCount } = await buildComicPdf('iss-test');+ expect(pageCount).toBe(3); // cover + page1 + colophon — page2 (missing) skipped+ });++ it('uses series name + issue number in the filename when no title', async () => {+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue),+ title: '',+ });+ const { filename } = await buildComicPdf('iss-test');+ expect(filename).toBe('bone-walker-03.pdf');+ });+});++describe('buildComicPdf — rejection paths', () => {+ it('throws ERR_NO_RENDERED_PAGES when neither cover nor pages have filenames', async () => {+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue),+ stages: { comicPages: { cover: null, pages: [{ filename: '' }] } },+ });+ await expect(buildComicPdf('iss-test')).rejects.toMatchObject({ code: ERR_NO_RENDERED_PAGES });+ });++ it('throws ERR_NO_RENDERED_PAGES when every page-file embed fails', async () => {+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue),+ stages: {+ comicPages: {+ cover: null,+ pages: [+ { filename: 'missing-1.png' },+ { filename: 'missing-2.png' },+ ],+ },+ },+ });+ await expect(buildComicPdf('iss-test', { includeColophon: false }))+ .rejects.toMatchObject({ code: ERR_NO_RENDERED_PAGES });+ });+});