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([versioning-diff-view-per-stage-persist-last-n]): per-text-stage history with inline-diff modal

[._.]/ Adam Eivyd0886dc26c48
diff --git a/client/src/components/insights/CrossDomainTab.jsx b/client/src/components/insights/CrossDomainTab.jsx
index ee67eaee69..b1dc45a786 100644
--- a/client/src/components/insights/CrossDomainTab.jsx
+++ b/client/src/components/insights/CrossDomainTab.jsx
@@ -1,57 +1,8 @@
-import { useState, useEffect, memo } from 'react';
+import { useState, useEffect } from 'react';
import { RefreshCw, GitCompare } from 'lucide-react';
import { getInsightNarrative, refreshInsightNarrative } from '../../services/api';
import { formatDate, timeAgo } from '../../utils/formatters';
-
-// Inline word-level diff using Myers LCS algorithm
-function lcs(a, b) {
- const m = a.length, n = b.length;
- const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
- for (let i = 1; i <= m; i++)
- for (let j = 1; j <= n; j++)
- dp[i][j] = a[i-1] === b[j-1] ? dp[i-1][j-1] + 1 : Math.max(dp[i-1][j], dp[i][j-1]);
- const seq = [];
- let i = m, j = n;
- while (i > 0 && j > 0) {
- if (a[i-1] === b[j-1]) { seq.unshift(a[i-1]); i--; j--; }
- else if (dp[i-1][j] >= dp[i][j-1]) i--;
- else j--;
- }
- return seq;
-}
-
-const InlineDiff = memo(function InlineDiff({ oldText, newText }) {
- const oldWords = (oldText || '').split(/(\s+)/);
- const newWords = (newText || '').split(/(\s+)/);
- const commonSeq = lcs(oldWords, newWords);
-
- const render = (words, added) => {
- const spans = [];
- let run = [];
- let ci = 0;
- words.forEach((w, i) => {
- if (ci < commonSeq.length && w === commonSeq[ci]) {
- ci++;
- if (run.length) { spans.push(<span key={i + 'r'} className={added ? 'bg-green-900/50 text-green-300' : 'bg-red-900/50 text-red-300'}>{run.join('')}</span>); run = []; }
- spans.push(w);
- } else { run.push(w); }
- });
- if (run.length) spans.push(<span key="last" className={added ? 'bg-green-900/50 text-green-300' : 'bg-red-900/50 text-red-300'}>{run.join('')}</span>);
- return spans;
- };
-
- return (
- <div className="font-mono text-xs p-4 space-y-2 bg-port-bg">
- {oldText !== newText && (
- <>
- <div className="text-red-400 leading-relaxed">{render(oldWords, false)}</div>
- <div className="text-green-400 leading-relaxed">{render(newWords, true)}</div>
- </>
- )}
- {oldText === newText && <div className="text-gray-500">No changes.</div>}
- </div>
- );
-});
+import InlineDiff from '../ui/InlineDiff';
export default function CrossDomainTab() {
const [data, setData] = useState(null);
diff --git a/client/src/components/pipeline/stages/StageHistoryModal.jsx b/client/src/components/pipeline/stages/StageHistoryModal.jsx
new file mode 100644
index 0000000000..7c7dbc507b
--- /dev/null
+++ b/client/src/components/pipeline/stages/StageHistoryModal.jsx
@@ -0,0 +1,145 @@
+/**
+ * Per-stage version history modal — lists prior `runHistory` snapshots for a
+ * text stage and shows an inline word-diff between the selected snapshot and
+ * the live stage output. "Restore" sets the snapshot back as the active state;
+ * the just-replaced version is itself snapshotted server-side, so restore is
+ * reversible.
+ */
+
+import { useEffect, useState } from 'react';
+import { History, Loader2, RotateCcw, X } from 'lucide-react';
+import Modal from '../../ui/Modal';
+import InlineDiff from '../../ui/InlineDiff';
+import { restorePipelineStageVersion, PIPELINE_STAGE_LABELS } from '../../../services/api';
+import { useAsyncAction } from '../../../hooks/useAsyncAction';
+import { timeAgo } from '../../../utils/formatters';
+import toast from '../../ui/Toast';
+
+export default function StageHistoryModal({
+ open,
+ onClose,
+ issueId,
+ stageId,
+ currentOutput,
+ currentRunId,
+ runHistory = [],
+ onRestored,
+}) {
+ const [selectedRunId, setSelectedRunId] = useState(null);
+
+ // Default-select the newest snapshot on open so the user sees a diff
+ // immediately. Successful restore closes the modal, so we don't need to
+ // re-pick when runHistory changes mid-session.
+ useEffect(() => {
+ if (open && runHistory.length > 0) setSelectedRunId(runHistory[0].runId);
+ else if (!open) setSelectedRunId(null);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ const selected = runHistory.find((e) => e.runId === selectedRunId) || null;
+
+ const [runRestore, restoring] = useAsyncAction(
+ async () => {
+ if (!selected) return null;
+ return restorePipelineStageVersion(issueId, stageId, selected.runId);
+ },
+ { errorMessage: 'Restore failed' },
+ );
+
+ const handleRestore = async () => {
+ if (!selected) return;
+ const result = await runRestore();
+ if (!result) return;
+ onRestored?.(result.stage, result.issue);
+ toast.success(`Restored ${PIPELINE_STAGE_LABELS[stageId] || stageId} to run ${selected.runId.slice(0, 8)}`);
+ onClose?.();
+ };
+
+ return (
+ <Modal open={open} onClose={onClose} size="3xl" ariaLabel="Stage version history">
+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col max-h-[85vh]">
+ <div className="flex items-center justify-between px-5 py-3 border-b border-port-border">
+ <div className="flex items-center gap-2">
+ <History size={16} className="text-port-accent" />
+ <h2 className="text-base font-semibold text-white">
+ {PIPELINE_STAGE_LABELS[stageId] || stageId} — Version History
+ </h2>
+ <span className="text-xs text-gray-500">
+ {runHistory.length} prior version{runHistory.length === 1 ? '' : 's'}
+ </span>
+ </div>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close"
+ className="text-gray-400 hover:text-white"
+ >
+ <X size={18} />
+ </button>
+ </div>
+
+ {runHistory.length === 0 ? (
+ <div className="p-6 text-sm text-gray-400 text-center">
+ No prior versions yet — every regenerate of this stage will be snapshotted here.
+ </div>
+ ) : (
+ <div className="flex flex-col sm:flex-row min-h-0 flex-1">
+ {/* Version list — left rail on desktop, top stack on mobile */}
+ <div className="sm:w-56 sm:border-r border-b sm:border-b-0 border-port-border overflow-y-auto bg-port-bg/40">
+ <ul className="divide-y divide-port-border">
+ {runHistory.map((entry) => {
+ const isActive = entry.runId === selectedRunId;
+ return (
+ <li key={entry.runId}>
+ <button
+ type="button"
+ onClick={() => setSelectedRunId(entry.runId)}
+ className={`w-full text-left px-3 py-2 text-xs hover:bg-port-card transition-colors ${
+ isActive ? 'bg-port-card border-l-2 border-port-accent' : 'border-l-2 border-transparent'
+ }`}
+ >
+ <div className="font-mono text-gray-300">run {entry.runId.slice(0, 8)}</div>
+ <div className="text-gray-500 mt-0.5">
+ {entry.createdAt ? timeAgo(entry.createdAt) : 'unknown time'}
+ </div>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+
+ {/* Diff pane */}
+ <div className="flex-1 flex flex-col min-w-0">
+ <div className="flex items-center justify-between px-4 py-2 border-b border-port-border bg-port-bg/40">
+ <div className="text-xs text-gray-500">
+ {selected ? (
+ <>
+ <span className="text-red-400">prior</span>
+ {' → '}
+ <span className="text-green-400">current{currentRunId ? ` (run ${currentRunId.slice(0, 8)})` : ''}</span>
+ </>
+ ) : 'Pick a version on the left to view the diff'}
+ </div>
+ <button
+ type="button"
+ onClick={handleRestore}
+ disabled={!selected || restoring}
+ className="inline-flex items-center gap-1.5 px-3 py-1 rounded bg-port-accent text-white text-xs font-medium hover:bg-port-accent/80 disabled:opacity-40"
+ >
+ {restoring ? <Loader2 size={12} className="animate-spin" /> : <RotateCcw size={12} />}
+ Restore this version
+ </button>
+ </div>
+ <div className="flex-1 overflow-auto">
+ {selected ? (
+ <InlineDiff oldText={selected.output} newText={currentOutput || ''} />
+ ) : null}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ </Modal>
+ );
+}
diff --git a/client/src/components/pipeline/stages/StageHistoryModal.test.jsx b/client/src/components/pipeline/stages/StageHistoryModal.test.jsx
new file mode 100644
index 0000000000..ed5907e9a4
--- /dev/null
+++ b/client/src/components/pipeline/stages/StageHistoryModal.test.jsx
@@ -0,0 +1,126 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+vi.mock('../../../services/api', () => ({
+ PIPELINE_STAGE_LABELS: { idea: 'Idea', prose: 'Prose' },
+ restorePipelineStageVersion: vi.fn(),
+}));
+
+vi.mock('../../ui/Toast', () => ({
+ default: { success: vi.fn(), error: vi.fn() },
+}));
+
+import StageHistoryModal from './StageHistoryModal';
+import { restorePipelineStageVersion } from '../../../services/api';
+import toast from '../../ui/Toast';
+
+const makeEntry = (runId, output, daysAgo = 1) => ({
+ runId,
+ output,
+ input: '',
+ createdAt: new Date(Date.now() - daysAgo * 86_400_000).toISOString(),
+});
+
+describe('StageHistoryModal', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('shows an empty state when runHistory is empty', () => {
+ render(
+ <StageHistoryModal
+ open
+ onClose={() => {}}
+ issueId="iss-1"
+ stageId="idea"
+ currentOutput="current"
+ currentRunId="run-cur"
+ runHistory={[]}
+ />,
+ );
+ expect(screen.getByText(/No prior versions yet/i)).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Restore this version/i })).not.toBeInTheDocument();
+ });
+
+ it('defaults to the newest snapshot and renders its diff against current', () => {
+ const history = [
+ makeEntry('run-3', 'newest beats', 1),
+ makeEntry('run-2', 'middle beats', 2),
+ makeEntry('run-1', 'oldest beats', 3),
+ ];
+ const { container } = render(
+ <StageHistoryModal
+ open
+ onClose={() => {}}
+ issueId="iss-1"
+ stageId="idea"
+ currentOutput="current beats"
+ currentRunId="run-cur"
+ runHistory={history}
+ />,
+ );
+ // List shows all three runIds.
+ expect(screen.getByText('run run-3').textContent).toContain('run-3');
+ expect(screen.getByText('run run-2').textContent).toContain('run-2');
+ expect(screen.getByText('run run-1').textContent).toContain('run-1');
+ // Header echoes the current runId.
+ expect(screen.getByText(/run run-cur/)).toBeInTheDocument();
+ // The diff is rendered (some red/green spans must exist since "newest" → "current").
+ expect(container.querySelector('.text-red-400')).toBeInTheDocument();
+ expect(container.querySelector('.text-green-400')).toBeInTheDocument();
+ });
+
+ it('switches the diff when a different version is selected', async () => {
+ const user = userEvent.setup();
+ render(
+ <StageHistoryModal
+ open
+ onClose={() => {}}
+ issueId="iss-1"
+ stageId="idea"
+ currentOutput="current"
+ currentRunId="run-cur"
+ runHistory={[
+ makeEntry('run-2', 'second version', 1),
+ makeEntry('run-1', 'first version', 2),
+ ]}
+ />,
+ );
+ // Clicking the older entry re-anchors the diff.
+ await user.click(screen.getByRole('button', { name: /run-1/ }));
+ // Active selection adds the accent border class — assert via DOM.
+ const oldButton = screen.getByRole('button', { name: /run-1/ });
+ expect(oldButton.className).toContain('border-port-accent');
+ });
+
+ it('calls restorePipelineStageVersion and fires onRestored on success', async () => {
+ restorePipelineStageVersion.mockResolvedValue({
+ stage: { lastRunId: 'run-2', output: 'second version', runHistory: [] },
+ issue: { id: 'iss-1', stages: {} },
+ });
+ const onRestored = vi.fn();
+ const onClose = vi.fn();
+ const user = userEvent.setup();
+ render(
+ <StageHistoryModal
+ open
+ onClose={onClose}
+ issueId="iss-1"
+ stageId="idea"
+ currentOutput="current"
+ currentRunId="run-cur"
+ runHistory={[
+ makeEntry('run-2', 'second version', 1),
+ makeEntry('run-1', 'first version', 2),
+ ]}
+ onRestored={onRestored}
+ />,
+ );
+ await user.click(screen.getByRole('button', { name: /Restore this version/i }));
+ expect(restorePipelineStageVersion).toHaveBeenCalledWith('iss-1', 'idea', 'run-2');
+ expect(onRestored).toHaveBeenCalled();
+ expect(toast.success).toHaveBeenCalled();
+ expect(onClose).toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/pipeline/stages/TextStagePanel.jsx b/client/src/components/pipeline/stages/TextStagePanel.jsx
index e8621b7e18..3bc361161b 100644
--- a/client/src/components/pipeline/stages/TextStagePanel.jsx
+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx
@@ -6,7 +6,7 @@
*/
import { useEffect, useState } from 'react';
-import { Loader2, Sparkles, Save } from 'lucide-react';
+import { Loader2, Sparkles, Save, History } from 'lucide-react';
import toast from '../../ui/Toast';
import {
generatePipelineStage, updatePipelineIssue,
@@ -15,6 +15,7 @@ import {
PIPELINE_STAGE_STATUS_COLOR as STATUS_COLOR,
} from '../../../services/api';
import { useAsyncAction } from '../../../hooks/useAsyncAction';
+import StageHistoryModal from './StageHistoryModal';
export default function TextStagePanel({
issue,
@@ -27,13 +28,15 @@ export default function TextStagePanel({
extraActions = null,
actionsGated = false,
}) {
- const stage = issue.stages?.[stageId] || { status: 'empty', input: '', output: '' };
+ const stage = issue.stages?.[stageId] || { status: 'empty', input: '', output: '', runHistory: [] };
const [draftOutput, setDraftOutput] = useState(stage.output || '');
const [draftInput, setDraftInput] = useState(stage.input || '');
// Server-pushed in-flight state — separate from the hook's local-action
// running flag so an auto-run kicked off elsewhere still keeps the
// Generate button locked.
const [serverGenerating, setServerGenerating] = useState(stage.status === 'generating');
+ const [historyOpen, setHistoryOpen] = useState(false);
+ const runHistory = stage.runHistory || [];
// Reset local edits when the stage record changes from the parent (e.g.
// auto-run pushed a new output).
@@ -96,6 +99,16 @@ export default function TextStagePanel({
</div>
<div className="flex items-center gap-2">
{extraActions}
+ <button
+ type="button"
+ onClick={() => setHistoryOpen(true)}
+ disabled={runHistory.length === 0}
+ title={runHistory.length === 0 ? 'No prior versions yet' : `${runHistory.length} prior version${runHistory.length === 1 ? '' : 's'}`}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50 disabled:opacity-40"
+ >
+ <History size={14} />
+ History{runHistory.length ? ` (${runHistory.length})` : ''}
+ </button>
<button
type="button"
onClick={handleSave}
@@ -145,6 +158,19 @@ export default function TextStagePanel({
{stage.errorMessage ? (
<div className="text-xs text-port-error">{stage.errorMessage}</div>
) : null}
+
+ <StageHistoryModal
+ open={historyOpen}
+ onClose={() => setHistoryOpen(false)}
+ issueId={issue.id}
+ stageId={stageId}
+ currentOutput={stage.output || ''}
+ currentRunId={stage.lastRunId}
+ runHistory={runHistory}
+ onRestored={(restoredStage, restoredIssue) => {
+ onStageUpdate?.(stageId, restoredStage, restoredIssue);
+ }}
+ />
</div>
);
}
diff --git a/client/src/components/ui/InlineDiff.jsx b/client/src/components/ui/InlineDiff.jsx
new file mode 100644
index 0000000000..6c1e44627a
--- /dev/null
+++ b/client/src/components/ui/InlineDiff.jsx
@@ -0,0 +1,98 @@
+/**
+ * Inline word-level diff using Myers LCS. Renders two stacked rows:
+ * - the OLD text with removed words highlighted in red
+ * - the NEW text with added words highlighted in green
+ * Shared component — used by the Cross-Domain Insights narrative diff and the
+ * Pipeline text-stage history modal. Pure / memoized / no external deps.
+ */
+
+import { memo } from 'react';
+
+function lcs(a, b) {
+ const m = a.length, n = b.length;
+ const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
+ for (let i = 1; i <= m; i++)
+ for (let j = 1; j <= n; j++)
+ dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);
+ const seq = [];
+ let i = m, j = n;
+ while (i > 0 && j > 0) {
+ if (a[i - 1] === b[j - 1]) { seq.unshift(a[i - 1]); i--; j--; }
+ else if (dp[i - 1][j] >= dp[i][j - 1]) i--;
+ else j--;
+ }
+ return seq;
+}
+
+// LCS is O(m·n) and allocates an (m+1)×(n+1) DP table — a 30K-word document
+// diffed against another 30K-word document would allocate ~3.6GB of array
+// cells and stall the browser. Bail to a plain side-by-side render when
+// either side exceeds this many split tokens (whitespace counts as a token,
+// so this is roughly 2× word count).
+const DIFF_TOKEN_CAP = 8000;
+
+const InlineDiff = memo(function InlineDiff({ oldText, newText, emptyLabel = 'No changes.' }) {
+ const oldStr = oldText || '';
+ const newStr = newText || '';
+ const oldWords = oldStr.split(/(\s+)/);
+ const newWords = newStr.split(/(\s+)/);
+
+ if (oldStr === newStr) {
+ return (
+ <div className="font-mono text-xs p-4 bg-port-bg">
+ <div className="text-gray-500">{emptyLabel}</div>
+ </div>
+ );
+ }
+ if (oldWords.length > DIFF_TOKEN_CAP || newWords.length > DIFF_TOKEN_CAP) {
+ return (
+ <div className="font-mono text-xs p-4 space-y-2 bg-port-bg">
+ <div className="text-gray-500 text-[11px] uppercase tracking-wider">
+ Diff too large for inline highlighting — both versions shown in full
+ </div>
+ <div className="text-red-400 leading-relaxed whitespace-pre-wrap">{oldStr}</div>
+ <div className="text-green-400 leading-relaxed whitespace-pre-wrap">{newStr}</div>
+ </div>
+ );
+ }
+ const commonSeq = lcs(oldWords, newWords);
+
+ const render = (words, added) => {
+ const spans = [];
+ let run = [];
+ let ci = 0;
+ words.forEach((w, i) => {
+ if (ci < commonSeq.length && w === commonSeq[ci]) {
+ ci++;
+ if (run.length) {
+ spans.push(
+ <span key={`${i}r`} className={added ? 'bg-green-900/50 text-green-300' : 'bg-red-900/50 text-red-300'}>
+ {run.join('')}
+ </span>,
+ );
+ run = [];
+ }
+ spans.push(w);
+ } else {
+ run.push(w);
+ }
+ });
+ if (run.length) {
+ spans.push(
+ <span key="last" className={added ? 'bg-green-900/50 text-green-300' : 'bg-red-900/50 text-red-300'}>
+ {run.join('')}
+ </span>,
+ );
+ }
+ return spans;
+ };
+
+ return (
+ <div className="font-mono text-xs p-4 space-y-2 bg-port-bg">
+ <div className="text-red-400 leading-relaxed whitespace-pre-wrap">{render(oldWords, false)}</div>
+ <div className="text-green-400 leading-relaxed whitespace-pre-wrap">{render(newWords, true)}</div>
+ </div>
+ );
+});
+
+export default InlineDiff;
diff --git a/client/src/components/ui/InlineDiff.test.jsx b/client/src/components/ui/InlineDiff.test.jsx
new file mode 100644
index 0000000000..d2992715e0
--- /dev/null
+++ b/client/src/components/ui/InlineDiff.test.jsx
@@ -0,0 +1,49 @@
+import { describe, it, expect } from 'vitest';
+import { render, screen } from '@testing-library/react';
+
+import InlineDiff from './InlineDiff';
+
+describe('InlineDiff', () => {
+ it('shows the empty-label when the two texts are identical', () => {
+ render(<InlineDiff oldText="Hello world" newText="Hello world" />);
+ expect(screen.getByText('No changes.')).toBeInTheDocument();
+ });
+
+ it('shows a custom empty-label when supplied', () => {
+ render(<InlineDiff oldText="" newText="" emptyLabel="(blank on both sides)" />);
+ expect(screen.getByText('(blank on both sides)')).toBeInTheDocument();
+ });
+
+ it('renders both stacked rows when the texts differ', () => {
+ const { container } = render(<InlineDiff oldText="The cat sat" newText="The dog sat" />);
+ expect(screen.queryByText('No changes.')).not.toBeInTheDocument();
+ // Two stacked diff rows — the red (removed) and green (added) divs.
+ expect(container.querySelectorAll('.text-red-400')).toHaveLength(1);
+ expect(container.querySelectorAll('.text-green-400')).toHaveLength(1);
+ });
+
+ it('highlights only the changed words inside each row, not the unchanged ones', () => {
+ const { container } = render(<InlineDiff oldText="The cat sat" newText="The dog sat" />);
+ // Removed-word span lives inside the red row.
+ const removedSpans = container.querySelectorAll('.text-red-400 .bg-red-900\\/50');
+ const addedSpans = container.querySelectorAll('.text-green-400 .bg-green-900\\/50');
+ expect(removedSpans).toHaveLength(1);
+ expect(addedSpans).toHaveLength(1);
+ expect(removedSpans[0].textContent).toBe('cat');
+ expect(addedSpans[0].textContent).toBe('dog');
+ });
+
+ it('tolerates null/undefined inputs by treating them as empty strings', () => {
+ render(<InlineDiff oldText={null} newText={undefined} />);
+ expect(screen.getByText('No changes.')).toBeInTheDocument();
+ });
+
+ it('bails to plain side-by-side render when either side exceeds the token cap', () => {
+ // Build a string with way more than DIFF_TOKEN_CAP (8000) tokens.
+ const huge = Array.from({ length: 5000 }, (_, i) => `word${i}`).join(' '); // 5000 words → ~10K tokens after split on whitespace
+ const { container } = render(<InlineDiff oldText={huge} newText="short" />);
+ expect(screen.getByText(/Diff too large/i)).toBeInTheDocument();
+ // No per-word highlight spans — just the two flat color blocks.
+ expect(container.querySelectorAll('.bg-red-900\\/50, .bg-green-900\\/50')).toHaveLength(0);
+ });
+});
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index a97c775b2b..8b7c8e14ea 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -129,6 +129,15 @@ export const generatePipelineVisualImage = (issueId, stageId, opts) =>
body: JSON.stringify(opts),
});
+// Restore a prior `runHistory` snapshot as the active text-stage state. The
+// server snapshots the just-replaced version into runHistory automatically,
+// so restoring is reversible by clicking another snapshot.
+export const restorePipelineStageVersion = (issueId, stageId, runId) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/${encodeURIComponent(stageId)}/restore`, {
+ method: 'POST',
+ body: JSON.stringify({ runId }),
+ });
+
// Auto-fill the storyboards stage's scenes[] from the issue's prose or
// teleplay text stage. `from` defaults server-side to 'teleplay'. Pass
// `force: true` to replace existing hand-curated scenes.
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index df46a199b5..17b7f076e7 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -1280,6 +1280,27 @@ router.post('/issues/:id/stages/:stageId/generate', asyncHandler(async (req, res
res.json(result);
}));
+// Restore a prior text-stage version from history. See
+// issuesSvc.restoreStageFromHistory for the reversibility semantics.
+const restoreSchema = z.object({
+ runId: z.string().trim().min(1).max(200),
+});
+router.post('/issues/:id/stages/:stageId/restore', asyncHandler(async (req, res) => {
+ const { id, stageId } = req.params;
+ if (!issuesSvc.TEXT_STAGE_IDS.includes(stageId)) {
+ throw new ServerError(
+ `Stage "${stageId}" does not support history restore`,
+ { status: 400, code: 'PIPELINE_NON_TEXT_STAGE' },
+ );
+ }
+ const body = validateRequest(restoreSchema, req.body ?? {});
+ const issue = await issuesSvc.getIssue(id).catch((err) => { throw mapServiceError(err); });
+ issuesSvc.assertStageUnlocked(issue, stageId);
+ const result = await issuesSvc.restoreStageFromHistory(id, stageId, body.runId)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
// Auto-fill stages.storyboards.scenes[] from a text stage. Reads the issue's
// prose (paragraph-grain) or teleplay (slugline-grain) output, runs the
// shared scene extractor, and replaces stages.storyboards.scenes with the
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 6f41de9881..f824ac9b4f 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -351,6 +351,65 @@ describe('pipeline routes', () => {
expect(r.body.code || r.body.error).toBeTruthy();
});
+ describe('POST /issues/:id/stages/:stageId/restore', () => {
+ it('restores a prior runHistory snapshot and snapshots the displaced current state', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const issueId = iss.body.id;
+ // First run → no snapshot yet.
+ const r1 = await request(app)
+ .post(`/api/pipeline/issues/${issueId}/stages/idea/generate`)
+ .send({ seedInput: 'mystery v1' });
+ const firstRunId = r1.body.stage.lastRunId;
+ // Second run → snapshots v1.
+ const r2 = await request(app)
+ .post(`/api/pipeline/issues/${issueId}/stages/idea/generate`)
+ .send({ seedInput: 'mystery v2' });
+ expect(r2.body.stage.runHistory).toHaveLength(1);
+ expect(r2.body.stage.runHistory[0].runId).toBe(firstRunId);
+ // Restore v1.
+ const restored = await request(app)
+ .post(`/api/pipeline/issues/${issueId}/stages/idea/restore`)
+ .send({ runId: firstRunId });
+ expect(restored.status).toBe(200);
+ expect(restored.body.stage.lastRunId).toBe(firstRunId);
+ expect(restored.body.stage.status).toBe('edited');
+ // The just-replaced v2 now sits at the top of history.
+ expect(restored.body.stage.runHistory[0].runId).toBe(r2.body.stage.lastRunId);
+ });
+
+ it('rejects when the runId is not in the current snapshot list', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/idea/restore`)
+ .send({ runId: 'run-never-generated' });
+ expect(r.status).toBe(400);
+ });
+
+ it('rejects non-text stages', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/restore`)
+ .send({ runId: 'r1' });
+ expect(r.status).toBe(400);
+ });
+
+ it('rejects empty runId via Zod', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/idea/restore`)
+ .send({ runId: '' });
+ expect(r.status).toBe(400);
+ });
+ });
+
it('POST /issues/:id/stages/comicPages/visual enqueues an image job', async () => {
const app = makeApp();
const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index fa51f32048..40b1e7f547 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -66,6 +66,14 @@ export const STAGE_INPUT_MAX = 200_000; // ~200kB — fits a long prose draft
export const STAGE_OUTPUT_MAX = 400_000; // ~400kB — fits a long comic script
export const STAGE_NOTES_MAX = 4000;
export const ISSUES_PER_RESPONSE_MAX = 1000;
+// How many prior versions of a text stage to retain for the diff modal.
+// Each entry holds the full prior input+output, so the upper bound is
+// N × (STAGE_INPUT_MAX + STAGE_OUTPUT_MAX) per stage. Five keeps a useful
+// undo trail without ballooning pipeline-issues.json. Only text stages
+// snapshot — visual/audio artifact shapes (pages[]/scenes[]/lines[]) aren't
+// meaningfully diffable as plain text; see snapshot gating in
+// updateStageWithLatest + updateIssue.
+export const STAGE_RUN_HISTORY_MAX = 5;
// Stage IDs are ordered for UI display; the canonical order is also the
// auto-run text-chain order (idea → prose → scripts in parallel). Comic
@@ -103,6 +111,10 @@ const emptyStage = () => ({
errorMessage: '',
updatedAt: null,
locked: false,
+ // Most-recent-first list of prior `{ runId, createdAt, input, output }`
+ // snapshots, capped at STAGE_RUN_HISTORY_MAX. Populated only for text
+ // stages — visual/audio stages keep the field as [] for shape parity.
+ runHistory: [],
});
/**
@@ -122,6 +134,26 @@ export function assertStageUnlocked(issue, stageId) {
}
}
+const sanitizeRunHistoryEntry = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const runId = isStr(raw.runId) && raw.runId ? raw.runId : null;
+ if (!runId) return null;
+ return {
+ runId,
+ createdAt: isStr(raw.createdAt) && raw.createdAt ? raw.createdAt : null,
+ input: trimTo(raw.input, STAGE_INPUT_MAX),
+ output: trimTo(raw.output, STAGE_OUTPUT_MAX),
+ };
+};
+
+const sanitizeRunHistory = (raw) => {
+ if (!Array.isArray(raw)) return [];
+ return raw
+ .map(sanitizeRunHistoryEntry)
+ .filter(Boolean)
+ .slice(0, STAGE_RUN_HISTORY_MAX);
+};
+
const sanitizeStage = (raw) => {
if (!raw || typeof raw !== 'object') return emptyStage();
const status = STAGE_STATUSES.includes(raw.status) ? raw.status : 'empty';
@@ -137,9 +169,48 @@ const sanitizeStage = (raw) => {
// finalized comic script while still iterating storyboards. Independent
// of `series.locked.arc` and `season.locked`; any of the three rejects.
locked: raw.locked === true,
+ runHistory: sanitizeRunHistory(raw.runHistory),
};
};
+/**
+ * Decide whether `patch` represents a generate-replacement on `prevStage` and,
+ * if so, prepend a snapshot of the prior state to `prevStage.runHistory`.
+ * Returns the new runHistory array (capped at STAGE_RUN_HISTORY_MAX).
+ *
+ * Trigger conditions (ALL must hold):
+ * - `stageId` is in TEXT_STAGE_IDS — visual + audio shapes don't snapshot.
+ * - patch.lastRunId is a non-empty string that differs from prevStage.lastRunId.
+ * - prevStage.lastRunId is set AND prevStage.output is non-empty — there's
+ * prior content worth preserving for diff/restore.
+ *
+ * Skipped triggers (and why):
+ * - First-time generate (prev.lastRunId === null) — nothing to snapshot.
+ * - status: 'generating' transition — patch carries no new lastRunId yet.
+ * - status: 'error' from a failed LLM throw — patch carries no new lastRunId.
+ * - Save-edit (PATCH with input/output but no lastRunId) — caller explicitly
+ * editing the existing version, not replacing it. The previous run remains
+ * the active version; the next generate will snapshot it.
+ */
+export function snapshotRunHistory(prevStage, patch, stageId) {
+ const prevHistory = Array.isArray(prevStage?.runHistory) ? prevStage.runHistory : [];
+ if (!patch || typeof patch !== 'object') return prevHistory;
+ if (!TEXT_STAGE_IDS.includes(stageId)) return prevHistory;
+ const nextRunId = isStr(patch.lastRunId) ? patch.lastRunId : '';
+ if (!nextRunId) return prevHistory;
+ if (nextRunId === prevStage?.lastRunId) return prevHistory;
+ if (!prevStage?.lastRunId) return prevHistory;
+ const prevOutput = prevStage.output || '';
+ if (!prevOutput.trim()) return prevHistory;
+ const snapshot = {
+ runId: prevStage.lastRunId,
+ createdAt: prevStage.updatedAt || new Date().toISOString(),
+ input: prevStage.input || '',
+ output: prevOutput,
+ };
+ return [snapshot, ...prevHistory].slice(0, STAGE_RUN_HISTORY_MAX);
+}
+
// Episode-video render settings the user chose at kickoff time. Persisted
// on the stage so a page reload doesn't reset them to the defaults — the
// restart flow can render the same pickers populated with the user's
@@ -552,6 +623,11 @@ export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {
const prev = cur.stages?.[stageId];
if (prev && stagePatch && typeof prev === 'object' && typeof stagePatch === 'object') {
const merged = { ...prev, ...stagePatch };
+ // Mirror the snapshot trigger from updateStageWithLatest so a
+ // route-level PATCH that swaps lastRunId (e.g. the restore endpoint)
+ // also produces a runHistory entry. No-op when the patch is a plain
+ // save-edit without lastRunId.
+ merged.runHistory = snapshotRunHistory(prev, stagePatch, stageId);
for (const key of NESTED_DEEP_MERGE_KEYS) {
if (key in stagePatch
&& stagePatch[key] && typeof stagePatch[key] === 'object'
@@ -625,6 +701,37 @@ export function updateStage(issueId, stageId, patch = {}) {
return updateStageWithLatest(issueId, stageId, () => patch);
}
+/**
+ * Restore a prior `runHistory` snapshot as the active stage state. Looks up the
+ * snapshot by `runId` against the freshest persisted record (so a concurrent
+ * generate can't make the chosen snapshot disappear out from under the call).
+ * The previous active state is itself snapshotted into runHistory by the normal
+ * lastRunId-changed trigger in `updateStageWithLatest`, so restore is just
+ * another version event — there's no special "rollback" semantics.
+ *
+ * Resolves with `{ issue, stage }`. Rejects with ERR_VALIDATION when the runId
+ * isn't present in the current runHistory.
+ */
+export function restoreStageFromHistory(issueId, stageId, runId) {
+ if (!TEXT_STAGE_IDS.includes(stageId)) {
+ return Promise.reject(makeErr(`Stage "${stageId}" does not support history restore`, ERR_VALIDATION));
+ }
+ if (!isStr(runId) || !runId) {
+ return Promise.reject(makeErr('runId is required', ERR_VALIDATION));
+ }
+ return updateStageWithLatest(issueId, stageId, (cur) => {
+ const snapshot = (cur?.runHistory || []).find((entry) => entry.runId === runId);
+ if (!snapshot) throw makeErr(`Snapshot not found in stage history: ${runId}`, ERR_VALIDATION);
+ return {
+ status: 'edited',
+ input: snapshot.input || '',
+ output: snapshot.output || '',
+ lastRunId: snapshot.runId,
+ errorMessage: '',
+ };
+ });
+}
+
export function deleteIssue(id) {
return queueIssueWrite(async () => {
const state = await readState();
@@ -675,9 +782,14 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {
if (isPlainObject(patch) && Object.keys(patch).length === 0) {
return { issue: cur, stage: currentStage };
}
+ // Snapshot the prior `{ runId, input, output }` into runHistory when this
+ // patch carries a fresh lastRunId (i.e. a generate just replaced prior
+ // content). Computed BEFORE the spread so it reads pre-merge state.
+ const nextRunHistory = snapshotRunHistory(currentStage, patch, stageId);
const merged = {
...currentStage,
...patch,
+ runHistory: nextRunHistory,
updatedAt: new Date().toISOString(),
};
let next;
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index 968885629e..f676570e05 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -195,6 +195,143 @@ describe('pipeline issues service', () => {
expect(stage.pages[0].panels[0].imageJobId).toBe('j1');
});
+ describe('runHistory snapshots', () => {
+ const seedFirstRun = async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Pilot' });
+ await svc.updateStage(i.id, 'idea', {
+ status: 'ready', output: 'first beats', input: 'seed', lastRunId: 'run-1',
+ });
+ return i;
+ };
+
+ it('first generate does not snapshot — there is no prior content', async () => {
+ const i = await seedFirstRun();
+ const fresh = await svc.getIssue(i.id);
+ expect(fresh.stages.idea.runHistory).toEqual([]);
+ });
+
+ it('second generate snapshots the prior version into runHistory', async () => {
+ const i = await seedFirstRun();
+ await svc.updateStage(i.id, 'idea', {
+ status: 'ready', output: 'rewritten beats', lastRunId: 'run-2',
+ });
+ const fresh = await svc.getIssue(i.id);
+ expect(fresh.stages.idea.output).toBe('rewritten beats');
+ expect(fresh.stages.idea.lastRunId).toBe('run-2');
+ expect(fresh.stages.idea.runHistory).toHaveLength(1);
+ expect(fresh.stages.idea.runHistory[0]).toMatchObject({
+ runId: 'run-1', output: 'first beats', input: 'seed',
+ });
+ expect(fresh.stages.idea.runHistory[0].createdAt).toBeTruthy();
+ });
+
+ it('newest snapshot is prepended (most-recent-first ordering)', async () => {
+ const i = await seedFirstRun();
+ await svc.updateStage(i.id, 'idea', { status: 'ready', output: 'v2', lastRunId: 'run-2' });
+ await svc.updateStage(i.id, 'idea', { status: 'ready', output: 'v3', lastRunId: 'run-3' });
+ const fresh = await svc.getIssue(i.id);
+ expect(fresh.stages.idea.runHistory.map((e) => e.runId)).toEqual(['run-2', 'run-1']);
+ });
+
+ it('runHistory caps at STAGE_RUN_HISTORY_MAX', async () => {
+ const i = await seedFirstRun();
+ // Six more generates → seven total; cap is 5, so we should see runs 2..6 (most-recent-first).
+ for (let n = 2; n <= 7; n += 1) {
+ await svc.updateStage(i.id, 'idea', { status: 'ready', output: `v${n}`, lastRunId: `run-${n}` });
+ }
+ const fresh = await svc.getIssue(i.id);
+ expect(fresh.stages.idea.runHistory).toHaveLength(svc.STAGE_RUN_HISTORY_MAX);
+ expect(fresh.stages.idea.runHistory[0].runId).toBe('run-6');
+ expect(fresh.stages.idea.runHistory.at(-1).runId).toBe('run-2');
+ });
+
+ it('save-edit (PATCH without lastRunId) does NOT snapshot', async () => {
+ const i = await seedFirstRun();
+ // Simulate the editor blur-save: input/output PATCH, no lastRunId.
+ await svc.updateIssue(i.id, {
+ stages: { idea: { status: 'edited', input: 'tweaked', output: 'hand-edited beats' } },
+ });
+ const fresh = await svc.getIssue(i.id);
+ expect(fresh.stages.idea.output).toBe('hand-edited beats');
+ expect(fresh.stages.idea.runHistory).toEqual([]);
+ });
+
+ it('status:"generating" transition (no lastRunId) does NOT snapshot', async () => {
+ const i = await seedFirstRun();
+ await svc.updateStage(i.id, 'idea', { status: 'generating' });
+ const fresh = await svc.getIssue(i.id);
+ expect(fresh.stages.idea.runHistory).toEqual([]);
+ });
+
+ it('error after a failed generate (no new lastRunId) does NOT snapshot', async () => {
+ const i = await seedFirstRun();
+ await svc.updateStage(i.id, 'idea', { status: 'error', errorMessage: 'LLM exploded' });
+ const fresh = await svc.getIssue(i.id);
+ expect(fresh.stages.idea.runHistory).toEqual([]);
+ });
+
+ it('visual stages do NOT snapshot — only text stages have runHistory entries', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'P' });
+ await svc.updateStage(i.id, 'storyboards', { status: 'ready', output: 'v1', lastRunId: 'run-a' });
+ await svc.updateStage(i.id, 'storyboards', { status: 'ready', output: 'v2', lastRunId: 'run-b' });
+ const fresh = await svc.getIssue(i.id);
+ expect(fresh.stages.storyboards.runHistory).toEqual([]);
+ });
+
+ it('restoreStageFromHistory re-activates a snapshot and snapshots the current state', async () => {
+ const i = await seedFirstRun();
+ await svc.updateStage(i.id, 'idea', { status: 'ready', output: 'v2', lastRunId: 'run-2' });
+ // History now: [run-1]; active: run-2/'v2'.
+ const restored = await svc.restoreStageFromHistory(i.id, 'idea', 'run-1');
+ expect(restored.stage.output).toBe('first beats');
+ expect(restored.stage.input).toBe('seed');
+ expect(restored.stage.lastRunId).toBe('run-1');
+ expect(restored.stage.status).toBe('edited');
+ // Restore is itself a version event — the just-replaced run-2 should
+ // now sit at the top of history.
+ expect(restored.stage.runHistory.map((e) => e.runId)).toEqual(['run-2', 'run-1']);
+ });
+
+ it('restoreStageFromHistory rejects when runId is not in current history', async () => {
+ const i = await seedFirstRun();
+ await expect(svc.restoreStageFromHistory(i.id, 'idea', 'never-existed'))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('restoreStageFromHistory rejects non-text stage', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'P' });
+ await expect(svc.restoreStageFromHistory(i.id, 'storyboards', 'r1'))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('sanitizes hand-loaded runHistory: drops malformed entries and caps length', async () => {
+ // Simulate a hand-edited pipeline-issues.json on disk by creating an
+ // issue with a fat input.stages payload that includes a junk runHistory.
+ const oversize = Array.from({ length: 20 }, (_, n) => ({
+ runId: `r${n}`, createdAt: '2026-01-01T00:00:00Z', output: 'x', input: '',
+ }));
+ const i = await svc.createIssue({
+ seriesId: 'ser-1',
+ title: 'P',
+ stages: {
+ idea: {
+ status: 'ready', output: 'cur', lastRunId: 'cur',
+ runHistory: [
+ { /* missing runId */ output: 'no-id' },
+ null,
+ 'not-an-object',
+ ...oversize,
+ ],
+ },
+ },
+ });
+ expect(i.stages.idea.runHistory).toHaveLength(svc.STAGE_RUN_HISTORY_MAX);
+ // Order is preserved through sanitize — junk entries are dropped, then
+ // the cap takes the first N from what survives.
+ expect(i.stages.idea.runHistory.map((e) => e.runId)).toEqual(['r0', 'r1', 'r2', 'r3', 'r4']);
+ });
+ });
+
it('listIssues filters by seriesId and orders by number', async () => {
await svc.createIssue({ seriesId: 'ser-1', title: 'Issue 1' });
await svc.createIssue({ seriesId: 'ser-2', title: 'Other 1' });
@@ -522,6 +659,7 @@ describe('pipeline issues service', () => {
expect(i.stages.audio).toEqual({
status: 'empty', input: '', output: '', lastRunId: null,
errorMessage: '', updatedAt: null, lines: [], music: null, locked: false,
+ runHistory: [],
});
});