Skip to content

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

show and copy the generation prompt in sprite image preview modals

[._.]/ Adam Eivy33d6907337c5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e2951d114e..c2af73596d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,6 +17,7 @@
## Sprite Manager
+- **See — and copy — the prompt behind any sprite image** — click a reference-set image (the frozen main, a locked directional anchor, or any generation candidate) and the enlarged preview now shows the exact prompt that produced it, with a one-click **Copy prompt** button, the same way the image render-history preview does. The asset inspector gains the same prompt block, so a walk-animation clip or any generated asset you open there shows its prompt too. Older images generated before this shipped still show their prompt — it's reconstructed from the render's recorded design description, direction, and background color — so nothing in your existing library is blank. Imported artwork and internal metadata files simply omit the block. New endpoint `GET /api/sprites/:id/asset-prompt`.
- **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 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`.
- **Click any reference-set image to enlarge it** — the Reference Set's inline thumbnails (the frozen main reference, each locked directional anchor, and every generation candidate) are now click-to-zoom: clicking one opens a large, pixel-perfect preview over the same checkerboard the asset inspector uses, so you can actually judge a candidate before locking it instead of squinting at a thumbnail. Previews elsewhere are unaffected unless they opt in.
diff --git a/client/src/components/sprites/AssetInspector.jsx b/client/src/components/sprites/AssetInspector.jsx
index 72cd5aeb9e..9df9d8b65d 100644
--- a/client/src/components/sprites/AssetInspector.jsx
+++ b/client/src/components/sprites/AssetInspector.jsx
@@ -13,6 +13,7 @@ import { useEffect, useState } from 'react';
import { Download, ClipboardCopy, ExternalLink, Trash2, X } from 'lucide-react';
import Modal from '../ui/Modal.jsx';
import SpritePreview from './SpritePreview.jsx';
+import AssetPromptSection from './AssetPromptSection.jsx';
import { spriteAssetUrl, hasSpritePreview, isVideoAsset } from './spriteAssets.js';
import { isRuntimeVersionPath, isRuntimeSidecarManifest } from '../../lib/spriteFacets.js';
import { formatBytes, timeAgo } from '../../utils/formatters.js';
@@ -134,6 +135,8 @@ export default function AssetInspector({ recordId, asset, onClose, onDeleted = n
<Row label="Modified" value={asset.mtime ? timeAgo(asset.mtime) : null} />
</dl>
+ <AssetPromptSection recordId={recordId} path={asset.path} />
+
<div className="flex flex-wrap items-center gap-2">
<a
href={url}
diff --git a/client/src/components/sprites/AssetInspector.test.jsx b/client/src/components/sprites/AssetInspector.test.jsx
index bc0e158ce5..8178881452 100644
--- a/client/src/components/sprites/AssetInspector.test.jsx
+++ b/client/src/components/sprites/AssetInspector.test.jsx
@@ -16,7 +16,11 @@ const copyToClipboard = vi.fn();
vi.mock('../../lib/clipboard.js', () => ({ copyToClipboard: (...a) => copyToClipboard(...a) }));
const deleteSpriteAsset = vi.fn();
-vi.mock('../../services/apiSprites.js', () => ({ deleteSpriteAsset: (...a) => deleteSpriteAsset(...a) }));
+const getSpriteAssetPrompt = vi.fn(() => Promise.resolve(null));
+vi.mock('../../services/apiSprites.js', () => ({
+ deleteSpriteAsset: (...a) => deleteSpriteAsset(...a),
+ getSpriteAssetPrompt: (...a) => getSpriteAssetPrompt(...a),
+}));
const IMAGE = {
path: 'reference/main.png',
@@ -28,7 +32,12 @@ const IMAGE = {
frameCount: 1,
};
-beforeEach(() => { copyToClipboard.mockClear(); deleteSpriteAsset.mockReset(); });
+beforeEach(() => {
+ copyToClipboard.mockClear();
+ deleteSpriteAsset.mockReset();
+ getSpriteAssetPrompt.mockReset();
+ getSpriteAssetPrompt.mockResolvedValue(null);
+});
describe('hasSpritePreview', () => {
it('follows the server probe rather than the file extension', () => {
@@ -125,6 +134,24 @@ describe('AssetInspector', () => {
expect(open).not.toHaveAttribute('download');
});
+ it('shows the generation prompt with a copy button once it resolves', async () => {
+ getSpriteAssetPrompt.mockResolvedValue({ prompt: 'a brave knight, magenta background', designPrompt: 'a brave knight', source: 'candidate' });
+ render(<AssetInspector recordId="trail-hand" asset={IMAGE} onClose={() => {}} />);
+
+ expect(getSpriteAssetPrompt).toHaveBeenCalledWith('trail-hand', 'reference/main.png', { silent: true });
+ expect(await screen.findByText('a brave knight, magenta background')).toBeInTheDocument();
+ await userEvent.click(screen.getByRole('button', { name: /copy prompt/i }));
+ expect(copyToClipboard).toHaveBeenCalledWith('a brave knight, magenta background', 'Prompt copied');
+ });
+
+ it('omits the prompt block for an asset with no prompt provenance', async () => {
+ getSpriteAssetPrompt.mockResolvedValue(null);
+ render(<AssetInspector recordId="trail-hand" asset={IMAGE} onClose={() => {}} />);
+ // Give the effect a tick to resolve before asserting absence.
+ await screen.findByText('reference/main.png');
+ expect(screen.queryByRole('button', { name: /copy prompt/i })).not.toBeInTheDocument();
+ });
+
it('renders nothing when no asset is selected', () => {
const { container } = render(<AssetInspector recordId="trail-hand" asset={null} onClose={() => {}} />);
expect(container).toBeEmptyDOMElement();
diff --git a/client/src/components/sprites/AssetPromptSection.jsx b/client/src/components/sprites/AssetPromptSection.jsx
new file mode 100644
index 0000000000..4d01db5fcb
--- /dev/null
+++ b/client/src/components/sprites/AssetPromptSection.jsx
@@ -0,0 +1,55 @@
+/**
+ * The generation prompt for one sprite asset, shown inside an image-preview
+ * modal (SpriteLightbox, AssetInspector) with a copy button — the same
+ * "Prompt + copy" affordance the render-history MediaLightbox has.
+ *
+ * Self-fetching by (recordId, path): the two hosts open on quite different
+ * data (a reference candidate object vs. a bare on-disk asset row), so rather
+ * than thread a prompt prop down two paths this resolves it from the shared
+ * `/sprites/:id/asset-prompt` endpoint. Best-effort — renders nothing until a
+ * prompt resolves, and nothing at all for an asset with no prompt provenance
+ * (imports, manifests), so a host can drop it in unconditionally.
+ */
+
+import { useEffect, useState } from 'react';
+import { Copy } from 'lucide-react';
+import { getSpriteAssetPrompt } from '../../services/apiSprites.js';
+import { copyToClipboard } from '../../lib/clipboard.js';
+
+export default function AssetPromptSection({ recordId, path }) {
+ const [data, setData] = useState(null);
+
+ useEffect(() => {
+ let active = true;
+ setData(null);
+ if (!recordId || !path) return undefined;
+ // silent: this is a best-effort provenance lookup — a miss should never
+ // toast over the modal the user opened just to look at the image.
+ getSpriteAssetPrompt(recordId, path, { silent: true })
+ .then((res) => { if (active) setData(res); })
+ .catch(() => { if (active) setData(null); });
+ return () => { active = false; };
+ }, [recordId, path]);
+
+ if (!data?.prompt) return null;
+
+ return (
+ <div>
+ <div className="flex items-center justify-between mb-1">
+ <span className="text-[11px] uppercase tracking-wide text-gray-500">Prompt</span>
+ <button
+ type="button"
+ onClick={() => copyToClipboard(data.prompt, 'Prompt copied')}
+ className="p-1 rounded text-gray-400 hover:text-white hover:bg-port-border/50"
+ title="Copy prompt"
+ aria-label="Copy prompt"
+ >
+ <Copy className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ <p className="text-xs text-gray-200 whitespace-pre-wrap max-h-40 overflow-y-auto rounded border border-port-border bg-port-bg p-2">
+ {data.prompt}
+ </p>
+ </div>
+ );
+}
diff --git a/client/src/components/sprites/AssetPromptSection.test.jsx b/client/src/components/sprites/AssetPromptSection.test.jsx
new file mode 100644
index 0000000000..8de6db568a
--- /dev/null
+++ b/client/src/components/sprites/AssetPromptSection.test.jsx
@@ -0,0 +1,61 @@
+/**
+ * AssetPromptSection — the "Prompt + copy" block the sprite preview modals
+ * share. Covers the three states: resolved prompt (shown + copyable), no
+ * provenance (renders nothing), and a re-fetch when the asset path changes.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import AssetPromptSection from './AssetPromptSection.jsx';
+
+const copyToClipboard = vi.fn();
+vi.mock('../../lib/clipboard.js', () => ({ copyToClipboard: (...a) => copyToClipboard(...a) }));
+
+const getSpriteAssetPrompt = vi.fn();
+vi.mock('../../services/apiSprites.js', () => ({ getSpriteAssetPrompt: (...a) => getSpriteAssetPrompt(...a) }));
+
+beforeEach(() => { copyToClipboard.mockClear(); getSpriteAssetPrompt.mockReset(); });
+
+describe('AssetPromptSection', () => {
+ it('fetches silently and shows the prompt with a copy button', async () => {
+ getSpriteAssetPrompt.mockResolvedValue({ prompt: 'THE PROMPT', designPrompt: null, source: 'candidate' });
+ render(<AssetPromptSection recordId="hero" path="reference/candidates/walk-south-candidate-01.png" />);
+
+ expect(getSpriteAssetPrompt).toHaveBeenCalledWith('hero', 'reference/candidates/walk-south-candidate-01.png', { silent: true });
+ expect(await screen.findByText('THE PROMPT')).toBeInTheDocument();
+ await userEvent.click(screen.getByRole('button', { name: /copy prompt/i }));
+ expect(copyToClipboard).toHaveBeenCalledWith('THE PROMPT', 'Prompt copied');
+ });
+
+ it('renders nothing when the asset has no prompt provenance', async () => {
+ getSpriteAssetPrompt.mockResolvedValue(null);
+ const { container } = render(<AssetPromptSection recordId="hero" path="atlas/x.png" />);
+ await waitFor(() => expect(getSpriteAssetPrompt).toHaveBeenCalled());
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('renders nothing (and does not fetch) without a recordId or path', () => {
+ const { container } = render(<AssetPromptSection recordId={null} path={null} />);
+ expect(getSpriteAssetPrompt).not.toHaveBeenCalled();
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('never throws when the lookup fails — the modal still shows the image', async () => {
+ getSpriteAssetPrompt.mockRejectedValue(new Error('boom'));
+ const { container } = render(<AssetPromptSection recordId="hero" path="reference/main.png" />);
+ await waitFor(() => expect(getSpriteAssetPrompt).toHaveBeenCalled());
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('re-fetches when the path changes', async () => {
+ getSpriteAssetPrompt.mockResolvedValue({ prompt: 'first', source: 'candidate' });
+ const { rerender } = render(<AssetPromptSection recordId="hero" path="a.png" />);
+ expect(await screen.findByText('first')).toBeInTheDocument();
+
+ getSpriteAssetPrompt.mockResolvedValue({ prompt: 'second', source: 'candidate' });
+ rerender(<AssetPromptSection recordId="hero" path="b.png" />);
+ expect(await screen.findByText('second')).toBeInTheDocument();
+ expect(getSpriteAssetPrompt).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/client/src/components/sprites/SpriteLightbox.jsx b/client/src/components/sprites/SpriteLightbox.jsx
index 65bef6aab0..3d4ef5842b 100644
--- a/client/src/components/sprites/SpriteLightbox.jsx
+++ b/client/src/components/sprites/SpriteLightbox.jsx
@@ -12,6 +12,7 @@
import { X } from 'lucide-react';
import Modal from '../ui/Modal.jsx';
+import AssetPromptSection from './AssetPromptSection.jsx';
import { checkerboardStyle, spriteAssetUrl, PIXELATED } from './spriteAssets.js';
export default function SpriteLightbox({ recordId, path, alt, onClose }) {
@@ -48,6 +49,7 @@ export default function SpriteLightbox({ recordId, path, alt, onClose }) {
style={PIXELATED}
/>
</span>
+ <AssetPromptSection recordId={recordId} path={path} />
</div>
</Modal>
);
diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.js
index f1818a1da6..ed3d931ac5 100644
--- a/client/src/services/apiSprites.js
+++ b/client/src/services/apiSprites.js
@@ -20,6 +20,15 @@ export const listSpriteReferenceSources = (options = {}) => request('/sprites/re
// asset. Records with no usable image are omitted.
export const listSpriteThumbnails = (options = {}) => request('/sprites/thumbnails', options);
+// The generation prompt behind one on-disk asset (record-relative `path`) —
+// reference candidate, locked main/anchor, or walk render. Returns
+// `{ prompt, designPrompt, source }` or `null` when the asset has no prompt
+// provenance. Callers own their (best-effort) UI, so pass `{ silent: true }`.
+export const getSpriteAssetPrompt = (id, path, options = {}) => request(
+ `/sprites/${encodeURIComponent(id)}/asset-prompt?path=${encodeURIComponent(path)}`,
+ options,
+);
+
export const createSpriteRecord = (body, options = {}) => request('/sprites', {
method: 'POST', body: JSON.stringify(body), ...options,
});
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index f441a6bb8d..1c56fe4499 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -39,6 +39,7 @@ import {
getReferenceSet, startReferenceGeneration, lockReference, patchSpriteRecord,
listReferenceSources, listSpriteThumbnails, forkSprite,
} from '../services/sprites/reference.js';
+import { resolveSpriteAssetPrompt } from '../services/sprites/assetPrompt.js';
import {
getWalkState, startWalkGeneration, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
} from '../services/sprites/walk.js';
@@ -105,6 +106,16 @@ router.get('/:id', asyncHandler(async (req, res) => {
res.json({ ...detail, reference, walk, atlas });
}));
+// The generation prompt behind one on-disk asset (record-relative `path`) —
+// reference candidate, locked main/anchor, or walk-animation render — so the
+// client's preview modals can show + copy it. Returns `null` for an asset with
+// no prompt provenance (imports, manifests). Two path segments, so it never
+// collides with the single-segment `/:id` GET above.
+router.get('/:id/asset-prompt', asyncHandler(async (req, res) => {
+ const { path } = validateRequest(z.object({ path: z.string().min(1) }), req.query);
+ res.json(await resolveSpriteAssetPrompt(req.params.id, path));
+}));
+
// Queue one reference candidate render (main or a directional anchor).
// Accepts JSON, or multipart with an optional `referenceImage` file for the
// main target (an uploaded visual design reference → i2i).
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index 50b78324a5..388dd721c7 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -23,6 +23,10 @@ vi.mock('../services/sprites/reference.js', () => ({
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/assetPrompt.js', () => ({
+ resolveSpriteAssetPrompt: vi.fn(async () => ({ prompt: 'the built prompt', designPrompt: 'a knight', source: 'candidate' })),
+}));
+
vi.mock('../services/sprites/walk.js', () => ({
getWalkState: vi.fn(async () => ({ runs: [], selection: null, walkSet: null })),
startWalkGeneration: vi.fn(async () => ({ jobId: 'v1', runId: 'walk-east-0a1b2c3d', direction: 'east', duration: 6 })),
@@ -51,6 +55,7 @@ vi.mock('../services/sprites/assets.js', () => ({
import * as records from '../services/sprites/records.js';
import * as importer from '../services/sprites/importer.js';
import * as reference from '../services/sprites/reference.js';
+import * as assetPrompt from '../services/sprites/assetPrompt.js';
import * as walk from '../services/sprites/walk.js';
import * as walkTrims from '../services/sprites/walkTrims.js';
import * as atlas from '../services/sprites/atlas.js';
@@ -110,6 +115,21 @@ describe('sprites routes', () => {
expect(records.getRecordWithAssets).not.toHaveBeenCalled();
});
+ it('GET /:id/asset-prompt resolves an asset prompt by record-relative path', async () => {
+ const r = await request(app).get(`/api/sprites/pioneer/asset-prompt?path=${encodeURIComponent('reference/candidates/walk-south-candidate-01.png')}`);
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual({ prompt: 'the built prompt', designPrompt: 'a knight', source: 'candidate' });
+ expect(assetPrompt.resolveSpriteAssetPrompt).toHaveBeenCalledWith('pioneer', 'reference/candidates/walk-south-candidate-01.png');
+ // Two segments — the single-segment /:id GET must not swallow it.
+ expect(records.getRecordWithAssets).not.toHaveBeenCalled();
+ });
+
+ it('GET /:id/asset-prompt rejects a missing path at the schema', async () => {
+ const bad = await request(app).get('/api/sprites/pioneer/asset-prompt');
+ expect(bad.status).toBe(400);
+ expect(assetPrompt.resolveSpriteAssetPrompt).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' });
diff --git a/server/services/sprites/assetPrompt.js b/server/services/sprites/assetPrompt.js
new file mode 100644
index 0000000000..a631a3dffa
--- /dev/null
+++ b/server/services/sprites/assetPrompt.js
@@ -0,0 +1,126 @@
+/**
+ * Sprites — generation-prompt provenance for any on-disk asset.
+ *
+ * Resolves "what prompt produced this image?" for a record-relative asset path,
+ * so the client's image-preview surfaces (SpriteLightbox, AssetInspector) can
+ * show + copy the prompt the way the render-history MediaLightbox does. Covers
+ * every image the Sprite Manager generates:
+ *
+ * - reference/candidates/<anchor>-candidate-NN.png — the reviewable renders.
+ * Newer candidates persist the literal prompt in their `.generation.json`
+ * sidecar (attach hook); older ones predate that capture, so the prompt is
+ * reconstructed deterministically from the sidecar's designPrompt/direction
+ * /chromaKey via the same builders that generated it.
+ * - reference/<id>-walk-<dir>-vN.png — the locked main + directional anchors.
+ * Resolved through the manifest: prefer the frozen candidate's literal
+ * prompt (`lockedFrom`), else rebuild from the manifest's own designPrompt/
+ * chromaKey.
+ * - grok|runs/<run>/… — walk-animation assets, rebuilt from the run record's
+ * direction + chromaKey (the i2v motion prompt is a pure function of those).
+ *
+ * Returns `null` for an asset PortOS didn't generate from a prompt (imported
+ * atlases, manifests, uploads) so the client simply omits the prompt block.
+ * Reconstruction is deterministic and needs no migration — the stored literal
+ * is only ever a fidelity upgrade over it, never a correctness requirement.
+ */
+
+import { join } from 'path';
+import { readJSONFile } from '../../lib/fileUtils.js';
+import { spriteDir, resolveSpriteAssetPath, RUN_DIR_MATCH } from './paths.js';
+import { getRecord } from './records.js';
+import { loadManifest } from './reference.js';
+import { buildMainReferencePrompt, buildAnchorPrompt, buildWalkVideoPrompt } from './prompts.js';
+
+const CANDIDATE_RE = /^reference\/candidates\/(.+)\.png$/i;
+
+/**
+ * Turn a candidate's generation sidecar into a `{ prompt, designPrompt,
+ * source }` result — the stored literal prompt when captured, otherwise a
+ * faithful rebuild from the parameters the sidecar did record.
+ */
+function fromCandidateSidecar(sidecar, name) {
+ if (!sidecar) return null;
+ if (typeof sidecar.prompt === 'string' && sidecar.prompt) {
+ return { prompt: sidecar.prompt, designPrompt: sidecar.designPrompt || null, source: 'candidate' };
+ }
+ // Pre-capture candidate — rebuild with the builder that produced it.
+ const prompt = sidecar.target === 'main'
+ ? buildMainReferencePrompt({ name, designPrompt: sidecar.designPrompt, chromaKey: sidecar.chromaKey })
+ : buildAnchorPrompt({ name, direction: sidecar.direction || sidecar.target, chromaKey: sidecar.chromaKey });
+ return { prompt, designPrompt: sidecar.designPrompt || null, source: 'candidate-reconstructed' };
+}
+
+async function candidateSidecarFor(recordId, candidateStem) {
+ return readJSONFile(join(spriteDir(recordId), 'reference', 'candidates', `${candidateStem}.generation.json`), null);
+}
+
+/**
+ * The generation prompt for a record-relative sprite asset, or `null` when the
+ * asset has no prompt provenance. `relPath` is confined to the record dir
+ * (throws on traversal) before any file read.
+ */
+export async function resolveSpriteAssetPrompt(recordId, relPath) {
+ // Confinement + id validity gate (throws on escape / bad id) before I/O.
+ resolveSpriteAssetPath(recordId, relPath);
+ const record = await getRecord(recordId);
+ if (!record) return null;
+ const name = record.name;
+
+ // 1. Reviewable candidate — its own generation sidecar.
+ const cand = CANDIDATE_RE.exec(relPath);
+ if (cand) {
+ return fromCandidateSidecar(await candidateSidecarFor(recordId, cand[1]), name);
+ }
+
+ // 2. Locked main / directional anchor — resolved through the manifest.
+ if (/^reference\//i.test(relPath)) {
+ const manifest = await loadManifest(recordId);
+ if (manifest) {
+ const main = manifest.mainReference;
+ if (main?.path === relPath) {
+ // Prefer the frozen candidate's literal prompt; fall back to a rebuild
+ // from the manifest's own recorded design prompt + key.
+ const stem = candidateStem(main.lockedFrom);
+ const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name) : null;
+ return fromCandidate || {
+ prompt: buildMainReferencePrompt({ name, designPrompt: manifest.designPrompt, chromaKey: manifest.chromaKey }),
+ designPrompt: manifest.designPrompt || null,
+ source: 'reference-main',
+ };
+ }
+ const anchor = (manifest.anchors || []).find((a) => a.path === relPath);
+ if (anchor) {
+ const stem = candidateStem(anchor.lockedFrom);
+ const fromCandidate = stem ? fromCandidateSidecar(await candidateSidecarFor(recordId, stem), name) : null;
+ return fromCandidate || {
+ prompt: buildAnchorPrompt({ name, direction: anchor.direction, chromaKey: manifest.chromaKey }),
+ designPrompt: null,
+ source: 'reference-anchor',
+ };
+ }
+ }
+ }
+
+ // 3. Walk-animation asset — rebuild the i2v motion prompt from the run record.
+ const run = RUN_DIR_MATCH.exec(relPath);
+ if (run) {
+ const runRecord = await readJSONFile(join(spriteDir(recordId), run[0], 'animation-run.json'), null);
+ if (runRecord?.direction) {
+ return {
+ prompt: typeof runRecord.prompt === 'string' && runRecord.prompt
+ ? runRecord.prompt
+ : buildWalkVideoPrompt({ name, direction: runRecord.direction, chromaKey: runRecord.chromaKey }),
+ designPrompt: null,
+ source: 'walk',
+ };
+ }
+ }
+
+ return null;
+}
+
+// `reference/candidates/<stem>.png` → `<stem>`; anything else → null.
+function candidateStem(candidatePath) {
+ const m = typeof candidatePath === 'string' ? CANDIDATE_RE.exec(candidatePath) : null;
+ return m ? m[1] : null;
+}
diff --git a/server/services/sprites/assetPrompt.test.js b/server/services/sprites/assetPrompt.test.js
new file mode 100644
index 0000000000..982b894ae9
--- /dev/null
+++ b/server/services/sprites/assetPrompt.test.js
@@ -0,0 +1,161 @@
+/**
+ * Asset-prompt provenance resolver (#sprite-prompt-preview): maps a
+ * record-relative asset path to the prompt that generated it — stored literal
+ * when captured, deterministic rebuild otherwise — for the preview modals.
+ * Mirrors reference.test.js's mock setup (PATHS mutation + queue/imagegen/
+ * settings stubs) so importing reference.js doesn't pull the live graph.
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { mkdir, writeFile } from 'fs/promises';
+import { writeCandidatePng, placeCandidate as placeCandidateFixture } from './spriteTestFixtures.js';
+
+const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-assetprompt-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ Object.assign(actual.PATHS, {
+ data: TEST_ROOT,
+ sprites: join(TEST_ROOT, 'sprites'),
+ images: join(TEST_ROOT, 'images'),
+ });
+ return actual;
+});
+
+vi.mock('../mediaJobQueue/index.js', () => ({
+ enqueueJob: () => ({ jobId: 'job-x', position: 0, status: 'queued' }),
+ mediaJobEvents: { on: () => {}, off: () => {} },
+}));
+vi.mock('../imageGen/index.js', () => ({
+ resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }),
+}));
+vi.mock('../settings.js', () => ({ getSettings: async () => ({ imageGen: { mode: 'codex' } }) }));
+
+const records = await import('./records.js');
+const { lockReference, getReferenceSet } = await import('./reference.js');
+const { resolveSpriteAssetPrompt } = await import('./assetPrompt.js');
+
+let seq = 0;
+const newId = () => `hero-${++seq}`;
+const placeCandidate = (recordId, target, name, opts) => placeCandidateFixture(TEST_ROOT, recordId, target, name, opts);
+
+async function createCharacter(id) {
+ return records.createRecord({ kind: 'character', name: 'Hero' }, id);
+}
+
+beforeEach(() => {
+ rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });
+ rmSync(join(TEST_ROOT, 'sprites'), { force: true, recursive: true });
+});
+afterAll(() => rmSync(TEST_ROOT, { force: true, recursive: true }));
+
+describe('resolveSpriteAssetPrompt', () => {
+ it('returns the literal prompt stored in a candidate sidecar', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const candDir = join(TEST_ROOT, 'sprites', id, 'reference', 'candidates');
+ await writeCandidatePng(join(candDir, 'walk-south-candidate-01.png'));
+ await writeFile(join(candDir, 'walk-south-candidate-01.generation.json'), JSON.stringify({
+ schemaVersion: 1, target: 'main', chromaKey: '#FF00FF',
+ designPrompt: 'a brave knight', prompt: 'THE EXACT PROMPT THAT WAS SENT',
+ }));
+
+ const res = await resolveSpriteAssetPrompt(id, 'reference/candidates/walk-south-candidate-01.png');
+ expect(res).toEqual({ prompt: 'THE EXACT PROMPT THAT WAS SENT', designPrompt: 'a brave knight', source: 'candidate' });
+ });
+
+ it('reconstructs a main-candidate prompt when the sidecar predates prompt capture', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const candDir = join(TEST_ROOT, 'sprites', id, 'reference', 'candidates');
+ await writeCandidatePng(join(candDir, 'walk-south-candidate-01.png'));
+ await writeFile(join(candDir, 'walk-south-candidate-01.generation.json'), JSON.stringify({
+ schemaVersion: 1, target: 'main', chromaKey: '#FF00FF', designPrompt: 'a brave knight',
+ }));
+
+ const res = await resolveSpriteAssetPrompt(id, 'reference/candidates/walk-south-candidate-01.png');
+ expect(res.source).toBe('candidate-reconstructed');
+ expect(res.designPrompt).toBe('a brave knight');
+ expect(res.prompt).toContain('named Hero');
+ expect(res.prompt).toContain('a brave knight');
+ expect(res.prompt).toContain('magenta (#FF00FF)');
+ });
+
+ it('reconstructs an anchor-candidate prompt from its direction', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const candDir = join(TEST_ROOT, 'sprites', id, 'reference', 'candidates');
+ await writeCandidatePng(join(candDir, 'walk-east-candidate-02.png'));
+ await writeFile(join(candDir, 'walk-east-candidate-02.generation.json'), JSON.stringify({
+ schemaVersion: 1, target: 'east', direction: 'east', chromaKey: '#00FF00',
+ }));
+
+ const res = await resolveSpriteAssetPrompt(id, 'reference/candidates/walk-east-candidate-02.png');
+ expect(res.source).toBe('candidate-reconstructed');
+ expect(res.prompt).toContain('right-facing side profile');
+ expect(res.prompt).toContain('green (#00FF00)');
+ });
+
+ it('resolves the locked main reference through the manifest', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await lockReference(id, { target: 'main', candidate: await placeCandidate(id, 'main', 'walk-south-candidate-01.png') });
+ const { manifest } = await getReferenceSet(id);
+
+ const res = await resolveSpriteAssetPrompt(id, manifest.mainReference.path);
+ expect(res).not.toBeNull();
+ expect(res.prompt).toContain('named Hero');
+ expect(res.prompt).toContain('walk-south identity reference');
+ });
+
+ it('resolves a locked directional anchor through the manifest', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await lockReference(id, { target: 'main', candidate: await placeCandidate(id, 'main', 'walk-south-candidate-01.png') });
+ await lockReference(id, { target: 'east', candidate: await placeCandidate(id, 'east', 'walk-east-candidate-01.png') });
+ const { manifest } = await getReferenceSet(id);
+ const eastAnchor = manifest.anchors.find((a) => a.direction === 'east');
+
+ const res = await resolveSpriteAssetPrompt(id, eastAnchor.path);
+ expect(res).not.toBeNull();
+ expect(res.prompt.toLowerCase()).toContain('hero');
+ });
+
+ it('reconstructs a walk-animation prompt from the run record', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const runRel = 'grok/walk-east-abc12345';
+ const runDir = join(TEST_ROOT, 'sprites', id, runRel);
+ await mkdir(join(runDir, 'generated'), { recursive: true });
+ await writeFile(join(runDir, 'animation-run.json'), JSON.stringify({
+ schemaVersion: 1, id: 'walk-east-abc12345', characterId: id, direction: 'east', chromaKey: '#FF00FF',
+ }));
+ await writeFile(join(runDir, 'generated', 'walk.mp4'), 'fake');
+
+ const res = await resolveSpriteAssetPrompt(id, `${runRel}/generated/walk.mp4`);
+ expect(res.source).toBe('walk');
+ expect(res.prompt).toContain('walk-in-place loop');
+ expect(res.prompt).toContain('Hero');
+ });
+
+ it('returns null for an asset with no prompt provenance', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const res = await resolveSpriteAssetPrompt(id, 'atlas/pioneer-atlas.png');
+ expect(res).toBeNull();
+ });
+
+ it('returns null for an unknown record', async () => {
+ const res = await resolveSpriteAssetPrompt('ghost-999', 'reference/candidates/walk-south-candidate-01.png');
+ expect(res).toBeNull();
+ });
+
+ it('refuses a traversal path', async () => {
+ const id = newId();
+ await createCharacter(id);
+ await expect(resolveSpriteAssetPrompt(id, '../escape.png')).rejects.toThrow();
+ });
+});
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index 4c1cb1aacd..3ab4b741ff 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -461,6 +461,11 @@ export async function attachReferenceCandidate(ctx) {
// rewrites top-level params but carries the original tag through, so the
// tag's model can be stale provenance.
model: ctx.job?.params?.model || ctx.job?.params?.modelId || ctx.model || null,
+ // The literal prompt sent to the provider — the completed job's live params
+ // are canonical (Render Queue's Edit & Retry can rewrite it). Persisting it
+ // lets the preview modals show exactly what was rendered; older sidecars
+ // without it fall back to a deterministic rebuild (services/sprites/assetPrompt.js).
+ prompt: ctx.job?.params?.prompt || null,
jobId: ctx.jobId || null,
...(ctx.designPrompt ? { designPrompt: ctx.designPrompt } : {}),
...(ctx.designReferencePath ? { designReferencePath: ctx.designReferencePath } : {}),