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-2897]): Walk Cycles UI — per-direction generate/review/trim/approve with animated strip previews
[._.]/ Adam Eivy203dfe675654
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 33189a7472..6c4db76c5a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,7 @@## Sprite Manager+- **[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.- **[issue-2895] Media Gen gains a Sprites section (phase 1: library + import)** — a new Sprites tab lists your game-sprite characters and prop atlas families, browses each one's locked reference set, walk-cycle strips, and published atlas versions (with pixel-perfect previews), and imports the approved production assets from an existing sprite-pipeline checkout in one click. Only final/approved artifacts import — rejected candidates and raw video intermediates stay behind — and every file the source manifests hash-pin is verified on the way in. Reachable from ⌘K and voice ("take me to sprites"). Generation (reference → anchors → walk videos → publish-to-game) lands in the follow-up phases.diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxnew file mode 100644index 0000000000..8c466d4ab1--- /dev/null+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -0,0 +1,326 @@+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 { getMediaJob, listMediaJobs } from '../../services/apiMediaJobs.js';+import { useAsyncAction } from '../../hooks/useAsyncAction.js';+import { spriteAssetUrl } from './spriteAssets.js';++// 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.+// The server's run records / selection / walk-set are the source of truth;+// this component renders them and fires generate/approve/trim.++// Mirrors server/services/sprites/walkPostprocess.js WALK_PHASES.+const WALK_PHASES = [+ 'left-contact', 'left-down', 'left-passing', 'left-up',+ 'right-contact', 'right-down', 'right-passing', 'right-up',+];+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 } }`;++// 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, paused = false }) {+ return (+ <div+ role="img"+ aria-label="walk loop preview"+ 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`,+ imageRendering: 'pixelated',+ animation: paused ? 'none' : 'sprite-walk-loop 0.667s steps(8) infinite',+ }}+ />+ );+}++// Frame enable/disable trimmer for one packaged run — non-destructive: the+// server re-packs enabled frames into a versioned strip + GIF.+function TrimPanel({ recordId, run, onClose }) {+ const [enabled, setEnabled] = useState(() => new Set(WALK_PHASES.map((_, i) => i)));+ const [result, setResult] = useState(null);+ const toggle = (i) => setEnabled((prev) => {+ const next = new Set(prev);+ if (next.has(i)) next.delete(i); else next.add(i);+ return next;+ });+ const [save, saving] = useAsyncAction(async () => {+ const trim = await trimSpriteWalk(recordId, {+ slug: `${run.direction}-loop`,+ atlasPath: run.stripPreview.stripPath,+ row: 0,+ cellWidth: run.stripPreview.cellWidth,+ cellHeight: run.stripPreview.cellHeight,+ fps: run.stripPreview.fps,+ allColumns: WALK_PHASES.map((_, i) => i),+ enabledColumns: [...enabled].sort((a, b) => a - b),+ sourceFrameLabels: [...enabled].sort((a, b) => a - b).map((i) => WALK_PHASES[i]),+ }, { silent: true });+ setResult(trim);+ toast.success(`Trim saved (${trim.frameCount} frames)`);+ }, { errorMessage: 'Trim failed' });++ 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>+ ))}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={save}+ 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)`}+ </button>+ <button onClick={onClose} className="px-2 py-0.5 text-xs text-gray-400 hover:text-white">Close</button>+ </div>+ {result && (+ <div className="flex items-center gap-2">+ <img+ src={spriteAssetUrl(recordId, result.loop)}+ alt="trimmed loop"+ className="w-24 h-24 object-contain bg-port-card border border-port-border rounded"+ style={{ imageRendering: 'pixelated' }}+ />+ <p className="text-[10px] text-gray-500 break-all">{result.loop}</p>+ </div>+ )}+ </div>+ );+}++function DirectionCard({+ recordId, direction, anchorLocked, run, approved, finalized, pending, onGenerate, onApprove, onRetry,+}) {+ const [confirming, setConfirming] = useState(false);+ const [trimming, setTrimming] = useState(false);+ const candidate = run?.status === 'candidate' ? run : null;+ const statusLabel = approved ? 'approved'+ : pending ? 'rendering…'+ : run?.status === 'postprocessing' ? 'packaging…'+ : run?.status || (anchorLocked ? 'ready' : 'anchor not locked');++ return (+ <div className="bg-port-bg border border-port-border rounded p-2 space-y-1.5">+ <p className="text-xs text-gray-400 flex items-center justify-between">+ {direction}+ <span className={`text-[10px] ${approved ? 'text-port-success' : run?.status === 'error' ? 'text-port-error' : 'text-gray-500'}`}>+ {approved && <Check className="w-3 h-3 inline mr-0.5" />}{statusLabel}+ </span>+ </p>++ {(approved || candidate) && run?.stripPreview?.stripPath && (+ <StripLoop recordId={recordId} stripPath={run.stripPreview.stripPath} />+ )}++ {run?.status === 'error' && (+ <div className="space-y-1">+ <p className="text-[10px] text-port-error break-words">{run.postprocessError || 'postprocess failed'}</p>+ <button onClick={() => onRetry(run)} className="px-2 py-0.5 text-[10px] bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent">+ Retry postprocess+ </button>+ </div>+ )}++ {!finalized && !approved && (+ <div className="space-y-1.5">+ <button+ onClick={() => onGenerate(direction)}+ disabled={!anchorLocked || pending}+ title={anchorLocked ? undefined : 'Lock this direction\'s reference anchor first'}+ className="flex items-center gap-1 w-full justify-center px-2 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50"+ >+ {pending+ ? <><RefreshCw className="w-3 h-3 animate-spin" /> Rendering…</>+ : <><Film className="w-3 h-3" /> {candidate ? 'Regenerate' : 'Generate walk'}</>}+ </button>+ {candidate && (+ confirming ? (+ <div className="flex items-center gap-1 text-xs">+ <span className="text-port-warning">Approve?</span>+ <button onClick={() => { setConfirming(false); onApprove(direction, candidate.id); }} className="px-1.5 py-0.5 bg-port-accent text-white rounded">Yes</button>+ <button onClick={() => setConfirming(false)} className="px-1.5 py-0.5 text-gray-400 hover:text-white">No</button>+ </div>+ ) : (+ <div className="flex gap-1">+ <button onClick={() => setConfirming(true)} className="flex-1 px-2 py-0.5 text-xs bg-port-success/20 border border-port-success rounded text-port-success">+ Approve+ </button>+ <button+ onClick={() => setTrimming((t) => !t)}+ title="Trim loop frames"+ className="px-2 py-0.5 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ <Scissors className="w-3 h-3" />+ </button>+ </div>+ )+ )}+ {trimming && candidate && (+ <TrimPanel recordId={recordId} run={candidate} onClose={() => setTrimming(false)} />+ )}+ </div>+ )}+ </div>+ );+}++export default function WalkWorkflow({ record, reference, walk, onChanged }) {+ const recordId = record.id;+ const manifest = reference?.manifest || null;+ const runs = walk?.runs || [];+ const selection = walk?.selection || null;+ const finalized = Boolean(walk?.walkSet);+ // direction → jobId for in-flight video renders.+ const [pendingJobs, setPendingJobs] = useState({});++ // Rehydrate in-flight walk renders on mount/record switch (same contract+ // as ReferenceWorkflow's rehydrate — a reload must not re-enable Generate+ // mid-render).+ useEffect(() => {+ let stale = false;+ listMediaJobs({ kind: 'video', owner: 'sprites' }, { silent: true })+ .then((jobs) => {+ if (stale) return;+ const active = {};+ for (const job of jobs || []) {+ const tag = job.params?.spriteWalk;+ if (tag?.recordId === recordId && ['queued', 'running'].includes(job.status)) {+ active[tag.direction] = job.id;+ }+ }+ if (Object.keys(active).length > 0) setPendingJobs((prev) => ({ ...active, ...prev }));+ })+ .catch(() => {});+ return () => { stale = true; };+ }, [recordId]);++ // Poll in-flight renders; the completion hook packages server-side, so a+ // finished job needs one deferred refetch (plus a late sweep — the+ // postprocess takes seconds, unlike the reference hook's instant copy).+ useEffect(() => {+ if (Object.keys(pendingJobs).length === 0) return undefined;+ const timer = setInterval(async () => {+ const entries = Object.entries(pendingJobs).filter(([, jobId]) => jobId !== 'submitting');+ const results = await Promise.all(entries.map(async ([direction, jobId]) => {+ try {+ return { direction, job: await getMediaJob(jobId) };+ } catch (err) {+ return { direction, job: null, gone: err?.status === 404 };+ }+ }));+ const finished = results.filter(({ job, gone }) => (job ? ['completed', 'failed', 'canceled'].includes(job.status) : gone));+ if (finished.length === 0) return;+ setPendingJobs((prev) => {+ const next = { ...prev };+ for (const { direction } of finished) delete next[direction];+ return next;+ });+ for (const { direction, job } of finished) {+ if (job?.status === 'failed') toast.error(`Walk render failed for ${direction}: ${job.error || 'see media jobs'}`);+ }+ // The deterministic postprocess runs after the job completes — sweep+ // twice so the packaged candidate (or its error) lands in the UI.+ setTimeout(onChanged, 1500);+ setTimeout(onChanged, 8000);+ }, 4000);+ return () => clearInterval(timer);+ }, [pendingJobs, onChanged]);++ const latestRunByDirection = useMemo(() => {+ const byDir = {};+ for (const run of runs) {+ // runs arrive newest-first; prefer the approved run when one exists.+ if (!byDir[run.direction]) byDir[run.direction] = run;+ }+ for (const [direction, sel] of Object.entries(selection?.directions || {})) {+ const approvedRun = runs.find((r) => r.id === sel.runId);+ if (approvedRun) byDir[direction] = approvedRun;+ }+ return byDir;+ }, [runs, selection]);++ const generate = async (direction) => {+ setPendingJobs((prev) => ({ ...prev, [direction]: 'submitting' }));+ try {+ const { jobId } = await generateSpriteWalk(recordId, { direction }, { silent: true });+ setPendingJobs((prev) => ({ ...prev, [direction]: jobId }));+ } catch (err) {+ setPendingJobs((prev) => {+ const next = { ...prev };+ if (next[direction] === 'submitting') delete next[direction];+ return next;+ });+ 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`);+ onChanged();+ }, { errorMessage: 'Approve failed' });++ const [retryPostprocess] = useAsyncAction(async (run) => {+ await postprocessSpriteWalk(recordId, { runId: run.id }, { silent: true });+ toast.success('Postprocess complete');+ onChanged();+ }, { errorMessage: 'Postprocess failed' });++ // The walk workflow only becomes actionable once the main is frozen (the+ // south anchor IS the main); hide it entirely before that.+ if (!manifest?.mainReference?.locked) return null;++ const approvedCount = Object.values(selection?.directions || {})+ .filter((d) => d?.status === 'approved').length;++ return (+ <div 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">+ <Film className="w-4 h-4" /> Walk Cycles+ <span className="text-xs font-normal text-gray-500">+ {finalized ? 'finalized' : `${approvedCount}/8 approved`}+ </span>+ </h3>+ {finalized && (+ <p className="text-xs text-port-success flex items-center gap-1">+ <Lock className="w-3 h-3" /> walk set frozen · immutable+ </p>+ )}+ </div>+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">+ {(manifest.anchors || []).map((anchor) => (+ <DirectionCard+ key={anchor.direction}+ recordId={recordId}+ direction={anchor.direction}+ anchorLocked={anchor.status === 'locked'}+ run={latestRunByDirection[anchor.direction] || null}+ approved={selection?.directions?.[anchor.direction]?.status === 'approved'}+ finalized={finalized}+ pending={Boolean(pendingJobs[anchor.direction])}+ onGenerate={generate}+ onApprove={approve}+ onRetry={retryPostprocess}+ />+ ))}+ </div>+ </div>+ );+}diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex 15b7418640..e0a30b70e0 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -4,16 +4,18 @@ import { PersonStanding, Package, Download, FolderOpen, X, RefreshCw, Plus } froimport toast from '../components/ui/Toast';import { listSpriteRecords, getSpriteRecord, importSprites, createSpriteRecord } from '../services/apiSprites.js';import ReferenceWorkflow from '../components/sprites/ReferenceWorkflow.jsx';+import WalkWorkflow from '../components/sprites/WalkWorkflow.jsx';import { spriteAssetUrl } from '../components/sprites/spriteAssets.js';import { useAsyncAction } from '../hooks/useAsyncAction.js';import { formatBytes, timeAgo } from '../utils/formatters.js';// Sprite Manager: library over imported production sprites — characters// (reference sets, walk strips, runtime atlases) and props atlas families —-// plus the source-tree importer (#2895) and the phase-2 reference workflow+// plus the source-tree importer (#2895), the phase-2 reference workflow// (create a character, generate + freeze the main reference, derive + lock-// the 8 directional anchors — #2896). Animation and publish land in later-// phases.+// the 8 directional anchors — #2896), and the phase-3 walk workflow (one+// grok i2v clip per anchor, deterministic packaging, per-direction approval+// into the finalized walk set — #2897). Publish lands in phase 4.const IMAGE_EXT = /\.(png|gif|webp|jpe?g)$/i;@@ -216,8 +218,17 @@ function RecordList({ records, selectedId, onSelect }) {);}-function AssetGroups({ recordId, assets }) {+// Raw ffmpeg-extracted frame intermediates (30–96 PNGs per walk run) would+// swamp the asset browser — hide them, matching the importer's exclusion of+// raw/ from cross-machine copies. They stay on disk for the postprocessor.+const RUN_RAW_INTERMEDIATE = /^grok\/[^/]+\/generated\/raw\//;++function AssetGroups({ recordId, assets: allAssets }) {const [preview, setPreview] = useState(null);+ const assets = useMemo(+ () => allAssets.filter((a) => !RUN_RAW_INTERMEDIATE.test(a.path)),+ [allAssets],+ );const groups = useMemo(() => assets.reduce((acc, a) => {const g = topLevelGroup(a.path) || 'files';(acc[g] ||= []).push(a);@@ -372,11 +383,19 @@ export default function Sprites() {)}</div>{detail.record.kind === 'character' && (- <ReferenceWorkflow- record={detail.record}- reference={detail.reference}- onChanged={onWorkflowChanged}- />+ <>+ <ReferenceWorkflow+ record={detail.record}+ reference={detail.reference}+ onChanged={onWorkflowChanged}+ />+ <WalkWorkflow+ record={detail.record}+ reference={detail.reference}+ walk={detail.walk}+ onChanged={onWorkflowChanged}+ />+ </>)}{detail.assets.length === 0 ? (<p className="text-sm text-gray-500">No assets on disk for this record.</p>diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 8dfafd9bab..4006555153 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -96,7 +96,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiCreativeDirector.js` | Creative Director (video production). || `apiCreativeCommission.js` | Creative Commissions (Autonomous Creation Engine — standing recurring briefs). || `apiMusicVideo.js` | Music Video projects + scene board + audio analysis. |-| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896). |+| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), walk workflow: generate/approve/trim/postprocess (#2897). || `apiPipeline.js` | Pipeline (issues + stages + canon). || `apiUniverseBuilder.js` | Universe Builder (generate + edit + commit). || `apiAuthors.js` | Author personas (name, writing style, bio, headshot description/style). |diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsindex 651b9efcca..af1f93f9b7 100644--- a/client/src/services/apiSprites.js+++ b/client/src/services/apiSprites.js@@ -45,3 +45,28 @@ export const generateSpriteReference = (id, { referenceImageFile, ...fields }, oexport const lockSpriteReference = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/reference/lock`, {method: 'POST', body: JSON.stringify(body), ...options,});++// Phase 3 (#2897): walk-animation workflow — one grok i2v clip per locked+// directional anchor, deterministic server-side packaging, per-direction+// approval into the finalized walk set.++// Queue one walk video render. Returns { jobId, runId, direction, duration }.+export const generateSpriteWalk = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/generate`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});++// Approve a packaged candidate run for its direction. Returns the updated+// { runs, selection, walkSet } walk state.+export const approveSpriteWalk = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/approve`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});++// Re-run the deterministic postprocess on a run whose video already landed.+export const postprocessSpriteWalk = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/postprocess`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});++// Save a non-destructive loop trim (strip + GIF + manifest, versioned).+export const trimSpriteWalk = (id, body, options = {}) => request(`/sprites/${encodeURIComponent(id)}/walk/trim`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});