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

fix: address xhigh code-review findings on Story Builder image renders

Adam Eivy47a56c98138c
diff --git a/PLAN.md b/PLAN.md
index db275759f8..3c46c18653 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -199,6 +199,9 @@ The first slice shipped a working **seed-mode** conductor (`/story-builder`): cr
- [ ] [story-builder-embed-arccanvas] **Embed `ArcCanvas` / `StoryShapes` inline instead of read-only field blocks.** The plotArc + readerMap steps currently render read-only `FieldBlock`s + a deep-link to the Pipeline for editing. The plan called for reusing `client/src/components/pipeline/ArcCanvas.jsx` and the Vonnegut `StoryShapes` sparkline inline (and a beat timeline for the reader map). Embed them so editing happens in-builder. Deferred because `ArcCanvas` has a wide prop surface; the deep-link covers editing for v1.
- [ ] [story-builder-create-rollback] **`createStorySession` seed mode leaves an orphan universe if `createSeries` throws.** `server/services/storyBuilder.js` creates the universe shell, then the series shell, with no rollback — a `createSeries` failure (validation, disk, peer-import) leaves a stray universe (which also fired peer auto-subscribe) with no session pointing at it. Low severity under the single-user trust model, but repeated failed creates accumulate orphans. Wrap the two creates so a series failure deletes the just-created universe, or create the series first. Surfaced by the xhigh code-review (2026-05-27); deferred as non-blocking.
- [ ] [story-builder-goto-step-gate-divergence] **`goToStep` in `client/src/pages/StoryBuilder.jsx` (~line 414) swallows a `setStoryCurrentStep` rejection and navigates anyway.** If the server re-gate (fresh hashes) rejects the move while the client's `staleSteps` is stale, the UI lands on the target step but the persisted `currentStep` pointer stays behind, so reopening the session drops the user on a different step. Low severity (disabled controls prevent most cases). Either toast + revert nav on rejection, or refetch on failure. Surfaced by the xhigh code-review (2026-05-27).
+- [ ] [story-builder-import-partial-commit] **Import flow doesn't handle a partial commit.** `ImportPanel.importAndBuild` (`client/src/pages/StoryBuilder.jsx`) calls `commitImport` once; if it fails after the universe/arc/canon persist but the issue-create rolls back (`IMPORTER_PARTIAL_COMMIT_ISSUES`/`arcAlreadyPersisted`), it just toasts a generic error. Re-clicking re-sends the full payload — lower-risk than the standalone Importer (no editable preview, so arc/seasons are the same idempotent values) but a retry could duplicate issues. The standalone `Importer.jsx` guards this with the `arcAlreadyPersisted` retry (sends `arc:null, seasons:[]`). Either reuse that path or surface a "open in the Importer to recover" link. Surfaced by xhigh code-review (2026-05-27); deferred — rare, not data-corruption.
+- [ ] [universe-styleImageRefs-wire-and-journal] **`styleImageRefs` is wire-synced but not version-gated, and feeds the conflict-journal content hash.** Confirmed by review: `sanitizeRecordForWire('universe')` ships `styleImageRefs` to peers; an older (field-unaware) peer drops it on receive and, after its own edit bumps `updatedAt`, LWW-strips it back off a newer peer (same class as the readerMap bug, deliberately left ungated since a probe is one-click-regenerable). Separately, `contentHashForRecord` now includes `styleImageRefs`, so a probe render can contribute to a 3-way-divergence conflict-journal entry whose diff won't mention it (`RESTORABLE_FIELDS.universe` omits it) — Conflicts-tab noise on mixed-version federations. Options if it becomes annoying: bump the `universes` schema version (gate it), make `styleImageRefs` local-only (strip from wire), or exclude it from the content hash. Surfaced 2026-05-27; deferred — low-stakes, regenerable.
+- [ ] [story-builder-extract-image-render-hook] **Cleanup: the image-render lifecycle is duplicated 5×.** `StepCharacters` (StoryBuilder.jsx) + `StyleProbeImage.jsx` each re-implement `getSettings → readPipelineImageSettings → imageCfg` + a single-render jobId lifecycle, and `StepCharacters` near-verbatim copies `UniverseCanonSection`'s styled-render-and-persist routine (the `getSettings→imageCfg` block alone repeats in NounsStage/ComicScriptStage/UniverseBuilder too). Extract a `useImageRenderSettings()` + `useSingleImageRender({ buildPrompt, onComplete })` hook (home: `client/src/hooks/`) and a shared canon styled-render helper. Also: `ProviderModelPicker` (StoryBuilder.jsx) duplicates the Importer's `LlmPicker` + the `SeriesLlmPicker`/`FeatureProviderPicker`/`StagePromptModelPicker` pattern — promote one shared provider/model picker. Surfaced by xhigh code-review (2026-05-27); deferred — tech debt, not a bug.
- [ ] [story-builder-session-sync] **Optional cross-machine resumable sessions.** Sessions are intentionally local-only in v1 (excluded from peer sync — see `storyBuilder.js` header). If cross-machine resume is wanted later, key the staleness model on a content hash carried in the session (the integrity helper already produces one) rather than live-record diffing, so a peer's universe edit doesn't false-positive-stale the local session.
## Future Ideas
diff --git a/client/src/components/universe/StyleProbeImage.jsx b/client/src/components/universe/StyleProbeImage.jsx
index 6952acef98..b5b8b3c0de 100644
--- a/client/src/components/universe/StyleProbeImage.jsx
+++ b/client/src/components/universe/StyleProbeImage.jsx
@@ -9,7 +9,7 @@
* universe's `styleImageRefs[]` so it survives reload and shows in both the
* Universe Builder and the Story Builder aesthetic step.
*/
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useRef } from 'react';
import { generateImage, getSettings, updateUniverse } from '../../services/api';
import { universeStylePreset } from '../../lib/universeStylePreset';
import { pipelineImageCfgToRenderOpts, readPipelineImageSettings, PIPELINE_IMAGE_DEFAULTS } from '../../lib/pipelineImageDefaults';
@@ -33,6 +33,9 @@ export function hasStyleForProbe(universe) {
export default function StyleProbeImage({ universe, onUniverseChange, canRender = true }) {
const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);
const [jobId, setJobId] = useState(null);
+ // MediaJobThumb's onFilename effect can fire more than once — process each
+ // completed filename's persist exactly once.
+ const processedRef = useRef(new Set());
useEffect(() => {
getSettings({ silent: true })
@@ -57,10 +60,16 @@ export default function StyleProbeImage({ universe, onUniverseChange, canRender
const onComplete = async (filename) => {
setJobId(null);
if (!filename || !universe?.id) return;
- const next = [...(Array.isArray(universe.styleImageRefs) ? universe.styleImageRefs : []), filename];
+ if (processedRef.current.has(filename)) return; // multi-fire guard
+ processedRef.current.add(filename);
+ const existing = Array.isArray(universe.styleImageRefs) ? universe.styleImageRefs : [];
+ if (existing.includes(filename)) return;
+ const next = [...existing, filename];
const updated = await updateUniverse(universe.id, { styleImageRefs: next }, { silent: true })
.catch(() => null);
- onUniverseChange?.(updated || { ...universe, styleImageRefs: next });
+ // Only reflect the new ref when the save actually succeeded — otherwise the
+ // draft would show an image the server never persisted.
+ if (updated) onUniverseChange?.(updated);
};
return (
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index fd48fd5741..8457fa9ac1 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback, useMemo } from 'react';
+import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { filterSelectableModels } from '../utils/providers';
import { composeStyledPrompt } from '../lib/composeStyledPrompt';
@@ -532,6 +532,10 @@ function StepCharacters({ session, universe, locked, onChanged }) {
const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);
const [renderingJobs, setRenderingJobs] = useState({});
const [refiningId, setRefiningId] = useState(null);
+ // MediaJobThumb's onFilename effect can fire more than once (StrictMode +
+ // the unstable per-render onComplete arrow); guard so each (char, filename)
+ // append runs exactly once.
+ const processedRef = useRef(new Set());
useEffect(() => {
getSettings({ silent: true })
@@ -557,13 +561,22 @@ function StepCharacters({ session, universe, locked, onChanged }) {
};
// Section-local renders don't carry a universeRun tag, so the server's
- // imageRef append hook never fires — persist the filename ourselves (mirrors
- // UniverseCanonSection.handleRefCompleted).
+ // imageRef append hook never fires — persist the filename ourselves. Refetch
+ // the freshest universe before appending so a sibling character's just-
+ // persisted imageRef isn't clobbered by a stale full-array PATCH.
const onCharRendered = async (charId, filename) => {
setRenderingJobs((p) => { if (!p[charId]) return p; const n = { ...p }; delete n[charId]; return n; });
if (!filename || !universe?.id) return;
- const list = (universe.characters || []).map((e) =>
- e.id === charId ? { ...e, imageRefs: [...(e.imageRefs || []), filename] } : e);
+ const key = `${charId}:${filename}`;
+ if (processedRef.current.has(key)) return; // multi-fire guard
+ processedRef.current.add(key);
+ const fresh = await getUniverse(universe.id, { silent: true }).catch(() => null);
+ const chars = (fresh?.characters) || universe.characters || [];
+ const list = chars.map((e) => (
+ e.id === charId
+ ? { ...e, imageRefs: (e.imageRefs || []).includes(filename) ? e.imageRefs : [...(e.imageRefs || []), filename] }
+ : e
+ ));
await updateUniverse(universe.id, { characters: list }, { silent: true }).catch(() => {});
onChanged();
};
@@ -732,12 +745,15 @@ function StoryBuilderDetail({ storyId, stepParam }) {
onSuccess: (_updated, next) => {
reload();
// "Lock & continue" should actually continue — on a successful LOCK,
- // auto-advance to the next step (the just-locked step makes it reachable;
- // the server re-gates the pointer move). Unlocking stays put.
- if (next && activeIdx >= 0 && activeIdx < stepIds.length - 1) {
+ // auto-advance to the next step. Skip if the current step is stale (the
+ // user must re-review, not advance) and only navigate AFTER the server
+ // accepts the pointer move, so a rejected gate doesn't strand the URL
+ // ahead of the persisted currentStep. Unlocking stays put.
+ if (next && !isStale && activeIdx >= 0 && activeIdx < stepIds.length - 1) {
const nextId = stepIds[activeIdx + 1];
- setStoryCurrentStep(storyId, nextId, { silent: true }).catch(() => {});
- navigate(`/story-builder/${storyId}/${nextId}`);
+ setStoryCurrentStep(storyId, nextId, { silent: true })
+ .then(() => navigate(`/story-builder/${storyId}/${nextId}`))
+ .catch(() => {});
}
},
lockedMessage: `${activeStep?.label || 'Step'} locked`,
@@ -756,10 +772,13 @@ function StoryBuilderDetail({ storyId, stepParam }) {
// default provider/model for every generate/refine, so one selection drives
// the whole wizard.
const saveLlm = async (next) => {
- await updateStorySession(storyId, {
+ const updated = await updateStorySession(storyId, {
llm: { provider: next.provider || null, model: next.model || null },
- }, { silent: true }).catch(() => {});
- reload();
+ }, { silent: true }).catch(() => null);
+ // An llm-only change touches nothing else — merge it locally instead of a
+ // full reload() (which would refetch session + universe + series + issues
+ // and briefly flicker the view).
+ if (updated) setSession((prev) => (prev ? { ...prev, llm: updated.llm } : prev));
};
if (loading) return <div className="p-6 text-gray-400 flex items-center gap-2"><Loader2 className="w-5 h-5 animate-spin" /> Loading…</div>;