The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(i2v): faithful SVD image-to-video + prompt-named output files
purplec40d13f76c08
diff --git a/src/api/__tests__/prompt-filename-prefix.test.ts b/src/api/__tests__/prompt-filename-prefix.test.tsnew file mode 100644index 00000000..56849668--- /dev/null+++ b/src/api/__tests__/prompt-filename-prefix.test.ts@@ -0,0 +1,50 @@+/**+ * Prompt-derived output filenames (David 2026-06-11): images/videos should be+ * named after what was asked ("red_apple_on_white_plate_00001_.png"), not the+ * opaque "locally_uncensored_00123_.png", so the result string is self-+ * descriptive and a follow-up "animate the red-apple image" can pass the name+ * straight back.+ *+ * Run: npx vitest run src/api/__tests__/prompt-filename-prefix.test.ts+ */+import { describe, it, expect } from 'vitest'+import { promptFilenamePrefix } from '../dynamic-workflow'++describe('promptFilenamePrefix', () => {+ it('slugifies the first words of an image prompt', () => {+ expect(promptFilenamePrefix('a red apple on a white plate', false)).toBe('a_red_apple_on_a_white')+ })++ it('video prompts get a __vid tag so they never collide with the still', () => {+ expect(promptFilenamePrefix('ocean waves at sunset', true)).toBe('ocean_waves_at_sunset__vid')+ })++ it('caps length and word count, trims trailing underscores', () => {+ const r = promptFilenamePrefix('supercalifragilisticexpialidocious antidisestablishmentarianism pneumonoultramicroscopicsilicovolcanoconiosis', false)+ expect(r.length).toBeLessThanOrEqual(48)+ expect(r.endsWith('_')).toBe(false)+ })++ it('strips punctuation and collapses separators', () => {+ expect(promptFilenamePrefix('A cat, sitting!! on—a couch.', false)).toBe('a_cat_sitting_on_a_couch')+ })++ it('empty / whitespace / emoji-only prompt falls back to the legacy prefix', () => {+ expect(promptFilenamePrefix('', false)).toBe('locally_uncensored')+ expect(promptFilenamePrefix(' ', true)).toBe('locally_uncensored_vid')+ expect(promptFilenamePrefix('🎨🎬', false)).toBe('locally_uncensored')+ expect(promptFilenamePrefix(undefined, false)).toBe('locally_uncensored')+ })++ it('non-ASCII words degrade gracefully (umlauts dropped, ASCII kept)', () => {+ // "Über den Wolken" → ber_den_wolken (the Ü is non-[a-z0-9]).+ expect(promptFilenamePrefix('Über den Wolken', false)).toBe('ber_den_wolken')+ })++ it('result is always a safe filename fragment (no path separators or spaces)', () => {+ for (const p of ['a/b\\c', 'foo bar', 'x:y*z?', 'normal prompt']) {+ const r = promptFilenamePrefix(p, false)+ expect(r).toMatch(/^[a-z0-9_]+$/)+ }+ })+})diff --git a/src/api/__tests__/vram-handoff.test.ts b/src/api/__tests__/vram-handoff.test.tsindex bc37f52e..46a7b658 100644--- a/src/api/__tests__/vram-handoff.test.ts+++ b/src/api/__tests__/vram-handoff.test.ts@@ -81,7 +81,7 @@ vi.mock('../agent-context', () => ({// settingsStore is the real module — pure, no services. The orchestrator reads// settings.exclusiveVramMode through it; default DEFAULT_SETTINGS = 'auto'.-import { decideUnload, vramHandoffGenerate, pollGone, resolveClip, resolveModelName } from '../vram-handoff'+import { decideUnload, vramHandoffGenerate, pollGone, resolveClip, resolveModelName, resolveI2VResolution } from '../vram-handoff'import { useSettingsStore } from '../../stores/settingsStore'const GB = 1024 * 1024 * 1024@@ -216,6 +216,41 @@ describe('resolveClip', () => {})})+// ── resolveI2VResolution: pick native res from source aspect (David 2026-06-11:+// "I2V results are never what the source image showed" — portrait stills came+// back as squished 768×448 landscape) ──+describe('resolveI2VResolution', () => {+ it('SVD square source → landscape 1024×576 (square is closer to landscape; center-crop fills it)', () => {+ expect(resolveI2VResolution('svd', 1024, 1024)).toEqual({ width: 1024, height: 576 })+ })++ it('SVD portrait source → portrait native 576×1024 (no more squish to landscape)', () => {+ expect(resolveI2VResolution('svd', 1024, 1536)).toEqual({ width: 576, height: 1024 })+ })++ it('SVD landscape source → landscape native 1024×576', () => {+ expect(resolveI2VResolution('svd', 1920, 1080)).toEqual({ width: 1024, height: 576 })+ })++ it('SVD unknown dimensions → safe landscape default', () => {+ expect(resolveI2VResolution('svd', 0, 0)).toEqual({ width: 1024, height: 576 })+ })++ it('FramePack keeps the source aspect, snapped to a 16-multiple under the 768 cap', () => {+ // 1024×1024 → scaled to 768×768 (cap), already 16-aligned.+ expect(resolveI2VResolution('framepack', 1024, 1024)).toEqual({ width: 768, height: 768 })+ // 1920×1080 → long edge 1920>768 → ×0.4 → 768×432 (both 16-aligned).+ expect(resolveI2VResolution('framepack', 1920, 1080)).toEqual({ width: 768, height: 432 })+ })++ it('FramePack small source is not upscaled past its size, just 16-snapped', () => {+ const r = resolveI2VResolution('framepack', 500, 500)+ expect(r.width % 16).toBe(0)+ expect(r.height % 16).toBe(0)+ expect(r.width).toBeLessThanOrEqual(512)+ })+})+// ── helpers for the orchestrator tests ────────────────────────────/** Program a completed history with one image output for a given promptId. */diff --git a/src/api/comfyui.ts b/src/api/comfyui.tsindex 0ba433af..19a800e2 100644--- a/src/api/comfyui.ts+++ b/src/api/comfyui.ts@@ -58,6 +58,10 @@ export interface VideoParams extends GenerateParams {frames: numberfps: numberinputImage?: string // Uploaded image filename for I2V models (SVD, FramePack)+ // SVD motion strength (motion_bucket_id, 1–255). Lower = more faithful to the+ // source still / calmer motion; 127 (SVD default) drifts hard. We default ~90+ // for I2V fidelity (David 2026-06-11). Honoured only by the SVD path.+ motionBucketId?: number}export interface ComfyUIOutput {diff --git a/src/api/dynamic-workflow.ts b/src/api/dynamic-workflow.tsindex be7bc073..c80f44e0 100644--- a/src/api/dynamic-workflow.ts+++ b/src/api/dynamic-workflow.ts@@ -9,6 +9,34 @@ import {type AvailableModels,} from './comfyui-nodes'+// ─── Output filename slug (David 2026-06-11) ───+//+// Generated media used to be `locally_uncensored_00123_.png` /+// `locally_uncensored_vid_00011.mp4` — opaque. Now the ComfyUI SaveImage /+// VHS `filename_prefix` is derived from the PROMPT, so a file is+// `red_apple_on_white_plate_00001_.png`. That makes the result string+// self-descriptive, so a follow-up "animate the red-apple image" can pass the+// recognisable filename straight back. ComfyUI still appends its own+// `_NNNNN_` counter, so uniqueness is preserved.+//+// Exported + pure for the unit tests.+export function promptFilenamePrefix(prompt: string | undefined, isVideo: boolean): string {+ const slug = (prompt || '')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '_')+ .replace(/^_+|_+$/g, '')+ .split('_')+ .filter(Boolean)+ .slice(0, 6) // first ~6 words keep it readable+ .join('_')+ .slice(0, 48)+ .replace(/_+$/g, '')+ if (!slug) return isVideo ? 'locally_uncensored_vid' : 'locally_uncensored'+ // Keep a short tag so a folder full of generations is still recognisably ours+ // and videos never collide with the still they were made from.+ return isVideo ? `${slug}__vid` : slug+}+// ─── Strategy Detection ───export type WorkflowStrategy =@@ -747,6 +775,7 @@ export async function buildDynamicWorkflow(if (isVideo) {// Video output: prefer VHS > SaveAnimatedWEBP > SaveImage+ const vidPrefix = promptFilenamePrefix(params.prompt, true)if (nodes.videoSavers.includes('VHS_VideoCombine')) {workflow[saveId] = {class_type: 'VHS_VideoCombine',@@ -754,7 +783,7 @@ export async function buildDynamicWorkflow(images: [decodeId, 0],frame_rate: videoParams.fps,loop_count: 0,- filename_prefix: 'locally_uncensored_vid',+ filename_prefix: vidPrefix,format: 'video/h264-mp4',pingpong: false,save_output: true,@@ -765,7 +794,7 @@ export async function buildDynamicWorkflow(class_type: 'SaveAnimatedWEBP',inputs: {images: [decodeId, 0],- filename_prefix: 'locally_uncensored_vid',+ filename_prefix: vidPrefix,fps: videoParams.fps,lossless: false,quality: 90,@@ -777,7 +806,7 @@ export async function buildDynamicWorkflow(class_type: 'SaveImage',inputs: {images: [decodeId, 0],- filename_prefix: 'locally_uncensored_vid',+ filename_prefix: vidPrefix,},}}@@ -786,7 +815,7 @@ export async function buildDynamicWorkflow(class_type: 'SaveImage',inputs: {images: [decodeId, 0],- filename_prefix: 'locally_uncensored',+ filename_prefix: promptFilenamePrefix(params.prompt, false),},}}@@ -800,22 +829,23 @@ export async function buildDynamicWorkflow(// ─── Wrapper Workflow Builders ───-function addVideoOutput(workflow: Record<string, any>, n: number, decodeId: string, fps: number, nodes: CategorizedNodes): number {+function addVideoOutput(workflow: Record<string, any>, n: number, decodeId: string, fps: number, nodes: CategorizedNodes, prompt?: string): number {const saveId = String(n++)+ const prefix = promptFilenamePrefix(prompt, true)if (nodes.videoSavers.includes('VHS_VideoCombine')) {workflow[saveId] = {class_type: 'VHS_VideoCombine',- inputs: { images: [decodeId, 0], frame_rate: fps, loop_count: 0, filename_prefix: 'locally_uncensored_vid', format: 'video/h264-mp4', pingpong: false, save_output: true },+ inputs: { images: [decodeId, 0], frame_rate: fps, loop_count: 0, filename_prefix: prefix, format: 'video/h264-mp4', pingpong: false, save_output: true },}} else if (nodes.videoSavers.includes('SaveAnimatedWEBP')) {workflow[saveId] = {class_type: 'SaveAnimatedWEBP',- inputs: { images: [decodeId, 0], filename_prefix: 'locally_uncensored_vid', fps, lossless: false, quality: 90, method: 'default' },+ inputs: { images: [decodeId, 0], filename_prefix: prefix, fps, lossless: false, quality: 90, method: 'default' },}} else {workflow[saveId] = {class_type: 'SaveImage',- inputs: { images: [decodeId, 0], filename_prefix: 'locally_uncensored_vid' },+ inputs: { images: [decodeId, 0], filename_prefix: prefix },}}return n@@ -844,7 +874,7 @@ function buildCogVideoWorkflow(params: VideoParams, seed: number, nodes: Categor}workflow[decodeId] = { class_type: 'CogVideoXVAEDecode', inputs: { samples: [samplerId, 0], vae: [modelId, 1] } }- addVideoOutput(workflow, n, decodeId, params.fps, nodes)+ addVideoOutput(workflow, n, decodeId, params.fps, nodes, params.prompt)return workflow}@@ -854,6 +884,7 @@ function buildSVDWorkflow(params: VideoParams, seed: number, nodes: CategorizedNconst loaderId = String(n++)const imageId = String(n++)+ const scaleId = String(n++)const condId = String(n++)const guidanceId = String(n++)const samplerId = String(n++)@@ -861,12 +892,24 @@ function buildSVDWorkflow(params: VideoParams, seed: number, nodes: CategorizedNworkflow[loaderId] = { class_type: 'ImageOnlyCheckpointLoader', inputs: { ckpt_name: params.model } }workflow[imageId] = { class_type: 'LoadImage', inputs: { image: params.inputImage || 'input_image.png' } }+ // Aspect-fill the source into the SVD generation resolution (David 2026-06-11:+ // a portrait/square still fed straight in came back squished and no longer+ // matched the input). crop:'center' scales to cover width×height then+ // centre-crops — so the conditioning sees the source at the right aspect with+ // no distortion, instead of SVD stretching it internally.+ workflow[scaleId] = {+ class_type: 'ImageScale',+ inputs: { image: [imageId, 0], upscale_method: 'lanczos', width: params.width, height: params.height, crop: 'center' },+ }workflow[condId] = {class_type: 'SVD_img2vid_Conditioning',inputs: {- clip_vision: [loaderId, 1], init_image: [imageId, 0], vae: [loaderId, 2],+ clip_vision: [loaderId, 1], init_image: [scaleId, 0], vae: [loaderId, 2],augmentation_level: 0.0, width: params.width, height: params.height,- video_frames: params.frames, motion_bucket_id: 127, fps: params.fps,+ video_frames: params.frames,+ // Lower motion = stays closer to the source (127 = SVD's high-drift default).+ motion_bucket_id: params.motionBucketId ?? 90,+ fps: params.fps,},}workflow[guidanceId] = { class_type: 'VideoLinearCFGGuidance', inputs: { model: [loaderId, 0], min_cfg: 1.0 } }@@ -876,7 +919,7 @@ function buildSVDWorkflow(params: VideoParams, seed: number, nodes: CategorizedN}workflow[decodeId] = { class_type: 'VAEDecode', inputs: { samples: [samplerId, 0], vae: [loaderId, 2] } }- addVideoOutput(workflow, n, decodeId, params.fps, nodes)+ addVideoOutput(workflow, n, decodeId, params.fps, nodes, params.prompt)return workflow}@@ -927,7 +970,7 @@ function buildFramePackWorkflow(params: VideoParams, seed: number, nodes: Catego}workflow[decodeId] = { class_type: 'VAEDecode', inputs: { samples: [samplerId, 0], vae: [vaeId, 0] } }- addVideoOutput(workflow, n, decodeId, params.fps, nodes)+ addVideoOutput(workflow, n, decodeId, params.fps, nodes, params.prompt)return workflow}@@ -950,7 +993,7 @@ function buildPyramidFlowWorkflow(params: VideoParams, seed: number, nodes: Cate}workflow[decodeId] = { class_type: 'PyramidFlowDecode', inputs: { samples: [samplerId, 0] } }- addVideoOutput(workflow, n, decodeId, params.fps, nodes)+ addVideoOutput(workflow, n, decodeId, params.fps, nodes, params.prompt)return workflow}@@ -971,6 +1014,6 @@ function buildAllegroWorkflow(params: VideoParams, seed: number, nodes: Categori}workflow[decodeId] = { class_type: 'AllegroDecoder', inputs: { samples: [samplerId, 0] } }- addVideoOutput(workflow, n, decodeId, params.fps, nodes)+ addVideoOutput(workflow, n, decodeId, params.fps, nodes, params.prompt)return workflow}diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.tsindex 10386e2f..240cc8d3 100644--- a/src/api/vram-handoff.ts+++ b/src/api/vram-handoff.ts@@ -821,7 +821,7 @@ async function generateImage(prompt: string, model: string, args: VramHandoffArglet inputImage: string | undefinedlet denoise: number | undefinedif (typeof args.inputImage === 'string' && args.inputImage) {- inputImage = await resolveInputImage(args.inputImage)+ inputImage = (await resolveInputImage(args.inputImage)).namedenoise = clampFloat(args.denoise, 0.6, 0.05, 1.0)}const workflow = await buildDynamicWorkflow(@@ -895,17 +895,18 @@ async function generateVideo(const { buildDynamicWorkflow } = await import('./dynamic-workflow')// Resolve the source still; if the model gave a wrong/hallucinated name,// fall back to the last image LU actually produced this session.- let inputImage: string+ let resolved: ResolvedInputImagetry {- inputImage = await resolveInputImage(args.inputImage)+ resolved = await resolveInputImage(args.inputImage)} catch (e) {if (_lastImageFilename) {log.warn('vram_handoff.i2v_input_fallback', { bad: String(args.inputImage), fallback: _lastImageFilename })- inputImage = await resolveInputImage(_lastImageFilename)+ resolved = await resolveInputImage(_lastImageFilename)} else {throw e}}+ const inputImage = resolved.name// SVD-XT genuinely caps ~25 frames. FramePack PACKS long video, so its real// ceiling comes from getModelCapabilities (request-driven — David 2026-06-04:// "FramePacks frame cap anheben durch input von uns"). REJECT (not clamp) an@@ -918,8 +919,17 @@ async function generateVideo(const tun = resolveTunables(args, caps, { steps: type === 'framepack' ? 25 : 20, cfg: 3, sampler: 'euler', scheduler: 'normal' })if (tun.reject) return `Cannot generate: ${tun.reject}`const av = args as Record<string, unknown>- const snapped = snapToVideoGrid(clampInt(av.width, 768, 64, 2048), clampInt(av.height, 448, 64, 2048))+ // Resolution from the SOURCE aspect ratio (David 2026-06-11: portrait+ // stills came back as squished landscape that no longer matched the+ // input). An explicit user width/height still wins; otherwise we pick the+ // model's native bucket and an ImageScale(crop:center) fills it cleanly.+ const native = resolveI2VResolution(type, resolved.width, resolved.height)+ const snapped = snapToVideoGrid(+ clampInt(av.width, native.width, 64, 2048),+ clampInt(av.height, native.height, 64, 2048),+ )const seed = (typeof av.seed === 'number' && Number.isFinite(av.seed)) ? Math.floor(av.seed) : -1+ const motionBucketId = clampInt(av.motionBucketId ?? av.motion_bucket_id, 90, 1, 255)const workflow = await buildDynamicWorkflow({prompt,@@ -936,6 +946,7 @@ async function generateVideo(frames,fps,inputImage,+ motionBucketId,},type,)@@ -1176,7 +1187,15 @@ export function resolveClip(* Generated images live in ComfyUI's *output* folder, but LoadImage reads from* *input* — so we fetch the referenced image and re-upload it via /upload/image.*/-async function resolveInputImage(ref: string): Promise<string> {+interface ResolvedInputImage {+ /** Filename in ComfyUI's input folder, ready for a LoadImage node. */+ name: string+ /** Source pixel dimensions (0 when they could not be probed). */+ width: number+ height: number+}++async function resolveInputImage(ref: string): Promise<ResolvedInputImage> {let url: stringlet name: stringif (/^https?:\/\//i.test(ref)) {@@ -1190,8 +1209,60 @@ async function resolveInputImage(ref: string): Promise<string> {const resp = await fetch(url)if (!resp.ok) throw new Error(`could not read input image "${ref}" (HTTP ${resp.status})`)const blob = await resp.blob()+ // Probe the source dimensions so the I2V path can pick the model's native+ // aspect ratio (David 2026-06-11: a portrait still forced into 768×448+ // landscape no longer resembled the source). Best-effort — a probe failure+ // just yields 0×0 and the caller falls back to a sane default.+ let width = 0+ let height = 0+ try {+ const bmp = await createImageBitmap(blob)+ width = bmp.width+ height = bmp.height+ bmp.close()+ } catch { /* dimensions unknown → caller uses defaults */ }const file = new File([blob], name, { type: blob.type || 'image/png' })- return await uploadImage(file)+ const uploaded = await uploadImage(file)+ return { name: uploaded, width, height }+}++/**+ * Pick the generation resolution for an image-to-video model from the SOURCE+ * still's aspect ratio. SVD-XT was trained ONLY at 1024×576 (landscape) and+ * 576×1024 (portrait); feeding it the old fixed 768×448 squished every source+ * and the clip stopped resembling the input. We match the source ORIENTATION+ * to the nearest native bucket; an ImageScale(crop:center) in the workflow+ * then fills it exactly (aspect-fill, no squish). FramePack is far more+ * resolution-flexible, so it just gets a tidy 16-multiple of the source.+ *+ * Exported + pure for the unit tests.+ */+export function resolveI2VResolution(+ type: string,+ srcW: number,+ srcH: number,+): { width: number; height: number } {+ const landscapeDefault = { width: 1024, height: 576 }+ if (!srcW || !srcH || srcW <= 0 || srcH <= 0) {+ return type === 'svd' ? landscapeDefault : { width: 768, height: 768 }+ }+ const aspect = srcW / srcH+ if (type === 'svd') {+ // Square is closer to landscape than portrait; center-crop handles the rest.+ return aspect >= 0.95 ? { width: 1024, height: 576 } : { width: 576, height: 1024 }+ }+ // FramePack / others: keep the real aspect, snap to a 16-multiple, cap the+ // long edge so a 12 GB card stays safe.+ const cap = 768+ let w = srcW+ let h = srcH+ if (Math.max(w, h) > cap) {+ const s = cap / Math.max(w, h)+ w = Math.round(w * s)+ h = Math.round(h * s)+ }+ const snap = (v: number) => Math.max(64, Math.round(v / 16) * 16)+ return { width: snap(w), height: snap(h) }}function getImageTimeoutMs(): number {