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
feat([issue-2931]): group sprite assets by role with inline regenerate + trim actions
[._.]/ Adam Eivy28cf50499aa8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 20e17caf31..bc93d0030c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -7,6 +7,7 @@## Sprite Manager+- **[issue-2931] A character's assets now group by what they are, and you can act on them in place** — the asset browser used to be a flat dump grouped by folder name (`reference`, `grok`, `runtime`), with every tile inert. Assets are now grouped by their actual role — reference set, strips, animations, frames, atlases, review evidence, manifests — and each one carries a status badge (runtime · approved · candidate · superseded · rejected · source), so you can see at a glance which reference version is current and which have been replaced. Walk strips, frames and animations gain two buttons: **Regenerate**, which re-runs that direction's render, and **Edit in Loop Trimmer**, which jumps straight to the trimmer for that run — including for a direction you've already approved, since trims are saved separately and never overwrite the approved artwork. Regenerate is correctly greyed out when the walk set is finalized, when the direction is already approved, when its reference anchor isn't locked yet, or while a render for it is already running — and it now shares one in-flight view with the workflow panels above, so starting a render in one place immediately disables it in the other instead of letting you pay for the same render twice. An unlocked reference candidate can be re-rolled the same way. Switching between characters no longer carries a stale "Rendering…" state across from the previous one.- **[issue-2930] Sprites is now its own page, and assets are properly inspectable** — the Sprite Manager was a hidden tab inside Media Gen; it now has its own **Sprites** entry in the Create sidebar and lives at its own address, so it's directly linkable, bookmarkable, and reachable from ⌘K and voice. Old Media Gen sprite links (including links to a specific sprite) redirect to the new page and keep any deep-link state. Every surface that shows a transparent sprite — asset thumbnails, the reference set, walk-loop previews, trim results, and the compiled atlas — now paints a checkerboard behind the artwork, so a cut-out region is finally distinguishable from a black pixel instead of both reading as the same dark rectangle. Clicking any asset opens a real inspector: a pixel-perfect preview over that checkerboard, plus the file's path, dimensions, format, frame count, size, and last-modified time, with Download and Copy-path buttons. Non-image files (manifests, sidecars) open there too instead of silently downloading. An asset PortOS can't read — a truncated PNG, say — now shows its basic details rather than breaking the whole page.- **[issue-2928] Show walk previews for every imported run layout, not just one** — the walk viewer found a character's animation runs by looking in a single fixed folder, so an imported character whose source pipeline filed its runs elsewhere showed the same blank "approved ✓" card that #2924 just fixed for redraw directions. Each approved direction is now looked up by where its own approval record says its run lives, so any layout the importer produces animates. Unapproved candidates and in-flight generations still appear as before.- **[issue-2924] Animate walk directions approved from an imported redraw cycle** — a direction whose approved artwork came from the source pipeline's video-first *redraw* path (rather than a Grok walk clip) showed its "approved ✓" badge with a blank space where the loop preview should be, because there was no walk-run record behind it to render. Those directions now animate from their own packaged cycle: PortOS reads the redraw manifest, prefers its clean transparent strip (falling back to the keyed one), and plays the loop at the cycle's real length and frame rate. The viewer no longer assumes every walk strip is exactly 8 frames, so a 12-frame imported stride plays its full gait instead of being cropped to two thirds; native 8-phase runs are unchanged. A direction whose strip is missing on disk still shows nothing rather than a broken image.diff --git a/client/src/components/sprites/AssetCollection.jsx b/client/src/components/sprites/AssetCollection.jsxnew file mode 100644index 0000000000..05c9b21c4f--- /dev/null+++ b/client/src/components/sprites/AssetCollection.jsx@@ -0,0 +1,139 @@+/**+ * Character asset collection (#2931, phase 3 of the #2930 UX overhaul).+ *+ * Replaces the flat "group by first path segment" dump with a role-grouped+ * collection carrying a lifecycle status badge per asset, and puts the two+ * actions you actually want on the cards that can use them:+ *+ * - **Regenerate** — re-fires the workflow action that produced this asset+ * (walk generate for a strip/frame/animation, reference generate for an+ * anchor), gated on the same in-flight state the workflow itself uses.+ * - **Edit in Loop Trimmer** — opens the trimmer for the owning run.+ *+ * `ReferenceWorkflow` / `WalkWorkflow` / `PublishWorkflow` stay the+ * authoritative surfaces: this view links INTO them (the trim request is+ * routed back up to WalkWorkflow's panel) rather than duplicating their state.+ */++import { useMemo, useState } from 'react';+import { FolderOpen, RefreshCw, Scissors, Sparkles, Film } from 'lucide-react';+import AssetInspector from './AssetInspector.jsx';+import SpritePreview from './SpritePreview.jsx';+import { hasSpritePreview } from './spriteAssets.js';+import { groupSpriteAssetsByRole } from '../../lib/spriteFacets.js';+import { formatBytes } from '../../utils/formatters.js';++// Status → badge tone. Kept here rather than in the pure facet module so the+// classifier stays free of presentation concerns.+const STATUS_TONE = {+ runtime: 'bg-port-accent/20 text-port-accent border-port-accent/40',+ approved: 'bg-port-success/20 text-port-success border-port-success/40',+ candidate: 'bg-port-warning/20 text-port-warning border-port-warning/40',+ superseded: 'bg-port-bg text-gray-500 border-port-border',+ rejected: 'bg-port-error/20 text-port-error border-port-error/40',+ source: 'bg-port-bg text-gray-400 border-port-border',+};++function StatusBadge({ status }) {+ return (+ <span className={`inline-block px-1 rounded-sm border text-[9px] leading-4 ${STATUS_TONE[status] || STATUS_TONE.source}`}>+ {status}+ </span>+ );+}++function AssetCard({ recordId, asset, actions, onInspect }) {+ const { facets } = asset;+ const name = asset.path.split('/').pop();+ const regenerate = actions?.regenerateFor(asset);+ const trim = actions?.trimFor(asset);++ return (+ <div className="bg-port-bg border border-port-border rounded p-1 space-y-1">+ <button+ type="button"+ onClick={() => onInspect(asset)}+ className="block w-full text-left rounded hover:opacity-80"+ title={asset.path}+ >+ {hasSpritePreview(asset) && (+ <SpritePreview recordId={recordId} path={asset.path} className="h-20 rounded" />+ )}+ <span className="block text-[10px] text-gray-500 truncate">{name}</span>+ <span className="flex items-center gap-1 text-[10px] text-gray-600">+ <StatusBadge status={facets.status} />+ {hasSpritePreview(asset) ? `${asset.width}×${asset.height}` : formatBytes(asset.size)}+ </span>+ </button>+ {(regenerate || trim) && (+ <div className="flex gap-1">+ {regenerate && (+ <button+ type="button"+ onClick={regenerate.onClick}+ disabled={regenerate.disabled}+ title={regenerate.title}+ className="flex-1 flex items-center justify-center gap-1 px-1 py-0.5 text-[10px] bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-40"+ >+ {regenerate.pending+ ? <RefreshCw className="w-3 h-3 animate-spin" />+ : regenerate.kind === 'reference' ? <Sparkles className="w-3 h-3" /> : <Film className="w-3 h-3" />}+ {regenerate.pending ? 'Rendering…' : 'Regenerate'}+ </button>+ )}+ {trim && (+ <button+ type="button"+ onClick={trim.onClick}+ title="Edit in Loop Trimmer"+ aria-label={`Edit ${name} in Loop Trimmer`}+ className="px-1.5 py-0.5 text-[10px] bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ <Scissors className="w-3 h-3" />+ </button>+ )}+ </div>+ )}+ </div>+ );+}++/**+ * `actions` is null for a non-character record (props families have no walk /+ * reference workflow to re-fire). Shape:+ * { regenerateFor(asset) → { run, disabled, pending, title, kind } | null,+ * trimFor(asset) → { run } | null }+ */+export default function AssetCollection({ recordId, assets, actions = null }) {+ const [inspecting, setInspecting] = useState(null);+ const groups = useMemo(() => groupSpriteAssetsByRole(assets), [assets]);++ return (+ <div className="space-y-4">+ {groups.map(({ role, label, assets: rows }) => (+ <div key={role}>+ <h4 className="flex items-center gap-1.5 text-sm font-semibold text-gray-300 mb-2">+ <FolderOpen className="w-4 h-4" /> {label}+ <span className="text-xs text-gray-500 font-normal">({rows.length})</span>+ </h4>+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-2">+ {/* `actions` is the SINGLE gate on which cards get buttons — its+ two resolvers return null for an asset they can't act on (a+ manifest, an upload, a locked anchor), so there is no second+ role allow-list here to drift out of sync. */}+ {rows.map((asset) => (+ <AssetCard+ key={asset.path}+ recordId={recordId}+ asset={asset}+ actions={actions}+ onInspect={setInspecting}+ />+ ))}+ </div>+ </div>+ ))}+ <AssetInspector recordId={recordId} asset={inspecting} onClose={() => setInspecting(null)} />+ </div>+ );+}diff --git a/client/src/components/sprites/AssetCollection.test.jsx b/client/src/components/sprites/AssetCollection.test.jsxnew file mode 100644index 0000000000..ded7a50252--- /dev/null+++ b/client/src/components/sprites/AssetCollection.test.jsx@@ -0,0 +1,121 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import AssetCollection from './AssetCollection.jsx';+import { buildCollectionActions } from '../../lib/spriteCollectionActions.js';++// Role grouping + status badges + which cards get inline actions (#2931).+// The gating rules themselves are covered in spriteCollectionActions.test.js;+// this suite asserts the wiring — that the collection actually asks the+// resolvers per asset and renders/disables what they return.++const STRIP = 'grok/walk-east-abc12345/generated/example-walk-east-strip.png';+const asset = (path, over = {}) => ({ path, size: 2048, ...over });+const image = (path) => asset(path, { width: 96, height: 96, format: 'png' });++const ASSETS = [+ image('reference/example-walk-east-v1.png'),+ image('reference/example-walk-east-v2.png'),+ image(STRIP),+ asset('grok/walk-east-abc12345/generated/example-walk-east-manifest.json'),+];++const actionsFor = (over = {}, maps = {}) => buildCollectionActions({+ detail: {+ record: { id: 'example-walker', kind: 'character' },+ reference: { manifest: { anchors: [{ direction: 'east', status: 'locked' }] } },+ walk: {+ runs: [{ id: 'walk-east-abc12345', direction: 'east', status: 'candidate', stripPreview: { stripPath: STRIP } }],+ selection: { directions: {} },+ walkSet: null,+ },+ ...over,+ },+ generateWalk: vi.fn(),+ generateAnchor: vi.fn(),+ onRequestTrim: vi.fn(),+ ...maps,+});++const groupHeadings = () => screen.getAllByRole('heading', { level: 4 })+ .map((h) => h.textContent.replace(/\s+/g, ' ').trim());++describe('AssetCollection grouping', () => {+ it('groups by semantic role in the declared order, not by path segment', () => {+ render(<AssetCollection recordId="example-walker" assets={ASSETS} />);+ // Pre-#2931 this was `reference` / `grok` (raw first path segments) — the+ // strip and its sidecar manifest sat in one undifferentiated bucket.+ expect(groupHeadings()).toEqual(['Reference set(2)', 'Strips(1)', 'Manifests(1)']);+ });++ it('badges each asset with its lifecycle status, including the cross-set supersede', () => {+ render(<AssetCollection recordId="example-walker" assets={ASSETS} />);+ const referenceGroup = screen.getByRole('heading', { name: /Reference set/ }).parentElement;+ expect(within(referenceGroup).getByText('superseded')).toBeTruthy();+ expect(within(referenceGroup).getByText('approved')).toBeTruthy();+ });++ it('renders nothing but the inspector mount for an empty listing', () => {+ render(<AssetCollection recordId="example-walker" assets={[]} />);+ expect(screen.queryAllByRole('heading', { level: 4 })).toHaveLength(0);+ });+});++describe('AssetCollection inline actions', () => {+ const stripCard = () => screen.getByTitle(STRIP).parentElement;++ it('puts Regenerate and Edit-in-Trimmer on a walk strip', () => {+ render(<AssetCollection recordId="example-walker" assets={ASSETS} actions={actionsFor()} />);+ const card = stripCard();+ expect(within(card).getByRole('button', { name: /Regenerate/ })).toBeEnabled();+ expect(within(card).getByRole('button', { name: /Edit .* in Loop Trimmer/ })).toBeTruthy();+ });++ it('leaves non-actionable assets (a manifest, a locked reference) action-free', () => {+ render(<AssetCollection recordId="example-walker" assets={ASSETS} actions={actionsFor()} />);+ expect(screen.getAllByRole('button', { name: /Regenerate/ })).toHaveLength(1);+ });++ it('renders no actions at all for a record with no workflow (props family)', () => {+ render(<AssetCollection recordId="example-props" assets={ASSETS} actions={null} />);+ expect(screen.queryByRole('button', { name: /Regenerate/ })).toBeNull();+ });++ it('disables Regenerate while that direction render is in flight', () => {+ render(+ <AssetCollection recordId="example-walker" assets={ASSETS} actions={actionsFor({}, { walkPending: { east: 'job-1' } })} />,+ );+ expect(within(stripCard()).getByRole('button', { name: /Rendering/ })).toBeDisabled();+ });++ it('disables Regenerate once the walk set is finalized', () => {+ const actions = actionsFor({+ walk: {+ runs: [{ id: 'walk-east-abc12345', direction: 'east', status: 'approved', stripPreview: { stripPath: STRIP } }],+ selection: { directions: {} },+ walkSet: { frozen: true },+ },+ });+ render(<AssetCollection recordId="example-walker" assets={ASSETS} actions={actions} />);+ expect(within(stripCard()).getByRole('button', { name: /Regenerate/ })).toBeDisabled();+ });++ it('routes the trimmer request with the owning run id', async () => {+ const onRequestTrim = vi.fn();+ render(+ <AssetCollection+ recordId="example-walker"+ assets={ASSETS}+ actions={actionsFor({}, { onRequestTrim })}+ />,+ );+ await userEvent.click(within(stripCard()).getByRole('button', { name: /Edit .* in Loop Trimmer/ }));+ expect(onRequestTrim).toHaveBeenCalledWith('walk-east-abc12345');+ });++ it('opens the inspector from the card body, not from the action row', async () => {+ render(<AssetCollection recordId="example-walker" assets={ASSETS} actions={actionsFor()} />);+ await userEvent.click(screen.getByTitle(STRIP));+ expect(screen.getByText('Copy path')).toBeTruthy();+ });+});diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsxindex 513d1fe8dc..4082c979c3 100644--- a/client/src/components/sprites/ReferenceWorkflow.jsx+++ b/client/src/components/sprites/ReferenceWorkflow.jsx@@ -5,7 +5,6 @@ import { generateSpriteReference, lockSpriteReference, updateSpriteRecord } fromimport { getSettings } from '../../services/apiSystem.js';import { deriveAvailableBackends } from '../../lib/imageGenBackends.js';import { useAsyncAction } from '../../hooks/useAsyncAction.js';-import { useSpritePendingRenders } from '../../hooks/useSpritePendingRenders.js';import SpritePreview from './SpritePreview.jsx';// Reference workflow (issue #2896): generate main-reference candidates from@@ -66,7 +65,7 @@ function CandidateTile({ recordId, candidate, locking, onLock, clipRisk }) {);}-export default function ReferenceWorkflow({ record, reference, onChanged }) {+export default function ReferenceWorkflow({ record, reference, renders, onChanged }) {const recordId = record.id;const manifest = reference?.manifest || null;const candidates = reference?.candidates || [];@@ -78,11 +77,10 @@ export default function ReferenceWorkflow({ record, reference, onChanged }) {const [designPrompt, setDesignPrompt] = useState(manifest?.designPrompt || '');const [uploadFile, setUploadFile] = useState(null);const fileInputRef = useRef(null);- // target → jobId for in-flight renders; rehydrated + polled by the shared- // sprite render-tracking hook until each candidate lands.- const { pendingJobs, beginSubmit, resolveSubmit, cancelSubmit } = useSpritePendingRenders({- recordId, kind: 'image', tagKey: 'spriteRef', tagField: 'target', onChanged,- });+ // 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.+ const { pendingJobs, beginSubmit, resolveSubmit, cancelSubmit } = renders;useEffect(() => {getSettings({ silent: true })diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex f1b38935c1..39764b303f 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -1,14 +1,16 @@import { useEffect, useMemo, useState } from 'react';import { Check, Film, RefreshCw, Scissors, Lock } from 'lucide-react';import toast from '../ui/Toast';-import {- generateSpriteWalk, approveSpriteWalk, postprocessSpriteWalk, trimSpriteWalk,-} from '../../services/apiSprites.js';+import { approveSpriteWalk, postprocessSpriteWalk, trimSpriteWalk } from '../../services/apiSprites.js';import { useAsyncAction } from '../../hooks/useAsyncAction.js';-import { useSpritePendingRenders } from '../../hooks/useSpritePendingRenders.js';import { spriteAssetUrl, checkerboardStyle, PIXELATED } from './spriteAssets.js';import SpritePreview from './SpritePreview.jsx';+// Scroll anchor for the asset collection's "Edit in Loop Trimmer" action+// (#2931) — the trimmer lives in this card, potentially far above the asset+// grid that requested it.+export const WALK_WORKFLOW_DOM_ID = 'sprite-walk-workflow';+// Walk workflow (issue #2897): one grok image_to_video clip per locked// directional anchor, deterministic server-side packaging into the 8-phase// strip, per-direction review (loop preview + optional trim) and approval.@@ -26,7 +28,10 @@ const CELL_PX = 96; // preview cell size — the strip animates at 96px/frame// rule reads it from a per-preview custom property instead of hardcoding 8.const LOOP_KEYFRAMES = '@keyframes sprite-walk-loop { to { background-position-x: var(--sprite-walk-loop-end) } }';// Grok image_to_video clip lengths (videoGen/grok.js GROK_VIDEO_DURATIONS).-const WALK_DURATIONS = [6, 10];+// Exported so the Sprites page can seed the lifted `duration` state with the+// same default — the asset collection's Regenerate must honor whatever the+// user picked here rather than silently falling back to the server default.+export const WALK_DURATIONS = [6, 10];/*** Strip geometry for a preview/trim UI, defaulting to the native 8-phase@@ -145,11 +150,20 @@ function TrimPanel({ recordId, run, onClose }) {}function DirectionCard({- recordId, direction, anchorLocked, run, approved, finalized, pending, onGenerate, onApprove, onRetry,+ recordId, direction, anchorLocked, run, approved, finalized, pending,+ trimRequestRun = null, onTrimClose, onGenerate, onApprove, onRetry,}) {const [confirming, setConfirming] = useState(false);const [trimming, setTrimming] = useState(false);const candidate = run?.status === 'candidate' ? run : null;+ // Two ways in: this card's own Scissors toggle (the direction's current+ // candidate, as before) and an explicit request routed from an asset card+ // (#2931), which names the exact run — possibly an older or APPROVED one,+ // and possibly under a finalized walk set. That's sound: trims are+ // non-destructive derived artifacts under `walk/trims/` and the server only+ // requires a packaged manifest. It stays request-driven rather than becoming+ // a new always-on affordance on approved directions.+ const trimRun = trimRequestRun || (trimming ? candidate : null);const statusLabel = approved ? 'approved': pending ? 'rendering…': run?.status === 'postprocessing' ? 'packaging…'@@ -216,36 +230,40 @@ function DirectionCard({</div>))}- {trimming && candidate && (- <TrimPanel recordId={recordId} run={candidate} onClose={() => setTrimming(false)} />- )}</div>)}++ {/* Outside the !finalized && !approved block on purpose: an explicit+ trim request from the asset collection must open even for an+ approved direction or a finalized walk set. */}+ {trimRun && (+ <TrimPanel+ recordId={recordId}+ run={trimRun}+ onClose={() => { setTrimming(false); onTrimClose(); }}+ />+ )}</div>);}-export default function WalkWorkflow({ record, reference, walk, onChanged }) {+export default function WalkWorkflow({+ record, reference, walk, renders, duration, onDurationChange, onGenerate,+ trimRunId = null, onTrimClose = () => {}, onChanged,+}) {const recordId = record.id;const manifest = reference?.manifest || null;const runs = walk?.runs || [];const selection = walk?.selection || null;const finalized = Boolean(walk?.walkSet);- const [duration, setDuration] = useState(WALK_DURATIONS[0]);- // direction → jobId for in-flight video renders — rehydrated + polled by- // the shared sprite render-tracking hook. The deterministic postprocess- // runs server-side after the job completes, so the sweeps land later (and- // twice) compared to the reference workflow's instant candidate copy.- const { pendingJobs, beginSubmit, resolveSubmit, cancelSubmit } = useSpritePendingRenders({- recordId,- kind: 'video',- tagKey: 'spriteWalk',- tagField: 'direction',- onChanged,- sweepDelays: () => [1500, 8000],- failMessage: (direction, job) => `Walk render failed for ${direction}: ${job?.error || 'see media jobs'}`,- });+ // direction → jobId for in-flight video renders. The hook instance is owned+ // by the Sprites page and shared with the asset collection (#2931) so both+ // Generate buttons gate on ONE map — a second instance here would let a+ // Regenerate fired from an asset card leave this button enabled, inviting a+ // duplicate paid render for the same direction. The generate ACTION lives up+ // there too, so both entry points submit through one code path.+ const { pendingJobs } = renders;// The deterministic postprocess runs server-side AFTER the video job// completes (frame extraction + per-pixel un-key can take many seconds on@@ -273,6 +291,13 @@ export default function WalkWorkflow({ record, reference, walk, onChanged }) {return () => clearInterval(timer);}, [packaging, awaitingAttach, onChanged]);+ // Resolved by id, not by direction: the asset collection can name any run+ // that packed a strip, including one older than the direction's latest.+ const requestedTrimRun = useMemo(+ () => (trimRunId ? runs.find((r) => r.id === trimRunId) || null : null),+ [runs, trimRunId],+ );+const latestRunByDirection = useMemo(() => {const byDir = {};for (const run of runs) {@@ -286,17 +311,6 @@ export default function WalkWorkflow({ record, reference, walk, onChanged }) {return byDir;}, [runs, selection]);- const generate = async (direction) => {- beginSubmit(direction);- try {- const { jobId } = await generateSpriteWalk(recordId, { direction, duration }, { silent: true });- resolveSubmit(direction, jobId);- } catch (err) {- cancelSubmit(direction);- toast.error(err?.message || `Failed to queue ${direction} walk`);- }- };-const [approve] = useAsyncAction(async (direction, runId) => {await approveSpriteWalk(recordId, { direction, runId }, { silent: true });toast.success(`Walk ${direction} approved`);@@ -317,7 +331,7 @@ export default function WalkWorkflow({ record, reference, walk, onChanged }) {.filter((d) => d?.status === 'approved').length;return (- <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div id={WALK_WORKFLOW_DOM_ID} className="bg-port-card border border-port-border rounded-lg p-4 space-y-3"><style>{LOOP_KEYFRAMES}</style><div className="flex flex-wrap items-center justify-between gap-2"><h3 className="text-sm font-semibold text-white flex items-center gap-1.5">@@ -335,7 +349,7 @@ export default function WalkWorkflow({ record, reference, walk, onChanged }) {Clip length<selectvalue={duration}- onChange={(e) => setDuration(Number(e.target.value))}+ onChange={(e) => onDurationChange(Number(e.target.value))}className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white">{WALK_DURATIONS.map((d) => <option key={d} value={d}>{d}s</option>)}@@ -354,7 +368,9 @@ export default function WalkWorkflow({ record, reference, walk, onChanged }) {approved={selection?.directions?.[anchor.direction]?.status === 'approved'}finalized={finalized}pending={Boolean(pendingJobs[anchor.direction])}- onGenerate={generate}+ trimRequestRun={requestedTrimRun?.direction === anchor.direction ? requestedTrimRun : null}+ onTrimClose={onTrimClose}+ onGenerate={onGenerate}onApprove={approve}onRetry={retryPostprocess}/>diff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsxindex 25d30d4724..a5f84d03b8 100644--- a/client/src/components/sprites/WalkWorkflow.test.jsx+++ b/client/src/components/sprites/WalkWorkflow.test.jsx@@ -13,17 +13,17 @@ vi.mock('../../services/apiSprites.js', () => ({trimSpriteWalk: vi.fn(),}));-vi.mock('../../hooks/useSpritePendingRenders.js', () => ({- useSpritePendingRenders: () => ({- pendingJobs: {}, beginSubmit: vi.fn(), resolveSubmit: vi.fn(), cancelSubmit: vi.fn(),- }),-}));-import WalkWorkflow from './WalkWorkflow';const CELL_PX = 96;-const renderWalk = (stripPreview) => {+// The render-tracking hook is owned by the Sprites page now (#2931) and passed+// in, so the suite supplies it as a prop instead of mocking the module.+const noRenders = () => ({+ pendingJobs: {}, beginSubmit: vi.fn(), resolveSubmit: vi.fn(), cancelSubmit: vi.fn(),+});++const renderWalk = (stripPreview, props = {}) => {const run = {id: 'run-east', direction: 'east', status: 'approved', stripPreview,};@@ -36,12 +36,22 @@ const renderWalk = (stripPreview) => {selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },walkSet: null,}}+ renders={noRenders()}+ duration={6}+ onDurationChange={vi.fn()}+ onGenerate={vi.fn()}onChanged={vi.fn()}+ {...props}/>,);return screen.getByRole('img', { name: 'walk loop preview' });};+const APPROVED_STRIP = {+ stripPath: 'grok/run-east/generated/example-walk-east-strip.png',+ frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384,+};+describe('WalkWorkflow loop preview', () => {it('steps a native 8-frame strip 8 times over its 12fps cycle', () => {const loop = renderWalk({@@ -88,3 +98,25 @@ describe('WalkWorkflow loop preview', () => {expect(loop.style.backgroundSize).toBe(`${CELL_PX * 8}px ${CELL_PX / 2}px`);});});++// The asset collection's "Edit in Loop Trimmer" (#2931) routes back into this+// component's one TrimPanel. The run in this fixture is APPROVED, which the+// pre-existing Scissors toggle never reaches — so the panel has to render+// outside the `!finalized && !approved` action block or the action silently+// does nothing on exactly the assets most worth trimming.+describe('WalkWorkflow trim requests', () => {+ it('shows no trim panel until a run is requested', () => {+ renderWalk(APPROVED_STRIP);+ expect(screen.queryByRole('button', { name: /Save trim/ })).toBeNull();+ });++ it('opens the trim panel for an approved run named by id', () => {+ renderWalk(APPROVED_STRIP, { trimRunId: 'run-east' });+ expect(screen.getByRole('button', { name: /Save trim \(8\/8\)/ })).toBeTruthy();+ });++ it('ignores a run id that is not in this record listing', () => {+ renderWalk(APPROVED_STRIP, { trimRunId: 'run-that-does-not-exist' });+ expect(screen.queryByRole('button', { name: /Save trim/ })).toBeNull();+ });+});diff --git a/client/src/hooks/useSpritePendingRenders.js b/client/src/hooks/useSpritePendingRenders.jsindex 8880f62bd1..9267150bb7 100644--- a/client/src/hooks/useSpritePendingRenders.js+++ b/client/src/hooks/useSpritePendingRenders.js@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react';+import { useCallback, useEffect, useState } from 'react';import toast from '../components/ui/Toast';import { getMediaJob, listMediaJobs } from '../services/apiMediaJobs.js';import useMounted from './useMounted.js';@@ -34,11 +34,21 @@ export function useSpritePendingRenders({// sweep for the component's whole dev lifetime.const mountedRef = useMounted();+ // The map is keyed by direction/target, NOT by record — so a record switch+ // must clear it or character B inherits character A's in-flight entries and+ // shows "Rendering…" on a direction nothing is rendering. Runs before the+ // rehydrate below (effect order), whose async merge then refills it with+ // B's real jobs. Load-bearing now that the hook is owned by the page and+ // survives switching records (#2931) — previously it unmounted with the+ // workflow only when the character had no locked main.+ useEffect(() => { setPendingJobs({}); }, [recordId]);+// Rehydrate in-flight renders on mount/record switch — a reload or// navigate-away-and-back would otherwise lose the map and re-enable// Generate mid-render, inviting a duplicate paid render for the same key.// Locally-started jobs win over the snapshot on key collision.useEffect(() => {+ if (!recordId) return undefined;let stale = false;listMediaJobs({ kind, owner: 'sprites' }, { silent: true }).then((jobs) => {@@ -95,14 +105,17 @@ export function useSpritePendingRenders({// Sentinel jobId while the enqueue request is in flight — reserves the key// immediately so a double-click (or a slow multipart upload) can't submit- // two paid renders. The poll skips sentinel entries.- const beginSubmit = (key) => setPendingJobs((prev) => ({ ...prev, [key]: 'submitting' }));- const resolveSubmit = (key, jobId) => setPendingJobs((prev) => ({ ...prev, [key]: jobId }));- const cancelSubmit = (key) => setPendingJobs((prev) => {+ // two paid renders. The poll skips sentinel entries. Stable identities+ // (`useCallback([])`, closing only over `setPendingJobs`) so a consumer can+ // depend on them in its own `useCallback`/`useMemo` without churning every+ // render — the Sprites page (#2931) memoizes its action closures on these.+ const beginSubmit = useCallback((key) => setPendingJobs((prev) => ({ ...prev, [key]: 'submitting' })), []);+ const resolveSubmit = useCallback((key, jobId) => setPendingJobs((prev) => ({ ...prev, [key]: jobId })), []);+ const cancelSubmit = useCallback((key) => setPendingJobs((prev) => {const next = { ...prev };if (next[key] === 'submitting') delete next[key];return next;- });+ }), []);return { pendingJobs, beginSubmit, resolveSubmit, cancelSubmit };}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 8b253c6a98..c1a14e5930 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -136,6 +136,8 @@ grep -i "what you want to do" client/src/lib/README.md| `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift. || `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. || `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. |+| `spriteCollectionActions.js` | Gating for the Sprite Manager asset collection's inline actions (#2931). `buildCollectionActions({ detail, walkPending, referencePending, generateWalk, generateAnchor, onRequestTrim })` → `{ regenerateFor(asset), trimFor(asset) }`, each returning `null` for an asset it can't act on. Regenerate mirrors the authoritative workflow surfaces exactly — a walk direction is regenerable only when its anchor is locked, the direction isn't approved, the walk set isn't finalized and no render is in flight; a reference anchor only while it's an unlocked candidate (`south`/main is excluded, since it needs a design prompt or upload). Trim is offered only for a run that actually packed a strip (the trim endpoint 409s otherwise). Pure — takes callbacks, performs no I/O. Consumes the facets from `spriteFacets.js`. |+| `spriteFacets.js` | Client-side facet classifier for the Sprite Manager's asset collection (#2931), mirroring the source pipeline's `classify_asset()`. `classifySpriteAsset(path)` decodes a record-relative asset path into `{ family, status, role, direction, runId }` — `status ∈ runtime/approved/candidate/superseded/rejected/source`, `role ∈ reference/strip/animation/frame/atlas/evidence/sprite/manifest` — and is total (an unknown path degrades to `sprite`/`source` rather than throwing). `classifySpriteAssets(assets)` adds the one facet only knowable across a listing: an approved asset below the highest `-vN` of its stem becomes `superseded`. `groupSpriteAssetsByRole(assets)` returns render-ready `{ role, label, assets }` sections in `SPRITE_ASSET_ROLES` order. Also exports `SPRITE_DIRECTIONS` (mirror of `server/services/sprites/prompts.js`) — the `direction`/`runId` facets are what drive the collection's Regenerate and Edit-in-Loop-Trimmer actions. Pure — no React, no I/O. || `tribe.js` | Pure Tribe domain helpers shared by the Tribe page and its `TribeCircleMap` visualization: `RINGS` (support→core→tribe→village Dunbar rings + the uncapped `external` "outside the tribe" classification — caps, cadence defaults, Tailwind tones + `hex`), `TRIBE_RINGS` (the four inner rings the care queue/capacity/overdue counts operate over, excluding `external`), `ENERGY` (energy tiers + `hex`), `STATUS_HEX` (cadence-status → SVG stroke color), `contactStatus(contact)` (presentation wrapper over the shared `cadenceStatus` — attaches label/tone to the missing/overdue/soon/steady/`external` state) / `daysBetween(date)` (alias of the shared `daysSinceDate`), `ringFor` / `energyFor` lookups, `tagsToArray` / `tagsToInput`, and `initialsFor(name)` (node glyph). Ring `cadenceDays` mirror `DEFAULT_RING_CADENCE` in `server/services/tribe.js`; the cadence STATE MACHINE lives in `tribeCadence.js`. || `tribeCadence.js` | Mirror of `server/lib/tribeCadence.js` — the single authoritative Tribe care-cadence rules shared by the page, the Care dashboard widget, and the proactive alert: `cadenceStatus(entity)` → `{ state, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS`, `SOON_WINDOW_DAYS`. A cross-boundary contract test asserts it never drifts from the server copy. || `streakGlyph.js` | `streakGlyph(streak)` — the single POST streak emoji (✨ / ⚡ / 🔥 by day count) shared by the POST launcher, Morse trainer, daily widget, and dashboard streak widget. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 0fad646460..844535bb6e 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -104,6 +104,8 @@ export * from './singToScore.js';export * from './songCraft.js';export * from './songPlayback.js';export * from './songProgress.js';+export * from './spriteCollectionActions.js';+export * from './spriteFacets.js';export * from './streakGlyph.js';export * from './syncCounts.js';export * from './tabNotation.js';diff --git a/client/src/lib/spriteCollectionActions.js b/client/src/lib/spriteCollectionActions.jsnew file mode 100644index 0000000000..f73d6abc23--- /dev/null+++ b/client/src/lib/spriteCollectionActions.js@@ -0,0 +1,103 @@+/**+ * Sprite asset-collection action resolvers (#2931).+ *+ * Decides, for one classified asset row, whether the collection card gets a+ * **Regenerate** button (and whether it is enabled) and an **Edit in Loop+ * Trimmer** button. Split out of the page so the gating — which is the whole+ * correctness surface of the feature — is unit-testable without mounting the+ * Sprite Manager and its API graph.+ *+ * Pure: takes the already-fetched record detail plus the caller's in-flight+ * maps and callbacks, and returns closures. It performs no I/O itself and+ * knows nothing about React, toasts, or `apiSprites`.+ *+ * The gating deliberately TRACKS the authoritative workflow surfaces rather+ * than inventing its own rules — a walk direction is regenerable on the same+ * finalized/approved/anchor-locked/in-flight conditions `WalkWorkflow` gates+ * its Generate button on. The anchor path is intentionally looser than+ * `ReferenceWorkflow`'s: it omits the backend-availability (`!mode`) gate,+ * because the asset card doesn't own the backend picker and a re-roll falls+ * back to the install's configured image backend server-side.+ */++// Roles that represent a walk run's rendered output. A manifest or a review+// sheet from the same run is not something you re-render on its own.+const WALK_OUTPUT_ROLES = new Set(['strip', 'animation', 'frame']);++/**+ * @param detail the `/api/sprites/:id` payload (`{ record, reference, walk }`)+ * @param walkPending direction → jobId map for in-flight walk videos+ * @param referencePending target → jobId map for in-flight reference images+ * @param generateWalk (direction) => void — fires the walk render+ * @param generateAnchor (direction) => void — fires the anchor render+ * @param onRequestTrim (runId) => void — opens the Loop Trimmer for a run+ * @returns `{ regenerateFor(asset), trimFor(asset) }`, each returning null for+ * an asset it can't act on.+ */+export function buildCollectionActions({+ detail, walkPending = {}, referencePending = {},+ generateWalk, generateAnchor, onRequestTrim,+}) {+ const walk = detail?.walk || null;+ const finalized = Boolean(walk?.walkSet);+ const approvedDirections = walk?.selection?.directions || {};+ const anchors = detail?.reference?.manifest?.anchors || [];+ const lockedDirections = new Set(+ anchors.filter((a) => a.status === 'locked').map((a) => a.direction),+ );+ const knownDirections = new Set(anchors.map((a) => a.direction));+ // Only a run whose postprocess actually packed a strip can be trimmed — the+ // trim endpoint 409s (`RUN_NOT_CANDIDATE`) on anything else, so offering the+ // button would be a guaranteed error toast.+ const trimmableRunIds = new Set(+ (walk?.runs || []).filter((r) => r?.stripPreview?.stripPath).map((r) => r.id),+ );++ const regenerateFor = (asset) => {+ const { role, direction, runId, status } = asset?.facets || {};+ if (!direction || !knownDirections.has(direction)) return null;++ if (runId && WALK_OUTPUT_ROLES.has(role)) {+ const approved = approvedDirections[direction]?.status === 'approved';+ const locked = lockedDirections.has(direction);+ const pending = Boolean(walkPending[direction]);+ return {+ kind: 'walk',+ pending,+ disabled: finalized || approved || !locked || pending,+ title: finalized ? 'The walk set is finalized — regenerating is disabled'+ : approved ? 'This direction is already approved'+ : !locked ? "Lock this direction's reference anchor first"+ : 'Re-render this direction\'s walk cycle',+ onClick: () => generateWalk(direction),+ };+ }++ // A reference CANDIDATE can be re-rolled; an approved/superseded anchor+ // file only exists after the lock, and locks are irreversible. `south` is+ // excluded because the main reference needs a design prompt or an uploaded+ // image, neither of which an asset card can supply — that stays in+ // ReferenceWorkflow.+ if (role === 'reference' && status === 'candidate' && direction !== 'south') {+ const locked = lockedDirections.has(direction);+ const pending = Boolean(referencePending[direction]);+ return {+ kind: 'reference',+ pending,+ disabled: locked || pending,+ title: locked ? 'This anchor is locked — its reference set is frozen' : 'Render another candidate for this anchor',+ onClick: () => generateAnchor(direction),+ };+ }++ return null;+ };++ const trimFor = (asset) => {+ const { role, runId } = asset?.facets || {};+ if (!runId || !WALK_OUTPUT_ROLES.has(role) || !trimmableRunIds.has(runId)) return null;+ return { onClick: () => onRequestTrim(runId) };+ };++ return { regenerateFor, trimFor };+}diff --git a/client/src/lib/spriteCollectionActions.test.js b/client/src/lib/spriteCollectionActions.test.jsnew file mode 100644index 0000000000..501884b454--- /dev/null+++ b/client/src/lib/spriteCollectionActions.test.js@@ -0,0 +1,171 @@+import { describe, it, expect, vi } from 'vitest';+import { buildCollectionActions } from './spriteCollectionActions.js';+import { classifySpriteAsset } from './spriteFacets.js';++// The gating IS the feature here — every acceptance criterion on #2931's+// inline actions is a disabled/absent assertion. Assets are built through the+// real classifier so a facet-grammar change can't silently pass this suite.+const asset = (path) => ({ path, facets: classifySpriteAsset(path) });++const STRIP_EAST = asset('grok/walk-east-abc12345/generated/example-walk-east-strip.png');+const FRAME_EAST = asset('grok/walk-east-abc12345/generated/frames/00-left-contact.png');+const CANDIDATE_EAST = asset('reference/candidates/walk-east-candidate-1.png');++const RUN_EAST = {+ id: 'walk-east-abc12345',+ direction: 'east',+ status: 'candidate',+ stripPreview: { stripPath: 'grok/walk-east-abc12345/generated/example-walk-east-strip.png' },+};++const detailWith = (over = {}) => ({+ record: { id: 'example-walker', kind: 'character' },+ reference: { manifest: { anchors: [{ direction: 'east', status: 'locked' }, { direction: 'west', status: 'pending' }] } },+ walk: { runs: [RUN_EAST], selection: { directions: {} }, walkSet: null },+ ...over,+});++const build = (over = {}, maps = {}) => buildCollectionActions({+ detail: detailWith(over),+ generateWalk: vi.fn(),+ generateAnchor: vi.fn(),+ onRequestTrim: vi.fn(),+ ...maps,+});++describe('regenerateFor — walk outputs', () => {+ it('enables regenerate on a strip whose anchor is locked and nothing is in flight', () => {+ const r = build().regenerateFor(STRIP_EAST);+ expect(r).toMatchObject({ kind: 'walk', disabled: false, pending: false });+ });++ it('covers every walk output role, not just the strip', () => {+ expect(build().regenerateFor(FRAME_EAST)).toMatchObject({ kind: 'walk', disabled: false });+ });++ it('disables while a render for that direction is in flight', () => {+ const r = build({}, { walkPending: { east: 'job-1' } }).regenerateFor(STRIP_EAST);+ expect(r).toMatchObject({ disabled: true, pending: true });+ });++ it('treats the submitting sentinel as in flight — that is the double-click guard', () => {+ expect(build({}, { walkPending: { east: 'submitting' } }).regenerateFor(STRIP_EAST).disabled).toBe(true);+ });++ it('disables once the walk set is finalized', () => {+ const r = build({ walk: { runs: [RUN_EAST], selection: { directions: {} }, walkSet: { frozen: true } } })+ .regenerateFor(STRIP_EAST);+ expect(r.disabled).toBe(true);+ expect(r.title).toMatch(/finalized/);+ });++ it('disables for a direction that is already approved', () => {+ const r = build({ walk: { runs: [RUN_EAST], selection: { directions: { east: { status: 'approved' } } }, walkSet: null } })+ .regenerateFor(STRIP_EAST);+ expect(r.disabled).toBe(true);+ expect(r.title).toMatch(/already approved/);+ });++ it('disables while the direction anchor is still unlocked', () => {+ const r = build({ reference: { manifest: { anchors: [{ direction: 'east', status: 'pending' }] } } })+ .regenerateFor(STRIP_EAST);+ expect(r.disabled).toBe(true);+ expect(r.title).toMatch(/Lock this direction/);+ });++ it('fires the walk generator with the asset own direction', () => {+ const generateWalk = vi.fn();+ buildCollectionActions({+ detail: detailWith(), generateWalk, generateAnchor: vi.fn(), onRequestTrim: vi.fn(),+ }).regenerateFor(STRIP_EAST).onClick();+ expect(generateWalk).toHaveBeenCalledWith('east');+ });+});++describe('regenerateFor — reference anchors', () => {+ it('offers an anchor re-roll for an unlocked candidate', () => {+ const r = build({ reference: { manifest: { anchors: [{ direction: 'east', status: 'pending' }] } } })+ .regenerateFor(CANDIDATE_EAST);+ expect(r).toMatchObject({ kind: 'reference', disabled: false });+ r.onClick();+ });++ it('disables the re-roll once the anchor is locked — locks are irreversible', () => {+ expect(build().regenerateFor(CANDIDATE_EAST).disabled).toBe(true);+ });++ it('disables while an anchor render is in flight', () => {+ const r = build(+ { reference: { manifest: { anchors: [{ direction: 'east', status: 'pending' }] } } },+ { referencePending: { east: 'job-2' } },+ ).regenerateFor(CANDIDATE_EAST);+ expect(r).toMatchObject({ disabled: true, pending: true });+ });++ it('never offers a re-roll for the main reference — it needs a prompt or upload', () => {+ const main = asset('reference/candidates/walk-south-candidate-1.png');+ const actions = buildCollectionActions({+ detail: detailWith({ reference: { manifest: { anchors: [{ direction: 'south', status: 'pending' }] } } }),+ generateWalk: vi.fn(), generateAnchor: vi.fn(), onRequestTrim: vi.fn(),+ });+ expect(actions.regenerateFor(main)).toBeNull();+ });++ it('never offers a re-roll for a LOCKED reference file (not a candidate)', () => {+ expect(build().regenerateFor(asset('reference/example-walk-east-v1.png'))).toBeNull();+ });+});++describe('regenerateFor — non-actionable assets', () => {+ it.each([+ ['a manifest', 'grok/walk-east-abc12345/generated/example-walk-east-manifest.json'],+ ['a review sheet', 'grok/walk-east-abc12345/generated/review/example-walk-east-contrast-review.png'],+ ['an uploaded design image', 'reference/uploads/design.png'],+ ['a published atlas', 'runtime/v3/example-v3.png'],+ ])('returns null for %s', (_label, path) => {+ expect(build().regenerateFor(asset(path))).toBeNull();+ });++ it('returns null for a direction the record has no anchor for', () => {+ expect(build({ reference: { manifest: { anchors: [] } } }).regenerateFor(STRIP_EAST)).toBeNull();+ });++ it('tolerates a row with no facets', () => {+ expect(build().regenerateFor({ path: 'x.png' })).toBeNull();+ expect(build().trimFor(undefined)).toBeNull();+ });+});++describe('trimFor', () => {+ it('offers the trimmer for a run that packed a strip', () => {+ const onRequestTrim = vi.fn();+ const actions = buildCollectionActions({+ detail: detailWith(), generateWalk: vi.fn(), generateAnchor: vi.fn(), onRequestTrim,+ });+ actions.trimFor(STRIP_EAST).onClick();+ expect(onRequestTrim).toHaveBeenCalledWith('walk-east-abc12345');+ });++ it('stays available on an approved direction and a finalized walk set', () => {+ // Trims are non-destructive derived artifacts — the server only needs a+ // packaged manifest, so freezing the walk set must not hide the trimmer.+ const actions = build({+ walk: {+ runs: [{ ...RUN_EAST, status: 'approved' }],+ selection: { directions: { east: { status: 'approved' } } },+ walkSet: { frozen: true },+ },+ });+ expect(actions.trimFor(STRIP_EAST)).not.toBeNull();+ });++ it('is withheld for a run that never packed a strip — the endpoint would 409', () => {+ const actions = build({ walk: { runs: [{ id: 'walk-east-abc12345', direction: 'east', status: 'error' }], selection: { directions: {} }, walkSet: null } });+ expect(actions.trimFor(STRIP_EAST)).toBeNull();+ });++ it('is withheld for an asset outside a run', () => {+ expect(build().trimFor(CANDIDATE_EAST)).toBeNull();+ expect(build().trimFor(asset('runtime/v3/example-v3.png'))).toBeNull();+ });+});diff --git a/client/src/lib/spriteFacets.js b/client/src/lib/spriteFacets.jsnew file mode 100644index 0000000000..e54fd834fb--- /dev/null+++ b/client/src/lib/spriteFacets.js@@ -0,0 +1,205 @@+/**+ * Sprite asset facets (#2931) — classify a record-relative sprite asset path+ * into `{ family, status, role, direction, runId }` so the character asset+ * collection can group by what an asset *is* rather than by which directory it+ * happens to live in.+ *+ * This is the client-side counterpart of the source pipeline's+ * `assets.py:classify_asset()`. It stays client-side deliberately (#2930's+ * out-of-scope note): the listing is already scoped to one record, so a server+ * round-trip buys nothing, and the path grammar is stable enough to mirror.+ *+ * Pure module — no I/O, no React. The path grammar it decodes is written by:+ * reference/<id>-walk-<dir>-vN.png locked reference / anchor+ * reference/candidates/walk-<dir>-candidate-N.png+ * reference/uploads/<file> user-supplied design image+ * grok|runs/<runId>/generated/frames/NN-<phase>.png+ * grok|runs/<runId>/generated/<id>-walk-<dir>-strip.png+ * grok|runs/<runId>/generated/review/<id>-...-contrast-review.png+ * grok|runs/<runId>/generated/source-video.mp4+ * walk/trims/<slug>-vNNN-strip.png · <slug>-vNNN.gif+ * runtime/vN/<stem>-vN.png published atlas+ * atlas/<file> imported props atlas family+ */++// Mirrors server/services/sprites/prompts.js SPRITE_DIRECTIONS (the client+// can't import server modules; WalkWorkflow mirrors WALK_PHASES the same way).+export const SPRITE_DIRECTIONS = [+ 'south', 'south-east', 'east', 'north-east',+ 'north', 'north-west', 'west', 'south-west',+];++/**+ * Every role, in the order the collection renders its groups. `manifest` is a+ * PortOS addition to the source's role set: sidecar JSON is a real category+ * here (run records, reference sets, atlas manifests, the publish pointer) and+ * folding it into `sprite` would put JSON in the image grid.+ */+export const SPRITE_ASSET_ROLES = [+ 'reference', 'strip', 'animation', 'frame', 'atlas', 'evidence', 'sprite', 'manifest',+];++export const SPRITE_ROLE_LABELS = {+ reference: 'Reference set',+ strip: 'Strips',+ animation: 'Animations',+ frame: 'Frames',+ atlas: 'Atlases',+ evidence: 'Review evidence',+ sprite: 'Other sprites',+ manifest: 'Manifests',+};++// Longest-first alternation so `south-east` wins over `south` — regex+// alternation is ordered, which is what makes the boundary correct without a+// lookahead (`walk-south-east-abc` must not classify as `south`).+const DIRECTION_ALTERNATION = [...SPRITE_DIRECTIONS]+ .sort((a, b) => b.length - a.length)+ .join('|');+const ANCHOR_DIRECTION_MATCH = new RegExp(`walk-(${DIRECTION_ALTERNATION})`);+// Saved trims default to the slug `<direction>-loop`, which carries no+// `walk-` prefix — match it off the head of the filename instead.+const TRIM_DIRECTION_MATCH = new RegExp(`^walk/trims/(${DIRECTION_ALTERNATION})-`);++const RUN_DIR_MATCH = /^(?:grok|runs)\/([^/]+)\//;+const MANIFEST_EXT = /\.(json|ya?ml|txt|md|csv)$/i;+const ANIMATION_EXT = /\.(gif|mp4|webm|mov|m4v)$/i;+// `runtime/vN/` — the published-atlas version lives in the directory, not the+// filename, so supersede detection has to read it from there.+const RUNTIME_VERSION_DIR = /^runtime\/v(\d+)\//;+// `-v3.png`, `-v001-strip.png` — a trailing version marker on the filename.+const FILE_VERSION = /-v(\d+)(?=(-[a-z0-9-]+)?\.[a-z0-9]+$)/i;++const dirOf = (path) => {+ const idx = path.lastIndexOf('/');+ return idx < 0 ? '' : path.slice(0, idx);+};+const fileOf = (path) => path.slice(path.lastIndexOf('/') + 1);++function roleFor(path) {+ // Extension-driven checks come first: `runtime/current.json` is a manifest,+ // not an atlas, and a run's source clip is an animation, not a frame.+ if (MANIFEST_EXT.test(path)) return 'manifest';+ if (ANIMATION_EXT.test(path)) return 'animation';+ if (path.includes('/review/') || fileOf(path).includes('contrast-review')) return 'evidence';+ if (path.includes('/generated/frames/')) return 'frame';+ if (fileOf(path).includes('-strip')) return 'strip';+ if (path.startsWith('runtime/') || path.startsWith('atlas/')) return 'atlas';+ if (path.startsWith('reference/')) return 'reference';+ return 'sprite';+}++function statusFor(path) {+ // No PortOS path writes a `rejected/` segment today — the source pipeline+ // does, and imported trees can carry one, so it is honored rather than+ // silently classified as a candidate.+ if (/(^|\/)rejected\//.test(path)) return 'rejected';+ if (path.startsWith('runtime/') || path.startsWith('atlas/')) return 'runtime';+ if (path.startsWith('reference/candidates/')) return 'candidate';+ if (path.startsWith('reference/uploads/')) return 'source';+ if (path.startsWith('reference/')) return 'approved';+ // A saved trim is a deliberate, named output — not a raw run intermediate.+ if (path.startsWith('walk/')) return 'approved';+ if (RUN_DIR_MATCH.test(path)) return 'candidate';+ return 'source';+}++function familyFor(path, runId) {+ if (runId) return runId;+ if (path.startsWith('walk/trims/')) return 'trims';+ const idx = path.indexOf('/');+ return idx < 0 ? 'files' : path.slice(0, idx);+}++function directionFor(path) {+ const trim = TRIM_DIRECTION_MATCH.exec(path);+ if (trim) return trim[1];+ const anchor = ANCHOR_DIRECTION_MATCH.exec(path);+ return anchor ? anchor[1] : null;+}++/**+ * Version identity for supersede detection: assets sharing a `stem` are+ * successive versions of one artifact, and only the highest `version` is+ * current. Returns `null` when the path carries no version marker (nothing to+ * supersede against).+ */+function versionOf(path) {+ const runtimeDir = RUNTIME_VERSION_DIR.exec(path);+ if (runtimeDir) {+ // Strip the version from BOTH the directory and the filename so+ // `runtime/v2/hero-v2.png` and `runtime/v3/hero-v3.png` share a stem.+ return { stem: `runtime:${fileOf(path).replace(FILE_VERSION, '')}`, version: Number(runtimeDir[1]) };+ }+ const file = FILE_VERSION.exec(fileOf(path));+ if (!file) return null;+ return { stem: `${dirOf(path)}:${fileOf(path).replace(FILE_VERSION, '')}`, version: Number(file[1]) };+}++/**+ * Facets for a single record-relative asset path. Pure and total — an+ * unrecognized path degrades to `{ family: <first segment>, status: 'source',+ * role: 'sprite' }` rather than throwing.+ */+export function classifySpriteAsset(path) {+ if (typeof path !== 'string' || !path) {+ return { family: 'files', status: 'source', role: 'sprite', direction: null, runId: null };+ }+ const run = RUN_DIR_MATCH.exec(path);+ const runId = run ? run[1] : null;+ return {+ family: familyFor(path, runId),+ status: statusFor(path),+ role: roleFor(path),+ direction: directionFor(path),+ runId,+ };+}++/**+ * Classify a whole listing, adding the one facet that is only knowable across+ * the set: an `approved` asset that is NOT the highest version of its stem is+ * `superseded`. Deliberately scoped to `approved` — a runtime atlas stays+ * `runtime` (the publish pointer, not the version number, decides which is+ * live) and a candidate stays a candidate.+ *+ * Returns new objects; the input rows are never mutated.+ */+export function classifySpriteAssets(assets) {+ const rows = (Array.isArray(assets) ? assets : []).map((asset) => ({+ ...asset,+ facets: classifySpriteAsset(asset?.path),+ }));++ const latest = new Map();+ for (const row of rows) {+ if (row.facets.status !== 'approved') continue;+ const v = versionOf(row.path);+ if (!v) continue;+ latest.set(v.stem, Math.max(latest.get(v.stem) ?? -Infinity, v.version));+ }+ if (latest.size === 0) return rows;++ return rows.map((row) => {+ if (row.facets.status !== 'approved') return row;+ const v = versionOf(row.path);+ if (!v || v.version >= latest.get(v.stem)) return row;+ return { ...row, facets: { ...row.facets, status: 'superseded' } };+ });+}++/**+ * Classified assets grouped into render-ready role sections, in+ * `SPRITE_ASSET_ROLES` order. Empty roles are omitted.+ */+export function groupSpriteAssetsByRole(assets) {+ const rows = classifySpriteAssets(assets);+ const byRole = new Map();+ for (const row of rows) {+ const list = byRole.get(row.facets.role);+ if (list) list.push(row); else byRole.set(row.facets.role, [row]);+ }+ return SPRITE_ASSET_ROLES+ .filter((role) => byRole.has(role))+ .map((role) => ({ role, label: SPRITE_ROLE_LABELS[role], assets: byRole.get(role) }));+}diff --git a/client/src/lib/spriteFacets.test.js b/client/src/lib/spriteFacets.test.jsnew file mode 100644index 0000000000..963a459166--- /dev/null+++ b/client/src/lib/spriteFacets.test.js@@ -0,0 +1,156 @@+import { describe, it, expect } from 'vitest';+import {+ classifySpriteAsset, classifySpriteAssets, groupSpriteAssetsByRole,+ SPRITE_ASSET_ROLES, SPRITE_ROLE_LABELS,+} from './spriteFacets.js';++// Paths here are the shapes the server actually writes (see the module header)+// with a placeholder record id — never a real record from the live install.+const facets = (path) => classifySpriteAsset(path);++describe('classifySpriteAsset — role', () => {+ it('reads a locked reference and an anchor as the reference set', () => {+ expect(facets('reference/example-walk-south-v1.png').role).toBe('reference');+ expect(facets('reference/example-walk-north-east-v2.png').role).toBe('reference');+ expect(facets('reference/candidates/walk-east-candidate-3.png').role).toBe('reference');+ });++ it('separates strips, frames, animations and review evidence inside a run', () => {+ expect(facets('grok/walk-east-abc12345/generated/example-walk-east-strip.png').role).toBe('strip');+ expect(facets('grok/walk-east-abc12345/generated/frames/00-left-contact.png').role).toBe('frame');+ expect(facets('grok/walk-east-abc12345/generated/source-video.mp4').role).toBe('animation');+ expect(facets('grok/walk-east-abc12345/generated/review/example-walk-east-contrast-review.png').role).toBe('evidence');+ });++ it('classifies sidecar JSON as a manifest, not as the directory it sits in', () => {+ // The ordering trap: `runtime/current.json` starts with `runtime/`, which+ // would read as an atlas if the extension check ran second.+ expect(facets('runtime/current.json').role).toBe('manifest');+ expect(facets('runtime/v3/example-v3-manifest.json').role).toBe('manifest');+ expect(facets('reference/example-reference-set-v1.json').role).toBe('manifest');+ });++ it('classifies published atlases and imported props families as atlases', () => {+ expect(facets('runtime/v3/example-v3.png').role).toBe('atlas');+ expect(facets('atlas/props-crates.png').role).toBe('atlas');+ });++ it('splits a saved trim into its strip and its animation', () => {+ expect(facets('walk/trims/east-loop-v001-strip.png').role).toBe('strip');+ expect(facets('walk/trims/east-loop-v001.gif').role).toBe('animation');+ });+});++describe('classifySpriteAsset — status', () => {+ it('maps each tree to its lifecycle status', () => {+ expect(facets('runtime/v3/example-v3.png').status).toBe('runtime');+ expect(facets('reference/example-walk-south-v1.png').status).toBe('approved');+ expect(facets('reference/candidates/walk-east-candidate-1.png').status).toBe('candidate');+ expect(facets('reference/uploads/design.png').status).toBe('source');+ expect(facets('grok/walk-east-abc12345/generated/example-walk-east-strip.png').status).toBe('candidate');+ expect(facets('walk/trims/east-loop-v001-strip.png').status).toBe('approved');+ });++ it('honors an imported rejected/ segment', () => {+ expect(facets('runs/walk-east-legacy/rejected/take-1.png').status).toBe('rejected');+ });+});++describe('classifySpriteAsset — direction and run', () => {+ it('prefers the longest direction so a compound never truncates', () => {+ // `walk-south-east-…` must not read as `south` — ordered longest-first+ // alternation is what makes the boundary correct.+ expect(facets('grok/walk-south-east-abc12345/generated/frames/00-a.png').direction).toBe('south-east');+ expect(facets('grok/walk-south-abc12345/generated/frames/00-a.png').direction).toBe('south');+ });++ it('reads the direction off a default trim slug that carries no walk- prefix', () => {+ expect(facets('walk/trims/north-west-loop-v001-strip.png').direction).toBe('north-west');+ });++ it('extracts the run id from both on-disk run layouts', () => {+ expect(facets('grok/walk-east-abc12345/generated/x.png').runId).toBe('walk-east-abc12345');+ expect(facets('runs/imported-run-7/generated/x.png').runId).toBe('imported-run-7');+ expect(facets('reference/example-walk-east-v1.png').runId).toBeNull();+ });++ it('uses the run id as the family and the tree name otherwise', () => {+ expect(facets('grok/walk-east-abc12345/generated/x.png').family).toBe('walk-east-abc12345');+ expect(facets('walk/trims/east-loop-v001.gif').family).toBe('trims');+ expect(facets('reference/example-walk-east-v1.png').family).toBe('reference');+ expect(facets('loose-file.png').family).toBe('files');+ });++ it('degrades an unrecognized or missing path instead of throwing', () => {+ expect(facets('')).toEqual({ family: 'files', status: 'source', role: 'sprite', direction: null, runId: null });+ expect(facets(undefined).role).toBe('sprite');+ expect(facets('mystery/thing.png')).toMatchObject({ family: 'mystery', status: 'source', role: 'sprite' });+ });+});++describe('classifySpriteAssets — supersede', () => {+ it('demotes every approved version below the highest of its stem', () => {+ const rows = classifySpriteAssets([+ { path: 'reference/example-walk-east-v1.png' },+ { path: 'reference/example-walk-east-v2.png' },+ { path: 'reference/example-walk-east-v3.png' },+ ]);+ expect(rows.map((r) => r.facets.status)).toEqual(['superseded', 'superseded', 'approved']);+ });++ it('keeps versions of DIFFERENT stems independent', () => {+ const rows = classifySpriteAssets([+ { path: 'reference/example-walk-east-v2.png' },+ { path: 'reference/example-walk-west-v1.png' },+ ]);+ expect(rows.every((r) => r.facets.status === 'approved')).toBe(true);+ });++ it('matches a trim strip to its own stem across the -strip suffix', () => {+ const rows = classifySpriteAssets([+ { path: 'walk/trims/east-loop-v001-strip.png' },+ { path: 'walk/trims/east-loop-v002-strip.png' },+ ]);+ expect(rows.map((r) => r.facets.status)).toEqual(['superseded', 'approved']);+ });++ it('leaves runtime atlases alone — the publish pointer decides which is live', () => {+ const rows = classifySpriteAssets([+ { path: 'runtime/v1/example-v1.png' },+ { path: 'runtime/v2/example-v2.png' },+ ]);+ expect(rows.every((r) => r.facets.status === 'runtime')).toBe(true);+ });++ it('does not mutate the input rows', () => {+ const input = [{ path: 'reference/example-walk-east-v1.png' }, { path: 'reference/example-walk-east-v2.png' }];+ classifySpriteAssets(input);+ expect(input[0].facets).toBeUndefined();+ });++ it('tolerates a non-array listing', () => {+ expect(classifySpriteAssets(null)).toEqual([]);+ });+});++describe('groupSpriteAssetsByRole', () => {+ it('returns only non-empty roles, in the declared render order', () => {+ const groups = groupSpriteAssetsByRole([+ { path: 'runtime/current.json' },+ { path: 'grok/walk-east-abc12345/generated/example-walk-east-strip.png' },+ { path: 'reference/example-walk-east-v1.png' },+ ]);+ expect(groups.map((g) => g.role)).toEqual(['reference', 'strip', 'manifest']);+ expect(groups[0].label).toBe(SPRITE_ROLE_LABELS.reference);+ expect(groups.every((g) => g.assets.length > 0)).toBe(true);+ });++ it('labels every declared role', () => {+ expect(SPRITE_ASSET_ROLES.every((r) => typeof SPRITE_ROLE_LABELS[r] === 'string')).toBe(true);+ });++ it('carries the classified facets through onto each row', () => {+ const [group] = groupSpriteAssetsByRole([{ path: 'grok/walk-east-abc12345/generated/e-walk-east-strip.png', size: 12 }]);+ expect(group.assets[0]).toMatchObject({ size: 12, facets: { direction: 'east', runId: 'walk-east-abc12345' } });+ });+});diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex 1d3baef538..8431c97bf4 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -1,18 +1,21 @@import { useEffect, useState, useCallback, useMemo } from 'react';import { useParams, useNavigate } from 'react-router-dom';-import { PersonStanding, Package, Download, FolderOpen, X, RefreshCw, Plus } from 'lucide-react';+import { PersonStanding, Package, Download, X, RefreshCw, Plus } from 'lucide-react';import toast from '../components/ui/Toast';-import { listSpriteRecords, getSpriteRecord, importSprites, createSpriteRecord } from '../services/apiSprites.js';+import {+ listSpriteRecords, getSpriteRecord, importSprites, createSpriteRecord,+ generateSpriteWalk, generateSpriteReference,+} from '../services/apiSprites.js';import { getApps } from '../services/apiApps.js';import AppContextPicker from '../components/AppContextPicker.jsx';import ReferenceWorkflow from '../components/sprites/ReferenceWorkflow.jsx';-import WalkWorkflow from '../components/sprites/WalkWorkflow.jsx';+import WalkWorkflow, { WALK_WORKFLOW_DOM_ID, WALK_DURATIONS } from '../components/sprites/WalkWorkflow.jsx';import PublishWorkflow from '../components/sprites/PublishWorkflow.jsx';-import AssetInspector from '../components/sprites/AssetInspector.jsx';-import SpritePreview from '../components/sprites/SpritePreview.jsx';-import { hasSpritePreview } from '../components/sprites/spriteAssets.js';+import AssetCollection from '../components/sprites/AssetCollection.jsx';import { useAsyncAction } from '../hooks/useAsyncAction.js';-import { formatBytes, timeAgo } from '../utils/formatters.js';+import { useSpritePendingRenders } from '../hooks/useSpritePendingRenders.js';+import { buildCollectionActions } from '../lib/spriteCollectionActions.js';+import { timeAgo } from '../utils/formatters.js';// Sprite Manager: library over imported production sprites — characters// (reference sets, walk strips, runtime atlases) and props atlas families —@@ -22,11 +25,6 @@ import { formatBytes, timeAgo } from '../utils/formatters.js';// grok i2v clip per anchor, deterministic packaging, per-direction approval// into the finalized walk set — #2897). Publish lands in phase 4.-function topLevelGroup(assetPath) {- const idx = assetPath.indexOf('/');- return idx < 0 ? '' : assetPath.slice(0, idx);-}-function ImportPanel({ onImported }) {const [open, setOpen] = useState(false);const [apps, setApps] = useState([]);@@ -234,46 +232,6 @@ function RecordList({ records, selectedId, onSelect }) {);}-function AssetGroups({ recordId, assets }) {- const [inspecting, setInspecting] = useState(null);- const groups = useMemo(() => assets.reduce((acc, a) => {- const g = topLevelGroup(a.path) || 'files';- (acc[g] ||= []).push(a);- return acc;- }, {}), [assets]);- return (- <div className="space-y-4">- {Object.entries(groups).map(([group, files]) => (- <div key={group}>- <h4 className="flex items-center gap-1.5 text-sm font-semibold text-gray-300 mb-2">- <FolderOpen className="w-4 h-4" /> {group}- <span className="text-xs text-gray-500 font-normal">({files.length})</span>- </h4>- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-2">- {files.map((a) => (- <button- key={a.path}- onClick={() => setInspecting(a)}- className="bg-port-bg border border-port-border rounded p-1 text-left hover:border-port-accent"- title={a.path}- >- {hasSpritePreview(a) && (- <SpritePreview recordId={recordId} path={a.path} className="h-20 rounded" />- )}- <span className="block text-[10px] text-gray-500 truncate">{a.path.split('/').pop()}</span>- <span className="block text-[10px] text-gray-600">- {hasSpritePreview(a) ? `${a.width}×${a.height}` : formatBytes(a.size)}- </span>- </button>- ))}- </div>- </div>- ))}- <AssetInspector recordId={recordId} asset={inspecting} onClose={() => setInspecting(null)} />- </div>- );-}-export default function Sprites() {const { id } = useParams();const navigate = useNavigate();@@ -313,6 +271,93 @@ export default function Sprites() {return () => { stale = true; };}, [id, retryTick]);+ // In-flight render tracking is owned HERE rather than inside each workflow+ // (#2931): the asset collection's Regenerate buttons fire the same two+ // endpoints the workflows do, so they must share one map — two hook+ // instances would each rehydrate independently and let a Regenerate in the+ // collection leave the workflow's Generate button enabled (a second paid+ // render for the same direction). Hooks can't be conditional, so both run+ // for every record and no-op on a null/props record.+ const walkRenders = useSpritePendingRenders({+ recordId: id || null,+ kind: 'video',+ tagKey: 'spriteWalk',+ tagField: 'direction',+ onChanged: onWorkflowChanged,+ sweepDelays: () => [1500, 8000],+ failMessage: (direction, job) => `Walk render failed for ${direction}: ${job?.error || 'see media jobs'}`,+ });+ const referenceRenders = useSpritePendingRenders({+ recordId: id || null,+ kind: 'image',+ tagKey: 'spriteRef',+ tagField: 'target',+ onChanged: onWorkflowChanged,+ });++ // Which run the Loop Trimmer panel is open for. Phase 5 (#2933) turns this+ // into a `?spriteTab=trimmer&run=<id>` deep link; until then it routes the+ // collection's request into WalkWorkflow's existing inline TrimPanel so+ // there is still exactly one trim UI.+ const [trimRunId, setTrimRunId] = useState(null);+ useEffect(() => setTrimRunId(null), [id]);++ // Clip length lives here rather than inside WalkWorkflow so a Regenerate+ // fired from an asset card honors the length the user picked in the walk+ // panel instead of silently falling back to the server default.+ const [duration, setDuration] = useState(WALK_DURATIONS[0]);++ // Both generators share the reserve → submit → resolve/cancel dance; only+ // the endpoint, its args, and the fail message differ. The hook's setters+ // are stable identities, so depending on THEM (not the whole render-tracking+ // object, which is a fresh literal each render) keeps the memoized action+ // closures below from rebuilding every render.+ const { beginSubmit: walkBegin, resolveSubmit: walkResolve, cancelSubmit: walkCancel } = walkRenders;+ const { beginSubmit: refBegin, resolveSubmit: refResolve, cancelSubmit: refCancel } = referenceRenders;+ const submitRender = useCallback(async (begin, resolve, cancel, key, call, failMessage) => {+ begin(key);+ try {+ const { jobId } = await call();+ resolve(key, jobId);+ } catch (err) {+ cancel(key);+ toast.error(err?.message || failMessage);+ }+ }, []);++ const generateWalk = useCallback((direction) => submitRender(+ walkBegin, walkResolve, walkCancel, direction,+ () => generateSpriteWalk(id, { direction, duration }, { silent: true }),+ `Failed to queue ${direction} walk`,+ ), [id, duration, walkBegin, walkResolve, walkCancel, submitRender]);++ const generateAnchor = useCallback((direction) => submitRender(+ refBegin, refResolve, refCancel, direction,+ // The server falls back to the install's configured image backend — the+ // asset-card path deliberately doesn't thread ReferenceWorkflow's backend+ // picker (that state lives in the workflow); a re-roll uses the default.+ () => generateSpriteReference(id, { target: direction }, { silent: true }),+ `Failed to queue ${direction} render`,+ ), [id, refBegin, refResolve, refCancel, submitRender]);++ const collectionActions = useMemo(() => {+ if (detail?.record?.kind !== 'character') return null;+ return buildCollectionActions({+ detail,+ walkPending: walkRenders.pendingJobs,+ referencePending: referenceRenders.pendingJobs,+ generateWalk,+ generateAnchor,+ onRequestTrim: (runId) => {+ setTrimRunId(runId);+ // The trimmer lives inside WalkWorkflow further up the page; a request+ // from an asset card near the bottom must bring it into view or the+ // click looks like it did nothing.+ document.getElementById(WALK_WORKFLOW_DOM_ID)?.scrollIntoView({ behavior: 'smooth', block: 'start' });+ },+ });+ }, [detail, walkRenders.pendingJobs, referenceRenders.pendingJobs, generateWalk, generateAnchor]);+return (<div className="space-y-4"><div className="flex items-center gap-3">@@ -377,12 +422,19 @@ export default function Sprites() {<ReferenceWorkflowrecord={detail.record}reference={detail.reference}+ renders={referenceRenders}onChanged={onWorkflowChanged}/><WalkWorkflowrecord={detail.record}reference={detail.reference}walk={detail.walk}+ renders={walkRenders}+ duration={duration}+ onDurationChange={setDuration}+ onGenerate={generateWalk}+ trimRunId={trimRunId}+ onTrimClose={() => setTrimRunId(null)}onChanged={onWorkflowChanged}/>{/* Keyed by record so form state and an armed publish/overwrite@@ -399,7 +451,11 @@ export default function Sprites() {{detail.assets.length === 0 ? (<p className="text-sm text-gray-500">No assets on disk for this record.</p>) : (- <AssetGroups recordId={detail.record.id} assets={detail.assets} />+ <AssetCollection+ recordId={detail.record.id}+ assets={detail.assets}+ actions={collectionActions}+ />)}</div>)}