Compare commits

...
2 Commits
9 changed files with 228 additions and 28 deletions
+9
View File
@@ -0,0 +1,9 @@
# DOGMA 1.0.61
- Reorder model blocks by dragging their existing headings vertically, with no additional controls.
- Save model order in the session/workflow and retain it across reloads and Image/Video mode changes. Ignore unknown or duplicated saved keys and include newly available models.
- Preserve expansion, switches and all parameter values while moving existing blocks. Keep ordinary heading clicks and cancel a drag released outside the list. Support Escape and edge scrolling.
- Align the visible sidebar switches with the Image/Video tabs and section dividers while retaining their click-target sizes and the existing text positions.
- Change presentation only: generation planning, seeds, API payloads, video repair and workflow identifiers are unchanged.
Verified with the actual UI in the local browser preview: upward and downward drag, outside-drop cancellation, persistence after reload and mode switching, normal accordion clicks and enable switches. Sidebar switch, divider and tab edges match in Image and Video mode. Generation plans and compiled payloads checked before/after visual reordering. JavaScript syntax and package integrity checked without publication or paid generation.
+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.
+18
View File
@@ -238,3 +238,21 @@ When enabled, API Platform saves the generated original and a second locally pro
API Platform now has a compact **Compare** switch next to **Mostra errori** in the gallery filters and at the right of the enlarged image toolbar. Both controls share one saved session preference. OFF removes the original/reference overlay and divider immediately; ON enables the existing pointer comparison. Existing sessions default to ON. Selecting an explicit A/B pair still opens the comparison automatically and enables Compare. The enlarged-image switch is unavailable when there is no second image to compare.
The extra left inset below the Image/Video tabs is removed from the controls and Image Edit row. References, prompt, filename/workspace and model sections now align with the left edge of the tabs; their existing right edge is preserved. Works in Image and Video mode. Existing node IDs, generation behavior, video repair and workflow JSON are unchanged.
## Drag to reorder models / 1.0.61
Drag an existing model heading up or down to change the order of the blocks under **MODELS**. The order is saved with the session/workflow, including when switching between Image and Video. No new buttons or drag handles are added. A normal click still expands or collapses the model; switches, quantities and parameters keep their usual behavior. Drag near the sidebar edge to scroll, or release outside the list / press Escape to cancel.
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.60"
version = "1.0.62"
license = { file = "LICENSE" }
dependencies = ["scipy>=1.10", "av>=18.0", "opencv-python>=4.8"]
+38 -7
View File
@@ -8,6 +8,10 @@ export const FAMILIES=[
export const VIDEO_FAMILIES=[{key:'seedance',name:'Seedance',short:'V',type:'ByteDance2ReferenceNodeV2'}];
export const ALL_FAMILIES=[...FAMILIES,...VIDEO_FAMILIES];
export const families=s=>s.mode==='video'?VIDEO_FAMILIES:FAMILIES;
export function orderedFamilies(s){
const available=families(s),order=Array.isArray(s.modelOrder)?s.modelOrder:[];
return [...new Set([...order,...available.map(f=>f.key)])].map(key=>available.find(f=>f.key===key)).filter(Boolean);
}
export const safeName=s=>String(s||'').trim().replace(/[^\p{L}\p{N}_.-]+/gu,'_').replace(/^\.+/,'').slice(0,100);
export function inputSpec(def,values,name){
const parts=name.split('.');let inputs=def?.input;
@@ -48,6 +52,7 @@ export function migrateState(raw){
s.workspace ||= '';s.library ||= [];s.results ||= [];s.references ||= [];s.filters ||= {models:[],project:'*',scene:'*',kind:'all',workspace:'*'};s.density ??= 45;s.workExpanded ??= false;
for(const m of Object.values(s.models||{})){m.parameters ||= m.variants?.[0]||{};delete m.variants;delete m.editVariant;delete m.seedMode;}
s.filters.hideErrors ??= false;s.videoRepair ??= false;s.compareEnabled ??= true;
s.modelOrder=[...new Set([...(Array.isArray(s.modelOrder)?s.modelOrder:[]),...ALL_FAMILIES.map(f=>f.key)])].filter(key=>ALL_FAMILIES.some(f=>f.key===key));
for(const [i,r] of s.references.entries()){r.kind ||= 'image';r.role ||= 'reference';const legacyMask=raw.schema===1&&i===0&&!!raw.maskEnabled;r.process ||= {enabled:legacyMask,mask:legacyMask,maskMode:'edit',invert:false,flip:false,crop:false,resizeMpx:false,megapixels:1,expand:0,blur:0,fillHoles:false,targetWidth:0,targetHeight:0,source:'paint',prompt:'',segment:0,background:'#ff00ff'};}
if(raw.schema<3)for(const r of [...s.references])if(r.kind==='image'&&r.modes?.includes('video')&&['first','last'].includes(r.role))s.references.push({...copy(r),role:'reference'});
for(const r of s.results)r.kind ||= 'image';
@@ -57,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');
@@ -77,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;}
+65
View File
@@ -0,0 +1,65 @@
// Reorder only the model blocks. Controls and expansion state stay on their DOM nodes.
export function modelReorder(container,saveOrder){
let active=null,frame=0,suppressClick=false,scroller=null;
const models=()=>[...container.children].filter(e=>e.dataset.modelKey);
const inside=()=>{
const r=container.getBoundingClientRect(),s=scroller.getBoundingClientRect();
return active.x>=r.left&&active.x<=r.right&&active.y>=Math.max(r.top,s.top)&&active.y<=Math.min(r.bottom,s.bottom);
};
const place=()=>{
if(!inside())return;
const next=models().find(row=>{
if(row===active.row)return false;
const r=row.querySelector('.dap-model-head>details>summary').getBoundingClientRect();
return active.y<r.top+r.height/2;
});
if(active.row.nextElementSibling!==next&&(next||active.row!==container.lastElementChild))container.insertBefore(active.row,next||null);
};
const scroll=()=>{
if(!active?.dragging)return;
if(!container.isConnected){finish(false);return;}
const r=scroller.getBoundingClientRect();
if(active.x>=r.left&&active.x<=r.right){
const delta=active.y<r.top+36?-Math.min(12,(r.top+36-active.y)/3):active.y>r.bottom-36?Math.min(12,(active.y-r.bottom+36)/3):0;
if(delta){scroller.scrollTop+=delta;place();}
}
frame=requestAnimationFrame(scroll);
};
const finish=(commit=false)=>{
if(!active)return;
const {row,original,dragging,pointerId}=active;
active=null;cancelAnimationFrame(frame);row.classList.remove('dap-model-dragging');
document.removeEventListener('pointermove',move);document.removeEventListener('pointerup',up);document.removeEventListener('pointercancel',cancel);
document.removeEventListener('keydown',key,true);window.removeEventListener('blur',cancel);
if(container.hasPointerCapture(pointerId))container.releasePointerCapture(pointerId);
if(!dragging)return;
suppressClick=true;setTimeout(()=>suppressClick=false,0);
if(!commit){for(const item of original)container.append(item);return;}
const order=models().map(item=>item.dataset.modelKey);
if(order.some((value,i)=>value!==original[i].dataset.modelKey))saveOrder(order);
};
const move=e=>{
if(!active||e.pointerId!==active.pointerId)return;
active.x=e.clientX;active.y=e.clientY;
if(!active.dragging){
if(Math.hypot(e.clientX-active.startX,e.clientY-active.startY)<6)return;
active.dragging=true;container.setPointerCapture(e.pointerId);active.row.classList.add('dap-model-dragging');frame=requestAnimationFrame(scroll);
}
e.preventDefault();place();
};
const up=e=>{if(active&&e.pointerId===active.pointerId){active.x=e.clientX;active.y=e.clientY;if(active.dragging)e.preventDefault();finish(inside());}};
const cancel=()=>finish(false);
const key=e=>{if(e.key==='Escape'){e.preventDefault();e.stopPropagation();cancel();}};
container.addEventListener('pointerdown',e=>{
if(e.button!==0||e.pointerType==='touch'||active)return;
const summary=e.target.closest('.dap-model-head>details>summary');
if(!summary||!container.contains(summary))return;
scroller=container.closest('.dap-side');if(!scroller)return;
active={row:summary.closest('.dap-model'),original:models(),pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,x:e.clientX,y:e.clientY,dragging:false};
document.addEventListener('pointermove',move,{passive:false});document.addEventListener('pointerup',up);document.addEventListener('pointercancel',cancel);
document.addEventListener('keydown',key,true);window.addEventListener('blur',cancel);
});
container.addEventListener('click',e=>{if(suppressClick){e.preventDefault();e.stopPropagation();}},true);
container.addEventListener('dragstart',e=>{if(active)e.preventDefault();});
container.classList.add('dap-models-sortable');
}
+10
View File
@@ -191,5 +191,15 @@
/* Match the left edge of Image/Video; keep the existing right edge. */
.dap-controls{padding-left:0}
.dap-edit-mode{padding-left:0}
/* Align the visible sidebar levers with the tabs and section dividers. */
.dap-edit-mode>.dap-toggle,.dap-date-row>.dap-toggle,.dap-model-head>.dap-toggle,.dap-video-repair>.dap-toggle{justify-content:flex-start}
.dap-viewer-tools>.dap-compare-toggle{margin-left:auto;font:11px Arial,Helvetica,sans-serif}
.dap-compare-toggle:has(input:disabled){cursor:default;color:#666}
/* The existing model heading is the drag target; no extra handle or toolbar. */
.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.60';
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.60';
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.60',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();}
+66 -11
View File
@@ -1,6 +1,7 @@
import {ALL_FAMILIES,copy,families,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences,visibleReferences,choicesFor,sortedChoices,safeName,orderResults,savedFilename,preparedMask} from './dogma_api_core.js?v=1.0.60';
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';
import {referenceEditor} from './dogma_api_reference_editor.js?v=1.0.57';
export const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
@@ -17,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…');
@@ -86,7 +87,8 @@ export class PlatformUI {
this.field(work,'SCENE',s.scene,v=>{s.scene=v;this.save();this.updateHeader();this.namePreview.textContent=this.filenamePreview();},{placeholder:'Facoltativo'});
const date=el('div','','dap-date-row'),datePicker=el('input');datePicker.type='date';const code=s.date||todayCode();datePicker.value=`20${code.slice(4,6)}-${code.slice(2,4)}-${code.slice(0,2)}`;datePicker.setAttribute('aria-label','Data del filename');datePicker.onchange=()=>{const [year,month,day]=datePicker.value.split('-');if(!year)return;s.date=day+month+year.slice(-2);s.dateMode='manual';this.save();this.namePreview.textContent=this.filenamePreview();};date.append(this.toggle('Aggiungi data al filename',s.appendDate,v=>{s.appendDate=v;s.date ||= todayCode();this.save();this.namePreview.textContent=this.filenamePreview();}),el('span','Aggiungi data'),datePicker);work.append(date);
const choose=ib('folder','Scegli cartella di lavoro',()=>this.chooseWorkspace(),'dap-workspace-button');choose.append(el('span',s.workspace||'Scegli cartella di lavoro'));const folderRow=el('div','','dap-workspace-row'),explorer=btn('Esplora file',()=>this.openWorkspaceExplorer(),'dap-workspace-explorer','Apri in Esplora file');explorer.append(icon('external'));folderRow.append(choose,explorer);work.append(folderRow);
const models=el('section','','dap-section dap-models');models.append(el('div','MODELS','dap-label'));for(const f of families(s))models.append(this.model(f));
const models=el('section','','dap-section dap-models');models.append(el('div','MODELS','dap-label'));for(const f of orderedFamilies(s))models.append(this.model(f));
if(models.querySelectorAll('.dap-model').length>1)modelReorder(models,order=>{s.modelOrder=[...order,...(s.modelOrder||[]).filter(key=>!order.includes(key))];this.save();});
if(s.mode==='video'){const choice=el('section','','dap-video-choice');choice.append(el('div','WORKFLOW VIDEO','dap-label'));for(const [key,label] of [['reference','Ref → Video'],['frames','First / Last frame']]){const b=btn(label,()=>{s.models.seedance.engine=key;this.save();this.renderControls();this.refreshPrices();},key===s.models.seedance.engine?'active':'');choice.append(b);}c.append(choice);}
if(s.mode==='video'){const fix=el('label','','dap-video-repair');fix.append(this.toggle('Correggi scatti',s.videoRepair,v=>{s.videoRepair=v;this.save();},'span'),el('span','Correggi scatti'));fix.append(el('small','Salva anche una seconda copia · durata e fps originali'));c.append(fix);}
c.append(refs,prompt,workLabel,workSection,models);
@@ -115,10 +117,42 @@ 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.setAttribute('role','group');wrap.setAttribute('aria-label',f.name);
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);
const toggle=this.toggle(`Attiva ${f.name}`,m.enabled,v=>{m.enabled=v;wrap.classList.toggle('enabled',v);this.save();this.updateHeader();});wrap.classList.toggle('enabled',m.enabled);
const details=el('details');details.open=!!m.expanded;details.ontoggle=()=>{m.expanded=details.open;this.save();};
const summary=el('summary');this.priceLabels ||= new Map();const price=el('small','— CREDITS / '+(f.key==='seedance'?'RUN':'IMAGE'));this.priceLabels.set(f.key,price);summary.append(el('span',f.name),price,icon('chevron'));details.append(summary);
@@ -137,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'));
@@ -265,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)){
@@ -277,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;}