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(pipeline): extend in-flight save gating + finish file-level write serialization

[._.]/ Adam Eivyc6254cf3476c
diff --git a/client/src/components/pipeline/stages/ComicPagesStage.jsx b/client/src/components/pipeline/stages/ComicPagesStage.jsx
index 8715a2372c..bcb150268b 100644
--- a/client/src/components/pipeline/stages/ComicPagesStage.jsx
+++ b/client/src/components/pipeline/stages/ComicPagesStage.jsx
@@ -19,7 +19,7 @@ import { genConfigToImageOptions, genConfigToRefineOptions } from './VisualGenSe
// pure per-panel editor so a future view that lands directly here still
// works.
-export default function ComicPagesStage({ issue, onStageUpdate }) {
+export default function ComicPagesStage({ issue, onStageUpdate, actionsGated = false }) {
const stage = issue.stages?.comicPages || { status: 'empty', pages: [] };
const [pages, setPages] = useState(stage.pages || []);
const genConfig = stage.genConfig || null;
@@ -218,8 +218,8 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {
<button
type="button"
onClick={() => handleGeneratePage(pi)}
- disabled={renderingPages.has(pi) || !(page.panels?.length > 0)}
- title="Render the entire page as one image — recommended for Codex / cloud image models. Local models will produce draft-quality results."
+ disabled={renderingPages.has(pi) || !(page.panels?.length > 0) || actionsGated}
+ title={actionsGated ? 'Saving settings…' : 'Render the entire page as one image — recommended for Codex / cloud image models. Local models will produce draft-quality results.'}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-xs font-medium hover:bg-port-accent/90 disabled:opacity-40 disabled:cursor-not-allowed"
>
{renderingPages.has(pi)
@@ -262,8 +262,8 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {
<button
type="button"
onClick={() => handleRefinePanel(pi, ni)}
- disabled={refiningKey !== null}
- title="Elaborate this panel description into a richer image-gen prompt (LLM call — replaces the current text)"
+ disabled={refiningKey !== null || actionsGated}
+ title={actionsGated ? 'Saving settings…' : 'Elaborate this panel description into a richer image-gen prompt (LLM call — replaces the current text)'}
className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-card border border-port-border text-white text-xs hover:border-port-accent/50 disabled:opacity-50"
>
{refiningKey === `${pi}:${ni}` ? <Loader2 size={12} className="animate-spin" /> : <WandSparkles size={12} />}
@@ -272,7 +272,8 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {
<button
type="button"
onClick={() => handleGeneratePanel(pi, ni)}
- disabled={savingIdx === `${pi}:${ni}`}
+ disabled={savingIdx === `${pi}:${ni}` || actionsGated}
+ title={actionsGated ? 'Saving settings…' : undefined}
className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-accent text-white text-xs disabled:opacity-50"
>
{savingIdx === `${pi}:${ni}` ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsx
index 0608d853a4..02feba1ad9 100644
--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx
+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx
@@ -58,7 +58,7 @@ function panelsToMarkdown(panels, pageNumber) {
return lines.join('\n').trim();
}
-export default function ComicScriptStage({ issue, series, onStageUpdate }) {
+export default function ComicScriptStage({ issue, series, onStageUpdate, actionsGated = false }) {
const script = issue.stages?.comicScript || { status: 'empty', output: '' };
const comicPages = issue.stages?.comicPages || { status: 'empty', pages: [] };
const pages = Array.isArray(comicPages.pages) ? comicPages.pages : [];
@@ -212,7 +212,7 @@ export default function ComicScriptStage({ issue, series, onStageUpdate }) {
const result = await generatePipelineComicCover(issue.id, {
coverScript: draftCoverScript || '',
...renderOpts,
- }).catch((err) => {
+ }, { silent: true }).catch((err) => {
toast.error(err.message || 'Failed to render cover');
return null;
});
@@ -293,9 +293,9 @@ export default function ComicScriptStage({ issue, series, onStageUpdate }) {
<button
type="button"
onClick={handleGenerate}
- disabled={generating || extracting}
+ disabled={generating || extracting || actionsGated}
className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
- title="Re-adapt the prose into a fresh comic script and split it into pages"
+ title={actionsGated ? 'Saving settings…' : 'Re-adapt the prose into a fresh comic script and split it into pages'}
>
{generating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
{hasScript ? 'Re-generate pages' : 'Generate pages'}
@@ -322,10 +322,12 @@ export default function ComicScriptStage({ issue, series, onStageUpdate }) {
<button
type="button"
onClick={handleRenderCover}
- disabled={renderingCover || coverJobInFlight}
- title={coverJobInFlight
- ? 'Cover render in progress…'
- : 'Render the issue\'s front cover — series masthead + issue number tag + your cover concept.'}
+ disabled={renderingCover || coverJobInFlight || actionsGated}
+ title={actionsGated
+ ? 'Saving settings…'
+ : coverJobInFlight
+ ? 'Cover render in progress…'
+ : 'Render the issue\'s front cover — series masthead + issue number tag + your cover concept.'}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-xs font-medium hover:bg-port-accent/90 disabled:opacity-40 disabled:cursor-not-allowed"
>
{(renderingCover || coverJobInFlight) ? <Loader2 size={12} className="animate-spin" /> : <ImageIcon size={12} />}
diff --git a/client/src/components/pipeline/stages/IdeaStage.jsx b/client/src/components/pipeline/stages/IdeaStage.jsx
index 0c5fb851cb..69a8e6b26a 100644
--- a/client/src/components/pipeline/stages/IdeaStage.jsx
+++ b/client/src/components/pipeline/stages/IdeaStage.jsx
@@ -30,7 +30,7 @@ ${block}`;
}
export default function IdeaStage(props) {
- const { issue, series, onStageUpdate } = props;
+ const { issue, series, onStageUpdate, actionsGated = false } = props;
const output = issue.stages?.idea?.output || '';
const seedInput = issue.stages?.idea?.input || '';
const questions = useMemo(() => parseOpenQuestions(output), [output]);
@@ -64,6 +64,7 @@ export default function IdeaStage(props) {
generateLabel="Generate beat sheet"
seedPlaceholder="A rough idea for this issue — a single sentence is fine. The LLM expands it into a beat sheet."
outputPlaceholder="The generated beat sheet will appear here. You can edit it freely; downstream stages use this content verbatim as upstream context."
+ actionsGated={actionsGated}
/>
{questions.length > 0 ? (
@@ -75,9 +76,9 @@ export default function IdeaStage(props) {
<button
type="button"
onClick={handleRefine}
- disabled={refining}
+ disabled={refining || actionsGated}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium border bg-port-bg text-port-warning border-port-warning/40 hover:bg-port-warning/10 disabled:opacity-40"
- title="Re-run the beat sheet, folding your answers in and dropping the open-questions section"
+ title={actionsGated ? 'Saving settings…' : 'Re-run the beat sheet, folding your answers in and dropping the open-questions section'}
>
{refining ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}
Refine with answers
diff --git a/client/src/components/pipeline/stages/StoryboardsStage.jsx b/client/src/components/pipeline/stages/StoryboardsStage.jsx
index c1336be420..1b7eccffe0 100644
--- a/client/src/components/pipeline/stages/StoryboardsStage.jsx
+++ b/client/src/components/pipeline/stages/StoryboardsStage.jsx
@@ -29,7 +29,7 @@ import {
import MediaJobThumb from '../MediaJobThumb';
import { genConfigToImageOptions, genConfigToRefineOptions } from './VisualGenSettings';
-export default function StoryboardsStage({ issue, onStageUpdate }) {
+export default function StoryboardsStage({ issue, onStageUpdate, actionsGated = false }) {
const stage = issue.stages?.storyboards || { status: 'empty', scenes: [] };
const [scenes, setScenes] = useState(stage.scenes || []);
// Per-stage gen config — edited from the page-level settings modal.
@@ -266,8 +266,8 @@ export default function StoryboardsStage({ issue, onStageUpdate }) {
<button
type="button"
onClick={() => handleRefinePrompt(i)}
- disabled={refiningIdx !== null}
- title="Elaborate this description into a richer image-gen prompt (LLM call — replaces the current text)"
+ disabled={refiningIdx !== null || actionsGated}
+ title={actionsGated ? 'Saving settings…' : 'Elaborate this description into a richer image-gen prompt (LLM call — replaces the current text)'}
className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-card border border-port-border text-white text-xs hover:border-port-accent/50 disabled:opacity-50"
>
{refiningIdx === i ? <Loader2 size={12} className="animate-spin" /> : <WandSparkles size={12} />}
@@ -276,7 +276,8 @@ export default function StoryboardsStage({ issue, onStageUpdate }) {
<button
type="button"
onClick={() => handleGenerate(i)}
- disabled={savingIdx === i}
+ disabled={savingIdx === i || actionsGated}
+ title={actionsGated ? 'Saving settings…' : undefined}
className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-accent text-white text-xs disabled:opacity-50"
>
{savingIdx === i ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
@@ -285,8 +286,8 @@ export default function StoryboardsStage({ issue, onStageUpdate }) {
<button
type="button"
onClick={() => handleGenerateVideo(i)}
- disabled={renderingVideoIdx !== null}
- title="Render this scene as a video clip (independent of the full episode-video stitch)"
+ disabled={renderingVideoIdx !== null || actionsGated}
+ title={actionsGated ? 'Saving settings…' : 'Render this scene as a video clip (independent of the full episode-video stitch)'}
className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-card border border-port-border text-white text-xs hover:border-port-accent/50 disabled:opacity-50"
>
{renderingVideoIdx === i ? <Loader2 size={12} className="animate-spin" /> : <Film size={12} />}
diff --git a/client/src/components/pipeline/stages/TextStagePanel.jsx b/client/src/components/pipeline/stages/TextStagePanel.jsx
index c57368c80a..53014ee1a4 100644
--- a/client/src/components/pipeline/stages/TextStagePanel.jsx
+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx
@@ -25,6 +25,7 @@ export default function TextStagePanel({
outputPlaceholder,
generateLabel = 'Generate',
extraActions = null,
+ actionsGated = false,
}) {
const stage = issue.stages?.[stageId] || { status: 'empty', input: '', output: '' };
const [draftOutput, setDraftOutput] = useState(stage.output || '');
@@ -107,7 +108,8 @@ export default function TextStagePanel({
<button
type="button"
onClick={handleGenerate}
- disabled={generating}
+ disabled={generating || actionsGated}
+ title={actionsGated ? 'Saving settings…' : undefined}
className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
>
{generating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsx
index 51ad455d49..cd48ed2abc 100644
--- a/client/src/pages/PipelineIssue.jsx
+++ b/client/src/pages/PipelineIssue.jsx
@@ -85,6 +85,7 @@ export default function PipelineIssue() {
const [autoRunActive, setAutoRunActive] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [lengthProfileSaving, setLengthProfileSaving] = useState(false);
+ const [genConfigSaving, setGenConfigSaving] = useState(false);
// Close the settings modal whenever the active stage changes so it doesn't
// reopen unexpectedly when the user returns to a previously-visited stage.
useEffect(() => { setSettingsOpen(false); }, [stageId]);
@@ -160,12 +161,13 @@ export default function PipelineIssue() {
// visual stage owns the config record (we keep per-stage genConfig so a
// user can pin "codex" for comicPages but "local" for storyboards).
const handleGenConfigChange = async (next) => {
+ setGenConfigSaving(true);
const updated = await updatePipelineIssue(issueId, {
stages: { [stageId]: { genConfig: next } },
}).catch((err) => {
toast.error(err.message || 'Save failed');
return null;
- });
+ }).finally(() => setGenConfigSaving(false));
if (updated) setIssue(updated);
};
@@ -240,9 +242,9 @@ export default function PipelineIssue() {
<button
type="button"
onClick={() => handleAutoRun({})}
- disabled={autoRunStarting || autoRunActive || lengthProfileSaving}
+ disabled={autoRunStarting || autoRunActive || lengthProfileSaving || genConfigSaving}
className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
- title={lengthProfileSaving ? 'Saving length profile…' : 'Run idea → prose → (comic script + TV script) end to end'}
+ title={lengthProfileSaving ? 'Saving length profile…' : genConfigSaving ? 'Saving visual settings…' : 'Run idea → prose → (comic script + TV script) end to end'}
>
{autoRunStarting || autoRunActive ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
Auto-run text
@@ -250,9 +252,9 @@ export default function PipelineIssue() {
<button
type="button"
onClick={() => handleAutoRun({ includeVideo: true })}
- disabled={autoRunStarting || autoRunActive || lengthProfileSaving}
+ disabled={autoRunStarting || autoRunActive || lengthProfileSaving || genConfigSaving}
className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-accent/40 text-white text-sm font-medium disabled:opacity-50 hover:bg-port-accent/10"
- title={lengthProfileSaving ? 'Saving length profile…' : 'Run text stages and then kick off episode video via Creative Director (burns GPU)'}
+ title={lengthProfileSaving ? 'Saving length profile…' : genConfigSaving ? 'Saving visual settings…' : 'Run text stages and then kick off episode video via Creative Director (burns GPU)'}
>
{autoRunStarting || autoRunActive ? <Loader2 size={14} className="animate-spin" /> : <Clapperboard size={14} />}
Run everything (incl. video)
@@ -310,7 +312,13 @@ export default function PipelineIssue() {
{/* Active stage panel */}
<div className="flex-1 overflow-auto p-4 md:p-6">
{StageComponent ? (
- <StageComponent issue={issue} series={series} onStageUpdate={handleStageUpdate} onSeriesUpdate={setSeries} />
+ <StageComponent
+ issue={issue}
+ series={series}
+ onStageUpdate={handleStageUpdate}
+ onSeriesUpdate={setSeries}
+ actionsGated={lengthProfileSaving || genConfigSaving}
+ />
) : (
<div className="text-gray-500 text-sm">Unknown stage.</div>
)}
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index f51a45e984..a9125bffdf 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -156,10 +156,11 @@ export const generatePipelineComicPage = (issueId, pageIndex, opts = {}) =>
// the next reload reflects what was rendered). Server folds in series
// name, issue number, issue title, and style notes — caller only owns the
// cover-concept text. Returns { jobId, mode, prompt, cover, issue, stage }.
-export const generatePipelineComicCover = (issueId, opts = {}) =>
+export const generatePipelineComicCover = (issueId, opts = {}, options = {}) =>
request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/comicPages/cover/render`, {
method: 'POST',
body: JSON.stringify(opts),
+ ...options,
});
// Patch one comic page's raw markdown — the server re-parses panels from the
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index fa05710405..b5feb00acf 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -823,18 +823,27 @@ router.post('/issues/:id/stages/comicPages/extract-pages', asyncHandler(async (r
// clear any prior imageJobId / prompt — they were rendered against the old
// (likely placeholder / fallback) script, so leaving them would show a
// rendered cover image that doesn't match the new concept text.
- const existingCover = issue.stages?.comicPages?.cover || null;
- const existingCoverScript = existingCover?.script || '';
- const nextCover = coverConcept && !existingCoverScript
- ? { script: coverConcept, imageJobId: null, prompt: null }
- : existingCover;
-
- const { issue: updatedIssue, stage } = await issuesSvc.updateStage(issue.id, 'comicPages', {
- status: pages.length ? 'ready' : 'empty',
- pages,
- cover: nextCover,
- errorMessage: '',
- });
+ //
+ // The decision is made inside updateStageWithLatest so it reads the freshest
+ // persisted cover, not the stale snapshot from the getIssue read above. A
+ // concurrent cover/render call that writes imageJobId between the two awaits
+ // would otherwise be silently overwritten.
+ const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(
+ issue.id,
+ 'comicPages',
+ (currentStage) => {
+ const currentCoverScript = currentStage?.cover?.script || '';
+ const nextCover = coverConcept && !currentCoverScript
+ ? { script: coverConcept, imageJobId: null, prompt: null }
+ : currentStage?.cover ?? null;
+ return {
+ status: pages.length ? 'ready' : 'empty',
+ pages,
+ cover: nextCover,
+ errorMessage: '',
+ };
+ },
+ );
const panelCount = pages.reduce((n, p) => n + (p.panels?.length || 0), 0);
res.json({
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index c6761cc434..bd36527177 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -278,11 +278,12 @@ export async function getIssue(id) {
return found;
}
-export async function createIssue(input = {}) {
+export function createIssue(input = {}) {
const seriesId = trimTo(input.seriesId, SERIES_ID_MAX);
- if (!seriesId) throw makeErr('seriesId is required', ERR_VALIDATION);
+ if (!seriesId) return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));
const title = trimTo(input.title, TITLE_MAX);
- if (!title) throw makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION);
+ if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));
+ return queueIssueWrite(null, async () => {
const state = await readState();
const next = sanitizeIssue({
id: `iss-${randomUUID()}`,
@@ -305,6 +306,7 @@ export async function createIssue(input = {}) {
state.issues.push(next);
await writeState(state);
return next;
+ }); // end queueIssueWrite
}
function nextIssueNumber(issues, seriesId) {
@@ -393,8 +395,38 @@ export function updateIssue(id, patch = {}) {
* a stage write doesn't have to load the full issue, mutate, and re-validate.
* Patch keys: status, input, output, lastRunId, errorMessage, and (for
* visual stages) pages/scenes/cdProjectId/videoPath.
+ *
+ * When the patch depends on the current stage value (e.g. cover preservation),
+ * use `updateStageWithLatest` instead so the decision is made against the
+ * freshest persisted record inside the serialized write region.
*/
export function updateStage(issueId, stageId, patch = {}) {
+ return updateStageWithLatest(issueId, stageId, () => patch);
+}
+
+export function deleteIssue(id) {
+ return queueIssueWrite(id, async () => {
+ const state = await readState();
+ const before = state.issues.length;
+ state.issues = state.issues.filter((i) => i.id !== id);
+ if (state.issues.length === before) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+ await writeState(state);
+ return { id };
+ }); // end queueIssueWrite
+}
+
+/**
+ * Like `updateStage`, but the patch is computed from the *latest* persisted
+ * stage inside the serialized write region. Use this when the patch value
+ * depends on the current stage state (e.g. cover preservation) so a concurrent
+ * write that lands between the outer `getIssue` read and this call is not
+ * silently overwritten.
+ *
+ * `computeFn(currentStage) → patch` — called with the freshest stage record
+ * inside the queue; its return value is shallow-merged over the stage exactly
+ * as `updateStage` merges a static patch.
+ */
+export function updateStageWithLatest(issueId, stageId, computeFn) {
if (!STAGE_IDS.includes(stageId)) {
// Validate before queueing so the caller gets an immediate rejection
// rather than waiting in line for an error it already knows about.
@@ -406,8 +438,10 @@ export function updateStage(issueId, stageId, patch = {}) {
if (idx < 0) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);
const cur = state.issues[idx];
const isVisual = VISUAL_STAGE_IDS.includes(stageId);
+ const currentStage = cur.stages[stageId];
+ const patch = computeFn(currentStage);
const merged = {
- ...cur.stages[stageId],
+ ...currentStage,
...patch,
updatedAt: new Date().toISOString(),
};
@@ -422,12 +456,3 @@ export function updateStage(issueId, stageId, patch = {}) {
return { issue: mergedIssue, stage: mergedIssue.stages[stageId] };
}); // end queueIssueWrite
}
-
-export async function deleteIssue(id) {
- const state = await readState();
- const before = state.issues.length;
- state.issues = state.issues.filter((i) => i.id !== id);
- if (state.issues.length === before) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
- await writeState(state);
- return { id };
-}