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-4188]): codex review — stale-proposal guard, adopt bookkeeping, context budget, busy-modal dismissal
[._.]/ Adam Eivye62c876beb2e
diff --git a/client/src/components/universeBuilder/MoodBoardStyleSynthesis.jsx b/client/src/components/universeBuilder/MoodBoardStyleSynthesis.jsxindex 7b80507a23..fc25f10120 100644--- a/client/src/components/universeBuilder/MoodBoardStyleSynthesis.jsx+++ b/client/src/components/universeBuilder/MoodBoardStyleSynthesis.jsx@@ -4,15 +4,17 @@* "Synthesize style" on the universe's mood-board tool: runs the linked* board's collected content (notes, captions, per-item analyses) through a* user-picked API LLM, previews the proposed style guide as the shared- * StyleDiffPreview against the CURRENT draft values, and "Adopt" persists it- * via the universe's server-side queued write (never a client wholesale- * `influences` PATCH). Locks are honored at proposal time and re-checked+ * StyleDiffPreview against the CURRENT draft values, and "Adopt" hands the+ * proposal to the caller (`onAdopt` — the draft hook's queued-write adopt,+ * which also advances the saved-style bookkeeping). Never a client wholesale+ * `influences` PATCH. Locks are honored at proposal time and re-checked* server-side on adopt.*/-import { useState } from 'react';+import { useEffect, useState } from 'react';import { Loader2, Sparkles, Wand2, X } from 'lucide-react';-import { synthesizeMoodBoardStyle, adoptUniverseStyleGuide } from '../../services/api';+import { synthesizeMoodBoardStyle } from '../../services/api';+import useMounted from '../../hooks/useMounted';import useProviderModels from '../../hooks/useProviderModels';import ProviderModelSelector from '../ProviderModelSelector';import Modal from '../ui/Modal';@@ -22,11 +24,14 @@ import StyleDiffPreview from './StyleDiffPreview';const apiProviderFilter = (p) => p.enabled && p.type === 'api';// Inner body so the provider fetch (useProviderModels mounts it) is deferred-// until the modal actually opens.-function SynthesisBody({ boardId, universeId, styleNotes, influences, locked, onAdopted, onClose }) {+// until the modal actually opens. The parent keys this by universe+board, so+// switching targets remounts it and a stale proposal can never be adopted+// into a different universe.+function SynthesisBody({ boardId, styleNotes, influences, locked, onAdopt, onBusyChange, onClose }) {const [result, setResult] = useState(null);const [running, setRunning] = useState(false);const [adopting, setAdopting] = useState(false);+ const mountedRef = useMounted();const {providers,selectedProviderId,@@ -39,6 +44,13 @@ function SynthesisBody({ boardId, universeId, styleNotes, influences, locked, onconst busy = running || adopting;+ // The parent gates modal dismissal (backdrop/Escape/close button) on this,+ // so a run can't be silently orphaned mid-flight. Cleared on unmount.+ useEffect(() => {+ onBusyChange?.(busy);+ return () => onBusyChange?.(false);+ }, [busy, onBusyChange]);+const synthesize = async () => {if (!selectedProviderId || busy) return;setRunning(true);@@ -49,9 +61,10 @@ function SynthesisBody({ boardId, universeId, styleNotes, influences, locked, onproviderId: selectedProviderId,model: selectedModel || undefined,}, { silent: true }).catch((error) => {- toast.error(`Style synthesis failed: ${error.message}`);+ if (mountedRef.current) toast.error(`Style synthesis failed: ${error.message}`);return null;});+ if (!mountedRef.current) return;setRunning(false);if (data) setResult(data);};@@ -59,18 +72,16 @@ function SynthesisBody({ boardId, universeId, styleNotes, influences, locked, onconst adopt = async () => {if (!result?.proposed || busy) return;setAdopting(true);- const updated = await adoptUniverseStyleGuide(universeId, {+ const ok = await onAdopt?.({styleNotes: result.proposed.styleNotes || '',influences: result.proposed.influences || {},- }, { silent: true }).catch((error) => {- toast.error(`Adopting the style guide failed: ${error.message}`);- return null;});+ if (!mountedRef.current) return;setAdopting(false);- if (!updated) return;- onAdopted?.(updated);- toast.success('Style guide adopted');- onClose();+ // Force-close: the parent's busy gate reads its own state, which hasn't+ // re-rendered from the setAdopting(false) above yet — a plain close()+ // would still see busy and refuse.+ if (ok) onClose(true);};return (@@ -153,10 +164,19 @@ export default function MoodBoardStyleSynthesis({influences,locked,saved = false,- onAdopted,+ onAdopt,}) {const [open, setOpen] = useState(false);+ const [bodyBusy, setBodyBusy] = useState(false);if (!boardId) return null;+ // Guarded close: backdrop, Escape (Modal routes both here), and the body's+ // Cancel/X are ignored mid-run so a request can't be silently orphaned.+ // The body passes `force === true` after a successful adopt, where its own+ // busy flag has just cleared but this component hasn't re-rendered yet.+ const close = (force) => {+ if (bodyBusy && force !== true) return;+ setOpen(false);+ };return (<div className="flex items-center gap-2"><button@@ -174,21 +194,23 @@ export default function MoodBoardStyleSynthesis({<span className="text-[11px] text-gray-500">Board notes + analyses → style prompt, negative prompt, style notes.</span><Modalopen={open}- onClose={() => setOpen(false)}+ onClose={close}size="2xl"+ closeOnBackdrop={!bodyBusy}usePortalpanelClassName="bg-port-card border border-port-border rounded-xl max-h-[90vh] overflow-y-auto"ariaLabel="Synthesize universe style from mood board">{open ? (<SynthesisBody+ key={`${universeId || ''}:${boardId}`}boardId={boardId}- universeId={universeId}styleNotes={styleNotes}influences={influences}locked={locked}- onAdopted={onAdopted}- onClose={() => setOpen(false)}+ onAdopt={onAdopt}+ onBusyChange={setBodyBusy}+ onClose={close}/>) : null}</Modal>diff --git a/client/src/components/universeBuilder/MoodBoardStyleSynthesis.test.jsx b/client/src/components/universeBuilder/MoodBoardStyleSynthesis.test.jsxindex 5a83b4a028..eb3508fc9a 100644--- a/client/src/components/universeBuilder/MoodBoardStyleSynthesis.test.jsx+++ b/client/src/components/universeBuilder/MoodBoardStyleSynthesis.test.jsx@@ -4,7 +4,6 @@ import MoodBoardStyleSynthesis from './MoodBoardStyleSynthesis';const apiMocks = vi.hoisted(() => ({synthesizeMoodBoardStyle: vi.fn(),- adoptUniverseStyleGuide: vi.fn(),}));vi.mock('../../services/api', () => ({ ...apiMocks }));vi.mock('../../hooks/useProviderModels', () => ({@@ -38,18 +37,25 @@ const synthesis = {llm: { provider: 'ollama', model: 'qwen' },};+const baseProps = {+ boardId: 'mb-1',+ universeId: 'u1',+ styleNotes: 'Clean vector art',+ influences: { embrace: ['clean vectors'], avoid: ['grain'] },+ locked: { influencesAvoid: true },+ saved: true,+};+const renderPanel = (props = {}) => render(- <MoodBoardStyleSynthesis- boardId="mb-1"- universeId="u1"- styleNotes="Clean vector art"- influences={{ embrace: ['clean vectors'], avoid: ['grain'] }}- locked={{ influencesAvoid: true }}- saved- {...props}- />,+ <MoodBoardStyleSynthesis {...baseProps} {...props} />,);+const runSynthesis = async () => {+ fireEvent.click(screen.getByRole('button', { name: /synthesize style/i }));+ fireEvent.click(screen.getByRole('button', { name: /^synthesize$/i }));+ await waitFor(() => expect(screen.getByText('Style guide preview')).toBeInTheDocument());+};+describe('MoodBoardStyleSynthesis (#4188 Phase 4)', () => {beforeEach(() => vi.clearAllMocks());@@ -61,38 +67,34 @@ describe('MoodBoardStyleSynthesis (#4188 Phase 4)', () => {expect(screen.getByRole('button', { name: /synthesize style/i })).toBeDisabled();});- it('synthesizes with the draft style context, previews the diff, and adopts via the queued write', async () => {+ it('synthesizes with the draft style context, previews the diff, and adopts through the caller', async () => {apiMocks.synthesizeMoodBoardStyle.mockResolvedValue(synthesis);- const adopted = { id: 'u1', styleNotes: 'Tactile ink-wash science fiction.', influences: synthesis.proposed.influences };- apiMocks.adoptUniverseStyleGuide.mockResolvedValue(adopted);- const onAdopted = vi.fn();+ const onAdopt = vi.fn().mockResolvedValue(true);- renderPanel({ onAdopted });- fireEvent.click(screen.getByRole('button', { name: /synthesize style/i }));- fireEvent.click(screen.getByRole('button', { name: /^synthesize$/i }));+ renderPanel({ onAdopt });+ await runSynthesis();- await waitFor(() => {- expect(apiMocks.synthesizeMoodBoardStyle).toHaveBeenCalledWith('mb-1', {- styleNotes: 'Clean vector art',- influences: { embrace: ['clean vectors'], avoid: ['grain'] },- locked: { influencesAvoid: true },- providerId: 'ollama',- model: 'qwen',- }, { silent: true });- });-- // Diff preview renders the proposal.- expect(screen.getByText('Style guide preview')).toBeInTheDocument();+ expect(apiMocks.synthesizeMoodBoardStyle).toHaveBeenCalledWith('mb-1', {+ styleNotes: 'Clean vector art',+ influences: { embrace: ['clean vectors'], avoid: ['grain'] },+ locked: { influencesAvoid: true },+ providerId: 'ollama',+ model: 'qwen',+ }, { silent: true });expect(screen.getByText('+ ink wash')).toBeInTheDocument();fireEvent.click(screen.getByRole('button', { name: /adopt style/i }));await waitFor(() => {- expect(apiMocks.adoptUniverseStyleGuide).toHaveBeenCalledWith('u1', {+ expect(onAdopt).toHaveBeenCalledWith({styleNotes: 'Tactile ink-wash science fiction.',influences: { embrace: ['ink wash'], avoid: ['gloss'] },- }, { silent: true });+ });+ });+ // A successful adopt closes the modal (force path — the parent's busy+ // gate hasn't re-rendered yet when the body requests the close).+ await waitFor(() => {+ expect(screen.queryByText('Style guide preview')).toBeNull();});- expect(onAdopted).toHaveBeenCalledWith(adopted);});it('disables Adopt when the proposal matches the current guidance', async () => {@@ -101,10 +103,21 @@ describe('MoodBoardStyleSynthesis (#4188 Phase 4)', () => {diff: { ...synthesis.diff, hasChanges: false },});renderPanel();- fireEvent.click(screen.getByRole('button', { name: /synthesize style/i }));- fireEvent.click(screen.getByRole('button', { name: /^synthesize$/i }));- await waitFor(() => {- expect(screen.getByRole('button', { name: /adopt style/i })).toBeDisabled();- });+ await runSynthesis();+ expect(screen.getByRole('button', { name: /adopt style/i })).toBeDisabled();+ });++ it('discards a stale proposal when the target universe changes (remount by key)', async () => {+ apiMocks.synthesizeMoodBoardStyle.mockResolvedValue(synthesis);+ const { rerender } = renderPanel();+ await runSynthesis();+ expect(screen.getByRole('button', { name: /adopt style/i })).toBeInTheDocument();++ // Navigating to a different universe while the modal is open must wipe+ // the proposal — adopting universe A's synthesis into B would silently+ // copy one universe's style into another.+ rerender(<MoodBoardStyleSynthesis {...baseProps} universeId="u2" />);+ expect(screen.queryByRole('button', { name: /adopt style/i })).toBeNull();+ expect(screen.queryByText('Style guide preview')).toBeNull();});});diff --git a/client/src/components/universeBuilder/UniverseBibleTab.jsx b/client/src/components/universeBuilder/UniverseBibleTab.jsxindex 9cbe4746b8..17a8f7c13c 100644--- a/client/src/components/universeBuilder/UniverseBibleTab.jsx+++ b/client/src/components/universeBuilder/UniverseBibleTab.jsx@@ -112,6 +112,7 @@ export default function BibleTab({saved = false,onPersistStyleReference,onRemoveStyleReference,+ onAdoptStyleGuide,}) {const { providers, providerModels, providerLabel, activeProviderId } = llm;const {@@ -178,8 +179,10 @@ export default function BibleTab({/>{/* Board → style synthesis (#4188 Phase 4): distill the linked board- into the style guide; adoption is a server-side queued write and- the adopted values are merged back into the draft here. */}+ into the style guide. Adoption goes through the draft hook+ (adoptStyleGuideFromBoard), which runs the server-side queued+ write AND the same saved-snapshot/watermark bookkeeping as an+ art-reference adopt — so styleProbeDirty clears correctly. */}<MoodBoardStyleSynthesisboardId={draft.moodBoardId || ''}universeId={draft.id}@@ -187,10 +190,7 @@ export default function BibleTab({influences={draft.influences || {}}locked={draft.locked || {}}saved={saved}- onAdopted={(updated) => updateDraft({- styleNotes: updated?.styleNotes ?? '',- influences: ensureInfluences(updated?.influences),- })}+ onAdopt={onAdoptStyleGuide}/><div className="flex items-center gap-2 flex-wrap">diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsxindex 38c6fec69c..08f9ddddf1 100644--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx@@ -130,6 +130,7 @@ export default function UniverseBuilder() {providerLabel,providerModels,providers,+ adoptStyleGuideFromBoard,persistStyleReference,removeCategory,removeStyleReference,@@ -400,6 +401,7 @@ export default function UniverseBuilder() {saved={!!selectedId}onPersistStyleReference={persistStyleReference}onRemoveStyleReference={removeStyleReference}+ onAdoptStyleGuide={adoptStyleGuideFromBoard}/>)}diff --git a/client/src/hooks/useUniverseDraft.js b/client/src/hooks/useUniverseDraft.jsindex b3afde840c..724e1699bd 100644--- a/client/src/hooks/useUniverseDraft.js+++ b/client/src/hooks/useUniverseDraft.js@@ -3,6 +3,7 @@ import useMounted from './useMounted';import toast from '../components/ui/Toast';import {addUniverseStyleReference,+ adoptUniverseStyleGuide,createUniverse,deleteUniverse,getProviders,@@ -496,6 +497,32 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {return true;}, [applyStyleReferenceResult, draft, selectedId]);+ // Adopt a board-synthesized style guide (#4188 Phase 4) — the reference-less+ // sibling of the persistStyleReference adopt path. Routes through the same+ // applyStyleReferenceResult bookkeeping so the saved snapshot + update+ // watermark advance and styleProbeDirty clears, exactly as an art-reference+ // adopt does; the server re-checks field locks in its queued write.+ const adoptStyleGuideFromBoard = useCallback(async (proposed) => {+ if (!selectedId) return false;+ const targetId = selectedId;+ const current = draftRef.current || draft;+ const capturedStyle = {+ styleNotes: current.styleNotes || '',+ influences: ensureInfluences(current.influences),+ };+ const updated = await adoptUniverseStyleGuide(targetId, {+ styleNotes: proposed?.styleNotes || '',+ influences: ensureInfluences(proposed?.influences),+ }, { silent: true }).catch((error) => {+ toast.error(`Adopting the style guide failed: ${error.message}`);+ return null;+ });+ if (!updated) return false;+ applyStyleReferenceResult(targetId, updated, capturedStyle);+ toast.success('Style guide adopted from mood board');+ return true;+ }, [applyStyleReferenceResult, draft, selectedId]);+// Remove one art reference by id. Also a delta, so back-to-back removals need// no client-side queue — the server's record write queue serializes them.const removeStyleReference = useCallback(async (referenceId) => {@@ -719,6 +746,7 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {// Exposed so a consumer can retry the catalog/settings load after a failed// refresh instead of forcing a full page reload.refresh,+ adoptStyleGuideFromBoard,persistStyleReference,removeCategory,removeStyleReference,diff --git a/server/services/moodBoardStyleSynthesis.js b/server/services/moodBoardStyleSynthesis.jsindex fe134b1d70..2b060ee046 100644--- a/server/services/moodBoardStyleSynthesis.js+++ b/server/services/moodBoardStyleSynthesis.js@@ -23,10 +23,17 @@ import { buildStyleReferenceDiff } from './universeStyleReference.js';// Context bounds: a board caps at 500 items, but the synthesis context must// stay well inside a chat-completion window. Items are taken in board order-// (the user's curation order); fragments beyond the cap are dropped and the-// count is reported in the result so the UI can say so.+// (the user's curation order); fragments beyond either cap are dropped and+// the count is reported in the result so the UI can say so. The aggregate+// character budget is the load-bearing one — 60 items can each carry four+// 600-char fields, far past what a small local model's window fits — and it+// is a FIXED conservative budget (≈6k tokens) rather than model-aware:+// provider window metadata isn't reliably known here, and a proposal+// synthesized from the first N curated items beats a request the model+// truncates or rejects.const CONTEXT_ITEMS_MAX = 60;const CONTEXT_FIELD_MAX = 600;+const CONTEXT_TOTAL_CHARS_MAX = 24000;const RATIONALE_MAX = 1000;/**@@ -40,6 +47,7 @@ export function collectBoardStyleContext(board) {const items = Array.isArray(board?.items) ? board.items : [];const fragments = [];let dropped = 0;+ let totalChars = 0;for (const it of items) {if (!it || typeof it !== 'object') continue;const entry = {};@@ -60,10 +68,12 @@ export function collectBoardStyleContext(board) {}}if (!Object.keys(entry).length) continue;- if (fragments.length >= CONTEXT_ITEMS_MAX) {+ const entrySize = Object.values(entry).reduce((sum, v) => sum + v.length, 0);+ if (fragments.length >= CONTEXT_ITEMS_MAX || totalChars + entrySize > CONTEXT_TOTAL_CHARS_MAX) {dropped += 1;continue;}+ totalChars += entrySize;fragments.push({ kind: it.type, ...entry });}return {diff --git a/server/services/moodBoardStyleSynthesis.test.js b/server/services/moodBoardStyleSynthesis.test.jsindex 62af0f5bf8..fa66e6b55b 100644--- a/server/services/moodBoardStyleSynthesis.test.js+++ b/server/services/moodBoardStyleSynthesis.test.js@@ -78,6 +78,18 @@ describe('collectBoardStyleContext', () => {expect(ctx.items).toHaveLength(60);expect(ctx.droppedItems).toBe(10);});++ it('bounds the AGGREGATE character budget, not just the fragment count', () => {+ // 50 items × ~600 chars each ≈ 30k chars — under the 60-item cap but past+ // the 24k aggregate budget, so the tail must be dropped.+ const big = Array.from({ length: 50 }, (_, i) => ({ id: `t${i}`, type: 'text', text: 'x'.repeat(600) }));+ const ctx = collectBoardStyleContext(boardWith(big));+ expect(ctx.items.length).toBeLessThan(50);+ expect(ctx.items.length).toBeGreaterThan(0);+ expect(ctx.droppedItems).toBe(50 - ctx.items.length);+ const total = ctx.items.reduce((sum, it) => sum + it.note.length, 0);+ expect(total).toBeLessThanOrEqual(24000);+ });});describe('synthesizeBoardStyle', () => {