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

17.2 KB
Raw Blame
/**
 * Universes page — universe index.
 *
 * Lists every universe (the long-lived style/canon parent that pipeline series
 * inherit from) in a table and lets the user create, open, or delete any of
 * them. Mirrors the Series Pipeline index (`Pipeline.jsx`): the heavy editor
 * lives at `/universes/:id`, and `New Universe` drops into a blank editor at
 * `/universes/new`.
 */

import { useEffect, useMemo, useState, useCallback } from 'react';
import { Link, useNavigate } from 'react-router';
import { Plus, Globe, Trash2, Users, Workflow as WorkflowIcon, Copy, BadgeCheck } from 'lucide-react';
import PageHeader from '../components/PageHeader';
import toast from '../components/ui/Toast';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
import ImageThumb from '../components/ui/ImageThumb';
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 ListLoadError from '../components/ui/ListLoadError';
import MergeModal from '../components/sharing/MergeModal';
import { timeAgo } from '../utils/formatters';
import { listUniverseSummaries, deleteUniverse, listPipelineSeriesSummaries, listMediaCollections, listUniverseDuplicates } from '../services/api';
import { useSyncIntegrity, syncBadgeStatus } from '../hooks/useSyncIntegrity';
import { useRecordMerge } from '../hooks/useRecordMerge';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
import useListResource from '../hooks/useListResource';

// Chip on a universe whose `factual` flag is set (#7616): its people and
// places are real, so captured text is extracted as lived record rather than
// as invented story material. Rendered beside the name in both list layouts.
const FactualBadge = () => (
  <span
    className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-port-accent/15 text-port-accent border border-port-accent/30"
    title="Real-world universe — captured text is read as lived record, not invented story material"
  >
    <BadgeCheck size={10} />
    Real
  </span>
);

// Build universeId → latest image filename from media collections. Mirrors
// resolveCover() in MediaCollections.jsx but trimmed: we only care about image
// items (videos don't render as a row thumbnail here) and the bucket is
// already identified by `collection.universeId`, so coverKey-pinning + cross-
// gallery lookup are unnecessary — items are already keyed to /data/images.
// Single O(n) pass per collection to avoid O(n log n) on near-ITEMS_MAX buckets.
const buildLatestImageByUniverse = (collections) => {
  const out = new Map();
  for (const c of collections || []) {
    if (!c?.universeId) continue;
    let bestRef = null;
    let bestTs = -Infinity;
    for (const it of c.items || []) {
      if (it.kind !== 'image') continue;
      const ts = new Date(it.addedAt || 0).getTime();
      if (ts > bestTs) { bestTs = ts; bestRef = it.ref; }
    }
    if (bestRef) out.set(c.universeId, bestRef);
  }
  return out;
};

// 48px square thumbnail showing the universe's base style image, falling back
// to the latest image from its auto-managed media collection, then a Globe
// placeholder when neither exists (or hasn't loaded yet). The shared ImageThumb
// hides the <img> on error so a stale ref pointing at a deleted file falls back
// to the placeholder instead of a broken-image icon. Used by desktop row + card.
function UniverseThumb({ imageRef }) {
  return <ImageThumb imageRef={imageRef} FallbackIcon={Globe} />;
}

// Shared between the desktop table row and the mobile card so the inline-confirm
// affordance + a11y labels stay in one place. An explicit Delete?/Cancel row
// replaces the two-click-arm button once the row is armed.
function DeleteButton({ universe, confirming, onRequest, onConfirm, onCancel }) {
  const name = universe.name || '(untitled universe)';
  if (confirming) {
    return (
      <ConfirmButtonPair
        prompt="Delete?"
        ariaLabel={`Confirm delete universe ${name}`}
        onConfirm={() => onConfirm(universe)}
        onCancel={onCancel}
      />
    );
  }
  return (
    <button
      type="button"
      onClick={() => onRequest(universe.id)}
      className="p-2 text-gray-500 hover:text-port-error"
      aria-label={`Delete universe ${name}`}
      title="Delete universe"
    >
      <Trash2 size={16} />
    </button>
  );
}

export default function Universes() {
  const navigate = useNavigate();
  const fetchUniverses = useCallback(() => listUniverseSummaries({ silent: true }), []);
  const universesResource = useListResource(fetchUniverses);
  const { items: universes, setItems: setUniverses } = universesResource;
  const fetchSeries = useCallback(() => listPipelineSeriesSummaries({ silent: true }), []);
  const seriesResource = useListResource(fetchSeries);
  const { items: series } = seriesResource;
  const fetchCollections = useCallback(() => listMediaCollections({ silent: true }), []);
  const collectionsResource = useListResource(fetchCollections);
  const latestImageByUniverse = useMemo(
    () => buildLatestImageByUniverse(collectionsResource.items),
    [collectionsResource.items],
  );
  // 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(() => {
    // Duplicate detection is on-demand (computed server-side from the live
    // universe set), independent of the list/joins above.
    loadDuplicates();
  }, [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(() => {
    universesResource.retry();
    seriesResource.retry();
    collectionsResource.retry();
    return loadDuplicates();
  }, [loadDuplicates, universesResource.retry, seriesResource.retry, collectionsResource.retry]);

  const { merge, setMerge, openMerge, runPreview, executeMerge, runAIMerge, updateOverride } = 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).
  const seriesCountByUniverse = useMemo(() => {
    const m = {};
    for (const s of series) {
      if (s.universeId) m[s.universeId] = (m[s.universeId] || 0) + 1;
    }
    return m;
  }, [series]);

  // Inline delete confirm: the trash button arms the row (one at a time) and an
  // explicit Delete?/Cancel row fires it. Avoids window.confirm (banned per
  // AGENTS.md) and the non-discoverable two-click-arm pattern.
  const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
  const handleDelete = (u) => confirmDelete(async () => {
    setUniverses((prev) => prev.filter((x) => x.id !== u.id));
    // silent: the custom catch below owns the error toast (AGENTS.md).
    await deleteUniverse(u.id, { silent: true }).catch((err) => {
      toast.error(err.message || 'Delete failed');
      // Roll back only this row (re-insert if still missing) so a concurrent
      // delete's optimistic removal isn't clobbered by a stale full-list
      // snapshot. Re-sort by the server's order (createdAt desc, newest-first)
      // so the restored row lands in its original position, not at the end.
      setUniverses((prev) =>
        prev.some((x) => x.id === u.id)
          ? prev
          : [...prev, u].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || '')),
      );
    });
  });

  return (
    <div className="flex h-full min-h-0 flex-col">
      <PageHeader
        icon={Globe}
        title="Universes"
        subtitle="A universe holds the shared style, influences, and canon (characters, places, objects) that every pipeline series and batch render inherits. Build one here, then link series to it from the Series Pipeline."
        actions={(
          <Link
            to="/universes/new"
            className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium"
          >
            <Plus size={16} aria-hidden="true" />
            New Universe
          </Link>
        )}
      />
      <div className="flex-1 min-h-0 overflow-auto p-4">

      {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>
      )}

      {seriesResource.state === 'error' ? (
        <ListLoadError what="series counts" error={seriesResource.error} onRetry={seriesResource.retry} className="mb-3" />
      ) : null}
      {collectionsResource.state === 'error' ? (
        <ListLoadError what="universe thumbnails" error={collectionsResource.error} onRetry={collectionsResource.retry} className="mb-3" />
      ) : null}

      {universesResource.state === 'loading' ? (
        <div className="text-gray-500 text-sm">Loading universes…</div>
      ) : universesResource.state === 'error' ? (
        <ListLoadError what="universes" error={universesResource.error} onRetry={universesResource.retry} />
      ) : universes.length === 0 ? (
        <div className="text-gray-500 text-sm">
          No universes yet. Click <span className="text-port-accent">New Universe</span> to start.
        </div>
      ) : (
        <>
          {/* Desktop table */}
          <div className="hidden sm:block overflow-x-auto bg-port-card border border-port-border rounded-lg">
            <table className="w-full min-w-[640px]">
              <thead>
                <tr className="border-b border-port-border">
                  <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Name</th>
                  <th className="px-4 py-3 text-right text-xs font-semibold uppercase tracking-wider text-gray-500">Canon</th>
                  <th className="px-4 py-3 text-right text-xs font-semibold uppercase tracking-wider text-gray-500">Series</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Updated</th>
                  <th className="px-4 py-3 text-right text-xs font-semibold uppercase tracking-wider text-gray-500">Actions</th>
                </tr>
              </thead>
              <tbody>
                {universes.map((u) => (
                  <tr key={u.id} className="border-b border-port-border/50 last:border-0 hover:bg-port-bg/40 transition-colors">
                    <td className="px-4 py-3 align-top">
                      <div className="flex items-start gap-2 min-w-0">
                        <Link to={`/universes/${encodeURIComponent(u.id)}`} className="flex items-start gap-3 min-w-0 group flex-1">
                          <UniverseThumb imageRef={u.styleImageRef || latestImageByUniverse.get(u.id)} />
                          <div className="min-w-0 flex-1">
                            <div className="text-white font-medium flex items-center gap-2 flex-wrap group-hover:text-port-accent transition-colors">
                              <span>{u.name || '(untitled universe)'}</span>
                              {u.origin ? <OriginBadge origin={u.origin} compact /> : null}
                              {u.factual ? <FactualBadge /> : null}
                            </div>
                            {u.logline ? (
                              <div className="text-xs text-gray-500 mt-0.5 line-clamp-1 break-words">{u.logline}</div>
                            ) : null}
                          </div>
                        </Link>
                        <SyncBadge
                          status={syncBadgeStatus(sync, u.id)}
                          onClick={() => navigate(`/universes/${encodeURIComponent(u.id)}/sync`)}
                        />
                      </div>
                    </td>
                    <td className="px-4 py-3 text-right whitespace-nowrap text-sm text-gray-300 font-mono">{u.canonCount || 0}</td>
                    <td className="px-4 py-3 text-right whitespace-nowrap text-sm text-gray-300 font-mono">{seriesResource.state === 'ready' ? (seriesCountByUniverse[u.id] || 0) : '—'}</td>
                    <td className="px-4 py-3 whitespace-nowrap text-xs text-gray-500">{timeAgo(u.updatedAt || u.createdAt)}</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-1">
                        <ShareToButton kind="universe" ids={[u.id]} compact />
                        <SyncToPeerButton recordKind="universe" recordId={u.id} compact />
                        <DeleteButton universe={u} confirming={isConfirming(u.id)} onRequest={requestDelete} onConfirm={handleDelete} onCancel={cancelDelete} />
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Mobile cards */}
          <ul className="space-y-2 sm:hidden">
            {universes.map((u) => (
              <li key={u.id} className="p-3 bg-port-card border border-port-border rounded-lg">
                <div className="flex items-start justify-between gap-3">
                  <Link to={`/universes/${encodeURIComponent(u.id)}`} className="flex items-start gap-3 flex-1 min-w-0">
                    <UniverseThumb imageRef={u.styleImageRef || latestImageByUniverse.get(u.id)} />
                    <div className="min-w-0 flex-1">
                      <div className="text-white font-medium flex items-center gap-2 flex-wrap">
                        <span>{u.name || '(untitled universe)'}</span>
                        {u.origin ? <OriginBadge origin={u.origin} compact /> : null}
                        {u.factual ? <FactualBadge /> : null}
                      </div>
                      {u.logline ? (
                        <div className="text-xs text-gray-500 mt-0.5 break-words">{u.logline}</div>
                      ) : null}
                      <div className="flex items-center gap-3 mt-2 text-xs text-gray-500">
                        <span className="inline-flex items-center gap-1"><Users size={12} /> {u.canonCount || 0} canon</span>
                        <span className="inline-flex items-center gap-1"><WorkflowIcon size={12} /> {seriesResource.state === 'ready' ? (seriesCountByUniverse[u.id] || 0) : '—'} series</span>
                        <span>{timeAgo(u.updatedAt || u.createdAt)}</span>
                      </div>
                    </div>
                  </Link>
                  <DeleteButton universe={u} confirming={isConfirming(u.id)} onRequest={requestDelete} onConfirm={handleDelete} onCancel={cancelDelete} />
                </div>
                <div className="flex items-center gap-1 mt-2">
                  <ShareToButton kind="universe" ids={[u.id]} compact />
                  <SyncToPeerButton recordKind="universe" recordId={u.id} compact />
                  <SyncBadge
                    status={syncBadgeStatus(sync, u.id)}
                    onClick={() => navigate(`/universes/${encodeURIComponent(u.id)}/sync`)}
                  />
                </div>
              </li>
            ))}
          </ul>
        </>
      )}

      {merge && (
        <MergeModal
          merge={merge} setMerge={setMerge} onExecute={executeMerge}
          onRepreview={(survivorId, loserId) => runPreview(merge.kind, survivorId, loserId, merge.records)}
          onAIMerge={runAIMerge} onUpdateOverride={updateOverride}
        />
      )}
      </div>
    </div>
  );
}