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: render sprite animations on local MiniMax H3, not only grok (#4876)
[._.]/ Adam Eivy9641e70605a0
diff --git a/client/src/components/sprites/AnimationProviderPicker.jsx b/client/src/components/sprites/AnimationProviderPicker.jsxnew file mode 100644index 0000000000..e48fc65e33--- /dev/null+++ b/client/src/components/sprites/AnimationProviderPicker.jsx@@ -0,0 +1,51 @@+/**+ * Which engine renders an animation track's source clip (#4876).+ *+ * Grok's cloud i2v lane was the only option until PortOS grew a local MiniMax H3+ * one, and the two are interchangeable from here down: everything after the MP4+ * — chroma recovery, frame selection, loop trimming, geometry QC, approval,+ * atlas compile — is the same deterministic pipeline. So this is a plain picker+ * shared by the walk panel and every track panel rather than a second workflow.+ *+ * Renders NOTHING until the server's readiness list arrives, and nothing when+ * there is at most one lane: an install with no local build should not carry a+ * one-option dropdown implying a choice it does not have.+ *+ * An unready lane stays visible but disabled, with the server's own `reason`+ * shown as text beside it. That is deliberate — hiding it would leave the user+ * with no way to discover the local lane exists, and per the repo's UI rules a+ * warning that lives only in a `title` is missed on touch.+ */+export default function AnimationProviderPicker({+ id, providers, provider, onChange, disabled = false,+}) {+ // `null` = not fetched yet (distinct from `[]` = fetched and empty), so a+ // slow or failed probe never flashes a picker that then disappears.+ if (!Array.isArray(providers) || providers.length < 2) return null;+ const selected = providers.find((entry) => entry.id === provider) || null;+ const blockedReason = selected && selected.ready === false ? selected.reason : null;+ return (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <label className="flex items-center gap-1.5 text-xs text-gray-400" htmlFor={id}>+ Render on+ <select+ id={id}+ value={provider}+ disabled={disabled}+ onChange={(e) => onChange(e.target.value)}+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white disabled:opacity-50"+ >+ {providers.map((entry) => (+ <option key={entry.id} value={entry.id} disabled={entry.ready === false}>+ {entry.label}+ {entry.ready === false ? ' (unavailable)' : ''}+ </option>+ ))}+ </select>+ </label>+ {blockedReason && (+ <p className="text-xs text-port-warning basis-full sm:basis-auto">{blockedReason}</p>+ )}+ </div>+ );+}diff --git a/client/src/components/sprites/AnimationProviderPicker.test.jsx b/client/src/components/sprites/AnimationProviderPicker.test.jsxnew file mode 100644index 0000000000..1824070725--- /dev/null+++ b/client/src/components/sprites/AnimationProviderPicker.test.jsx@@ -0,0 +1,87 @@+import { describe, it, expect, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';++/**+ * The render-lane picker shared by the walk panel and every track panel (#4876).+ *+ * The behaviors that matter are all about NOT misleading the user: it must stay+ * invisible until the server's readiness list arrives (so a slow probe does not+ * flash a control that then vanishes), it must not imply a choice on an install+ * that has only one lane, and an unusable lane must stay visible-but-blocked with+ * the reason spelled out as text rather than hidden in a title attribute.+ */++import AnimationProviderPicker from './AnimationProviderPicker.jsx';++const GROK = { id: 'grok', label: 'Grok (cloud)', ready: true, reason: null };+const LOCAL_READY = { id: 'local', label: 'Local (MiniMax H3)', ready: true, reason: null };+const LOCAL_BLOCKED = {+ id: 'local',+ label: 'Local (MiniMax H3)',+ ready: false,+ reason: 'The MiniMax H3 MLX runtime is not installed — install it from Video Gen, then reload.',+};++const renderPicker = (props = {}) => render(+ <AnimationProviderPicker+ id="walk-provider-hero"+ providers={[GROK, LOCAL_READY]}+ provider="grok"+ onChange={vi.fn()}+ {...props}+ />,+);++describe('AnimationProviderPicker', () => {+ it('renders nothing while the readiness list has not arrived', () => {+ const { container } = renderPicker({ providers: null });+ expect(container).toBeEmptyDOMElement();+ });++ it('renders nothing when this install offers only one lane', () => {+ // A single-option dropdown implies a choice the user does not have.+ const { container } = renderPicker({ providers: [GROK] });+ expect(container).toBeEmptyDOMElement();+ expect(renderPicker({ providers: [] }).container).toBeEmptyDOMElement();+ });++ it('lists both lanes and pairs its label to the select by id', () => {+ renderPicker();+ const select = screen.getByLabelText(/Render on/);+ expect(select).toHaveAttribute('id', 'walk-provider-hero');+ expect(select.value).toBe('grok');+ expect(screen.getByRole('option', { name: 'Grok (cloud)' })).toBeInTheDocument();+ expect(screen.getByRole('option', { name: 'Local (MiniMax H3)' })).toBeInTheDocument();+ });++ it('reports the chosen lane by id', () => {+ const onChange = vi.fn();+ renderPicker({ onChange });+ fireEvent.change(screen.getByLabelText(/Render on/), { target: { value: 'local' } });+ expect(onChange).toHaveBeenCalledWith('local');+ });++ it('disables an unready lane and marks it in the option text', () => {+ renderPicker({ providers: [GROK, LOCAL_BLOCKED] });+ const option = screen.getByRole('option', { name: /Local \(MiniMax H3\) \(unavailable\)/ });+ expect(option).toBeDisabled();+ expect(screen.getByRole('option', { name: 'Grok (cloud)' })).not.toBeDisabled();+ });++ it('shows the blocking reason as TEXT once that lane is the selected one', () => {+ // Not a `title`: per the repo's UI rules a tooltip-only warning is missed on+ // touch, and this is the only place the fix is named.+ renderPicker({ providers: [GROK, LOCAL_BLOCKED], provider: 'local' });+ expect(screen.getByText(/runtime is not installed/)).toBeInTheDocument();+ });++ it('stays quiet about a blocked lane the user has not selected', () => {+ renderPicker({ providers: [GROK, LOCAL_BLOCKED], provider: 'grok' });+ expect(screen.queryByText(/runtime is not installed/)).toBeNull();+ });++ it('disables the whole control when the caller says the set is frozen', () => {+ renderPicker({ disabled: true });+ expect(screen.getByLabelText(/Render on/)).toBeDisabled();+ });+});diff --git a/client/src/components/sprites/TrackWorkflow.jsx b/client/src/components/sprites/TrackWorkflow.jsxindex 947d1c7db9..86fe021554 100644--- a/client/src/components/sprites/TrackWorkflow.jsx+++ b/client/src/components/sprites/TrackWorkflow.jsx@@ -6,6 +6,7 @@ import { useAsyncAction } from '../../hooks/useAsyncAction.js';import { SPRITE_DIRECTIONS } from '../../lib/spriteFacets.js';import { CorrectionNoteToggle, trackCorrectionKey } from './CorrectionNote.jsx';import { checkerboardStyle, spriteAssetUrl } from './spriteAssets.js';+import AnimationProviderPicker from './AnimationProviderPicker.jsx';/*** One review/approve surface for EVERY non-walk animation track (#3136).@@ -28,6 +29,7 @@ import { checkerboardStyle, spriteAssetUrl } from './spriteAssets.js';*/export default function TrackWorkflow({record, reference, state, onGenerate, onChanged, corrections = null, onCorrectionChange = null,+ providers = null, provider = 'grok', onProviderChange = () => {},}) {const definition = state?.definition || null;const runs = state?.runs || [];@@ -81,7 +83,7 @@ export default function TrackWorkflow({return (<section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">- <div className="flex items-center justify-between gap-3">+ <div className="flex flex-wrap items-center justify-between gap-3"><h3 className="flex items-center gap-1.5 text-sm font-semibold text-white"><Icon className="w-4 h-4" /> {definition.label}<span className="text-xs font-normal text-gray-500">@@ -89,7 +91,22 @@ export default function TrackWorkflow({{' · '}{definition.defaultFrameCount}f @ {definition.defaultFps}fps</span></h3>- <span className="text-[11px] text-gray-500">directly requested Grok render; local deterministic packing</span>+ {/* The lane caption is derived, not hardcoded (#4876): it read+ "directly requested Grok render" while grok was the only engine, and+ would have been a lie the moment a local render was picked. Only the+ packing half is unconditional — that is deterministic either way. */}+ <div className="flex flex-wrap items-center justify-end gap-x-3 gap-y-1">+ <AnimationProviderPicker+ id={`track-provider-${record.id}-${definition.id}`}+ providers={providers}+ provider={provider}+ onChange={onProviderChange}+ disabled={finalized}+ />+ <span className="text-[11px] text-gray-500">+ directly requested {provider === 'local' ? 'local' : 'Grok'} render; local deterministic packing+ </span>+ </div></div><div className={`grid gap-2 ${directional ? 'sm:grid-cols-2 xl:grid-cols-4' : ''}`}>{directions.map((direction) => {diff --git a/client/src/components/sprites/TrackWorkflow.test.jsx b/client/src/components/sprites/TrackWorkflow.test.jsxindex 6d92048bab..458a7bb987 100644--- a/client/src/components/sprites/TrackWorkflow.test.jsx+++ b/client/src/components/sprites/TrackWorkflow.test.jsx@@ -147,6 +147,34 @@ describe.each(TRACKS)('TrackWorkflow renders the $definition.id track from its d});});+describe.each(TRACKS)('render-lane picker on the $definition.id track (#4876)', ({ definition }) => {+ const PROVIDERS = [+ { id: 'grok', label: 'Grok (cloud)', ready: true, reason: null },+ { id: 'local', label: 'Local (MiniMax H3)', ready: true, reason: null },+ ];++ it('offers the picker and reports the chosen lane', () => {+ const onProviderChange = vi.fn();+ renderTrack(definition, {}, { providers: PROVIDERS, provider: 'grok', onProviderChange });+ fireEvent.change(screen.getByLabelText(/Render on/), { target: { value: 'local' } });+ expect(onProviderChange).toHaveBeenCalledWith('local');+ });++ it('shows no picker when the page never learned about a second lane', () => {+ renderTrack(definition);+ expect(screen.queryByLabelText(/Render on/)).toBeNull();+ });++ it('names the SELECTED lane in the caption instead of hardcoding Grok', () => {+ // The caption read "directly requested Grok render" unconditionally, which+ // became a lie the moment a local render was picked.+ renderTrack(definition, {}, { providers: PROVIDERS, provider: 'local', onProviderChange: vi.fn() });+ expect(screen.getByText(/directly requested local render/)).toBeInTheDocument();+ renderTrack(definition, {}, { providers: PROVIDERS, provider: 'grok', onProviderChange: vi.fn() });+ expect(screen.getAllByText(/directly requested Grok render/).length).toBeGreaterThan(0);+ });+});+describe('a track this client build has never heard of (#3136)', () => {// The acceptance criterion for the epic: a user-defined track renders with no// client change at all, because every track-specific string and count is readdiff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex 8168dff894..6f477632f0 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -10,6 +10,7 @@ import {import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';import Banner from '../ui/Banner.jsx';import CycleTarget from './CycleTarget.jsx';+import AnimationProviderPicker from './AnimationProviderPicker.jsx';import { CorrectionNoteToggle, walkCorrectionKey } from './CorrectionNote.jsx';import SpritePreview from './SpritePreview.jsx';import { useAsyncAction } from '../../hooks/useAsyncAction.js';@@ -529,6 +530,7 @@ function DirectionCard({export default function WalkWorkflow({record, reference, walk, renders, duration, onDurationChange, onGenerate,onOpenTrimmer = () => {}, onChanged, corrections = null, onCorrectionChange = null,+ providers = null, provider = 'grok', onProviderChange = () => {},}) {const recordId = record.id;// The cycle target is server-resolved (app contract → set pin → first approved@@ -733,7 +735,16 @@ export default function WalkWorkflow({onChanged={onChanged}onSavingChange={setTargetSaving}/>- <label className="flex items-center gap-1.5 text-xs text-gray-400" htmlFor={`walk-clip-${recordId}`} title="grok renders 6s or 10s clips — these are the only lengths it offers, and a shorter request comes back as 6s. Length only affects how much source footage the packer has to choose from, not the walk's speed.">+ <AnimationProviderPicker+ id={`walk-provider-${recordId}`}+ providers={providers}+ provider={provider}+ onChange={onProviderChange}+ disabled={finalized}+ />+ <label className="flex items-center gap-1.5 text-xs text-gray-400" htmlFor={`walk-clip-${recordId}`} title={provider === 'local'+ ? "The local model renders on a fixed frame grid, so this length is snapped to the nearest legal clip. Length only affects how much source footage the packer has to choose from, not the walk's speed."+ : "grok renders 6s or 10s clips — these are the only lengths it offers, and a shorter request comes back as 6s. Length only affects how much source footage the packer has to choose from, not the walk's speed."}>Clip<selectid={`walk-clip-${recordId}`}diff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsxindex 79e482b1cd..96d703aa3e 100644--- a/client/src/components/sprites/WalkWorkflow.test.jsx+++ b/client/src/components/sprites/WalkWorkflow.test.jsx@@ -209,6 +209,61 @@ describe('WalkWorkflow loop preview', () => {});});+describe('WalkWorkflow render-lane picker (#4876)', () => {+ const renderPanel = (props = {}) => render(+ <MemoryRouter>+ <WalkWorkflow+ record={{ id: 'example-walker' }}+ reference={{+ manifest: {+ mainReference: { locked: true },+ anchors: [{ direction: 'east', status: 'locked', path: 'reference/example-walker-east-v1.png' }],+ },+ }}+ walk={{ runs: [], selection: { directions: {} }, walkSet: null }}+ renders={noRenders()}+ duration={6}+ onDurationChange={vi.fn()}+ onGenerate={vi.fn()}+ onChanged={vi.fn()}+ {...props}+ />+ </MemoryRouter>,+ );++ const PROVIDERS = [+ { id: 'grok', label: 'Grok (cloud)', ready: true, reason: null },+ { id: 'local', label: 'Local (MiniMax H3)', ready: true, reason: null },+ ];++ it('offers the lane picker beside the clip length once both lanes are known', () => {+ renderPanel({ providers: PROVIDERS, provider: 'grok', onProviderChange: vi.fn() });+ expect(screen.getByLabelText(/Render on/)).toBeInTheDocument();+ expect(screen.getByLabelText(/^Clip/)).toBeInTheDocument();+ });++ it('shows no picker on an install that never learned about a second lane', () => {+ // Default props — an older page build, or a readiness probe that failed.+ renderPanel();+ expect(screen.queryByLabelText(/Render on/)).toBeNull();+ });++ it('hands the chosen lane back to the page', () => {+ const onProviderChange = vi.fn();+ renderPanel({ providers: PROVIDERS, provider: 'grok', onProviderChange });+ fireEvent.change(screen.getByLabelText(/Render on/), { target: { value: 'local' } });+ expect(onProviderChange).toHaveBeenCalledWith('local');+ });++ it('describes the clip length in LOCAL terms when the local lane is selected', () => {+ // The grok copy names 6s/10s clips, which is not what H3 renders.+ renderPanel({ providers: PROVIDERS, provider: 'local', onProviderChange: vi.fn() });+ expect(screen.getByLabelText(/^Clip/).closest('label')).toHaveAttribute(+ 'title', expect.stringContaining('fixed frame grid'),+ );+ });+});+describe('WalkWorkflow idle anchor preview', () => {it('shows the locked directional anchor until the direction has a packaged animation', () => {render(diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex dae1fd162a..04c9710db9 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -6,6 +6,7 @@ import toast from '../components/ui/Toast';import {listSpriteRecords, getSpriteRecord,generateSpriteWalk, generateSpriteTrack, generateSpriteReference, listSpriteThumbnails,+ listSpriteAnimationProviders,} from '../services/apiSprites.js';import { getSettings } from '../services/apiSystem.js';import { deriveAvailableBackends, renderPinLadder } from '../lib/imageGenBackends.js';@@ -200,6 +201,24 @@ export default function Sprites() {// is no longer showing.const [duration, setDuration] = useState(GROK_VIDEO_DEFAULT_DURATION);+ // WHICH engine renders the clip (#4876) — the cloud grok lane or the local+ // MiniMax H3 one. Page state for the same reason `duration` is: a Regenerate+ // fired from an asset card must use the lane the user picked in the walk+ // panel, not a second copy that drifted from it.+ //+ // `null` = not fetched yet, `[]` = fetched and this install offers none —+ // distinct on purpose, so a failed fetch never renders as "grok is gone".+ // The selection stays on the server's own default until the list arrives,+ // which keeps the pre-#4876 behavior for the first paint and for any install+ // whose readiness probe fails.+ const [animationProviders, setAnimationProviders] = useState(null);+ const [animationProvider, setAnimationProvider] = useState('grok');+ useEffect(() => {+ listSpriteAnimationProviders({ silent: true })+ .then((res) => setAnimationProviders(Array.isArray(res?.providers) ? res.providers : []))+ .catch(() => setAnimationProviders([]));+ }, []);+// Image-backend availability + the selected backend `mode` are page-owned// (#2938): both ReferenceWorkflow's picker and the asset collection's anchor// Regenerate must read ONE mode, or a card re-roll would use a different@@ -303,6 +322,7 @@ export default function Sprites() {() => generateSpriteWalk(id, {direction,duration,+ provider: animationProvider,...correctionPromptPayload(corrections, walkCorrectionKey(direction)),}, { silent: true }),`Failed to queue ${direction} walk`,@@ -311,7 +331,7 @@ export default function Sprites() {// button briefly re-enables and a second click would 409 the in-flight// render. The server guard is the real backstop; this closes the UI gap.onWorkflowChanged,- ), [id, duration, corrections, walkBegin, walkResolve, walkCancel, submitRender, onWorkflowChanged]);+ ), [id, duration, animationProvider, corrections, walkBegin, walkResolve, walkCancel, submitRender, onWorkflowChanged]);// ONE submit path for every non-walk track (#3136) — the track id is a// parameter, so a user-defined track needs no new handler here.@@ -332,13 +352,14 @@ export default function Sprites() {try {await generateSpriteTrack(id, trackId, {...(direction ? { direction } : {}),+ provider: animationProvider,...correctionPromptPayload(corrections, correctionKey),}, { silent: true });onWorkflowChanged();} catch (err) {toast.error(err?.message || `Failed to queue the ${trackId} render`);}- }, [id, corrections, onWorkflowChanged]);+ }, [id, animationProvider, corrections, onWorkflowChanged]);// The ambient main takes BOTH inputs: `designPrompt` replaces the design// outright, while the correction (#3134) keeps it and fixes one thing about@@ -370,8 +391,14 @@ export default function Sprites() {onChanged={onWorkflowChanged}corrections={corrections}onCorrectionChange={setCorrections}+ providers={animationProviders}+ provider={animationProvider}+ onProviderChange={setAnimationProvider}/>- )), [detail?.tracks, detail?.record, detail?.reference, generateTrack, onWorkflowChanged, corrections]);+ )), [+ detail?.tracks, detail?.record, detail?.reference, generateTrack, onWorkflowChanged, corrections,+ animationProviders, animationProvider,+ ]);// `mode` is the workflow-selected backend, threaded from the asset card via@@ -540,6 +567,9 @@ export default function Sprites() {renders={walkRenders}duration={duration}onDurationChange={setDuration}+ providers={animationProviders}+ provider={animationProvider}+ onProviderChange={setAnimationProvider}onGenerate={generateWalk}onOpenTrimmer={openTrimmer}onChanged={onWorkflowChanged}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex e032b7ebbd..42fabc8b4e 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -105,7 +105,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiFableLoom.js` | FableLoom branching narratives — loom/episode/scene-node/transition CRUD, deterministic graph validation, and the AI lanes (weave, branch, review, play turns, per-episode scene reformat). || `apiGames.js` | Game studio records, managed-app binding, reusable sprite/music bindings, deterministic asset-bundle compilation/integrity preflight, and AI feedback history. || `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), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980). |+| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980), and animation render-provider readiness (#4876). || `apiShell.js` | Shell sessions over HTTP: hand a photo (plus a message) to the agent TUI running in a session. Keystrokes/output stay on the `shell:*` socket protocol. || `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, deletion, and the subject-family checklist options. || `apiImageTo3d.js` | Image-to-3D (`/3d`): selectable targets (TRELLIS.2) with host availability/install status, and per-image model records — create/list/get/generate/delete + GLB asset URL and the full-resolution OBJ download URL. |diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.jsindex 5aa88d0440..cba5ec617c 100644--- a/client/src/services/apiSprites.js+++ b/client/src/services/apiSprites.js@@ -165,6 +165,14 @@ export const reopenSpriteTrack = (id, trackId, body = {}, options = {}) => reque// they all pass `{ silent: true }`.export const listSpriteAnimationTracks = (options = {}) => request('/sprites/animation-tracks', options);+// Which engines can render an animation clip on THIS install (#4876) —+// `{ providers: [{ id, label, ready, reason, … }] }`. `ready: false` always+// carries a `reason` naming the one thing to fix, which the workflow surfaces+// beside the disabled option rather than making the user discover it by+// clicking Generate and reading a 409.+export const listSpriteAnimationProviders = (options = {}) => request('/sprites/animation-providers', options);++export const createSpriteAnimationTrack = (body, options = {}) => request('/sprites/animation-tracks', {method: 'POST', body: JSON.stringify(body), ...options,});diff --git a/server/lib/spriteValidation.js b/server/lib/spriteValidation.jsindex cd4fd5e989..25cac8734a 100644--- a/server/lib/spriteValidation.js+++ b/server/lib/spriteValidation.js@@ -2,6 +2,7 @@ import { z } from 'zod';import { SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS } from '../services/sprites/recordsLogic.js';import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS, TURNAROUND_ID } from '../services/sprites/prompts.js';import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';+import { ANIMATION_PROVIDER_IDS } from '../services/sprites/animationWorkflow.js';import {WALK_TRACK, AUTHORED_TRACK_FIELDS, TRACK_BOUND_TRIPLES,} from '../services/sprites/animationTracks.js';@@ -299,6 +300,11 @@ const spriteWalkFpsSchema = spriteTrackFpsSchema(WALK_TRACK);export const spriteWalkGenerateSchema = z.object({direction: spriteWalkDirectionSchema,+ // WHICH engine renders the source clip (#4876): the cloud grok lane or the+ // local MiniMax H3 one. Omitted → grok, so an older client and every persisted+ // retry render exactly where they did before the local lane existed.+ provider: z.enum(ANIMATION_PROVIDER_IDS).optional(),+// Clip length in seconds; the service defaults to 6s when omitted. Only// affects how much source footage the packer can choose from — the cycle's// look is set by frameCount/fps below.@@ -330,6 +336,11 @@ export const spriteWalkGenerateSchema = z.object({// - the remaining knobs are already registry-derived.const buildSpriteTrackGenerateSchema = (track) => z.object({direction: spriteWalkDirectionSchema.optional(),+ // WHICH engine renders the source clip (#4876): the cloud grok lane or the+ // local MiniMax H3 one. Omitted → grok, so an older client and every persisted+ // retry render exactly where they did before the local lane existed.+ provider: z.enum(ANIMATION_PROVIDER_IDS).optional(),+duration: grokVideoDurationSchema.optional(),frameCount: spriteTrackFrameCountSchema(track).optional(),fps: spriteTrackFpsSchema(track).optional(),diff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex fa6a6568d6..b7d59fb075 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -54,6 +54,7 @@ import {listReferenceSources, listSpriteThumbnails, forkSprite,} from '../services/sprites/reference.js';import { resolveSpriteAssetPrompt } from '../services/sprites/assetPrompt.js';+import { listAnimationProviders } from '../services/sprites/localAnimationRender.js';import {WALK_TRACK,isAnimationTrack, kindSupportsTrack, tracksForKind,@@ -199,6 +200,19 @@ router.delete('/animation-tracks/:trackId', asyncHandler(async (req, res) => {res.json(await deleteAnimationTrack(trackId));}));+// Which engines can render an animation clip on THIS install, and why one+// cannot (#4876). Must precede `GET /:id` for the same reason the block above+// does — a literal first segment would otherwise be captured as a record id.+//+// Read-only readiness: it probes an already-installed venv and the local HF+// cache, and starts no render, so it does not touch the user-triggered+// AI-provider gate. The client shows the reason beside a disabled option, which+// is what turns "why is Local greyed out?" into an answer in place rather than a+// 409 after a click.+router.get('/animation-providers', asyncHandler(async (_req, res) => {+ res.json({ providers: await listAnimationProviders() });+}));+// Create a character record — the entry point of the reference workflow.// Id derivation and the kind live in the service (createCharacter).router.post('/', asyncHandler(async (req, res) => {diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.jsindex b08bbddf21..8e0bdb47f7 100644--- a/server/routes/sprites.test.js+++ b/server/routes/sprites.test.js@@ -23,6 +23,13 @@ vi.mock('../services/sprites/reference.js', () => ({forkSprite: vi.fn(async (sourceId, body) => ({ record: { id: 'pioneer-fork', kind: 'character', name: body.name }, jobId: 'j1', mode: 'codex', target: 'main', anchorId: 'walk-south' })),}));+vi.mock('../services/sprites/localAnimationRender.js', () => ({+ listAnimationProviders: vi.fn(async () => [+ { id: 'grok', label: 'Grok (cloud)', ready: true, reason: null },+ { id: 'local', label: 'Local (MiniMax H3)', ready: true, reason: null },+ ]),+}));+vi.mock('../services/sprites/assetPrompt.js', () => ({resolveSpriteAssetPrompt: vi.fn(async () => ({ prompt: 'the built prompt', designPrompt: 'a knight', source: 'candidate' })),}));@@ -115,6 +122,7 @@ vi.mock('../services/sprites/assets.js', () => ({import * as records from '../services/sprites/records.js';import * as importer from '../services/sprites/importer.js';import * as reference from '../services/sprites/reference.js';+import * as localAnimationRender from '../services/sprites/localAnimationRender.js';import * as assetPrompt from '../services/sprites/assetPrompt.js';import * as walk from '../services/sprites/walk.js';import * as trackWorkflow from '../services/sprites/animationTrackWorkflow.js';@@ -773,6 +781,46 @@ describe('sprites routes', () => {});});+ it('GET /animation-providers reports each lane and why one is unusable', async () => {+ localAnimationRender.listAnimationProviders.mockResolvedValueOnce([+ { id: 'grok', label: 'Grok (cloud)', ready: true, reason: null },+ { id: 'local', label: 'Local (MiniMax H3)', ready: false, reason: 'The MiniMax H3 MLX runtime is not installed — install it from Video Gen, then reload.' },+ ]);+ const r = await request(app).get('/api/sprites/animation-providers');+ expect(r.status).toBe(200);+ expect(r.body.providers.map((p) => p.id)).toEqual(['grok', 'local']);+ expect(r.body.providers[1].reason).toMatch(/not installed/);+ });++ it('GET /animation-providers is not captured as a record id by GET /:id', async () => {+ // The literal-segment routes must precede `GET /:id`; without that ordering+ // this would 404 (or worse, look up a record named "animation-providers").+ await request(app).get('/api/sprites/animation-providers');+ expect(records.getRecordWithAssets).not.toHaveBeenCalled();+ });++ it('POST /:id/walk/generate forwards a valid provider and rejects an unknown one', async () => {+ const ok = await request(app).post('/api/sprites/pioneer/walk/generate')+ .send({ direction: 'east', provider: 'local' });+ expect(ok.status).toBe(200);+ expect(walk.startWalkGeneration).toHaveBeenCalledWith('pioneer', { direction: 'east', provider: 'local' });+ const bad = await request(app).post('/api/sprites/pioneer/walk/generate')+ .send({ direction: 'east', provider: 'minimax' });+ expect(bad.status).toBe(400);+ });++ it('POST /:id/tracks/:trackId/generate forwards a valid provider and rejects an unknown one', async () => {+ const ok = await request(app).post('/api/sprites/pioneer/tracks/scanner/generate')+ .send({ direction: 'east', provider: 'local' });+ expect(ok.status).toBe(200);+ expect(trackWorkflow.startTrackGeneration).toHaveBeenCalledWith(+ 'scanner', 'pioneer', { direction: 'east', provider: 'local' },+ );+ const bad = await request(app).post('/api/sprites/pioneer/tracks/scanner/generate')+ .send({ direction: 'east', provider: 'minimax' });+ expect(bad.status).toBe(400);+ });+it('POST /:id/walk/generate validates direction and duration', async () => {const r = await request(app).post('/api/sprites/pioneer/walk/generate').send({ direction: 'east', duration: 10 });diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.jsindex 771cf683a3..710ef78b89 100644--- a/server/services/sprites/animationTrackWorkflow.js+++ b/server/services/sprites/animationTrackWorkflow.js@@ -45,6 +45,10 @@ import { ServerError } from '../../lib/errorHandler.js';import { executeTuiRun } from '../../lib/tuiPromptRunner.js';import { GROK_TUI_ID } from '../../lib/grok.js';import { resolveGrokDuration } from '../../lib/grokVideoClip.js';+import {+ planLocalAnimationRender, enqueueLocalAnimationRender, collectLocalAnimationRender,+ localRenderManifest,+} from './localAnimationRender.js';import { getSettings } from '../settings.js';import { getRecord, listRecords } from './records.js';import { requireTrack, loadManifest } from './reference.js';@@ -62,6 +66,7 @@ import { verifyPackagedFrames } from './walkFrames.js';import {resolveChromaKey, withAnimationWriteTail, lockedAnchorFor, lockedMainFor,GROK_TUI_IDLE_MS, GROK_TUI_TIMEOUT_MS, grokTuiProvider, buildGrokI2vTask,+ resolveAnimationProvider, isLocalProviderRun,} from './animationWorkflow.js';const RUN_RECORD_NAME = 'animation-run.json';@@ -277,6 +282,15 @@ async function startTrackGenerationImpl(trackId, recordId, body) {// Optional re-roll note (#3134) — blank leaves the prompt and the run record// exactly as a blind regenerate would.const correctionPrompt = typeof body.correctionPrompt === 'string' ? body.correctionPrompt.trim() : '';+ // WHICH lane renders the clip (#4876) — same contract the walk lane uses, so a+ // track never needs its own provider rules. Absent → grok.+ const provider = resolveAnimationProvider(body.provider);+ const duration = resolveGrokDuration(body.duration);+ // Readiness first: an install with no runnable local model 409s here, before a+ // run record exists.+ const localPlan = provider === 'local'+ ? await planLocalAnimationRender({ durationSeconds: duration })+ : null;// Run ids stay in the clones' shapes: `<track>-<direction>-<uuid8>` for a// directional track, `<track>-<uuid8>` for a single-row one.const runId = row.directional@@ -293,11 +307,21 @@ async function startTrackGenerationImpl(trackId, recordId, body) {);}const inputAbs = join(generatedAbs, source.inputName);- const [{ preparation, sha256: inputSha256 }, settings] = await Promise.all([- prepareWalkAnchorChromaInput(sourceAbs, inputAbs, chromaKey), getSettings(),+ const [{ preparation, sha256: inputSha256, canvas }, settings] = await Promise.all([+ prepareWalkAnchorChromaInput(sourceAbs, inputAbs, chromaKey, localPlan?.chooseCanvas || null),+ getSettings(),]);- const duration = resolveGrokDuration(body.duration);const videoAbs = join(generatedAbs, SOURCE_CLIP_NAME);+ const prompt = buildTrackVideoPrompt(row.id, {+ name: record.name, kind: record.kind, direction, chromaKey, correctionPrompt,+ });+ // Stamped on the run record BEFORE anything awaits the job — see the walk+ // lane's note: a local run with no `jobId` can never be told from a dead one.+ const jobId = localPlan+ ? enqueueLocalAnimationRender({+ plan: localPlan, canvas, prompt, inputAbs, owner: `sprite-${row.id}:${recordId}:${direction}`,+ })+ : null;const run = {schemaVersion: 1,kind: 'grok-game-animation-frames-run',@@ -322,27 +346,33 @@ async function startTrackGenerationImpl(trackId, recordId, body) {animationInputPreparation: preparation,...(correctionPrompt ? { correctionPrompt } : {}),createdAt: new Date().toISOString(),+ // Spread LAST so the local lane's provider/geometry provenance wins over the+ // grok defaults above. A local render is a queued media job, not a PTY, so it+ // carries `jobId` in place of an attachable `shellSession`.+ ...(localPlan ? { ...localRenderManifest(localPlan, canvas), jobId, shellSession: null } : {}),};await saveRun(recordId, run);+ if (localPlan) {+ collectLocalAnimationRender({ jobId, videoAbs, label: `sprite ${row.id} ${recordId}/${direction}` })+ .then(() => withAnimationWriteTail(recordId, () => attachTrackTuiResult(row.id, recordId, runId, videoAbs)))+ .catch((err) => console.error(`❌ sprite ${row.id} local render crashed ${recordId}/${runId}: ${err?.message || err}`));+ console.log(`📡 sprite ${row.id} local render started ${recordId}/${runId} (job ${jobId.slice(0, 8)}, ${localPlan.numFrames}f @ ${localPlan.fps}fps)`);+ return row.directional+ ? { runId, direction, duration, provider: 'local', jobId }+ : { runId, duration, provider: 'local', jobId };+ }runTrackTuiRender(row, recordId, {runId,direction,generatedAbs,videoAbs,grokPath: settings.imageGen?.grok?.grokPath,- task: buildGrokI2vTask({- prompt: buildTrackVideoPrompt(row.id, {- name: record.name, kind: record.kind, direction, chromaKey, correctionPrompt,- }),- inputAbs,- videoAbs,- duration,- }),+ task: buildGrokI2vTask({ prompt, inputAbs, videoAbs, duration }),}).catch((err) => console.error(`❌ sprite ${row.id} grok-tui render crashed ${recordId}/${runId}: ${err?.message || err}`));console.log(`📡 sprite ${row.id} grok-tui render started ${recordId}/${runId}`);return row.directional- ? { runId, direction, duration, shellSession: runId }- : { runId, duration, shellSession: runId };+ ? { runId, direction, duration, provider: 'grok', shellSession: runId }+ : { runId, duration, provider: 'grok', shellSession: runId };}async function runTrackTuiRender(row, recordId, { runId, direction, generatedAbs, videoAbs, grokPath, task }) {@@ -366,7 +396,9 @@ export async function attachTrackTuiResult(trackId, recordId, runId, videoAbs) {if (selection?.directions?.[run.direction]?.runId === runId) return;if (!await pathExists(videoAbs)) {run.status = 'error';- run.postprocessError = `Grok finished without writing the ${row.label.toLowerCase()} video — check the shell session output`;+ run.postprocessError = isLocalProviderRun(run)+ ? `The local render produced no ${row.label.toLowerCase()} video — check the Render Queue for the failed job`+ : `Grok finished without writing the ${row.label.toLowerCase()} video — check the shell session output`;run.completedAt = new Date().toISOString();await saveRun(recordId, run);return;diff --git a/server/services/sprites/animationTrackWorkflow.test.js b/server/services/sprites/animationTrackWorkflow.test.jsindex 6af9bf5e93..d3733a500e 100644--- a/server/services/sprites/animationTrackWorkflow.test.js+++ b/server/services/sprites/animationTrackWorkflow.test.js@@ -44,13 +44,17 @@ vi.mock('../settings.js', () => ({getSettings: async () => ({ imageGen: { grok: { grokPath: '/usr/local/bin/grok' } } }),}));-const prepareWalkAnchorChromaInput = vi.fn(async (_sourceAbs, inputAbs) => {+// Reports a fixed PORTRAIT anchor size so the local lane's REAL canvas chooser+// is exercised — only the sharp measurement is stubbed.+const STUB_ANCHOR_SIZE = { width: 512, height: 896 };+const prepareWalkAnchorChromaInput = vi.fn(async (_sourceAbs, inputAbs, _chromaKey, chooseCanvas = null) => {await mkdir(join(inputAbs, '..'), { recursive: true });const bytes = Buffer.from('track-chroma-input');await writeFile(inputAbs, bytes);return {preparation: 'composited-over-solid-chroma-matte',sha256: createHash('sha256').update(bytes).digest('hex'),+ canvas: chooseCanvas ? chooseCanvas(STUB_ANCHOR_SIZE) : null,};});vi.mock('./walkPostprocess.js', async (importOriginal) => ({@@ -58,6 +62,51 @@ vi.mock('./walkPostprocess.js', async (importOriginal) => ({prepareWalkAnchorChromaInput: (...args) => prepareWalkAnchorChromaInput(...args),}));+// ── Local render lane (#4876) ───────────────────────────────────────────────+// Only the ENVIRONMENT is stubbed (model catalog, runtime/weight probes, job+// queue) so the real lane logic runs through the workflow — see the same note in+// walk.test.js. The point of running the table over BOTH tracks is that the+// provider is registry-agnostic: a directional and a non-directional row must+// dispatch identically, with no `if (track === …)` anywhere in the lane.+const H3_MODEL = {+ id: 'minimax_h3_8bit',+ name: 'MiniMax H3 MLX 8-bit',+ repo: 'pipenetwork/MiniMax-H3-MLX-8bit',+ revision: 'rev-abc',+ runtime: 'minimax_h3',+ defaultFrames: 124,+ frameOptions: [107, 124, 141, 158, 175],+ fpsOptions: [24],+ defaultWidth: 1344,+ defaultHeight: 768,+ resolutionOptions: [{ w: 1344, h: 768 }, { w: 768, h: 768 }, { w: 768, h: 1024 }],+};+let localRuntimeReady = true;+vi.mock('../../lib/mediaModels.js', async (importOriginal) => ({+ ...await importOriginal(),+ getVideoModels: () => [H3_MODEL],+}));+vi.mock('../videoGen/runtimes.js', async (importOriginal) => ({+ ...await importOriginal(),+ BYOV_RUNTIME_INFO: { minimax_h3: { label: 'MiniMax H3 MLX' } },+ isByovRuntimeReady: async () => localRuntimeReady,+}));+vi.mock('../../lib/hfCache.js', async (importOriginal) => ({+ ...await importOriginal(),+ inspectModelCache: async () => ({ cached: true, sizeBytes: 1, snapshotPath: '/snap' }),+ findCachedRepoFiles: async () => ['/snap/a.safetensors'],+}));+const enqueuedVideoJobs = [];+vi.mock('../mediaJobQueue/index.js', async (importOriginal) => ({+ ...await importOriginal(),+ enqueueJob: (job) => {+ const id = `mjob-${enqueuedVideoJobs.length + 1}`;+ enqueuedVideoJobs.push({ id, ...job });+ return { jobId: id, position: 1, status: 'queued' };+ },+ getJob: (id) => ({ id, status: 'running' }),+}));+const records = await import('./records.js');const { lockReference } = await import('./reference.js');const {@@ -290,6 +339,76 @@ describe.each(TRACKS)('the generic workflow drives the $id track', (track) => {});});+describe('local render lane (#4876)', () => {+ beforeEach(() => {+ localRuntimeReady = true;+ enqueuedVideoJobs.length = 0;+ });++ it.each(TRACKS)('$id defaults to the grok TUI when no provider is named', async (track) => {+ const id = await track.seed(newId());+ const res = await startTrackGeneration(track.id, id, track.body);+ expect(res.provider).toBe('grok');+ expect(res.shellSession).toBe(res.runId);+ expect(executeTuiRun).toHaveBeenCalledTimes(1);+ expect(enqueuedVideoJobs).toHaveLength(0);+ });++ it.each(TRACKS)('$id queues a local media job instead, carrying its OWN prompt', async (track) => {+ const id = await track.seed(newId());+ const res = await startTrackGeneration(track.id, id, { ...track.body, provider: 'local' });+ expect(executeTuiRun).not.toHaveBeenCalled();+ expect(res.provider).toBe('local');+ expect(res.jobId).toBe('mjob-1');+ expect(res.shellSession).toBeUndefined();+ expect(enqueuedVideoJobs).toHaveLength(1);+ expect(enqueuedVideoJobs[0]).toMatchObject({ kind: 'video' });+ expect(enqueuedVideoJobs[0].params).toMatchObject({+ modelId: 'minimax_h3_8bit', mode: 'image', fps: 24, hidden: true,+ });+ // The track's own prompt, not the walk's or the sibling track's.+ expect(enqueuedVideoJobs[0].params.prompt).toContain(track.promptMarker);+ // Portrait anchor → portrait canvas, so videoGen's center-crop is a no-op.+ expect(enqueuedVideoJobs[0].params).toMatchObject({ width: 768, height: 1024 });+ });++ it.each(TRACKS)('$id stamps the lane provenance on its run record', async (track) => {+ const id = await track.seed(newId());+ const { runId } = await startTrackGeneration(track.id, id, { ...track.body, provider: 'local' });+ const run = (await getTrackState(track.id, id)).runs.find((r) => r.id === runId);+ expect(run).toMatchObject({+ provider: 'minimax-h3-local',+ videoModelId: 'minimax_h3_8bit',+ videoRuntime: 'minimax_h3',+ renderFps: 24,+ jobId: 'mjob-1',+ track: track.id,+ status: 'rendering',+ });+ expect(run.shellSession).toBeNull();+ // The track's own registry-derived packing knobs are untouched by the render.+ expect(run.frameCount).toBe(EFFECTIVE[track.id].defaultFrameCount);+ expect(run.fps).toBe(EFFECTIVE[track.id].defaultFps);+ });++ it.each(TRACKS)('$id 409s without creating a run directory when the runtime is missing', async (track) => {+ const id = await track.seed(newId());+ localRuntimeReady = false;+ await expect(startTrackGeneration(track.id, id, { ...track.body, provider: 'local' }))+ .rejects.toMatchObject({ status: 409, code: 'LOCAL_VIDEO_PROVIDER_NOT_READY' });+ expect((await getTrackState(track.id, id)).runs).toEqual([]);+ expect(enqueuedVideoJobs).toHaveLength(0);+ });++ it.each(TRACKS)('$id refuses an unknown provider rather than falling back to the paid lane', async (track) => {+ const id = await track.seed(newId());+ await expect(startTrackGeneration(track.id, id, { ...track.body, provider: 'minimax' }))+ .rejects.toMatchObject({ status: 400, code: 'ANIMATION_PROVIDER_INVALID' });+ expect(executeTuiRun).not.toHaveBeenCalled();+ expect(enqueuedVideoJobs).toHaveLength(0);+ });+});+describe('registry-derived authoring shape (#3136)', () => {it('authors a directional track across every facing and a non-directional one across row 0 only', () => {// The rule the two clones each hardcoded — `SPRITE_DIRECTIONS.every(...)` indiff --git a/server/services/sprites/animationWorkflow.js b/server/services/sprites/animationWorkflow.jsindex 37b455b72a..056f636fcc 100644--- a/server/services/sprites/animationWorkflow.js+++ b/server/services/sprites/animationWorkflow.js@@ -1,6 +1,7 @@/*** Shared animation-render plumbing: per-record write serialization, chroma-key- * precedence, the grok-TUI invocation, and the i2v task wrapper.+ * precedence, the grok-TUI invocation, the i2v task wrapper, and the render-lane+ * vocabulary both lanes and the request schemas share (#4876).** Everything here is a fact about "how PortOS renders a sprite animation" rather* than about any one track, so both animation services (`walk.js`'s bespoke@@ -11,6 +12,7 @@import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';import { GROK_TUI_ID } from '../../lib/grok.js';+import { ServerError } from '../../lib/errorHandler.js';const animationWriteTail = createKeyCachedQueue();@@ -79,3 +81,49 @@ export const buildGrokI2vTask = ({ prompt, inputAbs, videoAbs, duration }) => (+ `Save the resulting animation as an MP4 file at exactly this path:\n${videoAbs}\n\n`+ 'Do not create or modify any other files, and do not run any tools beyond what is needed to render and save that MP4.');++// ── Render lanes ────────────────────────────────────────────────────────────+// Which engine produces a track's source clip. Grok's observable TUI session was+// the only answer until #4876 added the local MiniMax H3 lane; the pipeline+// downstream of the MP4 is identical either way, so the choice is a request+// field and a run-record field, never a second pipeline.+//+// These four live HERE rather than beside the local lane's implementation+// because `lib/spriteValidation.js` needs the id list to build its request+// enum, and this module is dependency-light by design — importing the local+// lane (which reaches the media-job queue and the model catalog) into the+// validation layer would drag both into every route's import graph.++/** The run record's `provider` for a locally-rendered clip. */+export const LOCAL_VIDEO_PROVIDER_ID = 'minimax-h3-local';++/** The provider ids a generate REQUEST may carry. */+export const ANIMATION_PROVIDER_IDS = Object.freeze(['grok', 'local']);++/**+ * Absent → grok, so every pre-existing client, persisted retry, and test+ * renders exactly where it did before the local lane existed.+ */+export const DEFAULT_ANIMATION_PROVIDER = 'grok';++/**+ * Normalize a request's `provider` to one of ANIMATION_PROVIDER_IDS.+ *+ * An unknown value is REFUSED rather than silently defaulted: a typo'd provider+ * quietly rendering on the paid cloud lane is the one outcome nobody wants. The+ * Zod enum already rejects it at the route, so this is the service-level+ * backstop for a direct or internal caller.+ */+export const resolveAnimationProvider = (value) => {+ if (value === undefined || value === null || value === '') return DEFAULT_ANIMATION_PROVIDER;+ if (!ANIMATION_PROVIDER_IDS.includes(value)) {+ throw new ServerError(+ `Unknown animation provider "${value}" — expected one of ${ANIMATION_PROVIDER_IDS.join(', ')}`,+ { status: 400, code: 'ANIMATION_PROVIDER_INVALID' },+ );+ }+ return value;+};++/** Whether a run record was produced by the local lane. */+export const isLocalProviderRun = (run) => run?.provider === LOCAL_VIDEO_PROVIDER_ID;diff --git a/server/services/sprites/localAnimationRender.js b/server/services/sprites/localAnimationRender.jsnew file mode 100644index 0000000000..dea73993b5--- /dev/null+++ b/server/services/sprites/localAnimationRender.js@@ -0,0 +1,394 @@+/**+ * Sprites — the LOCAL (MiniMax H3) animation-render lane.+ *+ * Every sprite animation track used to have exactly one way to produce its+ * source clip: an observable grok TUI session (`animationWorkflow.js`). That is+ * a paid cloud call, which made the whole sprite pipeline unusable offline even+ * though PortOS already ships MiniMax H3 locally — the MLX port on Apple Silicon+ * and the diffusers/CUDA runtime on Windows and Linux (`videoGen/runtimes.js`).+ *+ * This module is the second lane. It is deliberately NOT a second copy of the+ * pipeline: everything downstream of the clip — chroma recovery, frame+ * selection, loop trimming, geometry QC, approval, atlas compile — is the same+ * deterministic postprocess both lanes hand a `source-video.mp4` to. All that+ * differs is who renders that MP4, so the only things here are:+ *+ * - which local model this platform can render on, and whether it is ready;+ * - how a sprite's authoring knobs (a clip length in seconds, an anchor of+ * arbitrary aspect) map onto H3's fixed contract (a 17n+5 frame grid at a+ * locked 24 fps, on one of six trained canvases);+ * - queueing one render through `mediaJobQueue` and putting the finished clip+ * where the postprocess expects it.+ *+ * Unlike the grok lane this is NOT a PTY session, so a local run has no+ * attachable Shell session. It carries a `jobId` instead, which is both what the+ * Render Queue UI shows and — via `localRunLiveness` — how a read path tells a+ * genuinely-live multi-hour render from one the server died in the middle of.+ */++import { join } from 'path';+import { copyFile } from 'fs/promises';+import { PATHS, pathExists } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { getVideoModels } from '../../lib/mediaModels.js';+import { inspectModelCache, findCachedRepoFiles } from '../../lib/hfCache.js';+import { BYOV_RUNTIME_INFO, isByovRuntimeReady } from '../videoGen/runtimes.js';+import { enqueueJob, getJob, mediaJobEvents } from '../mediaJobQueue/index.js';+import { LOCAL_VIDEO_PROVIDER_ID } from './animationWorkflow.js';++// H3's video VAE decodes only 17n+5 frame counts and the model runs at a fixed+// 24 fps (both enforced by `videoGen/minimaxH3Controls.js`), so a sprite's+// requested clip length can only ever be honoured approximately. 24 is read+// from the model row when it declares one so a future re-profile moves both.+const H3_FALLBACK_FPS = 24;++// Both H3 runtimes PortOS ships. A platform exposes exactly one of them+// (`getVideoModels()` already selects the mlx or cuda bucket), so this set is+// what identifies "an H3 row" inside whichever bucket is active rather than a+// platform test of its own — which is what keeps this lane working on Linux+// CUDA installs without a second branch.+const MINIMAX_H3_RUNTIME_IDS = Object.freeze(new Set(['minimax_h3', 'minimax_h3_cuda']));++/**+ * The MiniMax H3 model row this install can render on, or null.+ *+ * `getVideoModels()` has already filtered to the active platform bucket and+ * dropped anything flagged broken there, so an H3 row surviving that filter is+ * by definition the one this machine would use. Null is the honest answer for a+ * platform with no H3 build at all (and is reported as such rather than+ * collapsing into "not installed", which would send the user to an install+ * button that cannot help them).+ */+export const resolveLocalVideoModel = () => (+ getVideoModels().find((model) => MINIMAX_H3_RUNTIME_IDS.has(model.runtime)) || null+);++/** The render fps a model row is locked to (H3: 24). */+export const localRenderFps = (model) => {+ const declared = Array.isArray(model?.fpsOptions) ? Number(model.fpsOptions[0]) : NaN;+ return Number.isFinite(declared) && declared > 0 ? declared : H3_FALLBACK_FPS;+};++/**+ * The legal H3 frame count closest to `durationSeconds` of footage.+ *+ * The sprite lanes ask for a clip length in seconds because that is what grok+ * takes; H3 takes a frame count off a fixed grid. Snapping to the CLOSEST legal+ * option (rather than rounding up) matters because the grid is coarse — at 24+ * fps the MLX options step by ~0.7 s but the CUDA window starts at 124 frames,+ * so rounding a 6 s request up would cost a materially longer render for+ * footage the packer discards anyway.+ *+ * Ties go to the shorter option: two equally-close counts render for different+ * lengths of time and the cheaper one is never the wrong call for source+ * footage the postprocess is going to resample regardless.+ */+export const resolveLocalFrameCount = (model, durationSeconds) => {+ const options = (Array.isArray(model?.frameOptions) ? model.frameOptions : [])+ .map(Number)+ .filter((frames) => Number.isFinite(frames) && frames > 0)+ .sort((a, b) => a - b);+ const fallback = Number(model?.defaultFrames);+ if (!options.length) {+ return Number.isFinite(fallback) && fallback > 0 ? fallback : null;+ }+ const seconds = Number(durationSeconds);+ if (!Number.isFinite(seconds) || seconds <= 0) {+ return options.includes(fallback) ? fallback : options[0];+ }+ const target = seconds * localRenderFps(model);+ return options.reduce((best, frames) => (+ Math.abs(frames - target) < Math.abs(best - target) ? frames : best+ ), options[0]);+};++/**+ * The trained H3 canvas whose aspect ratio is closest to the anchor's.+ *+ * H3 renders only on the six canvases its row declares, and `generateVideo`+ * conforms a conditioning image to the chosen one with+ * `scale=increase,crop` — a CENTER CROP. Handing it a portrait sprite anchor on+ * H3's 16:9 default would therefore slice the character's head and feet off+ * before the render even starts, and the geometry QC would fail every run for a+ * reason invisible in the output. Picking the nearest-aspect canvas here (and+ * padding the input to it in `prepareWalkAnchorChromaInput`) makes that crop a+ * no-op instead.+ *+ * Ties go to the SMALLER canvas: equal aspect fidelity for less render time.+ */+export const pickLocalRenderCanvas = (model, { width, height } = {}) => {+ const presets = (Array.isArray(model?.resolutionOptions) ? model.resolutionOptions : [])+ .map((preset) => ({ width: Number(preset?.w), height: Number(preset?.h) }))+ .filter((preset) => (+ Number.isFinite(preset.width) && preset.width > 0+ && Number.isFinite(preset.height) && preset.height > 0+ ));+ const fallbackWidth = Number(model?.defaultWidth);+ const fallbackHeight = Number(model?.defaultHeight);+ const fallback = Number.isFinite(fallbackWidth) && fallbackWidth > 0+ && Number.isFinite(fallbackHeight) && fallbackHeight > 0+ ? { width: fallbackWidth, height: fallbackHeight }+ : null;+ if (!presets.length) return fallback;+ const w = Number(width);+ const h = Number(height);+ // No measurable anchor: the model's declared default is the honest choice —+ // guessing an aspect from nothing would be worse than the row's own answer.+ if (!Number.isFinite(w) || w <= 0 || !Number.isFinite(h) || h <= 0) {+ return fallback || presets[0];+ }+ const wanted = w / h;+ // Compared in LOG space so "twice as wide as wanted" and "half as wide" score+ // equally — a linear difference is asymmetric and biases every portrait+ // anchor toward the landscape presets.+ const distance = (preset) => Math.abs(Math.log((preset.width / preset.height) / wanted));+ return presets.reduce((best, preset) => {+ const delta = distance(preset) - distance(best);+ if (delta < 0) return preset;+ if (delta > 0) return best;+ return preset.width * preset.height < best.width * best.height ? preset : best;+ }, presets[0]);+};++/**+ * Whether every weight `model` needs is resolvable in the HF cache.+ *+ * Coarse ON PURPOSE relative to the render path's own preflight+ * (`assertMiniMaxH3Preflight`), which additionally verifies the pinned runtime+ * checkout is clean. Restating that contract here would be a second copy free to+ * drift; this answers the question the UI actually asks — "is there any point+ * offering the button?" — and a deeper failure still surfaces as a captured+ * error on the run record, naming the exact missing piece.+ */+const localModelWeightsCached = async (model) => {+ const [base, ...deps] = await Promise.all([+ inspectModelCache(model.repo, model.revision ? { revision: model.revision } : {}),+ ...(Array.isArray(model.requiredWeights) ? model.requiredWeights : []).map((dep) => (+ Array.isArray(dep?.files) && dep.files.length && dep.repo+ ? findCachedRepoFiles(dep.repo, dep.files, dep.revision ? { revision: dep.revision } : {})+ : Promise.resolve(null)+ )),+ ]);+ if (!base.cached) return false;+ // findCachedRepoFiles resolves to null when ANY pinned file is missing, so a+ // dependency that has no resolvable set is a hard no — but a model with no+ // requiredWeights at all (the CUDA row) never enters this loop.+ return deps.every((resolved) => Array.isArray(resolved) && resolved.length > 0);+};++/**+ * Readiness for the local lane, shaped for direct display.+ *+ * Always resolves — an unavailable lane is a `ready: false` plus a `reason`+ * naming the one thing to fix, never a throw. The client renders the reason+ * beside a disabled option, so "why can't I pick this?" is answered in place+ * rather than as a 409 after a click.+ */+export async function getLocalAnimationProviderStatus() {+ const model = resolveLocalVideoModel();+ if (!model) {+ return {+ id: 'local',+ label: 'Local (MiniMax H3)',+ ready: false,+ reason: 'This platform has no local MiniMax H3 video build — sprite animation renders on grok here.',+ };+ }+ const base = {+ id: 'local',+ label: 'Local (MiniMax H3)',+ modelId: model.id,+ modelName: model.name,+ runtime: model.runtime,+ fps: localRenderFps(model),+ };+ const runtimeLabel = BYOV_RUNTIME_INFO[model.runtime]?.label || model.runtime;+ if (!await isByovRuntimeReady(model.runtime)) {+ return {+ ...base,+ ready: false,+ reason: `The ${runtimeLabel} runtime is not installed — install it from Video Gen, then reload.`,+ };+ }+ if (!await localModelWeightsCached(model)) {+ return {+ ...base,+ ready: false,+ reason: `${model.name} is not downloaded — download it from Video Gen, then reload.`,+ };+ }+ return { ...base, ready: true, reason: null };+}++/**+ * Every animation provider the sprite lanes offer, in display order.+ *+ * grok reports `ready: true` unconditionally: it is the pre-existing default and+ * nothing here gates it, so claiming to know its CLI is installed would be an+ * invented gate that could only ever be wrong in the direction of hiding a+ * working button.+ */+export async function listAnimationProviders() {+ return [+ {+ id: 'grok',+ label: 'Grok (cloud)',+ ready: true,+ reason: null,+ },+ await getLocalAnimationProviderStatus(),+ ];+}++/**+ * Resolve the render plan for one local clip, or throw the 409 that says why+ * this install cannot render one.+ *+ * Called BEFORE the run record is written so an unusable lane costs the user a+ * clear error instead of an inert `error` run they then have to go delete.+ *+ * The canvas is NOT decided here — it depends on the anchor's aspect ratio, and+ * only the input-prep step measures that. The plan carries a `chooseCanvas` the+ * prep step calls with the measured size and hands back on its result, so the+ * measurement happens exactly once and the padded input and the render argv+ * cannot disagree about which canvas was picked.+ */+export async function planLocalAnimationRender({ durationSeconds } = {}) {+ const status = await getLocalAnimationProviderStatus();+ if (!status.ready) {+ throw new ServerError(status.reason, { status: 409, code: 'LOCAL_VIDEO_PROVIDER_NOT_READY' });+ }+ const model = resolveLocalVideoModel();+ const numFrames = resolveLocalFrameCount(model, durationSeconds);+ if (!numFrames) {+ throw new ServerError(+ `${model.name} declares no legal frame counts, so a local render cannot be sized.`,+ { status: 500, code: 'LOCAL_VIDEO_MODEL_MISCONFIGURED' },+ );+ }+ return {+ model,+ numFrames,+ fps: localRenderFps(model),+ chooseCanvas: (anchorSize) => pickLocalRenderCanvas(model, anchorSize),+ };+}++/**+ * The provenance a local run stamps on its record, so a finished clip+ * self-documents which lane, model, runtime, and geometry produced it — the same+ * question `provider` alone answered while grok was the only lane.+ */+export const localRenderManifest = (plan, canvas) => ({+ provider: LOCAL_VIDEO_PROVIDER_ID,+ videoModelId: plan.model.id,+ videoRuntime: plan.model.runtime,+ renderFrames: plan.numFrames,+ renderFps: plan.fps,+ renderSeconds: Math.round((plan.numFrames / plan.fps) * 100) / 100,+ ...(canvas ? { renderWidth: canvas.width, renderHeight: canvas.height } : {}),+});++/**+ * Queue the render. Returns the media-job id synchronously enough to stamp on+ * the run record before anything awaits the result.+ *+ * `hidden: true` keeps the clip out of the user's video gallery: it is an+ * intermediate the sprite pipeline consumes, not a video they asked to keep.+ * `enqueueJob` rather than `enqueueUnattendedMediaJob` is deliberate — the user+ * explicitly chose the LOCAL provider, and the unattended helper's default+ * routing could send the job to a peer instead.+ */+export function enqueueLocalAnimationRender({ plan, canvas, prompt, inputAbs, owner }) {+ return enqueueJob({+ kind: 'video',+ owner,+ params: {+ modelId: plan.model.id,+ prompt,+ mode: 'image',+ sourceImagePath: inputAbs,+ ...(canvas ? { width: canvas.width, height: canvas.height } : {}),+ numFrames: plan.numFrames,+ fps: plan.fps,+ hidden: true,+ },+ }).jobId;+}++const TERMINAL_JOB_STATUSES = Object.freeze(['completed', 'failed', 'canceled']);++/**+ * Resolve when `jobId` reaches a terminal state, as `{ status, error }`.+ *+ * The immediate re-check after the listeners are attached is load-bearing, not+ * belt-and-braces: `enqueueJob` starts the worker synchronously, so a job that+ * fails fast (an unconfigured interpreter, a buildArgs throw) can settle in the+ * gap between the enqueue and this subscription — and a missed terminal event+ * strands the run at `rendering` forever with nothing to advance it.+ */+export function awaitMediaJobTerminalState(jobId) {+ return new Promise((resolve) => {+ let settled = false;+ const settle = (job) => {+ if (settled || job?.id !== jobId) return;+ settled = true;+ mediaJobEvents.off('completed', settle);+ mediaJobEvents.off('failed', settle);+ mediaJobEvents.off('canceled', settle);+ resolve({ status: job.status, error: job.error || null });+ };+ mediaJobEvents.on('completed', settle);+ mediaJobEvents.on('failed', settle);+ mediaJobEvents.on('canceled', settle);+ const current = getJob(jobId);+ if (current && TERMINAL_JOB_STATUSES.includes(current.status)) settle(current);+ });+}++/**+ * Drive one queued local render to completion and put its clip where the+ * deterministic postprocess expects it.+ *+ * Resolves either way — like the grok lane, the attach decides the outcome from+ * whether the MP4 actually landed on disk, so a failure here needs only to leave+ * the destination absent (and say why in the log).+ */+export async function collectLocalAnimationRender({ jobId, videoAbs, label }) {+ const { status, error } = await awaitMediaJobTerminalState(jobId);+ if (status !== 'completed') {+ console.error(`❌ ${label} local render ${status} [${jobId.slice(0, 8)}]: ${error || 'no error reported'}`);+ return;+ }+ // generateVideo names its output after the job id (`filename = ${jobId}.mp4`).+ const renderedAbs = join(PATHS.videos, `${jobId}.mp4`);+ if (!await pathExists(renderedAbs)) {+ console.error(`❌ ${label} local render completed without an MP4 at ${renderedAbs}`);+ return;+ }+ // COPY rather than move: the gallery record generateVideo wrote still points+ // at this file (hidden, but real), and its thumbnail sits beside it. Moving it+ // would leave a history row pointing at nothing.+ await copyFile(renderedAbs, videoAbs);+}++/**+ * Whether a `rendering` local run is still genuinely live.+ *+ * A local H3 render is a multi-HOUR job on current Apple Silicon, so the grok+ * lane's wall-clock staleness cutoff (its TUI hard cap plus a minute) would+ * declare a perfectly healthy render dead less than an hour in. The media job+ * is the real signal, and it survives a restart because the queue persists and+ * rehydrates both its queue and its archive.+ *+ * Three outcomes, deliberately not two: a job the queue has never heard of is+ * `unknown`, NOT `terminal`. Collapsing those would turn "the archive has rolled+ * past this job" into "this render failed" and mark a live run errored.+ */+export const localRunLiveness = (run) => {+ const jobId = run?.jobId;+ if (typeof jobId !== 'string' || !jobId) return 'unknown';+ const job = getJob(jobId);+ if (!job) return 'unknown';+ return TERMINAL_JOB_STATUSES.includes(job.status) ? 'terminal' : 'live';+};diff --git a/server/services/sprites/localAnimationRender.test.js b/server/services/sprites/localAnimationRender.test.jsnew file mode 100644index 0000000000..8db8b3c801--- /dev/null+++ b/server/services/sprites/localAnimationRender.test.js@@ -0,0 +1,491 @@+/**+ * The LOCAL (MiniMax H3) sprite-animation render lane (#4876).+ *+ * The behaviors under test are the ones that decide whether a local render is+ * USABLE, not merely started: the frame count has to land on H3's fixed grid,+ * the canvas has to match the anchor's aspect (or videoGen center-crops the+ * character's head off before rendering), an unready install has to say which+ * one thing to fix, and a run's liveness has to survive a multi-hour render+ * without being mistaken for a dead one.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { mkdtempSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { mkdir, writeFile, readFile } from 'fs/promises';++const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-local-render-test-'));++vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ Object.assign(actual.PATHS, {+ data: TEST_ROOT,+ videos: join(TEST_ROOT, 'videos'),+ });+ return actual;+});++// The catalog, the runtime probes, and the HF cache are all environment facts;+// each test states the environment it is about rather than depending on what+// this machine happens to have installed.+let videoModels = [];+vi.mock('../../lib/mediaModels.js', () => ({+ getVideoModels: () => videoModels,+}));++let runtimeReady = true;+vi.mock('../videoGen/runtimes.js', () => ({+ BYOV_RUNTIME_INFO: { minimax_h3: { label: 'MiniMax H3 MLX' } },+ isByovRuntimeReady: async () => runtimeReady,+}));++let cacheState = { cached: true };+let cachedFiles = ['/cache/a.safetensors'];+vi.mock('../../lib/hfCache.js', () => ({+ inspectModelCache: async () => cacheState,+ findCachedRepoFiles: async () => cachedFiles,+}));++const enqueued = [];+let queueJobs = new Map();+const { EventEmitter } = await import('events');+const mediaJobEvents = new EventEmitter();+vi.mock('../mediaJobQueue/index.js', () => ({+ enqueueJob: (job) => {+ enqueued.push(job);+ return { jobId: `job-${enqueued.length}` };+ },+ getJob: (id) => queueJobs.get(id) || null,+ mediaJobEvents,+}));++const {+ resolveLocalVideoModel, resolveLocalFrameCount, pickLocalRenderCanvas, localRenderFps,+ getLocalAnimationProviderStatus, listAnimationProviders, planLocalAnimationRender,+ localRenderManifest, enqueueLocalAnimationRender, awaitMediaJobTerminalState,+ collectLocalAnimationRender, localRunLiveness,+} = await import('./localAnimationRender.js');+// The lane VOCABULARY (ids, the request normalizer, the run-record predicate)+// lives in animationWorkflow.js so lib/spriteValidation.js can build its enum+// without pulling the media-job queue into the validation layer.+const {+ isLocalProviderRun, resolveAnimationProvider, LOCAL_VIDEO_PROVIDER_ID,+} = await import('./animationWorkflow.js');++// A stand-in for the shipped MLX row, carrying only the fields this lane reads.+// Frame options are H3's real 17n+5 grid so the snapping assertions are about+// the actual contract rather than a convenient synthetic one.+const H3_MLX = Object.freeze({+ id: 'minimax_h3_8bit',+ name: 'MiniMax H3 MLX 8-bit',+ repo: 'pipenetwork/MiniMax-H3-MLX-8bit',+ revision: 'abc123',+ runtime: 'minimax_h3',+ defaultFrames: 124,+ frameOptions: [107, 124, 141, 158, 175],+ fpsOptions: [24],+ defaultWidth: 1344,+ defaultHeight: 768,+ resolutionOptions: [+ { label: '1536x672', w: 1536, h: 672 },+ { label: '1344x768', w: 1344, h: 768 },+ { label: '1024x768', w: 1024, h: 768 },+ { label: '768x768', w: 768, h: 768 },+ { label: '768x1024', w: 768, h: 1024 },+ { label: '768x1344', w: 768, h: 1344 },+ ],+ requiredWeights: [{ repo: 'MiniMaxAI/MiniMax-H3', revision: 'def456', files: ['FL2VA/model_index.json'] }],+});++beforeEach(() => {+ videoModels = [{ id: 'ltx', runtime: 'ltx2' }, H3_MLX];+ runtimeReady = true;+ cacheState = { cached: true };+ cachedFiles = ['/cache/a.safetensors'];+ enqueued.length = 0;+ queueJobs = new Map();+ mediaJobEvents.removeAllListeners();+});++describe('resolveLocalVideoModel', () => {+ it('picks the H3 row out of the platform bucket, ignoring other runtimes', () => {+ expect(resolveLocalVideoModel()?.id).toBe('minimax_h3_8bit');+ });++ it('finds the CUDA row on a bucket that ships that one instead', () => {+ videoModels = [{ id: 'minimax_h3_cuda', runtime: 'minimax_h3_cuda' }];+ expect(resolveLocalVideoModel()?.id).toBe('minimax_h3_cuda');+ });++ it('is null when this platform has no H3 build at all', () => {+ videoModels = [{ id: 'ltx', runtime: 'ltx2' }];+ expect(resolveLocalVideoModel()).toBeNull();+ });+});++describe('resolveLocalFrameCount', () => {+ it('snaps a requested clip length onto the model grid', () => {+ // 6s * 24fps = 144 frames requested; 141 is the closest legal count.+ expect(resolveLocalFrameCount(H3_MLX, 6)).toBe(141);+ // 5s = 120 → 124 is closer than 107.+ expect(resolveLocalFrameCount(H3_MLX, 5)).toBe(124);+ });++ it('snaps DOWN when the closest legal count is shorter than requested', () => {+ // Rounding up unconditionally would pick 124 and render ~15% longer for+ // footage the packer discards.+ expect(resolveLocalFrameCount(H3_MLX, 4.6)).toBe(107);+ });++ it('clamps a request beyond the grid to its nearest end', () => {+ expect(resolveLocalFrameCount(H3_MLX, 60)).toBe(175);+ expect(resolveLocalFrameCount(H3_MLX, 0.5)).toBe(107);+ });++ it('breaks an exact tie toward the SHORTER (cheaper) render', () => {+ const model = { frameOptions: [100, 200], fpsOptions: [1], defaultFrames: 100 };+ expect(resolveLocalFrameCount(model, 150)).toBe(100);+ });++ it('falls back to the row default when no duration is given', () => {+ expect(resolveLocalFrameCount(H3_MLX, undefined)).toBe(124);+ expect(resolveLocalFrameCount(H3_MLX, 0)).toBe(124);+ });++ it('uses defaultFrames when the row declares no grid, and null when it declares neither', () => {+ expect(resolveLocalFrameCount({ defaultFrames: 90 }, 6)).toBe(90);+ expect(resolveLocalFrameCount({}, 6)).toBeNull();+ });+});++describe('pickLocalRenderCanvas', () => {+ it('gives a PORTRAIT anchor a portrait canvas', () => {+ // The whole point: H3's default is 1344x768, and conforming a tall sprite to+ // it center-crops the character's head and feet away before the render.+ expect(pickLocalRenderCanvas(H3_MLX, { width: 512, height: 896 })).toEqual({ width: 768, height: 1344 });+ });++ it('gives a square anchor the square canvas', () => {+ expect(pickLocalRenderCanvas(H3_MLX, { width: 1024, height: 1024 })).toEqual({ width: 768, height: 768 });+ });++ it('gives a wide anchor the widest canvas', () => {+ expect(pickLocalRenderCanvas(H3_MLX, { width: 2100, height: 900 })).toEqual({ width: 1536, height: 672 });+ });++ it('scores aspect error symmetrically, so a 3:4 anchor is not pulled landscape', () => {+ // In LINEAR ratio space 1344/768 (1.75) sits 0.75 from 1.0 while 768/1024+ // (0.75) sits only 0.25 below — a naive difference would still favour the+ // portrait one here, but for 3:4 vs 4:3 the linear metric flips the answer.+ expect(pickLocalRenderCanvas(H3_MLX, { width: 750, height: 1000 })).toEqual({ width: 768, height: 1024 });+ expect(pickLocalRenderCanvas(H3_MLX, { width: 1000, height: 750 })).toEqual({ width: 1024, height: 768 });+ });++ it('falls back to the row default when the anchor could not be measured', () => {+ expect(pickLocalRenderCanvas(H3_MLX, {})).toEqual({ width: 1344, height: 768 });+ expect(pickLocalRenderCanvas(H3_MLX, { width: 0, height: 0 })).toEqual({ width: 1344, height: 768 });+ });++ it('is null for a row that declares neither presets nor a default', () => {+ expect(pickLocalRenderCanvas({}, { width: 10, height: 10 })).toBeNull();+ });+});++describe('localRenderFps', () => {+ it('reads the row, and falls back to H3 24 when it declares none', () => {+ expect(localRenderFps(H3_MLX)).toBe(24);+ expect(localRenderFps({ fpsOptions: [30] })).toBe(30);+ expect(localRenderFps({})).toBe(24);+ });+});++describe('resolveAnimationProvider', () => {+ it('defaults to grok so an older client renders exactly where it used to', () => {+ expect(resolveAnimationProvider(undefined)).toBe('grok');+ expect(resolveAnimationProvider(null)).toBe('grok');+ expect(resolveAnimationProvider('')).toBe('grok');+ });++ it('passes a known provider through', () => {+ expect(resolveAnimationProvider('local')).toBe('local');+ expect(resolveAnimationProvider('grok')).toBe('grok');+ });++ it('REFUSES an unknown provider rather than silently billing the cloud lane', () => {+ expect(() => resolveAnimationProvider('minimax')).toThrow(/Unknown animation provider/);+ try {+ resolveAnimationProvider('minimax');+ } catch (err) {+ expect(err.status).toBe(400);+ expect(err.code).toBe('ANIMATION_PROVIDER_INVALID');+ }+ });+});++describe('getLocalAnimationProviderStatus', () => {+ it('is ready, with the model named, when runtime and weights are both present', async () => {+ const status = await getLocalAnimationProviderStatus();+ expect(status).toMatchObject({+ id: 'local', ready: true, reason: null, modelId: 'minimax_h3_8bit', runtime: 'minimax_h3', fps: 24,+ });+ });++ it('reports an unsupported PLATFORM distinctly from an uninstalled runtime', async () => {+ videoModels = [{ id: 'ltx', runtime: 'ltx2' }];+ const status = await getLocalAnimationProviderStatus();+ expect(status.ready).toBe(false);+ expect(status.reason).toMatch(/no local MiniMax H3 video build/);+ // No model id to offer, so the client cannot mislabel it as installable.+ expect(status.modelId).toBeUndefined();+ });++ it('names the RUNTIME when the venv is missing', async () => {+ runtimeReady = false;+ const status = await getLocalAnimationProviderStatus();+ expect(status.ready).toBe(false);+ expect(status.reason).toMatch(/MiniMax H3 MLX runtime is not installed/);+ });++ it('names the MODEL when the runtime is installed but the weights are not', async () => {+ cacheState = { cached: false };+ const status = await getLocalAnimationProviderStatus();+ expect(status.ready).toBe(false);+ expect(status.reason).toMatch(/is not downloaded/);+ });++ it('is not ready when a required dependency repo is only partially cached', async () => {+ // findCachedRepoFiles resolves null when ANY pinned file is missing — the+ // base snapshot being present must not be enough on its own.+ cachedFiles = null;+ expect((await getLocalAnimationProviderStatus()).ready).toBe(false);+ });+});++// The CUDA row is what a Windows or Linux install renders on. It differs from+// the MLX row in exactly two ways this lane can see — a NARROWER frame window,+// and no `requiredWeights` (its download is an explicit file list against the+// base repo) — so both are asserted rather than assumed to fall out.+describe('the CUDA bucket (Windows / Linux installs)', () => {+ const H3_CUDA = {+ id: 'minimax_h3_cuda',+ name: 'MiniMax H3 CUDA int8',+ repo: 'MiniMaxAI/MiniMax-H3',+ revision: 'cuda-rev',+ runtime: 'minimax_h3_cuda',+ defaultFrames: 124,+ // The diffusers integration refuses 107 (under its 5s floor) and anything+ // past 345, so the same 6s request must land inside a different window.+ frameOptions: [124, 141, 158, 175],+ fpsOptions: [24],+ defaultWidth: 1344,+ defaultHeight: 768,+ resolutionOptions: [{ w: 1344, h: 768 }, { w: 768, h: 1024 }],+ };++ beforeEach(() => {+ videoModels = [H3_CUDA];+ });++ it('is ready without any requiredWeights to resolve', async () => {+ // findCachedRepoFiles is never consulted for this row; a stubbed-null result+ // must not drag it to unready the way it does for the MLX row.+ cachedFiles = null;+ const status = await getLocalAnimationProviderStatus();+ expect(status).toMatchObject({ ready: true, modelId: 'minimax_h3_cuda', runtime: 'minimax_h3_cuda' });+ });++ it('honours its own narrower frame window rather than the MLX grid', async () => {+ const plan = await planLocalAnimationRender({ durationSeconds: 6 });+ expect(plan.numFrames).toBe(141);+ // 4.5s is legal on MLX (107) but below this row's floor.+ expect(resolveLocalFrameCount(H3_CUDA, 4.5)).toBe(124);+ });++ it('names its own runtime in the not-installed reason', async () => {+ runtimeReady = false;+ const status = await getLocalAnimationProviderStatus();+ // No BYOV_RUNTIME_INFO label is stubbed for this runtime, so the id itself+ // is the fallback — an unlabeled runtime must still name something.+ expect(status.reason).toContain('minimax_h3_cuda');+ });+});++describe('listAnimationProviders', () => {+ it('offers grok unconditionally alongside the probed local lane', async () => {+ const providers = await listAnimationProviders();+ expect(providers.map((p) => p.id)).toEqual(['grok', 'local']);+ expect(providers[0]).toMatchObject({ ready: true });+ expect(providers[1]).toMatchObject({ ready: true });+ });++ it('still lists grok when the local lane is unusable', async () => {+ runtimeReady = false;+ const providers = await listAnimationProviders();+ expect(providers[0].ready).toBe(true);+ expect(providers[1].ready).toBe(false);+ });+});++describe('planLocalAnimationRender', () => {+ it('resolves the model and frame count for a ready install', async () => {+ const plan = await planLocalAnimationRender({ durationSeconds: 6 });+ expect(plan.model.id).toBe('minimax_h3_8bit');+ expect(plan.numFrames).toBe(141);+ expect(plan.fps).toBe(24);+ expect(plan.chooseCanvas({ width: 512, height: 896 })).toEqual({ width: 768, height: 1344 });+ });++ it('409s with the readiness reason instead of queueing an impossible render', async () => {+ runtimeReady = false;+ await expect(planLocalAnimationRender({ durationSeconds: 6 })).rejects.toMatchObject({+ status: 409,+ code: 'LOCAL_VIDEO_PROVIDER_NOT_READY',+ });+ });+});++describe('localRenderManifest', () => {+ it('stamps the lane, model, runtime, and resolved geometry', () => {+ const plan = { model: H3_MLX, numFrames: 141, fps: 24 };+ expect(localRenderManifest(plan, { width: 768, height: 1344 })).toEqual({+ provider: LOCAL_VIDEO_PROVIDER_ID,+ videoModelId: 'minimax_h3_8bit',+ videoRuntime: 'minimax_h3',+ renderFrames: 141,+ renderFps: 24,+ renderSeconds: 5.88,+ renderWidth: 768,+ renderHeight: 1344,+ });+ });++ it('omits the canvas keys entirely when none was chosen', () => {+ const manifest = localRenderManifest({ model: H3_MLX, numFrames: 124, fps: 24 }, null);+ expect(manifest).not.toHaveProperty('renderWidth');+ expect(manifest).not.toHaveProperty('renderHeight');+ });+});++describe('enqueueLocalAnimationRender', () => {+ it('queues an image-conditioned, hidden render at the planned geometry', () => {+ const plan = { model: H3_MLX, numFrames: 141, fps: 24 };+ const jobId = enqueueLocalAnimationRender({+ plan, canvas: { width: 768, height: 1344 }, prompt: 'walk east', inputAbs: '/in.png', owner: 'sprite-walk:a:east',+ });+ expect(jobId).toBe('job-1');+ expect(enqueued[0]).toMatchObject({ kind: 'video', owner: 'sprite-walk:a:east' });+ expect(enqueued[0].params).toMatchObject({+ modelId: 'minimax_h3_8bit',+ prompt: 'walk east',+ mode: 'image',+ sourceImagePath: '/in.png',+ width: 768,+ height: 1344,+ numFrames: 141,+ fps: 24,+ // The clip is a pipeline intermediate, not a video the user asked to keep.+ hidden: true,+ });+ });+});++describe('awaitMediaJobTerminalState', () => {+ it('resolves when the queue emits the job terminal', async () => {+ const pending = awaitMediaJobTerminalState('job-9');+ mediaJobEvents.emit('completed', { id: 'job-9', status: 'completed' });+ await expect(pending).resolves.toEqual({ status: 'completed', error: null });+ });++ it('ignores terminal events for OTHER jobs', async () => {+ let settled = false;+ const pending = awaitMediaJobTerminalState('job-9').then((r) => { settled = true; return r; });+ mediaJobEvents.emit('failed', { id: 'job-other', status: 'failed', error: 'nope' });+ await Promise.resolve();+ expect(settled).toBe(false);+ mediaJobEvents.emit('failed', { id: 'job-9', status: 'failed', error: 'boom' });+ await expect(pending).resolves.toEqual({ status: 'failed', error: 'boom' });+ });++ it('settles from queue state when the job ALREADY finished before we subscribed', async () => {+ // enqueueJob starts the worker synchronously, so a fast failure can settle+ // in the gap before this subscription — without the re-check the run would+ // sit at 'rendering' forever.+ queueJobs.set('job-fast', { id: 'job-fast', status: 'failed', error: 'PYTHON not configured' });+ await expect(awaitMediaJobTerminalState('job-fast')).resolves.toEqual({+ status: 'failed', error: 'PYTHON not configured',+ });+ });++ it('does NOT settle early for a job the queue reports still running', async () => {+ queueJobs.set('job-live', { id: 'job-live', status: 'running' });+ let settled = false;+ awaitMediaJobTerminalState('job-live').then(() => { settled = true; });+ await Promise.resolve();+ expect(settled).toBe(false);+ });+});++describe('collectLocalAnimationRender', () => {+ const videosDir = join(TEST_ROOT, 'videos');++ it('copies the rendered clip to where the postprocess reads it', async () => {+ await mkdir(videosDir, { recursive: true });+ await writeFile(join(videosDir, 'job-ok.mp4'), 'clip-bytes');+ const dest = join(TEST_ROOT, 'run', 'source-video.mp4');+ await mkdir(join(TEST_ROOT, 'run'), { recursive: true });+ const pending = collectLocalAnimationRender({ jobId: 'job-ok', videoAbs: dest, label: 'walk east' });+ mediaJobEvents.emit('completed', { id: 'job-ok', status: 'completed' });+ await pending;+ expect(await readFile(dest, 'utf8')).toBe('clip-bytes');+ });++ it('leaves the destination ABSENT on a failed job, so the attach reports the failure', async () => {+ const dest = join(TEST_ROOT, 'run2', 'source-video.mp4');+ await mkdir(join(TEST_ROOT, 'run2'), { recursive: true });+ const pending = collectLocalAnimationRender({ jobId: 'job-bad', videoAbs: dest, label: 'walk east' });+ mediaJobEvents.emit('failed', { id: 'job-bad', status: 'failed', error: 'oom' });+ await pending;+ await expect(readFile(dest, 'utf8')).rejects.toThrow();+ });++ it('does not throw when a completed job wrote no MP4', async () => {+ const dest = join(TEST_ROOT, 'run3', 'source-video.mp4');+ await mkdir(join(TEST_ROOT, 'run3'), { recursive: true });+ const pending = collectLocalAnimationRender({ jobId: 'job-empty', videoAbs: dest, label: 'walk east' });+ mediaJobEvents.emit('completed', { id: 'job-empty', status: 'completed' });+ await expect(pending).resolves.toBeUndefined();+ });+});++describe('localRunLiveness', () => {+ it('reports a queued or running job as live', () => {+ queueJobs.set('j', { id: 'j', status: 'running' });+ expect(localRunLiveness({ jobId: 'j' })).toBe('live');+ queueJobs.set('j', { id: 'j', status: 'queued' });+ expect(localRunLiveness({ jobId: 'j' })).toBe('live');+ });++ it('reports a settled job as terminal', () => {+ for (const status of ['completed', 'failed', 'canceled']) {+ queueJobs.set('j', { id: 'j', status });+ expect(localRunLiveness({ jobId: 'j' })).toBe('terminal');+ }+ });++ it('reports UNKNOWN — not terminal — for a job the queue has forgotten', () => {+ // Collapsing this into 'terminal' would flip a live run to error the moment+ // its job aged out of the archive.+ expect(localRunLiveness({ jobId: 'gone' })).toBe('unknown');+ expect(localRunLiveness({})).toBe('unknown');+ expect(localRunLiveness(null)).toBe('unknown');+ });+});++describe('isLocalProviderRun', () => {+ it('distinguishes the two lanes by the run record alone', () => {+ expect(isLocalProviderRun({ provider: LOCAL_VIDEO_PROVIDER_ID })).toBe(true);+ expect(isLocalProviderRun({ provider: 'grok-tui' })).toBe(false);+ expect(isLocalProviderRun({})).toBe(false);+ });+});diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex 23fc0c820a..2934706a58 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -57,10 +57,15 @@ import { resolveGrokDuration } from '../../lib/grokVideoClip.js';import {withAnimationWriteTail, resolveChromaKey, lockedAnchorFor,GROK_TUI_IDLE_MS, GROK_TUI_TIMEOUT_MS, grokTuiProvider, buildGrokI2vTask,+ resolveAnimationProvider, isLocalProviderRun,} from './animationWorkflow.js';import {SCANNER_TRACK, sourceReferenceFor,} from './animationTracks.js';+import {+ planLocalAnimationRender, enqueueLocalAnimationRender, collectLocalAnimationRender,+ localRenderManifest, localRunLiveness,+} from './localAnimationRender.js';// #3152 — the anchor-invalidation sweep below must cover a USER-DEFINED track too:// a stored row seeded from a directional anchor holds approvals descended from the// same reference, and sweeping only the compiled table would leave them standing@@ -286,10 +291,31 @@ function runCreatedAtMs(createdAt) {// forever, surfaces regenerate, and the in-flight guard in startWalkGeneration// stops treating it as live. RENDER_STALE_MS is the hard cap plus a buffer.const RENDER_STALE_MS = WALK_TUI_TIMEOUT_MS + 60_000;+// The LOCAL lane's backstop, used only when the media-job queue can no longer+// answer for a run (its archive has rolled past that job). Deliberately a day+// rather than grok's half hour: a local H3 clip is a multi-HOUR render on+// current Apple Silicon, so anything tighter would report healthy work as dead.+const LOCAL_RENDER_STALE_MS = 24 * 60 * 60_000;+// Which lane a run came from, for logs shared by both.+const runProviderLabel = (run) => (isLocalProviderRun(run) ? 'local' : 'grok-tui');+const STALE_RENDER_ERROR = 'Walk render was interrupted (server restart or timeout) — regenerate to retry.';function normalizeStaleRendering(run) {if (run?.status !== 'rendering') return run;- if (Date.now() - runCreatedAtMs(run.createdAt) <= RENDER_STALE_MS) return run;- return { ...run, status: 'error', postprocessError: 'Walk render was interrupted (server restart or timeout) — regenerate to retry.' };+ const staleAfterMs = isLocalProviderRun(run) ? LOCAL_RENDER_STALE_MS : RENDER_STALE_MS;+ // A local render's real liveness signal is its queued media job, not the wall+ // clock — the queue persists and rehydrates across restarts, so it answers+ // correctly for a render that has legitimately been going for hours AND for+ // one whose server died. The clock is only the fallback for `unknown` (no job+ // id, or a job the archive has forgotten), which is why the three-way liveness+ // is not collapsed to a boolean: treating `unknown` as `terminal` would error+ // a live run the moment its job aged out of the archive.+ if (isLocalProviderRun(run)) {+ const liveness = localRunLiveness(run);+ if (liveness === 'live') return run;+ if (liveness === 'terminal') return { ...run, status: 'error', postprocessError: STALE_RENDER_ERROR };+ }+ if (Date.now() - runCreatedAtMs(run.createdAt) <= staleAfterMs) return run;+ return { ...run, status: 'error', postprocessError: STALE_RENDER_ERROR };}// PortOS's own postprocess stamps `stripPreview.stripPath` record-relative@@ -702,7 +728,7 @@ export async function getWalkState(recordId) {return loadRunRecordAt(recordId, runDirRel).then((run) => (run ? normalizeRunRecord(recordId, run, runDirRel) : null));}),- )).filter(isWalkRun)+ )).filter((run) => run && isWalkRun(run))// Second pass: a record whose own `id` differs from its directory name is// already covered by an entry that named it by id. Dedupe on id too, so a// run that somehow exists under both scan roots surfaces once.@@ -1000,6 +1026,24 @@ async function startWalkGenerationImpl(recordId, body) {throw new ServerError('Locked anchor file is missing on disk', { status: 500, code: 'ANCHOR_MISSING' });}+ // WHICH lane renders the clip (#4876). Absent → grok, so every pre-existing+ // client, persisted retry, and test renders exactly where it did before the+ // local lane existed.+ const provider = resolveAnimationProvider(body.provider);+ // Clip length grok will actually deliver — a request it does not offer falls+ // back to its shortest (see lib/grokVideoClip.js). The walk's look comes from+ // frameCount/fps below, not from how much footage the packer had to pick from.+ // The local lane snaps the same request onto H3's 17n+5 frame grid instead,+ // which is why `duration` stays the shared unit rather than a grok-only field.+ const duration = resolveGrokDuration(body.duration);+ // Resolved BEFORE the run directory is created, not just before the run+ // record: an install with no runnable local model must leave NOTHING behind.+ // An empty run directory is not inert — the run scan reads it back, finds no+ // record, and (before this) took getWalkState down with it.+ const localPlan = provider === 'local'+ ? await planLocalAnimationRender({ durationSeconds: duration })+ : null;+const runId = `walk-${direction}-${randomUUID().slice(0, 8)}`;const runRel = runRelPath(runId);const runAbs = join(spriteDir(recordId), runRel);@@ -1012,16 +1056,12 @@ async function startWalkGenerationImpl(recordId, body) {// prepareWalkAnchorChromaInput). Saved without mutating the locked anchor.// Overlap the input prep with the (independent) settings read.const inputAbs = join(generatedAbs, 'input-anchor-chroma.png');- const [{ preparation, sha256: inputSha256 }, settings] = await Promise.all([- prepareWalkAnchorChromaInput(anchorAbs, inputAbs, chromaKey),+ const [{ preparation, sha256: inputSha256, canvas }, settings] = await Promise.all([+ prepareWalkAnchorChromaInput(anchorAbs, inputAbs, chromaKey, localPlan?.chooseCanvas || null),getSettings(),]);- // Clip length grok will actually deliver — a request it doesn't offer falls- // back to its shortest (see lib/grokVideoClip.js). The walk's look comes from- // frameCount/fps below, not from how much footage the packer had to pick from.- const duration = resolveGrokDuration(body.duration);// Frame count + playback fps are the deterministic-postprocess knobs, not the- // grok clip's — grok animates the same clip regardless, and the packer+ // clip's — the provider animates the same clip regardless, and the packer// resamples/labels the cycle afterward. Resolved from the set target above and// stored on the run so the completion hook's packageRun (and any later// reprocess) applies exactly what the set is pinned to.@@ -1033,6 +1073,15 @@ async function startWalkGenerationImpl(recordId, body) {const prompt = buildWalkVideoPrompt({ name: record.name, direction, chromaKey, correctionPrompt });const videoAbs = join(generatedAbs, 'source-video.mp4');const grokPath = settings.imageGen?.grok?.grokPath;+ // The local job id has to be on the run record BEFORE anything awaits it —+ // `localRunLiveness` reads it to tell a live multi-hour render from one the+ // server died inside, and a run saved without it would read as `unknown`+ // forever. `enqueueJob` returns synchronously, so there is no window here.+ const jobId = localPlan+ ? enqueueLocalAnimationRender({+ plan: localPlan, canvas, prompt, inputAbs, owner: `sprite-walk:${recordId}:${direction}`,+ })+ : null;// Run record BEFORE the render starts: a crash between the two leaves an inert// 'rendering' run (harmless, regenerable) rather than a session the attach@@ -1041,13 +1090,15 @@ async function startWalkGenerationImpl(recordId, body) {const run = {schemaVersion: 1,kind: 'grok-game-animation-frames-run',- // Vendor recorded as metadata, not baked into the storage path — a future- // non-grok source stamps its own provider and stores under the same runs/ tree.+ // Vendor recorded as metadata, not baked into the storage path — the local+ // lane stamps its own provider and stores under the same runs/ tree.provider: GROK_TUI_ID,status: 'rendering',id: runId,// The TUI run id doubles as the attachable Shell session id (executeTuiRun// registers the PTY under this id), so the card can link to /shell/<id>.+ // A local render is a queued media job, not a PTY, so it carries `jobId`+ // instead — the two are mutually exclusive on purpose.shellSession: runId,characterId: recordId,direction,@@ -1062,20 +1113,30 @@ async function startWalkGenerationImpl(recordId, body) {animationInputPreparation: preparation,...(correctionPrompt ? { correctionPrompt } : {}),createdAt: now,+ // Spread LAST so the local lane's provider/geometry provenance overrides the+ // grok defaults above rather than being silently overwritten by them.+ ...(localPlan ? { ...localRenderManifest(localPlan, canvas), jobId, shellSession: null } : {}),};await saveRunRecord(recordId, run);- // Fire the observable grok-tui render fire-and-forget (do NOT await — this- // impl holds the per-record write tail, which a ~10-min render must not).- // Completion re-enters the tail via attachTuiWalkResult; errors are captured- // onto the run record (no request lifecycle to bubble to).+ // Fire the render off fire-and-forget (do NOT await — this impl holds the+ // per-record write tail, which a long render must not). Completion re-enters+ // the tail via attachTuiWalkResult; errors are captured onto the run record+ // (no request lifecycle to bubble to).+ if (localPlan) {+ collectLocalAnimationRender({ jobId, videoAbs, label: `sprite walk ${recordId}/${direction}` })+ .then(() => walkWriteTail(recordId, () => attachTuiWalkResult(recordId, runId, videoAbs)))+ .catch((err) => console.error(`❌ sprite walk local render crashed ${recordId}/${runId}: ${err?.message || err}`));+ console.log(`🚶 sprite walk local render started ${recordId}/${runId} (job ${jobId.slice(0, 8)}, ${localPlan.numFrames}f @ ${localPlan.fps}fps)`);+ return { runId, direction, duration, provider: 'local', jobId };+ }runWalkTuiRender(recordId, {runId, direction, grokPath, task: buildGrokI2vTask({ prompt, inputAbs, videoAbs, duration }),generatedAbs, videoAbs,}).catch((err) => console.error(`❌ sprite walk grok-tui render crashed ${recordId}/${runId}: ${err?.message || err}`));console.log(`🚶 sprite walk grok-tui render started ${recordId}/${runId} (shell session ${runId})`);- return { runId, direction, duration, shellSession: runId };+ return { runId, direction, duration, provider: 'grok', shellSession: runId };}/**@@ -1101,10 +1162,12 @@ async function runWalkTuiRender(recordId, { runId, direction, grokPath, task, ge}/**- * Attach the finished grok-tui clip and run the deterministic postprocess.- * Guards against overwriting frozen evidence (finalized set / already-approved- * run); the source video is already at its final path (grok wrote it there- * directly), so there's no copy — unlike a queued-job attach.+ * Attach the finished clip and run the deterministic postprocess — shared by+ * BOTH render lanes, because everything downstream of `source-video.mp4` is+ * provider-agnostic. Guards against overwriting frozen evidence (finalized set /+ * already-approved run). The source video is already at its final path by the+ * time this runs (grok writes it there directly; the local lane copies it out of+ * the media-job output), so there is no copy here either way.*/export async function attachTuiWalkResult(recordId, runId, videoAbs) {const run = await loadRunRecord(recordId, runId);@@ -1123,10 +1186,12 @@ export async function attachTuiWalkResult(recordId, runId, videoAbs) {}if (!await pathExists(videoAbs)) {run.status = 'error';- run.postprocessError = 'Grok finished without writing the walk video — check the shell session output';+ run.postprocessError = isLocalProviderRun(run)+ ? 'The local render produced no walk video — check the Render Queue for the failed job'+ : 'Grok finished without writing the walk video — check the shell session output';run.completedAt = new Date().toISOString();await saveRunRecord(recordId, run);- console.error(`❌ sprite walk grok-tui produced no video ${recordId}/${runId}`);+ console.error(`❌ sprite walk ${runProviderLabel(run)} produced no video ${recordId}/${runId}`);return;}run.sourceVideoSha256 = await sha256File(videoAbs);@@ -1134,7 +1199,7 @@ export async function attachTuiWalkResult(recordId, runId, videoAbs) {await saveRunRecord(recordId, run);await packageRun(recordId, run);await saveRunRecord(recordId, run);- console.log(`🚶 sprite walk grok-tui run ${recordId}/${runId} → ${run.status}`);+ console.log(`🚶 sprite walk ${runProviderLabel(run)} run ${recordId}/${runId} → ${run.status}`);}/**@@ -1160,8 +1225,8 @@ async function packageRun(recordId, run, overrides = {}, location = {}) {run.frameCount = frameCount;run.fps = fps;// Record-relative path to the raw clip, stamped BEFORE the (possibly failing)- // postprocess so a run that errors in packaging still surfaces the video grok- // actually produced in the UI, not just the error text. Set here (shared by+ // postprocess so a run that errors in packaging still surfaces the video the+ // provider actually produced in the UI, not just the error text. Set here (shared by// attach + rerun) so a retry backfills it onto an older run too — and for an// imported run that means persisting the record-relative form in place of the// source-repo anchor its manifest was copied with.@@ -1172,8 +1237,9 @@ async function packageRun(recordId, run, overrides = {}, location = {}) {// failure is CAPTURED onto the run record — a throw escaping here would// strand an attach at 'postprocessing' with no error text.const videoAbs = resolveSpriteAssetPath(recordId, run.sourceVideoPath);- // What grok DELIVERED, as opposed to what `run.duration` asked for — the- // requested length is not a promise (see lib/grokVideoClip.js). Stamped+ // What the provider DELIVERED, as opposed to what `run.duration` asked for —+ // the requested length is not a promise on either lane (grok picks from its+ // own menu, see lib/grokVideoClip.js; H3 snaps to its 17n+5 grid). Stamped// here, shared by attach + rerun, so a reprocess backfills it onto an older// run. Overlap the probe with the (independent) manifest read.//diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex 341061448b..a92583e015 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -64,10 +64,20 @@ vi.mock('../../lib/ffmpeg.js', async (importOriginal) => ({probeVideoDuration: (...args) => probeVideoDuration(...args),}));-const prepareWalkAnchorChromaInput = vi.fn(async (_anchorAbs, destAbs) => {+// The real helper measures the anchor with sharp; the stub reports a fixed+// PORTRAIT size so the local lane's canvas choice is exercised for real (the+// chooser is the production one — only the measurement is stubbed).+const STUB_ANCHOR_SIZE = { width: 512, height: 896 };+const prepareWalkAnchorChromaInput = vi.fn(async (_anchorAbs, destAbs, _chromaKey, chooseCanvas = null) => {await mkdir(join(destAbs, '..'), { recursive: true });await writeFile(destAbs, 'stub-chroma-anchor');- return { preparation: 'composited-over-solid-chroma-matte' };+ const canvas = chooseCanvas ? chooseCanvas(STUB_ANCHOR_SIZE) : null;+ return {+ preparation: canvas+ ? 'composited-over-solid-chroma-matte-padded-to-render-canvas'+ : 'composited-over-solid-chroma-matte',+ canvas,+ };});const runWalkPostprocess = vi.fn(async ({runRel, runAbs, recordId, direction, frameCount = 8, fps = 12,@@ -119,6 +129,56 @@ vi.mock('./walkPostprocess.js', async (importOriginal) => {};});+// ── Local render lane (#4876) ───────────────────────────────────────────────+// The lane's own unit coverage lives in localAnimationRender.test.js; what these+// mocks buy HERE is that the real lane logic runs THROUGH walk.js, so the+// dispatch, the run-record provenance, and the job-backed staleness rule are+// exercised end to end. Only the ENVIRONMENT is stubbed — the model catalog, the+// runtime/weight probes, and the job queue — never the lane itself, which would+// make these assertions a restatement of the mock.+const H3_MODEL = {+ id: 'minimax_h3_8bit',+ name: 'MiniMax H3 MLX 8-bit',+ repo: 'pipenetwork/MiniMax-H3-MLX-8bit',+ revision: 'rev-abc',+ runtime: 'minimax_h3',+ defaultFrames: 124,+ frameOptions: [107, 124, 141, 158, 175],+ fpsOptions: [24],+ defaultWidth: 1344,+ defaultHeight: 768,+ resolutionOptions: [+ { w: 1344, h: 768 }, { w: 1024, h: 768 }, { w: 768, h: 768 }, { w: 768, h: 1024 },+ ],+};+let localRuntimeReady = true;+vi.mock('../../lib/mediaModels.js', async (importOriginal) => ({+ ...await importOriginal(),+ getVideoModels: () => [H3_MODEL],+}));+vi.mock('../videoGen/runtimes.js', async (importOriginal) => ({+ ...await importOriginal(),+ BYOV_RUNTIME_INFO: { minimax_h3: { label: 'MiniMax H3 MLX' } },+ isByovRuntimeReady: async () => localRuntimeReady,+}));+vi.mock('../../lib/hfCache.js', async (importOriginal) => ({+ ...await importOriginal(),+ inspectModelCache: async () => ({ cached: true, sizeBytes: 1, snapshotPath: '/snap' }),+ findCachedRepoFiles: async () => ['/snap/a.safetensors'],+}));+const enqueuedVideoJobs = [];+const queuedJobsById = new Map();+vi.mock('../mediaJobQueue/index.js', async (importOriginal) => ({+ ...await importOriginal(),+ enqueueJob: (job) => {+ const id = `mjob-${enqueuedVideoJobs.length + 1}`;+ enqueuedVideoJobs.push({ id, ...job });+ queuedJobsById.set(id, { id, status: 'running' });+ return { jobId: id, position: 1, status: 'queued' };+ },+ getJob: (id) => queuedJobsById.get(id) || null,+}));+const records = await import('./records.js');const { listSpriteAssets } = await import('./paths.js');const { lockReference } = await import('./reference.js');@@ -501,6 +561,155 @@ describe('startWalkGeneration', () => {});});+describe('startWalkGeneration — local render lane (#4876)', () => {+ beforeEach(() => {+ localRuntimeReady = true;+ enqueuedVideoJobs.length = 0;+ queuedJobsById.clear();+ });++ it('defaults to grok when no provider is requested, exactly as before the lane existed', async () => {+ const id = await characterWithLockedAnchors(newId());+ const res = await startWalkGeneration(id, { direction: 'east' });+ expect(res.provider).toBe('grok');+ expect(res.shellSession).toBe(res.runId);+ expect(enqueuedVideoJobs).toHaveLength(0);+ expect(executeTuiRun).toHaveBeenCalled();+ const [run] = (await getWalkState(id)).runs;+ expect(run.provider).toBe('grok-tui');+ expect(run.jobId).toBeUndefined();+ });++ it('queues a MEDIA JOB instead of a TUI session when provider is local', async () => {+ const id = await characterWithLockedAnchors(newId());+ executeTuiRun.mockClear();+ const res = await startWalkGeneration(id, { direction: 'east', provider: 'local', duration: 6 });+ expect(executeTuiRun).not.toHaveBeenCalled();+ expect(res.provider).toBe('local');+ expect(res.jobId).toBe('mjob-1');+ // No PTY exists, so the card must not offer a Shell deep-link.+ expect(res.shellSession).toBeUndefined();+ expect(enqueuedVideoJobs[0]).toMatchObject({ kind: 'video', owner: `sprite-walk:${id}:east` });+ expect(enqueuedVideoJobs[0].params).toMatchObject({+ modelId: 'minimax_h3_8bit',+ mode: 'image',+ // 6s at 24fps = 144 requested → 141 is the nearest legal H3 count.+ numFrames: 141,+ fps: 24,+ hidden: true,+ });+ expect(enqueuedVideoJobs[0].params.prompt).toMatch(/walk-in-place/);+ });++ it('renders on the canvas matching the ANCHOR aspect, not the model default', async () => {+ const id = await characterWithLockedAnchors(newId());+ await startWalkGeneration(id, { direction: 'east', provider: 'local' });+ // The stub anchor is 512x896 (portrait). H3 defaults to 1344x768; sending+ // that would center-crop the character's head and feet off.+ expect(enqueuedVideoJobs[0].params).toMatchObject({ width: 768, height: 1024 });+ });++ it('stamps the lane, model, runtime, geometry, and job id on the run record', async () => {+ const id = await characterWithLockedAnchors(newId());+ const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local', duration: 6 });+ const run = (await getWalkState(id)).runs.find((r) => r.id === runId);+ expect(run).toMatchObject({+ provider: 'minimax-h3-local',+ videoModelId: 'minimax_h3_8bit',+ videoRuntime: 'minimax_h3',+ renderFrames: 141,+ renderFps: 24,+ renderWidth: 768,+ renderHeight: 1024,+ jobId: 'mjob-1',+ status: 'rendering',+ });+ // The provenance spread must WIN over the grok defaults, not be overwritten.+ expect(run.shellSession).toBeNull();+ // The postprocess knobs stay the SET's target, untouched by the render+ // geometry above — a 141-frame 24fps source clip still packs the pinned cycle.+ const { walkTarget } = await getWalkState(id);+ expect(run.frameCount).toBe(walkTarget.frameCount);+ expect(run.fps).toBe(walkTarget.fps);+ expect(run.frameCount).not.toBe(run.renderFrames);+ expect(run.animationInputPreparation).toBe('composited-over-solid-chroma-matte-padded-to-render-canvas');+ });++ it('409s before writing any run record when the local runtime is not installed', async () => {+ const id = await characterWithLockedAnchors(newId());+ localRuntimeReady = false;+ await expect(startWalkGeneration(id, { direction: 'east', provider: 'local' }))+ .rejects.toMatchObject({ status: 409, code: 'LOCAL_VIDEO_PROVIDER_NOT_READY' });+ expect((await getWalkState(id)).runs).toHaveLength(0);+ expect(enqueuedVideoJobs).toHaveLength(0);+ });++ it('rejects an unknown provider rather than falling back to the paid lane', async () => {+ const id = await characterWithLockedAnchors(newId());+ await expect(startWalkGeneration(id, { direction: 'east', provider: 'minimax' }))+ .rejects.toMatchObject({ status: 400, code: 'ANIMATION_PROVIDER_INVALID' });+ expect(executeTuiRun).not.toHaveBeenCalledWith(expect.objectContaining({ label: expect.stringContaining(id) }));+ });++ it('keeps a long-running local render LIVE past the grok staleness cutoff', async () => {+ const id = await characterWithLockedAnchors(newId());+ const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local' });+ // Backdate the run well beyond grok's ~31-minute cutoff. A local H3 clip is+ // a multi-hour render, so the wall clock must not decide this.+ const runJson = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json');+ const stored = JSON.parse(await readFile(runJson, 'utf8'));+ stored.createdAt = new Date(Date.now() - 5 * 60 * 60_000).toISOString();+ await writeFile(runJson, JSON.stringify(stored));+ const run = (await getWalkState(id)).runs.find((r) => r.id === runId);+ expect(run.status).toBe('rendering');+ });++ it('flips a local run to error as soon as its job settles without an attach', async () => {+ const id = await characterWithLockedAnchors(newId());+ const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local' });+ // Job terminal but the run still says 'rendering' — the server died between+ // the two. Reported immediately rather than after a wall-clock wait.+ queuedJobsById.set('mjob-1', { id: 'mjob-1', status: 'failed', error: 'oom' });+ const run = (await getWalkState(id)).runs.find((r) => r.id === runId);+ expect(run.status).toBe('error');+ expect(run.postprocessError).toMatch(/interrupted/);+ });++ it('leaves a local run alone when the queue has forgotten its job but the clock is young', async () => {+ const id = await characterWithLockedAnchors(newId());+ const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local' });+ queuedJobsById.delete('mjob-1');+ const run = (await getWalkState(id)).runs.find((r) => r.id === runId);+ expect(run.status).toBe('rendering');+ });++ it('reports a local attach that found no clip in local terms, not grok terms', async () => {+ const id = await characterWithLockedAnchors(newId());+ const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local' });+ await attachTuiWalkResult(id, runId, join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4'));+ const stored = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json'), 'utf8'));+ expect(stored.status).toBe('error');+ expect(stored.postprocessError).toMatch(/Render Queue/);+ expect(stored.postprocessError).not.toMatch(/shell session/);+ });++ it('runs the SAME deterministic postprocess on a local clip as on a grok one', async () => {+ const id = await characterWithLockedAnchors(newId());+ const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local' });+ const videoAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4');+ await writeFile(videoAbs, 'local-rendered-clip');+ runWalkPostprocess.mockClear();+ await attachTuiWalkResult(id, runId, videoAbs);+ expect(runWalkPostprocess).toHaveBeenCalledTimes(1);+ const stored = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json'), 'utf8'));+ expect(stored.status).toBe('candidate');+ // Provenance survives packaging, so an approved frame set still names the+ // model that produced it.+ expect(stored.provider).toBe('minimax-h3-local');+ expect(stored.videoModelId).toBe('minimax_h3_8bit');+ });+});+describe('attachTuiWalkResult (grok-tui completion)', () => {// Write a source video directly into a run's generated dir (grok's TUI run// saves it there in production) and return its abs path.@@ -1792,6 +2001,28 @@ describe('listSpriteAssets run-intermediate exclusion', () => {});});+describe('getWalkState — run directory with no readable record', () => {+ it('skips the orphan instead of failing the whole read', async () => {+ // A run directory can exist with no `animation-run.json`: the server died+ // between creating it and writing the record, or a partial copy landed. The+ // scan used to keep that null (`isWalkRun(null)` is true, since a run with no+ // `track` IS a walk run) and then dereference `.id` on it — taking the entire+ // walk panel down with a 500 for one stray directory.+ const id = await characterWithLockedAnchors(newId());+ await mkdir(join(TEST_ROOT, 'sprites', id, 'runs', 'walk-east-orphaned', 'generated'), { recursive: true });+ const state = await getWalkState(id);+ expect(state.runs).toEqual([]);+ });++ it('still surfaces the healthy runs alongside an orphan directory', async () => {+ const id = await characterWithLockedAnchors(newId());+ const { runId } = await makeCandidateRun(id, 'east');+ await mkdir(join(TEST_ROOT, 'sprites', id, 'runs', 'walk-east-orphaned2', 'generated'), { recursive: true });+ const state = await getWalkState(id);+ expect(state.runs.map((r) => r.id)).toEqual([runId]);+ });+});+describe('getWalkState', () => {it('returns empty state for a fresh character and newest-first runs', async () => {const id = await characterWithLockedAnchors(newId(), ['east', 'west']);diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex 51a651d216..0039a6fd3b 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -995,10 +995,31 @@ export async function extractVideoFrames(videoPath, rawDir) {* signatureOf uses) — correct and fast over a ~1.7M-pixel anchor without a* per-pixel JS loop. `hexToRgb` returns `{ r, g, b }`, exactly flatten's shape.*/-export async function prepareWalkAnchorChromaInput(anchorAbs, destAbs, chromaKey) {- const buf = await sharp(anchorAbs).flatten({ background: hexToRgb(chromaKey) }).png().toBuffer();+export async function prepareWalkAnchorChromaInput(anchorAbs, destAbs, chromaKey, chooseCanvas = null) {+ const background = hexToRgb(chromaKey);+ const image = sharp(anchorAbs).flatten({ background });+ let preparation = 'composited-over-solid-chroma-matte';+ let canvas = null;+ // Local-lane only (#4876). A cloud i2v model animates whatever aspect it is+ // handed, but a local runtime renders on ONE of a few trained canvases and+ // videoGen conforms the conditioning image to it with a center CROP — which+ // would slice the head and feet off a portrait sprite anchor before the render+ // began. Padding to the chosen canvas with the SAME matte color makes that+ // crop a no-op: the character survives whole, and the added margin is more of+ // exactly the background the postprocess keys out. The grok lane passes no+ // chooser and is byte-identical to before.+ if (chooseCanvas) {+ const { width, height } = await sharp(anchorAbs).metadata();+ const chosen = chooseCanvas({ width, height });+ if (chosen?.width > 0 && chosen?.height > 0) {+ canvas = chosen;+ image.resize({ width: canvas.width, height: canvas.height, fit: 'contain', background });+ preparation = 'composited-over-solid-chroma-matte-padded-to-render-canvas';+ }+ }+ const buf = await image.png().toBuffer();await writeFile(destAbs, buf);- return { preparation: 'composited-over-solid-chroma-matte', sha256: sha256Buffer(buf) };+ return { preparation, sha256: sha256Buffer(buf), canvas };}/**