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(pipeline): Vonnegut story shapes, Series Pipeline UX, stale-build socket detection

[._.]/ Adam Eivy8bb6d0617a6c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6890d577d9..1a0741734c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,50 @@
## Added
+- **Series Pipeline — Vonnegut story-shape picker + sparkline visualization.**
+ Series records can now carry an explicit narrative-shape decision drawn from
+ Kurt Vonnegut's eight story shapes (Rags to Riches, Tragedy, Man in Hole,
+ Icarus, Cinderella, Oedipus, Boy Meets Girl, Creation Story). New
+ `series.arc.shape` field; each shape has a label, one-line description, and
+ a normalized 7-point [-1, 1] series that drives a small inline SVG sparkline.
+ Picker is a 2×4 grid of toggle chips; re-clicking the selected shape clears
+ it back to none. Rendered both inline in the create-series form (new row
+ alongside the new `Story size` issue/episode-count input — both fields
+ thread into the create payload, falling through to server defaults when
+ empty) and on the arc-canvas header + edit form for existing series. Each
+ series card on the Series Pipeline index shows the shape as a small chip
+ next to the name when set. **Files:** new `client/src/components/pipeline/StoryShapes.jsx`
+ (display metadata + `ArcShapeSparkline` + `ArcShapePicker`), new
+ `ARC_SHAPE_IDS` export in `server/lib/storyArc.js`, `shape` field on the
+ arc sanitizer (treated as identifying content — a "shape only" arc survives
+ so an explicit narrative-design choice at create time isn't silently
+ dropped), schema parity in `server/routes/pipeline.js` (`arcSchema.shape`),
+ and arc-resolve LLM merge preserves shape across LLM rewrites
+ (`server/services/pipeline/arcPlanner.js`).
+
+- **Stale-build detection — Socket.IO `build:id` event + Vite preload-error catch.**
+ The "Failed to fetch dynamically imported module" red error screen after a
+ server restart now self-resolves without user action. Two layers:
+ - **Build-ID broadcast.** `server/lib/buildId.js` hashes `client/dist/index.html`
+ once at boot (the file changes every Vite build because it embeds the
+ bundle-hash filenames), injects `<meta name="portos-build-id" content="…">`
+ into the served HTML, and exposes `getBuildId()` to the socket service.
+ `express.static(CLIENT_DIST, { index: false })` so `/` flows through the
+ SPA-fallback handler (which serves the stamped HTML) instead of being
+ short-circuited by static. `initSocket` emits `build:id` on every connect.
+ Client reads its embedded build id from the meta tag and on mismatch shows
+ a sticky toast ("New build available. [Reload]") with a manual reload
+ button — protects unsaved input. JSX-bearing toast extracted to
+ `staleBuildToast.jsx` so `socket.js` stays JS.
+ - **`vite:preloadError` listener in main.jsx.** Catches the chunk-preload
+ 404 *before* it propagates to React's error boundary, falls through to
+ `reloadOnceForStaleChunk()`. Anti-loop guard now keys its sessionStorage
+ flag on the build id (was a single session-wide one-shot, which left the
+ user stranded on the error screen after a second rebuild — a fresh build
+ now gets a fresh reload attempt). Same handler also runs on
+ `unhandledrejection` so a stale-chunk rejection outside React's tree is
+ caught too.
+
- **Comic Pages — rendered filename persisted on the record (survives queue TTL).**
Comic-page records previously stored only `imageJobId`. After the
mediaJobQueue's 24-hour archive TTL, the UI could no longer resolve
@@ -676,6 +720,17 @@
versions, `data/migrations/003-*.js`, and `data/runs/*/metadata.json`
left as-is (record of past work, not current state).
+- **Series Pipeline index — renamed + cards wrap + shape visible.** The
+ `/pipeline` page is now titled **Series Pipeline** (matching the URL's
+ intent — the page lists series in a pipeline, not just a generic
+ "Pipeline"); sidebar label + nav-manifest label updated in lockstep
+ (existing `pipeline` / `series` / `series-pipeline` aliases keep ⌘K and
+ voice navigation working). Series rows no longer truncate — name uses
+ `flex-wrap` so the shape chip can sit beside it, and the logline wraps
+ with `whitespace-pre-wrap break-words` for full-length descriptions. Each
+ card with `series.arc.shape` set renders an inline shape badge (40×14
+ sparkline + uppercase label) next to the series name.
+
- **Sidebar nav: "Pipeline" → "Series".** Label change only — URLs,
files, server routes, and API endpoints all retain the `pipeline`
namespace because the inner Series record already owns the word
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 7ac7ee1024..832891f241 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -195,7 +195,7 @@ const navItems = [
defaultTo: '/media',
children: [
{ to: '/media', label: 'Media Gen', icon: Layers },
- { to: '/pipeline', label: 'Series', icon: WorkflowIcon, dynamic: 'pipelineSeries' },
+ { to: '/pipeline', label: 'Series Pipeline', icon: WorkflowIcon, dynamic: 'pipelineSeries' },
{ to: '/sharing', label: 'Sharing', icon: Share2 },
{ to: '/universe-builder', label: 'Universe Builder', icon: Globe },
{ to: '/writers-room', label: 'Writers Room', icon: NotebookPen }
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsx
index 3dcfc17773..3e659c6240 100644
--- a/client/src/components/pipeline/ArcCanvas.jsx
+++ b/client/src/components/pipeline/ArcCanvas.jsx
@@ -40,6 +40,7 @@ import {
listPipelineIssues, updatePipelineSeries,
} from '../../services/api';
import SeriesLlmPicker from './SeriesLlmPicker';
+import { ArcShapePicker, ArcShapeSparkline, getStoryShape } from './StoryShapes';
const ISSUE_STATUS_COLORS = {
draft: 'text-gray-400 bg-gray-700/30',
@@ -327,6 +328,11 @@ function ArcContent({ series, onSeriesUpdate }) {
placeholder="Themes (comma-separated)"
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
/>
+ <ArcShapePicker
+ value={draft.shape || null}
+ onChange={(shape) => setDraft({ ...draft, shape })}
+ disabled={saving}
+ />
<div className="flex items-center gap-2">
<button
type="button"
@@ -350,12 +356,23 @@ function ArcContent({ series, onSeriesUpdate }) {
);
}
+ const shapeDef = arc.shape ? getStoryShape(arc.shape) : null;
+
return (
<div className="space-y-2">
{arc.logline ? <p className="text-sm text-white">{arc.logline}</p> : null}
- {arc.themes?.length ? (
- <div className="flex flex-wrap gap-1.5">
- {arc.themes.map((t) => (
+ {(arc.themes?.length || shapeDef) ? (
+ <div className="flex flex-wrap items-center gap-1.5">
+ {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={48} height={16} />
+ {shapeDef.label}
+ </span>
+ ) : null}
+ {arc.themes?.map((t) => (
<span key={t} className="text-[10px] uppercase tracking-wider px-2 py-0.5 rounded bg-port-bg border border-port-border text-gray-300">
{t}
</span>
diff --git a/client/src/components/pipeline/StoryShapes.jsx b/client/src/components/pipeline/StoryShapes.jsx
new file mode 100644
index 0000000000..5449fd83b1
--- /dev/null
+++ b/client/src/components/pipeline/StoryShapes.jsx
@@ -0,0 +1,135 @@
+/**
+ * Kurt Vonnegut's eight story shapes — the rendering side.
+ *
+ * Server validates `series.arc.shape` against `ARC_SHAPE_IDS` in
+ * `server/lib/storyArc.js`. This file owns the display metadata: label,
+ * one-line description, and a 7-point series in [-1, 1] (where +1 is
+ * "good fortune" and -1 is "ill fortune") that drives the SVG sparkline.
+ *
+ * To add a shape: add an entry here AND to `ARC_SHAPE_IDS` on the server.
+ */
+
+export const STORY_SHAPES = [
+ {
+ id: 'rags-to-riches',
+ label: 'Rags to Riches',
+ description: 'Steady rise from misfortune to triumph.',
+ points: [-1, -0.7, -0.4, -0.1, 0.3, 0.7, 1],
+ },
+ {
+ id: 'tragedy',
+ label: 'Tragedy',
+ description: 'Steady fall from good fortune to ruin.',
+ points: [1, 0.7, 0.4, 0.1, -0.3, -0.7, -1],
+ },
+ {
+ id: 'man-in-hole',
+ label: 'Man in Hole',
+ description: 'Falls into trouble, climbs out better than before.',
+ points: [0.4, 0, -0.6, -1, -0.5, 0.3, 0.9],
+ },
+ {
+ id: 'icarus',
+ label: 'Icarus',
+ description: 'Soars high, then crashes.',
+ points: [-0.4, 0.2, 0.7, 1, 0.5, -0.2, -1],
+ },
+ {
+ id: 'cinderella',
+ label: 'Cinderella',
+ description: 'Rises, suffers a setback, soars to the highest peak.',
+ points: [-0.7, -0.3, 0.2, 0.5, -0.3, 0.4, 1],
+ },
+ {
+ id: 'oedipus',
+ label: 'Oedipus',
+ description: 'Falls, briefly recovers, falls again to the worst.',
+ points: [0.3, -0.2, -0.7, 0.2, 0.5, 0, -1],
+ },
+ {
+ id: 'boy-meets-girl',
+ label: 'Boy Meets Girl',
+ description: 'Gets the thing, loses it, gets it back for good.',
+ points: [0, 0.6, 0.9, 0.2, -0.5, 0.3, 0.9],
+ },
+ {
+ id: 'creation-story',
+ label: 'Creation Story',
+ description: 'Stepped ascent — each plateau a new world.',
+ points: [-1, -1, -0.4, -0.4, 0.3, 0.3, 1],
+ },
+];
+
+const SHAPES_BY_ID = new Map(STORY_SHAPES.map((s) => [s.id, s]));
+
+export function getStoryShape(id) {
+ return SHAPES_BY_ID.get(id) || null;
+}
+
+/**
+ * Render a single story-shape curve as an inline SVG sparkline.
+ * `points` is a [-1, 1] series; the renderer maps it into the viewBox and
+ * draws the good-fortune midline behind the curve.
+ */
+export function ArcShapeSparkline({ shape, width = 64, height = 24, className = '', stroke = 'currentColor' }) {
+ const def = typeof shape === 'string' ? getStoryShape(shape) : shape;
+ if (!def) return null;
+ const { points } = def;
+ const n = points.length;
+ const padX = 2;
+ const padY = 3;
+ const innerW = width - padX * 2;
+ const innerH = height - padY * 2;
+ // Map v in [-1, 1] to y in [height - padY, padY] (invert for SVG).
+ const toX = (i) => padX + (i / (n - 1)) * innerW;
+ const toY = (v) => padY + ((1 - v) / 2) * innerH;
+ const d = points.map((v, i) => `${i === 0 ? 'M' : 'L'} ${toX(i).toFixed(2)} ${toY(v).toFixed(2)}`).join(' ');
+ const midY = padY + innerH / 2;
+ return (
+ <svg
+ viewBox={`0 0 ${width} ${height}`}
+ width={width}
+ height={height}
+ className={className}
+ role="img"
+ aria-label={`${def.label} story shape`}
+ >
+ <line x1={padX} x2={width - padX} y1={midY} y2={midY} stroke="currentColor" strokeOpacity={0.15} strokeWidth={1} />
+ <path d={d} fill="none" stroke={stroke} strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ );
+}
+
+/**
+ * Grid of selectable shape chips. Each chip shows the mini sparkline + label
+ * and toggles selection on click. `value === null` means no shape chosen.
+ */
+export function ArcShapePicker({ value, onChange, disabled = false }) {
+ return (
+ <div className="space-y-1.5">
+ <label className="text-[10px] uppercase tracking-wider text-gray-500">Story shape (Vonnegut)</label>
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-1.5">
+ {STORY_SHAPES.map((s) => {
+ const selected = value === s.id;
+ return (
+ <button
+ key={s.id}
+ type="button"
+ onClick={() => onChange(selected ? null : s.id)}
+ disabled={disabled}
+ title={s.description}
+ className={`flex flex-col items-start gap-1 px-2 py-1.5 rounded border text-left transition-colors disabled:opacity-40 ${
+ selected
+ ? 'border-port-accent bg-port-accent/10 text-port-accent'
+ : 'border-port-border bg-port-bg text-gray-300 hover:border-port-accent/40 hover:text-white'
+ }`}
+ >
+ <ArcShapeSparkline shape={s} width={72} height={22} />
+ <span className="text-[10px] uppercase tracking-wider truncate w-full">{s.label}</span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/main.jsx b/client/src/main.jsx
index 6ba777070c..872f7aeff4 100644
--- a/client/src/main.jsx
+++ b/client/src/main.jsx
@@ -4,11 +4,25 @@ import { BrowserRouter } from 'react-router-dom';
import { Toaster } from './components/ui/Toast';
import ErrorBoundary from './components/ErrorBoundary';
import { ThemeProvider } from './components/ThemeContext';
+import { isStaleChunkError, reloadOnceForStaleChunk } from './utils/staleChunkReload';
import App from './App';
import './index.css';
-// Handle unhandled promise rejections
+// Vite emits `vite:preloadError` when a code-split chunk's preload 404s —
+// usually because the server rebuilt and the chunk filename changed while
+// this tab was still open. Catching it here reloads before React's error
+// boundary ever sees the failure.
+window.addEventListener('vite:preloadError', (event) => {
+ if (reloadOnceForStaleChunk()) event.preventDefault?.();
+});
+
+// Handle unhandled promise rejections — also a chance to catch stale chunks
+// that surface as a rejected dynamic-import promise outside React's tree.
window.addEventListener('unhandledrejection', (event) => {
+ if (isStaleChunkError(event.reason) && reloadOnceForStaleChunk()) {
+ event.preventDefault();
+ return;
+ }
console.error(`❌ Unhandled Promise Rejection: ${event.reason}`);
event.preventDefault();
});
diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsx
index 09ea31aff2..23621d37dd 100644
--- a/client/src/pages/Pipeline.jsx
+++ b/client/src/pages/Pipeline.jsx
@@ -22,6 +22,7 @@ import {
WORLD_PREMISE_MAX,
WORLD_STYLE_NOTES_MAX,
} from '../services/api';
+import { ArcShapePicker, ArcShapeSparkline, getStoryShape } from '../components/pipeline/StoryShapes';
const emptyForm = () => ({
name: '',
@@ -29,6 +30,8 @@ const emptyForm = () => ({
logline: '',
premise: '',
styleNotes: '',
+ shape: null,
+ issueCountTarget: '',
});
export default function Pipeline() {
@@ -86,12 +89,15 @@ export default function Pipeline() {
return;
}
setCreating(true);
+ const target = parseInt(form.issueCountTarget, 10);
const created = await createPipelineSeries({
name,
logline: form.logline.trim(),
premise: form.premise.trim(),
styleNotes: form.styleNotes.trim(),
universeId: form.universeId || undefined,
+ issueCountTarget: Number.isFinite(target) && target > 0 ? target : undefined,
+ arc: form.shape ? { shape: form.shape } : undefined,
}).catch((err) => {
toast.error(err.message || 'Failed to create series');
return null;
@@ -128,7 +134,7 @@ export default function Pipeline() {
<div className="flex items-center justify-between mb-6 flex-wrap gap-3">
<div className="flex items-center gap-3">
<WorkflowIcon className="w-6 h-6 text-port-accent" />
- <h1 className="text-2xl font-bold text-white">Series</h1>
+ <h1 className="text-2xl font-bold text-white">Series Pipeline</h1>
</div>
<button
type="button"
@@ -202,6 +208,30 @@ export default function Pipeline() {
maxLength={WORLD_LOGLINE_MAX}
/>
</div>
+ <div className="grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-3 items-start">
+ <ArcShapePicker
+ value={form.shape}
+ onChange={(shape) => setForm((f) => ({ ...f, shape }))}
+ />
+ <div>
+ <label htmlFor="series-issue-count" className="block text-[10px] uppercase tracking-wider text-gray-500 mb-1.5">
+ Story size (issues / episodes)
+ </label>
+ <input
+ id="series-issue-count"
+ type="number"
+ value={form.issueCountTarget}
+ onChange={(e) => setForm((f) => ({ ...f, issueCountTarget: e.target.value }))}
+ placeholder="e.g. 12"
+ min={0}
+ max={999}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ <p className="text-[11px] text-gray-500 mt-1">
+ Target count across the whole arc — guides issue/episode planning.
+ </p>
+ </div>
+ </div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
<label htmlFor="series-premise" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
@@ -258,17 +288,28 @@ export default function Pipeline() {
<div className="text-gray-500 text-sm">No series yet. Click <span className="text-port-accent">New Series</span> to start.</div>
) : (
<ul className="space-y-2">
- {series.map((s) => (
- <li key={s.id} className="flex items-center justify-between gap-3 p-3 bg-port-card border border-port-border rounded-lg hover:border-port-accent/40 transition-colors">
+ {series.map((s) => {
+ 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 truncate flex items-center gap-2">
- <span className="truncate">{s.name}</span>
+ <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 truncate">{s.logline}</div>
+ <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">No logline yet</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">
@@ -287,7 +328,8 @@ export default function Pipeline() {
<Trash2 size={16} />
</button>
</li>
- ))}
+ );
+ })}
</ul>
)}
</div>
diff --git a/client/src/services/socket.js b/client/src/services/socket.js
index 64c5f16921..4443663deb 100644
--- a/client/src/services/socket.js
+++ b/client/src/services/socket.js
@@ -1,4 +1,5 @@
import { io } from 'socket.io-client';
+import { showStaleBuildToast } from './staleBuildToast';
// Connect to Socket.IO using relative path (works with Tailscale)
// The connection will use the same host the page was loaded from
@@ -23,6 +24,24 @@ socket.on('connect_error', () => {
// Connection error - Socket.IO will retry automatically
});
+// Embedded build id from the served index.html. The server injects a
+// <meta name="portos-build-id" content="..."> tag into index.html at boot;
+// a freshly-rebuilt-and-restarted server will have a different id, and the
+// `build:id` socket event below catches the mismatch so the tab can reload.
+const EMBEDDED_BUILD_ID = (() => {
+ if (typeof document === 'undefined') return null;
+ const el = document.querySelector('meta[name="portos-build-id"]');
+ return el ? el.getAttribute('content') : null;
+})();
+
+let staleToastShown = false;
+socket.on('build:id', ({ buildId } = {}) => {
+ if (!buildId || !EMBEDDED_BUILD_ID || buildId === EMBEDDED_BUILD_ID) return;
+ if (staleToastShown) return;
+ staleToastShown = true;
+ showStaleBuildToast();
+});
+
export default socket;
/**
@@ -31,3 +50,10 @@ export default socket;
export function isConnected() {
return socket.connected;
}
+
+/**
+ * The build id the running client was served with. Components that want to
+ * key per-session state to a specific bundle version (e.g. anti-loop guards
+ * in stale-chunk reload) can import this.
+ */
+export const CLIENT_BUILD_ID = EMBEDDED_BUILD_ID;
diff --git a/client/src/services/staleBuildToast.jsx b/client/src/services/staleBuildToast.jsx
new file mode 100644
index 0000000000..152daf36b8
--- /dev/null
+++ b/client/src/services/staleBuildToast.jsx
@@ -0,0 +1,22 @@
+import toast from '../components/ui/Toast';
+
+/**
+ * Sticky toast shown when the server's build id no longer matches the build
+ * id the current tab was served with. Manual reload — we don't auto-refresh
+ * because the user might be mid-typing in a form.
+ */
+export function showStaleBuildToast() {
+ toast(
+ <div className="flex items-center gap-3">
+ <span>New build available.</span>
+ <button
+ type="button"
+ onClick={() => window.location.reload()}
+ className="px-2 py-1 rounded bg-port-accent text-white text-xs font-medium hover:bg-port-accent/80"
+ >
+ Reload
+ </button>
+ </div>,
+ { id: 'portos-stale-build', duration: Infinity },
+ );
+}
diff --git a/client/src/utils/staleChunkReload.js b/client/src/utils/staleChunkReload.js
index 3a09bf3d70..fea5527880 100644
--- a/client/src/utils/staleChunkReload.js
+++ b/client/src/utils/staleChunkReload.js
@@ -20,12 +20,22 @@ export const isStaleChunkError = (err) => {
return STALE_CHUNK_PATTERNS.some(p => msg.includes(p));
};
-// Reloads once per session — sessionStorage guard prevents infinite loops if
-// the new bundle is also broken. Returns true if a reload was triggered.
+// Anti-loop guard: stash the build id we already attempted a reload for. A
+// stale-chunk error in a *different* build (one we haven't yet tried to
+// recover from) still triggers a reload. The old session-wide one-shot
+// guard left the user stuck on the error screen after a second rebuild.
+const getCurrentBuildId = () => {
+ if (typeof document === 'undefined') return null;
+ const el = document.querySelector('meta[name="portos-build-id"]');
+ return el ? el.getAttribute('content') : null;
+};
+
export const reloadOnceForStaleChunk = () => {
- if (sessionStorage.getItem(RELOAD_FLAG)) return false;
- sessionStorage.setItem(RELOAD_FLAG, '1');
- console.warn('🔄 Stale chunk detected — reloading to pick up new bundle');
+ const buildId = getCurrentBuildId();
+ const flag = buildId ? `${buildId}` : '1';
+ if (sessionStorage.getItem(RELOAD_FLAG) === flag) return false;
+ sessionStorage.setItem(RELOAD_FLAG, flag);
+ console.warn(`🔄 Stale chunk detected (build ${buildId || 'unknown'}) — reloading to pick up new bundle`);
window.location.reload();
return true;
};
diff --git a/server/index.js b/server/index.js
index 08bc146ea9..1fd81fc9e8 100644
--- a/server/index.js
+++ b/server/index.js
@@ -8,6 +8,7 @@ import { existsSync } from 'fs';
import { readFile, unlink } from 'fs/promises';
import { createTailscaleServers } from '../lib/tailscale-https.js';
import { getSelfHost } from './lib/peerSelfHost.js';
+import { getBuildId, getStampedIndexHtml } from './lib/buildId.js';
import alertsRoutes from './routes/alerts.js';
import appleHealthRoutes from './routes/appleHealth.js';
@@ -476,17 +477,27 @@ app.use('/data/video-thumbnails', express.static(PATHS.videoThumbnails));
// Serve built client UI (production mode — no Vite dev server needed)
const CLIENT_DIST = join(__dirname, '..', 'client', 'dist');
if (existsSync(CLIENT_DIST)) {
- app.use(express.static(CLIENT_DIST));
+ // `index: false` keeps express.static from short-circuiting `/` (and any
+ // bare directory) with the raw index.html — that path needs to flow through
+ // the splat handler below so the meta-tag injection runs.
+ app.use(express.static(CLIENT_DIST, { index: false }));
// SPA fallback: serve index.html for page navigations only
// Skip asset requests (.js, .css, etc.) so stale chunk requests get a proper 404
- // instead of index.html with text/html MIME type
+ // instead of index.html with text/html MIME type. We serve the stamped HTML
+ // string (with <meta name="portos-build-id"> injected) instead of sendFile
+ // so the bundled JS can read its own build id at boot.
+ const stampedIndexHtml = getStampedIndexHtml();
app.get('/{*splat}', (req, res, next) => {
if (req.path.match(/\.\w+$/) && !req.path.endsWith('.html')) {
return next();
}
- res.sendFile(join(CLIENT_DIST, 'index.html'));
+ if (stampedIndexHtml) {
+ res.type('html').send(stampedIndexHtml);
+ } else {
+ res.sendFile(join(CLIENT_DIST, 'index.html'));
+ }
});
- console.log(`📦 Serving built UI from client/dist`);
+ console.log(`📦 Serving built UI from client/dist (build ${getBuildId()})`);
}
// 404 handler (API routes that didn't match)
diff --git a/server/lib/buildId.js b/server/lib/buildId.js
new file mode 100644
index 0000000000..86c221fae0
--- /dev/null
+++ b/server/lib/buildId.js
@@ -0,0 +1,53 @@
+/**
+ * Build-ID derived from the built client bundle.
+ *
+ * Computed once at server boot from `client/dist/index.html` (the file
+ * changes every Vite build because it embeds the bundle-hash filenames).
+ * Used in two places:
+ *
+ * - `server/index.js` — injects `<meta name="portos-build-id" content="...">`
+ * into the served index.html so the bundled JS can read its own build id.
+ * - `server/services/socket.js` — emits the current build id to every
+ * connecting socket. A client whose embedded id differs from the live
+ * server's id knows it's running stale code and can prompt to reload.
+ *
+ * During `npm run dev` (Vite dev server, no `client/dist`) the id falls
+ * back to `'dev'` and the socket emission is a no-op match.
+ */
+
+import { existsSync, readFileSync } from 'fs';
+import { createHash } from 'crypto';
+import { fileURLToPath } from 'url';
+import { dirname, join } from 'path';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const INDEX_PATH = join(__dirname, '..', '..', 'client', 'dist', 'index.html');
+
+let cached = null;
+
+function compute() {
+ if (!existsSync(INDEX_PATH)) {
+ return { id: 'dev', html: null };
+ }
+ const html = readFileSync(INDEX_PATH, 'utf8');
+ const id = createHash('sha256').update(html).digest('hex').slice(0, 12);
+ // Inject the meta tag once at boot. Idempotent: if a previous boot already
+ // injected (unlikely — Vite rewrites index.html on every build), regex
+ // replace instead of double-inserting.
+ const META = `<meta name="portos-build-id" content="${id}">`;
+ const META_RE = /<meta name="portos-build-id" content="[^"]*">/;
+ const stamped = META_RE.test(html)
+ ? html.replace(META_RE, META)
+ : html.replace('</head>', ` ${META}\n </head>`);
+ return { id, html: stamped };
+}
+
+export function getBuildId() {
+ if (!cached) cached = compute();
+ return cached.id;
+}
+
+export function getStampedIndexHtml() {
+ if (!cached) cached = compute();
+ return cached.html;
+}
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 2490d5a7b8..56815c1bea 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -19,7 +19,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },
{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk'] },
{ id: 'nav.create.universe-builder', path: '/universe-builder', label: 'Universe Builder', section: 'Create', aliases: ['universe-builder', 'worldbuilder', 'worldbuild', 'world', 'universe', 'lore'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations'] },
- { id: 'nav.create.pipeline', path: '/pipeline', label: 'Series', section: 'Create', aliases: ['series', 'pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },
+ { id: 'nav.create.pipeline', path: '/pipeline', label: 'Series Pipeline', section: 'Create', aliases: ['series', 'pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },
{ id: 'nav.create.sharing', path: '/sharing', label: 'Sharing', section: 'Create', aliases: ['sharing', 'share', 'buckets', 'share-buckets'], keywords: ['google drive', 'dropbox', 'icloud', 'syncthing', 'export', 'import', 'collaborate', 'federation', 'peer', 'cross-network'] },
{ id: 'nav.media.loras', path: '/media/loras', label: 'LoRAs', section: 'Create', aliases: ['loras', 'lora', 'lora-manager', 'civitai'], keywords: ['lora', 'civitai', 'fine-tune', 'style adapter', 'realstagram', 'photoreal', 'flux lora'] },
{ id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'Create', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },
diff --git a/server/lib/storyArc.js b/server/lib/storyArc.js
index 2f07662ef4..33fe14d8c3 100644
--- a/server/lib/storyArc.js
+++ b/server/lib/storyArc.js
@@ -38,6 +38,20 @@ export const ARC_LIMITS = Object.freeze({
export const ARC_STATUSES = Object.freeze(['draft', 'verified']);
export const SEASON_STATUSES = Object.freeze(['draft', 'verified', 'in-production', 'complete']);
+// Kurt Vonnegut's eight story shapes. The server only validates the id; the
+// client owns the display metadata (label, point series for the sparkline).
+// Keep this list in sync with `client/src/components/pipeline/StoryShapes.jsx`.
+export const ARC_SHAPE_IDS = Object.freeze([
+ 'rags-to-riches',
+ 'tragedy',
+ 'man-in-hole',
+ 'icarus',
+ 'cinderella',
+ 'oedipus',
+ 'boy-meets-girl',
+ 'creation-story',
+]);
+
const SEASON_ID_PREFIX = 'sea-';
// `id` of an existing season as written by us. Used by `sanitizeSeason` so
// callers (route patch handlers, season service) accept either an id we
@@ -78,10 +92,13 @@ export function sanitizeArc(raw) {
const themes = cleanThemes(raw.themes);
// An arc with zero identifying content is indistinguishable from "no arc"
// — store null so the UI can render the empty state instead of a blank
- // expanded panel. This also keeps the JSON tighter on disk.
- if (!logline && !summary && !protagonistArc && themes.length === 0) return null;
+ // expanded panel. This also keeps the JSON tighter on disk. A picked
+ // `shape` counts as identifying content: it's an explicit narrative
+ // decision the user made at create time and shouldn't silently vanish.
+ const shape = isStr(raw.shape) && ARC_SHAPE_IDS.includes(raw.shape) ? raw.shape : null;
+ if (!logline && !summary && !protagonistArc && themes.length === 0 && !shape) return null;
const status = ARC_STATUSES.includes(raw.status) ? raw.status : 'draft';
- return { logline, summary, protagonistArc, themes, status };
+ return { logline, summary, protagonistArc, themes, shape, status };
}
/**
diff --git a/server/lib/storyArc.test.js b/server/lib/storyArc.test.js
index 18c1557fda..d77814d94f 100644
--- a/server/lib/storyArc.test.js
+++ b/server/lib/storyArc.test.js
@@ -29,6 +29,7 @@ describe('storyArc — sanitizeArc', () => {
summary: '',
protagonistArc: '',
themes: [],
+ shape: null,
status: 'draft',
});
});
@@ -38,6 +39,23 @@ describe('storyArc — sanitizeArc', () => {
expect(sanitizeArc({ logline: 'x', status: 'verified' }).status).toBe('verified');
});
+ it('accepts allowed Vonnegut shape ids and nulls out anything else', () => {
+ expect(sanitizeArc({ logline: 'x', shape: 'cinderella' }).shape).toBe('cinderella');
+ expect(sanitizeArc({ logline: 'x', shape: 'man-in-hole' }).shape).toBe('man-in-hole');
+ expect(sanitizeArc({ logline: 'x', shape: 'not-a-real-shape' }).shape).toBe(null);
+ expect(sanitizeArc({ logline: 'x', shape: 42 }).shape).toBe(null);
+ expect(sanitizeArc({ logline: 'x' }).shape).toBe(null);
+ });
+
+ it('treats a picked shape as identifying content (explicit narrative decision)', () => {
+ const arc = sanitizeArc({ shape: 'cinderella' });
+ expect(arc).not.toBe(null);
+ expect(arc.shape).toBe('cinderella');
+ expect(arc.logline).toBe('');
+ // Invalid shape strings still fall through to "no arc"
+ expect(sanitizeArc({ shape: 'not-a-shape' })).toBe(null);
+ });
+
it('trims fields to their cap and cleans themes', () => {
const arc = sanitizeArc({
logline: 'a'.repeat(ARC_LIMITS.LOGLINE_MAX + 50),
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 225aaff41b..9e17c19c80 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -56,7 +56,7 @@ import {
} from '../lib/issueLength.js';
import { llmSchema } from './universeBuilder.js';
import { BIBLE_KIND } from '../lib/storyBible.js';
-import { ARC_LIMITS, ARC_STATUSES, SEASON_STATUSES } from '../lib/storyArc.js';
+import { ARC_LIMITS, ARC_STATUSES, ARC_SHAPE_IDS, SEASON_STATUSES } from '../lib/storyArc.js';
const router = Router();
@@ -117,6 +117,7 @@ const arcSchema = z.object({
protagonistArc: z.string().trim().max(ARC_LIMITS.PROTAGONIST_ARC_MAX).optional().default(''),
themes: z.array(z.string().trim().min(1).max(ARC_LIMITS.THEME_MAX))
.max(ARC_LIMITS.THEMES_PER_ARC_MAX).optional(),
+ shape: z.enum(ARC_SHAPE_IDS).nullable().optional(),
status: z.enum(ARC_STATUSES).optional(),
});
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index 0a78954e6a..b48bdc6fa5 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -525,6 +525,7 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
summary: content?.arc?.summary || series.arc.summary || '',
themes: content?.arc?.themes ?? series.arc.themes,
protagonistArc: content?.arc?.protagonistArc ?? series.arc.protagonistArc ?? '',
+ shape: content?.arc?.shape ?? series.arc.shape ?? null,
status: 'draft',
});
diff --git a/server/services/socket.js b/server/services/socket.js
index d2fdb84ecf..e60c2ca50d 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -40,6 +40,7 @@ import * as appsService from './apps.js';
import * as appUpdater from './appUpdater.js';
import * as appDeployer from './appDeployer.js';
import { registerVoiceHandlers } from '../sockets/voice.js';
+import { getBuildId } from '../lib/buildId.js';
// Store active log streams per socket
const activeStreams = new Map();
@@ -83,6 +84,12 @@ export function initSocket(io) {
console.log(`🔌 Client connected: ${socket.id}`);
registerVoiceHandlers(socket);
+ // Tell the client what build the server is on. The client compares this
+ // to its own embedded <meta name="portos-build-id"> value; a mismatch
+ // means the tab is running stale code against a freshly-rebuilt server
+ // and the user is offered a reload.
+ socket.emit('build:id', { buildId: getBuildId() });
+
// Handle streaming app detection
socket.on('detect:start', async (rawData) => {
try {