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
address review (codex): job-scoped video cancel, grok state restore, upload cleanup, forced terminal on finalize throw
[._.]/ Adam Eivyfa379665079f
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 1557c994ed..272db8135c 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -98,7 +98,12 @@ export default function VideoGen() {const incomingHeight = searchParams.get('h');const settingsOpen = searchParams.get('settings') === '1';const openSettings = () => setSearchParams(prev => { const n = new URLSearchParams(prev); n.set('settings', '1'); return n; });- const closeSettings = () => setSearchParams(prev => { const n = new URLSearchParams(prev); n.delete('settings'); return n; });+ const closeSettings = () => {+ setSearchParams(prev => { const n = new URLSearchParams(prev); n.delete('settings'); return n; });+ // The drawer hosts the Grok enable toggle — re-read it so the+ // Local/Grok backend switch appears/disappears without a reload.+ refreshGrokEnabled();+ };const [status, setStatus] = useState(null);const [statusLoading, setStatusLoading] = useState(true);@@ -106,14 +111,18 @@ export default function VideoGen() {// user enabled Grok in Settings → Image Gen (one toggle covers image +// video). 'local' keeps every existing flow untouched.const [grokEnabled, setGrokEnabled] = useState(false);+ // The jobId of the render this tab's Generate button currently owns —+ // threaded into cancelVideoGen so cancellation is job-scoped.+ const activeJobIdRef = useRef(null);const [backend, setBackend] = useState('local');const [grokDuration, setGrokDuration] = useState(6);const [models, setModels] = useState([]);- useEffect(() => {+ const refreshGrokEnabled = useCallback(() => {getSettings({ silent: true }).then((sv) => setGrokEnabled(sv?.imageGen?.grok?.enabled === true)).catch(() => {});}, []);+ useEffect(() => { refreshGrokEnabled(); }, [refreshGrokEnabled]);const [mode, setMode] = useState(incomingSourceImage ? 'image' : 'text');const [prompt, setPrompt] = useState(incomingPrompt || '');@@ -604,7 +613,12 @@ export default function VideoGen() {if (p.seed != null) setSeed(String(p.seed));if (p.tiling) setTiling(p.tiling);if (typeof p.disableAudio === 'boolean') setDisableAudio(p.disableAudio);- if (p.mode) setMode(p.mode);+ if (p.mode === 'grok') {+ // Grok job: 'grok' is the queue discriminator, not a semantic video+ // mode — restore the backend switch and the real t2v/i2v mode.+ setBackend('grok');+ setMode(p.videoMode === 'image' ? 'image' : 'text');+ } else if (p.mode) setMode(p.mode);if (p.chunks && p.chunks > 1) setChunks(p.chunks);// Multi-keyframe FFLF: the route maps the stored { path, index } back to// { file, index } (gallery basename) for us, so restore the picker@@ -1151,6 +1165,11 @@ export default function VideoGen() {// earlier handleCancel() already settled the Promise via runRejectRef.if (!isCurrent()) return;const jobId = data.jobId || data.generationId;+ // Remember which job this run owns — with the cloud lane, video+ // renders are no longer single-flight, so Cancel must target exactly+ // this job instead of "the first running video" (which could be an+ // unrelated local or grok render).+ activeJobIdRef.current = jobId;attachJobEvents(jobId, { isCurrent, settleResolve, settleReject, withToast: true });}).catch((err) => {if (!isCurrent()) return;@@ -1213,7 +1232,8 @@ export default function VideoGen() {// EventSource for a job we've already declared cancelled.runTokenRef.current += 1;eventSourceRef.current?.close();- await cancelVideoGen().catch(() => {});+ await cancelVideoGen(activeJobIdRef.current || undefined).catch(() => {});+ activeJobIdRef.current = null;setGenerating(false);setStatusMsg('Cancelled');// Settle the in-flight runGeneration Promise so the queue worker's@@ -1840,8 +1860,8 @@ export default function VideoGen() {onClear={clearFinishedQueue}summarize={(item) => (<>- <span className="uppercase mr-2">{item.params.mode}</span>- {item.params.width}×{item.params.height} · {item.params.numFrames}f+ <span className="uppercase mr-2">{item.params.backend === 'grok' ? `grok ${item.params.mode}` : item.params.mode}</span>+ {item.params.width}×{item.params.height} · {item.params.backend === 'grok' ? `${item.params.grokDuration || 6}s` : `${item.params.numFrames}f`}</>)}/>diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex 62a0f32ff8..acb27c97f4 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -176,7 +176,13 @@ export const repairTextEncoder = ({ deep = false } = {}) => request('/video-gen/body: JSON.stringify({ deep }),silent: true,});-export const cancelVideoGen = () => request('/video-gen/cancel', { method: 'POST' });+// With the cloud lane, video renders are no longer single-flight — pass the+// jobId so the server cancels exactly this render, not "the first running+// video". Omitting it keeps the legacy cancel-the-running-one behavior.+export const cancelVideoGen = (jobId) => request('/video-gen/cancel', {+ method: 'POST',+ ...(jobId ? { body: JSON.stringify({ jobId }) } : {}),+});// Per-runtime BYOV setup probe (venv/deps present?) run BEFORE the user hits// Generate so a missing-runtime install banner can surface instead of a// buildArgs-time 500. Silent — VideoGen owns its own error handling and passesdiff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex bfd609523e..1628d07127 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -749,6 +749,10 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {// the t2v/i2v semantic (text/image/fflf/…), which never collides// with the literal 'grok'.mode: IMAGE_GEN_MODE.GROK,+ // Semantic t2v/i2v mode, kept separate from the discriminator so a+ // client restoring form state from /active never feeds 'grok' back+ // into its mode selector.+ videoMode: sourceImagePath ? 'image' : 'text',grokPath: g.grokPath,aspectRatio: g.aspectRatio,prompt: body.prompt,diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 4fe4357c84..03ac5bf634 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -255,6 +255,7 @@ describe('videoGen routes', () => {kind: 'video',params: expect.objectContaining({mode: 'grok',+ videoMode: 'text',grokPath: '/opt/grok',aspectRatio: '16:9',prompt: 'a fox running through snow',diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.jsindex b0f6ab96cf..e526b724d0 100644--- a/server/services/videoGen/grok.js+++ b/server/services/videoGen/grok.js@@ -115,6 +115,7 @@ export function buildGrokVideoPrompt({ prompt, negativePrompt, aspectRatio, duraexport async function generateVideo({grokPath, aspectRatio, prompt = '', negativePrompt, width, height,sourceImagePath = null, duration,+ uploadedTempPath = null,jobId: providedJobId = null,}) {await ensureDir(PATHS.videos);@@ -173,7 +174,7 @@ export async function generateVideo({broadcastSse(job, { type: 'status', message: 'Spawning grok…' });runGrokVideo(job, jobId, bin, args, {- useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta,+ useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta, uploadedTempPath,}).catch((err) => {console.log(`❌ grok video run failed [${jobId.slice(0, 8)}]: ${err?.message}`);});@@ -186,7 +187,7 @@ export async function generateVideo({}async function runGrokVideo(job, jobId, bin, args, {- useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta,+ useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta, uploadedTempPath,}) {// 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.@@ -195,6 +196,11 @@ async function runGrokVideo(job, jobId, bin, 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(() => {});+ // The route stages a multipart source image into data/uploads and hands us+ // its path — the provider owns unlinking it on every terminal path (same+ // contract as videoGen/local.js; the queue only cleans up when the+ // provider throws before spawning, or on boot-restore of a dead job).+ const removeUpload = () => { if (uploadedTempPath) unlink(uploadedTempPath).catch(() => {}); };if (useStdin) {proc.stdin.on('error', () => {});@@ -217,6 +223,7 @@ async function runGrokVideo(job, jobId, bin, args, {clearTimeout(timeoutTimer);cleanupPromptFile();removeScratch();+ removeUpload();finalizeError(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);});@@ -245,11 +252,13 @@ async function runGrokVideo(job, jobId, bin, args, {const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;const tail = stderrTail.trim().split('\n').slice(-6).join('\n');removeScratch();+ removeUpload();return finalizeError(job, jobId, proc, `Grok video generation failed: ${reason}\n${tail}`);}const harvested = await harvestStagedVideo(stagingPath, 10000);if (!harvested.found) {removeScratch();+ removeUpload();const prefix = harvested.invalid ? 'Grok wrote a non-MP4 file at the directed path. ' : '';return finalizeError(job, jobId, proc, `${prefix}${noVideoReason(stdoutTail)}`);}@@ -260,6 +269,7 @@ async function runGrokVideo(job, jobId, bin, args, {await unlink(stagingPath).catch(() => {});});removeScratch();+ removeUpload();if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);activeJobs.delete(jobId);// Shared finalizer: faststart optimization, thumbnail, history entry,@@ -270,7 +280,12 @@ async function runGrokVideo(job, jobId, bin, args, {closeJobAfterDelay(jobs, jobId);} catch (err) {removeScratch();- finalizeError(job, jobId, proc, `Grok video post-exit handler failed: ${err?.message || err}`);+ removeUpload();+ // finalizeGeneratedVideo marks job.status='complete' BEFORE its async+ // post-processing (faststart/thumbnail/history) — a throw there must+ // still surface as a terminal failure or the queue's job stays+ // 'running' until the watchdog. Force past the idempotence guard.+ finalizeError(job, jobId, proc, `Grok video post-exit handler failed: ${err?.message || err}`, { force: true });}});}@@ -284,8 +299,11 @@ function noVideoReason(stdoutTail = '') {.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;+const finalizeError = (job, jobId, proc, reason, { force = false } = {}) => {+ // Idempotent except under `force` — used when finalizeGeneratedVideo threw+ // AFTER stamping 'complete' but BEFORE emitting the completed event, so a+ // terminal 'failed' must still go out.+ if (!force && (job.status === 'error' || job.status === 'complete')) return;if (proc == null || activeProcs.get(jobId) === proc) activeProcs.delete(jobId);job.status = 'error';activeJobs.delete(jobId);