Skip to content

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

feat([issue-2859]): add Grok Build CLI video generation (phase 2)

[._.]/ Adam Eivy91152d5b3a09
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7030cb0163..dd8d349754 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Image generation
+- **[issue-2859] Grok can now generate videos too** — with Grok enabled, the Video Gen page gains a Local/Grok backend switch: Grok renders 6- or 10-second clips via its image-first flow (it generates a base image from your prompt, or animates a source image you pick, then runs its video tool). Clips land in the same render history with thumbnails, run in the parallel cloud queue lane alongside Grok/Codex image jobs, and never require local Python or GPU runtimes.
- **[issue-2859] xAI Grok (Grok Build CLI) is a new image-generation backend** — enable it in Settings → Image Gen → Grok CLI and every image surface (Image Gen page, pipeline renders, character sheets, universe builder batches, avatars, voice `image_generate`) can route through the Grok CLI's built-in `image_gen` tool, including image-to-image editing via `image_edit`. Configuration is just the binary path and an optional default aspect ratio — Grok picks the model internally. Grok renders run in the same parallel queue lane as Codex, and Grok video generation is planned as a follow-up phase.
## Tribe outreach
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 1c3cf7cdde..1557c994ed 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -65,6 +65,7 @@ import {
listImageGallery,
patchSettingsSlice,
getActiveVideoJob,
+ getSettings,
getVideoGenRuntimeStatus,
listLorasFull,
} from '../services/api';
@@ -101,7 +102,18 @@ export default function VideoGen() {
const [status, setStatus] = useState(null);
const [statusLoading, setStatusLoading] = useState(true);
+ // Grok Build CLI video backend (#2859 phase 2) — surfaced only when the
+ // user enabled Grok in Settings → Image Gen (one toggle covers image +
+ // video). 'local' keeps every existing flow untouched.
+ const [grokEnabled, setGrokEnabled] = useState(false);
+ const [backend, setBackend] = useState('local');
+ const [grokDuration, setGrokDuration] = useState(6);
const [models, setModels] = useState([]);
+ useEffect(() => {
+ getSettings({ silent: true })
+ .then((sv) => setGrokEnabled(sv?.imageGen?.grok?.enabled === true))
+ .catch(() => {});
+ }, []);
const [mode, setMode] = useState(incomingSourceImage ? 'image' : 'text');
const [prompt, setPrompt] = useState(incomingPrompt || '');
@@ -1023,8 +1035,25 @@ export default function VideoGen() {
// Snapshot the current form into a generate-payload. Used both by the
// inline Generate button and by enqueue, so the two paths stay in lockstep.
+ const isGrok = grokEnabled && backend === 'grok';
+
const buildGeneratePayload = () => {
const composed = composeStyledPrompt(prompt, negativePrompt, stylePreset);
+ if (isGrok) {
+ // Grok's image-first flow reads only these fields; width/height ride
+ // along so the server maps them to the closest supported aspect ratio.
+ return {
+ backend: 'grok',
+ prompt: composed.prompt,
+ negativePrompt: composed.negativePrompt,
+ grokDuration,
+ width: clampImageEdge(width, VIDEO_EDGE_BOUNDS),
+ height: clampImageEdge(height, VIDEO_EDGE_BOUNDS),
+ mode: mode === 'image' ? 'image' : 'text',
+ sourceImageFile: mode === 'image' ? (sourceImageFile || '') : '',
+ sourceImage: mode === 'image' ? (sourceImageUpload || '') : '',
+ };
+ }
// Append "no music, no soundtrack" only when the toggle is on AND audio
// generation is itself active — there's no point steering audio output
// when audio is disabled outright. Idempotent: if the user already
@@ -1163,7 +1192,7 @@ export default function VideoGen() {
// Without these guards the user could press Enter in the prompt
// textarea and fire a request the disabled button would otherwise
// have prevented.
- if (!prompt.trim() || generating || notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked || keyframesBlocked) return;
+ if (!prompt.trim() || generating || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked || keyframesBlocked))) return;
await runGeneration(buildGeneratePayload()).catch(() => {});
};
@@ -1172,7 +1201,7 @@ export default function VideoGen() {
// would silently queue a doomed job that fails late in the worker with
// VENV_MISSING, hiding the installer banner from the user. Block at
// enqueue time so the only path forward is the install banner above.
- if (!prompt.trim() || notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked || keyframesBlocked) return;
+ if (!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked || keyframesBlocked))) return;
// useVideoGenQueue strips the File blobs into `_blobs` and snapshots the
// rest as a stable summary for the queue UI.
enqueue(buildGeneratePayload());
@@ -1207,7 +1236,7 @@ export default function VideoGen() {
// ONLY a BYOV runtime via the modal would stay stuck behind a "not
// configured" error from the unrelated legacy probe.
const notConnected = !!status && status.connected === false && !needsByovProbe;
- const canEnqueue = prompt.trim() && !notConnected && !extendModeBlocked && !a2vModeBlocked && !byovGateBlocked && !keyframesBlocked;
+ const canEnqueue = prompt.trim() && (isGrok || (!notConnected && !extendModeBlocked && !a2vModeBlocked && !byovGateBlocked && !keyframesBlocked));
return (
<div className="space-y-3">
@@ -1276,13 +1305,41 @@ export default function VideoGen() {
);
})()}
+ {/* Backend switch — shown only when the user enabled Grok in Settings →
+ Image Gen. Grok's image_to_video supports text (image-first) and
+ image modes only, so switching to it snaps an unsupported mode back
+ to the nearest one. */}
+ {grokEnabled && (
+ <div className="bg-port-card border border-port-border rounded-xl p-1 flex gap-1" role="group" aria-label="Video generation backend">
+ {[{ id: 'local', label: 'Local' }, { id: 'grok', label: 'Grok' }].map(({ id, label }) => (
+ <button
+ key={id}
+ type="button"
+ aria-pressed={backend === id}
+ onClick={() => {
+ setBackend(id);
+ if (id === 'grok' && mode !== 'text' && mode !== 'image') {
+ setMode((sourceImageFile || sourceImageUpload) ? 'image' : 'text');
+ }
+ }}
+ className={`flex-1 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-colors ${
+ backend === id ? 'bg-port-accent text-white shadow' : 'text-gray-400 hover:text-white hover:bg-port-border/40'
+ }`}
+ title={id === 'grok' ? 'Render via the Grok Build CLI (image_gen → image_to_video). Counts against your Grok plan.' : 'Render on this machine with the local runtimes.'}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ )}
+
{/* Mode switch — segmented control above the form. Sets state that
both the form rendering and the submit payload react to.
Implemented as plain toggle buttons with `aria-pressed` rather than
WAI-ARIA Tabs, since the mode-specific inputs aren't structured as
tabpanels and we don't implement roving-tabindex/arrow-key focus. */}
<div className="bg-port-card border border-port-border rounded-xl p-1 flex flex-wrap gap-1" role="group" aria-label="Video generation mode">
- {MODES.map(({ id, label, icon: Icon, desc }) => {
+ {(isGrok ? MODES.filter((m) => m.id === 'text' || m.id === 'image') : MODES).map(({ id, label, icon: Icon, desc }) => {
const active = mode === id;
return (
<button
@@ -1306,7 +1363,7 @@ export default function VideoGen() {
<form onSubmit={handleGenerate} className="grid grid-cols-1 lg:grid-cols-[3fr_2fr] gap-4">
<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-3">
- {byovRuntimeMissing && (
+ {!isGrok && byovRuntimeMissing && (
<div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-3 text-xs text-port-warning flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
<div>
<strong className="font-semibold">{byovStatus.label}</strong> isn't installed yet.
@@ -1472,6 +1529,33 @@ export default function VideoGen() {
/>
)}
+ {isGrok ? (
+ <div className="grid grid-cols-2 gap-3">
+ <FormField label="Clip length" labelClassName="block text-xs font-medium text-gray-400 mb-1">
+ <select
+ value={grokDuration}
+ onChange={(e) => setGrokDuration(Number(e.target.value))}
+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ >
+ <option value={6}>6 seconds</option>
+ <option value={10}>10 seconds</option>
+ </select>
+ </FormField>
+ <ResolutionField
+ presets={VIDEO_RESOLUTIONS}
+ width={width}
+ height={height}
+ onChange={handleResolutionChange}
+ {...VIDEO_EDGE_BOUNDS}
+ snapOnBlur
+ note="Grok maps the size to its closest supported aspect ratio — exact pixel dimensions are chosen by the model."
+ />
+ <p className="col-span-2 text-[11px] text-gray-500 leading-snug">
+ Grok generates a base image first (or animates your source image in Image mode), then renders motion with its
+ <code className="text-gray-400"> image_to_video </code> tool. Model, frames, and seed are chosen by Grok; renders count against your Grok plan.
+ </p>
+ </div>
+ ) : (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
{models.length > 0 && (
<FormField className="col-span-2 sm:col-span-3" label="Model" labelClassName="block text-xs font-medium text-gray-400 mb-1">
@@ -1692,6 +1776,7 @@ export default function VideoGen() {
</label>
)}
</div>
+ )}
<div className="flex flex-wrap items-center gap-2 pt-1">
{generating ? (
@@ -1705,7 +1790,7 @@ export default function VideoGen() {
) : (
<button
type="submit"
- disabled={!prompt.trim() || notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked || keyframesBlocked}
+ disabled={!prompt.trim() || (!isGrok && (notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked || keyframesBlocked))}
className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"
title={
byovRuntimeMissing ? `${byovStatus?.label || byovRuntime} runtime is not installed — use the install banner above`
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 14846fd8e5..bfd609523e 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -18,6 +18,7 @@ import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.j
import { uploadFields } from '../lib/multipart.js';
import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';
import { safeUnder } from '../lib/ffmpeg.js';
+import { IMAGE_GEN_MODE } from '../services/imageGen/modes.js';
import { getSettings } from '../services/settings.js';
import { checkPackages, isAllowedPython } from '../lib/pythonSetup.js';
import { safeChildProcessEnv } from '../lib/processEnv.js';
@@ -107,6 +108,18 @@ const optionalInt = (min, max, label) => z.preprocess(
z.number().int().refine((n) => n >= min && n <= max, `${label} ${min}..${max}`).optional(),
);
const generateBodySchema = z.object({
+ // Render backend: the local runtimes (default) or the Grok Build CLI's
+ // image-first image_to_video flow (#2859 phase 2). Grok ignores the
+ // local-only knobs below; it reads prompt/negativePrompt, width/height
+ // (mapped to an aspect ratio), sourceImageFile/sourceImage, and
+ // 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.
+ grokDuration: z.preprocess(
+ (v) => (v == null || v === '' ? undefined : Number(v)),
+ z.union([z.literal(6), z.literal(10)]).optional(),
+ ),
prompt: z.string().min(1).max(8000),
negativePrompt: z.string().max(8000).optional(),
modelId: z.string().max(64).optional(),
@@ -591,7 +604,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
// shared with services/videoGen/local.js so the route and worker stay
// in sync.
const runtimeBringsOwnVenv = effectiveModel && BYOV_VIDEO_RUNTIMES.has(effectiveModel.runtime);
- if (!pythonPath && !runtimeBringsOwnVenv) {
+ if (!pythonPath && !runtimeBringsOwnVenv && body.backend !== 'grok') {
await cleanupTempUploads();
throw new ServerError(
'Local video generation is not configured (settings.imageGen.local.pythonPath is missing).',
@@ -713,6 +726,44 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
{ status: 400, code: 'MUSIC_VIDEO_SOURCE_REQUIRED' },
);
}
+ // Grok backend short-circuit (#2859 phase 2): everything past this point —
+ // last-frame/keyframe staging, extend resolution, LoRA gating — is
+ // local-runtime machinery grok doesn't use. sourceImagePath (upload or
+ // gallery pick) is already resolved above, so an i2v render animates that
+ // frame and a plain prompt runs the image-first image_gen → image_to_video
+ // flow inside the provider.
+ if (body.backend === 'grok') {
+ const g = s.imageGen?.grok || {};
+ if (!g.enabled) {
+ await cleanupAllStaged();
+ throw new ServerError(
+ 'Grok Imagegen is disabled — enable it in Settings → Image Gen first',
+ { status: 400, code: 'GROK_IMAGEGEN_DISABLED' },
+ );
+ }
+ const { jobId, position, status } = enqueueJob({
+ kind: 'video',
+ params: {
+ // `mode: 'grok'` is the queue's discriminator — the cloud lane and
+ // getGenModuleForJob route on it. Local video jobs use `mode` for
+ // the t2v/i2v semantic (text/image/fflf/…), which never collides
+ // with the literal 'grok'.
+ mode: IMAGE_GEN_MODE.GROK,
+ grokPath: g.grokPath,
+ aspectRatio: g.aspectRatio,
+ prompt: body.prompt,
+ negativePrompt: body.negativePrompt || '',
+ width: body.width,
+ height: body.height,
+ duration: body.grokDuration,
+ sourceImagePath,
+ uploadedTempPath,
+ ...(body.musicVideo ? { musicVideo: body.musicVideo } : {}),
+ },
+ });
+ return res.json({ jobId, generationId: jobId, filename: `${jobId}.mp4`, model: 'grok', mode: 'grok', status, position });
+ }
+
if (uploads.lastImage) {
lastImagePath = await stageUploadDurable(uploads.lastImage, 'last');
extraUploadedTempPaths.push(lastImagePath);
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 1bc3f22cd2..4fe4357c84 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -235,6 +235,59 @@ describe('videoGen routes', () => {
});
});
+ describe('POST / — grok backend (#2859 phase 2)', () => {
+ it('enqueues a grok video job with the saved grok config and no local-python dependency', async () => {
+ const { getSettings } = await import('../services/settings.js');
+ // No local pythonPath at all — grok must not trip VIDEO_GEN_NOT_CONFIGURED.
+ getSettings.mockResolvedValueOnce({ imageGen: { grok: { enabled: true, grokPath: '/opt/grok', aspectRatio: '16:9' } } });
+ const r = await request(app).post('/api/video-gen/').send({
+ backend: 'grok',
+ prompt: 'a fox running through snow',
+ grokDuration: '10',
+ width: 1920,
+ height: 1080,
+ });
+ expect(r.status).toBe(200);
+ expect(r.body.status).toBe('queued');
+ expect(r.body.mode).toBe('grok');
+ expect(r.body.model).toBe('grok');
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'video',
+ params: expect.objectContaining({
+ mode: 'grok',
+ grokPath: '/opt/grok',
+ aspectRatio: '16:9',
+ prompt: 'a fox running through snow',
+ duration: 10,
+ width: 1920,
+ height: 1080,
+ }),
+ }));
+ });
+
+ it('rejects when the grok toggle is disabled', async () => {
+ const { getSettings } = await import('../services/settings.js');
+ getSettings.mockResolvedValueOnce({ imageGen: { grok: { enabled: false } } });
+ const r = await request(app).post('/api/video-gen/').send({ backend: 'grok', prompt: 'a fox' });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/disabled/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unsupported grokDuration', async () => {
+ const r = await request(app).post('/api/video-gen/').send({ backend: 'grok', prompt: 'a fox', grokDuration: 7 });
+ expect(r.status).toBe(400);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('does not touch the grok path for default local renders', async () => {
+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a cat' });
+ expect(r.status).toBe(200);
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.mode).not.toBe('grok');
+ });
+ });
+
describe('POST /', () => {
it('rejects missing prompt', async () => {
const r = await request(app).post('/api/video-gen/').send({ width: 512 });
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 286fe4ba5b..3ef7a7d620 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -47,13 +47,16 @@ import { audioGenEvents } from '../audioGen/events.js';
import { getSettings } from '../settings.js';
import { IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES } from '../imageGen/modes.js';
-// Cloud-CLI image jobs (codex, grok) share one parallel lane — each render
+// Cloud-CLI jobs (codex/grok images, grok videos) share one parallel lane —
+// each render
// shells out to its own external child spending remote quota, so they don't
// serialize on the MLX runtime the way GPU jobs do. The lane's slot count is
// `codexParallelLimit` (settings key `imageGen.codex.parallelLimit`, kept
// under the codex name for backward compat — it now bounds codex + grok
// renders combined).
-const isCloudImageJob = (j) => j.kind === 'image' && CLOUD_IMAGE_GEN_MODES.includes(j.params?.mode);
+const isCloudImageJob = (j) =>
+ (j.kind === 'image' && CLOUD_IMAGE_GEN_MODES.includes(j.params?.mode))
+ || (j.kind === 'video' && j.params?.mode === IMAGE_GEN_MODE.GROK);
const JOBS_FILE = join(PATHS.data, 'media-jobs.json');
const COMPLETED_TTL_MS = 24 * 60 * 60 * 1000;
@@ -129,6 +132,7 @@ export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'fa
// of provider-dispatch truth — used by the watchdog, runJob, and cancelJob
// so a new provider addition is one edit instead of three.
function getGenModuleForJob(job) {
+ if (job.kind === 'video' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../videoGen/grok.js');
if (job.kind === 'video') return import('../videoGen/local.js');
if (job.kind === 'training') return import('../loraTraining/index.js');
if (job.kind === 'audio') return import('../audioGen/local.js');
@@ -158,7 +162,7 @@ async function resolveLiveParams(job, safeParams) {
// mflux training runs in the same venv as local image renders, so the
// live settings pythonPath wins there too. flux2 training resolves its
// own venv (resolveFlux2Python) inside runTraining — skip it here.
- const usesLocalPython = job.kind === 'video'
+ const usesLocalPython = (job.kind === 'video' && job.params?.mode !== IMAGE_GEN_MODE.GROK)
|| (job.kind === 'image' && !CLOUD_IMAGE_GEN_MODES.includes(job.params?.mode))
|| (job.kind === 'training' && job.params?.runtime === 'mflux');
if (!usesLocalPython) return;
@@ -786,10 +790,13 @@ async function runJob(job) {
// imageGen/videoGen/local.js#handleLine emits 'activity' which resets
// lastActivityAt; only true hangs (process wedged, no output) trip it.
const idleTimeoutMs = (() => {
+ // Cloud check first — a grok VIDEO job must take the cloud watchdog, not
+ // the chunk-scaled local-video one (the provider emits 'activity' on
+ // stdout so a long-but-active render never trips the idle cap).
+ if (isCloudImageJob(job)) return WATCHDOG_CODEX_MS;
if (job.kind === 'video') return WATCHDOG_VIDEO_MS * Math.max(1, Number(safeParams.chunks) || 1);
if (job.kind === 'training') return WATCHDOG_TRAINING_MS;
if (job.kind === 'audio') return WATCHDOG_AUDIO_MS;
- if (isCloudImageJob(job)) return WATCHDOG_CODEX_MS;
return WATCHDOG_IMAGE_MS;
})();
let lastActivityAt = Date.now();
diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.js
new file mode 100644
index 0000000000..b0f6ab96cf
--- /dev/null
+++ b/server/services/videoGen/grok.js
@@ -0,0 +1,326 @@
+/**
+ * Video Gen — xAI Grok Build CLI provider (image-first flow).
+ *
+ * Grok has no text-to-video tool: its `image_to_video` animates a source
+ * image (durations 6s/10s). So the flow, following grok's bundled
+ * `game-animation-frames` skill, is image-first — one headless agent turn
+ * that (1) generates a base image with `image_gen` when the caller didn't
+ * supply one, then (2) animates it with `image_to_video`, saving the MP4 to
+ * a directed scratch path PortOS harvests. When the caller supplies a
+ * source image (i2v from the gallery or an upload), step 1 is skipped and
+ * `image_to_video` runs on it directly.
+ *
+ * Mirrors the imageGen/grok.js provider's lifecycle (scratch-cwd
+ * confinement, signature sniff, tree-kill on cancel — see that module's
+ * containment note) and hands the harvested file to the shared
+ * `finalizeGeneratedVideo` helper so streaming optimization, thumbnailing,
+ * the history entry, and the completed events all match local renders.
+ *
+ * The user gate is the same `imageGen.grok.enabled` toggle as image
+ * generation — one Grok backend, both media kinds. The route rejects
+ * disabled/missing-binary up front; this module assumes it's enabled.
+ */
+
+import { spawn } from 'child_process';
+import { copyFile, mkdir, open, rename, rm, stat, unlink } from 'fs/promises';
+import { isAbsolute, join, resolve as pathResolve, sep } from 'path';
+import { tmpdir } from 'os';
+import { randomUUID } from 'crypto';
+import { ensureDir, PATHS } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
+import { killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';
+import { ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../../lib/grok.js';
+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';
+
+// 30 minutes — an image-first video turn is two sequential tool calls
+// (image_gen then image_to_video render + download), so it runs meaningfully
+// longer than a single image. Keep this ABOVE the mediaJobQueue cloud-lane
+// idle watchdog (20 min) — the provider emits `activity` on every stdout
+// chunk (grok narrates while it works), so the idle watchdog only trips on
+// a truly silent hang while this wall-clock cap bounds the whole run.
+const GROK_VIDEO_TIMEOUT_MS = (() => {
+ const n = Number(process.env.GROK_VIDEO_TIMEOUT_MS);
+ return Number.isFinite(n) && n > 0 ? n : 30 * 60 * 1000;
+})();
+
+const DEFAULT_BIN = 'grok';
+
+// Durations grok's image_to_video tool accepts, in seconds.
+export const GROK_VIDEO_DURATIONS = Object.freeze([6, 10]);
+
+// Per-job state — keyed by jobId (cloud lane allows parallel renders). Same
+// client shape as videoGen/local.js so attachSseClient/broadcastSse work.
+const jobs = new Map();
+const activeProcs = new Map();
+const activeJobs = new Map();
+
+export const getActiveJob = () => {
+ const entries = [...activeJobs.values()];
+ return entries.length ? entries[entries.length - 1] : null;
+};
+
+export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);
+
+const sigtermWithEscalation = (id, proc) => {
+ if (process.platform === 'win32') {
+ // prepareCliSpawn wraps a .cmd shim in cmd.exe on Windows — taskkill /T
+ // the whole tree so the real grok child dies too (mirrors imageGen/grok.js).
+ killProcessTree(proc);
+ return;
+ }
+ killWithEscalation(proc, { label: 'grok video child', delayMs: 5000, stillRunning: () => activeProcs.get(id) === proc });
+};
+
+export const cancel = (jobId) => {
+ if (!jobId) {
+ throw new Error("videoGen/grok.cancel requires a jobId — use cancelAll() to terminate every in-flight render");
+ }
+ const proc = activeProcs.get(jobId);
+ if (!proc) return false;
+ sigtermWithEscalation(jobId, proc);
+ return true;
+};
+
+export const cancelAll = () => {
+ const entries = [...activeProcs.entries()];
+ if (entries.length === 0) return false;
+ for (const [id, proc] of entries) sigtermWithEscalation(id, proc);
+ return true;
+};
+
+// MP4/QuickTime signature: a top-level `ftyp` box at byte offset 4. Grok is
+// directed to save MP4; anything else (webm, text error, truncated file) is
+// rejected rather than shipped into the gallery mislabeled.
+const isMp4Header = (buf) =>
+ Buffer.isBuffer(buf) && buf.length >= 8
+ && buf[4] === 0x66 && buf[5] === 0x74 && buf[6] === 0x79 && buf[7] === 0x70;
+
+// Build the single-turn agent prompt for the image-first flow. Explicit about
+// the tools, the save path, and staying out of everything else (the child is
+// additionally cwd-confined to the scratch dir).
+export function buildGrokVideoPrompt({ prompt, negativePrompt, aspectRatio, duration, stagingPath, sourceImagePath, scratchDir }) {
+ const avoid = negativePrompt?.trim() ? `\nAvoid: ${negativePrompt.trim()}` : '';
+ const ratio = aspectRatio ? `\nUse aspect_ratio "${aspectRatio}" for the base image.` : '';
+ const steps = sourceImagePath
+ ? `Use your built-in image_to_video tool to animate the source image at ${sourceImagePath} for ${duration} seconds.\nMotion/direction prompt: ${prompt.trim()}${avoid}`
+ : `First, use your built-in image_gen tool to generate one base image for this prompt and save it as ${join(scratchDir, 'base.png')}:\n${prompt.trim()}${avoid}${ratio}\nThen use your built-in image_to_video tool to animate that base image for ${duration} seconds, using the same prompt as the motion description.`;
+ return `${steps}\nSave the resulting video as an MP4 file at exactly this path: ${stagingPath}\nDo not create any other files, do not modify any code, and do not run any other tools beyond what is needed to generate the image/video and write the MP4 to that path. When the file is written, you are done.`;
+}
+
+export async function generateVideo({
+ grokPath, aspectRatio, prompt = '', negativePrompt, width, height,
+ sourceImagePath = null, duration,
+ jobId: providedJobId = null,
+}) {
+ await ensureDir(PATHS.videos);
+
+ if (!prompt?.trim()) {
+ 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 jobId = providedJobId || randomUUID();
+ const filename = `${jobId}.mp4`;
+ const outputPath = join(PATHS.videos, filename);
+ // Per-job scratch dir doubles as the child's cwd (containment) and holds
+ // both the intermediate base image and the staged MP4. Removed on every
+ // terminal path.
+ const scratchDir = join(tmpdir(), `portos-grok-video-${jobId}`);
+ const stagingPath = join(scratchDir, 'output.mp4');
+ await mkdir(scratchDir, { recursive: true });
+
+ const derived = deriveAspectRatio(width, height);
+ const configured = GROK_ASPECT_RATIOS.includes(aspectRatio) ? aspectRatio : null;
+ const effectiveRatio = derived || configured;
+
+ const fullPrompt = buildGrokVideoPrompt({
+ prompt, negativePrompt, aspectRatio: effectiveRatio, duration: effectiveDuration,
+ stagingPath, sourceImagePath, scratchDir,
+ });
+
+ const bin = grokPath || DEFAULT_BIN;
+ const baseArgs = ensureGrokHeadlessArgs([], null);
+ const { args, useStdin, cleanup: cleanupPromptFile } = prepareGrokPromptFile(baseArgs, fullPrompt);
+
+ // History/meta shape mirrors local.js's fields that the Media History
+ // consumers (normalize.js, the lightbox) actually read; grok has no
+ // seed/steps/fps knobs so those stay absent. `modelId: 'grok'` tags the
+ // record's engine for the grid badge and keeps Remix from offering
+ // local-only dials.
+ const meta = {
+ id: jobId,
+ prompt: prompt.trim(),
+ negativePrompt: negativePrompt || '',
+ modelId: 'grok',
+ duration: effectiveDuration,
+ ...(effectiveRatio ? { aspectRatio: effectiveRatio } : {}),
+ filename,
+ createdAt: new Date().toISOString(),
+ mode: sourceImagePath ? 'image' : 'text',
+ };
+ const job = { ...meta, clients: [], status: 'running' };
+ jobs.set(jobId, job);
+
+ console.log(`🎬 Generating video [${jobId.slice(0, 8)}] grok: ${prompt.slice(0, 60)}…`);
+ videoGenEvents.emit('started', { generationId: jobId, totalSteps: 1, ...meta });
+ activeJobs.set(jobId, { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0 });
+ broadcastSse(job, { type: 'status', message: 'Spawning grok…' });
+
+ runGrokVideo(job, jobId, bin, args, {
+ useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta,
+ }).catch((err) => {
+ console.log(`❌ grok video run failed [${jobId.slice(0, 8)}]: ${err?.message}`);
+ });
+
+ return {
+ jobId, filename, path: `/data/videos/${filename}`, generationId: jobId,
+ mode: 'grok',
+ status: 'running',
+ };
+}
+
+async function runGrokVideo(job, jobId, bin, args, {
+ useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta,
+}) {
+ // Resolve a path-shaped grokPath against the PortOS cwd before the child's
+ // cwd moves to the scratch dir; bare names stay bare for PATH lookup.
+ const resolvedBin = (!isAbsolute(bin) && (bin.includes('/') || bin.includes(sep))) ? pathResolve(bin) : bin;
+ const { command: spawnBin, args: spawnArgs } = prepareCliSpawn(resolvedBin, args);
+ const proc = spawn(spawnBin, spawnArgs, { cwd: scratchDir, shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
+ activeProcs.set(jobId, proc);
+ const removeScratch = () => rm(scratchDir, { recursive: true, force: true }).catch(() => {});
+
+ if (useStdin) {
+ proc.stdin.on('error', () => {});
+ proc.stdin.write(fullPrompt);
+ proc.stdin.end();
+ }
+
+ let stdoutTail = '';
+ const STDOUT_TAIL_BYTES = 8 * 1024;
+ let stderrTail = '';
+ const STDERR_TAIL_BYTES = 32 * 1024;
+ const timeoutTimer = setTimeout(() => {
+ if (activeProcs.get(jobId) === proc) {
+ console.log(`⏱️ grok video timed out after ${GROK_VIDEO_TIMEOUT_MS}ms [${jobId.slice(0, 8)}]`);
+ sigtermWithEscalation(jobId, proc);
+ }
+ }, GROK_VIDEO_TIMEOUT_MS);
+
+ proc.on('error', (err) => {
+ clearTimeout(timeoutTimer);
+ cleanupPromptFile();
+ removeScratch();
+ finalizeError(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
+ });
+
+ proc.stdout.on('data', (chunk) => {
+ stdoutTail += chunk.toString();
+ if (stdoutTail.length > STDOUT_TAIL_BYTES) stdoutTail = stdoutTail.slice(-STDOUT_TAIL_BYTES);
+ broadcastSse(job, { type: 'status', message: 'Running…' });
+ // Feed the mediaJobQueue's idle watchdog — grok narrates while working,
+ // so a genuinely wedged child stops emitting and still trips the 20-min
+ // idle cap, while a long-but-active image_to_video render doesn't.
+ videoGenEvents.emit('activity', { generationId: jobId });
+ });
+
+ proc.stderr.on('data', (chunk) => {
+ const text = chunk.toString();
+ stderrTail += text;
+ if (stderrTail.length > STDERR_TAIL_BYTES) stderrTail = stderrTail.slice(-STDERR_TAIL_BYTES);
+ videoGenEvents.emit('activity', { generationId: jobId });
+ });
+
+ proc.on('close', async (code, signal) => {
+ clearTimeout(timeoutTimer);
+ cleanupPromptFile();
+ try {
+ if (code !== 0) {
+ const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;
+ const tail = stderrTail.trim().split('\n').slice(-6).join('\n');
+ removeScratch();
+ return finalizeError(job, jobId, proc, `Grok video generation failed: ${reason}\n${tail}`);
+ }
+ const harvested = await harvestStagedVideo(stagingPath, 10000);
+ if (!harvested.found) {
+ removeScratch();
+ const prefix = harvested.invalid ? 'Grok wrote a non-MP4 file at the directed path. ' : '';
+ return finalizeError(job, jobId, proc, `${prefix}${noVideoReason(stdoutTail)}`);
+ }
+ // Move, not copy (metadata-only when tmp and the videos dir share a
+ // filesystem); copy+unlink is the cross-device fallback.
+ await rename(stagingPath, outputPath).catch(async () => {
+ await copyFile(stagingPath, outputPath);
+ await unlink(stagingPath).catch(() => {});
+ });
+ removeScratch();
+ if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
+ activeJobs.delete(jobId);
+ // Shared finalizer: faststart optimization, thumbnail, history entry,
+ // SSE complete + videoGenEvents 'completed' — identical to local
+ // renders so every downstream consumer (history grid, media index,
+ // completion hooks) sees the same contract.
+ await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed: null, mutateHistory: mutateVideoHistory });
+ closeJobAfterDelay(jobs, jobId);
+ } catch (err) {
+ removeScratch();
+ finalizeError(job, jobId, proc, `Grok video post-exit handler failed: ${err?.message || err}`);
+ }
+ });
+}
+
+// Reuse the image provider's narration-tail formatting but with video wording.
+function noVideoReason(stdoutTail = '') {
+ const reason = noImageReason(stdoutTail);
+ return reason
+ .replace('Grok returned no image', 'Grok returned no video')
+ .replace('Grok did not produce an image at the directed path', 'Grok did not produce a video at the directed path')
+ .replace('the image_gen tool may be unavailable', 'the image_to_video tool may be unavailable');
+}
+
+const finalizeError = (job, jobId, proc, reason) => {
+ if (job.status === 'error' || job.status === 'complete') return;
+ if (proc == null || activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
+ job.status = 'error';
+ activeJobs.delete(jobId);
+ console.log(`❌ grok video generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
+ broadcastSse(job, { type: 'error', error: reason });
+ videoGenEvents.emit('failed', { generationId: jobId, error: reason });
+ closeJobAfterDelay(jobs, jobId);
+};
+
+// Poll for the directed MP4 until it exists non-empty with an `ftyp` header,
+// or timeoutMs elapses. { found, invalid } mirrors the image harvest —
+// `invalid` means a non-empty file appeared that never matched MP4.
+async function harvestStagedVideo(stagingPath, timeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ let sawInvalid = false;
+ while (Date.now() < deadline) {
+ const s = await stat(stagingPath).catch(() => null);
+ if (s && s.size > 0) {
+ const head = Buffer.alloc(12);
+ const fh = await open(stagingPath, 'r').catch(() => null);
+ if (fh) {
+ const { bytesRead } = await fh.read(head, 0, 12, 0).catch(() => ({ bytesRead: 0 }));
+ await fh.close().catch(() => {});
+ if (isMp4Header(head.subarray(0, bytesRead))) return { found: true, invalid: false };
+ sawInvalid = true;
+ }
+ }
+ await new Promise((r) => setTimeout(r, 250));
+ }
+ return { found: false, invalid: sawInvalid };
+}
+
+// Test-only handles (mirrors imageGen/grok.js's carve-out).
+export const _internals = {
+ harvestStagedVideo,
+ buildGrokVideoPrompt,
+ isMp4Header,
+};
diff --git a/server/services/videoGen/grok.test.js b/server/services/videoGen/grok.test.js
new file mode 100644
index 0000000000..aa0144d6be
--- /dev/null
+++ b/server/services/videoGen/grok.test.js
@@ -0,0 +1,246 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { mkdir, writeFile, rm, readFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { EventEmitter } from 'events';
+
+// Spawn mock — capture calls, drive stdout/stderr, capture the stdin-delivered
+// prompt (grok reads it via --prompt-file /dev/stdin).
+const spawnCalls = [];
+const makeFakeChild = () => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.stdin = { written: '', on: vi.fn(), write: vi.fn(function (s) { child.stdin.written += s; }), end: vi.fn() };
+ child.kill = vi.fn();
+ child.exitCode = null;
+ child.signalCode = null;
+ return child;
+};
+vi.mock('child_process', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ spawn: vi.fn((bin, args) => {
+ const child = makeFakeChild();
+ spawnCalls.push({ bin, args, child });
+ return child;
+ }),
+ };
+});
+
+// Test-root PATHS so the harvest move + history file land somewhere we can
+// read back (mirrors imageGen/grok.test.js).
+const TEST_ROOT = join(tmpdir(), `portos-grok-video-test-${process.pid}-${Date.now()}`);
+const FAKE_VIDEOS_DIR = join(TEST_ROOT, 'data-videos');
+const FAKE_DATA_DIR = join(TEST_ROOT, 'data');
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ actual.PATHS.videos = FAKE_VIDEOS_DIR;
+ actual.PATHS.data = FAKE_DATA_DIR;
+ return {
+ ...actual,
+ ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
+ };
+});
+
+// finalizeGeneratedVideo shells out to ffmpeg (faststart + thumbnail) — stub
+// the ffmpeg layer so the shared finalizer's history/SSE/event flow still
+// runs for real against fake MP4 bytes.
+vi.mock('../../lib/ffmpeg.js', async () => {
+ const actual = await vi.importActual('../../lib/ffmpeg.js');
+ return {
+ ...actual,
+ optimizeForStreaming: vi.fn(async () => {}),
+ generateThumbnail: vi.fn(async (_p, jobId) => `${jobId}.jpg`),
+ };
+});
+
+const grok = await import('./grok.js');
+const { videoGenEvents } = await import('./events.js');
+const { loadHistory } = await import('./history.js');
+
+const flush = () => new Promise((r) => setImmediate(r));
+const scratchDirFor = (jobId) => join(tmpdir(), `portos-grok-video-${jobId}`);
+const stagingPathFor = (jobId) => join(scratchDirFor(jobId), 'output.mp4');
+const promptOf = (i = 0) => spawnCalls[i].child.stdin.written;
+const closeChild = async (i = 0, code = 1) => {
+ spawnCalls[i].child.exitCode = code;
+ spawnCalls[i].child.emit('close', code, null);
+ await flush();
+};
+// Minimal valid MP4 header: size box + `ftyp` at offset 4.
+const MP4_BYTES = Buffer.concat([
+ Buffer.from([0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70]),
+ Buffer.from('isommp42-fake-payload'),
+]);
+
+beforeEach(async () => {
+ spawnCalls.length = 0;
+ videoGenEvents.removeAllListeners();
+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});
+ await mkdir(FAKE_DATA_DIR, { recursive: true });
+});
+
+afterEach(async () => {
+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});
+});
+
+describe('videoGen/grok — generateVideo', () => {
+ it('spawns grok headlessly and prompts the image-first flow for text mode', async () => {
+ const job = await grok.generateVideo({ prompt: 'a fox running' });
+ expect(job.mode).toBe('grok');
+ expect(job.filename).toMatch(/^[0-9a-f-]{36}\.mp4$/);
+ expect(job.status).toBe('running');
+ const { bin, args } = spawnCalls[0];
+ expect(bin).toBe('grok');
+ expect(args).toEqual(expect.arrayContaining(['--permission-mode', 'bypassPermissions']));
+ const prompt = promptOf();
+ // Image-first: base image via image_gen, then image_to_video.
+ expect(prompt).toContain('image_gen');
+ expect(prompt).toContain('image_to_video');
+ expect(prompt).toContain('a fox running');
+ expect(prompt).toContain(stagingPathFor(job.jobId));
+ // Default duration is the shortest supported clip.
+ expect(prompt).toContain('6 seconds');
+ await closeChild();
+ });
+
+ it('skips the base-image step when a source image is supplied', async () => {
+ await grok.generateVideo({ prompt: 'gentle pan', sourceImagePath: '/abs/frame.png', duration: 10 });
+ const prompt = promptOf();
+ expect(prompt).not.toContain('image_gen');
+ expect(prompt).toContain('image_to_video');
+ expect(prompt).toContain('/abs/frame.png');
+ expect(prompt).toContain('10 seconds');
+ await closeChild();
+ });
+
+ it('falls back to 6s for an unsupported duration', async () => {
+ await grok.generateVideo({ prompt: 'a fox', duration: 42 });
+ expect(promptOf()).toContain('6 seconds');
+ await closeChild();
+ });
+
+ it('derives the base-image aspect ratio from width/height', async () => {
+ await grok.generateVideo({ prompt: 'a fox', width: 1920, height: 1080 });
+ expect(promptOf()).toContain('aspect_ratio "16:9"');
+ await closeChild();
+ });
+
+ it('rejects an empty prompt', async () => {
+ await expect(grok.generateVideo({ prompt: ' ' })).rejects.toThrow(/Prompt is required/);
+ });
+
+ it('emits started on videoGenEvents with the job meta', async () => {
+ const started = vi.fn();
+ videoGenEvents.on('started', started);
+ const job = await grok.generateVideo({ prompt: 'a fox' });
+ expect(started).toHaveBeenCalledWith(expect.objectContaining({ generationId: job.jobId, modelId: 'grok' }));
+ await closeChild();
+ });
+
+ it('emits activity on stdout so the queue idle watchdog resets', async () => {
+ const activity = vi.fn();
+ videoGenEvents.on('activity', activity);
+ const job = await grok.generateVideo({ prompt: 'a fox' });
+ spawnCalls[0].child.stdout.emit('data', Buffer.from('rendering…\n'));
+ expect(activity).toHaveBeenCalledWith({ generationId: job.jobId });
+ await closeChild();
+ });
+});
+
+describe('videoGen/grok — harvest and finalize', () => {
+ it('moves a staged MP4 into PATHS.videos, writes history, and emits completed', async () => {
+ const completed = vi.fn();
+ videoGenEvents.on('completed', completed);
+
+ const job = await grok.generateVideo({ prompt: 'a fox running' });
+ await mkdir(scratchDirFor(job.jobId), { recursive: true });
+ await writeFile(stagingPathFor(job.jobId), MP4_BYTES);
+ await closeChild(0, 0);
+
+ const deadline = Date.now() + 5000;
+ while (Date.now() < deadline && completed.mock.calls.length === 0) {
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ expect(completed).toHaveBeenCalledTimes(1);
+ expect(completed.mock.calls[0][0]).toEqual(expect.objectContaining({
+ generationId: job.jobId,
+ path: `/data/videos/${job.filename}`,
+ thumbnail: `${job.jobId}.jpg`,
+ }));
+ const written = await readFile(join(FAKE_VIDEOS_DIR, job.filename));
+ expect(Buffer.compare(written, MP4_BYTES)).toBe(0);
+ // Scratch dir cleaned up; history entry recorded with the grok engine tag.
+ expect(existsSync(scratchDirFor(job.jobId))).toBe(false);
+ const history = await loadHistory();
+ expect(history[0]).toEqual(expect.objectContaining({ id: job.jobId, modelId: 'grok', mode: 'text', duration: 6 }));
+ });
+
+ it('rejects a staged file that is not MP4 (signature sniff)', async () => {
+ const failed = vi.fn();
+ videoGenEvents.on('failed', failed);
+
+ const job = await grok.generateVideo({ prompt: 'a fox' });
+ await mkdir(scratchDirFor(job.jobId), { recursive: true });
+ await writeFile(stagingPathFor(job.jobId), 'Error: render failed');
+ await closeChild(0, 0);
+
+ const deadline = Date.now() + 13000;
+ while (Date.now() < deadline && failed.mock.calls.length === 0) {
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ expect(failed).toHaveBeenCalledTimes(1);
+ expect(failed.mock.calls[0][0].error).toMatch(/non-MP4 file/);
+ expect(existsSync(join(FAKE_VIDEOS_DIR, job.filename))).toBe(false);
+ expect(existsSync(scratchDirFor(job.jobId))).toBe(false);
+ }, 16000);
+
+ it('fails with the narration tail when grok exits 0 with no file', async () => {
+ const failed = vi.fn();
+ videoGenEvents.on('failed', failed);
+
+ await grok.generateVideo({ prompt: 'a fox' });
+ spawnCalls[0].child.stdout.emit('data', Buffer.from('I cannot animate that.\n'));
+ await closeChild(0, 0);
+
+ const deadline = Date.now() + 13000;
+ while (Date.now() < deadline && failed.mock.calls.length === 0) {
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ expect(failed).toHaveBeenCalledTimes(1);
+ expect(failed.mock.calls[0][0].error).toMatch(/I cannot animate that/);
+ // Video-flavored wording, not the image provider's.
+ expect(failed.mock.calls[0][0].error).toMatch(/video/i);
+ }, 16000);
+
+ it('fails with the stderr tail on non-zero exit', async () => {
+ const failed = vi.fn();
+ videoGenEvents.on('failed', failed);
+ await grok.generateVideo({ prompt: 'a fox' });
+ spawnCalls[0].child.stderr.emit('data', Buffer.from('boom: session expired\n'));
+ await closeChild(0, 1);
+ expect(failed).toHaveBeenCalledTimes(1);
+ expect(failed.mock.calls[0][0].error).toMatch(/Exit code 1/);
+ expect(failed.mock.calls[0][0].error).toMatch(/session expired/);
+ });
+});
+
+describe('videoGen/grok — cancel', () => {
+ it('cancel() requires a jobId; cancel(jobId) SIGTERMs; cancelAll() sweeps', async () => {
+ expect(() => grok.cancel()).toThrow(/requires a jobId/);
+ const a = await grok.generateVideo({ prompt: 'one' });
+ const b = await grok.generateVideo({ prompt: 'two' });
+ expect(grok.cancel(a.jobId)).toBe(true);
+ expect(spawnCalls[0].child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(spawnCalls[1].child.kill).not.toHaveBeenCalled();
+ expect(grok.cancelAll()).toBe(true);
+ expect(spawnCalls[1].child.kill).toHaveBeenCalledWith('SIGTERM');
+ await closeChild(0);
+ await closeChild(1);
+ expect(grok.cancel(b.jobId)).toBe(false);
+ expect(grok.cancelAll()).toBe(false);
+ });
+});