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
feat(chat): capability-aware image/video generation — every model fully chat-controllable
purple22238f1997c2
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rsindex 1b6300f2..dbaf2584 100644--- a/src-tauri/src/commands/remote.rs+++ b/src-tauri/src/commands/remote.rs@@ -1461,7 +1461,7 @@ button{-webkit-appearance:none;appearance:none}parameters:[]},{name:'screenshot', description:'Capture the primary display as a base64 PNG. Zero arguments. USE for visual verification when the user asks "what\'s on my screen" or "look at X". Returns a short summary string (size + filename); the actual image is forwarded to the model via message content. NEVER call in a tight loop — screenshots are expensive and privacy-sensitive.',parameters:[]},- {name:'image_generate', description:'Generate an image from a text prompt via the local ComfyUI pipeline. Blocks up to 5 minutes. USE for "draw me", "make an image of", "generate a picture". Pass `inputImage` (a filename from an earlier image_generate result) for image-to-image — restyle / edit an existing image at the given `denoise` strength; omit it for text-to-image. First installed image model is auto-selected (or pass `model`). EXPECT A PAUSE: on a single-GPU machine LU may briefly unload the chat model from VRAM to fit the image model, then reload it after — typically a 30-90s swap (longer on a cold ComfyUI start). This avoids out-of-memory errors; your conversation is fully preserved across the swap. Rate-limit yourself to 1 call per turn — ComfyUI serializes generations internally so parallel calls will queue, not speed up.',+ {name:'image_generate', description:'Generate an image from a text prompt via the local ComfyUI pipeline. Blocks up to 5 minutes. USE for "draw me", "make an image of", "generate a picture". Pass `inputImage` (a filename from an earlier image_generate result) for image-to-image — restyle / edit an existing image at the given `denoise` strength; omit it for text-to-image. First installed image model is auto-selected (or pass `model`). EXPECT A PAUSE: on a single-GPU machine LU may briefly unload the chat model from VRAM to fit the image model, then reload it after — typically a 30-90s swap (longer on a cold ComfyUI start). This avoids out-of-memory errors; your conversation is fully preserved across the swap. Rate-limit yourself to 1 call per turn — ComfyUI serializes generations internally so parallel calls will queue, not speed up. Fine-tune with the optional `settings` object (steps, cfg, sampler, scheduler, width/height, seed, lora, vae); set ONLY what the user asked for. A value beyond the installed model\'s real limit is REJECTED with the actual limit so you can retry lower — values are never silently changed.',parameters:[{name:'prompt',type:'string',description:'Positive text description of the desired image',required:true},{name:'negativePrompt',type:'string',description:'Things to avoid (blurry, deformed, etc.)',required:false},{name:'model',type:'string',description:'Optional image model filename to use. Omit to auto-select the first installed image model.',required:false},diff --git a/src/api/__tests__/dynamic-workflow-strategy.test.ts b/src/api/__tests__/dynamic-workflow-strategy.test.tsindex 70bc8048..cf86bc50 100644--- a/src/api/__tests__/dynamic-workflow-strategy.test.ts+++ b/src/api/__tests__/dynamic-workflow-strategy.test.ts@@ -263,3 +263,19 @@ describe('dynamic-workflow — determineStrategy', () => {})})})++// ── FramePack length wiring (source verification) ────────────────────────+// buildDynamicWorkflow needs a live ComfyUI connection, so we verify the+// frame→duration wiring at the source level (same pattern as ernie-image).+// David 2026-06-04: FramePack ignored the requested length because the sampler+// read a non-existent `params.numFrames` (VideoParams only has `frames`).+describe('FramePack length wiring (source verification)', () => {+ it('total_second_length is driven by params.frames, not the dead params.numFrames', () => {+ const { readFileSync } = require('fs')+ const { resolve } = require('path')+ const src = readFileSync(resolve(__dirname, '../dynamic-workflow.ts'), 'utf8')+ expect(src).toContain('total_second_length: (params.frames || 49) / (params.fps || 16)')+ // The dead field must be gone — otherwise FramePack silently pins to 49 frames.+ expect(src).not.toContain('params.numFrames')+ })+})diff --git a/src/api/__tests__/model-capabilities.test.ts b/src/api/__tests__/model-capabilities.test.tsnew file mode 100644index 00000000..07e4a257--- /dev/null+++ b/src/api/__tests__/model-capabilities.test.ts@@ -0,0 +1,190 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'++// Mock the backend transport so getAllNodeInfo()'s localFetch returns a synthetic+// /object_info payload — ComfyUI is not live in CI.+const localFetch = vi.fn()+vi.mock('../backend', () => ({+ comfyuiUrl: (p: string) => `http://127.0.0.1:8188${p}`,+ localFetch: (...a: unknown[]) => localFetch(...a),+}))++import { getModelCapabilities, clearNodeCache, type ModelCapabilities } from '../comfyui-nodes'+import { clampOrReject, enumReject, videoFrameReject } from '../vram-handoff'++// Tuple shape mirrors real ComfyUI /object_info: [enumList, {}] for enums,+// ['INT'|'FLOAT', {default,min,max,step}] for numeric inputs.+const OBJECT_INFO: Record<string, any> = {+ KSampler: { input: { required: {+ sampler_name: [['euler', 'dpmpp_2m', 'uni_pc'], {}],+ scheduler: [['normal', 'karras'], {}],+ steps: ['INT', { default: 20, min: 1, max: 100 }],+ cfg: ['FLOAT', { default: 7, min: 0, max: 30 }],+ } } },+ SVD_img2vid_Conditioning: { input: { required: {+ video_frames: ['INT', { default: 14, min: 1, max: 25 }],+ } } },+ CogVideoXSampler: { input: { required: {+ steps: ['INT', { default: 50, min: 1, max: 200 }],+ cfg: ['FLOAT', { default: 6, min: 0, max: 30 }],+ } } },+ FramePackSampler: { input: { required: {+ steps: ['INT', { default: 25, min: 1, max: 100 }],+ cfg: ['FLOAT', { default: 1, min: 0, max: 30 }],+ total_second_length: ['FLOAT', { default: 5, min: 0.1, max: 120 }],+ } } },+}++const okJson = (payload: any) => ({ ok: true, status: 200, json: async () => payload })++beforeEach(() => {+ clearNodeCache() // also clears the capability cache (hooked)+ localFetch.mockReset()+ localFetch.mockResolvedValue(okJson(OBJECT_INFO))+})++describe('getModelCapabilities — real limits from /object_info', () => {+ it('SDXL → KSampler enums + numeric ranges, no frameRange', async () => {+ const c = await getModelCapabilities('my_sdxl_model.safetensors')+ expect(c).toBeTruthy()+ expect(c!.usesKSampler).toBe(true)+ expect(c!.stepsRange).toEqual({ min: 1, max: 100, default: 20 })+ expect(c!.cfgRange).toEqual({ min: 0, max: 30, default: 7 })+ expect(c!.availableSamplers).toEqual(['euler', 'dpmpp_2m', 'uni_pc'])+ expect(c!.availableSchedulers).toEqual(['normal', 'karras'])+ expect(c!.frameRange).toBeUndefined()+ })++ it('SVD → frameRange from SVD_img2vid_Conditioning.video_frames, KSampler for the rest', async () => {+ const c = await getModelCapabilities('svd_xt_1_1.safetensors')+ expect(c!.frameRange).toEqual({ min: 1, max: 25 })+ expect(c!.usesKSampler).toBe(true)+ expect(c!.availableSamplers).toEqual(['euler', 'dpmpp_2m', 'uni_pc'])+ })++ it('FramePack → maxSeconds + frame ceiling from total_second_length, usesKSampler false', async () => {+ const c = await getModelCapabilities('FramePackI2V_HY_fp8.safetensors')+ expect(c!.maxSeconds).toBe(120)+ expect(c!.frameRange).toEqual({ min: 1, max: 1920 }) // 120s × 16fps+ expect(c!.usesKSampler).toBe(false)+ expect(c!.availableSamplers).toBeUndefined() // FramePackSampler exposes no sampler_name enum+ })++ it('CogVideoX → wrapper sampler (usesKSampler false), no sampler enum, fallback frameRange', async () => {+ const c = await getModelCapabilities('CogVideoX_5b.safetensors')+ expect(c!.usesKSampler).toBe(false)+ expect(c!.availableSamplers).toBeUndefined()+ expect(c!.stepsRange).toEqual({ min: 1, max: 200, default: 50 })+ expect(c!.frameRange).toEqual({ min: 1, max: 49 }) // CogVideoXEmptyLatents absent → fallback+ })++ it('unknown model → PARTIAL caps (KSampler enums), NOT null', async () => {+ const c = await getModelCapabilities('totally_mystery_xyz.safetensors')+ expect(c).toBeTruthy()+ expect(c!.modelType).toBe('unknown')+ expect(c!.usesKSampler).toBe(true)+ expect(c!.availableSamplers).toEqual(['euler', 'dpmpp_2m', 'uni_pc'])+ expect(c!.frameRange).toBeUndefined()+ })++ it('missing SVD node → frameRange soft-falls back to {1,25}', async () => {+ localFetch.mockResolvedValue(okJson({ KSampler: OBJECT_INFO.KSampler }))+ const c = await getModelCapabilities('svd_xt_1_1.safetensors')+ expect(c!.frameRange).toEqual({ min: 1, max: 25 })+ })++ it('caches per model — repeat + new model do not refetch /object_info', async () => {+ await getModelCapabilities('my_sdxl_model.safetensors')+ await getModelCapabilities('my_sdxl_model.safetensors')+ await getModelCapabilities('svd_xt_1_1.safetensors')+ expect(localFetch).toHaveBeenCalledTimes(1)+ })++ it('/object_info unreachable → null (caller proceeds with defaults, no validation)', async () => {+ localFetch.mockReset()+ localFetch.mockResolvedValue({ ok: false, status: 500, json: async () => ({}) })+ const c = await getModelCapabilities('my_sdxl_model.safetensors')+ expect(c).toBeNull()+ })+})++describe('clampOrReject / enumReject — reject-and-report (decision 2)', () => {+ it('within range → null', () => {+ expect(clampOrReject('steps', 30, { min: 1, max: 100 })).toBeNull()+ })+ it('over the max → message naming the actual limit', () => {+ const m = clampOrReject('steps', 500, { min: 1, max: 100 })+ expect(m).toContain('exceeds')+ expect(m).toContain('100')+ })+ it('below the min → message naming the minimum', () => {+ const m = clampOrReject('cfg', -3, { min: 0, max: 30 })+ expect(m).toContain('below')+ expect(m).toContain('0')+ })+ it('undefined value OR undefined range → null (only explicit user values are checked)', () => {+ expect(clampOrReject('steps', undefined, { min: 1, max: 100 })).toBeNull()+ expect(clampOrReject('steps', 9999, undefined)).toBeNull()+ })+ it('enumReject: supported → null; unsupported → lists the available options', () => {+ expect(enumReject('sampler', 'euler', ['euler', 'dpmpp_2m'])).toBeNull()+ const m = enumReject('sampler', 'made_up', ['euler', 'dpmpp_2m'])+ expect(m).toContain('not available')+ expect(m).toContain('euler')+ })+ it('enumReject: no value / empty options → null (skip the check)', () => {+ expect(enumReject('sampler', undefined, ['euler'])).toBeNull()+ expect(enumReject('sampler', 'euler', undefined)).toBeNull()+ expect(enumReject('sampler', 'euler', [])).toBeNull()+ })+})++describe('videoFrameReject — only reject the genuinely-impossible (C1 regression guard)', () => {+ const svd: ModelCapabilities = { modelType: 'svd', usesKSampler: true, frameRange: { min: 1, max: 25 } }+ const framepack: ModelCapabilities = { modelType: 'framepack', usesKSampler: false, frameRange: { min: 1, max: 1920 }, maxSeconds: 120 }++ it('caps null → never reject', () => {+ expect(videoFrameReject('m', { seconds: 999 }, null)).toBeNull()+ })++ // The C1 bug: SVD seconds=4 was wrongly rejected even though resolveClip delivers+ // 25f@6fps≈4.2s. Duration requests within maxFrames/4 must NOT reject.+ it('SVD seconds=4 → NULL (resolveClip slows fps to deliver ~4s; do NOT reject)', () => {+ expect(videoFrameReject('svd', { seconds: 4 }, svd)).toBeNull()+ })+ it('SVD seconds=6 → NULL (6 ≤ 25/4 ≈ 6.25s deliverable)', () => {+ expect(videoFrameReject('svd', { seconds: 6 }, svd)).toBeNull()+ })+ it('SVD seconds=60 → reject (beyond ~6s deliverable), names the real limit', () => {+ const m = videoFrameReject('svd', { seconds: 60 }, svd)+ expect(m).toContain('at most')+ expect(m).toContain('25 frames')+ })+ it('SVD explicit frames=99 → reject (exact count over the 25 cap)', () => {+ const m = videoFrameReject('svd', { frames: 99 }, svd)+ expect(m).toContain('99')+ expect(m).toContain('25')+ })+ it('SVD frames=25 (== cap) → null', () => {+ expect(videoFrameReject('svd', { frames: 25 }, svd)).toBeNull()+ })+ it('no frames/seconds → null', () => {+ expect(videoFrameReject('svd', { prompt: 'x' }, svd)).toBeNull()+ })++ // FramePack must honor the original ask (long clips). 7s @ 40fps = 280 frames ≤ 600.+ it('FramePack seconds=7 fps=40 → NULL (the original David ask is deliverable)', () => {+ expect(videoFrameReject('framepack', { seconds: 7, fps: 40 }, framepack)).toBeNull()+ })+ it('FramePack seconds=100 → NULL (within the real 120s total_second_length limit)', () => {+ expect(videoFrameReject('framepack', { seconds: 100 }, framepack)).toBeNull()+ })+ it('FramePack seconds=200 → reject via maxSeconds (real 120s limit)', () => {+ const m = videoFrameReject('framepack', { seconds: 200 }, framepack)+ expect(m).toContain('at most 120s')+ })+ it('FramePack explicit frames=2500 → reject (over the 1920 frame ceiling)', () => {+ const m = videoFrameReject('framepack', { frames: 2500 }, framepack)+ expect(m).toContain('2500')+ expect(m).toContain('1920')+ })+})diff --git a/src/api/__tests__/vram-handoff.test.ts b/src/api/__tests__/vram-handoff.test.tsindex ea7f64d1..cffee748 100644--- a/src/api/__tests__/vram-handoff.test.ts+++ b/src/api/__tests__/vram-handoff.test.ts@@ -198,6 +198,22 @@ describe('resolveClip', () => {it('Wan default → the model default length', () => {expect(resolveClip({ prompt: 'x' }, WAN)).toEqual({ frames: 81, fps: 16 })})++ // FramePack packs long video, so its I2V branch uses a high ceiling instead of+ // SVD's 25 (David 2026-06-04: "FramePacks frame cap anheben durch input von uns").+ const FRAMEPACK = { defFps: 16, defFrames: 49, maxFrames: 600 }++ it('FramePack default → 49 frames @ 16fps (model default)', () => {+ expect(resolveClip({ prompt: 'x' }, FRAMEPACK)).toEqual({ frames: 49, fps: 16 })+ })++ it('FramePack honors the request beyond SVD: seconds=7 fps=40 → 280 frames @ 40fps (true 40fps, NOT capped to 25)', () => {+ expect(resolveClip({ prompt: 'x', seconds: 7, fps: 40 }, FRAMEPACK)).toEqual({ frames: 280, fps: 40 })+ })++ it('FramePack clamps a runaway request to the 600-frame safety ceiling', () => {+ expect(resolveClip({ prompt: 'x', seconds: 60, fps: 40 }, FRAMEPACK).frames).toBe(600)+ })})// ── helpers for the orchestrator tests ────────────────────────────diff --git a/src/api/comfyui-nodes.ts b/src/api/comfyui-nodes.tsindex cc13ee9b..c9721ab8 100644--- a/src/api/comfyui-nodes.ts+++ b/src/api/comfyui-nodes.ts@@ -1,5 +1,9 @@import { comfyuiUrl, localFetch } from './backend'import { log } from '../lib/logger'+// Type-only import — erased at runtime, so it cannot form a comfyui.ts ↔+// comfyui-nodes.ts import cycle. classifyModel/MODEL_TYPE_DEFAULTS (runtime+// values) are pulled via a DYNAMIC import inside getModelCapabilities() below.+import type { ModelType } from './comfyui'// ─── Types ───@@ -69,6 +73,7 @@ export async function getAllNodeInfo(forceRefresh = false): Promise<Record<strinexport function clearNodeCache() {nodeInfoCache = nullcacheTimestamp = 0+ clearCapabilityCache()}// ─── Node existence check (from cache) ───@@ -198,3 +203,159 @@ export function getSchedulerOptions(allNodes: Record<string, NodeMetadata>): strif (Array.isArray(spec) && Array.isArray(spec[0])) return spec[0]return ['normal']}++// ─── Model capability discovery (v2.5.0 — "every model fully chat-controllable") ───+//+// Single source of truth for "what can THIS model actually do". Reads the real+// per-field limits/enums from ComfyUI's /object_info instead of hardcoded+// per-model magic numbers. The chat-agent generation path (vram-handoff) calls+// this to (a) thread the user's settings through and (b) REJECT-AND-REPORT a+// request that exceeds the model's real capability with the actual limit, so the+// user/LLM can retry lower (decision 2). Soft-fails to documented fallbacks so a+// missing node/field never breaks generation — worst case we skip a check.++export interface ModelCapabilities {+ modelType: ModelType+ /** Max generatable frames — video models only; undefined for image models. */+ frameRange?: { min: number; max: number }+ /** Max clip length in seconds — for duration-driven models (FramePack) whose node+ * exposes total_second_length instead of a discrete frame count. */+ maxSeconds?: number+ availableSamplers?: string[]+ availableSchedulers?: string[]+ stepsRange?: { min: number; max: number; default?: number }+ cfgRange?: { min: number; max: number; default?: number }+ widthRange?: { min: number; max: number; step?: number }+ heightRange?: { min: number; max: number; step?: number }+ /**+ * false for wrapper samplers (CogVideoX / Pyramid / Allegro / FramePack) that+ * expose no sampler_name/scheduler enum → callers skip enum validation for them.+ */+ usesKSampler: boolean+ discoveryErrors?: string[]+}++// Per-entry timestamp (not a single shared one) so one model's refresh never+// extends another stale entry's TTL.+let capabilityCache = new Map<string, { caps: ModelCapabilities | null; ts: number }>()++/** Test/refresh hook — also called from clearNodeCache() so a node refresh invalidates caps. */+export function clearCapabilityCache() {+ capabilityCache = new Map()+}++/**+ * Which ComfyUI sampler node carries a family's tunable params, and whether it's+ * a real KSampler (exposes sampler_name/scheduler enums). SVD + AnimateDiff run+ * through KSampler too; FramePackSampler hardcodes its own sampler ('unipc_bh2')+ * and has no scheduler enum, so it is treated as a non-KSampler wrapper.+ */+function getSamplerNodeForCaps(type: ModelType): { node: string; usesKSampler: boolean } {+ switch (type) {+ case 'cogvideo': return { node: 'CogVideoXSampler', usesKSampler: false }+ case 'pyramidflow': return { node: 'PyramidFlowSampler', usesKSampler: false }+ case 'allegro': return { node: 'AllegroSampler', usesKSampler: false }+ case 'framepack': return { node: 'FramePackSampler', usesKSampler: false }+ default: return { node: 'KSampler', usesKSampler: true }+ }+}++export async function getModelCapabilities(model: string): Promise<ModelCapabilities | null> {+ if (!model) return null+ const cached = capabilityCache.get(model)+ if (cached && Date.now() - cached.ts < CACHE_TTL) {+ return cached.caps+ }++ let allNodes: Record<string, NodeMetadata>+ try {+ allNodes = await getAllNodeInfo()+ } catch (e) {+ // /object_info unreachable — caller treats null as "no validation, proceed with defaults".+ log.warn('comfyui_nodes.caps_objectinfo_failed', { err: String(e) })+ return null+ }++ // classifyModel + MODEL_TYPE_DEFAULTS are runtime VALUES from comfyui.ts. Import+ // them DYNAMICALLY so this module never forms a runtime import cycle.+ const { classifyModel, MODEL_TYPE_DEFAULTS } = await import('./comfyui')+ const type = classifyModel(model)+ const caps: ModelCapabilities = { modelType: type, usesKSampler: true, discoveryErrors: [] }++ const numRange = (node: string, field: string): { min: number; max: number; default?: number } | undefined => {+ const spec = allNodes[node]?.input?.required?.[field] ?? allNodes[node]?.input?.optional?.[field]+ if (Array.isArray(spec) && typeof spec[0] === 'string' && spec[1] && typeof spec[1] === 'object') {+ const o = spec[1] as { min?: number; max?: number; default?: number }+ return {+ min: typeof o.min === 'number' ? o.min : 0,+ max: typeof o.max === 'number' ? o.max : 10000,+ default: typeof o.default === 'number' ? o.default : undefined,+ }+ }+ return undefined+ }+ const enumOpts = (node: string, field: string): string[] | undefined => {+ const spec = allNodes[node]?.input?.required?.[field] ?? allNodes[node]?.input?.optional?.[field]+ if (Array.isArray(spec) && Array.isArray(spec[0]) && spec[0].length > 0) return spec[0] as string[]+ return undefined+ }+ const frameFrom = (node: string, field: string, fbMin: number, fbMax: number): { min: number; max: number } => {+ const r = numRange(node, field)+ return r && r.max > 0 ? { min: r.min || 1, max: r.max } : { min: fbMin, max: fbMax }+ }++ // ── Sampler-node params (steps/cfg always; sampler/scheduler only on real KSampler) ──+ const sn = getSamplerNodeForCaps(type)+ caps.usesKSampler = sn.usesKSampler+ if (!allNodes[sn.node]) caps.discoveryErrors!.push(`sampler node ${sn.node} not in /object_info`)+ caps.availableSamplers = enumOpts(sn.node, 'sampler_name')+ caps.availableSchedulers = enumOpts(sn.node, 'scheduler')+ caps.stepsRange = numRange(sn.node, 'steps')+ caps.cfgRange = numRange(sn.node, 'cfg')++ // ── Frame range (video families only; image families leave it undefined) ──+ switch (type) {+ case 'svd':+ caps.frameRange = frameFrom('SVD_img2vid_Conditioning', 'video_frames', 1, 25)+ break+ case 'framepack': {+ // FramePack is DURATION-driven: FramePackSampler exposes total_second_length+ // (seconds), not a discrete frame count. Read the real max (≈120s) from+ // /object_info instead of guessing a frame ceiling — honors "ComfyUI is truth".+ const tsl = numRange('FramePackSampler', 'total_second_length')+ const maxSec = tsl && tsl.max > 0 ? tsl.max : 120+ caps.maxSeconds = maxSec+ // resolveClip works in frames; derive a frame ceiling from the real duration+ // limit (× the 16-fps default) so its frame math stays bounded.+ caps.frameRange = { min: 1, max: Math.max(1, Math.round(maxSec * 16)) }+ if (!tsl) caps.discoveryErrors!.push('framepack total_second_length absent — using 120s fallback')+ break+ }+ case 'cogvideo':+ caps.frameRange = frameFrom('CogVideoXEmptyLatents', 'frames', 1, 49)+ break+ case 'pyramidflow':+ caps.frameRange = frameFrom('PyramidFlowSampler', 'frames', 1, 16)+ break+ case 'allegro':+ caps.frameRange = frameFrom('AllegroSampler', 'frames', 1, 88)+ break+ case 'wan':+ case 'hunyuan':+ case 'ltx':+ case 'mochi':+ case 'cosmos': {+ // The latent node types `length` as a generic INT (max ~10000) — meaningless+ // per-model. Derive a sane ceiling from the family defaults (heuristic).+ const d = MODEL_TYPE_DEFAULTS[type] ?? MODEL_TYPE_DEFAULTS.wan+ caps.frameRange = { min: 1, max: Math.max(d.frames * 2, 161) }+ caps.discoveryErrors!.push(`${type} frame cap is a heuristic (defaults×2), not /object_info-derived`)+ break+ }+ default:+ break+ }++ capabilityCache.set(model, { caps, ts: Date.now() })+ return caps+}diff --git a/src/api/comfyui.ts b/src/api/comfyui.tsindex f2df44d1..3c2aaa74 100644--- a/src/api/comfyui.ts+++ b/src/api/comfyui.ts@@ -919,6 +919,13 @@ export async function fetchComfyImageBase64(url: string): Promise<string> {}// ─── Validate params ───+//+// LEGACY static bounds (steps 1-200 / frames 1-256). The chat-agent path+// (vram-handoff → buildDynamicWorkflow) now validates against REAL per-model+// limits via getModelCapabilities() in comfyui-nodes.ts and rejects-and-reports+// over-limit requests (decision 2). These hard bounds remain only for the legacy+// static workflow builders below (buildSDXLImgWorkflow / buildFluxImgWorkflow /+// buildWanVideoWorkflow); new validation must use getModelCapabilities.function validateParams(params: GenerateParams) {if (!params.prompt.trim()) throw new Error('Prompt is empty')diff --git a/src/api/dynamic-workflow.ts b/src/api/dynamic-workflow.tsindex 9286a7fe..e9496b6b 100644--- a/src/api/dynamic-workflow.ts+++ b/src/api/dynamic-workflow.ts@@ -785,7 +785,11 @@ function buildFramePackWorkflow(params: VideoParams, seed: number, nodes: Categostart_latent: [vaeEncodeId, 0], image_embeds: [clipVisionEncodeId, 0],steps: params.steps, cfg: params.cfgScale || 1.0,guidance_scale: 10.0, shift: 3.0, seed, latent_window_size: 9,- total_second_length: (params.numFrames || 49) / (params.fps || 16),+ // VideoParams carries `frames` (not `numFrames`) — reading the wrong field+ // pinned every FramePack clip to the 49-frame default and silently ignored+ // the caller's requested length. FramePack is duration-driven, so the clip+ // length = frames / fps seconds.+ total_second_length: (params.frames || 49) / (params.fps || 16),gpu_memory_preservation: 6.0, sampler: 'unipc_bh2',use_teacache: true, teacache_rel_l1_thresh: 0.15,},diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.tsindex 92de40a1..99c2bf7a 100644--- a/src/api/mcp/builtin-tools.ts+++ b/src/api/mcp/builtin-tools.ts@@ -474,7 +474,8 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [+ 'Pass `inputImage` (a filename from an earlier image_generate result) for image-to-image — restyle / edit an existing image at the given `denoise` strength; omit it for text-to-image. '+ 'First installed image model is auto-selected (or pass `model`). '+ 'EXPECT A PAUSE: on a single-GPU machine LU may briefly unload the chat model from VRAM to fit the image model, then reload it after — typically a 30-90s swap (longer on a cold ComfyUI start). This avoids out-of-memory errors; your conversation is fully preserved across the swap. '- + 'Rate-limit yourself to 1 call per turn — ComfyUI serializes generations internally so parallel calls will queue, not speed up.',+ + 'Rate-limit yourself to 1 call per turn — ComfyUI serializes generations internally so parallel calls will queue, not speed up. '+ + 'Fine-tune with the optional `settings` object (steps, cfg, sampler, scheduler, width/height, seed, lora, vae); set ONLY what the user asked for. A value beyond the installed model\'s real limit is REJECTED with the actual limit so you can retry lower — values are never silently changed.',inputSchema: {type: 'object',properties: {@@ -483,6 +484,25 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [model: { type: 'string', description: 'Optional image model filename to use. Omit to auto-select the first installed image model.' },inputImage: { type: 'string', description: 'Optional. Filename of a previously generated image (from an earlier image_generate result) to use as the base for image-to-image. Omit for text-to-image.' },denoise: { type: 'number', description: 'Image-to-image strength 0.05–1.0 (default 0.6). Lower keeps more of the input image, higher follows the prompt more. Only used together with inputImage.' },+ settings: {+ type: 'object',+ description: 'Optional fine-tuning. Set ONLY what the user explicitly asked for; omit the rest (the model\'s own defaults apply). Any value beyond the installed model\'s real limit is rejected with the actual limit. Flat top-level args (above) win over the same key here.',+ additionalProperties: true,+ properties: {+ steps: { type: 'number', description: 'Sampling steps.' },+ cfg: { type: 'number', description: 'CFG / guidance scale.' },+ sampler: { type: 'string', description: 'Sampler name — must be one this model supports, else rejected.' },+ scheduler: { type: 'string', description: 'Scheduler name — must be one this model supports, else rejected.' },+ seed: { type: 'number', description: 'Seed; omit or -1 for random.' },+ width: { type: 'number', description: 'Output width in px.' },+ height: { type: 'number', description: 'Output height in px.' },+ negativePrompt: { type: 'string', description: 'Things to avoid.' },+ denoise: { type: 'number', description: 'Image-to-image strength 0.05–1.0 (only with inputImage).' },+ lora: { type: 'string', description: 'LoRA filename to apply.' },+ loraStrength: { type: 'number', description: 'LoRA strength (~0–2).' },+ vae: { type: 'string', description: 'Override VAE filename.' },+ },+ },},required: ['prompt'],},@@ -497,7 +517,8 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [+ 'For a specific length pass `seconds` (e.g. seconds=4 for a 4-second clip) — prefer this over raw frames. Image-to-video (SVD) effectively tops out around 3-4 seconds; text-to-video can run longer. '+ 'Pass `inputImage` (a filename from an earlier image_generate result) to animate a still image — image-to-video, which auto-selects an installed I2V model such as SVD; omit it for text-to-video. First installed video model is auto-selected (or pass `model`). '+ 'Write ONE clear prompt and call this ONCE per turn — video generation is slow and ComfyUI queues parallel calls rather than speeding up. '- + 'EXPECT A PAUSE: LU will briefly unload the chat model from VRAM to fit the (large) video model, then reload it after — typically a 30-90s swap, longer on a cold ComfyUI start. This prevents out-of-memory errors; your conversation is preserved across the swap.',+ + 'EXPECT A PAUSE: LU will briefly unload the chat model from VRAM to fit the (large) video model, then reload it after — typically a 30-90s swap, longer on a cold ComfyUI start. This prevents out-of-memory errors; your conversation is preserved across the swap. '+ + 'Fine-tune with the optional `settings` object (steps, cfg, sampler, scheduler, width/height, seed); set ONLY what the user asked for. A value beyond the installed model\'s real limit (e.g. more frames than the model can make) is REJECTED with the actual limit so you can retry lower — values are never silently changed.',inputSchema: {type: 'object',properties: {@@ -505,9 +526,27 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [negativePrompt: { type: 'string', description: 'Things to avoid (static, blurry, deformed, etc.)' },model: { type: 'string', description: 'Optional video model filename to use. Omit to auto-select the first installed video model.' },seconds: { type: 'number', description: 'Desired clip length in seconds (e.g. 4). PREFER this over frames for "an N second video". Image-to-video (SVD) effectively maxes near 3-4s; text-to-video can be longer.' },- frames: { type: 'number', description: 'Advanced: exact frame count (clamped per model; e.g. ~81 for Wan, ~25 for SVD). Prefer `seconds`. Omit for the model default.' },+ frames: { type: 'number', description: 'Advanced: exact frame count (rejected if beyond the model max; e.g. ~81 for Wan, ~25 for SVD). Prefer `seconds`. Omit for the model default.' },fps: { type: 'number', description: 'Frames per second of the output clip (e.g. 16). Omit for the model default.' },inputImage: { type: 'string', description: 'Optional. Filename of a previously generated image to animate (image-to-video). Requires an installed I2V model such as SVD. Omit for text-to-video.' },+ settings: {+ type: 'object',+ description: 'Optional fine-tuning. Set ONLY what the user explicitly asked for; omit the rest (the model\'s own defaults apply). Any value beyond the installed model\'s real limit is rejected with the actual limit. Flat top-level args (above) win over the same key here.',+ additionalProperties: true,+ properties: {+ seconds: { type: 'number', description: 'Clip length in seconds (preferred length control).' },+ frames: { type: 'number', description: 'Exact frame count — rejected if beyond the model max.' },+ fps: { type: 'number', description: 'Frames per second of the output clip.' },+ steps: { type: 'number', description: 'Sampling steps.' },+ cfg: { type: 'number', description: 'CFG / guidance scale.' },+ sampler: { type: 'string', description: 'Sampler name — must be one this model supports (ignored by FramePack, which uses a fixed sampler).' },+ scheduler: { type: 'string', description: 'Scheduler name — must be one this model supports.' },+ seed: { type: 'number', description: 'Seed; omit or -1 for random.' },+ width: { type: 'number', description: 'Output width in px (snapped to the video grid).' },+ height: { type: 'number', description: 'Output height in px (snapped to the video grid).' },+ negativePrompt: { type: 'string', description: 'Things to avoid.' },+ },+ },},// prompt intentionally NOT required: image-to-video can animate a still// without an explicit text prompt, and small models sometimes omit it —@@ -947,8 +986,12 @@ async function executeImageGenerate(args: Record<string, any>): Promise<string>// ToolCallBlock renders it inline and useAgentChat feeds it back unchanged.const prompt = args.prompt || args.description || ''if (!prompt) return 'Error: No prompt provided for image generation.'+ const settings = (args.settings && typeof args.settings === 'object') ? args.settings : {}+ const flat: Record<string, any> = {}+ for (const [k, v] of Object.entries(args)) if (k !== 'settings' && v !== undefined) flat[k] = v+ const merged: Record<string, any> = { ...settings, ...flat } // explicit flat args win; undefined never clobbers settingsconst { vramHandoffGenerate } = await import('../vram-handoff')- return vramHandoffGenerate('image', args)+ return vramHandoffGenerate('image', merged)}async function executeVideoGenerate(args: Record<string, any>): Promise<string> {@@ -963,8 +1006,12 @@ async function executeVideoGenerate(args: Record<string, any>): Promise<string>// defaults a gentle-motion prompt for video, normalizes a snake_case// input_image alias, and falls back to the last generated image — so the// "animate the image you just made" chain works even with a sloppy call.+ const settings = (args.settings && typeof args.settings === 'object') ? args.settings : {}+ const flat: Record<string, any> = {}+ for (const [k, v] of Object.entries(args)) if (k !== 'settings' && v !== undefined) flat[k] = v+ const merged: Record<string, any> = { ...settings, ...flat } // explicit flat args win; undefined never clobbers settingsconst { vramHandoffGenerate } = await import('../vram-handoff')- return vramHandoffGenerate('video', args)+ return vramHandoffGenerate('video', merged)}async function executeGetCurrentTime(_args: Record<string, any>): Promise<string> {diff --git a/src/api/mcp/types.ts b/src/api/mcp/types.tsindex 7f3fca45..c9d13c87 100644--- a/src/api/mcp/types.ts+++ b/src/api/mcp/types.ts@@ -17,17 +17,31 @@ export const DEFAULT_PERMISSIONS: PermissionMap = {workflow: 'confirm',}+// A loose JSON-Schema-ish property shape. Deliberately recursive so tool inputs+// can model arrays (`items`), nested objects (`properties` / `additionalProperties`+// — e.g. the image/video `settings` pass-through), and numeric bounds. Kept+// permissive on purpose: this is forwarded verbatim to the model as the tool's+// `parameters`, not strictly validated here.+export interface JSONSchemaProp {+ type: string+ description?: string+ enum?: string[]+ items?: JSONSchemaProp+ properties?: Record<string, JSONSchemaProp>+ additionalProperties?: boolean | JSONSchemaProp+ default?: unknown+ minimum?: number+ maximum?: number+}+export interface MCPToolDefinition {name: stringdescription: stringinputSchema: {type: 'object'- properties: Record<string, {- type: string- description: string- enum?: string[]- }>+ properties: Record<string, JSONSchemaProp>required: string[]+ additionalProperties?: boolean}category: ToolCategorysource: 'builtin' | 'external'diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.tsindex 7121aa4c..9f153de3 100644--- a/src/api/vram-handoff.ts+++ b/src/api/vram-handoff.ts@@ -65,6 +65,7 @@ import {MODEL_TYPE_DEFAULTS,type VideoBackend,} from './comfyui'+import type { ModelCapabilities } from './comfyui-nodes'import { getActiveAgentModel } from './agent-context'import { log } from '../lib/logger'@@ -220,6 +221,13 @@ export interface DecideUnloadResult {const BYTES_PER_GB = 1024 * 1024 * 1024+// Fallback FramePack frame ceiling. FramePack is duration-driven (total_second_length),+// so /object_info exposes no per-model frame max — getModelCapabilities() returns this+// same 600 for framepack, and generateVideo passes it as resolveClip's maxFrames fallback+// when capabilities are unavailable. Guards a typo'd seconds×fps from queuing an+// hours-long render. ~15 s @ 40 fps / ~37 s @ 16 fps.+const FRAMEPACK_MAX_FRAMES = 600+/*** Pure decision: should we evict the text model before generating?*@@ -423,7 +431,7 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promiconst models = await getImageModels()if (models.length === 0) {emitHandoff('error', { kind, detail: 'no image model installed' })- return 'Error: No image model installed in ComfyUI. Download one from the Create tab (Model Manager) and try again.'+ return 'Error: No image model installed. Download one from Models → Discover (e.g. "FLUX.1 [schnell] FP8", "Z-Image Turbo", or "Juggernaut XL V9") and try again.'}targetModel = typeof args.model === 'string' && args.model ? args.model : models[0].name} else {@@ -447,7 +455,7 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promiconst t2vModels = models.filter((m) => !isI2VModel(m.name))if (t2vModels.length === 0 || backend === 'none') {emitHandoff('error', { kind, detail: 'no text-to-video model installed' })- return 'Error: No text-to-video model installed (an SVD model is image-to-video only). Download a Wan/Hunyuan model from the Create tab — or generate an image first and animate it (image-to-video).'+ return 'Error: No text-to-video model installed. Download one from Models → Discover (e.g. "Wan 2.1 — 1.3B (Lightweight)" for 8-10 GB VRAM or "HunyuanVideo 1.5 T2V FP8" for 12+ GB) — or generate an image first and animate it with an I2V model like "SVD-XT 1.1".'}targetModel = typeof args.model === 'string' && args.model ? args.model : t2vModels[0].namevideoBackend = backend@@ -571,6 +579,18 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promiasync function generateImage(prompt: string, model: string, args: VramHandoffArgs): Promise<string> {const { buildDynamicWorkflow } = await import('./dynamic-workflow')try {+ // Capability-aware: read this model's REAL limits/enums from ComfyUI and+ // REJECT (not clamp) any explicit user value beyond them (decision 2).+ const caps = await fetchCaps(model, 'image')+ const tun = resolveTunables(args, caps, { steps: 20, cfg: 7, sampler: 'euler', scheduler: 'normal' })+ if (tun.reject) return `Cannot generate: ${tun.reject}`++ const a = args as Record<string, unknown>+ const width = clampInt(a.width, 1024, 64, 4096)+ const height = clampInt(a.height, 1024, 64, 4096)+ const seed = (typeof a.seed === 'number' && Number.isFinite(a.seed)) ? Math.floor(a.seed) : -1+ const batchSize = clampInt(a.batchSize ?? a.batch_size, 1, 1, 8)+// Image-to-image: resolve the referenced output image into ComfyUI's input// folder, then let buildDynamicWorkflow wire LoadImage → VAEEncode + denoise.let inputImage: string | undefined@@ -584,14 +604,18 @@ async function generateImage(prompt: string, model: string, args: VramHandoffArgprompt,negativePrompt: typeof args.negativePrompt === 'string' ? args.negativePrompt : '',model,- sampler: 'euler',- scheduler: 'normal',- steps: 20,- cfgScale: 7,- width: 1024,- height: 1024,- seed: -1,- batchSize: 1,+ sampler: tun.sampler,+ scheduler: tun.scheduler,+ steps: tun.steps,+ cfgScale: tun.cfg,+ width,+ height,+ seed,+ batchSize,+ ...(typeof a.lora === 'string' && a.lora ? { lora: a.lora as string } : {}),+ ...(typeof a.loraStrength === 'number' ? { loraStrength: a.loraStrength as number } : {}),+ ...(typeof a.vae === 'string' && a.vae ? { vae: a.vae as string } : {}),+ ...(typeof a.clipSkip === 'number' ? { clipSkip: a.clipSkip as number } : {}),...(inputImage ? { inputImage, denoise } : {}),},classifyModel(model),@@ -624,6 +648,8 @@ async function generateVideo(): Promise<string> {try {const type = classifyModel(model)+ // Capability-aware (decision 2): real per-model limits/enums from ComfyUI.+ const caps = await fetchCaps(model, 'video')// ── Image-to-video (SVD / FramePack) ───────────────────────────// Resolve the still into ComfyUI's input folder and route through the@@ -644,21 +670,32 @@ async function generateVideo(throw e}}- // SVD-XT caps ~25 frames. Default to the full clip (~3 s @ 8 fps) and honor- // a requested `seconds` (lowering playback fps if 25 frames can't reach it).- const { frames, fps } = resolveClip(args, { defFps: 8, defFrames: 25, maxFrames: 25 })+ // 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+ // explicit over-limit request so the user sees the actual max (decision 2).+ const defFps = type === 'framepack' ? 16 : 8+ const frameRej = videoFrameReject(model, args, caps)+ if (frameRej) return frameRej+ const i2vMax = caps?.frameRange?.max ?? (type === 'framepack' ? FRAMEPACK_MAX_FRAMES : 25)+ const { frames, fps } = resolveClip(args, { defFps, defFrames: type === 'framepack' ? 49 : 25, maxFrames: i2vMax })+ 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))+ const seed = (typeof av.seed === 'number' && Number.isFinite(av.seed)) ? Math.floor(av.seed) : -1const workflow = await buildDynamicWorkflow({prompt,negativePrompt: typeof args.negativePrompt === 'string' ? args.negativePrompt : '',model,- sampler: 'euler',- scheduler: 'normal',- steps: 20,- cfgScale: 3,- width: 768,- height: 448,- seed: -1,+ sampler: tun.sampler,+ scheduler: tun.scheduler,+ steps: tun.steps,+ cfgScale: tun.cfg,+ width: snapped.width,+ height: snapped.height,+ seed,batchSize: 1,frames,fps,@@ -674,23 +711,30 @@ async function generateVideo(// ── Text-to-video ──────────────────────────────────────────────const defaults = MODEL_TYPE_DEFAULTS[type] ?? MODEL_TYPE_DEFAULTS.wan- const snapped = snapToVideoGrid(defaults.width, defaults.height)- // Text-to-video (Wan/Hunyuan/AnimateDiff) can run longer than SVD — honor a- // requested `seconds` up to a generous cap; default to the model's own length.- const { frames, fps } = resolveClip(args, { defFps: defaults.fps, defFrames: defaults.frames, maxFrames: Math.max(defaults.frames, 161) })+ // Text-to-video (Wan/Hunyuan/etc.) can run longer than SVD. Real ceiling from+ // getModelCapabilities; REJECT (not clamp) an explicit over-limit request.+ const tFrameRej = videoFrameReject(model, args, caps)+ if (tFrameRej) return tFrameRej+ const t2vMax = caps?.frameRange?.max ?? Math.max(defaults.frames, 161)+ const { frames, fps } = resolveClip(args, { defFps: defaults.fps, defFrames: defaults.frames, maxFrames: t2vMax })+ const tun = resolveTunables(args, caps, { steps: defaults.steps, cfg: defaults.cfg, sampler: defaults.sampler, scheduler: defaults.scheduler })+ if (tun.reject) return `Cannot generate: ${tun.reject}`+ const av = args as Record<string, unknown>+ const snapped = snapToVideoGrid(clampInt(av.width, defaults.width, 64, 2048), clampInt(av.height, defaults.height, 64, 2048))+ const seed = (typeof av.seed === 'number' && Number.isFinite(av.seed)) ? Math.floor(av.seed) : -1const workflow = await buildTxt2VidWorkflow({prompt,negativePrompt: typeof args.negativePrompt === 'string' ? args.negativePrompt : '',model,- sampler: defaults.sampler,- scheduler: defaults.scheduler,- steps: defaults.steps,- cfgScale: defaults.cfg,+ sampler: tun.sampler,+ scheduler: tun.scheduler,+ steps: tun.steps,+ cfgScale: tun.cfg,width: snapped.width,height: snapped.height,- seed: -1,+ seed,batchSize: 1,frames,fps,@@ -759,6 +803,104 @@ function clampFloat(v: unknown, fallback: number, min: number, max: number): numreturn Math.max(min, Math.min(max, n))}+// ── Capability validation helpers (v2.5.0 — reject-and-report, decision 2) ──+//+// REJECT, don't clamp: when the user EXPLICITLY asks for a value beyond the+// installed model's real ComfyUI capability, return a clear message with the+// actual limit so they (or the LLM) can retry lower. Only explicit user values+// are checked — our own defaults are never rejected. Exported for unit tests.++export function clampOrReject(label: string, val: number | undefined, range: { min: number; max: number } | undefined): string | null {+ if (val === undefined || range === undefined) return null+ if (val < range.min) return `${label} ${val} is below this model's minimum ${range.min}. Increase it.`+ if (val > range.max) return `${label} ${val} exceeds this model's maximum ${range.max} (from its ComfyUI capabilities). Lower it to ≤${range.max}, or install a model that supports a higher ${label}.`+ return null+}++export function enumReject(label: string, val: string | undefined, options: string[] | undefined): string | null {+ if (!val || !options || options.length === 0) return null+ return options.includes(val) ? null : `${label} "${val}" is not available on this model. Available: ${options.join(', ')}.`+}++interface Tunables { steps: number; cfg: number; sampler: string; scheduler: string; reject: string | null }++/**+ * Resolve steps/cfg/sampler/scheduler from args (explicit user value → else the+ * model/sane default) and reject explicit out-of-range values. Shared by image ++ * video paths. `reject` is non-null only when the USER asked for something the+ * model can't do.+ */+function resolveTunables(+ args: VramHandoffArgs,+ caps: ModelCapabilities | null,+ defs: { steps: number; cfg: number; sampler: string; scheduler: string },+): Tunables {+ const a = args as Record<string, unknown>+ const steps = clampInt(args.steps, caps?.stepsRange?.default ?? defs.steps, 1, 10000)+ const cfgRaw = a.cfg ?? a.cfg_scale ?? a.cfgScale+ const cfg = clampFloat(cfgRaw, caps?.cfgRange?.default ?? defs.cfg, 0, 100)+ const samplerRaw = typeof a.sampler === 'string' ? a.sampler : (typeof a.sampler_name === 'string' ? a.sampler_name : undefined)+ const sampler = samplerRaw ?? defs.sampler+ const scheduler = typeof a.scheduler === 'string' ? a.scheduler : defs.scheduler+ // Report the user's RAW ask in the reject message, not the internally clamped value.+ const stepsAsk = a.steps !== undefined ? Number(a.steps) : undefined+ const cfgAsk = cfgRaw !== undefined ? Number(cfgRaw) : undefined+ const reject =+ clampOrReject('steps', stepsAsk, caps?.stepsRange)+ || clampOrReject('cfg', cfgAsk, caps?.cfgRange)+ || (caps?.usesKSampler+ ? (enumReject('sampler', samplerRaw, caps?.availableSamplers)+ || enumReject('scheduler', typeof a.scheduler === 'string' ? scheduler : undefined, caps?.availableSchedulers))+ : null)+ return { steps, cfg, sampler, scheduler, reject }+}++// resolveClip honors a `seconds` request by lowering playback fps down to a floor+// of 4, so the longest clip a frame-capped model can actually deliver is+// maxFrames / 4 seconds.+const MIN_PLAYBACK_FPS = 4++/**+ * Reject (decision 2) ONLY when the request genuinely exceeds what the model can+ * deliver — NOT when resolveClip would still satisfy it by capping frames and+ * slowing playback (that path is the intended behavior, e.g. SVD seconds=4 →+ * 25f@6fps≈4.2s). Two cases:+ * - explicit `frames` (the exact-count advanced path) → reject if > model max.+ * - `seconds` (the duration control) → resolveClip slows fps to honor it, so only+ * reject when even the slowest playback (maxFrames / 4 fps) can't reach it.+ * Exported for unit tests.+ */+export function videoFrameReject(model: string, args: VramHandoffArgs, caps: ModelCapabilities | null): string | null {+ if (!caps) return null+ // Duration-driven models (FramePack): the real ceiling is seconds (total_second_length).+ if (typeof caps.maxSeconds === 'number' && typeof args.seconds === 'number' && args.seconds > caps.maxSeconds + 0.5) {+ return `Cannot generate: ${model} can make at most ${caps.maxSeconds}s of video (you asked for ${args.seconds}s). Shorten it, or install a model that makes longer clips.`+ }+ if (!caps.frameRange) return null+ const max = caps.frameRange.max+ if (typeof args.frames === 'number' && args.frames > 0 && Math.round(args.frames) > max) {+ return `Cannot generate: ${model} supports at most ${max} frames (you requested ${Math.round(args.frames)}). Lower the frame count, or install a model that makes longer clips (e.g. FramePack or Wan).`+ }+ if (typeof args.seconds === 'number' && args.seconds > 0) {+ const deliverableMaxSec = max / MIN_PLAYBACK_FPS+ if (args.seconds > deliverableMaxSec + 0.5) {+ return `Cannot generate: ${model} can make at most ~${Math.floor(deliverableMaxSec)}s (${max} frames). You asked for ${args.seconds}s. Shorten it, or install a model that makes longer clips (e.g. FramePack or Wan).`+ }+ }+ return null+}++/** Fetch model capabilities; non-fatal (null → caller proceeds with defaults, no validation). */+async function fetchCaps(model: string, kind: 'image' | 'video'): Promise<ModelCapabilities | null> {+ try {+ const m = await import('./comfyui-nodes')+ return await m.getModelCapabilities(model)+ } catch (e) {+ log.warn(`vram_handoff.${kind}.caps_failed`, { model, err: String(e) })+ return null+ }+}+/*** Resolve a clip's (frames, fps) from the agent's optional `seconds` / `frames`* / `fps`, capped to a model's frame limit.