Compare commits

...
1 Commits
13 changed files with 253 additions and 96 deletions
+3
View File
@@ -0,0 +1,3 @@
# DOGMA 1.0.55 / API Platform V3
Immediate UI shell; one-node workflow; native model dropdowns and sorted resolutions; separate video reference and first/last modes; input-only image references; fixed nested reference preview URL; in-browser folder selection and reveal; server-enforced project/scene hierarchy; Stop; progress/estimated time; luminous trail; original A/B geometry; collapsible filename controls. Preset and Custom dimensions retain native behavior.
+4
View File
@@ -196,3 +196,7 @@ The original graphs are retained but inactive; use Run in the DOGMA panel.
Includes image/video references, per-reference preparation, Seedance video,
project library, workspace copies, Comfy credits/pricing and zoom comparison.
Existing DOGMA and H3 workflows keep their identifiers.
## API Platform V3 / 1.0.55
Open DOGMA_API_PLATFORM_V3.json: one launcher node. The panel appears before asynchronous initialization. Folder navigation stays in the browser. Stop cancels DOGMA jobs; provider billing for already completed work still applies. Remaining time is an estimate from completed jobs when available.
+99 -35
View File
@@ -16,6 +16,7 @@ import uuid
_LOCK = threading.RLock()
_WORKSPACES = set()
_FRONTEND_CACHE = {}
def _output():
@@ -63,9 +64,13 @@ def _record(metadata, files, kind):
shutil.copy2(source, destination)
exported.append(str(destination))
sidecar = target / (identifier+'.dogma.json')
sidecar.write_text(json.dumps({**data, 'exported': exported}, ensure_ascii=False, indent=2), encoding='utf8')
sidecar.write_text(json.dumps({**data, 'exported': exported, 'dogma_schema':3, 'workspace_relative':target.relative_to(workspace).as_posix()}, ensure_ascii=False, indent=2), encoding='utf8')
except (OSError, ValueError) as exc:
warning = 'File salvato in Comfy; copia nella cartella di lavoro non riuscita: '+str(exc)
if not workspace:
for file in files:
target=root/file.get('subfolder','')
(target/(identifier+'.dogma.json')).write_text(json.dumps({**data,'dogma_schema':3},ensure_ascii=False,indent=2),encoding='utf8')
data['exported'] = exported
if warning:data['warning'] = warning
path = _library() / (identifier+'.json')
@@ -76,6 +81,38 @@ def _record(metadata, files, kind):
return data
def _import_workspace(root):
"""Portable sidecars travel with the output; no inference from filename tags."""
root=Path(root).resolve();records=[];seen=set()
from itertools import chain
legacy=(p for directory in root.rglob('.library') if directory.is_dir() for p in directory.glob('*.json'))
for path in chain(root.rglob('*.dogma.json'),legacy):
if len(records)>=5000:break
if not path.resolve().is_relative_to(root):continue
try:
data=json.loads(path.read_text('utf8'));identifier=str(data.get('id',''))
if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}',identifier):continue
if identifier in seen:continue
files=[];exported=[]
for index,original in enumerate(data.get('images',[])):
copies=data.get('exported',[])
name=Path(copies[index].replace('\\','/')).name if index<len(copies) else Path(original.get('filename','')).name
if path.parent.name=='.library':
subfolder=str(original.get('subfolder','')).replace('\\','/')
relative=subfolder.removeprefix('DOGMA/API').lstrip('/')
candidate=(path.parent.parent/relative/name).resolve()
else:candidate=(path.parent/name).resolve()
if not candidate.is_relative_to(root) or not candidate.is_file():continue
files.append({'filename':name,'workspace':str(root),'relative':candidate.relative_to(root).as_posix(),'type':'workspace'})
exported.append(str(candidate))
if not files:continue
data.update(workspace=str(root),images=files,exported=exported,status='completed',imported=True)
(_library()/(identifier+'.json')).write_text(json.dumps(data,ensure_ascii=False),encoding='utf8')
records.append(data);seen.add(identifier)
except (ValueError,OSError,KeyError,TypeError):continue
return records
def process_reference(image, mask, settings):
"""Shared Pillow operation used by the node and by the no-generation preview."""
import numpy as np
@@ -144,6 +181,11 @@ class DOGMAAPIReferenceV2:
return (torch.stack(results),)
def _save_prefix(data):
basename=Path(str(data.get('prefix') or 'DOGMA').replace('\\','/')).name
return '/'.join(['DOGMA','API',*[_clean(data.get(k)) for k in ('project','scene') if _clean(data.get(k))],basename])
class DOGMAAPIImageOutputV2:
@classmethod
def INPUT_TYPES(cls):
@@ -157,7 +199,7 @@ class DOGMAAPIImageOutputV2:
from nodes import SaveImage
data=json.loads(metadata)
# Same output and metadata behavior as the native SaveImage node.
result=SaveImage().save_images(images,data['prefix'],prompt,extra_pnginfo)
result=SaveImage().save_images(images,_save_prefix(data),prompt,extra_pnginfo)
record=_record(metadata,result['ui']['images'],'image')
return {'ui':{**result['ui'],'dogma_records':[record]},'result':()}
@@ -176,7 +218,7 @@ class DOGMAAPIVideoOutputV2:
import folder_paths
from comfy.cli_args import args
data=json.loads(metadata);width,height=video.get_dimensions()
folder,filename,counter,subfolder,_=folder_paths.get_save_image_path(data['prefix'],str(_output()),width,height)
folder,filename,counter,subfolder,_=folder_paths.get_save_image_path(_save_prefix(data),str(_output()),width,height)
filename=f'{filename}_{counter:05}_.mp4'
saved_metadata=None if args.disable_metadata else {**(extra_pnginfo or {}),'prompt':prompt}
video.save_to(str(Path(folder)/filename),format=Types.VideoContainer('mp4'),codec=Types.VideoCodec('auto'),metadata=saved_metadata)
@@ -187,6 +229,8 @@ class DOGMAAPIVideoOutputV2:
def frontend_modules(web_root):
"""Discover the installed frontend's own shared billing/pricing modules."""
cache_key=str(web_root)
if cache_key in _FRONTEND_CACHE:return _FRONTEND_CACHE[cache_key]
assets=Path(web_root)/'assets';result={}
for path in assets.glob('*.js'):
if path.name.startswith('useBillingContext-'):
@@ -198,6 +242,7 @@ def frontend_modules(web_root):
elif path.name.startswith('creditsUtil-'):
text=path.read_text('utf8');match=re.search(r'formatCreditsFromCents as (\w+)',text)
if match:result['credits']={'file':path.name,'format':match[1]}
_FRONTEND_CACHE[cache_key]=result
return result
@@ -211,7 +256,7 @@ def register_routes():
@routes.get('/dogma/api/v2/catalog')
async def catalog(request):
capabilities=access.catalog(request,_output())
return web.json_response({'access':capabilities,'frontend':frontend_modules(PromptServer.instance.web_root),'version':'1.0.54'})
return web.json_response({'access':{**capabilities,'output_root':str(_output()/'DOGMA'/'API')},'frontend':frontend_modules(PromptServer.instance.web_root),'version':'1.0.55'})
@routes.post('/dogma/api/v2/workspace')
async def workspace(request):
@@ -220,42 +265,62 @@ def register_routes():
path=access.output_path(request,data.get('path'),_output())
if not path.is_dir():raise ValueError('Scegli una cartella esistente.')
_WORKSPACES.add(str(path))
return web.json_response({'path':str(path)})
records=await asyncio.to_thread(_import_workspace,path)
return web.json_response({'path':str(path),'records':records})
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
@routes.post('/dogma/api/v2/choose-folder')
async def choose(request):
access.browser(request);access.local(request)
if os.name!='nt':raise web.HTTPBadRequest(text='Usa il browser delle cartelle sul server.')
data=await request.json();initial=str(data.get('path') or _output())
script="""[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
Add-Type -AssemblyName System.Windows.Forms
$dialog = New-Object System.Windows.Forms.FolderBrowserDialog
$dialog.Description = 'DOGMA / Scegli la cartella di lavoro'
$dialog.SelectedPath = $env:DOGMA_FOLDER_INITIAL
$dialog.ShowNewFolderButton = $true
if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Write($dialog.SelectedPath) }
"""
def select():
env=os.environ.copy();env['DOGMA_FOLDER_INITIAL']=initial
result=subprocess.run(['powershell.exe','-NoProfile','-STA','-WindowStyle','Hidden','-Command',script],capture_output=True,env=env,encoding='utf8',timeout=300,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
if result.returncode:raise ValueError('La scelta cartella non è riuscita.')
return result.stdout.strip()
try:
selected=await asyncio.to_thread(select)
if selected:_WORKSPACES.add(str(Path(selected).resolve()))
return web.json_response({'path':selected,'cancelled':not selected})
except (ValueError,OSError,subprocess.TimeoutExpired) as exc:raise web.HTTPBadRequest(text=str(exc))
access.browser(request)
return web.json_response({'browse':True})
@routes.get('/dogma/api/v2/folders')
async def folders(request):
access.browser(request)
try:
path=access.output_path(request,request.query.get('path'),_output())
path=access.output_path(request,request.query.get('path') or str(_library().parent),_output())
if not path.is_dir():raise ValueError('Cartella inesistente.')
dirs=[{'name':p.name,'path':str(p.resolve())} for p in path.iterdir() if p.is_dir() and (access.is_local(request) or p.resolve().is_relative_to(_output()))]
parent=str(path.parent) if access.is_local(request) or path.parent.is_relative_to(_output()) else None
return web.json_response({'path':str(path),'parent':parent,'directories':sorted(dirs,key=lambda d:d['name'].lower())})
local=access.is_local(request)
def scan():
dirs=[];files=[]
for p in path.iterdir():
if p.name.startswith('.'):continue
try:
if not local and not p.resolve().is_relative_to(_output()):continue
if p.is_dir():dirs.append({'name':p.name,'path':str(p.resolve())})
elif p.is_file():files.append({'name':p.name})
except OSError:continue
parent=str(path.parent) if path.parent!=path and (local or path.parent.is_relative_to(_output())) else None
roots=[]
if local and os.name=='nt':
roots=[{'name':letter+':','path':letter+':/'} for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if Path(letter+':/').is_dir()]
return {'path':str(path),'parent':parent,'roots':roots,'directories':sorted(dirs,key=lambda d:d['name'].lower()),'files':sorted(files,key=lambda d:d['name'].lower())[:5000]}
return web.json_response(await asyncio.to_thread(scan))
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
@routes.post('/dogma/api/v2/mkdir')
async def mkdir(request):
access.browser(request);data=await request.json()
try:
parent=access.output_path(request,data.get('path'),_output())
name=str(data.get('name','')).strip()
if not name or name in ('.','..') or re.search(r'[<>:"/\\|?*]',name) or name.endswith(('.', ' ')):raise ValueError('Nome cartella non valido.')
target=parent/name
if not parent.is_dir():raise ValueError('Cartella superiore inesistente.')
target.mkdir(exist_ok=False)
return web.json_response({'path':str(target.resolve())})
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
@routes.get('/dogma/api/v2/workspace-media')
async def workspace_media(request):
access.fetch_site(request)
try:
root=access.output_path(request,request.query.get('workspace'),_output())
if str(root) not in _WORKSPACES:raise ValueError('Riseleziona la cartella di lavoro.')
relative=request.query.get('relative','');file=(root/relative).resolve()
if not file.is_relative_to(root) or file.suffix.lower() not in ('.png','.jpg','.jpeg','.webp','.mp4','.webm','.mov'):raise ValueError('File non valido.')
if not file.is_file():raise ValueError('File non disponibile.')
return web.FileResponse(file)
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
@routes.get('/dogma/api/v2/library')
@@ -271,7 +336,7 @@ if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console
@routes.post('/dogma/api/v2/open-output')
async def open_output(request):
access.browser(request);access.local(request)
access.browser(request)
data=await request.json();identifier=str(data.get('id',''))
if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}',identifier):raise web.HTTPBadRequest(text='Output non valido.')
try:
@@ -279,9 +344,8 @@ if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console
index=max(0,int(data.get('index',0)));copies=record.get('exported',[])
file=Path(copies[index]) if index<len(copies) else _output()/record['images'][index].get('subfolder','')/record['images'][index]['filename']
if not file.is_file():raise ValueError('Il file è stato spostato o rimosso.')
if os.name=='nt':subprocess.Popen(['explorer.exe','/select,',str(file)],creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
else:raise ValueError('Esplora risorse è disponibile sul Comfy Windows locale.')
return web.json_response({'ok':True})
access.output_path(request,str(file.parent),_output())
return web.json_response({'path':str(file.parent),'filename':file.name})
except (ValueError,OSError,IndexError,KeyError) as exc:raise web.HTTPBadRequest(text=str(exc))
@routes.post('/dogma/api/v2/reference-preview')
@@ -291,7 +355,7 @@ if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console
def prepare():
source=Path(folder_paths.get_annotated_filepath(data['file'])).resolve()
if not source.is_relative_to(Path(folder_paths.get_input_directory()).resolve()):raise ValueError('Reference esterna a input.')
rgba=Image.open(source).convert('RGBA');mask=ImageOps.invert(rgba.getchannel('A'))
rgba=ImageOps.exif_transpose(Image.open(source)).convert('RGBA');mask=ImageOps.invert(rgba.getchannel('A'))
settings=data['settings']
if settings.get('source')=='prompt' and settings.get('mask'):raise ValueError('La maschera da testo viene calcolata da SAM3 durante Run. Per l’anteprima usa una maschera dipinta.')
if settings.get('maskFile'):
+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.54"
version = "1.0.55"
license = { file = "LICENSE" }
dependencies = ["scipy>=1.10"]
+28 -3
View File
@@ -18,20 +18,43 @@ export function inputSpec(def,values,name){
}
return null;
}
export function viewParameters(file){
if(typeof file!=='string')return {filename:file.filename,subfolder:file.subfolder||'',type:file.type||'output'};
const parts=file.replaceAll('\\','/').split('/');return {filename:parts.pop(),subfolder:parts.join('/'),type:'input'};
}
export function choicesFor(spec){if(!spec)return null;if(Array.isArray(spec[0]))return spec[0];if(spec[0]==='COMBO')return spec[1].options;if(spec[0]==='COMFY_DYNAMICCOMBO_V3')return spec[1].options.map(o=>o.key);return null;}
export function parameterSpecs(def,values){
const result={};const walk=(inputs,prefix='')=>{for(const [key,spec] of Object.entries({...inputs?.required,...inputs?.optional})){
const name=prefix+key;const choices=choicesFor(spec);
if(choices||['INT','FLOAT','BOOLEAN','STRING'].includes(spec[0]))result[name]=spec;
if(spec[0]==='COMFY_DYNAMICCOMBO_V3')walk(spec[1].options.find(o=>o.key===values[name])?.inputs,name+'.');
}};walk(def?.input);return result;
}
export function modelValues(def,values){
const specs=parameterSpecs(def,values),next={};for(const [key,spec] of Object.entries(specs)){
const choices=choicesFor(spec),value=values[key];next[key]=value!==undefined&&(!choices||choices.includes(value))?value:spec[1]?.default??choices?.[0]??(spec[0]==='BOOLEAN'?false:spec[0]==='STRING'?'':0);
}return next;
}
export function sortedChoices(key,values){
const list=[...new Set(values.map(String))];if(!/resolution|size_preset|size$/.test(key))return list;
const score=v=>{if(key==='model.size_preset'){const tier=v.match(/([\d.]+)K/i);return tier?+tier[1]:Infinity;}const dims=v.match(/(\d+)x(\d+)/);if(dims)return +dims[1]*+dims[2];const k=v.match(/([\d.]+)\s*[kK]/);if(k)return +k[1]*1000;const p=v.match(/(\d+)p/i);if(p)return +p[1];return Infinity;};return list.sort((a,b)=>score(a)-score(b));
}
export function todayCode(){const parts=new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/Rome',day:'2-digit',month:'2-digit',year:'2-digit'}).formatToParts(new Date());return ['day','month','year'].map(k=>parts.find(p=>p.type===k).value).join('');}
export function titleParts(s){return [s.project,s.scene,s.filename||'DOGMA',s.appendDate?(s.dateMode==='today'?todayCode():s.date||todayCode()):''].map(safeName).filter(Boolean);}
export function prefix(s,f){return ['DOGMA/API',safeName(s.project),safeName(s.scene),titleParts(s).join('_')+'_'+f.short].filter(Boolean).join('/');}
export function migrateState(raw){
const s=copy(raw);s.schema=2;s.session ||= crypto.randomUUID();s.prompts ||= {image:s.prompt||'',video:''};s.mode ||= 'image';s.imageEdit ??= true;s.appendDate ??= false;s.date ||= todayCode();
const s=copy(raw);s.schema=3;s.session ||= crypto.randomUUID();s.prompts ||= {image:s.prompt||'',video:''};s.mode ||= 'image';s.imageEdit ??= true;s.appendDate ??= false;s.date ||= todayCode();
s.dateMode ||= raw.schema===1?'manual':'today';if(s.dateMode==='today')s.date=todayCode();
s.workspace ||= '';s.library ||= [];s.results ||= [];s.references ||= [];s.filters ||= {models:[],project:'*',scene:'*',kind:'all',workspace:'*'};s.density ??= 45;
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;}
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:legacyMask?'edit':'isolate',invert:false,flip:false,crop:false,resizeMpx:false,megapixels:1,expand:0,blur:0,fillHoles:true,targetWidth:0,targetHeight:0,source:'paint',prompt:'',segment:0,background:legacyMask?'#ff00ff':'#00ff00'};}
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';
return s;
}
export function plannedJobs(s){return families(s).flatMap(f=>{const m=s.models[f.key];if(!m?.enabled)return[];const n=Number(m.quantity);if(!Number.isInteger(n)||n<1||n>64)throw new Error('Quantity deve essere da 1 a 64.');return Array.from({length:n},(_,i)=>({family:f.key,index:i,kind:s.mode==='video'?'video':'image'}));});}
export function activeReferences(s){return s.references.filter(r=>r.enabled&&(!r.modes||r.modes.includes(s.mode))&&(s.mode==='video'||r.kind!=='video'));}
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){
if(!s.prompts[s.mode]?.trim())throw new Error('Scrivi un prompt.');
if(!plannedJobs(s).length)throw new Error('Attiva almeno un modello.');
@@ -42,6 +65,8 @@ export function validateState(s){
const limits={nano:14,gpt:16,flux:10,seedream:10},max=Math.min(...FAMILIES.filter(f=>s.models[f.key]?.enabled).map(f=>limits[f.key]));if(imgs.length>max)throw new Error(`I modelli attivi supportano fino a ${max} reference.`);
}else {
const m=s.models.seedance;
if(m.engine==='frames'&&imgs.length>2)throw new Error('Usa al massimo un First frame e un Last frame.');
if(m.engine==='frames'&&['first','last'].some(role=>imgs.filter(r=>r.role===role).length>1))throw new Error('Assegna un solo First frame e un solo Last frame.');
if(m.engine==='frames'&&!imgs.length)throw new Error('Aggiungi almeno un frame immagine.');
if(m.engine!=='frames'&&!refs.length)throw new Error('Aggiungi una reference immagine o video.');
const p=m.engine==='frames'?m.frames:m.parameters;
+1 -1
View File
@@ -1,5 +1,5 @@
{
"schema": 2,
"schema": 3,
"session": "",
"mode": "image",
"imageEdit": true,
File diff suppressed because one or more lines are too long
+9
View File
@@ -21,3 +21,12 @@
.dap-date-row input[type=date]{margin-left:auto;min-width:0;width:105px;border:0;background:transparent;color:#9a623f;font:9px Courier New,monospace;cursor:pointer}.dap-date-row input[type=date]:hover{color:var(--orange)}.dap-operation-note{flex-shrink:0;font:10px/1.4 Courier New,monospace;color:var(--orange);margin:8px 0 0;text-align:center}
.dap-field-step{width:10px;min-width:10px;height:16px;flex:none;border:0;padding:0;color:#999}.dap-field-step .dap-icon{width:9px;height:13px;stroke-width:1.4}.dap-field-step.next{transform:rotate(180deg)}.dap-field select{padding-right:0}.dap-field input[type=checkbox]{appearance:none;border:1px solid #454545;border-radius:50%;background:#000}.dap-field input[type=checkbox]:checked{border-color:var(--orange);background:var(--orange);box-shadow:inset 0 0 0 3px #000}.dap-field input[type=checkbox]:hover{border-color:var(--orange)}
/* 1.0.55: immediate shell, in-panel folders and live progress */
.dap-stop{border:1px solid #ef382e;background:#cf2922;color:white!important;border-radius:25px;padding:8px 22px;font-weight:bold!important;min-width:100px;cursor:pointer}.dap-stop:hover{background:#f34135;box-shadow:0 0 20px #ee302733}.dap-stop:disabled{opacity:.24;cursor:default}.dap-project{background:none;border:0;text-align:left;cursor:pointer;max-width:55%}.dap-project:hover{color:var(--orange)}
.dap-work>summary{display:flex;align-items:center;justify-content:space-between;cursor:pointer;padding:8px 0;border-bottom:1px solid #292018}.dap-work>summary:hover{color:var(--orange)}.dap-work>summary .dap-icon{width:12px;height:12px}.dap-work[open]>summary .dap-icon{transform:rotate(180deg)}.dap-work>div{padding-top:10px}.dap-video-choice{margin:0 0 25px}.dap-video-choice>button{background:#000;border:1px solid #333;border-radius:22px;color:#aaa;padding:9px 16px;margin-right:8px;font:11px Courier New,monospace}.dap-video-choice>button.active{border-color:var(--orange);color:var(--orange)}
.dap-views>button:first-child .dap-icon{width:40px;height:24px}.dap-card-tools .dap-icon-button:first-child .dap-icon{width:23px}
.dap-folder-modal{width:min(1000px,90vw);height:75vh;display:flex;flex-direction:column}.dap-folder-navigation,.dap-folder-footer{display:flex;gap:10px;flex-shrink:0;margin:10px 0}.dap-folder-navigation input{flex:1;min-width:0}.dap-folder-navigation input,.dap-folder-footer input{background:#111;color:#ccc;border:1px solid #444;border-radius:8px;padding:9px;font:12px Courier New,monospace}.dap-folder-list{flex:1;overflow:auto;min-height:0}.dap-folder-file{padding:10px 14px;color:#999;font:12px Courier New,monospace;border:1px solid transparent;border-radius:6px}.dap-folder-file.selected{background:#ff662622;border-color:var(--orange);color:#eee}.dap-folder-footer{flex-wrap:wrap}
.dap-progress-track{height:3px;background:#271308;overflow:hidden;border-radius:2px}.dap-progress-track>i{display:block;height:100%;width:0;background:#ff6626;box-shadow:0 0 7px #ff6626;transition:width .7s linear}.dap-total-progress{margin:0 0 12px;flex-shrink:0}.dap-total-progress>span{display:block;text-align:right;font:10px Courier New,monospace;color:#b47753;margin-top:8px}.dap-card-progress{position:absolute;bottom:0;left:0;right:0}.dap-progress-track.indeterminate>i{width:28%!important;animation:dap-progress 1.8s ease-in-out infinite}.dap-spinner{border:0;animation:none;width:38px;height:38px;position:relative}.dap-spinner>i{position:absolute;left:17px;top:17px;width:4px;height:4px;border-radius:50%;background:#ff742d;transform:rotate(calc(var(--i)*22.5deg)) translateY(-16px);box-shadow:0 0 6px #ff6626,0 0 12px #ff662666;opacity:0;animation:dap-light 1.25s linear infinite;animation-delay:calc(var(--i)*.078125s)}
@keyframes dap-light{0%{opacity:1}70%,100%{opacity:0}}@keyframes dap-progress{from{transform:translateX(-110%)}to{transform:translateX(470%)}}
.dap-generated{opacity:1;transition:opacity .2s}.dap-reference-preview[hidden],.dap-total-progress[hidden]{display:none}.dap-field select{min-width:35%;cursor:pointer}
+22 -15
View File
@@ -1,22 +1,23 @@
import { app } from '../../scripts/app.js';
import { api } from '../../scripts/api.js';
import { PlatformUI } from './dogma_api_ui.js?v=1.0.54';
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec } from './dogma_api_core.js?v=1.0.54';
import { PlatformUI } from './dogma_api_ui.js?v=1.0.55';
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.55';
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.54',ROOT);document.head.append(css);
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_api_platform.css?v=1.0.55',ROOT);document.head.append(css);
let opened=null,queueLock=false;
const cachedSchemas=fetch(new URL('dogma_api_schemas.json?v=1.0.55',ROOT)).then(r=>r.json()).catch(()=>({}));
class ComfyBridge {
constructor(node){this.node=node;this.preview=false;this.pricingNodes=new Map();}
get widget(){return this.node.widgets.find(w=>w.name==='config');}
load(){const s=JSON.parse(this.widget.value||'{}');if(!s.models)throw new Error('Apri DOGMA_API_PLATFORM_V2.json.');return migrateState(s);}
load(){const s=JSON.parse(this.widget.value||'{}');if(!s.models)throw new Error('Apri DOGMA_API_PLATFORM_V3.json.');return migrateState(s);}
async initialize(state){
const defaults=await (await fetch(new URL('dogma_api_defaults.json?v=1.0.54',ROOT))).json();
const [defaults,catalog,cached]=await Promise.all([(await fetch(new URL('dogma_api_defaults.json?v=1.0.55',ROOT))).json(),this.request('/catalog'),cachedSchemas]);
for(const [key,value] of Object.entries(defaults.models))state.models[key] ||= copy(value);
state.prompts.video ||= defaults.prompts.video;
this.catalog=await this.request('/catalog');
this.defs=await (await api.fetchApi('/object_info')).json();
if(state.workspace){try{await this.workspace(state.workspace);}catch{state.workspace='';}}
this.catalog=catalog;this.defs=cached;
const live=await Promise.allSettled(Object.keys(cached).map(async type=>{const r=await api.fetchApi('/object_info/'+encodeURIComponent(type));if(!r.ok)throw new Error(type);const d=await r.json();return [type,d[type]];}));
for(const r of live)if(r.status==='fulfilled'&&r.value[1])this.defs[r.value[0]]=r.value[1];
if(state.workspace){try{await this.workspace(state.workspace);}catch(e){this.workspaceError=e.message;}}
try{
const script=[...document.querySelectorAll('script[type=module][src]')].find(x=>x.src.includes('/assets/'));
const base=script?.src||new URL('/assets/index.js',location.href).href;
@@ -29,11 +30,12 @@ class ComfyBridge {
}
save(s){this.widget.value=JSON.stringify(s);this.node.setDirtyCanvas?.(true,true);clearTimeout(this.saveTimer);this.saveTimer=setTimeout(()=>{if(this.node.graph===app.graph)app.graph.change?.();},250);}
logo(){return new URL('dogma_api_logo.png',ROOT).href;}
view(file){if(file?.url)return file.url;const p=new URLSearchParams(typeof file==='string'?{filename:file,type:'input'}:{filename:file.filename,subfolder:file.subfolder||'',type:file.type||'output'});return api.apiURL('/view?'+p);}
view(file){if(file?.workspace&&file?.relative)return api.apiURL('/dogma/api/v2/workspace-media?'+new URLSearchParams({workspace:file.workspace,relative:file.relative}));if(file?.url)return file.url;return api.apiURL('/view?'+new URLSearchParams(viewParameters(file)));}
async request(path,body){const headers={};if(this.catalog?.access?.token)headers['X-Dogma-Access']=this.catalog.access.token;if(body!==undefined)headers['Content-Type']='application/json';const response=await api.fetchApi('/dogma/api/v2'+path,{method:body===undefined?'GET':'POST',headers,...(body!==undefined?{body:JSON.stringify(body)}:{})});if(!response.ok)throw new Error((await response.text()).slice(0,800));return response.json();}
async upload(file){const body=new FormData();body.append('image',file,file.name);body.append('type','input');body.append('subfolder','DOGMA_API');body.append('overwrite','false');const r=await api.fetchApi('/upload/image',{method:'POST',body});if(!r.ok)throw new Error('Caricamento non riuscito.');const d=await r.json();return {file:[d.subfolder,d.name].filter(Boolean).join('/'),kind:file.type.startsWith('video/')?'video':'image'};}
async workspace(path){return this.request('/workspace',{path});}
async chooseFolder(path){if(this.catalog?.access?.open_folder)return this.request('/choose-folder',{path});return {browse:true};}
async chooseFolder(){return {browse:true};}
async mkdir(path,name){return this.request('/mkdir',{path,name});}
async folders(path){return this.request('/folders?'+new URLSearchParams({path:path||''}));}
async library(){return (await this.request('/library')).records;}
async previewReference(ref,settings){return this.request('/reference-preview',{file:ref.file,settings});}
@@ -43,6 +45,8 @@ class ComfyBridge {
try{await this.billing.fetchBalance();const raw=this.billing.balance,b=raw&&'value' in raw?raw.value:raw;const amount=b?.effectiveBalanceMicros??b?.amountMicros;if(!Number.isFinite(amount))return {text:'ACCEDI A COMFY',title:'Accedi all’account da Comfy per vedere i crediti.'};return {text:this.formatCredits({cents:amount,locale:'it-IT',numberOptions:{minimumFractionDigits:0,maximumFractionDigits:2}})+' CREDITS LEFT',title:'Saldo dello stesso account e workspace di Comfy'};}catch{return {text:'CREDITS —',title:'Saldo temporaneamente non disponibile. Clicca per aggiornare.'};}
}
inputSpec(state,f,key){const m=state.models[f.key],frames=m.engine==='frames';return inputSpec(this.defs?.[frames?'ByteDance2FirstLastFrameNode':f.type],frames?m.frames:m.parameters,key);}
parameterSpecs(state,f){const m=state.models[f.key],frames=m.engine==='frames';return parameterSpecs(this.defs?.[frames?'ByteDance2FirstLastFrameNode':f.type],frames?m.frames:m.parameters);}
changeModel(state,f){const m=state.models[f.key],frames=m.engine==='frames',key=frames?'frames':'parameters';m[key]=modelValues(this.defs?.[frames?'ByteDance2FirstLastFrameNode':f.type],m[key]);}
price(state,f){
if(!this.nativePricing||!this.defs)return '';
const m=state.models[f.key],frames=f.key==='seedance'&&m.engine==='frames',type=frames?'ByteDance2FirstLastFrameNode':f.type,def=this.defs[type];if(!def)return '';
@@ -51,13 +55,16 @@ class ComfyBridge {
const values=frames?m.frames:m.parameters;n.widgets=Object.entries(values).map(([name,value])=>({name,value}));
n.inputs=[];
if(f.key==='nano'&&images.length)n.inputs.push({name:'images',link:1});
else if(f.key==='seedance'&&frames){for(const r of images)n.inputs.push({name:r.role==='last'?'last_frame':'first_frame',link:1});}
else if(f.key==='seedance'){images.forEach((r,i)=>n.inputs.push({name:`model.reference_images.image_${i+1}`,link:1}));videos.forEach((r,i)=>n.inputs.push({name:`model.reference_videos.video_${i+1}`,link:1}));}
else images.forEach((r,i)=>n.inputs.push({name:`${f.key==='flux'?'':'model.'}images.image_${i+1}`,link:1}));
try{return this.nativePricing.getNodeDisplayPrice(n,new Map(Object.entries(values)))||'';}catch{return '';}
}
async check(state,compiled){
this.defs=await (await api.fetchApi('/object_info')).json();const missing=[...new Set(Object.values(compiled.output).map(n=>n.class_type))].filter(type=>!this.defs[type]);if(missing.length)throw new Error('Nodi mancanti: '+missing.join(', '));
for(const ref of activeReferences(state))for(const file of [ref.file,ref.process?.maskFile].filter(Boolean)){const r=await api.fetchApi('/view?'+new URLSearchParams({filename:file,type:'input'}),{method:'HEAD'});if(!r.ok)throw new Error('Reference assente: '+file+'. Ricaricala dal pannello.');}
const types=[...new Set(Object.values(compiled.output).map(n=>n.class_type))];
const available=await Promise.all(types.map(async type=>{const r=await api.fetchApi('/object_info/'+encodeURIComponent(type));return r.ok&&(await r.json())[type]?type:null;}));
const missing=types.filter(t=>!available.includes(t));if(missing.length)throw new Error('Nodi mancanti: '+missing.join(', '));
await Promise.all(activeReferences(state).flatMap(ref=>[ref.file,ref.process?.maskFile].filter(Boolean)).map(async file=>{const r=await fetch(this.view(file),{method:'HEAD'});if(!r.ok)throw new Error('Reference assente: '+file+'. Ricaricala dal pannello.');}));
}
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.');
@@ -69,9 +76,9 @@ class ComfyBridge {
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;}
}
subscribe(handler){const controller=new AbortController();for(const name of ['execution_start','executing','executed','execution_success','execution_error','execution_interrupted','progress'])api.addEventListener(name,e=>handler(name,e.detail),{signal:controller.signal});return ()=>controller.abort();}
subscribe(handler){const controller=new AbortController();for(const name of ['execution_start','executing','executed','execution_success','execution_error','execution_interrupted','progress','progress_state'])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();}
async cancel(id){if(typeof api.cancelJob==='function')return api.cancelJob(id);return api.interrupt(id);}
async cancel(id){const r=await api.fetchApi('/jobs/'+encodeURIComponent(id)+'/cancel',{method:'POST'});if(r.ok)return r.json();if(r.status!==404)throw new Error('Interruzione non riuscita.');await api.fetchApi('/queue',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({delete:[id]})});const stopped=await api.fetchApi('/interrupt',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt_id:id})});if(!stopped.ok)throw new Error('Interruzione non riuscita.');}
download(state){this.save(state);const url=URL.createObjectURL(new Blob([JSON.stringify(app.graph.serialize(),null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='DOGMA_API_PLATFORM_SESSION.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
close(){opened=null;}
}
+3 -3
View File
@@ -1,5 +1,5 @@
import {copy} from './dogma_api_core.js?v=1.0.54';
import {icon} from './dogma_api_icons.js?v=1.0.54';
import {copy} from './dogma_api_core.js?v=1.0.55';
import {icon} from './dogma_api_icons.js?v=1.0.55';
export async function referenceEditor(ui,ref){
const make=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
@@ -43,7 +43,7 @@ export async function referenceEditor(ui,ref){
const preview=make('img','','dap-reference-preview');preview.alt='Anteprima della reference preparata';preview.hidden=!previewFile;if(previewFile)preview.src=ui.bridge.view(previewFile);right.append(preview);
async function uploadMask(){if(!maskChanged)return;const out=make('canvas');out.width=mask.width;out.height=mask.height;const ctx=out.getContext('2d'),pixels=mc.getImageData(0,0,mask.width,mask.height);for(let i=0;i<pixels.data.length;i+=4){const v=pixels.data[i+3];pixels.data[i]=pixels.data[i+1]=pixels.data[i+2]=v;pixels.data[i+3]=255;}ctx.putImageData(pixels,0,0);const blob=await new Promise(resolve=>out.toBlob(resolve,'image/png'));if(!blob)throw new Error('Maschera non esportata.');const result=await ui.bridge.upload(new File([blob],'DOGMA_mask_'+Date.now()+'.png',{type:'image/png'}));draft.maskFile=result.file;maskChanged=false;}
const footer=make('div','','dap-reference-footer');
const previewButton=button('Anteprima',async()=>{previewButton.disabled=true;try{await uploadMask();const result=await ui.bridge.previewReference(ref,draft);if(!box.isConnected)return;previewFile=result.file;preview.src=ui.bridge.view(previewFile);preview.hidden=false;status.textContent=`${result.width} × ${result.height} · Anteprima aggiornata`;}catch(e){status.textContent=e.message;}finally{previewButton.disabled=false;}});
const previewButton=button('Anteprima',async()=>{previewButton.disabled=true;try{await uploadMask();const result=await ui.bridge.previewReference(ref,draft);if(!box.isConnected)return;previewFile=result.file;preview.src=ui.bridge.view(previewFile);await preview.decode();preview.hidden=false;status.textContent=`${result.width} × ${result.height} · Anteprima aggiornata`;}catch(e){preview.hidden=true;status.textContent='Anteprima non disponibile: '+e.message;}finally{previewButton.disabled=false;}});
footer.append(button('Sostituisci file',()=>{box.close();ui.pickReferences(ref);}),previewButton,button('Applica',async()=>{try{await uploadMask();ref.process=copy(draft);ref.process.enabled=true;ref.processedPreview=previewFile;ui.save();ui.renderRefs();ui.refreshPrices();box.close();ui.note('Preparazione reference salvata.');}catch(e){status.textContent=e.message;}},'dap-primary'));
box.append(footer);setTool('brush');draw();
}
File diff suppressed because one or more lines are too long
+73 -36
View File
@@ -1,7 +1,7 @@
import {ALL_FAMILIES,copy,families,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences} from './dogma_api_core.js?v=1.0.54';
import {icon} from './dogma_api_icons.js?v=1.0.54';
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.54';
import {referenceEditor} from './dogma_api_reference_editor.js?v=1.0.54';
import {ALL_FAMILIES,copy,families,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences,visibleReferences,choicesFor,sortedChoices,safeName} from './dogma_api_core.js?v=1.0.55';
import {icon} from './dogma_api_icons.js?v=1.0.55';
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.55';
import {referenceEditor} from './dogma_api_reference_editor.js?v=1.0.55';
export const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
export const btn=(text,fn,cls='',aria=text)=>{const b=el('button',text,cls);b.type='button';b.onclick=fn;b.setAttribute('aria-label',aria);b.title=aria;return b;};
@@ -13,14 +13,17 @@ export class PlatformUI {
constructor(bridge){this.bridge=bridge;this.state=bridge.load();this.library=[];this.selection=[];this.cards=new Map();this.urls=new Set();this.closed=false;this.busy=false;}
save(){if(!this.closed)this.bridge.save(this.state);}
async open(){
await this.bridge.initialize?.(this.state);this.state=migrateState(this.state);
this.ready=false;
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]);});
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));
await Promise.allSettled([this.recover(),this.refreshLibrary(),this.refreshCredits()]);
this.note('Apertura · Collegamento a Comfy…');
await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
try{await this.bridge.initialize?.(this.state);if(this.closed)return;this.ready=true;this.renderControls();this.updateHeader();this.refreshPrices();this.note(this.bridge.preview?'ANTEPRIMA · Nessuna richiesta API':'Pronto.');}catch(e){this.note('Collegamento non riuscito: '+e.message,true);}
Promise.allSettled([this.recover(),this.refreshLibrary(),this.refreshCredits()]);
this.timer=setInterval(()=>{this.updateCards();this.refreshPrices();if(this.state.results.some(r=>!terminal.has(r.status)))this.recover();},1800);
this.creditTimer=setInterval(()=>this.refreshCredits(),30000);
}
@@ -30,30 +33,31 @@ export class PlatformUI {
const header=el('header','','dap-header'),brand=el('div','','dap-brand'),logo=el('img');logo.src=this.bridge.logo();logo.alt='DOGMA';brand.append(logo,el('span','API Platform'));
const actions=el('div','','dap-actions');this.credit=btn('CREDITS —',()=>this.refreshCredits(),'dap-credit','Aggiorna crediti');
this.runButton=btn('',()=>this.run(),'dap-run','Avvia generazioni in parallelo');this.runLabel=el('span','Run');this.runButton.append(this.runLabel,icon('play'));
actions.append(this.credit,ib('download','Salva sessione e workflow',()=>this.bridge.download(this.state)),ib('close','Torna a Comfy',()=>this.close()),this.runButton);header.append(brand,actions);
this.stopButton=btn('■ Stop',()=>this.stop(),'dap-stop','Ferma le generazioni DOGMA');this.stopButton.disabled=true;
actions.append(this.stopButton,this.credit,ib('download','Salva sessione e workflow',()=>this.bridge.download(this.state)),ib('close','Torna a Comfy',()=>this.close()),this.runButton);header.append(brand,actions);
const layout=el('div','','dap-layout');this.side=el('aside','','dap-side');const tabs=el('nav','','dap-tabs');
this.imageTab=btn('',()=>this.switchMode('image'),'','Image');this.imageTab.append(icon('image'),el('span','Image'));this.videoTab=btn('',()=>this.switchMode('video'),'','Video');this.videoTab.append(icon('video'),el('span','Video'));tabs.append(this.imageTab,this.videoTab);
this.editRow=el('div','','dap-edit-mode');this.editRow.append(this.toggle('Image Edit',this.state.imageEdit,v=>{this.state.imageEdit=v;this.save();}),el('span','Image Edit'),el('small','Image 1 → compare'));
this.controls=el('div','','dap-controls');this.side.append(tabs,this.editRow,this.controls);
const main=el('main','','dap-main'),toolbar=el('div','','dap-toolbar');this.context=el('div','','dap-project');
const main=el('main','','dap-main'),toolbar=el('div','','dap-toolbar');this.context=btn('',()=>this.folderBrowser(false),'dap-project','Apri cartella di lavoro');
const views=el('div','','dap-views');this.ab=ib('compare','Confronta due risultati',()=>this.compare());
const slider=this.slider=el('input');slider.type='range';slider.min='0';slider.max='100';slider.step='any';slider.value=String(this.state.density);slider.setAttribute('aria-label','Dimensione delle immagini');
slider.oninput=()=>{this.state.density=Number(slider.value);this.applyDensity();this.save();};
views.append(this.ab,ib('single','Una immagine grande',()=>{slider.value='0';slider.oninput();}),slider,ib('grid','Griglia compatta',()=>{slider.value='100';slider.oninput();}));toolbar.append(this.context,views);
this.filters=el('div','','dap-filters');this.notice=el('div','','dap-notice');this.notice.setAttribute('role','status');
this.galleryViewport=el('div','','dap-gallery-viewport');this.gallery=el('div','','dap-gallery');this.galleryViewport.append(this.gallery);
main.append(toolbar,this.filters,this.notice,this.galleryViewport);layout.append(this.side,main);this.root.append(header,layout);
this.totalProgress=el('div','','dap-total-progress');this.totalBar=el('div','','dap-progress-track');this.totalFill=el('i');this.totalBar.append(this.totalFill);this.totalText=el('span');this.totalProgress.append(this.totalBar,this.totalText);this.totalProgress.hidden=true;main.append(toolbar,this.filters,this.totalProgress,this.notice,this.galleryViewport);layout.append(this.side,main);this.root.append(header,layout);
this.renderControls();this.renderFilters();this.renderGallery();this.updateHeader();this.applyDensity();
this.resize=new ResizeObserver(()=>this.applyDensity());this.resize.observe(this.galleryViewport);this.root.addEventListener('close',()=>this.resize.disconnect(),{once:true});
this.note(this.bridge.preview?'ANTEPRIMA · Immagini dal tuo design · Nessuna richiesta API':'Reference, parametri e cartella pronti.');
}
applyDensity(){if(!this.gallery)return;const columns=1+3*Number(this.state.density)/100,width=(this.galleryViewport.clientWidth||1400)/columns;this.gallery.style.setProperty('--card-min',Math.max(170,width-18)+'px');this.slider.title=`Dimensione galleria / ${Math.round(width)} px`;}
updateHeader(){const s=this.state;this.context.textContent=[s.project,s.scene].filter(Boolean).join(' / ')||'Tutti gli output';this.imageTab.classList.toggle('active',s.mode==='image');this.videoTab.classList.toggle('active',s.mode==='video');this.editRow.hidden=s.mode==='video';let n=0;try{n=plannedJobs(s).length;}catch{}this.runLabel.textContent=this.busy?'Invio…':`Run${n?' / '+n:''}`;this.runButton.disabled=this.busy||!n;this.runButton.title=`${n} generazioni API indipendenti, in parallelo`;}
updateHeader(){const s=this.state;this.context.textContent=[s.workspace||this.bridge.catalog?.access?.output_root||'Comfy output / DOGMA / API',safeName(s.project),safeName(s.scene)].filter(Boolean).join(' / ');this.context.title=this.context.textContent;this.imageTab.classList.toggle('active',s.mode==='image');this.videoTab.classList.toggle('active',s.mode==='video');this.editRow.hidden=s.mode==='video';let n=0;try{n=plannedJobs(s).length;}catch{}this.runLabel.textContent=this.busy?'Invio…':`Run${n?' / '+n:''}`;this.runButton.disabled=this.busy||!n||!this.ready;this.updateProgress();this.runButton.title=`${n} generazioni API indipendenti, in parallelo`;}
switchMode(mode){this.state.mode=mode;this.save();this.renderControls();this.updateHeader();this.refreshPrices();}
toggle(label,checked,onchange){const b=btn('',()=>{checked=!checked;b.classList.toggle('on',checked);b.setAttribute('aria-checked',String(checked));onchange(checked);},'dap-toggle'+(checked?' on':''),label);b.setAttribute('role','switch');b.setAttribute('aria-checked',String(checked));const knob=el('span','','dap-toggle-knob');knob.append(icon('lines'));b.append(knob);return b;}
field(parent,name,value,onchange,opts={}){
const row=el('label','','dap-field');row.append(el('span',name));let input;
if(opts.choices){input=el('select');for(const choice of [...new Set([String(value),...opts.choices])]){const o=el('option',choice);o.value=choice;input.append(o);}input.value=String(value);row.classList.add('has-select');}
if(opts.choices){input=el('select');for(const choice of [...new Set([...opts.choices.map(String),...(!opts.choices.map(String).includes(String(value))?[String(value)]:[])])]){const o=el('option',choice);o.value=choice;input.append(o);}input.value=String(value);row.classList.add('has-select');}
else{input=el('input');input.type=opts.type||'text';if(input.type==='checkbox')input.checked=!!value;else input.value=String(value??'');}
input.setAttribute('aria-label',name);if(opts.min!==undefined)input.min=String(opts.min);if(opts.max!==undefined)input.max=String(opts.max);if(opts.step!==undefined)input.step=String(opts.step);if(opts.placeholder)input.placeholder=opts.placeholder;if(opts.readonly)input.readOnly=true;
input.onchange=()=>onchange(input.type==='checkbox'?input.checked:input.value);row.append(input);
@@ -71,7 +75,7 @@ export class PlatformUI {
const prompt=el('section','','dap-section dap-prompt');prompt.append(el('div','PROMPT','dap-label'));const wrap=el('div','','dap-prompt-wrap'),area=el('textarea');area.value=s.prompts[s.mode]||'';area.setAttribute('aria-label','Prompt');area.placeholder='Scrivi il prompt…';area.oninput=()=>{s.prompts[s.mode]=area.value;this.save();};
const resize=el('div','','dap-resize-handle');resize.title='Trascina per ingrandire il prompt';let start=null;
resize.onpointerdown=e=>{e.preventDefault();start={y:e.clientY,height:area.offsetHeight};resize.setPointerCapture(e.pointerId);};resize.onpointermove=e=>{if(start)area.style.height=Math.max(90,start.height+e.clientY-start.y)+'px';};resize.onpointerup=resize.onpointercancel=()=>start=null;wrap.append(area,resize);prompt.append(wrap);
const work=el('section','','dap-section dap-work');work.append(el('div','FILENAME / WORKSPACE','dap-label'));
const workSection=el('details','','dap-section dap-work');workSection.open=!!s.workExpanded;workSection.ontoggle=()=>{s.workExpanded=workSection.open;this.save();};const workTitle=el('summary','FILENAME / WORKSPACE','dap-label');workTitle.append(icon('chevron'));const work=el('div');workSection.append(workTitle,work);
this.field(work,'FILENAME',s.filename,v=>{s.filename=v;this.save();this.namePreview.textContent=this.filenamePreview();},{placeholder:'DOGMA'});
this.field(work,'PROJECT',s.project,v=>{s.project=v;this.save();this.updateHeader();this.namePreview.textContent=this.filenamePreview();},{placeholder:'Facoltativo'});
this.field(work,'SCENE',s.scene,v=>{s.scene=v;this.save();this.updateHeader();this.namePreview.textContent=this.filenamePreview();},{placeholder:'Facoltativo'});
@@ -79,12 +83,13 @@ export class PlatformUI {
const choose=ib('folder','Scegli cartella di lavoro',()=>this.chooseWorkspace(),'dap-workspace-button');choose.append(el('span',s.workspace||'Scegli cartella di lavoro'));work.append(choose);
this.namePreview=el('div',this.filenamePreview(),'dap-filename-preview');work.append(this.namePreview);
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));
c.append(refs,prompt,work,models);
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);}
c.append(refs,prompt,workSection,models);
}
filenamePreview(){return [...titleParts(this.state),'MODEL',this.state.mode==='video'?'00001.mp4':'00001.png'].filter(Boolean).join('_');}
renderRefs(){
if(!this.refs)return;this.refs.replaceChildren();
const visible=this.state.references.filter(r=>!r.modes||r.modes.includes(this.state.mode));
const visible=visibleReferences(this.state);
visible.forEach((r,i)=>{
const tile=el('article','','dap-ref');tile.classList.toggle('disabled',!r.enabled);tile.dataset.ref=String(i);
const media=el(r.kind==='video'?'video':'img');media.src=r.processedPreview?this.bridge.view(r.processedPreview):r.preview||this.bridge.view(r.file);media.draggable=false;if(r.kind==='video'){media.muted=true;media.preload='metadata';media.onpointerenter=()=>media.play().catch(()=>{});media.onpointerleave=()=>media.pause();}else media.alt=`Image ${i+1}`;
@@ -97,15 +102,15 @@ export class PlatformUI {
tools.append(ib('close',`Rimuovi reference ${i+1}`,()=>{this.state.references.splice(this.state.references.indexOf(r),1);this.save();this.renderRefs();this.refreshPrices();}));
tile.append(media,el('span',`${String(i+1).padStart(2,'0')} / ${r.kind==='video'?'VIDEO':'IMAGE'}`,'dap-ref-order'),tools);
if(r.process?.enabled)tile.append(el('span','EDIT','dap-ref-edited'));
if(this.state.mode==='video'&&r.kind==='image'){
const select=el('select','','dap-ref-role');select.setAttribute('aria-label',`Ruolo reference ${i+1}`);for(const [key,text] of [['reference','Reference'],['first','First frame'],['last','Last frame']]){const o=el('option',text);o.value=key;select.append(o);}select.value=r.role||'reference';select.onchange=()=>{r.role=select.value;this.save();};tile.append(select);
if(this.state.mode==='video'&&this.state.models.seedance.engine==='frames'&&r.kind==='image'){
const select=el('select','','dap-ref-role');select.setAttribute('aria-label',`Ruolo reference ${i+1}`);for(const [key,text] of [['first','First frame'],['last','Last frame']]){const o=el('option',text);o.value=key;select.append(o);}select.value=r.role||'reference';select.onchange=()=>{r.role=select.value;this.save();};tile.append(select);
}
this.refs.append(tile);
});
const add=ib('plus','Aggiungi immagini o video',()=>this.pickReferences(),'dap-add');add.append(el('span','Immagini / Video'));this.refs.append(add);
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');add.append(el('span',mixed?'Immagini / Video':frames?'First / Last frame':'Immagini'));if(!frames||visible.length<2)this.refs.append(add);
}
pickReferences(replace=null){const i=el('input');i.type='file';i.accept='image/*,video/*';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 uploaded=await this.bridge.upload(file);if(this.closed)return;const r={...uploaded,enabled:true,modes:[this.state.mode],role:'reference',process:{enabled:false,mask:false,maskMode:'isolate',source:'paint',flip:false,invert:false,crop:false,fillHoles:true,expand:0,blur:0,targetWidth:0,targetHeight:0,background:'#00ff00'}};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);}}
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:'isolate',source:'paint',flip:false,invert:false,crop:false,fillHoles:true,expand:0,blur:0,targetWidth:0,targetHeight:0,background:'#00ff00'}};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);}}
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);
@@ -115,20 +120,22 @@ export class PlatformUI {
const body=el('div','','dap-model-body');
this.field(body,'QUANTITY',m.quantity,v=>{m.quantity=Number(v);this.save();this.updateHeader();},{type:'number',min:1,max:64});
body.append(el('div','Richieste in parallelo · Seed diversi','dap-field-hint'));
if(f.key==='seedance')this.field(body,'WORKFLOW',m.engine,v=>{m.engine=v;this.save();wrap.replaceWith(this.model(f));this.refreshPrices();},{choices:['reference','frames']});
const values=m.engine==='frames'?m.frames:m.parameters;
for(const [key,value] of Object.entries(values)){
const nativeSpecs=this.bridge.parameterSpecs?.(this.state,f);const entries=nativeSpecs&&Object.keys(nativeSpecs).length?Object.keys(nativeSpecs).map(key=>[key,values[key]??nativeSpecs[key][1]?.default??choicesFor(nativeSpecs[key])?.[0]??'']):Object.entries(values);
for(const [key,value] of entries){
if(['prompt','model.prompt','system_prompt','seed','model.seed','n'].includes(key)||key.startsWith('control_after_generate')||key.endsWith('asset_id'))continue;
const opts={};if(enumValues[key])opts.choices=enumValues[key];
if(key==='model'){if(f.key==='nano')opts.choices=['gemini-3-pro-image-preview','Nano Banana 2 (Gemini 3.1 Flash Image)'];else opts.readonly=true;}
if(key==='resolution'&&f.key==='flux')opts.choices=['0.75K','1K','1.5K','2K','4K'];
if(typeof value==='boolean')opts.type='checkbox';if(typeof value==='number'){opts.type='number';opts.min=key==='model.duration'?4:0;opts.max=key==='model.duration'?30:8594;}
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(spec[0]==='COMBO')opts.choices=info.options;if(info.min!==undefined)opts.min=info.min;if(info.max!==undefined)opts.max=info.max;if(info.step!==undefined)opts.step=info.step;}
this.field(body,displayName(key),value,v=>{values[key]=typeof value==='boolean'?v:typeof value==='number'?Number(v):v;this.save();this.refreshPrices();},opts);
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);
}
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','Reference: genera, modifica o estende un video. Frames: usa i ruoli First / Last delle reference. In Edit la durata segue il video sorgente.','dap-field-hint'));
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'));
details.append(body);row.append(toggle,details);wrap.append(row);return wrap;
}
async refreshCredits(){if(this.creditBusy||this.closed)return;this.creditBusy=true;try{const result=await this.bridge.credits();if(!this.closed){this.credit.textContent=result.text;this.credit.title=result.title;}}catch{}finally{this.creditBusy=false;}}
@@ -163,30 +170,58 @@ export class PlatformUI {
const select=ib('compare','Seleziona per confronto A/B',()=>{const at=this.selection.findIndex(x=>x.id===item.id);if(at>=0){this.selection.splice(at,1);select.classList.remove('selected');}else if(this.selection.length<2){this.selection.push(item);select.classList.add('selected');}this.ab.classList.toggle('active',this.selection.length===2);this.note(`${this.selection.length}/2 risultati selezionati per A/B.`);});
tools.append(select,ib('plus','Usa come reference',()=>this.reuse(file,job.kind)),ib('download','Scarica file',()=>this.downloadImage(file)));card.append(tools);
if(job.study)card.append(el('span','DESIGN REFERENCE','dap-study'));
}else{card.classList.add('pending');card.append(el('div','','dap-spinner'),el('span','','dap-job-state'));}
}else{card.classList.add('pending');const spinner=el('div','','dap-spinner');for(let i=0;i<16;i++){const dot=el('i');dot.style.setProperty('--i',i);spinner.append(dot);}const track=el('div','','dap-progress-track dap-card-progress');track.append(el('i'));card.append(spinner,el('span','','dap-job-state'),track);}
const footer=el('footer','','dap-card-footer');footer.append(el('span',title+(job.index!==undefined?' / '+(job.index+1):'')),el('span','','dap-elapsed'));card.append(footer);
const tags=[job.project,job.scene].filter(Boolean);if(tags.length)card.append(el('div',tags.join(' / '),'dap-card-tags'));
if(job.warning||job.error)card.append(el('p',job.warning||job.error,'dap-card-error'));
if(!this.cards.has(job.id))this.cards.set(job.id,[]);this.cards.get(job.id).push(card);return card;
}
updateCards(){for(const job of this.allResults())for(const card of this.cards.get(job.id)||[]){const status=card.querySelector('.dap-job-state');if(status)status.textContent=({submitting:'Invio',queued:'In attesa di Comfy',running:'Generazione API',failed:'Errore',cancelled:'Interrotta'})[job.status]||job.status;card.classList.toggle('stopped',terminal.has(job.status));const elapsed=card.querySelector('.dap-elapsed');elapsed.textContent=job.study?'LAYOUT':job.started?Math.floor(((job.finished||Date.now())-job.started)/1000)+'s':'';if(job.error&&!card.querySelector('.dap-card-error'))card.append(el('p',job.error,'dap-card-error'));}}
updateCards(){this.updateProgress();for(const job of this.allResults())for(const card of this.cards.get(job.id)||[]){const bar=card.querySelector('.dap-card-progress>i');if(bar){const p=this.jobProgress(job);bar.style.width=p.percent+'%';bar.parentElement.classList.toggle('indeterminate',p.indeterminate);bar.parentElement.title=p.label;}const status=card.querySelector('.dap-job-state');if(status)status.textContent=({submitting:'Invio',queued:'In attesa di Comfy',running:'Generazione API',failed:'Errore',cancelled:'Interrotta'})[job.status]||job.status;card.classList.toggle('stopped',terminal.has(job.status));const elapsed=card.querySelector('.dap-elapsed');elapsed.textContent=job.study?'LAYOUT':job.started?Math.floor(((job.finished||Date.now())-job.started)/1000)+'s':'';if(job.error&&!card.querySelector('.dap-card-error'))card.append(el('p',job.error,'dap-card-error'));}}
modalBox(title,cls=''){
this.modal?.close();const dialog=this.modal=el('dialog','','dap-modal '+cls);dialog.setAttribute('aria-label',title);const header=el('header');header.append(el('span',title),ib('close','Chiudi',()=>dialog.close()));dialog.append(header);this.root.append(dialog);
let down=false;dialog.addEventListener('pointerdown',e=>down=e.target===dialog);dialog.addEventListener('click',e=>{if(down&&e.target===dialog)dialog.close();down=false;});
dialog.addEventListener('cancel',e=>e.stopPropagation());dialog.addEventListener('keydown',e=>{if(e.key==='Escape'){e.preventDefault();e.stopPropagation();dialog.close();}});dialog.addEventListener('close',()=>{dialog.remove();if(this.modal===dialog)this.modal=null;});dialog.tabIndex=-1;dialog.showModal();dialog.focus({preventScroll:true});return dialog;
}
compare(){if(this.selection.length!==2){this.note('Seleziona due immagini con il bottone A/B sulle miniature.');return;}if(this.selection.some(x=>x.job.kind==='video')){this.note('Il confronto A/B è disponibile per le immagini.');return;}openViewer(this,this.selection[0],this.selection[1]);}
async openOutput(job,index){try{await this.bridge.openOutput(job.id,index);}catch(e){this.note(e.message,true);if(this.modal){let note=this.modal.querySelector('.dap-operation-note');if(!note){note=el('p','','dap-operation-note');this.modal.append(note);}note.textContent=e.message;}}}
async openOutput(job,index){try{const target=await this.bridge.openOutput(job.id,index);await this.folderBrowser(false,target.path,target.filename);}catch(e){this.note(e.message,true);if(this.modal)this.modal.append(el('p',e.message,'dap-operation-note'));}}
async downloadImage(file){try{const r=await fetch(this.bridge.view(file));if(!r.ok)throw new Error('File non disponibile.');const url=URL.createObjectURL(await r.blob());this.urls.add(url);const a=el('a');a.href=url;a.download=file.filename||'DOGMA_output';a.click();}catch(e){this.note(e.message,true);}}
async reuse(file,kind){try{const r=await fetch(this.bridge.view(file));if(!r.ok)throw new Error('File non disponibile.');const blob=await r.blob();await this.addReferences([new File([blob],file.filename||'DOGMA_reference.png',{type:blob.type|| (kind==='video'?'video/mp4':'image/png')})]);}catch(e){this.note(e.message,true);}}
async chooseWorkspace(){
try{const chosen=await this.bridge.chooseFolder(this.state.workspace);if(chosen.cancelled)return;if(chosen.path){this.state.workspace=chosen.path;this.save();this.renderControls();this.note('Cartella di lavoro selezionata.');return;}if(chosen.browse)await this.folderBrowser();}catch(e){this.note(e.message,true);}
async chooseWorkspace(){return this.folderBrowser(true);}
async folderBrowser(choose=true,initial=null,selected=''){
const box=this.modalBox(choose?'SCEGLI CARTELLA DI LAVORO':'CARTELLA / FILE','dap-folder-modal'),bar=el('div','','dap-folder-navigation'),address=el('input'),list=el('div','','dap-folder-list'),footer=el('div','','dap-folder-footer'),error=el('p','','dap-operation-note');address.setAttribute('aria-label','Percorso cartella');bar.append(address,btn('Apri',()=>render(address.value),'dap-outline'));box.append(bar,list,error,footer);
const render=async path=>{list.replaceChildren(el('p','Caricamento cartella…'));error.textContent='';try{const data=await this.bridge.folders(path);if(!box.isConnected)return;address.value=data.path;list.replaceChildren();footer.replaceChildren();
if(data.parent)list.append(btn('↑ Cartella superiore',()=>render(data.parent),'dap-outline'));
for(const root of data.roots||[]){const b=ib('folder',root.name,()=>render(root.path));b.append(el('span',root.name));list.append(b);}
for(const dir of data.directories){const b=ib('folder',dir.name,()=>render(dir.path));b.append(el('span',dir.name));list.append(b);}
for(const file of data.files||[]){const row=el('div',file.name,'dap-folder-file'+(file.name===selected?' selected':''));if(file.name===selected)row.setAttribute('aria-current','true');list.append(row);}
const name=el('input');name.placeholder='Nome nuova cartella';name.setAttribute('aria-label','Nome nuova cartella');footer.append(name,btn('Crea cartella',async()=>{try{const d=await this.bridge.mkdir(data.path,name.value);await render(d.path);}catch(e){error.textContent=e.message;}},'dap-outline'));
if(choose)footer.append(btn('Usa questa cartella',async()=>{try{const result=await this.bridge.workspace(data.path);this.state.workspace=result.path;for(const record of result.records||[]){const existing=this.state.results.find(j=>j.id===record.id);if(existing)Object.assign(existing,record);}this.library=[...this.library.filter(r=>!(result.records||[]).some(x=>x.id===r.id)),...(result.records||[])];this.save();this.renderFilters();this.renderGallery();box.close();this.renderControls();this.updateHeader();this.note('Cartella di lavoro selezionata.');}catch(e){error.textContent=e.message;}},'dap-primary'));
list.querySelector('[aria-current]')?.scrollIntoView({block:'center'});
}catch(e){list.replaceChildren();error.textContent=e.message;}};address.onkeydown=e=>{if(e.key==='Enter')render(address.value);};await render(initial??this.state.workspace);
}
async folderBrowser(){const box=this.modalBox('CARTELLA DI LAVORO'),list=el('div','','dap-folder-list');box.append(list);const render=async path=>{try{const data=await this.bridge.folders(path);list.replaceChildren(el('div',data.path,'dap-folder-path'));if(data.parent)list.append(btn('↑ Cartella superiore',()=>render(data.parent),'dap-outline'));for(const dir of data.directories){const b=ib('folder',dir.name,()=>render(dir.path));b.append(el('span',dir.name));list.append(b);}list.append(btn('Usa questa cartella',async()=>{try{const result=await this.bridge.workspace(data.path);this.state.workspace=result.path;this.save();box.close();this.renderControls();}catch(e){this.note(e.message,true);}},'dap-outline'));}catch(e){list.replaceChildren(el('p',e.message));}};await render(this.state.workspace);}
async refreshLibrary(){if(!this.bridge.library||this.closed)return;try{this.library=await this.bridge.library();if(this.closed)return;this.renderFilters();this.renderGallery();}catch(e){this.note('Libreria temporaneamente non disponibile.',true);}}
jobProgress(job){
if(terminal.has(job.status))return {percent:100,label:job.status,remaining:0};
if(Number.isFinite(job.progress)&&job.progress>0)return {percent:Math.min(99,job.progress*100),label:Math.round(job.progress*100)+'% · avanzamento Comfy',remaining:job.progress<1?Math.max(0,Math.round((Date.now()-job.started)/1000*(1-job.progress)/job.progress)):0};
const samples=this.allResults().filter(j=>j.family===job.family&&j.status==='completed'&&j.finished>j.started&&!j.study).slice(0,8).map(j=>(j.finished-j.started)/1000);
if(!samples.length)return {percent:15,indeterminate:true,label:'Tempo trascorso · stima disponibile dopo le prime generazioni',remaining:null};
const expected=samples.reduce((a,b)=>a+b,0)/samples.length,elapsed=(Date.now()-job.started)/1000;
return {percent:Math.min(94,100*elapsed/expected),remaining:Math.max(0,Math.round(expected-elapsed)),label:elapsed<expected?'~'+Math.round(expected-elapsed)+'s rimanenti · stima':'Finalizzazione · stima superata'};
}
updateProgress(){
if(!this.totalProgress)return;const jobs=this.state.results.filter(j=>!terminal.has(j.status)),ids=new Set(jobs.map(j=>j.batch));const batch=this.state.results.filter(j=>ids.has(j.batch));
this.stopButton.disabled=!jobs.length&&!this.busy;this.totalProgress.hidden=!jobs.length;if(!jobs.length)return;
const points=batch.map(j=>this.jobProgress(j));this.totalFill.style.width=points.reduce((s,p)=>s+p.percent,0)/points.length+'%';this.totalBar.classList.toggle('indeterminate',points.some(p=>p.indeterminate));
const known=jobs.map(j=>this.jobProgress(j).remaining);this.totalText.textContent=`${batch.filter(j=>terminal.has(j.status)).length} / ${batch.length} completate · `+(known.every(n=>n!==null)?`~${Math.max(...known)}s rimanenti · stima`:'Calcolo in corso · tempo residuo non ancora disponibile');
}
async stop(){
this.stopRequested=true;const jobs=this.state.results.filter(j=>!terminal.has(j.status));const ids=[...new Set(jobs.map(j=>j.promptId).filter(Boolean))];this.stopButton.disabled=true;this.note('Interruzione richiesta…');
const results=await Promise.allSettled(ids.map(id=>this.bridge.cancel(id)));for(let i=0;i<ids.length;i++)if(results[i].status==='fulfilled')for(const job of jobs.filter(j=>j.promptId===ids[i]))if(!terminal.has(job.status)){job.status='cancelled';job.finished=Date.now();}
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);}}
async run(){
if(this.busy)return;try{validateState(this.state);}catch(e){this.note(e.message,true);return;}
this.busy=true;this.updateHeader();const snapshot=copy(this.state),batch=crypto.randomUUID(),started=Date.now();
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=>({...p,id:crypto.randomUUID(),batch,started,status:'submitting',images:[]}));
try{
const primary=activeReferences(snapshot).find(r=>r.kind==='image');
@@ -194,13 +229,15 @@ export class PlatformUI {
this.note('Preparazione Image 1 per il confronto…');const prepared=await this.bridge.previewReference(primary,primary.process);primary.processedPreview=prepared.file;
}
const seed=new Uint32Array(1);crypto.getRandomValues(seed);const compiled=compileBatch(snapshot,jobs,seed[0]%2147483647);
this.note('Controllo reference e nodi…');await this.bridge.check(snapshot,compiled);if(this.closed)return;
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';}this.save();this.updateCards();this.note(`${jobs.length} generazioni indipendenti inviate in un unico batch parallelo.`);
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.status='failed';j.error=e.message;j.finished=Date.now();}}this.save();this.updateCards();this.note(e.message,true);}finally{this.busy=false;if(!this.closed)this.updateHeader();}
}
event(name,d){
if(!d?.prompt_id)return;const jobs=this.state.results.filter(j=>j.promptId===d.prompt_id);if(!jobs.length)return;
if(!d?.prompt_id)return;const jobs=this.state.results.filter(j=>j.promptId===d.prompt_id);if(!jobs.length){this.pendingEvents ||= [];if(this.busy&&this.pendingEvents.length<200)this.pendingEvents.push([name,d]);return;}
if(name==='progress_state'){for(const [id,n] of Object.entries(d.nodes||{})){const j=jobs.find(x=>x.generator===String(id));if(j&&!terminal.has(j.status)){if(n.state==='running')j.status='running';if(n.max>0&&n.value>0)j.progress=n.value/n.max;}}}
if(name==='progress'){const j=jobs.find(x=>x.generator===String(d.node));if(j&&d.max>0){j.progress=d.value/d.max;j.status='running';}}
if(name==='executing'&&d.node){const j=jobs.find(x=>x.generator===String(d.node));if(j)j.status='running';}
if(name==='executed'){
const job=jobs.find(x=>x.output===String(d.node));if(job&&d.output?.images){const record=d.output.dogma_records?.[0];Object.assign(job,record||{images:d.output.images,status:'completed',finished:Date.now()});this.renderFilters();this.renderGallery();}
@@ -214,7 +251,7 @@ export class PlatformUI {
try{const history=await this.bridge.history();if(this.closed)return;let changed=false;
for(const record of Object.values(history||{})){
const meta=record.prompt?.[3]?.extra_pnginfo?.workflow?.extra?.dogma_api_batch;if(meta?.session!==this.state.session)continue;
for(const saved of meta.jobs){let job=this.state.results.find(x=>x.id===saved.id);if(!job){job=copy(saved);this.state.results.push(job);changed=true;}job.promptId=record.prompt[1];const ui=record.outputs?.[job.output];if(ui?.images?.length){const result=ui.dogma_records?.[0]||{images:ui.images,status:'completed',finished:Date.now()};if(JSON.stringify(job.images)!==JSON.stringify(result.images))changed=true;Object.assign(job,result);}else if(record.status?.completed&&!terminal.has(job.status)){job.status=record.status.status_str==='success'?'missing':'failed';job.finished=Date.now();job.error='Comfy non ha restituito questo output.';}}
for(const saved of meta.jobs){let job=this.state.results.find(x=>x.id===saved.id);if(!job){job=copy(saved);this.state.results.push(job);changed=true;}if(job.imported)continue;job.promptId=record.prompt[1];const ui=record.outputs?.[job.output];if(ui?.images?.length){const result=ui.dogma_records?.[0]||{images:ui.images,status:'completed',finished:Date.now()};if(JSON.stringify(job.images)!==JSON.stringify(result.images))changed=true;Object.assign(job,result);}else if(record.status?.completed&&!terminal.has(job.status)){job.status=record.status.status_str==='success'?'missing':'failed';job.finished=Date.now();job.error='Comfy non ha restituito questo output.';}}
}
this.save();if(changed){this.renderFilters();this.renderGallery();}else this.updateCards();
}catch{this.note('La cronologia non è momentaneamente disponibile. I batch già accettati continuano in Comfy.',true);}finally{this.recovering=false;}
+1 -1
View File
@@ -1,4 +1,4 @@
import { icon } from './dogma_api_icons.js?v=1.0.54';
import { icon } from './dogma_api_icons.js?v=1.0.55';
export function hoverCompare(host,generated,original){
const a=document.createElement('img');a.src=generated;a.alt='Generata';a.draggable=false;a.className='dap-generated';host.append(a);host.classList.add('dap-compare-host');