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
chore(quality): batch dedup pass across server + client (#266)
[._.]/ Adam Eivya544f64003bb
diff --git a/PLAN.md b/PLAN.mdindex 1386495740..b5c0ae0009 100644--- a/PLAN.md+++ b/PLAN.md@@ -99,31 +99,11 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]- [ ] **Extract `useSwipeNav` hook + `lib/clipboard.js`.** `MediaLightbox` swipe nav; clipboard inlined across 8+ call sites. Clipboard can move now.- [ ] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`.** Reconcile `Drawer`'s flat Esc handler with the lightbox's layered Escape cascade.-- [ ] **Extract `<ModelSelect>` component for the active+Legacy optgroup pattern.** `VideoGen.jsx` + `CreativeDirector.jsx` render identical blocks differing only in `m.name` vs `m.name || m.id`.-- [ ] **Extract `mockPathsDataRoot()` test helper.** 6 test files open with byte-identical PATHS mocking setup.- [ ] **`useAsyncAction` post-unmount setState guard.** Add `mountedRef` to gate `setRunning(false)`. YAGNI today; do at 4th consumer.-- [ ] **Extract `CollectionPickerShell` from `AddToCollectionMenu` + `BulkTargetPicker`.** Two near-identical portal popovers. While extracting, accept a `collections` prop so `MediaCollectionDetail` avoids per-mount `listMediaCollections` round-trip.-- [ ] **Server-side bulk endpoint for collection items.** `POST /api/media/collections/:id/items/bulk` taking `{ add, remove }` — single read-modify-write per collection. Halves wall-clock for Move; dodges N-call race window. Real use case: "select all" on world-builder collections with 50+ items.-- [ ] **Drop legacy `description` fallback in `sanitizeCharacter`.** Migrate `series.characters[].description` → `physicalDescription`; drop `|| raw.description` at `storyBible.js:246`.-- [ ] **Migrate `worldBuilderRefine.runRefine` onto `runPromptThroughProvider`.** Last LLM-runner site still hand-rolling the createRun → branch → executeApi/CliRun → accumulate-text pattern. ~30 LOC dedup.-- [ ] **Extract `usePersistedState` hook.** Six components repeat `useState(() => localStorage.getItem(KEY) === '1')` + setter. Add `useLocalStorageBool(key, default)` + JSON-blob variant.-- [ ] **Lift `runFfmpegProcess({ args, signal, stderrTailBytes }) → { ok, reason }` into `server/lib/ffmpeg.js`.** Three sites share spawn → stderr-tail → close → SIGTERM-on-abort. Leave `videoTimeline/local.js` (broadcast complicates it).- [ ] **Scene-level wardrobe picking.** Per-scene `characterAppearances: [{ characterId, wardrobeId? }]` on storyboard scenes with wardrobe-picker dropdown. Decide first: does the extractor guess or does the user pick? Append wardrobe after physicalDescription vs substitute body fields?-- [ ] **Extract `sanitizeListWith(raw, sanitizer, cap)` helper in `storyBible.js`.** Three array-walk + per-item sanitize + cap sites.- [ ] **Extract `useCanonPatch(universe, setUniverse, universeId, mountedRef)`.** `UniverseCanon.jsx` + `NounsStage.jsx` 95% identical optimistic-patch handlers. Extract when a 3rd caller appears.-- [ ] **AbortSignal listener cleanup in `audioMux.js#runFfmpeg`.** `addEventListener('abort', kill, { once: true })` never removed on normal completion. Theoretical until the stitch step passes a signal.-- [ ] **Extract `listDirectoryByExtension(dir, { extensions, mapEntry })`.** Three readdir + filter + stat-per-entry sites in `fileUtils.js`.-- [ ] **Teach `request()` in `apiCore.js` about FormData.** Drop hard-coded `Content-Type: application/json` when body is FormData. Two helpers (`apiHealth#uploadAppleHealthXml`, `apiPipeline#uploadPipelineMusicTrack`) bypass `request()` today.-- [ ] **`mergeVariations` NPE guard in `UniverseBuilder.jsx`.** Add `.label?.toLowerCase()` + `.filter(Boolean)` parity to the locked variations Set (post-rename file/line drift — agent confirmed line 57 still lacks the guard).- [ ] **Client tests for deep routing + drag.** Smoke tests for `goToWorld(id)` URL transitions and chip-reorder ordering (mock `useSortable`).-- [ ] **`useMediaAnnotations.getCardProps(key)` helper.** Single `{ starred, hasNote, onToggleStar }` lookup at 6 sites across 4 gallery pages.-- [ ] **Cache `resolveGlobalDisplayName()` settings read.** Memoize for ~30s or invalidate on `settings:updated` event.- [ ] **Shallow-equal guard in `useMediaAnnotations` socket handler.** Speculative micro-opt; theoretical until observed.-- [ ] **Hoist identity lookup out of `liftLegacyEntry` loop in `mediaAnnotations.js#readAll()`.** Pass `localInstanceId`, `defaultAuthorName` in once; make `liftLegacyEntry` synchronous.-- [ ] **Bulk reassign helper to collapse N+1 writes in `deleteSeason`.** Add `issuesSvc.bulkReassignSeason(seriesId, fromSeasonId, toSeasonId)` — one readState + N in-memory mutations + one writeState + one renumber.-- [ ] **Extract shared task block + review-loop section in `agentPromptBuilder.js`.** The light path (`buildLightContextPrompt` ~line 510) and full path (`buildAgentPrompt` fallback ~line 425) now emit nearly identical task blocks (`description` + optional `**Target App**:` + optional `**Screenshots**:`). The review-loop follow-up section is duplicated between the full-context block (~line 312-343) and the light-context block (~line 575-602) — same 7-step loop, same `gh pr merge --squash --delete-branch` command, same `gh pr view --json state` verification, same "10 iterations" hard stop. The auto-merge bug fix (PR removing `--auto`) had to be applied in both places. Extract `buildTaskBlock(task, { screenshotsAsList })` + `buildReviewLoopFollowUpSection(metadata, { verbose })` so the next sync edit doesn't drift.-- [ ] **Flatten the giant `isReadOnly ? … : isTui ? … : worktreeInfo && willOpenPR ? …` ternary in `agentPromptBuilder.js` Guidelines bullet (~line 458).** Pre-existing 4-branch one-liner that covers readOnly/TUI/worktree+PR/worktree-only/default-empty. Extract a `buildCompletionGuidelineBullet({ isReadOnly, isTui, tuiCompletionCommand, worktreeInfo, willOpenPR, willReviewLoop })` helper mirroring the pattern the light path already uses (`worktreeCommitGuidance`, `buildTuiCompletionSection`). Returns string or `null`.-- [ ] **Test the untested `worktreeCommitGuidance` branches in `agentPromptBuilder.js`.** Five-branch decision tree at ~line 617; tests don't cover `isWorktreeOnExistingBranch=true` or `hasSlashdo && !willOpenPR`.- [ ] **Extract a `tryReadFile(path, encoding='utf8')` helper into `server/lib/fileUtils.js`.** The `readFile(path).catch(() => null)` pattern is inlined 15+ times across the codebase (`server/routes/apps.js:38` `safeReadJson`, `server/lib/fileUtils.js:505`, `server/lib/hfToken.js:16`, `server/services/agentDrafts.js:22`, `server/services/messageAccounts.js:10`, `server/services/missions.js:35`, `server/lib/tuiPromptRunner.js` new at line ~202, etc.). One helper + migrate; small win, prevents future drift. Defer until next infra pass.- [ ] **Skip the `text` accumulator in `promptRunner.runPromptThroughProvider` for TUI providers.** `APPEND_CHUNK(acc, chunk)` runs per stream chunk regardless of provider type, but the TUI branch (post `fix-prose-stage-override`) discards the accumulated `text` and uses `result.text` from `executeTuiRun` instead. Streams can hit hundreds of KB of screen redraws per run — gate the accumulator on `effectiveProvider.type !== 'tui'` in `onData` to skip the per-chunk string concat. Pre-existing buffer cap on `outputBuffer` inside `executeTuiRun` already bounds memory; this is a CPU/alloc micro-opt, not a correctness fix.diff --git a/client/src/components/ModelSelect.jsx b/client/src/components/ModelSelect.jsxnew file mode 100644index 0000000000..28b7f30034--- /dev/null+++ b/client/src/components/ModelSelect.jsx@@ -0,0 +1,34 @@+// Active + Legacy optgroup `<select>` shared by media-gen pages (VideoGen,+// CreativeDirector). Splits `models` into active and `m.deprecated === true`+// groups; the Legacy optgroup only renders when at least one deprecated model+// exists. `getLabel` picks the option text — defaults to `m.name`; callers+// whose model shape may omit `name` pass `(m) => m.name || m.id`.+const defaultGetLabel = (m) => m.name;+export default function ModelSelect({+ models,+ value,+ onChange,+ getLabel = defaultGetLabel,+ id,+ className = 'w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50',+ disabled = false,+}) {+ const active = models.filter((m) => !m.deprecated);+ const legacy = models.filter((m) => m.deprecated);+ return (+ <select+ id={id}+ value={value}+ onChange={onChange}+ disabled={disabled}+ className={className}+ >+ {active.map((m) => <option key={m.id} value={m.id}>{getLabel(m)}</option>)}+ {legacy.length > 0 && (+ <optgroup label="Legacy">+ {legacy.map((m) => <option key={m.id} value={m.id}>{getLabel(m)}</option>)}+ </optgroup>+ )}+ </select>+ );+}diff --git a/client/src/components/meatspace/tabs/SettingsTab.jsx b/client/src/components/meatspace/tabs/SettingsTab.jsxindex f4bf7c6af9..b5db4f1b43 100644--- a/client/src/components/meatspace/tabs/SettingsTab.jsx+++ b/client/src/components/meatspace/tabs/SettingsTab.jsx@@ -93,7 +93,9 @@ export default function SettingsTab({ onRefresh }) {setXmlProgress(0);setXmlImporting(true);- api.uploadAppleHealthXml(file).catch(err => {+ // Owns its own error UI (xmlError) so suppress the helper's toast — per+ // CLAUDE.md "custom catch ⇒ silent: true" convention.+ api.uploadAppleHealthXml(file, { silent: true }).catch(err => {setXmlError(err.message);setXmlImporting(false);});diff --git a/client/src/components/media/AddToCollectionMenu.jsx b/client/src/components/media/AddToCollectionMenu.jsxindex 34ed47294c..6b7ccfe8b7 100644--- a/client/src/components/media/AddToCollectionMenu.jsx+++ b/client/src/components/media/AddToCollectionMenu.jsx@@ -1,24 +1,17 @@-import { useEffect, useLayoutEffect, useRef, useState, useCallback, useMemo } from 'react';-import { createPortal } from 'react-dom';-import { FolderPlus, Check, Plus, Search } from 'lucide-react';+import { useCallback, useRef, useState } from 'react';+import { FolderPlus, Check } from 'lucide-react';import toast from '../ui/Toast';-import {- listMediaCollections, createMediaCollection,- addMediaCollectionItem, removeMediaCollectionItem,-} from '../../services/api';+import CollectionPickerShell from './CollectionPickerShell';+import { addMediaCollectionItem, removeMediaCollectionItem } from '../../services/api';// Self-contained popover button used by MediaCard. The popover is portalled-// into <body> with fixed positioning so it escapes the parent grid's-// `overflow-auto` clip and stacks above the sidebar (which is z-50).+// into <body> by CollectionPickerShell with fixed positioning so it escapes+// the parent grid's `overflow-auto` clip and stacks above the sidebar.//-// `itemKey` is "<kind>:<ref>" — the same format the server uses for-// coverKey and for the DELETE /items/:key route.--const MENU_WIDTH = 240;-const MENU_GAP = 6;-const VIEWPORT_PADDING = 8;-// Show search affordance only when the list could meaningfully scroll.-const SEARCH_THRESHOLD = 6;+// `itemKey` is "<kind>:<ref>" — the same format the server uses for coverKey+// and for the DELETE /items/:key route.+//+// The shell is now shared with BulkTargetPicker (see CollectionPickerShell.jsx).// Only the trigger button varies by size — popover styling is fixed.const SIZES = {@@ -28,115 +21,18 @@ const SIZES = {export default function AddToCollectionMenu({ item, size = 'sm' }) {const [open, setOpen] = useState(false);- const [collections, setCollections] = useState(null); // null = not loaded- const [creating, setCreating] = useState(false);- const [newName, setNewName] = useState('');const [busyId, setBusyId] = useState(null);- const [query, setQuery] = useState('');- const [menuStyle, setMenuStyle] = useState(null);const triggerRef = useRef(null);- const menuRef = useRef(null);const itemKey = item.key;const itemRef = item.kind === 'video' ? item.id : item.filename;- const filtered = useMemo(() => {- if (!collections) return null;- const q = query.trim().toLowerCase();- if (!q) return collections;- return collections.filter((c) => c.name.toLowerCase().includes(q));- }, [collections, query]);-- const updateMenuPosition = useCallback(() => {- const trigger = triggerRef.current;- const menu = menuRef.current;- if (!trigger || !menu) return;-- const viewportWidth = window.innerWidth;- const viewportHeight = window.innerHeight;- const width = Math.min(MENU_WIDTH, Math.max(180, viewportWidth - VIEWPORT_PADDING * 2));- menu.style.width = `${width}px`;-- const triggerRect = trigger.getBoundingClientRect();- const menuRect = menu.getBoundingClientRect();-- const maxLeft = viewportWidth - width - VIEWPORT_PADDING;- const left = Math.min(- Math.max(triggerRect.right - width, VIEWPORT_PADDING),- Math.max(VIEWPORT_PADDING, maxLeft),- );-- const aboveTop = triggerRect.top - menuRect.height - MENU_GAP;- const belowTop = triggerRect.bottom + MENU_GAP;- const wouldOverflowTop = aboveTop < VIEWPORT_PADDING;- let top = wouldOverflowTop ? belowTop : aboveTop;- const maxTop = Math.max(VIEWPORT_PADDING, viewportHeight - menuRect.height - VIEWPORT_PADDING);- top = Math.min(Math.max(top, VIEWPORT_PADDING), maxTop);-- setMenuStyle((prev) => {- const next = { left: `${left}px`, top: `${top}px`, width: `${width}px` };- if (prev && prev.left === next.left && prev.top === next.top && prev.width === next.width) return prev;- return next;- });- }, []);-- useEffect(() => {- if (!open) return undefined;- const onClickAway = (e) => {- const onTrigger = triggerRef.current?.contains(e.target);- const onMenu = menuRef.current?.contains(e.target);- if (!onTrigger && !onMenu) setOpen(false);- };- const onEsc = (e) => { if (e.key === 'Escape') setOpen(false); };- let rafId = null;- const onReposition = () => {- if (rafId !== null) return;- rafId = requestAnimationFrame(() => {- rafId = null;- updateMenuPosition();- });- };- document.addEventListener('mousedown', onClickAway);- document.addEventListener('keydown', onEsc);- window.addEventListener('resize', onReposition);- window.addEventListener('scroll', onReposition, true);- return () => {- if (rafId !== null) cancelAnimationFrame(rafId);- document.removeEventListener('mousedown', onClickAway);- document.removeEventListener('keydown', onEsc);- window.removeEventListener('resize', onReposition);- window.removeEventListener('scroll', onReposition, true);- };- }, [open, updateMenuPosition]);-- useLayoutEffect(() => {- if (!open) {- setMenuStyle(null);- return;- }- updateMenuPosition();- }, [open, updateMenuPosition, collections, filtered, query]);-- const ensureLoaded = async () => {- if (collections != null) return;- const data = await listMediaCollections().catch((err) => {- toast.error(err.message || 'Failed to load collections');- return [];- });- setCollections(Array.isArray(data) ? data : []);- };-- const handleToggleOpen = async (e) => {+ const handleToggleOpen = (e) => {e.stopPropagation();- const next = !open;- setOpen(next);- if (next) {- setQuery('');- await ensureLoaded();- }+ setOpen((prev) => !prev);};- const handleToggleMembership = async (collection) => {+ const handleToggleMembership = useCallback(async (collection, updateCollections) => {const inIt = collection.items.some((it) => `${it.kind}:${it.ref}` === itemKey);setBusyId(collection.id);const updated = inIt@@ -150,37 +46,46 @@ export default function AddToCollectionMenu({ item, size = 'sm' }) {});setBusyId(null);if (!updated) return;- setCollections((prev) => (prev || []).map((c) => (c.id === collection.id ? updated : c)));+ updateCollections((prev) => (prev || []).map((c) => (c.id === collection.id ? updated : c)));toast.success(inIt ? `Removed from ${collection.name}` : `Added to ${collection.name}`);+ }, [itemKey, itemRef, item.kind]);++ const renderItem = (c, { updateCollections }) => {+ const inIt = c.items.some((it) => `${it.kind}:${it.ref}` === itemKey);+ return (+ <button+ key={c.id}+ type="button"+ disabled={busyId === c.id}+ onClick={() => handleToggleMembership(c, updateCollections)}+ className="w-full flex items-center justify-between gap-2 px-2 py-1.5 text-left text-[12px] text-gray-200 hover:bg-port-border rounded disabled:opacity-50"+ role="menuitemcheckbox"+ aria-checked={inIt}+ >+ <span className="break-words min-w-0 flex-1">{c.name}</span>+ {inIt && <Check className="w-3.5 h-3.5 text-port-success shrink-0" />}+ </button>+ );};- const handleCreate = async (e) => {- e.preventDefault();- const name = newName.trim();- if (!name) return;- setCreating(true);- const created = await createMediaCollection({ name }).catch((err) => {- toast.error(err.message || 'Create failed');- return null;- });- if (!created) { setCreating(false); return; }+ const handleCreated = useCallback(async (created, { addToCollectionsState }) => {+ // For this variant of the picker, creating a collection means "add the+ // current item to the new collection." Surface the underlying-add failure+ // separately from the create itself so the user knows the collection+ // exists even if the auto-add failed.let addError = null;const withItem = await addMediaCollectionItem(created.id, { kind: item.kind, ref: itemRef }).catch((err) => {addError = err;return created;});- setCollections((prev) => ([...(prev || []), withItem]));- setNewName('');- setCreating(false);+ addToCollectionsState((prev) => ([...(prev || []), withItem]));if (addError) {toast.error(`Created "${created.name}" but failed to add: ${addError.message}`);} else {toast.success(`Added to ${created.name}`);}- };+ }, [item.kind, itemRef]);- const showSearch = (collections?.length || 0) >= SEARCH_THRESHOLD;- const list = filtered ?? collections;const sizeCls = SIZES[size] || SIZES.sm;return (@@ -196,83 +101,18 @@ export default function AddToCollectionMenu({ item, size = 'sm' }) {><FolderPlus className={sizeCls.icon} /></button>- {open && createPortal(- <div- ref={menuRef}- className="fixed bg-port-card border border-port-border rounded-lg shadow-xl z-[100] p-1.5 flex flex-col"- style={{- left: menuStyle?.left ?? `${VIEWPORT_PADDING}px`,- top: menuStyle?.top ?? `${VIEWPORT_PADDING}px`,- width: menuStyle?.width ?? `${MENU_WIDTH}px`,- maxHeight: 'min(360px, calc(100vh - 16px))',- visibility: menuStyle ? 'visible' : 'hidden',- }}- onClick={(e) => e.stopPropagation()}- role="menu"- >- <div className="text-[10px] text-gray-500 uppercase tracking-wide px-1 pt-1 pb-1.5 shrink-0">Collections</div>- {showSearch && (- <div className="relative shrink-0 mb-1.5">- <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none" />- <input- type="text"- value={query}- onChange={(e) => setQuery(e.target.value)}- placeholder="Search collections…"- className="w-full bg-port-bg border border-port-border rounded pl-7 pr-2 py-1 text-[11px] text-white focus:outline-none focus:border-port-accent"- autoFocus- />- </div>- )}- <div className="flex-1 min-h-0 overflow-y-auto">- {collections == null && (- <div className="text-[11px] text-gray-500 px-2 py-2">Loading…</div>- )}- {collections != null && collections.length === 0 && (- <div className="text-[11px] text-gray-500 px-2 py-2">No collections yet — create one below.</div>- )}- {list != null && collections?.length > 0 && list.length === 0 && (- <div className="text-[11px] text-gray-500 px-2 py-2">No matches for “{query}”</div>- )}- {list != null && list.map((c) => {- const inIt = c.items.some((it) => `${it.kind}:${it.ref}` === itemKey);- return (- <button- key={c.id}- type="button"- disabled={busyId === c.id}- onClick={() => handleToggleMembership(c)}- className="w-full flex items-center justify-between gap-2 px-2 py-1.5 text-left text-[12px] text-gray-200 hover:bg-port-border rounded disabled:opacity-50"- role="menuitemcheckbox"- aria-checked={inIt}- >- <span className="break-words min-w-0 flex-1">{c.name}</span>- {inIt && <Check className="w-3.5 h-3.5 text-port-success shrink-0" />}- </button>- );- })}- </div>- <form onSubmit={handleCreate} className="mt-1.5 pt-1.5 border-t border-port-border flex gap-1 shrink-0">- <input- type="text"- value={newName}- onChange={(e) => setNewName(e.target.value)}- placeholder="New collection name"- maxLength={80}- className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-white focus:outline-none focus:border-port-accent"- />- <button- type="submit"- disabled={creating || !newName.trim()}- className="px-2 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[11px] rounded disabled:opacity-40 flex items-center gap-1"- title="Create and add"- >- <Plus className="w-3 h-3" />- </button>- </form>- </div>,- document.body,- )}+ <CollectionPickerShell+ anchorRef={triggerRef}+ open={open}+ onClose={() => setOpen(false)}+ title="Collections"+ width={240}+ minWidth={180}+ newCollectionPlaceholder="New collection name"+ createTitle="Create and add"+ renderItem={renderItem}+ onCreated={handleCreated}+ /></>);}diff --git a/client/src/components/media/BulkTargetPicker.jsx b/client/src/components/media/BulkTargetPicker.jsxindex a9974896cd..7694c664b4 100644--- a/client/src/components/media/BulkTargetPicker.jsx+++ b/client/src/components/media/BulkTargetPicker.jsx@@ -1,185 +1,62 @@-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';-import { createPortal } from 'react-dom';-import { Plus, Search } from 'lucide-react';-import toast from '../ui/Toast';-import { listMediaCollections, createMediaCollection } from '../../services/api';+import { useCallback } from 'react';+import CollectionPickerShell from './CollectionPickerShell';// Single-target picker used by MediaCollectionDetail's bulk-action bar.// AddToCollectionMenu toggles membership for one item across many collections;// this picker is the inverse — one click picks a destination for many items.//-// Sibling-component prior art (AddToCollectionMenu) handles popover positioning-// the same way: portal into body, fixed coords, recompute on scroll/resize.--const MENU_WIDTH = 260;-const MENU_GAP = 6;-const VIEWPORT_PADDING = 8;-const SEARCH_THRESHOLD = 6;+// Both share the same popover/positioning/create-form shell — see+// CollectionPickerShell.jsx. The differences this caller layers on:+// - rows render with an item-count badge instead of a membership checkmark+// - clicking a row calls onPick(id, name) instead of toggling membership+// - creating a new collection picks it as the destination+//+// `collections` (optional): the parent's already-fetched list, so the shell+// skips its own listMediaCollections() round-trip. MediaCollectionDetail+// passes this to dedupe the load it already performed.export default function BulkTargetPicker({anchorRef,excludeId,busy,title = 'Pick a collection',+ collections,onPick,onClose,}) {- const [collections, setCollections] = useState(null);- const [query, setQuery] = useState('');- const [creating, setCreating] = useState(false);- const [newName, setNewName] = useState('');- const [style, setStyle] = useState(null);- const menuRef = useRef(null);- // Parent passes inline arrows for onClose; reading it through a ref keeps- // the listener effect from tearing down + re-attaching every parent render.- const onCloseRef = useRef(onClose);- useEffect(() => { onCloseRef.current = onClose; });-- const filtered = useMemo(() => {- if (!collections) return null;- const base = excludeId ? collections.filter((c) => c.id !== excludeId) : collections;- const q = query.trim().toLowerCase();- return q ? base.filter((c) => c.name.toLowerCase().includes(q)) : base;- }, [collections, query, excludeId]);-- useEffect(() => {- listMediaCollections().then(- (data) => setCollections(Array.isArray(data) ? data : []),- (err) => { toast.error(err?.message || 'Failed to load collections'); setCollections([]); },- );- }, []);-- const reposition = () => {- const trigger = anchorRef?.current;- const menu = menuRef.current;- if (!trigger || !menu) return;- const vw = window.innerWidth;- const vh = window.innerHeight;- const width = Math.min(MENU_WIDTH, Math.max(200, vw - VIEWPORT_PADDING * 2));- menu.style.width = `${width}px`;- const tr = trigger.getBoundingClientRect();- const mr = menu.getBoundingClientRect();- const maxLeft = vw - width - VIEWPORT_PADDING;- const left = Math.min(Math.max(tr.right - width, VIEWPORT_PADDING), Math.max(VIEWPORT_PADDING, maxLeft));- const above = tr.top - mr.height - MENU_GAP;- const below = tr.bottom + MENU_GAP;- const top = above < VIEWPORT_PADDING ? below : above;- const maxTop = Math.max(VIEWPORT_PADDING, vh - mr.height - VIEWPORT_PADDING);- const clampedTop = Math.min(Math.max(top, VIEWPORT_PADDING), maxTop);- setStyle({ left: `${left}px`, top: `${clampedTop}px`, width: `${width}px` });- };-- useLayoutEffect(reposition, [filtered, excludeId]);- useEffect(() => {- const close = () => onCloseRef.current?.();- const onKey = (e) => { if (e.key === 'Escape') close(); };- const onAway = (e) => {- const onTrigger = anchorRef?.current?.contains(e.target);- const onMenu = menuRef.current?.contains(e.target);- if (!onTrigger && !onMenu) close();- };- let raf = null;- const onScroll = () => { if (raf !== null) return; raf = requestAnimationFrame(() => { raf = null; reposition(); }); };- document.addEventListener('keydown', onKey);- document.addEventListener('mousedown', onAway);- window.addEventListener('resize', onScroll);- window.addEventListener('scroll', onScroll, true);- return () => {- if (raf !== null) cancelAnimationFrame(raf);- document.removeEventListener('keydown', onKey);- document.removeEventListener('mousedown', onAway);- window.removeEventListener('resize', onScroll);- window.removeEventListener('scroll', onScroll, true);- };- }, []);+ const renderItem = useCallback((c) => (+ <button+ key={c.id}+ type="button"+ disabled={busy}+ onClick={() => onPick(c.id, c.name)}+ className="w-full flex items-center gap-2 px-2 py-1.5 text-left text-[12px] text-gray-200 hover:bg-port-border rounded disabled:opacity-50"+ role="menuitem"+ >+ <span className="break-words min-w-0 flex-1">{c.name}</span>+ <span className="text-[10px] text-gray-500 shrink-0">{c.items?.length ?? 0}</span>+ </button>+ ), [busy, onPick]);- const handleCreate = async (e) => {- e.preventDefault();- const name = newName.trim();- if (!name) return;- setCreating(true);- const created = await createMediaCollection({ name }).catch((err) => {- toast.error(err?.message || 'Create failed');- return null;- });- setCreating(false);- if (!created) return;- setNewName('');+ const handleCreated = useCallback((created) => {onPick(created.id, created.name);- };-- const showSearch = (collections?.length || 0) >= SEARCH_THRESHOLD;- const list = filtered ?? collections;-- return createPortal(- <div- ref={menuRef}- role="menu"- className="fixed bg-port-card border border-port-border rounded-lg shadow-xl z-[100] p-1.5 flex flex-col"- style={{- left: style?.left ?? `${VIEWPORT_PADDING}px`,- top: style?.top ?? `${VIEWPORT_PADDING}px`,- width: style?.width ?? `${MENU_WIDTH}px`,- maxHeight: 'min(360px, calc(100vh - 16px))',- visibility: style ? 'visible' : 'hidden',- }}- onClick={(e) => e.stopPropagation()}- >- <div className="text-[10px] text-gray-500 uppercase tracking-wide px-1 pt-1 pb-1.5 shrink-0">{title}</div>- {showSearch && (- <div className="relative shrink-0 mb-1.5">- <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none" />- <input- type="text"- value={query}- onChange={(e) => setQuery(e.target.value)}- placeholder="Search collections…"- className="w-full bg-port-bg border border-port-border rounded pl-7 pr-2 py-1 text-[11px] text-white focus:outline-none focus:border-port-accent"- autoFocus- />- </div>- )}- <div className="flex-1 min-h-0 overflow-y-auto">- {collections == null && <div className="text-[11px] text-gray-500 px-2 py-2">Loading…</div>}- {collections != null && list?.length === 0 && (- <div className="text-[11px] text-gray-500 px-2 py-2">- {query ? `No matches for "${query}"` : 'No other collections — create one below.'}- </div>- )}- {list?.map((c) => (- <button- key={c.id}- type="button"- disabled={busy}- onClick={() => onPick(c.id, c.name)}- className="w-full flex items-center gap-2 px-2 py-1.5 text-left text-[12px] text-gray-200 hover:bg-port-border rounded disabled:opacity-50"- role="menuitem"- >- <span className="break-words min-w-0 flex-1">{c.name}</span>- <span className="text-[10px] text-gray-500 shrink-0">{c.items?.length ?? 0}</span>- </button>- ))}- </div>- <form onSubmit={handleCreate} className="mt-1.5 pt-1.5 border-t border-port-border flex gap-1 shrink-0">- <input- type="text"- value={newName}- onChange={(e) => setNewName(e.target.value)}- placeholder="New collection"- maxLength={80}- disabled={busy}- className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-white focus:outline-none focus:border-port-accent disabled:opacity-50"- />- <button- type="submit"- disabled={creating || busy || !newName.trim()}- className="px-2 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[11px] rounded disabled:opacity-40 flex items-center gap-1"- title="Create and pick"- >- <Plus className="w-3 h-3" />- </button>- </form>- </div>,- document.body,+ }, [onPick]);++ return (+ <CollectionPickerShell+ anchorRef={anchorRef}+ open+ onClose={onClose}+ title={title}+ excludeId={excludeId}+ busy={busy}+ emptyMessage="No collections yet — create one below."+ noMatchMessage={(q) => (q ? `No matches for "${q}"` : 'No other collections — create one below.')}+ newCollectionPlaceholder="New collection"+ createTitle="Create and pick"+ collections={collections}+ renderItem={renderItem}+ onCreated={handleCreated}+ />);}diff --git a/client/src/components/media/CollectionPickerShell.jsx b/client/src/components/media/CollectionPickerShell.jsxnew file mode 100644index 0000000000..d131cb561d--- /dev/null+++ b/client/src/components/media/CollectionPickerShell.jsx@@ -0,0 +1,253 @@+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { Plus, Search } from 'lucide-react';+import toast from '../ui/Toast';+import { listMediaCollections, createMediaCollection } from '../../services/api';++// Shared popover shell for the two collection pickers:+//+// - AddToCollectionMenu (one item → many collections, toggles membership)+// - BulkTargetPicker (many items → one destination, pick + dispatch)+//+// Both portal a fixed-position popover into <body>, compute placement relative+// to a trigger element, ship a search input above a threshold, and end with a+// "create new" inline form. This shell owns all of that plumbing; the caller+// provides `renderItem` for the per-row UI and `onCreated`/`onPickCreated` for+// what to do after the inline create succeeds.+//+// Collections data flow (per PLAN.md item 2):+// - If `collections` is provided by the parent, we never call+// `listMediaCollections()` ourselves — this lets MediaCollectionDetail+// reuse its already-fetched list instead of paying a per-mount round-trip.+// - If `collections` is `null`/omitted, the shell auto-loads on mount (old+// AddToCollectionMenu behavior). Use `onCollectionsLoaded` if the parent+// wants to learn the fetched list (e.g. for membership rendering).+//+// `excludeId` is a single-item allow-list filter so BulkTargetPicker can hide+// the current collection from its move/copy target list.++const DEFAULT_MENU_WIDTH = 260;+const MENU_GAP = 6;+const VIEWPORT_PADDING = 8;+const SEARCH_THRESHOLD = 6;++export default function CollectionPickerShell({+ anchorRef,+ open = true,+ title,+ emptyMessage = 'No collections yet — create one below.',+ noMatchMessage = (query) => `No matches for "${query}"`,+ excludeId,+ busy = false,+ width = DEFAULT_MENU_WIDTH,+ minWidth = 200,+ newCollectionPlaceholder = 'New collection',+ createTitle = 'Create and pick',+ // The caller renders each collection row — keeps the per-row UI flexible+ // (membership checkmarks vs item counts vs anything else) without dragging+ // every prop combination through the shell.+ renderItem,+ collections: collectionsProp,+ onCollectionsLoaded,+ onCollectionsChange,+ onCreated,+ onClose,+}) {+ const [collectionsState, setCollectionsState] = useState(collectionsProp ?? null);+ const [query, setQuery] = useState('');+ const [creating, setCreating] = useState(false);+ const [newName, setNewName] = useState('');+ const [style, setStyle] = useState(null);+ const menuRef = useRef(null);++ // Parents may pass inline arrow handlers — read through a ref so the+ // event-listener effect doesn't tear down on every parent render.+ const onCloseRef = useRef(onClose);+ useEffect(() => { onCloseRef.current = onClose; });++ // When the parent owns `collections`, mirror it into local state on each+ // change so the same render path works for both modes.+ useEffect(() => {+ if (collectionsProp !== undefined) setCollectionsState(collectionsProp);+ }, [collectionsProp]);++ // Auto-load only when uncontrolled (no `collections` prop). Mirrors the old+ // AddToCollectionMenu behavior of fetching when the popover opens.+ useEffect(() => {+ if (collectionsProp !== undefined) return undefined;+ if (!open) return undefined;+ let cancelled = false;+ listMediaCollections().then(+ (data) => {+ if (cancelled) return;+ const list = Array.isArray(data) ? data : [];+ setCollectionsState(list);+ onCollectionsLoaded?.(list);+ },+ (err) => {+ if (cancelled) return;+ toast.error(err?.message || 'Failed to load collections');+ setCollectionsState([]);+ },+ );+ return () => { cancelled = true; };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open, collectionsProp]);++ const filtered = useMemo(() => {+ if (!collectionsState) return null;+ const base = excludeId ? collectionsState.filter((c) => c.id !== excludeId) : collectionsState;+ const q = query.trim().toLowerCase();+ return q ? base.filter((c) => c.name.toLowerCase().includes(q)) : base;+ }, [collectionsState, query, excludeId]);++ const reposition = useCallback(() => {+ const trigger = anchorRef?.current;+ const menu = menuRef.current;+ if (!trigger || !menu) return;+ const vw = window.innerWidth;+ const vh = window.innerHeight;+ const w = Math.min(width, Math.max(minWidth, vw - VIEWPORT_PADDING * 2));+ menu.style.width = `${w}px`;+ const tr = trigger.getBoundingClientRect();+ const mr = menu.getBoundingClientRect();+ const maxLeft = vw - w - VIEWPORT_PADDING;+ const left = Math.min(Math.max(tr.right - w, VIEWPORT_PADDING), Math.max(VIEWPORT_PADDING, maxLeft));+ const above = tr.top - mr.height - MENU_GAP;+ const below = tr.bottom + MENU_GAP;+ const top = above < VIEWPORT_PADDING ? below : above;+ const maxTop = Math.max(VIEWPORT_PADDING, vh - mr.height - VIEWPORT_PADDING);+ const clampedTop = Math.min(Math.max(top, VIEWPORT_PADDING), maxTop);+ setStyle((prev) => {+ const next = { left: `${left}px`, top: `${clampedTop}px`, width: `${w}px` };+ if (prev && prev.left === next.left && prev.top === next.top && prev.width === next.width) return prev;+ return next;+ });+ }, [anchorRef, width, minWidth]);++ useLayoutEffect(() => {+ if (!open) { setStyle(null); return; }+ reposition();+ }, [open, reposition, filtered, query, collectionsState]);++ useEffect(() => {+ if (!open) return undefined;+ const close = () => onCloseRef.current?.();+ const onKey = (e) => { if (e.key === 'Escape') close(); };+ const onAway = (e) => {+ const onTrigger = anchorRef?.current?.contains(e.target);+ const onMenu = menuRef.current?.contains(e.target);+ if (!onTrigger && !onMenu) close();+ };+ let raf = null;+ const onScroll = () => { if (raf !== null) return; raf = requestAnimationFrame(() => { raf = null; reposition(); }); };+ document.addEventListener('keydown', onKey);+ document.addEventListener('mousedown', onAway);+ window.addEventListener('resize', onScroll);+ window.addEventListener('scroll', onScroll, true);+ return () => {+ if (raf !== null) cancelAnimationFrame(raf);+ document.removeEventListener('keydown', onKey);+ document.removeEventListener('mousedown', onAway);+ window.removeEventListener('resize', onScroll);+ window.removeEventListener('scroll', onScroll, true);+ };+ }, [open, anchorRef, reposition]);++ const updateCollections = useCallback((updater) => {+ setCollectionsState((prev) => {+ const next = typeof updater === 'function' ? updater(prev) : updater;+ onCollectionsChange?.(next);+ return next;+ });+ }, [onCollectionsChange]);++ const handleCreate = async (e) => {+ e.preventDefault();+ const name = newName.trim();+ if (!name) return;+ setCreating(true);+ const created = await createMediaCollection({ name }).catch((err) => {+ toast.error(err?.message || 'Create failed');+ return null;+ });+ setCreating(false);+ if (!created) return;+ setNewName('');+ // Parent decides what happens next — AddToCollectionMenu wants to also add+ // the item to the new collection, BulkTargetPicker just picks it as the+ // destination. The shell tells the parent which collection was created+ // and how the parent should merge it back into the local list.+ onCreated?.(created, { addToCollectionsState: (mergeFn) => updateCollections(mergeFn) });+ };++ if (!open) return null;++ const showSearch = (collectionsState?.length || 0) >= SEARCH_THRESHOLD;+ const list = filtered ?? collectionsState;++ return createPortal(+ <div+ ref={menuRef}+ role="menu"+ className="fixed bg-port-card border border-port-border rounded-lg shadow-xl z-[100] p-1.5 flex flex-col"+ style={{+ left: style?.left ?? `${VIEWPORT_PADDING}px`,+ top: style?.top ?? `${VIEWPORT_PADDING}px`,+ width: style?.width ?? `${width}px`,+ maxHeight: 'min(360px, calc(100vh - 16px))',+ visibility: style ? 'visible' : 'hidden',+ }}+ onClick={(e) => e.stopPropagation()}+ >+ {title && (+ <div className="text-[10px] text-gray-500 uppercase tracking-wide px-1 pt-1 pb-1.5 shrink-0">{title}</div>+ )}+ {showSearch && (+ <div className="relative shrink-0 mb-1.5">+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none" />+ <input+ type="text"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search collections…"+ className="w-full bg-port-bg border border-port-border rounded pl-7 pr-2 py-1 text-[11px] text-white focus:outline-none focus:border-port-accent"+ autoFocus+ />+ </div>+ )}+ <div className="flex-1 min-h-0 overflow-y-auto">+ {collectionsState == null && (+ <div className="text-[11px] text-gray-500 px-2 py-2">Loading…</div>+ )}+ {collectionsState != null && collectionsState.length === 0 && (+ <div className="text-[11px] text-gray-500 px-2 py-2">{emptyMessage}</div>+ )}+ {list != null && collectionsState?.length > 0 && list.length === 0 && (+ <div className="text-[11px] text-gray-500 px-2 py-2">{noMatchMessage(query)}</div>+ )}+ {list != null && list.map((c) => renderItem(c, { updateCollections }))}+ </div>+ <form onSubmit={handleCreate} className="mt-1.5 pt-1.5 border-t border-port-border flex gap-1 shrink-0">+ <input+ type="text"+ value={newName}+ onChange={(e) => setNewName(e.target.value)}+ placeholder={newCollectionPlaceholder}+ maxLength={80}+ disabled={busy}+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ />+ <button+ type="submit"+ disabled={creating || busy || !newName.trim()}+ className="px-2 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[11px] rounded disabled:opacity-40 flex items-center gap-1"+ title={createTitle}+ >+ <Plus className="w-3 h-3" />+ </button>+ </form>+ </div>,+ document.body,+ );+}diff --git a/client/src/components/pipeline/stages/AudioStage.jsx b/client/src/components/pipeline/stages/AudioStage.jsxindex 0f8ec89897..6b56ca0c85 100644--- a/client/src/components/pipeline/stages/AudioStage.jsx+++ b/client/src/components/pipeline/stages/AudioStage.jsx@@ -83,7 +83,9 @@ export default function AudioStage({ issue, onStageUpdate }) {const handleMusicUpload = async (file) => {if (!file) return;setMusicUploading(true);- const result = await uploadPipelineMusicTrack(issue.id, file).catch((err) => {+ // Owns its own error UI (toast.error below) so suppress the helper's toast+ // — per CLAUDE.md "custom catch ⇒ silent: true" convention.+ const result = await uploadPipelineMusicTrack(issue.id, file, {}, { silent: true }).catch((err) => {toast.error(err.message || 'Upload failed');return null;});diff --git a/client/src/hooks/useLocalStorageBool.js b/client/src/hooks/useLocalStorageBool.jsnew file mode 100644index 0000000000..10c5560286--- /dev/null+++ b/client/src/hooks/useLocalStorageBool.js@@ -0,0 +1,93 @@+import { useCallback, useState } from 'react';++// Boolean-valued `useState` mirror that round-trips through `localStorage`.+//+// History: six pages independently re-implemented this with subtly different+// encodings — `'1'/'0'`, `'true'/'false'`, sometimes wrapped in `try/catch` for+// sandboxed-storage failures, sometimes not. We accept both legacy encodings+// on read so swapping any one call site to the hook is non-breaking; writes+// are pinned to whichever format the page already uses (`format` option).+//+// `format`: `'1'` writes `'1'`/`'0'`; `'true'` writes `'true'`/`'false'`.+// Reads always treat either `'1'` or `'true'` as truthy so existing values+// keep working when a page switches its `format` later.+export function useLocalStorageBool(key, defaultValue = false, { format = '1' } = {}) {+ const [value, setValue] = useState(() => readBool(key, defaultValue));++ const write = useCallback((next) => {+ setValue((prev) => {+ const resolved = typeof next === 'function' ? next(prev) : next;+ const bool = !!resolved;+ writeBool(key, bool, format);+ return bool;+ });+ }, [key, format]);++ return [value, write];+}++// JSON-blob variant: hydrates from localStorage on first render, persists on+// every change via the setter. `defaultValue` is returned both when the key is+// missing and when JSON.parse fails (corrupted/old-shape value).+//+// Pass `{ parse: (raw) => merged }` to migrate older shapes — `parse` is only+// invoked when JSON.parse succeeded, so it sees the raw stored object. Use it+// to spread fresh defaults under saved values (additive shape changes) so a+// new field appears for users with pre-existing storage.+export function useLocalStoragePersisted(key, defaultValue, { parse } = {}) {+ const [value, setValue] = useState(() => {+ const raw = readJsonRaw(key);+ if (raw === undefined) return defaultValue;+ return parse ? parse(raw) : raw;+ });++ const write = useCallback((next) => {+ setValue((prev) => {+ const resolved = typeof next === 'function' ? next(prev) : next;+ writeJson(key, resolved);+ return resolved;+ });+ }, [key]);++ return [value, write];+}++function readBool(key, defaultValue) {+ if (typeof window === 'undefined') return defaultValue;+ try {+ const raw = window.localStorage.getItem(key);+ if (raw === null) return defaultValue;+ return raw === '1' || raw === 'true';+ } catch {+ return defaultValue;+ }+}++function writeBool(key, bool, format) {+ if (typeof window === 'undefined') return;+ try {+ const v = format === 'true' ? String(bool) : (bool ? '1' : '0');+ window.localStorage.setItem(key, v);+ } catch { /* sandboxed storage */ }+}++// Returns `undefined` to distinguish "key missing / parse failed" (caller+// applies the default) from a stored `null`. useLocalStoragePersisted uses+// this so it can run an optional `parse` migration only on real stored data.+function readJsonRaw(key) {+ if (typeof window === 'undefined') return undefined;+ try {+ const raw = window.localStorage.getItem(key);+ if (raw === null) return undefined;+ return JSON.parse(raw);+ } catch {+ return undefined;+ }+}++function writeJson(key, value) {+ if (typeof window === 'undefined') return;+ try {+ window.localStorage.setItem(key, JSON.stringify(value));+ } catch { /* sandboxed storage */ }+}diff --git a/client/src/hooks/useMediaAnnotations.js b/client/src/hooks/useMediaAnnotations.jsindex 594565effc..b8db53ef63 100644--- a/client/src/hooks/useMediaAnnotations.js+++ b/client/src/hooks/useMediaAnnotations.js@@ -118,5 +118,15 @@ export function useMediaAnnotations() {updateAnnotation(item.key, { starred: !priorStarred });}, [updateAnnotation]);- return { annotations, toggleStar, updateAnnotation };+ // Shortcut for the `{ starred, hasNote, onToggleStar }` triple that every+ // <MediaCard> consumer reads from this hook. Callers spread it onto the card+ // and can still override individual fields (e.g. clear onToggleStar in+ // select/stitch modes by passing `onToggleStar={undefined}` after the spread).+ const getCardProps = useCallback((key) => ({+ starred: !!annotations[key]?.starred,+ hasNote: !!annotations[key]?.anyNote,+ onToggleStar: toggleStar,+ }), [annotations, toggleStar]);++ return { annotations, toggleStar, updateAnnotation, getCardProps };}diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 9fabe500c2..69c029cbba 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -1,6 +1,7 @@import { useState, useEffect, useCallback, useMemo, useRef } from 'react';import { useParams, useNavigate } from 'react-router-dom';import { useSocket } from '../hooks/useSocket';+import { useLocalStorageBool } from '../hooks/useLocalStorageBool';import * as api from '../services/api';import { Play, Square, Clock, CheckCircle, AlertCircle, Cpu, ChevronDown, ChevronUp, ChevronLeft, ChevronRight, Brain, PanelLeftClose, PanelLeftOpen } from 'lucide-react';import toast from '../components/ui/Toast';@@ -62,8 +63,10 @@ export default function ChiefOfStaff() {const [liveOutputs, setLiveOutputs] = useState({});const [eventLogs, setEventLogs] = useState([]);const [agentPanelCollapsed, setAgentPanelCollapsed] = useState(false);- const [desktopPanelCollapsed, setDesktopPanelCollapsed] = useState(() =>- localStorage.getItem('cos-panel-collapsed') === 'true'+ const [desktopPanelCollapsed, setDesktopPanelCollapsed] = useLocalStorageBool(+ 'cos-panel-collapsed',+ false,+ { format: 'true' },);const [activeAgentMeta, setActiveAgentMeta] = useState(null);const [learningSummary, setLearningSummary] = useState(null);@@ -85,12 +88,8 @@ export default function ChiefOfStaff() {};const toggleDesktopPanel = useCallback(() => {- setDesktopPanelCollapsed(prev => {- const next = !prev;- localStorage.setItem('cos-panel-collapsed', String(next));- return next;- });- }, []);+ setDesktopPanelCollapsed((prev) => !prev);+ }, [setDesktopPanelCollapsed]);// Countdown to next evaluationconst evalCountdown = useNextEvalCountdown(diff --git a/client/src/pages/CreativeDirector.jsx b/client/src/pages/CreativeDirector.jsxindex 1acc2dc419..5e83b7b53f 100644--- a/client/src/pages/CreativeDirector.jsx+++ b/client/src/pages/CreativeDirector.jsx@@ -11,6 +11,7 @@ import {pauseCreativeDirectorProject,} from '../services/apiCreativeDirector.js';import { listVideoModels } from '../services/apiImageVideo.js';+import ModelSelect from '../components/ModelSelect';const ASPECT_RATIOS = ['16:9', '9:16', '1:1'];const QUALITIES = ['draft', 'standard', 'high'];@@ -184,18 +185,13 @@ export default function CreativeDirector() {</label><label className="block text-sm"><span className="text-port-text-muted">Model</span>- <select+ <ModelSelect+ models={models}value={form.modelId}onChange={(e) => setForm({ ...form, modelId: e.target.value })}+ getLabel={(m) => m.name || m.id}className="w-full mt-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm"- >- {models.filter((m) => !m.deprecated).map((m) => <option key={m.id} value={m.id}>{m.name || m.id}</option>)}- {models.some((m) => m.deprecated) && (- <optgroup label="Legacy">- {models.filter((m) => m.deprecated).map((m) => <option key={m.id} value={m.id}>{m.name || m.id}</option>)}- </optgroup>- )}- </select>+ /></label><label className="block text-sm"><span className="text-port-text-muted">Aspect ratio</span>diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 110efb726f..5b85f220b8 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -103,7 +103,7 @@ export default function ImageGen() {const [preview, setPreview] = useState(null);const [showHidden, setShowHidden] = useState(false);const [favoritesOnly, setFavoritesOnly] = useState(false);- const { annotations, toggleStar, updateAnnotation } = useMediaAnnotations();+ const { annotations, updateAnnotation, getCardProps } = useMediaAnnotations();// FLUX.2 readiness — drives the gating banner. Lazy-fetched on the first// selection of a flux2 model so we don't make an extra request when the// user is only using mflux/external/codex.@@ -1163,9 +1163,7 @@ export default function ImageGen() {onSendToVideo={() => sendToVideo(img)}onDelete={() => handleDelete(img.filename)}onToggleHidden={() => handleToggleHidden(item)}- starred={!!annotations[item.key]?.starred}- hasNote={!!annotations[item.key]?.anyNote}- onToggleStar={toggleStar}+ {...getCardProps(item.key)}/>);})}@@ -1197,9 +1195,7 @@ export default function ImageGen() {onSendToVideo={() => sendToVideo(img)}onDelete={() => handleDelete(img.filename)}onToggleHidden={() => handleToggleHidden(item)}- starred={!!annotations[item.key]?.starred}- hasNote={!!annotations[item.key]?.anyNote}- onToggleStar={toggleStar}+ {...getCardProps(item.key)}/>);})}diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex f4fc25877a..e194ce4801 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -18,6 +18,7 @@ import {import PeerAppsList from '../components/instances/PeerAppsList';import PeerAgentsSection from '../components/instances/PeerAgentsSection';import { timeAgo } from '../utils/formatters';+import { useLocalStorageBool } from '../hooks/useLocalStorageBool';const STATUS_COLORS = {online: 'text-port-success',@@ -81,17 +82,11 @@ function HealthSummary({ health, version }) {}function TailnetHelpBanner({ tailnetInfo }) {- const [collapsed, setCollapsed] = useState(() => {- return localStorage.getItem('portos-tailnet-help-collapsed') === '1';- });+ const [collapsed, setCollapsed] = useLocalStorageBool('portos-tailnet-help-collapsed', false);const [provisioning, setProvisioning] = useState(false);const [provisionResult, setProvisionResult] = useState(null);- const toggle = () => {- const next = !collapsed;- setCollapsed(next);- localStorage.setItem('portos-tailnet-help-collapsed', next ? '1' : '0');- };+ const toggle = () => setCollapsed((prev) => !prev);const provision = async (e) => {e.stopPropagation();diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsxindex 7112804897..98417f2c0a 100644--- a/client/src/pages/MediaCollectionDetail.jsx+++ b/client/src/pages/MediaCollectionDetail.jsx@@ -44,6 +44,10 @@ export default function MediaCollectionDetail() {const isUnsorted = id === UNSORTED_ID;const navigate = useNavigate();const [collection, setCollection] = useState(null);+ // Full collections list — fetched once for the bulk move/copy picker so it+ // doesn't pay a per-mount listMediaCollections() round-trip when opened.+ // Already loaded for the unsorted view as part of buildUnsortedCollection().+ const [allCollections, setAllCollections] = useState(null);const [imagesByName, setImagesByName] = useState(new Map());const [videosById, setVideosById] = useState(new Map());const [loading, setLoading] = useState(true);@@ -57,7 +61,7 @@ export default function MediaCollectionDetail() {const [pickerMode, setPickerMode] = useState(null);const moveBtnRef = useRef(null);const copyBtnRef = useRef(null);- const { annotations, toggleStar, updateAnnotation } = useMediaAnnotations();+ const { annotations, toggleStar, updateAnnotation, getCardProps } = useMediaAnnotations();const refresh = useCallback(async () => {setLoading(true);@@ -67,21 +71,24 @@ export default function MediaCollectionDetail() {listImageGallery().catch(() => []),listVideoHistory().catch(() => []),]);+ setAllCollections(Array.isArray(cols) ? cols : []);setCollection(buildUnsortedCollection(cols, images, videos));setImagesByName(new Map((images || []).map((i) => [i.filename, i])));setVideosById(new Map((videos || []).map((v) => [v.id, v])));setLoading(false);return;}- const [c, images, videos] = await Promise.all([+ const [c, cols, images, videos] = await Promise.all([getMediaCollection(id).catch((err) => {toast.error(err.message || 'Collection not found');return null;}),+ listMediaCollections().catch(() => []),listImageGallery().catch(() => []),listVideoHistory().catch(() => []),]);setCollection(c);+ setAllCollections(Array.isArray(cols) ? cols : []);setNameDraft(c?.name || '');setImagesByName(new Map((images || []).map((i) => [i.filename, i])));setVideosById(new Map((videos || []).map((v) => [v.id, v])));@@ -430,6 +437,7 @@ export default function MediaCollectionDetail() {excludeId={collection.id}busy={bulkBusy}title={`${pickerMode === 'move' ? 'Move' : 'Copy'} ${selected.size} to…`}+ collections={allCollections}onPick={bulkMoveOrCopy}onClose={() => setPickerMode(null)}/>@@ -461,8 +469,7 @@ export default function MediaCollectionDetail() {onDelete={!selectMode ? handleDelete : undefined}hideActions={selectMode}selected={isSelected}- starred={!!annotations[key]?.starred}- hasNote={!!annotations[key]?.anyNote}+ {...getCardProps(key)}onToggleStar={!selectMode ? toggleStar : undefined}/>{!selectMode && !isUnsorted && (diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsxindex daaec4e92c..881bea397b 100644--- a/client/src/pages/MediaHistory.jsx+++ b/client/src/pages/MediaHistory.jsx@@ -37,7 +37,7 @@ export default function MediaHistory() {const [stitching, setStitching] = useState(false);const [preview, setPreview] = useState(null);const [favoritesOnly, setFavoritesOnly] = useState(false);- const { annotations, toggleStar, updateAnnotation } = useMediaAnnotations();+ const { annotations, toggleStar, updateAnnotation, getCardProps } = useMediaAnnotations();const refresh = useCallback(async ({ silent = false } = {}) => {if (!silent) setLoading(true);@@ -302,8 +302,7 @@ export default function MediaHistory() {selected={idx !== -1}disabled={stitchMode && it.kind !== 'video'}hideActions={stitchMode}- starred={!!annotations[it.key]?.starred}- hasNote={!!annotations[it.key]?.anyNote}+ {...getCardProps(it.key)}onToggleStar={!stitchMode ? toggleStar : undefined}/>);diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex fe0b220fcf..7e50bfbb5f 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -25,6 +25,7 @@ import {listUniverses,} from '../services/api';import { recommendStructure, describeStructure } from '../lib/seasonStructure';+import { useLocalStorageBool } from '../hooks/useLocalStorageBool';const PIPELINE_SIDEBAR_KEY = 'portos-pipeline-series-sidebar-collapsed';@@ -36,9 +37,11 @@ export default function PipelineSeries() {const [universes, setWorlds] = useState([]);const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);- const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {- return localStorage.getItem(PIPELINE_SIDEBAR_KEY) === 'true';- });+ const [sidebarCollapsed, setSidebarCollapsed] = useLocalStorageBool(+ PIPELINE_SIDEBAR_KEY,+ false,+ { format: 'true' },+ );useEffect(() => {let canceled = false;@@ -62,13 +65,7 @@ export default function PipelineSeries() {return () => { canceled = true; };}, [seriesId, navigate]);- const toggleSidebar = () => {- setSidebarCollapsed((prev) => {- const next = !prev;- localStorage.setItem(PIPELINE_SIDEBAR_KEY, String(next));- return next;- });- };+ const toggleSidebar = () => setSidebarCollapsed((prev) => !prev);// Track the last server-persisted snapshot so `flushPending` knows whether// the local draft has diverged. Ref instead of state — we don't wantdiff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex 5d9cbb8d4a..ca2d11c702 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -26,6 +26,7 @@ import {listImageModels, getSettings,} from '../services/api';import useClickOutside from '../hooks/useClickOutside';+import { useLocalStorageBool, useLocalStoragePersisted } from '../hooks/useLocalStorageBool';import InfluenceChipsInput from '../components/universeBuilder/InfluenceChipsInput';import BackendChipStrip from '../components/media/BackendChipStrip';import ImageGenControls from '../components/imageGen/ImageGenControls';@@ -54,11 +55,15 @@ const normalizeCategoryKey = (raw) => (raw || '')// Merge `fresh` items after `existing`, case-insensitively deduping by label.// Used by both Expand (locked + LLM result) and per-category Generate (current// + LLM additions); pinned/existing entries keep their slot at the top.+// Rows with a missing/non-string label (older universes pre-rename, partial+// LLM payloads) are dropped from both sides — keeping them in `merged` while+// excluding from the dedup Set would let a fresh row with the same missing+// label silently duplicate.const mergeVariations = (existing, fresh) => {- const seen = new Set((existing || []).map((v) => v.label.toLowerCase()));- const merged = [...(existing || [])];- for (const v of fresh || []) {- const key = v.label?.toLowerCase();+ const merged = [];+ const seen = new Set();+ for (const v of [...(existing || []), ...(fresh || [])]) {+ const key = v?.label?.toLowerCase();if (!key || seen.has(key)) continue;seen.add(key);merged.push(v);@@ -237,16 +242,15 @@ export default function UniverseBuilder() {// Per-page render knobs. Persisted to localStorage so the user's// preferred batch size sticks across visits.- const [renderOpts, setRenderOpts] = useState(() => {- const saved = localStorage.getItem('universeBuilder.renderOpts');- if (saved) {- try { return { ...DEFAULT_RENDER_OPTS, ...JSON.parse(saved) }; } catch { /* fall through */ }- }- return DEFAULT_RENDER_OPTS;- });- useEffect(() => {- localStorage.setItem('universeBuilder.renderOpts', JSON.stringify(renderOpts));- }, [renderOpts]);+ // useLocalStoragePersisted handles JSON round-trip + parse-failure fallback.+ // The `parse` hook spreads DEFAULT_RENDER_OPTS under the saved object so a+ // shape change (new field added to DEFAULT_RENDER_OPTS) populates that+ // field without nuking the user's saved batch-size / cadence preferences.+ const [renderOpts, setRenderOpts] = useLocalStoragePersisted(+ 'universeBuilder.renderOpts',+ DEFAULT_RENDER_OPTS,+ { parse: (raw) => ({ ...DEFAULT_RENDER_OPTS, ...(raw || {}) }) },+ );const [runs, setRuns] = useState([]);@@ -271,16 +275,11 @@ export default function UniverseBuilder() {// Universes list collapsed state — desktop only (mobile stacks the sidebar// above the editor and there's no horizontal-space tradeoff to make).// Persists across visits so users who prefer a maximized editor stay there.- const [worldsCollapsed, setWorldsCollapsed] = useState(() => {- try { return localStorage.getItem('universeBuilder.worldsCollapsed') === '1'; } catch { return false; }- });- const toggleWorldsCollapsed = () => {- setWorldsCollapsed((prev) => {- const next = !prev;- try { localStorage.setItem('universeBuilder.worldsCollapsed', next ? '1' : '0'); } catch { /* sandboxed */ }- return next;- });- };+ const [worldsCollapsed, setWorldsCollapsed] = useLocalStorageBool(+ 'universeBuilder.worldsCollapsed',+ false,+ );+ const toggleWorldsCollapsed = () => setWorldsCollapsed((prev) => !prev);const refresh = async () => {setLoading(true);diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 9f9ea6ed6c..aabd52bcab 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -42,6 +42,7 @@ import BrailleSpinner from '../components/BrailleSpinner';import BatchQueuePanel from '../components/media/BatchQueuePanel';import MediaJobsQueue from '../components/media/MediaJobsQueue';import FavoritesFilterChip from '../components/media/FavoritesFilterChip';+import ModelSelect from '../components/ModelSelect';import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';import { useMediaAnnotations } from '../hooks/useMediaAnnotations';import {@@ -216,7 +217,7 @@ export default function VideoGen() {hiddenHistory: history.filter((v) => v.hidden),}), [history]);const [favoritesOnly, setFavoritesOnly] = useState(false);- const { annotations, toggleStar, updateAnnotation } = useMediaAnnotations();+ const { annotations, updateAnnotation, getCardProps } = useMediaAnnotations();// Gallery sections respect the favorites filter; the extend-mode dropdown// (which reads visibleHistory directly) intentionally does not, since// hiding non-favorites from the "pick a previous video" picker would@@ -1029,18 +1030,11 @@ export default function VideoGen() {{models.length > 0 && (<div className="col-span-2 sm:col-span-3"><label className="block text-xs font-medium text-gray-400 mb-1">Model</label>- <select+ <ModelSelect+ models={models}value={modelId}onChange={(e) => { setModelId(e.target.value); setSteps(''); setGuidanceScale(''); }}- className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"- >- {models.filter((m) => !m.deprecated).map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}- {models.some((m) => m.deprecated) && (- <optgroup label="Legacy">- {models.filter((m) => m.deprecated).map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}- </optgroup>- )}- </select>+ /></div>)}@@ -1328,9 +1322,7 @@ export default function VideoGen() {onUpscale={() => handleUpscaleHistory(v)}onDelete={() => handleDeleteHistory(v)}onToggleHidden={() => handleToggleHistoryHidden(v)}- starred={!!annotations[item.key]?.starred}- hasNote={!!annotations[item.key]?.anyNote}- onToggleStar={toggleStar}+ {...getCardProps(item.key)}/>);})}@@ -1361,9 +1353,7 @@ export default function VideoGen() {onContinue={() => handleContinueHistory(v)}onDelete={() => handleDeleteHistory(v)}onToggleHidden={() => handleToggleHistoryHidden(v)}- starred={!!annotations[item.key]?.starred}- hasNote={!!annotations[item.key]?.anyNote}- onToggleStar={toggleStar}+ {...getCardProps(item.key)}/>);})}diff --git a/client/src/pages/WritersRoom.jsx b/client/src/pages/WritersRoom.jsxindex a5ccb38825..eb80b4be49 100644--- a/client/src/pages/WritersRoom.jsx+++ b/client/src/pages/WritersRoom.jsx@@ -9,6 +9,7 @@ import {listWritersRoomWorks,getWritersRoomWork,} from '../services/apiWritersRoom';+import { useLocalStorageBool } from '../hooks/useLocalStorageBool';const LIBRARY_COLLAPSED_KEY = 'wr.libraryCollapsed';@@ -22,16 +23,10 @@ export default function WritersRoom() {const [showExercise, setShowExercise] = useState(false);// Library collapsed state — desktop only; mobile keeps the library inline// because there's no editor-vs-library tradeoff to make on a small screen.- const [libraryCollapsed, setLibraryCollapsed] = useState(() => {- try { return localStorage.getItem(LIBRARY_COLLAPSED_KEY) === '1'; } catch { return false; }- });+ const [libraryCollapsed, setLibraryCollapsed] = useLocalStorageBool(LIBRARY_COLLAPSED_KEY, false);const toggleLibrary = useCallback(() => {- setLibraryCollapsed((prev) => {- const next = !prev;- try { localStorage.setItem(LIBRARY_COLLAPSED_KEY, next ? '1' : '0'); } catch { /* sandboxed storage */ }- return next;- });- }, []);+ setLibraryCollapsed((prev) => !prev);+ }, [setLibraryCollapsed]);// Skip setState when an in-flight library or work fetch resolves after the// page unmounts (rapid nav across pages). Reset on mount so React 18diff --git a/client/src/services/apiCore.js b/client/src/services/apiCore.jsindex 12705421ec..3564f33bd6 100644--- a/client/src/services/apiCore.js+++ b/client/src/services/apiCore.js@@ -8,12 +8,17 @@ export const PORTOS_APP_ID = 'portos-default';export async function request(endpoint, options = {}) {const { silent, ...fetchOptions } = options;const url = `${API_BASE}${endpoint}`;+ // Skip the JSON content-type header for FormData bodies — the browser must+ // set `multipart/form-data; boundary=…` itself, and any pre-supplied value+ // (including ours) suppresses the auto-boundary and breaks the upload.+ const isFormData = typeof FormData !== 'undefined' && fetchOptions.body instanceof FormData;+ const baseHeaders = isFormData ? {} : { 'Content-Type': 'application/json' };const config = {+ ...fetchOptions,headers: {- 'Content-Type': 'application/json',+ ...baseHeaders,...fetchOptions.headers- },- ...fetchOptions+ }};const response = await fetch(url, config).catch(() => null);diff --git a/client/src/services/apiHealth.js b/client/src/services/apiHealth.jsindex 3bf318fc8f..c7c7c11de8 100644--- a/client/src/services/apiHealth.js+++ b/client/src/services/apiHealth.js@@ -1,4 +1,4 @@-import { request, API_BASE } from './apiCore.js';+import { request } from './apiCore.js';// Apple Healthexport const ingestAppleHealth = (data) => request('/health/ingest', {@@ -27,21 +27,13 @@ export const getAppleHealthCorrelation = (from, to) => {if (to) params.set('to', to);return request(`/health/correlation?${params}`);};-export const uploadAppleHealthXml = (file) => {+export const uploadAppleHealthXml = (file, options = {}) => {const formData = new FormData();formData.append('file', file);- // Use fetch directly — the request helper sets Content-Type: application/json- // which conflicts with multipart/form-data. Browser sets correct boundary automatically.- return fetch(`${API_BASE}/health/import/xml`, {- method: 'POST',- body: formData,- }).then(async res => {- if (!res.ok) {- const err = await res.json().catch(() => ({ error: res.statusText }));- throw new Error(err.error || res.statusText);- }- return res.json();- });+ // request() detects FormData bodies and lets the browser set the multipart+ // boundary automatically. Accept `options` so callers with their own error+ // UI can pass `{ silent: true }` to suppress the helper's toast.+ return request('/health/import/xml', { method: 'POST', body: formData, ...options });};// Genome / Health Correlationsdiff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex f7d6803fab..bcd06d8f6f 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -1,4 +1,4 @@-import { request, API_BASE } from './apiCore.js';+import { request } from './apiCore.js';import { buildFormData } from './apiImageVideo.js';// Stage IDs mirror server/services/pipeline/issues.js — keep these in sync.@@ -397,23 +397,14 @@ export const patchPipelineAudioLine = (issueId, lineIdx, patch) =>export const listPipelineMusicLibrary = () =>request('/pipeline/audio/music-library');-// Bypasses `request()` because that helper hard-codes-// `Content-Type: application/json`, which conflicts with FormData's-// auto-generated multipart boundary.-export const uploadPipelineMusicTrack = async (issueId, file, { label } = {}) => {- const res = await fetch(- `${API_BASE}/pipeline/issues/${encodeURIComponent(issueId)}/stages/audio/music/upload`,- { method: 'POST', body: buildFormData({ track: file, label }) },+// request() now detects FormData bodies and lets the browser set the multipart+// boundary automatically — no need to bypass it. Accept `options` so callers+// with their own error UI can pass `{ silent: true }`.+export const uploadPipelineMusicTrack = (issueId, file, { label } = {}, options = {}) =>+ request(+ `/pipeline/issues/${encodeURIComponent(issueId)}/stages/audio/music/upload`,+ { method: 'POST', body: buildFormData({ track: file, label }), ...options },);- if (!res.ok) {- const err = await res.json().catch(() => ({ error: res.statusText }));- const e = new Error(err.error || res.statusText);- e.code = err.code;- e.status = res.status;- throw e;- }- return res.json();-};export const attachPipelineMusicTrack = (issueId, { trackFilename, label } = {}) =>request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/audio/music/attach`, {diff --git a/scripts/migrations/019-character-description-to-physical.js b/scripts/migrations/019-character-description-to-physical.jsnew file mode 100644index 0000000000..dcc2fd7863--- /dev/null+++ b/scripts/migrations/019-character-description-to-physical.js@@ -0,0 +1,119 @@+/**+ * Normalize legacy character.description → character.physicalDescription+ * across every store that persists a `characters[]` array.+ *+ * Background: pipeline early on used `description` as the visual descriptor+ * field for characters; the writers-room/canon refactor moved everything to+ * `physicalDescription`. `sanitizeCharacter` keeps a defensive read-side+ * fallback (`raw.physicalDescription || raw.description`) so a load that+ * happens before this migration runs doesn't silently drop the text on save,+ * but the persisted alias is otherwise dead weight — this migration rewrites+ * any character record that still carries it so the on-disk shape matches+ * what the sanitizer writes back.+ *+ * Targeted files (each may or may not exist depending on the install):+ * data/pipeline-series.json — series.characters[]+ * data/universe-builder.json — universes[].characters[]+ *+ * Idempotent: a record that already has `physicalDescription` (or that+ * never had a `description` field) is left alone. A record where both+ * fields are present has the legacy `description` field deleted (the+ * sanitizer was already preferring `physicalDescription` in that case).+ */++import { readFile, writeFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';++async function readJsonOr(path, fallback) {+ if (!existsSync(path)) return fallback;+ const raw = await readFile(path, 'utf8').catch(() => null);+ if (!raw) return fallback;+ return JSON.parse(raw);+}++// Returns { changed, character } — changed=true only when a write is needed.+function normalizeCharacter(raw) {+ if (!raw || typeof raw !== 'object') return { changed: false, character: raw };+ if (!('description' in raw)) return { changed: false, character: raw };+ const { description, ...rest } = raw;+ // If physicalDescription is missing/blank, lift description into it.+ // Otherwise (both present) drop the legacy alias and keep physicalDescription.+ if (typeof rest.physicalDescription !== 'string' || !rest.physicalDescription.trim()) {+ const lifted = typeof description === 'string' ? description : '';+ return { changed: true, character: { ...rest, physicalDescription: lifted } };+ }+ return { changed: true, character: rest };+}++function normalizeCharacterList(list) {+ if (!Array.isArray(list)) return { changed: false, list };+ let changed = false;+ const next = list.map((c) => {+ const { changed: cChanged, character } = normalizeCharacter(c);+ if (cChanged) changed = true;+ return character;+ });+ return { changed, list: next };+}++async function migrateSeriesFile(path) {+ if (!existsSync(path)) return { changed: false, recordsTouched: 0, charactersTouched: 0 };+ const state = await readJsonOr(path, null);+ if (!state || !Array.isArray(state.series)) return { changed: false, recordsTouched: 0, charactersTouched: 0 };+ let recordsTouched = 0;+ let charactersTouched = 0;+ const next = state.series.map((s) => {+ if (!s || typeof s !== 'object' || !Array.isArray(s.characters)) return s;+ const { changed, list } = normalizeCharacterList(s.characters);+ if (!changed) return s;+ recordsTouched += 1;+ charactersTouched += list.filter((c, i) => c !== s.characters[i]).length;+ return { ...s, characters: list };+ });+ if (recordsTouched === 0) return { changed: false, recordsTouched: 0, charactersTouched: 0 };+ await writeFile(path, JSON.stringify({ ...state, series: next }, null, 2));+ return { changed: true, recordsTouched, charactersTouched };+}++async function migrateUniverseFile(path) {+ if (!existsSync(path)) return { changed: false, recordsTouched: 0, charactersTouched: 0 };+ const state = await readJsonOr(path, null);+ if (!state || !Array.isArray(state.universes)) return { changed: false, recordsTouched: 0, charactersTouched: 0 };+ let recordsTouched = 0;+ let charactersTouched = 0;+ const next = state.universes.map((u) => {+ if (!u || typeof u !== 'object' || !Array.isArray(u.characters)) return u;+ const { changed, list } = normalizeCharacterList(u.characters);+ if (!changed) return u;+ recordsTouched += 1;+ charactersTouched += list.filter((c, i) => c !== u.characters[i]).length;+ return { ...u, characters: list };+ });+ if (recordsTouched === 0) return { changed: false, recordsTouched: 0, charactersTouched: 0 };+ await writeFile(path, JSON.stringify({ ...state, universes: next }, null, 2));+ return { changed: true, recordsTouched, charactersTouched };+}++export default {+ async up({ rootDir }) {+ const seriesPath = join(rootDir, 'data', 'pipeline-series.json');+ const universePath = join(rootDir, 'data', 'universe-builder.json');++ const [seriesResult, universeResult] = await Promise.all([+ migrateSeriesFile(seriesPath),+ migrateUniverseFile(universePath),+ ]);++ const totalRecords = seriesResult.recordsTouched + universeResult.recordsTouched;+ const totalChars = seriesResult.charactersTouched + universeResult.charactersTouched;++ if (totalRecords === 0) {+ return { changed: false, reason: 'no-legacy-description-fields' };+ }+ console.log(+ `📝 migration 019: normalized character.description → physicalDescription on ${totalRecords} record(s), ${totalChars} character(s) (series=${seriesResult.recordsTouched}, universe=${universeResult.recordsTouched})`,+ );+ return { changed: true, seriesRecords: seriesResult.recordsTouched, universeRecords: universeResult.recordsTouched, charactersTouched: totalChars };+ },+};diff --git a/scripts/run-migrations.js b/scripts/run-migrations.jsindex bf227212a1..3634d4cf30 100644--- a/scripts/run-migrations.js+++ b/scripts/run-migrations.js@@ -32,9 +32,11 @@ async function run() {applied = parsed;}- // Scan for migration files (*.js, sorted by filename)+ // Scan for migration files (*.js, sorted by filename). Test files live+ // alongside their migration; exclude them so the runner doesn't try to+ // import a vitest module as a migration.const files = (await readdir(migrationsDir))- .filter(f => f.endsWith('.js'))+ .filter(f => f.endsWith('.js') && !f.endsWith('.test.js')).sort();let ran = 0;diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex 6b577c72de..9bc0a7617c 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -45,6 +45,81 @@ export const findFfmpeg = async () => {return cachedFfmpegPath;};+/**+ * Spawn an ffmpeg child process and resolve with a structured result.+ * Collapses three sibling implementations (audioMux mux, optimizeForStreaming+ * faststart remux, upscaleVideo2x) onto one primitive so the spawn → stderr-+ * tail → close → SIGTERM-on-abort behavior stays in sync.+ *+ * - `bin`: absolute ffmpeg path (call `findFfmpeg()` upstream — keeps the+ * discovery cache hot and lets the caller decide what to do when ffmpeg+ * is missing). Required.+ * - `args`: argv passed to spawn. Required.+ * - `signal`: optional `AbortSignal`. When the signal fires we SIGTERM the+ * child; the close handler reports `{ ok:false, reason: 'cancelled (SIGTERM)' }`.+ * The abort listener is removed in a `finally`-shaped path so a long-lived+ * signal (one per render queue, used across many calls) doesn't accumulate+ * listeners on every successful ffmpeg run.+ * - `stderrTailBytes`: cap on the stderr buffer. `0` → `stdio: 'ignore'` (no+ * stderr captured, matches the historical optimize/upscale behavior).+ * Default `2000` mirrors audioMux's prior cap.+ *+ * Returns `{ ok: true }` on exit code 0, otherwise `{ ok: false, reason }`+ * where `reason` is a short human-readable string suitable for logging or+ * surfacing in a UI error. Spawn errors are translated into `reason: 'spawn+ * failed: …'` so callers don't need a separate `.on('error', …)` handler.+ */+export function runFfmpegProcess({ bin, args, signal, stderrTailBytes = 2000 } = {}) {+ if (!bin || typeof bin !== 'string') {+ return Promise.resolve({ ok: false, reason: 'invalid ffmpeg binary' });+ }+ if (!Array.isArray(args)) {+ return Promise.resolve({ ok: false, reason: 'invalid ffmpeg args' });+ }+ return new Promise((resolve) => {+ const stdio = stderrTailBytes > 0 ? ['ignore', 'ignore', 'pipe'] : 'ignore';+ const proc = spawn(bin, args, { stdio });+ let stderrTail = '';+ if (stderrTailBytes > 0 && proc.stderr) {+ proc.stderr.on('data', (chunk) => {+ stderrTail += chunk.toString();+ if (stderrTail.length > stderrTailBytes) {+ stderrTail = stderrTail.slice(-stderrTailBytes);+ }+ });+ }+ // `{ once: true }` auto-removes the listener when it fires. We still call+ // removeEventListener on normal completion so a signal reused across many+ // ffmpeg calls (one per render queue) doesn't accumulate dozens of unfired+ // listeners — the leak the audioMux audit flagged.+ let onAbort = null;+ if (signal) {+ onAbort = () => proc.kill('SIGTERM');+ signal.addEventListener('abort', onAbort, { once: true });+ }+ const cleanupSignal = () => {+ if (signal && onAbort) signal.removeEventListener('abort', onAbort);+ };+ proc.on('error', (err) => {+ cleanupSignal();+ resolve({ ok: false, reason: `spawn failed: ${err.message}` });+ });+ proc.on('close', (code, sig) => {+ cleanupSignal();+ if (sig === 'SIGTERM' || sig === 'SIGKILL') {+ resolve({ ok: false, reason: `cancelled (${sig})` });+ return;+ }+ if (code !== 0) {+ const tail = stderrTail.split(/\r?\n/).slice(-4).join(' | ');+ resolve({ ok: false, reason: tail ? `ffmpeg exit ${code}: ${tail}` : `ffmpeg exit ${code}` });+ return;+ }+ resolve({ ok: true });+ });+ });+}+// ffprobe sits next to ffmpeg in standard distributions — derive the path// from the cached ffmpeg discovery so we don't shell out twice.let cachedFfprobePath;@@ -106,21 +181,15 @@ export const generateThumbnail = async (videoPath, jobId) => {// and not at an unreliable boundary. For short clips (<2s) seek to the// actual midpoint. Fall back to 1s when ffprobe is unavailable.const seekSec = duration ? Math.min(2.5, Math.max(0.5, duration / 2)) : 1.0;- return new Promise((resolve) => {- const proc = spawn(ffmpeg, [- '-ss', seekSec.toFixed(2),- '-i', videoPath,- '-vframes', '1',- '-q:v', '5',- '-y',- thumbPath,- ], { stdio: 'ignore' });- proc.on('close', (code) => resolve(code === 0 ? thumbFilename : null));- proc.on('error', (err) => {- console.log(`⚠️ ffmpeg thumbnail failed to spawn: ${err.message}`);- resolve(null);- });+ const result = await runFfmpegProcess({+ bin: ffmpeg,+ args: ['-ss', seekSec.toFixed(2), '-i', videoPath, '-vframes', '1', '-q:v', '5', '-y', thumbPath],+ stderrTailBytes: 0,});+ if (!result.ok && result.reason?.startsWith('spawn failed: ')) {+ console.log(`⚠️ ffmpeg thumbnail failed to spawn: ${result.reason.slice('spawn failed: '.length)}`);+ }+ return result.ok ? thumbFilename : null;};// Probe the video's total frame count. Tries the fast metadata path first@@ -229,23 +298,15 @@ export const extractEvaluationFrames = async (videoPath, jobId, count = 5) => {const selectExpr = frameIndices.map((i) => `eq(n,${i})`).join('+');const outPattern = join(PATHS.videoThumbnails, `${jobId}-f%d.jpg`);- const ok = await new Promise((resolve) => {- const proc = spawn(ffmpeg, [- '-i', videoPath,- '-vf', `select='${selectExpr}'`,- '-vsync', 'vfr',- '-q:v', '5',- '-y',- outPattern,- ], { stdio: 'ignore' });- proc.on('close', (code) => resolve(code === 0));- proc.on('error', (err) => {- console.log(`⚠️ ffmpeg multi-frame extract failed to spawn: ${err.message}`);- resolve(false);- });+ const result = await runFfmpegProcess({+ bin: ffmpeg,+ args: ['-i', videoPath, '-vf', `select='${selectExpr}'`, '-vsync', 'vfr', '-q:v', '5', '-y', outPattern],+ stderrTailBytes: 0,});-- if (!ok) return [];+ if (!result.ok && result.reason?.startsWith('spawn failed: ')) {+ console.log(`⚠️ ffmpeg multi-frame extract failed to spawn: ${result.reason.slice('spawn failed: '.length)}`);+ }+ if (!result.ok) return [];// ffmpeg's image2 muxer numbers output starting at 1 in match order, so// the basenames map 1:1 to our frameIndices in timeline order.return frameIndices.map((_, i) => `${jobId}-f${i + 1}.jpg`);@@ -284,8 +345,9 @@ export const upscaleVideo2x = async (videoPath) => {// exact 2× width and the matching height. Avoiding `iw*2:ih*2` because// any user-supplied source with an odd dimension would otherwise fail.const tmpPath = `${videoPath}.up2x.mp4`;- const ok = await new Promise((resolve) => {- const proc = spawn(ffmpeg, [+ const result = await runFfmpegProcess({+ bin: ffmpeg,+ args: ['-i', videoPath,'-vf', 'scale=iw*2:-2:flags=lanczos','-c:v', 'libx264',@@ -295,11 +357,9 @@ export const upscaleVideo2x = async (videoPath) => {'-c:a', 'copy','-movflags', '+faststart','-y', tmpPath,- ], { stdio: 'ignore' });- proc.on('close', (code) => resolve(code === 0));- proc.on('error', () => resolve(false));+ ],});- if (!ok) {+ if (!result.ok) {await unlink(tmpPath).catch(() => {});return { ok: false, reason: 'ffmpeg upscale failed' };}@@ -330,12 +390,11 @@ export const optimizeForStreaming = async (videoPath) => {const ffmpeg = await findFfmpeg();if (!ffmpeg) return;const tmpPath = `${videoPath}.fs.mp4`;- const ok = await new Promise((resolve) => {- const proc = spawn(ffmpeg, ['-i', videoPath, '-c', 'copy', '-movflags', '+faststart', '-y', tmpPath], { stdio: 'ignore' });- proc.on('close', (code) => resolve(code === 0));- proc.on('error', () => resolve(false));+ const result = await runFfmpegProcess({+ bin: ffmpeg,+ args: ['-i', videoPath, '-c', 'copy', '-movflags', '+faststart', '-y', tmpPath],});- if (!ok) { await unlink(tmpPath).catch(() => {}); return; }+ if (!result.ok) { await unlink(tmpPath).catch(() => {}); return; }// POSIX rename atomically replaces an existing dest in one syscall. On// Windows, fs.rename fails when the destination already exists — but a// simple unlink-first would destroy the rendered video if the subsequentdiff --git a/server/lib/ffmpeg.test.js b/server/lib/ffmpeg.test.jsindex 906358e17a..0cec356d93 100644--- a/server/lib/ffmpeg.test.js+++ b/server/lib/ffmpeg.test.js@@ -3,7 +3,7 @@ import { writeFileSync, mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { verifyVideoPlayable, safeUnder } from './ffmpeg.js';+import { verifyVideoPlayable, safeUnder, runFfmpegProcess } from './ffmpeg.js';describe('verifyVideoPlayable', () => {let tmpDir;@@ -51,6 +51,72 @@ describe('verifyVideoPlayable', () => {});});+describe('runFfmpegProcess', () => {+ it('returns ok:false when bin is not a string', async () => {+ const res = await runFfmpegProcess({ args: ['-version'] });+ expect(res.ok).toBe(false);+ expect(res.reason).toMatch(/invalid ffmpeg binary/);+ });++ it('returns ok:false when args is not an array', async () => {+ const res = await runFfmpegProcess({ bin: '/bin/true', args: 'oops' });+ expect(res.ok).toBe(false);+ expect(res.reason).toMatch(/invalid ffmpeg args/);+ });++ it('returns ok:true when the child exits 0 (using /bin/true as a fake ffmpeg)', async () => {+ // POSIX-only — Windows skips. The helper only cares about the spawn-+ // exit-0 contract, not anything ffmpeg-specific, so any zero-exit binary+ // exercises the happy path.+ if (process.platform === 'win32') return;+ const res = await runFfmpegProcess({ bin: '/usr/bin/true', args: [] });+ if (res.ok) {+ expect(res).toEqual({ ok: true });+ } else {+ // Some hosts ship /bin/true instead — try once more.+ const res2 = await runFfmpegProcess({ bin: '/bin/true', args: [] });+ expect(res2).toEqual({ ok: true });+ }+ });++ it('returns ok:false with non-zero exit code in reason', async () => {+ if (process.platform === 'win32') return;+ const res = await runFfmpegProcess({ bin: '/usr/bin/false', args: [] });+ if (res.reason?.includes('spawn failed')) {+ // /usr/bin/false may not exist (e.g. macOS sometimes uses /bin/false);+ // try the alternative and re-assert.+ const res2 = await runFfmpegProcess({ bin: '/bin/false', args: [] });+ expect(res2.ok).toBe(false);+ expect(res2.reason).toMatch(/ffmpeg exit 1/);+ } else {+ expect(res.ok).toBe(false);+ expect(res.reason).toMatch(/ffmpeg exit 1/);+ }+ });++ it('returns ok:false with spawn-failed reason for a missing binary', async () => {+ const res = await runFfmpegProcess({ bin: '/this/does/not/exist/ffmpeg-fake', args: ['-x'] });+ expect(res.ok).toBe(false);+ expect(res.reason).toMatch(/spawn failed/);+ });++ it('removes the abort listener on normal completion (no listener leak)', async () => {+ if (process.platform === 'win32') return;+ const controller = new AbortController();+ // Spy on add/remove to confirm the helper cleans up.+ let added = 0;+ let removed = 0;+ const origAdd = controller.signal.addEventListener.bind(controller.signal);+ const origRemove = controller.signal.removeEventListener.bind(controller.signal);+ controller.signal.addEventListener = (...args) => { added += 1; return origAdd(...args); };+ controller.signal.removeEventListener = (...args) => { removed += 1; return origRemove(...args); };+ const trueBin = process.platform === 'darwin' ? '/usr/bin/true' : '/bin/true';+ await runFfmpegProcess({ bin: trueBin, args: [], signal: controller.signal });+ expect(added).toBe(1);+ expect(removed).toBe(1);+ });+});+describe('safeUnder', () => {it('accepts a plain basename under a root', () => {const root = '/tmp/portos-root';diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 4fd9bfa52f..b0391ef01d 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -4,12 +4,12 @@* Shared utilities for file operations used across services.*/-import { mkdir, readFile, writeFile, rename, unlink } from 'fs/promises';+import { mkdir, readFile, readdir, stat, writeFile, rename, unlink } from 'fs/promises';import { existsSync, statSync } from 'fs';import { execFile } from 'child_process';import { promisify } from 'util';import { randomUUID } from 'crypto';-import { join, dirname, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';+import { join, dirname, basename, extname, resolve as resolvePath, sep as PATH_SEP } from 'path';import { fileURLToPath } from 'url';import { homedir } from 'os';import { ServerError } from './errorHandler.js';@@ -641,6 +641,51 @@ export function resolveGalleryImage(name, { mustExist = true } = {}) {}}+/**+ * List a directory, keep entries whose extension matches `extensions`, stat+ * each, and project the survivors through `mapEntry(name, fullPath, stat)`.+ * Three sibling helpers (listLoras / listGallery / listMusicLibrary) used to+ * spell this loop out by hand — collapsed onto one primitive so the dir-+ * missing fallback, extension filter, and stat-failure handling all stay in+ * sync.+ *+ * - `extensions`: array of lowercased extensions including the leading dot+ * (`['.png']`, `['.mp3', '.wav', ...]`). Matched against `extname(name)`+ * case-insensitively so `FOO.PNG` and `foo.png` both pass.+ * - `mapEntry`: async/sync `(name, fullPath, stat) => entry|null`. Return+ * `null` to drop the entry. Final array preserves readdir order minus drops.+ * - `requireRegularFile` (default `true`): when true, entries whose stat+ * reports `!isFile()` are dropped before `mapEntry` runs (skips directories+ * with matching extensions). Pass `false` to match the gallery's legacy+ * behavior (only drops on stat failure).+ *+ * Missing directory → `[]` (no surprise 500 on a fresh install). Stat errors+ * on individual entries → drop that entry (matches the prior per-site+ * `.catch(() => null)` pattern).+ */+export async function listDirectoryByExtension(dir, { extensions, mapEntry, requireRegularFile = true } = {}) {+ if (!Array.isArray(extensions) || extensions.length === 0) {+ throw new Error('listDirectoryByExtension: extensions allowlist is required');+ }+ if (typeof mapEntry !== 'function') {+ throw new Error('listDirectoryByExtension: mapEntry must be a function');+ }+ const allowed = new Set(extensions.map((e) => String(e).toLowerCase()));+ const names = await readdir(dir).catch((err) => {+ if (err?.code === 'ENOENT') return [];+ throw err;+ });+ const filtered = names.filter((name) => allowed.has((extname(name) || '').toLowerCase()));+ const entries = await Promise.all(filtered.map(async (name) => {+ const fullPath = join(dir, name);+ const s = await stat(fullPath).catch(() => null);+ if (!s) return null;+ if (requireRegularFile && !s.isFile()) return null;+ return mapEntry(name, fullPath, s);+ }));+ return entries.filter(Boolean);+}+// Size in bytes of every file under `path`. Shells out to `du -sk` (or// PowerShell on Windows) — orders of magnitude faster than walking with// node's recursive readdir on large trees (hundreds of GB / 200k+ files).diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex f4e61f849c..7885dfe8bc 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -5,6 +5,7 @@ import { tmpdir } from 'os';import {assertSafeFilename,isValidJSON,+ listDirectoryByExtension,safeJSONParse,safeJSONLParse,readJSONFile,@@ -427,4 +428,84 @@ describe('fileUtils', () => {}});});++ describe('listDirectoryByExtension', () => {+ const tmpRoot = join(tmpdir(), `portos-listdir-test-${process.pid}-${Date.now()}`);++ beforeEach(async () => {+ await rm(tmpRoot, { recursive: true, force: true }).catch(() => {});+ await mkdir(tmpRoot, { recursive: true });+ });++ afterEach(async () => {+ await rm(tmpRoot, { recursive: true, force: true }).catch(() => {});+ });++ it('returns [] when the directory does not exist', async () => {+ const res = await listDirectoryByExtension(join(tmpRoot, 'missing'), {+ extensions: ['.png'],+ mapEntry: (n) => ({ filename: n }),+ });+ expect(res).toEqual([]);+ });++ it('filters by extension (case-insensitive) and maps survivors', async () => {+ await writeFile(join(tmpRoot, 'a.png'), 'a');+ await writeFile(join(tmpRoot, 'b.PNG'), 'b');+ await writeFile(join(tmpRoot, 'c.jpg'), 'c');+ const res = await listDirectoryByExtension(tmpRoot, {+ extensions: ['.png'],+ mapEntry: (name, _full, s) => ({ name, sizeBytes: s.size }),+ });+ const names = res.map((r) => r.name).sort();+ expect(names).toEqual(['a.png', 'b.PNG']);+ });++ it('drops directories when requireRegularFile is true (default)', async () => {+ await writeFile(join(tmpRoot, 'real.safetensors'), 'data');+ await mkdir(join(tmpRoot, 'fake.safetensors'));+ const res = await listDirectoryByExtension(tmpRoot, {+ extensions: ['.safetensors'],+ mapEntry: (name) => ({ name }),+ });+ expect(res).toEqual([{ name: 'real.safetensors' }]);+ });++ it('keeps directories when requireRegularFile is false (gallery legacy)', async () => {+ await writeFile(join(tmpRoot, 'real.png'), 'data');+ await mkdir(join(tmpRoot, 'fake.png'));+ const res = await listDirectoryByExtension(tmpRoot, {+ extensions: ['.png'],+ requireRegularFile: false,+ mapEntry: (name) => ({ name }),+ });+ const names = res.map((r) => r.name).sort();+ expect(names).toEqual(['fake.png', 'real.png']);+ });++ it('drops entries whose mapEntry returns null', async () => {+ await writeFile(join(tmpRoot, 'a.json'), 'a');+ await writeFile(join(tmpRoot, 'b.json'), 'b');+ const res = await listDirectoryByExtension(tmpRoot, {+ extensions: ['.json'],+ mapEntry: (name) => (name === 'a.json' ? null : { name }),+ });+ expect(res).toEqual([{ name: 'b.json' }]);+ });++ it('throws if extensions is missing or empty', async () => {+ await expect(+ listDirectoryByExtension(tmpRoot, { mapEntry: (n) => n }),+ ).rejects.toThrow(/extensions allowlist/);+ await expect(+ listDirectoryByExtension(tmpRoot, { extensions: [], mapEntry: (n) => n }),+ ).rejects.toThrow(/extensions allowlist/);+ });++ it('throws if mapEntry is not a function', async () => {+ await expect(+ listDirectoryByExtension(tmpRoot, { extensions: ['.png'] }),+ ).rejects.toThrow(/mapEntry must be a function/);+ });+ });});diff --git a/server/lib/mockPathsDataRoot.js b/server/lib/mockPathsDataRoot.jsnew file mode 100644index 0000000000..d1942daf67--- /dev/null+++ b/server/lib/mockPathsDataRoot.js@@ -0,0 +1,105 @@+/**+ * Shared `vi.mock` factory for the "PATHS.data → temp dir" pattern.+ *+ * Eight (and growing) test files duplicated the same Proxy-over-fileUtils+ * mock to redirect `PATHS.data` at a per-test temp directory:+ *+ * vi.mock('../../lib/fileUtils.js', async () => {+ * const actual = await vi.importActual('../../lib/fileUtils.js');+ * return new Proxy(actual, {+ * get(target, prop) {+ * if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };+ * return target[prop];+ * },+ * });+ * });+ *+ * This module gives the same behavior via a single helper. The relative path+ * to `fileUtils.js` stays at each call site because `vi.mock` is hoisted to+ * module top before any test code runs — Vitest must see a string literal to+ * a real file from the *test's* directory. The helper computes the temp dir+ * and exposes a Proxy factory; the caller still writes the one-liner+ * `vi.mock(...)` so Vitest's hoister can find it. See `mockPathsDataRoot()`+ * below for the canonical usage example.+ *+ * To keep the call site short and avoid forcing every test to write the Proxy+ * block, this module exports:+ *+ * - `makePathsProxy(actual, { dataRoot, extraOverrides? })` — used inside+ * the test's own `vi.mock` factory. Returns the Proxy.+ * - `createTempDataRoot()` — returns `{ tempRoot }` allocated under os.tmpdir().+ *+ * Migration: tests that need MULTIPLE PATHS members redirected+ * (e.g. `images`, `videos`) can pass `extraOverrides` (object or function)+ * — the helper merges those on top of the `data: tempRoot` override.+ */++import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++/**+ * Allocate a unique temp dir suitable for use as `PATHS.data` in a test file.+ * Caller is responsible for cleanup (`rmSync` in afterAll) when needed.+ */+export function createTempDataRoot(prefix = 'portos-test-') {+ return mkdtempSync(join(tmpdir(), prefix));+}++/**+ * Build the Proxy returned from a `vi.mock('../lib/fileUtils.js', ...)`+ * factory. Pass the already-resolved `actual` (from `vi.importActual`) and+ * the `dataRoot` you want `PATHS.data` to point at.+ *+ * `dataRoot` accepts either:+ * - a string — captured by value at construction time, or+ * - a function `() => string` — resolved lazily on each PATHS read. Use+ * the function form when the test allocates a fresh temp dir per test+ * (a `let tempRoot` that the per-test setup reassigns). The Proxy reads+ * it through the getter so it always sees the current value.+ *+ * `extraOverrides` is either:+ * - a plain object — merged over `{ data: <resolved root> }`, or+ * - a function `(dataRoot) => overridesObject` — for cases where the+ * extra keys are derived (e.g. `images: join(dataRoot, 'images')`).+ */+export function makePathsProxy(actual, { dataRoot, extraOverrides = null } = {}) {+ const resolveRoot = typeof dataRoot === 'function' ? dataRoot : () => dataRoot;+ const buildOverrides = () => {+ const root = resolveRoot();+ const extras = typeof extraOverrides === 'function'+ ? extraOverrides(root)+ : (extraOverrides || {});+ return { ...actual.PATHS, data: root, ...extras };+ };+ return new Proxy(actual, {+ get(target, prop) {+ if (prop === 'PATHS') return buildOverrides();+ return target[prop];+ },+ });+}++/**+ * Convenience wrapper for the most-common case: a single per-file temp dir+ * plus a Proxy factory. Returns `{ tempRoot, makeProxy, cleanup }` where+ * `makeProxy(actual)` is called from the test's `vi.mock` factory.+ *+ * Example:+ *+ * import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+ * const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot();+ * vi.mock('../lib/fileUtils.js', async () => {+ * const actual = await vi.importActual('../lib/fileUtils.js');+ * return makeProxy(actual);+ * });+ * afterAll(cleanup);+ */+export function mockPathsDataRoot({ prefix = 'portos-test-', extraOverrides = null } = {}) {+ const tempRoot = createTempDataRoot(prefix);+ return {+ tempRoot,+ makeProxy: (actual) => makePathsProxy(actual, { dataRoot: tempRoot, extraOverrides }),+ cleanup: () => rmSync(tempRoot, { recursive: true, force: true }),+ };+}diff --git a/server/lib/mockPathsDataRoot.test.js b/server/lib/mockPathsDataRoot.test.jsnew file mode 100644index 0000000000..039dbb7960--- /dev/null+++ b/server/lib/mockPathsDataRoot.test.js@@ -0,0 +1,87 @@+import { describe, it, expect, afterAll } from 'vitest';+import { existsSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { createTempDataRoot, makePathsProxy, mockPathsDataRoot } from './mockPathsDataRoot.js';++describe('mockPathsDataRoot', () => {+ describe('createTempDataRoot', () => {+ const created = [];+ afterAll(() => created.forEach((d) => rmSync(d, { recursive: true, force: true })));++ it('returns a path under the OS temp dir', () => {+ const dir = createTempDataRoot('portos-mockpaths-test-');+ created.push(dir);+ expect(dir).toMatch(/portos-mockpaths-test-/);+ expect(dir.startsWith(tmpdir())).toBe(true);+ expect(existsSync(dir)).toBe(true);+ });++ it('returns distinct paths on successive calls', () => {+ const a = createTempDataRoot('mp-distinct-');+ const b = createTempDataRoot('mp-distinct-');+ created.push(a, b);+ expect(a).not.toBe(b);+ });+ });++ describe('makePathsProxy', () => {+ const fakeActual = {+ PATHS: { data: '/real/data', images: '/real/images', logs: '/real/logs' },+ ensureDir: () => 'ensureDir-fn',+ otherFn: 42,+ };++ it('overrides only PATHS.data by default and passes other PATHS keys through', () => {+ const proxy = makePathsProxy(fakeActual, { dataRoot: '/tmp/x' });+ expect(proxy.PATHS.data).toBe('/tmp/x');+ expect(proxy.PATHS.images).toBe('/real/images');+ expect(proxy.PATHS.logs).toBe('/real/logs');+ });++ it('passes non-PATHS exports through untouched', () => {+ const proxy = makePathsProxy(fakeActual, { dataRoot: '/tmp/x' });+ expect(proxy.ensureDir()).toBe('ensureDir-fn');+ expect(proxy.otherFn).toBe(42);+ });++ it('extraOverrides (object) merges over the default { data } override', () => {+ const proxy = makePathsProxy(fakeActual, {+ dataRoot: '/tmp/x',+ extraOverrides: { images: '/tmp/x/images', videos: '/tmp/x/videos' },+ });+ expect(proxy.PATHS.data).toBe('/tmp/x');+ expect(proxy.PATHS.images).toBe('/tmp/x/images');+ expect(proxy.PATHS.videos).toBe('/tmp/x/videos');+ expect(proxy.PATHS.logs).toBe('/real/logs'); // untouched+ });++ it('extraOverrides (function) receives the dataRoot', () => {+ const proxy = makePathsProxy(fakeActual, {+ dataRoot: '/tmp/x',+ extraOverrides: (root) => ({ images: join(root, 'images') }),+ });+ expect(proxy.PATHS.images).toBe('/tmp/x/images');+ });++ it('dataRoot (function) resolves lazily on each PATHS read', () => {+ let current = '/initial';+ const proxy = makePathsProxy(fakeActual, { dataRoot: () => current });+ expect(proxy.PATHS.data).toBe('/initial');+ current = '/after-mutation';+ expect(proxy.PATHS.data).toBe('/after-mutation');+ });+ });++ describe('mockPathsDataRoot wrapper', () => {+ it('returns a tempRoot + makeProxy + cleanup triple', () => {+ const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'mp-wrap-' });+ expect(existsSync(tempRoot)).toBe(true);+ const proxy = makeProxy({ PATHS: { data: 'orig', logs: 'l' } });+ expect(proxy.PATHS.data).toBe(tempRoot);+ expect(proxy.PATHS.logs).toBe('l');+ cleanup();+ expect(existsSync(tempRoot)).toBe(false);+ });+ });+});diff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex f92c8bbf08..09f36658d7 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -144,17 +144,27 @@ const DEFAULT_ID_PREFIX = Object.freeze({// series.js, issues.js, etc.) stop redefining the same one-liners.export const isStr = (v) => typeof v === 'string';export const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');-const cleanStringArray = (raw, itemMax, listMax) => {++// Walk a raw array through a per-item sanitizer, dropping rejected entries+// (falsy return from `sanitizer`) and capping the output at `cap`. Three+// near-identical loops elsewhere in this file (cleanStringArray, the wardrobe+// list, the per-kind bible list) collapsed onto this single primitive so a+// future cap/skip rule change lands in one place.+const sanitizeListWith = (raw, sanitizer, cap) => {if (!Array.isArray(raw)) return [];const out = [];for (const v of raw) {- const s = trimTo(v, itemMax);- if (s) out.push(s);- if (out.length >= listMax) break;+ const s = sanitizer(v);+ if (!s) continue;+ out.push(s);+ if (out.length >= cap) break;}return out;};+const cleanStringArray = (raw, itemMax, listMax) =>+ sanitizeListWith(raw, (v) => trimTo(v, itemMax), listMax);+export const isBlank = (v) => {if (v == null) return true;if (Array.isArray(v)) return v.length === 0;@@ -209,15 +219,11 @@ function sanitizeWardrobe(raw, { preserveTimestamps = true } = {}) {}function sanitizeWardrobeList(raw, opts = {}) {- if (!Array.isArray(raw)) return [];- const out = [];- for (const w of raw) {- const sanitized = sanitizeWardrobe(w, opts);- if (!sanitized) continue;- out.push(sanitized);- if (out.length >= BIBLE_LIMITS.WARDROBES_PER_CHARACTER_MAX) break;- }- return out;+ return sanitizeListWith(+ raw,+ (w) => sanitizeWardrobe(w, opts),+ BIBLE_LIMITS.WARDROBES_PER_CHARACTER_MAX,+ );}// Shared canon extras applied to every kind. `locked` follows the on-disk@@ -234,10 +240,11 @@ function applyCanonExtras(raw) {return out;}-// Accepts the writers-room shape natively; legacy pipeline `description`-// is treated as `physicalDescription` when the latter is empty so old-// series.json migrates forward on first save. TODO(item-4): drop the-// `description` fallback once pipeline characters extract natively.+// Pipeline + writers-room shapes both use `physicalDescription`. Migration 019+// rewrites the legacy `description` alias forward, but the read-side fallback+// stays in place so a load-before-migration doesn't silently drop the text on+// next save (only `physicalDescription` is written back, so any record that+// survives this read normalizes on its next persist).export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character, preserveTimestamps = true } = {}) {if (!raw || typeof raw !== 'object') return null;const name = trimTo(raw.name, BIBLE_LIMITS.NAME_MAX);@@ -345,17 +352,13 @@ export function sanitizeObject(raw, { idPrefix = DEFAULT_ID_PREFIX.object, prese* agree on what an on-disk bible looks like.*/export function sanitizeBibleList(rawList, kind, opts = {}) {- if (!Array.isArray(rawList)) return [];const sanitizer = SANITIZERS[kind];if (!sanitizer) return [];- const out = [];- for (const raw of rawList) {- const s = sanitizer(raw, opts);- if (!s) continue;- out.push(s);- if (out.length >= BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX) break;- }- return out;+ return sanitizeListWith(+ rawList,+ (raw) => sanitizer(raw, opts),+ BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX,+ );}const SANITIZERS = Object.freeze({diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.jsindex 0fa08823db..b37eb70502 100644--- a/server/lib/storyBible.test.js+++ b/server/lib/storyBible.test.js@@ -2,19 +2,16 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdtempSync, rmSync, existsSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';+import { makePathsProxy } from './mockPathsDataRoot.js';let tempRoot;-// Mock PATHS.data so the factory writes into a temp dir per test. Mirrors-// the pattern used by writers-room CRUD tests.+// Mock PATHS.data so the factory writes into a temp dir per test. `tempRoot`+// is a `let` that beforeEach reassigns — the function form of dataRoot makes+// the Proxy re-read it on every PATHS access so each test sees its own dir.vi.mock('./fileUtils.js', async () => {const actual = await vi.importActual('./fileUtils.js');- return new Proxy(actual, {- get(target, prop) {- if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };- return target[prop];- },- });+ return makePathsProxy(actual, { dataRoot: () => tempRoot });});const storyBible = await import('./storyBible.js');@@ -42,12 +39,13 @@ describe('storyBible — sanitizeCharacter', () => {expect(sanitizeCharacter({ name: ' ' })).toBeNull();});- it('back-compat: accepts pipeline-shape `description` and migrates to `physicalDescription`', () => {+ it('lifts the legacy `description` alias into `physicalDescription` on read', () => {const out = sanitizeCharacter({ name: 'Aria', description: 'tall, dark hair' });expect(out.physicalDescription).toBe('tall, dark hair');+ expect(out).not.toHaveProperty('description');});- it('prefers explicit `physicalDescription` over legacy `description` when both present', () => {+ it('prefers `physicalDescription` when both fields are present', () => {const out = sanitizeCharacter({ name: 'Aria', description: 'old', physicalDescription: 'new' });expect(out.physicalDescription).toBe('new');});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 1ec7780229..0fb133d451 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -880,6 +880,36 @@ export function sanitizeTaskMetadata(raw) {}+// =============================================================================+// MEDIA COLLECTIONS — bulk add/remove items+// =============================================================================++// `ref` rules mirror server/services/mediaCollections.js#sanitizeItem: ":"+// is the API key separator (`<kind>:<ref>` split on first ":"), so a ref+// containing one would be unaddressable for DELETE/coverKey lookups.+const mediaCollectionItemSchema = z.object({+ kind: z.enum(['image', 'video']),+ ref: z.string().trim().min(1).max(500).refine((s) => !s.includes(':'), {+ message: 'ref may not contain ":"',+ }),+}).strict();++// Remove keys are `<kind>:<ref>` strings the client already addresses items+// by — kept loose here (length cap only) because invalid keys are silently+// ignored by the service. Strict validation would force the client to filter+// stale selections itself.+const mediaCollectionRemoveKeySchema = z.string().min(3).max(520);++// Bulk endpoint: { add?, remove? } — at least one of the two arrays must be+// non-empty so a no-op call surfaces as a 400 instead of an opaque success.+export const mediaCollectionBulkItemsSchema = z.object({+ add: z.array(mediaCollectionItemSchema).max(1000).optional(),+ remove: z.array(mediaCollectionRemoveKeySchema).max(1000).optional(),+}).strict().refine(+ (d) => (Array.isArray(d.add) && d.add.length > 0) || (Array.isArray(d.remove) && d.remove.length > 0),+ { message: 'bulk update requires at least one item in add or remove' },+);+// =============================================================================// SHARING (cross-network share buckets via cloud-synced folders)// =============================================================================diff --git a/server/routes/mediaCollections.js b/server/routes/mediaCollections.jsindex 61e5a57bbb..c8da77d6f1 100644--- a/server/routes/mediaCollections.js+++ b/server/routes/mediaCollections.js@@ -5,13 +5,15 @@* PATCH /api/media/collections/:id → Collection (body: { name?, description?, coverKey? })* DELETE /api/media/collections/:id → { id }* POST /api/media/collections/:id/items → Collection (body: { kind, ref })+ * POST /api/media/collections/:id/items/bulk → { collection, added, removed }+ * (body: { add?: [{kind,ref}], remove?: ["<kind>:<ref>"] })* DELETE /api/media/collections/:id/items/:key → Collection (key = "<kind>:<ref>")*/import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest } from '../lib/validation.js';+import { validateRequest, mediaCollectionBulkItemsSchema } from '../lib/validation.js';import * as svc from '../services/mediaCollections.js';const router = Router();@@ -83,6 +85,16 @@ router.post('/:id/items', asyncHandler(async (req, res) => {res.json(c);}));+// Bulk add+remove in a single read-modify-write. Returns+// `{ collection, added, removed }` so callers can show "Added 3, removed 12"+// confirmations without re-deriving the diff client-side.+router.post('/:id/items/bulk', asyncHandler(async (req, res) => {+ const body = validateRequest(mediaCollectionBulkItemsSchema, req.body ?? {});+ const result = await svc.bulkUpdateCollectionItems(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));+router.delete('/:id/items/:key', asyncHandler(async (req, res) => {// The :key route param is "<kind>:<ref>" — Express decodes it for us, but// we still validate the shape so a hand-rolled curl can't sneak past thediff --git a/server/routes/mediaCollections.test.js b/server/routes/mediaCollections.test.jsnew file mode 100644index 0000000000..e2ea78a33e--- /dev/null+++ b/server/routes/mediaCollections.test.js@@ -0,0 +1,101 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Stub the service layer so we can assert the route's request → svc-call+// → response wiring without standing up the real file-backed store.+const stubs = {+ bulkUpdateCollectionItems: vi.fn(),+};++vi.mock('../services/mediaCollections.js', async () => {+ const actual = await vi.importActual('../services/mediaCollections.js');+ return {+ ...actual,+ bulkUpdateCollectionItems: (...args) => stubs.bulkUpdateCollectionItems(...args),+ };+});++const router = (await import('./mediaCollections.js')).default;++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/media/collections', router);+ app.use(errorMiddleware);+ return app;+}++describe('mediaCollections routes — POST /:id/items/bulk', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('400s when both add and remove are empty', async () => {+ const r = await request(makeApp()).post('/api/media/collections/c1/items/bulk').send({});+ expect(r.status).toBe(400);+ expect(stubs.bulkUpdateCollectionItems).not.toHaveBeenCalled();+ });++ it('400s for unknown body fields (strict schema)', async () => {+ const r = await request(makeApp()).post('/api/media/collections/c1/items/bulk').send({+ add: [{ kind: 'image', ref: 'a.png' }],+ bogus: true,+ });+ expect(r.status).toBe(400);+ expect(stubs.bulkUpdateCollectionItems).not.toHaveBeenCalled();+ });++ it('400s when an add item carries an invalid kind', async () => {+ const r = await request(makeApp()).post('/api/media/collections/c1/items/bulk').send({+ add: [{ kind: 'movie', ref: 'x.mp4' }],+ });+ expect(r.status).toBe(400);+ });++ it('400s when an add ref contains ":"', async () => {+ const r = await request(makeApp()).post('/api/media/collections/c1/items/bulk').send({+ add: [{ kind: 'image', ref: 'bad:ref.png' }],+ });+ expect(r.status).toBe(400);+ });++ it('200s and returns { collection, added, removed } on success', async () => {+ stubs.bulkUpdateCollectionItems.mockResolvedValueOnce({+ collection: { id: 'c1', name: 'A', items: [], coverKey: null },+ added: 2,+ removed: 1,+ });+ const r = await request(makeApp()).post('/api/media/collections/c1/items/bulk').send({+ add: [{ kind: 'image', ref: 'a.png' }, { kind: 'video', ref: 'v1' }],+ remove: ['image:b.png'],+ });+ expect(r.status).toBe(200);+ expect(r.body).toMatchObject({ added: 2, removed: 1 });+ expect(stubs.bulkUpdateCollectionItems).toHaveBeenCalledWith('c1', {+ add: [{ kind: 'image', ref: 'a.png' }, { kind: 'video', ref: 'v1' }],+ remove: ['image:b.png'],+ });+ });++ it('404s when the service throws NOT_FOUND', async () => {+ stubs.bulkUpdateCollectionItems.mockRejectedValueOnce(+ Object.assign(new Error('not found'), { code: 'NOT_FOUND' }),+ );+ const r = await request(makeApp()).post('/api/media/collections/ghost/items/bulk').send({+ add: [{ kind: 'image', ref: 'a.png' }],+ });+ expect(r.status).toBe(404);+ });++ it('409s when the service throws DUPLICATE (defensive — bulk path is idempotent today)', async () => {+ stubs.bulkUpdateCollectionItems.mockRejectedValueOnce(+ Object.assign(new Error('dup'), { code: 'DUPLICATE' }),+ );+ const r = await request(makeApp()).post('/api/media/collections/c1/items/bulk').send({+ add: [{ kind: 'image', ref: 'a.png' }],+ });+ expect(r.status).toBe(409);+ });+});diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 9d367ecb03..a2486ea8b5 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -153,6 +153,163 @@ ${hints.map(h => `- ${h}`).join('\n')}*/const LIGHT_CONTEXT_PROVIDER_TYPES = new Set(['tui', 'cli']);+/**+ * Build the shared task block — the description plus optional `**Target App**`+ * and `**Screenshots**` fields. Used by BOTH the light and full prompt paths+ * so a new task-metadata field gets surfaced in both without drift.+ *+ * Returns three pre-rendered slots (`description`, `targetApp`, `screenshots`).+ * Absent fields come back as empty strings so the full path's template literal+ * can interpolate them in fixed positions and preserve byte-identical line+ * spacing. The light path filters out the empty strings and joins what remains.+ *+ * @param {Object} task+ * @param {Object} [opts]+ * @param {boolean} [opts.screenshotsAsList=false] - When true, render screenshots+ * as a `### Screenshots` header followed by a bulleted list of paths (light+ * path style). When false, render as a single inline `**Screenshots**: a, b`+ * line (full path style).+ * @returns {{ description: string, targetApp: string, screenshots: string }}+ */+export function buildTaskBlock(task, { screenshotsAsList = false } = {}) {+ const description = task.description;+ const targetApp = task.metadata?.app ? `**Target App**: ${task.metadata.app}` : '';+ const shots = task.metadata?.screenshots;+ let screenshots = '';+ if (Array.isArray(shots) && shots.length > 0) {+ screenshots = screenshotsAsList+ ? '### Screenshots\nUse your filesystem tools to inspect each path:\n' ++ shots.map(s => `- \`${s}\``).join('\n')+ : `**Screenshots**: ${shots.join(', ')}`;+ }+ return { description, targetApp, screenshots };+}++/**+ * Build the **review-loop follow-up** section — the instructions for the+ * agent spawned by `spawnReviewLoopFollowUp` to drive Copilot's review-and-fix+ * loop until the PR merges. Same 7-step procedure, same merge command, same+ * MERGED-state verification, same 10-iteration cap in BOTH the light and full+ * paths — extracted so the two can't drift independently.+ *+ * I/O (the slashdo `/do:rpr` body) is intentionally pulled outside this helper+ * and threaded in via `rprBody` so the function stays pure and synchronous.+ *+ * @param {Object} metadata - task.metadata (reviewLoopPR* fields, sourceTaskId)+ * @param {Object} [opts]+ * @param {boolean} [opts.verbose=false] - When true, emit the verbose prose+ * variant the full (api) path uses, with PR Details list and an inlined+ * `/do:rpr` reference. When false, emit the compact list the light path uses.+ * @param {string|null} [opts.rprBody=null] - The loaded `/do:rpr` slashdo body.+ * Only appended in verbose mode; ignored in compact mode.+ * @returns {string}+ */+export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null } = {}) {+ const prUrl = metadata.reviewLoopPRUrl || '';+ const prBranch = metadata.reviewLoopPRBranch || '';+ const prNumber = metadata.reviewLoopPRNumber ?? '';+ const prOwner = metadata.reviewLoopPROwner ?? '';+ const prRepo = metadata.reviewLoopPRRepo ?? '';+ const sourceTaskId = metadata.sourceTaskId || 'unknown';++ if (verbose) {+ return `+## Review-Loop Follow-up (PRIMARY OBJECTIVE)+A previous agent finished implementing the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on branch \`${prBranch}\`. The system has already requested an initial Copilot code review. **Your job is to drive the review-and-fix loop to completion and merge the PR.**++**Run this loop UNTIL the PR has zero unresolved Copilot comments OR you hit the iteration cap of 10:**++1. Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round).+2. If there are unresolved review threads, fix them in this worktree, run the project's tests, commit (\`feat:\`/\`fix:\` prefix, no Co-Authored-By), push, and resolve the addressed threads.+3. Re-request a Copilot review.+4. Repeat from step 1.+5. When Copilot returns "0 comments" / no unresolved threads, merge the PR **immediately** with this exact command (flags: \`--squash --delete-branch\`, nothing else):+ \`\`\`bash+ gh pr merge "${prUrl}" --squash --delete-branch+ \`\`\`+ ${prOwner && prRepo && prNumber ? `(Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --delete-branch\`.)` : ''}+ You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.+6. Confirm the PR is actually merged before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is \`MERGED\`.+7. Exit. Do **not** run \`/do:push\` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.++**Hard stop:** if the loop hasn't converged after 10 iterations, post a PR comment summarising the unresolved blockers and exit. Do not loop indefinitely.++**Repeated comments:** If a new Copilot round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on to merge.++PR Details:+- **URL**: ${prUrl}+- **Branch**: \`${prBranch}\`+${prNumber !== '' ? `- **Number**: ${prNumber}` : ''}+${prOwner && prRepo ? `- **Repo**: ${prOwner}/${prRepo}` : ''}+- **Source task**: ${sourceTaskId}+${rprBody ? `\n### /do:rpr Reference (full procedure)\n\n${rprBody}\n` : ''}`;+ }++ // Compact light-path variant.+ return [+ '## Review-Loop Follow-up (PRIMARY OBJECTIVE)',+ `A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. The system has requested an initial Copilot review. Drive the review-and-fix loop to completion and merge.`,+ '',+ '**Loop UNTIL zero unresolved Copilot comments OR 10 iterations:**',+ '1. Wait for the latest Copilot review (poll 5–15s, max 5 min per round).',+ '2. If unresolved threads: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, resolve threads.',+ '3. Re-request a Copilot review.',+ '4. Repeat.',+ '5. When clean, merge **immediately** with this exact command (flags: `--squash --delete-branch`, nothing else):',+ ' ```bash',+ ` gh pr merge "${prUrl}" --squash --delete-branch`,+ ' ```',+ prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --delete-branch\`.)` : null,+ ' You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.',+ `6. Confirm the merge happened before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (failing check, unresolved thread, branch protection) — fix and retry. Do NOT exit until state is \`MERGED\`.`,+ '7. Exit — do NOT run `/do:push` or open a new PR.',+ '',+ '**Hard stop:** if not converged after 10 rounds, post a PR comment summarising blockers and exit.',+ '**Repeated comments:** if a round only re-raises feedback you intentionally rejected (with a reply explaining why), treat as clean and merge.'+ ].filter(Boolean).join('\n');+}++/**+ * Build the single "## Guidelines" completion-handoff bullet for the full+ * (api) prompt path. Mirrors the helper pattern the light path already uses+ * (`worktreeCommitGuidance`, `buildTuiCompletionSection`) — same 4-branch+ * decision tree (read-only / TUI / worktree+PR / worktree-only / default) but+ * flattened into a function so reading is linear instead of a nested ternary.+ *+ * Returns the bullet body WITHOUT the leading `- ` marker (caller prepends),+ * or `null` when the branch produces no text (the legacy empty-string tail).+ *+ * @param {Object} opts+ * @param {boolean} opts.isReadOnly+ * @param {boolean} opts.isTui+ * @param {string} opts.tuiCompletionCommand - `/do:pr` or `/do:push`+ * @param {Object|null} opts.worktreeInfo+ * @param {boolean} opts.willOpenPR+ * @param {boolean} opts.willReviewLoop+ * @returns {string|null}+ */+export function buildCompletionGuidelineBullet({+ isReadOnly, isTui, tuiCompletionCommand,+ worktreeInfo, willOpenPR, willReviewLoop,+}) {+ if (isReadOnly) {+ return '**This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.';+ }+ if (isTui) {+ return `On successful completion, YOU run the Completion Workflow above (\`${tuiCompletionCommand}\`, write the sentinel, \`/quit\`).`;+ }+ if (worktreeInfo && willOpenPR) {+ const reviewSuffix = willReviewLoop+ ? ' For GitHub PRs, a Copilot code review will also be requested automatically (skipped on GitLab and other non-GitHub forges) — do NOT run `/do:rpr` or attempt to address review comments yourself; you will have already exited.'+ : '';+ return `On successful completion, the system will push your branch and open a pull request — do NOT open a PR manually. (If the task fails, no PR is opened; the worktree is then cleaned up unless a safety check preserves it for manual recovery.)${reviewSuffix}`;+ }+ if (worktreeInfo) {+ return 'Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.';+ }+ return null;+}+/*** Build the agent prompt.*@@ -301,44 +458,8 @@ After your task completes, the system will request a Copilot code review automatconst isReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);let reviewLoopFollowUpSection = '';if (isReviewLoopFollowUp) {- const prUrl = task.metadata?.reviewLoopPRUrl || '';- const prBranch = task.metadata?.reviewLoopPRBranch || '';- const prNumber = task.metadata?.reviewLoopPRNumber ?? '';- const prOwner = task.metadata?.reviewLoopPROwner ?? '';- const prRepo = task.metadata?.reviewLoopPRRepo ?? '';- const sourceTaskId = task.metadata?.sourceTaskId || 'unknown';const rprBody = await loadSlashdoFile('rpr').catch(() => null);-- reviewLoopFollowUpSection = `-## Review-Loop Follow-up (PRIMARY OBJECTIVE)-A previous agent finished implementing the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on branch \`${prBranch}\`. The system has already requested an initial Copilot code review. **Your job is to drive the review-and-fix loop to completion and merge the PR.**--**Run this loop UNTIL the PR has zero unresolved Copilot comments OR you hit the iteration cap of 10:**--1. Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round).-2. If there are unresolved review threads, fix them in this worktree, run the project's tests, commit (\`feat:\`/\`fix:\` prefix, no Co-Authored-By), push, and resolve the addressed threads.-3. Re-request a Copilot review.-4. Repeat from step 1.-5. When Copilot returns "0 comments" / no unresolved threads, merge the PR **immediately** with this exact command (flags: \`--squash --delete-branch\`, nothing else):- \`\`\`bash- gh pr merge "${prUrl}" --squash --delete-branch- \`\`\`- ${prOwner && prRepo && prNumber ? `(Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --delete-branch\`.)` : ''}- You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.-6. Confirm the PR is actually merged before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is \`MERGED\`.-7. Exit. Do **not** run \`/do:push\` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.--**Hard stop:** if the loop hasn't converged after 10 iterations, post a PR comment summarising the unresolved blockers and exit. Do not loop indefinitely.--**Repeated comments:** If a new Copilot round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on to merge.--PR Details:-- **URL**: ${prUrl}-- **Branch**: \`${prBranch}\`-${prNumber !== '' ? `- **Number**: ${prNumber}` : ''}-${prOwner && prRepo ? `- **Repo**: ${prOwner}/${prRepo}` : ''}-- **Source task**: ${sourceTaskId}-${rprBody ? `\n### /do:rpr Reference (full procedure)\n\n${rprBody}\n` : ''}`;+ reviewLoopFollowUpSection = buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: true, rprBody });}// Build JIRA context section if applicable@@ -418,15 +539,17 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switchreturn promptData.prompt;}+ const taskBlock = buildTaskBlock(task, { screenshotsAsList: false });+// Fallback to built-in templatereturn `${claudeMdSection || ''}${memorySection || ''}-${task.description}+${taskBlock.description}${task.metadata?.context ? (task.metadata.context.includes('\n') ? `\n### Task Context\n\n${task.metadata.context.trimEnd()}\n` : `\n### Task Context\n\n${task.metadata.context}\n`) : ''}-${task.metadata?.app ? `**Target App**: ${task.metadata.app}` : ''}-${Array.isArray(task.metadata?.screenshots) && task.metadata.screenshots.length > 0 ? `**Screenshots**: ${task.metadata.screenshots.join(', ')}` : ''}+${taskBlock.targetApp}+${taskBlock.screenshots}${worktreeSection}${pipelineSection}${jiraSection}@@ -454,7 +577,13 @@ ${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${too- Do not make unrelated changes- If blocked, explain clearly why- Never update the PortOS changelog (\`.changelog/\`) for work on managed apps — the PortOS changelog tracks PortOS core changes only-${isTruthyMetaFn(task.metadata?.readOnly) ? `- **This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.` : isTui ? `- On successful completion, YOU run the Completion Workflow above (\`${tuiCompletionCommand}\`, write the sentinel, \`/quit\`).` : worktreeInfo && willOpenPR ? `- On successful completion, the system will push your branch and open a pull request — do NOT open a PR manually. (If the task fails, no PR is opened; the worktree is then cleaned up unless a safety check preserves it for manual recovery.)${willReviewLoop ? ' For GitHub PRs, a Copilot code review will also be requested automatically (skipped on GitLab and other non-GitHub forges) — do NOT run \`/do:rpr\` or attempt to address review comments yourself; you will have already exited.' : ''}` : worktreeInfo ? `- Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.` : ``}+${(() => {+ const bullet = buildCompletionGuidelineBullet({+ isReadOnly: isTruthyMetaFn(task.metadata?.readOnly),+ isTui, tuiCompletionCommand, worktreeInfo, willOpenPR, willReviewLoop,+ });+ return bullet ? `- ${bullet}` : '';+})()}## Git Hygiene (CRITICAL)- **Before starting work**, run \`git status\` to verify a clean working tree. Do NOT stash or discard uncommitted changes — other agents may be working concurrently and expecting those changes to be present. If the tree is dirty, only commit files YOU changed for this task.@@ -506,9 +635,10 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrut// --- Task block --------------------------------------------------------// cwd is set by the spawner and the agent knows its own id from the// runner, so the prompt skips that metadata. Target app is kept because- // it scopes managed-app work.- sections.push(task.description);- if (task.metadata?.app) sections.push(`**Target App**: ${task.metadata.app}`);+ // it scopes managed-app work. Shared with the full path via buildTaskBlock.+ const taskBlock = buildTaskBlock(task, { screenshotsAsList: true });+ sections.push(taskBlock.description);+ if (taskBlock.targetApp) sections.push(taskBlock.targetApp);const context = task.metadata?.context;if (context) {@@ -517,12 +647,7 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrut: `### Context\n${context}`);}- if (Array.isArray(task.metadata?.screenshots) && task.metadata.screenshots.length > 0) {- sections.push(- '### Screenshots\nUse your filesystem tools to inspect each path:\n' +- task.metadata.screenshots.map(s => `- \`${s}\``).join('\n')- );- }+ if (taskBlock.screenshots) sections.push(taskBlock.screenshots);// --- Worktree ----------------------------------------------------------if (worktreeInfo) {@@ -565,33 +690,7 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrutif (isReadOnly) {sections.push('## Read-Only Task\nDo NOT commit, push, or modify any files. Read data and report findings only.');} else if (isReviewLoopFollowUp) {- const prUrl = task.metadata?.reviewLoopPRUrl || '';- const prBranch = task.metadata?.reviewLoopPRBranch || '';- const prNumber = task.metadata?.reviewLoopPRNumber ?? '';- const prOwner = task.metadata?.reviewLoopPROwner ?? '';- const prRepo = task.metadata?.reviewLoopPRRepo ?? '';- const sourceTaskId = task.metadata?.sourceTaskId || 'unknown';- sections.push([- '## Review-Loop Follow-up (PRIMARY OBJECTIVE)',- `A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. The system has requested an initial Copilot review. Drive the review-and-fix loop to completion and merge.`,- '',- '**Loop UNTIL zero unresolved Copilot comments OR 10 iterations:**',- '1. Wait for the latest Copilot review (poll 5–15s, max 5 min per round).',- '2. If unresolved threads: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, resolve threads.',- '3. Re-request a Copilot review.',- '4. Repeat.',- '5. When clean, merge **immediately** with this exact command (flags: `--squash --delete-branch`, nothing else):',- ' ```bash',- ` gh pr merge "${prUrl}" --squash --delete-branch`,- ' ```',- prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --delete-branch\`.)` : null,- ' You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.',- `6. Confirm the merge happened before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (failing check, unresolved thread, branch protection) — fix and retry. Do NOT exit until state is \`MERGED\`.`,- '7. Exit — do NOT run `/do:push` or open a new PR.',- '',- '**Hard stop:** if not converged after 10 rounds, post a PR comment summarising blockers and exit.',- '**Repeated comments:** if a round only re-raises feedback you intentionally rejected (with a reply explaining why), treat as clean and merge.'- ].filter(Boolean).join('\n'));+ sections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false }));} else if (isTui) {sections.push(buildTuiCompletionSection({willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 57229d46fa..628b12e871 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -260,6 +260,47 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/## Completion Workflow/);});+ it('worktreeCommitGuidance: existing-branch wins over slashdo/PR — emits the review-fix push wording', () => {+ // When the worktree reuses a pre-existing PR branch (e.g. a review-loop+ // follow-up agent picking up where the prior agent left off), the agent+ // must push directly — the PR points at this branch and Copilot only+ // sees commits that are actually pushed. This branch is selected even+ // for a Claude Code CLI provider with `openPR: true`, because the PR+ // already exists; opening another one would be wrong.+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, simplify: true } }),+ '/r',+ { branchName: 'feat-x', worktreePath: '/tmp/wt', existingBranch: true },+ isTruthyMeta,+ { isTui: false, providerId: 'claude-code' });+ expect(prompt).toMatch(/## Git Worktree/);+ expect(prompt).toMatch(/\*\(pre-existing PR branch\)\*/);+ // The review-fix push wording — distinct from the slashdo/post-exit ones.+ expect(prompt).toMatch(/Commit and \*\*push\*\* any review-fix commits to this branch/);+ expect(prompt).toMatch(/git pull --rebase/);+ // And it must NOT emit the slashdo-driven Completion guidance for this branch.+ expect(prompt).not.toMatch(/the \*\*Completion\*\* section below drives the push and PR/);+ });++ it('worktreeCommitGuidance: hasSlashdo + !willOpenPR emits the push-only Completion wording', () => {+ // Claude Code CLI with a worktree but no PR (e.g. a managed-app task+ // whose flow is "push the branch, no PR"). The agent owns its own+ // /simplify + /do:push, so the worktree guidance points at the+ // Completion section's push (not the PR variant).+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: false, simplify: true } }),+ '/r',+ { branchName: 'feat-x', worktreePath: '/tmp/wt' },+ isTruthyMeta,+ { isTui: false, providerId: 'claude-code' });+ expect(prompt).toMatch(/## Git Worktree/);+ // Push-only Completion wording — NOT the "push and PR" variant.+ expect(prompt).toMatch(/the \*\*Completion\*\* section below drives the push\./);+ expect(prompt).not.toMatch(/drives the push and PR/);+ // And NOT the post-exit handoff message (that's the codex/gemini path).+ expect(prompt).not.toMatch(/The system will push and open a PR after you exit/);+ });+it('renders the pipeline block when previousStageAgentId is present', () => {const prompt = buildLightContextPrompt(makeTask({metadata: { pipeline: {diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex e520bf88f0..f31a61794d 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -18,7 +18,7 @@ import { existsSync, watch as fsWatch } from 'fs';import { join, dirname, resolve as resolvePath, sep as PATH_SEP, basename } from 'path';import { tmpdir } from 'os';import { randomUUID } from 'crypto';-import { assertSafeFilename, ensureDir, PATHS, safeJSONParse, resolveGalleryImage } from '../../lib/fileUtils.js';+import { assertSafeFilename, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { imageGenEvents } from '../imageGenEvents.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';@@ -555,21 +555,24 @@ export async function readImageSidecar(filename) {export async function listGallery() {if (!existsSync(PATHS.images)) return [];- const files = await readdir(PATHS.images);- const pngs = files.filter((f) => f.endsWith('.png'));- const items = await Promise.all(pngs.map(async (f) => {- const fullPath = join(PATHS.images, f);- const s = await stat(fullPath).catch(() => null);- if (!s) return null;- const { metadata } = await readImageSidecar(f);- return {- filename: f,- path: `/data/images/${f}`,- createdAt: metadata.createdAt || s.birthtime.toISOString(),- ...metadata,- };- }));- return items.filter(Boolean).sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));+ // requireRegularFile:false preserves the original gallery behavior — it+ // never checked isFile(), only dropped on stat failure. listLoras /+ // listMusicLibrary do filter directories; mirroring that here would be a+ // behavior change.+ const items = await listDirectoryByExtension(PATHS.images, {+ extensions: ['.png'],+ requireRegularFile: false,+ mapEntry: async (f, _fullPath, s) => {+ const { metadata } = await readImageSidecar(f);+ return {+ filename: f,+ path: `/data/images/${f}`,+ createdAt: metadata.createdAt || s.birthtime.toISOString(),+ ...metadata,+ };+ },+ });+ return items.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));}export async function deleteImage(filename) {diff --git a/server/services/loras.js b/server/services/loras.jsindex 5424fe0186..a019f67d79 100644--- a/server/services/loras.js+++ b/server/services/loras.js@@ -18,14 +18,14 @@*/import { existsSync } from 'fs';-import { link, mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'fs/promises';+import { link, mkdir, readFile, rename, rm, stat, unlink, writeFile } from 'fs/promises';import { createWriteStream } from 'fs';import { randomBytes } from 'crypto';import { Readable } from 'stream';import { pipeline } from 'stream/promises';import { basename, join } from 'path';import { ServerError } from '../lib/errorHandler.js';-import { assertSafeFilename, PATHS } from '../lib/fileUtils.js';+import { assertSafeFilename, listDirectoryByExtension, PATHS } from '../lib/fileUtils.js';import {applyDownloadToken,baseModelToRunner,@@ -89,45 +89,43 @@ export const listLoras = async () => {console.log(`⚠️ PATHS.loras exists but is not a directory: ${PATHS.loras}`);return [];}- const files = await readdir(PATHS.loras);- const safetensors = files.filter((f) => f.endsWith('.safetensors'));- const out = await Promise.all(safetensors.map(async (filename) => {- const fullPath = join(PATHS.loras, filename);- const s = await stat(fullPath).catch(() => null);- // Skip directories or other non-regular entries that happen to end in- // `.safetensors` — otherwise listLoras would surface them and deleteLora- // would later fail with EISDIR.- if (!s || !s.isFile()) return null;- const sidecar = await readSidecar(filename);- const fallbackName = filename.replace(/^lora-/, '').replace(/\.safetensors$/, '');- // Re-derive runnerFamily from civitai.baseModel at read time so- // sidecars written before a baseModelToRunner() mapping update (e.g.- // an install before 'Ernie' was a recognized base) don't permanently- // show as runnerFamily=null and leak across compat filters. Falls- // back to the stored value for legacy LoRAs without civitai metadata.- const baseModel = sidecar?.civitai?.baseModel;- const runnerFamily = baseModel- ? baseModelToRunner(baseModel)- : (sidecar?.runnerFamily || null);- return {- filename,- name: sidecar?.name || fallbackName,- sizeBytes: s.size,- installedAt: sidecar?.installedAt || s.birthtime?.toISOString?.() || null,- // sidecar fields surfaced for the picker / manager UI:- civitai: sidecar?.civitai || null,- runnerFamily,- triggerWords: sidecar?.triggerWords || [],- // Coerce non-finite values (NaN, Infinity, missing/malformed sidecar- // fields) to the default — `?? 1.0` alone wouldn't catch NaN.- recommendedScale: Number.isFinite(sidecar?.recommendedScale) ? sidecar.recommendedScale : 1.0,- // Normalize on read so already-installed LoRAs (sidecars written- // before the URL-normalize fix) also benefit without a reinstall.- previewImageUrl: normalizeCivitaiImageUrl(sidecar?.previewImageUrl) || null,- description: sidecar?.description || '',- };- }));- return out.filter(Boolean).sort((a, b) => (b.installedAt || '').localeCompare(a.installedAt || ''));+ // listDirectoryByExtension handles the readdir + extension filter + per-+ // entry stat + isFile check (so directories named `foo.safetensors` are+ // dropped before deleteLora would later trip on EISDIR).+ const out = await listDirectoryByExtension(PATHS.loras, {+ extensions: ['.safetensors'],+ mapEntry: async (filename, _fullPath, s) => {+ const sidecar = await readSidecar(filename);+ const fallbackName = filename.replace(/^lora-/, '').replace(/\.safetensors$/, '');+ // Re-derive runnerFamily from civitai.baseModel at read time so+ // sidecars written before a baseModelToRunner() mapping update (e.g.+ // an install before 'Ernie' was a recognized base) don't permanently+ // show as runnerFamily=null and leak across compat filters. Falls+ // back to the stored value for legacy LoRAs without civitai metadata.+ const baseModel = sidecar?.civitai?.baseModel;+ const runnerFamily = baseModel+ ? baseModelToRunner(baseModel)+ : (sidecar?.runnerFamily || null);+ return {+ filename,+ name: sidecar?.name || fallbackName,+ sizeBytes: s.size,+ installedAt: sidecar?.installedAt || s.birthtime?.toISOString?.() || null,+ // sidecar fields surfaced for the picker / manager UI:+ civitai: sidecar?.civitai || null,+ runnerFamily,+ triggerWords: sidecar?.triggerWords || [],+ // Coerce non-finite values (NaN, Infinity, missing/malformed sidecar+ // fields) to the default — `?? 1.0` alone wouldn't catch NaN.+ recommendedScale: Number.isFinite(sidecar?.recommendedScale) ? sidecar.recommendedScale : 1.0,+ // Normalize on read so already-installed LoRAs (sidecars written+ // before the URL-normalize fix) also benefit without a reinstall.+ previewImageUrl: normalizeCivitaiImageUrl(sidecar?.previewImageUrl) || null,+ description: sidecar?.description || '',+ };+ },+ });+ return out.sort((a, b) => (b.installedAt || '').localeCompare(a.installedAt || ''));};export const getLora = async (filename) => {diff --git a/server/services/mediaAnnotations.js b/server/services/mediaAnnotations.jsindex 50fe7ab01f..27a2971211 100644--- a/server/services/mediaAnnotations.js+++ b/server/services/mediaAnnotations.js@@ -49,8 +49,12 @@ function sanitizeAuthorEntry(raw) {}// Safety net for a stale install: migration 014 rewrites the file once, but a-// hand-edited or pre-014 file still parses correctly here.-async function liftLegacyEntry(rawEntry) {+// hand-edited or pre-014 file still parses correctly here. Identity inputs+// (`localInstanceId`, `defaultAuthorName`) are resolved ONCE per readAll() and+// passed in — when the file holds N legacy entries the previous shape paid+// N awaits on getInstanceId() + N on resolveLocalAuthorName() while every+// call returned the same value.+function liftLegacyEntry(rawEntry, { localInstanceId, defaultAuthorName }) {const isLegacy = rawEntry&& typeof rawEntry === 'object'&& !rawEntry.authors@@ -58,9 +62,8 @@ async function liftLegacyEntry(rawEntry) {if (!isLegacy) return rawEntry;const author = sanitizeAuthorEntry(rawEntry);if (!author) return null;- const instanceId = await getInstanceId().catch(() => 'unknown');- const authorName = author.authorName || await resolveLocalAuthorName().catch(() => '');- return { authors: { [instanceId]: { ...author, authorName } } };+ const authorName = author.authorName || defaultAuthorName;+ return { authors: { [localInstanceId]: { ...author, authorName } } };}async function readAll() {@@ -69,10 +72,17 @@ async function readAll() {const annotations = raw && typeof raw.annotations === 'object' && raw.annotations !== null? raw.annotations: {};+ // Resolve identity inputs ONCE for the whole file scan — every legacy entry+ // would otherwise repeat both awaits below.+ const [localInstanceId, defaultAuthorName] = await Promise.all([+ getInstanceId().catch(() => 'unknown'),+ resolveLocalAuthorName().catch(() => ''),+ ]);+ const liftCtx = { localInstanceId, defaultAuthorName };const out = {};for (const [key, value] of Object.entries(annotations)) {if (!isValidKey(key)) continue;- const lifted = await liftLegacyEntry(value);+ const lifted = liftLegacyEntry(value, liftCtx);if (!lifted || !lifted.authors || typeof lifted.authors !== 'object') continue;const authors = {};for (const [instanceId, sub] of Object.entries(lifted.authors)) {diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex b36c7af852..ca507a5333 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -223,9 +223,10 @@ export async function deleteCollection(id) {return { id };}-export async function addItem(id, item) {- // Mirror sanitizeItem so direct callers can't write a record that the- // next listCollections() would drop (silent add).+// Mirror sanitizeItem so direct callers (addItem + bulkUpdateCollectionItems)+// can't write a record that the next listCollections() would drop (silent add).+// Returns a normalized `{ kind, ref }` so callers don't re-trim.+const validateItemInput = (item) => {if (!item || !ITEM_KIND.has(item.kind)) {throw makeErr('item.kind must be "image" or "video"', ERR_VALIDATION);}@@ -233,11 +234,16 @@ export async function addItem(id, item) {if (!ref || ref.length > REF_MAX_LENGTH || ref.includes(':')) {throw makeErr('item.ref invalid (empty, too long, or contains ":")', ERR_VALIDATION);}+ return { kind: item.kind, ref };+};++export async function addItem(id, item) {+ const { kind, ref } = validateItemInput(item);const all = await listCollections();const idx = all.findIndex((c) => c.id === id);if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);const cur = all[idx];- const key = `${item.kind}:${ref}`;+ const key = `${kind}:${ref}`;if (cur.items.find((it) => itemKey(it) === key)) {throw makeErr(`Item already in collection: ${key}`, ERR_DUPLICATE);}@@ -246,7 +252,7 @@ export async function addItem(id, item) {}const merged = {...cur,- items: [...cur.items, { kind: item.kind, ref, addedAt: new Date().toISOString() }],+ items: [...cur.items, { kind, ref, addedAt: new Date().toISOString() }],updatedAt: new Date().toISOString(),};const next = [...all];@@ -256,6 +262,84 @@ export async function addItem(id, item) {return merged;}+/**+ * Bulk add/remove items in a single read-modify-write. Halves wall-clock for+ * UI "Move N items" / "select all" flows that would otherwise issue 2N+ * round-trips (one DELETE per source-collection item + one POST per+ * destination-collection item) and dodges the race window where an in-flight+ * AddItem can collide with a parallel RemoveItem on the same collection.+ *+ * `add` items use sanitizeItem rules (kind + ref); duplicates of items+ * already present are skipped silently (idempotent), matching the+ * UI's expectation that "add what isn't already there." `remove` keys+ * are `<kind>:<ref>` strings; unknown keys are silently ignored so a+ * stale UI selection can't 404 the whole batch.+ *+ * Validation rules mirror `addItem`: any invalid `add` entry throws before+ * any mutation lands. `remove` keys that aren't strings throw too.+ *+ * Returns the post-write collection plus counts: `{ collection, added, removed }`.+ */+export async function bulkUpdateCollectionItems(id, { add = [], remove = [] } = {}) {+ if (!Array.isArray(add)) throw makeErr('add must be an array', ERR_VALIDATION);+ if (!Array.isArray(remove)) throw makeErr('remove must be an array', ERR_VALIDATION);++ // Validate every `add` entry up front so a single bad item doesn't leave+ // a partially-applied batch behind.+ const cleanAdd = add.map(validateItemInput);+ for (const key of remove) {+ if (typeof key !== 'string' || !key) {+ throw makeErr('remove keys must be non-empty strings of the form "<kind>:<ref>"', ERR_VALIDATION);+ }+ }++ const all = await listCollections();+ const idx = all.findIndex((c) => c.id === id);+ if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);+ const cur = all[idx];++ const removeSet = new Set(remove);+ const remainingItems = cur.items.filter((it) => !removeSet.has(itemKey(it)));+ const removed = cur.items.length - remainingItems.length;++ // Dedupe `add` against itself AND against items that survived the removal.+ // This is intentionally tolerant — re-adding an existing item is a no-op+ // rather than an error, so a multi-select Move that overlaps with prior+ // membership stays idempotent.+ const presentKeys = new Set(remainingItems.map(itemKey));+ const now = new Date().toISOString();+ const additions = [];+ for (const { kind, ref } of cleanAdd) {+ const key = `${kind}:${ref}`;+ if (presentKeys.has(key)) continue;+ presentKeys.add(key);+ additions.push({ kind, ref, addedAt: now });+ }++ const nextItems = [...remainingItems, ...additions];+ if (nextItems.length > ITEMS_MAX) {+ throw makeErr(`Collection full (limit ${ITEMS_MAX})`, ERR_VALIDATION);+ }++ // Drop a cover that pointed at a now-removed item — matches the+ // single-item removeItem path so the cover never dangles after a batch.+ const coverKey = cur.coverKey && removeSet.has(cur.coverKey) ? null : cur.coverKey;++ const merged = {+ ...cur,+ items: nextItems,+ coverKey,+ updatedAt: now,+ };+ const next = [...all];+ next[idx] = merged;+ await writeAll(next);+ if (merged.universeId && (additions.length || removed)) {+ emitRecordUpdated('universe', merged.universeId);+ }+ return { collection: merged, added: additions.length, removed };+}+export async function removeItem(id, key) {const all = await listCollections();const idx = all.findIndex((c) => c.id === id);diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.jsindex 3b7c47e0bd..bc5cc67d13 100644--- a/server/services/mediaCollections.test.js+++ b/server/services/mediaCollections.test.js@@ -97,6 +97,89 @@ describe('mediaCollections service', () => {.rejects.toMatchObject({ code: svc.ERR_VALIDATION });});+ describe('bulkUpdateCollectionItems', () => {+ it('applies adds and removes in one write', async () => {+ const c = await svc.createCollection({ name: 'A' });+ await svc.addItem(c.id, { kind: 'image', ref: 'keep.png' });+ await svc.addItem(c.id, { kind: 'image', ref: 'drop.png' });+ const result = await svc.bulkUpdateCollectionItems(c.id, {+ add: [{ kind: 'image', ref: 'new1.png' }, { kind: 'video', ref: 'v1' }],+ remove: ['image:drop.png'],+ });+ expect(result.added).toBe(2);+ expect(result.removed).toBe(1);+ const refs = result.collection.items.map((it) => it.ref).sort();+ expect(refs).toEqual(['keep.png', 'new1.png', 'v1']);+ });++ it('is idempotent — re-adding an existing item is a no-op (not an error)', async () => {+ const c = await svc.createCollection({ name: 'A' });+ await svc.addItem(c.id, { kind: 'image', ref: 'foo.png' });+ const result = await svc.bulkUpdateCollectionItems(c.id, {+ add: [{ kind: 'image', ref: 'foo.png' }, { kind: 'image', ref: 'bar.png' }],+ });+ expect(result.added).toBe(1);+ expect(result.collection.items).toHaveLength(2);+ });++ it('silently ignores remove keys that aren\'t present', async () => {+ const c = await svc.createCollection({ name: 'A' });+ await svc.addItem(c.id, { kind: 'image', ref: 'foo.png' });+ const result = await svc.bulkUpdateCollectionItems(c.id, {+ remove: ['image:foo.png', 'image:ghost.png'],+ });+ expect(result.removed).toBe(1);+ });++ it('drops the cover when the cover item is removed', async () => {+ const c = await svc.createCollection({ name: 'A' });+ await svc.addItem(c.id, { kind: 'image', ref: 'cover.png' });+ await svc.updateCollection(c.id, { coverKey: 'image:cover.png' });+ const result = await svc.bulkUpdateCollectionItems(c.id, {+ remove: ['image:cover.png'],+ });+ expect(result.collection.coverKey).toBeNull();+ });++ it('rejects invalid item.kind without applying any partial mutation', async () => {+ const c = await svc.createCollection({ name: 'A' });+ await svc.addItem(c.id, { kind: 'image', ref: 'existing.png' });+ await expect(svc.bulkUpdateCollectionItems(c.id, {+ add: [{ kind: 'image', ref: 'ok.png' }, { kind: 'bogus', ref: 'bad.png' }],+ remove: ['image:existing.png'],+ })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });+ const after = await svc.getCollection(c.id);+ expect(after.items.map((it) => it.ref)).toEqual(['existing.png']);+ });++ it('rejects when the collection would exceed ITEMS_MAX after the merge', async () => {+ const c = await svc.createCollection({ name: 'A' });+ // Seed a collection that's already at capacity via a hand-set file+ // (faster than calling addItem 5000 times).+ const all = await svc.listCollections();+ const fat = { ...all[0], items: Array.from({ length: svc.ITEMS_MAX }, (_, i) => ({+ kind: 'image', ref: `r${i}.png`, addedAt: new Date().toISOString(),+ })) };+ fileStore.set('/mock/data/media-collections.json', { collections: [fat] });+ await expect(svc.bulkUpdateCollectionItems(c.id, {+ add: [{ kind: 'image', ref: 'overflow.png' }],+ })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });+ });++ it('throws ERR_NOT_FOUND for unknown collection id', async () => {+ await expect(svc.bulkUpdateCollectionItems('ghost', { add: [{ kind: 'image', ref: 'a.png' }] }))+ .rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });+ });++ it('rejects non-array add or remove', async () => {+ const c = await svc.createCollection({ name: 'A' });+ await expect(svc.bulkUpdateCollectionItems(c.id, { add: 'not-array' }))+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });+ await expect(svc.bulkUpdateCollectionItems(c.id, { remove: 'not-array' }))+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });+ });+ });+it('sanitizes hand-edited JSON with bogus items', async () => {fileStore.set('/mock/data/media-collections.json', {collections: [diff --git a/server/services/pipeline/audioMux.js b/server/services/pipeline/audioMux.jsindex 95d9ed2d41..ed290672bb 100644--- a/server/services/pipeline/audioMux.js+++ b/server/services/pipeline/audioMux.js@@ -14,13 +14,12 @@* beats blocking the whole stitch on an optional cosmetic step.*/-import { spawn } from 'child_process';import { join } from 'path';import { rename, unlink } from 'fs/promises';import { existsSync } from 'fs';import { randomUUID } from 'crypto';import { PATHS } from '../../lib/fileUtils.js';-import { findFfmpeg } from '../../lib/ffmpeg.js';+import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';import { statMusicTrack } from './musicLibrary.js';// 0.5 ≈ -6 dB — quiet enough to sit under dialogue once VO mixing lands@@ -72,7 +71,7 @@ export async function muxMusicBed(inputVideoPath, { musicPath, musicGain = DEFAUtmpOut,];- const result = await runFfmpeg(ffmpeg, args, { signal });+ const result = await runFfmpegProcess({ bin: ffmpeg, args, signal });if (!result.ok) {await unlink(tmpOut).catch(() => {});return result;@@ -83,34 +82,4 @@ export async function muxMusicBed(inputVideoPath, { musicPath, musicGain = DEFAUreturn { ok: true };}-function runFfmpeg(bin, args, { signal } = {}) {- return new Promise((resolve) => {- const proc = spawn(bin, args, { stdio: ['ignore', 'ignore', 'pipe'] });- let stderrTail = '';- const STDERR_TAIL_MAX = 2000;- proc.stderr.on('data', (chunk) => {- stderrTail += chunk.toString();- if (stderrTail.length > STDERR_TAIL_MAX) {- stderrTail = stderrTail.slice(-STDERR_TAIL_MAX);- }- });- proc.on('error', (err) => resolve({ ok: false, reason: `spawn failed: ${err.message}` }));- proc.on('close', (code, sig) => {- if (sig === 'SIGTERM' || sig === 'SIGKILL') {- resolve({ ok: false, reason: `cancelled (${sig})` });- return;- }- if (code !== 0) {- const tail = stderrTail.split(/\r?\n/).slice(-4).join(' | ');- resolve({ ok: false, reason: `ffmpeg exit ${code}: ${tail}` });- return;- }- resolve({ ok: true });- });- if (signal) {- signal.addEventListener('abort', () => proc.kill('SIGTERM'), { once: true });- }- });-}-export { DEFAULT_MUSIC_GAIN };diff --git a/server/services/pipeline/audioMux.test.js b/server/services/pipeline/audioMux.test.jsindex ee8e8ac114..59a955e964 100644--- a/server/services/pipeline/audioMux.test.js+++ b/server/services/pipeline/audioMux.test.js@@ -15,9 +15,16 @@ vi.mock('../../lib/fileUtils.js', async () => {});const findFfmpegMock = vi.fn();-vi.mock('../../lib/ffmpeg.js', () => ({- findFfmpeg: (...a) => findFfmpegMock(...a),-}));+// Pull the real runFfmpegProcess through — it's the helper audioMux now+// delegates to. The child_process mock below still intercepts spawn, so the+// real helper drives our fake ffmpeg.+vi.mock('../../lib/ffmpeg.js', async () => {+ const actual = await vi.importActual('../../lib/ffmpeg.js');+ return {+ ...actual,+ findFfmpeg: (...a) => findFfmpegMock(...a),+ };+});// Capture spawn so the test asserts the ffmpeg args without actually// running ffmpeg. The mock returns a fake child-process object that firesdiff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex 563fc92b35..6d1dfe2125 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -417,6 +417,50 @@ export function recomputeIssueNumbersForSeries(seriesId, fromSeasonId = null) {});}+/**+ * Reassign every issue under `(seriesId, fromSeasonId)` to `toSeasonId` in a+ * single readState → in-memory mutate → writeState → one renumber pass.+ * Used by `deleteSeason` (and any future bulk season-move flow) to collapse+ * N per-issue queueIssueWrite cycles into one — the legacy N+1 pattern was+ * `for (iss of children) await updateIssue(iss.id, { seasonId: toSeasonId }, { skipRenumber: true })`+ * which paid N readState + N writeState round-trips and N debounced re-exports+ * even with `withReexportSuppressed`.+ *+ * Returns `{ reassigned, fromSeasonId, toSeasonId }`. `toSeasonId` may be+ * `null` (un-grouped). A re-export of the parent series is emitted once, after+ * the renumber pass — callers under `withReexportSuppressed` get exactly one+ * `series:updated` event regardless of the issue count.+ */+export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null) {+ return queueIssueWrite(null, async () => {+ const state = await readState();+ let reassigned = 0;+ const now = new Date().toISOString();+ for (let i = 0; i < state.issues.length; i += 1) {+ const iss = state.issues[i];+ if (iss.seriesId !== seriesId) continue;+ if ((iss.seasonId || null) !== (fromSeasonId || null)) continue;+ // Re-sanitize through the same pipeline updateIssue uses so the+ // in-memory rewrite gets the same shape guarantees as a route PATCH.+ const merged = sanitizeIssue({+ ...iss,+ seasonId: toSeasonId,+ updatedAt: now,+ });+ if (!merged) continue;+ state.issues[i] = merged;+ reassigned += 1;+ }+ if (reassigned === 0) return { reassigned: 0, fromSeasonId, toSeasonId };+ // One renumber pass after the bulk move — the source AND destination+ // volume both reshuffled, so use the series-wide form (fromSeasonId=null).+ await renumberInline(state, seriesId, null);+ await writeState(state);+ emitRecordUpdated('series', seriesId);+ return { reassigned, fromSeasonId, toSeasonId };+ });+}+/*** Insert an issue with a caller-supplied id (used by the share-bucket importer* so re-imports of the same issue LWW-merge onto the same local row).diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex 8e345290a2..3197cf04d8 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -508,4 +508,59 @@ describe('pipeline issues service', () => {expect(stage.lines[0].characterId).toBe('chr-9');});});++ describe('bulkReassignSeason', () => {+ const setup = async () => {+ const series = await seriesSvc.createSeries({ name: 'Saga' });+ const a = await seasonsSvc.createSeason(series.id, { title: 'Vol A', number: 1 });+ const b = await seasonsSvc.createSeason(series.id, { title: 'Vol B', number: 2 });+ for (let i = 1; i <= 3; i += 1) {+ await svc.createIssue({ seriesId: series.id, seasonId: a.id, arcPosition: i, title: `A${i}` });+ }+ for (let i = 1; i <= 2; i += 1) {+ await svc.createIssue({ seriesId: series.id, seasonId: b.id, arcPosition: i, title: `B${i}` });+ }+ return { series, a, b };+ };++ it('moves every issue from one season to another and renumbers contiguously', async () => {+ const { series, a, b } = await setup();+ const result = await svc.bulkReassignSeason(series.id, a.id, b.id);+ expect(result.reassigned).toBe(3);+ const list = await svc.listIssues({ seriesId: series.id });+ const bIssues = list.filter((i) => i.seasonId === b.id);+ expect(bIssues).toHaveLength(5);+ // Numbers should be contiguous 1..5 across the (now sole) season.+ const numbers = list.map((i) => i.number).sort((x, y) => x - y);+ expect(numbers).toEqual([1, 2, 3, 4, 5]);+ });++ it('reassigning to null leaves issues un-grouped', async () => {+ const { series, a } = await setup();+ const result = await svc.bulkReassignSeason(series.id, a.id, null);+ expect(result.reassigned).toBe(3);+ const list = await svc.listIssues({ seriesId: series.id });+ const orphans = list.filter((i) => !i.seasonId);+ expect(orphans).toHaveLength(3);+ });++ it('returns { reassigned: 0 } and does not write when no issues match', async () => {+ const { series } = await setup();+ const result = await svc.bulkReassignSeason(series.id, 'sea-ghost', null);+ expect(result.reassigned).toBe(0);+ });++ it('only touches issues in the matching series — other series untouched', async () => {+ const { series, a, b } = await setup();+ const other = await seriesSvc.createSeries({ name: 'Other' });+ const otherSeason = await seasonsSvc.createSeason(other.id, { title: 'X', number: 1 });+ await svc.createIssue({ seriesId: other.id, seasonId: otherSeason.id, title: 'Other-1' });++ await svc.bulkReassignSeason(series.id, a.id, b.id);++ const otherList = await svc.listIssues({ seriesId: other.id });+ expect(otherList).toHaveLength(1);+ expect(otherList[0].seasonId).toBe(otherSeason.id);+ });+ });});diff --git a/server/services/pipeline/musicLibrary.js b/server/services/pipeline/musicLibrary.jsindex 18890be1b9..146e32b2e8 100644--- a/server/services/pipeline/musicLibrary.js+++ b/server/services/pipeline/musicLibrary.js@@ -14,11 +14,11 @@* care which one wrote the bytes.*/-import { readdir, stat, copyFile, unlink } from 'fs/promises';+import { stat, copyFile, unlink } from 'fs/promises';import { existsSync } from 'fs';import { join, extname, basename } from 'path';import { randomUUID } from 'crypto';-import { PATHS, ensureDir, assertSafeFilename } from '../../lib/fileUtils.js';+import { PATHS, ensureDir, assertSafeFilename, listDirectoryByExtension } from '../../lib/fileUtils.js';// Mirror of the sanitizer's MUSIC_SOURCES set in `services/pipeline/issues.js`.// Exported so routes don't sprinkle bare strings; `'gen'` is reserved for the@@ -97,29 +97,19 @@ export function deriveDefaultLabel(originalName) {*/export async function listMusicLibrary() {await ensureDir(PATHS.music);- let names = [];- try {- names = await readdir(PATHS.music);- } catch (err) {- if (err.code === 'ENOENT') return [];- throw err;- }- const entries = await Promise.all(- names- .filter((name) => SUPPORTED_AUDIO_EXTENSIONS.includes((extname(name) || '').toLowerCase()))- .map(async (name) => {- const full = join(PATHS.music, name);- const s = await stat(full).catch(() => null);- if (!s || !s.isFile()) return null;- return {- filename: name,- label: deriveDefaultLabel(name),- sizeBytes: s.size,- updatedAt: s.mtime.toISOString(),- };- }),- );- return entries.filter(Boolean).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));+ // listDirectoryByExtension covers readdir + ENOENT → [] + extension filter+ // + stat + isFile drop. ensureDir runs first, so ENOENT shouldn't trip+ // anyway — but the helper preserves the original safety net.+ const entries = await listDirectoryByExtension(PATHS.music, {+ extensions: [...SUPPORTED_AUDIO_EXTENSIONS],+ mapEntry: (name, _full, s) => ({+ filename: name,+ label: deriveDefaultLabel(name),+ sizeBytes: s.size,+ updatedAt: s.mtime.toISOString(),+ }),+ });+ return entries.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));}/**diff --git a/server/services/pipeline/seasons.js b/server/services/pipeline/seasons.jsindex 2966cf0abc..f380fa1d8b 100644--- a/server/services/pipeline/seasons.js+++ b/server/services/pipeline/seasons.js@@ -113,27 +113,23 @@ export async function deleteSeason(seriesId, seasonId, { reassignTo = null } = {}}// Re-point child issues first so a mid-write crash doesn't leave them- // dangling against a deleted season id. `updateIssue` is per-issue (and- // each call writes the file), so we batch-iterate; the data set is small- // (issues per series ~< 100) so the cost is bounded.- const childIssues = await issuesSvc.listIssues({ seriesId });- const reassignList = childIssues.filter((iss) => iss.seasonId === seasonId);+ // dangling against a deleted season id. `bulkReassignSeason` collapses what+ // used to be N per-issue queueIssueWrite cycles into a single readState →+ // in-memory mutate → writeState → one renumber pass.+ //+ // Each updateSeries + bulkReassignSeason still emits `emitRecordUpdated('series', …)`. Without+ // suppression those two events would schedule two debounced re-exports of the same+ // series; the exporter then logs "imageJobId not found" warnings per re-run for+ // any image jobs that have already aged out of the archive. Collapse the pair+ // into a single re-export by suppressing during the writes and emitting once+ // at the end against the final state.const merged = seasons.filter((s) => s.id !== seasonId);- // Each updateIssue + updateSeries emits `emitRecordUpdated('series', …)`. Without- // suppression a cascade of N issues would schedule N debounced re-exports of the- // same series; the exporter then logs "imageJobId not found" warnings per re-run- // for any image jobs that have already aged out of the archive. Collapse the- // cascade into a single re-export by suppressing during the writes and emitting- // once at the end against the final state.+ let reassignedIssueCount = 0;await withReexportSuppressed('series', seriesId, async () => {- for (const iss of reassignList) {- await issuesSvc.updateIssue(iss.id, { seasonId: reassignTo }, { skipRenumber: true });- }+ const result = await issuesSvc.bulkReassignSeason(seriesId, seasonId, reassignTo);+ reassignedIssueCount = result.reassigned;await seriesSvc.updateSeries(seriesId, { seasons: merged });- // One renumber pass after the bulk reassign + season removal so the loop- // doesn't pay for N per-update renumbers.- await issuesSvc.recomputeIssueNumbersForSeries(seriesId);});emitRecordUpdated('series', seriesId);- return { id: seasonId, reassignedIssueCount: reassignList.length, reassignedTo: reassignTo };+ return { id: seasonId, reassignedIssueCount, reassignedTo: reassignTo };}diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.jsindex e69520a01d..bee8f11d1b 100644--- a/server/services/pipeline/textStages.test.js+++ b/server/services/pipeline/textStages.test.js@@ -75,7 +75,7 @@ describe('pipeline text stage generator', () => {logline: 'A foundry city goes silent.',premise: 'Salt-mining city on a dying tideflat.',styleNotes: 'moebius linework',- characters: [{ name: 'Lina', description: 'foundry surveyor' }],+ characters: [{ name: 'Lina', physicalDescription: 'foundry surveyor' }],});const issue = await issuesSvc.createIssue({ seriesId: series.id, title: 'The Hush' });return { series, issue };diff --git a/server/services/settings.js b/server/services/settings.jsindex 620035307a..a9b990e65e 100644--- a/server/services/settings.js+++ b/server/services/settings.js@@ -1,9 +1,20 @@import { readFile, writeFile } from 'fs/promises';import { join } from 'path';+import { EventEmitter } from 'events';import { safeJSONParse, PATHS } from '../lib/fileUtils.js';const SETTINGS_FILE = join(PATHS.data, 'settings.json');+// Tiny pub/sub so cache holders (annotationIdentity, etc.) can invalidate on+// writes without each subscribing through socket.io. Listeners receive the+// merged settings object so they can pick fields they care about. Use a+// shared module-level emitter so duplicate imports observe the same bus.+export const settingsEvents = new EventEmitter();+// Cache holders that subscribe per-process can accumulate without bound on+// hot-reload — bump the cap so vitest's per-test re-imports don't trip the+// default-10-listeners warning.+settingsEvents.setMaxListeners(50);+const load = async () => {const raw = await readFile(SETTINGS_FILE, 'utf-8').catch(() => '{}');return safeJSONParse(raw, {});@@ -11,6 +22,7 @@ const load = async () => {const save = async (settings) => {await writeFile(SETTINGS_FILE, JSON.stringify(settings, null, 2) + '\n');+ settingsEvents.emit('settings:updated', settings);};export const getSettings = load;diff --git a/server/services/sharing/annotationIdentity.js b/server/services/sharing/annotationIdentity.jsindex 3a4beef5e9..9e580f4851 100644--- a/server/services/sharing/annotationIdentity.js+++ b/server/services/sharing/annotationIdentity.js@@ -8,18 +8,58 @@** exporter.js#resolveSourceName layers a per-bucket `displayNameOverride`* short-circuit on top of this for manifest envelopes.+ *+ * Result is memoized for `CACHE_TTL_MS` so hot annotation paths (sync flush,+ * bucket export, every setAnnotation) don't re-read settings.json off disk+ * once per call. settings.js emits `settings:updated` on every save and the+ * lazy listener invalidates the cache; the 30-second TTL covers hand-edited+ * settings.json + the brief race window before the listener attaches.+ * Callers that need a fresh read (e.g. a test asserting a just-saved value)+ * can call `invalidateGlobalDisplayNameCache()`.*/import * as os from 'os';-import { getSettings } from '../settings.js';+import { getSettings, settingsEvents } from '../settings.js';import { isStr } from '../../lib/storyBible.js';+const CACHE_TTL_MS = 30_000;+let cachedName = null;+let cachedAt = 0;+let subscribed = false;++export function invalidateGlobalDisplayNameCache() {+ cachedName = null;+ cachedAt = 0;+}++// Lazy subscription so vitest module re-imports don't accumulate listeners on+// `settingsEvents` for tests that never touch the sharing path. One listener+// per process for the in-process write event; the 30s TTL covers hand-edited+// settings.json + the brief race window between a write and the listener+// firing in another module's microtask.+const ensureSubscribed = () => {+ if (subscribed) return;+ subscribed = true;+ settingsEvents.on('settings:updated', invalidateGlobalDisplayNameCache);+};+export async function resolveGlobalDisplayName() {- const settings = await getSettings().catch(() => ({}));- if (isStr(settings?.sharingDisplayName) && settings.sharingDisplayName.trim()) {- return settings.sharingDisplayName.trim();+ ensureSubscribed();+ const now = Date.now();+ if (cachedName !== null && (now - cachedAt) < CACHE_TTL_MS) {+ return cachedName;+ }+ const settings = await getSettings().then((s) => s, () => null);+ const sharing = (settings && isStr(settings.sharingDisplayName) && settings.sharingDisplayName.trim()) || '';+ const resolved = sharing || os.userInfo().username || 'unknown';+ // Skip caching when settings.json was unreadable — otherwise a transient+ // read failure pins the OS-username fallback for 30s and masks a recovered+ // sharingDisplayName until the TTL expires.+ if (settings !== null) {+ cachedName = resolved;+ cachedAt = now;}- return os.userInfo().username || 'unknown';+ return resolved;}export const resolveLocalAuthorName = resolveGlobalDisplayName;diff --git a/server/services/sharing/buckets.test.js b/server/services/sharing/buckets.test.jsindex 50693afb63..58a90a4928 100644--- a/server/services/sharing/buckets.test.js+++ b/server/services/sharing/buckets.test.js@@ -3,6 +3,7 @@ import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { vi } from 'vitest';+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';let tempRoot;let bucketTargetDir;@@ -10,12 +11,7 @@ let bucketTargetDir;// Mock PATHS so the registry writes into a temp dir per test.vi.mock('../../lib/fileUtils.js', async () => {const actual = await vi.importActual('../../lib/fileUtils.js');- return new Proxy(actual, {- get(target, prop) {- if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };- return target[prop];- },- });+ return makePathsProxy(actual, { dataRoot: () => tempRoot });});const buckets = await import('./buckets.js');diff --git a/server/services/sharing/manifest.test.js b/server/services/sharing/manifest.test.jsindex 8997e054d1..578402e5ee 100644--- a/server/services/sharing/manifest.test.js+++ b/server/services/sharing/manifest.test.js@@ -3,17 +3,13 @@ import { mkdtempSync, rmSync, existsSync, writeFileSync, readdirSync, mkdirSyncimport { tmpdir } from 'os';import { join } from 'path';import { vi } from 'vitest';+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';let tempRoot;vi.mock('../../lib/fileUtils.js', async () => {const actual = await vi.importActual('../../lib/fileUtils.js');- return new Proxy(actual, {- get(target, prop) {- if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };- return target[prop];- },- });+ return makePathsProxy(actual, { dataRoot: () => tempRoot });});const manifest = await import('./manifest.js');diff --git a/server/services/writersRoom/characters.test.js b/server/services/writersRoom/characters.test.jsindex 724f5cce17..f373883c7c 100644--- a/server/services/writersRoom/characters.test.js+++ b/server/services/writersRoom/characters.test.js@@ -2,17 +2,13 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdtempSync, rmSync, existsSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';let tempRoot;vi.mock('../../lib/fileUtils.js', async () => {const actual = await vi.importActual('../../lib/fileUtils.js');- return new Proxy(actual, {- get(target, prop) {- if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };- return target[prop];- },- });+ return makePathsProxy(actual, { dataRoot: () => tempRoot });});const local = await import('./local.js');diff --git a/server/services/writersRoom/local.test.js b/server/services/writersRoom/local.test.jsindex 103a26a0b9..54f60ca57f 100644--- a/server/services/writersRoom/local.test.js+++ b/server/services/writersRoom/local.test.js@@ -2,19 +2,13 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdtempSync, rmSync, existsSync, readFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';let tempRoot;vi.mock('../../lib/fileUtils.js', async () => {const actual = await vi.importActual('../../lib/fileUtils.js');- return new Proxy(actual, {- get(target, prop) {- if (prop === 'PATHS') {- return { ...actual.PATHS, data: tempRoot };- }- return target[prop];- },- });+ return makePathsProxy(actual, { dataRoot: () => tempRoot });});const local = await import('./local.js');diff --git a/server/services/writersRoom/objects.test.js b/server/services/writersRoom/objects.test.jsindex 5eda67eea0..e556a0e8c1 100644--- a/server/services/writersRoom/objects.test.js+++ b/server/services/writersRoom/objects.test.js@@ -2,17 +2,13 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdtempSync, rmSync, existsSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';let tempRoot;vi.mock('../../lib/fileUtils.js', async () => {const actual = await vi.importActual('../../lib/fileUtils.js');- return new Proxy(actual, {- get(target, prop) {- if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };- return target[prop];- },- });+ return makePathsProxy(actual, { dataRoot: () => tempRoot });});const local = await import('./local.js');diff --git a/server/services/writersRoom/promoteToPipeline.test.js b/server/services/writersRoom/promoteToPipeline.test.jsindex b21a2ae5b8..c4ea1c0886 100644--- a/server/services/writersRoom/promoteToPipeline.test.js+++ b/server/services/writersRoom/promoteToPipeline.test.js@@ -2,17 +2,13 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdtempSync, rmSync, existsSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';let tempRoot;vi.mock('../../lib/fileUtils.js', async () => {const actual = await vi.importActual('../../lib/fileUtils.js');- return new Proxy(actual, {- get(target, prop) {- if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };- return target[prop];- },- });+ return makePathsProxy(actual, { dataRoot: () => tempRoot });});const wrLocal = await import('./local.js');diff --git a/server/services/writersRoom/settings.test.js b/server/services/writersRoom/settings.test.jsindex 83910312ad..99e67cbd36 100644--- a/server/services/writersRoom/settings.test.js+++ b/server/services/writersRoom/settings.test.js@@ -2,17 +2,13 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdtempSync, rmSync, existsSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';let tempRoot;vi.mock('../../lib/fileUtils.js', async () => {const actual = await vi.importActual('../../lib/fileUtils.js');- return new Proxy(actual, {- get(target, prop) {- if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };- return target[prop];- },- });+ return makePathsProxy(actual, { dataRoot: () => tempRoot });});const local = await import('./local.js');