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: preserve series plan edits during AI and saves
[._.]/ Adam Eivyf33b18e952c9
diff --git a/client/src/components/fableloom/LoomSeriesPlan.jsx b/client/src/components/fableloom/LoomSeriesPlan.jsxindex d4b81d3701..4ca6d6f735 100644--- a/client/src/components/fableloom/LoomSeriesPlan.jsx+++ b/client/src/components/fableloom/LoomSeriesPlan.jsx@@ -4,7 +4,7 @@* and editing its copy cannot race as independent PATCH requests.*/-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { BrainCircuit, ChevronDown, ChevronUp, Loader2, MessageSquareText, Plus, Save, Sparkles, Trash2 } from 'lucide-react';import toast from '../ui/Toast';import { FormField } from '../ui/FormField.jsx';@@ -30,15 +30,33 @@ const normalizePlan = (plan) => ({export default function LoomSeriesPlan({ loom, onLoomUpdate }) {const [plan, setPlan] = useState(() => normalizePlan(loom.seriesPlan));const [dirty, setDirty] = useState(false);+ const revisionRef = useRef(0);+ const savedRevisionRef = useRef(0);+ const loomIdRef = useRef(loom.id);const routeGuard = useUnsavedChangesGuard(dirty);useEffect(() => {+ if (loomIdRef.current !== loom.id) {+ loomIdRef.current = loom.id;+ revisionRef.current = 0;+ savedRevisionRef.current = 0;+ setPlan(normalizePlan(loom.seriesPlan));+ setDirty(false);+ return;+ }+ // A save response may arrive after the author has continued typing. Keep+ // that newer draft instead of replacing it with the just-saved snapshot.+ if (revisionRef.current > savedRevisionRef.current) {+ setDirty(true);+ return;+ }setPlan(normalizePlan(loom.seriesPlan));setDirty(false);}, [loom.id, loom.seriesPlan]);const changePlan = (updater) => {setPlan((current) => (typeof updater === 'function' ? updater(current) : updater));+ revisionRef.current += 1;setDirty(true);};@@ -61,9 +79,11 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {});const [save, saving] = useAsyncAction(async () => {+ const submittedRevision = revisionRef.current;const updated = await updateLoom(loom.id, { seriesPlan: plan }, { silent: true });+ savedRevisionRef.current = submittedRevision;onLoomUpdate(updated);- setDirty(false);+ setDirty(revisionRef.current > submittedRevision);toast.success('Series plan saved');}, { errorMessage: 'Could not save series plan' });diff --git a/client/src/components/fableloom/LoomSeriesPlan.test.jsx b/client/src/components/fableloom/LoomSeriesPlan.test.jsxindex fc9693e46c..60b4dee3b7 100644--- a/client/src/components/fableloom/LoomSeriesPlan.test.jsx+++ b/client/src/components/fableloom/LoomSeriesPlan.test.jsx@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { fireEvent, render, screen, waitFor } from '@testing-library/react';import { createMemoryRouter, RouterProvider } from 'react-router';+import { useState } from 'react';vi.mock('../../services/api', () => ({feedbackLoomSeriesPlan: vi.fn(),@@ -34,6 +35,11 @@ const renderPlan = (props) => render(<RouterProvider router={createMemoryRouter({ path: '/', element: <LoomSeriesPlan {...props} /> },], { initialEntries: ['/'] })} />);+function StatefulPlan({ initial }) {+ const [record, setRecord] = useState(initial);+ return <LoomSeriesPlan loom={record} onLoomUpdate={setRecord} />;+}+describe('LoomSeriesPlan', () => {it('edits and saves the series-level plan as one patch', async () => {const onLoomUpdate = vi.fn();@@ -67,4 +73,21 @@ describe('LoomSeriesPlan', () => {expect(screen.getByText('Move the reversal into episode 3')).toBeInTheDocument();expect(screen.getByText('Episode feedback for Pilot')).toBeInTheDocument();});++ it('keeps typing performed while a save response is in flight', async () => {+ let resolveSave;+ api.updateLoom.mockImplementation(() => new Promise((resolve) => { resolveSave = resolve; }));+ render(<RouterProvider router={createMemoryRouter([+ { path: '/', element: <StatefulPlan initial={loom()} /> },+ ], { initialEntries: ['/'] })} />);++ const arc = screen.getByRole('textbox', { name: /story arc/i });+ fireEvent.change(arc, { target: { value: 'First draft.' } });+ fireEvent.click(screen.getByRole('button', { name: /save plan/i }));+ fireEvent.change(arc, { target: { value: 'Typed while saving.' } });+ resolveSave(loom({ seriesPlan: { ...loom().seriesPlan, storyArc: 'First draft.' } }));++ await waitFor(() => expect(screen.getByRole('textbox', { name: /story arc/i })).toHaveValue('Typed while saving.'));+ expect(screen.getByRole('button', { name: /save plan/i })).toBeEnabled();+ });});diff --git a/data.reference/prompts/stages/fableloom-feedback-series-plan.md b/data.reference/prompts/stages/fableloom-feedback-series-plan.mdindex 76a2009a90..f8832bc1e6 100644--- a/data.reference/prompts/stages/fableloom-feedback-series-plan.md+++ b/data.reference/prompts/stages/fableloom-feedback-series-plan.md@@ -21,9 +21,9 @@ You are the story editor for an interactive branching series. Apply the author's## Editing contract- Make the smallest coherent change that fully satisfies the instruction.-- A missing top-level field preserves it. A present empty string or empty array intentionally clears it.-- `plotPoints` and `sideQuests` are ordered complete arrays when present; include every item that should remain.-- Preserve existing item ids. New items omit `id`; the server will mint one.+- A missing field preserves it. A present empty string or `null` intentionally clears it.+- Return sparse item edits. Preserve existing item ids; new items omit `id`; removal uses `remove: true`.+- Reordering is separate: include the existing ids to move in the desired relative order. Items omitted from an order array remain after the explicitly ordered items.- Episode references must use an episode id from the supplied outline or `null`.- Side-quest status is one of `idea`, `planned`, `active`, or `resolved`.- Do not change episode titles, synopses, scenes, paths, or ids in this pass.@@ -33,8 +33,10 @@ Return ONLY valid JSON matching this shape, omitting unchanged top-level fields:```json{"storyArc": "complete revised arc",- "plotPoints": [{ "id": "existing id", "title": "Beat", "description": "Purpose and consequence", "episodeId": "episode id or null" }],- "sideQuests": [{ "id": "existing id", "title": "Thread", "description": "Progression and payoff", "status": "planned", "startEpisodeId": "episode id or null", "endEpisodeId": "episode id or null" }],+ "plotPointEdits": [{ "id": "existing id, or omit for new", "title": "only when changed", "description": "only when changed", "episodeId": "episode id or null, only when changed", "remove": false }],+ "plotPointOrder": ["existing plot-point id"],+ "sideQuestEdits": [{ "id": "existing id, or omit for new", "title": "only when changed", "description": "only when changed", "status": "planned", "startEpisodeId": "episode id or null", "endEpisodeId": "episode id or null", "remove": false }],+ "sideQuestOrder": ["existing side-quest id"],"changes": ["short description of an applied change"]}```diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.jsindex 33daa11697..53621cfdaa 100644--- a/server/services/fableLoom/weave.js+++ b/server/services/fableLoom/weave.js@@ -69,12 +69,26 @@ export async function buildCanonDigest(loom) {return universe ? renderCanonForPrompt(universe) : '';}-const seriesPlanContext = (plan) => {+const seriesPlanContext = (loom, episode) => {+ const plan = loom.seriesPlan;if (!plan) return [];- const plotPoints = (plan.plotPoints || []).slice(0, 12).map((item, index) =>- `Plot point ${index + 1}: ${item.title || 'Untitled'}${item.description ? ` — ${trimTo(item.description, 300)}` : ''}`);- const sideQuests = (plan.sideQuests || []).slice(0, 12).map((item) =>- `Side quest (${item.status}): ${item.title || 'Untitled'}${item.description ? ` — ${trimTo(item.description, 300)}` : ''}`);+ const episodeLabels = new Map(loom.episodes.map((item) => [item.id, `Episode ${item.number}: ${item.title || 'Untitled'}`]));+ const relevantFirst = (items, matchesEpisode) => episode+ ? [...items].sort((a, b) => Number(matchesEpisode(b, episode.id)) - Number(matchesEpisode(a, episode.id)))+ : items;+ const plotPoints = relevantFirst(plan.plotPoints || [], (item, id) => item.episodeId === id)+ .slice(0, 12)+ .map((item, index) => {+ const assignment = item.episodeId ? ` [planned for ${episodeLabels.get(item.episodeId) || item.episodeId}]` : ' [unassigned]';+ return `Plot point ${index + 1}${assignment}: ${item.title || 'Untitled'}${item.description ? ` — ${trimTo(item.description, 300)}` : ''}`;+ });+ const sideQuests = relevantFirst(plan.sideQuests || [], (item, id) => item.startEpisodeId === id || item.endEpisodeId === id)+ .slice(0, 12)+ .map((item) => {+ const start = item.startEpisodeId ? episodeLabels.get(item.startEpisodeId) || item.startEpisodeId : 'unassigned';+ const end = item.endEpisodeId ? episodeLabels.get(item.endEpisodeId) || item.endEpisodeId : 'unassigned';+ return `Side quest (${item.status}; starts ${start}; ends ${end}): ${item.title || 'Untitled'}${item.description ? ` — ${trimTo(item.description, 300)}` : ''}`;+ });return [plan.storyArc ? `Series arc: ${trimTo(plan.storyArc, 4000)}` : '',...plotPoints,@@ -87,23 +101,21 @@ const storyContext = (loom, episode) => [`Scene format: ${loomFormatLabel(loom.format)}`,loom.logline ? `Logline: ${loom.logline}` : '',loom.premise ? `Premise: ${loom.premise}` : '',- ...seriesPlanContext(loom.seriesPlan),+ ...seriesPlanContext(loom, episode),episode ? `Episode ${episode.number}: ${episode.title || 'Untitled'}` : '',episode?.synopsis ? `Synopsis: ${episode.synopsis}` : '',].filter(Boolean).join('\n');const seriesPlanDigest = (loom) => JSON.stringify({storyArc: trimTo(loom.seriesPlan?.storyArc, 6000),- plotPoints: (loom.seriesPlan?.plotPoints || []).slice(0, 30).map((item) => ({- ...item, description: trimTo(item.description, 600),+ plotPoints: (loom.seriesPlan?.plotPoints || []).map((item) => ({+ ...item, description: trimTo(item.description, 400),})),- omittedPlotPoints: Math.max(0, (loom.seriesPlan?.plotPoints?.length || 0) - 30),- sideQuests: (loom.seriesPlan?.sideQuests || []).slice(0, 30).map((item) => ({- ...item, description: trimTo(item.description, 600),+ sideQuests: (loom.seriesPlan?.sideQuests || []).map((item) => ({+ ...item, description: trimTo(item.description, 400),})),- omittedSideQuests: Math.max(0, (loom.seriesPlan?.sideQuests?.length || 0) - 30),episodes: loom.episodes.map(({ id, number, title, synopsis }) => ({- id, number, title, synopsis: trimTo(synopsis, 500),+ id, number, title, synopsis: trimTo(synopsis, 300),})),}, null, 2);@@ -433,14 +445,21 @@ export async function feedbackSeriesPlan(loomId, {if (!content || typeof content !== 'object') {throw aiShapeError('The model returned no series-plan edits');}- const patch = {};- if (hasOwn(content, 'storyArc') && typeof content.storyArc === 'string') patch.storyArc = content.storyArc;- if (hasOwn(content, 'plotPoints') && Array.isArray(content.plotPoints)) patch.plotPoints = content.plotPoints;- if (hasOwn(content, 'sideQuests') && Array.isArray(content.sideQuests)) patch.sideQuests = content.sideQuests;- if (!Object.keys(patch).length) throw aiShapeError('The model returned no usable series-plan edits');+ const hasPlanEdit = (hasOwn(content, 'storyArc') && typeof content.storyArc === 'string')+ || Array.isArray(content.plotPointEdits) || Array.isArray(content.plotPointOrder)+ || Array.isArray(content.sideQuestEdits) || Array.isArray(content.sideQuestOrder);+ if (!hasPlanEdit) throw aiShapeError('The model returned no usable series-plan edits');const updated = await mutateLoom(loomId, (current) => {- current.seriesPlan = { ...current.seriesPlan, ...patch };+ const plan = { ...current.seriesPlan };+ if (hasOwn(content, 'storyArc') && typeof content.storyArc === 'string') plan.storyArc = content.storyArc;+ plan.plotPoints = applyPlanItemEdits(plan.plotPoints, content.plotPointEdits, content.plotPointOrder, {+ prefix: 'plot', fields: ['title', 'description', 'episodeId'],+ });+ plan.sideQuests = applyPlanItemEdits(plan.sideQuests, content.sideQuestEdits, content.sideQuestOrder, {+ prefix: 'quest', fields: ['title', 'description', 'status', 'startEpisodeId', 'endEpisodeId'],+ });+ current.seriesPlan = plan;return current;});return {@@ -450,6 +469,39 @@ export async function feedbackSeriesPlan(loomId, {};}+function applyPlanItemEdits(currentItems = [], rawEdits, rawOrder, { prefix, fields }) {+ const items = currentItems.map((item) => ({ ...item }));+ const byId = new Map(items.map((item) => [item.id, item]));+ const removed = new Set();+ for (const edit of (Array.isArray(rawEdits) ? rawEdits : []).slice(0, LOOM_LIMITS.PLAN_ITEMS_MAX)) {+ if (!edit || typeof edit !== 'object') continue;+ if (typeof edit.id === 'string' && byId.has(edit.id)) {+ if (edit.remove === true) {+ removed.add(edit.id);+ continue;+ }+ const item = byId.get(edit.id);+ for (const field of fields) {+ if (hasOwn(edit, field)) item[field] = edit[field];+ }+ continue;+ }+ if (!edit.id && edit.remove !== true) {+ const item = { id: `${prefix}-${randomUUID()}` };+ for (const field of fields) {+ if (hasOwn(edit, field)) item[field] = edit[field];+ }+ items.push(item);+ byId.set(item.id, item);+ }+ }+ const kept = items.filter((item) => !removed.has(item.id));+ if (!Array.isArray(rawOrder)) return kept;+ const order = rawOrder.filter((id) => typeof id === 'string' && byId.has(id) && !removed.has(id));+ const ranked = new Map(order.map((id, index) => [id, index]));+ return [...kept].sort((a, b) => (ranked.get(a.id) ?? Number.MAX_SAFE_INTEGER) - (ranked.get(b.id) ?? Number.MAX_SAFE_INTEGER));+}+// --- Play: resolve a reader's free-text intent ------------------------------/** Reader-facing scene shape — trigger phrases stay server-side. */diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.jsindex 5245074e61..0f5ca1efd0 100644--- a/server/services/fableLoom/weave.test.js+++ b/server/services/fableLoom/weave.test.js@@ -618,4 +618,34 @@ describe('series plan AI', () => {expect(result.loom.seriesPlan.plotPoints).toHaveLength(1);expect(result.changes).toEqual(['Raised the stakes']);});++ it('preserves plan items outside the AI digest and patches existing items by id', async () => {+ const { loomId, episodeId } = await setup();+ const plotPoints = Array.from({ length: 35 }, (_, index) => ({+ id: `plot-${index + 1}`, title: `Beat ${index + 1}`, description: `Purpose ${index + 1}`, episodeId,+ }));+ await updateLoom(loomId, { seriesPlan: { storyArc: 'Arc', plotPoints, sideQuests: [] } });+ runStagedLLM.mockResolvedValueOnce({+ content: { plotPointEdits: [{ id: 'plot-1', description: 'A sharper purpose.' }] },+ runId: 'run-feedback',+ });+ const result = await feedbackSeriesPlan(loomId, { feedback: 'Sharpen the opening beat.' });+ expect(result.loom.seriesPlan.plotPoints).toHaveLength(35);+ expect(result.loom.seriesPlan.plotPoints[0].description).toBe('A sharper purpose.');+ expect(result.loom.seriesPlan.plotPoints[34].title).toBe('Beat 35');+ });++ it('annotates and prioritizes episode-assigned plan beats in episode AI context', async () => {+ const { loomId, episodeId } = await setup();+ const manyBeats = Array.from({ length: 13 }, (_, index) => ({+ id: `plot-${index}`, title: `Beat ${index}`, description: '', episodeId: null,+ }));+ manyBeats.push({ id: 'plot-relevant', title: 'Episode turn', description: '', episodeId });+ await updateLoom(loomId, { seriesPlan: { storyArc: '', plotPoints: manyBeats, sideQuests: [] } });+ runStagedLLM.mockResolvedValueOnce({ content: generatedGraph(), runId: 'run-weave' });+ await weaveEpisode(loomId, episodeId, { replace: true });+ expect(runStagedLLM).toHaveBeenCalledWith('fableloom-weave-episode', expect.objectContaining({+ storyContext: expect.stringContaining('Plot point 1 [planned for Episode 1: Pilot]: Episode turn'),+ }), expect.anything());+ });});