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
Add reference-image seed sources + character fork to the sprite reference workflow
[._.]/ Adam Eivy9ea64d4a7686
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6d6c9ea561..c18281927e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -13,6 +13,8 @@## 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.- **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/ForkSpriteModal.jsx b/client/src/components/sprites/ForkSpriteModal.jsxnew file mode 100644index 0000000000..874680cefc--- /dev/null+++ b/client/src/components/sprites/ForkSpriteModal.jsx@@ -0,0 +1,158 @@+// Fork a character from its locked main reference (#sprite-i2i): creates a new+// sprite whose main is generated image+text→image from THIS sprite's reference+// plus a required prompt describing the change. Thin form over+// forkSpriteRecord → the server creates the record and queues the main render;+// on success we hand the new record back so the page can navigate to it.++import { useState } from 'react';+import { GitFork, RefreshCw, X } from 'lucide-react';+import Modal from '../ui/Modal';+import toast from '../ui/Toast';+import SpritePreview from './SpritePreview.jsx';+import { forkSpriteRecord } from '../../services/apiSprites.js';+import { useAsyncAction } from '../../hooks/useAsyncAction.js';++export default function ForkSpriteModal({ open, onClose, source, referencePath, backends, mode, onForked }) {+ const [name, setName] = useState(`${source?.name || ''} fork`);+ const [id, setId] = useState('');+ const [designPrompt, setDesignPrompt] = useState('');+ const [forkMode, setForkMode] = useState(mode || '');+ const [strength, setStrength] = useState(0.65);++ const hasBackends = Array.isArray(backends) && backends.length > 0;++ const [submit, submitting] = useAsyncAction(async () => {+ const { record } = await forkSpriteRecord(source.id, {+ name: name.trim(),+ ...(id.trim() ? { id: id.trim() } : {}),+ designPrompt: designPrompt.trim(),+ ...(forkMode ? { mode: forkMode } : {}),+ initImageStrength: strength,+ }, { silent: true });+ toast.success(`Forked ${source.name} → ${record.name} — main render queued`);+ onForked(record);+ onClose();+ }, { errorMessage: 'Fork failed' });++ const canSubmit = !submitting && name.trim() && designPrompt.trim() && (!hasBackends || forkMode);++ return (+ <Modal+ open={open}+ onClose={onClose}+ size="lg"+ usePortal+ closeOnBackdrop={false}+ panelClassName="bg-port-card border border-port-border rounded-xl max-h-[85vh] flex flex-col"+ ariaLabel="Fork sprite"+ >+ <div className="flex items-center justify-between gap-3 p-3 border-b border-port-border">+ <h2 className="text-sm font-medium text-white flex items-center gap-1.5">+ <GitFork className="w-4 h-4" /> Fork {source?.name}+ </h2>+ <button type="button" onClick={onClose} aria-label="Close" className="p-1.5 text-gray-400 hover:text-white rounded">+ <X className="w-4 h-4" />+ </button>+ </div>++ <div className="flex-1 overflow-y-auto p-4 space-y-3">+ <div className="flex items-start gap-3">+ {referencePath && (+ <SpritePreview+ recordId={source.id}+ path={referencePath}+ className="w-24 h-24 object-contain bg-port-bg border border-port-border rounded shrink-0"+ />+ )}+ <p className="text-xs text-gray-400">+ The new character's main reference is generated from this reference image plus your prompt+ (image+text→image). Everything else — anchors, walk cycle, atlas — starts fresh.+ </p>+ </div>++ <div>+ <label htmlFor="fork-name" className="block text-xs text-gray-400 mb-1">New name</label>+ <input+ id="fork-name"+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white"+ />+ </div>++ <div>+ <label htmlFor="fork-id" className="block text-xs text-gray-400 mb-1">+ Id <span className="text-gray-600">(optional — derived from the name)</span>+ </label>+ <input+ id="fork-id"+ type="text"+ value={id}+ onChange={(e) => setId(e.target.value)}+ placeholder="derived-from-name"+ className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white"+ />+ </div>++ <div>+ <label htmlFor="fork-prompt" className="block text-xs text-gray-400 mb-1">Prompt — describe the change</label>+ <textarea+ id="fork-prompt"+ value={designPrompt}+ onChange={(e) => setDesignPrompt(e.target.value)}+ rows={3}+ placeholder="e.g. same character but wearing a red coat and a wide-brim hat"+ className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white"+ />+ </div>++ <div className="flex flex-wrap items-center gap-4">+ {hasBackends && (+ <label className="flex items-center gap-2 text-xs text-gray-400">+ Backend+ <select+ value={forkMode}+ onChange={(e) => setForkMode(e.target.value)}+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"+ >+ {backends.map((b) => <option key={b.id} value={b.id}>{b.label || b.id}</option>)}+ </select>+ </label>+ )}+ <label className="flex items-center gap-2 text-xs text-gray-400">+ Fidelity to reference+ <input+ type="range"+ min="0"+ max="1"+ step="0.05"+ value={strength}+ onChange={(e) => setStrength(Number(e.target.value))}+ className="accent-port-accent"+ />+ <span className="tabular-nums text-gray-500 w-8">{strength.toFixed(2)}</span>+ </label>+ </div>+ {!hasBackends && (+ <p className="text-xs text-port-warning">+ No image backend configured — enable Codex or Grok, or set a local Python path, in Settings → Image Gen.+ </p>+ )}+ </div>++ <div className="flex justify-end gap-2 p-3 border-t border-port-border">+ <button type="button" onClick={onClose} className="px-3 py-1.5 text-sm text-gray-400 hover:text-white">Cancel</button>+ <button+ type="button"+ onClick={submit}+ disabled={!canSubmit}+ className="flex items-center gap-1.5 px-3 py-1.5 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white rounded text-sm"+ >+ {submitting ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <GitFork className="w-3.5 h-3.5" />}+ Fork & generate+ </button>+ </div>+ </Modal>+ );+}diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsxindex bfcfbf46f3..46cde31aa6 100644--- a/client/src/components/sprites/ReferenceWorkflow.jsx+++ b/client/src/components/sprites/ReferenceWorkflow.jsx@@ -1,11 +1,15 @@import { useEffect, useMemo, useRef, useState } from 'react';import {Lock, Sparkles, RefreshCw, Upload, ChevronDown, ChevronRight,+ Images, PersonStanding, GitFork, X,} from 'lucide-react';import toast from '../ui/Toast';import { generateSpriteReference, lockSpriteReference, updateSpriteRecord } from '../../services/apiSprites.js';import { useAsyncAction } from '../../hooks/useAsyncAction.js';import SpritePreview from './SpritePreview.jsx';+import GalleryImagePicker from '../imageGen/GalleryImagePicker.jsx';+import SpriteReferencePicker from './SpriteReferencePicker.jsx';+import ForkSpriteModal from './ForkSpriteModal.jsx';// Reference workflow (issue #2896): generate main-reference candidates from// text + optional uploaded design image, freeze the approved main, then@@ -65,7 +69,7 @@ function CandidateTile({ recordId, candidate, locking, onLock, clipRisk }) {);}-export default function ReferenceWorkflow({ record, reference, renders, backends, mode, onModeChange, onChanged }) {+export default function ReferenceWorkflow({ record, reference, renders, backends, mode, onModeChange, onChanged, onForked }) {const recordId = record.id;const manifest = reference?.manifest || null;const candidates = reference?.candidates || [];@@ -90,8 +94,35 @@ export default function ReferenceWorkflow({ record, reference, renders, backends// diverge). `backends`: null = settings not loaded yet; [] = loaded, no// backend configured.const [designPrompt, setDesignPrompt] = useState(manifest?.designPrompt || '');- const [uploadFile, setUploadFile] = useState(null);+ // The main render can be seeded (image+text→image) from one of three sources:+ // an uploaded file, a pick from the render-history gallery, or another sprite's+ // locked main reference. One unified `refSource` holds whichever is active so+ // the generate payload and the preview stay in sync.+ // null | { type:'upload', file, previewUrl }+ // | { type:'gallery', filename, previewUrl, label }+ // | { type:'sprite', id, name, path }+ const [refSource, setRefSource] = useState(null);+ const [strength, setStrength] = useState(0.65);+ const [galleryOpen, setGalleryOpen] = useState(false);+ const [spritePickerOpen, setSpritePickerOpen] = useState(false);+ const [forkOpen, setForkOpen] = useState(false);const fileInputRef = useRef(null);++ // Revoke the previous upload's object URL whenever the source changes or the+ // component unmounts (cleanup runs with the prior closure).+ useEffect(() => {+ const url = refSource?.type === 'upload' ? refSource.previewUrl : null;+ return () => { if (url) URL.revokeObjectURL(url); };+ }, [refSource]);++ const clearSource = () => {+ setRefSource(null);+ if (fileInputRef.current) fileInputRef.current.value = '';+ };+ const pickUpload = (file) => {+ if (!file) return;+ setRefSource({ type: 'upload', file, previewUrl: URL.createObjectURL(file) });+ };// target → jobId for in-flight renders. Owned by the Sprites page and shared// with the asset collection's anchor Regenerate buttons (#2931) so both gate// on one map — see the matching note in WalkWorkflow.@@ -109,11 +140,16 @@ export default function ReferenceWorkflow({ record, reference, renders, backendsconst { jobId } = await generateSpriteReference(recordId, {target,...(mode ? { mode } : {}),- ...(target === 'main' ? { designPrompt, referenceImageFile: uploadFile || undefined } : {}),+ ...(target === 'main' ? {+ designPrompt,+ ...(refSource?.type === 'upload' ? { referenceImageFile: refSource.file } : {}),+ ...(refSource?.type === 'gallery' ? { initImageGalleryFile: refSource.filename } : {}),+ ...(refSource?.type === 'sprite' ? { initImageSpriteId: refSource.id } : {}),+ ...(refSource ? { initImageStrength: strength } : {}),+ } : {}),}, { silent: true });resolveSubmit(target, jobId);- setUploadFile(null);- if (fileInputRef.current) fileInputRef.current.value = '';+ if (target === 'main') clearSource();} catch (err) {cancelSubmit(target);toast.error(err?.message || `Failed to queue ${target} render`);@@ -216,7 +252,18 @@ export default function ReferenceWorkflow({ record, reference, renders, backends{mainLocked ? (<div className="flex items-start gap-3"><SpriteImg recordId={recordId} path={manifest.mainReference.path} className="w-32 h-32 object-contain bg-port-bg border border-port-border rounded" />- <p className="text-xs text-gray-500 flex items-center gap-1"><Lock className="w-3 h-3" /> frozen · immutable root</p>+ <div className="space-y-2">+ <p className="text-xs text-gray-500 flex items-center gap-1"><Lock className="w-3 h-3" /> frozen · immutable root</p>+ {/* A locked main can never be regenerated — to iterate on it, fork+ into a new character seeded from this reference (image+text→image). */}+ <button+ type="button"+ onClick={() => setForkOpen(true)}+ className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ <GitFork className="w-3.5 h-3.5" /> Fork from this reference+ </button>+ </div></div>) : (<div className="space-y-2">@@ -227,22 +274,84 @@ export default function ReferenceWorkflow({ record, reference, renders, backendsrows={2}className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white"/>+ {/* Reference image (optional, i2i seed) — pick ONE of three sources.+ Hidden file input driven by the Upload button. */}+ <input+ ref={fileInputRef}+ type="file"+ accept="image/png,image/jpeg,image/webp"+ className="hidden"+ onChange={(e) => pickUpload(e.target.files?.[0] || null)}+ />+ {refSource ? (+ <div className="flex items-center gap-3 bg-port-bg border border-port-border rounded p-2">+ {refSource.type === 'sprite' ? (+ <SpriteImg recordId={refSource.id} path={refSource.path} className="w-14 h-14 object-contain shrink-0" />+ ) : (+ <img src={refSource.previewUrl} alt="reference" className="w-14 h-14 object-contain rounded shrink-0" />+ )}+ <div className="min-w-0 flex-1">+ <p className="text-xs text-gray-300 truncate">+ {refSource.type === 'upload' ? refSource.file.name+ : refSource.type === 'gallery' ? (refSource.label || 'gallery image')+ : refSource.name}+ </p>+ <p className="text-[10px] text-gray-500">+ {refSource.type === 'upload' ? 'uploaded image'+ : refSource.type === 'gallery' ? 'from render history'+ : 'from reference sprite'}+ </p>+ <label className="mt-1 flex items-center gap-2 text-[10px] text-gray-500">+ fidelity+ <input+ type="range" min="0" max="1" step="0.05" value={strength}+ onChange={(e) => setStrength(Number(e.target.value))}+ className="accent-port-accent"+ aria-label="Reference fidelity"+ />+ <span className="tabular-nums w-8">{strength.toFixed(2)}</span>+ </label>+ </div>+ <button+ type="button"+ onClick={clearSource}+ aria-label="Remove reference image"+ className="p-1 text-gray-400 hover:text-white shrink-0"+ >+ <X className="w-4 h-4" />+ </button>+ </div>+ ) : (+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs text-gray-500">Reference image (optional):</span>+ <button+ type="button"+ onClick={() => fileInputRef.current?.click()}+ className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ <Upload className="w-3.5 h-3.5" /> Upload+ </button>+ <button+ type="button"+ onClick={() => setGalleryOpen(true)}+ className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ <Images className="w-3.5 h-3.5" /> From history+ </button>+ <button+ type="button"+ onClick={() => setSpritePickerOpen(true)}+ className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ <PersonStanding className="w-3.5 h-3.5" /> From sprite+ </button>+ </div>+ )}<div className="flex flex-wrap items-center gap-3">- <label className="flex items-center gap-1.5 text-xs text-gray-400 cursor-pointer">- <Upload className="w-3.5 h-3.5" />- {uploadFile ? uploadFile.name : 'Design image (optional)'}- <input- ref={fileInputRef}- type="file"- accept="image/png,image/jpeg,image/webp"- className="hidden"- onChange={(e) => setUploadFile(e.target.files?.[0] || null)}- />- </label>{modePicker}<buttononClick={() => generate('main')}- disabled={!mode || !!pendingJobs.main || (!designPrompt.trim() && !uploadFile)}+ disabled={!mode || !!pendingJobs.main || (!designPrompt.trim() && !refSource)}className="flex items-center gap-1.5 px-3 py-1 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white rounded text-sm">{pendingJobs.main ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}@@ -315,6 +424,33 @@ export default function ReferenceWorkflow({ record, reference, renders, backends)}</div>)}++ {/* Reference-image source pickers + fork. Portal-based modals, so their+ placement in the tree doesn't matter. */}+ <GalleryImagePicker+ open={galleryOpen}+ onClose={() => setGalleryOpen(false)}+ onSelect={(item) => setRefSource({+ type: 'gallery', filename: item.filename, previewUrl: item.previewUrl, label: item.prompt || item.filename,+ })}+ />+ <SpriteReferencePicker+ open={spritePickerOpen}+ onClose={() => setSpritePickerOpen(false)}+ excludeId={recordId}+ onSelect={(it) => setRefSource({ type: 'sprite', id: it.id, name: it.name, path: it.path })}+ />+ {mainLocked && (+ <ForkSpriteModal+ open={forkOpen}+ onClose={() => setForkOpen(false)}+ source={{ id: recordId, name: record.name }}+ referencePath={manifest.mainReference.path}+ backends={backends}+ mode={mode}+ onForked={(rec) => onForked?.(rec)}+ />+ )}</div>);}diff --git a/client/src/components/sprites/SpriteReferencePicker.jsx b/client/src/components/sprites/SpriteReferencePicker.jsxnew file mode 100644index 0000000000..2d38818504--- /dev/null+++ b/client/src/components/sprites/SpriteReferencePicker.jsx@@ -0,0 +1,113 @@+// Picker over sprites that already have a locked main reference (#sprite-i2i):+// the "select an existing reference sprite" source for seeding a new main via+// image+text→image. Fetches GET /sprites/reference-sources on open, shows a+// searchable grid of reference thumbnails, and calls onSelect({ id, name, path })+// then closes. `excludeId` drops the sprite being edited (seeding a main from+// its own — not-yet-locked — reference is nonsensical, and once locked it can't+// be regenerated anyway).++import { useEffect, useMemo, useState } from 'react';+import { Search, X, RefreshCw } from 'lucide-react';+import Modal from '../ui/Modal';+import SpritePreview from './SpritePreview.jsx';+import { listSpriteReferenceSources } from '../../services/apiSprites.js';++export default function SpriteReferencePicker({ open, onClose, onSelect, excludeId }) {+ const [items, setItems] = useState([]);+ const [loading, setLoading] = useState(false);+ const [query, setQuery] = useState('');++ // Refetch each open so a sprite whose main was just locked shows up; reset the+ // search on close so a re-open starts clean.+ useEffect(() => {+ if (!open) { setQuery(''); return undefined; }+ let cancelled = false;+ setLoading(true);+ listSpriteReferenceSources({ silent: true })+ .then((list) => { if (!cancelled) setItems(Array.isArray(list) ? list : []); })+ .catch(() => { if (!cancelled) setItems([]); })+ .finally(() => { if (!cancelled) setLoading(false); });+ return () => { cancelled = true; };+ }, [open]);++ const filtered = useMemo(() => {+ const pool = items.filter((it) => it.id !== excludeId);+ const q = query.trim().toLowerCase();+ if (!q) return pool;+ return pool.filter((it) => `${it.name} ${it.id}`.toLowerCase().includes(q));+ }, [items, query, excludeId]);++ return (+ <Modal+ open={open}+ onClose={onClose}+ size="3xl"+ usePortal+ panelClassName="bg-port-card border border-port-border rounded-xl max-h-[85vh] flex flex-col"+ ariaLabel="Pick a reference sprite"+ >+ <div className="flex items-center justify-between gap-3 p-3 border-b border-port-border">+ <h2 className="text-sm font-medium text-white shrink-0">Pick a reference sprite</h2>+ <div className="relative flex-1 max-w-md">+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-500" />+ <input+ type="text"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search by name or id…"+ aria-label="Search reference sprites"+ className="w-full pl-7 pr-7 py-1.5 text-xs bg-port-bg border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"+ autoFocus+ />+ {query && (+ <button+ type="button"+ onClick={() => setQuery('')}+ className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"+ aria-label="Clear search"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ )}+ </div>+ <button+ type="button"+ onClick={onClose}+ className="shrink-0 p-1.5 text-gray-400 hover:text-white rounded"+ aria-label="Close"+ >+ <X className="w-4 h-4" />+ </button>+ </div>++ <div className="flex-1 overflow-y-auto p-3">+ {loading ? (+ <div className="flex items-center justify-center gap-2 text-xs text-gray-400 py-10">+ <RefreshCw className="w-4 h-4 animate-spin" /> Loading reference sprites…+ </div>+ ) : filtered.length === 0 ? (+ <div className="text-xs text-gray-500 py-10 text-center">+ {items.length === 0+ ? 'No sprites with a locked main reference yet — lock one first.'+ : 'No reference sprites match your search.'}+ </div>+ ) : (+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">+ {filtered.map((it) => (+ <button+ key={it.id}+ type="button"+ onClick={() => { onSelect?.(it); onClose?.(); }}+ className="text-left bg-port-bg border border-port-border rounded-lg p-2 hover:border-port-accent"+ >+ <SpritePreview recordId={it.id} path={it.path} className="w-full h-28 object-contain mb-1.5" />+ <span className="block text-xs font-medium text-white truncate">{it.name}</span>+ <span className="block text-[10px] text-gray-500 truncate">{it.id}</span>+ </button>+ ))}+ </div>+ )}+ </div>+ </Modal>+ );+}diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex 68fcbfed0c..d978024ffc 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -753,6 +753,7 @@ export default function Sprites() {mode={imageMode}onModeChange={setImageMode}onChanged={onWorkflowChanged}+ onForked={(rec) => { refresh(); navigate(`/sprites/${rec.id}`); }}/><WalkWorkflowrecord={detail.record}diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsindex f1e4bc6e83..aaa5dd9694 100644--- a/client/src/services/apiSprites.js+++ b/client/src/services/apiSprites.js@@ -9,6 +9,11 @@ import { request } from './apiCore.js';export const listSpriteRecords = (options = {}) => request('/sprites', options);export const getSpriteRecord = (id, options = {}) => request(`/sprites/${encodeURIComponent(id)}`, options);+// Characters with a locked main reference — the pool to seed a new main from+// (i2i) or fork. Returns [{ id, name, kind, path }] (path = record-relative+// main reference image).+export const listSpriteReferenceSources = (options = {}) => request('/sprites/reference-sources', options);+export const createSpriteRecord = (body, options = {}) => request('/sprites', {method: 'POST', body: JSON.stringify(body), ...options,});@@ -55,6 +60,13 @@ export const lockSpriteReference = (id, body, options = {}) => request(`/spritesmethod: 'POST', body: JSON.stringify(body), ...options,});+// Fork `id` into a new character seeded (image+text→image) from its locked main+// reference. Body: { name, id?, designPrompt, mode?, model?, effort?,+// initImageStrength? }. Returns { record, jobId, mode, target, anchorId }.+export const forkSpriteRecord = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/fork`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});+// Phase 3 (#2897): walk-animation workflow — one grok i2v clip per locked// directional anchor, deterministic server-side packaging, per-direction// approval into the finalized walk set.diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 55b3b60f48..75718aee65 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1052,6 +1052,27 @@ export const spriteReferenceGenerateSchema = z.object({effort: z.string().trim().max(32).optional(),designPrompt: z.string().max(4000).optional(),initImageStrength: optionalUnitNumber,+ // Alternative i2i seed sources for the main target — resolved server-side and+ // mutually exclusive with an uploaded `referenceImage` file (which the route+ // handles separately). `initImageGalleryFile` is a render-history gallery+ // basename; `initImageSpriteId` is another sprite whose locked main reference+ // seeds this one (the "fork"/derive-from case). Ignored for anchor targets.+ initImageGalleryFile: z.string().trim().max(300).optional(),+ initImageSpriteId: z.string().trim().max(200).optional(),+});++// 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. The+// design prompt is REQUIRED here (unlike a from-scratch generate) — a fork with+// no instructions is just a duplicate.+export const spriteForkSchema = z.object({+ name: z.string().trim().min(1).max(200),+ id: z.string().trim().max(200).optional(),+ designPrompt: z.string().trim().min(1).max(4000),+ mode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),+ model: z.string().trim().max(64).optional(),+ effort: z.string().trim().max(32).optional(),+ initImageStrength: optionalUnitNumber,});export const spriteReferenceLockSchema = z.object({diff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex 2a04b4da47..c2a19de701 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -19,6 +19,7 @@ import {spriteCreateSchema,spriteReferenceGenerateSchema,spriteReferenceLockSchema,+ spriteForkSchema,spriteWalkGenerateSchema,spriteWalkApproveSchema,spriteWalkPostprocessSchema,@@ -36,6 +37,7 @@ import {import { importFromSource } from '../services/sprites/importer.js';import {getReferenceSet, startReferenceGeneration, lockReference, patchSpriteRecord,+ listReferenceSources, forkSprite,} from '../services/sprites/reference.js';import {getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,@@ -61,6 +63,13 @@ router.get('/', asyncHandler(async (_req, res) => {res.json(await listRecords());}));+// Characters with a locked main reference — the pool that can seed a new main+// (i2i) or be forked. MUST precede `/:id` so the literal path isn't captured as+// an id param.+router.get('/reference-sources', asyncHandler(async (_req, res) => {+ res.json(await listReferenceSources());+}));+// 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) => {@@ -115,6 +124,14 @@ router.post('/:id/reference/lock', asyncHandler(async (req, res) => {res.json(await lockReference(req.params.id, body));}));+// Fork `:id` into a new character seeded (image+text→image) from its locked+// main reference. Creates the record then queues the main render; returns the+// new record + jobId. User-triggered per the AI-provider policy.+router.post('/:id/fork', asyncHandler(async (req, res) => {+ const body = validateRequest(spriteForkSchema, req.body);+ res.status(201).json(await forkSprite(req.params.id, body));+}));+// Phase 3 (#2897): queue one grok walk video for a locked directional// anchor. User-triggered per the AI-provider policy; everything after the// clip is deterministic local postprocessing.diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.jsindex 4edaa0073e..50b78324a5 100644--- a/server/routes/sprites.test.js+++ b/server/routes/sprites.test.js@@ -19,6 +19,8 @@ vi.mock('../services/sprites/reference.js', () => ({startReferenceGeneration: vi.fn(async () => ({ jobId: 'j1', mode: 'codex', target: 'main', anchorId: 'walk-south' })),lockReference: vi.fn(async () => ({ manifest: { status: 'in-progress' }, candidates: [] })),patchSpriteRecord: vi.fn(async (id, patch) => ({ id, ...patch })),+ listReferenceSources: vi.fn(async () => [{ id: 'pioneer', name: 'Pioneer', kind: 'character', path: 'reference/pioneer-walk-south-v1.png' }]),+ forkSprite: vi.fn(async (sourceId, body) => ({ record: { id: 'pioneer-fork', kind: 'character', name: body.name }, jobId: 'j1', mode: 'codex', target: 'main', anchorId: 'walk-south' })),}));vi.mock('../services/sprites/walk.js', () => ({@@ -99,6 +101,38 @@ describe('sprites routes', () => {expect(records.createCharacter).not.toHaveBeenCalled();});+ it('GET /reference-sources lists lockable reference sprites (before /:id)', async () => {+ const r = await request(app).get('/api/sprites/reference-sources');+ expect(r.status).toBe(200);+ expect(r.body).toEqual([{ id: 'pioneer', name: 'Pioneer', kind: 'character', path: 'reference/pioneer-walk-south-v1.png' }]);+ expect(reference.listReferenceSources).toHaveBeenCalled();+ // The literal path must not be swallowed by the /:id route.+ expect(records.getRecordWithAssets).not.toHaveBeenCalled();+ });++ it('POST /:id/fork validates and delegates to forkSprite', async () => {+ const r = await request(app).post('/api/sprites/pioneer/fork')+ .send({ name: 'Pioneer Fork', designPrompt: 'now with a red coat' });+ expect(r.status).toBe(201);+ expect(r.body.record.id).toBe('pioneer-fork');+ expect(reference.forkSprite).toHaveBeenCalledWith('pioneer', expect.objectContaining({ name: 'Pioneer Fork', designPrompt: 'now with a red coat' }));+ });++ it('POST /:id/fork rejects a missing design prompt at the schema', async () => {+ const bad = await request(app).post('/api/sprites/pioneer/fork').send({ name: 'Pioneer Fork' });+ expect(bad.status).toBe(400);+ expect(reference.forkSprite).not.toHaveBeenCalled();+ });++ it('POST /:id/reference/generate accepts a gallery/sprite seed source in JSON', async () => {+ const r = await request(app).post('/api/sprites/pioneer/reference/generate')+ .send({ target: 'main', designPrompt: 'x', initImageSpriteId: 'trailhand' });+ expect(r.status).toBe(200);+ expect(reference.startReferenceGeneration).toHaveBeenCalledWith(+ 'pioneer', expect.objectContaining({ target: 'main', initImageSpriteId: 'trailhand' }), null,+ );+ });+it('GET /:id returns record + assets + reference set for characters', async () => {records.getRecordWithAssets.mockResolvedValueOnce({record: { id: 'pioneer', kind: 'character' },diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.jsindex 351b9b37b4..d3a4284e50 100644--- a/server/services/sprites/reference.js+++ b/server/services/sprites/reference.js@@ -19,7 +19,7 @@ import { join } from 'path';import { readdir, copyFile } from 'fs/promises';import {PATHS, ensureDir, sha256File, atomicWrite, pathExists, readJSONFile,- importFileToDir, listDirectoryByExtension,+ importFileToDir, listDirectoryByExtension, resolveGalleryImage,} from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';@@ -30,7 +30,7 @@ import {} from '../imageGen/modes.js';import { resolveImageCleaners } from '../imageGen/index.js';import { getSettings } from '../settings.js';-import { getRecord, updateRecord } from './records.js';+import { getRecord, updateRecord, listRecords, createCharacter } from './records.js';import { spriteDir, resolveSpriteAssetPath } from './paths.js';import {SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS, anchorIdForDirection,@@ -239,23 +239,41 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {throw new ServerError('Main reference is locked — corrections require a new character version, never regeneration', { status: 409, code: 'REFERENCE_LOCKED' });}const designPrompt = typeof body.designPrompt === 'string' ? body.designPrompt.trim() : '';- if (!designPrompt && !upload) {+ // A main render needs SOME input: a prompt, an uploaded image, a gallery+ // pick, or another sprite's reference to seed from.+ const hasInitSource = !!upload || !!body.initImageGalleryFile || !!body.initImageSpriteId;+ if (!designPrompt && !hasInitSource) {throw new ServerError('Provide a design prompt and/or a reference image', { status: 400, code: 'DESIGN_INPUT_REQUIRED' });}anchorId = anchorIdForDirection('south');direction = 'south';prompt = buildMainReferencePrompt({ name: record.name, designPrompt, chromaKey: genKey });+ // Resolve the i2i seed image from exactly one source (upload wins, then a+ // gallery pick, then another sprite's locked main). `designReferencePath`+ // is the provenance marker that rides the tag into the candidate sidecar.if (upload) {- // Shared temp-import (uuid-prefixed name, EXDEV-safe copy+unlink) —- // the upload persists in the record dir as design provenance, and its- // record-relative path rides the tag into the candidate sidecar so a- // locked candidate stays traceable to the upload that guided it.+ // Shared temp-import (uuid-prefixed name, EXDEV-safe copy+unlink) — the+ // upload persists in the record dir as design provenance so a locked+ // candidate stays traceable to the upload that guided it.const uploadsDir = join(spriteDir(recordId), 'reference', 'uploads');const { filename } = await importFileToDir(upload.tempPath, upload.originalname || 'design-reference.png', uploadsDir);initImagePath = join(uploadsDir, filename);designReferencePath = `reference/uploads/${filename}`;- initImageStrength ??= UPLOAD_DEFAULT_STRENGTH;+ } else if (body.initImageGalleryFile) {+ const resolved = resolveGalleryImage(body.initImageGalleryFile);+ if (!resolved) {+ throw new ServerError('Reference image not found in the render-history gallery', { status: 400, code: 'INIT_IMAGE_NOT_FOUND' });+ }+ initImagePath = resolved;+ designReferencePath = `gallery:${body.initImageGalleryFile}`;+ } else if (body.initImageSpriteId) {+ const sourceMain = await resolveSourceReference(body.initImageSpriteId);+ initImagePath = sourceMain.absPath;+ designReferencePath = `sprite:${body.initImageSpriteId}/${sourceMain.relPath}`;}+ // Every main seed source shares the same default fidelity (anchors use a+ // higher one, set in their own branch).+ if (initImagePath) initImageStrength ??= UPLOAD_DEFAULT_STRENGTH;if (designPrompt) manifest.designPrompt = designPrompt;// Only the main branch mutates (or may have just seeded) the manifest —// the anchor branch requires a locked main, so its manifest already@@ -321,6 +339,69 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {return { jobId, mode, target, anchorId };}+/**+ * Resolve a source sprite's locked main reference to an on-disk init image.+ * Throws (400/500) rather than silently degrading to text-to-image so the+ * caller learns the fork/derive source is unusable up front.+ */+async function resolveSourceReference(sourceId) {+ // loadManifest, not getReferenceSet — we only need mainReference, and the+ // latter also enumerates + reads every candidate sidecar (wasted here).+ const manifest = await loadManifest(sourceId);+ const main = manifest?.mainReference;+ if (!main?.locked || !main.path) {+ throw new ServerError('The source sprite has no locked main reference to seed from', { status: 400, code: 'SOURCE_REFERENCE_MISSING' });+ }+ const absPath = resolveSpriteAssetPath(sourceId, main.path);+ if (!await pathExists(absPath)) {+ throw new ServerError('The source sprite reference file is missing on disk', { status: 500, code: 'SOURCE_REFERENCE_FILE_MISSING' });+ }+ return { absPath, relPath: main.path };+}++/**+ * List every character whose main reference is locked — the pool that can seed+ * a new main (the "select an existing reference sprite" picker) or be forked.+ * Reads each character's manifest (loadManifest, not getReferenceSet — the+ * candidate enumeration the latter does is wasted here), so it's a per-request+ * O(characters) scan; fine for a user-triggered modal fetch, revisit if the+ * library grows huge.+ */+export async function listReferenceSources() {+ const records = await listRecords();+ const out = [];+ for (const r of records) {+ if (r.kind !== 'character' || r.deleted) continue;+ const manifest = await loadManifest(r.id);+ const main = manifest?.mainReference;+ if (main?.locked && main.path) out.push({ id: r.id, name: r.name, kind: r.kind, path: main.path });+ }+ return out;+}++/**+ * 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 the+ * shared generate path (`initImageSpriteId`). Validates the source BEFORE+ * creating the record so a bad fork never leaves an orphan character behind.+ * User-triggered only.+ */+export async function forkSprite(sourceId, body) {+ await resolveSourceReference(sourceId); // fail fast before creating a record+ const record = await createCharacter({ name: body.name, id: body.id, kind: 'character' });+ const gen = await startReferenceGeneration(record.id, {+ target: 'main',+ designPrompt: body.designPrompt,+ initImageSpriteId: sourceId,+ ...(body.mode ? { mode: body.mode } : {}),+ ...(body.model ? { model: body.model } : {}),+ ...(body.effort ? { effort: body.effort } : {}),+ ...(Number.isFinite(body.initImageStrength) ? { initImageStrength: body.initImageStrength } : {}),+ });+ console.log(`🧬 sprite fork ${sourceId} → ${record.id} jobId=${gen.jobId.slice(0, 8)}`);+ return { record, ...gen };+}+/*** Completion-hook attach: copy a finished render from the shared image* gallery into the record's reference/candidates/ with a generation sidecar.diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.jsindex 39b039a577..75d330ca2e 100644--- a/server/services/sprites/reference.test.js+++ b/server/services/sprites/reference.test.js@@ -53,6 +53,7 @@ vi.mock('../settings.js', () => ({ getSettings: async () => settings }));const records = await import('./records.js');const {getReferenceSet, startReferenceGeneration, attachReferenceCandidate, lockReference, patchSpriteRecord,+ listReferenceSources, forkSprite,} = await import('./reference.js');let seq = 0;@@ -446,3 +447,90 @@ describe('lockReference', () => {expect(record.status).toBe('reference-complete');});});++describe('main-reference i2i seed sources', () => {+ it('seeds the main from a gallery image (initImageGalleryFile)', async () => {+ const id = newId();+ await createCharacter(id);+ // resolveGalleryImage resolves a basename under PATHS.images (the test root).+ const galleryName = 'render-history-pick.png';+ await writeCandidatePng(join(TEST_ROOT, 'images', galleryName));+ await startReferenceGeneration(id, { target: 'main', designPrompt: 'red coat', initImageGalleryFile: galleryName });+ const call = enqueueJob.mock.calls[0][0];+ expect(call.params.initImagePath).toBe(join(TEST_ROOT, 'images', galleryName));+ expect(call.params.initImageStrength).toBe(0.65);+ expect(call.params.spriteRef.designReferencePath).toBe(`gallery:${galleryName}`);+ });++ it('400s a gallery pick that is not in the gallery', async () => {+ const id = newId();+ await createCharacter(id);+ await expect(startReferenceGeneration(id, { target: 'main', designPrompt: 'x', initImageGalleryFile: 'ghost.png' }))+ .rejects.toMatchObject({ code: 'INIT_IMAGE_NOT_FOUND', status: 400 });+ });++ it('seeds the main from another sprite\'s locked reference (initImageSpriteId)', async () => {+ const source = newId();+ await createCharacter(source);+ await lockMain(source);+ const dest = newId();+ await createCharacter(dest);+ enqueueJob.mockClear();+ await startReferenceGeneration(dest, { target: 'main', designPrompt: 'now with a hat', initImageSpriteId: source });+ const call = enqueueJob.mock.calls[0][0];+ expect(call.params.initImagePath).toBe(join(TEST_ROOT, 'sprites', source, `reference/${source}-walk-south-v1.png`));+ expect(call.params.spriteRef.designReferencePath).toBe(`sprite:${source}/reference/${source}-walk-south-v1.png`);+ });++ it('400s seeding from a source with no locked main', async () => {+ const source = newId();+ await createCharacter(source); // never locked+ const dest = newId();+ await createCharacter(dest);+ await expect(startReferenceGeneration(dest, { target: 'main', designPrompt: 'x', initImageSpriteId: source }))+ .rejects.toMatchObject({ code: 'SOURCE_REFERENCE_MISSING', status: 400 });+ });+});++describe('listReferenceSources', () => {+ it('returns only characters whose main reference is locked', async () => {+ const locked = newId();+ await createCharacter(locked, { name: 'Locked One' });+ await lockMain(locked);+ const draft = newId();+ await createCharacter(draft, { name: 'Draft One' }); // no main lock+ const sources = await listReferenceSources();+ const ids = sources.map((s) => s.id);+ expect(ids).toContain(locked);+ expect(ids).not.toContain(draft);+ const entry = sources.find((s) => s.id === locked);+ expect(entry).toMatchObject({ id: locked, name: 'Locked One', kind: 'character' });+ expect(entry.path).toContain(`${locked}-walk-south-v1.png`);+ });+});++describe('forkSprite', () => {+ it('creates a new character and queues its main seeded from the source reference', async () => {+ const source = newId();+ await createCharacter(source, { name: 'Origin' });+ await lockMain(source);+ enqueueJob.mockClear();+ const { record, jobId, target } = await forkSprite(source, { name: 'Origin Fork', designPrompt: 'wearing a red coat' });+ expect(target).toBe('main');+ expect(jobId).toBe('job-1234567890');+ expect(record.kind).toBe('character');+ expect(record.name).toBe('Origin Fork');+ // The new record exists and the render was seeded from the source's ref.+ expect(await records.getRecord(record.id)).toBeTruthy();+ const call = enqueueJob.mock.calls[0][0];+ expect(call.params.spriteRef.recordId).toBe(record.id);+ expect(call.params.initImagePath).toBe(join(TEST_ROOT, 'sprites', source, `reference/${source}-walk-south-v1.png`));+ });++ it('400s forking a source with no locked main and creates no orphan record', async () => {+ const source = newId();+ await createCharacter(source);+ await expect(forkSprite(source, { name: 'Bad Fork', designPrompt: 'x' }))+ .rejects.toMatchObject({ code: 'SOURCE_REFERENCE_MISSING', status: 400 });+ });+});