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

refactor([extract-upsertbyidprepend-helper-universe-builder]): consolidate filter-by-id-then-prepend upsert into one helper

[._.]/ Adam Eivycfae094ee935
diff --git a/DONE.md b/DONE.md
index 94861e3058..3fde88f3bd 100644
--- a/DONE.md
+++ b/DONE.md
@@ -10,6 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
### 2026-05-17
+- **[extract-upsertbyidprepend-helper-universe-builder] Extract `upsertByIdPrepend(list, item)` helper.** New `client/src/lib/upsertByIdPrepend.js` collapses the "filter-by-id then prepend" worlds-list upsert into one helper. The PLAN line called out 3 sites; the actual count was 7 — all collapsed to `setWorlds((prev) => upsertByIdPrepend(prev, entity))`: 1 in `client/src/hooks/useUniverseAction.js` (LLM-action result merge) + 6 in `client/src/pages/UniverseBuilder.jsx` (`handleCreate`, `handleSave`, expand auto-save, refine auto-save, `handleMoveCategoryToTrunk`, `handleGenerateInCategory`). 4 new vitest cases in `upsertByIdPrepend.test.js` (new-id prepend, id replacement, empty-list, no input mutation).
- **[universe-builder-redesign-trunks-sub-buckets] Universe Builder redesign — trunks + sub-buckets layout (Phases A–D + Phase C follow-ups).** Multi-phase rewrite landing across 2026-05-15 → 2026-05-17. Phase A added a `kind: 'characters'|'settings'|'objects'|'other'` field to every category bucket + a migration to backfill the built-in defaults; Phase B taught `buildExpansionPrompt()` + `isExpansionShape()` to emit and accept rich canon arrays alongside categories, with client-side `handleExpand` merging canon entries into `universe.{characters,settings,objects}` (dedupe by name, respect locks); Phase C rewrote the page as a tabbed-trunk layout (Bible / Cast / Places / Objects / Other / Composites / Render) with URL state, a unified `EntryCard` rendering both canon entries and category variations, and per-trunk / per-bucket / all-canon batch-render targeting; Phase D shipped `POST /:id/promote-variation` to LLM-expand a variation into a full canon entry (atomic canon append + variation removal in one `updateUniverse` patch, duplicate-name 409 before the LLM call, trunk picker for `kind: 'other'` buckets). Phase C follow-ups closed today: (1) `updateUniverse(id, mutator)` now accepts an async `mutator(latest) => patch` callback that runs INSIDE `queueUniverseWrite` — `autoSortOtherBuckets` and `promoteVariationToCanon` route their read-modify-write through this so a slow LLM call can't admit a concurrent edit between read and persist; promote's variation removal also re-locates by label inside the queue rather than relying on the stale pre-LLM index, and the duplicate-name 409 is re-checked against the latest canon (returns `UNIVERSE_PROMOTE_CATEGORY_GONE` / `UNIVERSE_PROMOTE_VARIATION_GONE` when the bucket/variation disappears mid-flight); (2) `handleAutoSort` / `handlePromoteVariation` / `handleGenerateInCategory` now flush a dirty draft via `handleSave()` before kicking off — `UniverseBuilder.jsx` tracks a `savedDraftSnapshotRef` baseline (compared via `draftSnapshotForDirty`) that updates on universe-load, manual save, expand auto-save, refine auto-save, generate auto-save, and after each LLM mutator's `onFreshResult` merge. `useUniverseAction` gained a `preflight` option that runs AFTER the ref/savedId guard so double-clicks short-circuit before flushing. 5 new server tests (`updateUniverse` mutator overload — happy path, null-skip, throw-propagation, non-object validation, queue-ordering against a parallel literal-patch write) + 4 new client tests (`useUniverseAction` preflight — returns-false abort, throw-as-false, returns-true continue, post-ref-guard ordering).
- **[canoncard-from-series-name-full-provenance-label] CanonCard "from series: <name>" full provenance label.** The provenance chip now reads `seriesNameMap?.[entry.sourceSeriesId]` to render `from <Series Name>` with `Introduced by series "<name>" (<id>)` in the tooltip; missing-name fallback preserves the existing `from series` label + id-only tooltip. Chip rendering extracted into a `SourceSeriesChip` helper alongside `ChipPicker` / `ReadonlyChip` in `client/src/components/pipeline/CanonCard.jsx`. Map plumbed from both parents: `UniverseCanonSection.jsx` passes `usage?.seriesNameMap` (no new fetch — reuses the canon-usage call it already makes), and `NounsStage.jsx` fetches `getUniverseCanonUsage(series.universeId)` once on universe load. Server-side `getUniverseCanonUsage` (`server/services/canonUsage.js`) gains a top-level `seriesNameMap: { [seriesId]: name }` field built from every `linkedSeries` (not just ones with prose-match rows) so an entry whose `sourceSeriesId` points at a series with no matching prose still resolves to a name. Coverage: 4 new vitest cases in `CanonCard.test.jsx` (chip omitted with no `sourceSeriesId`; generic fallback when map missing; resolved name + dual-tooltip when present; fallback when id not in map) and 2 new `canonUsage.test.js` cases (linked-with-no-prose-match included; empty map when no series link). NounsStage's per-render fetch is acknowledged as quadratic-cost relative to need; deferred to `[nounsstage-cheaper-seriesnamemap-fetch]` for a thin-endpoint follow-up.
- **[extract-useuniverseaction-hook] Extract `useUniverseAction` hook from `UniverseBuilder.jsx`.** New `client/src/hooks/useUniverseAction.js` consolidates the scaffolding shared by `handlePromoteVariation` + `handleAutoSort`: `selectedId` guard, per-action ref re-entrancy, `capturedId` snapshot, loading-toast lifecycle (`silent: true` + `.catch` → dismiss + error), mountedRef-gated busy reset, always-update `setWorlds`, and the `mountedRef.current && capturedId === selectedId` stale-write guard. Each caller now passes only what varies — its `ref`/`setBusy`/`loadingMessage`/`errorPrefix`/`notSavedMessage`, the API call (receives `capturedId`), and an `onFreshResult(result)` callback that does the selective `setDraft` and returns the success-toast string. `handleGenerateInCategory` is intentionally NOT a consumer (the PLAN line's "to a lesser extent" — eager local merge first + best-effort save is a different shape; forcing it through would warp it); the hook header documents this. 9 new vitest cases in `useUniverseAction.test.jsx` (selectedId guard, re-entrancy, happy path, stale-write, action-rejects, no-loading-toast variant, falsy-universe result, suppressed-toast onFreshResult, unmount mid-flight). PLAN.md description gated this on "extract when a 4th handler lands"; promoted now with 3 — the hook itself is small and the scaffold is the most-bug-prone piece of these handlers.
diff --git a/PLAN.md b/PLAN.md
index 0fd99059b5..ac7e0bbcf5 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -102,7 +102,6 @@ _Nothing currently parked — pick the next item from the Backlog._
### Code quality / dedup (from `/simplify` passes)
-- [ ] [extract-upsertbyidprepend-helper-universe-builder] **Extract `upsertByIdPrepend(list, item)` helper.** The "filter out by id then prepend" upsert pattern is duplicated in three places: `client/src/pages/UniverseBuilder.jsx#handleMoveCategoryToTrunk` (~line 1393), `client/src/pages/UniverseBuilder.jsx#handleGenerateInCategory` (~line 1479), and `client/src/hooks/useUniverseAction.js` (~line 72). A two-line helper in `client/src/lib/` would dedupe all three. Surfaced by `/simplify` during the `useUniverseAction` extraction; deferred so that PR stays focused on the hook itself.
- [ ] [tabpills-pipelineissue-status-dot-trailing-slot] **Extend `<TabPills>` with a `trailing` slot to migrate `PipelineIssue.jsx`.** That page's tab row renders a per-tab status dot (`<span className="w-1.5 h-1.5 rounded-full ${STATUS_DOT[status]}" />`) after the label (see `client/src/pages/PipelineIssue.jsx:298-319`). Add an optional `t.trailing` ReactNode to the tab shape (rendered after the count), then migrate the call site. Defer until the next time a tab-bar variant lands so the API surface grows in response to a concrete second user, not in anticipation.
- [ ] [more-resolveproviderandmodel-migration-candidates] **More `resolveProviderAndModel` migration candidates.** When the helper landed in `server/lib/promptRunner.js` (universe-builder PR), three additional pure two-step provider-resolution chains were left alone to keep scope tight: `server/services/agentContentGenerator.js#runAIGeneration` (line ~80–90), `server/services/agentPersonalityGenerator.js` (line ~68–79), `server/services/loops.js` (line ~64–77). All three are textbook fits (no `enabled` gate, no typed-error throw mid-chain). Migration is one-import + 5-line collapse per file.
- [ ] [extract-assertprovider-provider-errormessage-code] **Extract `assertProvider(provider, { errorMessage, code, status })` helper.** After the `resolveProviderAndModel` migration there are now 4 `if (!provider) throw …` sites with varying error shapes (`Error` vs `ServerError`, `status: 400/503`, codes `NO_PROVIDER`/`UNIVERSE_PROMOTE_NO_PROVIDER`/etc.). One helper that takes the error-shape args would consolidate without forcing each caller to share the same error type.
diff --git a/client/src/hooks/useUniverseAction.js b/client/src/hooks/useUniverseAction.js
index 80b16137ed..0a9081eb5d 100644
--- a/client/src/hooks/useUniverseAction.js
+++ b/client/src/hooks/useUniverseAction.js
@@ -1,5 +1,6 @@
import { useCallback } from 'react';
import toast from '../components/ui/Toast';
+import { upsertByIdPrepend } from '../lib/upsertByIdPrepend';
// Scaffolding for LLM-driven universe mutations that follow the
// "guarded API call → setWorlds → stale-write-checked setDraft" pattern.
@@ -70,10 +71,7 @@ export default function useUniverseAction({ selectedId, mountedRef, setWorlds })
// away mid-flight, the persisted shape changed and other surfaces
// (list page, palette) should see it.
const updated = result.universe;
- setWorlds((prev) => {
- const without = prev.filter((w) => w.id !== updated.id);
- return [updated, ...without];
- });
+ setWorlds((prev) => upsertByIdPrepend(prev, updated));
if (!mountedRef.current || capturedId !== selectedId) {
if (toastId) toast.dismiss(toastId);
diff --git a/client/src/lib/upsertByIdPrepend.js b/client/src/lib/upsertByIdPrepend.js
new file mode 100644
index 0000000000..9eb5f0da6f
--- /dev/null
+++ b/client/src/lib/upsertByIdPrepend.js
@@ -0,0 +1,6 @@
+// Newest-first upsert into an id-keyed list: drop any existing entry with
+// the same `id`, then prepend `item`. Used by UniverseBuilder list updates
+// so the most-recently-edited universe surfaces at the top.
+export function upsertByIdPrepend(list, item) {
+ return [item, ...list.filter((entry) => entry.id !== item.id)];
+}
diff --git a/client/src/lib/upsertByIdPrepend.test.js b/client/src/lib/upsertByIdPrepend.test.js
new file mode 100644
index 0000000000..30129220cd
--- /dev/null
+++ b/client/src/lib/upsertByIdPrepend.test.js
@@ -0,0 +1,26 @@
+import { describe, it, expect } from 'vitest';
+import { upsertByIdPrepend } from './upsertByIdPrepend';
+
+describe('upsertByIdPrepend', () => {
+ it('prepends a new item when the id is absent', () => {
+ const list = [{ id: 'a' }, { id: 'b' }];
+ const next = upsertByIdPrepend(list, { id: 'c', name: 'fresh' });
+ expect(next).toEqual([{ id: 'c', name: 'fresh' }, { id: 'a' }, { id: 'b' }]);
+ });
+
+ it('replaces an existing entry with the new one at the front', () => {
+ const list = [{ id: 'a', v: 1 }, { id: 'b', v: 1 }, { id: 'c', v: 1 }];
+ const next = upsertByIdPrepend(list, { id: 'b', v: 2 });
+ expect(next).toEqual([{ id: 'b', v: 2 }, { id: 'a', v: 1 }, { id: 'c', v: 1 }]);
+ });
+
+ it('handles an empty list', () => {
+ expect(upsertByIdPrepend([], { id: 'a' })).toEqual([{ id: 'a' }]);
+ });
+
+ it('does not mutate the input list', () => {
+ const list = [{ id: 'a' }, { id: 'b' }];
+ upsertByIdPrepend(list, { id: 'a', changed: true });
+ expect(list).toEqual([{ id: 'a' }, { id: 'b' }]);
+ });
+});
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 94d0e540b4..d3d93e234e 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -40,6 +40,7 @@ import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends
import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings } from '../lib/pipelineImageDefaults';
import { normalizeSlugline } from '../lib/scenePrompt';
import { hasCanonDescriptorContent } from '../lib/canonPrompt';
+import { upsertByIdPrepend } from '../lib/upsertByIdPrepend';
const CATEGORY_LABELS = {
landscapes: 'Landscapes',
@@ -757,10 +758,7 @@ export default function UniverseBuilder() {
setSaving(false);
if (!result) return;
toast.success('World created');
- setWorlds((prev) => {
- const without = prev.filter((w) => w.id !== result.id);
- return [result, ...without];
- });
+ setWorlds((prev) => upsertByIdPrepend(prev, result));
goToWorld(result.id);
};
@@ -839,10 +837,7 @@ export default function UniverseBuilder() {
}
markDraftSaved(payload);
toast.success(selectedId ? 'World updated' : 'World created');
- setWorlds((prev) => {
- const without = prev.filter((w) => w.id !== result.id);
- return [result, ...without];
- });
+ setWorlds((prev) => upsertByIdPrepend(prev, result));
// After Create: jump to the new id's URL so back-button / refresh
// returns to the same world. After Update: id is unchanged, but
// navigating is harmless (replace-style).
@@ -1109,10 +1104,7 @@ export default function UniverseBuilder() {
.catch((e) => { toast.error(`Auto-save after expand failed: ${e.message}`); return null; })
.finally(() => setSaving(false));
if (saved) {
- setWorlds((prev) => {
- const without = prev.filter((w) => w.id !== saved.id);
- return [saved, ...without];
- });
+ setWorlds((prev) => upsertByIdPrepend(prev, saved));
// Auto-save succeeded — server now has the merged canon, so a
// subsequent manual Save shouldn't re-send it (avoids the
// concurrent-edit clobber). Drain the additions ledger too since
@@ -1178,10 +1170,7 @@ export default function UniverseBuilder() {
const updated = await updateUniverse(selectedId, refinePayload)
.catch((e) => { toast.error(`Auto-save after refine failed: ${e.message}`); return null; });
if (updated) {
- setWorlds((prev) => {
- const without = prev.filter((w) => w.id !== updated.id);
- return [updated, ...without];
- });
+ setWorlds((prev) => upsertByIdPrepend(prev, updated));
markDraftSaved(refinePayload);
}
}
@@ -1428,10 +1417,7 @@ export default function UniverseBuilder() {
const updated = await updateUniverse(selectedId, { categories: { [bucket]: nextBucket } }, { silent: true })
.catch((e) => { toast.error(`Move failed: ${e.message}`); return null; });
if (updated) {
- setWorlds((prev) => {
- const without = prev.filter((w) => w.id !== updated.id);
- return [updated, ...without];
- });
+ setWorlds((prev) => upsertByIdPrepend(prev, updated));
toast.success(`Moved "${humanizeCategory(bucket)}" to ${trunk.label}`);
}
};
@@ -1530,10 +1516,7 @@ export default function UniverseBuilder() {
const updated = await updateUniverse(selectedId, { categories: nextDraft.categories })
.catch((e) => { toast.error(`Auto-save after generate failed: ${e.message}`); return null; });
if (updated) {
- setWorlds((prev) => {
- const without = prev.filter((w) => w.id !== updated.id);
- return [updated, ...without];
- });
+ setWorlds((prev) => upsertByIdPrepend(prev, updated));
markDraftSaved(nextDraft);
toast.success(`Added ${additionCount} variation${additionCount === 1 ? '' : 's'} to ${humanizeCategory(cat)} — saved`);
return;