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

refactor([arccanvas-sync-shared-hook]): extract ArcCanvas host-wiring into useArcCanvasSync

[._.]/ Adam Eivy29ebe5e4554e
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index d6097fea7d..0bf8d4c4db 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -25,6 +25,12 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useAgentFeedbackToast` | Agent completion toast with thumbs-up/down UI. | Show actionable agent-run completion feedback. |
| `useSharingNotifications` | Subscriber for share-bucket notifications. | Wire once to surface federation/sync events. |
+## Pipeline / Story Builder wiring
+
+| Hook | Purpose | Use when |
+|---|---|---|
+| `useArcCanvasSync` | Host-side wiring for the embedded `<ArcCanvas>`: `lastSavedRef` dirty-check + `updateSeriesFromServer` / `handleIssuesUpdate` / `flushPending`. Parameterized by `flushFields` (which bible fields to flush) + `silent`/`onFlushError`. | Embedding `<ArcCanvas>` in a host that owns `series`/`issues` state (PipelineSeries, Story Builder arc step). Don't re-implement the setter contract. |
+
## Progress & streaming (SSE / socket)
| Hook | Purpose | Use when |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 7683bb725c..6cbfe32baf 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -41,6 +41,9 @@ export * from './useErrorNotifications.js';
export * from './useNotifications.js';
export * from './useSharingNotifications.js';
+// === Pipeline / Story Builder wiring ===
+export * from './useArcCanvasSync.js';
+
// === Progress & streaming (SSE / socket) ===
export * from './useImageGenProgress.js';
export * from './useImporterProgress.js';
diff --git a/client/src/hooks/useArcCanvasSync.js b/client/src/hooks/useArcCanvasSync.js
new file mode 100644
index 0000000000..0341e65a36
--- /dev/null
+++ b/client/src/hooks/useArcCanvasSync.js
@@ -0,0 +1,80 @@
+import { useCallback, useEffect, useRef } from 'react';
+import { updatePipelineSeries } from '../services/api';
+
+// Host-side wiring for the embedded <ArcCanvas>. The canvas edits `series.arc`
+// + the issue roadmap in place and expects three callbacks from its host:
+//
+// onSeriesUpdate → updateSeriesFromServer(next): a server-confirmed series
+// setter that also advances the dirty-check baseline so a
+// subsequent flushPending() doesn't re-PATCH the same state.
+// onIssuesUpdate → handleIssuesUpdate(update): accepts ArcCanvas's
+// `setState(fn)`-shaped updates AND plain arrays.
+// onFlushPending → flushPending(): if local bible fields diverged from the
+// last server snapshot, PATCH so generate / verify / resolve
+// run against the on-screen state. Returns `true` when a save
+// occurred so the caller can surface a confirmation toast.
+//
+// Both PipelineSeries and the embedded StoryBuilder arc step used to hand-roll
+// this identical contract; the only real divergence is WHICH bible fields each
+// host flushes (PipelineSeries carries 10 + cover/style overrides; StoryBuilder
+// only 6) and whether a pre-flush save failure toasts or is swallowed. Those are
+// the parameters below.
+//
+// `lastSavedRef` is a ref (not state) — we only need up-to-date comparison data
+// for the async flush, not a re-render. Its baseline is (re)captured on the
+// FIRST load of each series, keyed on `id`, so an unrelated refetch can't clobber
+// the baseline (which would defeat the dirty-check) and navigating between series
+// resets it. After capture it only advances via updateSeriesFromServer.
+
+export function useArcCanvasSync({
+ series,
+ setSeries,
+ setIssues,
+ flushFields,
+ payloadDefaults = {},
+ silent = false,
+ onFlushError,
+}) {
+ const lastSavedRef = useRef(null);
+ useEffect(() => {
+ if (series && lastSavedRef.current?.id !== series.id) lastSavedRef.current = series;
+ }, [series]);
+
+ const updateSeriesFromServer = useCallback((next) => {
+ setSeries(next);
+ lastSavedRef.current = next;
+ }, [setSeries]);
+
+ const handleIssuesUpdate = useCallback((update) => {
+ setIssues((prev) => {
+ if (typeof update === 'function') return update(prev);
+ if (Array.isArray(update)) return update;
+ return prev;
+ });
+ }, [setIssues]);
+
+ const flushPending = useCallback(async () => {
+ if (!series) return false;
+ const saved = lastSavedRef.current || series;
+ const dirty = flushFields.some((k) => (series[k] ?? '') !== (saved[k] ?? ''))
+ || JSON.stringify(series.llm || {}) !== JSON.stringify(saved.llm || {});
+ if (!dirty) return false;
+ // Build the PATCH payload from the same field list, applying any per-field
+ // empty-value default (e.g. `titleLogo: '' ` so the server clears rather than
+ // sees `undefined`). `llm` is always sent.
+ const patch = { llm: series.llm || { provider: null, model: null } };
+ for (const k of flushFields) {
+ patch[k] = k in payloadDefaults ? (series[k] || payloadDefaults[k]) : series[k];
+ }
+ const updated = await updatePipelineSeries(series.id, patch, { silent })
+ .catch((err) => {
+ if (onFlushError) onFlushError(err);
+ return null;
+ });
+ if (!updated) return false;
+ updateSeriesFromServer(updated);
+ return true;
+ }, [series, flushFields, payloadDefaults, silent, onFlushError, updateSeriesFromServer]);
+
+ return { updateSeriesFromServer, handleIssuesUpdate, flushPending, lastSavedRef };
+}
diff --git a/client/src/hooks/useArcCanvasSync.test.jsx b/client/src/hooks/useArcCanvasSync.test.jsx
new file mode 100644
index 0000000000..586e5c3273
--- /dev/null
+++ b/client/src/hooks/useArcCanvasSync.test.jsx
@@ -0,0 +1,115 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import { useState } from 'react';
+
+const updatePipelineSeries = vi.fn();
+vi.mock('../services/api', () => ({
+ updatePipelineSeries: (...args) => updatePipelineSeries(...args),
+}));
+
+import { useArcCanvasSync } from './useArcCanvasSync.js';
+
+// Drive the hook with real useState setters so the lastSavedRef effect and the
+// server-confirmed setter interact the way they do in the host pages.
+function useHarness(initialSeries, initialIssues, opts) {
+ const [series, setSeries] = useState(initialSeries);
+ const [issues, setIssues] = useState(initialIssues);
+ const sync = useArcCanvasSync({ series, setSeries, setIssues, ...opts });
+ return { series, issues, setSeries, ...sync };
+}
+
+const FLUSH_FIELDS = ['name', 'logline', 'premise', 'styleNotes', 'issueCountTarget', 'universeId'];
+
+beforeEach(() => {
+ updatePipelineSeries.mockReset();
+});
+
+describe('useArcCanvasSync', () => {
+ it('flushPending is a no-op when nothing diverged from the server snapshot', async () => {
+ const series = { id: 's1', name: 'A', logline: 'L', llm: { provider: 'p', model: 'm' } };
+ const { result } = renderHook(() => useHarness(series, [], { flushFields: FLUSH_FIELDS }));
+
+ let did;
+ await act(async () => { did = await result.current.flushPending(); });
+ expect(did).toBe(false);
+ expect(updatePipelineSeries).not.toHaveBeenCalled();
+ });
+
+ it('flushPending PATCHes when a tracked field diverged, then advances the baseline', async () => {
+ const server = { id: 's1', name: 'A', logline: 'L', llm: null };
+ updatePipelineSeries.mockResolvedValue({ ...server, name: 'B' });
+ const { result } = renderHook(() => useHarness(server, [], { flushFields: FLUSH_FIELDS, silent: true }));
+
+ // Diverge the local draft (un-persisted edit ArcCanvas would flush).
+ act(() => { result.current.setSeries((s) => ({ ...s, name: 'B' })); });
+
+ let did;
+ await act(async () => { did = await result.current.flushPending(); });
+ expect(did).toBe(true);
+ expect(updatePipelineSeries).toHaveBeenCalledWith('s1', expect.objectContaining({ name: 'B' }), { silent: true });
+
+ // Baseline advanced → a second flush with no new edits is a no-op.
+ updatePipelineSeries.mockClear();
+ await act(async () => { did = await result.current.flushPending(); });
+ expect(did).toBe(false);
+ expect(updatePipelineSeries).not.toHaveBeenCalled();
+ });
+
+ it('applies payloadDefaults for empty optional fields', async () => {
+ const server = { id: 's1', name: 'A', titleLogo: '', author: '' };
+ updatePipelineSeries.mockResolvedValue({ ...server });
+ const { result } = renderHook(() => useHarness(server, [], {
+ flushFields: ['name', 'titleLogo', 'author'],
+ payloadDefaults: { titleLogo: '', author: '' },
+ silent: true,
+ }));
+
+ act(() => { result.current.setSeries((s) => ({ ...s, name: 'B', titleLogo: undefined })); });
+ await act(async () => { await result.current.flushPending(); });
+
+ const patch = updatePipelineSeries.mock.calls[0][1];
+ expect(patch.titleLogo).toBe('');
+ expect(patch.author).toBe('');
+ expect(patch.name).toBe('B');
+ });
+
+ it('calls onFlushError and returns false when the PATCH rejects', async () => {
+ const server = { id: 's1', name: 'A' };
+ updatePipelineSeries.mockRejectedValue(new Error('boom'));
+ const onFlushError = vi.fn();
+ const { result } = renderHook(() => useHarness(server, [], {
+ flushFields: FLUSH_FIELDS, silent: true, onFlushError,
+ }));
+
+ act(() => { result.current.setSeries((s) => ({ ...s, name: 'B' })); });
+ let did;
+ await act(async () => { did = await result.current.flushPending(); });
+ expect(did).toBe(false);
+ expect(onFlushError).toHaveBeenCalledWith(expect.any(Error));
+ });
+
+ it('handleIssuesUpdate accepts both functional and array updates', () => {
+ const { result } = renderHook(() => useHarness({ id: 's1' }, [{ id: 'i1' }], { flushFields: FLUSH_FIELDS }));
+
+ act(() => { result.current.handleIssuesUpdate((prev) => [...prev, { id: 'i2' }]); });
+ expect(result.current.issues.map((i) => i.id)).toEqual(['i1', 'i2']);
+
+ act(() => { result.current.handleIssuesUpdate([{ id: 'i3' }]); });
+ expect(result.current.issues.map((i) => i.id)).toEqual(['i3']);
+
+ // Non-array / non-function update is ignored.
+ act(() => { result.current.handleIssuesUpdate('nope'); });
+ expect(result.current.issues.map((i) => i.id)).toEqual(['i3']);
+ });
+
+ it('updateSeriesFromServer keeps the baseline aligned so a follow-up flush is a no-op', async () => {
+ const server = { id: 's1', name: 'A' };
+ const { result } = renderHook(() => useHarness(server, [], { flushFields: FLUSH_FIELDS }));
+
+ act(() => { result.current.updateSeriesFromServer({ id: 's1', name: 'Z' }); });
+ let did;
+ await act(async () => { did = await result.current.flushPending(); });
+ expect(did).toBe(false);
+ expect(updatePipelineSeries).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index 7005b1fa98..4c6e45e100 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -10,7 +10,7 @@
* Mobile (< lg): single column, sidebar reflows above canvas.
*/
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useState } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import {
ArrowLeft, Save, Loader2, Workflow as WorkflowIcon, Globe, NotebookPen,
@@ -29,6 +29,7 @@ import {
} from '../services/api';
import { recommendStructure, describeStructure } from '../lib/seasonStructure';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
+import { useArcCanvasSync } from '../hooks/useArcCanvasSync';
const PIPELINE_SIDEBAR_KEY = 'portos-pipeline-series-sidebar-collapsed';
@@ -41,6 +42,20 @@ const STYLE_OVERRIDE_MODE_TABS = [
{ id: 'override', label: 'Replace' },
];
+// Bible fields the host flushes before an ArcCanvas generate/verify, plus the
+// empty-value defaults the server expects for the optional ones. Module-level
+// constants so the `useArcCanvasSync` callbacks keep a stable identity.
+const ARC_FLUSH_FIELDS = [
+ 'name', 'logline', 'premise', 'styleNotes', 'titleLogo', 'author',
+ 'stylePromptOverride', 'stylePromptOverrideMode', 'issueCountTarget', 'universeId',
+];
+const ARC_PAYLOAD_DEFAULTS = {
+ titleLogo: '',
+ author: '',
+ stylePromptOverride: '',
+ stylePromptOverrideMode: STYLE_OVERRIDE_MODE_DEFAULT,
+};
+
export default function PipelineSeries() {
const { seriesId } = useParams();
const navigate = useNavigate();
@@ -79,54 +94,20 @@ export default function PipelineSeries() {
const toggleSidebar = () => setSidebarCollapsed((prev) => !prev);
- // Track the last server-persisted snapshot so `flushPending` knows whether
- // the local draft has diverged. Ref instead of state — we don't want
- // re-renders, just up-to-date comparison data for the async LLM hooks below.
- const lastSavedRef = useRef(null);
- useEffect(() => { if (series && !lastSavedRef.current) lastSavedRef.current = series; }, [series]);
-
const patchSeries = (patch) => setSeries((prev) => ({ ...prev, ...patch }));
- // Wrapped setter that ArcCanvas (and other LLM-flow children) use when the
- // server has just confirmed a save. Keeps the dirty-check ref aligned so a
- // subsequent flushPending() doesn't re-PATCH the same state.
- const updateSeriesFromServer = (next) => {
- setSeries(next);
- lastSavedRef.current = next;
- };
-
- // If local bible fields diverged from the last server snapshot, PATCH so
- // generate / verify / resolve work against the on-screen state. Returns
- // `true` if a save occurred so the caller can decide whether to surface a
- // confirmation toast.
- const flushPending = async () => {
- if (!series) return false;
- const saved = lastSavedRef.current || series;
- const fields = ['name', 'logline', 'premise', 'styleNotes', 'titleLogo', 'author', 'stylePromptOverride', 'stylePromptOverrideMode', 'issueCountTarget', 'universeId'];
- const dirty = fields.some((k) => (series[k] ?? '') !== (saved[k] ?? ''))
- || JSON.stringify(series.llm || {}) !== JSON.stringify(saved.llm || {});
- if (!dirty) return false;
- const updated = await updatePipelineSeries(series.id, {
- name: series.name,
- logline: series.logline,
- premise: series.premise,
- universeId: series.universeId,
- styleNotes: series.styleNotes,
- titleLogo: series.titleLogo || '',
- author: series.author || '',
- stylePromptOverride: series.stylePromptOverride || '',
- stylePromptOverrideMode: series.stylePromptOverrideMode || STYLE_OVERRIDE_MODE_DEFAULT,
- issueCountTarget: series.issueCountTarget,
- llm: series.llm || { provider: null, model: null },
- }).catch((err) => {
- toast.error(`Pre-flush save failed: ${err.message}`);
- return null;
- });
- if (!updated) return false;
- setSeries(updated);
- lastSavedRef.current = updated;
- return true;
- };
+ // Host-side ArcCanvas wiring (lastSavedRef dirty-check + server-confirmed
+ // setters). Flushes the full bible field-set; a pre-flush failure surfaces a
+ // toast (non-silent) so the user knows their edits didn't persist.
+ const { updateSeriesFromServer, handleIssuesUpdate, flushPending } = useArcCanvasSync({
+ series,
+ setSeries,
+ setIssues,
+ flushFields: ARC_FLUSH_FIELDS,
+ payloadDefaults: ARC_PAYLOAD_DEFAULTS,
+ silent: true,
+ onFlushError: (err) => toast.error(`Pre-flush save failed: ${err.message}`),
+ });
const handleSave = async () => {
if (!series) return;
@@ -136,18 +117,6 @@ export default function PipelineSeries() {
if (didSave) toast.success('Series saved');
};
- // ArcCanvas mutates issues via a setter-style update (`setState(fn)`-shaped)
- // so child components can do prev-aware patches without parent intervention.
- // Plain array updates also work — flatten through `Array.isArray` to keep
- // both shapes supported.
- const handleIssuesUpdate = (update) => {
- setIssues((prev) => {
- if (typeof update === 'function') return update(prev);
- if (Array.isArray(update)) return update;
- return prev;
- });
- };
-
if (loading) return <div className="p-6 text-gray-500 text-sm">Loading series…</div>;
if (!series) return null;
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index 839bb1dd4e..095ef9f6d6 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -19,15 +19,22 @@ import {
getStoryBuilderSteps, listStorySessions, getStorySession, createStorySession,
updateStorySession, setStoryCurrentStep, lockStoryStep, unlockStoryStep,
generateStoryStep, refineStoryStep, setStoryIssueLock, generateStoryIssues,
- getUniverse, getPipelineSeries, listPipelineIssues, updatePipelineSeries,
+ getUniverse, getPipelineSeries, listPipelineIssues,
analyzeImport, commitImport, retryImporterIssues, IMPORTER_CONTENT_TYPES,
getProviders, getSettings, generateImage, updateUniverse,
} from '../services/api';
import ArcCanvas from '../components/pipeline/ArcCanvas';
+import { useArcCanvasSync } from '../hooks/useArcCanvasSync';
import { BEAT_KIND_COLORS, getBeatKindColor } from '../lib/beatColors';
// Mirror Importer.jsx's commit picker — only these arc fields are sent on commit.
const ARC_FIELDS_TO_COMMIT = ['logline', 'summary', 'protagonistArc', 'themes', 'shape'];
+
+// Bible fields the embedded arc step flushes before an ArcCanvas generate/verify.
+// The Story Builder edits these on their own steps (not inside the arc step), so
+// the flush is usually a no-op — kept for API-shape parity with ArcCanvas's
+// contract. Module-level so the `useArcCanvasSync` callbacks keep a stable identity.
+const ARC_FLUSH_FIELDS = ['name', 'logline', 'premise', 'styleNotes', 'issueCountTarget', 'universeId'];
const pickArcFields = (arc) => {
if (!arc) return null;
const out = {};
@@ -1005,58 +1012,16 @@ function StoryBuilderDetail({ storyId, stepParam }) {
// ── Embedded ArcCanvas wiring (plotArc step) ──────────────────────────────
// The Arc Canvas edits series.arc + the issue roadmap in place, so it needs
- // server-confirmed setters. Mirrors PipelineSeries.jsx: a `lastSavedRef`
- // dirty-check, an `updateSeriesFromServer` that keeps it aligned, and an
- // issues setter that accepts ArcCanvas's `setState(fn)`-shaped updates.
- const lastSavedRef = useRef(null);
- // Capture the server snapshot as the dirty-check baseline, but only on the
- // FIRST load of each series (keyed on id) — NOT on every `series` change,
- // which would clobber the baseline on an unrelated refetch and defeat
- // flushPending's dirty-check (it would always see series === lastSaved).
- // Re-keying on id also resets the baseline when this mounted detail view
- // navigates to a different story/series. After capture, the ref only advances
- // via updateSeriesFromServer (a server-confirmed save).
- useEffect(() => {
- if (series && lastSavedRef.current?.id !== series.id) lastSavedRef.current = series;
- }, [series]);
-
- const updateSeriesFromServer = useCallback((next) => {
- setSeries(next);
- lastSavedRef.current = next;
- }, []);
-
- // ArcCanvas mutates issues via a setter-style update (`setState(fn)`-shaped);
- // plain arrays also work — flatten through Array.isArray to support both.
- const handleIssuesUpdate = useCallback((update) => {
- setIssues((prev) => {
- if (typeof update === 'function') return update(prev);
- if (Array.isArray(update)) return update;
- return prev;
- });
- }, []);
-
- // ArcCanvas calls this before a generate/verify so the server works against
- // the on-screen bible fields. The Story Builder edits those fields on their
- // own steps (not inside the arc step), so the only divergence to flush here
- // is whatever ArcCanvas itself set via updateSeriesFromServer — which already
- // persisted. So flush is a no-op unless a future inline bible edit lands;
- // kept for API-shape parity with ArcCanvas's contract.
- const flushPending = useCallback(async () => {
- if (!series) return false;
- const saved = lastSavedRef.current || series;
- const fields = ['name', 'logline', 'premise', 'styleNotes', 'issueCountTarget', 'universeId'];
- const dirty = fields.some((k) => (series[k] ?? '') !== (saved[k] ?? ''))
- || JSON.stringify(series.llm || {}) !== JSON.stringify(saved.llm || {});
- if (!dirty) return false;
- const updated = await updatePipelineSeries(series.id, {
- name: series.name, logline: series.logline, premise: series.premise,
- universeId: series.universeId, styleNotes: series.styleNotes,
- issueCountTarget: series.issueCountTarget, llm: series.llm || { provider: null, model: null },
- }, { silent: true }).catch(() => null);
- if (!updated) return false;
- updateSeriesFromServer(updated);
- return true;
- }, [series, updateSeriesFromServer]);
+ // server-confirmed setters. The flush is usually a no-op here (the bible
+ // fields are edited on their own steps, not inside the arc step), so a
+ // pre-flush save failure is swallowed (silent) rather than toasted.
+ const { updateSeriesFromServer, handleIssuesUpdate, flushPending } = useArcCanvasSync({
+ series,
+ setSeries,
+ setIssues,
+ flushFields: ARC_FLUSH_FIELDS,
+ silent: true,
+ });
// Load the step manifest first; gate the loading spinner on BOTH it and the
// session so the detail view never renders with an empty step rail.