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: scope useSingleImageRender base-style render per-universe via scopeId (#1393)

Adam Eivya1677f4bd0af
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 24f25bcd97..9bb278e61e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -113,6 +113,8 @@
## Fixed
+- **[issue-1393] The universe base-style probe now scopes its in-flight render per universe instead of remounting on every switch.** The probe spinner used to be kept from leaking across universe switches by remounting the whole `StyleProbeImage` (a `key={universe.id}` in the Universe Builder and Story Builder). That worked but had two costs: every switch re-ran the probe's `{ silent: true }` image-settings GET, and switching *away* from an in-flight render abandoned its completion — the server still filed the image, but switching back never resumed the spinner or pinned the result onto the universe's style refs for that session. `useSingleImageRender` now takes a `scopeId` that namespaces the single-target key per universe (`<id>:__single__`), so the displayed universe's job is read without a remount: no per-switch settings refetch, and switching back to a still-running (or already-finished) render resumes it and captures its completion. The mid-render style-drift guard is now keyed per universe too, so a stale image can't pin to the wrong record when two probes overlap across a switch. (`client/src/hooks/useSingleImageRender.js`, `client/src/components/universe/StyleProbeImage.jsx`, `client/src/pages/{UniverseBuilder,StoryBuilder}.jsx`, #1393)
+
- **[issue-1422] Re-planning a goal that has scheduled calendar blocks no longer silently strands those calendar events, and a malformed AI plan now fails fast.** Accepting a new AI-generated plan (either *Generate Plan* phases or *Decompose into Tasks*) replaces a goal's milestones wholesale — but if you'd already pushed those milestones onto your calendar as time blocks, the old blocks were left pointing at milestones that no longer existed. Accepting now refuses with a clear message asking you to unschedule first, so your calendar can't drift out of sync with your plan. Separately, both *Generate Plan* and *Decompose into Tasks* now validate the AI's proposal the moment it comes back — a garbled response surfaces a clear error up front instead of looking fine in the review screen and only breaking when you try to accept it.
- **The Chief of Staff 3D avatar no longer slowly zooms itself in until you reload.** The full-bleed background avatar keeps a constant apparent size by moving the camera back as the panel grows (`CoSBackgroundCamera` derives `camera.position.z` from the live-measured canvas height). But a transient *zero / pre-layout / hidden* size reading — which fires when the agent panel collapses and re-expands, when the EventLog mounts on the "working on task" transition, or from tab-occlusion ResizeObserver frames — collapsed the scale factor to its floor and slammed the camera to its closest (most zoomed-in) position, which `OrbitControls` then latched with no guaranteed correction. Over a busy night of state transitions the avatar ended up "zoomed way in," fixable only by a page reload. The camera-distance math is now a pure, unit-tested helper that returns `null` for any degenerate (non-finite or sub-pixel) measurement, so those frames leave the camera at its last good framing instead of yanking it in. (`client/src/components/cos/CoSBackgroundCamera.jsx`)
diff --git a/client/src/components/universe/StyleProbeImage.jsx b/client/src/components/universe/StyleProbeImage.jsx
index 39243acf80..09ed804c29 100644
--- a/client/src/components/universe/StyleProbeImage.jsx
+++ b/client/src/components/universe/StyleProbeImage.jsx
@@ -63,8 +63,11 @@ export const shouldPersistProbe = ({ styleDirty, capturedKey, currentKey }) =>
export default function StyleProbeImage({ universe, onUniverseChange, canRender = true, styleDirty = false, onPreview = null, onRenderComplete = null }) {
const { imageCfg } = useImageRenderSettings();
// The style key the in-flight probe was queued against, captured at render
- // time so the async completion can detect mid-render style drift.
- const probeStyleKeyRef = useRef(null);
+ // time so the async completion can detect mid-render style drift. Keyed by
+ // universe so this component can stay mounted across a universe switch (no
+ // remount) without one universe's captured key shadowing another's.
+ const probeStyleKeysRef = useRef(new Map());
+ const probeScope = universe?.id || '__new__';
const styleReady = hasStyleForProbe(universe);
// The probe prompt is built from the in-memory `influences`, but `onComplete`
@@ -81,7 +84,7 @@ export default function StyleProbeImage({ universe, onUniverseChange, canRender
// record AND the live style matches what the probe was queued against — else
// the image would pin to a record built from different influences (the very
// mismatch the render-time gate exists to prevent).
- if (!shouldPersistProbe({ styleDirty, capturedKey: probeStyleKeyRef.current, currentKey: probeStyleKey(universe) })) {
+ if (!shouldPersistProbe({ styleDirty, capturedKey: probeStyleKeysRef.current.get(probeScope) ?? null, currentKey: probeStyleKey(universe) })) {
toast.error('Style changed while the base style rendered — re-run the probe');
return;
}
@@ -105,6 +108,10 @@ export default function StyleProbeImage({ universe, onUniverseChange, canRender
buildPrompt: () => buildStyleProbePrompt(universe),
onComplete,
onError: (err) => toast.error(err?.message || 'Style render failed'),
+ // Scope the single-target render per universe so this component can stay
+ // mounted across a universe switch (no `key` remount) and still read the
+ // in-flight job / resume completion relative to the displayed universe.
+ scopeId: universe?.id,
});
const render = async () => {
@@ -122,7 +129,7 @@ export default function StyleProbeImage({ universe, onUniverseChange, canRender
? { universeId: universe.id, universeName: universe.name, label: 'Base style', category: 'style' }
: undefined;
const queuedJobId = await queueRender(imageCfg, undefined, universeRun && { universeRun });
- if (queuedJobId) probeStyleKeyRef.current = JSON.stringify(probe);
+ if (queuedJobId) probeStyleKeysRef.current.set(probeScope, JSON.stringify(probe));
};
const hasExistingImage = Array.isArray(universe?.styleImageRefs) && universe.styleImageRefs.length > 0;
diff --git a/client/src/hooks/useSingleImageRender.js b/client/src/hooks/useSingleImageRender.js
index 674bb511c0..3cbc4771ff 100644
--- a/client/src/hooks/useSingleImageRender.js
+++ b/client/src/hooks/useSingleImageRender.js
@@ -34,6 +34,14 @@ const SINGLE_KEY = '__single__';
* @param {Function} opts.onComplete — `(filename, key) => void | Promise<void>`
* @param {Function} [opts.onError] — `(err) => void` for a failed queue POST.
* Defaults to a no-op; the POST is sent `{ silent: true }` so the caller owns UI.
+ * @param {string} [opts.scopeId] — namespaces the single-target key per scope.
+ * Single-target callers that show one of several entities in the same mounted
+ * hook (the universe base-style probe, one universe at a time) pass the entity
+ * id here so the default `jobId`/completion are read relative to the displayed
+ * entity as `<scopeId>:__single__` — switching scope and back resumes a still
+ * in-flight (or already-finished) job instead of abandoning it on a remount.
+ * Omit it for a truly single render. Multi-target callers (explicit keys) are
+ * unaffected.
* @returns {{ jobId, renderingJobs, render, handleComplete }}
* - `jobId` — the single in-flight job's id (or null). Convenience for
* single-target callers; multi-target callers read `renderingJobs[key]`.
@@ -43,7 +51,7 @@ const SINGLE_KEY = '__single__';
* `universeRun` collection target the server routes the finished render to).
* - `handleComplete(filename, key)` — clear the job + run the guarded onComplete.
*/
-export default function useSingleImageRender({ buildPrompt, onComplete, onError } = {}) {
+export default function useSingleImageRender({ buildPrompt, onComplete, onError, scopeId } = {}) {
// Keyed by an arbitrary caller key (a character id, or a stable sentinel for
// single-target callers). Single-target callers also read `jobId`.
const [renderingJobs, setRenderingJobs] = useState({});
@@ -51,6 +59,15 @@ export default function useSingleImageRender({ buildPrompt, onComplete, onError
// effect can re-fire under StrictMode + unstable per-render onComplete arrows.
const processedRef = useRef(new Set());
+ // The default key for single-target callers. With `scopeId` it is namespaced
+ // per scope so a single mounted hook can track one in-flight render per
+ // displayed entity (no remount to reset state). Recomputed each render so
+ // `jobId` re-reads the displayed scope; held in a ref so the `render` /
+ // `handleComplete` callbacks stay identity-stable.
+ const effectiveSingleKey = scopeId == null || scopeId === '' ? SINGLE_KEY : `${scopeId}:${SINGLE_KEY}`;
+ const singleKeyRef = useRef(effectiveSingleKey);
+ singleKeyRef.current = effectiveSingleKey;
+
const buildPromptRef = useRef(buildPrompt);
buildPromptRef.current = buildPrompt;
const onCompleteRef = useRef(onComplete);
@@ -58,7 +75,7 @@ export default function useSingleImageRender({ buildPrompt, onComplete, onError
const onErrorRef = useRef(onError);
onErrorRef.current = onError;
- const render = useCallback(async (imageCfg, key = SINGLE_KEY, extraParams = undefined) => {
+ const render = useCallback(async (imageCfg, key = singleKeyRef.current, extraParams = undefined) => {
const built = buildPromptRef.current?.(key);
if (!built) return null; // caller aborted (already toasted why)
const baseOpts = pipelineImageCfgToRenderOpts(imageCfg);
@@ -75,7 +92,7 @@ export default function useSingleImageRender({ buildPrompt, onComplete, onError
return queued.jobId;
}, []);
- const handleComplete = useCallback(async (filename, key = SINGLE_KEY) => {
+ const handleComplete = useCallback(async (filename, key = singleKeyRef.current) => {
setRenderingJobs((prev) => {
if (!prev[key]) return prev;
const next = { ...prev };
@@ -89,5 +106,5 @@ export default function useSingleImageRender({ buildPrompt, onComplete, onError
await onCompleteRef.current?.(filename, key);
}, []);
- return { jobId: renderingJobs[SINGLE_KEY] || null, renderingJobs, render, handleComplete };
+ return { jobId: renderingJobs[effectiveSingleKey] || null, renderingJobs, render, handleComplete };
}
diff --git a/client/src/hooks/useSingleImageRender.test.jsx b/client/src/hooks/useSingleImageRender.test.jsx
index 3d83e7222e..27b47cb801 100644
--- a/client/src/hooks/useSingleImageRender.test.jsx
+++ b/client/src/hooks/useSingleImageRender.test.jsx
@@ -90,6 +90,43 @@ describe('useSingleImageRender', () => {
expect(onComplete).toHaveBeenLastCalledWith('a.png', 'char-b');
});
+ it('namespaces the single-target key per scopeId (jobId + completion key)', async () => {
+ generateImage.mockResolvedValue({ jobId: 'job-u1' });
+ const onComplete = vi.fn();
+ const { result } = renderHook(() =>
+ useSingleImageRender({ buildPrompt: () => ({ prompt: 'p' }), onComplete, scopeId: 'u1' }));
+
+ await act(async () => { await result.current.render(IMG_CFG); });
+ // The job is tracked under the scoped key, and `jobId` reads it back.
+ expect(result.current.renderingJobs).toEqual({ 'u1:__single__': 'job-u1' });
+ expect(result.current.jobId).toBe('job-u1');
+
+ await act(async () => { await result.current.handleComplete('out.png'); });
+ expect(onComplete).toHaveBeenCalledWith('out.png', 'u1:__single__');
+ expect(result.current.jobId).toBeNull();
+ });
+
+ it('reads the displayed scope and resumes a still-running job on switch-back', async () => {
+ generateImage.mockResolvedValueOnce({ jobId: 'job-u1' }).mockResolvedValueOnce({ jobId: 'job-u2' });
+ const onComplete = vi.fn();
+ const { result, rerender } = renderHook(
+ ({ scopeId }) => useSingleImageRender({ buildPrompt: () => ({ prompt: 'p' }), onComplete, scopeId }),
+ { initialProps: { scopeId: 'u1' } },
+ );
+
+ // Queue a render for u1, then switch to u2 (no remount) and queue one there.
+ await act(async () => { await result.current.render(IMG_CFG); });
+ rerender({ scopeId: 'u2' });
+ expect(result.current.jobId).toBeNull(); // u2 has nothing in flight yet
+ await act(async () => { await result.current.render(IMG_CFG); });
+ expect(result.current.jobId).toBe('job-u2');
+
+ // Switch back to u1 — its still-running job resurfaces instead of being lost.
+ rerender({ scopeId: 'u1' });
+ expect(result.current.jobId).toBe('job-u1');
+ expect(result.current.renderingJobs).toEqual({ 'u1:__single__': 'job-u1', 'u2:__single__': 'job-u2' });
+ });
+
it('ignores a completion with no filename but still clears the job', async () => {
generateImage.mockResolvedValue({ jobId: 'job-1' });
const onComplete = vi.fn();
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index e2e289c226..4a26663bc1 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -686,7 +686,10 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange
<div className="border-t border-port-border pt-3">
{/* Keyed by universe id so an in-flight base-style render's spinner +
completion stay scoped to one universe across a selection change. */}
- <StyleProbeImage key={universe?.id || 'new'} universe={universe} onUniverseChange={() => onChanged()} canRender={!locked} />
+ {/* No `key` remount — `useSingleImageRender` scopes the probe per
+ universe via `scopeId`, so the in-flight render/completion follows
+ the displayed universe without a settings refetch on each switch. */}
+ <StyleProbeImage universe={universe} onUniverseChange={() => onChanged()} canRender={!locked} />
</div>
<div className="flex items-center gap-2">
{!locked && genButton('Expand aesthetic', Boolean((universe?.premise || universe?.styleNotes || '').trim()))}
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index a8209b1fa6..7aba88e584 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -3019,14 +3019,13 @@ function BibleTab({
only that field into the draft so unsaved style edits aren't lost.
`styleDirty` blocks the render while influences have unsaved edits —
otherwise the probe pins to a saved record that lacks that style. */}
- {/* Key by universe id so the probe's in-flight render state (the
- EntryThumbSlot spinner + the async completion handler) is scoped
- to one universe. Without the key the editor stays mounted across a
- `/universes/:id` switch and the prior universe's spinner — and its
- completion — would leak onto the next universe's slot. The server
- still files the abandoned render into its own collection. */}
+ {/* The probe's in-flight render state (the EntryThumbSlot spinner +
+ the async completion handler) is scoped to one universe by
+ `useSingleImageRender`'s `scopeId` (the universe id), so this stays
+ mounted across a `/universes/:id` switch WITHOUT a `key` remount —
+ no per-switch settings refetch, and switching back resumes a
+ still-running render instead of abandoning its completion. */}
<StyleProbeImage
- key={draft.id || 'new'}
universe={draft}
onUniverseChange={(updated) => updateDraft({ styleImageRefs: updated?.styleImageRefs || [] })}
onPreview={onPreview}