Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
sprite walk: observable grok-tui generation + chroma-matte input fix + selectable durations
[._.]/ Adam Eivy34cb8428c6eb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 196bc085d5..2eb5e53591 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,6 +20,12 @@- **Steer a directional-anchor re-roll with a correction note** — when a directional anchor comes out wrong (say the north-east pose grew a pocket on the arm that has none in every other view), re-rolling it with the same inputs tended to just reproduce the same mistake. Each unlocked anchor tile now has a small **Correction (optional)** box: type what to fix ("no pocket on the right sleeve") and hit **Regenerate**, and the note is appended to that pose's prompt as an explicit override so the new render actually diverges. The button reads **Generate** on the first render and **Regenerate** once candidates exist, the correction is per-direction (so eight different fixes don't collide), and it rides into the candidate's saved prompt so the image preview shows exactly what was asked for. Main-reference iteration is unchanged — it already has its own design-prompt box.- **Locking a main reference no longer leaves a colored halo around the character** — when you lock a character's main reference, PortOS re-keys the background to whichever chroma color (magenta, green, or blue) sits farthest from the character's own palette. If that swapped the background — e.g. a magenta render re-keyed onto blue — the anti-aliased pixels along the character's outline kept their old magenta tint and showed up as a faint magenta ring against the new blue backdrop. Locking now cleans those edge pixels as it re-keys, so the outline blends into the new background with no leftover halo. Already-locked references (which are immutable and can't be re-locked) are healed automatically on upgrade: each one is re-derived from its saved candidate with the fix applied, and its stored checksum is refreshed — no action needed on your part.+- **Generate Walk is faster, more reliable, and you can watch grok do it** — the walk-cycle generator got three fixes and a new window into the render:+ - **Watch grok in the Shell.** Clicking **Generate walk** now runs grok as a live, interactive TUI session instead of a headless background job. The direction's card shows a **Watch in Shell** link while it renders — click it to pop into the Shell page, watch grok animate the frames in real time, and (if it goes off the rails) type to course-correct or Stop it. The session goes away once the clip is rendered and the deterministic packaging takes over.+ - **Shorter clips.** Walk clip length is now selectable from **1 / 2 / 3 / 6 / 10 seconds and defaults to 2s** (was 6s/10s only). A looping walk cycle only needs one gait (~8 frames), so a 2s clip renders in a fraction of the time — the old 6s default took ~10 minutes to render a clip we harvest 8 frames from.+ - **Fixed the "not a usable matte" failure.** Grok clips that faded in from a black frame, or rendered a slightly off-magenta background, used to fail packaging outright with `Measured background [0,0,0] is not a usable #FF00FF matte` — throwing away a perfectly good clip. The postprocess now drops black lead-in/out frames and tolerates grok's real-world magenta. The deeper cause is also fixed: we now hand grok the character **on its magenta matte** (the anchor already has it) instead of a transparent cut-out it had to composite over black and re-invent a background for — so the rendered clip keys out cleanly.+ - **A failed render isn't a dead end.** If packaging still fails, the card now plays grok's raw clip inline (alongside the error and a Retry) so you can see exactly what grok produced instead of staring at an error string.+- **See — and copy — the prompt behind any sprite image** — click a reference-set image (the frozen main, a locked directional anchor, or any generation candidate) and the enlarged preview now shows the exact prompt that produced it, with a one-click **Copy prompt** button, the same way the image render-history preview does. The asset inspector gains the same prompt block, so a walk-animation clip or any generated asset you open there shows its prompt too. Older images generated before this shipped still show their prompt — it's reconstructed from the render's recorded design description, direction, and background color — so nothing in your existing library is blank. Imported artwork and internal metadata files simply omit the block. New endpoint `GET /api/sprites/:id/asset-prompt`.- **Seed a character's main reference from an existing sprite, an upload, or your render history — and fork a character from its reference** — the "design image (optional)" upload on the main-reference form is now a three-way **Reference image** picker: upload a file, pick one from your image render-history gallery, or pick another sprite that already has a locked reference, each with a fidelity slider controlling how tightly the render follows it (image+text→image). Separately, a locked reference is immutable and can never be regenerated — so a character with a frozen main now shows a **Fork from this reference** button that spins up a brand-new character whose main is generated from this one's reference plus a prompt describing the change ("same character but in a red coat"), then opens the new sprite. New endpoints `GET /api/sprites/reference-sources` and `POST /api/sprites/:id/fork`.- **The Sprite Manager opens on a full Library catalog, with rename and delete built in** — landing on the Sprite Manager now shows the **Library** itself: a searchable, grouped grid of every character/place/object, each card carrying a real preview thumbnail — a character's locked main reference, or, for a place/object (or a character with no reference yet), the first image asset on disk, falling back to a kind icon only when there's no image at all — instead of jumping you straight into one sprite. The catalog is the `/sprites` route (not a modal buried behind a button), so it's directly linkable, and each card gives you full record control: click to open it, the pencil to **rename** in place (for records whose generated name you want to fix), or the trash to **delete** behind a cautious inline Cancel/Delete confirm (a delete drops the record from your library; its files stay on disk and its id stays reserved). The same **rename** and **delete** controls sit in a sprite's detail header, so you can fix or remove the one you're looking at without going back to the grid (deleting it returns you there). Search, **New Sprite**, and **Import** live in the page header (New Sprite/Import are modals), the left sidebar is gone so the catalog and detail panes run full width, and opening a sprite shows a **Library** link back to the grid. The per-character workspace tab that used to read "Library" is now **Assets**, since "Library" means the catalog. New endpoint `GET /api/sprites/thumbnails`.diff --git a/PLAN.md b/PLAN.mdindex 9a1edd123e..61d91ddf0b 100644--- a/PLAN.md+++ b/PLAN.md@@ -309,3 +309,4 @@ is not reliably announced.only the rules the repo already honors (`jsx-a11y/alt-text`,`jsx-a11y/aria-props`, `jsx-a11y/role-has-required-aria-props`,`jsx-a11y/label-has-associated-control`) rather than the full `recommended` set.+diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex ba6e4806b8..ae5a6b0800 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -1,5 +1,6 @@import { useEffect, useMemo, useState } from 'react';-import { Check, Film, RefreshCw, Scissors, Lock, Unlock } from 'lucide-react';+import { Link } from 'react-router-dom';+import { Check, Film, RefreshCw, Scissors, Lock, Unlock, Terminal } from 'lucide-react';import toast from '../ui/Toast';import { approveSpriteWalk, postprocessSpriteWalk, unlockSpriteWalk } from '../../services/apiSprites.js';import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';@@ -23,7 +24,10 @@ const LOOP_KEYFRAMES = '@keyframes sprite-walk-loop { to { background-position-x// Exported so the Sprites page can seed the lifted `duration` state with the// same default — the asset collection's Regenerate must honor whatever the// user picked here rather than silently falling back to the server default.-export const WALK_DURATIONS = [6, 10];+// A looping walk cycle only needs one gait cycle (~8 frames), so short clips+// render much faster; the default is deliberately short.+export const WALK_DURATIONS = [1, 2, 3, 6, 10];+export const WALK_DEFAULT_DURATION = 2;/*** Strip geometry for a preview/trim UI, defaulting to the native 8-phase@@ -80,6 +84,12 @@ function DirectionCard({}) {const [confirming, setConfirming] = useState(false);const candidate = run?.status === 'candidate' ? run : null;+ // grok renders as an observable TUI session while status is 'rendering'; the+ // deterministic packaging follows as 'postprocessing'. Both block a second+ // Generate (server truth, since the client pending flag drops once the run is+ // persisted). Only 'rendering' has a live Shell session to link to.+ const rendering = run?.status === 'rendering';+ const busy = pending || rendering || run?.status === 'postprocessing';// Any run that carries a packed strip preview is trimmable — the trim service// resolves geometry from the run's own manifest/stripPreview regardless of// on-disk layout (native `runs/`, legacy `grok/`, imported `runs/`, or an@@ -88,7 +98,7 @@ function DirectionCard({// non-destructive derived artifact under `walk/trims/`.const trimmable = Boolean(run?.stripPreview?.stripPath);const statusLabel = approved ? 'approved'- : pending ? 'rendering…'+ : (pending || rendering) ? 'rendering…': run?.status === 'postprocessing' ? 'packaging…': run?.status || (anchorLocked ? 'ready' : 'anchor not locked');@@ -105,11 +115,39 @@ function DirectionCard({<StripLoop recordId={recordId} stripPreview={run.stripPreview} />)}+ {/* grok animates in an observable TUI session — link into the Shell page+ to watch it, and (if needed) type to course-correct or Stop it. The+ session exists only while the render is live ('rendering'). */}+ {rendering && run?.shellSession && (+ <Link+ to={`/shell/${run.shellSession}`}+ title="Watch grok render this walk in the Shell (observe / course-correct / stop)"+ className="flex items-center gap-1 w-full justify-center px-2 py-0.5 text-xs bg-port-card border border-port-accent rounded text-port-accent hover:bg-port-accent hover:text-white"+ >+ <Terminal className="w-3 h-3" /> Watch in Shell+ </Link>+ )}+{/* Retry also covers a run wedged at 'postprocessing' (crash betweenthe video copy and the packaged save) — the endpoint is thedocumented recovery path and validates readiness server-side. */}{(run?.status === 'error' || run?.status === 'postprocessing') && (<div className="space-y-1">+ {/* Even when packaging failed, grok still produced a clip — show it so+ the render isn't a dead end. The raw clip carries its own magenta+ matte (not transparent), so no checkerboard behind it. */}+ {run.status === 'error' && run.sourceVideoPath && (+ <video+ src={spriteAssetUrl(recordId, run.sourceVideoPath)}+ className="w-full rounded border border-port-border"+ autoPlay+ loop+ muted+ playsInline+ controls+ aria-label={`raw grok walk clip (${direction})`}+ />+ )}{run.status === 'error' && (<p className="text-[10px] text-port-error break-words">{run.postprocessError || 'postprocess failed'}</p>)}@@ -123,12 +161,12 @@ function DirectionCard({<div className="space-y-1.5"><buttononClick={() => onGenerate(direction)}- disabled={!anchorLocked || pending}+ disabled={!anchorLocked || busy}title={anchorLocked ? undefined : 'Lock this direction\'s reference anchor first'}className="flex items-center gap-1 w-full justify-center px-2 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50">- {pending- ? <><RefreshCw className="w-3 h-3 animate-spin" /> Rendering…</>+ {busy+ ? <><RefreshCw className="w-3 h-3 animate-spin" /> {run?.status === 'postprocessing' ? 'Packaging…' : 'Rendering…'}</>: <><Film className="w-3 h-3" /> {candidate ? 'Regenerate' : 'Generate walk'}</>}</button>{candidate && (@@ -187,31 +225,34 @@ export default function WalkWorkflow({// there too, so both entry points submit through one code path.const { pendingJobs } = renders;- // The deterministic postprocess runs server-side AFTER the video job- // completes (frame extraction + per-pixel un-key can take many seconds on- // slower machines) — the job-completion sweeps alone can both land while a- // run is still 'postprocessing', which would strand the card on- // "packaging…" forever. Keep refreshing until no run is packaging. A run- // still 'queued' with no live job is an attach waiting behind the record's- // write tail (e.g. a long rerun ahead of it) — poll for that too, but give- // up after ~60s so a genuinely dead job doesn't poll indefinitely.+ // Keep the card in sync with server-side run progress. Three long-ish states+ // need polling: 'rendering' (the observable grok-tui clip render, up to+ // ~10 min — the client pending flag drops as soon as the run persists, so+ // this poll is what carries the card through the render), 'postprocessing'+ // (the deterministic frame-extraction/un-key, seconds-to-minutes), and a+ // stale 'queued' with no live job (an attach waiting behind the write tail —+ // bounded to ~60s so a genuinely dead job doesn't poll forever). 'rendering'+ // and 'postprocessing' are legitimately long, so they poll unbounded until+ // they flip (executeTuiRun's 30-min hard cap guarantees 'rendering' resolves).// Booleans (not the runs array) as deps: refetches produce fresh array// identities every 4s, which would otherwise reset the bounded tick count.- const packaging = runs.some((r) => r.status === 'postprocessing');+ // 'rendering' and 'postprocessing' are legitimately long — poll unbounded+ // until they flip; only the stale-'queued' case is bounded (~60s).+ const unbounded = runs.some((r) => r.status === 'rendering' || r.status === 'postprocessing');const awaitingAttach = runs.some((r) => r.status === 'queued' && !pendingJobs[r.direction]);useEffect(() => {- if (!packaging && !awaitingAttach) return undefined;+ if (!unbounded && !awaitingAttach) return undefined;let ticks = 0;const timer = setInterval(() => {ticks += 1;- if (!packaging && ticks > 15) {+ if (!unbounded && ticks > 15) {clearInterval(timer);return;}onChanged();}, 4000);return () => clearInterval(timer);- }, [packaging, awaitingAttach, onChanged]);+ }, [unbounded, awaitingAttach, onChanged]);const latestRunByDirection = useMemo(() => {const byDir = {};diff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsxindex c7d06e5675..db8427a25a 100644--- a/client/src/components/sprites/WalkWorkflow.test.jsx+++ b/client/src/components/sprites/WalkWorkflow.test.jsx@@ -1,5 +1,6 @@import { describe, it, expect, vi } from 'vitest';import { render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';// Coverage for the walk viewer's loop preview (#2924). The load-bearing behavior:// the stepped background animation is derived from the packaged strip's own@@ -129,3 +130,72 @@ describe('WalkWorkflow loop trimmer link', () => {expect(onOpenTrimmer).toHaveBeenCalledWith('run-east');});});++// Render the workflow with a single run of the given shape. Router-wrapped so+// the card's <Link> (shown while rendering) resolves in every case.+const renderRun = (run) => render(+ <MemoryRouter>+ <WalkWorkflow+ record={{ id: 'example-walker' }}+ reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}+ walk={{ runs: [run], selection: { directions: {} }, walkSet: null }}+ renders={noRenders()}+ duration={2}+ onDurationChange={vi.fn()}+ onGenerate={vi.fn()}+ onChanged={vi.fn()}+ />+ </MemoryRouter>,+);++describe('WalkWorkflow failed-run clip', () => {+ it('renders grok\'s raw clip and the error text when postprocess failed', () => {+ renderRun({+ id: 'walk-east-deadbeef', direction: 'east', status: 'error',+ postprocessError: 'Measured background [0,0,0] is not a usable #FF00FF matte',+ sourceVideoPath: 'runs/walk-east-deadbeef/generated/source-video.mp4',+ });+ const video = screen.getByLabelText('raw grok walk clip (east)');+ expect(video.getAttribute('src')).toBe(+ '/data/sprites/example-walker/runs/walk-east-deadbeef/generated/source-video.mp4',+ );+ expect(screen.getByText(/not a usable #FF00FF matte/)).toBeTruthy();+ expect(screen.getByRole('button', { name: /Retry postprocess/ })).toBeTruthy();+ });++ it('shows only the error text when no clip landed', () => {+ renderRun({+ id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'boom',+ });+ expect(screen.queryByLabelText('raw grok walk clip (east)')).toBeNull();+ expect(screen.getByText('boom')).toBeTruthy();+ });+});++describe('WalkWorkflow observable render', () => {+ it('links to the live Shell session while grok is rendering', () => {+ renderRun({+ id: 'walk-east-abc12345', direction: 'east', status: 'rendering', shellSession: 'walk-east-abc12345',+ });+ const link = screen.getByRole('link', { name: /Watch in Shell/ });+ expect(link.getAttribute('href')).toBe('/shell/walk-east-abc12345');+ // Generate is disabled while rendering (server truth), showing the spinner.+ expect(screen.getByRole('button', { name: /Rendering/ })).toBeDisabled();+ });++ it('shows no shell link once the render has moved on to packaging', () => {+ renderRun({+ id: 'walk-east-abc12345', direction: 'east', status: 'postprocessing', shellSession: 'walk-east-abc12345',+ });+ expect(screen.queryByRole('link', { name: /Watch in Shell/ })).toBeNull();+ });+});++describe('WalkWorkflow clip-length options', () => {+ it('offers the short clip lengths for an unfinalized set', () => {+ renderRun({ id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'x' });+ const select = screen.getByRole('combobox');+ const values = [...select.options].map((o) => o.value);+ expect(values).toEqual(['1', '2', '3', '6', '10']);+ });+});diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex 1be16d4fee..16db35dc21 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -12,7 +12,7 @@ import { getSettings } from '../services/apiSystem.js';import { deriveAvailableBackends } from '../lib/imageGenBackends.js';import AppContextPicker from '../components/AppContextPicker.jsx';import ReferenceWorkflow from '../components/sprites/ReferenceWorkflow.jsx';-import WalkWorkflow, { WALK_DURATIONS } from '../components/sprites/WalkWorkflow.jsx';+import WalkWorkflow, { WALK_DEFAULT_DURATION } from '../components/sprites/WalkWorkflow.jsx';import LoopTrimmer from '../components/sprites/LoopTrimmer.jsx';import PublishWorkflow from '../components/sprites/PublishWorkflow.jsx';import AssetCollection from '../components/sprites/AssetCollection.jsx';@@ -456,7 +456,7 @@ export default function Sprites() {// Clip length lives here rather than inside WalkWorkflow so a Regenerate// fired from an asset card honors the length the user picked in the walk// panel instead of silently falling back to the server default.- const [duration, setDuration] = useState(WALK_DURATIONS[0]);+ const [duration, setDuration] = useState(WALK_DEFAULT_DURATION);// Image-backend availability + the selected backend `mode` are page-owned// (#2938): both ReferenceWorkflow's picker and the asset collection's anchor@@ -514,8 +514,11 @@ export default function Sprites() {const startId = idRef.current;begin(key);try {- const { jobId } = await call();- if (idRef.current === startId) resolve(key, jobId);+ // Anchor renders go through the media-job queue (jobId); the walk render+ // is an observable grok-tui run (runId, no media job). Either reserves+ // the key so a double-submit can't fire two paid renders.+ const result = await call();+ if (idRef.current === startId) resolve(key, result?.jobId || result?.runId);} catch (err) {if (idRef.current === startId) cancel(key);toast.error(err?.message || failMessage);diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex 3285d8010f..bef4619e74 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -99,12 +99,18 @@ const PTY_ROWS = 50;* AFTER this fires.* @param {number} [options.timeout] — hard cap on a single run (ms). Falls back to* `provider.timeout`, then `DEFAULT_TIMEOUT_MS`.+ * @param {number} [options.idleMs] — response-complete idle threshold (ms) for+ * THIS call, overriding `provider.tuiOneShotIdleMs` and the 8s default. The+ * default suits a chatty text reply that goes quiet within seconds; a task+ * that streams sparse output during a long operation (e.g. a multi-minute+ * grok `image_to_video` render) needs a larger value so a mid-work lull isn't+ * mistaken for completion. Pair with a larger `timeout`.* @param {string} [options.label] — human label for the live Shell view (the* run `source`, e.g. `'pipeline-manuscript-completeness'`). Surfaced in the* Shell page's session tab; falls back to `command · model` when absent.* @returns {Promise<void>}*/-export async function executeTuiRun({ runId, provider, prompt, workspacePath, onData, onComplete, timeout, label }) {+export async function executeTuiRun({ runId, provider, prompt, workspacePath, onData, onComplete, timeout, idleMs, label }) {if (!provider || typeof provider !== 'object') {throw new Error('executeTuiRun: provider is required');}@@ -114,7 +120,7 @@ export async function executeTuiRun({ runId, provider, prompt, workspacePath, onconst { command, args } = buildTuiInvocation(provider, provider.defaultModel);const promptDelayMs = provider.tuiPromptDelayMs ?? DEFAULT_TUI_PROMPT_DELAY_MS;- const idleThresholdMs = provider.tuiOneShotIdleMs ?? DEFAULT_ONE_SHOT_IDLE_MS;+ const idleThresholdMs = idleMs ?? provider.tuiOneShotIdleMs ?? DEFAULT_ONE_SHOT_IDLE_MS;const totalTimeoutMs = timeout ?? provider.timeout ?? DEFAULT_TIMEOUT_MS;const workingDir = (typeof workspacePath === 'string' && workspacePath) ? workspacePath : PATHS.root;diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 40fe35a26f..341f3f3217 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1095,9 +1095,11 @@ const spriteWalkRunIdSchema = z.string().regex(/^walk-[a-z-]+-[0-9a-f]{8}$/);export const spriteWalkGenerateSchema = z.object({direction: spriteWalkDirectionSchema,- // Grok image_to_video accepts exactly these lengths; the service defaults- // to the shorter clip when omitted.- duration: z.union([z.literal(6), z.literal(10)]).optional(),+ // Clip length in seconds (see GROK_VIDEO_DURATIONS). Short clips are ample+ // for a looping walk cycle; the walk service defaults to 2s when omitted.+ duration: z.union([+ z.literal(1), z.literal(2), z.literal(3), z.literal(6), z.literal(10),+ ]).optional(),});export const spriteWalkApproveSchema = z.object({diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex dd2c8004ef..f0091789ef 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -96,7 +96,6 @@ import { initMusicVideoSceneImageHook } from './musicVideoSceneImageHook.js';import { initMusicVideoSceneVideoHook } from './musicVideoSceneVideoHook.js';import { initCreativeDirectorMusicBedHook } from './creativeDirectorMusicBedHook.js';import { initSpriteReferenceImageHook } from './spriteReferenceImageHook.js';-import { initSpriteWalkVideoHook } from './spriteWalkVideoHook.js';import { initCreativeDirectorSceneImageHook } from './creativeDirectorSceneImageHook.js';import { initComicPagesFilenameHook } from './pipeline/comicPagesFilenameHook.js';import { initStoryboardsFilenameHook } from './pipeline/storyboardsFilenameHook.js';@@ -458,7 +457,6 @@ const initMediaJobDependentHooks = () => {// render into the sprite record's reference/candidates/ with a generation// sidecar (#2896).initSpriteReferenceImageHook();- initSpriteWalkVideoHook();// Creative Director scene-frame hook — durably files a queued first-pass// reference-frame render onto its project scene's `sourceImageFile` on// completion, even if no client is watching (#1867).diff --git a/server/services/spriteWalkVideoHook.js b/server/services/spriteWalkVideoHook.jsdeleted file mode 100644index faa0e79a7e..0000000000--- a/server/services/spriteWalkVideoHook.js+++ /dev/null@@ -1,45 +0,0 @@-/**- * Sprite walk-video attach hook (issue #2897, phase 3).- *- * Subscribes to mediaJobEvents and, for each completed VIDEO job carrying- * `params.spriteWalk`, copies the finished grok clip into that run's- * `runs/<runId>/generated/source-video.mp4` and runs the deterministic- * postprocess (frame harvest → un-key → cycle select → align → despill →- * strip/manifest) server-side — a slow cloud render still packages after the- * user navigated away. Runs accumulate as reviewable candidates (no- * newest-wins guard); per-record serialization lives in walk.js's write tail.- */--import { createMediaJobImageHook } from './mediaJobImageHook.js';-import { attachWalkVideo } from './sprites/walk.js';--const hook = createMediaJobImageHook({- label: 'sprite walk-video',- initLog: '🚶 Sprite walk-video hook initialized',- kind: 'video',- tagKey: 'spriteWalk',- // Grok video filenames are always `<jobId>.mp4`; the completed payload- // echoes it, with the job id as fallback (same contract as the- // music-video scene hook).- extractResult: (job) => {- const filename = (typeof job.result?.filename === 'string' && job.result.filename)- || (typeof job.id === 'string' ? `${job.id}.mp4` : null);- return filename ? { filename } : null;- },- identify: (tag, job) => (tag?.recordId && tag.direction && tag.runId- ? { ...tag, jobId: job?.id || null }- : null),- serializeKey: ({ recordId }) => recordId,- describe: ({ recordId, runId }) => `${recordId}/${runId}`,- attach: attachWalkVideo,- onAttached: ({ recordId, runId }, result) => {- console.log(`🚶 sprite walk run ${recordId}/${runId} → ${result?.status || 'attached'}`);- },-});--export function initSpriteWalkVideoHook() {- hook.init();-}--// Test-only reset so suites that re-init can do so cleanly.-export const __testing = hook.__testing;diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex 7a257ee9d7..64c7970bb0 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -18,15 +18,15 @@*/import { join } from 'path';-import { copyFile, readdir, rm } from 'fs/promises';+import { readdir, rm } from 'fs/promises';import { randomUUID } from 'crypto';import {- PATHS, ensureDir, atomicWrite, readJSONFile, pathExists, sha256File,+ ensureDir, atomicWrite, readJSONFile, pathExists, sha256File,} from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';-import { enqueueJob } from '../mediaJobQueue/index.js';-import { IMAGE_GEN_MODE } from '../imageGen/modes.js';+import { executeTuiRun } from '../../lib/tuiPromptRunner.js';+import { GROK_TUI_ID } from '../../lib/grok.js';import { getSettings } from '../settings.js';import { updateRecord } from './records.js';import {@@ -35,10 +35,23 @@ import {import { requireCharacter, loadManifest } from './reference.js';import { SPRITE_DIRECTIONS, anchorIdForDirection, buildWalkVideoPrompt } from './prompts.js';import {- prepareWalkAnchorInput, runWalkPostprocess, WALK_FPS, WALK_FRAME_COUNT, WALK_CELL_SIZE,+ prepareWalkAnchorChromaInput, runWalkPostprocess, WALK_FPS, WALK_FRAME_COUNT, WALK_CELL_SIZE,} from './walkPostprocess.js';import { GROK_VIDEO_DURATIONS } from '../videoGen/grok.js';+// Walk clips default SHORTER than general video gen: a looping walk cycle needs+// only ~8 frames of one gait, so a 2s clip renders far faster than the 6s+// general default while still giving the cycle selector plenty of frames.+const WALK_DEFAULT_DURATION = 2;++// grok's walk render runs as an OBSERVABLE TUI session (issue: user wants to+// watch/course-correct grok in the Shell) rather than a headless mediaJobQueue+// spawn. The idle threshold must be long enough that grok's narration lulls+// during the multi-minute image_to_video render aren't mistaken for completion;+// the hard cap mirrors the old headless GROK_VIDEO_TIMEOUT_MS.+const WALK_TUI_IDLE_MS = 90_000;+const WALK_TUI_TIMEOUT_MS = 30 * 60_000;+const selectionRelPath = (id) => `walk/${id}-walk-selection-v1.json`;// Exported: atlas.js (phase 4) reads the finalized walk set as compile input.export const walkSetRelPath = (id) => `walk/${id}-walk-set-v1.json`;@@ -329,9 +342,16 @@ export async function getWalkState(recordId) {}/**- * Queue one grok walk video for a direction whose anchor is locked.- * User-triggered only (route-invoked); exactly one image_to_video call per- * run — all derivatives are deterministic local work.+ * Start one observable grok walk-video render for a direction whose anchor is+ * locked. User-triggered only (route-invoked); exactly one image_to_video call+ * per run — all derivatives are deterministic local work.+ *+ * grok runs as an interactive TUI session (executeTuiRun) rather than a headless+ * job so the user can pop into the Shell page to watch it, and — if needed —+ * type to course-correct or Stop it. The session id IS the run id, so the walk+ * card can deep-link to `/shell/<runId>` the moment the render starts. The+ * render itself runs OUTSIDE the per-record write tail (a ~10-min PTY run must+ * not block other walk ops); its completion re-enters the tail to attach.*/export function startWalkGeneration(recordId, body) {return walkWriteTail(recordId, () => startWalkGenerationImpl(recordId, body));@@ -361,58 +381,133 @@ async function startWalkGenerationImpl(recordId, body) {const generatedAbs = join(runAbs, 'generated');await ensureDir(generatedAbs);- // Transparent i2v motion input derived from the locked anchor without- // mutating it (measured-key alpha recovery + despill).- const inputAbs = join(generatedAbs, 'input-anchor-transparent.png');- const { preparation, sha256: inputSha256 } = await prepareWalkAnchorInput(anchorAbs, inputAbs, chromaKey);-- const settings = await getSettings();- const duration = GROK_VIDEO_DURATIONS.includes(Number(body.duration)) ? Number(body.duration) : GROK_VIDEO_DURATIONS[0];+ // i2v motion input: the anchor composited onto the SOLID chroma matte grok+ // must animate over (NOT a transparent PNG — that made grok composite over+ // black and reinvent an off-spec magenta from the prompt text; see+ // 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),+ getSettings(),+ ]);+ const duration = GROK_VIDEO_DURATIONS.includes(Number(body.duration)) ? Number(body.duration) : WALK_DEFAULT_DURATION;const prompt = buildWalkVideoPrompt({ name: record.name, direction, chromaKey });+ const videoAbs = join(generatedAbs, 'source-video.mp4');+ const grokPath = settings.imageGen?.grok?.grokPath;- // Run record BEFORE enqueue: a crash between the two leaves an inert- // 'queued' run (harmless, regenerable) rather than a completed job the- // hook can't file.+ // Run record BEFORE the render starts: a crash between the two leaves an inert+ // 'rendering' run (harmless, regenerable) rather than a session the attach+ // can't file. `shellSession` is the id the walk card deep-links to.const now = new Date().toISOString();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.- provider: 'grok',- status: 'queued',+ provider: GROK_TUI_ID,+ status: 'rendering',id: runId,- jobId: null,+ // 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>.+ shellSession: runId,characterId: recordId,direction,chromaKey,+ duration,anchorPath: anchor.path,anchorSha256: anchor.sha256 || await sha256File(anchorAbs),- animationInputPath: `${runRel}/generated/input-anchor-transparent.png`,+ animationInputPath: `${runRel}/generated/input-anchor-chroma.png`,animationInputSha256: inputSha256,animationInputPreparation: preparation,createdAt: now,};await saveRunRecord(recordId, run);- const { jobId } = enqueueJob({- kind: 'video',- params: {- mode: IMAGE_GEN_MODE.GROK,- videoMode: 'image',- grokPath: settings.imageGen?.grok?.grokPath,- prompt,- sourceImagePath: inputAbs,- duration,- // Destination tag the completion hook files the video by.- spriteWalk: { recordId, direction, runId, chromaKey },- },- owner: 'sprites',+ // 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).+ runWalkTuiRender(recordId, {+ runId, direction, grokPath, task: buildWalkTuiTask({ 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 };+}++// The single-turn TUI task: reuse the shared motion/matte prompt, then point+// grok at the concrete input path and the exact MP4 output path. executeTuiRun+// wraps this with its "write your final response to the response file when done"+// instruction, so grok saves the MP4 first and its completion signal is the+// response file (with the long idle threshold as a backstop).+function buildWalkTuiTask({ prompt, inputAbs, videoAbs, duration }) {+ return `${prompt}\n\n`+ + `Use your built-in image_to_video tool to animate the image at this exact path for ${duration} seconds:\n${inputAbs}\n\n`+ + `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.';+}++/**+ * Drive the observable grok-tui render to completion, then attach its result.+ * executeTuiRun spawns grok in a PTY and registers it as a Shell session under+ * `runId`; its promise resolves on success OR failure, so the attach decides+ * outcome from whether the directed MP4 actually landed on disk.+ */+async function runWalkTuiRender(recordId, { runId, direction, grokPath, task, generatedAbs, videoAbs }) {+ // args:[] is intentional — buildTuiInvocation → applyCommandDefaults routes a+ // grok command through ensureGrokTuiArgs (adds --permission-mode bypassPermissions).+ const provider = { id: GROK_TUI_ID, type: 'tui', command: grokPath || 'grok', args: [] };+ await executeTuiRun({+ runId,+ provider,+ prompt: task,+ workspacePath: generatedAbs,+ idleMs: WALK_TUI_IDLE_MS,+ timeout: WALK_TUI_TIMEOUT_MS,+ label: `sprite walk ${recordId}/${direction}`,+ }).catch((err) => {+ console.error(`❌ sprite walk grok-tui run failed ${recordId}/${runId}: ${err?.message || err}`);});- run.jobId = jobId;+ await walkWriteTail(recordId, () => attachTuiWalkResult(recordId, runId, videoAbs));+}++/**+ * 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.+ */+export async function attachTuiWalkResult(recordId, runId, videoAbs) {+ const run = await loadRunRecord(recordId, runId);+ if (!run) {+ console.error(`❌ sprite walk run record missing for ${recordId}/${runId} — skipping attach`);+ return;+ }+ if (await loadWalkSet(recordId)) {+ console.error(`❌ sprite walk attach skipped for ${recordId}/${runId} — walk set is finalized`);+ return;+ }+ const selection = await loadSelection(recordId);+ if (selection?.directions?.[run.direction]?.runId === runId) {+ console.error(`❌ sprite walk attach skipped for ${recordId}/${runId} — run is approved (immutable)`);+ return;+ }+ if (!await pathExists(videoAbs)) {+ run.status = 'error';+ run.postprocessError = '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}`);+ return;+ }+ run.sourceVideoSha256 = await sha256File(videoAbs);+ run.status = 'postprocessing';+ await saveRunRecord(recordId, run);+ await packageRun(recordId, run);await saveRunRecord(recordId, run);- console.log(`🚶 sprite walk video queued ${recordId}/${runId} jobId=${jobId.slice(0, 8)}`);- return { jobId, runId, direction, duration };+ console.log(`🚶 sprite walk grok-tui run ${recordId}/${runId} → ${run.status}`);}/**@@ -424,6 +519,11 @@ async function startWalkGenerationImpl(recordId, body) {async function packageRun(recordId, run) {const runRel = runRelPath(run.id);const runAbs = join(spriteDir(recordId), runRel);+ // Record-relative path to grok's 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 attach + rerun) so a retry backfills it onto an older run too.+ run.sourceVideoPath = `${runRel}/generated/source-video.mp4`;try {const manifest = await loadManifest(recordId);const anchor = manifest?.anchors?.find((a) => a.direction === run.direction);@@ -451,54 +551,6 @@ async function packageRun(recordId, run) {run.completedAt = new Date().toISOString();}-/**- * Completion-hook attach: copy the finished grok video into the run root and- * run the deterministic postprocess. Errors are captured onto the run record- * (status 'error') so the UI can surface them — the hook context has no- * request to bubble to.- */-export function attachWalkVideo(ctx) {- return walkWriteTail(ctx.recordId, () => attachWalkVideoImpl(ctx));-}--async function attachWalkVideoImpl({ recordId, runId, filename, jobId }) {- const run = await loadRunRecord(recordId, runId);- if (!run) {- console.error(`❌ sprite walk run record missing for ${recordId}/${runId} — skipping attach`);- return null;- }- // Immutability guard, mirroring the rerun path: a Render Queue retry of a- // terminal job re-carries the spriteWalk tag, so a clip can land AFTER the- // run was approved (or the set finalized) — attaching would silently- // replace frozen evidence and break the selection's recorded sha256s.- if (await loadWalkSet(recordId)) {- console.error(`❌ sprite walk attach skipped for ${recordId}/${runId} — walk set is finalized`);- return null;- }- const selection = await loadSelection(recordId);- if (selection?.directions?.[run.direction]?.runId === runId) {- console.error(`❌ sprite walk attach skipped for ${recordId}/${runId} — run is approved (immutable)`);- return null;- }- const src = join(PATHS.videos, filename);- if (!await pathExists(src)) {- console.error(`❌ sprite walk video missing for ${recordId}/${runId} (${filename}) — skipping attach`);- return null;- }- const runAbs = join(spriteDir(recordId), runRelPath(runId));- const videoAbs = join(runAbs, 'generated', 'source-video.mp4');- await ensureDir(join(runAbs, 'generated'));- await copyFile(src, videoAbs);- run.jobId = run.jobId || jobId || null;- run.sourceVideoSha256 = await sha256File(videoAbs);- run.status = 'postprocessing';- await saveRunRecord(recordId, run);-- await packageRun(recordId, run);- await saveRunRecord(recordId, run);- return { runId, status: run.status };-}-/*** Re-run the deterministic postprocess for a run whose source video already* landed (crash recovery, or determinism verification). Approved/finalizeddiff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex 7af86aa5aa..f83afc6112 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -27,10 +27,14 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {return actual;});-const enqueueJob = vi.fn(() => ({ jobId: 'vid-job-1234567890', position: 0, status: 'queued' }));-vi.mock('../mediaJobQueue/index.js', () => ({- enqueueJob: (...args) => enqueueJob(...args),- mediaJobEvents: { on: () => {}, off: () => {} },+// Walk generation now runs grok as an observable TUI session (executeTuiRun)+// rather than a headless media-job. Default mock returns a promise that never+// resolves, so the fire-and-forget render started by startWalkGeneration does+// NOT race the test with a background attach; a happy-path test overrides it+// with mockImplementationOnce to simulate grok writing the MP4.+const executeTuiRun = vi.fn(() => new Promise(() => {}));+vi.mock('../../lib/tuiPromptRunner.js', () => ({+ executeTuiRun: (...args) => executeTuiRun(...args),}));vi.mock('../imageGen/index.js', () => ({@@ -45,12 +49,12 @@ vi.mock('../settings.js', () => ({// Keep the videoGen graph out of this mocked suite — only the duration// contract is consumed.-vi.mock('../videoGen/grok.js', () => ({ GROK_VIDEO_DURATIONS: [6, 10] }));+vi.mock('../videoGen/grok.js', () => ({ GROK_VIDEO_DURATIONS: [1, 2, 3, 6, 10] }));-const prepareWalkAnchorInput = vi.fn(async (_anchorAbs, destAbs) => {+const prepareWalkAnchorChromaInput = vi.fn(async (_anchorAbs, destAbs) => {await mkdir(join(destAbs, '..'), { recursive: true });- await writeFile(destAbs, 'stub-transparent-anchor');- return { preparation: 'measured-key-alpha-recovery-plus-despill' };+ await writeFile(destAbs, 'stub-chroma-anchor');+ return { preparation: 'composited-over-solid-chroma-matte' };});const runWalkPostprocess = vi.fn(async ({ runRel }) => ({manifestPath: `${runRel}/generated/manifest.json`,@@ -60,7 +64,7 @@ vi.mock('./walkPostprocess.js', async (importOriginal) => {const actual = await importOriginal();return {...actual,- prepareWalkAnchorInput: (...args) => prepareWalkAnchorInput(...args),+ prepareWalkAnchorChromaInput: (...args) => prepareWalkAnchorChromaInput(...args),runWalkPostprocess: (...args) => runWalkPostprocess(...args),};});@@ -69,7 +73,7 @@ const records = await import('./records.js');const { listSpriteAssets } = await import('./paths.js');const { lockReference } = await import('./reference.js');const {- getWalkState, startWalkGeneration, attachWalkVideo, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,+ getWalkState, startWalkGeneration, attachTuiWalkResult, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,} = await import('./walk.js');const { SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS } = await import('./prompts.js');@@ -116,8 +120,9 @@ async function makeCandidateRun(recordId, direction, { stripBytes = `strip-${dir}beforeEach(() => {- enqueueJob.mockClear();- prepareWalkAnchorInput.mockClear();+ executeTuiRun.mockClear();+ executeTuiRun.mockImplementation(() => new Promise(() => {}));+ prepareWalkAnchorChromaInput.mockClear();runWalkPostprocess.mockClear();rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });});@@ -131,125 +136,131 @@ describe('startWalkGeneration', () => {.rejects.toMatchObject({ code: 'ANCHOR_NOT_LOCKED' });});- it('queues a grok i2v job with the spriteWalk tag off a locked anchor', async () => {+ it('starts an observable grok-tui render off a locked anchor', async () => {const id = await characterWithLockedAnchors(newId(), ['east']);const result = await startWalkGeneration(id, { direction: 'east' });- expect(result.jobId).toBe('vid-job-1234567890');expect(result.runId).toMatch(/^walk-east-[0-9a-f]{8}$/);- expect(result.duration).toBe(6);-- const call = enqueueJob.mock.calls[0][0];- expect(call.kind).toBe('video');- expect(call.owner).toBe('sprites');- expect(call.params.mode).toBe('grok');- expect(call.params.videoMode).toBe('image');- expect(call.params.grokPath).toBe('/usr/local/bin/grok');- expect(call.params.sourceImagePath).toBe(- join(TEST_ROOT, 'sprites', id, 'runs', result.runId, 'generated', 'input-anchor-transparent.png'),- );- expect(call.params.prompt).toContain('walking east');- expect(call.params.prompt).toContain('magenta (#FF00FF)');- expect(call.params.spriteWalk).toEqual({ recordId: id, direction: 'east', runId: result.runId, chromaKey: '#FF00FF' });-- // Transparent input was prepared from the locked anchor, and the run- // record persisted with the queue job id.- expect(prepareWalkAnchorInput).toHaveBeenCalledOnce();+ expect(result.duration).toBe(2); // walk default (WALK_DEFAULT_DURATION)+ // The shell session id is the run id, so the card can deep-link to /shell/<id>.+ expect(result.shellSession).toBe(result.runId);++ // grok runs as a TUI session (not a media job) so the user can watch it.+ expect(executeTuiRun).toHaveBeenCalledOnce();+ const call = executeTuiRun.mock.calls[0][0];+ expect(call.runId).toBe(result.runId);+ expect(call.provider).toMatchObject({ id: 'grok-tui', type: 'tui', command: '/usr/local/bin/grok' });+ expect(call.workspacePath).toBe(join(TEST_ROOT, 'sprites', id, 'runs', result.runId, 'generated'));+ // The task points grok at the chroma-backed input and the exact MP4 path.+ expect(call.prompt).toContain('walking east');+ expect(call.prompt).toContain('magenta (#FF00FF)');+ expect(call.prompt).toContain(join(TEST_ROOT, 'sprites', id, 'runs', result.runId, 'generated', 'input-anchor-chroma.png'));+ expect(call.prompt).toContain(join(TEST_ROOT, 'sprites', id, 'runs', result.runId, 'generated', 'source-video.mp4'));+ expect(call.idleMs).toBeGreaterThan(8000); // longer than the default one-shot idle++ // Chroma-backed input prepared from the anchor; run persisted as 'rendering'+ // with the shell session id.+ expect(prepareWalkAnchorChromaInput).toHaveBeenCalledOnce();const { runs } = await getWalkState(id);expect(runs).toHaveLength(1);expect(runs[0]).toMatchObject({- id: result.runId, status: 'queued', jobId: 'vid-job-1234567890', direction: 'east', chromaKey: '#FF00FF',+ id: result.runId, status: 'rendering', provider: 'grok-tui', shellSession: result.runId,+ direction: 'east', chromaKey: '#FF00FF',});- expect(runs[0].animationInputPreparation).toBe('measured-key-alpha-recovery-plus-despill');+ expect(runs[0].animationInputPreparation).toBe('composited-over-solid-chroma-matte');});- it('animates south straight off the frozen main and honors duration 10', async () => {+ it('honors duration 10 (passed to the grok task)', async () => {const id = await characterWithLockedAnchors(newId(), []);const result = await startWalkGeneration(id, { direction: 'south', duration: 10 });expect(result.duration).toBe(10);- expect(enqueueJob.mock.calls[0][0].params.duration).toBe(10);+ expect(executeTuiRun.mock.calls[0][0].prompt).toContain('for 10 seconds');});-});-describe('attachWalkVideo (completion hook)', () => {- async function queuedRun(id) {- const { runId } = await startWalkGeneration(id, { direction: 'east' });- await mkdir(join(TEST_ROOT, 'videos'), { recursive: true });- await writeFile(join(TEST_ROOT, 'videos', 'vid-job-1234567890.mp4'), 'fake-mp4-bytes');- return runId;- }+ it('honors a short 2s clip length', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const result = await startWalkGeneration(id, { direction: 'east', duration: 2 });+ expect(result.duration).toBe(2);+ expect(executeTuiRun.mock.calls[0][0].prompt).toContain('for 2 seconds');+ });- it('copies the video into the run and records the packaged candidate', async () => {+ it('packages the candidate once grok writes the clip (full render→attach)', async () => {const id = await characterWithLockedAnchors(newId(), ['east']);- const runId = await queuedRun(id);- const result = await attachWalkVideo({- recordId: id, direction: 'east', runId, filename: 'vid-job-1234567890.mp4', jobId: 'vid-job-1234567890',+ // Simulate grok saving the MP4 to the directed path, then finishing.+ executeTuiRun.mockImplementationOnce(async ({ workspacePath }) => {+ await writeFile(join(workspacePath, 'source-video.mp4'), 'grok-clip-bytes');+ });+ const { runId } = await startWalkGeneration(id, { direction: 'east' });+ // The render + attach run fire-and-forget after generation returns.+ await vi.waitFor(async () => {+ const { runs } = await getWalkState(id);+ expect(runs[0].status).toBe('candidate');});- expect(result).toEqual({ runId, status: 'candidate' });expect(runWalkPostprocess).toHaveBeenCalledOnce();- const ppArgs = runWalkPostprocess.mock.calls[0][0];- expect(ppArgs).toMatchObject({ recordId: id, direction: 'east', chromaKey: '#FF00FF', runRel: `runs/${runId}` });- const video = await readFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4'), 'utf8');- expect(video).toBe('fake-mp4-bytes');const { runs } = await getWalkState(id);expect(runs[0]).toMatchObject({- status: 'candidate',- postprocessManifest: `runs/${runId}/generated/manifest.json`,+ id: runId, status: 'candidate', postprocessManifest: `runs/${runId}/generated/manifest.json`,});- expect(runs[0].stripPreview.frameCount).toBe(8);- expect(runs[0].sourceVideoSha256).toBe(sha256(Buffer.from('fake-mp4-bytes')));+ expect(runs[0].sourceVideoSha256).toBe(sha256(Buffer.from('grok-clip-bytes')));});- it('captures a postprocess failure on the run record instead of throwing', async () => {+ it('marks the run errored when grok finishes without a clip', async () => {const id = await characterWithLockedAnchors(newId(), ['east']);- const runId = await queuedRun(id);- runWalkPostprocess.mockRejectedValueOnce(new Error('no detectable moving walk cycle'));- const result = await attachWalkVideo({- recordId: id, direction: 'east', runId, filename: 'vid-job-1234567890.mp4',+ executeTuiRun.mockImplementationOnce(async () => {}); // resolves, writes no MP4+ await startWalkGeneration(id, { direction: 'east' });+ await vi.waitFor(async () => {+ const { runs } = await getWalkState(id);+ expect(runs[0].status).toBe('error');});- expect(result.status).toBe('error');const { runs } = await getWalkState(id);- expect(runs[0].status).toBe('error');- expect(runs[0].postprocessError).toMatch(/walk cycle/);+ expect(runs[0].postprocessError).toMatch(/without writing the walk video/);+ expect(runWalkPostprocess).not.toHaveBeenCalled();});+});- it('refuses to attach onto an approved run (Render Queue retry can re-fire the tag)', async () => {+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.+ async function landVideo(id, runId, bytes = 'grok-clip') {+ const videoAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4');+ await mkdir(join(videoAbs, '..'), { recursive: true });+ await writeFile(videoAbs, bytes);+ return videoAbs;+ }++ it('refuses to attach onto an approved run (a late render must not overwrite frozen evidence)', async () => {const id = await characterWithLockedAnchors(newId(), ['east']);const { runId } = await makeCandidateRun(id, 'east');await approveWalkDirection(id, { direction: 'east', runId });- await mkdir(join(TEST_ROOT, 'videos'), { recursive: true });- await writeFile(join(TEST_ROOT, 'videos', 'retry-clip.mp4'), 'retried');+ const videoAbs = await landVideo(id, runId, 'late');runWalkPostprocess.mockClear();- expect(await attachWalkVideo({ recordId: id, direction: 'east', runId, filename: 'retry-clip.mp4' })).toBeNull();+ await attachTuiWalkResult(id, runId, videoAbs);expect(runWalkPostprocess).not.toHaveBeenCalled();- // The frozen artifacts were not touched.const { runs } = await getWalkState(id);- expect(runs.find((r) => r.id === runId).status).toBe('candidate');+ expect(runs.find((r) => r.id === runId).status).toBe('candidate'); // untouched});it('refuses to attach after the walk set is finalized', async () => {const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);for (const direction of SPRITE_DIRECTIONS) {const { runId } = await makeCandidateRun(id, direction);- await approveWalkDirection(id, { direction, runId });+ await approveWalkDirection(id, { direction, runId }); // eslint-disable-line no-await-in-loop}- // A stale queued run whose clip lands after finalization must not attach.const staleRunId = 'walk-east-0badc0de';- await mkdir(join(TEST_ROOT, 'sprites', id, 'grok', staleRunId), { recursive: true });- await writeFile(join(TEST_ROOT, 'sprites', id, 'grok', staleRunId, 'animation-run.json'), JSON.stringify({- schemaVersion: 1, id: staleRunId, status: 'queued', characterId: id, direction: 'east', chromaKey: '#FF00FF',+ await mkdir(join(TEST_ROOT, 'sprites', id, 'runs', staleRunId, 'generated'), { recursive: true });+ await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', staleRunId, 'animation-run.json'), JSON.stringify({+ schemaVersion: 1, id: staleRunId, status: 'rendering', characterId: id, direction: 'east', chromaKey: '#FF00FF',}));- await mkdir(join(TEST_ROOT, 'videos'), { recursive: true });- await writeFile(join(TEST_ROOT, 'videos', 'late-clip.mp4'), 'late');+ const videoAbs = await landVideo(id, staleRunId, 'late');runWalkPostprocess.mockClear();- expect(await attachWalkVideo({ recordId: id, direction: 'east', runId: staleRunId, filename: 'late-clip.mp4' })).toBeNull();+ await attachTuiWalkResult(id, staleRunId, videoAbs);expect(runWalkPostprocess).not.toHaveBeenCalled();});- it('skips silently when the run record or video is missing', async () => {+ it('skips silently when the run record is missing', async () => {const id = await characterWithLockedAnchors(newId(), ['east']);- expect(await attachWalkVideo({ recordId: id, direction: 'east', runId: 'walk-east-deadbeef', filename: 'x.mp4' })).toBeNull();- const runId = await queuedRun(id);- expect(await attachWalkVideo({ recordId: id, direction: 'east', runId, filename: 'not-there.mp4' })).toBeNull();+ const videoAbs = await landVideo(id, 'walk-east-deadbeef');+ await attachTuiWalkResult(id, 'walk-east-deadbeef', videoAbs); // no throw+ expect(runWalkPostprocess).not.toHaveBeenCalled();});});diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex e848818400..7945dc13b4 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -25,7 +25,7 @@ import { readdir, writeFile } from 'fs/promises';import { createHash } from 'crypto';import { ensureDir, atomicWrite, sha256File } from '../../lib/fileUtils.js';import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';-import { keyChannelSplit, keyness, keyShareFn } from './chromaKey.js';+import { keyChannelSplit, keyness, keyShareFn, hexToRgb } from './chromaKey.js';// Source pipeline constants (animation_postprocess.py) — values are part of// the cross-install artifact contract (imported manifests carry them).@@ -40,6 +40,19 @@ export const WALK_PHASES = ['right-contact', 'right-down', 'right-passing', 'right-up',];+// Border-key acceptance thresholds. The key channels must dominate the dark+// channels by ≥ KEY_DOMINANCE_MIN, and each channel group must be balanced+// within KEY_GROUP_SPREAD_MAX. The spread tolerance was 80 (tuned to the source+// pipeline's near-ideal [255,0,255] magenta). Even when grok is handed the exact+// magenta matte (see prepareWalkAnchorChromaInput), the H.264 4:2:0 chroma+// subsampling in the delivered MP4 shifts saturated magenta at decode — a real+// trailhand clip measured ~[250,56,152] (r-b spread ~98) at the border. That is+// still a perfectly usable matte: the per-channel unmix keys off the MEASURED+// background, so a consistent codec-shifted matte reverses correctly. 120 admits+// it while still rejecting a single-channel-dominant color (e.g. [255,0,100]+// spread 155 = "red with a little blue", not magenta).+const KEY_DOMINANCE_MIN = 80;+const KEY_GROUP_SPREAD_MAX = 120;const KEY_NOISE_FLOOR = 0.01; // background share below this → fully opaqueconst BACKGROUND_ALPHA_FLOOR = 0.06; // source alpha at/below this → fully transparentconst ALPHA_NOISE_FLOOR = 2; // output alpha at/below this → zeroed@@ -127,20 +140,56 @@ export function sampleBorderKey(frame) {}/**- * Reject a measured border key that isn't a plausible sample of the expected- * chroma key: its saturated channels must dominate its dark channels by ≥80,- * and channels within each group must be balanced within 80 (the source's- * "balanced magenta" check, generalized).+ * Is a measured border key a plausible sample of the expected chroma key? Its+ * saturated channels must dominate its dark channels by ≥80, and channels+ * within each group must be balanced within 80 (the source's "balanced+ * magenta" check, generalized). A grok clip that fades in from — or pads with+ * — a black/near-black frame samples as [0,0,0] here and returns false, so the+ * caller can drop that frame rather than fail the whole run on it.*/-export function validateMeasuredKey(measured, split, keyHex) {+export function isUsableMeasuredKey(measured, split) {const minHigh = Math.min(...split.highs.map((i) => measured[i]));const maxLow = Math.max(...split.lows.map((i) => measured[i]));const groupSpread = (idx) => Math.max(...idx.map((i) => measured[i])) - Math.min(...idx.map((i) => measured[i]));- if (minHigh - maxLow < 80 || groupSpread(split.highs) > 80 || groupSpread(split.lows) > 80) {+ return !(minHigh - maxLow < KEY_DOMINANCE_MIN+ || groupSpread(split.highs) > KEY_GROUP_SPREAD_MAX+ || groupSpread(split.lows) > KEY_GROUP_SPREAD_MAX);+}++/**+ * Throwing variant for single-image callers (the anchor input prep), where a+ * non-key measurement is a hard error rather than a droppable frame.+ */+export function validateMeasuredKey(measured, split, keyHex) {+ if (!isUsableMeasuredKey(measured, split)) {throw new Error(`Measured background [${measured.join(',')}] is not a usable ${keyHex} matte`);}}+/**+ * The longest run of consecutive usable-matte frames in a decoded clip. Grok+ * clips commonly fade in from (or pad with) a non-key intro/outro frame; the+ * longest contiguous usable span drops that lead-in/lead-out WITHOUT breaking+ * the temporal adjacency selectCycleIndices relies on (dropping an interior+ * frame would make two non-adjacent frames look adjacent). Returns+ * `{ start, length }` into the input array.+ */+export function longestUsableSpan(usableFlags) {+ let best = { start: 0, length: 0 };+ let runStart = 0;+ let runLen = 0;+ for (let i = 0; i < usableFlags.length; i++) {+ if (usableFlags[i]) {+ if (runLen === 0) runStart = i;+ runLen += 1;+ if (runLen > best.length) best = { start: runStart, length: runLen };+ } else {+ runLen = 0;+ }+ }+ return best;+}+/*** Chroma un-key: reverse antialiased source-over-key compositing into a* straight-alpha RGBA frame. Per-pixel math is the source's, generalized to@@ -554,26 +603,27 @@ export async function extractVideoFrames(videoPath, rawDir) {}/**- * Prepare the transparent i2v motion input from a locked anchor (opaque on- * its key): measured-key alpha recovery + despill, saved as a straight-alpha- * PNG. An anchor that already carries transparency is passed through.+ * Prepare the i2v motion input for grok as an OPAQUE, chroma-backed frame.+ *+ * grok's image_to_video must receive the character sitting ON the exact chroma+ * matte we key against — NOT a transparent PNG. Handing grok transparency forces+ * it to (a) composite over black (producing black intro/fade frames whose border+ * measures [0,0,0]) and (b) reinvent the "magenta background" from the prompt+ * text. Compositing the anchor over solid chroma hands grok the literal+ * background to extend, so the rendered clip keeps a well-formed matte the+ * postprocess can unkey deterministically (codec chroma subsampling still shifts+ * it a little at decode — handled by the measured-key unmix, not here). An+ * already-opaque, chroma-backed anchor (the common case) is unchanged; a+ * transparent one has its holes filled with the matte color.+ *+ * `flatten` is libvips' native source-over-solid-color compositing (the same op+ * 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 prepareWalkAnchorInput(anchorAbs, destAbs, chromaKey) {- const split = keyChannelSplit(chromaKey);- const frame = await decodeRgbaFrame(anchorAbs);- let alreadyTransparent = false;- for (let i = 3; i < frame.data.length; i += 4) {- if (frame.data[i] < 255) { alreadyTransparent = true; break; }- }- let prepared = frame;- if (!alreadyTransparent) {- const measured = sampleBorderKey(frame);- validateMeasuredKey(measured, split, chromaKey);- prepared = recoverAlphaFrame(frame, measured, split);- }- prepared = despillKeyFrame(prepared, split);- const sha256 = await encodePngWithHash(prepared, destAbs);- return { preparation: 'measured-key-alpha-recovery-plus-despill', sha256 };+export async function prepareWalkAnchorChromaInput(anchorAbs, destAbs, chromaKey) {+ const buf = await sharp(anchorAbs).flatten({ background: hexToRgb(chromaKey) }).png().toBuffer();+ await writeFile(destAbs, buf);+ return { preparation: 'composited-over-solid-chroma-matte', sha256: sha256Buffer(buf) };}/**@@ -592,15 +642,31 @@ export async function runWalkPostprocess({const rawDir = join(generatedAbs, 'raw');const rawNames = await extractVideoFrames(videoAbs, rawDir);- const recovered = [];- const measuredKeys = [];+ // Decode + measure every frame, then keep only the longest contiguous run of+ // frames whose border is a usable chroma matte. Grok clips routinely open on+ // a black fade-in frame (border measures [0,0,0]) before the magenta-backed+ // walk begins — the old "validate every frame, throw on the first bad one"+ // failed the whole run on that intro frame even though 70+ good frames+ // followed it. `frames`/`measured`/`usable` stay index-aligned with rawNames.+ const decoded = [];for (const name of rawNames) {const frame = await decodeRgbaFrame(join(rawDir, name));const measured = sampleBorderKey(frame);- validateMeasuredKey(measured, split, chromaKey);- measuredKeys.push(measured);- recovered.push(recoverAlphaFrame(frame, measured, split));+ decoded.push({ frame, measured, usable: isUsableMeasuredKey(measured, split) });+ }+ const span = longestUsableSpan(decoded.map((d) => d.usable));+ if (span.length < WALK_FRAME_COUNT + 1) {+ const usableTotal = decoded.filter((d) => d.usable).length;+ throw new Error(usableTotal === 0+ ? `No frame has a usable ${chromaKey} matte (measured e.g. [${decoded[0]?.measured?.join(',')}] across ${decoded.length} frames)`+ : `Only ${span.length} contiguous frames have a usable ${chromaKey} matte (need ${WALK_FRAME_COUNT + 1}); the ${chromaKey} background is unstable across the clip`);}+ // span.start offsets every downstream lookup back into the raw source-%04d+ // numbering, so the manifest's sourceFrameIndex/sourcePath stay correct.+ const usable = decoded.slice(span.start, span.start + span.length);+ const usableRawNames = rawNames.slice(span.start, span.start + span.length);+ const measuredKeys = usable.map((d) => d.measured);+ const recovered = usable.map((d) => recoverAlphaFrame(d.frame, d.measured, split));const signatures = await Promise.all(recovered.map(signatureOf));const { indices, cycle } = selectCycleIndices(signatures);@@ -619,9 +685,11 @@ export async function runWalkPostprocess({frameRecords.push({outputIndex: i,phase,- sourceFrameIndex: indices[i] + 1, // 1-based, matches raw source-%04d numbering- sourcePath: `${generatedRel}/raw/${rawNames[indices[i]]}`,- sourceSha256: await sha256File(join(rawDir, rawNames[indices[i]])),+ // raw frames are 1-based sequential (source-%04d); indices[i] is relative+ // to the usable span, so span.start offsets it back to the raw numbering.+ sourceFrameIndex: span.start + indices[i] + 1,+ sourcePath: `${generatedRel}/raw/${usableRawNames[indices[i]]}`,+ sourceSha256: await sha256File(join(rawDir, usableRawNames[indices[i]])),measuredKeyRgb: measuredKeys[indices[i]],path: `${generatedRel}/frames/${name}`,sha256: await encodePngWithHash(despilled[i], join(framesDir, name)),diff --git a/server/services/sprites/walkPostprocess.test.js b/server/services/sprites/walkPostprocess.test.jsindex 5f7a40403f..163db17c5c 100644--- a/server/services/sprites/walkPostprocess.test.js+++ b/server/services/sprites/walkPostprocess.test.js@@ -12,9 +12,10 @@ import { join } from 'path';import sharp from 'sharp';import {pyRound, pyRoundTo, median, sampleBorderKey, validateMeasuredKey,+ isUsableMeasuredKey, longestUsableSpan,recoverAlphaFrame, despillKeyFrame, imageDistance, selectCycleIndices,alphaBbox, rootX, alignFrames, packStrip, validateFrames, buildContrastSheet,- prepareWalkAnchorInput, WALK_PHASES, WALK_CELL_SIZE, WALK_FRAME_COUNT,+ prepareWalkAnchorChromaInput, WALK_PHASES, WALK_CELL_SIZE, WALK_FRAME_COUNT,} from './walkPostprocess.js';import { keyChannelSplit } from './chromaKey.js';@@ -81,6 +82,29 @@ describe('sampleBorderKey / validateMeasuredKey', () => {// A magenta screen is not a usable green matte.expect(() => validateMeasuredKey([250, 5, 252], GREEN, '#00FF00')).toThrow(/matte/);});++ it('accepts grok\'s real red-leaning magenta but still rejects a black frame', () => {+ // grok image_to_video renders ~[250,56,152] (r-b spread ~98) — usable, and+ // the regression this whole fix exists for. A faded-in black intro frame+ // ([0,0,0]) is not, so the postprocess can drop it rather than fail on it.+ expect(isUsableMeasuredKey([250, 56, 152], MAGENTA)).toBe(true);+ expect(isUsableMeasuredKey([0, 0, 0], MAGENTA)).toBe(false);+ // The lopsided "red with a little blue" case stays rejected (spread 155).+ expect(isUsableMeasuredKey([255, 0, 100], MAGENTA)).toBe(false);+ });+});++describe('longestUsableSpan', () => {+ it('finds the longest contiguous run of usable frames', () => {+ // A leading black intro frame + a trailing one, good frames between.+ expect(longestUsableSpan([false, true, true, true, false])).toEqual({ start: 1, length: 3 });+ // Prefers the longer of two runs.+ expect(longestUsableSpan([true, false, true, true, true])).toEqual({ start: 2, length: 3 });+ // All usable → the whole array.+ expect(longestUsableSpan([true, true, true])).toEqual({ start: 0, length: 3 });+ // None usable → zero-length.+ expect(longestUsableSpan([false, false])).toEqual({ start: 0, length: 0 });+ });});describe('recoverAlphaFrame', () => {@@ -273,8 +297,8 @@ describe('buildContrastSheet', () => {});});-describe('prepareWalkAnchorInput', () => {- it('recovers a transparent despilled input from an opaque keyed anchor', async () => {+describe('prepareWalkAnchorChromaInput', () => {+ it('passes an opaque chroma-backed anchor through unchanged (opaque, matte preserved)', async () => {const w = 64; const h = 64;const rgb = Buffer.alloc(w * h * 3);for (let p = 0; p < w * h; p++) rgb.set([255, 0, 255], p * 3);@@ -284,15 +308,32 @@ describe('prepareWalkAnchorInput', () => {const anchorAbs = join(TEST_ROOT, 'anchor.png');const destAbs = join(TEST_ROOT, 'input.png');await sharp(rgb, { raw: { width: w, height: h, channels: 3 } }).png().toFile(anchorAbs);- const { preparation } = await prepareWalkAnchorInput(anchorAbs, destAbs, '#FF00FF');- expect(preparation).toBe('measured-key-alpha-recovery-plus-despill');+ const { preparation } = await prepareWalkAnchorChromaInput(anchorAbs, destAbs, '#FF00FF');+ expect(preparation).toBe('composited-over-solid-chroma-matte');const { data, info } = await sharp(destAbs).ensureAlpha().raw().toBuffer({ resolveWithObject: true });expect(info.channels).toBe(4);- expect(data[3]).toBe(0); // key corner → transparent+ // The whole frame is opaque — grok animates the character ON the matte.+ expect(data[3]).toBe(255); // key corner stays the OPAQUE magenta matte+ expect([data[0], data[1], data[2]]).toEqual([255, 0, 255]);const charI = ((25 * w) + 30) * 4;expect(data[charI + 3]).toBe(255); // character stays opaqueexpect([data[charI], data[charI + 1], data[charI + 2]]).toEqual([30, 110, 60]);});++ it('fills a transparent anchor\'s holes with the solid chroma matte', async () => {+ const w = 16; const h = 16;+ // Fully transparent except one opaque character pixel.+ const rgba = Buffer.alloc(w * h * 4);+ rgba.set([30, 110, 60, 255], ((8 * w) + 8) * 4);+ const anchorAbs = join(TEST_ROOT, 'anchor-t.png');+ const destAbs = join(TEST_ROOT, 'input-t.png');+ await sharp(rgba, { raw: { width: w, height: h, channels: 4 } }).png().toFile(anchorAbs);+ await prepareWalkAnchorChromaInput(anchorAbs, destAbs, '#FF00FF');+ const { data } = await sharp(destAbs).ensureAlpha().raw().toBuffer({ resolveWithObject: true });+ expect([data[0], data[1], data[2], data[3]]).toEqual([255, 0, 255, 255]); // hole → opaque magenta+ const charI = ((8 * w) + 8) * 4;+ expect([data[charI], data[charI + 1], data[charI + 2], data[charI + 3]]).toEqual([30, 110, 60, 255]);+ });});describe('constants', () => {diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.jsindex e526b724d0..0f3fe57c98 100644--- a/server/services/videoGen/grok.js+++ b/server/services/videoGen/grok.js@@ -50,8 +50,16 @@ const GROK_VIDEO_TIMEOUT_MS = (() => {const DEFAULT_BIN = 'grok';-// Durations grok's image_to_video tool accepts, in seconds.-export const GROK_VIDEO_DURATIONS = Object.freeze([6, 10]);+// Clip lengths (seconds) offered for grok's image_to_video tool. grok's own+// game-animation skill documents 6s/10s, but shorter clips animate fine and are+// plenty for a looping walk cycle (the postprocess only harvests ~8 frames of+// one gait cycle) — 6s took ~10.5 min to render and yielded 73 usable frames+// where the cycle selector needs 9. The shorter options let the user trade+// render time for material; GROK_VIDEO_DEFAULT_DURATION is the general-video+// fallback when a caller omits duration (kept at 6 so non-walk video gen is+// unchanged — the walk path picks its own shorter default).+export const GROK_VIDEO_DURATIONS = Object.freeze([1, 2, 3, 6, 10]);+export const GROK_VIDEO_DEFAULT_DURATION = 6;// Per-job state — keyed by jobId (cloud lane allows parallel renders). Same// client shape as videoGen/local.js so attachSseClient/broadcastSse work.@@ -124,7 +132,7 @@ export async function generateVideo({throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });}- const effectiveDuration = GROK_VIDEO_DURATIONS.includes(Number(duration)) ? Number(duration) : GROK_VIDEO_DURATIONS[0];+ const effectiveDuration = GROK_VIDEO_DURATIONS.includes(Number(duration)) ? Number(duration) : GROK_VIDEO_DEFAULT_DURATION;const jobId = providedJobId || randomUUID();const filename = `${jobId}.mp4`;