Compare commits

..
1 Commits
7 changed files with 129 additions and 26 deletions
+9
View File
@@ -0,0 +1,9 @@
# DOGMA 1.0.62
- Fix false Seedream rejection of odd Custom dimensions. Preserve the exact requested width and height, including 2816 × 1485.
- Respect preset precedence over unused Custom fields. Check Seedream's actual megapixel/range/aspect limits before queueing and identify the relevant fields.
- Reveal invalid fields and clear their validation error after correction. Release submission state and queue hooks even when preparation or native submission fails; allow a manual retry without restart.
- Replace a reference when files are dropped onto its thumbnail. Preserve slot/state/role and clear obsolete masks/crops/previews. Keep the original reference if upload fails; validate image/video and First/Last constraints before upload.
- No changes to workflow IDs, API authentication, backend generation or video repair. No paid requests or automatic retries during verification.
Validation: exact Custom payload and preset regression tests; real Seedream limits; upload failures and replacement routing with hidden references; image/video and First/Last roles; Run and queue failure/retry cleanup. Browser preview confirmed invalid-field focus, correction to 2816 × 1485, and successful mocked resubmission after a simulated Comfy error. Package integrity and JavaScript syntax checked.
+9
View File
@@ -247,3 +247,12 @@ Drag an existing model heading up or down to change the order of the blocks unde
The visible switches in model headings, Image Edit, the date row and video repair align with the left edge of the Image/Video tabs and section dividers. Their existing click targets and text positions are preserved; switches inside reference thumbnails and parameter fields keep their own inset.
Generation quantities and seeds, API execution, video repair behavior and existing workflow identifiers remain unchanged. Previous workflows load with their original model order.
## Seedream Custom dimensions and reference replacement / 1.0.62
Seedream Custom dimensions such as **2816 × 1485** are submitted exactly as entered. The previous DOGMA check incorrectly treated the native widget's increment of 2 as a mandatory divisibility rule. Selecting a size preset now validates that preset, rather than the unused Custom values. Current Seedream pixel-count and aspect-ratio limits are checked before submission; errors identify and reveal the affected fields. Correcting a value allows Run to be retried without reopening Comfy. Submission cleanup also restores the queue hooks and releases the DOGMA lock after preparation or queue failures. No automatic retries or dimension rounding are introduced.
Drop an image or video file directly on an existing reference thumbnail to replace that slot. Drops elsewhere keep adding references. If multiple files are dropped onto a thumbnail, the first replaces it and the remaining files are added. Replacement preserves position, enabled state, modes and First/Last role; old masks, crops and previews are discarded because they belong to the previous file. A failed upload leaves the old reference intact. Image-only modes still reject video, and First/Last mode still permits at most two images.
Existing workflow JSON, model ordering, compare controls and video-repair behavior remain unchanged.
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "comfyui-dogma-nodes"
description = "Custom ComfyUI nodes for DOGMA AI video workflows."
version = "1.0.61"
version = "1.0.62"
license = { file = "LICENSE" }
dependencies = ["scipy>=1.10", "av>=18.0", "opencv-python>=4.8"]
+33 -7
View File
@@ -62,7 +62,36 @@ export function plannedJobs(s){const repeats=Number(s.runCount??1);if(!Number.is
export const preparedMask=ref=>!!ref.process?.maskFile&&ref.process.samSource===ref.file&&ref.process.samPrompt===ref.process.prompt&&Number(ref.process.samSegment)===Number(ref.process.segment||0);
export function visibleReferences(s){return s.references.filter(r=>(!r.modes||r.modes.includes(s.mode))&&(s.mode==='video'?(s.models.seedance?.engine==='frames'?r.kind==='image'&&['first','last'].includes(r.role):r.role!=='first'&&r.role!=='last'):r.kind!=='video'));}
export function activeReferences(s){return visibleReferences(s).filter(r=>r.enabled);}
export function validateState(s){
export function mediaKind(file){
if(file.type?.startsWith('image/'))return 'image';if(file.type?.startsWith('video/'))return 'video';
if(file.type&&file.type!=='application/octet-stream')return null;
if(/\.(png|jpe?g|webp|avif|gif|bmp|tiff?)$/i.test(file.name||''))return 'image';
if(/\.(mp4|mov|m4v|webm|mkv|avi)$/i.test(file.name||''))return 'video';return null;
}
function dimensionError(f,fields,message){return Object.assign(new Error(`${f.name}: ${message}`),{family:f.key,fields});}
function validateDimensions(f,p,specFor){
const seedream=f.key==='seedream',model=String(p.model||'').toLowerCase();
const modern=seedream&&(/5[.-]5/.test(model)||/5[.-]0.*(?:pro|flash)/.test(model));
const preset=seedream&&p['model.size_preset']&&p['model.size_preset']!=='Custom';
if(!preset)for(const [k,v] of Object.entries(p))if(/(?:width|height)$/.test(k)){
const info=specFor?.(f,k)?.[1]||{},n=Number(v);
const min=info.min??(seedream&&!/5[.-]5/.test(model)?1024:f.key==='gpt'?480:240);
const max=info.max??(seedream?(/5[.-]5/.test(model)?8594:modern?4514:k.endsWith('width')?6240:4992):f.key==='gpt'?3840:8594);
// Seedream's step=2 is a widget increment, not a server-side divisibility rule.
const step=seedream?1:f.key==='gpt'?16:2,label=k.split('.').at(-1).toUpperCase();
if(!Number.isInteger(n)||n<min||n>max||n%step)throw dimensionError(f,[k],`${label} = ${v}. Inserisci un intero da ${min} a ${max}${step>1?`, multiplo di ${step}`:''}.`);
}
if(!seedream)return;
const match=preset&&String(p['model.size_preset']).match(/(\d+)\s*[x×]\s*(\d+)/i);
// Presets retain native precedence over the unused Custom width and height.
const w=Number(match?match[1]:p['model.width']),h=Number(match?match[2]:p['model.height']);
if(preset&&!match)return;
const fields=preset?['model.size_preset']:['model.width','model.height'];
const pixels=w*h,min=modern||/4[.-]0/.test(model)?921600:3686400,max=modern?4624220:16777216;
if(pixels<min||pixels>max)throw dimensionError(f,fields,`${p.model}: ${w} × ${h} = ${(pixels/1e6).toFixed(2)} MP. Il modello richiede da ${(min/1e6).toFixed(2)} a ${(max/1e6).toFixed(2)} MP. Correggi ${preset?'SIZE PRESET':'WIDTH / HEIGHT'} e premi Run.`);
if(/5[.-]5/.test(model)&&(w/h<1/16||w/h>16))throw dimensionError(f,fields,`${w} × ${h}: rapporto consentito da 1:16 a 16:1. Correggi ${preset?'SIZE PRESET':'WIDTH / HEIGHT'} e premi Run.`);
}
export function validateState(s,specFor){
if(!s.prompts[s.mode]?.trim())throw new Error('Scrivi un prompt.');
if(!plannedJobs(s).length)throw new Error('Attiva almeno un modello.');
const refs=activeReferences(s),imgs=refs.filter(r=>r.kind==='image'),videos=refs.filter(r=>r.kind==='video');
@@ -82,14 +111,11 @@ export function validateState(s){
}
for(const f of families(s)){
const m=s.models[f.key];if(!m.enabled)continue;const p=m.engine==='frames'?m.frames:m.parameters;
for(const [k,v] of Object.entries(p))if(/(?:width|height)$/.test(k)){
const n=Number(v),min=f.key==='gpt'?480:240,max=f.key==='gpt'?3840:8594,step=f.key==='gpt'?16:2;
if(!Number.isInteger(n)||n<min||n>max||n%step)throw new Error(`${f.name}: dimensioni da ${min} a ${max}, multiple di ${step}.`);
}
validateDimensions(f,p,specFor);
}
}
export function compileBatch(s,jobs,baseSeed){
validateState(s);const output={},refs=activeReferences(s),images=[],videos=[];
export function compileBatch(s,jobs,baseSeed,specFor){
validateState(s,specFor);const output={},refs=activeReferences(s),images=[],videos=[];
refs.forEach((ref,i)=>{
const id=String(9000+i*10);output[id]={class_type:ref.kind==='video'?'LoadVideo':'LoadImage',inputs:{[ref.kind==='video'?'file':'image']:ref.file}};
if(ref.kind==='video'){videos.push({ref,link:[id,0]});return;}
+3
View File
@@ -200,3 +200,6 @@
.dap-models-sortable>.dap-model>.dap-model-head>details>summary{cursor:grab;user-select:none}
.dap-models-sortable>.dap-model>.dap-model-head>details>summary:active{cursor:grabbing}
.dap-model-dragging{opacity:.55}
/* Explain validation in the affected field without adding permanent controls. */
.dap-field:has([aria-invalid="true"]){outline:1px solid var(--orange);outline-offset:-1px}
+12 -9
View File
@@ -1,9 +1,9 @@
import { app } from '../../scripts/app.js';
import { api } from '../../scripts/api.js';
import { PlatformUI } from './dogma_api_ui.js?v=1.0.61';
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.61';
import { PlatformUI } from './dogma_api_ui.js?v=1.0.62';
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.62';
const ROOT=new URL('.',import.meta.url);
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_api_platform.css?v=1.0.61',ROOT);document.head.append(css);
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_api_platform.css?v=1.0.62',ROOT);document.head.append(css);
let opened=null,queueLock=false;
const cachedSchemas=fetch(new URL('dogma_api_schemas.json?v=1.0.57',ROOT)).then(r=>r.json()).catch(()=>({}));
@@ -70,13 +70,16 @@ class ComfyBridge {
}
async queue(compiled,batch,state){
if(queueLock||app.processingQueue||app.queueItems?.length)throw new Error('Comfy sta già inviando una richiesta. Riprova tra un momento.');
queueLock=true;let result=null,used=false;const workflow=copy(app.graph.serialize());workflow.extra ||= {};workflow.extra.dogma_api_batch={session:state.session,id:batch,jobs:copy(compiled.jobs)};
queueLock=true;let result=null,used=false,queueError=null,build,capture;
const nativeBuild=app.graphToPrompt,nativeQueue=api.queuePrompt;
const build=function(...args){if(used)return nativeBuild.apply(this,args);used=true;return Promise.resolve({workflow,output:compiled.output});};
const capture=async function(...args){const r=await nativeQueue.apply(this,args);if(args[1]?.workflow===workflow)result=r;return r;};
app.graphToPrompt=build;api.queuePrompt=capture;
try{await app.queuePrompt(0,1);if(!result?.prompt_id)throw new Error('Comfy non ha accettato il batch. Controlla accesso e messaggi di Comfy.');return result.prompt_id;}
finally{if(app.graphToPrompt===build)app.graphToPrompt=nativeBuild;if(api.queuePrompt===capture)api.queuePrompt=nativeQueue;queueLock=false;}
try{
const workflow=copy(app.graph.serialize());workflow.extra ||= {};workflow.extra.dogma_api_batch={session:state.session,id:batch,jobs:copy(compiled.jobs)};
build=function(...args){if(used)return nativeBuild.apply(this,args);used=true;return Promise.resolve({workflow,output:compiled.output});};
capture=async function(...args){try{const r=await nativeQueue.apply(this,args);if(args[1]?.workflow===workflow)result=r;return r;}catch(e){if(args[1]?.workflow===workflow)queueError=e;throw e;}};
app.graphToPrompt=build;api.queuePrompt=capture;
await app.queuePrompt(0,1);if(queueError)throw queueError;
if(!result?.prompt_id)throw new Error('Comfy non ha accettato il batch. Controlla accesso e messaggi di Comfy.');return result.prompt_id;
}finally{if(build&&app.graphToPrompt===build)app.graphToPrompt=nativeBuild;if(capture&&api.queuePrompt===capture)api.queuePrompt=nativeQueue;queueLock=false;}
}
subscribe(handler){const controller=new AbortController();for(const name of ['execution_start','executing','executed','execution_success','execution_error','execution_interrupted','progress','progress_state','dogma_video_repair'])api.addEventListener(name,e=>{let d=e.detail;if(name==='execution_start')this.activePrompt=d.prompt_id;if(name==='executing'&&(typeof d==='string'||d===null))d={node:d,prompt_id:this.activePrompt};handler(name,d);},{signal:controller.signal});return ()=>controller.abort();}
async history(){const r=await api.fetchApi('/history?max_items=200');if(!r.ok)throw new Error('Cronologia non disponibile.');return r.json();}
+62 -9
View File
@@ -1,4 +1,4 @@
import {ALL_FAMILIES,copy,families,orderedFamilies,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences,visibleReferences,choicesFor,sortedChoices,safeName,orderResults,savedFilename,preparedMask} from './dogma_api_core.js?v=1.0.61';
import {ALL_FAMILIES,copy,families,orderedFamilies,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences,visibleReferences,choicesFor,sortedChoices,safeName,orderResults,savedFilename,preparedMask,mediaKind} from './dogma_api_core.js?v=1.0.62';
import {icon} from './dogma_api_icons.js?v=1.0.57';
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.60';
import {modelReorder} from './dogma_api_model_order.js?v=1.0.61';
@@ -18,7 +18,7 @@ export class PlatformUI {
this.root=el('dialog','','dap');this.root.setAttribute('aria-label','DOGMA API Platform');
this.root.addEventListener('cancel',e=>{e.preventDefault();this.close();});
this.root.addEventListener('dragover',e=>{if([...e.dataTransfer.types].includes('Files'))e.preventDefault();});
this.root.addEventListener('drop',e=>{e.preventDefault();if(e.dataTransfer.files.length)this.addReferences([...e.dataTransfer.files]);});
this.root.addEventListener('drop',e=>this.dropReferences(e));
document.body.append(this.root);this.build();this.root.tabIndex=-1;this.root.showModal();this.root.focus({preventScroll:true});
this.unsubscribe=this.bridge.subscribe?.((name,d)=>this.event(name,d));
this.note('Apertura · Collegamento a Comfy…');
@@ -117,7 +117,39 @@ export class PlatformUI {
const frames=this.state.mode==='video'&&this.state.models.seedance.engine==='frames',mixed=this.state.mode==='video'&&!frames;const add=ib('plus',mixed?'Aggiungi immagini o video':'Aggiungi immagine',()=>this.pickReferences(),'dap-add');const hoverIcon=icon(mixed?'media':'image');hoverIcon.classList.add('dap-add-hover');add.append(hoverIcon);if(!frames||visible.length<2)this.refs.append(add);
}
pickReferences(replace=null){const i=el('input');i.type='file';i.accept=this.state.mode==='video'&&this.state.models.seedance.engine!=='frames'?'image/*,video/*':'image/*';i.multiple=!replace;i.hidden=true;this.root.append(i);i.onchange=()=>{this.addReferences([...i.files],replace);i.remove();};i.addEventListener('cancel',()=>i.remove(),{once:true});i.click();}
async addReferences(files,replace=null){try{this.note('Caricamento reference…');for(const file of files){if(!/^(image|video)\//.test(file.type))throw new Error('Scegli immagini o video.');const frames=this.state.mode==='video'&&this.state.models.seedance.engine==='frames';if(file.type.startsWith('video/')&&(this.state.mode==='image'||frames))throw new Error('In questa modalità puoi caricare solo immagini.');if(frames&&!replace&&visibleReferences(this.state).length>=2)throw new Error('First / Last frame accetta due immagini.');const uploaded=await this.bridge.upload(file);if(this.closed)return;const r={...uploaded,enabled:true,modes:[this.state.mode],role:frames?(replace?.role|| (visibleReferences(this.state).some(r=>r.role==='first')?'last':'first')):'reference',process:{enabled:false,mask:false,maskMode:'edit',source:'paint',flip:false,invert:false,crop:false,fillHoles:false,expand:0,blur:0,targetWidth:0,targetHeight:0,background:'#ff00ff'}};if(replace){const at=this.state.references.indexOf(replace);this.state.references.splice(at,1,r);}else this.state.references.push(r);}this.save();this.renderRefs();this.refreshPrices();this.note('Reference aggiornate. L’ordine è quello mostrato.');}catch(e){this.note(e.message,true);}}
dropReferences(e){
const files=[...(e.dataTransfer?.files||[])];if(!files.length)return;
e.preventDefault();e.stopPropagation();
const tile=e.target.closest?.('.dap-ref'),replace=tile&&this.refs?.contains(tile)?visibleReferences(this.state)[Number(tile.dataset.ref)]:null;
return this.addReferences(files,replace);
}
async addReferences(files,replace=null){
if(!files.length)return;
try{
const mode=this.state.mode,engine=this.state.models.seedance?.engine,frames=mode==='video'&&engine==='frames';
const kinds=files.map(mediaKind);
if(kinds.some(k=>!k))throw new Error('Scegli immagini o video.');
if(kinds.includes('video')&&(mode==='image'||frames))throw new Error('In questa modalità puoi caricare solo immagini.');
if(replace&&!this.state.references.includes(replace))throw new Error('La reference da sostituire non è più presente.');
if(frames&&visibleReferences(this.state).length+files.length-(replace?1:0)>2)throw new Error('First / Last frame accetta due immagini.');
this.note(replace?'Sostituzione reference…':'Caricamento reference…');
const uploaded=[];for(const file of files)uploaded.push(await this.bridge.upload(file));
if(this.closed)return;
if(this.state.mode!==mode||this.state.models.seedance?.engine!==engine)throw new Error('Modalità cambiata durante il caricamento. Rilascia nuovamente i file.');
const at=replace?this.state.references.indexOf(replace):-1;
if(replace&&at<0)throw new Error('La reference da sostituire è stata rimossa. Rilascia nuovamente il file.');
if(frames&&visibleReferences(this.state).length+files.length-(replace?1:0)>2)throw new Error('First / Last frame accetta due immagini.');
const roles=new Set(visibleReferences(this.state).filter(r=>r!==replace).map(r=>r.role));
const incoming=uploaded.map((item,i)=>{
const previous=i===0?replace:null,role=previous?.role||(frames?(!roles.has('first')?'first':'last'):'reference');roles.add(role);
return {...item,kind:kinds[i],enabled:previous?.enabled??true,modes:previous?.modes?[...previous.modes]:[mode],role,
process:{enabled:false,mask:false,maskMode:'edit',source:'paint',flip:false,invert:false,crop:false,fillHoles:false,expand:0,blur:0,targetWidth:0,targetHeight:0,background:'#ff00ff'}};
});
if(replace){this.state.references.splice(at,1,incoming[0]);this.state.references.push(...incoming.slice(1));}
else this.state.references.push(...incoming);
this.save();this.renderRefs();this.refreshPrices();this.note(replace?'Reference sostituita.':'Reference aggiornate. L’ordine è quello mostrato.');
}catch(e){this.note(e.message,true);}
}
referenceVideo(ref){openViewer(this,{job:{kind:'video',label:ref.file,study:true},file:{url:ref.preview||this.bridge.view(ref.file)},index:0});}
model(f){
const m=this.state.models[f.key],wrap=el('div','','dap-model'),row=el('div','','dap-model-head');wrap.dataset.modelKey=f.key;wrap.setAttribute('role','group');wrap.setAttribute('aria-label',f.name);
@@ -139,7 +171,7 @@ export class PlatformUI {
const spec=this.bridge.inputSpec?.(this.state,f,key);
if(spec){const info=spec[1]||{};if(Array.isArray(spec[0]))opts.choices=spec[0];else if(choicesFor(spec))opts.choices=choicesFor(spec);if(info.min!==undefined)opts.min=info.min;if(info.max!==undefined)opts.max=info.max;if(info.step!==undefined)opts.step=info.step;}
if(opts.choices){opts.choices=sortedChoices(key,opts.choices);delete opts.readonly;}
this.field(body,displayName(key),value,v=>{values[key]=typeof value==='boolean'?v:typeof value==='number'?Number(v):v;if(key==='model'){this.bridge.changeModel?.(this.state,f);this.renderControls();}this.save();this.refreshPrices();},opts);
this.field(body,displayName(key),value,v=>{values[key]=typeof value==='boolean'?v:typeof value==='number'?Number(v):v;if(key==='model'){this.bridge.changeModel?.(this.state,f);this.renderControls();}this.save();this.refreshPrices();this.recheckValidation();},opts);
}
if(values.system_prompt!==undefined){const advanced=el('details','','dap-advanced');advanced.append(el('summary','SYSTEM PROMPT'));const text=el('textarea');text.value=values.system_prompt;text.setAttribute('aria-label',f.name+' system prompt');text.oninput=()=>{values.system_prompt=text.value;this.save();};advanced.append(text);body.append(advanced);}
if(f.key==='seedance')body.append(el('div',m.engine==='frames'?'Usa un First frame, un Last frame o entrambi. Sono accettate soltanto immagini.':'Usa immagini o video come reference. In Edit la durata segue il video sorgente.','dap-field-hint'));
@@ -267,11 +299,32 @@ export class PlatformUI {
this.save();this.updateCards();this.note(results.some(r=>r.status==='rejected')?'Una richiesta di stop non è riuscita. Riprova.':'Stop inviato a Comfy. Le richieste già completate dal servizio possono essere addebitate.',results.some(r=>r.status==='rejected'));
}
async refreshLibrary(){if(!this.bridge.library||this.closed)return;try{this.library=await this.bridge.library();if(this.closed)return;for(const r of this.library.filter(r=>r.imported)){const existing=this.state.results.find(j=>j.id===r.id);if(existing)Object.assign(existing,r);}this.renderFilters();this.renderGallery();}catch(e){this.note('Libreria temporaneamente non disponibile.',true);}}
clearValidation(){
this.validationError=null;for(const input of this.controls?.querySelectorAll('[aria-invalid="true"]')||[])input.removeAttribute('aria-invalid');
}
reportValidation(error,focus=true){
this.clearValidation();this.validationError=error;this.note(error.message,true);
if(!error.family)return;
const model=[...(this.controls?.querySelectorAll('.dap-model')||[])].find(e=>e.dataset.modelKey===error.family);if(!model)return;
const fields=new Set((error.fields||[]).map(displayName)),inputs=[...model.querySelectorAll('input,select')].filter(e=>fields.has(e.getAttribute('aria-label')));
for(const input of inputs)input.setAttribute('aria-invalid','true');
if(focus){model.querySelector('details').open=true;this.state.models[error.family].expanded=true;this.save();
if(inputs[0]){inputs[0].focus({preventScroll:true});inputs[0].scrollIntoView({block:'center',inline:'nearest'});}
}
}
recheckValidation(){
if(!this.validationError)return;
try{validateState(this.state,(f,k)=>this.bridge.inputSpec?.(this.state,f,k));this.clearValidation();this.note('Parametri validi. Premi Run per generare.');}
catch(e){this.reportValidation(e,false);}
}
async run(){
if(this.busy)return;try{validateState(this.state);}catch(e){this.note(e.message,true);return;}
this.stopRequested=false;this.busy=true;this.updateHeader();const snapshot=copy(this.state),batch=crypto.randomUUID(),started=Date.now();
const jobs=plannedJobs(snapshot).map((p,ordinal)=>({...p,id:crypto.randomUUID(),batch,started,batchStarted:started,ordinal,status:'submitting',images:[]}));
if(this.busy||!this.ready)return;const specFor=(f,k)=>this.bridge.inputSpec?.(this.state,f,k);
try{validateState(this.state,specFor);}catch(e){this.reportValidation(e);return;}
this.clearValidation();let jobs=[];
try{
this.stopRequested=false;this.busy=true;this.pendingEvents=[];this.updateHeader();
const snapshot=copy(this.state),batch=crypto.randomUUID(),started=Date.now();
jobs=plannedJobs(snapshot).map((p,ordinal)=>({...p,id:crypto.randomUUID(),batch,started,batchStarted:started,ordinal,status:'submitting',images:[]}));
const primary=activeReferences(snapshot).find(r=>r.kind==='image');
for(const ref of activeReferences(snapshot).filter(r=>r.kind==='image'&&r.process?.enabled)){
if((ref.process.source==='prompt'&&ref.process.mask)||(ref===primary&&snapshot.mode==='image'&&snapshot.imageEdit)){
@@ -279,11 +332,11 @@ export class PlatformUI {
if(prepared.maskFile)Object.assign(ref.process,{maskFile:prepared.maskFile,samSource:prepared.samSource,samPrompt:prepared.samPrompt,samSegment:prepared.samSegment});
}
}
const seed=new Uint32Array(1);crypto.getRandomValues(seed);const compiled=compileBatch(snapshot,jobs,seed[0]%2147483647);
const seed=new Uint32Array(1);crypto.getRandomValues(seed);const compiled=compileBatch(snapshot,jobs,seed[0]%2147483647,(f,k)=>this.bridge.inputSpec?.(snapshot,f,k));
this.note('Controllo reference e nodi…');await this.bridge.check(snapshot,compiled);if(this.closed||this.stopRequested)return;
this.state.results.push(...jobs);this.save();this.renderFilters();this.renderGallery();this.galleryViewport.scrollTop=0;
const promptId=await this.bridge.queue(compiled,batch,this.state);for(const job of jobs){job.promptId=promptId;if(job.status==='submitting')job.status='queued';}for(const [name,d] of this.pendingEvents||[])this.event(name,d);this.pendingEvents=[];if(this.stopRequested)await this.stop();this.save();this.updateCards();this.note(`${jobs.length} generazioni indipendenti inviate in un unico batch parallelo.`);
}catch(e){for(const j of jobs){if(!terminal.has(j.status)){j.stoppedProgress=this.jobProgress(j).percent;j.status='failed';j.error=e.message;j.finished=Date.now();j.errorVisibleUntil=Date.now()+5000;}}this.save();this.updateCards();this.note(e.message,true);}finally{this.busy=false;if(!this.closed)this.updateHeader();}
}catch(e){for(const j of jobs){if(!terminal.has(j.status)){j.stoppedProgress=this.jobProgress(j).percent;j.status='failed';j.error=e.message;j.finished=Date.now();j.errorVisibleUntil=Date.now()+5000;}}this.save();this.updateCards();this.reportValidation(e);}finally{this.busy=false;this.pendingEvents=[];if(!this.closed)this.updateHeader();}
}
event(name,d){
if(name==='dogma_video_repair'){const job=this.state.results.find(j=>j.id===d?.job_id);if(job&&!terminal.has(job.status)){job.status='repairing';job.repairProgress=d.value;job.repairStage=d.stage;this.save();this.updateCards();}return;}