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

fix([versioning-diff-view-per-stage-persist-last-n]): address codex review

[._.]/ Adam Eivybb85438fc5cc
diff --git a/client/src/components/pipeline/stages/StageHistoryModal.jsx b/client/src/components/pipeline/stages/StageHistoryModal.jsx
index 7c7dbc507b..d0a8240c62 100644
--- a/client/src/components/pipeline/stages/StageHistoryModal.jsx
+++ b/client/src/components/pipeline/stages/StageHistoryModal.jsx
@@ -23,6 +23,7 @@ export default function StageHistoryModal({
currentOutput,
currentRunId,
runHistory = [],
+ restoreBlockedReason = null,
onRestored,
}) {
const [selectedRunId, setSelectedRunId] = useState(null);
@@ -41,7 +42,7 @@ export default function StageHistoryModal({
const [runRestore, restoring] = useAsyncAction(
async () => {
if (!selected) return null;
- return restorePipelineStageVersion(issueId, stageId, selected.runId);
+ return restorePipelineStageVersion(issueId, stageId, selected.runId, { silent: true });
},
{ errorMessage: 'Restore failed' },
);
@@ -111,8 +112,8 @@ export default function StageHistoryModal({
{/* 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">
+ <div className="flex items-center justify-between px-4 py-2 border-b border-port-border bg-port-bg/40 gap-3">
+ <div className="text-xs text-gray-500 min-w-0">
{selected ? (
<>
<span className="text-red-400">prior</span>
@@ -120,11 +121,15 @@ export default function StageHistoryModal({
<span className="text-green-400">current{currentRunId ? ` (run ${currentRunId.slice(0, 8)})` : ''}</span>
</>
) : 'Pick a version on the left to view the diff'}
+ {restoreBlockedReason ? (
+ <div className="mt-1 text-port-warning">{restoreBlockedReason}</div>
+ ) : null}
</div>
<button
type="button"
onClick={handleRestore}
- disabled={!selected || restoring}
+ disabled={!selected || restoring || !!restoreBlockedReason}
+ title={restoreBlockedReason || undefined}
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} />}
diff --git a/client/src/components/pipeline/stages/StageHistoryModal.test.jsx b/client/src/components/pipeline/stages/StageHistoryModal.test.jsx
index ed5907e9a4..7759757e62 100644
--- a/client/src/components/pipeline/stages/StageHistoryModal.test.jsx
+++ b/client/src/components/pipeline/stages/StageHistoryModal.test.jsx
@@ -94,6 +94,24 @@ describe('StageHistoryModal', () => {
expect(oldButton.className).toContain('border-port-accent');
});
+ it('disables Restore and shows the warning banner when restoreBlockedReason is set', () => {
+ render(
+ <StageHistoryModal
+ open
+ onClose={() => {}}
+ issueId="iss-1"
+ stageId="idea"
+ currentOutput="current"
+ currentRunId="run-cur"
+ runHistory={[makeEntry('run-1', 'first', 1)]}
+ restoreBlockedReason="Save or discard your unsaved edits before restoring."
+ />,
+ );
+ const restoreBtn = screen.getByRole('button', { name: /Restore this version/i });
+ expect(restoreBtn).toBeDisabled();
+ expect(screen.getByText(/Save or discard your unsaved edits/i)).toBeInTheDocument();
+ });
+
it('calls restorePipelineStageVersion and fires onRestored on success', async () => {
restorePipelineStageVersion.mockResolvedValue({
stage: { lastRunId: 'run-2', output: 'second version', runHistory: [] },
@@ -118,7 +136,7 @@ describe('StageHistoryModal', () => {
/>,
);
await user.click(screen.getByRole('button', { name: /Restore this version/i }));
- expect(restorePipelineStageVersion).toHaveBeenCalledWith('iss-1', 'idea', 'run-2');
+ expect(restorePipelineStageVersion).toHaveBeenCalledWith('iss-1', 'idea', 'run-2', { silent: true });
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 3bc361161b..d213c4c65e 100644
--- a/client/src/components/pipeline/stages/TextStagePanel.jsx
+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx
@@ -167,6 +167,7 @@ export default function TextStagePanel({
currentOutput={stage.output || ''}
currentRunId={stage.lastRunId}
runHistory={runHistory}
+ restoreBlockedReason={dirty ? 'Save or discard your unsaved edits before restoring.' : null}
onRestored={(restoredStage, restoredIssue) => {
onStageUpdate?.(stageId, restoredStage, restoredIssue);
}}
diff --git a/client/src/components/ui/InlineDiff.jsx b/client/src/components/ui/InlineDiff.jsx
index 6c1e44627a..e8c365a9f8 100644
--- a/client/src/components/ui/InlineDiff.jsx
+++ b/client/src/components/ui/InlineDiff.jsx
@@ -24,12 +24,12 @@ function lcs(a, b) {
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;
+// LCS allocates an (m+1)×(n+1) DP table; the product — not each side — is
+// what matters. Cap at ~4M cells (~16MB at 4 bytes/cell, well inside browser
+// memory for a per-modal computation). A 2000×2000 diff stays in budget;
+// a 4000×4000 (real-world comic script vs full rewrite) bails to the
+// side-by-side fallback below.
+const DIFF_CELL_CAP = 4_000_000;
const InlineDiff = memo(function InlineDiff({ oldText, newText, emptyLabel = 'No changes.' }) {
const oldStr = oldText || '';
@@ -44,7 +44,7 @@ const InlineDiff = memo(function InlineDiff({ oldText, newText, emptyLabel = 'No
</div>
);
}
- if (oldWords.length > DIFF_TOKEN_CAP || newWords.length > DIFF_TOKEN_CAP) {
+ if (oldWords.length * newWords.length > DIFF_CELL_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 --git a/client/src/components/ui/InlineDiff.test.jsx b/client/src/components/ui/InlineDiff.test.jsx
index d2992715e0..e07d9343b8 100644
--- a/client/src/components/ui/InlineDiff.test.jsx
+++ b/client/src/components/ui/InlineDiff.test.jsx
@@ -38,12 +38,20 @@ describe('InlineDiff', () => {
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" />);
+ it('bails to plain side-by-side render when m·n exceeds the DP-cell budget', () => {
+ // 2500 words on each side → 5000 tokens after whitespace split → 25M cells,
+ // well past the 4M budget; bail to the fallback.
+ const buildHuge = (prefix) => Array.from({ length: 2500 }, (_, i) => `${prefix}${i}`).join(' ');
+ const { container } = render(<InlineDiff oldText={buildHuge('a')} newText={buildHuge('b')} />);
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);
});
+
+ it('stays within the LCS path when one side is short, even if the other is long', () => {
+ // 5000 words × 2 tokens = 10K, but other side has 1 token → 10K cells (in budget).
+ const long = Array.from({ length: 5000 }, (_, i) => `w${i}`).join(' ');
+ render(<InlineDiff oldText={long} newText="x" />);
+ expect(screen.queryByText(/Diff too large/i)).not.toBeInTheDocument();
+ });
});
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 8b7c8e14ea..38c54e7149 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -131,11 +131,14 @@ export const generatePipelineVisualImage = (issueId, stageId, 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) =>
+// so restoring is reversible by clicking another snapshot. `options` accepts
+// `{ silent: true }` so callers that wrap the call in `useAsyncAction` (which
+// toasts on throw) don't double-toast when the request fails.
+export const restorePipelineStageVersion = (issueId, stageId, runId, options = {}) =>
request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/${encodeURIComponent(stageId)}/restore`, {
method: 'POST',
body: JSON.stringify({ runId }),
+ ...options,
});
// Auto-fill the storyboards stage's scenes[] from the issue's prose or
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index 40b1e7f547..076d1e4401 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -208,7 +208,14 @@ export function snapshotRunHistory(prevStage, patch, stageId) {
input: prevStage.input || '',
output: prevOutput,
};
- return [snapshot, ...prevHistory].slice(0, STAGE_RUN_HISTORY_MAX);
+ // Drop any prior entry whose runId matches the now-active runId. This is
+ // the restore case: snapshot r1 → user restores r1 → r1 becomes the active
+ // runId AND is still sitting in prevHistory. Without the filter the next
+ // regenerate would push the just-displaced state and leave a duplicate
+ // r1 in the list, breaking React keys and making restore-by-runId
+ // ambiguous (which r1 to apply?).
+ const dedupedPrior = prevHistory.filter((entry) => entry.runId !== nextRunId);
+ return [snapshot, ...dedupedPrior].slice(0, STAGE_RUN_HISTORY_MAX);
}
// Episode-video render settings the user chose at kickoff time. Persisted
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index f676570e05..9957ff3b86 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -287,9 +287,26 @@ describe('pipeline issues service', () => {
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']);
+ // Restore snapshots the just-displaced run-2 and dedups run-1 out of
+ // the prior history (it's the new active runId, so leaving it in would
+ // create a duplicate after the next regenerate).
+ expect(restored.stage.runHistory.map((e) => e.runId)).toEqual(['run-2']);
+ });
+
+ it('restore → regenerate does not leave duplicate runIds in runHistory', async () => {
+ const i = await seedFirstRun();
+ await svc.updateStage(i.id, 'idea', { status: 'ready', output: 'v2', lastRunId: 'run-2' });
+ // History: [run-1], active: run-2.
+ await svc.restoreStageFromHistory(i.id, 'idea', 'run-1');
+ // History: [run-2], active: run-1 (run-1 filtered out of prior history when displaced).
+ await svc.updateStage(i.id, 'idea', { status: 'ready', output: 'v3', lastRunId: 'run-3' });
+ const fresh = await svc.getIssue(i.id);
+ const ids = fresh.stages.idea.runHistory.map((e) => e.runId);
+ // Must contain run-1 (just displaced) and run-2 (from earlier displacement),
+ // each exactly once. Active is run-3.
+ expect(fresh.stages.idea.lastRunId).toBe('run-3');
+ expect(ids).toEqual(['run-1', 'run-2']);
+ expect(new Set(ids).size).toBe(ids.length);
});
it('restoreStageFromHistory rejects when runId is not in current history', async () => {