Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: detect duplicate-named universes on the Universes page with inline merge (#493)

[._.]/ Adam Eivy732bfd6ed4ba
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8a6cde8bd2..5c2c295abd 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,7 +10,7 @@ TBD
- **Writers Room Guide.** A new deep-linkable documentation page at `/writers-room/guide` (reachable via a "Guide" link in the Writers Room header and from `⌘K` / voice). It documents the literary length ladder — Microfiction, Flash Fiction, Standard Short Story, Novelette, plus Novella/Novel for context — with both word and character bands, a page-based book-length estimate table (200/300 pages), and craft principles grouped by structure, character, prose, and revision. The length targets and principles live in a single canonical data module (`client/src/lib/writingGuide.js`, with a `classifyByWordCount()` helper) so forthcoming editor analyses — including the planned **emotional-roadmap evaluator** that charts the reader's emotional journey beat by beat — read the same source the docs render from.
- **Sync hygiene: duplicate resolution + a non-blocking edit-conflict journal.** Because two PortOS installs (or two machines federated as peers, or two copies of a `data/` folder synced through Google Drive/Dropbox) can each independently create a Universe or Series with the same name — and records are keyed by random id, not name — sync used to leave silent duplicates (e.g. two "Clandestiny" universes) and silently discard the loser whenever both sides edited the same record. Two new tabs under **Sharing** fix this:
- - **Duplicates** — finds same-named-but-different-id Universes (and Series, scoped within their universe) and offers to **Merge** (smart field-union: canon, categories, variations, influences, and render history are unioned; genuinely-conflicting fields are resolved field-by-field via a side-by-side diff; child series/issues and media collections are re-pointed to the survivor; the loser is tombstoned and propagated to peers) or **Rename** one to keep both.
+ - **Duplicates** — finds same-named-but-different-id Universes (and Series, scoped within their universe) and offers to **Merge** (smart field-union: canon, categories, variations, influences, and render history are unioned; genuinely-conflicting fields are resolved field-by-field via a side-by-side diff; child series/issues and media collections are re-pointed to the survivor; the loser is tombstoned and propagated to peers) or **Rename** one to keep both. The same detection + merge is also surfaced **inline on the Universes page** — when two universes share a name a warning banner appears at the top of the list with the same Merge / Rename / Keep-both controls, so a duplicate that slipped past sync time can be resolved without leaving the page.
- **Conflicts** — when a cross-install last-write-wins merge would overwrite a record both sides edited, the losing version is now archived to a local conflict journal instead of vanishing. Review the diff and **Restore mine**, **Merge** specific fields back, or **Discard**. Convergence is never blocked — peers still agree on the LWW winner; no edit is lost.
Both surfaces are deep-linkable (`/sharing/duplicates`, `/sharing/conflicts`) and reachable from ⌘K / voice.
diff --git a/client/src/components/sharing/DuplicateGroup.jsx b/client/src/components/sharing/DuplicateGroup.jsx
new file mode 100644
index 0000000000..62b76fa844
--- /dev/null
+++ b/client/src/components/sharing/DuplicateGroup.jsx
@@ -0,0 +1,89 @@
+/**
+ * One group of same-named-but-different-id duplicate records (Universes or
+ * Series in a universe). Renders each copy with its counts + an inline rename,
+ * plus group-level "Merge…" and "Keep both" actions. Shared between Sharing →
+ * Duplicates (DuplicatesTab) and the inline resolver on the Universes page.
+ */
+
+import { useEffect, useState } from 'react';
+import { GitMerge, Pencil, Check, X, Copy } from 'lucide-react';
+import toast from '../ui/Toast';
+import { updateUniverse, updatePipelineSeries } from '../../services/api';
+
+export default function DuplicateGroup({ kind, label, group, onMerge, onRenamed, onKeepBoth }) {
+ return (
+ <div className="border border-port-border rounded-lg p-4 bg-port-card">
+ <div className="flex items-center justify-between mb-3">
+ <h3 className="text-sm font-medium text-white flex items-center gap-2">
+ <Copy size={14} className="text-port-warning" /> {label}: <span className="text-port-warning">{group.records[0].name}</span>
+ <span className="text-xs text-gray-500">({group.records.length} copies)</span>
+ </h3>
+ <div className="flex items-center gap-2">
+ <button type="button" onClick={() => onMerge(kind, group.records)}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent hover:bg-port-accent/90 text-white text-xs font-medium">
+ <GitMerge size={13} /> Merge…
+ </button>
+ <button type="button" onClick={onKeepBoth}
+ className="px-2.5 py-1.5 rounded border border-port-border text-gray-400 hover:text-white text-xs">
+ Keep both
+ </button>
+ </div>
+ </div>
+ <div className="space-y-2">
+ {group.records.map((r) => <RecordRow key={r.id} kind={kind} record={r} onRenamed={onRenamed} />)}
+ </div>
+ </div>
+ );
+}
+
+function RecordRow({ kind, record, onRenamed }) {
+ const [editing, setEditing] = useState(false);
+ const [name, setName] = useState(record.name);
+ const [busy, setBusy] = useState(false);
+
+ // Keep the editable name in sync with the prop after a rename + reload so
+ // reopening the inline editor never shows the stale initial value. Only when
+ // not actively editing, so we don't clobber the user's in-progress text.
+ useEffect(() => {
+ if (!editing) setName(record.name);
+ }, [record.name, editing]);
+
+ const save = async () => {
+ if (!name.trim() || name === record.name) { setEditing(false); return; }
+ setBusy(true);
+ const update = kind === 'universe' ? updateUniverse : updatePipelineSeries;
+ const ok = await update(record.id, { name: name.trim() }, { silent: true })
+ .then(() => true).catch((err) => { toast.error(`Rename failed: ${err.message}`); return false; });
+ setBusy(false);
+ if (ok) { toast.success('Renamed'); setEditing(false); onRenamed(); }
+ };
+
+ const counts = record.counts;
+ return (
+ <div className="flex items-center justify-between gap-3 text-xs bg-port-bg border border-port-border rounded px-3 py-2">
+ <div className="min-w-0 flex-1">
+ {editing ? (
+ <div className="flex items-center gap-2">
+ <input autoFocus value={name} onChange={(e) => setName(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') save(); if (e.key === 'Escape') setEditing(false); }}
+ className="flex-1 px-2 py-1 bg-port-card border border-port-border rounded text-white" />
+ <button type="button" onClick={save} disabled={busy} className="text-port-success hover:opacity-80"><Check size={14} /></button>
+ <button type="button" onClick={() => { setEditing(false); setName(record.name); }} className="text-gray-500 hover:text-white"><X size={14} /></button>
+ </div>
+ ) : (
+ <div className="flex items-center gap-2">
+ <span className="text-white truncate">{record.name}</span>
+ <button type="button" onClick={() => setEditing(true)} className="text-gray-500 hover:text-white" title="Rename"><Pencil size={12} /></button>
+ </div>
+ )}
+ <div className="text-gray-500 mt-0.5 font-mono truncate">{record.id}</div>
+ </div>
+ <div className="text-gray-400 text-right whitespace-nowrap">
+ {counts && <div>{counts.characters}c · {counts.places}p · {counts.objects}o · {counts.categories} cats</div>}
+ {kind === 'universe' && <div>{record.linkedSeriesCount} series · {record.linkedCollectionItemCount} media</div>}
+ {kind === 'series' && <div>{record.seasonCount} seasons{record.hasArc ? ' · arc' : ''}</div>}
+ <div className="text-[10px]">updated {record.updatedAt?.slice(0, 10)}</div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/sharing/DuplicatesTab.jsx b/client/src/components/sharing/DuplicatesTab.jsx
index df18294de0..257693fb34 100644
--- a/client/src/components/sharing/DuplicatesTab.jsx
+++ b/client/src/components/sharing/DuplicatesTab.jsx
@@ -3,23 +3,18 @@
* that cross-install sync produced, and lets the user MERGE (smart field-union
* + cascade) or RENAME one to disambiguate. "Keep both" hides the group for the
* session (the records are legitimately distinct).
+ *
+ * The merge flow itself lives in shared pieces so the Universes page can offer
+ * the same resolution inline: `useRecordMerge` (orchestration), `MergeModal`
+ * (conflict picker), and `DuplicateGroup` (per-group rows + rename).
*/
import { useEffect, useState, useCallback } from 'react';
-import { Loader2, GitMerge, Pencil, Check, X, Copy } from 'lucide-react';
-import toast from '../ui/Toast';
-import Modal from '../ui/Modal';
-import InlineDiff from '../ui/InlineDiff';
-import {
- listUniverseDuplicates, listSeriesDuplicates,
- previewUniverseMerge, mergeUniverses, previewSeriesMerge, mergeSeries,
- updateUniverse, updatePipelineSeries,
-} from '../../services/api';
-
-const asText = (v) => {
- if (v === null || v === undefined) return '';
- return typeof v === 'string' ? v : JSON.stringify(v, null, 2);
-};
+import { Loader2 } from 'lucide-react';
+import { listUniverseDuplicates, listSeriesDuplicates } from '../../services/api';
+import { useRecordMerge } from '../../hooks/useRecordMerge';
+import DuplicateGroup from './DuplicateGroup';
+import MergeModal from './MergeModal';
export default function DuplicatesTab() {
const [loading, setLoading] = useState(true);
@@ -27,7 +22,6 @@ export default function DuplicatesTab() {
const [seriesGroups, setSeriesGroups] = useState([]);
const [orphanCount, setOrphanCount] = useState(0);
const [dismissed, setDismissed] = useState(() => new Set());
- const [merge, setMerge] = useState(null); // { kind, records, survivorId, loserId, preview, choices, busy }
const load = useCallback(async () => {
setLoading(true);
@@ -43,50 +37,9 @@ export default function DuplicatesTab() {
useEffect(() => { load(); }, [load]);
- const groupKey = (kind, normalizedName, scope = '') => `${kind}:${scope}:${normalizedName}`;
-
- const openMerge = async (kind, records) => {
- const survivorId = records[0].id;
- const loserId = records[1].id;
- setMerge({ kind, records, survivorId, loserId, preview: null, choices: {}, busy: true });
- await runPreview(kind, survivorId, loserId, records);
- };
+ const { merge, setMerge, openMerge, runPreview, executeMerge } = useRecordMerge({ onMerged: load });
- const runPreview = async (kind, survivorId, loserId, records) => {
- // Commit the new survivor/loser ids and invalidate the current preview up
- // front so a quick "Merge" click during the in-flight request can't run with
- // stale ids/choices (the Merge button gates on `busy || !preview`).
- setMerge((m) => (m ? {
- ...m, kind, survivorId, loserId, records: records || m.records, preview: null, choices: {}, busy: true,
- } : m));
- const preview = (kind === 'universe' ? previewUniverseMerge : previewSeriesMerge);
- const result = await preview({ survivorId, loserId }, { silent: true }).catch((err) => {
- toast.error(`Preview failed: ${err.message}`);
- return null;
- });
- setMerge((m) => (m ? {
- ...m, kind, survivorId, loserId, records: records || m.records, preview: result,
- // Default each conflicting field to the survivor's value.
- choices: Object.fromEntries((result?.conflicts || []).map((c) => [c.field, 'survivor'])),
- busy: false,
- } : m));
- };
-
- const executeMerge = async () => {
- const { kind, survivorId, loserId, choices } = merge;
- setMerge((m) => ({ ...m, busy: true }));
- const run = kind === 'universe' ? mergeUniverses : mergeSeries;
- const ok = await run({ survivorId, loserId, fieldChoices: choices }, { silent: true })
- .then(() => true)
- .catch((err) => { toast.error(`Merge failed: ${err.message}`); return false; });
- if (ok) {
- toast.success('Merged — the duplicate was folded in and tombstoned.');
- setMerge(null);
- await load();
- } else {
- setMerge((m) => (m ? { ...m, busy: false } : m));
- }
- };
+ const groupKey = (kind, normalizedName, scope = '') => `${kind}:${scope}:${normalizedName}`;
if (loading) {
return <div className="flex items-center gap-2 text-gray-400 text-sm py-8"><Loader2 className="animate-spin" size={16} /> Scanning for duplicates…</div>;
@@ -135,177 +88,3 @@ export default function DuplicatesTab() {
</div>
);
}
-
-function DuplicateGroup({ kind, label, group, onMerge, onRenamed, onKeepBoth }) {
- return (
- <div className="border border-port-border rounded-lg p-4 bg-port-card">
- <div className="flex items-center justify-between mb-3">
- <h3 className="text-sm font-medium text-white flex items-center gap-2">
- <Copy size={14} className="text-port-warning" /> {label}: <span className="text-port-warning">{group.records[0].name}</span>
- <span className="text-xs text-gray-500">({group.records.length} copies)</span>
- </h3>
- <div className="flex items-center gap-2">
- <button type="button" onClick={() => onMerge(kind, group.records)}
- className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent hover:bg-port-accent/90 text-white text-xs font-medium">
- <GitMerge size={13} /> Merge…
- </button>
- <button type="button" onClick={onKeepBoth}
- className="px-2.5 py-1.5 rounded border border-port-border text-gray-400 hover:text-white text-xs">
- Keep both
- </button>
- </div>
- </div>
- <div className="space-y-2">
- {group.records.map((r) => <RecordRow key={r.id} kind={kind} record={r} onRenamed={onRenamed} />)}
- </div>
- </div>
- );
-}
-
-function RecordRow({ kind, record, onRenamed }) {
- const [editing, setEditing] = useState(false);
- const [name, setName] = useState(record.name);
- const [busy, setBusy] = useState(false);
-
- // Keep the editable name in sync with the prop after a rename + reload so
- // reopening the inline editor never shows the stale initial value. Only when
- // not actively editing, so we don't clobber the user's in-progress text.
- useEffect(() => {
- if (!editing) setName(record.name);
- }, [record.name, editing]);
-
- const save = async () => {
- if (!name.trim() || name === record.name) { setEditing(false); return; }
- setBusy(true);
- const update = kind === 'universe' ? updateUniverse : updatePipelineSeries;
- const ok = await update(record.id, { name: name.trim() }, { silent: true })
- .then(() => true).catch((err) => { toast.error(`Rename failed: ${err.message}`); return false; });
- setBusy(false);
- if (ok) { toast.success('Renamed'); setEditing(false); onRenamed(); }
- };
-
- const counts = record.counts;
- return (
- <div className="flex items-center justify-between gap-3 text-xs bg-port-bg border border-port-border rounded px-3 py-2">
- <div className="min-w-0 flex-1">
- {editing ? (
- <div className="flex items-center gap-2">
- <input autoFocus value={name} onChange={(e) => setName(e.target.value)}
- onKeyDown={(e) => { if (e.key === 'Enter') save(); if (e.key === 'Escape') setEditing(false); }}
- className="flex-1 px-2 py-1 bg-port-card border border-port-border rounded text-white" />
- <button type="button" onClick={save} disabled={busy} className="text-port-success hover:opacity-80"><Check size={14} /></button>
- <button type="button" onClick={() => { setEditing(false); setName(record.name); }} className="text-gray-500 hover:text-white"><X size={14} /></button>
- </div>
- ) : (
- <div className="flex items-center gap-2">
- <span className="text-white truncate">{record.name}</span>
- <button type="button" onClick={() => setEditing(true)} className="text-gray-500 hover:text-white" title="Rename"><Pencil size={12} /></button>
- </div>
- )}
- <div className="text-gray-500 mt-0.5 font-mono truncate">{record.id}</div>
- </div>
- <div className="text-gray-400 text-right whitespace-nowrap">
- {counts && <div>{counts.characters}c · {counts.places}p · {counts.objects}o · {counts.categories} cats</div>}
- {kind === 'universe' && <div>{record.linkedSeriesCount} series · {record.linkedCollectionItemCount} media</div>}
- {kind === 'series' && <div>{record.seasonCount} seasons{record.hasArc ? ' · arc' : ''}</div>}
- <div className="text-[10px]">updated {record.updatedAt?.slice(0, 10)}</div>
- </div>
- </div>
- );
-}
-
-function MergeModal({ merge, setMerge, onExecute, onRepreview }) {
- const { kind, records, survivorId, loserId, preview, choices, busy } = merge;
- const conflicts = preview?.conflicts || [];
- const cascade = preview?.cascade || {};
- const multi = records.length > 2; // 3+ copies fold one pair at a time
-
- const setChoice = (field, val) => setMerge((m) => ({ ...m, choices: { ...m.choices, [field]: val } }));
- const swapSurvivor = (newSurvivorId) => {
- // Keep the current loser unless it collides with the new survivor, then
- // pick the first remaining record so survivor and loser always differ.
- const keepLoser = loserId !== newSurvivorId && records.some((r) => r.id === loserId);
- const newLoser = keepLoser ? loserId : records.find((r) => r.id !== newSurvivorId)?.id;
- onRepreview(newSurvivorId, newLoser);
- };
- const loser = records.find((r) => r.id === loserId);
-
- return (
- <Modal open onClose={() => !busy && setMerge(null)} size="2xl" ariaLabel="Merge duplicates">
- <div className="p-5 space-y-4">
- <h2 className="text-lg font-semibold text-white flex items-center gap-2"><GitMerge size={18} /> Merge {kind}</h2>
-
- <div>
- <label className="block text-xs text-gray-400 mb-1">Keep (survivor)</label>
- <div className="grid gap-2">
- {records.map((r) => (
- <label key={r.id} className={`flex items-center gap-2 px-3 py-2 rounded border cursor-pointer text-sm ${r.id === survivorId ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400'}`}>
- <input type="radio" name="survivor" checked={r.id === survivorId} onChange={() => swapSurvivor(r.id)} />
- <span className="truncate">{r.name} <span className="font-mono text-[10px] text-gray-500">{r.id.slice(0, 12)}</span></span>
- {r.id === loserId && <span className="ml-auto text-[10px] text-port-error">→ folds in</span>}
- </label>
- ))}
- </div>
- </div>
-
- {multi ? (
- <div>
- <label className="block text-xs text-gray-400 mb-1">Fold in (this merge folds one copy at a time — repeat for the rest)</label>
- <div className="grid gap-2">
- {records.filter((r) => r.id !== survivorId).map((r) => (
- <label key={r.id} className={`flex items-center gap-2 px-3 py-2 rounded border cursor-pointer text-sm ${r.id === loserId ? 'border-port-error/60 bg-port-error/10 text-white' : 'border-port-border text-gray-400'}`}>
- <input type="radio" name="loser" checked={r.id === loserId} onChange={() => onRepreview(survivorId, r.id)} />
- <span className="truncate">{r.name} <span className="font-mono text-[10px] text-gray-500">{r.id.slice(0, 12)}</span></span>
- </label>
- ))}
- </div>
- </div>
- ) : (
- <p className="text-xs text-gray-500">Folding in &amp; tombstoning <span className="text-port-error">{loser?.name}</span> <span className="font-mono text-[10px]">{loser?.id.slice(0, 12)}</span>.</p>
- )}
-
- {busy && !preview && <div className="flex items-center gap-2 text-gray-400 text-sm"><Loader2 className="animate-spin" size={14} /> Building preview…</div>}
-
- {preview && conflicts.length > 0 && (
- <div>
- <label className="block text-xs text-gray-400 mb-2">{conflicts.length} conflicting field(s) — pick which value wins:</label>
- <div className="space-y-3">
- {conflicts.map((c) => (
- <div key={c.field} className="border border-port-border rounded p-3">
- <div className="flex items-center justify-between mb-2">
- <span className="text-xs font-medium text-white">{c.field}</span>
- <div className="flex gap-1 text-[11px]">
- <button type="button" onClick={() => setChoice(c.field, 'survivor')} className={`px-2 py-0.5 rounded ${choices[c.field] === 'survivor' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400'}`}>Keep survivor</button>
- <button type="button" onClick={() => setChoice(c.field, 'loser')} className={`px-2 py-0.5 rounded ${choices[c.field] === 'loser' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400'}`}>Use folded</button>
- </div>
- </div>
- <InlineDiff oldText={asText(c.survivorValue)} newText={asText(c.loserValue)} />
- </div>
- ))}
- </div>
- </div>
- )}
-
- {preview && conflicts.length === 0 && (
- <div className="text-xs text-port-success">No conflicting fields — unique data from both will be unioned.</div>
- )}
-
- {preview && (
- <div className="text-xs text-gray-400 border-t border-port-border pt-3">
- Cascade: {kind === 'universe'
- ? `${cascade.seriesToRepoint?.length || 0} child series re-pointed · ${cascade.loserCollectionItemCount || 0} media items folded`
- : `${cascade.issuesToRepoint || 0} issues re-pointed · ${cascade.loserCollectionItemCount || 0} media items folded`}
- </div>
- )}
-
- <div className="flex justify-end gap-2 pt-2">
- <button type="button" onClick={() => setMerge(null)} disabled={busy} className="px-3 py-2 rounded border border-port-border text-gray-300 text-sm">Cancel</button>
- <button type="button" onClick={onExecute} disabled={busy || !preview || survivorId === loserId}
- className="inline-flex items-center gap-2 px-3 py-2 rounded bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium disabled:opacity-50">
- {busy ? <Loader2 className="animate-spin" size={14} /> : <GitMerge size={14} />} Merge
- </button>
- </div>
- </div>
- </Modal>
- );
-}
diff --git a/client/src/components/sharing/MergeModal.jsx b/client/src/components/sharing/MergeModal.jsx
new file mode 100644
index 0000000000..10d15ccf23
--- /dev/null
+++ b/client/src/components/sharing/MergeModal.jsx
@@ -0,0 +1,114 @@
+/**
+ * Merge modal for duplicate Universes / Series. Renders the survivor picker,
+ * the per-field conflict resolver (survivor vs. folded value), and the cascade
+ * summary, then fires the merge. Driven entirely by the `merge` state object
+ * managed by `useRecordMerge` — shared between Sharing → Duplicates
+ * (DuplicatesTab) and the inline resolver on the Universes page.
+ */
+
+import { Loader2, GitMerge } from 'lucide-react';
+import Modal from '../ui/Modal';
+import InlineDiff from '../ui/InlineDiff';
+
+// Conflict values can be strings or structured (arrays/objects). Render strings
+// as-is so InlineDiff can word-diff them; pretty-print everything else.
+const asText = (v) => {
+ if (v === null || v === undefined) return '';
+ return typeof v === 'string' ? v : JSON.stringify(v, null, 2);
+};
+
+export default function MergeModal({ merge, setMerge, onExecute, onRepreview }) {
+ const { kind, records, survivorId, loserId, preview, choices, busy } = merge;
+ const conflicts = preview?.conflicts || [];
+ const cascade = preview?.cascade || {};
+ const multi = records.length > 2; // 3+ copies fold one pair at a time
+
+ const setChoice = (field, val) => setMerge((m) => ({ ...m, choices: { ...m.choices, [field]: val } }));
+ const swapSurvivor = (newSurvivorId) => {
+ // Keep the current loser unless it collides with the new survivor, then
+ // pick the first remaining record so survivor and loser always differ.
+ const keepLoser = loserId !== newSurvivorId && records.some((r) => r.id === loserId);
+ const newLoser = keepLoser ? loserId : records.find((r) => r.id !== newSurvivorId)?.id;
+ onRepreview(newSurvivorId, newLoser);
+ };
+ const loser = records.find((r) => r.id === loserId);
+
+ return (
+ <Modal open onClose={() => !busy && setMerge(null)} size="2xl" ariaLabel="Merge duplicates">
+ <div className="p-5 space-y-4">
+ <h2 className="text-lg font-semibold text-white flex items-center gap-2"><GitMerge size={18} /> Merge {kind}</h2>
+
+ <div>
+ <label className="block text-xs text-gray-400 mb-1">Keep (survivor)</label>
+ <div className="grid gap-2">
+ {records.map((r) => (
+ <label key={r.id} className={`flex items-center gap-2 px-3 py-2 rounded border cursor-pointer text-sm ${r.id === survivorId ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400'}`}>
+ <input type="radio" name="survivor" checked={r.id === survivorId} onChange={() => swapSurvivor(r.id)} />
+ <span className="truncate">{r.name} <span className="font-mono text-[10px] text-gray-500">{r.id.slice(0, 12)}</span></span>
+ {r.id === loserId && <span className="ml-auto text-[10px] text-port-error">→ folds in</span>}
+ </label>
+ ))}
+ </div>
+ </div>
+
+ {multi ? (
+ <div>
+ <label className="block text-xs text-gray-400 mb-1">Fold in (this merge folds one copy at a time — repeat for the rest)</label>
+ <div className="grid gap-2">
+ {records.filter((r) => r.id !== survivorId).map((r) => (
+ <label key={r.id} className={`flex items-center gap-2 px-3 py-2 rounded border cursor-pointer text-sm ${r.id === loserId ? 'border-port-error/60 bg-port-error/10 text-white' : 'border-port-border text-gray-400'}`}>
+ <input type="radio" name="loser" checked={r.id === loserId} onChange={() => onRepreview(survivorId, r.id)} />
+ <span className="truncate">{r.name} <span className="font-mono text-[10px] text-gray-500">{r.id.slice(0, 12)}</span></span>
+ </label>
+ ))}
+ </div>
+ </div>
+ ) : (
+ <p className="text-xs text-gray-500">Folding in &amp; tombstoning <span className="text-port-error">{loser?.name}</span> <span className="font-mono text-[10px]">{loser?.id.slice(0, 12)}</span>.</p>
+ )}
+
+ {busy && !preview && <div className="flex items-center gap-2 text-gray-400 text-sm"><Loader2 className="animate-spin" size={14} /> Building preview…</div>}
+
+ {preview && conflicts.length > 0 && (
+ <div>
+ <label className="block text-xs text-gray-400 mb-2">{conflicts.length} conflicting field(s) — pick which value wins:</label>
+ <div className="space-y-3">
+ {conflicts.map((c) => (
+ <div key={c.field} className="border border-port-border rounded p-3">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs font-medium text-white">{c.field}</span>
+ <div className="flex gap-1 text-[11px]">
+ <button type="button" onClick={() => setChoice(c.field, 'survivor')} className={`px-2 py-0.5 rounded ${choices[c.field] === 'survivor' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400'}`}>Keep survivor</button>
+ <button type="button" onClick={() => setChoice(c.field, 'loser')} className={`px-2 py-0.5 rounded ${choices[c.field] === 'loser' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400'}`}>Use folded</button>
+ </div>
+ </div>
+ <InlineDiff oldText={asText(c.survivorValue)} newText={asText(c.loserValue)} />
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {preview && conflicts.length === 0 && (
+ <div className="text-xs text-port-success">No conflicting fields — unique data from both will be unioned.</div>
+ )}
+
+ {preview && (
+ <div className="text-xs text-gray-400 border-t border-port-border pt-3">
+ Cascade: {kind === 'universe'
+ ? `${cascade.seriesToRepoint?.length || 0} child series re-pointed · ${cascade.loserCollectionItemCount || 0} media items folded`
+ : `${cascade.issuesToRepoint || 0} issues re-pointed · ${cascade.loserCollectionItemCount || 0} media items folded`}
+ </div>
+ )}
+
+ <div className="flex justify-end gap-2 pt-2">
+ <button type="button" onClick={() => setMerge(null)} disabled={busy} className="px-3 py-2 rounded border border-port-border text-gray-300 text-sm">Cancel</button>
+ <button type="button" onClick={onExecute} disabled={busy || !preview || survivorId === loserId}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium disabled:opacity-50">
+ {busy ? <Loader2 className="animate-spin" size={14} /> : <GitMerge size={14} />} Merge
+ </button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index c94933ee62..ef0ec2cf01 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -95,6 +95,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useDeathClock` | 1-second countdown for death-clock display. | Mortality / death-clock surfaces. |
| `useNextEvalCountdown` | 1-second countdown to the next CoS evaluation tick. | Chief of Staff "next eval in Xs" displays. |
| `usePostSession` | Post-render callback scheduling. | Generic post-action chaining. |
+| `useRecordMerge` | Duplicate Universe/Series merge flow: open → dry-run preview → resolve field conflicts → execute, with an `onMerged` refresh callback. Drives `<MergeModal>`. | Surfacing the merge-duplicates UI anywhere (Sharing → Duplicates, Universes page). Don't re-implement the preview/execute dance. |
| `useProviderModels` | AI providers + two-step provider→model selection. | Any UI that picks a provider + model. |
| `useTheme` | Dark/light theme + paired-theme switching. | Theme picker. |
| `useSyncIntegrity` | Fetches per-kind integrity diff from every eligible online peer; reduces to worst-case `statusById` + `byPeer` breakdown maps. | Federated media sync integrity UI — badges, drawers, peer breakdown. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index b72d4c13be..f2a45d5fd0 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -76,6 +76,7 @@ export * from './useAppOperation.js';
export * from './useCityData.js';
export * from './useDeathClock.js';
export * from './usePostSession.js';
+export * from './useRecordMerge.js';
export * from './useSyncIntegrity.js';
export * from './useUniverseNav.js';
export * from './useVoiceUiSync.js';
diff --git a/client/src/hooks/useRecordMerge.js b/client/src/hooks/useRecordMerge.js
new file mode 100644
index 0000000000..85f705b022
--- /dev/null
+++ b/client/src/hooks/useRecordMerge.js
@@ -0,0 +1,72 @@
+import { useState, useCallback } from 'react';
+import toast from '../components/ui/Toast';
+import {
+ previewUniverseMerge, mergeUniverses, previewSeriesMerge, mergeSeries,
+} from '../services/api';
+
+// Orchestrates the duplicate-record merge flow (Universe or Series): open →
+// dry-run preview → resolve field conflicts → execute. The returned `merge`
+// state object drives <MergeModal>; `openMerge`/`runPreview`/`executeMerge`
+// are the handlers it (and the trigger button) call. `onMerged` runs after a
+// successful merge so the caller can refresh its list (the loser is tombstoned).
+//
+// Shared between Sharing → Duplicates (DuplicatesTab) and the inline resolver
+// on the Universes page so both surface identical merge behavior.
+//
+// Usage:
+// const { merge, setMerge, openMerge, runPreview, executeMerge } =
+// useRecordMerge({ onMerged: reload });
+// <DuplicateGroup kind="universe" group={g} onMerge={openMerge} ... />
+// {merge && <MergeModal merge={merge} setMerge={setMerge}
+// onExecute={executeMerge}
+// onRepreview={(s, l) => runPreview(merge.kind, s, l, merge.records)} />}
+export function useRecordMerge({ onMerged } = {}) {
+ // { kind, records, survivorId, loserId, preview, choices, busy }
+ const [merge, setMerge] = useState(null);
+
+ const runPreview = useCallback(async (kind, survivorId, loserId, records) => {
+ // Commit the new survivor/loser ids and invalidate the current preview up
+ // front so a quick "Merge" click during the in-flight request can't run with
+ // stale ids/choices (the Merge button gates on `busy || !preview`).
+ setMerge((m) => (m ? {
+ ...m, kind, survivorId, loserId, records: records || m.records, preview: null, choices: {}, busy: true,
+ } : m));
+ const previewFn = kind === 'universe' ? previewUniverseMerge : previewSeriesMerge;
+ const result = await previewFn({ survivorId, loserId }, { silent: true }).catch((err) => {
+ toast.error(`Preview failed: ${err.message}`);
+ return null;
+ });
+ setMerge((m) => (m ? {
+ ...m, kind, survivorId, loserId, records: records || m.records, preview: result,
+ // Default each conflicting field to the survivor's value.
+ choices: Object.fromEntries((result?.conflicts || []).map((c) => [c.field, 'survivor'])),
+ busy: false,
+ } : m));
+ }, []);
+
+ const openMerge = useCallback(async (kind, records) => {
+ const survivorId = records[0].id;
+ const loserId = records[1].id;
+ setMerge({ kind, records, survivorId, loserId, preview: null, choices: {}, busy: true });
+ await runPreview(kind, survivorId, loserId, records);
+ }, [runPreview]);
+
+ const executeMerge = useCallback(async () => {
+ if (!merge) return;
+ const { kind, survivorId, loserId, choices } = merge;
+ setMerge((m) => (m ? { ...m, busy: true } : m));
+ const run = kind === 'universe' ? mergeUniverses : mergeSeries;
+ const ok = await run({ survivorId, loserId, fieldChoices: choices }, { silent: true })
+ .then(() => true)
+ .catch((err) => { toast.error(`Merge failed: ${err.message}`); return false; });
+ if (ok) {
+ toast.success('Merged — the duplicate was folded in and tombstoned.');
+ setMerge(null);
+ await onMerged?.();
+ } else {
+ setMerge((m) => (m ? { ...m, busy: false } : m));
+ }
+ }, [merge, onMerged]);
+
+ return { merge, setMerge, openMerge, runPreview, executeMerge };
+}
diff --git a/client/src/pages/Universes.jsx b/client/src/pages/Universes.jsx
index 8def207774..39a2bf0141 100644
--- a/client/src/pages/Universes.jsx
+++ b/client/src/pages/Universes.jsx
@@ -8,17 +8,20 @@
* `/universes/new`.
*/
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo, useState, useCallback } from 'react';
import { Link, useNavigate } from 'react-router-dom';
-import { Plus, Globe, Trash2, Users, Workflow as WorkflowIcon } from 'lucide-react';
+import { Plus, Globe, Trash2, Users, Workflow as WorkflowIcon, Copy } from 'lucide-react';
import toast from '../components/ui/Toast';
import ShareToButton from '../components/sharing/ShareToButton';
import SyncToPeerButton from '../components/sharing/SyncToPeerButton';
import OriginBadge from '../components/sharing/OriginBadge';
import SyncBadge from '../components/sync/SyncBadge';
+import DuplicateGroup from '../components/sharing/DuplicateGroup';
+import MergeModal from '../components/sharing/MergeModal';
import { timeAgo } from '../utils/formatters';
-import { listUniverses, deleteUniverse, listPipelineSeries, listMediaCollections } from '../services/api';
+import { listUniverses, deleteUniverse, listPipelineSeries, listMediaCollections, listUniverseDuplicates } from '../services/api';
import { useSyncIntegrity, syncBadgeStatus } from '../hooks/useSyncIntegrity';
+import { useRecordMerge } from '../hooks/useRecordMerge';
// Named canon entities across all trunks — the "Canon" column reflects the
// characters/places/objects the user has registered, not the looser variation
@@ -98,9 +101,22 @@ export default function Universes() {
const [series, setSeries] = useState([]);
const [latestImageByUniverse, setLatestImageByUniverse] = useState(() => new Map());
const [loading, setLoading] = useState(true);
+ // Same-named-but-different-id universes (e.g. cross-install sync produced two
+ // "Clandestiny"s). Surfaced as a banner so the user can merge them here even
+ // when it wasn't caught at sync time. Mirrors Sharing → Duplicates, scoped to
+ // universes. `dismissedDupes` hides a group for the session ("Keep both").
+ const [duplicateGroups, setDuplicateGroups] = useState([]);
+ const [dismissedDupes, setDismissedDupes] = useState(() => new Set());
const sync = useSyncIntegrity('universe');
+ const loadDuplicates = useCallback(
+ () => listUniverseDuplicates({ silent: true })
+ .then((d) => setDuplicateGroups(Array.isArray(d?.groups) ? d.groups : []))
+ .catch(() => {}),
+ [],
+ );
+
useEffect(() => {
// Guard setState against a navigate-away before the fetch resolves —
// mirrors the editor's load effect (UniverseBuilder.jsx).
@@ -137,8 +153,35 @@ export default function Universes() {
if (cancelled) return;
setLatestImageByUniverse(buildLatestImageByUniverse(cols));
});
+ // Duplicate detection is on-demand (computed server-side from the live
+ // universe set), independent of the list/joins above.
+ loadDuplicates();
return () => { cancelled = true; };
- }, []);
+ }, [loadDuplicates]);
+
+ // Re-fetch after a merge or rename: the loser is tombstoned (so it drops from
+ // the list), its child series are re-pointed (series counts shift), and its
+ // media folds into the survivor (thumbnails shift). Re-scan duplicates last so
+ // a folded group disappears from the banner.
+ const refresh = useCallback(() => {
+ listUniverses({ silent: true })
+ .then((u) => setUniverses(Array.isArray(u) ? u : []))
+ .catch((err) => toast.error(err.message || 'Failed to reload universes'));
+ listPipelineSeries({ silent: true })
+ .then((s) => setSeries(Array.isArray(s) ? s : []))
+ .catch(() => {});
+ listMediaCollections({ silent: true })
+ .then((cols) => setLatestImageByUniverse(buildLatestImageByUniverse(cols)))
+ .catch(() => {});
+ return loadDuplicates();
+ }, [loadDuplicates]);
+
+ const { merge, setMerge, openMerge, runPreview, executeMerge } = useRecordMerge({ onMerged: refresh });
+
+ // "Keep both" hides a group for the session; the records are legitimately
+ // distinct. Filtered against the live group list so a newly-merged group that
+ // re-fetches away is simply gone (no stale dismissal lingering).
+ const visibleDupes = duplicateGroups.filter((g) => !dismissedDupes.has(g.normalizedName));
// universeId → linked-series count. Reverse of the join Pipeline.jsx does
// (series carry universeId; here we tally per universe).
@@ -197,6 +240,25 @@ export default function Universes() {
pipeline series and batch render inherits. Build one here, then link series to it from the Series Pipeline.
</p>
+ {visibleDupes.length > 0 && (
+ <div className="mb-6 border border-port-warning/40 bg-port-warning/10 rounded-lg p-4 space-y-3">
+ <div className="flex items-center gap-2 text-sm text-port-warning font-medium">
+ <Copy size={16} aria-hidden="true" />
+ <span>
+ {visibleDupes.length} duplicate-named {visibleDupes.length === 1 ? 'universe' : 'universes'} detected.
+ Merge folds one copy into the other — unioning canon, re-pointing series, and tombstoning the duplicate.
+ </span>
+ </div>
+ {visibleDupes.map((g) => (
+ <DuplicateGroup
+ key={g.normalizedName} kind="universe" label="Universe" group={g}
+ onMerge={openMerge} onRenamed={refresh}
+ onKeepBoth={() => setDismissedDupes((s) => new Set(s).add(g.normalizedName))}
+ />
+ ))}
+ </div>
+ )}
+
{loading ? (
<div className="text-gray-500 text-sm">Loading universes…</div>
) : universes.length === 0 ? (
@@ -293,6 +355,13 @@ export default function Universes() {
</ul>
</>
)}
+
+ {merge && (
+ <MergeModal
+ merge={merge} setMerge={setMerge} onExecute={executeMerge}
+ onRepreview={(survivorId, loserId) => runPreview(merge.kind, survivorId, loserId, merge.records)}
+ />
+ )}
</div>
);
}
diff --git a/client/src/pages/Universes.test.jsx b/client/src/pages/Universes.test.jsx
new file mode 100644
index 0000000000..60b9ba055b
--- /dev/null
+++ b/client/src/pages/Universes.test.jsx
@@ -0,0 +1,105 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router-dom';
+
+// The page pulls in network-y siblings (sync integrity hook, share/sync peer
+// buttons) that fetch on mount. Stub them so the test only exercises the
+// duplicate-detection banner + merge flow added here.
+vi.mock('../services/api', () => ({
+ listUniverses: vi.fn(),
+ deleteUniverse: vi.fn(),
+ listPipelineSeries: vi.fn(),
+ listMediaCollections: vi.fn(),
+ listUniverseDuplicates: vi.fn(),
+ previewUniverseMerge: vi.fn(),
+ mergeUniverses: vi.fn(),
+ previewSeriesMerge: vi.fn(),
+ mergeSeries: vi.fn(),
+ updateUniverse: vi.fn(),
+ updatePipelineSeries: vi.fn(),
+}));
+vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+vi.mock('../components/ui/Modal', () => ({ default: ({ open, children }) => (open ? <div role="dialog">{children}</div> : null) }));
+vi.mock('../components/ui/InlineDiff', () => ({ default: ({ oldText, newText }) => <div data-testid="diff">{oldText}|{newText}</div> }));
+vi.mock('../hooks/useSyncIntegrity', () => ({ useSyncIntegrity: () => ({}), syncBadgeStatus: () => 'unknown' }));
+vi.mock('../components/sharing/ShareToButton', () => ({ default: () => null }));
+vi.mock('../components/sharing/SyncToPeerButton', () => ({ default: () => null }));
+vi.mock('../components/sync/SyncBadge', () => ({ default: () => null }));
+
+import * as api from '../services/api';
+import Universes from './Universes';
+
+const dupGroup = {
+ normalizedName: 'clandestiny',
+ records: [
+ { id: 'u-new', name: 'Clandestiny', updatedAt: '2026-05-22T00:00:00Z', counts: { characters: 5, places: 2, objects: 1, categories: 4 }, linkedSeriesCount: 1, linkedCollectionItemCount: 3 },
+ { id: 'u-old', name: 'Clandestiny', updatedAt: '2026-05-11T00:00:00Z', counts: { characters: 1, places: 0, objects: 0, categories: 4 }, linkedSeriesCount: 0, linkedCollectionItemCount: 0 },
+ ],
+};
+
+const renderPage = () => render(<MemoryRouter><Universes /></MemoryRouter>);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.listUniverses.mockResolvedValue([
+ { id: 'u-new', name: 'Clandestiny', createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z' },
+ { id: 'u-old', name: 'Clandestiny', createdAt: '2026-05-11T00:00:00Z', updatedAt: '2026-05-11T00:00:00Z' },
+ ]);
+ api.listPipelineSeries.mockResolvedValue([]);
+ api.listMediaCollections.mockResolvedValue([]);
+ api.listUniverseDuplicates.mockResolvedValue({ groups: [dupGroup] });
+});
+
+describe('Universes page — duplicate detection', () => {
+ it('shows a banner when duplicate-named universes are detected', async () => {
+ renderPage();
+ await waitFor(() => expect(screen.getByText(/1 duplicate-named universe detected/)).toBeInTheDocument());
+ expect(screen.getByText(/2 copies/)).toBeInTheDocument();
+ });
+
+ it('hides the banner when no duplicates exist', async () => {
+ api.listUniverseDuplicates.mockResolvedValue({ groups: [] });
+ renderPage();
+ await waitFor(() => expect(screen.getByText('Universes')).toBeInTheDocument());
+ expect(screen.queryByText(/duplicate-named/)).not.toBeInTheDocument();
+ });
+
+ it('opens the merge modal, previews, executes with field choices, and re-scans', async () => {
+ api.previewUniverseMerge.mockResolvedValue({
+ conflicts: [{ field: 'starterPrompt', survivorValue: 'A', loserValue: 'B' }],
+ cascade: { seriesToRepoint: [{ id: 's1' }], loserCollectionItemCount: 3 },
+ });
+ api.mergeUniverses.mockResolvedValue({ merged: true });
+ // After the merge tombstones the loser, the re-scan returns no duplicates.
+ api.listUniverseDuplicates
+ .mockResolvedValueOnce({ groups: [dupGroup] })
+ .mockResolvedValue({ groups: [] });
+
+ const user = userEvent.setup();
+ renderPage();
+ await waitFor(() => expect(screen.getByText(/2 copies/)).toBeInTheDocument());
+
+ await user.click(screen.getByRole('button', { name: /Merge…/ }));
+ await waitFor(() => expect(api.previewUniverseMerge).toHaveBeenCalledWith({ survivorId: 'u-new', loserId: 'u-old' }, expect.anything()));
+ await waitFor(() => expect(screen.getByText('starterPrompt')).toBeInTheDocument());
+ expect(screen.getByText(/child series re-pointed/)).toBeInTheDocument();
+
+ await user.click(screen.getByRole('button', { name: /^Merge$/ }));
+ await waitFor(() => expect(api.mergeUniverses).toHaveBeenCalledWith(
+ { survivorId: 'u-new', loserId: 'u-old', fieldChoices: { starterPrompt: 'survivor' } },
+ expect.anything(),
+ ));
+ // Banner clears after the re-scan finds nothing.
+ await waitFor(() => expect(screen.queryByText(/duplicate-named/)).not.toBeInTheDocument());
+ });
+
+ it('dismisses a group via "Keep both" for the session', async () => {
+ const user = userEvent.setup();
+ renderPage();
+ await waitFor(() => expect(screen.getByText(/duplicate-named/)).toBeInTheDocument());
+
+ await user.click(screen.getByRole('button', { name: /Keep both/ }));
+ await waitFor(() => expect(screen.queryByText(/duplicate-named/)).not.toBeInTheDocument());
+ });
+});