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
fix([issue-2924]): render walk loop previews for imagegen-redraw-approved directions
[._.]/ Adam Eivycfc222cad011
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3d376cf440..c5ab01fb35 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -7,6 +7,7 @@## Sprite Manager+- **[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.- **[issue-2898] Compile the runtime atlas and publish it to your game (phase 4)** — a finalized walk set can now be compiled into the immutable runtime sprite-sheet (the 10×8 grid of idle, the 8 named gait phases, and a scanner placeholder for all 8 directions, each frame scaled once per direction and pinned to the pivot ground line) and published straight into a managed app's repository. Every compile revalidates the whole evidence chain first — the finalized walk set, every packaged frame, and every locked anchor are checksum-verified — and recompiling the same set is a no-op instead of a new version. Publishing binds a character to a managed app and a repo-relative destination, replaces the atlas atomically, and refuses to clobber a destination that changed outside PortOS since the last publish; an optional code-binding guard verifies (occurrence-counted) that the game source still references the atlas where expected before anything is written. The Sprites tab gains the compile/publish panel with an inline confirmation and a publish history, and sprite walk-run raw frame intermediates are now excluded from backups by default (they regenerate deterministically from the archived source video — the toggle to re-include them is in the Backup tab).- **[issue-2897] Animate walk cycles from locked anchors (phase 3)** — each locked directional anchor can now be animated: PortOS asks Grok for exactly one walk-in-place video on the character's key-color matte, then packages it locally and deterministically — no further AI involved — into the canonical 8-phase walk strip (frame extraction, chroma un-key and de-spill keyed to the character's selected key color, automatic walk-cycle detection, fixed-scale pivot alignment, and a light/dark/checker contrast review sheet). Review each direction's loop right in the Sprites tab (animated preview), optionally trim frames non-destructively into a versioned loop GIF, and approve per direction; the eighth approval freezes the finalized walk set, which becomes immutable like the reference set. Every run carries a full provenance manifest with per-frame checksums, matching the format the phase-1 importer already understands.- **[issue-2896] Create characters and build their reference sets with AI (phase 2)** — the Sprites tab can now create a character from a name plus a text description and/or an uploaded design image, generate main-reference candidates through your configured image backend (Codex, Grok, or local), and freeze the approved candidate as the character's immutable identity root. From the frozen main you then derive the 8 directional anchors (front/back/profiles/three-quarters), review each candidate, and lock the set. On lock, PortOS normalizes the art onto a clean key-color square and auto-picks the best chroma key for that character — magenta, green, or blue, whichever sits farthest from the character's own colors (with a manual override limited to the same three keys, and a warning when every key risks clipping). Locked references are server-side immutable: regeneration and replacement are refused, corrections always land as new versions.diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex 877b73e7cf..a97167397f 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -19,15 +19,34 @@ const WALK_PHASES = ['left-contact', 'left-down', 'left-passing', 'left-up','right-contact', 'right-down', 'right-passing', 'right-up',];-const ALL_COLUMNS = WALK_PHASES.map((_, i) => i);const CELL_PX = 96; // preview cell size — the strip animates at 96px/frame-const LOOP_KEYFRAMES = `@keyframes sprite-walk-loop { to { background-position-x: -${CELL_PX * 8}px } }`;+// The scrub distance varies with the strip's frame count (a native run packs+// 8, an imported redraw cycle can pack 12 — #2924), so the single keyframe+// 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];-// Animated preview of a packed 8-frame strip: the strip PNG as a stepped-// background animation (8 frames at 12fps ≈ 0.67s per loop).-function StripLoop({ recordId, stripPath }) {+/**+ * Strip geometry for a preview/trim UI, defaulting to the native 8-phase+ * packaging when a run predates (or omits) the richer stripPreview fields.+ */+function stripGeometry(stripPreview) {+ const rawCount = Math.round(Number(stripPreview?.frameCount));+ const frameCount = Number.isInteger(rawCount) && rawCount > 1 ? rawCount : WALK_PHASES.length;+ const fps = Number(stripPreview?.fps) > 0 ? Number(stripPreview.fps) : 12;+ const cellWidth = Number(stripPreview?.cellWidth);+ const cellHeight = Number(stripPreview?.cellHeight);+ const aspect = cellWidth > 0 && cellHeight > 0 ? cellHeight / cellWidth : 1;+ return { frameCount, fps, height: Math.round(CELL_PX * aspect) };+}++// Animated preview of a packed strip: the strip PNG as a stepped background+// animation (8 frames at 12fps ≈ 0.67s per loop for a native run; an imported+// 12-frame redraw cycle steps 12 times over 1s).+function StripLoop({ recordId, stripPreview }) {+ const { frameCount, fps, height } = stripGeometry(stripPreview);+ const scrub = CELL_PX * frameCount;return (<divrole="img"@@ -35,11 +54,12 @@ function StripLoop({ recordId, stripPath }) {className="bg-port-bg border border-port-border rounded"style={{width: CELL_PX,- height: CELL_PX,- backgroundImage: `url(${spriteAssetUrl(recordId, stripPath)})`,- backgroundSize: `${CELL_PX * 8}px ${CELL_PX}px`,+ height,+ backgroundImage: `url(${spriteAssetUrl(recordId, stripPreview.stripPath)})`,+ backgroundSize: `${scrub}px ${height}px`,imageRendering: 'pixelated',- animation: 'sprite-walk-loop 0.667s steps(8) infinite',+ '--sprite-walk-loop-end': `-${scrub}px`,+ animation: `sprite-walk-loop ${(frameCount / fps).toFixed(3)}s steps(${frameCount}) infinite`,}}/>);@@ -49,7 +69,13 @@ function StripLoop({ recordId, stripPath }) {// server derives the strip geometry from the run manifest and re-packs the// enabled frames into a versioned strip + GIF.function TrimPanel({ recordId, run, onClose }) {- const [enabled, setEnabled] = useState(() => new Set(ALL_COLUMNS));+ // Column count follows the packaged strip rather than the 8-phase constant,+ // so a longer imported cycle trims every frame it actually contains (#2924).+ const columns = useMemo(() => {+ const { frameCount } = stripGeometry(run?.stripPreview);+ return Array.from({ length: frameCount }, (_, i) => i);+ }, [run?.stripPreview]);+ const [enabled, setEnabled] = useState(() => new Set(columns));const [result, setResult] = useState(null);const toggle = (i) => setEnabled((prev) => {const next = new Set(prev);@@ -68,12 +94,15 @@ function TrimPanel({ recordId, run, onClose }) {return (<div className="bg-port-bg border border-port-border rounded p-2 space-y-2"><div className="grid grid-cols-4 gap-1">- {WALK_PHASES.map((phase, i) => (- <label key={phase} className="flex items-center gap-1 text-[10px] text-gray-400 cursor-pointer">- <input type="checkbox" checked={enabled.has(i)} onChange={() => toggle(i)} />- <span className="truncate" title={phase}>{i}·{phase}</span>- </label>- ))}+ {columns.map((i) => {+ const phase = WALK_PHASES[i] || `frame ${i}`;+ return (+ <label key={i} className="flex items-center gap-1 text-[10px] text-gray-400 cursor-pointer">+ <input type="checkbox" checked={enabled.has(i)} onChange={() => toggle(i)} />+ <span className="truncate" title={phase}>{i}·{phase}</span>+ </label>+ );+ })}</div><div className="flex items-center gap-2"><button@@ -81,7 +110,7 @@ function TrimPanel({ recordId, run, onClose }) {disabled={saving || enabled.size < 2}className="px-2 py-0.5 text-xs bg-port-accent text-white rounded disabled:opacity-50">- {saving ? 'Saving…' : `Save trim (${enabled.size}/8)`}+ {saving ? 'Saving…' : `Save trim (${enabled.size}/${columns.length})`}</button><button onClick={onClose} className="px-2 py-0.5 text-xs text-gray-400 hover:text-white">Close</button></div>@@ -121,7 +150,7 @@ function DirectionCard({</p>{(approved || candidate) && run?.stripPreview?.stripPath && (- <StripLoop recordId={recordId} stripPath={run.stripPreview.stripPath} />+ <StripLoop recordId={recordId} stripPreview={run.stripPreview} />)}{/* Retry also covers a run wedged at 'postprocessing' (crash betweendiff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsxnew file mode 100644index 0000000000..b3b6748c2e--- /dev/null+++ b/client/src/components/sprites/WalkWorkflow.test.jsx@@ -0,0 +1,84 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen } from '@testing-library/react';++// Coverage for the walk viewer's loop preview (#2924). The load-bearing behavior:+// the stepped background animation is derived from the packaged strip's own+// geometry, so a 12-frame imported redraw cycle animates over 12 steps while a+// native 8-phase run keeps stepping 8 times.++vi.mock('../../services/apiSprites.js', () => ({+ generateSpriteWalk: vi.fn(),+ approveSpriteWalk: vi.fn(),+ postprocessSpriteWalk: vi.fn(),+ 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) => {+ const run = {+ id: 'run-east', direction: 'east', status: 'approved', stripPreview,+ };+ render(+ <WalkWorkflow+ record={{ id: 'example-walker' }}+ reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}+ walk={{+ runs: [run],+ selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },+ walkSet: null,+ }}+ onChanged={vi.fn()}+ />,+ );+ return screen.getByRole('img', { name: 'walk loop preview' });+};++describe('WalkWorkflow loop preview', () => {+ it('steps a native 8-frame strip 8 times over its 12fps cycle', () => {+ const loop = renderWalk({+ stripPath: 'grok/walk-east-abc/generated/strip.png',+ frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,+ });+ expect(loop.style.animation).toContain('steps(8)');+ expect(loop.style.animation).toContain('0.667s');+ expect(loop.style.backgroundSize).toBe(`${CELL_PX * 8}px ${CELL_PX}px`);+ });++ // The imported redraw cycle (#2924) packs 12 frames — the pre-fix hardcoded+ // steps(8)/-768px scrub cropped it to two thirds of the stride and skewed the gait.+ it('steps an imported 12-frame redraw strip 12 times', () => {+ const loop = renderWalk({+ stripPath: 'imagegen/v19/strip-video-12-clean-alpha.png',+ frameCount: 12, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,+ });+ expect(loop.style.animation).toContain('steps(12)');+ expect(loop.style.animation).toContain('1.000s');+ expect(loop.style.backgroundSize).toBe(`${CELL_PX * 12}px ${CELL_PX}px`);+ expect(loop.style.getPropertyValue('--sprite-walk-loop-end')).toBe(`-${CELL_PX * 12}px`);+ expect(loop.style.backgroundImage).toContain('/data/sprites/example-walker/imagegen/v19/strip-video-12-clean-alpha.png');+ });++ it('falls back to the native 8-phase geometry when the strip carries no frame count', () => {+ const loop = renderWalk({ stripPath: 'grok/walk-east-abc/generated/strip.png' });+ expect(loop.style.animation).toContain('steps(8)');+ expect(loop.style.backgroundSize).toBe(`${CELL_PX * 8}px ${CELL_PX}px`);+ });++ it('scales the preview box to a non-square cell', () => {+ const loop = renderWalk({+ stripPath: 'grok/walk-east-abc/generated/strip.png',+ frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 192,+ });+ expect(loop.style.height).toBe(`${CELL_PX / 2}px`);+ expect(loop.style.backgroundSize).toBe(`${CELL_PX * 8}px ${CELL_PX / 2}px`);+ });+});diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex e9782bf070..0d717c216d 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -33,7 +33,7 @@ import { spriteDir, resolveSpriteAssetPath, toRecordRelativeAssetPath } from './import { requireCharacter, loadManifest } from './reference.js';import { SPRITE_DIRECTIONS, anchorIdForDirection, buildWalkVideoPrompt } from './prompts.js';import {- prepareWalkAnchorInput, runWalkPostprocess, WALK_FPS, WALK_FRAME_COUNT,+ prepareWalkAnchorInput, runWalkPostprocess, WALK_FPS, WALK_FRAME_COUNT, WALK_CELL_SIZE,} from './walkPostprocess.js';import { GROK_VIDEO_DURATIONS } from '../videoGen/grok.js';@@ -110,6 +110,68 @@ function normalizeStripPreview(recordId, run) {return { ...run, stripPreview: { ...run.stripPreview, stripPath } };}+// Strip candidates on an imported redraw manifest, in preference order. The+// clean straight-alpha derivative comes first so the preview matches native+// runs (which are always transparent); the keyed matte is the last resort+// because it renders with the chroma background baked in.+const REDRAW_STRIP_FIELDS = ['stripAlpha', 'stripAlphaOriginal', 'stripKeyed'];++/**+ * Synthesize a preview-only run object for a direction approved from an+ * imagegen **redraw** manifest (issue #2924) rather than a grok walk run.+ *+ * The source pipeline's video-first redraw path (e.g. pioneer's east, packaged+ * as `imagegen/vN/…-manifest.json` with a 12-frame cycle) predates PortOS's own+ * grok-direct walk workflow, so the selection's `runPath` points at an+ * `imagegen/` directory with no matching `grok/` run record — `getWalkState`+ * surfaced nothing and the direction rendered its "approved" badge with no+ * loop preview. Rather than model a second full run-record type, read the+ * redraw manifest's `cycle` block and shape the minimum the UI needs. Returns+ * null when the manifest isn't a redraw cycle or its strip is missing on disk,+ * so a genuinely absent run stays absent instead of rendering a broken image.+ */+async function loadRedrawRun(recordId, direction, entry) {+ const manifestRel = toRecordRelativeAssetPath(recordId, entry.runManifest);+ if (!manifestRel) return null;+ const manifest = await readJSONFile(join(spriteDir(recordId), manifestRel), null);+ const cycle = manifest?.cycle;+ const frameCount = Number(cycle?.frameCount);+ if (!Number.isInteger(frameCount) || frameCount < 2) return null;++ let stripPath = null;+ for (const field of REDRAW_STRIP_FIELDS) {+ const rel = toRecordRelativeAssetPath(recordId, cycle[field]);+ // eslint-disable-next-line no-await-in-loop -- ordered preference: stop at the first strip that exists+ if (rel && await pathExists(join(spriteDir(recordId), rel))) {+ stripPath = rel;+ break;+ }+ }+ if (!stripPath) return null;++ const cellSize = Number(manifest.cellSize) > 0 ? Number(manifest.cellSize) : WALK_CELL_SIZE;+ const fps = Number(cycle.referenceFps) > 0 ? Number(cycle.referenceFps) : WALK_FPS;+ return {+ schemaVersion: 1,+ kind: 'imported-redraw-walk-cycle',+ status: 'approved',+ id: entry.runId,+ characterId: recordId,+ direction,+ createdAt: entry.approvedAt,+ postprocessManifest: manifestRel,+ stripPreview: {+ stripPath,+ frameCount,+ fps,+ cellWidth: cellSize,+ cellHeight: cellSize,+ row: 0,+ startColumn: 0,+ },+ };+}+/*** Walk-workflow view for the detail endpoint: every animation run (newest* first), the per-direction selection, and the finalized set when present.@@ -129,12 +191,24 @@ export async function getWalkState(recordId) {.map((e) => loadRunRecord(recordId, e.name)),).then((loaded) => loaded.filter(Boolean)- .map((run) => normalizeStripPreview(recordId, run))- .sort((a, b) => runCreatedAtMs(b.createdAt) - runCreatedAtMs(a.createdAt))),+ .map((run) => normalizeStripPreview(recordId, run))),loadSelection(recordId),loadWalkSet(recordId),]);- return { runs, selection, walkSet };++ // Directions approved from an imported redraw manifest have no grok run+ // record to scan — synthesize their preview from the manifest (#2924).+ const approvedDirections = walkSet?.directions || selection?.directions || {};+ const scannedRunIds = new Set(runs.map((run) => run.id));+ const redrawRuns = (await Promise.all(+ Object.entries(approvedDirections)+ .filter(([, entry]) => entry?.runId && entry?.runManifest && !scannedRunIds.has(entry.runId))+ .map(([direction, entry]) => loadRedrawRun(recordId, direction, entry)),+ )).filter(Boolean);++ const allRuns = [...runs, ...redrawRuns]+ .sort((a, b) => runCreatedAtMs(b.createdAt) - runCreatedAtMs(a.createdAt));+ return { runs: allRuns, selection, walkSet };}/**diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex a5f9600957..2aab909af6 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -416,4 +416,110 @@ describe('getWalkState', () => {// hash-pinned provenance) is never rewritten on disk.expect(await readFile(legacyPath)).toEqual(legacyBytesBefore);});++ // Issue #2924: a direction approved from the source pipeline's video-first+ // imagegen REDRAW path has no grok/ run directory at all — its selection+ // entry points at imagegen/vN. Synthesize the preview from that manifest's+ // cycle block so the card animates instead of showing a bare badge.+ describe('imagegen-redraw approved directions', () => {+ const REDRAW_MANIFEST_REL = 'imagegen/v19/walk-east-v19-manifest.json';++ async function characterWithRedrawEast(id, { cycle, cellSize = 384, strips = ['clean-alpha.png'] } = {}) {+ await characterWithLockedAnchors(id, ['east']);+ const dir = join(TEST_ROOT, 'sprites', id, 'imagegen', 'v19');+ await mkdir(dir, { recursive: true });+ for (const name of strips) await writeFile(join(dir, name), `strip:${name}`);+ await writeFile(join(TEST_ROOT, 'sprites', id, REDRAW_MANIFEST_REL), JSON.stringify({+ schemaVersion: 1,+ characterId: id,+ direction: 'east',+ pipeline: 'game-animation-frames-video-first',+ cellSize,+ cycle: cycle ?? {+ frameCount: 12,+ referenceFps: 12,+ // Source-repo-anchored, exactly as the importer copies it.+ stripAlpha: `art-source/sprites/${id}/imagegen/v19/clean-alpha.png`,+ stripKeyed: `art-source/sprites/${id}/imagegen/v19/keyed.png`,+ },+ }));+ await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });+ await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`), JSON.stringify({+ schemaVersion: 1,+ kind: 'reviewed-directional-walk-selection',+ characterId: id,+ status: 'in-progress',+ directions: {+ east: {+ status: 'approved',+ runId: `${id}-v19-east`,+ runPath: `art-source/sprites/${id}/imagegen/v19`,+ runManifest: `art-source/sprites/${id}/${REDRAW_MANIFEST_REL}`,+ approvedAt: 'established-production-v19',+ },+ },+ }));+ }++ it('synthesizes a run with the redraw cycle geometry and the clean-alpha strip', async () => {+ const id = newId();+ await characterWithRedrawEast(id);+ const { runs } = await getWalkState(id);+ expect(runs).toHaveLength(1);+ expect(runs[0]).toMatchObject({+ id: `${id}-v19-east`,+ direction: 'east',+ status: 'approved',+ kind: 'imported-redraw-walk-cycle',+ postprocessManifest: REDRAW_MANIFEST_REL,+ stripPreview: {+ stripPath: 'imagegen/v19/clean-alpha.png',+ frameCount: 12,+ fps: 12,+ cellWidth: 384,+ cellHeight: 384,+ row: 0,+ startColumn: 0,+ },+ });+ });++ it('falls back to the keyed strip when the clean-alpha derivative is absent on disk', async () => {+ const id = newId();+ await characterWithRedrawEast(id, { strips: ['keyed.png'] });+ const { runs } = await getWalkState(id);+ expect(runs[0].stripPreview.stripPath).toBe('imagegen/v19/keyed.png');+ });++ it('surfaces nothing when no strip exists, rather than a broken preview', async () => {+ const id = newId();+ await characterWithRedrawEast(id, { strips: [] });+ expect((await getWalkState(id)).runs).toEqual([]);+ });++ it('ignores a manifest with no usable cycle frame count', async () => {+ const id = newId();+ await characterWithRedrawEast(id, {+ cycle: { frameCount: 1, stripAlpha: 'imagegen/v19/clean-alpha.png' },+ });+ expect((await getWalkState(id)).runs).toEqual([]);+ });++ it('does not shadow a direction that DOES have a scanned grok run', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const { runId } = await startWalkGeneration(id, { direction: 'east' });+ await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });+ await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`), JSON.stringify({+ schemaVersion: 1,+ characterId: id,+ status: 'in-progress',+ directions: {+ east: { status: 'approved', runId, runManifest: `grok/${runId}/animation-run.json` },+ },+ }));+ const { runs } = await getWalkState(id);+ expect(runs).toHaveLength(1);+ expect(runs[0].kind).toBe('grok-game-animation-frames-run');+ });+ });});