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
sprite walk: /simplify pass — share bounds via a sharp-free leaf, dedup unlock/reopen, align clip length
[._.]/ Adam Eivyf53faec3559c
diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex b95d059a57..57ea716c00 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -43,6 +43,17 @@ export const WALK_DEFAULT_FPS = 10;export const WALK_FRAME_COUNT_RANGE = { min: 6, max: 16 };export const WALK_FPS_RANGE = { min: 4, max: 24 };+// Inclusive integer sequence [min..max] by step. Both dropdown option lists are+// derived from module-level constants, so build them once at load rather than+// on every render.+const seq = (min, max, step) => {+ const out = [];+ for (let v = min; v <= max; v += step) out.push(v);+ return out;+};+const FRAME_COUNT_OPTIONS = seq(WALK_FRAME_COUNT_RANGE.min, WALK_FRAME_COUNT_RANGE.max, 1);+const FPS_OPTIONS = seq(WALK_FPS_RANGE.min, WALK_FPS_RANGE.max, 2);+/*** Strip geometry for a preview/trim UI, defaulting to the native 8-phase* packaging when a run predates (or omits) the richer stripPreview fields.@@ -370,21 +381,24 @@ export default function WalkWorkflow({onChanged();}, { errorMessage: 'Approve failed' });- // Retry a wedged/errored run — re-runs the packer at the CURRENT frame-count- // and speed so a recovery also picks up the user's chosen cycle look.+ // Re-run the deterministic packer on a run's ON-DISK clip at the CURRENT+ // frame-count/speed — the one call shared by the errored-run "Retry" and the+ // candidate "Reprocess" buttons (no grok, no regeneration).+ const postprocessRun = (run) => postprocessSpriteWalk(recordId, { runId: run.id, frameCount, fps }, { silent: true });++ // Retry a wedged/errored run so a recovery also picks up the chosen cycle look.const [retryPostprocess] = useAsyncAction(async (run) => {- await postprocessSpriteWalk(recordId, { runId: run.id, frameCount, fps }, { silent: true });+ await postprocessRun(run);toast.success('Postprocess complete');onChanged();}, { errorMessage: 'Postprocess failed' });- // Reprocess a candidate from its ON-DISK clip at the current frame-count/speed- // (no grok call). Track the in-flight direction so only that card spins.+ // Reprocess a candidate. Track the in-flight direction so only that card spins.const [reprocessingDir, setReprocessingDir] = useState(null);const [reprocess] = useAsyncAction(async (run) => {setReprocessingDir(run.direction);try {- await postprocessSpriteWalk(recordId, { runId: run.id, frameCount, fps }, { silent: true });+ await postprocessRun(run);toast.success(`Walk ${run.direction} reprocessed · ${frameCount}f @ ${fps}fps`);onChanged();} finally {@@ -417,14 +431,6 @@ export default function WalkWorkflow({const approvedCount = Object.values(selection?.directions || {}).filter((d) => d?.status === 'approved').length;- const range = (min, max, step = 2) => {- const out = [];- for (let v = min; v <= max; v += step) out.push(v);- if (out[out.length - 1] !== max) out.push(max);- return out;- };- const frameCountOptions = range(WALK_FRAME_COUNT_RANGE.min, WALK_FRAME_COUNT_RANGE.max, 1);- const fpsOptions = range(WALK_FPS_RANGE.min, WALK_FPS_RANGE.max, 2);const cycleSeconds = (frameCount / fps).toFixed(2);const cycleLabel = `${frameCount}f @ ${fps}fps`;@@ -478,7 +484,7 @@ export default function WalkWorkflow({onChange={(e) => onFrameCountChange(Number(e.target.value))}className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white">- {frameCountOptions.map((n) => <option key={n} value={n}>{n}</option>)}+ {FRAME_COUNT_OPTIONS.map((n) => <option key={n} value={n}>{n}</option>)}</select></label><label className="flex items-center gap-1.5 text-xs text-gray-400">@@ -488,7 +494,7 @@ export default function WalkWorkflow({onChange={(e) => onFpsChange(Number(e.target.value))}className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white">- {fpsOptions.map((n) => <option key={n} value={n}>{n} fps</option>)}+ {FPS_OPTIONS.map((n) => <option key={n} value={n}>{n} fps</option>)}</select></label><label className="flex items-center gap-1.5 text-xs text-gray-400" title="grok renders 6s or 10s clips; length only affects how much source footage the packer has to choose from">diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 04961a2436..56761dd35c 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -5,6 +5,9 @@ import { WORK_TRACKERS } from './workTracker.js';import { SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS } from '../services/sprites/recordsLogic.js';import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS } from '../services/sprites/prompts.js';import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';+import {+ WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT, WALK_MIN_FPS, WALK_MAX_FPS,+} from '../services/sprites/walkBounds.js';import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total@@ -1093,20 +1096,20 @@ const spriteWalkDirectionSchema = z.enum(SPRITE_DIRECTIONS);const spriteWalkRunIdSchema = z.string().regex(/^walk-[a-z-]+-[0-9a-f]{8}$/);-// Walk-cycle authoring bounds. Mirror walkPostprocess.js WALK_MIN/MAX_* — kept-// as literals here so the validation graph doesn't pull sharp/ffmpeg in via-// walkPostprocess. The server re-clamps into the same range, so these are a-// guard, not the source of truth: frame count 6–16, playback fps 4–24.-const spriteWalkFrameCountSchema = z.number().int().min(6).max(16);-const spriteWalkFpsSchema = z.number().int().min(4).max(24);+// Walk-cycle authoring bounds — imported from the sharp-free walkBounds leaf so+// the request schema and the server-side clamp share ONE range definition (a+// bounds change can't silently diverge). walkBounds pulls in no native deps.+const spriteWalkFrameCountSchema = z.number().int().min(WALK_MIN_FRAME_COUNT).max(WALK_MAX_FRAME_COUNT);+const spriteWalkFpsSchema = z.number().int().min(WALK_MIN_FPS).max(WALK_MAX_FPS);export const spriteWalkGenerateSchema = z.object({direction: spriteWalkDirectionSchema,- // Clip length in seconds (see GROK_VIDEO_DURATIONS). Short clips are ample- // for a looping walk cycle; the walk service defaults to 2s when omitted.- duration: z.union([- z.literal(1), z.literal(2), z.literal(3), z.literal(6), z.literal(10),- ]).optional(),+ // Clip length in seconds. grok's image_to_video only honors its documented+ // 6s/10s options and clamps anything shorter to ~6s, so only those two are+ // accepted; the service defaults to 6s when omitted. Clip length only affects+ // how much source footage the packer can choose from — the cycle's look is set+ // by frameCount/fps below.+ duration: z.union([z.literal(6), z.literal(10)]).optional(),// Deterministic-postprocess knobs (not grok's): how many frames the packed// cycle holds and how fast it plays back. Omitted → service defaults.frameCount: spriteWalkFrameCountSchema.optional(),diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex f749703454..07df116958 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -42,10 +42,11 @@ import {} from './walkPostprocess.js';import { GROK_VIDEO_DURATIONS } from '../videoGen/grok.js';-// Walk clips default SHORTER than general video gen: a looping walk cycle needs-// only ~8 frames of one gait, so a 2s clip renders far faster than the 6s-// general default while still giving the cycle selector plenty of frames.-const WALK_DEFAULT_DURATION = 2;+// grok's image_to_video honors only 6s/10s and clamps shorter requests to ~6s,+// so 6 is both the floor and the sensible default: a 6s clip yields plenty of+// source frames (~70) for the cycle selector, and the walk's look is tuned by+// frame count + fps, not clip length.+const WALK_DEFAULT_DURATION = 6;// grok's walk render runs as an OBSERVABLE TUI session (issue: user wants to// watch/course-correct grok in the Shell) rather than a headless mediaJobQueue@@ -638,7 +639,7 @@ export function rerunWalkPostprocess(recordId, { runId, frameCount, fps }) {return walkWriteTail(recordId, () => rerunWalkPostprocessImpl(recordId, runId, { frameCount, fps }));}-async function rerunWalkPostprocessImpl(recordId, runId, overrides = {}) {+async function rerunWalkPostprocessImpl(recordId, runId, overrides) {await requireCharacter(recordId);await requireUnfinalized(recordId);const run = await loadRunRecord(recordId, runId);@@ -652,12 +653,10 @@ async function rerunWalkPostprocessImpl(recordId, runId, overrides = {}) {throw new ServerError('Run has no source video yet', { status: 409, code: 'VIDEO_NOT_READY' });}// Reprocess the SAME on-disk clip at a (possibly) new frame count / playback- // speed — no grok call, no regeneration. Only fields present in the override- // change; omitted ones fall through to the run's stored values in packageRun.- await packageRun(recordId, run, {- ...(overrides.frameCount != null ? { frameCount: overrides.frameCount } : {}),- ...(overrides.fps != null ? { fps: overrides.fps } : {}),- });+ // speed — no grok call, no regeneration. packageRun's `?? run.x ?? default`+ // merge treats an absent override identically to `undefined`, so pass them+ // straight through — no need to strip the undefined fields first.+ await packageRun(recordId, run, overrides);await saveRunRecord(recordId, run);if (run.status === 'error') {throw new ServerError(`Postprocess failed: ${run.postprocessError}`, { status: 422, code: 'POSTPROCESS_FAILED' });@@ -697,30 +696,42 @@ export function unlockWalkSet(recordId) {return walkWriteTail(recordId, () => unlockWalkSetImpl(recordId));}+// Imported source-pipeline sets carry no regenerable clips, so unlocking or+// reopening would strand the record with nothing to regenerate from — refuse+// both through one shared message (the `verb` is the only difference). No-op for+// a native set (or no set at all).+function assertNotImportedWalkSet(walkSet, verb) {+ if (walkSet && isImportedWalkSet(walkSet)) {+ throw new ServerError(+ `This walk set was imported from the source pipeline and has no regenerable clips — ${verb} is not supported. Create a new character version to revise it.`,+ { status: 409, code: 'LEGACY_IMPORTED_WALK_SET' },+ );+ }+}++// Un-finalize: drop the canonical "finalized" signal (the walk-set file) FIRST,+// then downgrade the record status — the exact inverse of finalize's order, so a+// crash mid-unfinalize can only leave a cosmetic stale status, never a+// walk-complete record with no frozen set behind it. Shared by unlock (re-opens+// all directions) and reopen (re-opens one).+async function dropFinalizedWalkSet(recordId) {+ await rm(join(spriteDir(recordId), walkSetRelPath(recordId)), { force: true });+ await updateRecord(recordId, { status: 'reference-complete' });+}+async function unlockWalkSetImpl(recordId) {await requireCharacter(recordId);const walkSet = await loadWalkSet(recordId);if (!walkSet) {throw new ServerError('No finalized walk set to unlock', { status: 409, code: 'WALK_SET_NOT_FINAL' });}- if (isImportedWalkSet(walkSet)) {- throw new ServerError(- 'This walk set was imported from the source pipeline and has no regenerable clips — unlocking is not supported. Create a new character version to revise it.',- { status: 409, code: 'LEGACY_IMPORTED_WALK_SET' },- );- }- // Order mirrors finalize's inverse: drop the canonical "finalized" signal- // (the walk-set file) first so a crash mid-unlock can only leave a cosmetic- // stale record status, never a walk-complete record with no frozen set.- await rm(join(spriteDir(recordId), walkSetRelPath(recordId)), { force: true });- // Reset the selection to in-progress: with the walk set gone `finalized` is- // false, but each direction still reads `approved` from the selection, which- // keeps the generate/regenerate buttons gated off. Seeding a fresh selection- // re-opens every direction; the rendered runs remain, so re-approval is a- // single click per direction the user is happy with. (atomicWrite ensures the- // walk/ dir, which already exists since we just removed the walk-set file.)+ assertNotImportedWalkSet(walkSet, 'unlocking');+ await dropFinalizedWalkSet(recordId);+ // Seed a fresh (empty) selection so EVERY direction re-opens: with the walk+ // set gone each direction would still read `approved` from the old selection+ // and keep the generate/regenerate buttons gated off, so reset it. The+ // rendered runs remain on disk, so re-approval is a single click per direction.await atomicWrite(join(spriteDir(recordId), selectionRelPath(recordId)), seedSelection(recordId));- await updateRecord(recordId, { status: 'reference-complete' });console.log(`🔓 sprite walk set unlocked for ${recordId}`);return getWalkState(recordId);}@@ -747,23 +758,15 @@ export function reopenWalkDirection(recordId, { direction }) {async function reopenWalkDirectionImpl(recordId, direction) {await requireCharacter(recordId);const walkSet = await loadWalkSet(recordId);- if (walkSet && isImportedWalkSet(walkSet)) {- throw new ServerError(- 'This walk set was imported from the source pipeline and has no regenerable clips — reopening is not supported. Create a new character version to revise it.',- { status: 409, code: 'LEGACY_IMPORTED_WALK_SET' },- );- }+ assertNotImportedWalkSet(walkSet, 'reopening');const selection = (await loadSelection(recordId)) || seedSelection(recordId);if (selection.directions?.[direction]?.status !== 'approved') {throw new ServerError(`Direction ${direction} is not approved`, { status: 409, code: 'DIRECTION_NOT_APPROVED' });}- // If the set was finalized, un-finalize it FIRST (drop the canonical signal)- // so a crash mid-reopen can only leave a cosmetic stale record status, never a- // walk-complete record with a hole in its set. Other approvals are untouched.- if (walkSet) {- await rm(join(spriteDir(recordId), walkSetRelPath(recordId)), { force: true });- await updateRecord(recordId, { status: 'reference-complete' });- }+ // If the set was finalized, un-finalize it FIRST (a set is "final" only when+ // all 8 are approved) — keeping every OTHER direction's approval intact, so+ // re-freezing is a single re-approval rather than all eight.+ if (walkSet) await dropFinalizedWalkSet(recordId);delete selection.directions[direction];selection.status = 'in-progress';await ensureDir(join(spriteDir(recordId), 'walk'));diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex d6cdac8ec4..359cb7d520 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -153,7 +153,7 @@ describe('startWalkGeneration', () => {const id = await characterWithLockedAnchors(newId(), ['east']);const result = await startWalkGeneration(id, { direction: 'east' });expect(result.runId).toMatch(/^walk-east-[0-9a-f]{8}$/);- expect(result.duration).toBe(2); // walk default (WALK_DEFAULT_DURATION)+ expect(result.duration).toBe(6); // walk default (WALK_DEFAULT_DURATION — grok's real floor)// The shell session id is the run id, so the card can deep-link to /shell/<id>.expect(result.shellSession).toBe(result.runId);@@ -189,11 +189,12 @@ describe('startWalkGeneration', () => {expect(executeTuiRun.mock.calls[0][0].prompt).toContain('for 10 seconds');});- it('honors a short 2s clip length', async () => {+ it('falls back to the default clip length for a duration grok does not offer', async () => {+ // Values outside GROK_VIDEO_DURATIONS fall back to WALK_DEFAULT_DURATION (6).const id = await characterWithLockedAnchors(newId(), ['east']);- const result = await startWalkGeneration(id, { direction: 'east', duration: 2 });- expect(result.duration).toBe(2);- expect(executeTuiRun.mock.calls[0][0].prompt).toContain('for 2 seconds');+ const result = await startWalkGeneration(id, { direction: 'east', duration: 5 });+ expect(result.duration).toBe(6);+ expect(executeTuiRun.mock.calls[0][0].prompt).toContain('for 6 seconds');});it('stores the chosen frame count + fps on the run and passes them to the packer', async () => {diff --git a/server/services/sprites/walkBounds.js b/server/services/sprites/walkBounds.jsnew file mode 100644index 0000000000..efd2594bfb--- /dev/null+++ b/server/services/sprites/walkBounds.js@@ -0,0 +1,60 @@+/**+ * Sprites — walk-cycle authoring bounds + pure label/clamp helpers.+ *+ * A dependency-free leaf module (NO sharp/ffmpeg) so both the deterministic+ * packer (walkPostprocess.js, which imports sharp) AND the request-validation+ * layer (server/lib/validation.js) can share ONE definition of the frame-count+ * / playback-fps range. Keeping these in walkPostprocess would drag its native+ * image graph into the validation graph; duplicating them as literals in the+ * Zod schema let the schema and the server-side clamp silently diverge. This+ * module is the single source of truth for both — see the recordsLogic.js+ * sharp-free split for the same pattern.+ */++// Source-pipeline gait phases (the historical 8-frame packing). Part of the+// cross-install artifact contract — imported manifests carry these exact labels.+export const WALK_PHASES = [+ 'left-contact', 'left-down', 'left-passing', 'left-up',+ 'right-contact', 'right-down', 'right-passing', 'right-up',+];++// Legacy default / fallback frame count for manifests (or clients) that omit it.+export const WALK_FRAME_COUNT = 8;++// Configurable authoring range (#sprite-walk-variable-frames). The packer+// resamples the detected gait window DOWN to `frameCount` distinct source frames+// (never upsamples), and playback fps is metadata — so a slower/smoother walk+// needs no regeneration, only a reprocess of the on-disk clip at a new count/fps.+export const WALK_DEFAULT_FRAME_COUNT = 12;+export const WALK_DEFAULT_FPS = 10;+export const WALK_MIN_FRAME_COUNT = 6;+export const WALK_MAX_FRAME_COUNT = 16;+export const WALK_MIN_FPS = 4;+export const WALK_MAX_FPS = 24;++/**+ * Column/phase labels for an N-frame packed strip. The historical 8-frame+ * packing keeps its named 2-beat gait phases (so existing atlases and imported+ * manifests round-trip byte-identically); any other length uses positional+ * `frame-NN` labels. Postprocess (which writes them) and atlas.js (which+ * asserts them) MUST derive labels through this one helper so they can never+ * disagree on a column's identity.+ */+export function walkPhaseLabels(n) {+ if (n === WALK_PHASES.length) return [...WALK_PHASES];+ return Array.from({ length: n }, (_, i) => `frame-${String(i).padStart(2, '0')}`);+}++/** Clamp a requested frame count into the supported authoring range. */+export function clampFrameCount(n) {+ const v = Math.round(Number(n));+ if (!Number.isFinite(v)) return WALK_DEFAULT_FRAME_COUNT;+ return Math.max(WALK_MIN_FRAME_COUNT, Math.min(WALK_MAX_FRAME_COUNT, v));+}++/** Clamp a requested playback fps into the supported authoring range. */+export function clampFps(n) {+ const v = Math.round(Number(n));+ if (!Number.isFinite(v)) return WALK_DEFAULT_FPS;+ return Math.max(WALK_MIN_FPS, Math.min(WALK_MAX_FPS, v));+}diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex bba9335baf..5d1979f5a5 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -27,6 +27,21 @@ import { ensureDir, atomicWrite, sha256File } from '../../lib/fileUtils.js';import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';import { keyChannelSplit, keyness, keyShareFn, hexToRgb } from './chromaKey.js';+// Authoring bounds + pure label/clamp helpers live in a sharp-free leaf module+// so server/lib/validation.js can share the SAME frame-count/fps range without+// pulling this module's native image graph in. Re-exported here so existing+// consumers (walk.js, atlas.js) keep importing them from walkPostprocess.+import {+ WALK_FRAME_COUNT, WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,+ walkPhaseLabels, clampFrameCount, clampFps,+} from './walkBounds.js';++export {+ WALK_PHASES, WALK_FRAME_COUNT, WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,+ WALK_MIN_FRAME_COUNT, WALK_MAX_FRAME_COUNT, WALK_MIN_FPS, WALK_MAX_FPS,+ walkPhaseLabels, clampFrameCount, clampFps,+} from './walkBounds.js';+// Source pipeline constants (animation_postprocess.py) — values are part of// the cross-install artifact contract (imported manifests carry them).// WALK_FPS is the source-EXTRACTION sampling rate (how densely we pull frames@@ -34,56 +49,10 @@ import { keyChannelSplit, keyness, keyShareFn, hexToRgb } from './chromaKey.js';// manifests that omit `frameRate`. Playback fps (how fast the packed cycle// animates) is now a separate, per-run value carried in the manifest.export const WALK_FPS = 12;-// Legacy default / fallback frame count for manifests (or clients) that omit it.-export const WALK_FRAME_COUNT = 8;-// Configurable authoring range (#sprite-walk-variable-frames): native-// generation now packs a fuller, slower cycle by default so a walk reads as a-// walk, not a run. The packer resamples the detected gait window DOWN to-// `frameCount` distinct source frames (it never upsamples — N is bounded by-// the source frames available in one cycle), and playback fps is metadata-// carried into the manifest/atlas. So a slower/smoother walk needs no-// regeneration — only a reprocess of the on-disk clip at a new count/fps.-export const WALK_DEFAULT_FRAME_COUNT = 12;-export const WALK_DEFAULT_FPS = 10;-export const WALK_MIN_FRAME_COUNT = 6;-export const WALK_MAX_FRAME_COUNT = 16;-export const WALK_MIN_FPS = 4;-export const WALK_MAX_FPS = 24;export const MAX_SOURCE_SECONDS = 8;export const MAX_SOURCE_DIMENSION = 512;export const WALK_CELL_SIZE = 384;export const WALK_PIVOT = [WALK_CELL_SIZE / 2, 352]; // [192, 352]-export const WALK_PHASES = [- 'left-contact', 'left-down', 'left-passing', 'left-up',- 'right-contact', 'right-down', 'right-passing', 'right-up',-];--/**- * Column/phase labels for an N-frame packed strip. The historical 8-frame- * packing keeps its named 2-beat gait phases (so existing atlases and imported- * manifests round-trip byte-identically); any other length uses positional- * `frame-NN` labels. Postprocess (which writes them) and atlas.js (which- * asserts them) MUST derive labels through this one helper so they can never- * disagree on a column's identity.- */-export function walkPhaseLabels(n) {- if (n === WALK_PHASES.length) return [...WALK_PHASES];- return Array.from({ length: n }, (_, i) => `frame-${String(i).padStart(2, '0')}`);-}--/** Clamp a requested frame count into the supported authoring range. */-export function clampFrameCount(n) {- const v = Math.round(Number(n));- if (!Number.isFinite(v)) return WALK_DEFAULT_FRAME_COUNT;- return Math.max(WALK_MIN_FRAME_COUNT, Math.min(WALK_MAX_FRAME_COUNT, v));-}--/** Clamp a requested playback fps into the supported authoring range. */-export function clampFps(n) {- const v = Math.round(Number(n));- if (!Number.isFinite(v)) return WALK_DEFAULT_FPS;- return Math.max(WALK_MIN_FPS, Math.min(WALK_MAX_FPS, v));-}// Border-key acceptance thresholds. The key channels must dominate the dark// channels by ≥ KEY_DOMINANCE_MIN, and each channel group must be balanced