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([issue-730]): return recomputed view from sync/reconcile so staleSteps update reactively
[._.]/ Adam Eivy540fa61b3dc7
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxindex 057bcc66ee..1be4775a90 100644--- a/client/src/pages/StoryBuilder.jsx+++ b/client/src/pages/StoryBuilder.jsx@@ -1094,31 +1094,37 @@ function StoryBuilderDetail({ storyId, stepParam }) {if (updated) setSession((prev) => (prev ? { ...prev, llm: updated.llm } : prev));};- // Cross-machine resume (#730). Toggling sync on captures a fresh staleness- // baseline from this machine's live records; reconcile re-captures it. Both- // settle drift to false, so we merge the server-confirmed `sync` flag and- // clear drift locally rather than refetching the whole view.+ // Cross-machine resume (#730). The sync/reconcile routes return the full+ // recomputed session view (staleSteps + syncDrift), not just the record —+ // because toggling sync or reconciling shifts the staleness baseline, which+ // can change which steps read as stale. Merge the whole view so the step rail+ // and the drift indicator both update reactively, no full refetch.+ const applySessionView = (view) => {+ setSession((prev) => (prev ? { ...prev, ...view } : view));+ setStaleSteps(view.staleSteps || []);+ setSyncDrift(view.syncDrift === true);+ };+const toggleSync = async () => {if (!session || syncBusy) return;const next = session.sync !== true;setSyncBusy(true);- const updated = await setStorySessionSync(storyId, next, { silent: true })+ const view = await setStorySessionSync(storyId, next, { silent: true }).catch(() => null).finally(() => setSyncBusy(false));- if (!updated) { toast.error('Failed to update cross-machine resume'); return; }- setSession((prev) => (prev ? { ...prev, sync: updated.sync === true } : prev));- setSyncDrift(false);+ if (!view) { toast.error('Failed to update cross-machine resume'); return; }+ applySessionView(view);toast.success(next ? 'Cross-machine resume enabled' : 'Cross-machine resume disabled');};const reconcile = async () => {if (!session || session.sync !== true || syncBusy) return;setSyncBusy(true);- const updated = await reconcileStorySession(storyId, { silent: true })+ const view = await reconcileStorySession(storyId, { silent: true }).catch(() => null).finally(() => setSyncBusy(false));- if (!updated) { toast.error('Failed to reconcile'); return; }- setSyncDrift(false);+ if (!view) { toast.error('Failed to reconcile'); return; }+ applySessionView(view);toast.success('Re-baselined to this machine');};diff --git a/client/src/pages/StoryBuilder.test.jsx b/client/src/pages/StoryBuilder.test.jsxindex ad8e6e42f1..9d1a3cbc1c 100644--- a/client/src/pages/StoryBuilder.test.jsx+++ b/client/src/pages/StoryBuilder.test.jsx@@ -95,8 +95,10 @@ beforeEach(() => {api.generateStoryStep.mockResolvedValue({ result: {} });api.refineStoryStep.mockResolvedValue({ result: {}, changes: [] });api.setStoryIssueLock.mockResolvedValue({});- api.setStorySessionSync.mockImplementation(async (_id, sync) => ({ id: 'stb-1', sync }));- api.reconcileStorySession.mockResolvedValue({ id: 'stb-1', sync: true });+ // The sync/reconcile routes return the recomputed view (staleSteps + syncDrift),+ // not just the record — toggling sync or reconciling can shift staleness.+ api.setStorySessionSync.mockImplementation(async (_id, sync) => ({ id: 'stb-1', sync, staleSteps: [], syncDrift: false }));+ api.reconcileStorySession.mockResolvedValue({ id: 'stb-1', sync: true, staleSteps: [], syncDrift: false });api.getUniverse.mockResolvedValue({ id: 'u1', logline: 'L', premise: 'P', styleNotes: 'S', influences: { embrace: [], avoid: [] }, characters: [] });api.getPipelineSeries.mockResolvedValue({ id: 's1', arc: { logline: 'AL', summary: 'AS', readerMap: { hooks: [{ id: 'rm-1', label: 'Why?' }] } } });api.listPipelineIssues.mockResolvedValue([]);@@ -512,4 +514,30 @@ describe('StoryBuilder — detail stepper', () => {await waitFor(() => expect(screen.getByText(/Baseline matches this machine/i)).toBeTruthy());expect(screen.getByRole('button', { name: /Reconcile/i }).disabled).toBe(true);});++ it('cross-machine resume: reconcile surfaces newly-stale steps from the recomputed view (#730)', async () => {+ const { fireEvent } = await import('@testing-library/react');+ api.getStorySession.mockResolvedValue({+ id: 'stb-1', title: 'Salt Run', currentStep: 'readerMap',+ universeId: 'u1', seriesId: 's1',+ steps: mkSteps({+ idea: { locked: true }, universeAesthetic: { locked: true },+ plotArc: { locked: true }, readerMap: { status: 'locked', locked: true },+ }),+ staleSteps: [], sync: true, syncDrift: true, llm: { provider: '', model: '' },+ });+ // Reconcile adopts this machine's records → a locked step whose frozen hash+ // differs from the adopted baseline becomes stale; the route returns it.+ api.reconcileStorySession.mockResolvedValue({ id: 'stb-1', sync: true, staleSteps: ['readerMap'], syncDrift: false });+ renderAt('/story-builder/stb-1/readerMap');+ await waitFor(() => expect(screen.getByRole('heading', { name: 'Reader Map' })).toBeTruthy());+ // No stale warning before reconcile.+ expect(screen.queryByText(/re-review and re-lock/i)).toBeNull();++ fireEvent.click(screen.getByRole('button', { name: /Reconcile/i }));+ await waitFor(() => expect(api.reconcileStorySession).toHaveBeenCalled());+ // The recomputed view's staleSteps merges reactively → stale banner appears+ // without a full refetch.+ await waitFor(() => expect(screen.getByText(/re-review and re-lock/i)).toBeTruthy());+ });});diff --git a/server/lib/README.md b/server/lib/README.mdindex c5613b069b..522a4a5ce4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -44,7 +44,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `storyBible.js` | Canonical Character / Place / Object shapes + `BIBLE_LIMITS`. || `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. || `storyBuilderSteps.js` | Unified Story Builder ordered step definitions + helpers (`STEPS`, `STEP_IDS`, `STEP_STATUSES`, `isValidStepId`, `stepIndex`). |-| `storyBuilderIntegrity.js` | Pure staleness hashing for the Story Builder (`hashUpstream`, `computeStaleSteps`). |+| `storyBuilderIntegrity.js` | Pure staleness hashing for the Story Builder (`hashUpstream`, `computeStaleSteps`, `computeSyncDrift`). || `canonPrompt.js` | Per-kind field-precedence rules; SHORT/RICH/PREVIEW spec tables; `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` / `descriptorForCanonEntry`. || `scenePrompt.js` | Scene-prompt composer + bible matchers (chars/places/objects in text). || `sceneExtractor.js` | Split prose or teleplay into scene list via LLM. |diff --git a/server/lib/storyBuilderIntegrity.js b/server/lib/storyBuilderIntegrity.jsindex 42e73c8a04..038857775a 100644--- a/server/lib/storyBuilderIntegrity.js+++ b/server/lib/storyBuilderIntegrity.js@@ -69,8 +69,10 @@ export function computeStaleSteps(session, currentHashes = {}) {* its staleness off `syncedHashes` (so a peer's edit can't false-positive it),* but the user may still want to adopt this machine's current records as the new* baseline — and they only need to when at least one locked step's live hash no- * longer matches the carried baseline. Returns false when no baseline exists or- * no locked step diverges.+ * longer matches the carried baseline. A locked step missing from the baseline+ * counts as drift (adopting the records would add a hash the session hasn't+ * recorded); a locked step with no live hash available is skipped. Returns+ * false when the session has no locked steps or every locked step matches.*/export function computeSyncDrift(session, currentHashes = {}, syncedHashes = {}) {const steps = session?.steps || {};diff --git a/server/routes/storyBuilder.js b/server/routes/storyBuilder.jsindex 2e4083911a..6c354add99 100644--- a/server/routes/storyBuilder.js+++ b/server/routes/storyBuilder.js@@ -58,11 +58,14 @@ router.post('/', asyncHandler(async (req, res) => {res.status(201).json(created);}));+// Flatten a session view into the shape the client consumes: the persisted+// session plus the computed (non-persisted) staleSteps array and the syncDrift+// flag (#730: this machine's live records diverged from the synced baseline).+const flattenView = (view) => ({ ...view.session, staleSteps: view.staleSteps, syncDrift: view.syncDrift });+router.get('/:id', asyncHandler(async (req, res) => {const view = await getStorySessionView(req.params.id).catch((err) => { throw mapServiceError(err); });- // Flatten the session with the computed (non-persisted) staleSteps array +- // the syncDrift flag (#730: live records diverged from the synced baseline).- res.json({ ...view.session, staleSteps: view.staleSteps, syncDrift: view.syncDrift });+ res.json(flattenView(view));}));router.patch('/:id', asyncHandler(async (req, res) => {@@ -83,15 +86,23 @@ router.delete('/:id', asyncHandler(async (req, res) => {// with the session so a peer's universe edit can't false-positive-stale it.router.post('/:id/sync', asyncHandler(async (req, res) => {const { sync } = validateRequest(storySessionSyncSchema, req.body || {});- const updated = await setStorySessionSync(req.params.id, sync).catch((err) => { throw mapServiceError(err); });- res.json(updated);+ await setStorySessionSync(req.params.id, sync).catch((err) => { throw mapServiceError(err); });+ // Return the recomputed view, not the bare record: toggling sync changes the+ // staleness baseline (live-diff ↔ carried syncedHashes), so staleSteps can+ // shift too — the client merges both reactively without a separate refetch.+ const view = await getStorySessionView(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(flattenView(view));}));// Re-snapshot a sync-enabled session's staleness baseline to the current live// records — the explicit "adopt this machine's universe/series state" gesture.router.post('/:id/reconcile', asyncHandler(async (req, res) => {- const updated = await reconcileStorySession(req.params.id).catch((err) => { throw mapServiceError(err); });- res.json(updated);+ await reconcileStorySession(req.params.id).catch((err) => { throw mapServiceError(err); });+ // Reconcile moves the carried baseline, so staleSteps recompute against it+ // (a locked step whose frozen hash differs from the adopted records becomes+ // stale). Return the fresh view so the step rail updates without a refetch.+ const view = await getStorySessionView(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(flattenView(view));}));// ── Step state machine ─────────────────────────────────────────────────────diff --git a/server/routes/storyBuilder.test.js b/server/routes/storyBuilder.test.jsindex 574dfb9e60..508ac6d2ef 100644--- a/server/routes/storyBuilder.test.js+++ b/server/routes/storyBuilder.test.js@@ -92,11 +92,15 @@ describe('GET /api/story-builder/:id', () => {});describe('cross-machine resume routes (#730)', () => {- it('POST /:id/sync toggles sync and dispatches to the service', async () => {+ it('POST /:id/sync toggles sync, dispatches to the service, and returns the recomputed view', async () => {const res = await request(makeApp()).post('/api/story-builder/stb-1/sync').send({ sync: true });expect(res.status).toBe(200);expect(svc.setStorySessionSync).toHaveBeenCalledWith('stb-1', true);- expect(res.body.sync).toBe(true);+ // Toggling sync can shift staleness, so the route returns the flattened view+ // (staleSteps + syncDrift) — not the bare record — for a reactive merge.+ expect(svc.getStorySessionView).toHaveBeenCalledWith('stb-1');+ expect(res.body.staleSteps).toEqual(['readerMap']);+ expect(res.body.syncDrift).toBe(true);});it('POST /:id/sync rejects a missing sync flag with 400', async () => {@@ -105,11 +109,15 @@ describe('cross-machine resume routes (#730)', () => {expect(svc.setStorySessionSync).not.toHaveBeenCalled();});- it('POST /:id/reconcile re-baselines and dispatches to the service', async () => {+ it('POST /:id/reconcile re-baselines, dispatches to the service, and returns the recomputed view', async () => {const res = await request(makeApp()).post('/api/story-builder/stb-1/reconcile').send({});expect(res.status).toBe(200);expect(svc.reconcileStorySession).toHaveBeenCalledWith('stb-1');- expect(res.body.reconciled).toBe(true);+ // Reconcile moves the baseline → staleSteps recompute; the route returns the+ // flattened view so the client updates the step rail without a refetch.+ expect(svc.getStorySessionView).toHaveBeenCalledWith('stb-1');+ expect(res.body.staleSteps).toEqual(['readerMap']);+ expect(res.body.syncDrift).toBe(true);});it('maps a reconcile VALIDATION error (local-only session) to 400', async () => {