Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-3022]): stop offering grok video clip lengths it silently renders as 6s
[._.]/ Adam Eivyd7d78000f505
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e75cc7a411..aaca67e8a7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -35,6 +35,7 @@## Sprite Manager+- **[issue-3022] Walk cards now show the clip length grok actually delivered** — the Clip picker offers 6s and 10s, and it turns out those really are the only two lengths available: asking for a shorter clip to save render time doesn't work, because grok renders 6 seconds regardless and charges the same for it. Rather than leave that buried in a code comment (where it had already drifted into two comments claiming opposite things), each walk direction now reports the length of the clip it actually got, measured from the file — and says so in amber if that differs from what was requested. So if grok's options ever change, you'll see it on the card instead of having to guess.- **[issue-2980] See every frame a walk's video produced — and rebuild the loop at a new frame count without re-rendering** — the Loop Trimmer could only *drop* columns from a strip that was already packed, so an 8-frame walk could never become a 12-frame one there: the extra source frames were thrown away at pack time and nothing in the workspace showed they had ever existed. The trimmer now has a **Source frames** section listing every frame extracted from that run's clip (typically ~70 at 12fps), with the gait cycle the packer picked marked in amber and the frames that became the strip's columns highlighted — so the headroom above the current count is visible at a glance. A **Re-derive from clip** control beside it repacks the loop from that same on-disk video at a new frame count / speed, with no AI call and no new render; the frame count and speed are the walk set's shared cycle target rather than a free per-run range, since every direction of one walk has to agree for the atlas to compile, and changing them says so before it retargets the set. A run whose extracted frames were cleaned up (which is every imported run — the importer doesn't copy them) says so and offers a one-click "Extract frames from clip" rather than quietly running ffmpeg for every direction you happen to click through; an approved direction or a frozen set offers the matching inline Reopen / Unlock instead of failing on click; a run with no clip at all explains that in one line rather than showing an empty grid, and names the right remedy for how it got there; and if the frames on disk turn out not to be the ones the strip was packed from, the cycle markers are withheld rather than pointing at the wrong frames. Re-deriving an *imported* run also works now — its run id was rejected by the reprocess endpoint before it ever reached the service that #2993 taught to handle it.- **[issue-3004] Turnaround sheets stop mirroring the front view, so a front-worn bag no longer ends up on the character's back** — the back panel of a generated turnaround sheet was often just the front figure flipped left-to-right, which meant anything mounted on the *front* of the body (a hip bag worn at the front, a chest pack, a belt buckle) reappeared on the character's back in the rear view, and the same mistake carried into any single rotated view derived from the sheet. The old instruction only pinned accessories to the same anatomical *side* — a rule a mirrored figure satisfies perfectly, because the bug is on the front/back axis, not left/right. The sheet prompt now states that the panels are one character physically *rotated* about a vertical axis and that no panel may be a flip or copy of another, each derived view is told it is a rotation rather than a mirrored copy, and every facing carries its own rule for what that angle hides: a rear view hides front-mounted gear (keeping only what genuinely wraps around, like a strap crossing the back) and shows no face or front closures; a front view hides backpacks and back-slung weapons; each profile hides whatever sits on the far side of the torso — hedged for the diagonal views, where a 45-degree turn only partly hides things, so gear doesn't pop in and out as the sprite rotates. The diagonal views are also now told to interpolate between the two sheet panels they sit between, instead of being pointed at a panel the four-panel sheet doesn't have. The front/back panels also now say where a right-hip item lands on screen once the character turns, so "same side" can't be satisfied by leaving it in the same pixels. The walk-video step is told not to invent gear the anchor hides mid-loop.- **[issue-2993] Imported characters can finally be re-derived — smoother walks, and an atlas you can compile here** — a character brought over from a source art pipeline was frozen the moment it arrived: Unlock, Reopen and Compile all refused it outright, so an imported 8-frame walk could never be brought up to 12 and its atlas could only ever be re-published, never rebuilt. That refusal was written when the import genuinely left nothing behind to work from — but the importer now copies each direction's source clip, so it had become a lie. Those actions are now gated on whether the clip is actually there: a direction with its clip on disk reopens and reprocesses at any frame count and speed, with no new render and no new spend, and the buttons appear instead of being hidden. A direction with no clip is still refused, but now says so plainly and tells you to re-import the character. Compiling is likewise per-direction: the atlas names the directions still packaged by the source pipeline instead of refusing the whole set, so an imported character becomes compilable one direction at a time as you re-derive them — and approving a direction whose packaged frames were never imported is now caught up front, rather than surfacing much later as an unexplained compile error.diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex 4e6a5f00c8..08b2a403f3 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -12,6 +12,7 @@ import CycleTarget from './CycleTarget.jsx';import SpritePreview from './SpritePreview.jsx';import { useAsyncAction } from '../../hooks/useAsyncAction.js';import { spriteAssetUrl, checkerboardStyle, PIXELATED } from './spriteAssets.js';+import { GROK_VIDEO_DURATIONS, GROK_VIDEO_DEFAULT_DURATION } from '../../lib/grokVideoClip.js';import {WALK_PHASES, WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,} from '../../lib/spriteTrimmer.js';@@ -28,14 +29,34 @@ const CELL_PX = 96; // preview cell size — the strip animates at 96px/frame// 8, an imported redraw cycle can pack 12 — #2924), so the single keyframe// rule reads it from a per-preview custom property instead of hardcoding 8.const LOOP_KEYFRAMES = '@keyframes sprite-walk-loop { to { background-position-x: var(--sprite-walk-loop-end) } }';-// Grok image_to_video clip lengths. In practice grok's tool only honors its-// documented 6s/10s options and clamps anything shorter to ~6s — so the picker-// offers just those two rather than lying about 1/2/3s. A 6s clip yields plenty-// of source frames for the packer; the CYCLE'S look (walk vs run) is set by the-// frame-count + speed controls below, not the clip length. Exported so the-// Sprites page can seed the lifted `duration` state with the same default.-export const WALK_DURATIONS = [6, 10];-export const WALK_DEFAULT_DURATION = 6;+// Grok image_to_video clip lengths, from the client mirror of the server list+// (`lib/grokVideoClip.js` — a server test fails if the two drift). grok's tool+// offers ONLY 6s/10s and silently renders 6s for anything shorter: requesting+// 2s or 3s returns the same 6.04s clip, at the same render cost — measured+// three ways in #3022, and reported by grok's own agent. So the picker offers+// exactly what it can deliver rather than advertising a saving that doesn't+// exist. A 6s clip yields ~73 source frames where the packer consumes at most+// 16; the CYCLE'S look (walk vs run) is set by the frame-count + speed controls+// below, not the clip length. Re-exported under the walk-flavored names the+// Sprites page already imports to seed its lifted `duration` state.+export const WALK_DURATIONS = GROK_VIDEO_DURATIONS;+export const WALK_DEFAULT_DURATION = GROK_VIDEO_DEFAULT_DURATION;++// Delivered clip length for a run, when the server managed to probe it+// (`sourceVideoSeconds` is absent on older runs and when ffprobe is missing —+// absent means UNKNOWN, so render nothing rather than implying a 0s clip).+// A mismatch against the requested `duration` is worth surfacing: it is the+// visible evidence of grok's clamp, and the thing that would tell us the+// clamp had changed.+export function clipLengthLabel(run) {+ const delivered = Number(run?.sourceVideoSeconds);+ if (!(delivered > 0)) return null;+ const shown = `${delivered.toFixed(1)}s clip`;+ const requested = Number(run?.duration);+ return requested > 0 && Math.abs(requested - delivered) >= 0.5+ ? { text: `${shown} (asked ${requested}s)`, mismatch: true }+ : { text: shown, mismatch: false };+}// The deterministic-postprocess authoring knobs (frame count + preview fps) and// their option lists moved to lib/spriteTrimmer.js (#2980) — the Loop Trimmer's@@ -187,6 +208,10 @@ function DirectionCard({: run?.status === 'postprocessing' ? 'packaging…': supersededAnchor ? 'anchor revised': run?.status || (anchorLocked ? 'ready' : 'anchor not locked');+ // What grok actually delivered, probed server-side — the durable answer to+ // "does the clip length picker do anything?", which used to live only in+ // contradicting code comments (#3022).+ const clipLength = clipLengthLabel(run);return (<div className="bg-port-bg border border-port-border rounded p-2 space-y-1.5">@@ -197,6 +222,17 @@ function DirectionCard({</span></p>+ {clipLength && (+ <p+ className={`text-[10px] ${clipLength.mismatch ? 'text-port-warning' : 'text-gray-500'}`}+ title={clipLength.mismatch+ ? 'grok delivered a different clip length than requested — its image_to_video tool renders only 6s or 10s'+ : 'Source clip length grok delivered (probed from the file)'}+ >+ {clipLength.text}+ </p>+ )}+{hasWalkPreview && (<StripLoop recordId={recordId} stripPreview={run.stripPreview} />)}@@ -622,7 +658,7 @@ 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; length only affects how much source footage the packer has to choose from">+ <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.">Clip<selectid={`walk-clip-${recordId}`}diff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsxindex cd8446eccf..812f00eda9 100644--- a/client/src/components/sprites/WalkWorkflow.test.jsx+++ b/client/src/components/sprites/WalkWorkflow.test.jsx@@ -712,3 +712,52 @@ describe('WalkWorkflow reprocess + reopen', () => {expect(screen.getByRole('button', { name: /^Reopen$/ })).toBeTruthy();});});++// The delivered-clip-length readout (#3022). grok's image_to_video offers only+// 6s/10s and renders 6s for anything shorter, so the requested length is not a+// promise — the card reports what the server probed off the file, and says so+// loudly when the two disagree.+describe('delivered clip length', () => {+ const renderWithRun = (run) => render(+ <MemoryRouter>+ <WalkWorkflow+ record={{ id: 'example-walker' }}+ reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}+ walk={{+ runs: [{ id: 'run-east', direction: 'east', status: 'candidate', ...run }],+ selection: { directions: {} },+ walkSet: null,+ }}+ renders={noRenders()}+ duration={6}+ onDurationChange={vi.fn()}+ onGenerate={vi.fn()}+ onChanged={vi.fn()}+ />+ </MemoryRouter>,+ );++ it('reports the probed clip length', () => {+ renderWithRun({ duration: 6, sourceVideoSeconds: 6.04 });+ expect(screen.getByText('6.0s clip')).toBeTruthy();+ });++ it('flags a delivered length that differs from the request', () => {+ // The exact case the field exists for: asked 2s, grok rendered 6s.+ renderWithRun({ duration: 2, sourceVideoSeconds: 6.04 });+ const badge = screen.getByText('6.0s clip (asked 2s)');+ expect(badge.className).toContain('text-port-warning');+ });++ it('does not treat a rounding-level difference as a mismatch', () => {+ renderWithRun({ duration: 6, sourceVideoSeconds: 6.041667 });+ expect(screen.queryByText(/asked/)).toBeNull();+ });++ it('renders nothing when the clip length is unknown', () => {+ // Absent (older run, or ffprobe unavailable) must NOT read as a 0s clip.+ renderWithRun({ duration: 6 });+ expect(screen.queryByText(/clip$/)).toBeNull();+ expect(screen.queryByText(/0\.0s/)).toBeNull();+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 83508472a4..62e9c498fd 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -37,6 +37,7 @@ grep -i "what you want to do" client/src/lib/README.md| `beatColors.js` | `BEAT_KIND_COLORS` + `getBeatKindColor(kind)` — per-kind display colors for reader-map emotional beats (kinds defined server-side in `storyArc.js`). Keeps every beat visualization consistent. || `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. || `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`. |+| `grokVideoClip.js` | Mirror of `server/lib/grokVideoClip.js` — `GROK_VIDEO_DURATIONS` (`[6, 10]`) + `GROK_VIDEO_DEFAULT_DURATION`, the clip lengths grok's `image_to_video` actually delivers. || `catalogTypes.js` | Client mirror of `server/lib/catalogTypes.js` — catalog ingredient type registry (label, badge color, primary-content key/label, snippet fallback chain, per-type editor field list) for the Catalog list/picker/editor. || `creativeDirectorPlan.js` | Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate `plan.steps[]` with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps. || `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. |diff --git a/client/src/lib/grokVideoClip.js b/client/src/lib/grokVideoClip.jsnew file mode 100644index 0000000000..97daf2c1f1--- /dev/null+++ b/client/src/lib/grokVideoClip.js@@ -0,0 +1,16 @@+// Client mirror of `server/lib/grokVideoClip.js` — the clip lengths grok's+// `image_to_video` tool actually delivers. Enforced by the "client mirror"+// suite in `server/lib/grokVideoClip.test.js`: if this drifts from the server+// list, that test fails. Update the SERVER file first, then this one.+//+// The values are measured, not documented (#3022): three renders requesting+// 2s / 3s / 6s all returned the same 6.04s clip, and grok's own agent reported+// that image_to_video "only supports 6 or 10 second durations". So a shorter+// request buys no render time — the picker offers exactly what grok delivers+// rather than advertising a saving that doesn't exist.++/** Clip lengths (seconds) grok's image_to_video delivers, ascending. */+export const GROK_VIDEO_DURATIONS = [6, 10];++/** Fallback when no clip length is chosen. */+export const GROK_VIDEO_DEFAULT_DURATION = 6;diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 0983077323..a9a4d68653 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -21,6 +21,7 @@ export * from './universeStylePreset.js';export * from './beatColors.js';export * from './beatGrid.js';export * from './bibleLimits.js';+export * from './grokVideoClip.js';export * from './catalogTypes.js';export * from './creativeDirectorPlan.js';export * from './creativeDirectorPreview.js';diff --git a/server/lib/README.md b/server/lib/README.mdindex 5774f7c2d2..e69c6212b7 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -105,6 +105,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. || `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. || `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |+| `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, and `resolveGrokDuration()`. Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. || `kimi.js` | Moonshot AI Kimi Code (`kimi`) provider helpers — id constants (`KIMI_CLI_ID`/`KIMI_TUI_ID`), `isKimiCommand`/`isKimiCliProvider`/`isKimiTuiProvider` predicates, `ensureKimiHeadlessArgs` (`--print`, implies `--afk`) / `ensureKimiTuiArgs` (`--yolo`) argv builders (model selection uses the `KIMI_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Grok/Antigravity), and `prepareKimiPrompt` (delivers the prompt as the `--prompt <value>` argv, not stdin). || `runners.js` | Image-runner family constants. || `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. |diff --git a/server/lib/grokVideoClip.js b/server/lib/grokVideoClip.jsnew file mode 100644index 0000000000..82c9e19f8b--- /dev/null+++ b/server/lib/grokVideoClip.js@@ -0,0 +1,53 @@+/**+ * Clip lengths grok's `image_to_video` tool actually delivers.+ *+ * **Measured, not assumed** (#3022). PortOS never passes grok a `duration`+ * parameter — both the general video path (`buildGrokVideoPrompt`) and the+ * sprite walk path (`buildWalkTuiTask`) ask the grok *agent* in prose ("animate+ * this for N seconds"), and the agent picks its own tool-call arguments. So the+ * only way to know which lengths are real is to render one and probe the result.+ *+ * Three headless renders of the same source image, requesting 2s / 3s / 6s, all+ * returned an identical 6.04s clip (145 native frames; 73 frames at the 12fps+ * extraction rate the walk packer uses) in 37-46s wall clock. grok's own agent+ * reported the constraint unprompted in two of the three runs:+ *+ * > `image_to_video` only supports 6 or 10 second durations, so this was+ * > rendered at 6 seconds (the minimum).+ *+ * There is therefore **no render time to save by requesting a shorter clip** —+ * a 2s request costs exactly what a 6s request costs and returns the same+ * footage. Offering 1/2/3 in a picker would be advertising a saving that does+ * not exist, which is why this list is exactly what grok delivers.+ *+ * This module is deliberately **dependency-free** so `lib/validation.js` and+ * `routes/videoGen.js` can derive their Zod schemas from the same list the+ * services gate on, without pulling the videoGen graph (spawn, sseUtils,+ * imageGen) into every suite that imports validation.js. Same reasoning as+ * `walkBounds.js`: hand-copied literals in a schema are exactly how a schema+ * and its service drift apart.+ *+ * If grok's tool ever gains shorter clips, change this list — the walk picker,+ * both Zod schemas, and the service gates all follow from it. Confirm with a+ * probe (`run.sourceVideoSeconds` is stamped on every walk run for exactly this+ * reason) rather than from a tool description.+ */++/** Clip lengths (seconds) grok's image_to_video delivers, ascending. */+export const GROK_VIDEO_DURATIONS = Object.freeze([6, 10]);++/** Fallback when a caller omits (or requests an undeliverable) clip length. */+export const GROK_VIDEO_DEFAULT_DURATION = 6;++/**+ * The requested length grok will actually honor, or the default.+ *+ * Only a number or a numeric string is considered — multipart bodies deliver+ * `"10"`, but `Number()` alone would also coerce `[10]` (and `true`, and `""`)+ * into a "supported" length, so the type is checked before the value.+ */+export const resolveGrokDuration = (requested) => {+ if (typeof requested !== 'number' && typeof requested !== 'string') return GROK_VIDEO_DEFAULT_DURATION;+ const n = Number(requested);+ return GROK_VIDEO_DURATIONS.includes(n) ? n : GROK_VIDEO_DEFAULT_DURATION;+};diff --git a/server/lib/grokVideoClip.test.js b/server/lib/grokVideoClip.test.jsnew file mode 100644index 0000000000..97ea9f4350--- /dev/null+++ b/server/lib/grokVideoClip.test.js@@ -0,0 +1,57 @@+import { describe, it, expect } from 'vitest';+import {+ GROK_VIDEO_DURATIONS, GROK_VIDEO_DEFAULT_DURATION, resolveGrokDuration,+} from './grokVideoClip.js';++describe('grokVideoClip', () => {+ // The list is the measured answer (#3022), not grok's documented one — three+ // renders requesting 2s/3s/6s all returned the same 6.04s clip. Locking it+ // down here so a future "shorter clips save render time" change has to come+ // with a new measurement rather than an assumption.+ it('offers exactly the clip lengths grok delivers', () => {+ expect(GROK_VIDEO_DURATIONS).toEqual([6, 10]);+ expect(Object.isFrozen(GROK_VIDEO_DURATIONS)).toBe(true);+ });++ it('defaults to the shortest deliverable clip', () => {+ expect(GROK_VIDEO_DEFAULT_DURATION).toBe(Math.min(...GROK_VIDEO_DURATIONS));+ });++ it('passes through a length grok offers', () => {+ for (const d of GROK_VIDEO_DURATIONS) expect(resolveGrokDuration(d)).toBe(d);+ expect(resolveGrokDuration('10')).toBe(10); // multipart bodies arrive as strings+ });++ it.each([+ ['a length grok clamps away', 2],+ ['zero', 0],+ ['a negative', -6],+ ['a non-numeric string', 'six'],+ ['null', null],+ ['undefined', undefined],+ ['NaN', NaN],+ ])('falls back to the default for %s', (_label, input) => {+ expect(resolveGrokDuration(input)).toBe(GROK_VIDEO_DEFAULT_DURATION);+ });++ // `Number([10])` is 10, so a bare Number() coercion would accept an array as+ // a "supported" length. 10 is deliberately used here (not 6) so the assertion+ // can't pass by coincidentally matching the default.+ it('does not coerce a non-scalar into a supported length', () => {+ expect(resolveGrokDuration([10])).toBe(GROK_VIDEO_DEFAULT_DURATION);+ expect(resolveGrokDuration({ valueOf: () => 10 })).toBe(GROK_VIDEO_DEFAULT_DURATION);+ });+});++describe('grokVideoClip client mirror', () => {+ it('matches client/src/lib/grokVideoClip.js', async () => {+ // The walk workflow's Clip picker builds its options from the client mirror,+ // which can't import server code. Without this guard the picker could go on+ // offering a length the server rejects (or stop offering one it accepts) —+ // the same silent drift #3022 was filed to end. If this fails, update the+ // client file to match the server list.+ const clientMirror = await import('../../client/src/lib/grokVideoClip.js');+ expect(clientMirror.GROK_VIDEO_DURATIONS).toEqual([...GROK_VIDEO_DURATIONS]);+ expect(clientMirror.GROK_VIDEO_DEFAULT_DURATION).toBe(GROK_VIDEO_DEFAULT_DURATION);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 653cd06761..3896f89b07 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -91,6 +91,7 @@ export * from './codexAssistantExtract.js';export * from './codexCliOutput.js';export * from './contextBudget.js';export * from './grok.js';+export * from './grokVideoClip.js';export * from './hfToken.js';export * from './hfErrors.js';export * from './hfCache.js';diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 1154a7afb6..1d419bebd4 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -7,6 +7,16 @@ import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS, TURNAROUND_ID } from '../servicesimport { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';import { WALK_TRACK, getAnimationTrack } from '../services/sprites/animationTracks.js';import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';+import { GROK_VIDEO_DURATIONS } from './grokVideoClip.js';++// Clip lengths grok's image_to_video delivers, as a Zod union built from the+// single shared list (grokVideoClip.js is dependency-free, so importing it here+// adds nothing to the graph every route pulls in via this module). `z.literal`+// per value rather than `z.number().refine()` keeps the "expected 6 | 10"+// error message the hand-written union produced.+const grokVideoDurationSchema = z.union(+ GROK_VIDEO_DURATIONS.map((d) => z.literal(d)),+);// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total// pixels. Mirror the ceiling for every image-gen route. Local mflux can@@ -1161,12 +1171,14 @@ const spriteWalkFpsSchema = spriteTrackFpsSchema(WALK_TRACK);export const spriteWalkGenerateSchema = z.object({direction: spriteWalkDirectionSchema,- // Clip length in seconds. grok's image_to_video only honors its documented- // 6s/10s options and clamps anything shorter to ~6s, so only those two are- // accepted; the service defaults to 6s when omitted. Clip length only affects+ // Clip length in seconds — derived from the shared list rather than repeated+ // as literals, so the schema can't drift from what the service gates on+ // (grokVideoClip.js is dependency-free precisely so this import is safe here).+ // grok's image_to_video offers only 6s/10s and renders 6s for anything+ // shorter; the service defaults to 6s when omitted. Clip length only affects// how much source footage the packer can choose from — the cycle's look is set// by frameCount/fps below.- duration: z.union([z.literal(6), z.literal(10)]).optional(),+ duration: grokVideoDurationSchema.optional(),// Deterministic-postprocess knobs (not grok's): how many frames the packed// cycle holds and how fast it plays back. Omitted → the set's pinned cycle// target; a value that DISAGREES with that target is refused with 409diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex f585e547ba..bb207ecd62 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -18,6 +18,7 @@ import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.jimport { uploadFields } from '../lib/multipart.js';import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';import { safeUnder } from '../lib/ffmpeg.js';+import { GROK_VIDEO_DURATIONS } from '../lib/grokVideoClip.js';import { IMAGE_GEN_MODE } from '../services/imageGen/modes.js';import { getSettings } from '../services/settings.js';import { checkPackages, isAllowedPython } from '../lib/pythonSetup.js';@@ -115,10 +116,12 @@ const generateBodySchema = z.object({// grokDuration.backend: z.enum(['local', 'grok']).optional(),// Grok image_to_video clip length in seconds — the tool supports exactly- // 6 or 10. Multipart bodies arrive as strings, so coerce first.+ // 6 or 10 (measured, #3022: a shorter request renders 6s anyway). Derived+ // from the shared list so this schema can't drift from the service gate.+ // Multipart bodies arrive as strings, so coerce first.grokDuration: z.preprocess((v) => (v == null || v === '' ? undefined : Number(v)),- z.union([z.literal(6), z.literal(10)]).optional(),+ z.union(GROK_VIDEO_DURATIONS.map((d) => z.literal(d))).optional(),),prompt: z.string().min(1).max(8000),negativePrompt: z.string().max(8000).optional(),diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex d1e12fef88..cefccd1d5c 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -50,13 +50,8 @@ import {WALK_TRACK, resolveAnimationTarget, withTrackTarget, targetDrift, describeTargetSource,} from './animationTargets.js';import { verifyPackagedFrames } from './walkFrames.js';-import { GROK_VIDEO_DURATIONS } from '../videoGen/grok.js';--// grok's image_to_video honors only 6s/10s and clamps shorter requests to ~6s,-// so 6 is both the floor and the sensible default: a 6s clip yields plenty of-// source frames (~70) for the cycle selector, and the walk's look is tuned by-// frame count + fps, not clip length.-const WALK_DEFAULT_DURATION = 6;+import { probeVideoDuration } from '../../lib/ffmpeg.js';+import { resolveGrokDuration } from '../../lib/grokVideoClip.js';// 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@@ -867,7 +862,12 @@ async function startWalkGenerationImpl(recordId, body) {prepareWalkAnchorChromaInput(anchorAbs, inputAbs, chromaKey),getSettings(),]);- const duration = GROK_VIDEO_DURATIONS.includes(Number(body.duration)) ? Number(body.duration) : WALK_DEFAULT_DURATION;+ // Clip length grok will actually deliver — a request it doesn't offer falls+ // back to its shortest (6s). There is no shorter option to expose: a 2s/3s+ // request returns the same 6s clip at the same cost (measured, #3022 — see+ // lib/grokVideoClip.js). The walk's look comes from frameCount/fps below,+ // not from how much footage the packer had to choose 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// resamples/labels the cycle afterward. Resolved from the set target above and@@ -1028,6 +1028,20 @@ 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. Stamped+ // here (shared by attach + rerun, so a reprocess backfills it onto an older+ // run) because the requested length is not a promise: grok's image_to_video+ // offers only 6s/10s and silently renders 6s for anything shorter (#3022).+ // Recording the probe is what keeps that fact honest — a code comment+ // asserting it drifted out of sync with a second comment asserting the+ // opposite, which is precisely what this field replaces.+ //+ // probeVideoDuration returns null when ffprobe is missing or the file has no+ // parseable duration; leave the field ABSENT in that case rather than+ // stamping 0, so "unknown" never reads as "a zero-length clip". A previously+ // stamped value survives — a probe that can't run is not evidence of change.+ const probedSeconds = await probeVideoDuration(videoAbs);+ if (probedSeconds) run.sourceVideoSeconds = Math.round(probedSeconds * 100) / 100;const manifest = await loadManifest(recordId);const anchor = manifest?.anchors?.find((a) => a.direction === run.direction);if (!anchor?.path) throw new Error(`No locked ${run.direction} anchor in the reference manifest`);diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex c19be94893..16adc75002 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -47,9 +47,19 @@ 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: [1, 2, 3, 6, 10] }));+// The clip-length contract now comes from the dependency-free lib/grokVideoClip.js+// leaf (#3022), so the videoGen graph is out of this suite by construction — no+// mock needed, and the REAL `[6, 10]` list is what the assertions below exercise.++// ffprobe isn't available to every test environment and the suite's stub clips+// aren't decodable media anyway, so the delivered-clip-length probe is a spy:+// unmocked it resolves null (the real "couldn't measure" path), and a test that+// cares about a measured value primes it with mockResolvedValueOnce.+const probeVideoDuration = vi.fn(async () => null);+vi.mock('../../lib/ffmpeg.js', async (importOriginal) => ({+ ...await importOriginal(),+ probeVideoDuration: (...args) => probeVideoDuration(...args),+}));const prepareWalkAnchorChromaInput = vi.fn(async (_anchorAbs, destAbs) => {await mkdir(join(destAbs, '..'), { recursive: true });@@ -326,6 +336,18 @@ describe('startWalkGeneration', () => {expect(executeTuiRun.mock.calls[0][0].prompt).toContain('for 6 seconds');});+ // The specific values a user would reach for to "save render time" (#3022).+ // grok renders 6s for these regardless, so asking for them must not put a+ // number in the prompt that the tool will silently ignore — the prompt has to+ // say 6, matching what actually comes back.+ it.each([1, 2, 3])('refuses the undeliverable %ss clip and asks grok for 6s', async (duration) => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const result = await startWalkGeneration(id, { direction: 'east', duration });+ expect(result.duration).toBe(6);+ expect(executeTuiRun.mock.calls[0][0].prompt).toContain('for 6 seconds');+ expect(executeTuiRun.mock.calls[0][0].prompt).not.toContain(`for ${duration} seconds`);+ });+it('stores the chosen frame count + fps on the run and passes them to the packer', async () => {const id = await characterWithLockedAnchors(newId(), ['east']);// Frame count / fps are pinned at the SET level now (#2985) — a render must@@ -362,6 +384,29 @@ describe('startWalkGeneration', () => {id: runId, status: 'candidate', postprocessManifest: `runs/${runId}/generated/manifest.json`,});expect(runs[0].sourceVideoSha256).toBe(sha256(Buffer.from('grok-clip-bytes')));+ // The stub clip isn't real media, so ffprobe finds no duration — the field+ // must be ABSENT rather than 0, so "we couldn't measure it" never renders as+ // "grok returned a zero-length clip" (#3022).+ expect(runs[0]).not.toHaveProperty('sourceVideoSeconds');+ });++ it('stamps the DELIVERED clip length, which need not match what was requested', async () => {+ // grok's image_to_video renders 6s for anything shorter than 6s, so the+ // requested length is not a promise — the probe is. Here the request is 10s+ // and the file measures 6s, the exact divergence the field exists to expose.+ probeVideoDuration.mockResolvedValueOnce(6.041667);+ const id = await characterWithLockedAnchors(newId(), ['east']);+ executeTuiRun.mockImplementationOnce(async ({ workspacePath }) => {+ await writeFile(join(workspacePath, 'source-video.mp4'), 'grok-clip-bytes');+ });+ await startWalkGeneration(id, { direction: 'east', duration: 10 });+ await vi.waitFor(async () => {+ const { runs } = await getWalkState(id);+ expect(runs[0].status).toBe('candidate');+ });+ const { runs } = await getWalkState(id);+ expect(runs[0].duration).toBe(10); // what we asked grok for+ expect(runs[0].sourceVideoSeconds).toBe(6.04); // what grok actually delivered});it('marks the run errored when grok finishes without a clip', async () => {diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.jsindex 0f3fe57c98..728dfb7072 100644--- a/server/services/videoGen/grok.js+++ b/server/services/videoGen/grok.js@@ -36,6 +36,9 @@ import { videoGenEvents } from './events.js';import { finalizeGeneratedVideo } from './generateVideoHelpers.js';import { mutateVideoHistory } from './history.js';import { noImageReason, deriveAspectRatio, GROK_ASPECT_RATIOS } from '../imageGen/grok.js';+import {+ GROK_VIDEO_DURATIONS, GROK_VIDEO_DEFAULT_DURATION, resolveGrokDuration,+} from '../../lib/grokVideoClip.js';// 30 minutes — an image-first video turn is two sequential tool calls// (image_gen then image_to_video render + download), so it runs meaningfully@@ -50,16 +53,14 @@ const GROK_VIDEO_TIMEOUT_MS = (() => {const DEFAULT_BIN = 'grok';-// 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;+// Clip lengths grok's image_to_video delivers. Re-exported from the+// dependency-free lib leaf so the Zod schemas in lib/validation.js and+// routes/videoGen.js derive from the same list this module gates on — see+// lib/grokVideoClip.js for the measurement behind `[6, 10]` (#3022). This list+// used to carry 1/2/3 on the theory that shorter clips "trade render time for+// material"; they don't — grok returns a 6s clip for a 2s request, at the same+// cost. Deep imports of these two names from this module keep working.+export { GROK_VIDEO_DURATIONS, GROK_VIDEO_DEFAULT_DURATION };// Per-job state — keyed by jobId (cloud lane allows parallel renders). Same// client shape as videoGen/local.js so attachSseClient/broadcastSse work.@@ -132,7 +133,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_DEFAULT_DURATION;+ const effectiveDuration = resolveGrokDuration(duration);const jobId = providedJobId || randomUUID();const filename = `${jobId}.mp4`;