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
make the Sprite Catalog a routable Library page with full record CRUD
[._.]/ Adam Eivyb18abf700fb5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9b6c06906d..55bc15aa07 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -18,7 +18,7 @@## Sprite Manager- **Seed a character's main reference from an existing sprite, an upload, or your render history — and fork a character from its reference** — the "design image (optional)" upload on the main-reference form is now a three-way **Reference image** picker: upload a file, pick one from your image render-history gallery, or pick another sprite that already has a locked reference, each with a fidelity slider controlling how tightly the render follows it (image+text→image). Separately, a locked reference is immutable and can never be regenerated — so a character with a frozen main now shows a **Fork from this reference** button that spins up a brand-new character whose main is generated from this one's reference plus a prompt describing the change ("same character but in a red coat"), then opens the new sprite. New endpoints `GET /api/sprites/reference-sources` and `POST /api/sprites/:id/fork`.-- **The Sprite Manager opens on your most recent character, with search and actions in the header** — landing on the Sprite Manager no longer shows a cold empty pane: it auto-opens the most recently touched character. Search, **New Sprite**, **Import**, and a new **Catalog** button move into the page header (New Sprite/Import are now modals), and the left sidebar is gone so the detail pane runs full width. The old "Browse all" list is replaced by a searchable, grouped **Catalog** modal for swapping which sprite is active — built to stay usable as the library grows.+- **The Sprite Manager opens on a full Library catalog, with rename and delete built in** — landing on the Sprite Manager now shows the **Library** itself: a searchable, grouped grid of every character/place/object, each card carrying a real preview thumbnail — a character's locked main reference, or, for a place/object (or a character with no reference yet), the first image asset on disk, falling back to a kind icon only when there's no image at all — instead of jumping you straight into one sprite. The catalog is the `/sprites` route (not a modal buried behind a button), so it's directly linkable, and each card gives you full record control: click to open it, the pencil to **rename** in place (for records whose generated name you want to fix), or the trash to **delete** behind a cautious inline Cancel/Delete confirm (a delete drops the record from your library; its files stay on disk and its id stays reserved). The same **rename** and **delete** controls sit in a sprite's detail header, so you can fix or remove the one you're looking at without going back to the grid (deleting it returns you there). Search, **New Sprite**, and **Import** live in the page header (New Sprite/Import are modals), the left sidebar is gone so the catalog and detail panes run full width, and opening a sprite shows a **Library** link back to the grid. The per-character workspace tab that used to read "Library" is now **Assets**, since "Library" means the catalog. New endpoint `GET /api/sprites/thumbnails`.- **Atlas manifests are folded into the atlas, not a confusing "Manifests" shelf** — a character's asset library used to show a separate **Manifests** group of near-identical JSON cards sitting apart from the sprite-sheet PNGs they describe, so it was never clear that each manifest is just the build metadata for one atlas version. Manifests are no longer their own group: a runtime atlas card gains a **Manifest** button that opens its sidecar (the geometry, chroma key, and source provenance the compiler recorded), and the inspector now says plainly that it's behind-the-scenes metadata removed together with its atlas. The other internal JSON (publish pointers, run records, the reference-set manifest) no longer appears as inert cards at all. Nothing changes on disk — manifests are still written and still deleted as a unit with their atlas version.- **Every walk direction is trimmable now, whatever produced it** — a direction whose art came from the source pipeline's older video-first "redraw" path (pioneer's *east* being the case in the wild) showed its "approved ✓" card with no **Edit in Loop Trimmer** link, because loop trimming was wired only to grok-generated runs. The Loop Trimmer now resolves any run's geometry from the run's own manifest/strip regardless of where it was authored, so imported and redraw directions are trimmable exactly like native ones — the link appears on every direction that has a packed strip. (Saved trims stay preview-only; there's no run behind them to re-trim.)- **Sprite runs are stored vendor-neutrally** — under the hood, PortOS used to file its own walk generations under a `grok/` directory, baking one provider into the on-disk layout. Runs now live under a neutral `runs/` tree with the provider recorded as run metadata instead, so future agent services or generation methods slot in without a storage change and nothing downstream (trimming, atlas compile, publish, backups) assumes a vendor. Existing installs are migrated automatically on upgrade: each character's `grok/<run>/` directories are renamed to `runs/<run>/`, every embedded path is rewritten, and the checksums that pin the finalized walk set + compiled atlas are recomputed so a re-compile stays a no-op — your published atlases are unaffected. Imported/redraw characters and the atlas image bytes are left untouched.diff --git a/client/src/components/sprites/SpriteCatalog.jsx b/client/src/components/sprites/SpriteCatalog.jsxnew file mode 100644index 0000000000..1f2bdeabd5--- /dev/null+++ b/client/src/components/sprites/SpriteCatalog.jsx@@ -0,0 +1,202 @@+/**+ * Sprite Catalog — the routable Library view of the Sprite Manager (was a modal+ * before this; the modal didn't scale and hid the library one click deep). It's+ * the default `/sprites` landing: a searchable, grouped grid of every sprite+ * with a preview thumbnail, plus per-card record CRUD — rename in place and+ * delete behind a cautious inline confirm (project convention: no+ * window.confirm, no two-click-arm — a discoverable Cancel/Delete pair).+ *+ * Picking a card navigates to `/sprites/:id`. Rename/delete call the record+ * endpoints directly and hand the result back up so the page updates its list+ * reactively (no full refetch).+ */++import { useMemo, useState } from 'react';+import {+ Search, Pencil, Trash2, Check, Package,+} from 'lucide-react';+import { groupSpriteRecords, filterSpriteRecords } from '../../lib/spriteRecordGroups.js';+import { GROUP_ICONS, groupIconForKind } from './spriteGroupIcons.js';+import SpritePreview from './SpritePreview.jsx';+import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';+import { timeAgo } from '../../utils/formatters.js';+import useSpriteRecordCrud from '../../hooks/useSpriteRecordCrud.js';++// One catalog tile. Self-contained view/rename/confirm state (via+// useSpriteRecordCrud) so a rename or delete in one card never touches its+// neighbours. In view mode the whole tile is a single open-record button with+// the two action icons as SIBLINGS in the relative wrapper (never nested+// buttons — that's invalid markup); rename and confirm swap the tile for their+// own form so no interactive element nests.+function CatalogCard({ record, thumbPath, onOpen, onRenamed, onDeleted }) {+ const {+ mode, name, setName, busy, error, cancel, startRename, startDelete, saveRename, runDelete,+ } = useSpriteRecordCrud(record, { onRenamed, onDeleted });+ const Icon = groupIconForKind(record.kind);++ if (mode === 'rename') {+ return (+ <div className="p-3 rounded-lg border border-port-accent bg-port-bg space-y-2">+ <label htmlFor={`sprite-rename-${record.id}`} className="block text-xs text-gray-400">+ Rename <span className="text-gray-300">{record.name}</span>+ </label>+ <input+ id={`sprite-rename-${record.id}`}+ type="text"+ autoFocus+ value={name}+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') saveRename(); if (e.key === 'Escape') cancel(); }}+ disabled={busy}+ className="w-full bg-port-card border border-port-border rounded px-2 py-1 text-sm text-white"+ />+ {error && <p className="text-xs text-port-error break-words">{error}</p>}+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={saveRename}+ disabled={busy}+ className="flex items-center gap-1 px-2 py-1 text-xs bg-port-accent hover:bg-blue-600 text-white rounded disabled:opacity-50"+ >+ <Check className="w-3.5 h-3.5" /> {busy ? 'Saving…' : 'Save'}+ </button>+ <button+ type="button"+ onClick={cancel}+ disabled={busy}+ className="px-2 py-1 text-xs bg-port-card border border-port-border text-gray-300 rounded hover:border-port-accent disabled:opacity-50"+ >+ Cancel+ </button>+ </div>+ </div>+ );+ }++ if (mode === 'confirm') {+ return (+ <div className="p-3 rounded-lg border border-port-error/50 bg-port-error/10 space-y-2">+ <p className="text-xs text-gray-200">+ Delete <span className="font-semibold break-words">{record.name}</span>? It leaves your+ library; the generated files stay on disk and its id stays reserved. This can’t be undone here.+ </p>+ {error && <p className="text-xs text-port-error break-words">{error}</p>}+ <ConfirmButtonPair+ confirmText="Delete"+ busyText="Deleting…"+ busy={busy}+ confirmIcon={Trash2}+ onConfirm={runDelete}+ onCancel={cancel}+ ariaLabel={`Confirm delete ${record.name}`}+ />+ </div>+ );+ }++ return (+ <div className="relative">+ <button+ type="button"+ onClick={() => onOpen(record.id)}+ className="w-full text-left rounded-lg border border-port-border bg-port-bg overflow-hidden transition-colors hover:border-gray-500"+ >+ {thumbPath ? (+ <SpritePreview+ recordId={record.id}+ path={thumbPath}+ alt=""+ cell={7}+ className="aspect-square w-full"+ imgClassName="w-full h-full object-contain"+ />+ ) : (+ <div className="aspect-square w-full flex items-center justify-center">+ <Icon className="w-10 h-10 text-gray-600" />+ </div>+ )}+ <div className="p-2 border-t border-port-border">+ <span className="block font-medium text-sm text-white truncate">{record.name}</span>+ <span className="block text-xs text-gray-500 truncate">+ {record.kind} · {record.status}{record.chromaKey ? ` · key ${record.chromaKey}` : ''}+ </span>+ <span className="block text-xs text-gray-600 truncate">+ {(record.updatedAt || record.createdAt) ? `updated ${timeAgo(record.updatedAt || record.createdAt)}` : ' '}+ </span>+ </div>+ </button>+ {/* Always-visible (not hover-gated — hover doesn't exist on touch) action+ icons in the corner, siblings of the card button so the markup stays+ valid. */}+ <div className="absolute top-1.5 right-1.5 flex gap-1">+ <button+ type="button"+ onClick={startRename}+ aria-label={`Rename ${record.name}`}+ className="p-1.5 rounded bg-port-card/90 border border-port-border text-gray-300 hover:text-white hover:border-port-accent"+ >+ <Pencil className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ onClick={startDelete}+ aria-label={`Delete ${record.name}`}+ className="p-1.5 rounded bg-port-card/90 border border-port-border text-gray-300 hover:text-port-error hover:border-port-error"+ >+ <Trash2 className="w-3.5 h-3.5" />+ </button>+ </div>+ </div>+ );+}++export default function SpriteCatalog({+ records, thumbs, onOpen, onRenamed, onDeleted,+}) {+ const [query, setQuery] = useState('');+ // Infinity limit: the sidebar picker caps suggestions at 8, but the catalog+ // is the full-library browser — every match must show.+ const filtered = useMemo(() => filterSpriteRecords(records, query, Infinity), [records, query]);+ const groups = useMemo(() => groupSpriteRecords(filtered), [filtered]);++ return (+ <div className="space-y-5">+ <div className="relative w-full sm:w-72">+ <label htmlFor="sprite-catalog-filter" className="sr-only">Filter sprites</label>+ <Search className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />+ <input+ id="sprite-catalog-filter"+ type="search"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Filter by name, id, or kind…"+ className="w-full bg-port-bg border border-port-border rounded pl-8 pr-3 py-1.5 text-sm text-white"+ />+ </div>+ {filtered.length === 0 ? (+ <p className="text-sm text-gray-500">No sprites match “{query}”.</p>+ ) : groups.map((g) => {+ const Icon = GROUP_ICONS[g.key] || Package;+ return (+ <section key={g.key}>+ <h3 className="flex items-center gap-1.5 text-xs uppercase tracking-wide text-gray-500 mb-2">+ <Icon className="w-3.5 h-3.5" /> {g.label} ({g.records.length})+ </h3>+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">+ {g.records.map((r) => (+ <CatalogCard+ key={r.id}+ record={r}+ thumbPath={thumbs?.get(r.id)}+ onOpen={onOpen}+ onRenamed={onRenamed}+ onDeleted={onDeleted}+ />+ ))}+ </div>+ </section>+ );+ })}+ </div>+ );+}diff --git a/client/src/components/sprites/SpriteCatalog.test.jsx b/client/src/components/sprites/SpriteCatalog.test.jsxnew file mode 100644index 0000000000..5938fd32a9--- /dev/null+++ b/client/src/components/sprites/SpriteCatalog.test.jsx@@ -0,0 +1,117 @@+/**+ * Sprite Catalog — the routable Library view. Covers the two record-CRUD paths+ * the modal never had: rename in place (the user has records whose generated+ * names are wrong) and delete behind a cautious inline confirm. Also pins the+ * grouped/filtered grid and that opening a card reports the id up.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import SpriteCatalog from './SpriteCatalog.jsx';++const updateSpriteRecord = vi.fn();+const deleteSpriteRecord = vi.fn();+vi.mock('../../services/apiSprites.js', () => ({+ updateSpriteRecord: (...a) => updateSpriteRecord(...a),+ deleteSpriteRecord: (...a) => deleteSpriteRecord(...a),+}));++const RECORDS = [+ { id: 'trail-hand', name: 'Trail Hand', kind: 'character', status: 'draft' },+ { id: 'bad-name-9x', name: 'sdxl_0007_final', kind: 'character', status: 'draft' },+ { id: 'saloon', name: 'Saloon', kind: 'place', status: 'imported' },+];++function renderCatalog(props = {}) {+ return render(+ <SpriteCatalog+ records={RECORDS}+ thumbs={new Map([['trail-hand', 'reference/main.png']])}+ onOpen={props.onOpen || (() => {})}+ onRenamed={props.onRenamed || (() => {})}+ onDeleted={props.onDeleted || (() => {})}+ />,+ );+}++beforeEach(() => { updateSpriteRecord.mockReset(); deleteSpriteRecord.mockReset(); });++describe('SpriteCatalog', () => {+ it('groups records and opens a card by id', async () => {+ const onOpen = vi.fn();+ renderCatalog({ onOpen });++ // Grouped headings (Characters has 2, Places has 1).+ expect(screen.getByText('Characters (2)')).toBeInTheDocument();+ expect(screen.getByText('Places (1)')).toBeInTheDocument();++ // Anchor to the start so this hits the open-card button, not its+ // "Rename …" / "Delete …" action icons.+ await userEvent.click(screen.getByRole('button', { name: /^Trail Hand/ }));+ expect(onOpen).toHaveBeenCalledWith('trail-hand');+ });++ it('filters the grid by the search box', async () => {+ renderCatalog();+ await userEvent.type(screen.getByLabelText('Filter sprites'), 'saloon');+ expect(screen.getByText('Places (1)')).toBeInTheDocument();+ expect(screen.queryByText(/Characters/)).not.toBeInTheDocument();+ });++ it('renames a record and reports the updated record up', async () => {+ const onRenamed = vi.fn();+ const updated = { id: 'bad-name-9x', name: 'Rattlesnake Kate', kind: 'character', status: 'draft' };+ updateSpriteRecord.mockResolvedValue(updated);+ renderCatalog({ onRenamed });++ await userEvent.click(screen.getByRole('button', { name: 'Rename sdxl_0007_final' }));+ const input = screen.getByRole('textbox');+ await userEvent.clear(input);+ await userEvent.type(input, 'Rattlesnake Kate');+ await userEvent.click(screen.getByRole('button', { name: /Save/ }));++ expect(updateSpriteRecord).toHaveBeenCalledWith('bad-name-9x', { name: 'Rattlesnake Kate' }, { silent: true });+ expect(onRenamed).toHaveBeenCalledWith(updated);+ });++ it('will not save an empty rename', async () => {+ renderCatalog();+ await userEvent.click(screen.getByRole('button', { name: 'Rename Saloon' }));+ const input = screen.getByRole('textbox');+ await userEvent.clear(input);+ await userEvent.click(screen.getByRole('button', { name: /Save/ }));++ expect(updateSpriteRecord).not.toHaveBeenCalled();+ expect(screen.getByText('Name can’t be empty')).toBeInTheDocument();+ });++ it('deletes only after the confirm step and reports the id up', async () => {+ const onDeleted = vi.fn();+ deleteSpriteRecord.mockResolvedValue({ deleted: true });+ renderCatalog({ onDeleted });++ // First click arms the confirm — it does NOT delete.+ await userEvent.click(screen.getByRole('button', { name: 'Delete Trail Hand' }));+ expect(deleteSpriteRecord).not.toHaveBeenCalled();+ expect(screen.getByText(/This can’t be undone/)).toBeInTheDocument();++ // Confirm.+ await userEvent.click(screen.getByRole('button', { name: /^Delete$/ }));+ expect(deleteSpriteRecord).toHaveBeenCalledWith('trail-hand', { silent: true });+ expect(onDeleted).toHaveBeenCalledWith('trail-hand');+ });++ it('cancels a delete without calling the API', async () => {+ const onDeleted = vi.fn();+ renderCatalog({ onDeleted });++ await userEvent.click(screen.getByRole('button', { name: 'Delete Saloon' }));+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));++ expect(deleteSpriteRecord).not.toHaveBeenCalled();+ expect(onDeleted).not.toHaveBeenCalled();+ // Back to the card view.+ expect(screen.getByRole('button', { name: 'Delete Saloon' })).toBeInTheDocument();+ });+});diff --git a/client/src/components/sprites/SpriteDetailHeader.jsx b/client/src/components/sprites/SpriteDetailHeader.jsxnew file mode 100644index 0000000000..b73eac0439--- /dev/null+++ b/client/src/components/sprites/SpriteDetailHeader.jsx@@ -0,0 +1,115 @@+/**+ * The header of a sprite's detail view — its name, kind/status/chroma-key/+ * import meta, and inline rename/delete controls for the record you're looking+ * at. Rename/delete share the same `useSpriteRecordCrud` state machine the+ * Library catalog cards use, so the two surfaces behave identically. Deleting+ * the open record bubbles up through `onDeleted`, which the page uses to+ * navigate back to the Library.+ */++import { Pencil, Trash2, Check } from 'lucide-react';+import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';+import { groupIconForKind } from './spriteGroupIcons.js';+import useSpriteRecordCrud from '../../hooks/useSpriteRecordCrud.js';+import { timeAgo } from '../../utils/formatters.js';++export default function SpriteDetailHeader({ record, onRenamed, onDeleted }) {+ const {+ mode, name, setName, busy, error, cancel, startRename, startDelete, saveRename, runDelete,+ } = useSpriteRecordCrud(record, { onRenamed, onDeleted });+ const Icon = groupIconForKind(record.kind);++ return (+ <div className="space-y-2">+ <div className="flex items-start gap-2">+ <Icon className="w-5 h-5 mt-1 shrink-0 text-gray-300" />+ {mode === 'rename' ? (+ <div className="flex-1 min-w-0 space-y-1">+ <label htmlFor="sprite-detail-rename" className="sr-only">Rename {record.name}</label>+ <div className="flex flex-wrap items-center gap-2">+ <input+ id="sprite-detail-rename"+ type="text"+ autoFocus+ value={name}+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') saveRename(); if (e.key === 'Escape') cancel(); }}+ disabled={busy}+ className="flex-1 min-w-0 bg-port-bg border border-port-accent rounded px-2 py-1 text-lg font-semibold text-white"+ />+ <button+ type="button"+ onClick={saveRename}+ disabled={busy}+ className="flex items-center gap-1 px-2 py-1 text-xs bg-port-accent hover:bg-blue-600 text-white rounded disabled:opacity-50"+ >+ <Check className="w-3.5 h-3.5" /> {busy ? 'Saving…' : 'Save'}+ </button>+ <button+ type="button"+ onClick={cancel}+ disabled={busy}+ className="px-2 py-1 text-xs bg-port-card border border-port-border text-gray-300 rounded hover:border-port-accent disabled:opacity-50"+ >+ Cancel+ </button>+ </div>+ {error && <p className="text-xs text-port-error break-words">{error}</p>}+ </div>+ ) : (+ <div className="flex-1 min-w-0 flex items-center gap-1.5">+ <h2 className="text-lg font-semibold text-white truncate">{record.name}</h2>+ <button+ type="button"+ onClick={startRename}+ aria-label={`Rename ${record.name}`}+ className="shrink-0 p-1 rounded text-gray-400 hover:text-white hover:bg-port-border/50"+ >+ <Pencil className="w-4 h-4" />+ </button>+ <button+ type="button"+ onClick={startDelete}+ aria-label={`Delete ${record.name}`}+ className="shrink-0 p-1 rounded text-gray-400 hover:text-port-error hover:bg-port-border/50"+ >+ <Trash2 className="w-4 h-4" />+ </button>+ </div>+ )}+ </div>+ <p className="text-xs text-gray-500">+ {record.kind} · {record.status}+ {record.chromaKey && (+ <>+ {' · chroma key '}+ <span className="inline-block w-3 h-3 rounded-sm align-middle border border-port-border" style={{ backgroundColor: record.chromaKey }} />{' '}+ {record.chromaKey}+ </>+ )}+ {record.importedFrom?.importedAt && ` · imported ${timeAgo(record.importedFrom.importedAt)}`}+ </p>+ {record.spec?.archetype && (+ <p className="text-xs text-gray-500">archetype: {record.spec.archetype}</p>+ )}+ {mode === 'confirm' && (+ <div className="p-3 rounded-lg border border-port-error/50 bg-port-error/10 space-y-2 max-w-md">+ <p className="text-xs text-gray-200">+ Delete <span className="font-semibold break-words">{record.name}</span>? It leaves your+ library; the generated files stay on disk and its id stays reserved. This can’t be undone here.+ </p>+ {error && <p className="text-xs text-port-error break-words">{error}</p>}+ <ConfirmButtonPair+ confirmText="Delete"+ busyText="Deleting…"+ busy={busy}+ confirmIcon={Trash2}+ onConfirm={runDelete}+ onCancel={cancel}+ ariaLabel={`Confirm delete ${record.name}`}+ />+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/sprites/SpriteDetailHeader.test.jsx b/client/src/components/sprites/SpriteDetailHeader.test.jsxnew file mode 100644index 0000000000..c89ae1cd11--- /dev/null+++ b/client/src/components/sprites/SpriteDetailHeader.test.jsx@@ -0,0 +1,60 @@+/**+ * SpriteDetailHeader — inline rename/delete for the sprite you're viewing.+ * Shares useSpriteRecordCrud with the catalog card, so this pins the header's+ * own wiring: the name + meta render, rename round-trips the API and reports+ * up, and delete is gated behind the confirm step.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import SpriteDetailHeader from './SpriteDetailHeader.jsx';++const updateSpriteRecord = vi.fn();+const deleteSpriteRecord = vi.fn();+vi.mock('../../services/apiSprites.js', () => ({+ updateSpriteRecord: (...a) => updateSpriteRecord(...a),+ deleteSpriteRecord: (...a) => deleteSpriteRecord(...a),+}));++const RECORD = { id: 'bad-name-9x', name: 'sdxl_0007_final', kind: 'character', status: 'draft' };++beforeEach(() => { updateSpriteRecord.mockReset(); deleteSpriteRecord.mockReset(); });++describe('SpriteDetailHeader', () => {+ it('renders the name and kind/status meta', () => {+ render(<SpriteDetailHeader record={RECORD} onRenamed={() => {}} onDeleted={() => {}} />);+ expect(screen.getByRole('heading', { name: 'sdxl_0007_final' })).toBeInTheDocument();+ expect(screen.getByText(/character · draft/)).toBeInTheDocument();+ });++ it('renames the open record and reports the update up', async () => {+ const onRenamed = vi.fn();+ const updated = { ...RECORD, name: 'Rattlesnake Kate' };+ updateSpriteRecord.mockResolvedValue(updated);+ render(<SpriteDetailHeader record={RECORD} onRenamed={onRenamed} onDeleted={() => {}} />);++ await userEvent.click(screen.getByRole('button', { name: 'Rename sdxl_0007_final' }));+ const input = screen.getByRole('textbox');+ await userEvent.clear(input);+ await userEvent.type(input, 'Rattlesnake Kate');+ await userEvent.click(screen.getByRole('button', { name: /Save/ }));++ expect(updateSpriteRecord).toHaveBeenCalledWith('bad-name-9x', { name: 'Rattlesnake Kate' }, { silent: true });+ expect(onRenamed).toHaveBeenCalledWith(updated);+ });++ it('deletes only after the confirm step and reports the id up', async () => {+ const onDeleted = vi.fn();+ deleteSpriteRecord.mockResolvedValue({ deleted: true });+ render(<SpriteDetailHeader record={RECORD} onRenamed={() => {}} onDeleted={onDeleted} />);++ await userEvent.click(screen.getByRole('button', { name: 'Delete sdxl_0007_final' }));+ expect(deleteSpriteRecord).not.toHaveBeenCalled();+ expect(screen.getByText(/This can’t be undone/)).toBeInTheDocument();++ await userEvent.click(screen.getByRole('button', { name: /^Delete$/ }));+ expect(deleteSpriteRecord).toHaveBeenCalledWith('bad-name-9x', { silent: true });+ expect(onDeleted).toHaveBeenCalledWith('bad-name-9x');+ });+});diff --git a/client/src/components/sprites/spriteGroupIcons.js b/client/src/components/sprites/spriteGroupIcons.jsnew file mode 100644index 0000000000..119f2446a1--- /dev/null+++ b/client/src/components/sprites/spriteGroupIcons.js@@ -0,0 +1,18 @@+/**+ * React-side companion to the pure `spriteRecordGroups` lib. That lib stays+ * React-free (a lib module can't import lucide components without pulling React+ * into its barrel), so the lucide mapping for the three sprite noun-groups+ * lives here instead — one shared copy for every React consumer (the Sprite+ * Manager page, the catalog, the search picker) rather than a per-file dupe.+ */++import { PersonStanding, MapPin, Package } from 'lucide-react';+import { groupKeyForKind } from '../../lib/spriteRecordGroups.js';++// Keyed by the group `key` the lib assigns (characters / places / objects).+export const GROUP_ICONS = { characters: PersonStanding, places: MapPin, objects: Package };++// Resolve a record `kind` straight to its group icon — collapses the repeated+// `GROUP_ICONS[groupKeyForKind(kind)] || Package` idiom. Package is the+// fallback for an unknown/legacy kind (mirrors the lib's Objects fold).+export const groupIconForKind = (kind) => GROUP_ICONS[groupKeyForKind(kind)] || Package;diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex d2013d7a64..1ed84e3bfc 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -41,6 +41,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useInstallStream` | BYO-runtime install-log EventSource lifecycle: `stage`/`log`/`complete`/`error` frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed `onComplete`, auto-scroll. | A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes). Don't re-roll the EventSource teardown/onComplete-ref dance. || `useModelDownloadStatus` | Image/video model cache-status + SSE pre-download. | Surfacing "Available" vs "Download" badge inline in the gen form. || `useSpritePendingRenders` | Sprite-workflow in-flight render map: queue rehydrate + 4s poll keyed by a media-job tag field, `'submitting'` double-render guard, 404-only drop, deferred `onChanged` sweeps. | A sprite workflow tracking `queued/running` media jobs by tag (reference renders, walk videos, phase-4 publish) — don't re-roll the rehydrate/poll dance. |+| `useSpriteRecordCrud` | Rename/delete state machine for one sprite record: `view`/`rename`/`confirm` mode, name draft, busy/inline-error, silent PATCH/DELETE. | A surface that renames or deletes a sprite record (the Library catalog card, the detail header) — share this so both stay in lock-step. || `useImageGenProgress` | Live diffusion progress for an image-gen call. | Showing per-call image-gen progress. || `useImporterProgress` | Live analyze-phase stage checklist via the `importer:progress` socket (runId-filtered); exports `stageStatusIcon` for the status→icon lookup. | Importer analyze progress UI only. || `useMediaJobProgress` | Live progress for a single `mediaJobQueue` job. | Subscribing to a known media-job id. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex d15100c8f9..7715f5a7d7 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -95,6 +95,7 @@ export * from './useModelDownloadStatus.js';// === Media (annotations, completion, attachments) ===export * from './useMediaAnnotations.js';export * from './useSpritePendingRenders.js';+export { default as useSpriteRecordCrud } from './useSpriteRecordCrud.js';export * from './useMediaCompletionRefresh.js';export * from './useOpenClawAttachments.js';diff --git a/client/src/hooks/useSpriteRecordCrud.js b/client/src/hooks/useSpriteRecordCrud.jsnew file mode 100644index 0000000000..1739e366e4--- /dev/null+++ b/client/src/hooks/useSpriteRecordCrud.js@@ -0,0 +1,49 @@+import { useState } from 'react';+import { updateSpriteRecord, deleteSpriteRecord } from '../services/apiSprites.js';++/**+ * Rename/delete state machine for a single sprite record, shared by the Library+ * catalog card and the Sprite Manager detail header so the two surfaces stay in+ * lock-step (same endpoints, same silent-toast + inline-error contract). The+ * caller owns the markup; this owns the mode/name/busy/error state and the two+ * mutations.+ *+ * `mode` is `'view' | 'rename' | 'confirm'`. `onRenamed` receives the updated+ * record; `onDeleted` receives the id. Both calls pass `{ silent: true }` (the+ * caller renders inline errors), so a failure sets `error` and stays in its+ * mode rather than toasting. On a successful delete the caller typically drops+ * the record from its list and unmounts this — so `busy` is only cleared on+ * failure, matching the catalog card's original behaviour.+ */+export default function useSpriteRecordCrud(record, { onRenamed, onDeleted } = {}) {+ const [mode, setMode] = useState('view');+ const [name, setName] = useState(record.name || '');+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState(null);++ const cancel = () => { setMode('view'); setError(null); };+ const startRename = () => { setName(record.name || ''); setError(null); setMode('rename'); };+ const startDelete = () => { setError(null); setMode('confirm'); };++ const saveRename = () => {+ const trimmed = name.trim();+ if (!trimmed) { setError('Name can’t be empty'); return; }+ if (trimmed === record.name) { cancel(); return; }+ setBusy(true);+ setError(null);+ updateSpriteRecord(record.id, { name: trimmed }, { silent: true })+ .then((updated) => { onRenamed?.(updated); setMode('view'); })+ .catch((err) => setError(err?.message || 'Rename failed'))+ .finally(() => setBusy(false));+ };++ const runDelete = () => {+ setBusy(true);+ setError(null);+ deleteSpriteRecord(record.id, { silent: true })+ .then(() => onDeleted?.(record.id))+ .catch((err) => { setError(err?.message || 'Delete failed'); setBusy(false); });+ };++ return { mode, name, setName, busy, error, cancel, startRename, startDelete, saveRename, runDelete };+}diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex d978024ffc..1be16d4fee 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -1,11 +1,11 @@import { useEffect, useState, useCallback, useMemo, useRef } from 'react';import { useParams, useNavigate, useSearchParams } from 'react-router-dom';-import { PersonStanding, MapPin, Package, Download, X, RefreshCw, Plus, LayoutGrid, Search, Images, Scissors } from 'lucide-react';+import { PersonStanding, Download, X, RefreshCw, Plus, LayoutGrid, Search, Images, Scissors } from 'lucide-react';import toast from '../components/ui/Toast';import Modal from '../components/ui/Modal.jsx';import {listSpriteRecords, getSpriteRecord, importSprites, createSpriteRecord,- generateSpriteWalk, generateSpriteReference,+ generateSpriteWalk, generateSpriteReference, listSpriteThumbnails,} from '../services/apiSprites.js';import { getApps } from '../services/apiApps.js';import { getSettings } from '../services/apiSystem.js';@@ -16,35 +16,16 @@ import WalkWorkflow, { WALK_DURATIONS } from '../components/sprites/WalkWorkflowimport LoopTrimmer from '../components/sprites/LoopTrimmer.jsx';import PublishWorkflow from '../components/sprites/PublishWorkflow.jsx';import AssetCollection from '../components/sprites/AssetCollection.jsx';+import SpriteCatalog from '../components/sprites/SpriteCatalog.jsx';+import SpriteDetailHeader from '../components/sprites/SpriteDetailHeader.jsx';import TabPills from '../components/ui/TabPills.jsx';import useDrawerTab from '../hooks/useDrawerTab.js';import useClickOutside from '../hooks/useClickOutside.js';import { useAsyncAction } from '../hooks/useAsyncAction.js';import { useSpritePendingRenders } from '../hooks/useSpritePendingRenders.js';import { buildCollectionActions } from '../lib/spriteCollectionActions.js';-import {- groupSpriteRecords, filterSpriteRecords, groupKeyForKind, NEW_SPRITE_KINDS,-} from '../lib/spriteRecordGroups.js';-import { timeAgo } from '../utils/formatters.js';--// Per-group sidebar icons — the pure grouping lib keys each group; the page-// owns the lucide component mapping so the lib stays React-free.-const GROUP_ICONS = { characters: PersonStanding, places: MapPin, objects: Package };--// Landing on /sprites with no id auto-opens the most recently touched sprite so-// the manager is never a cold empty pane (the user's ask). Prefer characters —-// the reference/walk/publish workflows are character-only, so that's the sprite-// someone most likely wants in front of them — and only fall back to the newest-// record of any kind when the library holds no characters. `updatedAt` is bumped-// on every create/patch/import; `createdAt` is the floor for a never-patched-// record. A record missing both sorts to 0 rather than NaN-poisoning the reduce.-function pickMostRecentSprite(records) {- if (!Array.isArray(records) || records.length === 0) return null;- const ts = (r) => Date.parse(r?.updatedAt || r?.createdAt || '') || 0;- const characters = records.filter((r) => r.kind === 'character');- const pool = characters.length ? characters : records;- return pool.reduce((best, r) => (ts(r) > ts(best) ? r : best), pool[0]);-}+import { filterSpriteRecords, NEW_SPRITE_KINDS } from '../lib/spriteRecordGroups.js';+import { groupIconForKind } from '../components/sprites/spriteGroupIcons.js';// Sprite Manager: library over imported production sprites — characters// (reference sets, walk strips, runtime atlases) and props atlas families —@@ -250,8 +231,8 @@ function NewSpritePanel({ onCreated }) {// Header autocomplete (#2932, reworked): a compact combobox that filters the// library by name/id/kind and navigates on Enter/click. It lives in the page// header rather than a sidebar, so it renders only the search field + its-// suggestion popover — full browsing moved to the Catalog modal below, because-// the library is expected to grow well past a scannable sidebar list.+// suggestion popover — full browsing lives in the Library catalog (the bare+// `/sprites` route), which scales past a scannable sidebar list.function SpriteSearch({ records, onSelect }) {const [query, setQuery] = useState('');const [activeIndex, setActiveIndex] = useState(-1);@@ -326,7 +307,7 @@ function SpriteSearch({ records, onSelect }) {{suggestions.length === 0 ? (<li className="px-3 py-2 text-xs text-gray-500">No matches</li>) : suggestions.map((r, i) => {- const Icon = GROUP_ICONS[groupKeyForKind(r.kind)] || Package;+ const Icon = groupIconForKind(r.kind);return (<li key={r.id} id={`sprite-opt-${r.id}`} role="option" aria-selected={i === activeIndex}><button@@ -348,85 +329,6 @@ function SpriteSearch({ records, onSelect }) {);}-// Full-library catalog viewer. Replaces the old "Browse all" sidebar disclosure-// (which didn't scale) with a searchable, grouped grid of every sprite. Picking-// a card navigates to it and closes — this is how the user swaps the active-// sprite when they don't remember its name to type into the header search.-function CatalogModal({ open, onClose, records, selectedId, onSelect }) {- const [query, setQuery] = useState('');- const filtered = useMemo(() => filterSpriteRecords(records, query), [records, query]);- const groups = useMemo(() => groupSpriteRecords(filtered), [filtered]);-- // The caller mounts this only while open (`{catalogOpen && <CatalogModal/>}`),- // so a fresh mount already starts with an empty filter — no stale-query reset- // needed, and the filter/group memos never run while the catalog is closed.- return (- <Modal open={open} onClose={onClose} size="3xl" ariaLabel="Sprite catalog" align="top">- <div className="bg-port-card border border-port-border rounded-lg flex flex-col max-h-[85vh]">- <header className="flex items-center gap-3 px-4 py-3 border-b border-port-border shrink-0">- <LayoutGrid className="w-5 h-5 text-port-accent shrink-0" />- <h2 className="text-base font-semibold text-white">Sprite Catalog</h2>- <span className="text-xs text-gray-500">{records.length} total</span>- <div className="relative ml-auto w-40 sm:w-56">- <Search className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />- <label htmlFor="sprite-catalog-search" className="sr-only">Filter catalog</label>- <input- id="sprite-catalog-search"- type="search"- value={query}- onChange={(e) => setQuery(e.target.value)}- placeholder="Filter…"- className="w-full bg-port-bg border border-port-border rounded pl-8 pr-3 py-1.5 text-sm text-white"- />- </div>- <button- type="button"- onClick={onClose}- aria-label="Close catalog"- className="p-2 rounded-lg text-gray-400 hover:text-white hover:bg-port-border/50 shrink-0"- >- <X className="w-5 h-5" />- </button>- </header>- <div className="flex-1 overflow-y-auto p-4 space-y-5">- {filtered.length === 0 ? (- <p className="text-sm text-gray-500">No sprites match “{query}”.</p>- ) : groups.map((g) => {- const Icon = GROUP_ICONS[g.key] || Package;- return (- <div key={g.key}>- <h3 className="flex items-center gap-1.5 text-xs uppercase tracking-wide text-gray-500 mb-2">- <Icon className="w-3.5 h-3.5" /> {g.label} ({g.records.length})- </h3>- <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2">- {g.records.map((r) => (- <button- key={r.id}- type="button"- onClick={() => { onSelect(r.id); onClose(); }}- aria-current={selectedId === r.id}- className={`text-left p-3 rounded-lg border transition-colors ${selectedId === r.id ? 'bg-port-accent/20 border-port-accent text-white' : 'bg-port-bg border-port-border text-gray-300 hover:border-gray-500'}`}- >- <span className="block font-medium truncate">{r.name}</span>- <span className="block text-xs text-gray-500 truncate">- {r.kind} · {r.status}- {r.chromaKey ? ` · key ${r.chromaKey}` : ''}- </span>- <span className="block text-xs text-gray-600 mt-0.5">- {r.updatedAt || r.createdAt ? `updated ${timeAgo(r.updatedAt || r.createdAt)}` : ''}- </span>- </button>- ))}- </div>- </div>- );- })}- </div>- </div>- </Modal>- );-}-export default function Sprites() {const { id } = useParams();const navigate = useNavigate();@@ -436,7 +338,10 @@ export default function Sprites() {// failure — the record may be fine, offer a retry instead of lying).const [detailState, setDetailState] = useState('idle');const [retryTick, setRetryTick] = useState(0);- const [catalogOpen, setCatalogOpen] = useState(false);+ // Catalog card thumbnails: id → record-relative locked main-reference path.+ // Only characters with a frozen main reference have one; everything else+ // falls back to its group icon.+ const [thumbs, setThumbs] = useState(() => new Map());const goto = useCallback((rid) => navigate(`/sprites/${rid}`), [navigate]);const refresh = useCallback(() => {@@ -445,16 +350,42 @@ export default function Sprites() {listSpriteRecords().then(setRecords).catch(() => setRecords([]));}, []);- // Landing on the bare /sprites route auto-opens the most recent sprite so the- // manager never presents a cold empty pane (the user's ask). Only fires when- // there's no id AND the library is non-empty; `replace` keeps the redirect out- // of history so Back doesn't bounce between /sprites and the sprite. An- // invalid :id lands in the 'missing' state below, not here, so no loop.+ // Catalog thumbnails are only shown on the Library view (`!id`), and+ // listSpriteThumbnails is an O(records) disk scan — so fetch them when the+ // catalog is on screen, NOT from refresh() (which rides walk/reference render+ // polling on the detail page). Best-effort: a failed fetch just falls back to+ // icon placeholders. Re-runs whenever we return to the catalog, so a main+ // reference locked (or an asset added) on a detail page shows on the way back.useEffect(() => {- if (id || !Array.isArray(records) || records.length === 0) return;- const recent = pickMostRecentSprite(records);- if (recent) navigate(`/sprites/${recent.id}`, { replace: true });- }, [id, records, navigate]);+ if (id) return undefined;+ let stale = false;+ listSpriteThumbnails({ silent: true })+ .then((thumbList) => { if (!stale) setThumbs(new Map((thumbList || []).map((t) => [t.id, t.path]))); })+ .catch(() => {});+ return () => { stale = true; };+ }, [id]);++ // `/sprites` now lands on the Library catalog (the user's ask — no more+ // auto-opening the most recent sprite). Records are reached by picking a card+ // or the header search, both of which navigate to `/sprites/:id`.++ // Reactive list updates for record CRUD from the catalog — rename patches the+ // matching row (and the open detail, if it's the same record) in place;+ // delete drops it. No full refetch (project convention). The stale thumbs+ // entry needs no pruning — a deleted record is filtered out of `records`, so+ // no card renders for it and its thumbnail is never read again.+ const onRecordRenamed = useCallback((updated) => {+ setRecords((prev) => (prev || []).map((r) => (r.id === updated.id ? { ...r, ...updated } : r)));+ setDetail((prev) => (prev?.record?.id === updated.id+ ? { ...prev, record: { ...prev.record, ...updated } }+ : prev));+ }, []);+ const onRecordDeleted = useCallback((deletedId) => {+ setRecords((prev) => (prev || []).filter((r) => r.id !== deletedId));+ toast.success('Sprite deleted');+ // Deleting the sprite you're viewing drops you back to the catalog.+ if (id === deletedId) navigate('/sprites');+ }, [id, navigate]);// Stable identity — ReferenceWorkflow's poll effect depends on it, and an// inline arrow would tear down/recreate the interval every parent render.@@ -628,46 +559,33 @@ export default function Sprites() {return (<div className="space-y-4">{/* Header owns identity (left) plus every library-wide control (right):- search, the Catalog viewer, and the create/import actions — no left- sidebar, so the detail pane below runs full width. */}+ a "Library" link back to the catalog (only while a sprite is open),+ search, and the create/import actions — no left sidebar, so the+ catalog/detail pane below runs full width. */}<div className="flex flex-wrap items-center gap-3"><div className="flex items-center gap-3 mr-auto"><PersonStanding className="w-6 h-6 text-port-accent" /><h1 className="text-2xl font-bold text-white">Sprite Manager</h1></div>- {records?.length > 0 && (- <>- <SpriteSearch records={records} onSelect={goto} />- <button- type="button"- onClick={() => setCatalogOpen(true)}- className="flex items-center gap-2 px-3 py-1.5 bg-port-card border border-port-border hover:border-port-accent text-gray-300 rounded text-sm"- >- <LayoutGrid className="w-4 h-4" /> Catalog- </button>- </>+ {id && (+ <button+ type="button"+ onClick={() => navigate('/sprites')}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-card border border-port-border hover:border-port-accent text-gray-300 rounded text-sm"+ >+ <LayoutGrid className="w-4 h-4" /> Library+ </button>)}+ {records?.length > 0 && <SpriteSearch records={records} onSelect={goto} />}<NewSpritePanel onCreated={(record) => { refresh(); navigate(`/sprites/${record.id}`); }} />{/* Re-import while a sprite is open must refresh the open detail too,not just the library list. */}<ImportPanel onImported={() => { refresh(); if (id) setRetryTick((t) => t + 1); }} /></div>- {/* Mounted only while open so its filter/group memos never run behind a- closed modal (and a fresh mount starts with an empty filter). */}- {catalogOpen && (- <CatalogModal- open- onClose={() => setCatalogOpen(false)}- records={records || []}- selectedId={id}- onSelect={goto}- />- )}<div><section className="min-w-0">{!id ? (- // No id yet: loading the list, an empty library, or the one-frame- // gap before the auto-redirect effect opens the most recent sprite.+ // The bare /sprites route IS the Library catalog now.records === null ? (<p className="text-sm text-gray-500">Loading…</p>) : records.length === 0 ? (@@ -675,12 +593,18 @@ export default function Sprites() {No sprites yet. Import a production set from a sprite-pipeline checkout to get started.</p>) : (- <p className="text-sm text-gray-500">Opening the most recent sprite…</p>+ <SpriteCatalog+ records={records}+ thumbs={thumbs}+ onOpen={goto}+ onRenamed={onRecordRenamed}+ onDeleted={onRecordDeleted}+ />)) : detailState === 'missing' ? (<div className="text-sm text-gray-400">Sprite not found.{' '}- <button onClick={() => setCatalogOpen(true)} className="text-port-accent hover:underline">Browse the catalog</button>+ <button onClick={() => navigate('/sprites')} className="text-port-accent hover:underline">Back to the library</button></div>) : detailState === 'error' ? (<div className="text-sm text-gray-400">@@ -691,32 +615,17 @@ export default function Sprites() {<p className="text-sm text-gray-500">Loading…</p>) : (<div className="space-y-4">- <div>- <h2 className="text-lg font-semibold text-white flex items-center gap-2">- {(() => {- const Icon = GROUP_ICONS[groupKeyForKind(detail.record.kind)] || Package;- return <Icon className="w-5 h-5" />;- })()}- {detail.record.name}- </h2>- <p className="text-xs text-gray-500">- {detail.record.kind} · {detail.record.status}- {detail.record.chromaKey && (- <>- {' · chroma key '}- <span className="inline-block w-3 h-3 rounded-sm align-middle border border-port-border" style={{ backgroundColor: detail.record.chromaKey }} />{' '}- {detail.record.chromaKey}- </>- )}- {detail.record.importedFrom?.importedAt && ` · imported ${timeAgo(detail.record.importedFrom.importedAt)}`}- </p>- {detail.record.spec?.archetype && (- <p className="text-xs text-gray-500">archetype: {detail.record.spec.archetype}</p>- )}- </div>- {/* Library / Loop Trimmer workspaces (#2933). The trimmer is+ <SpriteDetailHeader+ record={detail.record}+ onRenamed={onRecordRenamed}+ onDeleted={onRecordDeleted}+ />+ {/* Assets / Loop Trimmer workspaces (#2933). The trimmer ischaracter-only (it trims packaged walk runs), so non-character- records skip the tab bar and always show their asset library. */}+ records skip the tab bar and always show their asset library.+ The tab id stays 'library' so existing `?spriteTab=library`+ deep links keep working; only its label reads "Assets" now+ that "Library" means the top-level catalog. */}{detail.record.kind === 'character' && (<TabPillsvariant="pills"@@ -725,7 +634,7 @@ export default function Sprites() {mobileSelectId="sprite-workspace-tab"ariaLabel="Sprite workspace"tabs={[- { id: 'library', label: 'Library', icon: Images },+ { id: 'library', label: 'Assets', icon: Images },{ id: 'trimmer', label: 'Loop Trimmer', icon: Scissors },]}activeTab={spriteTab}diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsindex aaa5dd9694..f1818a1da6 100644--- a/client/src/services/apiSprites.js+++ b/client/src/services/apiSprites.js@@ -14,6 +14,12 @@ export const getSpriteRecord = (id, options = {}) => request(`/sprites/${encodeU// main reference image).export const listSpriteReferenceSources = (options = {}) => request('/sprites/reference-sources', options);+// Representative Library-catalog thumbnails for EVERY record — `[{ id, path }]`+// (record-relative image). Characters use their locked main reference; other+// kinds (places, objects, imported prop atlases) use their first previewable+// asset. Records with no usable image are omitted.+export const listSpriteThumbnails = (options = {}) => request('/sprites/thumbnails', options);+export const createSpriteRecord = (body, options = {}) => request('/sprites', {method: 'POST', body: JSON.stringify(body), ...options,});@@ -22,6 +28,14 @@ export const updateSpriteRecord = (id, patch, options = {}) => request(`/spritesmethod: 'PATCH', body: JSON.stringify(patch), ...options,});+// Delete (tombstone) a whole sprite record — drops it from the library while+// its on-disk assets and its id stay reserved (a re-create must use a new id).+// Callers own their confirmation UI, so pass `{ silent: true }` to suppress the+// auto-toast. Returns the delete result.+export const deleteSpriteRecord = (id, options = {}) => request(`/sprites/${encodeURIComponent(id)}`, {+ method: 'DELETE', ...options,+});+// Delete one on-disk asset by its record-relative path — an old runtime atlas// version (PNG + manifest removed together) or a superseded reference /// candidate render. Refuses the live atlas (409 ATLAS_IN_USE) and the record'sdiff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex c2a19de701..f441a6bb8d 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -37,7 +37,7 @@ import {import { importFromSource } from '../services/sprites/importer.js';import {getReferenceSet, startReferenceGeneration, lockReference, patchSpriteRecord,- listReferenceSources, forkSprite,+ listReferenceSources, listSpriteThumbnails, forkSprite,} from '../services/sprites/reference.js';import {getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,@@ -70,6 +70,12 @@ router.get('/reference-sources', asyncHandler(async (_req, res) => {res.json(await listReferenceSources());}));+// A representative thumbnail per record for the Library catalog — every kind,+// not just reference-workflow characters. MUST precede `/:id`.+router.get('/thumbnails', asyncHandler(async (_req, res) => {+ res.json(await listSpriteThumbnails());+}));+// Create a character record — the entry point of the reference workflow.// Id derivation and the kind live in the service (createCharacter).router.post('/', asyncHandler(async (req, res) => {diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.jsindex d3a4284e50..4c1cb1aacd 100644--- a/server/services/sprites/reference.js+++ b/server/services/sprites/reference.js@@ -31,7 +31,7 @@ import {import { resolveImageCleaners } from '../imageGen/index.js';import { getSettings } from '../settings.js';import { getRecord, updateRecord, listRecords, createCharacter } from './records.js';-import { spriteDir, resolveSpriteAssetPath } from './paths.js';+import { spriteDir, resolveSpriteAssetPath, listSpriteAssets } from './paths.js';import {SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, anchorIdForDirection,buildMainReferencePrompt, buildAnchorPrompt,@@ -379,6 +379,37 @@ export async function listReferenceSources() {return out;}+// Browser-renderable image formats (mirrors the client's spriteAssets probe+// list — sharp can read more than a browser can paint, so a TIFF is skipped).+const THUMBNAIL_RENDERABLE = /^(png|gif|webp|jpeg|jpg|svg)$/;++/**+ * A representative Library-catalog thumbnail for EVERY record, not just+ * reference-workflow characters. A character with a locked main uses that (its+ * canonical face, one manifest read); every other kind — places, objects,+ * imported prop atlases, and a character with no locked main yet — falls back+ * to its first previewable on-disk image (listSpriteAssets already sorts by+ * path, so it's deterministic). Returns `[{ id, path }]` (record-relative),+ * omitting records with no usable image. O(records): a locked character costs+ * one manifest read, everything else one asset-dir scan — a catalog-view fetch,+ * not a hot path (the client only calls it on the `/sprites` Library view).+ */+export async function listSpriteThumbnails() {+ const records = await listRecords();+ const results = await Promise.all(records.map(async (r) => {+ if (r.deleted) return null;+ if (r.kind === 'character') {+ const manifest = await loadManifest(r.id);+ const main = manifest?.mainReference;+ if (main?.locked && main.path) return { id: r.id, path: main.path };+ }+ const assets = await listSpriteAssets(r.id);+ const preview = assets.find((a) => a.width && a.height && THUMBNAIL_RENDERABLE.test(a.format || ''));+ return preview ? { id: r.id, path: preview.path } : null;+ }));+ return results.filter(Boolean);+}+/*** Fork a new character from an existing sprite's locked main reference: create* the record, then image+text→image its main from the source reference via thediff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.jsindex e6bf989885..3ecf7c2df1 100644--- a/server/services/sprites/reference.test.js+++ b/server/services/sprites/reference.test.js@@ -53,7 +53,7 @@ vi.mock('../settings.js', () => ({ getSettings: async () => settings }));const records = await import('./records.js');const {getReferenceSet, startReferenceGeneration, attachReferenceCandidate, lockReference, patchSpriteRecord,- listReferenceSources, forkSprite,+ listReferenceSources, listSpriteThumbnails, forkSprite,} = await import('./reference.js');let seq = 0;@@ -509,6 +509,40 @@ describe('listReferenceSources', () => {});});+describe('listSpriteThumbnails', () => {+ it('uses a locked character main, an on-disk asset for other kinds, and omits imageless records', async () => {+ // Character with a locked main → its canonical main-reference path (no+ // asset scan needed).+ const hero = newId();+ await createCharacter(hero, { name: 'Hero One' });+ await lockMain(hero);++ // A place with an on-disk previewable image → that asset.+ const place = 'saloon-thumb';+ await records.createRecord({ kind: 'place', name: 'Saloon' }, place);+ await mkdir(join(TEST_ROOT, 'sprites', place), { recursive: true });+ await writeCandidatePng(join(TEST_ROOT, 'sprites', place, 'establishing.png'));++ // A character with NO locked main but an asset → falls back to the asset.+ const drafted = newId();+ await createCharacter(drafted, { name: 'Draft Two' });+ await mkdir(join(TEST_ROOT, 'sprites', drafted), { recursive: true });+ await writeCandidatePng(join(TEST_ROOT, 'sprites', drafted, 'sketch.png'));++ // An object with no image at all → omitted entirely.+ const empty = 'crate-thumb';+ await records.createRecord({ kind: 'object', name: 'Crate' }, empty);++ const thumbs = await listSpriteThumbnails();+ const byId = Object.fromEntries(thumbs.map((t) => [t.id, t.path]));++ expect(byId[hero]).toContain(`${hero}-walk-south-v1.png`);+ expect(byId[place]).toBe('establishing.png');+ expect(byId[drafted]).toBe('sketch.png');+ expect(byId).not.toHaveProperty(empty);+ });+});+describe('forkSprite', () => {it('creates a new character and queues its main seeded from the source reference', async () => {const source = newId();