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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: keep unsaved series bible edits when another series action saves (#8423)
[._.]/ Adam Eivy69b01c626fa5
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex e62163712a..1054ab04c1 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -34,7 +34,7 @@ grep -i "what you want to do" client/src/hooks/README.md| 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. |+| `useArcCanvasSync` | Host-side wiring for the embedded `<ArcCanvas>`: `lastSavedRef` dirty-check + `updateSeriesFromServer` (merges, keeping pending bible edits) / `handleIssuesUpdate` / `flushPending` / `isDirty` (for `useUnsavedChangesGuard`). 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)diff --git a/client/src/hooks/useArcCanvasSync.js b/client/src/hooks/useArcCanvasSync.jsindex d7dedd6fec..702293fb51 100644--- a/client/src/hooks/useArcCanvasSync.js+++ b/client/src/hooks/useArcCanvasSync.js@@ -34,6 +34,24 @@ import { updatePipelineSeries } from '../services/api';// 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.+//+// updateSeriesFromServer MERGES rather than replaces (#8423). Sibling actions+// (format select, render pin, logo generation, season add, theme chips, a cover+// render landing, autopilot/review refetches) hand it a whole record while the+// user still has unsaved bible edits. A bible field is "pending" when the local+// value differs from the baseline; pending fields keep their local value AND+// their old baseline, so they stay dirty and the next Save still PATCHes them.+// Keeping the old baseline (not `next[k]`) matters because several callers build+// `next` from the local `series` (`{ ...series, seasons }`), which already+// carries the unsaved text — adopting it would mark those edits saved without+// any PATCH. Every other field takes the incoming value on both sides. Only+// flushPending, which knows its record came back from the bible PATCH, adopts+// the response wholesale as the new baseline.++const fieldValue = (record, k) => (k === 'llm' ? JSON.stringify(record?.llm || {}) : (record?.[k] ?? ''));+const pendingFields = (series, saved, flushFields) => (+ series && saved ? [...flushFields, 'llm'].filter((k) => fieldValue(series, k) !== fieldValue(saved, k)) : []+);export function useArcCanvasSync({series,@@ -45,7 +63,10 @@ export function useArcCanvasSync({onFlushError,}) {const lastSavedRef = useRef(null);+ // Latest committed local state, for server updates that land after an await.+ const latestSeriesRef = useRef(series);useEffect(() => {+ latestSeriesRef.current = series;if (series && lastSavedRef.current?.id !== series.id) lastSavedRef.current = series;}, [series]);@@ -55,10 +76,33 @@ export function useArcCanvasSync({const draftFlushRef = useRef(null);const registerDraftFlush = useCallback((fn) => { draftFlushRef.current = fn || null; }, []);- const updateSeriesFromServer = useCallback((next) => {- setSeries(next);- lastSavedRef.current = next;- }, [setSeries]);+ // `fromFlush` is internal: flushPending's PATCH response is the true server+ // state for every bible field, so it becomes the baseline outright.+ const applyServerRecord = useCallback((next, { fromFlush = false } = {}) => {+ const saved = lastSavedRef.current;+ const pendingIn = (local) => (+ next && saved?.id === next.id && local?.id === next.id ? pendingFields(local, saved, flushFields) : []+ );+ // The local merge reads `prev` so an edit queued in the same tick counts;+ // React may run this updater lazily, so the baseline below can't depend on it.+ setSeries((prev) => {+ const pending = pendingIn(prev);+ if (!pending.length) return next;+ const merged = { ...next };+ for (const k of pending) merged[k] = prev[k];+ return merged;+ });+ const pending = fromFlush ? [] : pendingIn(latestSeriesRef.current);+ if (!pending.length) {+ lastSavedRef.current = next;+ return;+ }+ const baseline = { ...next };+ for (const k of pending) baseline[k] = saved[k];+ lastSavedRef.current = baseline;+ }, [setSeries, flushFields]);++ const updateSeriesFromServer = useCallback((next) => applyServerRecord(next), [applyServerRecord]);const handleIssuesUpdate = useCallback((update) => {setIssues((prev) => {@@ -71,10 +115,8 @@ export function useArcCanvasSync({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 || {});let didSave = false;- if (dirty) {+ if (pendingFields(series, saved, flushFields).length) {// 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.@@ -88,7 +130,7 @@ export function useArcCanvasSync({return null;});if (!updated) return null;- updateSeriesFromServer(updated);+ applyServerRecord(updated, { fromFlush: true });didSave = true;}// Bible PATCH first, THEN the draft — the draft committer's response then@@ -99,7 +141,15 @@ export function useArcCanvasSync({if (draftSaved) didSave = true;}return didSave;- }, [series, flushFields, payloadDefaults, silent, onFlushError, updateSeriesFromServer]);+ }, [series, flushFields, payloadDefaults, silent, onFlushError, applyServerRecord]);++ // Unsaved bible edits, for a host's navigation guard. Only meaningful once the+ // baseline belongs to the rendered series — right after a series switch the+ // ref still holds the previous one until the capture effect runs.+ // Read per render, not memoized: the baseline is a ref, and every path that+ // moves it also sets `series`, so the next render sees both.+ const saved = lastSavedRef.current;+ const isDirty = !!series && saved?.id === series.id && pendingFields(series, saved, flushFields).length > 0;- return { updateSeriesFromServer, handleIssuesUpdate, flushPending, registerDraftFlush };+ return { updateSeriesFromServer, handleIssuesUpdate, flushPending, registerDraftFlush, isDirty };}diff --git a/client/src/hooks/useArcCanvasSync.test.jsx b/client/src/hooks/useArcCanvasSync.test.jsxindex 6e943ddd9c..caf7faffcb 100644--- a/client/src/hooks/useArcCanvasSync.test.jsx+++ b/client/src/hooks/useArcCanvasSync.test.jsx@@ -156,4 +156,72 @@ describe('useArcCanvasSync', () => {expect(did).toBe(false);expect(updatePipelineSeries).not.toHaveBeenCalled();});++ describe('pending bible edits survive a sibling action (#8423)', () => {+ const server = { id: 's1', name: 'A', premise: 'old', primaryFormat: 'novel', seasons: [] };+ const typePremise = (result) => act(() => { result.current.setSeries((s) => ({ ...s, premise: 'typed' })); });++ it('keeps the typed premise when a server record for another field lands, and Save persists it', async () => {+ const { result } = renderHook(() => useHarness(server, [], { flushFields: FLUSH_FIELDS, silent: true }));+ typePremise(result);++ // The format select PATCHes one field and hands back the whole server record.+ act(() => { result.current.updateSeriesFromServer({ ...server, primaryFormat: 'screenplay' }); });+ expect(result.current.series.premise).toBe('typed');+ expect(result.current.series.primaryFormat).toBe('screenplay');+ expect(result.current.isDirty).toBe(true);++ updatePipelineSeries.mockResolvedValue({ ...server, primaryFormat: 'screenplay', premise: 'typed' });+ let did;+ await act(async () => { did = await result.current.flushPending(); });+ expect(did).toBe(true);+ expect(updatePipelineSeries).toHaveBeenCalledWith('s1', expect.objectContaining({ premise: 'typed' }), { silent: true });+ expect(result.current.isDirty).toBe(false);+ });++ it('still PATCHes the premise after a caller spreads the local series into the update', async () => {+ const { result } = renderHook(() => useHarness(server, [], { flushFields: FLUSH_FIELDS, silent: true }));+ typePremise(result);++ // AddSeasonRow / SeasonEditor / VolumeCoverLiveUpdates build `{ ...series, seasons }`+ // from the local record, which already carries the unsaved text.+ act(() => { result.current.updateSeriesFromServer({ ...result.current.series, seasons: [{ id: 'v1' }] }); });+ expect(result.current.series.seasons).toEqual([{ id: 'v1' }]);++ updatePipelineSeries.mockResolvedValue({ ...server, seasons: [{ id: 'v1' }], premise: 'typed' });+ await act(async () => { await result.current.flushPending(); });+ expect(updatePipelineSeries).toHaveBeenCalledTimes(1);+ expect(updatePipelineSeries.mock.calls[0][1].premise).toBe('typed');+ });++ it('applies server changes to fields with no pending edit', async () => {+ const { result } = renderHook(() => useHarness(server, [], { flushFields: FLUSH_FIELDS }));+ typePremise(result);++ act(() => { result.current.updateSeriesFromServer({ ...server, name: 'Renamed by autopilot' }); });+ expect(result.current.series.name).toBe('Renamed by autopilot');+ expect(result.current.series.premise).toBe('typed');++ // Only the typed premise is dirty — the server's name is the new baseline.+ updatePipelineSeries.mockResolvedValue({ ...server, name: 'Renamed by autopilot', premise: 'typed' });+ await act(async () => { await result.current.flushPending(); });+ expect(updatePipelineSeries.mock.calls[0][1]).toEqual(expect.objectContaining({ name: 'Renamed by autopilot', premise: 'typed' }));+ expect(result.current.isDirty).toBe(false);+ });++ it('keeps an edit typed while the flush PATCH was in flight dirty', async () => {+ const { result } = renderHook(() => useHarness(server, [], { flushFields: FLUSH_FIELDS, silent: true }));+ typePremise(result);+ let resolvePatch;+ updatePipelineSeries.mockImplementation(() => new Promise((r) => { resolvePatch = r; }));++ let flush;+ act(() => { flush = result.current.flushPending(); });+ act(() => { result.current.setSeries((s) => ({ ...s, premise: 'typed more' })); });+ await act(async () => { resolvePatch({ ...server, premise: 'typed' }); await flush; });++ expect(result.current.series.premise).toBe('typed more');+ expect(result.current.isDirty).toBe(true);+ });+ });});diff --git a/client/src/pages/PipelineSeries.evolutionLens.test.jsx b/client/src/pages/PipelineSeries.evolutionLens.test.jsxindex 550758d36e..71ce10aaba 100644--- a/client/src/pages/PipelineSeries.evolutionLens.test.jsx+++ b/client/src/pages/PipelineSeries.evolutionLens.test.jsx@@ -9,7 +9,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { MemoryRouter, Route, Routes } from 'react-router';+import { createMemoryRouter, RouterProvider } from 'react-router';import PipelineSeries from './PipelineSeries';import {CHARACTER_ARC_LIMITS, TRANSITION_KINDS, TRANSITION_KIND_LABELS,@@ -72,11 +72,10 @@ const seriesWith = (arc) => ({function renderPage() {return render(- <MemoryRouter initialEntries={['/pipeline/series/series-1']}>- <Routes>- <Route path="/pipeline/series/:seriesId" element={<PipelineSeries />} />- </Routes>- </MemoryRouter>,+ <RouterProvider router={createMemoryRouter(+ [{ path: '/pipeline/series/:seriesId', element: <PipelineSeries /> }],+ { initialEntries: ['/pipeline/series/series-1'] },+ )} />,);}diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex 85b6f809df..348f511416 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -42,6 +42,8 @@ import { recommendStructure, describeStructure } from '../lib/seasonStructure';import useDrawerTab from '../hooks/useDrawerTab';import { useLocalStorageBool } from '../hooks/useLocalStorageBool';import { useArcCanvasSync } from '../hooks/useArcCanvasSync';+import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';+import UnsavedChangesConfirm from '../components/ui/UnsavedChangesConfirm';import RecordRenderPinRow from '../components/imageGen/RecordRenderPinRow';import CharacterEvolutionLens from '../components/character/CharacterEvolutionLens';import { EVOLUTION_STAGES, isDeclaredEvolution } from '../lib/characterEvolution.js';@@ -161,7 +163,7 @@ export default function PipelineSeries() {// setters). Flushes the full bible field-set; the API helper's auto-toast is// suppressed (silent) so `onFlushError` emits the single failure toast that// tells the user their edits didn't persist.- const { updateSeriesFromServer, handleIssuesUpdate, flushPending, registerDraftFlush } = useArcCanvasSync({+ const { updateSeriesFromServer, handleIssuesUpdate, flushPending, registerDraftFlush, isDirty } = useArcCanvasSync({series,setSeries,setIssues,@@ -170,6 +172,10 @@ export default function PipelineSeries() {silent: true,onFlushError: (err) => toast.error(`Pre-flush save failed: ${err.message}`),});+ // Unsaved bible edits park every exit — another series in the sidebar, ⌘K,+ // Back, tab close (#8423). Discarding just lets the navigation run; the next+ // series' load replaces the local state and recaptures the baseline.+ const routeGuard = useUnsavedChangesGuard(isDirty);const handleSave = async () => {if (!series) return;@@ -299,6 +305,14 @@ export default function PipelineSeries() {</button></header>+ <UnsavedChangesConfirm+ guard={routeGuard}+ when={!saving}+ question="Discard your unsaved series bible changes?"+ label={`Discard unsaved changes to ${series.name || 'this series'}`}+ onDiscard={routeGuard.proceed}+ />+<div className="flex flex-wrap items-center gap-3 text-sm">{issues.length > 0 && (<Link className="text-port-accent hover:underline" to={`/pipeline/issues/${[...issues].sort(compareIssuesInSeries)[0].id}`}>diff --git a/client/src/pages/PipelineSeries.responsive.test.jsx b/client/src/pages/PipelineSeries.responsive.test.jsxindex b29888e33b..c8230aa6cb 100644--- a/client/src/pages/PipelineSeries.responsive.test.jsx+++ b/client/src/pages/PipelineSeries.responsive.test.jsx@@ -1,11 +1,12 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { render, screen, fireEvent } from '@testing-library/react';-import { MemoryRouter, Route, Routes } from 'react-router';+import { act, render, screen, fireEvent } from '@testing-library/react';+import { createMemoryRouter, RouterProvider } from 'react-router';import PipelineSeries from './PipelineSeries';const getPipelineSeries = vi.fn();const listPipelineIssues = vi.fn();const listUniverses = vi.fn();+let mockBibleDirty = false;vi.mock('../services/api', () => ({getPipelineSeries: (...args) => getPipelineSeries(...args),@@ -22,6 +23,7 @@ vi.mock('../hooks/useArcCanvasSync', () => ({updateSeriesFromServer: vi.fn(),handleIssuesUpdate: vi.fn(),flushPending: vi.fn(async () => false),+ isDirty: mockBibleDirty,}),}));vi.mock('../hooks/useLocalStorageBool', () => ({ useLocalStorageBool: () => [false, vi.fn()] }));@@ -36,18 +38,17 @@ vi.mock('../components/imageGen/RecordRenderPinRow', () => ({ default: () => <divi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));function renderPage() {- return render(- <MemoryRouter initialEntries={['/pipeline/series/series-1']}>- <Routes>- <Route path="/pipeline/series/:seriesId" element={<PipelineSeries />} />- </Routes>- </MemoryRouter>,+ const router = createMemoryRouter(+ [{ path: '/pipeline/series/:seriesId', element: <PipelineSeries /> }],+ { initialEntries: ['/pipeline/series/series-1'] },);+ return { router, ...render(<RouterProvider router={router} />) };}describe('Pipeline series detail — mobile layout', () => {beforeEach(() => {vi.clearAllMocks();+ mockBibleDirty = false;getPipelineSeries.mockResolvedValue({ id: 'series-1', name: 'Example Series' });listPipelineIssues.mockResolvedValue([]);listUniverses.mockResolvedValue([]);@@ -74,3 +75,25 @@ describe('Pipeline series detail — mobile layout', () => {expect(page).toHaveClass('lg:overflow-hidden');});});++describe('Pipeline series detail — unsaved bible edits (#8423)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockBibleDirty = true;+ getPipelineSeries.mockResolvedValue({ id: 'series-1', name: 'Example Series' });+ listPipelineIssues.mockResolvedValue([]);+ listUniverses.mockResolvedValue([]);+ });++ it('parks a switch to another series behind the discard prompt', async () => {+ const { router } = renderPage();+ await screen.findByRole('heading', { name: 'Example Series' });++ await act(async () => { router.navigate('/pipeline/series/series-2'); });+ expect(screen.getByText('Discard your unsaved series bible changes?')).toBeInTheDocument();+ expect(router.state.location.pathname).toBe('/pipeline/series/series-1');++ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Discard' })); });+ expect(router.state.location.pathname).toBe('/pipeline/series/series-2');+ });+});